| 1 | // Copyright (c) 2018-2022, The Monero Project |
| 2 | |
| 3 | // |
| 4 | // All rights reserved. |
| 5 | // |
| 6 | // Redistribution and use in source and binary forms, with or without modification, are |
| 7 | // permitted provided that the following conditions are met: |
| 8 | // |
| 9 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 10 | // conditions and the following disclaimer. |
| 11 | // |
| 12 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 13 | // of conditions and the following disclaimer in the documentation and/or other |
| 14 | // materials provided with the distribution. |
| 15 | // |
| 16 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 17 | // used to endorse or promote products derived from this software without specific |
| 18 | // prior written permission. |
| 19 | // |
| 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 21 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 22 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 23 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 24 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 25 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 26 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 27 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 28 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | |
| 30 | #include <string.h> |
| 31 | #include <thread> |
| 32 | #include <boost/asio/post.hpp> |
| 33 | #include <boost/asio/ssl.hpp> |
| 34 | #include <boost/cerrno.hpp> |
| 35 | #include <boost/filesystem/operations.hpp> |
| 36 | #include <boost/asio/strand.hpp> |
| 37 | #include <condition_variable> |
| 38 | #include <boost/lambda/lambda.hpp> |
| 39 | #include <openssl/ssl.h> |
| 40 | #include <openssl/pem.h> |
| 41 | #include "misc_log_ex.h" |
| 42 | #include "net/net_helper.h" |
| 43 | #include "net/net_ssl.h" |
| 44 | #include "file_io_utils.h" // to validate .crt and .key paths |
| 45 | |
| 46 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 47 | #define MONERO_DEFAULT_LOG_CATEGORY "net.ssl" |
| 48 | |
| 49 | |
| 50 | #if BOOST_VERSION >= 107300 |
| 51 | #define MONERO_HOSTNAME_VERIFY boost::asio::ssl::host_name_verification |
| 52 | #else |
| 53 | #define MONERO_HOSTNAME_VERIFY boost::asio::ssl::rfc2818_verification |
| 54 | #endif |
| 55 | |
| 56 | // openssl genrsa -out /tmp/KEY 4096 |
| 57 | // openssl req -new -key /tmp/KEY -out /tmp/REQ |
| 58 | // openssl x509 -req -days 999999 -sha256 -in /tmp/REQ -signkey /tmp/KEY -out /tmp/CERT |
| 59 | |
| 60 | #ifdef _WIN32 |
| 61 | static void add_windows_root_certs(SSL_CTX *ctx) noexcept; |
| 62 | #endif |
| 63 | |
| 64 | namespace |
| 65 | { |
| 66 | struct openssl_bio_free |
| 67 | { |
| 68 | void operator()(BIO* ptr) const noexcept |
| 69 | { |
| 70 | BIO_free(ptr); |
| 71 | } |
| 72 | }; |
| 73 | using openssl_bio = std::unique_ptr<BIO, openssl_bio_free>; |
| 74 | |
| 75 | struct openssl_pkey_free |
| 76 | { |
| 77 | void operator()(EVP_PKEY* ptr) const noexcept |
| 78 | { |
| 79 | EVP_PKEY_free(ptr); |
| 80 | } |
| 81 | }; |
| 82 | using openssl_pkey = std::unique_ptr<EVP_PKEY, openssl_pkey_free>; |
| 83 | |
| 84 | struct openssl_rsa_free |
| 85 | { |
| 86 | void operator()(RSA* ptr) const noexcept |
| 87 | { |
| 88 | RSA_free(ptr); |
| 89 | } |
| 90 | }; |
| 91 | using openssl_rsa = std::unique_ptr<RSA, openssl_rsa_free>; |
| 92 | |
| 93 | struct openssl_bignum_free |
| 94 | { |
| 95 | void operator()(BIGNUM* ptr) const noexcept |
| 96 | { |
| 97 | BN_free(ptr); |
| 98 | } |
| 99 | }; |
| 100 | using openssl_bignum = std::unique_ptr<BIGNUM, openssl_bignum_free>; |
| 101 | |
| 102 | struct openssl_ec_key_free |
| 103 | { |
| 104 | void operator()(EC_KEY* ptr) const noexcept |
| 105 | { |
| 106 | EC_KEY_free(ptr); |
| 107 | } |
| 108 | }; |
| 109 | using openssl_ec_key = std::unique_ptr<EC_KEY, openssl_ec_key_free>; |
| 110 | |
| 111 | struct openssl_group_free |
| 112 | { |
| 113 | void operator()(EC_GROUP* ptr) const noexcept |
| 114 | { |
| 115 | EC_GROUP_free(ptr); |
| 116 | } |
| 117 | }; |
| 118 | using openssl_group = std::unique_ptr<EC_GROUP, openssl_group_free>; |
| 119 | |
| 120 | boost::system::error_code load_ca_file(boost::asio::ssl::context& ctx, const std::string& path) |
| 121 | { |
| 122 | SSL_CTX* const ssl_ctx = ctx.native_handle(); // could be moved from context |
| 123 | if (ssl_ctx == nullptr) |
| 124 | return {boost::asio::error::invalid_argument}; |
| 125 | |
| 126 | if (!SSL_CTX_load_verify_locations(ssl_ctx, path.c_str(), nullptr)) |
| 127 | { |
| 128 | return boost::system::error_code{ |
| 129 | int(::ERR_get_error()), boost::asio::error::get_ssl_category() |
| 130 | }; |
| 131 | } |
| 132 | return boost::system::error_code{}; |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | namespace epee |
| 137 | { |
| 138 | namespace net_utils |
| 139 | { |
| 140 | |
| 141 | |
| 142 | // https://stackoverflow.com/questions/256405/programmatically-create-x509-certificate-using-openssl |
| 143 | bool create_rsa_ssl_certificate(EVP_PKEY *&pkey, X509 *&cert) |
| 144 | { |
| 145 | MINFO("Generating SSL certificate"); |
| 146 | pkey = EVP_PKEY_new(); |
| 147 | if (!pkey) |
| 148 | { |
| 149 | MERROR("Failed to create new private key"); |
| 150 | return false; |
| 151 | } |
| 152 | |
| 153 | openssl_pkey pkey_deleter{pkey}; |
| 154 | openssl_rsa rsa{RSA_new()}; |
| 155 | if (!rsa) |
| 156 | { |
| 157 | MERROR("Error allocating RSA private key"); |
| 158 | return false; |
| 159 | } |
| 160 | |
| 161 | openssl_bignum exponent{BN_new()}; |
| 162 | if (!exponent) |
| 163 | { |
| 164 | MERROR("Error allocating exponent"); |
| 165 | return false; |
| 166 | } |
| 167 | |
| 168 | BN_set_word(exponent.get(), RSA_F4); |
| 169 | |
| 170 | if (RSA_generate_key_ex(rsa.get(), 4096, exponent.get(), nullptr) != 1) |
| 171 | { |
| 172 | MERROR("Error generating RSA private key"); |
| 173 | return false; |
| 174 | } |
| 175 | |
| 176 | if (EVP_PKEY_assign_RSA(pkey, rsa.get()) <= 0) |
| 177 | { |
| 178 | MERROR("Error assigning RSA private key"); |
| 179 | return false; |
| 180 | } |
| 181 | |
| 182 | // the RSA key is now managed by the EVP_PKEY structure |
| 183 | (void)rsa.release(); |
| 184 | |
| 185 | cert = X509_new(); |
| 186 | if (!cert) |
| 187 | { |
| 188 | MERROR("Failed to create new X509 certificate"); |
| 189 | return false; |
| 190 | } |
| 191 | ASN1_INTEGER_set(X509_get_serialNumber(cert), 1); |
| 192 | X509_gmtime_adj(X509_get_notBefore(cert), 0); |
| 193 | X509_gmtime_adj(X509_get_notAfter(cert), 3600 * 24 * 182); // half a year |
| 194 | if (!X509_set_pubkey(cert, pkey)) |
| 195 | { |
| 196 | MERROR("Error setting pubkey on certificate"); |
| 197 | X509_free(cert); |
| 198 | return false; |
| 199 | } |
| 200 | X509_NAME *name = X509_get_subject_name(cert); |
| 201 | X509_set_issuer_name(cert, name); |
| 202 | |
| 203 | if (X509_sign(cert, pkey, EVP_sha256()) == 0) |
| 204 | { |
| 205 | MERROR("Error signing certificate"); |
| 206 | X509_free(cert); |
| 207 | return false; |
| 208 | } |
| 209 | (void)pkey_deleter.release(); |
| 210 | return true; |
| 211 | } |
| 212 | |
| 213 | bool create_ec_ssl_certificate(EVP_PKEY *&pkey, X509 *&cert, int type) |
| 214 | { |
| 215 | MINFO("Generating SSL certificate"); |
| 216 | pkey = EVP_PKEY_new(); |
| 217 | if (!pkey) |
| 218 | { |
| 219 | MERROR("Failed to create new private key"); |
| 220 | return false; |
| 221 | } |
| 222 | |
| 223 | openssl_pkey pkey_deleter{pkey}; |
| 224 | openssl_ec_key ec_key{EC_KEY_new()}; |
| 225 | if (!ec_key) |
| 226 | { |
| 227 | MERROR("Error allocating EC private key"); |
| 228 | return false; |
| 229 | } |
| 230 | |
| 231 | EC_GROUP *group = EC_GROUP_new_by_curve_name(type); |
| 232 | if (!group) |
| 233 | { |
| 234 | MERROR("Error getting EC group " << type); |
| 235 | return false; |
| 236 | } |
| 237 | openssl_group group_deleter{group}; |
| 238 | |
| 239 | EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE); |
| 240 | EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED); |
| 241 | |
| 242 | if (!EC_GROUP_check(group, NULL)) |
| 243 | { |
| 244 | MERROR("Group failed check: " << ERR_reason_error_string(ERR_get_error())); |
| 245 | return false; |
| 246 | } |
| 247 | if (EC_KEY_set_group(ec_key.get(), group) != 1) |
| 248 | { |
| 249 | MERROR("Error setting EC group"); |
| 250 | return false; |
| 251 | } |
| 252 | if (EC_KEY_generate_key(ec_key.get()) != 1) |
| 253 | { |
| 254 | MERROR("Error generating EC private key"); |
| 255 | return false; |
| 256 | } |
| 257 | if (EVP_PKEY_assign_EC_KEY(pkey, ec_key.get()) <= 0) |
| 258 | { |
| 259 | MERROR("Error assigning EC private key"); |
| 260 | return false; |
| 261 | } |
| 262 | |
| 263 | // the key is now managed by the EVP_PKEY structure |
| 264 | (void)ec_key.release(); |
| 265 | |
| 266 | cert = X509_new(); |
| 267 | if (!cert) |
| 268 | { |
| 269 | MERROR("Failed to create new X509 certificate"); |
| 270 | return false; |
| 271 | } |
| 272 | ASN1_INTEGER_set(X509_get_serialNumber(cert), 1); |
| 273 | X509_gmtime_adj(X509_get_notBefore(cert), 0); |
| 274 | X509_gmtime_adj(X509_get_notAfter(cert), 3600 * 24 * 182); // half a year |
| 275 | if (!X509_set_pubkey(cert, pkey)) |
| 276 | { |
| 277 | MERROR("Error setting pubkey on certificate"); |
| 278 | X509_free(cert); |
| 279 | return false; |
| 280 | } |
| 281 | X509_NAME *name = X509_get_subject_name(cert); |
| 282 | X509_set_issuer_name(cert, name); |
| 283 | |
| 284 | if (X509_sign(cert, pkey, EVP_sha256()) == 0) |
| 285 | { |
| 286 | MERROR("Error signing certificate"); |
| 287 | X509_free(cert); |
| 288 | return false; |
| 289 | } |
| 290 | (void)pkey_deleter.release(); |
| 291 | return true; |
| 292 | } |
| 293 | |
| 294 | ssl_options_t::ssl_options_t(std::vector<std::vector<std::uint8_t>> fingerprints, std::string ca_path) |
| 295 | : fingerprints_(std::move(fingerprints)), |
| 296 | ca_path(std::move(ca_path)), |
| 297 | auth(), |
| 298 | support(ssl_support_t::e_ssl_support_enabled), |
| 299 | verification(ssl_verification_t::user_certificates) |
| 300 | { |
| 301 | std::sort(fingerprints_.begin(), fingerprints_.end()); |
| 302 | } |
| 303 | |
| 304 | boost::asio::ssl::context ssl_options_t::create_context() const |
| 305 | { |
| 306 | // note: this enables a lot of old and insecure protocols, which we |
| 307 | // promptly disable below - if the result is actually used |
| 308 | boost::asio::ssl::context ssl_context{boost::asio::ssl::context::sslv23}; |
| 309 | if (!bool(*this)) |
| 310 | return ssl_context; |
| 311 | |
| 312 | // only allow tls v1.2 and up |
| 313 | ssl_context.set_options(boost::asio::ssl::context::default_workarounds); |
| 314 | ssl_context.set_options(boost::asio::ssl::context::no_sslv2); |
| 315 | ssl_context.set_options(boost::asio::ssl::context::no_sslv3); |
| 316 | ssl_context.set_options(boost::asio::ssl::context::no_tlsv1); |
| 317 | ssl_context.set_options(boost::asio::ssl::context::no_tlsv1_1); |
| 318 | |
| 319 | // only allow a select handful of tls v1.3 and v1.2 ciphers to be used |
| 320 | SSL_CTX_set_cipher_list(ssl_context.native_handle(), "ECDHE-ECDSA-CHACHA20-POLY1305-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256"); |
| 321 | |
| 322 | // set options on the SSL context for added security |
| 323 | SSL_CTX *ctx = ssl_context.native_handle(); |
| 324 | CHECK_AND_ASSERT_THROW_MES(ctx, "Failed to get SSL context"); |
| 325 | SSL_CTX_clear_options(ctx, SSL_OP_LEGACY_SERVER_CONNECT); // SSL_CTX_SET_OPTIONS(3) |
| 326 | SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); // https://stackoverflow.com/questions/22378442 |
| 327 | #ifdef SSL_OP_NO_TICKET |
| 328 | SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET); // https://stackoverflow.com/questions/22378442 |
| 329 | #endif |
| 330 | #ifdef SSL_OP_NO_RENEGOTIATION |
| 331 | SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION); |
| 332 | #endif |
| 333 | #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
| 334 | SSL_CTX_set_options(ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); |
| 335 | #endif |
| 336 | #ifdef SSL_OP_NO_COMPRESSION |
| 337 | SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION); |
| 338 | #endif |
| 339 | #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE |
| 340 | SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); |
| 341 | #endif |
| 342 | SSL_CTX_set_ecdh_auto(ctx, 1); |
| 343 | |
| 344 | switch (verification) |
| 345 | { |
| 346 | case ssl_verification_t::system_ca: |
| 347 | #ifdef _WIN32 |
| 348 | try { add_windows_root_certs(ssl_context.native_handle()); } |
| 349 | catch (const std::exception &e) { ssl_context.set_default_verify_paths(); } |
| 350 | #else |
| 351 | ssl_context.set_default_verify_paths(); |
| 352 | #endif |
| 353 | break; |
| 354 | case ssl_verification_t::user_certificates: |
| 355 | ssl_context.set_verify_depth(0); |
| 356 | /* fallthrough */ |
| 357 | case ssl_verification_t::user_ca: |
| 358 | if (!ca_path.empty()) |
| 359 | { |
| 360 | const boost::system::error_code err = load_ca_file(ssl_context, ca_path); |
| 361 | if (err) |
| 362 | throw boost::system::system_error{err, "Failed to load user CA file at " + ca_path}; |
| 363 | } |
| 364 | break; |
| 365 | default: |
| 366 | break; |
| 367 | } |
| 368 | |
| 369 | CHECK_AND_ASSERT_THROW_MES(auth.private_key_path.empty() == auth.certificate_path.empty(), "private key and certificate must be either both given or both empty"); |
| 370 | |
| 371 | const bool private_key_exists = epee::file_io_utils::is_file_exist(auth.private_key_path); |
| 372 | const bool certificate_exists = epee::file_io_utils::is_file_exist(auth.certificate_path); |
| 373 | if (private_key_exists && !certificate_exists) { |
| 374 | ASSERT_MES_AND_THROW("private key is present, but certificate file '" << auth.certificate_path << "' is missing"); |
| 375 | } else if (!private_key_exists && certificate_exists) { |
| 376 | ASSERT_MES_AND_THROW("certificate is present, but private key file '" << auth.private_key_path << "' is missing"); |
| 377 | } |
| 378 | |
| 379 | if (auth.private_key_path.empty()) |
| 380 | { |
| 381 | EVP_PKEY *pkey; |
| 382 | X509 *cert; |
| 383 | bool ok = false; |
| 384 | |
| 385 | #ifdef USE_EXTRA_EC_CERT |
| 386 | CHECK_AND_ASSERT_THROW_MES(create_ec_ssl_certificate(pkey, cert, NID_secp256k1), "Failed to create certificate"); |
| 387 | CHECK_AND_ASSERT_THROW_MES(SSL_CTX_use_certificate(ctx, cert), "Failed to use generated certificate"); |
| 388 | if (!SSL_CTX_use_PrivateKey(ctx, pkey)) |
| 389 | MERROR("Failed to use generated EC private key for " << NID_secp256k1); |
| 390 | else |
| 391 | ok = true; |
| 392 | X509_free(cert); |
| 393 | EVP_PKEY_free(pkey); |
| 394 | #endif |
| 395 | |
| 396 | CHECK_AND_ASSERT_THROW_MES(create_rsa_ssl_certificate(pkey, cert), "Failed to create certificate"); |
| 397 | CHECK_AND_ASSERT_THROW_MES(SSL_CTX_use_certificate(ctx, cert), "Failed to use generated certificate"); |
| 398 | if (!SSL_CTX_use_PrivateKey(ctx, pkey)) |
| 399 | MERROR("Failed to use generated RSA private key for RSA"); |
| 400 | else |
| 401 | ok = true; |
| 402 | X509_free(cert); |
| 403 | EVP_PKEY_free(pkey); |
| 404 | |
| 405 | CHECK_AND_ASSERT_THROW_MES(ok, "Failed to use any generated certificate"); |
| 406 | } |
| 407 | else |
| 408 | auth.use_ssl_certificate(ssl_context); |
| 409 | |
| 410 | return ssl_context; |
| 411 | } |
| 412 | |
| 413 | void ssl_authentication_t::use_ssl_certificate(boost::asio::ssl::context &ssl_context) const |
| 414 | { |
| 415 | try { |
| 416 | ssl_context.use_private_key_file(private_key_path, boost::asio::ssl::context::pem); |
| 417 | } catch (const boost::system::system_error&) { |
| 418 | MERROR("Failed to load private key file '" << private_key_path << "' into SSL context"); |
| 419 | throw; |
| 420 | } |
| 421 | ssl_context.use_certificate_chain_file(certificate_path); |
| 422 | } |
| 423 | |
| 424 | bool is_ssl(const unsigned char *data, size_t len) |
| 425 | { |
| 426 | if (len < get_ssl_magic_size()) |
| 427 | return false; |
| 428 | |
| 429 | // https://security.stackexchange.com/questions/34780/checking-client-hello-for-https-classification |
| 430 | MDEBUG("SSL detection buffer, " << len << " bytes: " |
| 431 | << (unsigned)(unsigned char)data[0] << " " << (unsigned)(unsigned char)data[1] << " " |
| 432 | << (unsigned)(unsigned char)data[2] << " " << (unsigned)(unsigned char)data[3] << " " |
| 433 | << (unsigned)(unsigned char)data[4] << " " << (unsigned)(unsigned char)data[5] << " " |
| 434 | << (unsigned)(unsigned char)data[6] << " " << (unsigned)(unsigned char)data[7] << " " |
| 435 | << (unsigned)(unsigned char)data[8]); |
| 436 | if (data[0] == 0x16) // record |
| 437 | if (data[1] == 3) // major version |
| 438 | if (data[5] == 1) // ClientHello |
| 439 | if (data[6] == 0 && data[3]*256 + data[4] == data[7]*256 + data[8] + 4) // length check |
| 440 | return true; |
| 441 | return false; |
| 442 | } |
| 443 | |
| 444 | bool ssl_options_t::has_strong_verification(boost::string_ref host) const noexcept |
| 445 | { |
| 446 | // onion and i2p addresses contain information about the server cert |
| 447 | // which both authenticates and encrypts |
| 448 | if (host.ends_with(".onion") || host.ends_with(".i2p")) |
| 449 | return true; |
| 450 | switch (verification) |
| 451 | { |
| 452 | default: |
| 453 | case ssl_verification_t::none: |
| 454 | case ssl_verification_t::system_ca: |
| 455 | return false; |
| 456 | case ssl_verification_t::user_certificates: |
| 457 | case ssl_verification_t::user_ca: |
| 458 | break; |
| 459 | } |
| 460 | return true; |
| 461 | } |
| 462 | |
| 463 | bool ssl_options_t::has_fingerprint(boost::asio::ssl::verify_context &ctx) const |
| 464 | { |
| 465 | // can we check the certificate against a list of fingerprints? |
| 466 | if (!fingerprints_.empty()) { |
| 467 | X509_STORE_CTX *sctx = ctx.native_handle(); |
| 468 | if (!sctx) |
| 469 | { |
| 470 | MERROR("Error getting verify_context handle"); |
| 471 | return false; |
| 472 | } |
| 473 | |
| 474 | X509* cert = nullptr; |
| 475 | const STACK_OF(X509)* chain = X509_STORE_CTX_get_chain(sctx); |
| 476 | if (!chain || sk_X509_num(chain) < 1 || !(cert = sk_X509_value(chain, 0))) |
| 477 | { |
| 478 | MERROR("No certificate found in verify_context"); |
| 479 | return false; |
| 480 | } |
| 481 | |
| 482 | // buffer for the certificate digest and the size of the result |
| 483 | std::vector<uint8_t> digest(EVP_MAX_MD_SIZE); |
| 484 | unsigned int size{ 0 }; |
| 485 | |
| 486 | // create the digest from the certificate |
| 487 | if (!X509_digest(cert, EVP_sha256(), digest.data(), &size)) { |
| 488 | MERROR("Failed to create certificate fingerprint"); |
| 489 | return false; |
| 490 | } |
| 491 | |
| 492 | // strip unnecessary bytes from the digest |
| 493 | digest.resize(size); |
| 494 | |
| 495 | return std::binary_search(fingerprints_.begin(), fingerprints_.end(), digest); |
| 496 | } |
| 497 | |
| 498 | return false; |
| 499 | } |
| 500 | |
| 501 | void ssl_options_t::configure( |
| 502 | boost::asio::ssl::stream<boost::asio::ip::tcp::socket> &socket, |
| 503 | boost::asio::ssl::stream_base::handshake_type type, |
| 504 | const std::string& host) const |
| 505 | { |
| 506 | socket.next_layer().set_option(boost::asio::ip::tcp::no_delay(true)); |
| 507 | { |
| 508 | // in case server is doing "virtual" domains, set hostname |
| 509 | SSL* const ssl_ctx = socket.native_handle(); |
| 510 | if (type == boost::asio::ssl::stream_base::client && !host.empty() && ssl_ctx) |
| 511 | SSL_set_tlsext_host_name(ssl_ctx, host.c_str()); |
| 512 | } |
| 513 | |
| 514 | |
| 515 | /* Using system-wide CA store for client verification is funky - there is |
| 516 | no expected hostname for server to verify against. If server doesn't have |
| 517 | specific whitelisted certificates for client, don't require client to |
| 518 | send certificate at all. */ |
| 519 | const bool no_verification = verification == ssl_verification_t::none || |
| 520 | (type == boost::asio::ssl::stream_base::server && fingerprints_.empty() && ca_path.empty()); |
| 521 | |
| 522 | /* According to OpenSSL documentation (and SSL specifications), server must |
| 523 | always send certificate unless "anonymous" cipher mode is used which are |
| 524 | disabled by default. Either way, the certificate is never inspected. */ |
| 525 | if (no_verification) |
| 526 | socket.set_verify_mode(boost::asio::ssl::verify_none); |
| 527 | else |
| 528 | { |
| 529 | socket.set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert); |
| 530 | |
| 531 | |
| 532 | socket.set_verify_callback([&](const bool preverified, boost::asio::ssl::verify_context &ctx) |
| 533 | { |
| 534 | // preverified means it passed system or user CA check. System CA is never loaded |
| 535 | // when fingerprints are whitelisted. |
| 536 | const bool verified = preverified && |
| 537 | (verification != ssl_verification_t::system_ca || host.empty() || MONERO_HOSTNAME_VERIFY(host)(preverified, ctx)); |
| 538 | |
| 539 | if (!verified && !has_fingerprint(ctx)) |
| 540 | { |
| 541 | // autodetect will reconnect without SSL - warn and keep connection encrypted |
| 542 | if (support != ssl_support_t::e_ssl_support_autodetect) |
| 543 | { |
| 544 | MERROR("SSL certificate is not in the allowed list, connection dropped"); |
| 545 | return false; |
| 546 | } |
| 547 | MWARNING("SSL peer has not been verified"); |
| 548 | } |
| 549 | return true; |
| 550 | }); |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | bool ssl_options_t::handshake( |
| 555 | boost::asio::io_context& io_context, |
| 556 | boost::asio::ssl::stream<boost::asio::ip::tcp::socket> &socket, |
| 557 | boost::asio::ssl::stream_base::handshake_type type, |
| 558 | boost::asio::const_buffer buffer, |
| 559 | const std::string& host, |
| 560 | std::chrono::milliseconds timeout) const |
| 561 | { |
| 562 | configure(socket, type, host); |
| 563 | |
| 564 | auto start_handshake = [&]{ |
| 565 | using ec_t = boost::system::error_code; |
| 566 | using timer_t = boost::asio::steady_timer; |
| 567 | using strand_t = boost::asio::io_context::strand; |
| 568 | using socket_t = boost::asio::ip::tcp::socket; |
| 569 | |
| 570 | if (io_context.stopped()) |
| 571 | io_context.restart(); |
| 572 | strand_t strand(io_context); |
| 573 | timer_t deadline(io_context, timeout); |
| 574 | |
| 575 | struct state_t { |
| 576 | std::mutex lock; |
| 577 | std::condition_variable_any condition; |
| 578 | ec_t result; |
| 579 | bool wait_timer; |
| 580 | bool wait_handshake; |
| 581 | bool cancel_timer; |
| 582 | bool cancel_handshake; |
| 583 | }; |
| 584 | state_t state{}; |
| 585 | |
| 586 | state.wait_timer = true; |
| 587 | auto on_timer = [&](const ec_t &ec){ |
| 588 | std::lock_guard<std::mutex> guard(state.lock); |
| 589 | state.wait_timer = false; |
| 590 | state.condition.notify_all(); |
| 591 | if (!state.cancel_timer) { |
| 592 | state.cancel_handshake = true; |
| 593 | ec_t ec; |
| 594 | socket.next_layer().cancel(ec); |
| 595 | } |
| 596 | }; |
| 597 | |
| 598 | state.wait_handshake = true; |
| 599 | auto on_handshake = [&](const ec_t &ec, size_t bytes_transferred){ |
| 600 | std::lock_guard<std::mutex> guard(state.lock); |
| 601 | state.wait_handshake = false; |
| 602 | state.condition.notify_all(); |
| 603 | state.result = ec; |
| 604 | if (!state.cancel_handshake) { |
| 605 | state.cancel_timer = true; |
| 606 | deadline.cancel(); |
| 607 | } |
| 608 | }; |
| 609 | |
| 610 | deadline.async_wait(on_timer); |
| 611 | boost::asio::post( |
| 612 | strand, |
| 613 | [&]{ |
| 614 | socket.async_handshake( |
| 615 | type, |
| 616 | boost::asio::buffer(buffer), |
| 617 | strand.wrap(on_handshake) |
| 618 | ); |
| 619 | } |
| 620 | ); |
| 621 | |
| 622 | while (!io_context.stopped()) |
| 623 | { |
| 624 | io_context.poll_one(); |
| 625 | std::lock_guard<std::mutex> guard(state.lock); |
| 626 | state.condition.wait_for( |
| 627 | state.lock, |
| 628 | std::chrono::milliseconds(30), |
| 629 | [&]{ |
| 630 | return !state.wait_timer && !state.wait_handshake; |
| 631 | } |
| 632 | ); |
| 633 | if (!state.wait_timer && !state.wait_handshake) |
| 634 | break; |
| 635 | } |
| 636 | if (state.result.value()) { |
| 637 | ec_t ec; |
| 638 | socket.next_layer().shutdown(socket_t::shutdown_both, ec); |
| 639 | socket.next_layer().close(ec); |
| 640 | } |
| 641 | return state.result; |
| 642 | }; |
| 643 | const auto ec = start_handshake(); |
| 644 | |
| 645 | if (ec) |
| 646 | { |
| 647 | MERROR("SSL handshake failed, connection dropped: " << ec.message()); |
| 648 | return false; |
| 649 | } |
| 650 | MDEBUG("SSL handshake success"); |
| 651 | return true; |
| 652 | } |
| 653 | |
| 654 | bool ssl_support_from_string(ssl_support_t &ssl, boost::string_ref s) |
| 655 | { |
| 656 | if (s == "enabled") |
| 657 | ssl = epee::net_utils::ssl_support_t::e_ssl_support_enabled; |
| 658 | else if (s == "disabled") |
| 659 | ssl = epee::net_utils::ssl_support_t::e_ssl_support_disabled; |
| 660 | else if (s == "autodetect") |
| 661 | ssl = epee::net_utils::ssl_support_t::e_ssl_support_autodetect; |
| 662 | else |
| 663 | return false; |
| 664 | return true; |
| 665 | } |
| 666 | |
| 667 | boost::system::error_code store_ssl_keys(boost::asio::ssl::context& ssl, const boost::filesystem::path& base) |
| 668 | { |
| 669 | EVP_PKEY* ssl_key = nullptr; |
| 670 | X509* ssl_cert = nullptr; |
| 671 | const auto ctx = ssl.native_handle(); |
| 672 | CHECK_AND_ASSERT_MES(ctx, boost::system::error_code(EINVAL, boost::system::system_category()), "Context is null"); |
| 673 | CHECK_AND_ASSERT_MES(base.has_filename(), boost::system::error_code(EINVAL, boost::system::system_category()), "Need filename"); |
| 674 | std::unique_ptr<SSL, decltype(&SSL_free)> dflt_SSL(SSL_new(ctx), SSL_free); |
| 675 | if (!dflt_SSL || !(ssl_key = SSL_get_privatekey(dflt_SSL.get())) || !(ssl_cert = SSL_get_certificate(dflt_SSL.get()))) |
| 676 | return {EINVAL, boost::system::system_category()}; |
| 677 | |
| 678 | using file_closer = int(std::FILE*); |
| 679 | boost::system::error_code error{}; |
| 680 | std::unique_ptr<std::FILE, file_closer*> file{nullptr, std::fclose}; |
| 681 | |
| 682 | // write key file unencrypted |
| 683 | { |
| 684 | const boost::filesystem::path key_file{base.string() + ".key"}; |
| 685 | file.reset(std::fopen(key_file.string().c_str(), "wb")); |
| 686 | if (!file) |
| 687 | { |
| 688 | if (epee::file_io_utils::is_file_exist(key_file.string())) { |
| 689 | MERROR("Permission denied to overwrite SSL private key file: '" << key_file.string() << "'"); |
| 690 | } else { |
| 691 | MERROR("Could not open SSL private key file for writing: '" << key_file.string() << "'"); |
| 692 | } |
| 693 | |
| 694 | return {errno, boost::system::system_category()}; |
| 695 | } |
| 696 | boost::filesystem::permissions(key_file, boost::filesystem::owner_read, error); |
| 697 | if (error) |
| 698 | return error; |
| 699 | if (!PEM_write_PrivateKey(file.get(), ssl_key, nullptr, nullptr, 0, nullptr, nullptr)) |
| 700 | return boost::asio::error::ssl_errors(ERR_get_error()); |
| 701 | if (std::fclose(file.release()) != 0) |
| 702 | return {errno, boost::system::system_category()}; |
| 703 | } |
| 704 | |
| 705 | // write certificate file in standard SSL X.509 unencrypted |
| 706 | const boost::filesystem::path cert_file{base.string() + ".crt"}; |
| 707 | file.reset(std::fopen(cert_file.string().c_str(), "wb")); |
| 708 | if (!file) |
| 709 | return {errno, boost::system::system_category()}; |
| 710 | const auto cert_perms = (boost::filesystem::owner_read | boost::filesystem::group_read | boost::filesystem::others_read); |
| 711 | boost::filesystem::permissions(cert_file, cert_perms, error); |
| 712 | if (error) |
| 713 | return error; |
| 714 | if (!PEM_write_X509(file.get(), ssl_cert)) |
| 715 | return boost::asio::error::ssl_errors(ERR_get_error()); |
| 716 | if (std::fclose(file.release()) != 0) |
| 717 | return {errno, boost::system::system_category()}; |
| 718 | return error; |
| 719 | } |
| 720 | |
| 721 | } // namespace |
| 722 | } // namespace |
| 723 | |
| 724 | #ifdef _WIN32 |
| 725 | |
| 726 | // https://stackoverflow.com/questions/40307541 |
| 727 | // Because Windows always has to do things wonkily |
| 728 | #include <wincrypt.h> |
| 729 | static void add_windows_root_certs(SSL_CTX *ctx) noexcept |
| 730 | { |
| 731 | HCERTSTORE hStore = CertOpenSystemStore(0, "ROOT"); |
| 732 | if (hStore == NULL) { |
| 733 | return; |
| 734 | } |
| 735 | |
| 736 | X509_STORE *store = X509_STORE_new(); |
| 737 | PCCERT_CONTEXT pContext = NULL; |
| 738 | while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != NULL) { |
| 739 | // convert from DER to internal format |
| 740 | X509 *x509 = d2i_X509(NULL, |
| 741 | (const unsigned char **)&pContext->pbCertEncoded, |
| 742 | pContext->cbCertEncoded); |
| 743 | if(x509 != NULL) { |
| 744 | X509_STORE_add_cert(store, x509); |
| 745 | X509_free(x509); |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | CertFreeCertificateContext(pContext); |
| 750 | CertCloseStore(hStore, 0); |
| 751 | |
| 752 | // attach X509_STORE to boost ssl context |
| 753 | SSL_CTX_set_cert_store(ctx, store); |
| 754 | } |
| 755 | #endif |
| 756 |