1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "base/tlsutility.hpp"
4 #include "base/convert.hpp"
5 #include "base/logger.hpp"
6 #include "base/context.hpp"
7 #include "base/utility.hpp"
8 #include "base/application.hpp"
9 #include "base/exception.hpp"
10 #include <boost/asio/ssl/context.hpp>
16 static bool l_SSLInitialized = false;
17 static boost::mutex *l_Mutexes;
18 static boost::mutex l_RandomMutex;
21 static void OpenSSLLockingCallback(int mode, int type, const char *, int)
23 if (mode & CRYPTO_LOCK)
24 l_Mutexes[type].lock();
26 l_Mutexes[type].unlock();
29 static unsigned long OpenSSLIDCallback()
32 return (unsigned long)GetCurrentThreadId();
34 return (unsigned long)pthread_self();
37 #endif /* CRYPTO_LOCK */
40 * Initializes the OpenSSL library.
42 void InitializeOpenSSL()
48 SSL_load_error_strings();
50 SSL_COMP_get_compression_methods();
53 l_Mutexes = new boost::mutex[CRYPTO_num_locks()];
54 CRYPTO_set_locking_callback(&OpenSSLLockingCallback);
55 CRYPTO_set_id_callback(&OpenSSLIDCallback);
56 #endif /* CRYPTO_LOCK */
58 l_SSLInitialized = true;
61 static void SetupSslContext(SSL_CTX *sslContext, const String& pubkey, const String& privkey, const String& cakey)
65 long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_CIPHER_SERVER_PREFERENCE;
67 #ifdef SSL_OP_NO_COMPRESSION
68 flags |= SSL_OP_NO_COMPRESSION;
69 #endif /* SSL_OP_NO_COMPRESSION */
71 SSL_CTX_set_options(sslContext, flags);
73 SSL_CTX_set_mode(sslContext, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
74 SSL_CTX_set_session_id_context(sslContext, (const unsigned char *)"Icinga 2", 8);
76 if (!pubkey.IsEmpty()) {
77 if (!SSL_CTX_use_certificate_chain_file(sslContext, pubkey.CStr())) {
78 Log(LogCritical, "SSL")
79 << "Error with public key file '" << pubkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
80 BOOST_THROW_EXCEPTION(openssl_error()
81 << boost::errinfo_api_function("SSL_CTX_use_certificate_chain_file")
82 << errinfo_openssl_error(ERR_peek_error())
83 << boost::errinfo_file_name(pubkey));
87 if (!privkey.IsEmpty()) {
88 if (!SSL_CTX_use_PrivateKey_file(sslContext, privkey.CStr(), SSL_FILETYPE_PEM)) {
89 Log(LogCritical, "SSL")
90 << "Error with private key file '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
91 BOOST_THROW_EXCEPTION(openssl_error()
92 << boost::errinfo_api_function("SSL_CTX_use_PrivateKey_file")
93 << errinfo_openssl_error(ERR_peek_error())
94 << boost::errinfo_file_name(privkey));
97 if (!SSL_CTX_check_private_key(sslContext)) {
98 Log(LogCritical, "SSL")
99 << "Error checking private key '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
100 BOOST_THROW_EXCEPTION(openssl_error()
101 << boost::errinfo_api_function("SSL_CTX_check_private_key")
102 << errinfo_openssl_error(ERR_peek_error()));
106 if (!cakey.IsEmpty()) {
107 if (!SSL_CTX_load_verify_locations(sslContext, cakey.CStr(), nullptr)) {
108 Log(LogCritical, "SSL")
109 << "Error loading and verifying locations in ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
110 BOOST_THROW_EXCEPTION(openssl_error()
111 << boost::errinfo_api_function("SSL_CTX_load_verify_locations")
112 << errinfo_openssl_error(ERR_peek_error())
113 << boost::errinfo_file_name(cakey));
116 STACK_OF(X509_NAME) *cert_names;
118 cert_names = SSL_load_client_CA_file(cakey.CStr());
120 Log(LogCritical, "SSL")
121 << "Error loading client ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
122 BOOST_THROW_EXCEPTION(openssl_error()
123 << boost::errinfo_api_function("SSL_load_client_CA_file")
124 << errinfo_openssl_error(ERR_peek_error())
125 << boost::errinfo_file_name(cakey));
128 SSL_CTX_set_client_CA_list(sslContext, cert_names);
133 * Initializes an SSL context using the specified certificates.
135 * @param pubkey The public key.
136 * @param privkey The matching private key.
137 * @param cakey CA certificate chain file.
138 * @returns An SSL context.
140 std::shared_ptr<SSL_CTX> MakeSSLContext(const String& pubkey, const String& privkey, const String& cakey)
144 std::shared_ptr<SSL_CTX> sslContext = std::shared_ptr<SSL_CTX>(SSL_CTX_new(SSLv23_method()), SSL_CTX_free);
146 SetupSslContext(sslContext.get(), pubkey, privkey, cakey);
152 * Initializes an SSL context using the specified certificates.
154 * @param pubkey The public key.
155 * @param privkey The matching private key.
156 * @param cakey CA certificate chain file.
157 * @returns An SSL context.
159 std::shared_ptr<boost::asio::ssl::context> MakeAsioSslContext(const String& pubkey, const String& privkey, const String& cakey)
161 namespace ssl = boost::asio::ssl;
165 auto context (std::make_shared<ssl::context>(ssl::context::sslv23));
167 SetupSslContext(context->native_handle(), pubkey, privkey, cakey);
173 * Set the cipher list to the specified SSL context.
174 * @param context The ssl context.
175 * @param cipherList The ciper list.
177 void SetCipherListToSSLContext(const std::shared_ptr<boost::asio::ssl::context>& context, const String& cipherList)
181 if (SSL_CTX_set_cipher_list(context->native_handle(), cipherList.CStr()) == 0) {
182 Log(LogCritical, "SSL")
185 << "' does not specify any usable ciphers: "
186 << ERR_peek_error() << ", \""
187 << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
189 BOOST_THROW_EXCEPTION(openssl_error()
190 << boost::errinfo_api_function("SSL_CTX_set_cipher_list")
191 << errinfo_openssl_error(ERR_peek_error()));
196 * Set the minimum TLS protocol version to the specified SSL context.
198 * @param context The ssl context.
199 * @param tlsProtocolmin The minimum TLS protocol version.
201 void SetTlsProtocolminToSSLContext(const std::shared_ptr<boost::asio::ssl::context>& context, const String& tlsProtocolmin)
203 long flags = SSL_CTX_get_options(context->native_handle());
205 flags |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
207 #ifdef SSL_TXT_TLSV1_1
208 if (tlsProtocolmin == SSL_TXT_TLSV1_1)
209 flags |= SSL_OP_NO_TLSv1;
211 #endif /* SSL_TXT_TLSV1_1 */
212 #ifdef SSL_TXT_TLSV1_2
213 if (tlsProtocolmin == SSL_TXT_TLSV1_2)
214 flags |= SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1;
216 #endif /* SSL_TXT_TLSV1_2 */
217 if (tlsProtocolmin != SSL_TXT_TLSV1)
218 BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid TLS protocol version specified."));
220 SSL_CTX_set_options(context->native_handle(), flags);
224 * Loads a CRL and appends its certificates to the specified SSL context.
226 * @param context The SSL context.
227 * @param crlPath The path to the CRL file.
229 void AddCRLToSSLContext(const std::shared_ptr<boost::asio::ssl::context>& context, const String& crlPath)
232 X509_STORE *x509_store = SSL_CTX_get_cert_store(context->native_handle());
235 lookup = X509_STORE_add_lookup(x509_store, X509_LOOKUP_file());
238 Log(LogCritical, "SSL")
239 << "Error adding X509 store lookup: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
240 BOOST_THROW_EXCEPTION(openssl_error()
241 << boost::errinfo_api_function("X509_STORE_add_lookup")
242 << errinfo_openssl_error(ERR_peek_error()));
245 if (X509_LOOKUP_load_file(lookup, crlPath.CStr(), X509_FILETYPE_PEM) != 1) {
246 Log(LogCritical, "SSL")
247 << "Error loading crl file '" << crlPath << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
248 BOOST_THROW_EXCEPTION(openssl_error()
249 << boost::errinfo_api_function("X509_LOOKUP_load_file")
250 << errinfo_openssl_error(ERR_peek_error())
251 << boost::errinfo_file_name(crlPath));
254 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
255 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
256 X509_STORE_set1_param(x509_store, param);
257 X509_VERIFY_PARAM_free(param);
260 static String GetX509NameCN(X509_NAME *name)
265 int rc = X509_NAME_get_text_by_NID(name, NID_commonName, buffer, sizeof(buffer));
268 Log(LogCritical, "SSL")
269 << "Error with x509 NAME getting text by NID: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
270 BOOST_THROW_EXCEPTION(openssl_error()
271 << boost::errinfo_api_function("X509_NAME_get_text_by_NID")
272 << errinfo_openssl_error(ERR_peek_error()));
279 * Retrieves the common name for an X509 certificate.
281 * @param certificate The X509 certificate.
282 * @returns The common name.
284 String GetCertificateCN(const std::shared_ptr<X509>& certificate)
286 return GetX509NameCN(X509_get_subject_name(certificate.get()));
290 * Retrieves an X509 certificate from the specified file.
292 * @param pemfile The filename.
293 * @returns An X509 certificate.
295 std::shared_ptr<X509> GetX509Certificate(const String& pemfile)
299 BIO *fpcert = BIO_new(BIO_s_file());
302 Log(LogCritical, "SSL")
303 << "Error creating new BIO: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
304 BOOST_THROW_EXCEPTION(openssl_error()
305 << boost::errinfo_api_function("BIO_new")
306 << errinfo_openssl_error(ERR_peek_error()));
309 if (BIO_read_filename(fpcert, pemfile.CStr()) < 0) {
310 Log(LogCritical, "SSL")
311 << "Error reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
312 BOOST_THROW_EXCEPTION(openssl_error()
313 << boost::errinfo_api_function("BIO_read_filename")
314 << errinfo_openssl_error(ERR_peek_error())
315 << boost::errinfo_file_name(pemfile));
318 cert = PEM_read_bio_X509_AUX(fpcert, nullptr, nullptr, nullptr);
320 Log(LogCritical, "SSL")
321 << "Error on bio X509 AUX reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
322 BOOST_THROW_EXCEPTION(openssl_error()
323 << boost::errinfo_api_function("PEM_read_bio_X509_AUX")
324 << errinfo_openssl_error(ERR_peek_error())
325 << boost::errinfo_file_name(pemfile));
330 return std::shared_ptr<X509>(cert, X509_free);
333 int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile, const String& certfile, bool ca)
339 RSA *rsa = RSA_new();
340 BIGNUM *e = BN_new();
343 Log(LogCritical, "SSL")
344 << "Error while creating RSA key: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
345 BOOST_THROW_EXCEPTION(openssl_error()
346 << boost::errinfo_api_function("RSA_generate_key")
347 << errinfo_openssl_error(ERR_peek_error()));
350 BN_set_word(e, RSA_F4);
352 if (!RSA_generate_key_ex(rsa, 4096, e, nullptr)) {
353 Log(LogCritical, "SSL")
354 << "Error while creating RSA key: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
355 BOOST_THROW_EXCEPTION(openssl_error()
356 << boost::errinfo_api_function("RSA_generate_key")
357 << errinfo_openssl_error(ERR_peek_error()));
362 Log(LogInformation, "base")
363 << "Writing private key to '" << keyfile << "'.";
365 BIO *bio = BIO_new_file(const_cast<char *>(keyfile.CStr()), "w");
368 Log(LogCritical, "SSL")
369 << "Error while opening private RSA key file '" << keyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
370 BOOST_THROW_EXCEPTION(openssl_error()
371 << boost::errinfo_api_function("BIO_new_file")
372 << errinfo_openssl_error(ERR_peek_error())
373 << boost::errinfo_file_name(keyfile));
376 if (!PEM_write_bio_RSAPrivateKey(bio, rsa, nullptr, nullptr, 0, nullptr, nullptr)) {
377 Log(LogCritical, "SSL")
378 << "Error while writing private RSA key to file '" << keyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
379 BOOST_THROW_EXCEPTION(openssl_error()
380 << boost::errinfo_api_function("PEM_write_bio_RSAPrivateKey")
381 << errinfo_openssl_error(ERR_peek_error())
382 << boost::errinfo_file_name(keyfile));
388 chmod(keyfile.CStr(), 0600);
391 EVP_PKEY *key = EVP_PKEY_new();
392 EVP_PKEY_assign_RSA(key, rsa);
394 if (!certfile.IsEmpty()) {
395 X509_NAME *subject = X509_NAME_new();
396 X509_NAME_add_entry_by_txt(subject, "CN", MBSTRING_ASC, (unsigned char *)cn.CStr(), -1, -1, 0);
398 std::shared_ptr<X509> cert = CreateCert(key, subject, subject, key, ca);
400 X509_NAME_free(subject);
402 Log(LogInformation, "base")
403 << "Writing X509 certificate to '" << certfile << "'.";
405 bio = BIO_new_file(const_cast<char *>(certfile.CStr()), "w");
408 Log(LogCritical, "SSL")
409 << "Error while opening certificate file '" << certfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
410 BOOST_THROW_EXCEPTION(openssl_error()
411 << boost::errinfo_api_function("BIO_new_file")
412 << errinfo_openssl_error(ERR_peek_error())
413 << boost::errinfo_file_name(certfile));
416 if (!PEM_write_bio_X509(bio, cert.get())) {
417 Log(LogCritical, "SSL")
418 << "Error while writing certificate to file '" << certfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
419 BOOST_THROW_EXCEPTION(openssl_error()
420 << boost::errinfo_api_function("PEM_write_bio_X509")
421 << errinfo_openssl_error(ERR_peek_error())
422 << boost::errinfo_file_name(certfile));
428 if (!csrfile.IsEmpty()) {
429 X509_REQ *req = X509_REQ_new();
434 X509_REQ_set_version(req, 0);
435 X509_REQ_set_pubkey(req, key);
437 X509_NAME *name = X509_REQ_get_subject_name(req);
438 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)cn.CStr(), -1, -1, 0);
441 String san = "DNS:" + cn;
442 X509_EXTENSION *subjectAltNameExt = X509V3_EXT_conf_nid(nullptr, nullptr, NID_subject_alt_name, const_cast<char *>(san.CStr()));
443 if (subjectAltNameExt) {
444 /* OpenSSL 0.9.8 requires STACK_OF(X509_EXTENSION), otherwise we would just use stack_st_X509_EXTENSION. */
445 STACK_OF(X509_EXTENSION) *exts = sk_X509_EXTENSION_new_null();
446 sk_X509_EXTENSION_push(exts, subjectAltNameExt);
447 X509_REQ_add_extensions(req, exts);
448 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
452 X509_REQ_sign(req, key, EVP_sha256());
454 Log(LogInformation, "base")
455 << "Writing certificate signing request to '" << csrfile << "'.";
457 bio = BIO_new_file(const_cast<char *>(csrfile.CStr()), "w");
460 Log(LogCritical, "SSL")
461 << "Error while opening CSR file '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
462 BOOST_THROW_EXCEPTION(openssl_error()
463 << boost::errinfo_api_function("BIO_new_file")
464 << errinfo_openssl_error(ERR_peek_error())
465 << boost::errinfo_file_name(csrfile));
468 if (!PEM_write_bio_X509_REQ(bio, req)) {
469 Log(LogCritical, "SSL")
470 << "Error while writing CSR to file '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
471 BOOST_THROW_EXCEPTION(openssl_error()
472 << boost::errinfo_api_function("PEM_write_bio_X509")
473 << errinfo_openssl_error(ERR_peek_error())
474 << boost::errinfo_file_name(csrfile));
487 std::shared_ptr<X509> CreateCert(EVP_PKEY *pubkey, X509_NAME *subject, X509_NAME *issuer, EVP_PKEY *cakey, bool ca)
489 X509 *cert = X509_new();
490 X509_set_version(cert, 2);
491 X509_gmtime_adj(X509_get_notBefore(cert), 0);
492 X509_gmtime_adj(X509_get_notAfter(cert), 365 * 24 * 60 * 60 * 15);
493 X509_set_pubkey(cert, pubkey);
495 X509_set_subject_name(cert, subject);
496 X509_set_issuer_name(cert, issuer);
498 String id = Utility::NewUniqueID();
502 unsigned char digest[SHA_DIGEST_LENGTH];
504 if (!SHA1_Init(&context)) {
505 Log(LogCritical, "SSL")
506 << "Error on SHA1 Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
507 BOOST_THROW_EXCEPTION(openssl_error()
508 << boost::errinfo_api_function("SHA1_Init")
509 << errinfo_openssl_error(ERR_peek_error()));
512 if (!SHA1_Update(&context, (unsigned char*)id.CStr(), id.GetLength())) {
513 Log(LogCritical, "SSL")
514 << "Error on SHA1 Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
515 BOOST_THROW_EXCEPTION(openssl_error()
516 << boost::errinfo_api_function("SHA1_Update")
517 << errinfo_openssl_error(ERR_peek_error()));
520 if (!SHA1_Final(digest, &context)) {
521 Log(LogCritical, "SSL")
522 << "Error on SHA1 Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
523 BOOST_THROW_EXCEPTION(openssl_error()
524 << boost::errinfo_api_function("SHA1_Final")
525 << errinfo_openssl_error(ERR_peek_error()));
528 BIGNUM *bn = BN_new();
529 BN_bin2bn(digest, sizeof(digest), bn);
530 BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(cert));
534 X509V3_set_ctx_nodb(&ctx);
535 X509V3_set_ctx(&ctx, cert, cert, nullptr, nullptr, 0);
540 attr = "critical,CA:TRUE";
542 attr = "critical,CA:FALSE";
544 X509_EXTENSION *basicConstraintsExt = X509V3_EXT_conf_nid(nullptr, &ctx, NID_basic_constraints, const_cast<char *>(attr));
546 if (basicConstraintsExt) {
547 X509_add_ext(cert, basicConstraintsExt, -1);
548 X509_EXTENSION_free(basicConstraintsExt);
551 String cn = GetX509NameCN(subject);
554 String san = "DNS:" + cn;
555 X509_EXTENSION *subjectAltNameExt = X509V3_EXT_conf_nid(nullptr, &ctx, NID_subject_alt_name, const_cast<char *>(san.CStr()));
556 if (subjectAltNameExt) {
557 X509_add_ext(cert, subjectAltNameExt, -1);
558 X509_EXTENSION_free(subjectAltNameExt);
562 X509_sign(cert, cakey, EVP_sha256());
564 return std::shared_ptr<X509>(cert, X509_free);
567 String GetIcingaCADir()
569 return Configuration::DataDir + "/ca";
572 std::shared_ptr<X509> CreateCertIcingaCA(EVP_PKEY *pubkey, X509_NAME *subject)
576 String cadir = GetIcingaCADir();
578 String cakeyfile = cadir + "/ca.key";
582 BIO *cakeybio = BIO_new_file(const_cast<char *>(cakeyfile.CStr()), "r");
585 Log(LogCritical, "SSL")
586 << "Could not open CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
587 return std::shared_ptr<X509>();
590 rsa = PEM_read_bio_RSAPrivateKey(cakeybio, nullptr, nullptr, nullptr);
593 Log(LogCritical, "SSL")
594 << "Could not read RSA key from CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
595 return std::shared_ptr<X509>();
600 String cacertfile = cadir + "/ca.crt";
602 std::shared_ptr<X509> cacert = GetX509Certificate(cacertfile);
604 EVP_PKEY *privkey = EVP_PKEY_new();
605 EVP_PKEY_assign_RSA(privkey, rsa);
607 return CreateCert(pubkey, subject, X509_get_subject_name(cacert.get()), privkey, false);
610 std::shared_ptr<X509> CreateCertIcingaCA(const std::shared_ptr<X509>& cert)
612 std::shared_ptr<EVP_PKEY> pkey = std::shared_ptr<EVP_PKEY>(X509_get_pubkey(cert.get()), EVP_PKEY_free);
613 return CreateCertIcingaCA(pkey.get(), X509_get_subject_name(cert.get()));
616 String CertificateToString(const std::shared_ptr<X509>& cert)
618 BIO *mem = BIO_new(BIO_s_mem());
619 PEM_write_bio_X509(mem, cert.get());
622 long len = BIO_get_mem_data(mem, &data);
624 String result = String(data, data + len);
631 std::shared_ptr<X509> StringToCertificate(const String& cert)
633 BIO *bio = BIO_new(BIO_s_mem());
634 BIO_write(bio, (const void *)cert.CStr(), cert.GetLength());
636 X509 *rawCert = PEM_read_bio_X509_AUX(bio, nullptr, nullptr, nullptr);
641 BOOST_THROW_EXCEPTION(std::invalid_argument("The specified X509 certificate is invalid."));
643 return std::shared_ptr<X509>(rawCert, X509_free);
646 String PBKDF2_SHA1(const String& password, const String& salt, int iterations)
648 unsigned char digest[SHA_DIGEST_LENGTH];
649 PKCS5_PBKDF2_HMAC_SHA1(password.CStr(), password.GetLength(), reinterpret_cast<const unsigned char *>(salt.CStr()), salt.GetLength(),
650 iterations, sizeof(digest), digest);
652 char output[SHA_DIGEST_LENGTH*2+1];
653 for (int i = 0; i < SHA_DIGEST_LENGTH; i++)
654 sprintf(output + 2 * i, "%02x", digest[i]);
659 String PBKDF2_SHA256(const String& password, const String& salt, int iterations)
661 unsigned char digest[SHA256_DIGEST_LENGTH];
662 PKCS5_PBKDF2_HMAC(password.CStr(), password.GetLength(), reinterpret_cast<const unsigned char *>(salt.CStr()),
663 salt.GetLength(), iterations, EVP_sha256(), SHA256_DIGEST_LENGTH, digest);
665 char output[SHA256_DIGEST_LENGTH*2+1];
666 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
667 sprintf(output + 2 * i, "%02x", digest[i]);
672 String SHA1(const String& s, bool binary)
676 unsigned char digest[SHA_DIGEST_LENGTH];
678 if (!SHA1_Init(&context)) {
679 Log(LogCritical, "SSL")
680 << "Error on SHA Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
681 BOOST_THROW_EXCEPTION(openssl_error()
682 << boost::errinfo_api_function("SHA1_Init")
683 << errinfo_openssl_error(ERR_peek_error()));
686 if (!SHA1_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) {
687 Log(LogCritical, "SSL")
688 << "Error on SHA Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
689 BOOST_THROW_EXCEPTION(openssl_error()
690 << boost::errinfo_api_function("SHA1_Update")
691 << errinfo_openssl_error(ERR_peek_error()));
694 if (!SHA1_Final(digest, &context)) {
695 Log(LogCritical, "SSL")
696 << "Error on SHA Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
697 BOOST_THROW_EXCEPTION(openssl_error()
698 << boost::errinfo_api_function("SHA1_Final")
699 << errinfo_openssl_error(ERR_peek_error()));
703 return String(reinterpret_cast<const char*>(digest), reinterpret_cast<const char *>(digest + SHA_DIGEST_LENGTH));
705 char output[SHA_DIGEST_LENGTH*2+1];
706 for (int i = 0; i < 20; i++)
707 sprintf(output + 2 * i, "%02x", digest[i]);
712 String SHA256(const String& s)
716 unsigned char digest[SHA256_DIGEST_LENGTH];
718 if (!SHA256_Init(&context)) {
719 Log(LogCritical, "SSL")
720 << "Error on SHA256 Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
721 BOOST_THROW_EXCEPTION(openssl_error()
722 << boost::errinfo_api_function("SHA256_Init")
723 << errinfo_openssl_error(ERR_peek_error()));
726 if (!SHA256_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) {
727 Log(LogCritical, "SSL")
728 << "Error on SHA256 Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
729 BOOST_THROW_EXCEPTION(openssl_error()
730 << boost::errinfo_api_function("SHA256_Update")
731 << errinfo_openssl_error(ERR_peek_error()));
734 if (!SHA256_Final(digest, &context)) {
735 Log(LogCritical, "SSL")
736 << "Error on SHA256 Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
737 BOOST_THROW_EXCEPTION(openssl_error()
738 << boost::errinfo_api_function("SHA256_Final")
739 << errinfo_openssl_error(ERR_peek_error()));
742 char output[SHA256_DIGEST_LENGTH*2+1];
743 for (int i = 0; i < 32; i++)
744 sprintf(output + 2 * i, "%02x", digest[i]);
749 String RandomString(int length)
751 auto *bytes = new unsigned char[length];
753 /* Ensure that password generation is atomic. RAND_bytes is not thread-safe
754 * in OpenSSL < 1.1.0.
756 boost::mutex::scoped_lock lock(l_RandomMutex);
758 if (!RAND_bytes(bytes, length)) {
763 Log(LogCritical, "SSL")
764 << "Error for RAND_bytes: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
765 BOOST_THROW_EXCEPTION(openssl_error()
766 << boost::errinfo_api_function("RAND_bytes")
767 << errinfo_openssl_error(ERR_peek_error()));
772 auto *output = new char[length * 2 + 1];
773 for (int i = 0; i < length; i++)
774 sprintf(output + 2 * i, "%02x", bytes[i]);
776 String result = output;
783 bool VerifyCertificate(const std::shared_ptr<X509>& caCertificate, const std::shared_ptr<X509>& certificate)
785 X509_STORE *store = X509_STORE_new();
790 X509_STORE_add_cert(store, caCertificate.get());
792 X509_STORE_CTX *csc = X509_STORE_CTX_new();
793 X509_STORE_CTX_init(csc, store, certificate.get(), nullptr);
795 int rc = X509_verify_cert(csc);
797 X509_STORE_CTX_free(csc);
798 X509_STORE_free(store);
803 std::string to_string(const errinfo_openssl_error& e)
805 std::ostringstream tmp;
806 int code = e.value();
809 const char *message = ERR_error_string(code, errbuf);
812 message = "Unknown error.";
814 tmp << code << ", \"" << message << "\"";
815 return "[errinfo_openssl_error]" + tmp.str() + "\n";