Serenity Operating System
at master 507 lines 20 kB view raw
1/* 2 * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/Base64.h> 8#include <AK/Debug.h> 9#include <AK/Endian.h> 10#include <LibCore/ConfigFile.h> 11#include <LibCore/DateTime.h> 12#include <LibCore/Timer.h> 13#include <LibCrypto/ASN1/ASN1.h> 14#include <LibCrypto/ASN1/PEM.h> 15#include <LibCrypto/PK/Code/EMSA_PKCS1_V1_5.h> 16#include <LibCrypto/PK/Code/EMSA_PSS.h> 17#include <LibTLS/TLSv12.h> 18#include <errno.h> 19 20#ifndef SOCK_NONBLOCK 21# include <sys/ioctl.h> 22#endif 23 24namespace TLS { 25 26void TLSv12::consume(ReadonlyBytes record) 27{ 28 if (m_context.critical_error) { 29 dbgln("There has been a critical error ({}), refusing to continue", (i8)m_context.critical_error); 30 return; 31 } 32 33 if (record.size() == 0) { 34 return; 35 } 36 37 dbgln_if(TLS_DEBUG, "Consuming {} bytes", record.size()); 38 39 if (m_context.message_buffer.try_append(record).is_error()) { 40 dbgln("Not enough space in message buffer, dropping the record"); 41 return; 42 } 43 44 size_t index { 0 }; 45 size_t buffer_length = m_context.message_buffer.size(); 46 47 size_t size_offset { 3 }; // read the common record header 48 size_t header_size { 5 }; 49 50 dbgln_if(TLS_DEBUG, "message buffer length {}", buffer_length); 51 52 while (buffer_length >= 5) { 53 auto length = AK::convert_between_host_and_network_endian(ByteReader::load16(m_context.message_buffer.offset_pointer(index + size_offset))) + header_size; 54 if (length > buffer_length) { 55 dbgln_if(TLS_DEBUG, "Need more data: {} > {}", length, buffer_length); 56 break; 57 } 58 auto consumed = handle_message(m_context.message_buffer.bytes().slice(index, length)); 59 60 if constexpr (TLS_DEBUG) { 61 if (consumed > 0) 62 dbgln("consumed {} bytes", consumed); 63 else 64 dbgln("error: {}", consumed); 65 } 66 67 if (consumed != (i8)Error::NeedMoreData) { 68 if (consumed < 0) { 69 dbgln("Consumed an error: {}", consumed); 70 if (!m_context.critical_error) 71 m_context.critical_error = (i8)consumed; 72 m_context.error_code = (Error)consumed; 73 break; 74 } 75 } else { 76 continue; 77 } 78 79 index += length; 80 buffer_length -= length; 81 if (m_context.critical_error) { 82 dbgln("Broken connection"); 83 m_context.error_code = Error::BrokenConnection; 84 break; 85 } 86 } 87 if (m_context.error_code != Error::NoError && m_context.error_code != Error::NeedMoreData) { 88 dbgln("consume error: {}", (i8)m_context.error_code); 89 m_context.message_buffer.clear(); 90 return; 91 } 92 93 if (index) { 94 // FIXME: Propagate errors. 95 m_context.message_buffer = MUST(m_context.message_buffer.slice(index, m_context.message_buffer.size() - index)); 96 } 97} 98 99bool Certificate::is_valid() const 100{ 101 auto now = Core::DateTime::now(); 102 103 if (now < not_before) { 104 dbgln("certificate expired (not yet valid, signed for {})", not_before.to_deprecated_string()); 105 return false; 106 } 107 108 if (not_after < now) { 109 dbgln("certificate expired (expiry date {})", not_after.to_deprecated_string()); 110 return false; 111 } 112 113 return true; 114} 115 116void TLSv12::try_disambiguate_error() const 117{ 118 dbgln("Possible failure cause(s): "); 119 switch ((AlertDescription)m_context.critical_error) { 120 case AlertDescription::HandshakeFailure: 121 if (!m_context.cipher_spec_set) { 122 dbgln("- No cipher suite in common with {}", m_context.extensions.SNI); 123 } else { 124 dbgln("- Unknown internal issue"); 125 } 126 break; 127 case AlertDescription::InsufficientSecurity: 128 dbgln("- No cipher suite in common with {} (the server is oh so secure)", m_context.extensions.SNI); 129 break; 130 case AlertDescription::ProtocolVersion: 131 dbgln("- The server refused to negotiate with TLS 1.2 :("); 132 break; 133 case AlertDescription::UnexpectedMessage: 134 dbgln("- We sent an invalid message for the state we're in."); 135 break; 136 case AlertDescription::BadRecordMAC: 137 dbgln("- Bad MAC record from our side."); 138 dbgln("- Ciphertext wasn't an even multiple of the block length."); 139 dbgln("- Bad block cipher padding."); 140 dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network."); 141 break; 142 case AlertDescription::RecordOverflow: 143 dbgln("- Sent a ciphertext record which has a length bigger than 18432 bytes."); 144 dbgln("- Sent record decrypted to a compressed record that has a length bigger than 18432 bytes."); 145 dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network."); 146 break; 147 case AlertDescription::DecompressionFailure: 148 dbgln("- We sent invalid input for decompression (e.g. data that would expand to excessive length)"); 149 break; 150 case AlertDescription::IllegalParameter: 151 dbgln("- We sent a parameter in the handshake that is out of range or inconsistent with the other parameters."); 152 break; 153 case AlertDescription::DecodeError: 154 dbgln("- The message we sent cannot be decoded because a field was out of range or the length was incorrect."); 155 dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network."); 156 break; 157 case AlertDescription::DecryptError: 158 dbgln("- A handshake crypto operation failed. This includes signature verification and validating Finished."); 159 break; 160 case AlertDescription::AccessDenied: 161 dbgln("- The certificate is valid, but once access control was applied, the sender decided to stop negotiation."); 162 break; 163 case AlertDescription::InternalError: 164 dbgln("- No one knows, but it isn't a protocol failure."); 165 break; 166 case AlertDescription::DecryptionFailed: 167 case AlertDescription::NoCertificate: 168 case AlertDescription::ExportRestriction: 169 dbgln("- No one knows, the server sent a non-compliant alert."); 170 break; 171 default: 172 dbgln("- No one knows."); 173 break; 174 } 175} 176 177void TLSv12::set_root_certificates(Vector<Certificate> certificates) 178{ 179 if (!m_context.root_certificates.is_empty()) { 180 dbgln("TLS warn: resetting root certificates!"); 181 m_context.root_certificates.clear(); 182 } 183 184 for (auto& cert : certificates) { 185 if (!cert.is_valid()) 186 dbgln("Certificate for {} by {} is invalid, things may or may not work!", cert.subject.subject, cert.issuer.subject); 187 // FIXME: Figure out what we should do when our root certs are invalid. 188 189 m_context.root_certificates.set(cert.subject_identifier_string(), cert); 190 } 191 dbgln_if(TLS_DEBUG, "{}: Set {} root certificates", this, m_context.root_certificates.size()); 192} 193 194static bool wildcard_matches(StringView host, StringView subject) 195{ 196 if (host == subject) 197 return true; 198 199 if (subject.starts_with("*."sv)) { 200 auto maybe_first_dot_index = host.find('.'); 201 if (maybe_first_dot_index.has_value()) { 202 auto first_dot_index = maybe_first_dot_index.release_value(); 203 return wildcard_matches(host.substring_view(first_dot_index + 1), subject.substring_view(2)); 204 } 205 } 206 207 return false; 208} 209 210static bool certificate_subject_matches_host(Certificate& cert, StringView host) 211{ 212 if (wildcard_matches(host, cert.subject.subject)) 213 return true; 214 215 for (auto& san : cert.SAN) { 216 if (wildcard_matches(host, san)) 217 return true; 218 } 219 220 return false; 221} 222 223bool Context::verify_chain(StringView host) const 224{ 225 if (!options.validate_certificates) 226 return true; 227 228 Vector<Certificate> const* local_chain = nullptr; 229 if (is_server) { 230 dbgln("Unsupported: Server mode"); 231 TODO(); 232 } else { 233 local_chain = &certificates; 234 } 235 236 if (local_chain->is_empty()) { 237 dbgln("verify_chain: Attempting to verify an empty chain"); 238 return false; 239 } 240 241 // RFC5246 section 7.4.2: The sender's certificate MUST come first in the list. Each following certificate 242 // MUST directly certify the one preceding it. Because certificate validation requires that root keys be 243 // distributed independently, the self-signed certificate that specifies the root certificate authority MAY be 244 // omitted from the chain, under the assumption that the remote end must already possess it in order to validate 245 // it in any case. 246 247 if (!host.is_empty()) { 248 auto first_certificate = local_chain->first(); 249 auto subject_matches = certificate_subject_matches_host(first_certificate, host); 250 if (!subject_matches) { 251 dbgln("verify_chain: First certificate does not match the hostname"); 252 return false; 253 } 254 } else { 255 // FIXME: The host is taken from m_context.extensions.SNI, when is this empty? 256 dbgln("FIXME: verify_chain called without host"); 257 return false; 258 } 259 260 for (size_t cert_index = 0; cert_index < local_chain->size(); ++cert_index) { 261 auto cert = local_chain->at(cert_index); 262 263 auto subject_string = cert.subject_identifier_string(); 264 auto issuer_string = cert.issuer_identifier_string(); 265 266 if (!cert.is_valid()) { 267 dbgln("verify_chain: Certificate is not valid {}", subject_string); 268 return false; 269 } 270 271 auto maybe_root_certificate = root_certificates.get(issuer_string); 272 if (maybe_root_certificate.has_value()) { 273 auto& root_certificate = *maybe_root_certificate; 274 auto verification_correct = verify_certificate_pair(cert, root_certificate); 275 276 if (!verification_correct) { 277 dbgln("verify_chain: Signature inconsistent, {} was not signed by {} (root certificate)", subject_string, issuer_string); 278 return false; 279 } 280 281 // Root certificate reached, and correctly verified, so we can stop now 282 return true; 283 } 284 285 if (subject_string == issuer_string) { 286 dbgln("verify_chain: Non-root self-signed certificate"); 287 return options.allow_self_signed_certificates; 288 } 289 if ((cert_index + 1) >= local_chain->size()) { 290 dbgln("verify_chain: No trusted root certificate found before end of certificate chain"); 291 dbgln("verify_chain: Last certificate in chain was signed by {}", issuer_string); 292 return false; 293 } 294 295 auto parent_certificate = local_chain->at(cert_index + 1); 296 if (issuer_string != parent_certificate.subject_identifier_string()) { 297 dbgln("verify_chain: Next certificate in the chain is not the issuer of this certificate"); 298 return false; 299 } 300 301 if (!(parent_certificate.is_allowed_to_sign_certificate && parent_certificate.is_certificate_authority)) { 302 dbgln("verify_chain: {} is not marked as certificate authority", issuer_string); 303 return false; 304 } 305 if (parent_certificate.path_length_constraint.has_value() && cert_index > parent_certificate.path_length_constraint.value()) { 306 dbgln("verify_chain: Path length for certificate exceeded"); 307 return false; 308 } 309 310 bool verification_correct = verify_certificate_pair(cert, parent_certificate); 311 if (!verification_correct) { 312 dbgln("verify_chain: Signature inconsistent, {} was not signed by {}", subject_string, issuer_string); 313 return false; 314 } 315 } 316 317 // Either a root certificate is reached, or parent validation fails as the end of the local chain is reached 318 VERIFY_NOT_REACHED(); 319} 320 321bool Context::verify_certificate_pair(Certificate const& subject, Certificate const& issuer) const 322{ 323 Crypto::Hash::HashKind kind; 324 switch (subject.signature_algorithm) { 325 case CertificateKeyAlgorithm::RSA_SHA1: 326 kind = Crypto::Hash::HashKind::SHA1; 327 break; 328 case CertificateKeyAlgorithm::RSA_SHA256: 329 kind = Crypto::Hash::HashKind::SHA256; 330 break; 331 case CertificateKeyAlgorithm::RSA_SHA384: 332 kind = Crypto::Hash::HashKind::SHA384; 333 break; 334 case CertificateKeyAlgorithm::RSA_SHA512: 335 kind = Crypto::Hash::HashKind::SHA512; 336 break; 337 default: 338 dbgln("verify_certificate_pair: Unknown signature algorithm, expected RSA with SHA1/256/384/512, got {}", (u8)subject.signature_algorithm); 339 return false; 340 } 341 342 Crypto::PK::RSAPrivateKey dummy_private_key; 343 Crypto::PK::RSAPublicKey public_key_copy { issuer.public_key }; 344 auto rsa = Crypto::PK::RSA(public_key_copy, dummy_private_key); 345 auto verification_buffer_result = ByteBuffer::create_uninitialized(subject.signature_value.size()); 346 if (verification_buffer_result.is_error()) { 347 dbgln("verify_certificate_pair: Unable to allocate buffer for verification"); 348 return false; 349 } 350 auto verification_buffer = verification_buffer_result.release_value(); 351 auto verification_buffer_bytes = verification_buffer.bytes(); 352 rsa.verify(subject.signature_value, verification_buffer_bytes); 353 354 // FIXME: This slice is subject hack, this will work for most certificates, but you actually have to parse 355 // the ASN.1 data to correctly extract the signed part of the certificate. 356 ReadonlyBytes message = subject.original_asn1.bytes().slice(4, subject.original_asn1.size() - 4 - (5 + subject.signature_value.size()) - 15); 357 auto pkcs1 = Crypto::PK::EMSA_PKCS1_V1_5<Crypto::Hash::Manager>(kind); 358 auto verification = pkcs1.verify(message, verification_buffer_bytes, subject.signature_value.size() * 8); 359 return verification == Crypto::VerificationConsistency::Consistent; 360} 361 362template<typename HMACType> 363static void hmac_pseudorandom_function(Bytes output, ReadonlyBytes secret, u8 const* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b) 364{ 365 if (!secret.size()) { 366 dbgln("null secret"); 367 return; 368 } 369 370 auto append_label_seed = [&](auto& hmac) { 371 hmac.update(label, label_length); 372 hmac.update(seed); 373 if (seed_b.size() > 0) 374 hmac.update(seed_b); 375 }; 376 377 HMACType hmac(secret); 378 append_label_seed(hmac); 379 380 constexpr auto digest_size = hmac.digest_size(); 381 u8 digest[digest_size]; 382 auto digest_0 = Bytes { digest, digest_size }; 383 384 digest_0.overwrite(0, hmac.digest().immutable_data(), digest_size); 385 386 size_t index = 0; 387 while (index < output.size()) { 388 hmac.update(digest_0); 389 append_label_seed(hmac); 390 auto digest_1 = hmac.digest(); 391 392 auto copy_size = min(digest_size, output.size() - index); 393 394 output.overwrite(index, digest_1.immutable_data(), copy_size); 395 index += copy_size; 396 397 digest_0.overwrite(0, hmac.process(digest_0).immutable_data(), digest_size); 398 } 399} 400 401void TLSv12::pseudorandom_function(Bytes output, ReadonlyBytes secret, u8 const* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b) 402{ 403 // Simplification: We only support the HMAC PRF with the hash function SHA-256 or stronger. 404 405 // RFC 5246: "In this section, we define one PRF, based on HMAC. This PRF with the 406 // SHA-256 hash function is used for all cipher suites defined in this 407 // document and in TLS documents published prior to this document when 408 // TLS 1.2 is negotiated. New cipher suites MUST explicitly specify a 409 // PRF and, in general, SHOULD use the TLS PRF with SHA-256 or a 410 // stronger standard hash function." 411 412 switch (hmac_hash()) { 413 case Crypto::Hash::HashKind::SHA512: 414 hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA512>>(output, secret, label, label_length, seed, seed_b); 415 break; 416 case Crypto::Hash::HashKind::SHA384: 417 hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA384>>(output, secret, label, label_length, seed, seed_b); 418 break; 419 case Crypto::Hash::HashKind::SHA256: 420 hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA256>>(output, secret, label, label_length, seed, seed_b); 421 break; 422 default: 423 dbgln("Failed to find a suitable HMAC hash"); 424 VERIFY_NOT_REACHED(); 425 break; 426 } 427} 428 429TLSv12::TLSv12(StreamVariantType stream, Options options) 430 : m_stream(move(stream)) 431{ 432 m_context.options = move(options); 433 m_context.is_server = false; 434 m_context.tls_buffer = {}; 435 436 set_root_certificates(m_context.options.root_certificates.has_value() 437 ? *m_context.options.root_certificates 438 : DefaultRootCACertificates::the().certificates()); 439 440 setup_connection(); 441} 442 443Vector<Certificate> TLSv12::parse_pem_certificate(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes rsa_key) // FIXME: This should not be bound to RSA 444{ 445 if (certificate_pem_buffer.is_empty() || rsa_key.is_empty()) { 446 return {}; 447 } 448 449 auto decoded_certificate = Crypto::decode_pem(certificate_pem_buffer); 450 if (decoded_certificate.is_empty()) { 451 dbgln("Certificate not PEM"); 452 return {}; 453 } 454 455 auto maybe_certificate = Certificate::parse_asn1(decoded_certificate); 456 if (!maybe_certificate.has_value()) { 457 dbgln("Invalid certificate"); 458 return {}; 459 } 460 461 Crypto::PK::RSA rsa(rsa_key); 462 auto certificate = maybe_certificate.release_value(); 463 certificate.private_key = rsa.private_key(); 464 465 return { move(certificate) }; 466} 467 468Singleton<DefaultRootCACertificates> DefaultRootCACertificates::s_the; 469DefaultRootCACertificates::DefaultRootCACertificates() 470{ 471 // FIXME: This might not be the best format, find a better way to represent CA certificates. 472 auto config_result = Core::ConfigFile::open_for_system("ca_certs"); 473 if (config_result.is_error()) { 474 dbgln("Failed to load CA Certificates: {}", config_result.error()); 475 return; 476 } 477 auto config = config_result.release_value(); 478 reload_certificates(config); 479} 480 481void DefaultRootCACertificates::reload_certificates(Core::ConfigFile& config) 482{ 483 m_ca_certificates.clear(); 484 for (auto& entity : config.groups()) { 485 for (auto& subject : config.keys(entity)) { 486 auto certificate_base64 = config.read_entry(entity, subject); 487 auto certificate_data_result = decode_base64(certificate_base64); 488 if (certificate_data_result.is_error()) { 489 dbgln("Skipping CA Certificate {} {}: out of memory", entity, subject); 490 continue; 491 } 492 auto certificate_data = certificate_data_result.release_value(); 493 auto certificate_result = Certificate::parse_asn1(certificate_data.bytes()); 494 // If the certificate does not parse it is likely using elliptic curve keys/signatures, which are not 495 // supported right now. Currently, ca_certs.ini should only contain certificates with RSA keys/signatures. 496 if (!certificate_result.has_value()) { 497 dbgln("Skipping CA Certificate {} {}: unable to parse", entity, subject); 498 continue; 499 } 500 auto certificate = certificate_result.release_value(); 501 m_ca_certificates.append(move(certificate)); 502 } 503 } 504 505 dbgln("Loaded {} CA Certificates", m_ca_certificates.size()); 506} 507}