TLSv12.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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::HANDSHAKE_FAILURE:
  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::INSUFFICIENT_SECURITY:
  125. dbgln("- No cipher suite in common with {} (the server is oh so secure)", m_context.extensions.SNI);
  126. break;
  127. case AlertDescription::PROTOCOL_VERSION:
  128. dbgln("- The server refused to negotiate with TLS 1.2 :(");
  129. break;
  130. case AlertDescription::UNEXPECTED_MESSAGE:
  131. dbgln("- We sent an invalid message for the state we're in.");
  132. break;
  133. case AlertDescription::BAD_RECORD_MAC:
  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::RECORD_OVERFLOW:
  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::DECOMPRESSION_FAILURE_RESERVED:
  145. dbgln("- We sent invalid input for decompression (e.g. data that would expand to excessive length)");
  146. break;
  147. case AlertDescription::ILLEGAL_PARAMETER:
  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::DECODE_ERROR:
  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::DECRYPT_ERROR:
  155. dbgln("- A handshake crypto operation failed. This includes signature verification and validating Finished.");
  156. break;
  157. case AlertDescription::ACCESS_DENIED:
  158. dbgln("- The certificate is valid, but once access control was applied, the sender decided to stop negotiation.");
  159. break;
  160. case AlertDescription::INTERNAL_ERROR:
  161. dbgln("- No one knows, but it isn't a protocol failure.");
  162. break;
  163. case AlertDescription::DECRYPTION_FAILED_RESERVED:
  164. case AlertDescription::NO_CERTIFICATE_RESERVED:
  165. case AlertDescription::EXPORT_RESTRICTION_RESERVED:
  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. dbgln("- {}", enum_to_value((AlertDescription)m_context.critical_error));
  173. }
  174. void TLSv12::set_root_certificates(Vector<Certificate> certificates)
  175. {
  176. if (!m_context.root_certificates.is_empty()) {
  177. dbgln("TLS warn: resetting root certificates!");
  178. m_context.root_certificates.clear();
  179. }
  180. for (auto& cert : certificates) {
  181. if (!cert.is_valid()) {
  182. dbgln("Certificate for {} by {} is invalid, things may or may not work!", cert.subject.common_name(), cert.issuer.common_name());
  183. }
  184. // FIXME: Figure out what we should do when our root certs are invalid.
  185. m_context.root_certificates.set(MUST(cert.subject.to_string()).to_deprecated_string(), cert);
  186. }
  187. dbgln_if(TLS_DEBUG, "{}: Set {} root certificates", this, m_context.root_certificates.size());
  188. }
  189. static bool wildcard_matches(StringView host, StringView subject)
  190. {
  191. if (host == subject)
  192. return true;
  193. if (subject.starts_with("*."sv)) {
  194. auto maybe_first_dot_index = host.find('.');
  195. if (maybe_first_dot_index.has_value()) {
  196. auto first_dot_index = maybe_first_dot_index.release_value();
  197. return wildcard_matches(host.substring_view(first_dot_index + 1), subject.substring_view(2));
  198. }
  199. }
  200. return false;
  201. }
  202. static bool certificate_subject_matches_host(Certificate& cert, StringView host)
  203. {
  204. if (wildcard_matches(host, cert.subject.common_name()))
  205. return true;
  206. for (auto& san : cert.SAN) {
  207. if (wildcard_matches(host, san))
  208. return true;
  209. }
  210. return false;
  211. }
  212. bool Context::verify_chain(StringView host) const
  213. {
  214. if (!options.validate_certificates)
  215. return true;
  216. Vector<Certificate> const* local_chain = nullptr;
  217. if (is_server) {
  218. dbgln("Unsupported: Server mode");
  219. TODO();
  220. } else {
  221. local_chain = &certificates;
  222. }
  223. if (local_chain->is_empty()) {
  224. dbgln("verify_chain: Attempting to verify an empty chain");
  225. return false;
  226. }
  227. // RFC5246 section 7.4.2: The sender's certificate MUST come first in the list. Each following certificate
  228. // MUST directly certify the one preceding it. Because certificate validation requires that root keys be
  229. // distributed independently, the self-signed certificate that specifies the root certificate authority MAY be
  230. // omitted from the chain, under the assumption that the remote end must already possess it in order to validate
  231. // it in any case.
  232. if (!host.is_empty()) {
  233. auto first_certificate = local_chain->first();
  234. auto subject_matches = certificate_subject_matches_host(first_certificate, host);
  235. if (!subject_matches) {
  236. dbgln("verify_chain: First certificate does not match the hostname");
  237. return false;
  238. }
  239. } else {
  240. // FIXME: The host is taken from m_context.extensions.SNI, when is this empty?
  241. dbgln("FIXME: verify_chain called without host");
  242. return false;
  243. }
  244. for (size_t cert_index = 0; cert_index < local_chain->size(); ++cert_index) {
  245. auto cert = local_chain->at(cert_index);
  246. auto subject_string = MUST(cert.subject.to_string());
  247. auto issuer_string = MUST(cert.issuer.to_string());
  248. if (!cert.is_valid()) {
  249. dbgln("verify_chain: Certificate is not valid {}", subject_string);
  250. return false;
  251. }
  252. auto maybe_root_certificate = root_certificates.get(issuer_string.to_deprecated_string());
  253. if (maybe_root_certificate.has_value()) {
  254. auto& root_certificate = *maybe_root_certificate;
  255. auto verification_correct = verify_certificate_pair(cert, root_certificate);
  256. if (!verification_correct) {
  257. dbgln("verify_chain: Signature inconsistent, {} was not signed by {} (root certificate)", subject_string, issuer_string);
  258. return false;
  259. }
  260. // Root certificate reached, and correctly verified, so we can stop now
  261. return true;
  262. }
  263. if (subject_string == issuer_string) {
  264. dbgln("verify_chain: Non-root self-signed certificate");
  265. return options.allow_self_signed_certificates;
  266. }
  267. if ((cert_index + 1) >= local_chain->size()) {
  268. dbgln("verify_chain: No trusted root certificate found before end of certificate chain");
  269. dbgln("verify_chain: Last certificate in chain was signed by {}", issuer_string);
  270. return false;
  271. }
  272. auto parent_certificate = local_chain->at(cert_index + 1);
  273. if (issuer_string != MUST(parent_certificate.subject.to_string())) {
  274. dbgln("verify_chain: Next certificate in the chain is not the issuer of this certificate");
  275. return false;
  276. }
  277. if (!(parent_certificate.is_allowed_to_sign_certificate && parent_certificate.is_certificate_authority)) {
  278. dbgln("verify_chain: {} is not marked as certificate authority", issuer_string);
  279. return false;
  280. }
  281. if (parent_certificate.path_length_constraint.has_value() && cert_index > parent_certificate.path_length_constraint.value()) {
  282. dbgln("verify_chain: Path length for certificate exceeded");
  283. return false;
  284. }
  285. bool verification_correct = verify_certificate_pair(cert, parent_certificate);
  286. if (!verification_correct) {
  287. dbgln("verify_chain: Signature inconsistent, {} was not signed by {}", subject_string, issuer_string);
  288. return false;
  289. }
  290. }
  291. // Either a root certificate is reached, or parent validation fails as the end of the local chain is reached
  292. VERIFY_NOT_REACHED();
  293. }
  294. bool Context::verify_certificate_pair(Certificate const& subject, Certificate const& issuer) const
  295. {
  296. Crypto::Hash::HashKind kind = Crypto::Hash::HashKind::Unknown;
  297. auto identifier = subject.signature_algorithm.identifier;
  298. if (identifier == rsa_encryption_oid)
  299. kind = Crypto::Hash::HashKind::None;
  300. if (identifier == rsa_md5_encryption_oid)
  301. kind = Crypto::Hash::HashKind::MD5;
  302. if (identifier == rsa_sha1_encryption_oid)
  303. kind = Crypto::Hash::HashKind::SHA1;
  304. if (identifier == rsa_sha256_encryption_oid)
  305. kind = Crypto::Hash::HashKind::SHA256;
  306. if (identifier == rsa_sha384_encryption_oid)
  307. kind = Crypto::Hash::HashKind::SHA384;
  308. if (identifier == rsa_sha512_encryption_oid)
  309. kind = Crypto::Hash::HashKind::SHA512;
  310. if (kind == Crypto::Hash::HashKind::Unknown) {
  311. dbgln("verify_certificate_pair: Unknown signature algorithm, expected RSA with SHA1/256/384/512, got OID {}", identifier);
  312. return false;
  313. }
  314. Crypto::PK::RSAPrivateKey dummy_private_key;
  315. Crypto::PK::RSAPublicKey public_key_copy { issuer.public_key.rsa };
  316. auto rsa = Crypto::PK::RSA(public_key_copy, dummy_private_key);
  317. auto verification_buffer_result = ByteBuffer::create_uninitialized(subject.signature_value.size());
  318. if (verification_buffer_result.is_error()) {
  319. dbgln("verify_certificate_pair: Unable to allocate buffer for verification");
  320. return false;
  321. }
  322. auto verification_buffer = verification_buffer_result.release_value();
  323. auto verification_buffer_bytes = verification_buffer.bytes();
  324. rsa.verify(subject.signature_value, verification_buffer_bytes);
  325. // FIXME: This slice is subject hack, this will work for most certificates, but you actually have to parse
  326. // the ASN.1 data to correctly extract the signed part of the certificate.
  327. ReadonlyBytes message = subject.original_asn1.bytes().slice(4, subject.original_asn1.size() - 4 - (5 + subject.signature_value.size()) - 15);
  328. auto pkcs1 = Crypto::PK::EMSA_PKCS1_V1_5<Crypto::Hash::Manager>(kind);
  329. auto verification = pkcs1.verify(message, verification_buffer_bytes, subject.signature_value.size() * 8);
  330. return verification == Crypto::VerificationConsistency::Consistent;
  331. }
  332. template<typename HMACType>
  333. static void hmac_pseudorandom_function(Bytes output, ReadonlyBytes secret, u8 const* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b)
  334. {
  335. if (!secret.size()) {
  336. dbgln("null secret");
  337. return;
  338. }
  339. auto append_label_seed = [&](auto& hmac) {
  340. hmac.update(label, label_length);
  341. hmac.update(seed);
  342. if (seed_b.size() > 0)
  343. hmac.update(seed_b);
  344. };
  345. HMACType hmac(secret);
  346. append_label_seed(hmac);
  347. constexpr auto digest_size = hmac.digest_size();
  348. u8 digest[digest_size];
  349. auto digest_0 = Bytes { digest, digest_size };
  350. digest_0.overwrite(0, hmac.digest().immutable_data(), digest_size);
  351. size_t index = 0;
  352. while (index < output.size()) {
  353. hmac.update(digest_0);
  354. append_label_seed(hmac);
  355. auto digest_1 = hmac.digest();
  356. auto copy_size = min(digest_size, output.size() - index);
  357. output.overwrite(index, digest_1.immutable_data(), copy_size);
  358. index += copy_size;
  359. digest_0.overwrite(0, hmac.process(digest_0).immutable_data(), digest_size);
  360. }
  361. }
  362. void TLSv12::pseudorandom_function(Bytes output, ReadonlyBytes secret, u8 const* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b)
  363. {
  364. // Simplification: We only support the HMAC PRF with the hash function SHA-256 or stronger.
  365. // RFC 5246: "In this section, we define one PRF, based on HMAC. This PRF with the
  366. // SHA-256 hash function is used for all cipher suites defined in this
  367. // document and in TLS documents published prior to this document when
  368. // TLS 1.2 is negotiated. New cipher suites MUST explicitly specify a
  369. // PRF and, in general, SHOULD use the TLS PRF with SHA-256 or a
  370. // stronger standard hash function."
  371. switch (hmac_hash()) {
  372. case Crypto::Hash::HashKind::SHA512:
  373. hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA512>>(output, secret, label, label_length, seed, seed_b);
  374. break;
  375. case Crypto::Hash::HashKind::SHA384:
  376. hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA384>>(output, secret, label, label_length, seed, seed_b);
  377. break;
  378. case Crypto::Hash::HashKind::SHA256:
  379. hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA256>>(output, secret, label, label_length, seed, seed_b);
  380. break;
  381. default:
  382. dbgln("Failed to find a suitable HMAC hash");
  383. VERIFY_NOT_REACHED();
  384. break;
  385. }
  386. }
  387. TLSv12::TLSv12(StreamVariantType stream, Options options)
  388. : m_stream(move(stream))
  389. {
  390. m_context.options = move(options);
  391. m_context.is_server = false;
  392. m_context.tls_buffer = {};
  393. set_root_certificates(m_context.options.root_certificates.has_value()
  394. ? *m_context.options.root_certificates
  395. : DefaultRootCACertificates::the().certificates());
  396. setup_connection();
  397. }
  398. Vector<Certificate> TLSv12::parse_pem_certificate(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes rsa_key) // FIXME: This should not be bound to RSA
  399. {
  400. if (certificate_pem_buffer.is_empty() || rsa_key.is_empty()) {
  401. return {};
  402. }
  403. auto decoded_certificate = Crypto::decode_pem(certificate_pem_buffer);
  404. if (decoded_certificate.is_empty()) {
  405. dbgln("Certificate not PEM");
  406. return {};
  407. }
  408. auto maybe_certificate = Certificate::parse_certificate(decoded_certificate);
  409. if (!maybe_certificate.is_error()) {
  410. dbgln("Invalid certificate");
  411. return {};
  412. }
  413. Crypto::PK::RSA rsa(rsa_key);
  414. auto certificate = maybe_certificate.release_value();
  415. certificate.private_key = rsa.private_key();
  416. return { move(certificate) };
  417. }
  418. Singleton<DefaultRootCACertificates> DefaultRootCACertificates::s_the;
  419. DefaultRootCACertificates::DefaultRootCACertificates()
  420. {
  421. auto load_result = load_certificates();
  422. if (load_result.is_error()) {
  423. dbgln("Failed to load CA Certificates: {}", load_result.error());
  424. return;
  425. }
  426. m_ca_certificates = load_result.release_value();
  427. }
  428. ErrorOr<Vector<Certificate>> DefaultRootCACertificates::load_certificates()
  429. {
  430. auto cacert_file = TRY(Core::File::open("/etc/cacert.pem"sv, Core::File::OpenMode::Read));
  431. auto data = TRY(cacert_file->read_until_eof());
  432. auto user_cert_path = TRY(String::formatted("{}/.config/certs.pem", Core::StandardPaths::home_directory()));
  433. if (FileSystem::exists(user_cert_path)) {
  434. auto user_cert_file = TRY(Core::File::open(user_cert_path, Core::File::OpenMode::Read));
  435. TRY(data.try_append(TRY(user_cert_file->read_until_eof())));
  436. }
  437. return TRY(parse_pem_root_certificate_authorities(data));
  438. }
  439. ErrorOr<Vector<Certificate>> DefaultRootCACertificates::parse_pem_root_certificate_authorities(ByteBuffer& data)
  440. {
  441. Vector<Certificate> certificates;
  442. auto certs = TRY(Crypto::decode_pems(data));
  443. for (auto& cert : certs) {
  444. auto certificate_result = Certificate::parse_certificate(cert.bytes());
  445. if (certificate_result.is_error()) {
  446. // FIXME: It would be nice to have more informations about the certificate we failed to parse.
  447. // Like: Issuer, Algorithm, CN, etc
  448. dbgln("Failed to load certificate: {}", certificate_result.error());
  449. continue;
  450. }
  451. auto certificate = certificate_result.release_value();
  452. if (certificate.is_certificate_authority && certificate.is_self_signed()) {
  453. TRY(certificates.try_append(move(certificate)));
  454. } else {
  455. dbgln("Skipped '{}' because it is not a valid root CA", TRY(certificate.subject.to_string()));
  456. }
  457. }
  458. dbgln("Loaded {} of {} ({:.2}%) provided CA Certificates", certificates.size(), certs.size(), (certificates.size() * 100.0) / certs.size());
  459. return certificates;
  460. }
  461. }