ClientHandshake.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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 <AK/Endian.h>
  27. #include <AK/Random.h>
  28. #include <LibCore/Timer.h>
  29. #include <LibCrypto/ASN1/DER.h>
  30. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  31. #include <LibTLS/TLSv12.h>
  32. namespace TLS {
  33. ssize_t TLSv12::handle_server_hello_done(ReadonlyBytes buffer)
  34. {
  35. if (buffer.size() < 3)
  36. return (i8)Error::NeedMoreData;
  37. size_t size = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
  38. if (buffer.size() - 3 < size)
  39. return (i8)Error::NeedMoreData;
  40. return size + 3;
  41. }
  42. ssize_t TLSv12::handle_hello(ReadonlyBytes buffer, WritePacketStage& write_packets)
  43. {
  44. write_packets = WritePacketStage::Initial;
  45. if (m_context.connection_status != ConnectionStatus::Disconnected && m_context.connection_status != ConnectionStatus::Renegotiating) {
  46. dbgln("unexpected hello message");
  47. return (i8)Error::UnexpectedMessage;
  48. }
  49. ssize_t res = 0;
  50. size_t min_hello_size = 41;
  51. if (min_hello_size > buffer.size()) {
  52. dbgln("need more data");
  53. return (i8)Error::NeedMoreData;
  54. }
  55. size_t following_bytes = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
  56. res += 3;
  57. if (buffer.size() - res < following_bytes) {
  58. dbgln("not enough data after header: {} < {}", buffer.size() - res, following_bytes);
  59. return (i8)Error::NeedMoreData;
  60. }
  61. if (buffer.size() - res < 2) {
  62. dbgln("not enough data for version");
  63. return (i8)Error::NeedMoreData;
  64. }
  65. auto version = (Version)AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res));
  66. res += 2;
  67. if (!supports_version(version))
  68. return (i8)Error::NotSafe;
  69. memcpy(m_context.remote_random, buffer.offset_pointer(res), sizeof(m_context.remote_random));
  70. res += sizeof(m_context.remote_random);
  71. u8 session_length = buffer[res++];
  72. if (buffer.size() - res < session_length) {
  73. dbgln("not enough data for session id");
  74. return (i8)Error::NeedMoreData;
  75. }
  76. if (session_length && session_length <= 32) {
  77. memcpy(m_context.session_id, buffer.offset_pointer(res), session_length);
  78. m_context.session_id_size = session_length;
  79. #ifdef TLS_DEBUG
  80. dbgln("Remote session ID:");
  81. print_buffer(ReadonlyBytes { m_context.session_id, session_length });
  82. #endif
  83. } else {
  84. m_context.session_id_size = 0;
  85. }
  86. res += session_length;
  87. if (buffer.size() - res < 2) {
  88. dbgln("not enough data for cipher suite listing");
  89. return (i8)Error::NeedMoreData;
  90. }
  91. auto cipher = (CipherSuite)AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res));
  92. res += 2;
  93. if (!supports_cipher(cipher)) {
  94. m_context.cipher = CipherSuite::Invalid;
  95. dbgln("No supported cipher could be agreed upon");
  96. return (i8)Error::NoCommonCipher;
  97. }
  98. m_context.cipher = cipher;
  99. #ifdef TLS_DEBUG
  100. dbg() << "Cipher: " << (u16)cipher;
  101. #endif
  102. // The handshake hash function is _always_ SHA256
  103. m_context.handshake_hash.initialize(Crypto::Hash::HashKind::SHA256);
  104. if (buffer.size() - res < 1) {
  105. dbgln("not enough data for compression spec");
  106. return (i8)Error::NeedMoreData;
  107. }
  108. u8 compression = buffer[res++];
  109. if (compression != 0) {
  110. dbgln("Server told us to compress, we will not!");
  111. return (i8)Error::CompressionNotSupported;
  112. }
  113. if (res > 0) {
  114. if (m_context.connection_status != ConnectionStatus::Renegotiating)
  115. m_context.connection_status = ConnectionStatus::Negotiating;
  116. if (m_context.is_server) {
  117. dbgln("unsupported: server mode");
  118. write_packets = WritePacketStage::ServerHandshake;
  119. }
  120. }
  121. if (res > 2) {
  122. res += 2;
  123. }
  124. while ((ssize_t)buffer.size() - res >= 4) {
  125. auto extension_type = (HandshakeExtension)AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res));
  126. res += 2;
  127. u16 extension_length = AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res));
  128. res += 2;
  129. #ifdef TLS_DEBUG
  130. dbg() << "extension " << (u16)extension_type << " with length " << extension_length;
  131. #endif
  132. if (extension_length) {
  133. if (buffer.size() - res < extension_length) {
  134. dbgln("not enough data for extension");
  135. return (i8)Error::NeedMoreData;
  136. }
  137. // SNI
  138. if (extension_type == HandshakeExtension::ServerName) {
  139. u16 sni_host_length = AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res + 3));
  140. if (buffer.size() - res - 5 < sni_host_length) {
  141. dbgln("Not enough data for sni {} < {}", (buffer.size() - res - 5), sni_host_length);
  142. return (i8)Error::NeedMoreData;
  143. }
  144. if (sni_host_length) {
  145. m_context.SNI = String { (const char*)buffer.offset_pointer(res + 5), sni_host_length };
  146. dbgln("server name indicator: {}", m_context.SNI);
  147. }
  148. } else if (extension_type == HandshakeExtension::ApplicationLayerProtocolNegotiation && m_context.alpn.size()) {
  149. if (buffer.size() - res > 2) {
  150. auto alpn_length = AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res));
  151. if (alpn_length && alpn_length <= extension_length - 2) {
  152. const u8* alpn = buffer.offset_pointer(res + 2);
  153. size_t alpn_position = 0;
  154. while (alpn_position < alpn_length) {
  155. u8 alpn_size = alpn[alpn_position++];
  156. if (alpn_size + alpn_position >= extension_length)
  157. break;
  158. String alpn_str { (const char*)alpn + alpn_position, alpn_length };
  159. if (alpn_size && m_context.alpn.contains_slow(alpn_str)) {
  160. m_context.negotiated_alpn = alpn_str;
  161. dbgln("negotiated alpn: {}", alpn_str);
  162. break;
  163. }
  164. alpn_position += alpn_length;
  165. if (!m_context.is_server) // server hello must contain one ALPN
  166. break;
  167. }
  168. }
  169. }
  170. } else if (extension_type == HandshakeExtension::SignatureAlgorithms) {
  171. dbgln("supported signatures: ");
  172. print_buffer(buffer.slice(res, extension_length));
  173. // FIXME: what are we supposed to do here?
  174. }
  175. res += extension_length;
  176. }
  177. }
  178. return res;
  179. }
  180. ssize_t TLSv12::handle_finished(ReadonlyBytes buffer, WritePacketStage& write_packets)
  181. {
  182. if (m_context.connection_status < ConnectionStatus::KeyExchange || m_context.connection_status == ConnectionStatus::Established) {
  183. dbgln("unexpected finished message");
  184. return (i8)Error::UnexpectedMessage;
  185. }
  186. write_packets = WritePacketStage::Initial;
  187. if (buffer.size() < 3) {
  188. return (i8)Error::NeedMoreData;
  189. }
  190. size_t index = 3;
  191. u32 size = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
  192. if (size < 12) {
  193. #ifdef TLS_DEBUG
  194. dbg() << "finished packet smaller than minimum size: " << size;
  195. #endif
  196. return (i8)Error::BrokenPacket;
  197. }
  198. if (size < buffer.size() - index) {
  199. #ifdef TLS_DEBUG
  200. dbg() << "not enough data after length: " << size << " > " << buffer.size() - index;
  201. #endif
  202. return (i8)Error::NeedMoreData;
  203. }
  204. // TODO: Compare Hashes
  205. #ifdef TLS_DEBUG
  206. dbgln("FIXME: handle_finished :: Check message validity");
  207. #endif
  208. m_context.connection_status = ConnectionStatus::Established;
  209. if (m_handshake_timeout_timer) {
  210. // Disable the handshake timeout timer as handshake has been established.
  211. m_handshake_timeout_timer->stop();
  212. m_handshake_timeout_timer->remove_from_parent();
  213. m_handshake_timeout_timer = nullptr;
  214. }
  215. if (on_tls_ready_to_write)
  216. on_tls_ready_to_write(*this);
  217. return index + size;
  218. }
  219. void TLSv12::build_random(PacketBuilder& builder)
  220. {
  221. u8 random_bytes[48];
  222. size_t bytes = 48;
  223. AK::fill_with_random(random_bytes, bytes);
  224. // remove zeros from the random bytes
  225. for (size_t i = 0; i < bytes; ++i) {
  226. if (!random_bytes[i])
  227. random_bytes[i--] = AK::get_random<u8>();
  228. }
  229. if (m_context.is_server) {
  230. dbgln("Server mode not supported");
  231. return;
  232. } else {
  233. *(u16*)random_bytes = AK::convert_between_host_and_network_endian((u16)Version::V12);
  234. }
  235. m_context.premaster_key = ByteBuffer::copy(random_bytes, bytes);
  236. const auto& certificate_option = verify_chain_and_get_matching_certificate(m_context.SNI); // if the SNI is empty, we'll make a special case and match *a* leaf certificate.
  237. if (!certificate_option.has_value()) {
  238. dbgln("certificate verification failed :(");
  239. alert(AlertLevel::Critical, AlertDescription::BadCertificate);
  240. return;
  241. }
  242. auto& certificate = m_context.certificates[certificate_option.value()];
  243. #ifdef TLS_DEBUG
  244. dbgln("PreMaster secret");
  245. print_buffer(m_context.premaster_key);
  246. #endif
  247. Crypto::PK::RSA_PKCS1_EME rsa(certificate.public_key.modulus(), 0, certificate.public_key.public_exponent());
  248. u8 out[rsa.output_size()];
  249. auto outbuf = Bytes { out, rsa.output_size() };
  250. rsa.encrypt(m_context.premaster_key, outbuf);
  251. #ifdef TLS_DEBUG
  252. dbgln("Encrypted: ");
  253. print_buffer(outbuf);
  254. #endif
  255. if (!compute_master_secret(bytes)) {
  256. dbgln("oh noes we could not derive a master key :(");
  257. return;
  258. }
  259. builder.append_u24(outbuf.size() + 2);
  260. builder.append((u16)outbuf.size());
  261. builder.append(outbuf);
  262. }
  263. ssize_t TLSv12::handle_payload(ReadonlyBytes vbuffer)
  264. {
  265. if (m_context.connection_status == ConnectionStatus::Established) {
  266. #ifdef TLS_DEBUG
  267. dbgln("Renegotiation attempt ignored");
  268. #endif
  269. // FIXME: We should properly say "NoRenegotiation", but that causes a handshake failure
  270. // so we just roll with it and pretend that we _did_ renegotiate
  271. // This will cause issues when we decide to have long-lasting connections, but
  272. // we do not have those at the moment :^)
  273. return 1;
  274. }
  275. auto buffer = vbuffer;
  276. auto buffer_length = buffer.size();
  277. auto original_length = buffer_length;
  278. while (buffer_length >= 4 && !m_context.critical_error) {
  279. ssize_t payload_res = 0;
  280. if (buffer_length < 1)
  281. return (i8)Error::NeedMoreData;
  282. auto type = buffer[0];
  283. auto write_packets { WritePacketStage::Initial };
  284. size_t payload_size = buffer[1] * 0x10000 + buffer[2] * 0x100 + buffer[3] + 3;
  285. #ifdef TLS_DEBUG
  286. dbg() << "payload size: " << payload_size << " buffer length: " << buffer_length;
  287. #endif
  288. if (payload_size + 1 > buffer_length)
  289. return (i8)Error::NeedMoreData;
  290. switch (type) {
  291. case HelloRequest:
  292. if (m_context.handshake_messages[0] >= 1) {
  293. dbgln("unexpected hello request message");
  294. payload_res = (i8)Error::UnexpectedMessage;
  295. break;
  296. }
  297. ++m_context.handshake_messages[0];
  298. dbgln("hello request (renegotiation?)");
  299. if (m_context.connection_status == ConnectionStatus::Established) {
  300. // renegotiation
  301. payload_res = (i8)Error::NoRenegotiation;
  302. } else {
  303. // :shrug:
  304. payload_res = (i8)Error::UnexpectedMessage;
  305. }
  306. break;
  307. case ClientHello:
  308. // FIXME: We only support client mode right now
  309. if (m_context.is_server) {
  310. ASSERT_NOT_REACHED();
  311. }
  312. payload_res = (i8)Error::UnexpectedMessage;
  313. break;
  314. case ServerHello:
  315. if (m_context.handshake_messages[2] >= 1) {
  316. dbgln("unexpected server hello message");
  317. payload_res = (i8)Error::UnexpectedMessage;
  318. break;
  319. }
  320. ++m_context.handshake_messages[2];
  321. #ifdef TLS_DEBUG
  322. dbgln("server hello");
  323. #endif
  324. if (m_context.is_server) {
  325. dbgln("unsupported: server mode");
  326. ASSERT_NOT_REACHED();
  327. } else {
  328. payload_res = handle_hello(buffer.slice(1, payload_size), write_packets);
  329. }
  330. break;
  331. case HelloVerifyRequest:
  332. dbgln("unsupported: DTLS");
  333. payload_res = (i8)Error::UnexpectedMessage;
  334. break;
  335. case CertificateMessage:
  336. if (m_context.handshake_messages[4] >= 1) {
  337. dbgln("unexpected certificate message");
  338. payload_res = (i8)Error::UnexpectedMessage;
  339. break;
  340. }
  341. ++m_context.handshake_messages[4];
  342. #ifdef TLS_DEBUG
  343. dbgln("certificate");
  344. #endif
  345. if (m_context.connection_status == ConnectionStatus::Negotiating) {
  346. if (m_context.is_server) {
  347. dbgln("unsupported: server mode");
  348. ASSERT_NOT_REACHED();
  349. }
  350. payload_res = handle_certificate(buffer.slice(1, payload_size));
  351. if (m_context.certificates.size()) {
  352. auto it = m_context.certificates.find_if([](const auto& cert) { return cert.is_valid(); });
  353. if (it.is_end()) {
  354. // no valid certificates
  355. dbgln("No valid certificates found");
  356. payload_res = (i8)Error::BadCertificate;
  357. m_context.critical_error = payload_res;
  358. break;
  359. }
  360. // swap the first certificate with the valid one
  361. if (it.index() != 0)
  362. swap(m_context.certificates[0], m_context.certificates[it.index()]);
  363. }
  364. } else {
  365. payload_res = (i8)Error::UnexpectedMessage;
  366. }
  367. break;
  368. case ServerKeyExchange:
  369. if (m_context.handshake_messages[5] >= 1) {
  370. dbgln("unexpected server key exchange message");
  371. payload_res = (i8)Error::UnexpectedMessage;
  372. break;
  373. }
  374. ++m_context.handshake_messages[5];
  375. #ifdef TLS_DEBUG
  376. dbgln("server key exchange");
  377. #endif
  378. if (m_context.is_server) {
  379. dbgln("unsupported: server mode");
  380. ASSERT_NOT_REACHED();
  381. } else {
  382. payload_res = handle_server_key_exchange(buffer.slice(1, payload_size));
  383. }
  384. break;
  385. case CertificateRequest:
  386. if (m_context.handshake_messages[6] >= 1) {
  387. dbgln("unexpected certificate request message");
  388. payload_res = (i8)Error::UnexpectedMessage;
  389. break;
  390. }
  391. ++m_context.handshake_messages[6];
  392. if (m_context.is_server) {
  393. dbgln("invalid request");
  394. dbgln("unsupported: server mode");
  395. ASSERT_NOT_REACHED();
  396. } else {
  397. // we do not support "certificate request"
  398. dbgln("certificate request");
  399. if (on_tls_certificate_request)
  400. on_tls_certificate_request(*this);
  401. m_context.client_verified = VerificationNeeded;
  402. }
  403. break;
  404. case ServerHelloDone:
  405. if (m_context.handshake_messages[7] >= 1) {
  406. dbgln("unexpected server hello done message");
  407. payload_res = (i8)Error::UnexpectedMessage;
  408. break;
  409. }
  410. ++m_context.handshake_messages[7];
  411. #ifdef TLS_DEBUG
  412. dbgln("server hello done");
  413. #endif
  414. if (m_context.is_server) {
  415. dbgln("unsupported: server mode");
  416. ASSERT_NOT_REACHED();
  417. } else {
  418. payload_res = handle_server_hello_done(buffer.slice(1, payload_size));
  419. if (payload_res > 0)
  420. write_packets = WritePacketStage::ClientHandshake;
  421. }
  422. break;
  423. case CertificateVerify:
  424. if (m_context.handshake_messages[8] >= 1) {
  425. dbgln("unexpected certificate verify message");
  426. payload_res = (i8)Error::UnexpectedMessage;
  427. break;
  428. }
  429. ++m_context.handshake_messages[8];
  430. #ifdef TLS_DEBUG
  431. dbgln("certificate verify");
  432. #endif
  433. if (m_context.connection_status == ConnectionStatus::KeyExchange) {
  434. payload_res = handle_verify(buffer.slice(1, payload_size));
  435. } else {
  436. payload_res = (i8)Error::UnexpectedMessage;
  437. }
  438. break;
  439. case ClientKeyExchange:
  440. if (m_context.handshake_messages[9] >= 1) {
  441. dbgln("unexpected client key exchange message");
  442. payload_res = (i8)Error::UnexpectedMessage;
  443. break;
  444. }
  445. ++m_context.handshake_messages[9];
  446. #ifdef TLS_DEBUG
  447. dbgln("client key exchange");
  448. #endif
  449. if (m_context.is_server) {
  450. dbgln("unsupported: server mode");
  451. ASSERT_NOT_REACHED();
  452. } else {
  453. payload_res = (i8)Error::UnexpectedMessage;
  454. }
  455. break;
  456. case Finished:
  457. if (m_context.cached_handshake) {
  458. m_context.cached_handshake.clear();
  459. }
  460. if (m_context.handshake_messages[10] >= 1) {
  461. dbgln("unexpected finished message");
  462. payload_res = (i8)Error::UnexpectedMessage;
  463. break;
  464. }
  465. ++m_context.handshake_messages[10];
  466. #ifdef TLS_DEBUG
  467. dbgln("finished");
  468. #endif
  469. payload_res = handle_finished(buffer.slice(1, payload_size), write_packets);
  470. if (payload_res > 0) {
  471. memset(m_context.handshake_messages, 0, sizeof(m_context.handshake_messages));
  472. }
  473. break;
  474. default:
  475. dbgln("message type not understood: {}", type);
  476. return (i8)Error::NotUnderstood;
  477. }
  478. if (type != HelloRequest) {
  479. update_hash(buffer.slice(0, payload_size + 1));
  480. }
  481. // if something went wrong, send an alert about it
  482. if (payload_res < 0) {
  483. switch ((Error)payload_res) {
  484. case Error::UnexpectedMessage: {
  485. auto packet = build_alert(true, (u8)AlertDescription::UnexpectedMessage);
  486. write_packet(packet);
  487. break;
  488. }
  489. case Error::CompressionNotSupported: {
  490. auto packet = build_alert(true, (u8)AlertDescription::DecompressionFailure);
  491. write_packet(packet);
  492. break;
  493. }
  494. case Error::BrokenPacket: {
  495. auto packet = build_alert(true, (u8)AlertDescription::DecodeError);
  496. write_packet(packet);
  497. break;
  498. }
  499. case Error::NotVerified: {
  500. auto packet = build_alert(true, (u8)AlertDescription::BadRecordMAC);
  501. write_packet(packet);
  502. break;
  503. }
  504. case Error::BadCertificate: {
  505. auto packet = build_alert(true, (u8)AlertDescription::BadCertificate);
  506. write_packet(packet);
  507. break;
  508. }
  509. case Error::UnsupportedCertificate: {
  510. auto packet = build_alert(true, (u8)AlertDescription::UnsupportedCertificate);
  511. write_packet(packet);
  512. break;
  513. }
  514. case Error::NoCommonCipher: {
  515. auto packet = build_alert(true, (u8)AlertDescription::InsufficientSecurity);
  516. write_packet(packet);
  517. break;
  518. }
  519. case Error::NotUnderstood: {
  520. auto packet = build_alert(true, (u8)AlertDescription::InternalError);
  521. write_packet(packet);
  522. break;
  523. }
  524. case Error::NoRenegotiation: {
  525. auto packet = build_alert(true, (u8)AlertDescription::NoRenegotiation);
  526. write_packet(packet);
  527. break;
  528. }
  529. case Error::DecryptionFailed: {
  530. auto packet = build_alert(true, (u8)AlertDescription::DecryptionFailed);
  531. write_packet(packet);
  532. break;
  533. }
  534. case Error::NeedMoreData:
  535. // Ignore this, as it's not an "error"
  536. break;
  537. default:
  538. dbgln("Unknown TLS::Error with value {}", payload_res);
  539. ASSERT_NOT_REACHED();
  540. break;
  541. }
  542. if (payload_res < 0)
  543. return payload_res;
  544. }
  545. switch (write_packets) {
  546. case WritePacketStage::Initial:
  547. // nothing to write
  548. break;
  549. case WritePacketStage::ClientHandshake:
  550. if (m_context.client_verified == VerificationNeeded) {
  551. #ifdef TLS_DEBUG
  552. dbgln("> Client Certificate");
  553. #endif
  554. auto packet = build_certificate();
  555. write_packet(packet);
  556. m_context.client_verified = Verified;
  557. }
  558. {
  559. #ifdef TLS_DEBUG
  560. dbgln("> Key exchange");
  561. #endif
  562. auto packet = build_client_key_exchange();
  563. write_packet(packet);
  564. }
  565. {
  566. #ifdef TLS_DEBUG
  567. dbgln("> change cipher spec");
  568. #endif
  569. auto packet = build_change_cipher_spec();
  570. write_packet(packet);
  571. }
  572. m_context.cipher_spec_set = 1;
  573. m_context.local_sequence_number = 0;
  574. {
  575. #ifdef TLS_DEBUG
  576. dbgln("> client finished");
  577. #endif
  578. auto packet = build_finished();
  579. write_packet(packet);
  580. }
  581. m_context.cipher_spec_set = 0;
  582. break;
  583. case WritePacketStage::ServerHandshake:
  584. // server handshake
  585. dbgln("UNSUPPORTED: Server mode");
  586. ASSERT_NOT_REACHED();
  587. break;
  588. case WritePacketStage::Finished:
  589. // finished
  590. {
  591. #ifdef TLS_DEBUG
  592. dbgln("> change cipher spec");
  593. #endif
  594. auto packet = build_change_cipher_spec();
  595. write_packet(packet);
  596. }
  597. {
  598. #ifdef TLS_DEBUG
  599. dbgln("> client finished");
  600. #endif
  601. auto packet = build_finished();
  602. write_packet(packet);
  603. }
  604. m_context.connection_status = ConnectionStatus::Established;
  605. break;
  606. }
  607. payload_size++;
  608. buffer_length -= payload_size;
  609. buffer = buffer.slice(payload_size, buffer_length);
  610. }
  611. return original_length;
  612. }
  613. }