Record.cpp 23 KB

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