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 std::string generateSslCertificate(const std::string& cn) 272 { 273 BMCWEB_LOG_INFO("Generating new keys"); 274 275 std::string buffer; 276 BMCWEB_LOG_INFO("Generating EC key"); 277 EVP_PKEY* pPrivKey = createEcKey(); 278 if (pPrivKey != nullptr) 279 { 280 BMCWEB_LOG_INFO("Generating x509 Certificates"); 281 // Use this code to directly generate a certificate 282 X509* x509 = X509_new(); 283 if (x509 != nullptr) 284 { 285 // get a random number from the RNG for the certificate serial 286 // number If this is not random, regenerating certs throws browser 287 // errors 288 bmcweb::OpenSSLGenerator gen; 289 std::uniform_int_distribution<int> dis( 290 1, std::numeric_limits<int>::max()); 291 int serial = dis(gen); 292 293 ASN1_INTEGER_set(X509_get_serialNumber(x509), serial); 294 295 // not before this moment 296 X509_gmtime_adj(X509_get_notBefore(x509), 0); 297 // Cert is valid for 10 years 298 X509_gmtime_adj(X509_get_notAfter(x509), 299 60L * 60L * 24L * 365L * 10L); 300 301 // set the public key to the key we just generated 302 X509_set_pubkey(x509, pPrivKey); 303 304 // get the subject name 305 X509_NAME* name = X509_get_subject_name(x509); 306 307 using x509String = const unsigned char; 308 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) 309 x509String* country = reinterpret_cast<x509String*>("US"); 310 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) 311 x509String* company = reinterpret_cast<x509String*>("OpenBMC"); 312 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) 313 x509String* cnStr = reinterpret_cast<x509String*>(cn.c_str()); 314 315 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, country, -1, -1, 316 0); 317 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, company, -1, -1, 318 0); 319 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, cnStr, -1, -1, 320 0); 321 // set the CSR options 322 X509_set_issuer_name(x509, name); 323 324 X509_set_version(x509, 2); 325 addExt(x509, NID_basic_constraints, ("critical,CA:TRUE")); 326 addExt(x509, NID_subject_alt_name, ("DNS:" + cn).c_str()); 327 addExt(x509, NID_subject_key_identifier, ("hash")); 328 addExt(x509, NID_authority_key_identifier, ("keyid")); 329 addExt(x509, NID_key_usage, ("digitalSignature, keyEncipherment")); 330 addExt(x509, NID_ext_key_usage, ("serverAuth")); 331 addExt(x509, NID_netscape_comment, (x509Comment)); 332 333 // Sign the certificate with our private key 334 X509_sign(x509, pPrivKey, EVP_sha256()); 335 336 BIO* bufio = BIO_new(BIO_s_mem()); 337 338 int pkeyRet = PEM_write_bio_PrivateKey( 339 bufio, pPrivKey, nullptr, nullptr, 0, nullptr, nullptr); 340 if (pkeyRet <= 0) 341 { 342 BMCWEB_LOG_ERROR( 343 "Failed to write pkey with code {}. Ignoring.", pkeyRet); 344 } 345 346 char* data = nullptr; 347 long int dataLen = BIO_get_mem_data(bufio, &data); 348 buffer += std::string_view(data, static_cast<size_t>(dataLen)); 349 BIO_free(bufio); 350 351 bufio = BIO_new(BIO_s_mem()); 352 pkeyRet = PEM_write_bio_X509(bufio, x509); 353 if (pkeyRet <= 0) 354 { 355 BMCWEB_LOG_ERROR( 356 "Failed to write X509 with code {}. Ignoring.", pkeyRet); 357 } 358 dataLen = BIO_get_mem_data(bufio, &data); 359 buffer += std::string_view(data, static_cast<size_t>(dataLen)); 360 361 BIO_free(bufio); 362 BMCWEB_LOG_INFO("Cert size is {}", buffer.size()); 363 X509_free(x509); 364 } 365 366 EVP_PKEY_free(pPrivKey); 367 pPrivKey = nullptr; 368 } 369 370 // cleanup_openssl(); 371 return buffer; 372 } 373 374 EVP_PKEY* createEcKey() 375 { 376 EVP_PKEY* pKey = nullptr; 377 378 // Create context for curve parameter generation. 379 std::unique_ptr<EVP_PKEY_CTX, decltype(&::EVP_PKEY_CTX_free)> ctx{ 380 EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr), &::EVP_PKEY_CTX_free}; 381 if (!ctx) 382 { 383 return nullptr; 384 } 385 386 // Set up curve parameters. 387 EVP_PKEY* params = nullptr; 388 if ((EVP_PKEY_paramgen_init(ctx.get()) <= 0) || 389 (EVP_PKEY_CTX_set_ec_param_enc(ctx.get(), OPENSSL_EC_NAMED_CURVE) <= 390 0) || 391 (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx.get(), NID_secp384r1) <= 392 0) || 393 (EVP_PKEY_paramgen(ctx.get(), ¶ms) <= 0)) 394 { 395 return nullptr; 396 } 397 398 // Set up RAII holder for params. 399 std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)> pparams{ 400 params, &::EVP_PKEY_free}; 401 402 // Set new context for key generation, using curve parameters. 403 ctx.reset(EVP_PKEY_CTX_new_from_pkey(nullptr, params, nullptr)); 404 if (!ctx || (EVP_PKEY_keygen_init(ctx.get()) <= 0)) 405 { 406 return nullptr; 407 } 408 409 // Generate key. 410 if (EVP_PKEY_keygen(ctx.get(), &pKey) <= 0) 411 { 412 return nullptr; 413 } 414 415 return pKey; 416 } 417 418 std::string ensureOpensslKeyPresentAndValid(const std::string& filepath) 419 { 420 std::string cert = verifyOpensslKeyCert(filepath); 421 422 if (cert.empty()) 423 { 424 BMCWEB_LOG_WARNING("Error in verifying signature, regenerating"); 425 cert = generateSslCertificate("testhost"); 426 if (cert.empty()) 427 { 428 BMCWEB_LOG_ERROR("Failed to generate cert"); 429 } 430 else 431 { 432 writeCertificateToFile(filepath, cert); 433 } 434 } 435 return cert; 436 } 437 438 static std::string ensureCertificate() 439 { 440 namespace fs = std::filesystem; 441 // Cleanup older certificate file existing in the system 442 fs::path oldcertPath = fs::path("/home/root/server.pem"); 443 std::error_code ec; 444 fs::remove(oldcertPath, ec); 445 // Ignore failure to remove; File might not exist. 446 447 fs::path certPath = "/etc/ssl/certs/https/"; 448 // if path does not exist create the path so that 449 // self signed certificate can be created in the 450 // path 451 fs::path certFile = certPath / "server.pem"; 452 453 if (!fs::exists(certPath, ec)) 454 { 455 fs::create_directories(certPath, ec); 456 } 457 BMCWEB_LOG_INFO("Building SSL Context file= {}", certFile.string()); 458 std::string sslPemFile(certFile); 459 return ensuressl::ensureOpensslKeyPresentAndValid(sslPemFile); 460 } 461 462 static int nextProtoCallback(SSL* /*unused*/, const unsigned char** data, 463 unsigned int* len, void* /*unused*/) 464 { 465 // First byte is the length. 466 constexpr std::string_view h2 = "\x02h2"; 467 *data = std::bit_cast<const unsigned char*>(h2.data()); 468 *len = static_cast<unsigned int>(h2.size()); 469 return SSL_TLSEXT_ERR_OK; 470 } 471 472 static int alpnSelectProtoCallback( 473 SSL* /*unused*/, const unsigned char** out, unsigned char* outlen, 474 const unsigned char* in, unsigned int inlen, void* /*unused*/) 475 { 476 int rv = nghttp2_select_alpn(out, outlen, in, inlen); 477 if (rv == -1) 478 { 479 return SSL_TLSEXT_ERR_NOACK; 480 } 481 if (rv == 1) 482 { 483 BMCWEB_LOG_DEBUG("Selected HTTP2"); 484 } 485 return SSL_TLSEXT_ERR_OK; 486 } 487 488 static bool getSslContext(boost::asio::ssl::context& mSslContext, 489 const std::string& sslPemFile) 490 { 491 mSslContext.set_options( 492 boost::asio::ssl::context::default_workarounds | 493 boost::asio::ssl::context::no_sslv2 | 494 boost::asio::ssl::context::no_sslv3 | 495 boost::asio::ssl::context::single_dh_use | 496 boost::asio::ssl::context::no_tlsv1 | 497 boost::asio::ssl::context::no_tlsv1_1); 498 499 BMCWEB_LOG_DEBUG("Using default TrustStore location: {}", trustStorePath); 500 mSslContext.add_verify_path(trustStorePath); 501 502 if (!sslPemFile.empty()) 503 { 504 boost::system::error_code ec; 505 506 boost::asio::const_buffer buf(sslPemFile.data(), sslPemFile.size()); 507 mSslContext.use_certificate_chain(buf, ec); 508 if (ec) 509 { 510 return false; 511 } 512 mSslContext.use_private_key(buf, boost::asio::ssl::context::pem, ec); 513 if (ec) 514 { 515 BMCWEB_LOG_CRITICAL("Failed to open ssl pkey"); 516 return false; 517 } 518 } 519 520 // Set up EC curves to auto (boost asio doesn't have a method for this) 521 // There is a pull request to add this. Once this is included in an asio 522 // drop, use the right way 523 // http://stackoverflow.com/questions/18929049/boost-asio-with-ecdsa-certificate-issue 524 if (SSL_CTX_set_ecdh_auto(mSslContext.native_handle(), 1) != 1) 525 {} 526 527 if (SSL_CTX_set_cipher_list(mSslContext.native_handle(), 528 mozillaIntermediate) != 1) 529 { 530 BMCWEB_LOG_ERROR("Error setting cipher list"); 531 return false; 532 } 533 return true; 534 } 535 536 std::shared_ptr<boost::asio::ssl::context> getSslServerContext() 537 { 538 boost::asio::ssl::context sslCtx(boost::asio::ssl::context::tls_server); 539 540 auto certFile = ensureCertificate(); 541 if (!getSslContext(sslCtx, certFile)) 542 { 543 BMCWEB_LOG_CRITICAL("Couldn't get server context"); 544 return nullptr; 545 } 546 const persistent_data::AuthConfigMethods& c = 547 persistent_data::SessionStore::getInstance().getAuthMethodsConfig(); 548 549 boost::asio::ssl::verify_mode mode = boost::asio::ssl::verify_none; 550 if (c.tlsStrict) 551 { 552 BMCWEB_LOG_DEBUG("Setting verify peer and fail if no peer cert"); 553 mode |= boost::asio::ssl::verify_peer; 554 mode |= boost::asio::ssl::verify_fail_if_no_peer_cert; 555 } 556 else if (!forward_unauthorized::hasWebuiRoute) 557 { 558 // This is a HACK 559 // If the webui is installed, and TLSSTrict is false, we don't want to 560 // force the mtls popup to occur, which would happen if we requested a 561 // client cert by setting verify_peer. But, if the webui isn't 562 // installed, we'd like clients to be able to optionally log in with 563 // MTLS, which won't happen if we don't expose the MTLS client cert 564 // request. So, in this case detect if the webui is installed, and 565 // only request peer authentication if it's not present. 566 // This will likely need revisited in the future. 567 BMCWEB_LOG_DEBUG("Setting verify peer only"); 568 mode |= boost::asio::ssl::verify_peer; 569 } 570 571 boost::system::error_code ec; 572 sslCtx.set_verify_mode(mode, ec); 573 if (ec) 574 { 575 BMCWEB_LOG_DEBUG("Failed to set verify mode {}", ec.message()); 576 return nullptr; 577 } 578 579 SSL_CTX_set_options(sslCtx.native_handle(), SSL_OP_NO_RENEGOTIATION); 580 581 if constexpr (BMCWEB_EXPERIMENTAL_HTTP2) 582 { 583 SSL_CTX_set_next_protos_advertised_cb(sslCtx.native_handle(), 584 nextProtoCallback, nullptr); 585 586 SSL_CTX_set_alpn_select_cb(sslCtx.native_handle(), 587 alpnSelectProtoCallback, nullptr); 588 } 589 590 return std::make_shared<boost::asio::ssl::context>(std::move(sslCtx)); 591 } 592 593 std::optional<boost::asio::ssl::context> getSSLClientContext( 594 VerifyCertificate verifyCertificate) 595 { 596 namespace fs = std::filesystem; 597 598 boost::asio::ssl::context sslCtx(boost::asio::ssl::context::tls_client); 599 600 // NOTE, this path is temporary; In the future it will need to change to 601 // be set per subscription. Do not rely on this. 602 fs::path certPath = "/etc/ssl/certs/https/client.pem"; 603 std::string cert = verifyOpensslKeyCert(certPath); 604 605 if (!getSslContext(sslCtx, cert)) 606 { 607 return std::nullopt; 608 } 609 610 // Add a directory containing certificate authority files to be used 611 // for performing verification. 612 boost::system::error_code ec; 613 sslCtx.set_default_verify_paths(ec); 614 if (ec) 615 { 616 BMCWEB_LOG_ERROR("SSL context set_default_verify failed"); 617 return std::nullopt; 618 } 619 620 int mode = boost::asio::ssl::verify_peer; 621 if (verifyCertificate == VerifyCertificate::NoVerify) 622 { 623 mode = boost::asio::ssl::verify_none; 624 } 625 626 // Verify the remote server's certificate 627 sslCtx.set_verify_mode(mode, ec); 628 if (ec) 629 { 630 BMCWEB_LOG_ERROR("SSL context set_verify_mode failed"); 631 return std::nullopt; 632 } 633 634 if (SSL_CTX_set_cipher_list(sslCtx.native_handle(), mozillaIntermediate) != 635 1) 636 { 637 BMCWEB_LOG_ERROR("SSL_CTX_set_cipher_list failed"); 638 return std::nullopt; 639 } 640 641 return {std::move(sslCtx)}; 642 } 643 644 } // namespace ensuressl 645