TLSv12.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Endian.h>
  8. #include <LibCore/ConfigFile.h>
  9. #include <LibCore/DateTime.h>
  10. #include <LibCore/File.h>
  11. #include <LibCore/Timer.h>
  12. #include <LibCrypto/ASN1/ASN1.h>
  13. #include <LibCrypto/ASN1/PEM.h>
  14. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  15. #include <LibTLS/TLSv12.h>
  16. #include <errno.h>
  17. #ifndef SOCK_NONBLOCK
  18. # include <sys/ioctl.h>
  19. #endif
  20. namespace TLS {
  21. void TLSv12::consume(ReadonlyBytes record)
  22. {
  23. if (m_context.critical_error) {
  24. dbgln("There has been a critical error ({}), refusing to continue", (i8)m_context.critical_error);
  25. return;
  26. }
  27. if (record.size() == 0) {
  28. return;
  29. }
  30. dbgln_if(TLS_DEBUG, "Consuming {} bytes", record.size());
  31. if (!m_context.message_buffer.try_append(record)) {
  32. dbgln("Not enough space in message buffer, dropping the record");
  33. return;
  34. }
  35. size_t index { 0 };
  36. size_t buffer_length = m_context.message_buffer.size();
  37. size_t size_offset { 3 }; // read the common record header
  38. size_t header_size { 5 };
  39. dbgln_if(TLS_DEBUG, "message buffer length {}", buffer_length);
  40. while (buffer_length >= 5) {
  41. auto length = AK::convert_between_host_and_network_endian(ByteReader::load16(m_context.message_buffer.offset_pointer(index + size_offset))) + header_size;
  42. if (length > buffer_length) {
  43. dbgln_if(TLS_DEBUG, "Need more data: {} > {}", length, buffer_length);
  44. break;
  45. }
  46. auto consumed = handle_message(m_context.message_buffer.bytes().slice(index, length));
  47. if constexpr (TLS_DEBUG) {
  48. if (consumed > 0)
  49. dbgln("consumed {} bytes", consumed);
  50. else
  51. dbgln("error: {}", consumed);
  52. }
  53. if (consumed != (i8)Error::NeedMoreData) {
  54. if (consumed < 0) {
  55. dbgln("Consumed an error: {}", consumed);
  56. if (!m_context.critical_error)
  57. m_context.critical_error = (i8)consumed;
  58. m_context.error_code = (Error)consumed;
  59. break;
  60. }
  61. } else {
  62. continue;
  63. }
  64. index += length;
  65. buffer_length -= length;
  66. if (m_context.critical_error) {
  67. dbgln("Broken connection");
  68. m_context.error_code = Error::BrokenConnection;
  69. break;
  70. }
  71. }
  72. if (m_context.error_code != Error::NoError && m_context.error_code != Error::NeedMoreData) {
  73. dbgln("consume error: {}", (i8)m_context.error_code);
  74. m_context.message_buffer.clear();
  75. return;
  76. }
  77. if (index) {
  78. m_context.message_buffer = m_context.message_buffer.slice(index, m_context.message_buffer.size() - index);
  79. }
  80. }
  81. bool Certificate::is_valid() const
  82. {
  83. auto now = Core::DateTime::now();
  84. if (now < not_before) {
  85. dbgln("certificate expired (not yet valid, signed for {})", not_before.to_string());
  86. return false;
  87. }
  88. if (not_after < now) {
  89. dbgln("certificate expired (expiry date {})", not_after.to_string());
  90. return false;
  91. }
  92. return true;
  93. }
  94. void TLSv12::try_disambiguate_error() const
  95. {
  96. dbgln("Possible failure cause(s): ");
  97. switch ((AlertDescription)m_context.critical_error) {
  98. case AlertDescription::HandshakeFailure:
  99. if (!m_context.cipher_spec_set) {
  100. dbgln("- No cipher suite in common with {}", m_context.extensions.SNI);
  101. } else {
  102. dbgln("- Unknown internal issue");
  103. }
  104. break;
  105. case AlertDescription::InsufficientSecurity:
  106. dbgln("- No cipher suite in common with {} (the server is oh so secure)", m_context.extensions.SNI);
  107. break;
  108. case AlertDescription::ProtocolVersion:
  109. dbgln("- The server refused to negotiate with TLS 1.2 :(");
  110. break;
  111. case AlertDescription::UnexpectedMessage:
  112. dbgln("- We sent an invalid message for the state we're in.");
  113. break;
  114. case AlertDescription::BadRecordMAC:
  115. dbgln("- Bad MAC record from our side.");
  116. dbgln("- Ciphertext wasn't an even multiple of the block length.");
  117. dbgln("- Bad block cipher padding.");
  118. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  119. break;
  120. case AlertDescription::RecordOverflow:
  121. dbgln("- Sent a ciphertext record which has a length bigger than 18432 bytes.");
  122. dbgln("- Sent record decrypted to a compressed record that has a length bigger than 18432 bytes.");
  123. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  124. break;
  125. case AlertDescription::DecompressionFailure:
  126. dbgln("- We sent invalid input for decompression (e.g. data that would expand to excessive length)");
  127. break;
  128. case AlertDescription::IllegalParameter:
  129. dbgln("- We sent a parameter in the handshake that is out of range or inconsistent with the other parameters.");
  130. break;
  131. case AlertDescription::DecodeError:
  132. dbgln("- The message we sent cannot be decoded because a field was out of range or the length was incorrect.");
  133. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  134. break;
  135. case AlertDescription::DecryptError:
  136. dbgln("- A handshake crypto operation failed. This includes signature verification and validating Finished.");
  137. break;
  138. case AlertDescription::AccessDenied:
  139. dbgln("- The certificate is valid, but once access control was applied, the sender decided to stop negotiation.");
  140. break;
  141. case AlertDescription::InternalError:
  142. dbgln("- No one knows, but it isn't a protocol failure.");
  143. break;
  144. case AlertDescription::DecryptionFailed:
  145. case AlertDescription::NoCertificate:
  146. case AlertDescription::ExportRestriction:
  147. dbgln("- No one knows, the server sent a non-compliant alert.");
  148. break;
  149. default:
  150. dbgln("- No one knows.");
  151. break;
  152. }
  153. }
  154. void TLSv12::set_root_certificates(Vector<Certificate> certificates)
  155. {
  156. if (!m_context.root_ceritificates.is_empty())
  157. dbgln("TLS warn: resetting root certificates!");
  158. for (auto& cert : certificates) {
  159. if (!cert.is_valid())
  160. dbgln("Certificate for {} by {} is invalid, things may or may not work!", cert.subject.subject, cert.issuer.subject);
  161. // FIXME: Figure out what we should do when our root certs are invalid.
  162. }
  163. m_context.root_ceritificates = move(certificates);
  164. }
  165. bool Context::verify_chain() const
  166. {
  167. if (!options.validate_certificates)
  168. return true;
  169. const Vector<Certificate>* local_chain = nullptr;
  170. if (is_server) {
  171. dbgln("Unsupported: Server mode");
  172. TODO();
  173. } else {
  174. local_chain = &certificates;
  175. }
  176. // FIXME: Actually verify the signature, instead of just checking the name.
  177. HashMap<String, String> chain;
  178. HashTable<String> roots;
  179. // First, walk the root certs.
  180. for (auto& cert : root_ceritificates) {
  181. roots.set(cert.subject.subject);
  182. chain.set(cert.subject.subject, cert.issuer.subject);
  183. }
  184. // Then, walk the local certs.
  185. for (auto& cert : *local_chain) {
  186. auto& issuer_unique_name = cert.issuer.unit.is_empty() ? cert.issuer.subject : cert.issuer.unit;
  187. chain.set(cert.subject.subject, issuer_unique_name);
  188. }
  189. // Then verify the chain.
  190. for (auto& it : chain) {
  191. if (it.key == it.value) { // Allow self-signed certificates.
  192. if (!roots.contains(it.key))
  193. dbgln("Self-signed warning: Certificate for {} is self-signed", it.key);
  194. continue;
  195. }
  196. auto ref = chain.get(it.value);
  197. if (!ref.has_value()) {
  198. dbgln("Certificate for {} is not signed by anyone we trust ({})", it.key, it.value);
  199. return false;
  200. }
  201. if (ref.value() == it.key) // Allow (but warn about) mutually recursively signed cert A <-> B.
  202. dbgln("Co-dependency warning: Certificate for {} is issued by {}, which itself is issued by {}", ref.value(), it.key, ref.value());
  203. }
  204. return true;
  205. }
  206. template<typename HMACType>
  207. static void hmac_pseudorandom_function(Bytes output, ReadonlyBytes secret, const u8* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b)
  208. {
  209. if (!secret.size()) {
  210. dbgln("null secret");
  211. return;
  212. }
  213. auto append_label_seed = [&](auto& hmac) {
  214. hmac.update(label, label_length);
  215. hmac.update(seed);
  216. if (seed_b.size() > 0)
  217. hmac.update(seed_b);
  218. };
  219. HMACType hmac(secret);
  220. append_label_seed(hmac);
  221. constexpr auto digest_size = hmac.digest_size();
  222. u8 digest[digest_size];
  223. auto digest_0 = Bytes { digest, digest_size };
  224. digest_0.overwrite(0, hmac.digest().immutable_data(), digest_size);
  225. size_t index = 0;
  226. while (index < output.size()) {
  227. hmac.update(digest_0);
  228. append_label_seed(hmac);
  229. auto digest_1 = hmac.digest();
  230. auto copy_size = min(digest_size, output.size() - index);
  231. output.overwrite(index, digest_1.immutable_data(), copy_size);
  232. index += copy_size;
  233. digest_0.overwrite(0, hmac.process(digest_0).immutable_data(), digest_size);
  234. }
  235. }
  236. void TLSv12::pseudorandom_function(Bytes output, ReadonlyBytes secret, const u8* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b)
  237. {
  238. // Simplification: We only support the HMAC PRF with the hash function SHA-256 or stronger.
  239. // RFC 5246: "In this section, we define one PRF, based on HMAC. This PRF with the
  240. // SHA-256 hash function is used for all cipher suites defined in this
  241. // document and in TLS documents published prior to this document when
  242. // TLS 1.2 is negotiated. New cipher suites MUST explicitly specify a
  243. // PRF and, in general, SHOULD use the TLS PRF with SHA-256 or a
  244. // stronger standard hash function."
  245. switch (hmac_hash()) {
  246. case Crypto::Hash::HashKind::SHA512:
  247. hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA512>>(output, secret, label, label_length, seed, seed_b);
  248. break;
  249. case Crypto::Hash::HashKind::SHA384:
  250. hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA384>>(output, secret, label, label_length, seed, seed_b);
  251. break;
  252. case Crypto::Hash::HashKind::SHA256:
  253. hmac_pseudorandom_function<Crypto::Authentication::HMAC<Crypto::Hash::SHA256>>(output, secret, label, label_length, seed, seed_b);
  254. break;
  255. default:
  256. dbgln("Failed to find a suitable HMAC hash");
  257. VERIFY_NOT_REACHED();
  258. break;
  259. }
  260. }
  261. TLSv12::TLSv12(Core::Object* parent, Options options)
  262. : Core::Socket(Core::Socket::Type::TCP, parent)
  263. {
  264. m_context.options = move(options);
  265. m_context.is_server = false;
  266. m_context.tls_buffer = {};
  267. #ifdef SOCK_NONBLOCK
  268. int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  269. #else
  270. int fd = socket(AF_INET, SOCK_STREAM, 0);
  271. int option = 1;
  272. ioctl(fd, FIONBIO, &option);
  273. #endif
  274. if (fd < 0) {
  275. set_error(errno);
  276. } else {
  277. set_fd(fd);
  278. set_mode(Core::OpenMode::ReadWrite);
  279. set_error(0);
  280. }
  281. }
  282. bool TLSv12::add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes rsa_key) // FIXME: This should not be bound to RSA
  283. {
  284. if (certificate_pem_buffer.is_empty() || rsa_key.is_empty()) {
  285. return true;
  286. }
  287. auto decoded_certificate = Crypto::decode_pem(certificate_pem_buffer);
  288. if (decoded_certificate.is_empty()) {
  289. dbgln("Certificate not PEM");
  290. return false;
  291. }
  292. auto maybe_certificate = Certificate::parse_asn1(decoded_certificate);
  293. if (!maybe_certificate.has_value()) {
  294. dbgln("Invalid certificate");
  295. return false;
  296. }
  297. Crypto::PK::RSA rsa(rsa_key);
  298. auto certificate = maybe_certificate.value();
  299. certificate.private_key = rsa.private_key();
  300. return add_client_key(certificate);
  301. }
  302. Singleton<DefaultRootCACertificates> DefaultRootCACertificates::s_the;
  303. DefaultRootCACertificates::DefaultRootCACertificates()
  304. {
  305. // FIXME: This might not be the best format, find a better way to represent CA certificates.
  306. auto config = Core::ConfigFile::open_for_system("ca_certs");
  307. auto now = Core::DateTime::now();
  308. auto last_year = Core::DateTime::create(now.year() - 1);
  309. auto next_year = Core::DateTime::create(now.year() + 1);
  310. for (auto& entity : config->groups()) {
  311. Certificate cert;
  312. cert.subject.subject = entity;
  313. cert.issuer.subject = config->read_entry(entity, "issuer_subject", entity);
  314. cert.subject.country = config->read_entry(entity, "country");
  315. cert.not_before = Crypto::ASN1::parse_generalized_time(config->read_entry(entity, "not_before", "")).value_or(last_year);
  316. cert.not_after = Crypto::ASN1::parse_generalized_time(config->read_entry(entity, "not_after", "")).value_or(next_year);
  317. m_ca_certificates.append(move(cert));
  318. }
  319. }
  320. }