Record.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 <AK/MemoryStream.h>
  9. #include <LibCore/Timer.h>
  10. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  11. #include <LibTLS/TLSv12.h>
  12. namespace TLS {
  13. ByteBuffer TLSv12::build_alert(bool critical, u8 code)
  14. {
  15. PacketBuilder builder(MessageType::Alert, (u16)m_context.options.version);
  16. builder.append((u8)(critical ? AlertLevel::Critical : AlertLevel::Warning));
  17. builder.append(code);
  18. if (critical)
  19. m_context.critical_error = code;
  20. auto packet = builder.build();
  21. update_packet(packet);
  22. return packet;
  23. }
  24. void TLSv12::alert(AlertLevel level, AlertDescription code)
  25. {
  26. auto the_alert = build_alert(level == AlertLevel::Critical, (u8)code);
  27. write_packet(the_alert);
  28. flush();
  29. }
  30. void TLSv12::write_packet(ByteBuffer& packet)
  31. {
  32. m_context.tls_buffer.append(packet.data(), packet.size());
  33. if (m_context.connection_status > ConnectionStatus::Disconnected) {
  34. if (!m_has_scheduled_write_flush) {
  35. dbgln_if(TLS_DEBUG, "Scheduling write of {}", m_context.tls_buffer.size());
  36. deferred_invoke([this](auto&) { write_into_socket(); });
  37. m_has_scheduled_write_flush = true;
  38. } else {
  39. // multiple packet are available, let's flush some out
  40. dbgln_if(TLS_DEBUG, "Flushing scheduled write of {}", m_context.tls_buffer.size());
  41. write_into_socket();
  42. // the deferred invoke is still in place
  43. m_has_scheduled_write_flush = true;
  44. }
  45. }
  46. }
  47. void TLSv12::update_packet(ByteBuffer& packet)
  48. {
  49. u32 header_size = 5;
  50. ByteReader::store(packet.offset_pointer(3), AK::convert_between_host_and_network_endian((u16)(packet.size() - header_size)));
  51. if (packet[0] != (u8)MessageType::ChangeCipher) {
  52. if (packet[0] == (u8)MessageType::Handshake && packet.size() > header_size) {
  53. u8 handshake_type = packet[header_size];
  54. if (handshake_type != HandshakeType::HelloRequest && handshake_type != HandshakeType::HelloVerifyRequest) {
  55. update_hash(packet.bytes(), header_size);
  56. }
  57. }
  58. if (m_context.cipher_spec_set && m_context.crypto.created) {
  59. size_t length = packet.size() - header_size;
  60. size_t block_size = 0;
  61. size_t padding = 0;
  62. size_t mac_size = 0;
  63. m_cipher_local.visit(
  64. [&](Empty&) { VERIFY_NOT_REACHED(); },
  65. [&](Crypto::Cipher::AESCipher::GCMMode& gcm) {
  66. VERIFY(is_aead());
  67. block_size = gcm.cipher().block_size();
  68. padding = 0;
  69. mac_size = 0; // AEAD provides its own authentication scheme.
  70. },
  71. [&](Crypto::Cipher::AESCipher::CBCMode& cbc) {
  72. VERIFY(!is_aead());
  73. block_size = cbc.cipher().block_size();
  74. // If the length is already a multiple a block_size,
  75. // an entire block of padding is added.
  76. // In short, we _never_ have no padding.
  77. mac_size = mac_length();
  78. length += mac_size;
  79. padding = block_size - length % block_size;
  80. length += padding;
  81. });
  82. if (m_context.crypto.created == 1) {
  83. // `buffer' will continue to be encrypted
  84. auto buffer = ByteBuffer::create_uninitialized(length);
  85. size_t buffer_position = 0;
  86. auto iv_size = iv_length();
  87. // copy the packet, sans the header
  88. buffer.overwrite(buffer_position, packet.offset_pointer(header_size), packet.size() - header_size);
  89. buffer_position += packet.size() - header_size;
  90. ByteBuffer ct;
  91. m_cipher_local.visit(
  92. [&](Empty&) { VERIFY_NOT_REACHED(); },
  93. [&](Crypto::Cipher::AESCipher::GCMMode& gcm) {
  94. VERIFY(is_aead());
  95. // We need enough space for a header, the data, a tag, and the IV
  96. ct = ByteBuffer::create_uninitialized(length + header_size + iv_size + 16);
  97. // copy the header over
  98. ct.overwrite(0, packet.data(), header_size - 2);
  99. // AEAD AAD (13)
  100. // Seq. no (8)
  101. // content type (1)
  102. // version (2)
  103. // length (2)
  104. u8 aad[13];
  105. Bytes aad_bytes { aad, 13 };
  106. OutputMemoryStream aad_stream { aad_bytes };
  107. u64 seq_no = AK::convert_between_host_and_network_endian(m_context.local_sequence_number);
  108. u16 len = AK::convert_between_host_and_network_endian((u16)(packet.size() - header_size));
  109. aad_stream.write({ &seq_no, sizeof(seq_no) });
  110. aad_stream.write(packet.bytes().slice(0, 3)); // content-type + version
  111. aad_stream.write({ &len, sizeof(len) }); // length
  112. VERIFY(aad_stream.is_end());
  113. // AEAD IV (12)
  114. // IV (4)
  115. // (Nonce) (8)
  116. // -- Our GCM impl takes 16 bytes
  117. // zero (4)
  118. u8 iv[16];
  119. Bytes iv_bytes { iv, 16 };
  120. Bytes { m_context.crypto.local_aead_iv, 4 }.copy_to(iv_bytes);
  121. fill_with_random(iv_bytes.offset(4), 8);
  122. memset(iv_bytes.offset(12), 0, 4);
  123. // write the random part of the iv out
  124. iv_bytes.slice(4, 8).copy_to(ct.bytes().slice(header_size));
  125. // Write the encrypted data and the tag
  126. gcm.encrypt(
  127. packet.bytes().slice(header_size, length),
  128. ct.bytes().slice(header_size + 8, length),
  129. iv_bytes,
  130. aad_bytes,
  131. ct.bytes().slice(header_size + 8 + length, 16));
  132. VERIFY(header_size + 8 + length + 16 == ct.size());
  133. },
  134. [&](Crypto::Cipher::AESCipher::CBCMode& cbc) {
  135. VERIFY(!is_aead());
  136. // We need enough space for a header, iv_length bytes of IV and whatever the packet contains
  137. ct = ByteBuffer::create_uninitialized(length + header_size + iv_size);
  138. // copy the header over
  139. ct.overwrite(0, packet.data(), header_size - 2);
  140. // get the appropricate HMAC value for the entire packet
  141. auto mac = hmac_message(packet, {}, mac_size, true);
  142. // write the MAC
  143. buffer.overwrite(buffer_position, mac.data(), mac.size());
  144. buffer_position += mac.size();
  145. // Apply the padding (a packet MUST always be padded)
  146. memset(buffer.offset_pointer(buffer_position), padding - 1, padding);
  147. buffer_position += padding;
  148. VERIFY(buffer_position == buffer.size());
  149. auto iv = ByteBuffer::create_uninitialized(iv_size);
  150. fill_with_random(iv.data(), iv.size());
  151. // write it into the ciphertext portion of the message
  152. ct.overwrite(header_size, iv.data(), iv.size());
  153. VERIFY(header_size + iv_size + length == ct.size());
  154. VERIFY(length % block_size == 0);
  155. // get a block to encrypt into
  156. auto view = ct.bytes().slice(header_size + iv_size, length);
  157. cbc.encrypt(buffer, view, iv);
  158. });
  159. // store the correct ciphertext length into the packet
  160. u16 ct_length = (u16)ct.size() - header_size;
  161. ByteReader::store(ct.offset_pointer(header_size - 2), AK::convert_between_host_and_network_endian(ct_length));
  162. // replace the packet with the ciphertext
  163. packet = ct;
  164. }
  165. }
  166. }
  167. ++m_context.local_sequence_number;
  168. }
  169. void TLSv12::update_hash(ReadonlyBytes message, size_t header_size)
  170. {
  171. dbgln_if(TLS_DEBUG, "Update hash with message of size {}", message.size());
  172. m_context.handshake_hash.update(message.slice(header_size));
  173. }
  174. void TLSv12::ensure_hmac(size_t digest_size, bool local)
  175. {
  176. if (local && m_hmac_local)
  177. return;
  178. if (!local && m_hmac_remote)
  179. return;
  180. auto hash_kind = Crypto::Hash::HashKind::None;
  181. switch (digest_size) {
  182. case Crypto::Hash::SHA1::DigestSize:
  183. hash_kind = Crypto::Hash::HashKind::SHA1;
  184. break;
  185. case Crypto::Hash::SHA256::DigestSize:
  186. hash_kind = Crypto::Hash::HashKind::SHA256;
  187. break;
  188. case Crypto::Hash::SHA384::DigestSize:
  189. hash_kind = Crypto::Hash::HashKind::SHA384;
  190. break;
  191. case Crypto::Hash::SHA512::DigestSize:
  192. hash_kind = Crypto::Hash::HashKind::SHA512;
  193. break;
  194. default:
  195. dbgln("Failed to find a suitable hash for size {}", digest_size);
  196. break;
  197. }
  198. auto hmac = make<Crypto::Authentication::HMAC<Crypto::Hash::Manager>>(ReadonlyBytes { local ? m_context.crypto.local_mac : m_context.crypto.remote_mac, digest_size }, hash_kind);
  199. if (local)
  200. m_hmac_local = move(hmac);
  201. else
  202. m_hmac_remote = move(hmac);
  203. }
  204. ByteBuffer TLSv12::hmac_message(const ReadonlyBytes& buf, const Optional<ReadonlyBytes> buf2, size_t mac_length, bool local)
  205. {
  206. u64 sequence_number = AK::convert_between_host_and_network_endian(local ? m_context.local_sequence_number : m_context.remote_sequence_number);
  207. ensure_hmac(mac_length, local);
  208. auto& hmac = local ? *m_hmac_local : *m_hmac_remote;
  209. if constexpr (TLS_DEBUG) {
  210. dbgln("========================= PACKET DATA ==========================");
  211. print_buffer((const u8*)&sequence_number, sizeof(u64));
  212. print_buffer(buf.data(), buf.size());
  213. if (buf2.has_value())
  214. print_buffer(buf2.value().data(), buf2.value().size());
  215. dbgln("========================= PACKET DATA ==========================");
  216. }
  217. hmac.update((const u8*)&sequence_number, sizeof(u64));
  218. hmac.update(buf);
  219. if (buf2.has_value() && buf2.value().size()) {
  220. hmac.update(buf2.value());
  221. }
  222. auto digest = hmac.digest();
  223. auto mac = ByteBuffer::copy(digest.immutable_data(), digest.data_length());
  224. if constexpr (TLS_DEBUG) {
  225. dbgln("HMAC of the block for sequence number {}", sequence_number);
  226. print_buffer(mac);
  227. }
  228. return mac;
  229. }
  230. ssize_t TLSv12::handle_message(ReadonlyBytes buffer)
  231. {
  232. auto res { 5ll };
  233. size_t header_size = res;
  234. ssize_t payload_res = 0;
  235. dbgln_if(TLS_DEBUG, "buffer size: {}", buffer.size());
  236. if (buffer.size() < 5) {
  237. return (i8)Error::NeedMoreData;
  238. }
  239. auto type = (MessageType)buffer[0];
  240. size_t buffer_position { 1 };
  241. // FIXME: Read the version and verify it
  242. if constexpr (TLS_DEBUG) {
  243. auto version = ByteReader::load16(buffer.offset_pointer(buffer_position));
  244. dbgln("type={}, version={}", (u8)type, (u16)version);
  245. }
  246. buffer_position += 2;
  247. auto length = AK::convert_between_host_and_network_endian(ByteReader::load16(buffer.offset_pointer(buffer_position)));
  248. dbgln_if(TLS_DEBUG, "record length: {} at offset: {}", length, buffer_position);
  249. buffer_position += 2;
  250. if (buffer_position + length > buffer.size()) {
  251. dbgln_if(TLS_DEBUG, "record length more than what we have: {}", buffer.size());
  252. return (i8)Error::NeedMoreData;
  253. }
  254. dbgln_if(TLS_DEBUG, "message type: {}, length: {}", (u8)type, length);
  255. auto plain = buffer.slice(buffer_position, buffer.size() - buffer_position);
  256. ByteBuffer decrypted;
  257. if (m_context.cipher_spec_set && type != MessageType::ChangeCipher) {
  258. if constexpr (TLS_DEBUG) {
  259. dbgln("Encrypted: ");
  260. print_buffer(buffer.slice(header_size, length));
  261. }
  262. Error return_value = Error::NoError;
  263. m_cipher_remote.visit(
  264. [&](Empty&) { VERIFY_NOT_REACHED(); },
  265. [&](Crypto::Cipher::AESCipher::GCMMode& gcm) {
  266. VERIFY(is_aead());
  267. if (length < 24) {
  268. dbgln("Invalid packet length");
  269. auto packet = build_alert(true, (u8)AlertDescription::DecryptError);
  270. write_packet(packet);
  271. return_value = Error::BrokenPacket;
  272. return;
  273. }
  274. auto packet_length = length - iv_length() - 16;
  275. auto payload = plain;
  276. decrypted = ByteBuffer::create_uninitialized(packet_length);
  277. // AEAD AAD (13)
  278. // Seq. no (8)
  279. // content type (1)
  280. // version (2)
  281. // length (2)
  282. u8 aad[13];
  283. Bytes aad_bytes { aad, 13 };
  284. OutputMemoryStream aad_stream { aad_bytes };
  285. u64 seq_no = AK::convert_between_host_and_network_endian(m_context.remote_sequence_number);
  286. u16 len = AK::convert_between_host_and_network_endian((u16)packet_length);
  287. aad_stream.write({ &seq_no, sizeof(seq_no) }); // Sequence number
  288. aad_stream.write(buffer.slice(0, header_size - 2)); // content-type + version
  289. aad_stream.write({ &len, sizeof(u16) });
  290. VERIFY(aad_stream.is_end());
  291. auto nonce = payload.slice(0, iv_length());
  292. payload = payload.slice(iv_length());
  293. // AEAD IV (12)
  294. // IV (4)
  295. // (Nonce) (8)
  296. // -- Our GCM impl takes 16 bytes
  297. // zero (4)
  298. u8 iv[16];
  299. Bytes iv_bytes { iv, 16 };
  300. Bytes { m_context.crypto.remote_aead_iv, 4 }.copy_to(iv_bytes);
  301. nonce.copy_to(iv_bytes.slice(4));
  302. memset(iv_bytes.offset(12), 0, 4);
  303. auto ciphertext = payload.slice(0, payload.size() - 16);
  304. auto tag = payload.slice(ciphertext.size());
  305. auto consistency = gcm.decrypt(
  306. ciphertext,
  307. decrypted,
  308. iv_bytes,
  309. aad_bytes,
  310. tag);
  311. if (consistency != Crypto::VerificationConsistency::Consistent) {
  312. dbgln("integrity check failed (tag length {})", tag.size());
  313. auto packet = build_alert(true, (u8)AlertDescription::BadRecordMAC);
  314. write_packet(packet);
  315. return_value = Error::IntegrityCheckFailed;
  316. return;
  317. }
  318. plain = decrypted;
  319. },
  320. [&](Crypto::Cipher::AESCipher::CBCMode& cbc) {
  321. VERIFY(!is_aead());
  322. auto iv_size = iv_length();
  323. decrypted = cbc.create_aligned_buffer(length - iv_size);
  324. auto iv = buffer.slice(header_size, iv_size);
  325. Bytes decrypted_span = decrypted;
  326. cbc.decrypt(buffer.slice(header_size + iv_size, length - iv_size), decrypted_span, iv);
  327. length = decrypted_span.size();
  328. if constexpr (TLS_DEBUG) {
  329. dbgln("Decrypted: ");
  330. print_buffer(decrypted);
  331. }
  332. auto mac_size = mac_length();
  333. if (length < mac_size) {
  334. dbgln("broken packet");
  335. auto packet = build_alert(true, (u8)AlertDescription::DecryptError);
  336. write_packet(packet);
  337. return_value = Error::BrokenPacket;
  338. return;
  339. }
  340. length -= mac_size;
  341. const u8* message_hmac = decrypted_span.offset(length);
  342. u8 temp_buf[5];
  343. memcpy(temp_buf, buffer.offset_pointer(0), 3);
  344. *(u16*)(temp_buf + 3) = AK::convert_between_host_and_network_endian(length);
  345. auto hmac = hmac_message({ temp_buf, 5 }, decrypted_span.slice(0, length), mac_size);
  346. auto message_mac = ReadonlyBytes { message_hmac, mac_size };
  347. if (hmac != message_mac) {
  348. dbgln("integrity check failed (mac length {})", mac_size);
  349. dbgln("mac received:");
  350. print_buffer(message_mac);
  351. dbgln("mac computed:");
  352. print_buffer(hmac);
  353. auto packet = build_alert(true, (u8)AlertDescription::BadRecordMAC);
  354. write_packet(packet);
  355. return_value = Error::IntegrityCheckFailed;
  356. return;
  357. }
  358. plain = decrypted.bytes().slice(0, length);
  359. });
  360. if (return_value != Error::NoError) {
  361. return (i8)return_value;
  362. }
  363. }
  364. m_context.remote_sequence_number++;
  365. switch (type) {
  366. case MessageType::ApplicationData:
  367. if (m_context.connection_status != ConnectionStatus::Established) {
  368. dbgln("unexpected application data");
  369. payload_res = (i8)Error::UnexpectedMessage;
  370. auto packet = build_alert(true, (u8)AlertDescription::UnexpectedMessage);
  371. write_packet(packet);
  372. } else {
  373. dbgln_if(TLS_DEBUG, "application data message of size {}", plain.size());
  374. m_context.application_buffer.append(plain.data(), plain.size());
  375. }
  376. break;
  377. case MessageType::Handshake:
  378. dbgln_if(TLS_DEBUG, "tls handshake message");
  379. payload_res = handle_handshake_payload(plain);
  380. break;
  381. case MessageType::ChangeCipher:
  382. if (m_context.connection_status != ConnectionStatus::KeyExchange) {
  383. dbgln("unexpected change cipher message");
  384. auto packet = build_alert(true, (u8)AlertDescription::UnexpectedMessage);
  385. write_packet(packet);
  386. payload_res = (i8)Error::UnexpectedMessage;
  387. } else {
  388. dbgln_if(TLS_DEBUG, "change cipher spec message");
  389. m_context.cipher_spec_set = true;
  390. m_context.remote_sequence_number = 0;
  391. }
  392. break;
  393. case MessageType::Alert:
  394. dbgln_if(TLS_DEBUG, "alert message of length {}", length);
  395. if (length >= 2) {
  396. if constexpr (TLS_DEBUG)
  397. print_buffer(plain);
  398. auto level = plain[0];
  399. auto code = plain[1];
  400. dbgln_if(TLS_DEBUG, "Alert received with level {}, code {}", level, code);
  401. if (level == (u8)AlertLevel::Critical) {
  402. dbgln("We were alerted of a critical error: {} ({})", code, alert_name((AlertDescription)code));
  403. m_context.critical_error = code;
  404. try_disambiguate_error();
  405. res = (i8)Error::UnknownError;
  406. }
  407. if (code == (u8)AlertDescription::CloseNotify) {
  408. res += 2;
  409. alert(AlertLevel::Critical, AlertDescription::CloseNotify);
  410. m_context.connection_finished = true;
  411. if (!m_context.cipher_spec_set) {
  412. // AWS CloudFront hits this.
  413. dbgln("Server sent a close notify and we haven't agreed on a cipher suite. Treating it as a handshake failure.");
  414. m_context.critical_error = (u8)AlertDescription::HandshakeFailure;
  415. try_disambiguate_error();
  416. }
  417. }
  418. m_context.error_code = (Error)code;
  419. }
  420. break;
  421. default:
  422. dbgln("message not understood");
  423. return (i8)Error::NotUnderstood;
  424. }
  425. if (payload_res < 0)
  426. return payload_res;
  427. if (res > 0)
  428. return header_size + length;
  429. return res;
  430. }
  431. }