TLSv12.cpp 13 KB

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