TLSv12.cpp 13 KB

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