TLSv12.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. constexpr KeyExchangeAlgorithm get_key_exchange_algorithm(CipherSuite suite)
  154. {
  155. switch (suite) {
  156. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  157. case suite: \
  158. return key_exchange;
  159. ENUMERATE_CIPHERS(C)
  160. #undef C
  161. default:
  162. return KeyExchangeAlgorithm::Invalid;
  163. }
  164. }
  165. constexpr CipherAlgorithm get_cipher_algorithm(CipherSuite suite)
  166. {
  167. switch (suite) {
  168. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  169. case suite: \
  170. return cipher;
  171. ENUMERATE_CIPHERS(C)
  172. #undef C
  173. default:
  174. return CipherAlgorithm::Invalid;
  175. }
  176. }
  177. struct Options {
  178. static Vector<CipherSuite> default_usable_cipher_suites()
  179. {
  180. Vector<CipherSuite> cipher_suites;
  181. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  182. if constexpr (is_supported) \
  183. cipher_suites.empend(suite);
  184. ENUMERATE_CIPHERS(C)
  185. #undef C
  186. return cipher_suites;
  187. }
  188. Vector<CipherSuite> usable_cipher_suites = default_usable_cipher_suites();
  189. #define OPTION_WITH_DEFAULTS(typ, name, ...) \
  190. static typ default_##name() { return typ { __VA_ARGS__ }; } \
  191. typ name = default_##name();
  192. OPTION_WITH_DEFAULTS(Version, version, Version::V12)
  193. OPTION_WITH_DEFAULTS(Vector<SignatureAndHashAlgorithm>, supported_signature_algorithms,
  194. { HashAlgorithm::SHA512, SignatureAlgorithm::RSA },
  195. { HashAlgorithm::SHA384, SignatureAlgorithm::RSA },
  196. { HashAlgorithm::SHA256, SignatureAlgorithm::RSA },
  197. { HashAlgorithm::SHA1, SignatureAlgorithm::RSA });
  198. OPTION_WITH_DEFAULTS(bool, use_sni, true)
  199. OPTION_WITH_DEFAULTS(bool, use_compression, false)
  200. OPTION_WITH_DEFAULTS(bool, validate_certificates, true)
  201. #undef OPTION_WITH_DEFAULTS
  202. };
  203. struct Context {
  204. String to_string() const;
  205. bool verify() const;
  206. bool verify_chain() const;
  207. static void print_file(const StringView& fname);
  208. Options options;
  209. u8 remote_random[32];
  210. u8 local_random[32];
  211. u8 session_id[32];
  212. u8 session_id_size { 0 };
  213. CipherSuite cipher;
  214. bool is_server { false };
  215. Vector<Certificate> certificates;
  216. Certificate private_key;
  217. Vector<Certificate> client_certificates;
  218. ByteBuffer master_key;
  219. ByteBuffer premaster_key;
  220. u8 cipher_spec_set { 0 };
  221. struct {
  222. int created { 0 };
  223. u8 remote_mac[32];
  224. u8 local_mac[32];
  225. u8 local_iv[16];
  226. u8 remote_iv[16];
  227. u8 local_aead_iv[4];
  228. u8 remote_aead_iv[4];
  229. } crypto;
  230. Crypto::Hash::Manager handshake_hash;
  231. ByteBuffer message_buffer;
  232. u64 remote_sequence_number { 0 };
  233. u64 local_sequence_number { 0 };
  234. ConnectionStatus connection_status { ConnectionStatus::Disconnected };
  235. u8 critical_error { 0 };
  236. Error error_code { Error::NoError };
  237. ByteBuffer tls_buffer;
  238. ByteBuffer application_buffer;
  239. bool is_child { false };
  240. struct {
  241. // Server Name Indicator
  242. String SNI; // I hate your existence
  243. } extensions;
  244. u8 request_client_certificate { 0 };
  245. ByteBuffer cached_handshake;
  246. ClientVerificationStaus client_verified { Verified };
  247. bool connection_finished { false };
  248. // message flags
  249. u8 handshake_messages[11] { 0 };
  250. ByteBuffer user_data;
  251. Vector<Certificate> root_ceritificates;
  252. Vector<String> alpn;
  253. StringView negotiated_alpn;
  254. size_t send_retries { 0 };
  255. time_t handshake_initiation_timestamp { 0 };
  256. };
  257. class TLSv12 : public Core::Socket {
  258. C_OBJECT(TLSv12)
  259. public:
  260. ByteBuffer& write_buffer() { return m_context.tls_buffer; }
  261. bool is_established() const { return m_context.connection_status == ConnectionStatus::Established; }
  262. virtual bool connect(const String&, int) override;
  263. void set_sni(const StringView& sni)
  264. {
  265. if (m_context.is_server || m_context.critical_error || m_context.connection_status != ConnectionStatus::Disconnected) {
  266. dbgln("invalid state for set_sni");
  267. return;
  268. }
  269. m_context.extensions.SNI = sni;
  270. }
  271. bool load_certificates(ReadonlyBytes pem_buffer);
  272. bool load_private_key(ReadonlyBytes pem_buffer);
  273. void set_root_certificates(Vector<Certificate>);
  274. bool add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes key_pem_buffer);
  275. bool add_client_key(Certificate certificate)
  276. {
  277. m_context.client_certificates.append(move(certificate));
  278. return true;
  279. }
  280. ByteBuffer finish_build();
  281. const StringView& alpn() const { return m_context.negotiated_alpn; }
  282. void add_alpn(const StringView& alpn);
  283. bool has_alpn(const StringView& alpn) const;
  284. bool supports_cipher(CipherSuite suite) const
  285. {
  286. switch (suite) {
  287. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  288. case suite: \
  289. return is_supported;
  290. ENUMERATE_CIPHERS(C)
  291. #undef C
  292. default:
  293. return false;
  294. }
  295. }
  296. bool supports_version(Version v) const
  297. {
  298. return v == Version::V12;
  299. }
  300. Optional<ByteBuffer> read();
  301. ByteBuffer read(size_t max_size);
  302. bool write(ReadonlyBytes);
  303. void alert(AlertLevel, AlertDescription);
  304. bool can_read_line() const { return m_context.application_buffer.size() && memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size()); }
  305. bool can_read() const { return m_context.application_buffer.size() > 0; }
  306. String read_line(size_t max_size);
  307. Function<void(TLSv12&)> on_tls_ready_to_read;
  308. Function<void(TLSv12&)> on_tls_ready_to_write;
  309. Function<void(AlertDescription)> on_tls_error;
  310. Function<void()> on_tls_connected;
  311. Function<void()> on_tls_finished;
  312. Function<void(TLSv12&)> on_tls_certificate_request;
  313. private:
  314. explicit TLSv12(Core::Object* parent, Options = {});
  315. virtual bool common_connect(const struct sockaddr*, socklen_t) override;
  316. void consume(ReadonlyBytes record);
  317. ByteBuffer hmac_message(const ReadonlyBytes& buf, const Optional<ReadonlyBytes> buf2, size_t mac_length, bool local = false);
  318. void ensure_hmac(size_t digest_size, bool local);
  319. void update_packet(ByteBuffer& packet);
  320. void update_hash(ReadonlyBytes in, size_t header_size);
  321. void write_packet(ByteBuffer& packet);
  322. ByteBuffer build_client_key_exchange();
  323. ByteBuffer build_server_key_exchange();
  324. ByteBuffer build_hello();
  325. ByteBuffer build_handshake_finished();
  326. ByteBuffer build_certificate();
  327. ByteBuffer build_done();
  328. ByteBuffer build_alert(bool critical, u8 code);
  329. ByteBuffer build_change_cipher_spec();
  330. ByteBuffer build_verify_request();
  331. void build_rsa_pre_master_secret(PacketBuilder&);
  332. bool flush();
  333. void write_into_socket();
  334. void read_from_socket();
  335. bool check_connection_state(bool read);
  336. ssize_t handle_server_hello(ReadonlyBytes, WritePacketStage&);
  337. ssize_t handle_handshake_finished(ReadonlyBytes, WritePacketStage&);
  338. ssize_t handle_certificate(ReadonlyBytes);
  339. ssize_t handle_server_key_exchange(ReadonlyBytes);
  340. ssize_t handle_server_hello_done(ReadonlyBytes);
  341. ssize_t handle_certificate_verify(ReadonlyBytes);
  342. ssize_t handle_handshake_payload(ReadonlyBytes);
  343. ssize_t handle_message(ReadonlyBytes);
  344. ssize_t handle_random(ReadonlyBytes);
  345. size_t asn1_length(ReadonlyBytes, size_t* octets);
  346. void pseudorandom_function(Bytes output, ReadonlyBytes secret, const u8* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b);
  347. size_t key_length() const
  348. {
  349. switch (m_context.cipher) {
  350. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  351. case suite: \
  352. return cipher_key_size(cipher) / 8;
  353. ENUMERATE_CIPHERS(C)
  354. #undef C
  355. default:
  356. return 128 / 8;
  357. }
  358. }
  359. size_t mac_length() const
  360. {
  361. switch (m_context.cipher) {
  362. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  363. case suite: \
  364. return hash ::digest_size();
  365. ENUMERATE_CIPHERS(C)
  366. #undef C
  367. default:
  368. return Crypto::Hash::SHA256::digest_size();
  369. }
  370. }
  371. Crypto::Hash::HashKind hmac_hash() const
  372. {
  373. switch (mac_length()) {
  374. case Crypto::Hash::SHA512::DigestSize:
  375. return Crypto::Hash::HashKind::SHA512;
  376. case Crypto::Hash::SHA384::DigestSize:
  377. return Crypto::Hash::HashKind::SHA384;
  378. case Crypto::Hash::SHA256::DigestSize:
  379. case Crypto::Hash::SHA1::DigestSize:
  380. default:
  381. return Crypto::Hash::HashKind::SHA256;
  382. }
  383. }
  384. size_t iv_length() const
  385. {
  386. switch (m_context.cipher) {
  387. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  388. case suite: \
  389. return iv_size;
  390. ENUMERATE_CIPHERS(C)
  391. #undef C
  392. default:
  393. return 16;
  394. }
  395. }
  396. bool is_aead() const
  397. {
  398. switch (m_context.cipher) {
  399. #define C(is_supported, suite, key_exchange, cipher, hash, iv_size, is_aead) \
  400. case suite: \
  401. return is_aead;
  402. ENUMERATE_CIPHERS(C)
  403. #undef C
  404. default:
  405. return false;
  406. }
  407. }
  408. bool expand_key();
  409. bool compute_master_secret_from_pre_master_secret(size_t length);
  410. Optional<size_t> verify_chain_and_get_matching_certificate(const StringView& host) const;
  411. void try_disambiguate_error() const;
  412. Context m_context;
  413. OwnPtr<Crypto::Authentication::HMAC<Crypto::Hash::Manager>> m_hmac_local;
  414. OwnPtr<Crypto::Authentication::HMAC<Crypto::Hash::Manager>> m_hmac_remote;
  415. using CipherVariant = Variant<
  416. Empty,
  417. Crypto::Cipher::AESCipher::CBCMode,
  418. Crypto::Cipher::AESCipher::GCMMode>;
  419. CipherVariant m_cipher_local { Empty {} };
  420. CipherVariant m_cipher_remote { Empty {} };
  421. bool m_has_scheduled_write_flush { false };
  422. i32 m_max_wait_time_for_handshake_in_seconds { 10 };
  423. RefPtr<Core::Timer> m_handshake_timeout_timer;
  424. };
  425. }