HandshakeClient.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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/Random.h>
  8. #include <LibCrypto/ASN1/DER.h>
  9. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  10. #include <LibTLS/TLSv12.h>
  11. namespace TLS {
  12. bool TLSv12::expand_key()
  13. {
  14. u8 key[192]; // soooooooo many constants
  15. auto key_buffer = Bytes { key, sizeof(key) };
  16. auto is_aead = this->is_aead();
  17. if (m_context.master_key.size() == 0) {
  18. dbgln("expand_key() with empty master key");
  19. return false;
  20. }
  21. auto key_size = key_length();
  22. VERIFY(key_size);
  23. auto mac_size = mac_length();
  24. auto iv_size = iv_length();
  25. pseudorandom_function(
  26. key_buffer,
  27. m_context.master_key,
  28. (const u8*)"key expansion", 13,
  29. ReadonlyBytes { m_context.remote_random, sizeof(m_context.remote_random) },
  30. ReadonlyBytes { m_context.local_random, sizeof(m_context.local_random) });
  31. size_t offset = 0;
  32. if (is_aead) {
  33. iv_size = 4; // Explicit IV size.
  34. } else {
  35. memcpy(m_context.crypto.local_mac, key + offset, mac_size);
  36. offset += mac_size;
  37. memcpy(m_context.crypto.remote_mac, key + offset, mac_size);
  38. offset += mac_size;
  39. }
  40. auto client_key = key + offset;
  41. offset += key_size;
  42. auto server_key = key + offset;
  43. offset += key_size;
  44. auto client_iv = key + offset;
  45. offset += iv_size;
  46. auto server_iv = key + offset;
  47. offset += iv_size;
  48. if constexpr (TLS_DEBUG) {
  49. dbgln("client key");
  50. print_buffer(client_key, key_size);
  51. dbgln("server key");
  52. print_buffer(server_key, key_size);
  53. dbgln("client iv");
  54. print_buffer(client_iv, iv_size);
  55. dbgln("server iv");
  56. print_buffer(server_iv, iv_size);
  57. if (!is_aead) {
  58. dbgln("client mac key");
  59. print_buffer(m_context.crypto.local_mac, mac_size);
  60. dbgln("server mac key");
  61. print_buffer(m_context.crypto.remote_mac, mac_size);
  62. }
  63. }
  64. switch (get_cipher_algorithm(m_context.cipher)) {
  65. case CipherAlgorithm::AES_128_CBC:
  66. case CipherAlgorithm::AES_256_CBC: {
  67. VERIFY(!is_aead);
  68. memcpy(m_context.crypto.local_iv, client_iv, iv_size);
  69. memcpy(m_context.crypto.remote_iv, server_iv, iv_size);
  70. m_cipher_local = Crypto::Cipher::AESCipher::CBCMode(ReadonlyBytes { client_key, key_size }, key_size * 8, Crypto::Cipher::Intent::Encryption, Crypto::Cipher::PaddingMode::RFC5246);
  71. m_cipher_remote = Crypto::Cipher::AESCipher::CBCMode(ReadonlyBytes { server_key, key_size }, key_size * 8, Crypto::Cipher::Intent::Decryption, Crypto::Cipher::PaddingMode::RFC5246);
  72. break;
  73. }
  74. case CipherAlgorithm::AES_128_GCM:
  75. case CipherAlgorithm::AES_256_GCM: {
  76. VERIFY(is_aead);
  77. memcpy(m_context.crypto.local_aead_iv, client_iv, iv_size);
  78. memcpy(m_context.crypto.remote_aead_iv, server_iv, iv_size);
  79. m_cipher_local = Crypto::Cipher::AESCipher::GCMMode(ReadonlyBytes { client_key, key_size }, key_size * 8, Crypto::Cipher::Intent::Encryption, Crypto::Cipher::PaddingMode::RFC5246);
  80. m_cipher_remote = Crypto::Cipher::AESCipher::GCMMode(ReadonlyBytes { server_key, key_size }, key_size * 8, Crypto::Cipher::Intent::Decryption, Crypto::Cipher::PaddingMode::RFC5246);
  81. break;
  82. }
  83. case CipherAlgorithm::AES_128_CCM:
  84. dbgln("Requested unimplemented AES CCM cipher");
  85. TODO();
  86. case CipherAlgorithm::AES_128_CCM_8:
  87. dbgln("Requested unimplemented AES CCM-8 block cipher");
  88. TODO();
  89. default:
  90. dbgln("Requested unknown block cipher");
  91. VERIFY_NOT_REACHED();
  92. }
  93. m_context.crypto.created = 1;
  94. return true;
  95. }
  96. bool TLSv12::compute_master_secret_from_pre_master_secret(size_t length)
  97. {
  98. if (m_context.premaster_key.size() == 0 || length < 48) {
  99. dbgln("there's no way I can make a master secret like this");
  100. dbgln("I'd like to talk to your manager about this length of {}", length);
  101. return false;
  102. }
  103. m_context.master_key.clear();
  104. m_context.master_key.grow(length);
  105. pseudorandom_function(
  106. m_context.master_key,
  107. m_context.premaster_key,
  108. (const u8*)"master secret", 13,
  109. ReadonlyBytes { m_context.local_random, sizeof(m_context.local_random) },
  110. ReadonlyBytes { m_context.remote_random, sizeof(m_context.remote_random) });
  111. m_context.premaster_key.clear();
  112. if constexpr (TLS_DEBUG) {
  113. dbgln("master key:");
  114. print_buffer(m_context.master_key);
  115. }
  116. expand_key();
  117. return true;
  118. }
  119. static bool wildcard_matches(const StringView& host, const StringView& subject)
  120. {
  121. if (host.matches(subject))
  122. return true;
  123. if (subject.starts_with("*."))
  124. return wildcard_matches(host, subject.substring_view(2));
  125. return false;
  126. }
  127. Optional<size_t> TLSv12::verify_chain_and_get_matching_certificate(const StringView& host) const
  128. {
  129. if (m_context.certificates.is_empty() || !m_context.verify_chain())
  130. return {};
  131. if (host.is_empty())
  132. return 0;
  133. for (size_t i = 0; i < m_context.certificates.size(); ++i) {
  134. auto& cert = m_context.certificates[i];
  135. if (wildcard_matches(host, cert.subject.subject))
  136. return i;
  137. for (auto& san : cert.SAN) {
  138. if (wildcard_matches(host, san))
  139. return i;
  140. }
  141. }
  142. return {};
  143. }
  144. void TLSv12::build_rsa_pre_master_secret(PacketBuilder& builder)
  145. {
  146. u8 random_bytes[48];
  147. size_t bytes = 48;
  148. fill_with_random(random_bytes, bytes);
  149. // remove zeros from the random bytes
  150. for (size_t i = 0; i < bytes; ++i) {
  151. if (!random_bytes[i])
  152. random_bytes[i--] = get_random<u8>();
  153. }
  154. if (m_context.is_server) {
  155. dbgln("Server mode not supported");
  156. return;
  157. } else {
  158. *(u16*)random_bytes = AK::convert_between_host_and_network_endian((u16)Version::V12);
  159. }
  160. m_context.premaster_key = ByteBuffer::copy(random_bytes, bytes);
  161. const auto& certificate_option = verify_chain_and_get_matching_certificate(m_context.extensions.SNI); // if the SNI is empty, we'll make a special case and match *a* leaf certificate.
  162. if (!certificate_option.has_value()) {
  163. dbgln("certificate verification failed :(");
  164. alert(AlertLevel::Critical, AlertDescription::BadCertificate);
  165. return;
  166. }
  167. auto& certificate = m_context.certificates[certificate_option.value()];
  168. if constexpr (TLS_DEBUG) {
  169. dbgln("PreMaster secret");
  170. print_buffer(m_context.premaster_key);
  171. }
  172. Crypto::PK::RSA_PKCS1_EME rsa(certificate.public_key.modulus(), 0, certificate.public_key.public_exponent());
  173. Vector<u8, 32> out;
  174. out.resize(rsa.output_size());
  175. auto outbuf = out.span();
  176. rsa.encrypt(m_context.premaster_key, outbuf);
  177. if constexpr (TLS_DEBUG) {
  178. dbgln("Encrypted: ");
  179. print_buffer(outbuf);
  180. }
  181. if (!compute_master_secret_from_pre_master_secret(bytes)) {
  182. dbgln("oh noes we could not derive a master key :(");
  183. return;
  184. }
  185. builder.append_u24(outbuf.size() + 2);
  186. builder.append((u16)outbuf.size());
  187. builder.append(outbuf);
  188. }
  189. ByteBuffer TLSv12::build_certificate()
  190. {
  191. PacketBuilder builder { MessageType::Handshake, m_context.options.version };
  192. Vector<const Certificate*> certificates;
  193. Vector<Certificate>* local_certificates = nullptr;
  194. if (m_context.is_server) {
  195. dbgln("Unsupported: Server mode");
  196. VERIFY_NOT_REACHED();
  197. } else {
  198. local_certificates = &m_context.client_certificates;
  199. }
  200. constexpr size_t der_length_delta = 3;
  201. constexpr size_t certificate_vector_header_size = 3;
  202. size_t total_certificate_size = 0;
  203. for (size_t i = 0; i < local_certificates->size(); ++i) {
  204. auto& certificate = local_certificates->at(i);
  205. if (!certificate.der.is_empty()) {
  206. total_certificate_size += certificate.der.size() + der_length_delta;
  207. // FIXME: Check for and respond with only the requested certificate types.
  208. if (true) {
  209. certificates.append(&certificate);
  210. }
  211. }
  212. }
  213. builder.append((u8)HandshakeType::CertificateMessage);
  214. if (!total_certificate_size) {
  215. dbgln_if(TLS_DEBUG, "No certificates, sending empty certificate message");
  216. builder.append_u24(certificate_vector_header_size);
  217. builder.append_u24(total_certificate_size);
  218. } else {
  219. builder.append_u24(total_certificate_size + certificate_vector_header_size); // 3 bytes for header
  220. builder.append_u24(total_certificate_size);
  221. for (auto& certificate : certificates) {
  222. if (!certificate->der.is_empty()) {
  223. builder.append_u24(certificate->der.size());
  224. builder.append(certificate->der.bytes());
  225. }
  226. }
  227. }
  228. auto packet = builder.build();
  229. update_packet(packet);
  230. return packet;
  231. }
  232. ByteBuffer TLSv12::build_client_key_exchange()
  233. {
  234. PacketBuilder builder { MessageType::Handshake, m_context.options.version };
  235. builder.append((u8)HandshakeType::ClientKeyExchange);
  236. switch (get_key_exchange_algorithm(m_context.cipher)) {
  237. case KeyExchangeAlgorithm::RSA:
  238. build_rsa_pre_master_secret(builder);
  239. break;
  240. case KeyExchangeAlgorithm::DHE_DSS:
  241. dbgln("Client key exchange for DHE_DSS is not implemented");
  242. TODO();
  243. break;
  244. case KeyExchangeAlgorithm::DH_DSS:
  245. case KeyExchangeAlgorithm::DH_RSA:
  246. dbgln("Client key exchange for DH algorithms is not implemented");
  247. TODO();
  248. break;
  249. case KeyExchangeAlgorithm::DHE_RSA:
  250. dbgln("Client key exchange for DHE_RSA is not implemented");
  251. TODO();
  252. break;
  253. case KeyExchangeAlgorithm::DH_anon:
  254. dbgln("Client key exchange for DH_anon is not implemented");
  255. TODO();
  256. break;
  257. case KeyExchangeAlgorithm::ECDHE_RSA:
  258. case KeyExchangeAlgorithm::ECDH_ECDSA:
  259. case KeyExchangeAlgorithm::ECDH_RSA:
  260. case KeyExchangeAlgorithm::ECDHE_ECDSA:
  261. case KeyExchangeAlgorithm::ECDH_anon:
  262. dbgln("Client key exchange for ECDHE algorithms is not implemented");
  263. TODO();
  264. break;
  265. default:
  266. dbgln("Unknonwn client key exchange algorithm");
  267. VERIFY_NOT_REACHED();
  268. break;
  269. }
  270. m_context.connection_status = ConnectionStatus::KeyExchange;
  271. auto packet = builder.build();
  272. update_packet(packet);
  273. return packet;
  274. }
  275. }