Record.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <LibCore/Timer.h>
  27. #include <LibCrypto/ASN1/DER.h>
  28. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  29. #include <LibTLS/TLSv12.h>
  30. namespace TLS {
  31. void TLSv12::write_packet(ByteBuffer& packet)
  32. {
  33. m_context.tls_buffer.append(packet.data(), packet.size());
  34. if (m_context.connection_status > ConnectionStatus::Disconnected) {
  35. if (!m_has_scheduled_write_flush) {
  36. #ifdef TLS_DEBUG
  37. dbg() << "Scheduling write of " << m_context.tls_buffer.size();
  38. #endif
  39. deferred_invoke([this](auto&) { write_into_socket(); });
  40. m_has_scheduled_write_flush = true;
  41. } else {
  42. // multiple packet are available, let's flush some out
  43. #ifdef TLS_DEBUG
  44. dbg() << "Flushing scheduled write of " << m_context.tls_buffer.size();
  45. #endif
  46. write_into_socket();
  47. // the deferred invoke is still in place
  48. m_has_scheduled_write_flush = true;
  49. }
  50. }
  51. }
  52. void TLSv12::update_packet(ByteBuffer& packet)
  53. {
  54. u32 header_size = 5;
  55. *(u16*)packet.offset_pointer(3) = convert_between_host_and_network((u16)(packet.size() - header_size));
  56. if (packet[0] != (u8)MessageType::ChangeCipher) {
  57. if (packet[0] == (u8)MessageType::Handshake && packet.size() > header_size) {
  58. u8 handshake_type = packet[header_size];
  59. if (handshake_type != HandshakeType::HelloRequest && handshake_type != HandshakeType::HelloVerifyRequest) {
  60. update_hash(packet.slice_view(header_size, packet.size() - header_size));
  61. }
  62. }
  63. if (m_context.cipher_spec_set && m_context.crypto.created) {
  64. size_t length = packet.size() - header_size + mac_length();
  65. auto block_size = m_aes_local->cipher().block_size();
  66. // If the length is already a multiple a block_size,
  67. // an entire block of padding is added.
  68. // In short, we _never_ have no padding.
  69. size_t padding = block_size - length % block_size;
  70. length += padding;
  71. size_t mac_size = mac_length();
  72. if (m_context.crypto.created == 1) {
  73. // `buffer' will continue to be encrypted
  74. auto buffer = ByteBuffer::create_uninitialized(length);
  75. size_t buffer_position = 0;
  76. auto iv_size = iv_length();
  77. // We need enough space for a header, iv_length bytes of IV and whatever the packet contains
  78. auto ct = ByteBuffer::create_uninitialized(length + header_size + iv_size);
  79. // copy the header over
  80. ct.overwrite(0, packet.data(), header_size - 2);
  81. // copy the packet, sans the header
  82. buffer.overwrite(buffer_position, packet.offset_pointer(header_size), packet.size() - header_size);
  83. buffer_position += packet.size() - header_size;
  84. // get the appropricate HMAC value for the entire packet
  85. auto mac = hmac_message(packet, {}, mac_size, true);
  86. // write the MAC
  87. buffer.overwrite(buffer_position, mac.data(), mac.size());
  88. buffer_position += mac.size();
  89. // Apply the padding (a packet MUST always be padded)
  90. memset(buffer.offset_pointer(buffer_position), padding - 1, padding);
  91. buffer_position += padding;
  92. ASSERT(buffer_position == buffer.size());
  93. auto iv = ByteBuffer::create_uninitialized(iv_size);
  94. AK::fill_with_random(iv.data(), iv.size());
  95. // write it into the ciphertext portion of the message
  96. ct.overwrite(header_size, iv.data(), iv.size());
  97. ASSERT(header_size + iv_size + length == ct.size());
  98. ASSERT(length % block_size == 0);
  99. // get a block to encrypt into
  100. auto view = ct.bytes().slice(header_size + iv_size, length);
  101. m_aes_local->encrypt(buffer, view, iv);
  102. // store the correct ciphertext length into the packet
  103. u16 ct_length = (u16)ct.size() - header_size;
  104. *(u16*)ct.offset_pointer(header_size - 2) = convert_between_host_and_network(ct_length);
  105. // replace the packet with the ciphertext
  106. packet = ct;
  107. }
  108. }
  109. }
  110. ++m_context.local_sequence_number;
  111. }
  112. void TLSv12::update_hash(const ByteBuffer& message)
  113. {
  114. m_context.handshake_hash.update(message);
  115. }
  116. ByteBuffer TLSv12::hmac_message(const ReadonlyBytes& buf, const Optional<ReadonlyBytes> buf2, size_t mac_length, bool local)
  117. {
  118. u64 sequence_number = convert_between_host_and_network(local ? m_context.local_sequence_number : m_context.remote_sequence_number);
  119. ensure_hmac(mac_length, local);
  120. auto& hmac = local ? *m_hmac_local : *m_hmac_remote;
  121. #ifdef TLS_DEBUG
  122. dbg() << "========================= PACKET DATA ==========================";
  123. print_buffer((const u8*)&sequence_number, sizeof(u64));
  124. print_buffer(buf.data(), buf.size());
  125. if (buf2.has_value())
  126. print_buffer(buf2.value().data(), buf2.value().size());
  127. dbg() << "========================= PACKET DATA ==========================";
  128. #endif
  129. hmac.update((const u8*)&sequence_number, sizeof(u64));
  130. hmac.update(buf);
  131. if (buf2.has_value() && buf2.value().size()) {
  132. hmac.update(buf2.value());
  133. }
  134. auto digest = hmac.digest();
  135. auto mac = ByteBuffer::copy(digest.immutable_data(), digest.data_length());
  136. #ifdef TLS_DEBUG
  137. dbg() << "HMAC of the block for sequence number " << m_context.local_sequence_number;
  138. print_buffer(mac);
  139. #endif
  140. return mac;
  141. }
  142. ssize_t TLSv12::handle_message(const ByteBuffer& buffer)
  143. {
  144. auto res { 5ll };
  145. size_t header_size = res;
  146. ssize_t payload_res = 0;
  147. #ifdef TLS_DEBUG
  148. dbg() << "buffer size: " << buffer.size();
  149. #endif
  150. if (buffer.size() < 5) {
  151. return (i8)Error::NeedMoreData;
  152. }
  153. auto type = (MessageType)buffer[0];
  154. size_t buffer_position { 1 };
  155. // FIXME: Read the version and verify it
  156. #ifdef TLS_DEBUG
  157. auto version = (Version) * (const u16*)buffer.offset_pointer(buffer_position);
  158. dbg() << "type: " << (u8)type << " version: " << (u16)version;
  159. #endif
  160. buffer_position += 2;
  161. auto length = convert_between_host_and_network(*(const u16*)buffer.offset_pointer(buffer_position));
  162. #ifdef TLS_DEBUG
  163. dbg() << "record length: " << length << " at offset: " << buffer_position;
  164. #endif
  165. buffer_position += 2;
  166. if (buffer_position + length > buffer.size()) {
  167. #ifdef TLS_DEBUG
  168. dbg() << "record length more than what we have: " << buffer.size();
  169. #endif
  170. return (i8)Error::NeedMoreData;
  171. }
  172. #ifdef TLS_DEBUG
  173. dbg() << "message type: " << (u8)type << ", length: " << length;
  174. #endif
  175. ByteBuffer plain = buffer.slice_view(buffer_position, buffer.size() - buffer_position);
  176. if (m_context.cipher_spec_set && type != MessageType::ChangeCipher) {
  177. #ifdef TLS_DEBUG
  178. dbg() << "Encrypted: ";
  179. print_buffer(buffer.slice_view(header_size, length));
  180. #endif
  181. ASSERT(m_aes_remote);
  182. auto iv_size = iv_length();
  183. auto decrypted = m_aes_remote->create_aligned_buffer(length - iv_size);
  184. auto iv = buffer.slice_view(header_size, iv_size);
  185. Bytes decrypted_span = decrypted;
  186. m_aes_remote->decrypt(buffer.bytes().slice(header_size + iv_size, length - iv_size), decrypted_span, iv);
  187. length = decrypted_span.size();
  188. #ifdef TLS_DEBUG
  189. dbg() << "Decrypted: ";
  190. print_buffer(decrypted);
  191. #endif
  192. auto mac_size = mac_length();
  193. if (length < mac_size) {
  194. dbg() << "broken packet";
  195. auto packet = build_alert(true, (u8)AlertDescription::DecryptError);
  196. write_packet(packet);
  197. return (i8)Error::BrokenPacket;
  198. }
  199. const u8* message_hmac = decrypted_span.offset(length - mac_size);
  200. u8 temp_buf[5];
  201. memcpy(temp_buf, buffer.offset_pointer(0), 3);
  202. *(u16*)(temp_buf + 3) = convert_between_host_and_network(length);
  203. auto hmac = hmac_message({ temp_buf, 5 }, decrypted_span, mac_size);
  204. auto message_mac = ByteBuffer::wrap(const_cast<u8*>(message_hmac), mac_size);
  205. if (hmac != message_mac) {
  206. dbg() << "integrity check failed (mac length " << length << ")";
  207. dbg() << "mac received:";
  208. print_buffer(message_mac);
  209. dbg() << "mac computed:";
  210. print_buffer(hmac);
  211. auto packet = build_alert(true, (u8)AlertDescription::BadRecordMAC);
  212. write_packet(packet);
  213. return (i8)Error::IntegrityCheckFailed;
  214. }
  215. plain = decrypted.slice(0, length - mac_size);
  216. }
  217. m_context.remote_sequence_number++;
  218. switch (type) {
  219. case MessageType::ApplicationData:
  220. if (m_context.connection_status != ConnectionStatus::Established) {
  221. dbg() << "unexpected application data";
  222. payload_res = (i8)Error::UnexpectedMessage;
  223. auto packet = build_alert(true, (u8)AlertDescription::UnexpectedMessage);
  224. write_packet(packet);
  225. } else {
  226. #ifdef TLS_DEBUG
  227. dbg() << "application data message of size " << plain.size();
  228. #endif
  229. m_context.application_buffer.append(plain.data(), plain.size());
  230. }
  231. break;
  232. case MessageType::Handshake:
  233. #ifdef TLS_DEBUG
  234. dbg() << "tls handshake message";
  235. #endif
  236. payload_res = handle_payload(plain);
  237. break;
  238. case MessageType::ChangeCipher:
  239. if (m_context.connection_status != ConnectionStatus::KeyExchange) {
  240. dbg() << "unexpected change cipher message";
  241. auto packet = build_alert(true, (u8)AlertDescription::UnexpectedMessage);
  242. payload_res = (i8)Error::UnexpectedMessage;
  243. } else {
  244. #ifdef TLS_DEBUG
  245. dbg() << "change cipher spec message";
  246. #endif
  247. m_context.cipher_spec_set = true;
  248. m_context.remote_sequence_number = 0;
  249. }
  250. break;
  251. case MessageType::Alert:
  252. #ifdef TLS_DEBUG
  253. dbg() << "alert message of length " << length;
  254. #endif
  255. if (length >= 2) {
  256. #ifdef TLS_DEBUG
  257. print_buffer(plain);
  258. #endif
  259. auto level = plain[0];
  260. auto code = plain[1];
  261. if (level == (u8)AlertLevel::Critical) {
  262. dbg() << "We were alerted of a critical error: " << code << " (" << alert_name((AlertDescription)code) << ")";
  263. m_context.critical_error = code;
  264. try_disambiguate_error();
  265. res = (i8)Error::UnknownError;
  266. } else {
  267. dbg() << "Alert: " << code;
  268. }
  269. if (code == 0) {
  270. // close notify
  271. res += 2;
  272. alert(AlertLevel::Critical, AlertDescription::CloseNotify);
  273. m_context.connection_finished = true;
  274. }
  275. m_context.error_code = (Error)code;
  276. }
  277. break;
  278. default:
  279. dbg() << "message not understood";
  280. return (i8)Error::NotUnderstood;
  281. }
  282. if (payload_res < 0)
  283. return payload_res;
  284. if (res > 0)
  285. return header_size + length;
  286. return res;
  287. }
  288. }