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