HandshakeClient.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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.resize(length);
  104. pseudorandom_function(
  105. m_context.master_key,
  106. m_context.premaster_key,
  107. (const u8*)"master secret", 13,
  108. ReadonlyBytes { m_context.local_random, sizeof(m_context.local_random) },
  109. ReadonlyBytes { m_context.remote_random, sizeof(m_context.remote_random) });
  110. m_context.premaster_key.clear();
  111. if constexpr (TLS_DEBUG) {
  112. dbgln("master key:");
  113. print_buffer(m_context.master_key);
  114. }
  115. expand_key();
  116. return true;
  117. }
  118. static bool wildcard_matches(const StringView& host, const StringView& subject)
  119. {
  120. if (host.matches(subject))
  121. return true;
  122. if (subject.starts_with("*."))
  123. return wildcard_matches(host, subject.substring_view(2));
  124. return false;
  125. }
  126. Optional<size_t> TLSv12::verify_chain_and_get_matching_certificate(const StringView& host) const
  127. {
  128. if (m_context.certificates.is_empty() || !m_context.verify_chain())
  129. return {};
  130. if (host.is_empty())
  131. return 0;
  132. for (size_t i = 0; i < m_context.certificates.size(); ++i) {
  133. auto& cert = m_context.certificates[i];
  134. if (wildcard_matches(host, cert.subject.subject))
  135. return i;
  136. for (auto& san : cert.SAN) {
  137. if (wildcard_matches(host, san))
  138. return i;
  139. }
  140. }
  141. return {};
  142. }
  143. void TLSv12::build_rsa_pre_master_secret(PacketBuilder& builder)
  144. {
  145. u8 random_bytes[48];
  146. size_t bytes = 48;
  147. fill_with_random(random_bytes, bytes);
  148. // remove zeros from the random bytes
  149. for (size_t i = 0; i < bytes; ++i) {
  150. if (!random_bytes[i])
  151. random_bytes[i--] = get_random<u8>();
  152. }
  153. if (m_context.is_server) {
  154. dbgln("Server mode not supported");
  155. return;
  156. } else {
  157. *(u16*)random_bytes = AK::convert_between_host_and_network_endian((u16)Version::V12);
  158. }
  159. m_context.premaster_key = ByteBuffer::copy(random_bytes, bytes);
  160. 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.
  161. if (!certificate_option.has_value()) {
  162. dbgln("certificate verification failed :(");
  163. alert(AlertLevel::Critical, AlertDescription::BadCertificate);
  164. return;
  165. }
  166. auto& certificate = m_context.certificates[certificate_option.value()];
  167. if constexpr (TLS_DEBUG) {
  168. dbgln("PreMaster secret");
  169. print_buffer(m_context.premaster_key);
  170. }
  171. Crypto::PK::RSA_PKCS1_EME rsa(certificate.public_key.modulus(), 0, certificate.public_key.public_exponent());
  172. Vector<u8, 32> out;
  173. out.resize(rsa.output_size());
  174. auto outbuf = out.span();
  175. rsa.encrypt(m_context.premaster_key, outbuf);
  176. if constexpr (TLS_DEBUG) {
  177. dbgln("Encrypted: ");
  178. print_buffer(outbuf);
  179. }
  180. if (!compute_master_secret_from_pre_master_secret(bytes)) {
  181. dbgln("oh noes we could not derive a master key :(");
  182. return;
  183. }
  184. builder.append_u24(outbuf.size() + 2);
  185. builder.append((u16)outbuf.size());
  186. builder.append(outbuf);
  187. }
  188. ByteBuffer TLSv12::build_certificate()
  189. {
  190. PacketBuilder builder { MessageType::Handshake, m_context.options.version };
  191. Vector<Certificate const&> certificates;
  192. Vector<Certificate>* local_certificates = nullptr;
  193. if (m_context.is_server) {
  194. dbgln("Unsupported: Server mode");
  195. VERIFY_NOT_REACHED();
  196. } else {
  197. local_certificates = &m_context.client_certificates;
  198. }
  199. constexpr size_t der_length_delta = 3;
  200. constexpr size_t certificate_vector_header_size = 3;
  201. size_t total_certificate_size = 0;
  202. for (size_t i = 0; i < local_certificates->size(); ++i) {
  203. auto& certificate = local_certificates->at(i);
  204. if (!certificate.der.is_empty()) {
  205. total_certificate_size += certificate.der.size() + der_length_delta;
  206. // FIXME: Check for and respond with only the requested certificate types.
  207. if (true) {
  208. certificates.append(certificate);
  209. }
  210. }
  211. }
  212. builder.append((u8)HandshakeType::CertificateMessage);
  213. if (!total_certificate_size) {
  214. dbgln_if(TLS_DEBUG, "No certificates, sending empty certificate message");
  215. builder.append_u24(certificate_vector_header_size);
  216. builder.append_u24(total_certificate_size);
  217. } else {
  218. builder.append_u24(total_certificate_size + certificate_vector_header_size); // 3 bytes for header
  219. builder.append_u24(total_certificate_size);
  220. for (auto& certificate : certificates) {
  221. if (!certificate.der.is_empty()) {
  222. builder.append_u24(certificate.der.size());
  223. builder.append(certificate.der.bytes());
  224. }
  225. }
  226. }
  227. auto packet = builder.build();
  228. update_packet(packet);
  229. return packet;
  230. }
  231. ByteBuffer TLSv12::build_client_key_exchange()
  232. {
  233. PacketBuilder builder { MessageType::Handshake, m_context.options.version };
  234. builder.append((u8)HandshakeType::ClientKeyExchange);
  235. switch (get_key_exchange_algorithm(m_context.cipher)) {
  236. case KeyExchangeAlgorithm::RSA:
  237. build_rsa_pre_master_secret(builder);
  238. break;
  239. case KeyExchangeAlgorithm::DHE_DSS:
  240. dbgln("Client key exchange for DHE_DSS is not implemented");
  241. TODO();
  242. break;
  243. case KeyExchangeAlgorithm::DH_DSS:
  244. case KeyExchangeAlgorithm::DH_RSA:
  245. dbgln("Client key exchange for DH algorithms is not implemented");
  246. TODO();
  247. break;
  248. case KeyExchangeAlgorithm::DHE_RSA:
  249. dbgln("Client key exchange for DHE_RSA is not implemented");
  250. TODO();
  251. break;
  252. case KeyExchangeAlgorithm::DH_anon:
  253. dbgln("Client key exchange for DH_anon is not implemented");
  254. TODO();
  255. break;
  256. case KeyExchangeAlgorithm::ECDHE_RSA:
  257. case KeyExchangeAlgorithm::ECDH_ECDSA:
  258. case KeyExchangeAlgorithm::ECDH_RSA:
  259. case KeyExchangeAlgorithm::ECDHE_ECDSA:
  260. case KeyExchangeAlgorithm::ECDH_anon:
  261. dbgln("Client key exchange for ECDHE algorithms is not implemented");
  262. TODO();
  263. break;
  264. default:
  265. dbgln("Unknonwn client key exchange algorithm");
  266. VERIFY_NOT_REACHED();
  267. break;
  268. }
  269. m_context.connection_status = ConnectionStatus::KeyExchange;
  270. auto packet = builder.build();
  271. update_packet(packet);
  272. return packet;
  273. }
  274. }