]> granicus.if.org Git - icinga2/blob - lib/base/tlsutility.cpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / base / tlsutility.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
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>
11 #include <fstream>
12
13 namespace icinga
14 {
15
16 static bool l_SSLInitialized = false;
17 static boost::mutex *l_Mutexes;
18 static boost::mutex l_RandomMutex;
19
20 #ifdef CRYPTO_LOCK
21 static void OpenSSLLockingCallback(int mode, int type, const char *, int)
22 {
23         if (mode & CRYPTO_LOCK)
24                 l_Mutexes[type].lock();
25         else
26                 l_Mutexes[type].unlock();
27 }
28
29 static unsigned long OpenSSLIDCallback()
30 {
31 #ifdef _WIN32
32         return (unsigned long)GetCurrentThreadId();
33 #else /* _WIN32 */
34         return (unsigned long)pthread_self();
35 #endif /* _WIN32 */
36 }
37 #endif /* CRYPTO_LOCK */
38
39 /**
40  * Initializes the OpenSSL library.
41  */
42 void InitializeOpenSSL()
43 {
44         if (l_SSLInitialized)
45                 return;
46
47         SSL_library_init();
48         SSL_load_error_strings();
49
50         SSL_COMP_get_compression_methods();
51
52 #ifdef CRYPTO_LOCK
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 */
57
58         l_SSLInitialized = true;
59 }
60
61 static void SetupSslContext(SSL_CTX *sslContext, const String& pubkey, const String& privkey, const String& cakey)
62 {
63         char errbuf[256];
64
65         long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_CIPHER_SERVER_PREFERENCE;
66
67 #ifdef SSL_OP_NO_COMPRESSION
68         flags |= SSL_OP_NO_COMPRESSION;
69 #endif /* SSL_OP_NO_COMPRESSION */
70
71         SSL_CTX_set_options(sslContext, flags);
72
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);
75
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));
84                 }
85         }
86
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));
95                 }
96
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()));
103                 }
104         }
105
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));
114                 }
115
116                 STACK_OF(X509_NAME) *cert_names;
117
118                 cert_names = SSL_load_client_CA_file(cakey.CStr());
119                 if (!cert_names) {
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));
126                 }
127
128                 SSL_CTX_set_client_CA_list(sslContext, cert_names);
129         }
130 }
131
132 /**
133  * Initializes an SSL context using the specified certificates.
134  *
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.
139  */
140 std::shared_ptr<SSL_CTX> MakeSSLContext(const String& pubkey, const String& privkey, const String& cakey)
141 {
142         InitializeOpenSSL();
143
144         std::shared_ptr<SSL_CTX> sslContext = std::shared_ptr<SSL_CTX>(SSL_CTX_new(SSLv23_method()), SSL_CTX_free);
145
146         SetupSslContext(sslContext.get(), pubkey, privkey, cakey);
147
148         return sslContext;
149 }
150
151 /**
152  * Initializes an SSL context using the specified certificates.
153  *
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.
158  */
159 std::shared_ptr<boost::asio::ssl::context> MakeAsioSslContext(const String& pubkey, const String& privkey, const String& cakey)
160 {
161         namespace ssl = boost::asio::ssl;
162
163         InitializeOpenSSL();
164
165         auto context (std::make_shared<ssl::context>(ssl::context::sslv23));
166
167         SetupSslContext(context->native_handle(), pubkey, privkey, cakey);
168
169         return context;
170 }
171
172 /**
173  * Set the cipher list to the specified SSL context.
174  * @param context The ssl context.
175  * @param cipherList The ciper list.
176  **/
177 void SetCipherListToSSLContext(const std::shared_ptr<boost::asio::ssl::context>& context, const String& cipherList)
178 {
179         char errbuf[256];
180
181         if (SSL_CTX_set_cipher_list(context->native_handle(), cipherList.CStr()) == 0) {
182                 Log(LogCritical, "SSL")
183                         << "Cipher list '"
184                         << cipherList
185                         << "' does not specify any usable ciphers: "
186                         << ERR_peek_error() << ", \""
187                         << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
188
189                 BOOST_THROW_EXCEPTION(openssl_error()
190                         << boost::errinfo_api_function("SSL_CTX_set_cipher_list")
191                         << errinfo_openssl_error(ERR_peek_error()));
192         }
193 }
194
195 /**
196  * Set the minimum TLS protocol version to the specified SSL context.
197  *
198  * @param context The ssl context.
199  * @param tlsProtocolmin The minimum TLS protocol version.
200  */
201 void SetTlsProtocolminToSSLContext(const std::shared_ptr<boost::asio::ssl::context>& context, const String& tlsProtocolmin)
202 {
203         long flags = SSL_CTX_get_options(context->native_handle());
204
205         flags |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
206
207 #ifdef SSL_TXT_TLSV1_1
208         if (tlsProtocolmin == SSL_TXT_TLSV1_1)
209                 flags |= SSL_OP_NO_TLSv1;
210         else
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;
215         else
216 #endif /* SSL_TXT_TLSV1_2 */
217         if (tlsProtocolmin != SSL_TXT_TLSV1)
218                 BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid TLS protocol version specified."));
219
220         SSL_CTX_set_options(context->native_handle(), flags);
221 }
222
223 /**
224  * Loads a CRL and appends its certificates to the specified SSL context.
225  *
226  * @param context The SSL context.
227  * @param crlPath The path to the CRL file.
228  */
229 void AddCRLToSSLContext(const std::shared_ptr<boost::asio::ssl::context>& context, const String& crlPath)
230 {
231         char errbuf[256];
232         X509_STORE *x509_store = SSL_CTX_get_cert_store(context->native_handle());
233
234         X509_LOOKUP *lookup;
235         lookup = X509_STORE_add_lookup(x509_store, X509_LOOKUP_file());
236
237         if (!lookup) {
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()));
243         }
244
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));
252         }
253
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);
258 }
259
260 static String GetX509NameCN(X509_NAME *name)
261 {
262         char errbuf[256];
263         char buffer[256];
264
265         int rc = X509_NAME_get_text_by_NID(name, NID_commonName, buffer, sizeof(buffer));
266
267         if (rc == -1) {
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()));
273         }
274
275         return buffer;
276 }
277
278 /**
279  * Retrieves the common name for an X509 certificate.
280  *
281  * @param certificate The X509 certificate.
282  * @returns The common name.
283  */
284 String GetCertificateCN(const std::shared_ptr<X509>& certificate)
285 {
286         return GetX509NameCN(X509_get_subject_name(certificate.get()));
287 }
288
289 /**
290  * Retrieves an X509 certificate from the specified file.
291  *
292  * @param pemfile The filename.
293  * @returns An X509 certificate.
294  */
295 std::shared_ptr<X509> GetX509Certificate(const String& pemfile)
296 {
297         char errbuf[256];
298         X509 *cert;
299         BIO *fpcert = BIO_new(BIO_s_file());
300
301         if (!fpcert) {
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()));
307         }
308
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));
316         }
317
318         cert = PEM_read_bio_X509_AUX(fpcert, nullptr, nullptr, nullptr);
319         if (!cert) {
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));
326         }
327
328         BIO_free(fpcert);
329
330         return std::shared_ptr<X509>(cert, X509_free);
331 }
332
333 int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile, const String& certfile, bool ca)
334 {
335         char errbuf[256];
336
337         InitializeOpenSSL();
338
339         RSA *rsa = RSA_new();
340         BIGNUM *e = BN_new();
341
342         if (!rsa || !e) {
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()));
348         }
349
350         BN_set_word(e, RSA_F4);
351
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()));
358         }
359
360         BN_free(e);
361
362         Log(LogInformation, "base")
363                 << "Writing private key to '" << keyfile << "'.";
364
365         BIO *bio = BIO_new_file(const_cast<char *>(keyfile.CStr()), "w");
366
367         if (!bio) {
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));
374         }
375
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));
383         }
384
385         BIO_free(bio);
386
387 #ifndef _WIN32
388         chmod(keyfile.CStr(), 0600);
389 #endif /* _WIN32 */
390
391         EVP_PKEY *key = EVP_PKEY_new();
392         EVP_PKEY_assign_RSA(key, rsa);
393
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);
397
398                 std::shared_ptr<X509> cert = CreateCert(key, subject, subject, key, ca);
399
400                 X509_NAME_free(subject);
401
402                 Log(LogInformation, "base")
403                         << "Writing X509 certificate to '" << certfile << "'.";
404
405                 bio = BIO_new_file(const_cast<char *>(certfile.CStr()), "w");
406
407                 if (!bio) {
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));
414                 }
415
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));
423                 }
424
425                 BIO_free(bio);
426         }
427
428         if (!csrfile.IsEmpty()) {
429                 X509_REQ *req = X509_REQ_new();
430
431                 if (!req)
432                         return 0;
433
434                 X509_REQ_set_version(req, 0);
435                 X509_REQ_set_pubkey(req, key);
436
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);
439
440                 if (!ca) {
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);
449                         }
450                 }
451
452                 X509_REQ_sign(req, key, EVP_sha256());
453
454                 Log(LogInformation, "base")
455                         << "Writing certificate signing request to '" << csrfile << "'.";
456
457                 bio = BIO_new_file(const_cast<char *>(csrfile.CStr()), "w");
458
459                 if (!bio) {
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));
466                 }
467
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));
475                 }
476
477                 BIO_free(bio);
478
479                 X509_REQ_free(req);
480         }
481
482         EVP_PKEY_free(key);
483
484         return 1;
485 }
486
487 std::shared_ptr<X509> CreateCert(EVP_PKEY *pubkey, X509_NAME *subject, X509_NAME *issuer, EVP_PKEY *cakey, bool ca)
488 {
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);
494
495         X509_set_subject_name(cert, subject);
496         X509_set_issuer_name(cert, issuer);
497
498         String id = Utility::NewUniqueID();
499
500         char errbuf[120];
501         SHA_CTX context;
502         unsigned char digest[SHA_DIGEST_LENGTH];
503
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()));
510         }
511
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()));
518         }
519
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()));
526         }
527
528         BIGNUM *bn = BN_new();
529         BN_bin2bn(digest, sizeof(digest), bn);
530         BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(cert));
531         BN_free(bn);
532
533         X509V3_CTX ctx;
534         X509V3_set_ctx_nodb(&ctx);
535         X509V3_set_ctx(&ctx, cert, cert, nullptr, nullptr, 0);
536
537         const char *attr;
538
539         if (ca)
540                 attr = "critical,CA:TRUE";
541         else
542                 attr = "critical,CA:FALSE";
543
544         X509_EXTENSION *basicConstraintsExt = X509V3_EXT_conf_nid(nullptr, &ctx, NID_basic_constraints, const_cast<char *>(attr));
545
546         if (basicConstraintsExt) {
547                 X509_add_ext(cert, basicConstraintsExt, -1);
548                 X509_EXTENSION_free(basicConstraintsExt);
549         }
550
551         String cn = GetX509NameCN(subject);
552
553         if (!ca) {
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);
559                 }
560         }
561
562         X509_sign(cert, cakey, EVP_sha256());
563
564         return std::shared_ptr<X509>(cert, X509_free);
565 }
566
567 String GetIcingaCADir()
568 {
569         return Configuration::DataDir + "/ca";
570 }
571
572 std::shared_ptr<X509> CreateCertIcingaCA(EVP_PKEY *pubkey, X509_NAME *subject)
573 {
574         char errbuf[120];
575
576         String cadir = GetIcingaCADir();
577
578         String cakeyfile = cadir + "/ca.key";
579
580         RSA *rsa;
581
582         BIO *cakeybio = BIO_new_file(const_cast<char *>(cakeyfile.CStr()), "r");
583
584         if (!cakeybio) {
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>();
588         }
589
590         rsa = PEM_read_bio_RSAPrivateKey(cakeybio, nullptr, nullptr, nullptr);
591
592         if (!rsa) {
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>();
596         }
597
598         BIO_free(cakeybio);
599
600         String cacertfile = cadir + "/ca.crt";
601
602         std::shared_ptr<X509> cacert = GetX509Certificate(cacertfile);
603
604         EVP_PKEY *privkey = EVP_PKEY_new();
605         EVP_PKEY_assign_RSA(privkey, rsa);
606
607         return CreateCert(pubkey, subject, X509_get_subject_name(cacert.get()), privkey, false);
608 }
609
610 std::shared_ptr<X509> CreateCertIcingaCA(const std::shared_ptr<X509>& cert)
611 {
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()));
614 }
615
616 String CertificateToString(const std::shared_ptr<X509>& cert)
617 {
618         BIO *mem = BIO_new(BIO_s_mem());
619         PEM_write_bio_X509(mem, cert.get());
620
621         char *data;
622         long len = BIO_get_mem_data(mem, &data);
623
624         String result = String(data, data + len);
625
626         BIO_free(mem);
627
628         return result;
629 }
630
631 std::shared_ptr<X509> StringToCertificate(const String& cert)
632 {
633         BIO *bio = BIO_new(BIO_s_mem());
634         BIO_write(bio, (const void *)cert.CStr(), cert.GetLength());
635
636         X509 *rawCert = PEM_read_bio_X509_AUX(bio, nullptr, nullptr, nullptr);
637
638         BIO_free(bio);
639
640         if (!rawCert)
641                 BOOST_THROW_EXCEPTION(std::invalid_argument("The specified X509 certificate is invalid."));
642
643         return std::shared_ptr<X509>(rawCert, X509_free);
644 }
645
646 String PBKDF2_SHA1(const String& password, const String& salt, int iterations)
647 {
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);
651
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]);
655
656         return output;
657 }
658
659 String PBKDF2_SHA256(const String& password, const String& salt, int iterations)
660 {
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);
664
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]);
668
669         return output;
670 }
671
672 String SHA1(const String& s, bool binary)
673 {
674         char errbuf[120];
675         SHA_CTX context;
676         unsigned char digest[SHA_DIGEST_LENGTH];
677
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()));
684         }
685
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()));
692         }
693
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()));
700         }
701
702         if (binary)
703                 return String(reinterpret_cast<const char*>(digest), reinterpret_cast<const char *>(digest + SHA_DIGEST_LENGTH));
704
705         char output[SHA_DIGEST_LENGTH*2+1];
706         for (int i = 0; i < 20; i++)
707                 sprintf(output + 2 * i, "%02x", digest[i]);
708
709         return output;
710 }
711
712 String SHA256(const String& s)
713 {
714         char errbuf[120];
715         SHA256_CTX context;
716         unsigned char digest[SHA256_DIGEST_LENGTH];
717
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()));
724         }
725
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()));
732         }
733
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()));
740         }
741
742         char output[SHA256_DIGEST_LENGTH*2+1];
743         for (int i = 0; i < 32; i++)
744                 sprintf(output + 2 * i, "%02x", digest[i]);
745
746         return output;
747 }
748
749 String RandomString(int length)
750 {
751         auto *bytes = new unsigned char[length];
752
753         /* Ensure that password generation is atomic. RAND_bytes is not thread-safe
754          * in OpenSSL < 1.1.0.
755          */
756         boost::mutex::scoped_lock lock(l_RandomMutex);
757
758         if (!RAND_bytes(bytes, length)) {
759                 delete [] bytes;
760
761                 char errbuf[120];
762
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()));
768         }
769
770         lock.unlock();
771
772         auto *output = new char[length * 2 + 1];
773         for (int i = 0; i < length; i++)
774                 sprintf(output + 2 * i, "%02x", bytes[i]);
775
776         String result = output;
777         delete [] bytes;
778         delete [] output;
779
780         return result;
781 }
782
783 bool VerifyCertificate(const std::shared_ptr<X509>& caCertificate, const std::shared_ptr<X509>& certificate)
784 {
785         X509_STORE *store = X509_STORE_new();
786
787         if (!store)
788                 return false;
789
790         X509_STORE_add_cert(store, caCertificate.get());
791
792         X509_STORE_CTX *csc = X509_STORE_CTX_new();
793         X509_STORE_CTX_init(csc, store, certificate.get(), nullptr);
794
795         int rc = X509_verify_cert(csc);
796
797         X509_STORE_CTX_free(csc);
798         X509_STORE_free(store);
799
800         return rc == 1;
801 }
802
803 std::string to_string(const errinfo_openssl_error& e)
804 {
805         std::ostringstream tmp;
806         int code = e.value();
807         char errbuf[120];
808
809         const char *message = ERR_error_string(code, errbuf);
810
811         if (!message)
812                 message = "Unknown error.";
813
814         tmp << code << ", \"" << message << "\"";
815         return "[errinfo_openssl_error]" + tmp.str() + "\n";
816 }
817
818 }