TLSv12.cpp 23 KB

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