Handshake.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. * Copyright (c) 2022, Michiel Visser <opensource@webmichiel.nl>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/Random.h>
  10. #include <LibCore/Timer.h>
  11. #include <LibCrypto/ASN1/DER.h>
  12. #include <LibTLS/TLSv12.h>
  13. namespace TLS {
  14. ByteBuffer TLSv12::build_hello()
  15. {
  16. fill_with_random(m_context.local_random);
  17. auto packet_version = (u16)m_context.options.version;
  18. auto version = (u16)m_context.options.version;
  19. PacketBuilder builder { ContentType::HANDSHAKE, packet_version };
  20. builder.append(to_underlying(HandshakeType::CLIENT_HELLO));
  21. // hello length (for later)
  22. u8 dummy[3] = {};
  23. builder.append(dummy, 3);
  24. auto start_length = builder.length();
  25. builder.append(version);
  26. builder.append(m_context.local_random, sizeof(m_context.local_random));
  27. builder.append(m_context.session_id_size);
  28. if (m_context.session_id_size)
  29. builder.append(m_context.session_id, m_context.session_id_size);
  30. size_t extension_length = 0;
  31. size_t alpn_length = 0;
  32. size_t alpn_negotiated_length = 0;
  33. // ALPN
  34. if (!m_context.negotiated_alpn.is_empty()) {
  35. alpn_negotiated_length = m_context.negotiated_alpn.length();
  36. alpn_length = alpn_negotiated_length + 1;
  37. extension_length += alpn_length + 6;
  38. } else if (m_context.alpn.size()) {
  39. for (auto& alpn : m_context.alpn) {
  40. size_t length = alpn.length();
  41. alpn_length += length + 1;
  42. }
  43. if (alpn_length)
  44. extension_length += alpn_length + 6;
  45. }
  46. // Ciphers
  47. builder.append((u16)(m_context.options.usable_cipher_suites.size() * sizeof(u16)));
  48. for (auto suite : m_context.options.usable_cipher_suites)
  49. builder.append((u16)suite);
  50. // we don't like compression
  51. VERIFY(!m_context.options.use_compression);
  52. builder.append((u8)1);
  53. builder.append((u8)m_context.options.use_compression);
  54. // set SNI if we have one, and the user hasn't explicitly asked us to omit it.
  55. auto sni_length = 0;
  56. if (!m_context.extensions.SNI.is_empty() && m_context.options.use_sni)
  57. sni_length = m_context.extensions.SNI.length();
  58. auto elliptic_curves_length = 2 * m_context.options.elliptic_curves.size();
  59. auto supported_ec_point_formats_length = m_context.options.supported_ec_point_formats.size();
  60. bool supports_elliptic_curves = elliptic_curves_length && supported_ec_point_formats_length;
  61. bool enable_extended_master_secret = m_context.options.enable_extended_master_secret;
  62. // signature_algorithms: 2b extension ID, 2b extension length, 2b vector length, 2xN signatures and hashes
  63. extension_length += 2 + 2 + 2 + 2 * m_context.options.supported_signature_algorithms.size();
  64. if (sni_length)
  65. extension_length += sni_length + 9;
  66. // Only send elliptic_curves and ec_point_formats extensions if both are supported
  67. if (supports_elliptic_curves)
  68. extension_length += 6 + elliptic_curves_length + 5 + supported_ec_point_formats_length;
  69. if (enable_extended_master_secret)
  70. extension_length += 4;
  71. builder.append((u16)extension_length);
  72. if (sni_length) {
  73. // SNI extension
  74. builder.append((u16)ExtensionType::SERVER_NAME);
  75. // extension length
  76. builder.append((u16)(sni_length + 5));
  77. // SNI length
  78. builder.append((u16)(sni_length + 3));
  79. // SNI type
  80. builder.append((u8)0);
  81. // SNI host length + value
  82. builder.append((u16)sni_length);
  83. builder.append((u8 const*)m_context.extensions.SNI.characters(), sni_length);
  84. }
  85. // signature_algorithms extension
  86. builder.append((u16)ExtensionType::SIGNATURE_ALGORITHMS);
  87. // Extension length
  88. builder.append((u16)(2 + 2 * m_context.options.supported_signature_algorithms.size()));
  89. // Vector count
  90. builder.append((u16)(m_context.options.supported_signature_algorithms.size() * 2));
  91. // Entries
  92. for (auto& entry : m_context.options.supported_signature_algorithms) {
  93. builder.append((u8)entry.hash);
  94. builder.append((u8)entry.signature);
  95. }
  96. if (supports_elliptic_curves) {
  97. // elliptic_curves extension
  98. builder.append((u16)ExtensionType::SUPPORTED_GROUPS);
  99. builder.append((u16)(2 + elliptic_curves_length));
  100. builder.append((u16)elliptic_curves_length);
  101. for (auto& curve : m_context.options.elliptic_curves)
  102. builder.append((u16)curve);
  103. // ec_point_formats extension
  104. builder.append((u16)ExtensionType::EC_POINT_FORMATS);
  105. builder.append((u16)(1 + supported_ec_point_formats_length));
  106. builder.append((u8)supported_ec_point_formats_length);
  107. for (auto& format : m_context.options.supported_ec_point_formats)
  108. builder.append((u8)format);
  109. }
  110. if (enable_extended_master_secret) {
  111. // extended_master_secret extension
  112. builder.append((u16)ExtensionType::EXTENDED_MASTER_SECRET);
  113. builder.append((u16)0);
  114. }
  115. if (alpn_length) {
  116. // TODO
  117. VERIFY_NOT_REACHED();
  118. }
  119. // set the "length" field of the packet
  120. size_t remaining = builder.length() - start_length;
  121. size_t payload_position = 6;
  122. builder.set(payload_position, remaining / 0x10000);
  123. remaining %= 0x10000;
  124. builder.set(payload_position + 1, remaining / 0x100);
  125. remaining %= 0x100;
  126. builder.set(payload_position + 2, remaining);
  127. auto packet = builder.build();
  128. update_packet(packet);
  129. return packet;
  130. }
  131. ByteBuffer TLSv12::build_change_cipher_spec()
  132. {
  133. PacketBuilder builder { ContentType::CHANGE_CIPHER_SPEC, m_context.options.version, 64 };
  134. builder.append((u8)1);
  135. auto packet = builder.build();
  136. update_packet(packet);
  137. m_context.local_sequence_number = 0;
  138. return packet;
  139. }
  140. ByteBuffer TLSv12::build_handshake_finished()
  141. {
  142. PacketBuilder builder { ContentType::HANDSHAKE, m_context.options.version, 12 + 64 };
  143. builder.append((u8)HandshakeType::FINISHED);
  144. // RFC 5246 section 7.4.9: "In previous versions of TLS, the verify_data was always 12 octets
  145. // long. In the current version of TLS, it depends on the cipher
  146. // suite. Any cipher suite which does not explicitly specify
  147. // verify_data_length has a verify_data_length equal to 12."
  148. // Simplification: Assume that verify_data_length is always 12.
  149. constexpr u32 verify_data_length = 12;
  150. builder.append_u24(verify_data_length);
  151. u8 out[verify_data_length];
  152. auto outbuffer = Bytes { out, verify_data_length };
  153. ByteBuffer dummy;
  154. auto digest = m_context.handshake_hash.digest();
  155. auto hashbuf = ReadonlyBytes { digest.immutable_data(), m_context.handshake_hash.digest_size() };
  156. pseudorandom_function(outbuffer, m_context.master_key, (u8 const*)"client finished", 15, hashbuf, dummy);
  157. builder.append(outbuffer);
  158. auto packet = builder.build();
  159. update_packet(packet);
  160. return packet;
  161. }
  162. ssize_t TLSv12::handle_handshake_finished(ReadonlyBytes buffer, WritePacketStage& write_packets)
  163. {
  164. if (m_context.connection_status < ConnectionStatus::KeyExchange || m_context.connection_status == ConnectionStatus::Established) {
  165. dbgln("unexpected finished message");
  166. return (i8)Error::UnexpectedMessage;
  167. }
  168. write_packets = WritePacketStage::Initial;
  169. if (buffer.size() < 3) {
  170. return (i8)Error::NeedMoreData;
  171. }
  172. size_t index = 3;
  173. u32 size = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
  174. if (size < 12) {
  175. dbgln_if(TLS_DEBUG, "finished packet smaller than minimum size: {}", size);
  176. return (i8)Error::BrokenPacket;
  177. }
  178. if (size < buffer.size() - index) {
  179. dbgln_if(TLS_DEBUG, "not enough data after length: {} > {}", size, buffer.size() - index);
  180. return (i8)Error::NeedMoreData;
  181. }
  182. // TODO: Compare Hashes
  183. dbgln_if(TLS_DEBUG, "FIXME: handle_handshake_finished :: Check message validity");
  184. m_context.connection_status = ConnectionStatus::Established;
  185. if (m_handshake_timeout_timer) {
  186. // Disable the handshake timeout timer as handshake has been established.
  187. m_handshake_timeout_timer->stop();
  188. m_handshake_timeout_timer->remove_from_parent();
  189. m_handshake_timeout_timer = nullptr;
  190. }
  191. if (on_connected)
  192. on_connected();
  193. return index + size;
  194. }
  195. ssize_t TLSv12::handle_handshake_payload(ReadonlyBytes vbuffer)
  196. {
  197. if (m_context.connection_status == ConnectionStatus::Established) {
  198. dbgln_if(TLS_DEBUG, "Renegotiation attempt ignored");
  199. // FIXME: We should properly say "NoRenegotiation", but that causes a handshake failure
  200. // so we just roll with it and pretend that we _did_ renegotiate
  201. // This will cause issues when we decide to have long-lasting connections, but
  202. // we do not have those at the moment :^)
  203. return 1;
  204. }
  205. auto buffer = vbuffer;
  206. auto buffer_length = buffer.size();
  207. auto original_length = buffer_length;
  208. while (buffer_length >= 4 && !m_context.critical_error) {
  209. ssize_t payload_res = 0;
  210. if (buffer_length < 1)
  211. return (i8)Error::NeedMoreData;
  212. auto type = static_cast<HandshakeType>(buffer[0]);
  213. auto write_packets { WritePacketStage::Initial };
  214. size_t payload_size = buffer[1] * 0x10000 + buffer[2] * 0x100 + buffer[3] + 3;
  215. dbgln_if(TLS_DEBUG, "payload size: {} buffer length: {}", payload_size, buffer_length);
  216. if (payload_size + 1 > buffer_length)
  217. return (i8)Error::NeedMoreData;
  218. switch (type) {
  219. case HandshakeType::HELLO_REQUEST_RESERVED:
  220. if (m_context.handshake_messages[0] >= 1) {
  221. dbgln("unexpected hello request message");
  222. payload_res = (i8)Error::UnexpectedMessage;
  223. break;
  224. }
  225. ++m_context.handshake_messages[0];
  226. dbgln("hello request (renegotiation?)");
  227. if (m_context.connection_status == ConnectionStatus::Established) {
  228. // renegotiation
  229. payload_res = (i8)Error::NoRenegotiation;
  230. } else {
  231. // :shrug:
  232. payload_res = (i8)Error::UnexpectedMessage;
  233. }
  234. break;
  235. case HandshakeType::CLIENT_HELLO:
  236. // FIXME: We only support client mode right now
  237. if (m_context.is_server) {
  238. VERIFY_NOT_REACHED();
  239. }
  240. payload_res = (i8)Error::UnexpectedMessage;
  241. break;
  242. case HandshakeType::SERVER_HELLO:
  243. if (m_context.handshake_messages[2] >= 1) {
  244. dbgln("unexpected server hello message");
  245. payload_res = (i8)Error::UnexpectedMessage;
  246. break;
  247. }
  248. ++m_context.handshake_messages[2];
  249. dbgln_if(TLS_DEBUG, "server hello");
  250. if (m_context.is_server) {
  251. dbgln("unsupported: server mode");
  252. VERIFY_NOT_REACHED();
  253. }
  254. payload_res = handle_server_hello(buffer.slice(1, payload_size), write_packets);
  255. break;
  256. case HandshakeType::HELLO_VERIFY_REQUEST_RESERVED:
  257. dbgln("unsupported: DTLS");
  258. payload_res = (i8)Error::UnexpectedMessage;
  259. break;
  260. case HandshakeType::CERTIFICATE:
  261. if (m_context.handshake_messages[4] >= 1) {
  262. dbgln("unexpected certificate message");
  263. payload_res = (i8)Error::UnexpectedMessage;
  264. break;
  265. }
  266. ++m_context.handshake_messages[4];
  267. dbgln_if(TLS_DEBUG, "certificate");
  268. if (m_context.connection_status == ConnectionStatus::Negotiating) {
  269. if (m_context.is_server) {
  270. dbgln("unsupported: server mode");
  271. VERIFY_NOT_REACHED();
  272. }
  273. payload_res = handle_certificate(buffer.slice(1, payload_size));
  274. } else {
  275. payload_res = (i8)Error::UnexpectedMessage;
  276. }
  277. break;
  278. case HandshakeType::SERVER_KEY_EXCHANGE_RESERVED:
  279. if (m_context.handshake_messages[5] >= 1) {
  280. dbgln("unexpected server key exchange message");
  281. payload_res = (i8)Error::UnexpectedMessage;
  282. break;
  283. }
  284. ++m_context.handshake_messages[5];
  285. dbgln_if(TLS_DEBUG, "server key exchange");
  286. if (m_context.is_server) {
  287. dbgln("unsupported: server mode");
  288. VERIFY_NOT_REACHED();
  289. } else {
  290. payload_res = handle_server_key_exchange(buffer.slice(1, payload_size));
  291. }
  292. break;
  293. case HandshakeType::CERTIFICATE_REQUEST:
  294. if (m_context.handshake_messages[6] >= 1) {
  295. dbgln("unexpected certificate request message");
  296. payload_res = (i8)Error::UnexpectedMessage;
  297. break;
  298. }
  299. ++m_context.handshake_messages[6];
  300. if (m_context.is_server) {
  301. dbgln("invalid request");
  302. dbgln("unsupported: server mode");
  303. VERIFY_NOT_REACHED();
  304. } else {
  305. // we do not support "certificate request"
  306. dbgln("certificate request");
  307. if (on_tls_certificate_request)
  308. on_tls_certificate_request(*this);
  309. m_context.client_verified = VerificationNeeded;
  310. }
  311. break;
  312. case HandshakeType::SERVER_HELLO_DONE_RESERVED:
  313. if (m_context.handshake_messages[7] >= 1) {
  314. dbgln("unexpected server hello done message");
  315. payload_res = (i8)Error::UnexpectedMessage;
  316. break;
  317. }
  318. ++m_context.handshake_messages[7];
  319. dbgln_if(TLS_DEBUG, "server hello done");
  320. if (m_context.is_server) {
  321. dbgln("unsupported: server mode");
  322. VERIFY_NOT_REACHED();
  323. } else {
  324. payload_res = handle_server_hello_done(buffer.slice(1, payload_size));
  325. if (payload_res > 0)
  326. write_packets = WritePacketStage::ClientHandshake;
  327. }
  328. break;
  329. case HandshakeType::CERTIFICATE_VERIFY:
  330. if (m_context.handshake_messages[8] >= 1) {
  331. dbgln("unexpected certificate verify message");
  332. payload_res = (i8)Error::UnexpectedMessage;
  333. break;
  334. }
  335. ++m_context.handshake_messages[8];
  336. dbgln_if(TLS_DEBUG, "certificate verify");
  337. if (m_context.connection_status == ConnectionStatus::KeyExchange) {
  338. payload_res = handle_certificate_verify(buffer.slice(1, payload_size));
  339. } else {
  340. payload_res = (i8)Error::UnexpectedMessage;
  341. }
  342. break;
  343. case HandshakeType::CLIENT_KEY_EXCHANGE_RESERVED:
  344. if (m_context.handshake_messages[9] >= 1) {
  345. dbgln("unexpected client key exchange message");
  346. payload_res = (i8)Error::UnexpectedMessage;
  347. break;
  348. }
  349. ++m_context.handshake_messages[9];
  350. dbgln_if(TLS_DEBUG, "client key exchange");
  351. if (m_context.is_server) {
  352. dbgln("unsupported: server mode");
  353. VERIFY_NOT_REACHED();
  354. } else {
  355. payload_res = (i8)Error::UnexpectedMessage;
  356. }
  357. break;
  358. case HandshakeType::FINISHED:
  359. m_context.cached_handshake.clear();
  360. if (m_context.handshake_messages[10] >= 1) {
  361. dbgln("unexpected finished message");
  362. payload_res = (i8)Error::UnexpectedMessage;
  363. break;
  364. }
  365. ++m_context.handshake_messages[10];
  366. dbgln_if(TLS_DEBUG, "finished");
  367. payload_res = handle_handshake_finished(buffer.slice(1, payload_size), write_packets);
  368. if (payload_res > 0) {
  369. memset(m_context.handshake_messages, 0, sizeof(m_context.handshake_messages));
  370. }
  371. break;
  372. default:
  373. dbgln("message type not understood: {}", enum_to_string(type));
  374. return (i8)Error::NotUnderstood;
  375. }
  376. if (type != HandshakeType::HELLO_REQUEST_RESERVED) {
  377. update_hash(buffer.slice(0, payload_size + 1), 0);
  378. }
  379. // if something went wrong, send an alert about it
  380. if (payload_res < 0) {
  381. switch ((Error)payload_res) {
  382. case Error::UnexpectedMessage: {
  383. auto packet = build_alert(true, (u8)AlertDescription::UNEXPECTED_MESSAGE);
  384. write_packet(packet);
  385. break;
  386. }
  387. case Error::CompressionNotSupported: {
  388. auto packet = build_alert(true, (u8)AlertDescription::DECOMPRESSION_FAILURE_RESERVED);
  389. write_packet(packet);
  390. break;
  391. }
  392. case Error::BrokenPacket: {
  393. auto packet = build_alert(true, (u8)AlertDescription::DECODE_ERROR);
  394. write_packet(packet);
  395. break;
  396. }
  397. case Error::NotVerified: {
  398. auto packet = build_alert(true, (u8)AlertDescription::BAD_RECORD_MAC);
  399. write_packet(packet);
  400. break;
  401. }
  402. case Error::BadCertificate: {
  403. auto packet = build_alert(true, (u8)AlertDescription::BAD_CERTIFICATE);
  404. write_packet(packet);
  405. break;
  406. }
  407. case Error::UnsupportedCertificate: {
  408. auto packet = build_alert(true, (u8)AlertDescription::UNSUPPORTED_CERTIFICATE);
  409. write_packet(packet);
  410. break;
  411. }
  412. case Error::NoCommonCipher: {
  413. auto packet = build_alert(true, (u8)AlertDescription::INSUFFICIENT_SECURITY);
  414. write_packet(packet);
  415. break;
  416. }
  417. case Error::NotUnderstood:
  418. case Error::OutOfMemory: {
  419. auto packet = build_alert(true, (u8)AlertDescription::INTERNAL_ERROR);
  420. write_packet(packet);
  421. break;
  422. }
  423. case Error::NoRenegotiation: {
  424. auto packet = build_alert(true, (u8)AlertDescription::NO_RENEGOTIATION_RESERVED);
  425. write_packet(packet);
  426. break;
  427. }
  428. case Error::DecryptionFailed: {
  429. auto packet = build_alert(true, (u8)AlertDescription::DECRYPTION_FAILED_RESERVED);
  430. write_packet(packet);
  431. break;
  432. }
  433. case Error::NotSafe: {
  434. auto packet = build_alert(true, (u8)AlertDescription::DECRYPT_ERROR);
  435. write_packet(packet);
  436. break;
  437. }
  438. case Error::NeedMoreData:
  439. // Ignore this, as it's not an "error"
  440. dbgln_if(TLS_DEBUG, "More data needed");
  441. break;
  442. default:
  443. dbgln("Unknown TLS::Error with value {}", payload_res);
  444. VERIFY_NOT_REACHED();
  445. break;
  446. }
  447. if (payload_res < 0)
  448. return payload_res;
  449. }
  450. switch (write_packets) {
  451. case WritePacketStage::Initial:
  452. // nothing to write
  453. break;
  454. case WritePacketStage::ClientHandshake:
  455. if (m_context.client_verified == VerificationNeeded) {
  456. dbgln_if(TLS_DEBUG, "> Client Certificate");
  457. auto packet = build_certificate();
  458. write_packet(packet);
  459. m_context.client_verified = Verified;
  460. }
  461. {
  462. dbgln_if(TLS_DEBUG, "> Key exchange");
  463. auto packet = build_client_key_exchange();
  464. write_packet(packet);
  465. }
  466. {
  467. dbgln_if(TLS_DEBUG, "> change cipher spec");
  468. auto packet = build_change_cipher_spec();
  469. write_packet(packet);
  470. }
  471. m_context.cipher_spec_set = 1;
  472. m_context.local_sequence_number = 0;
  473. {
  474. dbgln_if(TLS_DEBUG, "> client finished");
  475. auto packet = build_handshake_finished();
  476. write_packet(packet);
  477. }
  478. m_context.cipher_spec_set = 0;
  479. break;
  480. case WritePacketStage::ServerHandshake:
  481. // server handshake
  482. dbgln("UNSUPPORTED: Server mode");
  483. VERIFY_NOT_REACHED();
  484. break;
  485. case WritePacketStage::Finished:
  486. // finished
  487. {
  488. dbgln_if(TLS_DEBUG, "> change cipher spec");
  489. auto packet = build_change_cipher_spec();
  490. write_packet(packet);
  491. }
  492. {
  493. dbgln_if(TLS_DEBUG, "> client finished");
  494. auto packet = build_handshake_finished();
  495. write_packet(packet);
  496. }
  497. m_context.connection_status = ConnectionStatus::Established;
  498. break;
  499. }
  500. payload_size++;
  501. buffer_length -= payload_size;
  502. buffer = buffer.slice(payload_size, buffer_length);
  503. }
  504. return original_length;
  505. }
  506. }