TLSv12.h 17 KB

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