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