ClientHandshake.cpp 24 KB

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