1 #pragma once
2 
3 #include "logging.hpp"
4 #include "random.hpp"
5 
6 #include <openssl/bio.h>
7 #include <openssl/dh.h>
8 #include <openssl/dsa.h>
9 #include <openssl/err.h>
10 #include <openssl/evp.h>
11 #include <openssl/pem.h>
12 #include <openssl/rand.h>
13 #include <openssl/rsa.h>
14 #include <openssl/ssl.h>
15 
16 #include <boost/asio/ssl/context.hpp>
17 
18 #include <optional>
19 #include <random>
20 #include <string>
21 
22 namespace ensuressl
23 {
24 constexpr char const* trustStorePath = "/etc/ssl/certs/authority";
25 constexpr char const* x509Comment = "Generated from OpenBMC service";
26 static void initOpenssl();
27 static EVP_PKEY* createEcKey();
28 
29 // Trust chain related errors.`
30 inline bool isTrustChainError(int errnum)
31 {
32     return (errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) ||
33            (errnum == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) ||
34            (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) ||
35            (errnum == X509_V_ERR_CERT_UNTRUSTED) ||
36            (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
37 }
38 
39 inline bool validateCertificate(X509* const cert)
40 {
41     // Create an empty X509_STORE structure for certificate validation.
42     X509_STORE* x509Store = X509_STORE_new();
43     if (x509Store == nullptr)
44     {
45         BMCWEB_LOG_ERROR << "Error occurred during X509_STORE_new call";
46         return false;
47     }
48 
49     // Load Certificate file into the X509 structure.
50     X509_STORE_CTX* storeCtx = X509_STORE_CTX_new();
51     if (storeCtx == nullptr)
52     {
53         BMCWEB_LOG_ERROR << "Error occurred during X509_STORE_CTX_new call";
54         X509_STORE_free(x509Store);
55         return false;
56     }
57 
58     int errCode = X509_STORE_CTX_init(storeCtx, x509Store, cert, nullptr);
59     if (errCode != 1)
60     {
61         BMCWEB_LOG_ERROR << "Error occurred during X509_STORE_CTX_init call";
62         X509_STORE_CTX_free(storeCtx);
63         X509_STORE_free(x509Store);
64         return false;
65     }
66 
67     errCode = X509_verify_cert(storeCtx);
68     if (errCode == 1)
69     {
70         BMCWEB_LOG_INFO << "Certificate verification is success";
71         X509_STORE_CTX_free(storeCtx);
72         X509_STORE_free(x509Store);
73         return true;
74     }
75     if (errCode == 0)
76     {
77         errCode = X509_STORE_CTX_get_error(storeCtx);
78         X509_STORE_CTX_free(storeCtx);
79         X509_STORE_free(x509Store);
80         if (isTrustChainError(errCode))
81         {
82             BMCWEB_LOG_DEBUG << "Ignoring Trust Chain error. Reason: "
83                              << X509_verify_cert_error_string(errCode);
84             return true;
85         }
86         BMCWEB_LOG_ERROR << "Certificate verification failed. Reason: "
87                          << X509_verify_cert_error_string(errCode);
88         return false;
89     }
90 
91     BMCWEB_LOG_ERROR
92         << "Error occurred during X509_verify_cert call. ErrorCode: "
93         << errCode;
94     X509_STORE_CTX_free(storeCtx);
95     X509_STORE_free(x509Store);
96     return false;
97 }
98 
99 inline bool verifyOpensslKeyCert(const std::string& filepath)
100 {
101     bool privateKeyValid = false;
102     bool certValid = false;
103 
104     std::cout << "Checking certs in file " << filepath << "\n";
105 
106     FILE* file = fopen(filepath.c_str(), "r");
107     if (file != nullptr)
108     {
109         EVP_PKEY* pkey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
110         if (pkey != nullptr)
111         {
112 #if (OPENSSL_VERSION_NUMBER < 0x30000000L)
113             RSA* rsa = EVP_PKEY_get1_RSA(pkey);
114             if (rsa != nullptr)
115             {
116                 std::cout << "Found an RSA key\n";
117                 if (RSA_check_key(rsa) == 1)
118                 {
119                     privateKeyValid = true;
120                 }
121                 else
122                 {
123                     std::cerr << "Key not valid error number "
124                               << ERR_get_error() << "\n";
125                 }
126                 RSA_free(rsa);
127             }
128             else
129             {
130                 EC_KEY* ec = EVP_PKEY_get1_EC_KEY(pkey);
131                 if (ec != nullptr)
132                 {
133                     std::cout << "Found an EC key\n";
134                     if (EC_KEY_check_key(ec) == 1)
135                     {
136                         privateKeyValid = true;
137                     }
138                     else
139                     {
140                         std::cerr << "Key not valid error number "
141                                   << ERR_get_error() << "\n";
142                     }
143                     EC_KEY_free(ec);
144                 }
145             }
146 #else
147             EVP_PKEY_CTX* pkeyCtx =
148                 EVP_PKEY_CTX_new_from_pkey(nullptr, pkey, nullptr);
149 
150             if (pkeyCtx == nullptr)
151             {
152                 std::cerr << "Unable to allocate pkeyCtx " << ERR_get_error()
153                           << "\n";
154             }
155             else if (EVP_PKEY_check(pkeyCtx) == 1)
156             {
157                 privateKeyValid = true;
158             }
159             else
160             {
161 
162                 std::cerr << "Key not valid error number " << ERR_get_error()
163                           << "\n";
164             }
165 #endif
166 
167             if (privateKeyValid)
168             {
169                 // If the order is certificate followed by key in input file
170                 // then, certificate read will fail. So, setting the file
171                 // pointer to point beginning of file to avoid certificate and
172                 // key order issue.
173                 fseek(file, 0, SEEK_SET);
174 
175                 X509* x509 = PEM_read_X509(file, nullptr, nullptr, nullptr);
176                 if (x509 == nullptr)
177                 {
178                     std::cout << "error getting x509 cert " << ERR_get_error()
179                               << "\n";
180                 }
181                 else
182                 {
183                     certValid = validateCertificate(x509);
184                     X509_free(x509);
185                 }
186             }
187 
188 #if (OPENSSL_VERSION_NUMBER > 0x30000000L)
189             EVP_PKEY_CTX_free(pkeyCtx);
190 #endif
191             EVP_PKEY_free(pkey);
192         }
193         fclose(file);
194     }
195     return certValid;
196 }
197 
198 inline X509* loadCert(const std::string& filePath)
199 {
200     BIO* certFileBio = BIO_new_file(filePath.c_str(), "rb");
201     if (certFileBio == nullptr)
202     {
203         BMCWEB_LOG_ERROR << "Error occured during BIO_new_file call, "
204                          << "FILE= " << filePath;
205         return nullptr;
206     }
207 
208     X509* cert = X509_new();
209     if (cert == nullptr)
210     {
211         BMCWEB_LOG_ERROR << "Error occured during X509_new call, "
212                          << ERR_get_error();
213         BIO_free(certFileBio);
214         return nullptr;
215     }
216 
217     if (PEM_read_bio_X509(certFileBio, &cert, nullptr, nullptr) == nullptr)
218     {
219         BMCWEB_LOG_ERROR << "Error occured during PEM_read_bio_X509 call, "
220                          << "FILE= " << filePath;
221 
222         BIO_free(certFileBio);
223         X509_free(cert);
224         return nullptr;
225     }
226     BIO_free(certFileBio);
227     return cert;
228 }
229 
230 inline int addExt(X509* cert, int nid, const char* value)
231 {
232     X509_EXTENSION* ex = nullptr;
233     X509V3_CTX ctx{};
234     X509V3_set_ctx(&ctx, cert, cert, nullptr, nullptr, 0);
235 
236     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
237     ex = X509V3_EXT_conf_nid(nullptr, &ctx, nid, const_cast<char*>(value));
238     if (ex == nullptr)
239     {
240         BMCWEB_LOG_ERROR << "Error: In X509V3_EXT_conf_nidn: " << value;
241         return -1;
242     }
243     X509_add_ext(cert, ex, -1);
244     X509_EXTENSION_free(ex);
245     return 0;
246 }
247 
248 inline void generateSslCertificate(const std::string& filepath,
249                                    const std::string& cn)
250 {
251     FILE* pFile = nullptr;
252     std::cout << "Generating new keys\n";
253     initOpenssl();
254 
255     std::cerr << "Generating EC key\n";
256     EVP_PKEY* pPrivKey = createEcKey();
257     if (pPrivKey != nullptr)
258     {
259         std::cerr << "Generating x509 Certificate\n";
260         // Use this code to directly generate a certificate
261         X509* x509 = X509_new();
262         if (x509 != nullptr)
263         {
264             // get a random number from the RNG for the certificate serial
265             // number If this is not random, regenerating certs throws broswer
266             // errors
267             bmcweb::OpenSSLGenerator gen;
268             std::uniform_int_distribution<int> dis(
269                 1, std::numeric_limits<int>::max());
270             int serial = dis(gen);
271 
272             ASN1_INTEGER_set(X509_get_serialNumber(x509), serial);
273 
274             // not before this moment
275             X509_gmtime_adj(X509_get_notBefore(x509), 0);
276             // Cert is valid for 10 years
277             X509_gmtime_adj(X509_get_notAfter(x509),
278                             60L * 60L * 24L * 365L * 10L);
279 
280             // set the public key to the key we just generated
281             X509_set_pubkey(x509, pPrivKey);
282 
283             // get the subject name
284             X509_NAME* name = X509_get_subject_name(x509);
285 
286             using x509String = const unsigned char;
287             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
288             x509String* country = reinterpret_cast<x509String*>("US");
289             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
290             x509String* company = reinterpret_cast<x509String*>("OpenBMC");
291             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
292             x509String* cnStr = reinterpret_cast<x509String*>(cn.c_str());
293 
294             X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, country, -1, -1,
295                                        0);
296             X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, company, -1, -1,
297                                        0);
298             X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, cnStr, -1, -1,
299                                        0);
300             // set the CSR options
301             X509_set_issuer_name(x509, name);
302 
303             X509_set_version(x509, 2);
304             addExt(x509, NID_basic_constraints, ("critical,CA:TRUE"));
305             addExt(x509, NID_subject_alt_name, ("DNS:" + cn).c_str());
306             addExt(x509, NID_subject_key_identifier, ("hash"));
307             addExt(x509, NID_authority_key_identifier, ("keyid"));
308             addExt(x509, NID_key_usage, ("digitalSignature, keyEncipherment"));
309             addExt(x509, NID_ext_key_usage, ("serverAuth"));
310             addExt(x509, NID_netscape_comment, (x509Comment));
311 
312             // Sign the certificate with our private key
313             X509_sign(x509, pPrivKey, EVP_sha256());
314 
315             pFile = fopen(filepath.c_str(), "wt");
316 
317             if (pFile != nullptr)
318             {
319                 PEM_write_PrivateKey(pFile, pPrivKey, nullptr, nullptr, 0,
320                                      nullptr, nullptr);
321 
322                 PEM_write_X509(pFile, x509);
323                 fclose(pFile);
324                 pFile = nullptr;
325             }
326 
327             X509_free(x509);
328         }
329 
330         EVP_PKEY_free(pPrivKey);
331         pPrivKey = nullptr;
332     }
333 
334     // cleanup_openssl();
335 }
336 
337 EVP_PKEY* createEcKey()
338 {
339     EVP_PKEY* pKey = nullptr;
340 
341 #if (OPENSSL_VERSION_NUMBER < 0x30000000L)
342     int eccgrp = 0;
343     eccgrp = OBJ_txt2nid("secp384r1");
344 
345     EC_KEY* myecc = EC_KEY_new_by_curve_name(eccgrp);
346     if (myecc != nullptr)
347     {
348         EC_KEY_set_asn1_flag(myecc, OPENSSL_EC_NAMED_CURVE);
349         EC_KEY_generate_key(myecc);
350         pKey = EVP_PKEY_new();
351         if (pKey != nullptr)
352         {
353             if (EVP_PKEY_assign(pKey, EVP_PKEY_EC, myecc) != 0)
354             {
355                 /* pKey owns myecc from now */
356                 if (EC_KEY_check_key(myecc) <= 0)
357                 {
358                     std::cerr << "EC_check_key failed.\n";
359                 }
360             }
361         }
362     }
363 #else
364     // Create context for curve parameter generation.
365     std::unique_ptr<EVP_PKEY_CTX, decltype(&::EVP_PKEY_CTX_free)> ctx{
366         EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr), &::EVP_PKEY_CTX_free};
367     if (!ctx)
368     {
369         return nullptr;
370     }
371 
372     // Set up curve parameters.
373     EVP_PKEY* params = nullptr;
374     if ((EVP_PKEY_paramgen_init(ctx.get()) <= 0) ||
375         (EVP_PKEY_CTX_set_ec_param_enc(ctx.get(), OPENSSL_EC_NAMED_CURVE) <=
376          0) ||
377         (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx.get(), NID_secp384r1) <=
378          0) ||
379         (EVP_PKEY_paramgen(ctx.get(), &params) <= 0))
380     {
381         return nullptr;
382     }
383 
384     // Set up RAII holder for params.
385     std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)> pparams{
386         params, &::EVP_PKEY_free};
387 
388     // Set new context for key generation, using curve parameters.
389     ctx.reset(EVP_PKEY_CTX_new_from_pkey(nullptr, params, nullptr));
390     if (!ctx || (EVP_PKEY_keygen_init(ctx.get()) <= 0))
391     {
392         return nullptr;
393     }
394 
395     // Generate key.
396     if (EVP_PKEY_keygen(ctx.get(), &pKey) <= 0)
397     {
398         return nullptr;
399     }
400 #endif
401 
402     return pKey;
403 }
404 
405 void initOpenssl()
406 {
407 #if OPENSSL_VERSION_NUMBER < 0x10100000L
408     SSL_load_error_strings();
409     OpenSSL_add_all_algorithms();
410     RAND_load_file("/dev/urandom", 1024);
411 #endif
412 }
413 
414 inline void ensureOpensslKeyPresentAndValid(const std::string& filepath)
415 {
416     bool pemFileValid = false;
417 
418     pemFileValid = verifyOpensslKeyCert(filepath);
419 
420     if (!pemFileValid)
421     {
422         std::cerr << "Error in verifying signature, regenerating\n";
423         generateSslCertificate(filepath, "testhost");
424     }
425 }
426 
427 inline std::shared_ptr<boost::asio::ssl::context>
428     getSslContext(const std::string& sslPemFile)
429 {
430     std::shared_ptr<boost::asio::ssl::context> mSslContext =
431         std::make_shared<boost::asio::ssl::context>(
432             boost::asio::ssl::context::tls_server);
433     mSslContext->set_options(boost::asio::ssl::context::default_workarounds |
434                              boost::asio::ssl::context::no_sslv2 |
435                              boost::asio::ssl::context::no_sslv3 |
436                              boost::asio::ssl::context::single_dh_use |
437                              boost::asio::ssl::context::no_tlsv1 |
438                              boost::asio::ssl::context::no_tlsv1_1);
439 
440     // BIG WARNING: This needs to stay disabled, as there will always be
441     // unauthenticated endpoints
442     // mSslContext->set_verify_mode(boost::asio::ssl::verify_peer);
443 
444     SSL_CTX_set_options(mSslContext->native_handle(), SSL_OP_NO_RENEGOTIATION);
445 
446     BMCWEB_LOG_DEBUG << "Using default TrustStore location: " << trustStorePath;
447     mSslContext->add_verify_path(trustStorePath);
448 
449     mSslContext->use_certificate_file(sslPemFile,
450                                       boost::asio::ssl::context::pem);
451     mSslContext->use_private_key_file(sslPemFile,
452                                       boost::asio::ssl::context::pem);
453 
454     // Set up EC curves to auto (boost asio doesn't have a method for this)
455     // There is a pull request to add this.  Once this is included in an asio
456     // drop, use the right way
457     // http://stackoverflow.com/questions/18929049/boost-asio-with-ecdsa-certificate-issue
458     if (SSL_CTX_set_ecdh_auto(mSslContext->native_handle(), 1) != 1)
459     {
460         BMCWEB_LOG_ERROR << "Error setting tmp ecdh list\n";
461     }
462 
463     std::string mozillaModern = "ECDHE-ECDSA-AES256-GCM-SHA384:"
464                                 "ECDHE-RSA-AES256-GCM-SHA384:"
465                                 "ECDHE-ECDSA-CHACHA20-POLY1305:"
466                                 "ECDHE-RSA-CHACHA20-POLY1305:"
467                                 "ECDHE-ECDSA-AES128-GCM-SHA256:"
468                                 "ECDHE-RSA-AES128-GCM-SHA256:"
469                                 "ECDHE-ECDSA-AES256-SHA384:"
470                                 "ECDHE-RSA-AES256-SHA384:"
471                                 "ECDHE-ECDSA-AES128-SHA256:"
472                                 "ECDHE-RSA-AES128-SHA256";
473 
474     if (SSL_CTX_set_cipher_list(mSslContext->native_handle(),
475                                 mozillaModern.c_str()) != 1)
476     {
477         BMCWEB_LOG_ERROR << "Error setting cipher list\n";
478     }
479     return mSslContext;
480 }
481 
482 inline std::optional<boost::asio::ssl::context> getSSLClientContext()
483 {
484     boost::asio::ssl::context sslCtx(boost::asio::ssl::context::tls_client);
485 
486     boost::system::error_code ec;
487 
488     // Support only TLS v1.2 & v1.3
489     sslCtx.set_options(boost::asio::ssl::context::default_workarounds |
490                            boost::asio::ssl::context::no_sslv2 |
491                            boost::asio::ssl::context::no_sslv3 |
492                            boost::asio::ssl::context::single_dh_use |
493                            boost::asio::ssl::context::no_tlsv1 |
494                            boost::asio::ssl::context::no_tlsv1_1,
495                        ec);
496     if (ec)
497     {
498         BMCWEB_LOG_ERROR << "SSL context set_options failed";
499         return std::nullopt;
500     }
501 
502     // Add a directory containing certificate authority files to be used
503     // for performing verification.
504     sslCtx.set_default_verify_paths(ec);
505     if (ec)
506     {
507         BMCWEB_LOG_ERROR << "SSL context set_default_verify failed";
508         return std::nullopt;
509     }
510 
511     // Verify the remote server's certificate
512     sslCtx.set_verify_mode(boost::asio::ssl::verify_peer, ec);
513     if (ec)
514     {
515         BMCWEB_LOG_ERROR << "SSL context set_verify_mode failed";
516         return std::nullopt;
517     }
518 
519     // All cipher suites are set as per OWASP datasheet.
520     // https://cheatsheetseries.owasp.org/cheatsheets/TLS_Cipher_String_Cheat_Sheet.html
521     constexpr const char* sslCiphers = "ECDHE-ECDSA-AES128-GCM-SHA256:"
522                                        "ECDHE-RSA-AES128-GCM-SHA256:"
523                                        "ECDHE-ECDSA-AES256-GCM-SHA384:"
524                                        "ECDHE-RSA-AES256-GCM-SHA384:"
525                                        "ECDHE-ECDSA-CHACHA20-POLY1305:"
526                                        "ECDHE-RSA-CHACHA20-POLY1305:"
527                                        "DHE-RSA-AES128-GCM-SHA256:"
528                                        "DHE-RSA-AES256-GCM-SHA384"
529                                        "TLS_AES_128_GCM_SHA256:"
530                                        "TLS_AES_256_GCM_SHA384:"
531                                        "TLS_CHACHA20_POLY1305_SHA256";
532 
533     if (SSL_CTX_set_cipher_list(sslCtx.native_handle(), sslCiphers) != 1)
534     {
535         BMCWEB_LOG_ERROR << "SSL_CTX_set_cipher_list failed";
536         return std::nullopt;
537     }
538 
539     return sslCtx;
540 }
541 
542 } // namespace ensuressl
543