TLSv12.cpp 19 KB

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