17 #include <openssl/bn.h>
18 #include <openssl/evp.h>
19 #include <openssl/pkcs7.h>
20 #include <openssl/x509v3.h>
52 const 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 const 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 const 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 const 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());
441 PEM_write_bio_PrivateKey(bp, private_key_, NULL, NULL, 0, 0, NULL);
443 char *bio_privkey_text;
444 long bytes = BIO_get_mem_data(bp, &bio_privkey_text);
446 std::string bio_privkey_str(bio_privkey_text, bytes);
448 return bio_privkey_str;
452 std::string SignatureManager::GetPrivateMasterKey() {
453 if (!private_master_key_)
456 BIO *bp = BIO_new(BIO_s_mem());
458 const bool rvb = PEM_write_bio_RSAPrivateKey(bp, private_master_key_, NULL,
461 char *bio_master_privkey_text;
462 long bytes = BIO_get_mem_data(bp, &bio_master_privkey_text);
464 std::string bio_master_privkey_str(bio_master_privkey_text, bytes);
466 return bio_master_privkey_str;
469 RSA *SignatureManager::GenerateRsaKeyPair() {
471 BIGNUM *bn = BN_new();
472 int retval = BN_set_word(bn, RSA_F4);
474 #ifdef OPENSSL_API_INTERFACE_V09
475 rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL);
479 retval = RSA_generate_key_ex(rsa, 2048, bn, NULL);
490 void SignatureManager::GenerateMasterKeyPair() {
491 UnloadPrivateMasterKey();
492 UnloadPublicRsaKeys();
494 RSA *rsa = GenerateRsaKeyPair();
495 private_master_key_ = RSAPrivateKey_dup(rsa);
496 public_keys_.push_back(RSAPublicKey_dup(rsa));
503 void SignatureManager::GenerateCertificate(
const std::string &cn) {
508 RSA *rsa = GenerateRsaKeyPair();
509 private_key_ = EVP_PKEY_new();
510 retval = EVP_PKEY_set1_RSA(private_key_, RSAPrivateKey_dup(rsa));
512 EVP_PKEY *pkey = EVP_PKEY_new();
513 retval = EVP_PKEY_set1_RSA(pkey, rsa);
516 certificate_ = X509_new();
517 X509_set_version(certificate_, 2L);
518 X509_set_pubkey(certificate_, pkey);
522 unsigned long rnd_serial_no = prng.
Next(uint64_t(1) + uint32_t(-1));
523 rnd_serial_no = rnd_serial_no
524 | uint64_t(prng.
Next(uint64_t(1) + uint32_t(-1))) << 32;
525 ASN1_INTEGER_set(X509_get_serialNumber(certificate_), rnd_serial_no);
529 reinterpret_cast<ASN1_TIME *>(X509_get_notBefore(certificate_)), 0);
532 reinterpret_cast<ASN1_TIME *>(X509_get_notAfter(certificate_)),
535 X509_NAME *name = X509_get_subject_name(certificate_);
536 #ifdef OPENSSL_API_INTERFACE_V09
537 X509_NAME_add_entry_by_txt(
538 name,
"CN", MBSTRING_ASC,
539 const_cast<unsigned char *>(
540 reinterpret_cast<const unsigned char *>(cn.c_str())),
543 X509_NAME_add_entry_by_txt(
544 name,
"CN", MBSTRING_ASC,
545 reinterpret_cast<const unsigned char *>(cn.c_str()), -1, -1, 0);
547 retval = X509_set_issuer_name(certificate_, name);
550 #ifdef OPENSSL_API_INTERFACE_V09
551 retval = X509_sign(certificate_, pkey, EVP_sha1());
553 retval = X509_sign(certificate_, pkey, EVP_sha256());
562 bool SignatureManager::LoadBlacklist(
const std::string &path_blacklist,
566 path_blacklist.c_str());
570 const int fd = open(path_blacklist.c_str(), O_RDONLY);
573 std::string blacklist_buffer;
579 unsigned num_bytes = 0;
580 while (num_bytes < blacklist_buffer.size()) {
581 const string line =
GetLineMem(blacklist_buffer.data() + num_bytes,
582 blacklist_buffer.size() - num_bytes);
583 blacklist_.push_back(line);
584 num_bytes += line.length() + 1;
591 vector<string> SignatureManager::GetBlacklist() {
604 bool SignatureManager::LoadTrustedCaCrl(
const string &path_list) {
610 const vector<string> paths =
SplitString(path_list,
':');
611 for (
unsigned i = 0; i < paths.size(); ++i) {
613 X509_LOOKUP_add_dir(x509_lookup_, paths[i].c_str(), X509_FILETYPE_PEM);
633 unsigned char *buffer = NULL;
635 buffer_size = i2d_X509(certificate_, &buffer);
652 string SignatureManager::FingerprintCertificate(
654 const shash::Any hash = HashCertificate(hash_algorithm);
658 const string hash_str = hash.
ToString();
660 for (
unsigned i = 0; i < hash_str.length(); ++i) {
662 if ((i > 0) && (i % 2 == 0))
665 result += toupper(hash_str[i]);
674 shash::Any SignatureManager::MkFromFingerprint(
const std::string &fingerprint) {
676 for (
unsigned i = 0; i < fingerprint.length(); ++i) {
677 if ((fingerprint[i] ==
' ') || (fingerprint[i] ==
'\t')
678 || (fingerprint[i] ==
'#')) {
681 if (fingerprint[i] !=
':')
682 convert.push_back(tolower(fingerprint[i]));
692 string SignatureManager::Whois() {
694 return "No certificate loaded";
697 X509_NAME *subject = X509_get_subject_name(certificate_);
698 X509_NAME *issuer = X509_get_issuer_name(certificate_);
700 buffer = X509_NAME_oneline(subject, NULL, 0);
702 result =
"Publisher: " + string(buffer);
705 buffer = X509_NAME_oneline(issuer, NULL, 0);
707 result +=
"\nCertificate issued by: " + string(buffer);
714 bool SignatureManager::WriteCertificateMem(
unsigned char **buffer,
715 unsigned *buffer_size) {
716 BIO *
mem = BIO_new(BIO_s_mem());
719 if (!PEM_write_bio_X509(mem, certificate_)) {
725 *buffer_size = BIO_get_mem_data(mem, &bio_buffer);
726 *buffer =
reinterpret_cast<unsigned char *
>(smalloc(*buffer_size));
727 memcpy(*buffer, bio_buffer, *buffer_size);
738 bool SignatureManager::KeysMatch() {
739 if (!certificate_ || !private_key_)
743 const unsigned char *sign_me =
reinterpret_cast<const unsigned char *
>(
745 unsigned char *signature = NULL;
746 unsigned signature_size;
747 if (Sign(sign_me, 7, &signature, &signature_size)
748 &&
Verify(sign_me, 7, signature, signature_size)) {
760 bool SignatureManager::VerifyCaChain() {
764 X509_STORE_CTX *csc = NULL;
765 csc = X509_STORE_CTX_new();
768 X509_STORE_CTX_init(csc, x509_store_, certificate_, NULL);
769 const bool result = X509_verify_cert(csc) == 1;
770 X509_STORE_CTX_free(csc);
781 bool SignatureManager::Sign(
const unsigned char *buffer,
782 const unsigned buffer_size,
783 unsigned char **signature,
784 unsigned *signature_size) {
792 #ifdef OPENSSL_API_INTERFACE_V11
793 EVP_MD_CTX *ctx_ptr = EVP_MD_CTX_new();
796 EVP_MD_CTX_init(&ctx);
797 EVP_MD_CTX *ctx_ptr = &
ctx;
800 *signature =
reinterpret_cast<unsigned char *
>(
801 smalloc(EVP_PKEY_size(private_key_)));
802 if (EVP_SignInit(ctx_ptr, EVP_sha1())
803 && EVP_SignUpdate(ctx_ptr, buffer, buffer_size)
804 && EVP_SignFinal(ctx_ptr, *signature, signature_size, private_key_)) {
807 #ifdef OPENSSL_API_INTERFACE_V11
808 EVP_MD_CTX_free(ctx_ptr);
810 EVP_MD_CTX_cleanup(&ctx);
827 bool SignatureManager::SignRsa(
const unsigned char *buffer,
828 const unsigned buffer_size,
829 unsigned char **signature,
830 unsigned *signature_size) {
831 if (!private_master_key_) {
837 unsigned char *to = (
unsigned char *)smalloc(RSA_size(private_master_key_));
838 unsigned char *from = (
unsigned char *)smalloc(buffer_size);
839 memcpy(from, buffer, buffer_size);
841 const int size = RSA_private_encrypt(buffer_size, from, to,
842 private_master_key_, RSA_PKCS1_PADDING);
850 *signature_size =
size;
861 const unsigned buffer_size,
862 const unsigned char *signature,
863 const unsigned signature_size) {
868 #ifdef OPENSSL_API_INTERFACE_V11
869 EVP_MD_CTX *ctx_ptr = EVP_MD_CTX_new();
872 EVP_MD_CTX_init(&ctx);
873 EVP_MD_CTX *ctx_ptr = &
ctx;
876 EVP_PKEY *pubkey = X509_get_pubkey(certificate_);
877 if (EVP_VerifyInit(ctx_ptr, EVP_sha1())
878 && EVP_VerifyUpdate(ctx_ptr, buffer, buffer_size) &&
880 EVP_VerifyFinal(ctx_ptr, const_cast<unsigned char *>(signature),
881 signature_size, pubkey)
883 EVP_VerifyFinal(ctx_ptr, signature, signature_size, pubkey)
889 EVP_PKEY_free(pubkey);
890 #ifdef OPENSSL_API_INTERFACE_V11
891 EVP_MD_CTX_free(ctx_ptr);
893 EVP_MD_CTX_cleanup(&ctx);
906 bool SignatureManager::VerifyRsa(
const unsigned char *buffer,
907 const unsigned buffer_size,
908 const unsigned char *signature,
909 const unsigned signature_size) {
910 for (
unsigned i = 0, s = public_keys_.size(); i < s; ++i) {
911 if (buffer_size > (
unsigned)RSA_size(public_keys_[i]))
914 unsigned char *to = (
unsigned char *)smalloc(RSA_size(public_keys_[i]));
915 unsigned char *from = (
unsigned char *)smalloc(signature_size);
916 memcpy(from, signature, signature_size);
918 const int size = RSA_public_decrypt(signature_size, from, to,
919 public_keys_[i], RSA_PKCS1_PADDING);
921 if ((size >= 0) && (
unsigned(size) == buffer_size)
922 && (memcmp(buffer, to, size) == 0)) {
938 void SignatureManager::CutLetter(
const unsigned char *buffer,
939 const unsigned buffer_size,
940 const char separator,
941 unsigned *letter_length,
942 unsigned *pos_after_mark) {
944 *letter_length = *pos_after_mark = 0;
946 if (pos == buffer_size) {
947 *pos_after_mark = pos;
948 *letter_length = pos;
952 if ((buffer[pos] ==
'\n') && (pos + 4 <= buffer_size)
953 && (buffer[pos + 1] == separator) && (buffer[pos + 2] == separator)
954 && (buffer[pos + 3] ==
'\n')) {
955 *letter_length = pos + 1;
961 *pos_after_mark = pos;
972 bool SignatureManager::VerifyLetter(
const unsigned char *buffer,
973 const unsigned buffer_size,
976 unsigned letter_length = 0;
977 CutLetter(buffer, buffer_size,
'-', &letter_length, &pos);
978 if (pos >= buffer_size)
981 string hash_str =
"";
982 const unsigned hash_pos = pos;
984 if (pos == buffer_size)
986 if (buffer[pos] ==
'\n') {
990 hash_str.push_back(buffer[pos++]);
995 if (hash_printed != hash_computed)
999 return VerifyRsa(&buffer[hash_pos], hash_str.length(), &buffer[pos],
1002 return Verify(&buffer[hash_pos], hash_str.length(), &buffer[pos],
1012 bool SignatureManager::VerifyPkcs7(
const unsigned char *buffer,
1013 const unsigned buffer_size,
1014 unsigned char **content,
1015 unsigned *content_size,
1016 vector<string> *alt_uris) {
1020 BIO *bp_pkcs7 = BIO_new(BIO_s_mem());
1023 if (BIO_write(bp_pkcs7, buffer, buffer_size) <= 0) {
1028 PKCS7 *pkcs7 = NULL;
1029 pkcs7 = PEM_read_bio_PKCS7(bp_pkcs7, NULL, NULL, NULL);
1036 BIO *bp_content = BIO_new(BIO_s_mem());
1042 const int flags = 0;
1043 STACK_OF(X509) *extra_signers = NULL;
1045 const bool result = PKCS7_verify(pkcs7, extra_signers, x509_store_, indata,
1048 BIO_free(bp_content);
1053 BUF_MEM *bufmem_content;
1054 BIO_get_mem_ptr(bp_content, &bufmem_content);
1056 (void)BIO_set_close(bp_content, BIO_NOCLOSE);
1057 BIO_free(bp_content);
1058 *content =
reinterpret_cast<unsigned char *
>(bufmem_content->data);
1059 *content_size = bufmem_content->length;
1060 free(bufmem_content);
1061 if (*content == NULL) {
1068 STACK_OF(X509) *signers = NULL;
1069 signers = PKCS7_get0_signers(pkcs7, NULL, 0);
1073 for (
int i = 0; i < sk_X509_num(signers); ++i) {
1074 X509 *this_signer = sk_X509_value(signers, i);
1075 GENERAL_NAMES *subject_alt_names = NULL;
1076 subject_alt_names =
reinterpret_cast<GENERAL_NAMES *
>(
1077 X509_get_ext_d2i(this_signer, NID_subject_alt_name, NULL, NULL));
1078 if (subject_alt_names != NULL) {
1079 for (
int j = 0; j < sk_GENERAL_NAME_num(subject_alt_names); ++j) {
1080 GENERAL_NAME *this_name = sk_GENERAL_NAME_value(subject_alt_names, j);
1081 if (this_name->type != GEN_URI)
1084 const char *name_ptr =
reinterpret_cast<const char *
>(
1085 #ifdef OPENSSL_API_INTERFACE_V11
1086 ASN1_STRING_get0_data(this_name->d.uniformResourceIdentifier));
1088 ASN1_STRING_data(this_name->d.uniformResourceIdentifier));
1090 const int name_len =
1091 ASN1_STRING_length(this_name->d.uniformResourceIdentifier);
1092 if (!name_ptr || (name_len <= 0))
1094 alt_uris->push_back(
string(name_ptr, name_len));
1098 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,...)