TLSv12.cpp 19 KB

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