TLSv12.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include "Certificate.h"
  8. #include <AK/IPv4Address.h>
  9. #include <AK/WeakPtr.h>
  10. #include <LibCore/Notifier.h>
  11. #include <LibCore/Socket.h>
  12. #include <LibCore/TCPSocket.h>
  13. #include <LibCrypto/Authentication/HMAC.h>
  14. #include <LibCrypto/BigInt/UnsignedBigInteger.h>
  15. #include <LibCrypto/Cipher/AES.h>
  16. #include <LibCrypto/Hash/HashManager.h>
  17. #include <LibCrypto/PK/RSA.h>
  18. #include <LibTLS/CipherSuite.h>
  19. #include <LibTLS/TLSPacketBuilder.h>
  20. namespace TLS {
  21. inline void print_buffer(ReadonlyBytes buffer)
  22. {
  23. StringBuilder builder(buffer.size() * 2);
  24. for (auto b : buffer)
  25. builder.appendff("{:02x} ", b);
  26. dbgln("{}", builder.string_view());
  27. }
  28. inline void print_buffer(const ByteBuffer& buffer)
  29. {
  30. print_buffer(buffer.bytes());
  31. }
  32. inline void print_buffer(const u8* buffer, size_t size)
  33. {
  34. print_buffer(ReadonlyBytes { buffer, size });
  35. }
  36. class Socket;
  37. #define ENUMERATE_ALERT_DESCRIPTIONS \
  38. ENUMERATE_ALERT_DESCRIPTION(CloseNotify, 0) \
  39. ENUMERATE_ALERT_DESCRIPTION(UnexpectedMessage, 10) \
  40. ENUMERATE_ALERT_DESCRIPTION(BadRecordMAC, 20) \
  41. ENUMERATE_ALERT_DESCRIPTION(DecryptionFailed, 21) \
  42. ENUMERATE_ALERT_DESCRIPTION(RecordOverflow, 22) \
  43. ENUMERATE_ALERT_DESCRIPTION(DecompressionFailure, 30) \
  44. ENUMERATE_ALERT_DESCRIPTION(HandshakeFailure, 40) \
  45. ENUMERATE_ALERT_DESCRIPTION(NoCertificate, 41) \
  46. ENUMERATE_ALERT_DESCRIPTION(BadCertificate, 42) \
  47. ENUMERATE_ALERT_DESCRIPTION(UnsupportedCertificate, 43) \
  48. ENUMERATE_ALERT_DESCRIPTION(CertificateRevoked, 44) \
  49. ENUMERATE_ALERT_DESCRIPTION(CertificateExpired, 45) \
  50. ENUMERATE_ALERT_DESCRIPTION(CertificateUnknown, 46) \
  51. ENUMERATE_ALERT_DESCRIPTION(IllegalParameter, 47) \
  52. ENUMERATE_ALERT_DESCRIPTION(UnknownCA, 48) \
  53. ENUMERATE_ALERT_DESCRIPTION(AccessDenied, 49) \
  54. ENUMERATE_ALERT_DESCRIPTION(DecodeError, 50) \
  55. ENUMERATE_ALERT_DESCRIPTION(DecryptError, 51) \
  56. ENUMERATE_ALERT_DESCRIPTION(ExportRestriction, 60) \
  57. ENUMERATE_ALERT_DESCRIPTION(ProtocolVersion, 70) \
  58. ENUMERATE_ALERT_DESCRIPTION(InsufficientSecurity, 71) \
  59. ENUMERATE_ALERT_DESCRIPTION(InternalError, 80) \
  60. ENUMERATE_ALERT_DESCRIPTION(InappropriateFallback, 86) \
  61. ENUMERATE_ALERT_DESCRIPTION(UserCanceled, 90) \
  62. ENUMERATE_ALERT_DESCRIPTION(NoRenegotiation, 100) \
  63. ENUMERATE_ALERT_DESCRIPTION(UnsupportedExtension, 110) \
  64. ENUMERATE_ALERT_DESCRIPTION(NoError, 255)
  65. enum class AlertDescription : u8 {
  66. #define ENUMERATE_ALERT_DESCRIPTION(name, value) name = value,
  67. ENUMERATE_ALERT_DESCRIPTIONS
  68. #undef ENUMERATE_ALERT_DESCRIPTION
  69. };
  70. constexpr static const char* alert_name(AlertDescription descriptor)
  71. {
  72. #define ENUMERATE_ALERT_DESCRIPTION(name, value) \
  73. case AlertDescription::name: \
  74. return #name;
  75. switch (descriptor) {
  76. ENUMERATE_ALERT_DESCRIPTIONS
  77. }
  78. return "Unknown";
  79. #undef ENUMERATE_ALERT_DESCRIPTION
  80. }
  81. enum class Error : i8 {
  82. NoError = 0,
  83. UnknownError = -1,
  84. BrokenPacket = -2,
  85. NotUnderstood = -3,
  86. NoCommonCipher = -5,
  87. UnexpectedMessage = -6,
  88. CloseConnection = -7,
  89. CompressionNotSupported = -8,
  90. NotVerified = -9,
  91. NotSafe = -10,
  92. IntegrityCheckFailed = -11,
  93. ErrorAlert = -12,
  94. BrokenConnection = -13,
  95. BadCertificate = -14,
  96. UnsupportedCertificate = -15,
  97. NoRenegotiation = -16,
  98. FeatureNotSupported = -17,
  99. DecryptionFailed = -20,
  100. NeedMoreData = -21,
  101. TimedOut = -22,
  102. };
  103. enum class AlertLevel : u8 {
  104. Warning = 0x01,
  105. Critical = 0x02
  106. };
  107. enum HandshakeType {
  108. HelloRequest = 0x00,
  109. ClientHello = 0x01,
  110. ServerHello = 0x02,
  111. HelloVerifyRequest = 0x03,
  112. CertificateMessage = 0x0b,
  113. ServerKeyExchange = 0x0c,
  114. CertificateRequest = 0x0d,
  115. ServerHelloDone = 0x0e,
  116. CertificateVerify = 0x0f,
  117. ClientKeyExchange = 0x10,
  118. Finished = 0x14
  119. };
  120. enum class HandshakeExtension : u16 {
  121. ServerName = 0x00,
  122. ApplicationLayerProtocolNegotiation = 0x10,
  123. SignatureAlgorithms = 0x0d,
  124. };
  125. enum class NameType : u8 {
  126. HostName = 0x00,
  127. };
  128. enum class WritePacketStage {
  129. Initial = 0,
  130. ClientHandshake = 1,
  131. ServerHandshake = 2,
  132. Finished = 3,
  133. };
  134. enum class ConnectionStatus {
  135. Disconnected,
  136. Negotiating,
  137. KeyExchange,
  138. Renegotiating,
  139. Established,
  140. };
  141. enum ClientVerificationStaus {
  142. Verified,
  143. VerificationNeeded,
  144. };
  145. // Note for the 16 iv length instead of 8:
  146. // 4 bytes of fixed IV, 8 random (nonce) bytes, 4 bytes for counter
  147. // GCM specifically asks us to transmit only the nonce, the counter is zero
  148. // and the fixed IV is derived from the premaster key.
  149. #define ENUMERATE_CIPHERS(C) \
  150. C(true, CipherSuite::RSA_WITH_AES_128_CBC_SHA, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_128_CBC, Crypto::Hash::SHA1, 16, false) \
  151. C(true, CipherSuite::RSA_WITH_AES_256_CBC_SHA, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_256_CBC, Crypto::Hash::SHA1, 16, false) \
  152. C(true, CipherSuite::RSA_WITH_AES_128_CBC_SHA256, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_128_CBC, Crypto::Hash::SHA256, 16, false) \
  153. C(true, CipherSuite::RSA_WITH_AES_256_CBC_SHA256, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_256_CBC, Crypto::Hash::SHA256, 16, false) \
  154. C(true, CipherSuite::RSA_WITH_AES_128_GCM_SHA256, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_128_GCM, Crypto::Hash::SHA256, 8, true) \
  155. C(true, CipherSuite::RSA_WITH_AES_256_GCM_SHA384, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_256_GCM, Crypto::Hash::SHA384, 8, true)
  156. constexpr KeyExchangeAlgorithm get_key_exchange_algorithm(CipherSuite suite)
  157. {
  158. switch (suite) {
  159. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  160. case suite: \
  161. return key_exchange;
  162. ENUMERATE_CIPHERS(C)
  163. #undef C
  164. default:
  165. return KeyExchangeAlgorithm::Invalid;
  166. }
  167. }
  168. constexpr CipherAlgorithm get_cipher_algorithm(CipherSuite suite)
  169. {
  170. switch (suite) {
  171. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  172. case suite: \
  173. return cipher;
  174. ENUMERATE_CIPHERS(C)
  175. #undef C
  176. default:
  177. return CipherAlgorithm::Invalid;
  178. }
  179. }
  180. struct Options {
  181. static Vector<CipherSuite> default_usable_cipher_suites()
  182. {
  183. Vector<CipherSuite> cipher_suites;
  184. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  185. if constexpr (is_supported) \
  186. cipher_suites.empend(suite);
  187. ENUMERATE_CIPHERS(C)
  188. #undef C
  189. return cipher_suites;
  190. }
  191. Vector<CipherSuite> usable_cipher_suites = default_usable_cipher_suites();
  192. #define OPTION_WITH_DEFAULTS(typ, name, ...) \
  193. static typ default_##name() { return typ { __VA_ARGS__ }; } \
  194. typ name = default_##name();
  195. OPTION_WITH_DEFAULTS(Version, version, Version::V12)
  196. OPTION_WITH_DEFAULTS(Vector<SignatureAndHashAlgorithm>, supported_signature_algorithms,
  197. { HashAlgorithm::SHA512, SignatureAlgorithm::RSA },
  198. { HashAlgorithm::SHA384, SignatureAlgorithm::RSA },
  199. { HashAlgorithm::SHA256, SignatureAlgorithm::RSA },
  200. { HashAlgorithm::SHA1, SignatureAlgorithm::RSA });
  201. OPTION_WITH_DEFAULTS(bool, use_sni, true)
  202. OPTION_WITH_DEFAULTS(bool, use_compression, false)
  203. OPTION_WITH_DEFAULTS(bool, validate_certificates, true)
  204. #undef OPTION_WITH_DEFAULTS
  205. };
  206. struct Context {
  207. String to_string() const;
  208. bool verify() const;
  209. bool verify_chain() const;
  210. static void print_file(const StringView& fname);
  211. Options options;
  212. u8 remote_random[32];
  213. u8 local_random[32];
  214. u8 session_id[32];
  215. u8 session_id_size { 0 };
  216. CipherSuite cipher;
  217. bool is_server { false };
  218. Vector<Certificate> certificates;
  219. Certificate private_key;
  220. Vector<Certificate> client_certificates;
  221. ByteBuffer master_key;
  222. ByteBuffer premaster_key;
  223. u8 cipher_spec_set { 0 };
  224. struct {
  225. int created { 0 };
  226. u8 remote_mac[32];
  227. u8 local_mac[32];
  228. u8 local_iv[16];
  229. u8 remote_iv[16];
  230. u8 local_aead_iv[4];
  231. u8 remote_aead_iv[4];
  232. } crypto;
  233. Crypto::Hash::Manager handshake_hash;
  234. ByteBuffer message_buffer;
  235. u64 remote_sequence_number { 0 };
  236. u64 local_sequence_number { 0 };
  237. ConnectionStatus connection_status { ConnectionStatus::Disconnected };
  238. u8 critical_error { 0 };
  239. Error error_code { Error::NoError };
  240. ByteBuffer tls_buffer;
  241. ByteBuffer application_buffer;
  242. bool is_child { false };
  243. struct {
  244. // Server Name Indicator
  245. String SNI; // I hate your existence
  246. } extensions;
  247. u8 request_client_certificate { 0 };
  248. ByteBuffer cached_handshake;
  249. ClientVerificationStaus client_verified { Verified };
  250. bool connection_finished { false };
  251. // message flags
  252. u8 handshake_messages[11] { 0 };
  253. ByteBuffer user_data;
  254. Vector<Certificate> root_ceritificates;
  255. Vector<String> alpn;
  256. StringView negotiated_alpn;
  257. size_t send_retries { 0 };
  258. time_t handshake_initiation_timestamp { 0 };
  259. };
  260. class TLSv12 : public Core::Socket {
  261. C_OBJECT(TLSv12)
  262. public:
  263. ByteBuffer& write_buffer() { return m_context.tls_buffer; }
  264. bool is_established() const { return m_context.connection_status == ConnectionStatus::Established; }
  265. virtual bool connect(const String&, int) override;
  266. void set_sni(const StringView& sni)
  267. {
  268. if (m_context.is_server || m_context.critical_error || m_context.connection_status != ConnectionStatus::Disconnected) {
  269. dbgln("invalid state for set_sni");
  270. return;
  271. }
  272. m_context.extensions.SNI = sni;
  273. }
  274. bool load_certificates(ReadonlyBytes pem_buffer);
  275. bool load_private_key(ReadonlyBytes pem_buffer);
  276. void set_root_certificates(Vector<Certificate>);
  277. bool add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes key_pem_buffer);
  278. bool add_client_key(Certificate certificate)
  279. {
  280. m_context.client_certificates.append(move(certificate));
  281. return true;
  282. }
  283. ByteBuffer finish_build();
  284. const StringView& alpn() const { return m_context.negotiated_alpn; }
  285. void add_alpn(const StringView& alpn);
  286. bool has_alpn(const StringView& alpn) const;
  287. bool supports_cipher(CipherSuite suite) const
  288. {
  289. switch (suite) {
  290. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  291. case suite: \
  292. return is_supported;
  293. ENUMERATE_CIPHERS(C)
  294. #undef C
  295. default:
  296. return false;
  297. }
  298. }
  299. bool supports_version(Version v) const
  300. {
  301. return v == Version::V12;
  302. }
  303. Optional<ByteBuffer> read();
  304. ByteBuffer read(size_t max_size);
  305. bool write(ReadonlyBytes);
  306. void alert(AlertLevel, AlertDescription);
  307. bool can_read_line() const { return m_context.application_buffer.size() && memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size()); }
  308. bool can_read() const { return m_context.application_buffer.size() > 0; }
  309. String read_line(size_t max_size);
  310. Function<void(TLSv12&)> on_tls_ready_to_read;
  311. Function<void(TLSv12&)> on_tls_ready_to_write;
  312. Function<void(AlertDescription)> on_tls_error;
  313. Function<void()> on_tls_connected;
  314. Function<void()> on_tls_finished;
  315. Function<void(TLSv12&)> on_tls_certificate_request;
  316. private:
  317. explicit TLSv12(Core::Object* parent, Options = {});
  318. virtual bool common_connect(const struct sockaddr*, socklen_t) override;
  319. void consume(ReadonlyBytes record);
  320. ByteBuffer hmac_message(const ReadonlyBytes& buf, const Optional<ReadonlyBytes> buf2, size_t mac_length, bool local = false);
  321. void ensure_hmac(size_t digest_size, bool local);
  322. void update_packet(ByteBuffer& packet);
  323. void update_hash(ReadonlyBytes in, size_t header_size);
  324. void write_packet(ByteBuffer& packet);
  325. ByteBuffer build_client_key_exchange();
  326. ByteBuffer build_server_key_exchange();
  327. ByteBuffer build_hello();
  328. ByteBuffer build_handshake_finished();
  329. ByteBuffer build_certificate();
  330. ByteBuffer build_done();
  331. ByteBuffer build_alert(bool critical, u8 code);
  332. ByteBuffer build_change_cipher_spec();
  333. ByteBuffer build_verify_request();
  334. void build_rsa_pre_master_secret(PacketBuilder&);
  335. bool flush();
  336. void write_into_socket();
  337. void read_from_socket();
  338. bool check_connection_state(bool read);
  339. ssize_t handle_server_hello(ReadonlyBytes, WritePacketStage&);
  340. ssize_t handle_handshake_finished(ReadonlyBytes, WritePacketStage&);
  341. ssize_t handle_certificate(ReadonlyBytes);
  342. ssize_t handle_server_key_exchange(ReadonlyBytes);
  343. ssize_t handle_server_hello_done(ReadonlyBytes);
  344. ssize_t handle_certificate_verify(ReadonlyBytes);
  345. ssize_t handle_handshake_payload(ReadonlyBytes);
  346. ssize_t handle_message(ReadonlyBytes);
  347. ssize_t handle_random(ReadonlyBytes);
  348. size_t asn1_length(ReadonlyBytes, size_t* octets);
  349. void pseudorandom_function(Bytes output, ReadonlyBytes secret, const u8* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b);
  350. size_t key_length() const
  351. {
  352. switch (m_context.cipher) {
  353. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  354. case suite: \
  355. return cipher_key_size(cipher) / 8;
  356. ENUMERATE_CIPHERS(C)
  357. #undef C
  358. default:
  359. return 128 / 8;
  360. }
  361. }
  362. size_t mac_length() const
  363. {
  364. switch (m_context.cipher) {
  365. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  366. case suite: \
  367. return hash ::digest_size();
  368. ENUMERATE_CIPHERS(C)
  369. #undef C
  370. default:
  371. return Crypto::Hash::SHA256::digest_size();
  372. }
  373. }
  374. size_t iv_length() const
  375. {
  376. switch (m_context.cipher) {
  377. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  378. case suite: \
  379. return iv_size;
  380. ENUMERATE_CIPHERS(C)
  381. #undef C
  382. default:
  383. return 16;
  384. }
  385. }
  386. bool is_aead() const
  387. {
  388. switch (m_context.cipher) {
  389. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  390. case suite: \
  391. return is_aead;
  392. ENUMERATE_CIPHERS(C)
  393. #undef C
  394. default:
  395. return false;
  396. }
  397. }
  398. bool expand_key();
  399. bool compute_master_secret_from_pre_master_secret(size_t length);
  400. Optional<size_t> verify_chain_and_get_matching_certificate(const StringView& host) const;
  401. void try_disambiguate_error() const;
  402. Context m_context;
  403. OwnPtr<Crypto::Authentication::HMAC<Crypto::Hash::Manager>> m_hmac_local;
  404. OwnPtr<Crypto::Authentication::HMAC<Crypto::Hash::Manager>> m_hmac_remote;
  405. using CipherVariant = Variant<
  406. Empty,
  407. Crypto::Cipher::AESCipher::CBCMode,
  408. Crypto::Cipher::AESCipher::GCMMode>;
  409. CipherVariant m_cipher_local { Empty {} };
  410. CipherVariant m_cipher_remote { Empty {} };
  411. bool m_has_scheduled_write_flush { false };
  412. i32 m_max_wait_time_for_handshake_in_seconds { 10 };
  413. RefPtr<Core::Timer> m_handshake_timeout_timer;
  414. };
  415. }