Handshake.cpp 21 KB

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