ClientHandshake.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. // Compression method
  104. if (buffer.size() - res < 1)
  105. return (i8)Error::NeedMoreData;
  106. u8 compression = buffer[res++];
  107. if (compression != 0)
  108. return (i8)Error::CompressionNotSupported;
  109. if (m_context.connection_status != ConnectionStatus::Renegotiating)
  110. m_context.connection_status = ConnectionStatus::Negotiating;
  111. if (m_context.is_server) {
  112. dbgln("unsupported: server mode");
  113. write_packets = WritePacketStage::ServerHandshake;
  114. }
  115. // Presence of extensions is determined by availability of bytes after compression_method
  116. if (buffer.size() - res >= 2) {
  117. auto extensions_bytes_total = AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res += 2));
  118. dbgln_if(TLS_DEBUG, "Extensions bytes total: {}", extensions_bytes_total);
  119. }
  120. while (buffer.size() - res >= 4) {
  121. auto extension_type = (HandshakeExtension)AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res));
  122. res += 2;
  123. u16 extension_length = AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res));
  124. res += 2;
  125. dbgln_if(TLS_DEBUG, "Extension {} with length {}", (u16)extension_type, extension_length);
  126. if (buffer.size() - res < extension_length)
  127. return (i8)Error::NeedMoreData;
  128. if (extension_type == HandshakeExtension::ServerName) {
  129. // RFC6066 section 3: SNI extension_data can be empty in the server hello
  130. if (extension_length > 0) {
  131. // ServerNameList total size
  132. if (buffer.size() - res < 2)
  133. return (i8)Error::NeedMoreData;
  134. auto sni_name_list_bytes = AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res += 2));
  135. dbgln_if(TLS_DEBUG, "SNI: expecting ServerNameList of {} bytes", sni_name_list_bytes);
  136. // Exactly one ServerName should be present
  137. if (buffer.size() - res < 3)
  138. return (i8)Error::NeedMoreData;
  139. auto sni_name_type = (NameType)(*(const u8*)buffer.offset_pointer(res++));
  140. auto sni_name_length = AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res += 2));
  141. if (sni_name_type != NameType::HostName)
  142. return (i8)Error::NotUnderstood;
  143. if (sizeof(sni_name_type) + sizeof(sni_name_length) + sni_name_length != sni_name_list_bytes)
  144. return (i8)Error::BrokenPacket;
  145. // Read out the host_name
  146. if (buffer.size() - res < sni_name_length)
  147. return (i8)Error::NeedMoreData;
  148. m_context.extensions.SNI = String { (const char*)buffer.offset_pointer(res), sni_name_length };
  149. res += sni_name_length;
  150. dbgln("SNI host_name: {}", m_context.extensions.SNI);
  151. }
  152. } else if (extension_type == HandshakeExtension::ApplicationLayerProtocolNegotiation && m_context.alpn.size()) {
  153. if (buffer.size() - res > 2) {
  154. auto alpn_length = AK::convert_between_host_and_network_endian(*(const u16*)buffer.offset_pointer(res));
  155. if (alpn_length && alpn_length <= extension_length - 2) {
  156. const u8* alpn = buffer.offset_pointer(res + 2);
  157. size_t alpn_position = 0;
  158. while (alpn_position < alpn_length) {
  159. u8 alpn_size = alpn[alpn_position++];
  160. if (alpn_size + alpn_position >= extension_length)
  161. break;
  162. String alpn_str { (const char*)alpn + alpn_position, alpn_length };
  163. if (alpn_size && m_context.alpn.contains_slow(alpn_str)) {
  164. m_context.negotiated_alpn = alpn_str;
  165. dbgln("negotiated alpn: {}", alpn_str);
  166. break;
  167. }
  168. alpn_position += alpn_length;
  169. if (!m_context.is_server) // server hello must contain one ALPN
  170. break;
  171. }
  172. }
  173. }
  174. res += extension_length;
  175. } else if (extension_type == HandshakeExtension::SignatureAlgorithms) {
  176. dbgln("supported signatures: ");
  177. print_buffer(buffer.slice(res, extension_length));
  178. res += extension_length;
  179. // FIXME: what are we supposed to do here?
  180. } else {
  181. dbgln("Encountered unknown extension {} with length {}", (u16)extension_type, extension_length);
  182. res += extension_length;
  183. }
  184. }
  185. return res;
  186. }
  187. ssize_t TLSv12::handle_finished(ReadonlyBytes buffer, WritePacketStage& write_packets)
  188. {
  189. if (m_context.connection_status < ConnectionStatus::KeyExchange || m_context.connection_status == ConnectionStatus::Established) {
  190. dbgln("unexpected finished message");
  191. return (i8)Error::UnexpectedMessage;
  192. }
  193. write_packets = WritePacketStage::Initial;
  194. if (buffer.size() < 3) {
  195. return (i8)Error::NeedMoreData;
  196. }
  197. size_t index = 3;
  198. u32 size = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
  199. if (size < 12) {
  200. dbgln_if(TLS_DEBUG, "finished packet smaller than minimum size: {}", size);
  201. return (i8)Error::BrokenPacket;
  202. }
  203. if (size < buffer.size() - index) {
  204. dbgln_if(TLS_DEBUG, "not enough data after length: {} > {}", size, buffer.size() - index);
  205. return (i8)Error::NeedMoreData;
  206. }
  207. // TODO: Compare Hashes
  208. dbgln_if(TLS_DEBUG, "FIXME: handle_finished :: Check message validity");
  209. m_context.connection_status = ConnectionStatus::Established;
  210. if (m_handshake_timeout_timer) {
  211. // Disable the handshake timeout timer as handshake has been established.
  212. m_handshake_timeout_timer->stop();
  213. m_handshake_timeout_timer->remove_from_parent();
  214. m_handshake_timeout_timer = nullptr;
  215. }
  216. if (on_tls_ready_to_write)
  217. on_tls_ready_to_write(*this);
  218. return index + size;
  219. }
  220. void TLSv12::build_random(PacketBuilder& builder)
  221. {
  222. u8 random_bytes[48];
  223. size_t bytes = 48;
  224. fill_with_random(random_bytes, bytes);
  225. // remove zeros from the random bytes
  226. for (size_t i = 0; i < bytes; ++i) {
  227. if (!random_bytes[i])
  228. random_bytes[i--] = get_random<u8>();
  229. }
  230. if (m_context.is_server) {
  231. dbgln("Server mode not supported");
  232. return;
  233. } else {
  234. *(u16*)random_bytes = AK::convert_between_host_and_network_endian((u16)Version::V12);
  235. }
  236. m_context.premaster_key = ByteBuffer::copy(random_bytes, bytes);
  237. // const auto& certificate_option = verify_chain_and_get_matching_certificate(m_context.extensions.SNI); // if the SNI is empty, we'll make a special case and match *a* leaf certificate.
  238. Optional<size_t> certificate_option = 0;
  239. if (!certificate_option.has_value()) {
  240. dbgln("certificate verification failed :(");
  241. alert(AlertLevel::Critical, AlertDescription::BadCertificate);
  242. return;
  243. }
  244. auto& certificate = m_context.certificates[certificate_option.value()];
  245. #if TLS_DEBUG
  246. dbgln("PreMaster secret");
  247. print_buffer(m_context.premaster_key);
  248. #endif
  249. Crypto::PK::RSA_PKCS1_EME rsa(certificate.public_key.modulus(), 0, certificate.public_key.public_exponent());
  250. u8 out[rsa.output_size()];
  251. auto outbuf = Bytes { out, rsa.output_size() };
  252. rsa.encrypt(m_context.premaster_key, outbuf);
  253. #if TLS_DEBUG
  254. dbgln("Encrypted: ");
  255. print_buffer(outbuf);
  256. #endif
  257. if (!compute_master_secret(bytes)) {
  258. dbgln("oh noes we could not derive a master key :(");
  259. return;
  260. }
  261. builder.append_u24(outbuf.size() + 2);
  262. builder.append((u16)outbuf.size());
  263. builder.append(outbuf);
  264. }
  265. ssize_t TLSv12::handle_payload(ReadonlyBytes vbuffer)
  266. {
  267. if (m_context.connection_status == ConnectionStatus::Established) {
  268. dbgln_if(TLS_DEBUG, "Renegotiation attempt ignored");
  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. dbgln_if(TLS_DEBUG, "payload size: {} buffer length: {}", payload_size, buffer_length);
  286. if (payload_size + 1 > buffer_length)
  287. return (i8)Error::NeedMoreData;
  288. switch (type) {
  289. case HelloRequest:
  290. if (m_context.handshake_messages[0] >= 1) {
  291. dbgln("unexpected hello request message");
  292. payload_res = (i8)Error::UnexpectedMessage;
  293. break;
  294. }
  295. ++m_context.handshake_messages[0];
  296. dbgln("hello request (renegotiation?)");
  297. if (m_context.connection_status == ConnectionStatus::Established) {
  298. // renegotiation
  299. payload_res = (i8)Error::NoRenegotiation;
  300. } else {
  301. // :shrug:
  302. payload_res = (i8)Error::UnexpectedMessage;
  303. }
  304. break;
  305. case ClientHello:
  306. // FIXME: We only support client mode right now
  307. if (m_context.is_server) {
  308. VERIFY_NOT_REACHED();
  309. }
  310. payload_res = (i8)Error::UnexpectedMessage;
  311. break;
  312. case ServerHello:
  313. if (m_context.handshake_messages[2] >= 1) {
  314. dbgln("unexpected server hello message");
  315. payload_res = (i8)Error::UnexpectedMessage;
  316. break;
  317. }
  318. ++m_context.handshake_messages[2];
  319. dbgln_if(TLS_DEBUG, "server hello");
  320. if (m_context.is_server) {
  321. dbgln("unsupported: server mode");
  322. VERIFY_NOT_REACHED();
  323. }
  324. payload_res = handle_hello(buffer.slice(1, payload_size), write_packets);
  325. break;
  326. case HelloVerifyRequest:
  327. dbgln("unsupported: DTLS");
  328. payload_res = (i8)Error::UnexpectedMessage;
  329. break;
  330. case CertificateMessage:
  331. if (m_context.handshake_messages[4] >= 1) {
  332. dbgln("unexpected certificate message");
  333. payload_res = (i8)Error::UnexpectedMessage;
  334. break;
  335. }
  336. ++m_context.handshake_messages[4];
  337. dbgln_if(TLS_DEBUG, "certificate");
  338. if (m_context.connection_status == ConnectionStatus::Negotiating) {
  339. if (m_context.is_server) {
  340. dbgln("unsupported: server mode");
  341. VERIFY_NOT_REACHED();
  342. }
  343. payload_res = handle_certificate(buffer.slice(1, payload_size));
  344. if (m_context.certificates.size()) {
  345. auto it = m_context.certificates.find_if([](const auto& cert) { return cert.is_valid(); });
  346. if (it.is_end()) {
  347. // no valid certificates
  348. dbgln("No valid certificates found");
  349. payload_res = (i8)Error::BadCertificate;
  350. m_context.critical_error = payload_res;
  351. break;
  352. }
  353. // swap the first certificate with the valid one
  354. if (it.index() != 0)
  355. swap(m_context.certificates[0], m_context.certificates[it.index()]);
  356. }
  357. } else {
  358. payload_res = (i8)Error::UnexpectedMessage;
  359. }
  360. break;
  361. case ServerKeyExchange:
  362. if (m_context.handshake_messages[5] >= 1) {
  363. dbgln("unexpected server key exchange message");
  364. payload_res = (i8)Error::UnexpectedMessage;
  365. break;
  366. }
  367. ++m_context.handshake_messages[5];
  368. dbgln_if(TLS_DEBUG, "server key exchange");
  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. dbgln_if(TLS_DEBUG, "server hello done");
  403. if (m_context.is_server) {
  404. dbgln("unsupported: server mode");
  405. VERIFY_NOT_REACHED();
  406. } else {
  407. payload_res = handle_server_hello_done(buffer.slice(1, payload_size));
  408. if (payload_res > 0)
  409. write_packets = WritePacketStage::ClientHandshake;
  410. }
  411. break;
  412. case CertificateVerify:
  413. if (m_context.handshake_messages[8] >= 1) {
  414. dbgln("unexpected certificate verify message");
  415. payload_res = (i8)Error::UnexpectedMessage;
  416. break;
  417. }
  418. ++m_context.handshake_messages[8];
  419. dbgln_if(TLS_DEBUG, "certificate verify");
  420. if (m_context.connection_status == ConnectionStatus::KeyExchange) {
  421. payload_res = handle_verify(buffer.slice(1, payload_size));
  422. } else {
  423. payload_res = (i8)Error::UnexpectedMessage;
  424. }
  425. break;
  426. case ClientKeyExchange:
  427. if (m_context.handshake_messages[9] >= 1) {
  428. dbgln("unexpected client key exchange message");
  429. payload_res = (i8)Error::UnexpectedMessage;
  430. break;
  431. }
  432. ++m_context.handshake_messages[9];
  433. dbgln_if(TLS_DEBUG, "client key exchange");
  434. if (m_context.is_server) {
  435. dbgln("unsupported: server mode");
  436. VERIFY_NOT_REACHED();
  437. } else {
  438. payload_res = (i8)Error::UnexpectedMessage;
  439. }
  440. break;
  441. case Finished:
  442. if (m_context.cached_handshake) {
  443. m_context.cached_handshake.clear();
  444. }
  445. if (m_context.handshake_messages[10] >= 1) {
  446. dbgln("unexpected finished message");
  447. payload_res = (i8)Error::UnexpectedMessage;
  448. break;
  449. }
  450. ++m_context.handshake_messages[10];
  451. dbgln_if(TLS_DEBUG, "finished");
  452. payload_res = handle_finished(buffer.slice(1, payload_size), write_packets);
  453. if (payload_res > 0) {
  454. memset(m_context.handshake_messages, 0, sizeof(m_context.handshake_messages));
  455. }
  456. break;
  457. default:
  458. dbgln("message type not understood: {}", type);
  459. return (i8)Error::NotUnderstood;
  460. }
  461. if (type != HelloRequest) {
  462. update_hash(buffer.slice(0, payload_size + 1), 0);
  463. }
  464. // if something went wrong, send an alert about it
  465. if (payload_res < 0) {
  466. switch ((Error)payload_res) {
  467. case Error::UnexpectedMessage: {
  468. auto packet = build_alert(true, (u8)AlertDescription::UnexpectedMessage);
  469. write_packet(packet);
  470. break;
  471. }
  472. case Error::CompressionNotSupported: {
  473. auto packet = build_alert(true, (u8)AlertDescription::DecompressionFailure);
  474. write_packet(packet);
  475. break;
  476. }
  477. case Error::BrokenPacket: {
  478. auto packet = build_alert(true, (u8)AlertDescription::DecodeError);
  479. write_packet(packet);
  480. break;
  481. }
  482. case Error::NotVerified: {
  483. auto packet = build_alert(true, (u8)AlertDescription::BadRecordMAC);
  484. write_packet(packet);
  485. break;
  486. }
  487. case Error::BadCertificate: {
  488. auto packet = build_alert(true, (u8)AlertDescription::BadCertificate);
  489. write_packet(packet);
  490. break;
  491. }
  492. case Error::UnsupportedCertificate: {
  493. auto packet = build_alert(true, (u8)AlertDescription::UnsupportedCertificate);
  494. write_packet(packet);
  495. break;
  496. }
  497. case Error::NoCommonCipher: {
  498. auto packet = build_alert(true, (u8)AlertDescription::InsufficientSecurity);
  499. write_packet(packet);
  500. break;
  501. }
  502. case Error::NotUnderstood: {
  503. auto packet = build_alert(true, (u8)AlertDescription::InternalError);
  504. write_packet(packet);
  505. break;
  506. }
  507. case Error::NoRenegotiation: {
  508. auto packet = build_alert(true, (u8)AlertDescription::NoRenegotiation);
  509. write_packet(packet);
  510. break;
  511. }
  512. case Error::DecryptionFailed: {
  513. auto packet = build_alert(true, (u8)AlertDescription::DecryptionFailed);
  514. write_packet(packet);
  515. break;
  516. }
  517. case Error::NeedMoreData:
  518. // Ignore this, as it's not an "error"
  519. dbgln_if(TLS_DEBUG, "More data needed");
  520. break;
  521. default:
  522. dbgln("Unknown TLS::Error with value {}", payload_res);
  523. VERIFY_NOT_REACHED();
  524. break;
  525. }
  526. if (payload_res < 0)
  527. return payload_res;
  528. }
  529. switch (write_packets) {
  530. case WritePacketStage::Initial:
  531. // nothing to write
  532. break;
  533. case WritePacketStage::ClientHandshake:
  534. if (m_context.client_verified == VerificationNeeded) {
  535. dbgln_if(TLS_DEBUG, "> Client Certificate");
  536. auto packet = build_certificate();
  537. write_packet(packet);
  538. m_context.client_verified = Verified;
  539. }
  540. {
  541. dbgln_if(TLS_DEBUG, "> Key exchange");
  542. auto packet = build_client_key_exchange();
  543. write_packet(packet);
  544. }
  545. {
  546. dbgln_if(TLS_DEBUG, "> change cipher spec");
  547. auto packet = build_change_cipher_spec();
  548. write_packet(packet);
  549. }
  550. m_context.cipher_spec_set = 1;
  551. m_context.local_sequence_number = 0;
  552. {
  553. dbgln_if(TLS_DEBUG, "> client finished");
  554. auto packet = build_finished();
  555. write_packet(packet);
  556. }
  557. m_context.cipher_spec_set = 0;
  558. break;
  559. case WritePacketStage::ServerHandshake:
  560. // server handshake
  561. dbgln("UNSUPPORTED: Server mode");
  562. VERIFY_NOT_REACHED();
  563. break;
  564. case WritePacketStage::Finished:
  565. // finished
  566. {
  567. dbgln_if(TLS_DEBUG, "> change cipher spec");
  568. auto packet = build_change_cipher_spec();
  569. write_packet(packet);
  570. }
  571. {
  572. dbgln_if(TLS_DEBUG, "> client finished");
  573. auto packet = build_finished();
  574. write_packet(packet);
  575. }
  576. m_context.connection_status = ConnectionStatus::Established;
  577. break;
  578. }
  579. payload_size++;
  580. buffer_length -= payload_size;
  581. buffer = buffer.slice(payload_size, buffer_length);
  582. }
  583. return original_length;
  584. }
  585. }