Record.cpp 23 KB

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