17 #include <openssl/bn.h>
18 #include <openssl/evp.h>
19 #include <openssl/pkcs7.h>
20 #include <openssl/x509v3.h>
51 int error = X509_STORE_CTX_get_error(ctx);
52 X509 *current_cert = X509_STORE_CTX_get_current_cert(ctx);
53 string subject =
"subject n/a";
56 buffer = X509_NAME_oneline(X509_get_subject_name(current_cert), NULL, 0);
58 subject = string(buffer);
63 "certificate verification error: %s, error %s (%d)",
64 subject.c_str(), X509_verify_cert_error_string(error), error);
69 SignatureManager::SignatureManager() {
71 private_master_key_ = NULL;
75 int retval = pthread_mutex_init(&lock_blacklist_, NULL);
80 void SignatureManager::InitX509Store() {
81 if (x509_store_) X509_STORE_free(x509_store_);
83 x509_store_ = X509_STORE_new();
84 assert(x509_store_ != NULL);
86 unsigned long verify_flags =
87 X509_V_FLAG_CRL_CHECK |
88 X509_V_FLAG_CRL_CHECK_ALL;
89 #ifdef OPENSSL_API_INTERFACE_V09
90 X509_STORE_set_flags(x509_store_, verify_flags);
93 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
95 retval = X509_VERIFY_PARAM_set_flags(param, verify_flags);
97 retval = X509_STORE_set1_param(x509_store_, param);
99 X509_VERIFY_PARAM_free(param);
102 x509_lookup_ = X509_STORE_add_lookup(x509_store_, X509_LOOKUP_hash_dir());
103 assert(x509_lookup_ != NULL);
110 OpenSSL_add_all_algorithms();
118 UnloadPrivateMasterKey();
119 UnloadPublicRsaKeys();
121 if (x509_store_) X509_STORE_free(x509_store_);
126 private_master_key_ = NULL;
136 string SignatureManager::GetCryptoError() {
139 while (ERR_peek_error() != 0) {
140 ERR_error_string(ERR_get_error(), buf);
153 bool SignatureManager::LoadPrivateMasterKeyPath(
const string &file_pem)
155 UnloadPrivateMasterKey();
157 if ((fp = fopen(file_pem.c_str(),
"r")) == NULL)
159 private_master_key_ = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
161 return (private_master_key_ != NULL);
164 bool SignatureManager::LoadPrivateMasterKeyMem(
const string &key)
166 UnloadPrivateMasterKey();
167 BIO *bp = BIO_new(BIO_s_mem());
169 if (BIO_write(bp, key.data(), key.size()) <= 0) {
173 private_master_key_ = PEM_read_bio_RSAPrivateKey(bp, NULL, NULL, NULL);
175 return (private_master_key_ != NULL);
185 bool SignatureManager::LoadPrivateKeyPath(
const string &file_pem,
186 const string &password)
191 char *tmp =
strdupa(password.c_str());
193 if ((fp = fopen(file_pem.c_str(),
"r")) == NULL)
195 result = (private_key_ = PEM_read_PrivateKey(fp, NULL, NULL, tmp)) != NULL;
200 bool SignatureManager::LoadPrivateKeyMem(
const std::string &key)
203 BIO *bp = BIO_new(BIO_s_mem());
205 if (BIO_write(bp, key.data(), key.size()) <= 0) {
209 private_key_ = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL);
211 return (private_key_ != NULL);
218 void SignatureManager::UnloadPrivateKey() {
219 if (private_key_) EVP_PKEY_free(private_key_);
224 void SignatureManager::UnloadCertificate() {
225 if (certificate_) X509_free(certificate_);
233 void SignatureManager::UnloadPrivateMasterKey() {
234 if (private_master_key_) RSA_free(private_master_key_);
235 private_master_key_ = NULL;
245 bool SignatureManager::LoadCertificatePath(
const string &file_pem) {
247 X509_free(certificate_);
255 if ((fp = fopen(file_pem.c_str(),
"r")) == NULL)
257 result = (certificate_ = PEM_read_X509_AUX(fp, NULL, NULL, nopwd)) != NULL;
259 if (!result && certificate_) {
260 X509_free(certificate_);
272 bool SignatureManager::LoadCertificateMem(
const unsigned char *buffer,
273 const unsigned buffer_size)
276 X509_free(certificate_);
283 BIO *
mem = BIO_new(BIO_s_mem());
284 if (!mem)
return false;
285 if (BIO_write(mem, buffer, buffer_size) <= 0) {
289 result = (certificate_ = PEM_read_bio_X509_AUX(mem, NULL, NULL, nopwd))
293 if (!result && certificate_) {
294 X509_free(certificate_);
305 bool SignatureManager::LoadPublicRsaKeys(
const string &path_list) {
306 UnloadPublicRsaKeys();
310 const vector<string> pem_files =
SplitString(path_list,
':');
315 for (
unsigned i = 0; i < pem_files.size(); ++i) {
316 const char* pubkey_file = pem_files[i].c_str();
319 fp = fopen(pubkey_file,
"r");
328 EVP_PKEY *this_key = PEM_read_PUBKEY(fp, NULL, NULL, nopwd);
330 if (this_key == NULL) {
338 RSA *key = EVP_PKEY_get1_RSA(this_key);
339 EVP_PKEY_free(this_key);
348 public_keys_.push_back(key);
355 void SignatureManager::UnloadPublicRsaKeys() {
356 for (
unsigned i = 0; i < public_keys_.size(); ++i)
357 RSA_free(public_keys_[i]);
358 public_keys_.clear();
362 std::string SignatureManager::GenerateKeyText(RSA *pubkey)
const {
363 if (!pubkey) {
return "";}
365 BIO *bp = BIO_new(BIO_s_mem());
368 " memory for pubkey");
371 if (!PEM_write_bio_RSA_PUBKEY(bp, pubkey)) {
373 " pubkey to memory");
376 char *bio_pubkey_text;
377 long bytes = BIO_get_mem_data(bp, &bio_pubkey_text);
378 std::string bio_pubkey_str(bio_pubkey_text, bytes);
381 return bio_pubkey_str;
385 std::string SignatureManager::GetActivePubkeys()
const {
387 for (std::vector<RSA *>::const_iterator it = public_keys_.begin();
388 it != public_keys_.end();
390 pubkeys += GenerateKeyText(*it);
397 std::vector<std::string> SignatureManager::GetActivePubkeysAsVector()
const {
398 std::vector<std::string> pubkeys;
399 for (std::vector<RSA *>::const_iterator it = public_keys_.begin();
400 it != public_keys_.end();
402 pubkeys.push_back(GenerateKeyText(*it));
409 std::string SignatureManager::GetCertificate()
const {
410 if (!certificate_)
return "";
412 BIO *bp = BIO_new(BIO_s_mem());
414 bool rvb = PEM_write_bio_X509(bp, certificate_);
417 long bytes = BIO_get_mem_data(bp, &bio_crt_text);
419 std::string bio_crt_str(bio_crt_text, bytes);
425 std::string SignatureManager::GetPrivateKey() {
426 if (!private_key_)
return "";
428 BIO *bp = BIO_new(BIO_s_mem());
430 bool rvb = PEM_write_bio_PrivateKey(bp, private_key_, NULL, NULL, 0, 0, NULL);
432 char *bio_privkey_text;
433 long bytes = BIO_get_mem_data(bp, &bio_privkey_text);
435 std::string bio_privkey_str(bio_privkey_text, bytes);
437 return bio_privkey_str;
441 std::string SignatureManager::GetPrivateMasterKey() {
442 if (!private_master_key_)
return "";
444 BIO *bp = BIO_new(BIO_s_mem());
446 bool rvb = PEM_write_bio_RSAPrivateKey(bp, private_master_key_,
447 NULL, NULL, 0, 0, NULL);
449 char *bio_master_privkey_text;
450 long bytes = BIO_get_mem_data(bp, &bio_master_privkey_text);
452 std::string bio_master_privkey_str(bio_master_privkey_text, bytes);
454 return bio_master_privkey_str;
457 RSA *SignatureManager::GenerateRsaKeyPair() {
459 BIGNUM *bn = BN_new();
460 int retval = BN_set_word(bn, RSA_F4);
462 #ifdef OPENSSL_API_INTERFACE_V09
463 rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL);
467 retval = RSA_generate_key_ex(rsa, 2048, bn, NULL);
478 void SignatureManager::GenerateMasterKeyPair() {
479 UnloadPrivateMasterKey();
480 UnloadPublicRsaKeys();
482 RSA *rsa = GenerateRsaKeyPair();
483 private_master_key_ = RSAPrivateKey_dup(rsa);
484 public_keys_.push_back(RSAPublicKey_dup(rsa));
491 void SignatureManager::GenerateCertificate(
const std::string &cn) {
496 RSA *rsa = GenerateRsaKeyPair();
497 private_key_ = EVP_PKEY_new();
498 retval = EVP_PKEY_set1_RSA(private_key_, RSAPrivateKey_dup(rsa));
500 EVP_PKEY *pkey = EVP_PKEY_new();
501 retval = EVP_PKEY_set1_RSA(pkey, rsa);
504 certificate_ = X509_new();
505 X509_set_version(certificate_, 2L);
506 X509_set_pubkey(certificate_, pkey);
510 unsigned long rnd_serial_no = prng.
Next(uint64_t(1) + uint32_t(-1));
511 rnd_serial_no = rnd_serial_no |
512 uint64_t(prng.
Next(uint64_t(1) + uint32_t(-1))) << 32;
513 ASN1_INTEGER_set(X509_get_serialNumber(certificate_), rnd_serial_no);
516 X509_gmtime_adj(reinterpret_cast<ASN1_TIME *>(
517 X509_get_notBefore(certificate_)), 0);
519 X509_gmtime_adj(reinterpret_cast<ASN1_TIME *>(
520 X509_get_notAfter(certificate_)), 3600 * 24 * 365);
522 X509_NAME *name = X509_get_subject_name(certificate_);
523 #ifdef OPENSSL_API_INTERFACE_V09
524 X509_NAME_add_entry_by_txt(name,
"CN", MBSTRING_ASC,
525 const_cast<unsigned char *>(
526 reinterpret_cast<const unsigned char *>(cn.c_str())),
529 X509_NAME_add_entry_by_txt(name,
"CN", MBSTRING_ASC,
530 reinterpret_cast<const unsigned char *>(cn.c_str()), -1, -1, 0);
532 retval = X509_set_issuer_name(certificate_, name);
535 #ifdef OPENSSL_API_INTERFACE_V09
536 retval = X509_sign(certificate_, pkey, EVP_sha1());
538 retval = X509_sign(certificate_, pkey, EVP_sha256());
547 bool SignatureManager::LoadBlacklist(
548 const std::string &path_blacklist,
553 path_blacklist.c_str());
557 int fd = open(path_blacklist.c_str(), O_RDONLY);
560 std::string blacklist_buffer;
566 unsigned num_bytes = 0;
567 while (num_bytes < blacklist_buffer.size()) {
568 const string line =
GetLineMem(blacklist_buffer.data() + num_bytes,
569 blacklist_buffer.size() - num_bytes);
570 blacklist_.push_back(line);
571 num_bytes += line.length() + 1;
578 vector<string> SignatureManager::GetBlacklist() {
591 bool SignatureManager::LoadTrustedCaCrl(
const string &path_list) {
597 const vector<string> paths =
SplitString(path_list,
':');
598 for (
unsigned i = 0; i < paths.size(); ++i) {
599 int retval = X509_LOOKUP_add_dir(x509_lookup_, paths[i].c_str(),
621 unsigned char *buffer = NULL;
623 buffer_size = i2d_X509(certificate_, &buffer);
640 string SignatureManager::FingerprintCertificate(
643 shash::Any hash = HashCertificate(hash_algorithm);
647 const string hash_str = hash.
ToString();
649 for (
unsigned i = 0; i < hash_str.length(); ++i) {
651 if ((i > 0) && (i%2 == 0)) result +=
":";
653 result += toupper(hash_str[i]);
662 shash::Any SignatureManager::MkFromFingerprint(
const std::string &fingerprint) {
664 for (
unsigned i = 0; i < fingerprint.length(); ++i) {
665 if ((fingerprint[i] ==
' ') || (fingerprint[i] ==
'\t') ||
666 (fingerprint[i] ==
'#'))
670 if (fingerprint[i] !=
':')
671 convert.push_back(tolower(fingerprint[i]));
681 string SignatureManager::Whois() {
682 if (!certificate_)
return "No certificate loaded";
685 X509_NAME *subject = X509_get_subject_name(certificate_);
686 X509_NAME *issuer = X509_get_issuer_name(certificate_);
688 buffer = X509_NAME_oneline(subject, NULL, 0);
690 result =
"Publisher: " + string(buffer);
693 buffer = X509_NAME_oneline(issuer, NULL, 0);
695 result +=
"\nCertificate issued by: " + string(buffer);
702 bool SignatureManager::WriteCertificateMem(
unsigned char **buffer,
703 unsigned *buffer_size)
705 BIO *
mem = BIO_new(BIO_s_mem());
706 if (!mem)
return false;
707 if (!PEM_write_bio_X509(mem, certificate_)) {
713 *buffer_size = BIO_get_mem_data(mem, &bio_buffer);
714 *buffer =
reinterpret_cast<unsigned char *
>(smalloc(*buffer_size));
715 memcpy(*buffer, bio_buffer, *buffer_size);
726 bool SignatureManager::KeysMatch() {
727 if (!certificate_ || !private_key_)
731 const unsigned char *sign_me =
reinterpret_cast<const unsigned char *
>
733 unsigned char *signature = NULL;
734 unsigned signature_size;
735 if (Sign(sign_me, 7, &signature, &signature_size) &&
736 Verify(sign_me, 7, signature, signature_size))
740 if (signature) free(signature);
748 bool SignatureManager::VerifyCaChain() {
752 X509_STORE_CTX *csc = NULL;
753 csc = X509_STORE_CTX_new();
756 X509_STORE_CTX_init(csc, x509_store_, certificate_, NULL);
757 bool result = X509_verify_cert(csc) == 1;
758 X509_STORE_CTX_free(csc);
769 bool SignatureManager::Sign(
const unsigned char *buffer,
770 const unsigned buffer_size,
771 unsigned char **signature,
772 unsigned *signature_size)
781 #ifdef OPENSSL_API_INTERFACE_V11
782 EVP_MD_CTX *ctx_ptr = EVP_MD_CTX_new();
785 EVP_MD_CTX_init(&ctx);
786 EVP_MD_CTX *ctx_ptr = &
ctx;
789 *signature =
reinterpret_cast<unsigned char *
>(
790 smalloc(EVP_PKEY_size(private_key_)));
791 if (EVP_SignInit(ctx_ptr, EVP_sha1()) &&
792 EVP_SignUpdate(ctx_ptr, buffer, buffer_size) &&
793 EVP_SignFinal(ctx_ptr, *signature, signature_size, private_key_))
797 #ifdef OPENSSL_API_INTERFACE_V11
798 EVP_MD_CTX_free(ctx_ptr);
800 EVP_MD_CTX_cleanup(&ctx);
817 bool SignatureManager::SignRsa(
const unsigned char *buffer,
818 const unsigned buffer_size,
819 unsigned char **signature,
820 unsigned *signature_size)
822 if (!private_master_key_) {
828 unsigned char *to = (
unsigned char *)smalloc(RSA_size(private_master_key_));
829 unsigned char *from = (
unsigned char *)smalloc(buffer_size);
830 memcpy(from, buffer, buffer_size);
832 int size = RSA_private_encrypt(buffer_size, from, to,
833 private_master_key_, RSA_PKCS1_PADDING);
841 *signature_size =
size;
852 const unsigned buffer_size,
853 const unsigned char *signature,
854 const unsigned signature_size)
856 if (!certificate_)
return false;
859 #ifdef OPENSSL_API_INTERFACE_V11
860 EVP_MD_CTX *ctx_ptr = EVP_MD_CTX_new();
863 EVP_MD_CTX_init(&ctx);
864 EVP_MD_CTX *ctx_ptr = &
ctx;
867 EVP_PKEY *pubkey = X509_get_pubkey(certificate_);
868 if (EVP_VerifyInit(ctx_ptr, EVP_sha1()) &&
869 EVP_VerifyUpdate(ctx_ptr, buffer, buffer_size) &&
871 EVP_VerifyFinal(ctx_ptr,
872 const_cast<unsigned char *>(signature), signature_size,
875 EVP_VerifyFinal(ctx_ptr, signature, signature_size, pubkey)
882 EVP_PKEY_free(pubkey);
883 #ifdef OPENSSL_API_INTERFACE_V11
884 EVP_MD_CTX_free(ctx_ptr);
886 EVP_MD_CTX_cleanup(&ctx);
898 bool SignatureManager::VerifyRsa(
const unsigned char *buffer,
899 const unsigned buffer_size,
900 const unsigned char *signature,
901 const unsigned signature_size)
903 for (
unsigned i = 0, s = public_keys_.size(); i < s; ++i) {
904 if (buffer_size > (
unsigned)RSA_size(public_keys_[i]))
907 unsigned char *to = (
unsigned char *)smalloc(RSA_size(public_keys_[i]));
908 unsigned char *from = (
unsigned char *)smalloc(signature_size);
909 memcpy(from, signature, signature_size);
911 int size = RSA_public_decrypt(signature_size, from, to,
912 public_keys_[i], RSA_PKCS1_PADDING);
914 if ((size >= 0) && (
unsigned(size) == buffer_size) &&
915 (memcmp(buffer, to, size) == 0))
932 void SignatureManager::CutLetter(
const unsigned char *buffer,
933 const unsigned buffer_size,
934 const char separator,
935 unsigned *letter_length,
936 unsigned *pos_after_mark)
939 *letter_length = *pos_after_mark = 0;
941 if (pos == buffer_size) {
942 *pos_after_mark = pos;
943 *letter_length = pos;
947 if ((buffer[pos] ==
'\n') && (pos+4 <= buffer_size) &&
948 (buffer[pos+1] == separator) && (buffer[pos+2] == separator) &&
949 (buffer[pos+3] ==
'\n'))
951 *letter_length = pos+1;
957 *pos_after_mark = pos;
968 bool SignatureManager::VerifyLetter(
const unsigned char *buffer,
969 const unsigned buffer_size,
973 unsigned letter_length = 0;
974 CutLetter(buffer, buffer_size,
'-', &letter_length, &pos);
975 if (pos >= buffer_size)
978 string hash_str =
"";
979 unsigned hash_pos = pos;
981 if (pos == buffer_size)
983 if (buffer[pos] ==
'\n') {
987 hash_str.push_back(buffer[pos++]);
992 if (hash_printed != hash_computed)
996 return VerifyRsa(&buffer[hash_pos], hash_str.length(),
997 &buffer[pos], buffer_size-pos);
999 return Verify(&buffer[hash_pos], hash_str.length(),
1000 &buffer[pos], buffer_size-pos);
1009 bool SignatureManager::VerifyPkcs7(
const unsigned char *buffer,
1010 const unsigned buffer_size,
1011 unsigned char **content,
1012 unsigned *content_size,
1013 vector<string> *alt_uris)
1018 BIO *bp_pkcs7 = BIO_new(BIO_s_mem());
1019 if (!bp_pkcs7)
return false;
1020 if (BIO_write(bp_pkcs7, buffer, buffer_size) <= 0) {
1025 PKCS7 *pkcs7 = NULL;
1026 pkcs7 = PEM_read_bio_PKCS7(bp_pkcs7, NULL, NULL, NULL);
1033 BIO *bp_content = BIO_new(BIO_s_mem());
1040 STACK_OF(X509) *extra_signers = NULL;
1042 bool result = PKCS7_verify(pkcs7, extra_signers, x509_store_, indata,
1045 BIO_free(bp_content);
1050 BUF_MEM *bufmem_content;
1051 BIO_get_mem_ptr(bp_content, &bufmem_content);
1053 (void) BIO_set_close(bp_content, BIO_NOCLOSE);
1054 BIO_free(bp_content);
1055 *content =
reinterpret_cast<unsigned char *
>(bufmem_content->data);
1056 *content_size = bufmem_content->length;
1057 free(bufmem_content);
1058 if (*content == NULL) {
1065 STACK_OF(X509) *signers = NULL;
1066 signers = PKCS7_get0_signers(pkcs7, NULL, 0);
1070 for (
int i = 0; i < sk_X509_num(signers); ++i) {
1071 X509* this_signer = sk_X509_value(signers, i);
1072 GENERAL_NAMES *subject_alt_names = NULL;
1073 subject_alt_names =
reinterpret_cast<GENERAL_NAMES *
>(
1074 X509_get_ext_d2i(this_signer, NID_subject_alt_name, NULL, NULL));
1075 if (subject_alt_names != NULL) {
1076 for (
int j = 0; j < sk_GENERAL_NAME_num(subject_alt_names); ++j) {
1077 GENERAL_NAME *this_name = sk_GENERAL_NAME_value(subject_alt_names, j);
1078 if (this_name->type != GEN_URI)
1081 const char *name_ptr =
reinterpret_cast<const char *
>(
1082 #ifdef OPENSSL_API_INTERFACE_V11
1083 ASN1_STRING_get0_data(this_name->d.uniformResourceIdentifier));
1085 ASN1_STRING_data(this_name->d.uniformResourceIdentifier));
1088 ASN1_STRING_length(this_name->d.uniformResourceIdentifier);
1089 if (!name_ptr || (name_len <= 0))
1091 alt_uris->push_back(
string(name_ptr, name_len));
1095 sk_X509_free(signers);
struct cvmcache_context * ctx
Failures Verify(unsigned char *manifest_data, size_t manifest_size, const std::string &base_url, const std::string &repository_name, const uint64_t minimum_timestamp, const shash::Any *base_catalog, signature::SignatureManager *signature_manager, download::DownloadManager *download_manager, ManifestEnsemble *ensemble)
string GetLineMem(const char *text, const int text_size)
std::string ToString(const bool with_suffix=false) const
assert((mem||(size==0))&&"Out Of Memory")
vector< string > SplitString(const string &str, char delim)
const char * kDefaultPublicKey
static int Init(const loader::LoaderExports *loader_exports)
static int CallbackCertVerify(int ok, X509_STORE_CTX *ctx)
#define OPENSSL_API_INTERFACE_V09
bool SafeReadToString(int fd, std::string *final_result)
void HashMem(const unsigned char *buffer, const unsigned buffer_size, Any *any_digest)
Any MkFromHexPtr(const HexPtr hex, const char suffix)
const unsigned kDigestSizes[]
uint32_t Next(const uint64_t boundary)
CVMFS_EXPORT void LogCvmfs(const LogSource source, const int mask, const char *format,...)