TLSv12.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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/Timer.h>
  13. #include <LibCrypto/Authentication/HMAC.h>
  14. #include <LibCrypto/BigInt/UnsignedBigInteger.h>
  15. #include <LibCrypto/Cipher/AES.h>
  16. #include <LibCrypto/Curves/EllipticCurve.h>
  17. #include <LibCrypto/Hash/HashManager.h>
  18. #include <LibCrypto/PK/RSA.h>
  19. #include <LibTLS/CipherSuite.h>
  20. #include <LibTLS/TLSPacketBuilder.h>
  21. namespace TLS {
  22. inline void print_buffer(ReadonlyBytes buffer)
  23. {
  24. dbgln("{:hex-dump}", buffer);
  25. }
  26. inline void print_buffer(ByteBuffer const& buffer)
  27. {
  28. print_buffer(buffer.bytes());
  29. }
  30. inline void print_buffer(u8 const* buffer, size_t size)
  31. {
  32. print_buffer(ReadonlyBytes { buffer, size });
  33. }
  34. class Socket;
  35. enum class Error : i8 {
  36. NoError = 0,
  37. UnknownError = -1,
  38. BrokenPacket = -2,
  39. NotUnderstood = -3,
  40. NoCommonCipher = -5,
  41. UnexpectedMessage = -6,
  42. CloseConnection = -7,
  43. CompressionNotSupported = -8,
  44. NotVerified = -9,
  45. NotSafe = -10,
  46. IntegrityCheckFailed = -11,
  47. ErrorAlert = -12,
  48. BrokenConnection = -13,
  49. BadCertificate = -14,
  50. UnsupportedCertificate = -15,
  51. NoRenegotiation = -16,
  52. FeatureNotSupported = -17,
  53. DecryptionFailed = -20,
  54. NeedMoreData = -21,
  55. TimedOut = -22,
  56. OutOfMemory = -23,
  57. };
  58. enum class WritePacketStage {
  59. Initial = 0,
  60. ClientHandshake = 1,
  61. ServerHandshake = 2,
  62. Finished = 3,
  63. };
  64. enum class ConnectionStatus {
  65. Disconnected,
  66. Negotiating,
  67. KeyExchange,
  68. Renegotiating,
  69. Established,
  70. };
  71. enum ClientVerificationStaus {
  72. Verified,
  73. VerificationNeeded,
  74. };
  75. // Note for the 16 iv length instead of 8:
  76. // 4 bytes of fixed IV, 8 random (nonce) bytes, 4 bytes for counter
  77. // GCM specifically asks us to transmit only the nonce, the counter is zero
  78. // and the fixed IV is derived from the premaster key.
  79. #define ENUMERATE_CIPHERS(C) \
  80. C(true, CipherSuite::TLS_RSA_WITH_AES_128_CBC_SHA, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_128_CBC, Crypto::Hash::SHA1, 16, false) \
  81. C(true, CipherSuite::TLS_RSA_WITH_AES_256_CBC_SHA, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_256_CBC, Crypto::Hash::SHA1, 16, false) \
  82. C(true, CipherSuite::TLS_RSA_WITH_AES_128_CBC_SHA256, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_128_CBC, Crypto::Hash::SHA256, 16, false) \
  83. C(true, CipherSuite::TLS_RSA_WITH_AES_256_CBC_SHA256, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_256_CBC, Crypto::Hash::SHA256, 16, false) \
  84. C(true, CipherSuite::TLS_RSA_WITH_AES_128_GCM_SHA256, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_128_GCM, Crypto::Hash::SHA256, 8, true) \
  85. C(true, CipherSuite::TLS_RSA_WITH_AES_256_GCM_SHA384, KeyExchangeAlgorithm::RSA, CipherAlgorithm::AES_256_GCM, Crypto::Hash::SHA384, 8, true) \
  86. C(true, CipherSuite::TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, KeyExchangeAlgorithm::DHE_RSA, CipherAlgorithm::AES_128_GCM, Crypto::Hash::SHA256, 8, true) \
  87. C(true, CipherSuite::TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, KeyExchangeAlgorithm::DHE_RSA, CipherAlgorithm::AES_256_GCM, Crypto::Hash::SHA384, 8, true) \
  88. C(true, CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, KeyExchangeAlgorithm::ECDHE_RSA, CipherAlgorithm::AES_128_GCM, Crypto::Hash::SHA256, 8, true) \
  89. C(true, CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, KeyExchangeAlgorithm::ECDHE_RSA, CipherAlgorithm::AES_256_GCM, Crypto::Hash::SHA384, 8, true)
  90. constexpr KeyExchangeAlgorithm get_key_exchange_algorithm(CipherSuite suite)
  91. {
  92. switch (suite) {
  93. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  94. case suite: \
  95. return key_exchange;
  96. ENUMERATE_CIPHERS(C)
  97. #undef C
  98. default:
  99. return KeyExchangeAlgorithm::Invalid;
  100. }
  101. }
  102. constexpr CipherAlgorithm get_cipher_algorithm(CipherSuite suite)
  103. {
  104. switch (suite) {
  105. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  106. case suite: \
  107. return cipher;
  108. ENUMERATE_CIPHERS(C)
  109. #undef C
  110. default:
  111. return CipherAlgorithm::Invalid;
  112. }
  113. }
  114. struct Options {
  115. static Vector<CipherSuite> default_usable_cipher_suites()
  116. {
  117. Vector<CipherSuite> cipher_suites;
  118. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  119. if constexpr (is_supported) \
  120. cipher_suites.empend(suite);
  121. ENUMERATE_CIPHERS(C)
  122. #undef C
  123. return cipher_suites;
  124. }
  125. Vector<CipherSuite> usable_cipher_suites = default_usable_cipher_suites();
  126. #define OPTION_WITH_DEFAULTS(typ, name, ...) \
  127. static typ default_##name() \
  128. { \
  129. return typ { __VA_ARGS__ }; \
  130. } \
  131. typ name = default_##name(); \
  132. Options& set_##name(typ new_value)& \
  133. { \
  134. name = move(new_value); \
  135. return *this; \
  136. } \
  137. Options&& set_##name(typ new_value)&& \
  138. { \
  139. name = move(new_value); \
  140. return move(*this); \
  141. }
  142. OPTION_WITH_DEFAULTS(ProtocolVersion, version, ProtocolVersion::VERSION_1_2)
  143. OPTION_WITH_DEFAULTS(Vector<SignatureAndHashAlgorithm>, supported_signature_algorithms,
  144. { HashAlgorithm::SHA512, SignatureAlgorithm::RSA },
  145. { HashAlgorithm::SHA384, SignatureAlgorithm::RSA },
  146. { HashAlgorithm::SHA256, SignatureAlgorithm::RSA },
  147. { HashAlgorithm::SHA1, SignatureAlgorithm::RSA });
  148. OPTION_WITH_DEFAULTS(Vector<SupportedGroup>, elliptic_curves,
  149. SupportedGroup::X25519,
  150. SupportedGroup::SECP256R1,
  151. SupportedGroup::X448)
  152. OPTION_WITH_DEFAULTS(Vector<ECPointFormat>, supported_ec_point_formats, ECPointFormat::UNCOMPRESSED)
  153. OPTION_WITH_DEFAULTS(bool, use_sni, true)
  154. OPTION_WITH_DEFAULTS(bool, use_compression, false)
  155. OPTION_WITH_DEFAULTS(bool, validate_certificates, true)
  156. OPTION_WITH_DEFAULTS(bool, allow_self_signed_certificates, false)
  157. OPTION_WITH_DEFAULTS(Optional<Vector<Certificate>>, root_certificates, )
  158. OPTION_WITH_DEFAULTS(Function<void(AlertDescription)>, alert_handler, [](auto) {})
  159. OPTION_WITH_DEFAULTS(Function<void()>, finish_callback, [] {})
  160. OPTION_WITH_DEFAULTS(Function<Vector<Certificate>()>, certificate_provider, [] { return Vector<Certificate> {}; })
  161. #undef OPTION_WITH_DEFAULTS
  162. };
  163. struct Context {
  164. bool verify_chain(StringView host) const;
  165. bool verify_certificate_pair(Certificate const& subject, Certificate const& issuer) const;
  166. Options options;
  167. u8 remote_random[32];
  168. u8 local_random[32];
  169. u8 session_id[32];
  170. u8 session_id_size { 0 };
  171. CipherSuite cipher;
  172. bool is_server { false };
  173. Vector<Certificate> certificates;
  174. Certificate private_key;
  175. Vector<Certificate> client_certificates;
  176. ByteBuffer master_key;
  177. ByteBuffer premaster_key;
  178. u8 cipher_spec_set { 0 };
  179. struct {
  180. int created { 0 };
  181. u8 remote_mac[32];
  182. u8 local_mac[32];
  183. u8 local_iv[16];
  184. u8 remote_iv[16];
  185. u8 local_aead_iv[4];
  186. u8 remote_aead_iv[4];
  187. } crypto;
  188. Crypto::Hash::Manager handshake_hash;
  189. ByteBuffer message_buffer;
  190. u64 remote_sequence_number { 0 };
  191. u64 local_sequence_number { 0 };
  192. ConnectionStatus connection_status { ConnectionStatus::Disconnected };
  193. u8 critical_error { 0 };
  194. Error error_code { Error::NoError };
  195. ByteBuffer tls_buffer;
  196. ByteBuffer application_buffer;
  197. bool is_child { false };
  198. struct {
  199. // Server Name Indicator
  200. DeprecatedString SNI; // I hate your existence
  201. } extensions;
  202. u8 request_client_certificate { 0 };
  203. ByteBuffer cached_handshake;
  204. ClientVerificationStaus client_verified { Verified };
  205. bool connection_finished { false };
  206. bool close_notify { false };
  207. bool has_invoked_finish_or_error_callback { false };
  208. // message flags
  209. u8 handshake_messages[11] { 0 };
  210. ByteBuffer user_data;
  211. HashMap<DeprecatedString, Certificate> root_certificates;
  212. Vector<DeprecatedString> alpn;
  213. StringView negotiated_alpn;
  214. size_t send_retries { 0 };
  215. time_t handshake_initiation_timestamp { 0 };
  216. struct {
  217. ByteBuffer p;
  218. ByteBuffer g;
  219. ByteBuffer Ys;
  220. } server_diffie_hellman_params;
  221. OwnPtr<Crypto::Curves::EllipticCurve> server_key_exchange_curve;
  222. };
  223. class TLSv12 final : public Core::Socket {
  224. private:
  225. Core::Socket& underlying_stream()
  226. {
  227. return *m_stream.visit([&](auto& stream) -> Core::Socket* { return stream; });
  228. }
  229. Core::Socket const& underlying_stream() const
  230. {
  231. return *m_stream.visit([&](auto& stream) -> Core::Socket const* { return stream; });
  232. }
  233. public:
  234. /// Reads into a buffer, with the maximum size being the size of the buffer.
  235. /// The amount of bytes read can be smaller than the size of the buffer.
  236. /// Returns either the bytes that were read, or an errno in the case of
  237. /// failure.
  238. virtual ErrorOr<Bytes> read_some(Bytes) override;
  239. /// Tries to write the entire contents of the buffer. It is possible for
  240. /// less than the full buffer to be written. Returns either the amount of
  241. /// bytes written into the stream, or an errno in the case of failure.
  242. virtual ErrorOr<size_t> write_some(ReadonlyBytes) override;
  243. virtual bool is_eof() const override { return m_context.application_buffer.is_empty() && (m_context.connection_finished || underlying_stream().is_eof()); }
  244. virtual bool is_open() const override { return is_established(); }
  245. virtual void close() override;
  246. virtual ErrorOr<size_t> pending_bytes() const override { return m_context.application_buffer.size(); }
  247. virtual ErrorOr<bool> can_read_without_blocking(int = 0) const override { return !m_context.application_buffer.is_empty(); }
  248. virtual ErrorOr<void> set_blocking(bool block) override
  249. {
  250. VERIFY(!block);
  251. return {};
  252. }
  253. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return underlying_stream().set_close_on_exec(enabled); }
  254. virtual void set_notifications_enabled(bool enabled) override { underlying_stream().set_notifications_enabled(enabled); }
  255. static ErrorOr<NonnullOwnPtr<TLSv12>> connect(DeprecatedString const& host, u16 port, Options = {});
  256. static ErrorOr<NonnullOwnPtr<TLSv12>> connect(DeprecatedString const& host, Core::Socket& underlying_stream, Options = {});
  257. using StreamVariantType = Variant<OwnPtr<Core::Socket>, Core::Socket*>;
  258. explicit TLSv12(StreamVariantType, Options);
  259. bool is_established() const { return m_context.connection_status == ConnectionStatus::Established; }
  260. void set_sni(StringView sni)
  261. {
  262. if (m_context.is_server || m_context.critical_error || m_context.connection_status != ConnectionStatus::Disconnected) {
  263. dbgln("invalid state for set_sni");
  264. return;
  265. }
  266. m_context.extensions.SNI = sni;
  267. }
  268. void set_root_certificates(Vector<Certificate>);
  269. static Vector<Certificate> parse_pem_certificate(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes key_pem_buffer);
  270. StringView alpn() const { return m_context.negotiated_alpn; }
  271. bool supports_cipher(CipherSuite suite) const
  272. {
  273. switch (suite) {
  274. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  275. case suite: \
  276. return is_supported;
  277. ENUMERATE_CIPHERS(C)
  278. #undef C
  279. default:
  280. return false;
  281. }
  282. }
  283. bool supports_version(ProtocolVersion v) const
  284. {
  285. return v == ProtocolVersion::VERSION_1_2;
  286. }
  287. void alert(AlertLevel, AlertDescription);
  288. bool can_read_line() const { return m_context.application_buffer.size() && memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size()); }
  289. bool can_read() const { return m_context.application_buffer.size() > 0; }
  290. DeprecatedString read_line(size_t max_size);
  291. Function<void(AlertDescription)> on_tls_error;
  292. Function<void()> on_tls_finished;
  293. Function<void(TLSv12&)> on_tls_certificate_request;
  294. Function<void()> on_connected;
  295. private:
  296. void setup_connection();
  297. void consume(ReadonlyBytes record);
  298. ByteBuffer hmac_message(ReadonlyBytes buf, Optional<ReadonlyBytes> const buf2, size_t mac_length, bool local = false);
  299. void ensure_hmac(size_t digest_size, bool local);
  300. void update_packet(ByteBuffer& packet);
  301. void update_hash(ReadonlyBytes in, size_t header_size);
  302. void write_packet(ByteBuffer& packet);
  303. ByteBuffer build_client_key_exchange();
  304. ByteBuffer build_server_key_exchange();
  305. ByteBuffer build_hello();
  306. ByteBuffer build_handshake_finished();
  307. ByteBuffer build_certificate();
  308. ByteBuffer build_alert(bool critical, u8 code);
  309. ByteBuffer build_change_cipher_spec();
  310. void build_rsa_pre_master_secret(PacketBuilder&);
  311. void build_dhe_rsa_pre_master_secret(PacketBuilder&);
  312. void build_ecdhe_rsa_pre_master_secret(PacketBuilder&);
  313. ErrorOr<bool> flush();
  314. void write_into_socket();
  315. ErrorOr<void> read_from_socket();
  316. bool check_connection_state(bool read);
  317. void notify_client_for_app_data();
  318. ssize_t handle_server_hello(ReadonlyBytes, WritePacketStage&);
  319. ssize_t handle_handshake_finished(ReadonlyBytes, WritePacketStage&);
  320. ssize_t handle_certificate(ReadonlyBytes);
  321. ssize_t handle_server_key_exchange(ReadonlyBytes);
  322. ssize_t handle_dhe_rsa_server_key_exchange(ReadonlyBytes);
  323. ssize_t handle_ecdhe_rsa_server_key_exchange(ReadonlyBytes);
  324. ssize_t handle_server_hello_done(ReadonlyBytes);
  325. ssize_t handle_certificate_verify(ReadonlyBytes);
  326. ssize_t handle_handshake_payload(ReadonlyBytes);
  327. ssize_t handle_message(ReadonlyBytes);
  328. void pseudorandom_function(Bytes output, ReadonlyBytes secret, u8 const* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b);
  329. ssize_t verify_rsa_server_key_exchange(ReadonlyBytes server_key_info_buffer, ReadonlyBytes signature_buffer);
  330. size_t key_length() const
  331. {
  332. switch (m_context.cipher) {
  333. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  334. case suite: \
  335. return cipher_key_size(cipher) / 8;
  336. ENUMERATE_CIPHERS(C)
  337. #undef C
  338. default:
  339. return 128 / 8;
  340. }
  341. }
  342. size_t mac_length() const
  343. {
  344. switch (m_context.cipher) {
  345. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  346. case suite: \
  347. return hash ::digest_size();
  348. ENUMERATE_CIPHERS(C)
  349. #undef C
  350. default:
  351. return Crypto::Hash::SHA256::digest_size();
  352. }
  353. }
  354. Crypto::Hash::HashKind hmac_hash() const
  355. {
  356. switch (mac_length()) {
  357. case Crypto::Hash::SHA512::DigestSize:
  358. return Crypto::Hash::HashKind::SHA512;
  359. case Crypto::Hash::SHA384::DigestSize:
  360. return Crypto::Hash::HashKind::SHA384;
  361. case Crypto::Hash::SHA256::DigestSize:
  362. case Crypto::Hash::SHA1::DigestSize:
  363. default:
  364. return Crypto::Hash::HashKind::SHA256;
  365. }
  366. }
  367. size_t iv_length() const
  368. {
  369. switch (m_context.cipher) {
  370. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  371. case suite: \
  372. return iv_size;
  373. ENUMERATE_CIPHERS(C)
  374. #undef C
  375. default:
  376. return 16;
  377. }
  378. }
  379. bool is_aead() const
  380. {
  381. switch (m_context.cipher) {
  382. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  383. case suite: \
  384. return is_aead;
  385. ENUMERATE_CIPHERS(C)
  386. #undef C
  387. default:
  388. return false;
  389. }
  390. }
  391. bool expand_key();
  392. bool compute_master_secret_from_pre_master_secret(size_t length);
  393. void try_disambiguate_error() const;
  394. bool m_eof { false };
  395. StreamVariantType m_stream;
  396. Context m_context;
  397. OwnPtr<Crypto::Authentication::HMAC<Crypto::Hash::Manager>> m_hmac_local;
  398. OwnPtr<Crypto::Authentication::HMAC<Crypto::Hash::Manager>> m_hmac_remote;
  399. using CipherVariant = Variant<
  400. Empty,
  401. Crypto::Cipher::AESCipher::CBCMode,
  402. Crypto::Cipher::AESCipher::GCMMode>;
  403. CipherVariant m_cipher_local {};
  404. CipherVariant m_cipher_remote {};
  405. bool m_has_scheduled_write_flush { false };
  406. bool m_has_scheduled_app_data_flush { false };
  407. i32 m_max_wait_time_for_handshake_in_seconds { 10 };
  408. RefPtr<Core::Timer> m_handshake_timeout_timer;
  409. };
  410. }