Record.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 length is a multiple of block size, pad it up again
  67. // since it seems no one handles aligned unpadded blocks
  68. size_t padding = 0;
  69. if (length % block_size == 0) {
  70. padding = block_size;
  71. length += padding;
  72. }
  73. size_t mac_size = mac_length();
  74. if (m_context.crypto.created == 1) {
  75. // `buffer' will continue to be encrypted
  76. auto buffer = ByteBuffer::create_zeroed(length);
  77. size_t buffer_position = 0;
  78. u16 aligned_length = length + block_size - length % block_size;
  79. auto iv_size = iv_length();
  80. // we need enough space for a header, iv_length bytes of IV and whatever the packet contains
  81. auto ct = ByteBuffer::create_zeroed(aligned_length + header_size + iv_size);
  82. // copy the header over
  83. ct.overwrite(0, packet.data(), header_size - 2);
  84. // copy the packet, sans the header
  85. buffer.overwrite(buffer_position, packet.offset_pointer(header_size), packet.size() - header_size);
  86. buffer_position += packet.size() - header_size;
  87. // get the appropricate HMAC value for the entire packet
  88. auto mac = hmac_message(packet, {}, mac_size, true);
  89. // write the MAC
  90. buffer.overwrite(buffer_position, mac.data(), mac.size());
  91. buffer_position += mac.size();
  92. // if there's some padding to be done (since a packet MUST always be padded)
  93. // apply it manually
  94. if (padding) {
  95. memset(buffer.offset_pointer(buffer_position), padding - 1, padding);
  96. buffer_position += padding;
  97. }
  98. // should be the same value, but the manual padding
  99. // throws a wrench into our plans
  100. buffer.trim(buffer_position);
  101. // FIXME: REALLY Should be filled with random bytes
  102. auto iv = ByteBuffer::create_zeroed(iv_size);
  103. // write it into the ciphertext portion of the message
  104. ct.overwrite(header_size, iv.data(), iv.size());
  105. ct.trim(length + block_size - length % block_size + header_size + block_size - padding);
  106. // get a block to encrypt into
  107. auto view = ct.slice_view(header_size + iv_size, length + block_size - length % block_size + block_size - padding - iv_size);
  108. // encrypt the message
  109. m_aes_local->encrypt(buffer, view, iv);
  110. // store the correct ciphertext length into the packet
  111. u16 ct_length = (u16)ct.size() - header_size;
  112. *(u16*)ct.offset_pointer(header_size - 2) = convert_between_host_and_network(ct_length);
  113. // replace the packet with the ciphertext
  114. packet = ct;
  115. }
  116. }
  117. }
  118. ++m_context.local_sequence_number;
  119. }
  120. void TLSv12::update_hash(const ByteBuffer& message)
  121. {
  122. m_context.handshake_hash.update(message);
  123. }
  124. ByteBuffer TLSv12::hmac_message(const ByteBuffer& buf, const Optional<ByteBuffer> buf2, size_t mac_length, bool local)
  125. {
  126. u64 sequence_number = convert_between_host_and_network(local ? m_context.local_sequence_number : m_context.remote_sequence_number);
  127. ensure_hmac(mac_length, local);
  128. auto& hmac = local ? *m_hmac_local : *m_hmac_remote;
  129. #ifdef TLS_DEBUG
  130. dbg() << "========================= PACKET DATA ==========================";
  131. print_buffer((const u8*)&sequence_number, sizeof(u64));
  132. print_buffer(buf);
  133. if (buf2.has_value())
  134. print_buffer(buf2.value());
  135. dbg() << "========================= PACKET DATA ==========================";
  136. #endif
  137. hmac.update((const u8*)&sequence_number, sizeof(u64));
  138. hmac.update(buf);
  139. if (buf2.has_value() && buf2.value().size()) {
  140. hmac.update(buf2.value());
  141. }
  142. auto digest = hmac.digest();
  143. auto mac = ByteBuffer::copy(digest.immutable_data(), digest.data_length());
  144. #ifdef TLS_DEBUG
  145. dbg() << "HMAC of the block for sequence number " << m_context.local_sequence_number;
  146. print_buffer(mac);
  147. #endif
  148. return mac;
  149. }
  150. ssize_t TLSv12::handle_message(const ByteBuffer& buffer)
  151. {
  152. auto res { 5ll };
  153. size_t header_size = res;
  154. ssize_t payload_res = 0;
  155. #ifdef TLS_DEBUG
  156. dbg() << "buffer size: " << buffer.size();
  157. #endif
  158. if (buffer.size() < 5) {
  159. return (i8)Error::NeedMoreData;
  160. }
  161. auto type = (MessageType)buffer[0];
  162. size_t buffer_position { 1 };
  163. // FIXME: Read the version and verify it
  164. #ifdef TLS_DEBUG
  165. auto version = (Version) * (const u16*)buffer.offset_pointer(buffer_position);
  166. dbg() << "type: " << (u8)type << " version: " << (u16)version;
  167. #endif
  168. buffer_position += 2;
  169. auto length = convert_between_host_and_network(*(const u16*)buffer.offset_pointer(buffer_position));
  170. #ifdef TLS_DEBUG
  171. dbg() << "record length: " << length << " at offset: " << buffer_position;
  172. #endif
  173. buffer_position += 2;
  174. if (buffer_position + length > buffer.size()) {
  175. #ifdef TLS_DEBUG
  176. dbg() << "record length more than what we have: " << buffer.size();
  177. #endif
  178. return (i8)Error::NeedMoreData;
  179. }
  180. #ifdef TLS_DEBUG
  181. dbg() << "message type: " << (u8)type << ", length: " << length;
  182. #endif
  183. ByteBuffer plain = buffer.slice_view(buffer_position, buffer.size() - buffer_position);
  184. if (m_context.cipher_spec_set && type != MessageType::ChangeCipher) {
  185. #ifdef TLS_DEBUG
  186. dbg() << "Encrypted: ";
  187. print_buffer(buffer.slice_view(header_size, length));
  188. #endif
  189. ASSERT(m_aes_remote);
  190. auto iv_size = iv_length();
  191. auto decrypted = m_aes_remote->create_aligned_buffer(length - iv_size);
  192. auto iv = buffer.slice_view(header_size, iv_size);
  193. m_aes_remote->decrypt(buffer.slice_view(header_size + iv_size, length - iv_size), decrypted, iv);
  194. length = decrypted.size();
  195. #ifdef TLS_DEBUG
  196. dbg() << "Decrypted: ";
  197. print_buffer(decrypted);
  198. #endif
  199. auto mac_size = mac_length();
  200. if (length < mac_size) {
  201. dbg() << "broken packet";
  202. auto packet = build_alert(true, (u8)AlertDescription::DecryptError);
  203. write_packet(packet);
  204. return (i8)Error::BrokenPacket;
  205. }
  206. const u8* message_hmac = decrypted.offset_pointer(length - mac_size);
  207. u8 temp_buf[5];
  208. memcpy(temp_buf, buffer.offset_pointer(0), 3);
  209. *(u16*)(temp_buf + 3) = convert_between_host_and_network(length);
  210. auto hmac = hmac_message(ByteBuffer::wrap(temp_buf, 5), decrypted, mac_size);
  211. auto message_mac = ByteBuffer::wrap(message_hmac, mac_size);
  212. if (hmac != message_mac) {
  213. dbg() << "integrity check failed (mac length " << length << ")";
  214. dbg() << "mac received:";
  215. print_buffer(message_mac);
  216. dbg() << "mac computed:";
  217. print_buffer(hmac);
  218. auto packet = build_alert(true, (u8)AlertDescription::BadRecordMAC);
  219. write_packet(packet);
  220. return (i8)Error::IntegrityCheckFailed;
  221. }
  222. plain = decrypted.slice(0, length - mac_size);
  223. }
  224. m_context.remote_sequence_number++;
  225. switch (type) {
  226. case MessageType::ApplicationData:
  227. if (m_context.connection_status != ConnectionStatus::Established) {
  228. dbg() << "unexpected application data";
  229. payload_res = (i8)Error::UnexpectedMessage;
  230. auto packet = build_alert(true, (u8)AlertDescription::UnexpectedMessage);
  231. write_packet(packet);
  232. } else {
  233. #ifdef TLS_DEBUG
  234. dbg() << "application data message of size " << plain.size();
  235. #endif
  236. m_context.application_buffer.append(plain.data(), plain.size());
  237. }
  238. break;
  239. case MessageType::Handshake:
  240. #ifdef TLS_DEBUG
  241. dbg() << "tls handshake message";
  242. #endif
  243. payload_res = handle_payload(plain);
  244. break;
  245. case MessageType::ChangeCipher:
  246. if (m_context.connection_status != ConnectionStatus::KeyExchange) {
  247. dbg() << "unexpected change cipher message";
  248. auto packet = build_alert(true, (u8)AlertDescription::UnexpectedMessage);
  249. payload_res = (i8)Error::UnexpectedMessage;
  250. } else {
  251. #ifdef TLS_DEBUG
  252. dbg() << "change cipher spec message";
  253. #endif
  254. m_context.cipher_spec_set = true;
  255. m_context.remote_sequence_number = 0;
  256. }
  257. break;
  258. case MessageType::Alert:
  259. dbg() << "alert message of length " << length;
  260. if (length >= 2) {
  261. print_buffer(plain);
  262. auto level = plain[0];
  263. auto code = plain[1];
  264. if (level == (u8)AlertLevel::Critical) {
  265. dbg() << "We were alerted of a critical error: " << code << " (" << alert_name((AlertDescription)code) << ")";
  266. m_context.critical_error = code;
  267. try_disambiguate_error();
  268. res = (i8)Error::UnknownError;
  269. } else {
  270. dbg() << "Alert: " << code;
  271. }
  272. if (code == 0) {
  273. // close notify
  274. res += 2;
  275. alert(AlertLevel::Critical, AlertDescription::CloseNotify);
  276. m_context.connection_finished = true;
  277. }
  278. m_context.error_code = (Error)code;
  279. }
  280. break;
  281. default:
  282. dbg() << "message not understood";
  283. return (i8)Error::NotUnderstood;
  284. }
  285. if (payload_res < 0)
  286. return payload_res;
  287. if (res > 0)
  288. return header_size + length;
  289. return res;
  290. }
  291. }