17 #include <openssl/bn.h>
18 #include <openssl/evp.h>
19 #include <openssl/pkcs7.h>
20 #include <openssl/x509v3.h>
52 int error = X509_STORE_CTX_get_error(ctx);
53 X509 *current_cert = X509_STORE_CTX_get_current_cert(ctx);
54 string subject =
"subject n/a";
57 buffer = X509_NAME_oneline(X509_get_subject_name(current_cert), NULL, 0);
59 subject = string(buffer);
64 "certificate verification error: %s, error %s (%d)", subject.c_str(),
65 X509_verify_cert_error_string(error), error);
70 SignatureManager::SignatureManager() {
72 private_master_key_ = NULL;
76 int retval = pthread_mutex_init(&lock_blacklist_, NULL);
81 void SignatureManager::InitX509Store() {
83 X509_STORE_free(x509_store_);
85 x509_store_ = X509_STORE_new();
86 assert(x509_store_ != NULL);
88 unsigned long verify_flags =
89 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL;
90 #ifdef OPENSSL_API_INTERFACE_V09
91 X509_STORE_set_flags(x509_store_, verify_flags);
94 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
96 retval = X509_VERIFY_PARAM_set_flags(param, verify_flags);
98 retval = X509_STORE_set1_param(x509_store_, param);
100 X509_VERIFY_PARAM_free(param);
103 x509_lookup_ = X509_STORE_add_lookup(x509_store_, X509_LOOKUP_hash_dir());
104 assert(x509_lookup_ != NULL);
111 OpenSSL_add_all_algorithms();
119 UnloadPrivateMasterKey();
120 UnloadPublicRsaKeys();
123 X509_STORE_free(x509_store_);
128 private_master_key_ = NULL;
138 string SignatureManager::GetCryptoError() {
141 while (ERR_peek_error() != 0) {
142 ERR_error_string(ERR_get_error(), buf);
155 bool SignatureManager::LoadPrivateMasterKeyPath(
const string &file_pem) {
156 UnloadPrivateMasterKey();
158 if ((fp = fopen(file_pem.c_str(),
"r")) == NULL)
160 private_master_key_ = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
162 return (private_master_key_ != NULL);
165 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) {
190 char *tmp =
strdupa(password.c_str());
192 if ((fp = fopen(file_pem.c_str(),
"r")) == NULL)
194 result = (private_key_ = PEM_read_PrivateKey(fp, NULL, NULL, tmp)) != NULL;
199 bool SignatureManager::LoadPrivateKeyMem(
const std::string &key) {
201 BIO *bp = BIO_new(BIO_s_mem());
203 if (BIO_write(bp, key.data(), key.size()) <= 0) {
207 private_key_ = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL);
209 return (private_key_ != NULL);
216 void SignatureManager::UnloadPrivateKey() {
218 EVP_PKEY_free(private_key_);
223 void SignatureManager::UnloadCertificate() {
225 X509_free(certificate_);
233 void SignatureManager::UnloadPrivateMasterKey() {
234 if (private_master_key_)
235 RSA_free(private_master_key_);
236 private_master_key_ = NULL;
246 bool SignatureManager::LoadCertificatePath(
const string &file_pem) {
248 X509_free(certificate_);
256 if ((fp = fopen(file_pem.c_str(),
"r")) == NULL)
258 result = (certificate_ = PEM_read_X509_AUX(fp, NULL, NULL, nopwd)) != NULL;
260 if (!result && certificate_) {
261 X509_free(certificate_);
273 bool SignatureManager::LoadCertificateMem(
const unsigned char *buffer,
274 const unsigned buffer_size) {
276 X509_free(certificate_);
283 BIO *
mem = BIO_new(BIO_s_mem());
286 if (BIO_write(mem, buffer, buffer_size) <= 0) {
290 result = (certificate_ = PEM_read_bio_X509_AUX(mem, NULL, NULL, nopwd))
294 if (!result && certificate_) {
295 X509_free(certificate_);
306 bool SignatureManager::LoadPublicRsaKeys(
const string &path_list) {
307 UnloadPublicRsaKeys();
311 const vector<string> pem_files =
SplitString(path_list,
':');
316 for (
unsigned i = 0; i < pem_files.size(); ++i) {
317 const char *pubkey_file = pem_files[i].c_str();
320 fp = fopen(pubkey_file,
"r");
330 EVP_PKEY *this_key = PEM_read_PUBKEY(fp, NULL, NULL, nopwd);
332 if (this_key == NULL) {
341 RSA *key = EVP_PKEY_get1_RSA(this_key);
342 EVP_PKEY_free(this_key);
352 public_keys_.push_back(key);
359 void SignatureManager::UnloadPublicRsaKeys() {
360 for (
unsigned i = 0; i < public_keys_.size(); ++i)
361 RSA_free(public_keys_[i]);
362 public_keys_.clear();
366 std::string SignatureManager::GenerateKeyText(RSA *pubkey)
const {
371 BIO *bp = BIO_new(BIO_s_mem());
375 " memory for pubkey");
378 if (!PEM_write_bio_RSA_PUBKEY(bp, pubkey)) {
381 " pubkey to memory");
384 char *bio_pubkey_text;
385 long bytes = BIO_get_mem_data(bp, &bio_pubkey_text);
386 std::string bio_pubkey_str(bio_pubkey_text, bytes);
389 return bio_pubkey_str;
393 std::string SignatureManager::GetActivePubkeys()
const {
395 for (std::vector<RSA *>::const_iterator it = public_keys_.begin();
396 it != public_keys_.end();
398 pubkeys += GenerateKeyText(*it);
405 std::vector<std::string> SignatureManager::GetActivePubkeysAsVector()
const {
406 std::vector<std::string> pubkeys;
407 for (std::vector<RSA *>::const_iterator it = public_keys_.begin();
408 it != public_keys_.end();
410 pubkeys.push_back(GenerateKeyText(*it));
417 std::string SignatureManager::GetCertificate()
const {
421 BIO *bp = BIO_new(BIO_s_mem());
423 bool rvb = PEM_write_bio_X509(bp, certificate_);
426 long bytes = BIO_get_mem_data(bp, &bio_crt_text);
428 std::string bio_crt_str(bio_crt_text, bytes);
434 std::string SignatureManager::GetPrivateKey() {
438 BIO *bp = BIO_new(BIO_s_mem());
440 bool rvb = PEM_write_bio_PrivateKey(bp, private_key_, NULL, NULL, 0, 0, NULL);
442 char *bio_privkey_text;
443 long bytes = BIO_get_mem_data(bp, &bio_privkey_text);
445 std::string bio_privkey_str(bio_privkey_text, bytes);
447 return bio_privkey_str;
451 std::string SignatureManager::GetPrivateMasterKey() {
452 if (!private_master_key_)
455 BIO *bp = BIO_new(BIO_s_mem());
457 bool rvb = PEM_write_bio_RSAPrivateKey(bp, private_master_key_, NULL, NULL, 0,
460 char *bio_master_privkey_text;
461 long bytes = BIO_get_mem_data(bp, &bio_master_privkey_text);
463 std::string bio_master_privkey_str(bio_master_privkey_text, bytes);
465 return bio_master_privkey_str;
468 RSA *SignatureManager::GenerateRsaKeyPair() {
470 BIGNUM *bn = BN_new();
471 int retval = BN_set_word(bn, RSA_F4);
473 #ifdef OPENSSL_API_INTERFACE_V09
474 rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL);
478 retval = RSA_generate_key_ex(rsa, 2048, bn, NULL);
489 void SignatureManager::GenerateMasterKeyPair() {
490 UnloadPrivateMasterKey();
491 UnloadPublicRsaKeys();
493 RSA *rsa = GenerateRsaKeyPair();
494 private_master_key_ = RSAPrivateKey_dup(rsa);
495 public_keys_.push_back(RSAPublicKey_dup(rsa));
502 void SignatureManager::GenerateCertificate(
const std::string &cn) {
507 RSA *rsa = GenerateRsaKeyPair();
508 private_key_ = EVP_PKEY_new();
509 retval = EVP_PKEY_set1_RSA(private_key_, RSAPrivateKey_dup(rsa));
511 EVP_PKEY *pkey = EVP_PKEY_new();
512 retval = EVP_PKEY_set1_RSA(pkey, rsa);
515 certificate_ = X509_new();
516 X509_set_version(certificate_, 2L);
517 X509_set_pubkey(certificate_, pkey);
521 unsigned long rnd_serial_no = prng.
Next(uint64_t(1) + uint32_t(-1));
522 rnd_serial_no = rnd_serial_no
523 | uint64_t(prng.
Next(uint64_t(1) + uint32_t(-1))) << 32;
524 ASN1_INTEGER_set(X509_get_serialNumber(certificate_), rnd_serial_no);
528 reinterpret_cast<ASN1_TIME *>(X509_get_notBefore(certificate_)), 0);
531 reinterpret_cast<ASN1_TIME *>(X509_get_notAfter(certificate_)),
534 X509_NAME *name = X509_get_subject_name(certificate_);
535 #ifdef OPENSSL_API_INTERFACE_V09
536 X509_NAME_add_entry_by_txt(
537 name,
"CN", MBSTRING_ASC,
538 const_cast<unsigned char *>(
539 reinterpret_cast<const unsigned char *>(cn.c_str())),
542 X509_NAME_add_entry_by_txt(
543 name,
"CN", MBSTRING_ASC,
544 reinterpret_cast<const unsigned char *>(cn.c_str()), -1, -1, 0);
546 retval = X509_set_issuer_name(certificate_, name);
549 #ifdef OPENSSL_API_INTERFACE_V09
550 retval = X509_sign(certificate_, pkey, EVP_sha1());
552 retval = X509_sign(certificate_, pkey, EVP_sha256());
561 bool SignatureManager::LoadBlacklist(
const std::string &path_blacklist,
565 path_blacklist.c_str());
569 int fd = open(path_blacklist.c_str(), O_RDONLY);
572 std::string blacklist_buffer;
578 unsigned num_bytes = 0;
579 while (num_bytes < blacklist_buffer.size()) {
580 const string line =
GetLineMem(blacklist_buffer.data() + num_bytes,
581 blacklist_buffer.size() - num_bytes);
582 blacklist_.push_back(line);
583 num_bytes += line.length() + 1;
590 vector<string> SignatureManager::GetBlacklist() {
603 bool SignatureManager::LoadTrustedCaCrl(
const string &path_list) {
609 const vector<string> paths =
SplitString(path_list,
':');
610 for (
unsigned i = 0; i < paths.size(); ++i) {
611 int retval = X509_LOOKUP_add_dir(x509_lookup_, paths[i].c_str(),
632 unsigned char *buffer = NULL;
634 buffer_size = i2d_X509(certificate_, &buffer);
651 string SignatureManager::FingerprintCertificate(
653 shash::Any hash = HashCertificate(hash_algorithm);
657 const string hash_str = hash.
ToString();
659 for (
unsigned i = 0; i < hash_str.length(); ++i) {
661 if ((i > 0) && (i % 2 == 0))
664 result += toupper(hash_str[i]);
673 shash::Any SignatureManager::MkFromFingerprint(
const std::string &fingerprint) {
675 for (
unsigned i = 0; i < fingerprint.length(); ++i) {
676 if ((fingerprint[i] ==
' ') || (fingerprint[i] ==
'\t')
677 || (fingerprint[i] ==
'#')) {
680 if (fingerprint[i] !=
':')
681 convert.push_back(tolower(fingerprint[i]));
691 string SignatureManager::Whois() {
693 return "No certificate loaded";
696 X509_NAME *subject = X509_get_subject_name(certificate_);
697 X509_NAME *issuer = X509_get_issuer_name(certificate_);
699 buffer = X509_NAME_oneline(subject, NULL, 0);
701 result =
"Publisher: " + string(buffer);
704 buffer = X509_NAME_oneline(issuer, NULL, 0);
706 result +=
"\nCertificate issued by: " + string(buffer);
713 bool SignatureManager::WriteCertificateMem(
unsigned char **buffer,
714 unsigned *buffer_size) {
715 BIO *
mem = BIO_new(BIO_s_mem());
718 if (!PEM_write_bio_X509(mem, certificate_)) {
724 *buffer_size = BIO_get_mem_data(mem, &bio_buffer);
725 *buffer =
reinterpret_cast<unsigned char *
>(smalloc(*buffer_size));
726 memcpy(*buffer, bio_buffer, *buffer_size);
737 bool SignatureManager::KeysMatch() {
738 if (!certificate_ || !private_key_)
742 const unsigned char *sign_me =
reinterpret_cast<const unsigned char *
>(
744 unsigned char *signature = NULL;
745 unsigned signature_size;
746 if (Sign(sign_me, 7, &signature, &signature_size)
747 &&
Verify(sign_me, 7, signature, signature_size)) {
759 bool SignatureManager::VerifyCaChain() {
763 X509_STORE_CTX *csc = NULL;
764 csc = X509_STORE_CTX_new();
767 X509_STORE_CTX_init(csc, x509_store_, certificate_, NULL);
768 bool result = X509_verify_cert(csc) == 1;
769 X509_STORE_CTX_free(csc);
780 bool SignatureManager::Sign(
const unsigned char *buffer,
781 const unsigned buffer_size,
782 unsigned char **signature,
783 unsigned *signature_size) {
791 #ifdef OPENSSL_API_INTERFACE_V11
792 EVP_MD_CTX *ctx_ptr = EVP_MD_CTX_new();
795 EVP_MD_CTX_init(&ctx);
796 EVP_MD_CTX *ctx_ptr = &
ctx;
799 *signature =
reinterpret_cast<unsigned char *
>(
800 smalloc(EVP_PKEY_size(private_key_)));
801 if (EVP_SignInit(ctx_ptr, EVP_sha1())
802 && EVP_SignUpdate(ctx_ptr, buffer, buffer_size)
803 && EVP_SignFinal(ctx_ptr, *signature, signature_size, private_key_)) {
806 #ifdef OPENSSL_API_INTERFACE_V11
807 EVP_MD_CTX_free(ctx_ptr);
809 EVP_MD_CTX_cleanup(&ctx);
826 bool SignatureManager::SignRsa(
const unsigned char *buffer,
827 const unsigned buffer_size,
828 unsigned char **signature,
829 unsigned *signature_size) {
830 if (!private_master_key_) {
836 unsigned char *to = (
unsigned char *)smalloc(RSA_size(private_master_key_));
837 unsigned char *from = (
unsigned char *)smalloc(buffer_size);
838 memcpy(from, buffer, buffer_size);
840 int size = RSA_private_encrypt(buffer_size, from, to, private_master_key_,
849 *signature_size =
size;
860 const unsigned buffer_size,
861 const unsigned char *signature,
862 const unsigned signature_size) {
867 #ifdef OPENSSL_API_INTERFACE_V11
868 EVP_MD_CTX *ctx_ptr = EVP_MD_CTX_new();
871 EVP_MD_CTX_init(&ctx);
872 EVP_MD_CTX *ctx_ptr = &
ctx;
875 EVP_PKEY *pubkey = X509_get_pubkey(certificate_);
876 if (EVP_VerifyInit(ctx_ptr, EVP_sha1())
877 && EVP_VerifyUpdate(ctx_ptr, buffer, buffer_size) &&
879 EVP_VerifyFinal(ctx_ptr, const_cast<unsigned char *>(signature),
880 signature_size, pubkey)
882 EVP_VerifyFinal(ctx_ptr, signature, signature_size, pubkey)
888 EVP_PKEY_free(pubkey);
889 #ifdef OPENSSL_API_INTERFACE_V11
890 EVP_MD_CTX_free(ctx_ptr);
892 EVP_MD_CTX_cleanup(&ctx);
905 bool SignatureManager::VerifyRsa(
const unsigned char *buffer,
906 const unsigned buffer_size,
907 const unsigned char *signature,
908 const unsigned signature_size) {
909 for (
unsigned i = 0, s = public_keys_.size(); i < s; ++i) {
910 if (buffer_size > (
unsigned)RSA_size(public_keys_[i]))
913 unsigned char *to = (
unsigned char *)smalloc(RSA_size(public_keys_[i]));
914 unsigned char *from = (
unsigned char *)smalloc(signature_size);
915 memcpy(from, signature, signature_size);
917 int size = RSA_public_decrypt(signature_size, from, to, public_keys_[i],
920 if ((size >= 0) && (
unsigned(size) == buffer_size)
921 && (memcmp(buffer, to, size) == 0)) {
937 void SignatureManager::CutLetter(
const unsigned char *buffer,
938 const unsigned buffer_size,
939 const char separator,
940 unsigned *letter_length,
941 unsigned *pos_after_mark) {
943 *letter_length = *pos_after_mark = 0;
945 if (pos == buffer_size) {
946 *pos_after_mark = pos;
947 *letter_length = pos;
951 if ((buffer[pos] ==
'\n') && (pos + 4 <= buffer_size)
952 && (buffer[pos + 1] == separator) && (buffer[pos + 2] == separator)
953 && (buffer[pos + 3] ==
'\n')) {
954 *letter_length = pos + 1;
960 *pos_after_mark = pos;
971 bool SignatureManager::VerifyLetter(
const unsigned char *buffer,
972 const unsigned buffer_size,
975 unsigned letter_length = 0;
976 CutLetter(buffer, buffer_size,
'-', &letter_length, &pos);
977 if (pos >= buffer_size)
980 string hash_str =
"";
981 unsigned hash_pos = pos;
983 if (pos == buffer_size)
985 if (buffer[pos] ==
'\n') {
989 hash_str.push_back(buffer[pos++]);
994 if (hash_printed != hash_computed)
998 return VerifyRsa(&buffer[hash_pos], hash_str.length(), &buffer[pos],
1001 return Verify(&buffer[hash_pos], hash_str.length(), &buffer[pos],
1011 bool SignatureManager::VerifyPkcs7(
const unsigned char *buffer,
1012 const unsigned buffer_size,
1013 unsigned char **content,
1014 unsigned *content_size,
1015 vector<string> *alt_uris) {
1019 BIO *bp_pkcs7 = BIO_new(BIO_s_mem());
1022 if (BIO_write(bp_pkcs7, buffer, buffer_size) <= 0) {
1027 PKCS7 *pkcs7 = NULL;
1028 pkcs7 = PEM_read_bio_PKCS7(bp_pkcs7, NULL, NULL, NULL);
1035 BIO *bp_content = BIO_new(BIO_s_mem());
1042 STACK_OF(X509) *extra_signers = NULL;
1044 bool result = PKCS7_verify(pkcs7, extra_signers, x509_store_, indata,
1047 BIO_free(bp_content);
1052 BUF_MEM *bufmem_content;
1053 BIO_get_mem_ptr(bp_content, &bufmem_content);
1055 (void)BIO_set_close(bp_content, BIO_NOCLOSE);
1056 BIO_free(bp_content);
1057 *content =
reinterpret_cast<unsigned char *
>(bufmem_content->data);
1058 *content_size = bufmem_content->length;
1059 free(bufmem_content);
1060 if (*content == NULL) {
1067 STACK_OF(X509) *signers = NULL;
1068 signers = PKCS7_get0_signers(pkcs7, NULL, 0);
1072 for (
int i = 0; i < sk_X509_num(signers); ++i) {
1073 X509 *this_signer = sk_X509_value(signers, i);
1074 GENERAL_NAMES *subject_alt_names = NULL;
1075 subject_alt_names =
reinterpret_cast<GENERAL_NAMES *
>(
1076 X509_get_ext_d2i(this_signer, NID_subject_alt_name, NULL, NULL));
1077 if (subject_alt_names != NULL) {
1078 for (
int j = 0; j < sk_GENERAL_NAME_num(subject_alt_names); ++j) {
1079 GENERAL_NAME *this_name = sk_GENERAL_NAME_value(subject_alt_names, j);
1080 if (this_name->type != GEN_URI)
1083 const char *name_ptr =
reinterpret_cast<const char *
>(
1084 #ifdef OPENSSL_API_INTERFACE_V11
1085 ASN1_STRING_get0_data(this_name->d.uniformResourceIdentifier));
1087 ASN1_STRING_data(this_name->d.uniformResourceIdentifier));
1089 int name_len = ASN1_STRING_length(
1090 this_name->d.uniformResourceIdentifier);
1091 if (!name_ptr || (name_len <= 0))
1093 alt_uris->push_back(
string(name_ptr, name_len));
1097 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,...)