TLSv12.cpp 23 KB

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