TLSv12.cpp 23 KB

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