1 #pragma once
2 
3 #include "bmcweb_config.h"
4 
5 #include "logging.hpp"
6 #include "ossl_random.hpp"
7 #include "persistent_data.hpp"
8 
9 #include <boost/beast/core/file_posix.hpp>
10 
11 extern "C"
12 {
13 #include <nghttp2/nghttp2.h>
14 #include <openssl/bio.h>
15 #include <openssl/dh.h>
16 #include <openssl/dsa.h>
17 #include <openssl/err.h>
18 #include <openssl/evp.h>
19 #include <openssl/pem.h>
20 #include <openssl/rand.h>
21 #include <openssl/rsa.h>
22 #include <openssl/ssl.h>
23 }
24 
25 #include <boost/asio/ssl/context.hpp>
26 #include <boost/system/error_code.hpp>
27 
28 #include <filesystem>
29 #include <memory>
30 #include <optional>
31 #include <random>
32 #include <string>
33 
34 namespace ensuressl
35 {
36 constexpr const char* trustStorePath = "/etc/ssl/certs/authority";
37 constexpr const char* x509Comment = "Generated from OpenBMC service";
38 static EVP_PKEY* createEcKey();
39 
40 // Trust chain related errors.`
41 inline bool isTrustChainError(int errnum)
42 {
43     return (errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) ||
44            (errnum == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) ||
45            (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) ||
46            (errnum == X509_V_ERR_CERT_UNTRUSTED) ||
47            (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
48 }
49 
50 inline bool validateCertificate(X509* const cert)
51 {
52     // Create an empty X509_STORE structure for certificate validation.
53     X509_STORE* x509Store = X509_STORE_new();
54     if (x509Store == nullptr)
55     {
56         BMCWEB_LOG_ERROR("Error occurred during X509_STORE_new call");
57         return false;
58     }
59 
60     // Load Certificate file into the X509 structure.
61     X509_STORE_CTX* storeCtx = X509_STORE_CTX_new();
62     if (storeCtx == nullptr)
63     {
64         BMCWEB_LOG_ERROR("Error occurred during X509_STORE_CTX_new call");
65         X509_STORE_free(x509Store);
66         return false;
67     }
68 
69     int errCode = X509_STORE_CTX_init(storeCtx, x509Store, cert, nullptr);
70     if (errCode != 1)
71     {
72         BMCWEB_LOG_ERROR("Error occurred during X509_STORE_CTX_init call");
73         X509_STORE_CTX_free(storeCtx);
74         X509_STORE_free(x509Store);
75         return false;
76     }
77 
78     errCode = X509_verify_cert(storeCtx);
79     if (errCode == 1)
80     {
81         BMCWEB_LOG_INFO("Certificate verification is success");
82         X509_STORE_CTX_free(storeCtx);
83         X509_STORE_free(x509Store);
84         return true;
85     }
86     if (errCode == 0)
87     {
88         errCode = X509_STORE_CTX_get_error(storeCtx);
89         X509_STORE_CTX_free(storeCtx);
90         X509_STORE_free(x509Store);
91         if (isTrustChainError(errCode))
92         {
93             BMCWEB_LOG_DEBUG("Ignoring Trust Chain error. Reason: {}",
94                              X509_verify_cert_error_string(errCode));
95             return true;
96         }
97         BMCWEB_LOG_ERROR("Certificate verification failed. Reason: {}",
98                          X509_verify_cert_error_string(errCode));
99         return false;
100     }
101 
102     BMCWEB_LOG_ERROR(
103         "Error occurred during X509_verify_cert call. ErrorCode: {}", errCode);
104     X509_STORE_CTX_free(storeCtx);
105     X509_STORE_free(x509Store);
106     return false;
107 }
108 
109 inline std::string verifyOpensslKeyCert(const std::string& filepath)
110 {
111     bool privateKeyValid = false;
112 
113     BMCWEB_LOG_INFO("Checking certs in file {}", filepath);
114     boost::beast::file_posix file;
115     boost::system::error_code ec;
116     file.open(filepath.c_str(), boost::beast::file_mode::read, ec);
117     if (ec)
118     {
119         return "";
120     }
121     bool certValid = false;
122     std::string fileContents;
123     fileContents.resize(static_cast<size_t>(file.size(ec)), '\0');
124     file.read(fileContents.data(), fileContents.size(), ec);
125     if (ec)
126     {
127         BMCWEB_LOG_ERROR("Failed to read file");
128         return "";
129     }
130 
131     BIO* bufio = BIO_new_mem_buf(static_cast<void*>(fileContents.data()),
132                                  static_cast<int>(fileContents.size()));
133     EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bufio, nullptr, nullptr, nullptr);
134     BIO_free(bufio);
135     if (pkey != nullptr)
136     {
137         EVP_PKEY_CTX* pkeyCtx = EVP_PKEY_CTX_new_from_pkey(nullptr, pkey,
138                                                            nullptr);
139 
140         if (pkeyCtx == nullptr)
141         {
142             BMCWEB_LOG_ERROR("Unable to allocate pkeyCtx {}", ERR_get_error());
143         }
144         else if (EVP_PKEY_check(pkeyCtx) == 1)
145         {
146             privateKeyValid = true;
147         }
148         else
149         {
150             BMCWEB_LOG_ERROR("Key not valid error number {}", ERR_get_error());
151         }
152 
153         if (privateKeyValid)
154         {
155             BIO* bufio2 =
156                 BIO_new_mem_buf(static_cast<void*>(fileContents.data()),
157                                 static_cast<int>(fileContents.size()));
158             X509* x509 = PEM_read_bio_X509(bufio2, nullptr, nullptr, nullptr);
159             BIO_free(bufio2);
160             if (x509 == nullptr)
161             {
162                 BMCWEB_LOG_ERROR("error getting x509 cert {}", ERR_get_error());
163             }
164             else
165             {
166                 certValid = validateCertificate(x509);
167                 X509_free(x509);
168             }
169         }
170 
171         EVP_PKEY_CTX_free(pkeyCtx);
172         EVP_PKEY_free(pkey);
173     }
174     if (!certValid)
175     {
176         return "";
177     }
178     return fileContents;
179 }
180 
181 inline X509* loadCert(const std::string& filePath)
182 {
183     BIO* certFileBio = BIO_new_file(filePath.c_str(), "rb");
184     if (certFileBio == nullptr)
185     {
186         BMCWEB_LOG_ERROR("Error occurred during BIO_new_file call, FILE= {}",
187                          filePath);
188         return nullptr;
189     }
190 
191     X509* cert = X509_new();
192     if (cert == nullptr)
193     {
194         BMCWEB_LOG_ERROR("Error occurred during X509_new call, {}",
195                          ERR_get_error());
196         BIO_free(certFileBio);
197         return nullptr;
198     }
199 
200     if (PEM_read_bio_X509(certFileBio, &cert, nullptr, nullptr) == nullptr)
201     {
202         BMCWEB_LOG_ERROR(
203             "Error occurred during PEM_read_bio_X509 call, FILE= {}", filePath);
204 
205         BIO_free(certFileBio);
206         X509_free(cert);
207         return nullptr;
208     }
209     BIO_free(certFileBio);
210     return cert;
211 }
212 
213 inline int addExt(X509* cert, int nid, const char* value)
214 {
215     X509_EXTENSION* ex = nullptr;
216     X509V3_CTX ctx{};
217     X509V3_set_ctx(&ctx, cert, cert, nullptr, nullptr, 0);
218 
219     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
220     ex = X509V3_EXT_conf_nid(nullptr, &ctx, nid, const_cast<char*>(value));
221     if (ex == nullptr)
222     {
223         BMCWEB_LOG_ERROR("Error: In X509V3_EXT_conf_nidn: {}", value);
224         return -1;
225     }
226     X509_add_ext(cert, ex, -1);
227     X509_EXTENSION_free(ex);
228     return 0;
229 }
230 
231 // Writes a certificate to a path, ignoring errors
232 inline void writeCertificateToFile(const std::string& filepath,
233                                    const std::string& certificate)
234 {
235     boost::system::error_code ec;
236     boost::beast::file_posix file;
237     file.open(filepath.c_str(), boost::beast::file_mode::write, ec);
238     if (!ec)
239     {
240         file.write(certificate.data(), certificate.size(), ec);
241         // ignore result
242     }
243 }
244 
245 inline std::string generateSslCertificate(const std::string& cn)
246 {
247     BMCWEB_LOG_INFO("Generating new keys");
248 
249     std::string buffer;
250     BMCWEB_LOG_INFO("Generating EC key");
251     EVP_PKEY* pPrivKey = createEcKey();
252     if (pPrivKey != nullptr)
253     {
254         BMCWEB_LOG_INFO("Generating x509 Certificates");
255         // Use this code to directly generate a certificate
256         X509* x509 = X509_new();
257         if (x509 != nullptr)
258         {
259             // get a random number from the RNG for the certificate serial
260             // number If this is not random, regenerating certs throws browser
261             // errors
262             bmcweb::OpenSSLGenerator gen;
263             std::uniform_int_distribution<int> dis(
264                 1, std::numeric_limits<int>::max());
265             int serial = dis(gen);
266 
267             ASN1_INTEGER_set(X509_get_serialNumber(x509), serial);
268 
269             // not before this moment
270             X509_gmtime_adj(X509_get_notBefore(x509), 0);
271             // Cert is valid for 10 years
272             X509_gmtime_adj(X509_get_notAfter(x509),
273                             60L * 60L * 24L * 365L * 10L);
274 
275             // set the public key to the key we just generated
276             X509_set_pubkey(x509, pPrivKey);
277 
278             // get the subject name
279             X509_NAME* name = X509_get_subject_name(x509);
280 
281             using x509String = const unsigned char;
282             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
283             x509String* country = reinterpret_cast<x509String*>("US");
284             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
285             x509String* company = reinterpret_cast<x509String*>("OpenBMC");
286             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
287             x509String* cnStr = reinterpret_cast<x509String*>(cn.c_str());
288 
289             X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, country, -1, -1,
290                                        0);
291             X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, company, -1, -1,
292                                        0);
293             X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, cnStr, -1, -1,
294                                        0);
295             // set the CSR options
296             X509_set_issuer_name(x509, name);
297 
298             X509_set_version(x509, 2);
299             addExt(x509, NID_basic_constraints, ("critical,CA:TRUE"));
300             addExt(x509, NID_subject_alt_name, ("DNS:" + cn).c_str());
301             addExt(x509, NID_subject_key_identifier, ("hash"));
302             addExt(x509, NID_authority_key_identifier, ("keyid"));
303             addExt(x509, NID_key_usage, ("digitalSignature, keyEncipherment"));
304             addExt(x509, NID_ext_key_usage, ("serverAuth"));
305             addExt(x509, NID_netscape_comment, (x509Comment));
306 
307             // Sign the certificate with our private key
308             X509_sign(x509, pPrivKey, EVP_sha256());
309 
310             BIO* bufio = BIO_new(BIO_s_mem());
311 
312             int pkeyRet = PEM_write_bio_PrivateKey(
313                 bufio, pPrivKey, nullptr, nullptr, 0, nullptr, nullptr);
314             if (pkeyRet <= 0)
315             {
316                 BMCWEB_LOG_ERROR(
317                     "Failed to write pkey with code {}.  Ignoring.", pkeyRet);
318             }
319 
320             char* data = nullptr;
321             long int dataLen = BIO_get_mem_data(bufio, &data);
322             buffer += std::string_view(data, static_cast<size_t>(dataLen));
323             BIO_free(bufio);
324 
325             bufio = BIO_new(BIO_s_mem());
326             pkeyRet = PEM_write_bio_X509(bufio, x509);
327             if (pkeyRet <= 0)
328             {
329                 BMCWEB_LOG_ERROR(
330                     "Failed to write X509 with code {}.  Ignoring.", pkeyRet);
331             }
332             dataLen = BIO_get_mem_data(bufio, &data);
333             buffer += std::string_view(data, static_cast<size_t>(dataLen));
334 
335             BIO_free(bufio);
336             BMCWEB_LOG_INFO("Cert size is {}", buffer.size());
337             X509_free(x509);
338         }
339 
340         EVP_PKEY_free(pPrivKey);
341         pPrivKey = nullptr;
342     }
343 
344     // cleanup_openssl();
345     return buffer;
346 }
347 
348 EVP_PKEY* createEcKey()
349 {
350     EVP_PKEY* pKey = nullptr;
351 
352     // Create context for curve parameter generation.
353     std::unique_ptr<EVP_PKEY_CTX, decltype(&::EVP_PKEY_CTX_free)> ctx{
354         EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr), &::EVP_PKEY_CTX_free};
355     if (!ctx)
356     {
357         return nullptr;
358     }
359 
360     // Set up curve parameters.
361     EVP_PKEY* params = nullptr;
362     if ((EVP_PKEY_paramgen_init(ctx.get()) <= 0) ||
363         (EVP_PKEY_CTX_set_ec_param_enc(ctx.get(), OPENSSL_EC_NAMED_CURVE) <=
364          0) ||
365         (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx.get(), NID_secp384r1) <=
366          0) ||
367         (EVP_PKEY_paramgen(ctx.get(), &params) <= 0))
368     {
369         return nullptr;
370     }
371 
372     // Set up RAII holder for params.
373     std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)> pparams{
374         params, &::EVP_PKEY_free};
375 
376     // Set new context for key generation, using curve parameters.
377     ctx.reset(EVP_PKEY_CTX_new_from_pkey(nullptr, params, nullptr));
378     if (!ctx || (EVP_PKEY_keygen_init(ctx.get()) <= 0))
379     {
380         return nullptr;
381     }
382 
383     // Generate key.
384     if (EVP_PKEY_keygen(ctx.get(), &pKey) <= 0)
385     {
386         return nullptr;
387     }
388 
389     return pKey;
390 }
391 
392 inline std::string ensureOpensslKeyPresentAndValid(const std::string& filepath)
393 {
394     std::string cert = verifyOpensslKeyCert(filepath);
395 
396     if (cert.empty())
397     {
398         BMCWEB_LOG_WARNING("Error in verifying signature, regenerating");
399         cert = generateSslCertificate("testhost");
400         if (cert.empty())
401         {
402             BMCWEB_LOG_ERROR("Failed to generate cert");
403         }
404         else
405         {
406             writeCertificateToFile(filepath, cert);
407         }
408     }
409     return cert;
410 }
411 
412 inline std::string ensureCertificate()
413 {
414     namespace fs = std::filesystem;
415     // Cleanup older certificate file existing in the system
416     fs::path oldcertPath = fs::path("/home/root/server.pem");
417     std::error_code ec;
418     fs::remove(oldcertPath, ec);
419     // Ignore failure to remove;  File might not exist.
420 
421     fs::path certPath = "/etc/ssl/certs/https/";
422     // if path does not exist create the path so that
423     // self signed certificate can be created in the
424     // path
425     fs::path certFile = certPath / "server.pem";
426 
427     if (!fs::exists(certPath, ec))
428     {
429         fs::create_directories(certPath, ec);
430     }
431     BMCWEB_LOG_INFO("Building SSL Context file= {}", certFile.string());
432     std::string sslPemFile(certFile);
433     return ensuressl::ensureOpensslKeyPresentAndValid(sslPemFile);
434 }
435 
436 inline int nextProtoCallback(SSL* /*unused*/, const unsigned char** data,
437                              unsigned int* len, void* /*unused*/)
438 {
439     // First byte is the length.
440     constexpr std::string_view h2 = "\x02h2";
441     *data = std::bit_cast<const unsigned char*>(h2.data());
442     *len = static_cast<unsigned int>(h2.size());
443     return SSL_TLSEXT_ERR_OK;
444 }
445 
446 inline int alpnSelectProtoCallback(SSL* /*unused*/, const unsigned char** out,
447                                    unsigned char* outlen,
448                                    const unsigned char* in, unsigned int inlen,
449                                    void* /*unused*/)
450 {
451     // There's a mismatch in constness for nghttp2_select_next_protocol.  The
452     // examples in nghttp2 don't show this problem.  Unclear what the right fix
453     // is here.
454 
455     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
456     unsigned char** outNew = const_cast<unsigned char**>(out);
457     int rv = nghttp2_select_next_protocol(outNew, outlen, in, inlen);
458     if (rv != 1)
459     {
460         return SSL_TLSEXT_ERR_NOACK;
461     }
462 
463     return SSL_TLSEXT_ERR_OK;
464 }
465 
466 inline bool getSslContext(boost::asio::ssl::context& mSslContext,
467                           const std::string& sslPemFile)
468 {
469     mSslContext.set_options(boost::asio::ssl::context::default_workarounds |
470                             boost::asio::ssl::context::no_sslv2 |
471                             boost::asio::ssl::context::no_sslv3 |
472                             boost::asio::ssl::context::single_dh_use |
473                             boost::asio::ssl::context::no_tlsv1 |
474                             boost::asio::ssl::context::no_tlsv1_1);
475 
476     BMCWEB_LOG_DEBUG("Using default TrustStore location: {}", trustStorePath);
477     mSslContext.add_verify_path(trustStorePath);
478 
479     if (!sslPemFile.empty())
480     {
481         boost::system::error_code ec;
482 
483         boost::asio::const_buffer buf(sslPemFile.data(), sslPemFile.size());
484         mSslContext.use_certificate(buf, boost::asio::ssl::context::pem, ec);
485         if (ec)
486         {
487             return false;
488         }
489         mSslContext.use_private_key(buf, boost::asio::ssl::context::pem, ec);
490         if (ec)
491         {
492             BMCWEB_LOG_CRITICAL("Failed to open ssl pkey");
493             return false;
494         }
495     }
496 
497     // Set up EC curves to auto (boost asio doesn't have a method for this)
498     // There is a pull request to add this.  Once this is included in an asio
499     // drop, use the right way
500     // http://stackoverflow.com/questions/18929049/boost-asio-with-ecdsa-certificate-issue
501     if (SSL_CTX_set_ecdh_auto(mSslContext->native_handle(), 1) != 1)
502     {}
503 
504     // Mozilla intermediate cipher suites v5.7
505     // Sourced from: https://ssl-config.mozilla.org/guidelines/5.7.json
506     const char* mozillaIntermediate = "ECDHE-ECDSA-AES128-GCM-SHA256:"
507                                       "ECDHE-RSA-AES128-GCM-SHA256:"
508                                       "ECDHE-ECDSA-AES256-GCM-SHA384:"
509                                       "ECDHE-RSA-AES256-GCM-SHA384:"
510                                       "ECDHE-ECDSA-CHACHA20-POLY1305:"
511                                       "ECDHE-RSA-CHACHA20-POLY1305:"
512                                       "DHE-RSA-AES128-GCM-SHA256:"
513                                       "DHE-RSA-AES256-GCM-SHA384:"
514                                       "DHE-RSA-CHACHA20-POLY1305";
515 
516     if (SSL_CTX_set_cipher_list(mSslContext.native_handle(),
517                                 mozillaIntermediate) != 1)
518     {
519         BMCWEB_LOG_ERROR("Error setting cipher list");
520         return false;
521     }
522     return true;
523 }
524 
525 inline std::shared_ptr<boost::asio::ssl::context> getSslServerContext()
526 {
527     boost::asio::ssl::context sslCtx(boost::asio::ssl::context::tls_server);
528 
529     auto certFile = ensureCertificate();
530     if (!getSslContext(sslCtx, certFile))
531     {
532         BMCWEB_LOG_CRITICAL("Couldn't get server context");
533         return nullptr;
534     }
535     const persistent_data::AuthConfigMethods& c =
536         persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
537 
538     boost::asio::ssl::verify_mode mode = boost::asio::ssl::verify_peer;
539     if (c.tlsStrict)
540     {
541         BMCWEB_LOG_DEBUG("Setting verify peer");
542         mode |= boost::asio::ssl::verify_fail_if_no_peer_cert;
543     }
544 
545     boost::system::error_code ec;
546     sslCtx.set_verify_mode(mode, ec);
547     if (ec)
548     {
549         BMCWEB_LOG_DEBUG("Failed to set verify mode {}", ec.message());
550         return nullptr;
551     }
552     SSL_CTX_set_options(sslCtx.native_handle(), SSL_OP_NO_RENEGOTIATION);
553 
554     if constexpr (BMCWEB_EXPERIMENTAL_HTTP2)
555     {
556         SSL_CTX_set_next_protos_advertised_cb(sslCtx.native_handle(),
557                                               nextProtoCallback, nullptr);
558 
559         SSL_CTX_set_alpn_select_cb(sslCtx.native_handle(),
560                                    alpnSelectProtoCallback, nullptr);
561     }
562 
563     return std::make_shared<boost::asio::ssl::context>(std::move(sslCtx));
564 }
565 
566 enum class VerifyCertificate
567 {
568     Verify,
569     NoVerify
570 };
571 
572 inline std::optional<boost::asio::ssl::context>
573     getSSLClientContext(VerifyCertificate verifyCertificate)
574 {
575     namespace fs = std::filesystem;
576 
577     boost::asio::ssl::context sslCtx(boost::asio::ssl::context::tls_client);
578 
579     // NOTE, this path is temporary;  In the future it will need to change to
580     // be set per subscription.  Do not rely on this.
581     fs::path certPath = "/etc/ssl/certs/https/client.pem";
582     std::string cert = verifyOpensslKeyCert(certPath);
583 
584     if (!getSslContext(sslCtx, cert))
585     {
586         return std::nullopt;
587     }
588 
589     // Add a directory containing certificate authority files to be used
590     // for performing verification.
591     boost::system::error_code ec;
592     sslCtx.set_default_verify_paths(ec);
593     if (ec)
594     {
595         BMCWEB_LOG_ERROR("SSL context set_default_verify failed");
596         return std::nullopt;
597     }
598 
599     int mode = boost::asio::ssl::verify_peer;
600     if (verifyCertificate == VerifyCertificate::NoVerify)
601     {
602         mode = boost::asio::ssl::verify_none;
603     }
604 
605     // Verify the remote server's certificate
606     sslCtx.set_verify_mode(mode, ec);
607     if (ec)
608     {
609         BMCWEB_LOG_ERROR("SSL context set_verify_mode failed");
610         return std::nullopt;
611     }
612 
613     // All cipher suites are set as per OWASP datasheet.
614     // https://cheatsheetseries.owasp.org/cheatsheets/TLS_Cipher_String_Cheat_Sheet.html
615     constexpr const char* sslCiphers = "ECDHE-ECDSA-AES128-GCM-SHA256:"
616                                        "ECDHE-RSA-AES128-GCM-SHA256:"
617                                        "ECDHE-ECDSA-AES256-GCM-SHA384:"
618                                        "ECDHE-RSA-AES256-GCM-SHA384:"
619                                        "ECDHE-ECDSA-CHACHA20-POLY1305:"
620                                        "ECDHE-RSA-CHACHA20-POLY1305:"
621                                        "DHE-RSA-AES128-GCM-SHA256:"
622                                        "DHE-RSA-AES256-GCM-SHA384"
623                                        "TLS_AES_128_GCM_SHA256:"
624                                        "TLS_AES_256_GCM_SHA384:"
625                                        "TLS_CHACHA20_POLY1305_SHA256";
626 
627     if (SSL_CTX_set_cipher_list(sslCtx.native_handle(), sslCiphers) != 1)
628     {
629         BMCWEB_LOG_ERROR("SSL_CTX_set_cipher_list failed");
630         return std::nullopt;
631     }
632 
633     return {std::move(sslCtx)};
634 }
635 
636 } // namespace ensuressl
637