TLSv12.cpp 20 KB

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