You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3283 lines
131 KiB

  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com).
  108. *
  109. */
  110. /* ====================================================================
  111. * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  112. * ECC cipher suite support in OpenSSL originally developed by
  113. * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
  114. */
  115. /* ====================================================================
  116. * Copyright 2005 Nokia. All rights reserved.
  117. *
  118. * The portions of the attached software ("Contribution") is developed by
  119. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  120. * license.
  121. *
  122. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  123. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  124. * support (see RFC 4279) to OpenSSL.
  125. *
  126. * No patent licenses or other rights except those expressly stated in
  127. * the OpenSSL open source license shall be deemed granted or received
  128. * expressly, by implication, estoppel, or otherwise.
  129. *
  130. * No assurances are provided by Nokia that the Contribution does not
  131. * infringe the patent or other intellectual property rights of any third
  132. * party or that the license provides you with all the necessary rights
  133. * to make use of the Contribution.
  134. *
  135. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  136. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  137. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  138. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  139. * OTHERWISE.
  140. */
  141. #ifndef OPENSSL_HEADER_SSL_INTERNAL_H
  142. #define OPENSSL_HEADER_SSL_INTERNAL_H
  143. #include <openssl/base.h>
  144. #include <stdlib.h>
  145. #include <limits>
  146. #include <new>
  147. #include <type_traits>
  148. #include <utility>
  149. #include <openssl/aead.h>
  150. #include <openssl/err.h>
  151. #include <openssl/lhash.h>
  152. #include <openssl/mem.h>
  153. #include <openssl/ssl.h>
  154. #include <openssl/span.h>
  155. #include <openssl/stack.h>
  156. #include "../crypto/err/internal.h"
  157. #include "../crypto/internal.h"
  158. #if defined(OPENSSL_WINDOWS)
  159. // Windows defines struct timeval in winsock2.h.
  160. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  161. #include <winsock2.h>
  162. OPENSSL_MSVC_PRAGMA(warning(pop))
  163. #else
  164. #include <sys/time.h>
  165. #endif
  166. namespace bssl {
  167. struct SSL_CONFIG;
  168. struct SSL_HANDSHAKE;
  169. struct SSL_PROTOCOL_METHOD;
  170. struct SSL_X509_METHOD;
  171. // C++ utilities.
  172. // New behaves like |new| but uses |OPENSSL_malloc| for memory allocation. It
  173. // returns nullptr on allocation error. It only implements single-object
  174. // allocation and not new T[n].
  175. //
  176. // Note: unlike |new|, this does not support non-public constructors.
  177. template <typename T, typename... Args>
  178. T *New(Args &&... args) {
  179. void *t = OPENSSL_malloc(sizeof(T));
  180. if (t == nullptr) {
  181. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  182. return nullptr;
  183. }
  184. return new (t) T(std::forward<Args>(args)...);
  185. }
  186. // Delete behaves like |delete| but uses |OPENSSL_free| to release memory.
  187. //
  188. // Note: unlike |delete| this does not support non-public destructors.
  189. template <typename T>
  190. void Delete(T *t) {
  191. if (t != nullptr) {
  192. t->~T();
  193. OPENSSL_free(t);
  194. }
  195. }
  196. // All types with kAllowUniquePtr set may be used with UniquePtr. Other types
  197. // may be C structs which require a |BORINGSSL_MAKE_DELETER| registration.
  198. namespace internal {
  199. template <typename T>
  200. struct DeleterImpl<T, typename std::enable_if<T::kAllowUniquePtr>::type> {
  201. static void Free(T *t) { Delete(t); }
  202. };
  203. }
  204. // MakeUnique behaves like |std::make_unique| but returns nullptr on allocation
  205. // error.
  206. template <typename T, typename... Args>
  207. UniquePtr<T> MakeUnique(Args &&... args) {
  208. return UniquePtr<T>(New<T>(std::forward<Args>(args)...));
  209. }
  210. #if defined(BORINGSSL_ALLOW_CXX_RUNTIME)
  211. #define HAS_VIRTUAL_DESTRUCTOR
  212. #define PURE_VIRTUAL = 0
  213. #else
  214. // HAS_VIRTUAL_DESTRUCTOR should be declared in any base class which defines a
  215. // virtual destructor. This avoids a dependency on |_ZdlPv| and prevents the
  216. // class from being used with |delete|.
  217. #define HAS_VIRTUAL_DESTRUCTOR \
  218. void operator delete(void *) { abort(); }
  219. // PURE_VIRTUAL should be used instead of = 0 when defining pure-virtual
  220. // functions. This avoids a dependency on |__cxa_pure_virtual| but loses
  221. // compile-time checking.
  222. #define PURE_VIRTUAL { abort(); }
  223. #endif
  224. // CONSTEXPR_ARRAY works around a VS 2015 bug where ranged for loops don't work
  225. // on constexpr arrays.
  226. #if defined(_MSC_VER) && !defined(__clang__) && _MSC_VER < 1910
  227. #define CONSTEXPR_ARRAY const
  228. #else
  229. #define CONSTEXPR_ARRAY constexpr
  230. #endif
  231. // Array<T> is an owning array of elements of |T|.
  232. template <typename T>
  233. class Array {
  234. public:
  235. // Array's default constructor creates an empty array.
  236. Array() {}
  237. Array(const Array &) = delete;
  238. Array(Array &&other) { *this = std::move(other); }
  239. ~Array() { Reset(); }
  240. Array &operator=(const Array &) = delete;
  241. Array &operator=(Array &&other) {
  242. Reset();
  243. other.Release(&data_, &size_);
  244. return *this;
  245. }
  246. const T *data() const { return data_; }
  247. T *data() { return data_; }
  248. size_t size() const { return size_; }
  249. bool empty() const { return size_ == 0; }
  250. const T &operator[](size_t i) const { return data_[i]; }
  251. T &operator[](size_t i) { return data_[i]; }
  252. T *begin() { return data_; }
  253. const T *cbegin() const { return data_; }
  254. T *end() { return data_ + size_; }
  255. const T *cend() const { return data_ + size_; }
  256. void Reset() { Reset(nullptr, 0); }
  257. // Reset releases the current contents of the array and takes ownership of the
  258. // raw pointer supplied by the caller.
  259. void Reset(T *new_data, size_t new_size) {
  260. for (size_t i = 0; i < size_; i++) {
  261. data_[i].~T();
  262. }
  263. OPENSSL_free(data_);
  264. data_ = new_data;
  265. size_ = new_size;
  266. }
  267. // Release releases ownership of the array to a raw pointer supplied by the
  268. // caller.
  269. void Release(T **out, size_t *out_size) {
  270. *out = data_;
  271. *out_size = size_;
  272. data_ = nullptr;
  273. size_ = 0;
  274. }
  275. // Init replaces the array with a newly-allocated array of |new_size|
  276. // default-constructed copies of |T|. It returns true on success and false on
  277. // error.
  278. //
  279. // Note that if |T| is a primitive type like |uint8_t|, it is uninitialized.
  280. bool Init(size_t new_size) {
  281. Reset();
  282. if (new_size == 0) {
  283. return true;
  284. }
  285. if (new_size > std::numeric_limits<size_t>::max() / sizeof(T)) {
  286. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  287. return false;
  288. }
  289. data_ = reinterpret_cast<T*>(OPENSSL_malloc(new_size * sizeof(T)));
  290. if (data_ == nullptr) {
  291. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  292. return false;
  293. }
  294. size_ = new_size;
  295. for (size_t i = 0; i < size_; i++) {
  296. new (&data_[i]) T;
  297. }
  298. return true;
  299. }
  300. // CopyFrom replaces the array with a newly-allocated copy of |in|. It returns
  301. // true on success and false on error.
  302. bool CopyFrom(Span<const T> in) {
  303. if (!Init(in.size())) {
  304. return false;
  305. }
  306. OPENSSL_memcpy(data_, in.data(), sizeof(T) * in.size());
  307. return true;
  308. }
  309. private:
  310. T *data_ = nullptr;
  311. size_t size_ = 0;
  312. };
  313. // CBBFinishArray behaves like |CBB_finish| but stores the result in an Array.
  314. OPENSSL_EXPORT bool CBBFinishArray(CBB *cbb, Array<uint8_t> *out);
  315. // Protocol versions.
  316. //
  317. // Due to DTLS's historical wire version differences and to support multiple
  318. // variants of the same protocol during development, we maintain two notions of
  319. // version.
  320. //
  321. // The "version" or "wire version" is the actual 16-bit value that appears on
  322. // the wire. It uniquely identifies a version and is also used at API
  323. // boundaries. The set of supported versions differs between TLS and DTLS. Wire
  324. // versions are opaque values and may not be compared numerically.
  325. //
  326. // The "protocol version" identifies the high-level handshake variant being
  327. // used. DTLS versions map to the corresponding TLS versions. Draft TLS 1.3
  328. // variants all map to TLS 1.3. Protocol versions are sequential and may be
  329. // compared numerically.
  330. // ssl_protocol_version_from_wire sets |*out| to the protocol version
  331. // corresponding to wire version |version| and returns true. If |version| is not
  332. // a valid TLS or DTLS version, it returns false.
  333. //
  334. // Note this simultaneously handles both DTLS and TLS. Use one of the
  335. // higher-level functions below for most operations.
  336. bool ssl_protocol_version_from_wire(uint16_t *out, uint16_t version);
  337. // ssl_get_version_range sets |*out_min_version| and |*out_max_version| to the
  338. // minimum and maximum enabled protocol versions, respectively.
  339. bool ssl_get_version_range(const SSL_HANDSHAKE *hs, uint16_t *out_min_version,
  340. uint16_t *out_max_version);
  341. // ssl_supports_version returns whether |hs| supports |version|.
  342. bool ssl_supports_version(SSL_HANDSHAKE *hs, uint16_t version);
  343. // ssl_method_supports_version returns whether |method| supports |version|.
  344. bool ssl_method_supports_version(const SSL_PROTOCOL_METHOD *method,
  345. uint16_t version);
  346. // ssl_add_supported_versions writes the supported versions of |hs| to |cbb|, in
  347. // decreasing preference order.
  348. bool ssl_add_supported_versions(SSL_HANDSHAKE *hs, CBB *cbb);
  349. // ssl_negotiate_version negotiates a common version based on |hs|'s preferences
  350. // and the peer preference list in |peer_versions|. On success, it returns true
  351. // and sets |*out_version| to the selected version. Otherwise, it returns false
  352. // and sets |*out_alert| to an alert to send.
  353. bool ssl_negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
  354. uint16_t *out_version, const CBS *peer_versions);
  355. // ssl_protocol_version returns |ssl|'s protocol version. It is an error to
  356. // call this function before the version is determined.
  357. uint16_t ssl_protocol_version(const SSL *ssl);
  358. // ssl_is_draft28 returns whether the version corresponds to a draft28 TLS 1.3
  359. // variant.
  360. bool ssl_is_draft28(uint16_t version);
  361. // Cipher suites.
  362. } // namespace bssl
  363. struct ssl_cipher_st {
  364. // name is the OpenSSL name for the cipher.
  365. const char *name;
  366. // standard_name is the IETF name for the cipher.
  367. const char *standard_name;
  368. // id is the cipher suite value bitwise OR-d with 0x03000000.
  369. uint32_t id;
  370. // algorithm_* determine the cipher suite. See constants below for the values.
  371. uint32_t algorithm_mkey;
  372. uint32_t algorithm_auth;
  373. uint32_t algorithm_enc;
  374. uint32_t algorithm_mac;
  375. uint32_t algorithm_prf;
  376. };
  377. namespace bssl {
  378. // Bits for |algorithm_mkey| (key exchange algorithm).
  379. #define SSL_kRSA 0x00000001u
  380. #define SSL_kECDHE 0x00000002u
  381. // SSL_kPSK is only set for plain PSK, not ECDHE_PSK.
  382. #define SSL_kPSK 0x00000004u
  383. #define SSL_kGENERIC 0x00000008u
  384. // Bits for |algorithm_auth| (server authentication).
  385. #define SSL_aRSA 0x00000001u
  386. #define SSL_aECDSA 0x00000002u
  387. // SSL_aPSK is set for both PSK and ECDHE_PSK.
  388. #define SSL_aPSK 0x00000004u
  389. #define SSL_aGENERIC 0x00000008u
  390. #define SSL_aCERT (SSL_aRSA | SSL_aECDSA)
  391. // Bits for |algorithm_enc| (symmetric encryption).
  392. #define SSL_3DES 0x00000001u
  393. #define SSL_AES128 0x00000002u
  394. #define SSL_AES256 0x00000004u
  395. #define SSL_AES128GCM 0x00000008u
  396. #define SSL_AES256GCM 0x00000010u
  397. #define SSL_eNULL 0x00000020u
  398. #define SSL_CHACHA20POLY1305 0x00000040u
  399. #define SSL_AES (SSL_AES128 | SSL_AES256 | SSL_AES128GCM | SSL_AES256GCM)
  400. // Bits for |algorithm_mac| (symmetric authentication).
  401. #define SSL_SHA1 0x00000001u
  402. // SSL_AEAD is set for all AEADs.
  403. #define SSL_AEAD 0x00000002u
  404. // Bits for |algorithm_prf| (handshake digest).
  405. #define SSL_HANDSHAKE_MAC_DEFAULT 0x1
  406. #define SSL_HANDSHAKE_MAC_SHA256 0x2
  407. #define SSL_HANDSHAKE_MAC_SHA384 0x4
  408. // An SSLCipherPreferenceList contains a list of SSL_CIPHERs with equal-
  409. // preference groups. For TLS clients, the groups are moot because the server
  410. // picks the cipher and groups cannot be expressed on the wire. However, for
  411. // servers, the equal-preference groups allow the client's preferences to be
  412. // partially respected. (This only has an effect with
  413. // SSL_OP_CIPHER_SERVER_PREFERENCE).
  414. //
  415. // The equal-preference groups are expressed by grouping SSL_CIPHERs together.
  416. // All elements of a group have the same priority: no ordering is expressed
  417. // within a group.
  418. //
  419. // The values in |ciphers| are in one-to-one correspondence with
  420. // |in_group_flags|. (That is, sk_SSL_CIPHER_num(ciphers) is the number of
  421. // bytes in |in_group_flags|.) The bytes in |in_group_flags| are either 1, to
  422. // indicate that the corresponding SSL_CIPHER is not the last element of a
  423. // group, or 0 to indicate that it is.
  424. //
  425. // For example, if |in_group_flags| contains all zeros then that indicates a
  426. // traditional, fully-ordered preference. Every SSL_CIPHER is the last element
  427. // of the group (i.e. they are all in a one-element group).
  428. //
  429. // For a more complex example, consider:
  430. // ciphers: A B C D E F
  431. // in_group_flags: 1 1 0 0 1 0
  432. //
  433. // That would express the following, order:
  434. //
  435. // A E
  436. // B -> D -> F
  437. // C
  438. struct SSLCipherPreferenceList {
  439. static constexpr bool kAllowUniquePtr = true;
  440. SSLCipherPreferenceList() = default;
  441. ~SSLCipherPreferenceList();
  442. bool Init(UniquePtr<STACK_OF(SSL_CIPHER)> ciphers,
  443. Span<const bool> in_group_flags);
  444. UniquePtr<STACK_OF(SSL_CIPHER)> ciphers;
  445. bool *in_group_flags = nullptr;
  446. };
  447. // ssl_cipher_get_evp_aead sets |*out_aead| to point to the correct EVP_AEAD
  448. // object for |cipher| protocol version |version|. It sets |*out_mac_secret_len|
  449. // and |*out_fixed_iv_len| to the MAC key length and fixed IV length,
  450. // respectively. The MAC key length is zero except for legacy block and stream
  451. // ciphers. It returns true on success and false on error.
  452. bool ssl_cipher_get_evp_aead(const EVP_AEAD **out_aead,
  453. size_t *out_mac_secret_len,
  454. size_t *out_fixed_iv_len, const SSL_CIPHER *cipher,
  455. uint16_t version, int is_dtls);
  456. // ssl_get_handshake_digest returns the |EVP_MD| corresponding to |version| and
  457. // |cipher|.
  458. const EVP_MD *ssl_get_handshake_digest(uint16_t version,
  459. const SSL_CIPHER *cipher);
  460. // ssl_create_cipher_list evaluates |rule_str|. It sets |*out_cipher_list| to a
  461. // newly-allocated |SSLCipherPreferenceList| containing the result. It returns
  462. // true on success and false on failure. If |strict| is true, nonsense will be
  463. // rejected. If false, nonsense will be silently ignored. An empty result is
  464. // considered an error regardless of |strict|.
  465. bool ssl_create_cipher_list(UniquePtr<SSLCipherPreferenceList> *out_cipher_list,
  466. const char *rule_str, bool strict);
  467. // ssl_cipher_get_value returns the cipher suite id of |cipher|.
  468. uint16_t ssl_cipher_get_value(const SSL_CIPHER *cipher);
  469. // ssl_cipher_auth_mask_for_key returns the mask of cipher |algorithm_auth|
  470. // values suitable for use with |key| in TLS 1.2 and below.
  471. uint32_t ssl_cipher_auth_mask_for_key(const EVP_PKEY *key);
  472. // ssl_cipher_uses_certificate_auth returns whether |cipher| authenticates the
  473. // server and, optionally, the client with a certificate.
  474. bool ssl_cipher_uses_certificate_auth(const SSL_CIPHER *cipher);
  475. // ssl_cipher_requires_server_key_exchange returns whether |cipher| requires a
  476. // ServerKeyExchange message.
  477. //
  478. // This function may return false while still allowing |cipher| an optional
  479. // ServerKeyExchange. This is the case for plain PSK ciphers.
  480. bool ssl_cipher_requires_server_key_exchange(const SSL_CIPHER *cipher);
  481. // ssl_cipher_get_record_split_len, for TLS 1.0 CBC mode ciphers, returns the
  482. // length of an encrypted 1-byte record, for use in record-splitting. Otherwise
  483. // it returns zero.
  484. size_t ssl_cipher_get_record_split_len(const SSL_CIPHER *cipher);
  485. // Transcript layer.
  486. // SSLTranscript maintains the handshake transcript as a combination of a
  487. // buffer and running hash.
  488. class SSLTranscript {
  489. public:
  490. SSLTranscript();
  491. ~SSLTranscript();
  492. // Init initializes the handshake transcript. If called on an existing
  493. // transcript, it resets the transcript and hash. It returns true on success
  494. // and false on failure.
  495. bool Init();
  496. // InitHash initializes the handshake hash based on the PRF and contents of
  497. // the handshake transcript. Subsequent calls to |Update| will update the
  498. // rolling hash. It returns one on success and zero on failure. It is an error
  499. // to call this function after the handshake buffer is released.
  500. bool InitHash(uint16_t version, const SSL_CIPHER *cipher);
  501. // UpdateForHelloRetryRequest resets the rolling hash with the
  502. // HelloRetryRequest construction. It returns true on success and false on
  503. // failure. It is an error to call this function before the handshake buffer
  504. // is released.
  505. bool UpdateForHelloRetryRequest();
  506. // CopyHashContext copies the hash context into |ctx| and returns true on
  507. // success.
  508. bool CopyHashContext(EVP_MD_CTX *ctx);
  509. Span<const uint8_t> buffer() {
  510. return MakeConstSpan(reinterpret_cast<const uint8_t *>(buffer_->data),
  511. buffer_->length);
  512. }
  513. // FreeBuffer releases the handshake buffer. Subsequent calls to
  514. // |Update| will not update the handshake buffer.
  515. void FreeBuffer();
  516. // DigestLen returns the length of the PRF hash.
  517. size_t DigestLen() const;
  518. // Digest returns the PRF hash. For TLS 1.1 and below, this is
  519. // |EVP_md5_sha1|.
  520. const EVP_MD *Digest() const;
  521. // Update adds |in| to the handshake buffer and handshake hash, whichever is
  522. // enabled. It returns true on success and false on failure.
  523. bool Update(Span<const uint8_t> in);
  524. // GetHash writes the handshake hash to |out| which must have room for at
  525. // least |DigestLen| bytes. On success, it returns true and sets |*out_len| to
  526. // the number of bytes written. Otherwise, it returns false.
  527. bool GetHash(uint8_t *out, size_t *out_len);
  528. // GetFinishedMAC computes the MAC for the Finished message into the bytes
  529. // pointed by |out| and writes the number of bytes to |*out_len|. |out| must
  530. // have room for |EVP_MAX_MD_SIZE| bytes. It returns true on success and false
  531. // on failure.
  532. bool GetFinishedMAC(uint8_t *out, size_t *out_len, const SSL_SESSION *session,
  533. bool from_server);
  534. private:
  535. // buffer_, if non-null, contains the handshake transcript.
  536. UniquePtr<BUF_MEM> buffer_;
  537. // hash, if initialized with an |EVP_MD|, maintains the handshake hash.
  538. ScopedEVP_MD_CTX hash_;
  539. };
  540. // tls1_prf computes the PRF function for |ssl|. It fills |out|, using |secret|
  541. // as the secret and |label| as the label. |seed1| and |seed2| are concatenated
  542. // to form the seed parameter. It returns true on success and false on failure.
  543. bool tls1_prf(const EVP_MD *digest, Span<uint8_t> out,
  544. Span<const uint8_t> secret, Span<const char> label,
  545. Span<const uint8_t> seed1, Span<const uint8_t> seed2);
  546. // Encryption layer.
  547. // SSLAEADContext contains information about an AEAD that is being used to
  548. // encrypt an SSL connection.
  549. class SSLAEADContext {
  550. public:
  551. SSLAEADContext(uint16_t version, bool is_dtls, const SSL_CIPHER *cipher);
  552. ~SSLAEADContext();
  553. static constexpr bool kAllowUniquePtr = true;
  554. SSLAEADContext(const SSLAEADContext &&) = delete;
  555. SSLAEADContext &operator=(const SSLAEADContext &&) = delete;
  556. // CreateNullCipher creates an |SSLAEADContext| for the null cipher.
  557. static UniquePtr<SSLAEADContext> CreateNullCipher(bool is_dtls);
  558. // Create creates an |SSLAEADContext| using the supplied key material. It
  559. // returns nullptr on error. Only one of |Open| or |Seal| may be used with the
  560. // resulting object, depending on |direction|. |version| is the normalized
  561. // protocol version, so DTLS 1.0 is represented as 0x0301, not 0xffef.
  562. static UniquePtr<SSLAEADContext> Create(enum evp_aead_direction_t direction,
  563. uint16_t version, int is_dtls,
  564. const SSL_CIPHER *cipher,
  565. Span<const uint8_t> enc_key,
  566. Span<const uint8_t> mac_key,
  567. Span<const uint8_t> fixed_iv);
  568. // SetVersionIfNullCipher sets the version the SSLAEADContext for the null
  569. // cipher, to make version-specific determinations in the record layer prior
  570. // to a cipher being selected.
  571. void SetVersionIfNullCipher(uint16_t version);
  572. // ProtocolVersion returns the protocol version associated with this
  573. // SSLAEADContext. It can only be called once |version_| has been set to a
  574. // valid value.
  575. uint16_t ProtocolVersion() const;
  576. // RecordVersion returns the record version that should be used with this
  577. // SSLAEADContext for record construction and crypto.
  578. uint16_t RecordVersion() const;
  579. const SSL_CIPHER *cipher() const { return cipher_; }
  580. // is_null_cipher returns true if this is the null cipher.
  581. bool is_null_cipher() const { return !cipher_; }
  582. // ExplicitNonceLen returns the length of the explicit nonce.
  583. size_t ExplicitNonceLen() const;
  584. // MaxOverhead returns the maximum overhead of calling |Seal|.
  585. size_t MaxOverhead() const;
  586. // SuffixLen calculates the suffix length written by |SealScatter| and writes
  587. // it to |*out_suffix_len|. It returns true on success and false on error.
  588. // |in_len| and |extra_in_len| should equal the argument of the same names
  589. // passed to |SealScatter|.
  590. bool SuffixLen(size_t *out_suffix_len, size_t in_len,
  591. size_t extra_in_len) const;
  592. // CiphertextLen calculates the total ciphertext length written by
  593. // |SealScatter| and writes it to |*out_len|. It returns true on success and
  594. // false on error. |in_len| and |extra_in_len| should equal the argument of
  595. // the same names passed to |SealScatter|.
  596. bool CiphertextLen(size_t *out_len, size_t in_len, size_t extra_in_len) const;
  597. // Open authenticates and decrypts |in| in-place. On success, it sets |*out|
  598. // to the plaintext in |in| and returns true. Otherwise, it returns
  599. // false. The output will always be |ExplicitNonceLen| bytes ahead of |in|.
  600. bool Open(Span<uint8_t> *out, uint8_t type, uint16_t record_version,
  601. const uint8_t seqnum[8], Span<const uint8_t> header,
  602. Span<uint8_t> in);
  603. // Seal encrypts and authenticates |in_len| bytes from |in| and writes the
  604. // result to |out|. It returns true on success and false on error.
  605. //
  606. // If |in| and |out| alias then |out| + |ExplicitNonceLen| must be == |in|.
  607. bool Seal(uint8_t *out, size_t *out_len, size_t max_out, uint8_t type,
  608. uint16_t record_version, const uint8_t seqnum[8],
  609. Span<const uint8_t> header, const uint8_t *in, size_t in_len);
  610. // SealScatter encrypts and authenticates |in_len| bytes from |in| and splits
  611. // the result between |out_prefix|, |out| and |out_suffix|. It returns one on
  612. // success and zero on error.
  613. //
  614. // On successful return, exactly |ExplicitNonceLen| bytes are written to
  615. // |out_prefix|, |in_len| bytes to |out|, and |SuffixLen| bytes to
  616. // |out_suffix|.
  617. //
  618. // |extra_in| may point to an additional plaintext buffer. If present,
  619. // |extra_in_len| additional bytes are encrypted and authenticated, and the
  620. // ciphertext is written to the beginning of |out_suffix|. |SuffixLen| should
  621. // be used to size |out_suffix| accordingly.
  622. //
  623. // If |in| and |out| alias then |out| must be == |in|. Other arguments may not
  624. // alias anything.
  625. bool SealScatter(uint8_t *out_prefix, uint8_t *out, uint8_t *out_suffix,
  626. uint8_t type, uint16_t record_version,
  627. const uint8_t seqnum[8], Span<const uint8_t> header,
  628. const uint8_t *in, size_t in_len, const uint8_t *extra_in,
  629. size_t extra_in_len);
  630. bool GetIV(const uint8_t **out_iv, size_t *out_iv_len) const;
  631. private:
  632. // GetAdditionalData returns the additional data, writing into |storage| if
  633. // necessary.
  634. Span<const uint8_t> GetAdditionalData(uint8_t storage[13], uint8_t type,
  635. uint16_t record_version,
  636. const uint8_t seqnum[8],
  637. size_t plaintext_len,
  638. Span<const uint8_t> header);
  639. const SSL_CIPHER *cipher_;
  640. ScopedEVP_AEAD_CTX ctx_;
  641. // fixed_nonce_ contains any bytes of the nonce that are fixed for all
  642. // records.
  643. uint8_t fixed_nonce_[12];
  644. uint8_t fixed_nonce_len_ = 0, variable_nonce_len_ = 0;
  645. // version_ is the wire version that should be used with this AEAD.
  646. uint16_t version_;
  647. // is_dtls_ is whether DTLS is being used with this AEAD.
  648. bool is_dtls_;
  649. // variable_nonce_included_in_record_ is true if the variable nonce
  650. // for a record is included as a prefix before the ciphertext.
  651. bool variable_nonce_included_in_record_ : 1;
  652. // random_variable_nonce_ is true if the variable nonce is
  653. // randomly generated, rather than derived from the sequence
  654. // number.
  655. bool random_variable_nonce_ : 1;
  656. // xor_fixed_nonce_ is true if the fixed nonce should be XOR'd into the
  657. // variable nonce rather than prepended.
  658. bool xor_fixed_nonce_ : 1;
  659. // omit_length_in_ad_ is true if the length should be omitted in the
  660. // AEAD's ad parameter.
  661. bool omit_length_in_ad_ : 1;
  662. // omit_ad_ is true if the AEAD's ad parameter should be omitted.
  663. bool omit_ad_ : 1;
  664. // ad_is_header_ is true if the AEAD's ad parameter is the record header.
  665. bool ad_is_header_ : 1;
  666. };
  667. // DTLS replay bitmap.
  668. // DTLS1_BITMAP maintains a sliding window of 64 sequence numbers to detect
  669. // replayed packets. It should be initialized by zeroing every field.
  670. struct DTLS1_BITMAP {
  671. // map is a bit mask of the last 64 sequence numbers. Bit
  672. // |1<<i| corresponds to |max_seq_num - i|.
  673. uint64_t map = 0;
  674. // max_seq_num is the largest sequence number seen so far as a 64-bit
  675. // integer.
  676. uint64_t max_seq_num = 0;
  677. };
  678. // Record layer.
  679. // ssl_record_sequence_update increments the sequence number in |seq|. It
  680. // returns one on success and zero on wraparound.
  681. int ssl_record_sequence_update(uint8_t *seq, size_t seq_len);
  682. // ssl_record_prefix_len returns the length of the prefix before the ciphertext
  683. // of a record for |ssl|.
  684. //
  685. // TODO(davidben): Expose this as part of public API once the high-level
  686. // buffer-free APIs are available.
  687. size_t ssl_record_prefix_len(const SSL *ssl);
  688. enum ssl_open_record_t {
  689. ssl_open_record_success,
  690. ssl_open_record_discard,
  691. ssl_open_record_partial,
  692. ssl_open_record_close_notify,
  693. ssl_open_record_error,
  694. };
  695. // tls_open_record decrypts a record from |in| in-place.
  696. //
  697. // If the input did not contain a complete record, it returns
  698. // |ssl_open_record_partial|. It sets |*out_consumed| to the total number of
  699. // bytes necessary. It is guaranteed that a successful call to |tls_open_record|
  700. // will consume at least that many bytes.
  701. //
  702. // Otherwise, it sets |*out_consumed| to the number of bytes of input
  703. // consumed. Note that input may be consumed on all return codes if a record was
  704. // decrypted.
  705. //
  706. // On success, it returns |ssl_open_record_success|. It sets |*out_type| to the
  707. // record type and |*out| to the record body in |in|. Note that |*out| may be
  708. // empty.
  709. //
  710. // If a record was successfully processed but should be discarded, it returns
  711. // |ssl_open_record_discard|.
  712. //
  713. // If a record was successfully processed but is a close_notify, it returns
  714. // |ssl_open_record_close_notify|.
  715. //
  716. // On failure or fatal alert, it returns |ssl_open_record_error| and sets
  717. // |*out_alert| to an alert to emit, or zero if no alert should be emitted.
  718. enum ssl_open_record_t tls_open_record(SSL *ssl, uint8_t *out_type,
  719. Span<uint8_t> *out, size_t *out_consumed,
  720. uint8_t *out_alert, Span<uint8_t> in);
  721. // dtls_open_record implements |tls_open_record| for DTLS. It only returns
  722. // |ssl_open_record_partial| if |in| was empty and sets |*out_consumed| to
  723. // zero. The caller should read one packet and try again.
  724. enum ssl_open_record_t dtls_open_record(SSL *ssl, uint8_t *out_type,
  725. Span<uint8_t> *out,
  726. size_t *out_consumed,
  727. uint8_t *out_alert, Span<uint8_t> in);
  728. // ssl_seal_align_prefix_len returns the length of the prefix before the start
  729. // of the bulk of the ciphertext when sealing a record with |ssl|. Callers may
  730. // use this to align buffers.
  731. //
  732. // Note when TLS 1.0 CBC record-splitting is enabled, this includes the one byte
  733. // record and is the offset into second record's ciphertext. Thus sealing a
  734. // small record may result in a smaller output than this value.
  735. //
  736. // TODO(davidben): Is this alignment valuable? Record-splitting makes this a
  737. // mess.
  738. size_t ssl_seal_align_prefix_len(const SSL *ssl);
  739. // tls_seal_record seals a new record of type |type| and body |in| and writes it
  740. // to |out|. At most |max_out| bytes will be written. It returns one on success
  741. // and zero on error. If enabled, |tls_seal_record| implements TLS 1.0 CBC 1/n-1
  742. // record splitting and may write two records concatenated.
  743. //
  744. // For a large record, the bulk of the ciphertext will begin
  745. // |ssl_seal_align_prefix_len| bytes into out. Aligning |out| appropriately may
  746. // improve performance. It writes at most |in_len| + |SSL_max_seal_overhead|
  747. // bytes to |out|.
  748. //
  749. // |in| and |out| may not alias.
  750. int tls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
  751. uint8_t type, const uint8_t *in, size_t in_len);
  752. enum dtls1_use_epoch_t {
  753. dtls1_use_previous_epoch,
  754. dtls1_use_current_epoch,
  755. };
  756. // dtls_max_seal_overhead returns the maximum overhead, in bytes, of sealing a
  757. // record.
  758. size_t dtls_max_seal_overhead(const SSL *ssl, enum dtls1_use_epoch_t use_epoch);
  759. // dtls_seal_prefix_len returns the number of bytes of prefix to reserve in
  760. // front of the plaintext when sealing a record in-place.
  761. size_t dtls_seal_prefix_len(const SSL *ssl, enum dtls1_use_epoch_t use_epoch);
  762. // dtls_seal_record implements |tls_seal_record| for DTLS. |use_epoch| selects
  763. // which epoch's cipher state to use. Unlike |tls_seal_record|, |in| and |out|
  764. // may alias but, if they do, |in| must be exactly |dtls_seal_prefix_len| bytes
  765. // ahead of |out|.
  766. int dtls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
  767. uint8_t type, const uint8_t *in, size_t in_len,
  768. enum dtls1_use_epoch_t use_epoch);
  769. // ssl_process_alert processes |in| as an alert and updates |ssl|'s shutdown
  770. // state. It returns one of |ssl_open_record_discard|, |ssl_open_record_error|,
  771. // |ssl_open_record_close_notify|, or |ssl_open_record_fatal_alert| as
  772. // appropriate.
  773. enum ssl_open_record_t ssl_process_alert(SSL *ssl, uint8_t *out_alert,
  774. Span<const uint8_t> in);
  775. // Private key operations.
  776. // ssl_has_private_key returns one if |cfg| has a private key configured and
  777. // zero otherwise.
  778. int ssl_has_private_key(const SSL_CONFIG *cfg);
  779. // ssl_private_key_* perform the corresponding operation on
  780. // |SSL_PRIVATE_KEY_METHOD|. If there is a custom private key configured, they
  781. // call the corresponding function or |complete| depending on whether there is a
  782. // pending operation. Otherwise, they implement the operation with
  783. // |EVP_PKEY|.
  784. enum ssl_private_key_result_t ssl_private_key_sign(
  785. SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len, size_t max_out,
  786. uint16_t sigalg, Span<const uint8_t> in);
  787. enum ssl_private_key_result_t ssl_private_key_decrypt(SSL_HANDSHAKE *hs,
  788. uint8_t *out,
  789. size_t *out_len,
  790. size_t max_out,
  791. Span<const uint8_t> in);
  792. // ssl_private_key_supports_signature_algorithm returns whether |hs|'s private
  793. // key supports |sigalg|.
  794. bool ssl_private_key_supports_signature_algorithm(SSL_HANDSHAKE *hs,
  795. uint16_t sigalg);
  796. // ssl_public_key_verify verifies that the |signature| is valid for the public
  797. // key |pkey| and input |in|, using the signature algorithm |sigalg|.
  798. bool ssl_public_key_verify(SSL *ssl, Span<const uint8_t> signature,
  799. uint16_t sigalg, EVP_PKEY *pkey,
  800. Span<const uint8_t> in);
  801. // Key shares.
  802. // SSLKeyShare abstracts over Diffie-Hellman-like key exchanges.
  803. class SSLKeyShare {
  804. public:
  805. virtual ~SSLKeyShare() {}
  806. static constexpr bool kAllowUniquePtr = true;
  807. HAS_VIRTUAL_DESTRUCTOR
  808. // Create returns a SSLKeyShare instance for use with group |group_id| or
  809. // nullptr on error.
  810. static UniquePtr<SSLKeyShare> Create(uint16_t group_id);
  811. // Create deserializes an SSLKeyShare instance previously serialized by
  812. // |Serialize|.
  813. static UniquePtr<SSLKeyShare> Create(CBS *in);
  814. // GroupID returns the group ID.
  815. virtual uint16_t GroupID() const PURE_VIRTUAL;
  816. // Offer generates a keypair and writes the public value to
  817. // |out_public_key|. It returns true on success and false on error.
  818. virtual bool Offer(CBB *out_public_key) PURE_VIRTUAL;
  819. // Accept performs a key exchange against the |peer_key| generated by |offer|.
  820. // On success, it returns true, writes the public value to |out_public_key|,
  821. // and sets |*out_secret| the shared secret. On failure, it returns false and
  822. // sets |*out_alert| to an alert to send to the peer.
  823. //
  824. // The default implementation calls |Offer| and then |Finish|, assuming a key
  825. // exchange protocol where the peers are symmetric.
  826. virtual bool Accept(CBB *out_public_key, Array<uint8_t> *out_secret,
  827. uint8_t *out_alert, Span<const uint8_t> peer_key);
  828. // Finish performs a key exchange against the |peer_key| generated by
  829. // |Accept|. On success, it returns true and sets |*out_secret| to the shared
  830. // secret. On failure, it returns zero and sets |*out_alert| to an alert to
  831. // send to the peer.
  832. virtual bool Finish(Array<uint8_t> *out_secret, uint8_t *out_alert,
  833. Span<const uint8_t> peer_key) PURE_VIRTUAL;
  834. // Serialize writes the state of the key exchange to |out|, returning true if
  835. // successful and false otherwise.
  836. virtual bool Serialize(CBB *out) { return false; }
  837. // Deserialize initializes the state of the key exchange from |in|, returning
  838. // true if successful and false otherwise. It is called by |Create|.
  839. virtual bool Deserialize(CBS *in) { return false; }
  840. };
  841. // ssl_nid_to_group_id looks up the group corresponding to |nid|. On success, it
  842. // sets |*out_group_id| to the group ID and returns one. Otherwise, it returns
  843. // zero.
  844. int ssl_nid_to_group_id(uint16_t *out_group_id, int nid);
  845. // ssl_name_to_group_id looks up the group corresponding to the |name| string
  846. // of length |len|. On success, it sets |*out_group_id| to the group ID and
  847. // returns one. Otherwise, it returns zero.
  848. int ssl_name_to_group_id(uint16_t *out_group_id, const char *name, size_t len);
  849. // Handshake messages.
  850. struct SSLMessage {
  851. bool is_v2_hello;
  852. uint8_t type;
  853. CBS body;
  854. // raw is the entire serialized handshake message, including the TLS or DTLS
  855. // message header.
  856. CBS raw;
  857. };
  858. // SSL_MAX_HANDSHAKE_FLIGHT is the number of messages, including
  859. // ChangeCipherSpec, in the longest handshake flight. Currently this is the
  860. // client's second leg in a full handshake when client certificates, NPN, and
  861. // Channel ID, are all enabled.
  862. #define SSL_MAX_HANDSHAKE_FLIGHT 7
  863. extern const uint8_t kHelloRetryRequest[SSL3_RANDOM_SIZE];
  864. extern const uint8_t kDraftDowngradeRandom[8];
  865. // ssl_max_handshake_message_len returns the maximum number of bytes permitted
  866. // in a handshake message for |ssl|.
  867. size_t ssl_max_handshake_message_len(const SSL *ssl);
  868. // tls_can_accept_handshake_data returns whether |ssl| is able to accept more
  869. // data into handshake buffer.
  870. bool tls_can_accept_handshake_data(const SSL *ssl, uint8_t *out_alert);
  871. // tls_has_unprocessed_handshake_data returns whether there is buffered
  872. // handshake data that has not been consumed by |get_message|.
  873. bool tls_has_unprocessed_handshake_data(const SSL *ssl);
  874. // dtls_has_unprocessed_handshake_data behaves like
  875. // |tls_has_unprocessed_handshake_data| for DTLS.
  876. bool dtls_has_unprocessed_handshake_data(const SSL *ssl);
  877. // tls_flush_pending_hs_data flushes any handshake plaintext data.
  878. bool tls_flush_pending_hs_data(SSL *ssl);
  879. struct DTLS_OUTGOING_MESSAGE {
  880. DTLS_OUTGOING_MESSAGE() {}
  881. DTLS_OUTGOING_MESSAGE(const DTLS_OUTGOING_MESSAGE &) = delete;
  882. DTLS_OUTGOING_MESSAGE &operator=(const DTLS_OUTGOING_MESSAGE &) = delete;
  883. ~DTLS_OUTGOING_MESSAGE() { Clear(); }
  884. void Clear();
  885. uint8_t *data = nullptr;
  886. uint32_t len = 0;
  887. uint16_t epoch = 0;
  888. bool is_ccs = false;
  889. };
  890. // dtls_clear_outgoing_messages releases all buffered outgoing messages.
  891. void dtls_clear_outgoing_messages(SSL *ssl);
  892. // Callbacks.
  893. // ssl_do_info_callback calls |ssl|'s info callback, if set.
  894. void ssl_do_info_callback(const SSL *ssl, int type, int value);
  895. // ssl_do_msg_callback calls |ssl|'s message callback, if set.
  896. void ssl_do_msg_callback(SSL *ssl, int is_write, int content_type,
  897. Span<const uint8_t> in);
  898. // Transport buffers.
  899. class SSLBuffer {
  900. public:
  901. SSLBuffer() {}
  902. ~SSLBuffer() { Clear(); }
  903. SSLBuffer(const SSLBuffer &) = delete;
  904. SSLBuffer &operator=(const SSLBuffer &) = delete;
  905. uint8_t *data() { return buf_ + offset_; }
  906. size_t size() const { return size_; }
  907. bool empty() const { return size_ == 0; }
  908. size_t cap() const { return cap_; }
  909. Span<uint8_t> span() { return MakeSpan(data(), size()); }
  910. Span<uint8_t> remaining() {
  911. return MakeSpan(data() + size(), cap() - size());
  912. }
  913. // Clear releases the buffer.
  914. void Clear();
  915. // EnsureCap ensures the buffer has capacity at least |new_cap|, aligned such
  916. // that data written after |header_len| is aligned to a
  917. // |SSL3_ALIGN_PAYLOAD|-byte boundary. It returns true on success and false
  918. // on error.
  919. bool EnsureCap(size_t header_len, size_t new_cap);
  920. // DidWrite extends the buffer by |len|. The caller must have filled in to
  921. // this point.
  922. void DidWrite(size_t len);
  923. // Consume consumes |len| bytes from the front of the buffer. The memory
  924. // consumed will remain valid until the next call to |DiscardConsumed| or
  925. // |Clear|.
  926. void Consume(size_t len);
  927. // DiscardConsumed discards the consumed bytes from the buffer. If the buffer
  928. // is now empty, it releases memory used by it.
  929. void DiscardConsumed();
  930. private:
  931. // buf_ is the memory allocated for this buffer.
  932. uint8_t *buf_ = nullptr;
  933. // offset_ is the offset into |buf_| which the buffer contents start at.
  934. uint16_t offset_ = 0;
  935. // size_ is the size of the buffer contents from |buf_| + |offset_|.
  936. uint16_t size_ = 0;
  937. // cap_ is how much memory beyond |buf_| + |offset_| is available.
  938. uint16_t cap_ = 0;
  939. };
  940. // ssl_read_buffer_extend_to extends the read buffer to the desired length. For
  941. // TLS, it reads to the end of the buffer until the buffer is |len| bytes
  942. // long. For DTLS, it reads a new packet and ignores |len|. It returns one on
  943. // success, zero on EOF, and a negative number on error.
  944. //
  945. // It is an error to call |ssl_read_buffer_extend_to| in DTLS when the buffer is
  946. // non-empty.
  947. int ssl_read_buffer_extend_to(SSL *ssl, size_t len);
  948. // ssl_handle_open_record handles the result of passing |ssl->s3->read_buffer|
  949. // to a record-processing function. If |ret| is a success or if the caller
  950. // should retry, it returns one and sets |*out_retry|. Otherwise, it returns <=
  951. // 0.
  952. int ssl_handle_open_record(SSL *ssl, bool *out_retry, ssl_open_record_t ret,
  953. size_t consumed, uint8_t alert);
  954. // ssl_write_buffer_flush flushes the write buffer to the transport. It returns
  955. // one on success and <= 0 on error. For DTLS, whether or not the write
  956. // succeeds, the write buffer will be cleared.
  957. int ssl_write_buffer_flush(SSL *ssl);
  958. // Certificate functions.
  959. // ssl_has_certificate returns one if a certificate and private key are
  960. // configured and zero otherwise.
  961. int ssl_has_certificate(const SSL_CONFIG *cfg);
  962. // ssl_parse_cert_chain parses a certificate list from |cbs| in the format used
  963. // by a TLS Certificate message. On success, it advances |cbs| and returns
  964. // true. Otherwise, it returns false and sets |*out_alert| to an alert to send
  965. // to the peer.
  966. //
  967. // If the list is non-empty then |*out_chain| and |*out_pubkey| will be set to
  968. // the certificate chain and the leaf certificate's public key
  969. // respectively. Otherwise, both will be set to nullptr.
  970. //
  971. // If the list is non-empty and |out_leaf_sha256| is non-NULL, it writes the
  972. // SHA-256 hash of the leaf to |out_leaf_sha256|.
  973. bool ssl_parse_cert_chain(uint8_t *out_alert,
  974. UniquePtr<STACK_OF(CRYPTO_BUFFER)> *out_chain,
  975. UniquePtr<EVP_PKEY> *out_pubkey,
  976. uint8_t *out_leaf_sha256, CBS *cbs,
  977. CRYPTO_BUFFER_POOL *pool);
  978. // ssl_add_cert_chain adds |hs->ssl|'s certificate chain to |cbb| in the format
  979. // used by a TLS Certificate message. If there is no certificate chain, it emits
  980. // an empty certificate list. It returns one on success and zero on error.
  981. int ssl_add_cert_chain(SSL_HANDSHAKE *hs, CBB *cbb);
  982. // ssl_cert_check_digital_signature_key_usage parses the DER-encoded, X.509
  983. // certificate in |in| and returns one if doesn't specify a key usage or, if it
  984. // does, if it includes digitalSignature. Otherwise it pushes to the error
  985. // queue and returns zero.
  986. int ssl_cert_check_digital_signature_key_usage(const CBS *in);
  987. // ssl_cert_parse_pubkey extracts the public key from the DER-encoded, X.509
  988. // certificate in |in|. It returns an allocated |EVP_PKEY| or else returns
  989. // nullptr and pushes to the error queue.
  990. UniquePtr<EVP_PKEY> ssl_cert_parse_pubkey(const CBS *in);
  991. // ssl_parse_client_CA_list parses a CA list from |cbs| in the format used by a
  992. // TLS CertificateRequest message. On success, it returns a newly-allocated
  993. // |CRYPTO_BUFFER| list and advances |cbs|. Otherwise, it returns nullptr and
  994. // sets |*out_alert| to an alert to send to the peer.
  995. UniquePtr<STACK_OF(CRYPTO_BUFFER)> ssl_parse_client_CA_list(SSL *ssl,
  996. uint8_t *out_alert,
  997. CBS *cbs);
  998. // ssl_has_client_CAs returns there are configured CAs.
  999. bool ssl_has_client_CAs(const SSL_CONFIG *cfg);
  1000. // ssl_add_client_CA_list adds the configured CA list to |cbb| in the format
  1001. // used by a TLS CertificateRequest message. It returns one on success and zero
  1002. // on error.
  1003. int ssl_add_client_CA_list(SSL_HANDSHAKE *hs, CBB *cbb);
  1004. // ssl_check_leaf_certificate returns one if |pkey| and |leaf| are suitable as
  1005. // a server's leaf certificate for |hs|. Otherwise, it returns zero and pushes
  1006. // an error on the error queue.
  1007. int ssl_check_leaf_certificate(SSL_HANDSHAKE *hs, EVP_PKEY *pkey,
  1008. const CRYPTO_BUFFER *leaf);
  1009. // ssl_on_certificate_selected is called once the certificate has been selected.
  1010. // It finalizes the certificate and initializes |hs->local_pubkey|. It returns
  1011. // one on success and zero on error.
  1012. int ssl_on_certificate_selected(SSL_HANDSHAKE *hs);
  1013. // TLS 1.3 key derivation.
  1014. // tls13_init_key_schedule initializes the handshake hash and key derivation
  1015. // state, and incorporates the PSK. The cipher suite and PRF hash must have been
  1016. // selected at this point. It returns one on success and zero on error.
  1017. int tls13_init_key_schedule(SSL_HANDSHAKE *hs, const uint8_t *psk,
  1018. size_t psk_len);
  1019. // tls13_init_early_key_schedule initializes the handshake hash and key
  1020. // derivation state from the resumption secret and incorporates the PSK to
  1021. // derive the early secrets. It returns one on success and zero on error.
  1022. int tls13_init_early_key_schedule(SSL_HANDSHAKE *hs, const uint8_t *psk,
  1023. size_t psk_len);
  1024. // tls13_advance_key_schedule incorporates |in| into the key schedule with
  1025. // HKDF-Extract. It returns one on success and zero on error.
  1026. int tls13_advance_key_schedule(SSL_HANDSHAKE *hs, const uint8_t *in,
  1027. size_t len);
  1028. // tls13_set_traffic_key sets the read or write traffic keys to
  1029. // |traffic_secret|. It returns one on success and zero on error.
  1030. int tls13_set_traffic_key(SSL *ssl, enum evp_aead_direction_t direction,
  1031. const uint8_t *traffic_secret,
  1032. size_t traffic_secret_len);
  1033. // tls13_derive_early_secrets derives the early traffic secret. It returns one
  1034. // on success and zero on error.
  1035. int tls13_derive_early_secrets(SSL_HANDSHAKE *hs);
  1036. // tls13_derive_handshake_secrets derives the handshake traffic secret. It
  1037. // returns one on success and zero on error.
  1038. int tls13_derive_handshake_secrets(SSL_HANDSHAKE *hs);
  1039. // tls13_rotate_traffic_key derives the next read or write traffic secret. It
  1040. // returns one on success and zero on error.
  1041. int tls13_rotate_traffic_key(SSL *ssl, enum evp_aead_direction_t direction);
  1042. // tls13_derive_application_secrets derives the initial application data traffic
  1043. // and exporter secrets based on the handshake transcripts and |master_secret|.
  1044. // It returns one on success and zero on error.
  1045. int tls13_derive_application_secrets(SSL_HANDSHAKE *hs);
  1046. // tls13_derive_resumption_secret derives the |resumption_secret|.
  1047. int tls13_derive_resumption_secret(SSL_HANDSHAKE *hs);
  1048. // tls13_export_keying_material provides an exporter interface to use the
  1049. // |exporter_secret|.
  1050. int tls13_export_keying_material(SSL *ssl, Span<uint8_t> out,
  1051. Span<const uint8_t> secret,
  1052. Span<const char> label,
  1053. Span<const uint8_t> context);
  1054. // tls13_finished_mac calculates the MAC of the handshake transcript to verify
  1055. // the integrity of the Finished message, and stores the result in |out| and
  1056. // length in |out_len|. |is_server| is 1 if this is for the Server Finished and
  1057. // 0 for the Client Finished.
  1058. int tls13_finished_mac(SSL_HANDSHAKE *hs, uint8_t *out,
  1059. size_t *out_len, int is_server);
  1060. // tls13_derive_session_psk calculates the PSK for this session based on the
  1061. // resumption master secret and |nonce|. It returns true on success, and false
  1062. // on failure.
  1063. bool tls13_derive_session_psk(SSL_SESSION *session, Span<const uint8_t> nonce);
  1064. // tls13_write_psk_binder calculates the PSK binder value and replaces the last
  1065. // bytes of |msg| with the resulting value. It returns 1 on success, and 0 on
  1066. // failure.
  1067. int tls13_write_psk_binder(SSL_HANDSHAKE *hs, uint8_t *msg, size_t len);
  1068. // tls13_verify_psk_binder verifies that the handshake transcript, truncated
  1069. // up to the binders has a valid signature using the value of |session|'s
  1070. // resumption secret. It returns 1 on success, and 0 on failure.
  1071. int tls13_verify_psk_binder(SSL_HANDSHAKE *hs, SSL_SESSION *session,
  1072. const SSLMessage &msg, CBS *binders);
  1073. // Handshake functions.
  1074. enum ssl_hs_wait_t {
  1075. ssl_hs_error,
  1076. ssl_hs_ok,
  1077. ssl_hs_read_server_hello,
  1078. ssl_hs_read_message,
  1079. ssl_hs_flush,
  1080. ssl_hs_certificate_selection_pending,
  1081. ssl_hs_handoff,
  1082. ssl_hs_handback,
  1083. ssl_hs_x509_lookup,
  1084. ssl_hs_channel_id_lookup,
  1085. ssl_hs_private_key_operation,
  1086. ssl_hs_pending_session,
  1087. ssl_hs_pending_ticket,
  1088. ssl_hs_early_return,
  1089. ssl_hs_early_data_rejected,
  1090. ssl_hs_read_end_of_early_data,
  1091. ssl_hs_read_change_cipher_spec,
  1092. ssl_hs_certificate_verify,
  1093. };
  1094. enum ssl_grease_index_t {
  1095. ssl_grease_cipher = 0,
  1096. ssl_grease_group,
  1097. ssl_grease_extension1,
  1098. ssl_grease_extension2,
  1099. ssl_grease_version,
  1100. ssl_grease_ticket_extension,
  1101. ssl_grease_last_index = ssl_grease_ticket_extension,
  1102. };
  1103. enum tls12_server_hs_state_t {
  1104. state12_start_accept = 0,
  1105. state12_read_client_hello,
  1106. state12_select_certificate,
  1107. state12_tls13,
  1108. state12_select_parameters,
  1109. state12_send_server_hello,
  1110. state12_send_server_certificate,
  1111. state12_send_server_key_exchange,
  1112. state12_send_server_hello_done,
  1113. state12_read_client_certificate,
  1114. state12_verify_client_certificate,
  1115. state12_read_client_key_exchange,
  1116. state12_read_client_certificate_verify,
  1117. state12_read_change_cipher_spec,
  1118. state12_process_change_cipher_spec,
  1119. state12_read_next_proto,
  1120. state12_read_channel_id,
  1121. state12_read_client_finished,
  1122. state12_send_server_finished,
  1123. state12_finish_server_handshake,
  1124. state12_done,
  1125. };
  1126. // handback_t lists the points in the state machine where a handback can occur.
  1127. // These are the different points at which key material is no longer needed.
  1128. enum handback_t {
  1129. handback_after_session_resumption,
  1130. handback_after_ecdhe,
  1131. handback_after_handshake,
  1132. };
  1133. struct SSL_HANDSHAKE {
  1134. explicit SSL_HANDSHAKE(SSL *ssl);
  1135. ~SSL_HANDSHAKE();
  1136. static constexpr bool kAllowUniquePtr = true;
  1137. // ssl is a non-owning pointer to the parent |SSL| object.
  1138. SSL *ssl;
  1139. // config is a non-owning pointer to the handshake configuration.
  1140. SSL_CONFIG *config;
  1141. // wait contains the operation the handshake is currently blocking on or
  1142. // |ssl_hs_ok| if none.
  1143. enum ssl_hs_wait_t wait = ssl_hs_ok;
  1144. // state is the internal state for the TLS 1.2 and below handshake. Its
  1145. // values depend on |do_handshake| but the starting state is always zero.
  1146. int state = 0;
  1147. // tls13_state is the internal state for the TLS 1.3 handshake. Its values
  1148. // depend on |do_handshake| but the starting state is always zero.
  1149. int tls13_state = 0;
  1150. // min_version is the minimum accepted protocol version, taking account both
  1151. // |SSL_OP_NO_*| and |SSL_CTX_set_min_proto_version| APIs.
  1152. uint16_t min_version = 0;
  1153. // max_version is the maximum accepted protocol version, taking account both
  1154. // |SSL_OP_NO_*| and |SSL_CTX_set_max_proto_version| APIs.
  1155. uint16_t max_version = 0;
  1156. size_t hash_len = 0;
  1157. uint8_t secret[EVP_MAX_MD_SIZE] = {0};
  1158. uint8_t early_traffic_secret[EVP_MAX_MD_SIZE] = {0};
  1159. uint8_t client_handshake_secret[EVP_MAX_MD_SIZE] = {0};
  1160. uint8_t server_handshake_secret[EVP_MAX_MD_SIZE] = {0};
  1161. uint8_t client_traffic_secret_0[EVP_MAX_MD_SIZE] = {0};
  1162. uint8_t server_traffic_secret_0[EVP_MAX_MD_SIZE] = {0};
  1163. uint8_t expected_client_finished[EVP_MAX_MD_SIZE] = {0};
  1164. union {
  1165. // sent is a bitset where the bits correspond to elements of kExtensions
  1166. // in t1_lib.c. Each bit is set if that extension was sent in a
  1167. // ClientHello. It's not used by servers.
  1168. uint32_t sent = 0;
  1169. // received is a bitset, like |sent|, but is used by servers to record
  1170. // which extensions were received from a client.
  1171. uint32_t received;
  1172. } extensions;
  1173. // retry_group is the group ID selected by the server in HelloRetryRequest in
  1174. // TLS 1.3.
  1175. uint16_t retry_group = 0;
  1176. // error, if |wait| is |ssl_hs_error|, is the error the handshake failed on.
  1177. UniquePtr<ERR_SAVE_STATE> error;
  1178. // key_share is the current key exchange instance.
  1179. UniquePtr<SSLKeyShare> key_share;
  1180. // transcript is the current handshake transcript.
  1181. SSLTranscript transcript;
  1182. // cookie is the value of the cookie received from the server, if any.
  1183. Array<uint8_t> cookie;
  1184. // key_share_bytes is the value of the previously sent KeyShare extension by
  1185. // the client in TLS 1.3.
  1186. Array<uint8_t> key_share_bytes;
  1187. // ecdh_public_key, for servers, is the key share to be sent to the client in
  1188. // TLS 1.3.
  1189. Array<uint8_t> ecdh_public_key;
  1190. // peer_sigalgs are the signature algorithms that the peer supports. These are
  1191. // taken from the contents of the signature algorithms extension for a server
  1192. // or from the CertificateRequest for a client.
  1193. Array<uint16_t> peer_sigalgs;
  1194. // peer_supported_group_list contains the supported group IDs advertised by
  1195. // the peer. This is only set on the server's end. The server does not
  1196. // advertise this extension to the client.
  1197. Array<uint16_t> peer_supported_group_list;
  1198. // peer_key is the peer's ECDH key for a TLS 1.2 client.
  1199. Array<uint8_t> peer_key;
  1200. // negotiated_token_binding_version is used by a server to store the
  1201. // on-the-wire encoding of the Token Binding protocol version to advertise in
  1202. // the ServerHello/EncryptedExtensions if the Token Binding extension is to be
  1203. // sent.
  1204. uint16_t negotiated_token_binding_version;
  1205. // cert_compression_alg_id, for a server, contains the negotiated certificate
  1206. // compression algorithm for this client. It is only valid if
  1207. // |cert_compression_negotiated| is true.
  1208. uint16_t cert_compression_alg_id;
  1209. // server_params, in a TLS 1.2 server, stores the ServerKeyExchange
  1210. // parameters. It has client and server randoms prepended for signing
  1211. // convenience.
  1212. Array<uint8_t> server_params;
  1213. // peer_psk_identity_hint, on the client, is the psk_identity_hint sent by the
  1214. // server when using a TLS 1.2 PSK key exchange.
  1215. UniquePtr<char> peer_psk_identity_hint;
  1216. // ca_names, on the client, contains the list of CAs received in a
  1217. // CertificateRequest message.
  1218. UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names;
  1219. // cached_x509_ca_names contains a cache of parsed versions of the elements of
  1220. // |ca_names|. This pointer is left non-owning so only
  1221. // |ssl_crypto_x509_method| needs to link against crypto/x509.
  1222. STACK_OF(X509_NAME) *cached_x509_ca_names = nullptr;
  1223. // certificate_types, on the client, contains the set of certificate types
  1224. // received in a CertificateRequest message.
  1225. Array<uint8_t> certificate_types;
  1226. // local_pubkey is the public key we are authenticating as.
  1227. UniquePtr<EVP_PKEY> local_pubkey;
  1228. // peer_pubkey is the public key parsed from the peer's leaf certificate.
  1229. UniquePtr<EVP_PKEY> peer_pubkey;
  1230. // new_session is the new mutable session being established by the current
  1231. // handshake. It should not be cached.
  1232. UniquePtr<SSL_SESSION> new_session;
  1233. // early_session is the session corresponding to the current 0-RTT state on
  1234. // the client if |in_early_data| is true.
  1235. UniquePtr<SSL_SESSION> early_session;
  1236. // new_cipher is the cipher being negotiated in this handshake.
  1237. const SSL_CIPHER *new_cipher = nullptr;
  1238. // key_block is the record-layer key block for TLS 1.2 and earlier.
  1239. Array<uint8_t> key_block;
  1240. // scts_requested is true if the SCT extension is in the ClientHello.
  1241. bool scts_requested:1;
  1242. // needs_psk_binder is true if the ClientHello has a placeholder PSK binder to
  1243. // be filled in.
  1244. bool needs_psk_binder:1;
  1245. bool received_hello_retry_request:1;
  1246. bool sent_hello_retry_request:1;
  1247. // handshake_finalized is true once the handshake has completed, at which
  1248. // point accessors should use the established state.
  1249. bool handshake_finalized:1;
  1250. // accept_psk_mode stores whether the client's PSK mode is compatible with our
  1251. // preferences.
  1252. bool accept_psk_mode:1;
  1253. // cert_request is true if a client certificate was requested.
  1254. bool cert_request:1;
  1255. // certificate_status_expected is true if OCSP stapling was negotiated and the
  1256. // server is expected to send a CertificateStatus message. (This is used on
  1257. // both the client and server sides.)
  1258. bool certificate_status_expected:1;
  1259. // ocsp_stapling_requested is true if a client requested OCSP stapling.
  1260. bool ocsp_stapling_requested:1;
  1261. // should_ack_sni is used by a server and indicates that the SNI extension
  1262. // should be echoed in the ServerHello.
  1263. bool should_ack_sni:1;
  1264. // in_false_start is true if there is a pending client handshake in False
  1265. // Start. The client may write data at this point.
  1266. bool in_false_start:1;
  1267. // in_early_data is true if there is a pending handshake that has progressed
  1268. // enough to send and receive early data.
  1269. bool in_early_data:1;
  1270. // early_data_offered is true if the client sent the early_data extension.
  1271. bool early_data_offered:1;
  1272. // can_early_read is true if application data may be read at this point in the
  1273. // handshake.
  1274. bool can_early_read:1;
  1275. // can_early_write is true if application data may be written at this point in
  1276. // the handshake.
  1277. bool can_early_write:1;
  1278. // next_proto_neg_seen is one of NPN was negotiated.
  1279. bool next_proto_neg_seen:1;
  1280. // ticket_expected is true if a TLS 1.2 NewSessionTicket message is to be sent
  1281. // or received.
  1282. bool ticket_expected:1;
  1283. // extended_master_secret is true if the extended master secret extension is
  1284. // negotiated in this handshake.
  1285. bool extended_master_secret:1;
  1286. // pending_private_key_op is true if there is a pending private key operation
  1287. // in progress.
  1288. bool pending_private_key_op:1;
  1289. // grease_seeded is true if |grease_seed| has been initialized.
  1290. bool grease_seeded:1;
  1291. // handback indicates that a server should pause the handshake after
  1292. // finishing operations that require private key material, in such a way that
  1293. // |SSL_get_error| returns |SSL_HANDBACK|. It is set by |SSL_apply_handoff|.
  1294. bool handback:1;
  1295. // cert_compression_negotiated is true iff |cert_compression_alg_id| is valid.
  1296. bool cert_compression_negotiated:1;
  1297. // client_version is the value sent or received in the ClientHello version.
  1298. uint16_t client_version = 0;
  1299. // early_data_read is the amount of early data that has been read by the
  1300. // record layer.
  1301. uint16_t early_data_read = 0;
  1302. // early_data_written is the amount of early data that has been written by the
  1303. // record layer.
  1304. uint16_t early_data_written = 0;
  1305. // session_id is the session ID in the ClientHello, used for the experimental
  1306. // TLS 1.3 variant.
  1307. uint8_t session_id[SSL_MAX_SSL_SESSION_ID_LENGTH] = {0};
  1308. uint8_t session_id_len = 0;
  1309. // grease_seed is the entropy for GREASE values. It is valid if
  1310. // |grease_seeded| is true.
  1311. uint8_t grease_seed[ssl_grease_last_index + 1] = {0};
  1312. // dummy_pq_padding_len, in a server, is the length of the extension that
  1313. // should be echoed in a ServerHello, or zero if no extension should be
  1314. // echoed.
  1315. uint16_t dummy_pq_padding_len = 0;
  1316. };
  1317. UniquePtr<SSL_HANDSHAKE> ssl_handshake_new(SSL *ssl);
  1318. // ssl_check_message_type checks if |msg| has type |type|. If so it returns
  1319. // one. Otherwise, it sends an alert and returns zero.
  1320. bool ssl_check_message_type(SSL *ssl, const SSLMessage &msg, int type);
  1321. // ssl_run_handshake runs the TLS handshake. It returns one on success and <= 0
  1322. // on error. It sets |out_early_return| to one if we've completed the handshake
  1323. // early.
  1324. int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return);
  1325. // The following are implementations of |do_handshake| for the client and
  1326. // server.
  1327. enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs);
  1328. enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs);
  1329. enum ssl_hs_wait_t tls13_client_handshake(SSL_HANDSHAKE *hs);
  1330. enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs);
  1331. // The following functions return human-readable representations of the TLS
  1332. // handshake states for debugging.
  1333. const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs);
  1334. const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs);
  1335. const char *tls13_client_handshake_state(SSL_HANDSHAKE *hs);
  1336. const char *tls13_server_handshake_state(SSL_HANDSHAKE *hs);
  1337. // tls13_post_handshake processes a post-handshake message. It returns one on
  1338. // success and zero on failure.
  1339. int tls13_post_handshake(SSL *ssl, const SSLMessage &msg);
  1340. int tls13_process_certificate(SSL_HANDSHAKE *hs, const SSLMessage &msg,
  1341. int allow_anonymous);
  1342. int tls13_process_certificate_verify(SSL_HANDSHAKE *hs, const SSLMessage &msg);
  1343. // tls13_process_finished processes |msg| as a Finished message from the
  1344. // peer. If |use_saved_value| is one, the verify_data is compared against
  1345. // |hs->expected_client_finished| rather than computed fresh.
  1346. int tls13_process_finished(SSL_HANDSHAKE *hs, const SSLMessage &msg,
  1347. int use_saved_value);
  1348. int tls13_add_certificate(SSL_HANDSHAKE *hs);
  1349. // tls13_add_certificate_verify adds a TLS 1.3 CertificateVerify message to the
  1350. // handshake. If it returns |ssl_private_key_retry|, it should be called again
  1351. // to retry when the signing operation is completed.
  1352. enum ssl_private_key_result_t tls13_add_certificate_verify(SSL_HANDSHAKE *hs);
  1353. int tls13_add_finished(SSL_HANDSHAKE *hs);
  1354. int tls13_process_new_session_ticket(SSL *ssl, const SSLMessage &msg);
  1355. bool ssl_ext_key_share_parse_serverhello(SSL_HANDSHAKE *hs,
  1356. Array<uint8_t> *out_secret,
  1357. uint8_t *out_alert, CBS *contents);
  1358. bool ssl_ext_key_share_parse_clienthello(SSL_HANDSHAKE *hs, bool *out_found,
  1359. Array<uint8_t> *out_secret,
  1360. uint8_t *out_alert, CBS *contents);
  1361. bool ssl_ext_key_share_add_serverhello(SSL_HANDSHAKE *hs, CBB *out);
  1362. bool ssl_ext_pre_shared_key_parse_serverhello(SSL_HANDSHAKE *hs,
  1363. uint8_t *out_alert,
  1364. CBS *contents);
  1365. bool ssl_ext_pre_shared_key_parse_clienthello(
  1366. SSL_HANDSHAKE *hs, CBS *out_ticket, CBS *out_binders,
  1367. uint32_t *out_obfuscated_ticket_age, uint8_t *out_alert, CBS *contents);
  1368. bool ssl_ext_pre_shared_key_add_serverhello(SSL_HANDSHAKE *hs, CBB *out);
  1369. // ssl_is_sct_list_valid does a shallow parse of the SCT list in |contents| and
  1370. // returns whether it's valid.
  1371. bool ssl_is_sct_list_valid(const CBS *contents);
  1372. int ssl_write_client_hello(SSL_HANDSHAKE *hs);
  1373. enum ssl_cert_verify_context_t {
  1374. ssl_cert_verify_server,
  1375. ssl_cert_verify_client,
  1376. ssl_cert_verify_channel_id,
  1377. };
  1378. // tls13_get_cert_verify_signature_input generates the message to be signed for
  1379. // TLS 1.3's CertificateVerify message. |cert_verify_context| determines the
  1380. // type of signature. It sets |*out| to a newly allocated buffer containing the
  1381. // result. This function returns true on success and false on failure.
  1382. bool tls13_get_cert_verify_signature_input(
  1383. SSL_HANDSHAKE *hs, Array<uint8_t> *out,
  1384. enum ssl_cert_verify_context_t cert_verify_context);
  1385. // ssl_is_alpn_protocol_allowed returns whether |protocol| is a valid server
  1386. // selection for |hs->ssl|'s client preferences.
  1387. bool ssl_is_alpn_protocol_allowed(const SSL_HANDSHAKE *hs,
  1388. Span<const uint8_t> protocol);
  1389. // ssl_negotiate_alpn negotiates the ALPN extension, if applicable. It returns
  1390. // true on successful negotiation or if nothing was negotiated. It returns false
  1391. // and sets |*out_alert| to an alert on error.
  1392. bool ssl_negotiate_alpn(SSL_HANDSHAKE *hs, uint8_t *out_alert,
  1393. const SSL_CLIENT_HELLO *client_hello);
  1394. struct SSL_EXTENSION_TYPE {
  1395. uint16_t type;
  1396. bool *out_present;
  1397. CBS *out_data;
  1398. };
  1399. // ssl_parse_extensions parses a TLS extensions block out of |cbs| and advances
  1400. // it. It writes the parsed extensions to pointers denoted by |ext_types|. On
  1401. // success, it fills in the |out_present| and |out_data| fields and returns one.
  1402. // Otherwise, it sets |*out_alert| to an alert to send and returns zero. Unknown
  1403. // extensions are rejected unless |ignore_unknown| is 1.
  1404. int ssl_parse_extensions(const CBS *cbs, uint8_t *out_alert,
  1405. const SSL_EXTENSION_TYPE *ext_types,
  1406. size_t num_ext_types, int ignore_unknown);
  1407. // ssl_verify_peer_cert verifies the peer certificate for |hs|.
  1408. enum ssl_verify_result_t ssl_verify_peer_cert(SSL_HANDSHAKE *hs);
  1409. enum ssl_hs_wait_t ssl_get_finished(SSL_HANDSHAKE *hs);
  1410. bool ssl_send_finished(SSL_HANDSHAKE *hs);
  1411. bool ssl_output_cert_chain(SSL_HANDSHAKE *hs);
  1412. // SSLKEYLOGFILE functions.
  1413. // ssl_log_secret logs |secret| with label |label|, if logging is enabled for
  1414. // |ssl|. It returns one on success and zero on failure.
  1415. int ssl_log_secret(const SSL *ssl, const char *label, const uint8_t *secret,
  1416. size_t secret_len);
  1417. // ClientHello functions.
  1418. bool ssl_client_hello_init(SSL *ssl, SSL_CLIENT_HELLO *out,
  1419. const SSLMessage &msg);
  1420. bool ssl_client_hello_get_extension(const SSL_CLIENT_HELLO *client_hello,
  1421. CBS *out, uint16_t extension_type);
  1422. bool ssl_client_cipher_list_contains_cipher(
  1423. const SSL_CLIENT_HELLO *client_hello, uint16_t id);
  1424. // GREASE.
  1425. // ssl_get_grease_value returns a GREASE value for |hs|. For a given
  1426. // connection, the values for each index will be deterministic. This allows the
  1427. // same ClientHello be sent twice for a HelloRetryRequest or the same group be
  1428. // advertised in both supported_groups and key_shares.
  1429. uint16_t ssl_get_grease_value(SSL_HANDSHAKE *hs, enum ssl_grease_index_t index);
  1430. // Signature algorithms.
  1431. // tls1_parse_peer_sigalgs parses |sigalgs| as the list of peer signature
  1432. // algorithms and saves them on |hs|. It returns true on success and false on
  1433. // error.
  1434. bool tls1_parse_peer_sigalgs(SSL_HANDSHAKE *hs, const CBS *sigalgs);
  1435. // tls1_get_legacy_signature_algorithm sets |*out| to the signature algorithm
  1436. // that should be used with |pkey| in TLS 1.1 and earlier. It returns true on
  1437. // success and false if |pkey| may not be used at those versions.
  1438. bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey);
  1439. // tls1_choose_signature_algorithm sets |*out| to a signature algorithm for use
  1440. // with |hs|'s private key based on the peer's preferences and the algorithms
  1441. // supported. It returns true on success and false on error.
  1442. bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out);
  1443. // tls12_add_verify_sigalgs adds the signature algorithms acceptable for the
  1444. // peer signature to |out|. It returns true on success and false on error. If
  1445. // |for_certs| is true, the potentially more restrictive list of algorithms for
  1446. // certificates is used. Otherwise, the online signature one is used.
  1447. bool tls12_add_verify_sigalgs(const SSL *ssl, CBB *out, bool for_certs);
  1448. // tls12_check_peer_sigalg checks if |sigalg| is acceptable for the peer
  1449. // signature. It returns true on success and false on error, setting
  1450. // |*out_alert| to an alert to send.
  1451. bool tls12_check_peer_sigalg(const SSL *ssl, uint8_t *out_alert,
  1452. uint16_t sigalg);
  1453. // tls12_has_different_verify_sigalgs_for_certs returns whether |ssl| has a
  1454. // different, more restrictive, list of signature algorithms acceptable for the
  1455. // certificate than the online signature.
  1456. bool tls12_has_different_verify_sigalgs_for_certs(const SSL *ssl);
  1457. // Underdocumented functions.
  1458. //
  1459. // Functions below here haven't been touched up and may be underdocumented.
  1460. #define TLSEXT_CHANNEL_ID_SIZE 128
  1461. // From RFC4492, used in encoding the curve type in ECParameters
  1462. #define NAMED_CURVE_TYPE 3
  1463. struct CERT {
  1464. static constexpr bool kAllowUniquePtr = true;
  1465. explicit CERT(const SSL_X509_METHOD *x509_method);
  1466. ~CERT();
  1467. UniquePtr<EVP_PKEY> privatekey;
  1468. // chain contains the certificate chain, with the leaf at the beginning. The
  1469. // first element of |chain| may be NULL to indicate that the leaf certificate
  1470. // has not yet been set.
  1471. // If |chain| != NULL -> len(chain) >= 1
  1472. // If |chain[0]| == NULL -> len(chain) >= 2.
  1473. // |chain[1..]| != NULL
  1474. UniquePtr<STACK_OF(CRYPTO_BUFFER)> chain;
  1475. // x509_chain may contain a parsed copy of |chain[1..]|. This is only used as
  1476. // a cache in order to implement “get0” functions that return a non-owning
  1477. // pointer to the certificate chain.
  1478. STACK_OF(X509) *x509_chain = nullptr;
  1479. // x509_leaf may contain a parsed copy of the first element of |chain|. This
  1480. // is only used as a cache in order to implement “get0” functions that return
  1481. // a non-owning pointer to the certificate chain.
  1482. X509 *x509_leaf = nullptr;
  1483. // x509_stash contains the last |X509| object append to the chain. This is a
  1484. // workaround for some third-party code that continue to use an |X509| object
  1485. // even after passing ownership with an “add0” function.
  1486. X509 *x509_stash = nullptr;
  1487. // key_method, if non-NULL, is a set of callbacks to call for private key
  1488. // operations.
  1489. const SSL_PRIVATE_KEY_METHOD *key_method = nullptr;
  1490. // x509_method contains pointers to functions that might deal with |X509|
  1491. // compatibility, or might be a no-op, depending on the application.
  1492. const SSL_X509_METHOD *x509_method = nullptr;
  1493. // sigalgs, if non-empty, is the set of signature algorithms supported by
  1494. // |privatekey| in decreasing order of preference.
  1495. Array<uint16_t> sigalgs;
  1496. // Certificate setup callback: if set is called whenever a
  1497. // certificate may be required (client or server). the callback
  1498. // can then examine any appropriate parameters and setup any
  1499. // certificates required. This allows advanced applications
  1500. // to select certificates on the fly: for example based on
  1501. // supported signature algorithms or curves.
  1502. int (*cert_cb)(SSL *ssl, void *arg) = nullptr;
  1503. void *cert_cb_arg = nullptr;
  1504. // Optional X509_STORE for certificate validation. If NULL the parent SSL_CTX
  1505. // store is used instead.
  1506. X509_STORE *verify_store = nullptr;
  1507. // Signed certificate timestamp list to be sent to the client, if requested
  1508. UniquePtr<CRYPTO_BUFFER> signed_cert_timestamp_list;
  1509. // OCSP response to be sent to the client, if requested.
  1510. UniquePtr<CRYPTO_BUFFER> ocsp_response;
  1511. // sid_ctx partitions the session space within a shared session cache or
  1512. // ticket key. Only sessions with a matching value will be accepted.
  1513. uint8_t sid_ctx_length = 0;
  1514. uint8_t sid_ctx[SSL_MAX_SID_CTX_LENGTH] = {0};
  1515. };
  1516. // |SSL_PROTOCOL_METHOD| abstracts between TLS and DTLS.
  1517. struct SSL_PROTOCOL_METHOD {
  1518. bool is_dtls;
  1519. bool (*ssl_new)(SSL *ssl);
  1520. void (*ssl_free)(SSL *ssl);
  1521. // get_message sets |*out| to the current handshake message and returns true
  1522. // if one has been received. It returns false if more input is needed.
  1523. bool (*get_message)(SSL *ssl, SSLMessage *out);
  1524. // next_message is called to release the current handshake message.
  1525. void (*next_message)(SSL *ssl);
  1526. // Use the |ssl_open_handshake| wrapper.
  1527. ssl_open_record_t (*open_handshake)(SSL *ssl, size_t *out_consumed,
  1528. uint8_t *out_alert, Span<uint8_t> in);
  1529. // Use the |ssl_open_change_cipher_spec| wrapper.
  1530. ssl_open_record_t (*open_change_cipher_spec)(SSL *ssl, size_t *out_consumed,
  1531. uint8_t *out_alert,
  1532. Span<uint8_t> in);
  1533. // Use the |ssl_open_app_data| wrapper.
  1534. ssl_open_record_t (*open_app_data)(SSL *ssl, Span<uint8_t> *out,
  1535. size_t *out_consumed, uint8_t *out_alert,
  1536. Span<uint8_t> in);
  1537. int (*write_app_data)(SSL *ssl, bool *out_needs_handshake, const uint8_t *buf,
  1538. int len);
  1539. int (*dispatch_alert)(SSL *ssl);
  1540. // init_message begins a new handshake message of type |type|. |cbb| is the
  1541. // root CBB to be passed into |finish_message|. |*body| is set to a child CBB
  1542. // the caller should write to. It returns true on success and false on error.
  1543. bool (*init_message)(SSL *ssl, CBB *cbb, CBB *body, uint8_t type);
  1544. // finish_message finishes a handshake message. It sets |*out_msg| to the
  1545. // serialized message. It returns true on success and false on error.
  1546. bool (*finish_message)(SSL *ssl, CBB *cbb, bssl::Array<uint8_t> *out_msg);
  1547. // add_message adds a handshake message to the pending flight. It returns
  1548. // true on success and false on error.
  1549. bool (*add_message)(SSL *ssl, bssl::Array<uint8_t> msg);
  1550. // add_change_cipher_spec adds a ChangeCipherSpec record to the pending
  1551. // flight. It returns true on success and false on error.
  1552. bool (*add_change_cipher_spec)(SSL *ssl);
  1553. // add_alert adds an alert to the pending flight. It returns true on success
  1554. // and false on error.
  1555. bool (*add_alert)(SSL *ssl, uint8_t level, uint8_t desc);
  1556. // flush_flight flushes the pending flight to the transport. It returns one on
  1557. // success and <= 0 on error.
  1558. int (*flush_flight)(SSL *ssl);
  1559. // on_handshake_complete is called when the handshake is complete.
  1560. void (*on_handshake_complete)(SSL *ssl);
  1561. // set_read_state sets |ssl|'s read cipher state to |aead_ctx|. It returns
  1562. // true on success and false if changing the read state is forbidden at this
  1563. // point.
  1564. bool (*set_read_state)(SSL *ssl, UniquePtr<SSLAEADContext> aead_ctx);
  1565. // set_write_state sets |ssl|'s write cipher state to |aead_ctx|. It returns
  1566. // true on success and false if changing the write state is forbidden at this
  1567. // point.
  1568. bool (*set_write_state)(SSL *ssl, UniquePtr<SSLAEADContext> aead_ctx);
  1569. };
  1570. // The following wrappers call |open_*| but handle |read_shutdown| correctly.
  1571. // ssl_open_handshake processes a record from |in| for reading a handshake
  1572. // message.
  1573. ssl_open_record_t ssl_open_handshake(SSL *ssl, size_t *out_consumed,
  1574. uint8_t *out_alert, Span<uint8_t> in);
  1575. // ssl_open_change_cipher_spec processes a record from |in| for reading a
  1576. // ChangeCipherSpec.
  1577. ssl_open_record_t ssl_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
  1578. uint8_t *out_alert,
  1579. Span<uint8_t> in);
  1580. // ssl_open_app_data processes a record from |in| for reading application data.
  1581. // On success, it returns |ssl_open_record_success| and sets |*out| to the
  1582. // input. If it encounters a post-handshake message, it returns
  1583. // |ssl_open_record_discard|. The caller should then retry, after processing any
  1584. // messages received with |get_message|.
  1585. ssl_open_record_t ssl_open_app_data(SSL *ssl, Span<uint8_t> *out,
  1586. size_t *out_consumed, uint8_t *out_alert,
  1587. Span<uint8_t> in);
  1588. struct SSL_X509_METHOD {
  1589. // check_client_CA_list returns one if |names| is a good list of X.509
  1590. // distinguished names and zero otherwise. This is used to ensure that we can
  1591. // reject unparsable values at handshake time when using crypto/x509.
  1592. int (*check_client_CA_list)(STACK_OF(CRYPTO_BUFFER) *names);
  1593. // cert_clear frees and NULLs all X509 certificate-related state.
  1594. void (*cert_clear)(CERT *cert);
  1595. // cert_free frees all X509-related state.
  1596. void (*cert_free)(CERT *cert);
  1597. // cert_flush_cached_chain drops any cached |X509|-based certificate chain
  1598. // from |cert|.
  1599. // cert_dup duplicates any needed fields from |cert| to |new_cert|.
  1600. void (*cert_dup)(CERT *new_cert, const CERT *cert);
  1601. void (*cert_flush_cached_chain)(CERT *cert);
  1602. // cert_flush_cached_chain drops any cached |X509|-based leaf certificate
  1603. // from |cert|.
  1604. void (*cert_flush_cached_leaf)(CERT *cert);
  1605. // session_cache_objects fills out |sess->x509_peer| and |sess->x509_chain|
  1606. // from |sess->certs| and erases |sess->x509_chain_without_leaf|. It returns
  1607. // one on success or zero on error.
  1608. int (*session_cache_objects)(SSL_SESSION *session);
  1609. // session_dup duplicates any needed fields from |session| to |new_session|.
  1610. // It returns one on success or zero on error.
  1611. int (*session_dup)(SSL_SESSION *new_session, const SSL_SESSION *session);
  1612. // session_clear frees any X509-related state from |session|.
  1613. void (*session_clear)(SSL_SESSION *session);
  1614. // session_verify_cert_chain verifies the certificate chain in |session|,
  1615. // sets |session->verify_result| and returns one on success or zero on
  1616. // error.
  1617. int (*session_verify_cert_chain)(SSL_SESSION *session, SSL_HANDSHAKE *ssl,
  1618. uint8_t *out_alert);
  1619. // hs_flush_cached_ca_names drops any cached |X509_NAME|s from |hs|.
  1620. void (*hs_flush_cached_ca_names)(SSL_HANDSHAKE *hs);
  1621. // ssl_new does any neccessary initialisation of |hs|. It returns one on
  1622. // success or zero on error.
  1623. int (*ssl_new)(SSL_HANDSHAKE *hs);
  1624. // ssl_free frees anything created by |ssl_new|.
  1625. void (*ssl_config_free)(SSL_CONFIG *cfg);
  1626. // ssl_flush_cached_client_CA drops any cached |X509_NAME|s from |ssl|.
  1627. void (*ssl_flush_cached_client_CA)(SSL_CONFIG *cfg);
  1628. // ssl_auto_chain_if_needed runs the deprecated auto-chaining logic if
  1629. // necessary. On success, it updates |ssl|'s certificate configuration as
  1630. // needed and returns one. Otherwise, it returns zero.
  1631. int (*ssl_auto_chain_if_needed)(SSL_HANDSHAKE *hs);
  1632. // ssl_ctx_new does any neccessary initialisation of |ctx|. It returns one on
  1633. // success or zero on error.
  1634. int (*ssl_ctx_new)(SSL_CTX *ctx);
  1635. // ssl_ctx_free frees anything created by |ssl_ctx_new|.
  1636. void (*ssl_ctx_free)(SSL_CTX *ctx);
  1637. // ssl_ctx_flush_cached_client_CA drops any cached |X509_NAME|s from |ctx|.
  1638. void (*ssl_ctx_flush_cached_client_CA)(SSL_CTX *ssl);
  1639. };
  1640. // ssl_crypto_x509_method provides the |SSL_X509_METHOD| functions using
  1641. // crypto/x509.
  1642. extern const SSL_X509_METHOD ssl_crypto_x509_method;
  1643. // ssl_noop_x509_method provides the |SSL_X509_METHOD| functions that avoid
  1644. // crypto/x509.
  1645. extern const SSL_X509_METHOD ssl_noop_x509_method;
  1646. struct TicketKey {
  1647. static constexpr bool kAllowUniquePtr = true;
  1648. uint8_t name[SSL_TICKET_KEY_NAME_LEN] = {0};
  1649. uint8_t hmac_key[16] = {0};
  1650. uint8_t aes_key[16] = {0};
  1651. // next_rotation_tv_sec is the time (in seconds from the epoch) when the
  1652. // current key should be superseded by a new key, or the time when a previous
  1653. // key should be dropped. If zero, then the key should not be automatically
  1654. // rotated.
  1655. uint64_t next_rotation_tv_sec = 0;
  1656. };
  1657. struct CertCompressionAlg {
  1658. static constexpr bool kAllowUniquePtr = true;
  1659. ssl_cert_compression_func_t compress = nullptr;
  1660. ssl_cert_decompression_func_t decompress = nullptr;
  1661. uint16_t alg_id = 0;
  1662. };
  1663. } // namespace bssl
  1664. DECLARE_LHASH_OF(SSL_SESSION)
  1665. DEFINE_NAMED_STACK_OF(CertCompressionAlg, bssl::CertCompressionAlg);
  1666. namespace bssl {
  1667. // An ssl_shutdown_t describes the shutdown state of one end of the connection,
  1668. // whether it is alive or has been shutdown via close_notify or fatal alert.
  1669. enum ssl_shutdown_t {
  1670. ssl_shutdown_none = 0,
  1671. ssl_shutdown_close_notify = 1,
  1672. ssl_shutdown_error = 2,
  1673. };
  1674. struct SSL3_STATE {
  1675. static constexpr bool kAllowUniquePtr = true;
  1676. SSL3_STATE();
  1677. ~SSL3_STATE();
  1678. uint8_t read_sequence[8] = {0};
  1679. uint8_t write_sequence[8] = {0};
  1680. uint8_t server_random[SSL3_RANDOM_SIZE] = {0};
  1681. uint8_t client_random[SSL3_RANDOM_SIZE] = {0};
  1682. // read_buffer holds data from the transport to be processed.
  1683. SSLBuffer read_buffer;
  1684. // write_buffer holds data to be written to the transport.
  1685. SSLBuffer write_buffer;
  1686. // pending_app_data is the unconsumed application data. It points into
  1687. // |read_buffer|.
  1688. Span<uint8_t> pending_app_data;
  1689. // partial write - check the numbers match
  1690. unsigned int wnum = 0; // number of bytes sent so far
  1691. int wpend_tot = 0; // number bytes written
  1692. int wpend_type = 0;
  1693. int wpend_ret = 0; // number of bytes submitted
  1694. const uint8_t *wpend_buf = nullptr;
  1695. // read_shutdown is the shutdown state for the read half of the connection.
  1696. enum ssl_shutdown_t read_shutdown = ssl_shutdown_none;
  1697. // write_shutdown is the shutdown state for the write half of the connection.
  1698. enum ssl_shutdown_t write_shutdown = ssl_shutdown_none;
  1699. // read_error, if |read_shutdown| is |ssl_shutdown_error|, is the error for
  1700. // the receive half of the connection.
  1701. UniquePtr<ERR_SAVE_STATE> read_error;
  1702. int alert_dispatch = 0;
  1703. int total_renegotiations = 0;
  1704. // This holds a variable that indicates what we were doing when a 0 or -1 is
  1705. // returned. This is needed for non-blocking IO so we know what request
  1706. // needs re-doing when in SSL_accept or SSL_connect
  1707. int rwstate = SSL_NOTHING;
  1708. // early_data_skipped is the amount of early data that has been skipped by the
  1709. // record layer.
  1710. uint16_t early_data_skipped = 0;
  1711. // empty_record_count is the number of consecutive empty records received.
  1712. uint8_t empty_record_count = 0;
  1713. // warning_alert_count is the number of consecutive warning alerts
  1714. // received.
  1715. uint8_t warning_alert_count = 0;
  1716. // key_update_count is the number of consecutive KeyUpdates received.
  1717. uint8_t key_update_count = 0;
  1718. // The negotiated Token Binding key parameter. Only valid if
  1719. // |token_binding_negotiated| is set.
  1720. uint8_t negotiated_token_binding_param = 0;
  1721. // skip_early_data instructs the record layer to skip unexpected early data
  1722. // messages when 0RTT is rejected.
  1723. bool skip_early_data:1;
  1724. // have_version is true if the connection's final version is known. Otherwise
  1725. // the version has not been negotiated yet.
  1726. bool have_version:1;
  1727. // v2_hello_done is true if the peer's V2ClientHello, if any, has been handled
  1728. // and future messages should use the record layer.
  1729. bool v2_hello_done:1;
  1730. // is_v2_hello is true if the current handshake message was derived from a
  1731. // V2ClientHello rather than received from the peer directly.
  1732. bool is_v2_hello:1;
  1733. // has_message is true if the current handshake message has been returned
  1734. // at least once by |get_message| and false otherwise.
  1735. bool has_message:1;
  1736. // initial_handshake_complete is true if the initial handshake has
  1737. // completed.
  1738. bool initial_handshake_complete:1;
  1739. // session_reused indicates whether a session was resumed.
  1740. bool session_reused:1;
  1741. bool send_connection_binding:1;
  1742. // In a client, this means that the server supported Channel ID and that a
  1743. // Channel ID was sent. In a server it means that we echoed support for
  1744. // Channel IDs and that |channel_id| will be valid after the handshake.
  1745. bool channel_id_valid:1;
  1746. // key_update_pending is true if we have a KeyUpdate acknowledgment
  1747. // outstanding.
  1748. bool key_update_pending:1;
  1749. // wpend_pending is true if we have a pending write outstanding.
  1750. bool wpend_pending:1;
  1751. // early_data_accepted is true if early data was accepted by the server.
  1752. bool early_data_accepted:1;
  1753. // draft_downgrade is whether the TLS 1.3 anti-downgrade logic would have
  1754. // fired, were it not a draft.
  1755. bool draft_downgrade:1;
  1756. // token_binding_negotiated is set if Token Binding was negotiated.
  1757. bool token_binding_negotiated:1;
  1758. // hs_buf is the buffer of handshake data to process.
  1759. UniquePtr<BUF_MEM> hs_buf;
  1760. // pending_hs_data contains the pending handshake data that has not yet
  1761. // been encrypted to |pending_flight|. This allows packing the handshake into
  1762. // fewer records.
  1763. UniquePtr<BUF_MEM> pending_hs_data;
  1764. // pending_flight is the pending outgoing flight. This is used to flush each
  1765. // handshake flight in a single write. |write_buffer| must be written out
  1766. // before this data.
  1767. UniquePtr<BUF_MEM> pending_flight;
  1768. // pending_flight_offset is the number of bytes of |pending_flight| which have
  1769. // been successfully written.
  1770. uint32_t pending_flight_offset = 0;
  1771. // ticket_age_skew is the difference, in seconds, between the client-sent
  1772. // ticket age and the server-computed value in TLS 1.3 server connections
  1773. // which resumed a session.
  1774. int32_t ticket_age_skew = 0;
  1775. // aead_read_ctx is the current read cipher state.
  1776. UniquePtr<SSLAEADContext> aead_read_ctx;
  1777. // aead_write_ctx is the current write cipher state.
  1778. UniquePtr<SSLAEADContext> aead_write_ctx;
  1779. // hs is the handshake state for the current handshake or NULL if there isn't
  1780. // one.
  1781. UniquePtr<SSL_HANDSHAKE> hs;
  1782. uint8_t write_traffic_secret[EVP_MAX_MD_SIZE] = {0};
  1783. uint8_t read_traffic_secret[EVP_MAX_MD_SIZE] = {0};
  1784. uint8_t exporter_secret[EVP_MAX_MD_SIZE] = {0};
  1785. uint8_t early_exporter_secret[EVP_MAX_MD_SIZE] = {0};
  1786. uint8_t write_traffic_secret_len = 0;
  1787. uint8_t read_traffic_secret_len = 0;
  1788. uint8_t exporter_secret_len = 0;
  1789. uint8_t early_exporter_secret_len = 0;
  1790. // Connection binding to prevent renegotiation attacks
  1791. uint8_t previous_client_finished[12] = {0};
  1792. uint8_t previous_client_finished_len = 0;
  1793. uint8_t previous_server_finished_len = 0;
  1794. uint8_t previous_server_finished[12] = {0};
  1795. uint8_t send_alert[2] = {0};
  1796. // established_session is the session established by the connection. This
  1797. // session is only filled upon the completion of the handshake and is
  1798. // immutable.
  1799. UniquePtr<SSL_SESSION> established_session;
  1800. // Next protocol negotiation. For the client, this is the protocol that we
  1801. // sent in NextProtocol and is set when handling ServerHello extensions.
  1802. //
  1803. // For a server, this is the client's selected_protocol from NextProtocol and
  1804. // is set when handling the NextProtocol message, before the Finished
  1805. // message.
  1806. Array<uint8_t> next_proto_negotiated;
  1807. // ALPN information
  1808. // (we are in the process of transitioning from NPN to ALPN.)
  1809. // In a server these point to the selected ALPN protocol after the
  1810. // ClientHello has been processed. In a client these contain the protocol
  1811. // that the server selected once the ServerHello has been processed.
  1812. Array<uint8_t> alpn_selected;
  1813. // hostname, on the server, is the value of the SNI extension.
  1814. UniquePtr<char> hostname;
  1815. // For a server:
  1816. // If |channel_id_valid| is true, then this contains the
  1817. // verified Channel ID from the client: a P256 point, (x,y), where
  1818. // each are big-endian values.
  1819. uint8_t channel_id[64] = {0};
  1820. // Contains the QUIC transport params received by the peer.
  1821. Array<uint8_t> peer_quic_transport_params;
  1822. // srtp_profile is the selected SRTP protection profile for
  1823. // DTLS-SRTP.
  1824. const SRTP_PROTECTION_PROFILE *srtp_profile = nullptr;
  1825. };
  1826. // lengths of messages
  1827. #define DTLS1_COOKIE_LENGTH 256
  1828. #define DTLS1_RT_HEADER_LENGTH 13
  1829. #define DTLS1_HM_HEADER_LENGTH 12
  1830. #define DTLS1_CCS_HEADER_LENGTH 1
  1831. #define DTLS1_AL_HEADER_LENGTH 2
  1832. struct hm_header_st {
  1833. uint8_t type;
  1834. uint32_t msg_len;
  1835. uint16_t seq;
  1836. uint32_t frag_off;
  1837. uint32_t frag_len;
  1838. };
  1839. // An hm_fragment is an incoming DTLS message, possibly not yet assembled.
  1840. struct hm_fragment {
  1841. static constexpr bool kAllowUniquePtr = true;
  1842. hm_fragment() {}
  1843. hm_fragment(const hm_fragment &) = delete;
  1844. hm_fragment &operator=(const hm_fragment &) = delete;
  1845. ~hm_fragment();
  1846. // type is the type of the message.
  1847. uint8_t type = 0;
  1848. // seq is the sequence number of this message.
  1849. uint16_t seq = 0;
  1850. // msg_len is the length of the message body.
  1851. uint32_t msg_len = 0;
  1852. // data is a pointer to the message, including message header. It has length
  1853. // |DTLS1_HM_HEADER_LENGTH| + |msg_len|.
  1854. uint8_t *data = nullptr;
  1855. // reassembly is a bitmask of |msg_len| bits corresponding to which parts of
  1856. // the message have been received. It is NULL if the message is complete.
  1857. uint8_t *reassembly = nullptr;
  1858. };
  1859. struct OPENSSL_timeval {
  1860. uint64_t tv_sec;
  1861. uint32_t tv_usec;
  1862. };
  1863. struct DTLS1_STATE {
  1864. static constexpr bool kAllowUniquePtr = true;
  1865. DTLS1_STATE();
  1866. ~DTLS1_STATE();
  1867. // has_change_cipher_spec is true if we have received a ChangeCipherSpec from
  1868. // the peer in this epoch.
  1869. bool has_change_cipher_spec:1;
  1870. // outgoing_messages_complete is true if |outgoing_messages| has been
  1871. // completed by an attempt to flush it. Future calls to |add_message| and
  1872. // |add_change_cipher_spec| will start a new flight.
  1873. bool outgoing_messages_complete:1;
  1874. // flight_has_reply is true if the current outgoing flight is complete and has
  1875. // processed at least one message. This is used to detect whether we or the
  1876. // peer sent the final flight.
  1877. bool flight_has_reply:1;
  1878. uint8_t cookie[DTLS1_COOKIE_LENGTH] = {0};
  1879. size_t cookie_len = 0;
  1880. // The current data and handshake epoch. This is initially undefined, and
  1881. // starts at zero once the initial handshake is completed.
  1882. uint16_t r_epoch = 0;
  1883. uint16_t w_epoch = 0;
  1884. // records being received in the current epoch
  1885. DTLS1_BITMAP bitmap;
  1886. uint16_t handshake_write_seq = 0;
  1887. uint16_t handshake_read_seq = 0;
  1888. // save last sequence number for retransmissions
  1889. uint8_t last_write_sequence[8] = {0};
  1890. UniquePtr<SSLAEADContext> last_aead_write_ctx;
  1891. // incoming_messages is a ring buffer of incoming handshake messages that have
  1892. // yet to be processed. The front of the ring buffer is message number
  1893. // |handshake_read_seq|, at position |handshake_read_seq| %
  1894. // |SSL_MAX_HANDSHAKE_FLIGHT|.
  1895. UniquePtr<hm_fragment> incoming_messages[SSL_MAX_HANDSHAKE_FLIGHT];
  1896. // outgoing_messages is the queue of outgoing messages from the last handshake
  1897. // flight.
  1898. DTLS_OUTGOING_MESSAGE outgoing_messages[SSL_MAX_HANDSHAKE_FLIGHT];
  1899. uint8_t outgoing_messages_len = 0;
  1900. // outgoing_written is the number of outgoing messages that have been
  1901. // written.
  1902. uint8_t outgoing_written = 0;
  1903. // outgoing_offset is the number of bytes of the next outgoing message have
  1904. // been written.
  1905. uint32_t outgoing_offset = 0;
  1906. unsigned mtu = 0; // max DTLS packet size
  1907. // num_timeouts is the number of times the retransmit timer has fired since
  1908. // the last time it was reset.
  1909. unsigned num_timeouts = 0;
  1910. // Indicates when the last handshake msg or heartbeat sent will
  1911. // timeout.
  1912. struct OPENSSL_timeval next_timeout = {0, 0};
  1913. // timeout_duration_ms is the timeout duration in milliseconds.
  1914. unsigned timeout_duration_ms = 0;
  1915. };
  1916. // SSL_CONFIG contains configuration bits that can be shed after the handshake
  1917. // completes. Objects of this type are not shared; they are unique to a
  1918. // particular |SSL|.
  1919. //
  1920. // See SSL_shed_handshake_config() for more about the conditions under which
  1921. // configuration can be shed.
  1922. struct SSL_CONFIG {
  1923. static constexpr bool kAllowUniquePtr = true;
  1924. explicit SSL_CONFIG(SSL *ssl_arg);
  1925. ~SSL_CONFIG();
  1926. // ssl is a non-owning pointer to the parent |SSL| object.
  1927. SSL *const ssl = nullptr;
  1928. // conf_max_version is the maximum acceptable protocol version configured by
  1929. // |SSL_set_max_proto_version|. Note this version is normalized in DTLS and is
  1930. // further constrainted by |SSL_OP_NO_*|.
  1931. uint16_t conf_max_version = 0;
  1932. // conf_min_version is the minimum acceptable protocol version configured by
  1933. // |SSL_set_min_proto_version|. Note this version is normalized in DTLS and is
  1934. // further constrainted by |SSL_OP_NO_*|.
  1935. uint16_t conf_min_version = 0;
  1936. X509_VERIFY_PARAM *param = nullptr;
  1937. // crypto
  1938. UniquePtr<SSLCipherPreferenceList> cipher_list;
  1939. // This is used to hold the local certificate used (i.e. the server
  1940. // certificate for a server or the client certificate for a client).
  1941. UniquePtr<CERT> cert;
  1942. int (*verify_callback)(int ok,
  1943. X509_STORE_CTX *ctx) =
  1944. nullptr; // fail if callback returns 0
  1945. enum ssl_verify_result_t (*custom_verify_callback)(
  1946. SSL *ssl, uint8_t *out_alert) = nullptr;
  1947. // Server-only: psk_identity_hint is the identity hint to send in
  1948. // PSK-based key exchanges.
  1949. UniquePtr<char> psk_identity_hint;
  1950. unsigned (*psk_client_callback)(SSL *ssl, const char *hint, char *identity,
  1951. unsigned max_identity_len, uint8_t *psk,
  1952. unsigned max_psk_len) = nullptr;
  1953. unsigned (*psk_server_callback)(SSL *ssl, const char *identity, uint8_t *psk,
  1954. unsigned max_psk_len) = nullptr;
  1955. // for server side, keep the list of CA_dn we can use
  1956. UniquePtr<STACK_OF(CRYPTO_BUFFER)> client_CA;
  1957. // cached_x509_client_CA is a cache of parsed versions of the elements of
  1958. // |client_CA|.
  1959. STACK_OF(X509_NAME) *cached_x509_client_CA = nullptr;
  1960. uint16_t dummy_pq_padding_len = 0;
  1961. Array<uint16_t> supported_group_list; // our list
  1962. // The client's Channel ID private key.
  1963. UniquePtr<EVP_PKEY> channel_id_private;
  1964. // For a client, this contains the list of supported protocols in wire
  1965. // format.
  1966. Array<uint8_t> alpn_client_proto_list;
  1967. // Contains a list of supported Token Binding key parameters.
  1968. Array<uint8_t> token_binding_params;
  1969. // Contains the QUIC transport params that this endpoint will send.
  1970. Array<uint8_t> quic_transport_params;
  1971. // verify_sigalgs, if not empty, is the set of signature algorithms
  1972. // accepted from the peer in decreasing order of preference.
  1973. Array<uint16_t> verify_sigalgs;
  1974. // srtp_profiles is the list of configured SRTP protection profiles for
  1975. // DTLS-SRTP.
  1976. UniquePtr<STACK_OF(SRTP_PROTECTION_PROFILE)> srtp_profiles;
  1977. // verify_mode is a bitmask of |SSL_VERIFY_*| values.
  1978. uint8_t verify_mode = SSL_VERIFY_NONE;
  1979. // Enable signed certificate time stamps. Currently client only.
  1980. bool signed_cert_timestamps_enabled:1;
  1981. // ocsp_stapling_enabled is only used by client connections and indicates
  1982. // whether OCSP stapling will be requested.
  1983. bool ocsp_stapling_enabled:1;
  1984. // channel_id_enabled is copied from the |SSL_CTX|. For a server, means that
  1985. // we'll accept Channel IDs from clients. For a client, means that we'll
  1986. // advertise support.
  1987. bool channel_id_enabled:1;
  1988. // retain_only_sha256_of_client_certs is true if we should compute the SHA256
  1989. // hash of the peer's certificate and then discard it to save memory and
  1990. // session space. Only effective on the server side.
  1991. bool retain_only_sha256_of_client_certs:1;
  1992. // handoff indicates that a server should stop after receiving the
  1993. // ClientHello and pause the handshake in such a way that |SSL_get_error|
  1994. // returns |SSL_HANDOFF|. This is copied in |SSL_new| from the |SSL_CTX|
  1995. // element of the same name and may be cleared if the handoff is declined.
  1996. bool handoff:1;
  1997. // shed_handshake_config indicates that the handshake config (this object!)
  1998. // should be freed after the handshake completes.
  1999. bool shed_handshake_config : 1;
  2000. };
  2001. // From draft-ietf-tls-tls13-18, used in determining PSK modes.
  2002. #define SSL_PSK_DHE_KE 0x1
  2003. // From draft-ietf-tls-tls13-16, used in determining whether to respond with a
  2004. // KeyUpdate.
  2005. #define SSL_KEY_UPDATE_NOT_REQUESTED 0
  2006. #define SSL_KEY_UPDATE_REQUESTED 1
  2007. // kMaxEarlyDataAccepted is the advertised number of plaintext bytes of early
  2008. // data that will be accepted. This value should be slightly below
  2009. // kMaxEarlyDataSkipped in tls_record.c, which is measured in ciphertext.
  2010. static const size_t kMaxEarlyDataAccepted = 14336;
  2011. UniquePtr<CERT> ssl_cert_dup(CERT *cert);
  2012. void ssl_cert_clear_certs(CERT *cert);
  2013. int ssl_set_cert(CERT *cert, UniquePtr<CRYPTO_BUFFER> buffer);
  2014. int ssl_is_key_type_supported(int key_type);
  2015. // ssl_compare_public_and_private_key returns one if |pubkey| is the public
  2016. // counterpart to |privkey|. Otherwise it returns zero and pushes a helpful
  2017. // message on the error queue.
  2018. int ssl_compare_public_and_private_key(const EVP_PKEY *pubkey,
  2019. const EVP_PKEY *privkey);
  2020. int ssl_cert_check_private_key(const CERT *cert, const EVP_PKEY *privkey);
  2021. int ssl_get_new_session(SSL_HANDSHAKE *hs, int is_server);
  2022. int ssl_encrypt_ticket(SSL_HANDSHAKE *hs, CBB *out, const SSL_SESSION *session);
  2023. int ssl_ctx_rotate_ticket_encryption_key(SSL_CTX *ctx);
  2024. // ssl_session_new returns a newly-allocated blank |SSL_SESSION| or nullptr on
  2025. // error.
  2026. UniquePtr<SSL_SESSION> ssl_session_new(const SSL_X509_METHOD *x509_method);
  2027. // ssl_hash_session_id returns a hash of |session_id|, suitable for a hash table
  2028. // keyed on session IDs.
  2029. uint32_t ssl_hash_session_id(Span<const uint8_t> session_id);
  2030. // SSL_SESSION_parse parses an |SSL_SESSION| from |cbs| and advances |cbs| over
  2031. // the parsed data.
  2032. OPENSSL_EXPORT UniquePtr<SSL_SESSION> SSL_SESSION_parse(
  2033. CBS *cbs, const SSL_X509_METHOD *x509_method, CRYPTO_BUFFER_POOL *pool);
  2034. // ssl_session_serialize writes |in| to |cbb| as if it were serialising a
  2035. // session for Session-ID resumption. It returns one on success and zero on
  2036. // error.
  2037. OPENSSL_EXPORT int ssl_session_serialize(const SSL_SESSION *in, CBB *cbb);
  2038. // ssl_session_is_context_valid returns one if |session|'s session ID context
  2039. // matches the one set on |hs| and zero otherwise.
  2040. int ssl_session_is_context_valid(const SSL_HANDSHAKE *hs,
  2041. const SSL_SESSION *session);
  2042. // ssl_session_is_time_valid returns one if |session| is still valid and zero if
  2043. // it has expired.
  2044. int ssl_session_is_time_valid(const SSL *ssl, const SSL_SESSION *session);
  2045. // ssl_session_is_resumable returns one if |session| is resumable for |hs| and
  2046. // zero otherwise.
  2047. int ssl_session_is_resumable(const SSL_HANDSHAKE *hs,
  2048. const SSL_SESSION *session);
  2049. // ssl_session_protocol_version returns the protocol version associated with
  2050. // |session|. Note that despite the name, this is not the same as
  2051. // |SSL_SESSION_get_protocol_version|. The latter is based on upstream's name.
  2052. uint16_t ssl_session_protocol_version(const SSL_SESSION *session);
  2053. // ssl_session_get_digest returns the digest used in |session|.
  2054. const EVP_MD *ssl_session_get_digest(const SSL_SESSION *session);
  2055. void ssl_set_session(SSL *ssl, SSL_SESSION *session);
  2056. // ssl_get_prev_session looks up the previous session based on |client_hello|.
  2057. // On success, it sets |*out_session| to the session or nullptr if none was
  2058. // found. If the session could not be looked up synchronously, it returns
  2059. // |ssl_hs_pending_session| and should be called again. If a ticket could not be
  2060. // decrypted immediately it returns |ssl_hs_pending_ticket| and should also
  2061. // be called again. Otherwise, it returns |ssl_hs_error|.
  2062. enum ssl_hs_wait_t ssl_get_prev_session(SSL_HANDSHAKE *hs,
  2063. UniquePtr<SSL_SESSION> *out_session,
  2064. bool *out_tickets_supported,
  2065. bool *out_renew_ticket,
  2066. const SSL_CLIENT_HELLO *client_hello);
  2067. // The following flags determine which parts of the session are duplicated.
  2068. #define SSL_SESSION_DUP_AUTH_ONLY 0x0
  2069. #define SSL_SESSION_INCLUDE_TICKET 0x1
  2070. #define SSL_SESSION_INCLUDE_NONAUTH 0x2
  2071. #define SSL_SESSION_DUP_ALL \
  2072. (SSL_SESSION_INCLUDE_TICKET | SSL_SESSION_INCLUDE_NONAUTH)
  2073. // SSL_SESSION_dup returns a newly-allocated |SSL_SESSION| with a copy of the
  2074. // fields in |session| or nullptr on error. The new session is non-resumable and
  2075. // must be explicitly marked resumable once it has been filled in.
  2076. OPENSSL_EXPORT UniquePtr<SSL_SESSION> SSL_SESSION_dup(SSL_SESSION *session,
  2077. int dup_flags);
  2078. // ssl_session_rebase_time updates |session|'s start time to the current time,
  2079. // adjusting the timeout so the expiration time is unchanged.
  2080. void ssl_session_rebase_time(SSL *ssl, SSL_SESSION *session);
  2081. // ssl_session_renew_timeout calls |ssl_session_rebase_time| and renews
  2082. // |session|'s timeout to |timeout| (measured from the current time). The
  2083. // renewal is clamped to the session's auth_timeout.
  2084. void ssl_session_renew_timeout(SSL *ssl, SSL_SESSION *session,
  2085. uint32_t timeout);
  2086. void ssl_update_cache(SSL_HANDSHAKE *hs, int mode);
  2087. int ssl_send_alert(SSL *ssl, int level, int desc);
  2088. bool ssl3_get_message(SSL *ssl, SSLMessage *out);
  2089. ssl_open_record_t ssl3_open_handshake(SSL *ssl, size_t *out_consumed,
  2090. uint8_t *out_alert, Span<uint8_t> in);
  2091. void ssl3_next_message(SSL *ssl);
  2092. int ssl3_dispatch_alert(SSL *ssl);
  2093. ssl_open_record_t ssl3_open_app_data(SSL *ssl, Span<uint8_t> *out,
  2094. size_t *out_consumed, uint8_t *out_alert,
  2095. Span<uint8_t> in);
  2096. ssl_open_record_t ssl3_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
  2097. uint8_t *out_alert,
  2098. Span<uint8_t> in);
  2099. int ssl3_write_app_data(SSL *ssl, bool *out_needs_handshake, const uint8_t *buf,
  2100. int len);
  2101. bool ssl3_new(SSL *ssl);
  2102. void ssl3_free(SSL *ssl);
  2103. bool ssl3_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type);
  2104. bool ssl3_finish_message(SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg);
  2105. bool ssl3_add_message(SSL *ssl, Array<uint8_t> msg);
  2106. bool ssl3_add_change_cipher_spec(SSL *ssl);
  2107. bool ssl3_add_alert(SSL *ssl, uint8_t level, uint8_t desc);
  2108. int ssl3_flush_flight(SSL *ssl);
  2109. bool dtls1_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type);
  2110. bool dtls1_finish_message(SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg);
  2111. bool dtls1_add_message(SSL *ssl, Array<uint8_t> msg);
  2112. bool dtls1_add_change_cipher_spec(SSL *ssl);
  2113. bool dtls1_add_alert(SSL *ssl, uint8_t level, uint8_t desc);
  2114. int dtls1_flush_flight(SSL *ssl);
  2115. // ssl_add_message_cbb finishes the handshake message in |cbb| and adds it to
  2116. // the pending flight. It returns true on success and false on error.
  2117. bool ssl_add_message_cbb(SSL *ssl, CBB *cbb);
  2118. // ssl_hash_message incorporates |msg| into the handshake hash. It returns true
  2119. // on success and false on allocation failure.
  2120. bool ssl_hash_message(SSL_HANDSHAKE *hs, const SSLMessage &msg);
  2121. ssl_open_record_t dtls1_open_app_data(SSL *ssl, Span<uint8_t> *out,
  2122. size_t *out_consumed, uint8_t *out_alert,
  2123. Span<uint8_t> in);
  2124. ssl_open_record_t dtls1_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
  2125. uint8_t *out_alert,
  2126. Span<uint8_t> in);
  2127. int dtls1_write_app_data(SSL *ssl, bool *out_needs_handshake,
  2128. const uint8_t *buf, int len);
  2129. // dtls1_write_record sends a record. It returns one on success and <= 0 on
  2130. // error.
  2131. int dtls1_write_record(SSL *ssl, int type, const uint8_t *buf, size_t len,
  2132. enum dtls1_use_epoch_t use_epoch);
  2133. int dtls1_retransmit_outgoing_messages(SSL *ssl);
  2134. bool dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
  2135. CBS *out_body);
  2136. bool dtls1_check_timeout_num(SSL *ssl);
  2137. void dtls1_start_timer(SSL *ssl);
  2138. void dtls1_stop_timer(SSL *ssl);
  2139. bool dtls1_is_timer_expired(SSL *ssl);
  2140. unsigned int dtls1_min_mtu(void);
  2141. bool dtls1_new(SSL *ssl);
  2142. void dtls1_free(SSL *ssl);
  2143. bool dtls1_get_message(SSL *ssl, SSLMessage *out);
  2144. ssl_open_record_t dtls1_open_handshake(SSL *ssl, size_t *out_consumed,
  2145. uint8_t *out_alert, Span<uint8_t> in);
  2146. void dtls1_next_message(SSL *ssl);
  2147. int dtls1_dispatch_alert(SSL *ssl);
  2148. // tls1_configure_aead configures either the read or write direction AEAD (as
  2149. // determined by |direction|) using the keys generated by the TLS KDF. The
  2150. // |key_block_cache| argument is used to store the generated key block, if
  2151. // empty. Otherwise it's assumed that the key block is already contained within
  2152. // it. Returns one on success or zero on error.
  2153. int tls1_configure_aead(SSL *ssl, evp_aead_direction_t direction,
  2154. Array<uint8_t> *key_block_cache,
  2155. const SSL_CIPHER *cipher,
  2156. Span<const uint8_t> iv_override);
  2157. int tls1_change_cipher_state(SSL_HANDSHAKE *hs, evp_aead_direction_t direction);
  2158. int tls1_generate_master_secret(SSL_HANDSHAKE *hs, uint8_t *out,
  2159. Span<const uint8_t> premaster);
  2160. // tls1_get_grouplist returns the locally-configured group preference list.
  2161. Span<const uint16_t> tls1_get_grouplist(const SSL_HANDSHAKE *ssl);
  2162. // tls1_check_group_id returns whether |group_id| is consistent with locally-
  2163. // configured group preferences.
  2164. bool tls1_check_group_id(const SSL_HANDSHAKE *ssl, uint16_t group_id);
  2165. // tls1_get_shared_group sets |*out_group_id| to the first preferred shared
  2166. // group between client and server preferences and returns true. If none may be
  2167. // found, it returns false.
  2168. bool tls1_get_shared_group(SSL_HANDSHAKE *hs, uint16_t *out_group_id);
  2169. // tls1_set_curves converts the array of NIDs in |curves| into a newly allocated
  2170. // array of TLS group IDs. On success, the function returns true and writes the
  2171. // array to |*out_group_ids|. Otherwise, it returns false.
  2172. bool tls1_set_curves(Array<uint16_t> *out_group_ids, Span<const int> curves);
  2173. // tls1_set_curves_list converts the string of curves pointed to by |curves|
  2174. // into a newly allocated array of TLS group IDs. On success, the function
  2175. // returns true and writes the array to |*out_group_ids|. Otherwise, it returns
  2176. // false.
  2177. bool tls1_set_curves_list(Array<uint16_t> *out_group_ids, const char *curves);
  2178. // ssl_add_clienthello_tlsext writes ClientHello extensions to |out|. It returns
  2179. // true on success and false on failure. The |header_len| argument is the length
  2180. // of the ClientHello written so far and is used to compute the padding length.
  2181. // (It does not include the record header.)
  2182. bool ssl_add_clienthello_tlsext(SSL_HANDSHAKE *hs, CBB *out, size_t header_len);
  2183. bool ssl_add_serverhello_tlsext(SSL_HANDSHAKE *hs, CBB *out);
  2184. bool ssl_parse_clienthello_tlsext(SSL_HANDSHAKE *hs,
  2185. const SSL_CLIENT_HELLO *client_hello);
  2186. bool ssl_parse_serverhello_tlsext(SSL_HANDSHAKE *hs, CBS *cbs);
  2187. #define tlsext_tick_md EVP_sha256
  2188. // ssl_process_ticket processes a session ticket from the client. It returns
  2189. // one of:
  2190. // |ssl_ticket_aead_success|: |*out_session| is set to the parsed session and
  2191. // |*out_renew_ticket| is set to whether the ticket should be renewed.
  2192. // |ssl_ticket_aead_ignore_ticket|: |*out_renew_ticket| is set to whether a
  2193. // fresh ticket should be sent, but the given ticket cannot be used.
  2194. // |ssl_ticket_aead_retry|: the ticket could not be immediately decrypted.
  2195. // Retry later.
  2196. // |ssl_ticket_aead_error|: an error occured that is fatal to the connection.
  2197. enum ssl_ticket_aead_result_t ssl_process_ticket(
  2198. SSL_HANDSHAKE *hs, UniquePtr<SSL_SESSION> *out_session,
  2199. bool *out_renew_ticket, const uint8_t *ticket, size_t ticket_len,
  2200. const uint8_t *session_id, size_t session_id_len);
  2201. // tls1_verify_channel_id processes |msg| as a Channel ID message, and verifies
  2202. // the signature. If the key is valid, it saves the Channel ID and returns true.
  2203. // Otherwise, it returns false.
  2204. bool tls1_verify_channel_id(SSL_HANDSHAKE *hs, const SSLMessage &msg);
  2205. // tls1_write_channel_id generates a Channel ID message and puts the output in
  2206. // |cbb|. |ssl->channel_id_private| must already be set before calling. This
  2207. // function returns true on success and false on error.
  2208. bool tls1_write_channel_id(SSL_HANDSHAKE *hs, CBB *cbb);
  2209. // tls1_channel_id_hash computes the hash to be signed by Channel ID and writes
  2210. // it to |out|, which must contain at least |EVP_MAX_MD_SIZE| bytes. It returns
  2211. // true on success and false on failure.
  2212. bool tls1_channel_id_hash(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len);
  2213. // tls1_record_handshake_hashes_for_channel_id records the current handshake
  2214. // hashes in |hs->new_session| so that Channel ID resumptions can sign that
  2215. // data.
  2216. bool tls1_record_handshake_hashes_for_channel_id(SSL_HANDSHAKE *hs);
  2217. // ssl_do_channel_id_callback checks runs |hs->ssl->ctx->channel_id_cb| if
  2218. // necessary. It returns true on success and false on fatal error. Note that, on
  2219. // success, |hs->ssl->channel_id_private| may be unset, in which case the
  2220. // operation should be retried later.
  2221. bool ssl_do_channel_id_callback(SSL_HANDSHAKE *hs);
  2222. // ssl_can_write returns whether |ssl| is allowed to write.
  2223. bool ssl_can_write(const SSL *ssl);
  2224. // ssl_can_read returns wheter |ssl| is allowed to read.
  2225. bool ssl_can_read(const SSL *ssl);
  2226. void ssl_get_current_time(const SSL *ssl, struct OPENSSL_timeval *out_clock);
  2227. void ssl_ctx_get_current_time(const SSL_CTX *ctx,
  2228. struct OPENSSL_timeval *out_clock);
  2229. // ssl_reset_error_state resets state for |SSL_get_error|.
  2230. void ssl_reset_error_state(SSL *ssl);
  2231. // ssl_set_read_error sets |ssl|'s read half into an error state, saving the
  2232. // current state of the error queue.
  2233. void ssl_set_read_error(SSL* ssl);
  2234. } // namespace bssl
  2235. // Opaque C types.
  2236. //
  2237. // The following types are exported to C code as public typedefs, so they must
  2238. // be defined outside of the namespace.
  2239. // ssl_method_st backs the public |SSL_METHOD| type. It is a compatibility
  2240. // structure to support the legacy version-locked methods.
  2241. struct ssl_method_st {
  2242. // version, if non-zero, is the only protocol version acceptable to an
  2243. // SSL_CTX initialized from this method.
  2244. uint16_t version;
  2245. // method is the underlying SSL_PROTOCOL_METHOD that initializes the
  2246. // SSL_CTX.
  2247. const bssl::SSL_PROTOCOL_METHOD *method;
  2248. // x509_method contains pointers to functions that might deal with |X509|
  2249. // compatibility, or might be a no-op, depending on the application.
  2250. const bssl::SSL_X509_METHOD *x509_method;
  2251. };
  2252. struct ssl_ctx_st {
  2253. explicit ssl_ctx_st(const SSL_METHOD *ssl_method);
  2254. ssl_ctx_st(const ssl_ctx_st &) = delete;
  2255. ssl_ctx_st &operator=(const ssl_ctx_st &) = delete;
  2256. const bssl::SSL_PROTOCOL_METHOD *method = nullptr;
  2257. const bssl::SSL_X509_METHOD *x509_method = nullptr;
  2258. // lock is used to protect various operations on this object.
  2259. CRYPTO_MUTEX lock;
  2260. // conf_max_version is the maximum acceptable protocol version configured by
  2261. // |SSL_CTX_set_max_proto_version|. Note this version is normalized in DTLS
  2262. // and is further constrainted by |SSL_OP_NO_*|.
  2263. uint16_t conf_max_version = 0;
  2264. // conf_min_version is the minimum acceptable protocol version configured by
  2265. // |SSL_CTX_set_min_proto_version|. Note this version is normalized in DTLS
  2266. // and is further constrainted by |SSL_OP_NO_*|.
  2267. uint16_t conf_min_version = 0;
  2268. // tls13_variant is the variant of TLS 1.3 we are using for this
  2269. // configuration.
  2270. tls13_variant_t tls13_variant = tls13_default;
  2271. bssl::UniquePtr<bssl::SSLCipherPreferenceList> cipher_list;
  2272. X509_STORE *cert_store = nullptr;
  2273. LHASH_OF(SSL_SESSION) *sessions = nullptr;
  2274. // Most session-ids that will be cached, default is
  2275. // SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited.
  2276. unsigned long session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
  2277. SSL_SESSION *session_cache_head = nullptr;
  2278. SSL_SESSION *session_cache_tail = nullptr;
  2279. // handshakes_since_cache_flush is the number of successful handshakes since
  2280. // the last cache flush.
  2281. int handshakes_since_cache_flush = 0;
  2282. // This can have one of 2 values, ored together,
  2283. // SSL_SESS_CACHE_CLIENT,
  2284. // SSL_SESS_CACHE_SERVER,
  2285. // Default is SSL_SESSION_CACHE_SERVER, which means only
  2286. // SSL_accept which cache SSL_SESSIONS.
  2287. int session_cache_mode = SSL_SESS_CACHE_SERVER;
  2288. // session_timeout is the default lifetime for new sessions in TLS 1.2 and
  2289. // earlier, in seconds.
  2290. uint32_t session_timeout = SSL_DEFAULT_SESSION_TIMEOUT;
  2291. // session_psk_dhe_timeout is the default lifetime for new sessions in TLS
  2292. // 1.3, in seconds.
  2293. uint32_t session_psk_dhe_timeout = SSL_DEFAULT_SESSION_PSK_DHE_TIMEOUT;
  2294. // If this callback is not null, it will be called each time a session id is
  2295. // added to the cache. If this function returns 1, it means that the
  2296. // callback will do a SSL_SESSION_free() when it has finished using it.
  2297. // Otherwise, on 0, it means the callback has finished with it. If
  2298. // remove_session_cb is not null, it will be called when a session-id is
  2299. // removed from the cache. After the call, OpenSSL will SSL_SESSION_free()
  2300. // it.
  2301. int (*new_session_cb)(SSL *ssl, SSL_SESSION *sess) = nullptr;
  2302. void (*remove_session_cb)(SSL_CTX *ctx, SSL_SESSION *sess) = nullptr;
  2303. SSL_SESSION *(*get_session_cb)(SSL *ssl, const uint8_t *data, int len,
  2304. int *copy) = nullptr;
  2305. CRYPTO_refcount_t references = 1;
  2306. // if defined, these override the X509_verify_cert() calls
  2307. int (*app_verify_callback)(X509_STORE_CTX *store_ctx, void *arg) = nullptr;
  2308. void *app_verify_arg = nullptr;
  2309. ssl_verify_result_t (*custom_verify_callback)(SSL *ssl,
  2310. uint8_t *out_alert) = nullptr;
  2311. // Default password callback.
  2312. pem_password_cb *default_passwd_callback = nullptr;
  2313. // Default password callback user data.
  2314. void *default_passwd_callback_userdata = nullptr;
  2315. // get client cert callback
  2316. int (*client_cert_cb)(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) = nullptr;
  2317. // get channel id callback
  2318. void (*channel_id_cb)(SSL *ssl, EVP_PKEY **out_pkey) = nullptr;
  2319. CRYPTO_EX_DATA ex_data;
  2320. // Default values used when no per-SSL value is defined follow
  2321. void (*info_callback)(const SSL *ssl, int type, int value) = nullptr;
  2322. // what we put in client cert requests
  2323. bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> client_CA;
  2324. // cached_x509_client_CA is a cache of parsed versions of the elements of
  2325. // |client_CA|.
  2326. STACK_OF(X509_NAME) *cached_x509_client_CA = nullptr;
  2327. // Default values to use in SSL structures follow (these are copied by
  2328. // SSL_new)
  2329. uint32_t options = 0;
  2330. // Disable the auto-chaining feature by default. wpa_supplicant relies on this
  2331. // feature, but require callers opt into it.
  2332. uint32_t mode = SSL_MODE_NO_AUTO_CHAIN;
  2333. uint32_t max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
  2334. bssl::UniquePtr<bssl::CERT> cert;
  2335. // callback that allows applications to peek at protocol messages
  2336. void (*msg_callback)(int write_p, int version, int content_type,
  2337. const void *buf, size_t len, SSL *ssl, void *arg) = nullptr;
  2338. void *msg_callback_arg = nullptr;
  2339. int verify_mode = SSL_VERIFY_NONE;
  2340. int (*default_verify_callback)(int ok, X509_STORE_CTX *ctx) =
  2341. nullptr; // called 'verify_callback' in the SSL
  2342. X509_VERIFY_PARAM *param = nullptr;
  2343. // select_certificate_cb is called before most ClientHello processing and
  2344. // before the decision whether to resume a session is made. See
  2345. // |ssl_select_cert_result_t| for details of the return values.
  2346. ssl_select_cert_result_t (*select_certificate_cb)(const SSL_CLIENT_HELLO *) =
  2347. nullptr;
  2348. // dos_protection_cb is called once the resumption decision for a ClientHello
  2349. // has been made. It returns one to continue the handshake or zero to
  2350. // abort.
  2351. int (*dos_protection_cb) (const SSL_CLIENT_HELLO *) = nullptr;
  2352. // Maximum amount of data to send in one fragment. actual record size can be
  2353. // more than this due to padding and MAC overheads.
  2354. uint16_t max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
  2355. // TLS extensions servername callback
  2356. int (*servername_callback)(SSL *, int *, void *) = nullptr;
  2357. void *servername_arg = nullptr;
  2358. // RFC 4507 session ticket keys. |ticket_key_current| may be NULL before the
  2359. // first handshake and |ticket_key_prev| may be NULL at any time.
  2360. // Automatically generated ticket keys are rotated as needed at handshake
  2361. // time. Hence, all access must be synchronized through |lock|.
  2362. bssl::UniquePtr<bssl::TicketKey> ticket_key_current;
  2363. bssl::UniquePtr<bssl::TicketKey> ticket_key_prev;
  2364. // Callback to support customisation of ticket key setting
  2365. int (*ticket_key_cb)(SSL *ssl, uint8_t *name, uint8_t *iv,
  2366. EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc) = nullptr;
  2367. // Server-only: psk_identity_hint is the default identity hint to send in
  2368. // PSK-based key exchanges.
  2369. bssl::UniquePtr<char> psk_identity_hint;
  2370. unsigned (*psk_client_callback)(SSL *ssl, const char *hint, char *identity,
  2371. unsigned max_identity_len, uint8_t *psk,
  2372. unsigned max_psk_len) = nullptr;
  2373. unsigned (*psk_server_callback)(SSL *ssl, const char *identity, uint8_t *psk,
  2374. unsigned max_psk_len) = nullptr;
  2375. // Next protocol negotiation information
  2376. // (for experimental NPN extension).
  2377. // For a server, this contains a callback function by which the set of
  2378. // advertised protocols can be provided.
  2379. int (*next_protos_advertised_cb)(SSL *ssl, const uint8_t **out,
  2380. unsigned *out_len, void *arg) = nullptr;
  2381. void *next_protos_advertised_cb_arg = nullptr;
  2382. // For a client, this contains a callback function that selects the
  2383. // next protocol from the list provided by the server.
  2384. int (*next_proto_select_cb)(SSL *ssl, uint8_t **out, uint8_t *out_len,
  2385. const uint8_t *in, unsigned in_len,
  2386. void *arg) = nullptr;
  2387. void *next_proto_select_cb_arg = nullptr;
  2388. // ALPN information
  2389. // (we are in the process of transitioning from NPN to ALPN.)
  2390. // For a server, this contains a callback function that allows the
  2391. // server to select the protocol for the connection.
  2392. // out: on successful return, this must point to the raw protocol
  2393. // name (without the length prefix).
  2394. // outlen: on successful return, this contains the length of |*out|.
  2395. // in: points to the client's list of supported protocols in
  2396. // wire-format.
  2397. // inlen: the length of |in|.
  2398. int (*alpn_select_cb)(SSL *ssl, const uint8_t **out, uint8_t *out_len,
  2399. const uint8_t *in, unsigned in_len,
  2400. void *arg) = nullptr;
  2401. void *alpn_select_cb_arg = nullptr;
  2402. // For a client, this contains the list of supported protocols in wire
  2403. // format.
  2404. bssl::Array<uint8_t> alpn_client_proto_list;
  2405. // SRTP profiles we are willing to do from RFC 5764
  2406. bssl::UniquePtr<STACK_OF(SRTP_PROTECTION_PROFILE)> srtp_profiles;
  2407. // Defined compression algorithms for certificates.
  2408. bssl::UniquePtr<STACK_OF(CertCompressionAlg)> cert_compression_algs;
  2409. // Supported group values inherited by SSL structure
  2410. bssl::Array<uint16_t> supported_group_list;
  2411. // The client's Channel ID private key.
  2412. bssl::UniquePtr<EVP_PKEY> channel_id_private;
  2413. // keylog_callback, if not NULL, is the key logging callback. See
  2414. // |SSL_CTX_set_keylog_callback|.
  2415. void (*keylog_callback)(const SSL *ssl, const char *line) = nullptr;
  2416. // current_time_cb, if not NULL, is the function to use to get the current
  2417. // time. It sets |*out_clock| to the current time. The |ssl| argument is
  2418. // always NULL. See |SSL_CTX_set_current_time_cb|.
  2419. void (*current_time_cb)(const SSL *ssl, struct timeval *out_clock) = nullptr;
  2420. // pool is used for all |CRYPTO_BUFFER|s in case we wish to share certificate
  2421. // memory.
  2422. CRYPTO_BUFFER_POOL *pool = nullptr;
  2423. // ticket_aead_method contains function pointers for opening and sealing
  2424. // session tickets.
  2425. const SSL_TICKET_AEAD_METHOD *ticket_aead_method = nullptr;
  2426. // legacy_ocsp_callback implements an OCSP-related callback for OpenSSL
  2427. // compatibility.
  2428. int (*legacy_ocsp_callback)(SSL *ssl, void *arg) = nullptr;
  2429. void *legacy_ocsp_callback_arg = nullptr;
  2430. // verify_sigalgs, if not empty, is the set of signature algorithms
  2431. // accepted from the peer in decreasing order of preference.
  2432. bssl::Array<uint16_t> verify_sigalgs;
  2433. // retain_only_sha256_of_client_certs is true if we should compute the SHA256
  2434. // hash of the peer's certificate and then discard it to save memory and
  2435. // session space. Only effective on the server side.
  2436. bool retain_only_sha256_of_client_certs:1;
  2437. // quiet_shutdown is true if the connection should not send a close_notify on
  2438. // shutdown.
  2439. bool quiet_shutdown:1;
  2440. // ocsp_stapling_enabled is only used by client connections and indicates
  2441. // whether OCSP stapling will be requested.
  2442. bool ocsp_stapling_enabled:1;
  2443. // If true, a client will request certificate timestamps.
  2444. bool signed_cert_timestamps_enabled:1;
  2445. // channel_id_enabled is whether Channel ID is enabled. For a server, means
  2446. // that we'll accept Channel IDs from clients. For a client, means that we'll
  2447. // advertise support.
  2448. bool channel_id_enabled:1;
  2449. // grease_enabled is whether draft-davidben-tls-grease-01 is enabled.
  2450. bool grease_enabled:1;
  2451. // allow_unknown_alpn_protos is whether the client allows unsolicited ALPN
  2452. // protocols from the peer.
  2453. bool allow_unknown_alpn_protos:1;
  2454. // ed25519_enabled is whether Ed25519 is advertised in the handshake.
  2455. bool ed25519_enabled:1;
  2456. // rsa_pss_rsae_certs_enabled is whether rsa_pss_rsae_* are supported by the
  2457. // certificate verifier.
  2458. bool rsa_pss_rsae_certs_enabled:1;
  2459. // false_start_allowed_without_alpn is whether False Start (if
  2460. // |SSL_MODE_ENABLE_FALSE_START| is enabled) is allowed without ALPN.
  2461. bool false_start_allowed_without_alpn:1;
  2462. // handoff indicates that a server should stop after receiving the
  2463. // ClientHello and pause the handshake in such a way that |SSL_get_error|
  2464. // returns |SSL_HANDOFF|.
  2465. bool handoff:1;
  2466. // If enable_early_data is true, early data can be sent and accepted.
  2467. bool enable_early_data : 1;
  2468. private:
  2469. ~ssl_ctx_st();
  2470. friend void SSL_CTX_free(SSL_CTX *);
  2471. };
  2472. struct ssl_st {
  2473. explicit ssl_st(SSL_CTX *ctx_arg);
  2474. ssl_st(const ssl_st &) = delete;
  2475. ssl_st &operator=(const ssl_st &) = delete;
  2476. ~ssl_st();
  2477. // method is the method table corresponding to the current protocol (DTLS or
  2478. // TLS).
  2479. const bssl::SSL_PROTOCOL_METHOD *method = nullptr;
  2480. // config is a container for handshake configuration. Accesses to this field
  2481. // should check for nullptr, since configuration may be shed after the
  2482. // handshake completes. (If you have the |SSL_HANDSHAKE| object at hand, use
  2483. // that instead, and skip the null check.)
  2484. bssl::UniquePtr<bssl::SSL_CONFIG> config;
  2485. // version is the protocol version.
  2486. uint16_t version = 0;
  2487. uint16_t max_send_fragment = 0;
  2488. // There are 2 BIO's even though they are normally both the same. This is so
  2489. // data can be read and written to different handlers
  2490. bssl::UniquePtr<BIO> rbio; // used by SSL_read
  2491. bssl::UniquePtr<BIO> wbio; // used by SSL_write
  2492. // do_handshake runs the handshake. On completion, it returns |ssl_hs_ok|.
  2493. // Otherwise, it returns a value corresponding to what operation is needed to
  2494. // progress.
  2495. bssl::ssl_hs_wait_t (*do_handshake)(bssl::SSL_HANDSHAKE *hs) = nullptr;
  2496. bssl::SSL3_STATE *s3 = nullptr; // TLS variables
  2497. bssl::DTLS1_STATE *d1 = nullptr; // DTLS variables
  2498. // callback that allows applications to peek at protocol messages
  2499. void (*msg_callback)(int write_p, int version, int content_type,
  2500. const void *buf, size_t len, SSL *ssl,
  2501. void *arg) = nullptr;
  2502. void *msg_callback_arg = nullptr;
  2503. // session info
  2504. // initial_timeout_duration_ms is the default DTLS timeout duration in
  2505. // milliseconds. It's used to initialize the timer any time it's restarted.
  2506. //
  2507. // RFC 6347 states that implementations SHOULD use an initial timer value of 1
  2508. // second.
  2509. unsigned initial_timeout_duration_ms = 1000;
  2510. // tls13_variant is the variant of TLS 1.3 we are using for this
  2511. // configuration.
  2512. tls13_variant_t tls13_variant = tls13_default;
  2513. // session is the configured session to be offered by the client. This session
  2514. // is immutable.
  2515. bssl::UniquePtr<SSL_SESSION> session;
  2516. void (*info_callback)(const SSL *ssl, int type, int value) = nullptr;
  2517. bssl::UniquePtr<SSL_CTX> ctx;
  2518. // session_ctx is the |SSL_CTX| used for the session cache and related
  2519. // settings.
  2520. bssl::UniquePtr<SSL_CTX> session_ctx;
  2521. // extra application data
  2522. CRYPTO_EX_DATA ex_data;
  2523. uint32_t options = 0; // protocol behaviour
  2524. uint32_t mode = 0; // API behaviour
  2525. uint32_t max_cert_list = 0;
  2526. bssl::UniquePtr<char> hostname;
  2527. // renegotiate_mode controls how peer renegotiation attempts are handled.
  2528. ssl_renegotiate_mode_t renegotiate_mode = ssl_renegotiate_never;
  2529. // server is true iff the this SSL* is the server half. Note: before the SSL*
  2530. // is initialized by either SSL_set_accept_state or SSL_set_connect_state,
  2531. // the side is not determined. In this state, server is always false.
  2532. bool server : 1;
  2533. // quiet_shutdown is true if the connection should not send a close_notify on
  2534. // shutdown.
  2535. bool quiet_shutdown : 1;
  2536. // did_dummy_pq_padding is only valid for a client. In that context, it is
  2537. // true iff the client observed the server echoing a dummy PQ padding
  2538. // extension.
  2539. bool did_dummy_pq_padding:1;
  2540. // If enable_early_data is true, early data can be sent and accepted.
  2541. bool enable_early_data : 1;
  2542. };
  2543. struct ssl_session_st {
  2544. explicit ssl_session_st(const bssl::SSL_X509_METHOD *method);
  2545. ssl_session_st(const ssl_session_st &) = delete;
  2546. ssl_session_st &operator=(const ssl_session_st &) = delete;
  2547. CRYPTO_refcount_t references = 1;
  2548. uint16_t ssl_version = 0; // what ssl version session info is being kept in here?
  2549. // group_id is the ID of the ECDH group used to establish this session or zero
  2550. // if not applicable or unknown.
  2551. uint16_t group_id = 0;
  2552. // peer_signature_algorithm is the signature algorithm used to authenticate
  2553. // the peer, or zero if not applicable or unknown.
  2554. uint16_t peer_signature_algorithm = 0;
  2555. // master_key, in TLS 1.2 and below, is the master secret associated with the
  2556. // session. In TLS 1.3 and up, it is the resumption secret.
  2557. int master_key_length = 0;
  2558. uint8_t master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
  2559. // session_id - valid?
  2560. unsigned session_id_length = 0;
  2561. uint8_t session_id[SSL_MAX_SSL_SESSION_ID_LENGTH] = {0};
  2562. // this is used to determine whether the session is being reused in
  2563. // the appropriate context. It is up to the application to set this,
  2564. // via SSL_new
  2565. uint8_t sid_ctx_length = 0;
  2566. uint8_t sid_ctx[SSL_MAX_SID_CTX_LENGTH] = {0};
  2567. bssl::UniquePtr<char> psk_identity;
  2568. // certs contains the certificate chain from the peer, starting with the leaf
  2569. // certificate.
  2570. bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> certs;
  2571. const bssl::SSL_X509_METHOD *x509_method = nullptr;
  2572. // x509_peer is the peer's certificate.
  2573. X509 *x509_peer = nullptr;
  2574. // x509_chain is the certificate chain sent by the peer. NOTE: for historical
  2575. // reasons, when a client (so the peer is a server), the chain includes
  2576. // |peer|, but when a server it does not.
  2577. STACK_OF(X509) *x509_chain = nullptr;
  2578. // x509_chain_without_leaf is a lazily constructed copy of |x509_chain| that
  2579. // omits the leaf certificate. This exists because OpenSSL, historically,
  2580. // didn't include the leaf certificate in the chain for a server, but did for
  2581. // a client. The |x509_chain| always includes it and, if an API call requires
  2582. // a chain without, it is stored here.
  2583. STACK_OF(X509) *x509_chain_without_leaf = nullptr;
  2584. // verify_result is the result of certificate verification in the case of
  2585. // non-fatal certificate errors.
  2586. long verify_result = X509_V_ERR_INVALID_CALL;
  2587. // timeout is the lifetime of the session in seconds, measured from |time|.
  2588. // This is renewable up to |auth_timeout|.
  2589. uint32_t timeout = SSL_DEFAULT_SESSION_TIMEOUT;
  2590. // auth_timeout is the non-renewable lifetime of the session in seconds,
  2591. // measured from |time|.
  2592. uint32_t auth_timeout = SSL_DEFAULT_SESSION_TIMEOUT;
  2593. // time is the time the session was issued, measured in seconds from the UNIX
  2594. // epoch.
  2595. uint64_t time = 0;
  2596. const SSL_CIPHER *cipher = nullptr;
  2597. CRYPTO_EX_DATA ex_data; // application specific data
  2598. // These are used to make removal of session-ids more efficient and to
  2599. // implement a maximum cache size.
  2600. SSL_SESSION *prev = nullptr, *next = nullptr;
  2601. bssl::Array<uint8_t> ticket;
  2602. bssl::UniquePtr<CRYPTO_BUFFER> signed_cert_timestamp_list;
  2603. // The OCSP response that came with the session.
  2604. bssl::UniquePtr<CRYPTO_BUFFER> ocsp_response;
  2605. // peer_sha256 contains the SHA-256 hash of the peer's certificate if
  2606. // |peer_sha256_valid| is true.
  2607. uint8_t peer_sha256[SHA256_DIGEST_LENGTH] = {0};
  2608. // original_handshake_hash contains the handshake hash (either SHA-1+MD5 or
  2609. // SHA-2, depending on TLS version) for the original, full handshake that
  2610. // created a session. This is used by Channel IDs during resumption.
  2611. uint8_t original_handshake_hash[EVP_MAX_MD_SIZE] = {0};
  2612. uint8_t original_handshake_hash_len = 0;
  2613. uint32_t ticket_lifetime_hint = 0; // Session lifetime hint in seconds
  2614. uint32_t ticket_age_add = 0;
  2615. // ticket_max_early_data is the maximum amount of data allowed to be sent as
  2616. // early data. If zero, 0-RTT is disallowed.
  2617. uint32_t ticket_max_early_data = 0;
  2618. // early_alpn is the ALPN protocol from the initial handshake. This is only
  2619. // stored for TLS 1.3 and above in order to enforce ALPN matching for 0-RTT
  2620. // resumptions.
  2621. bssl::Array<uint8_t> early_alpn;
  2622. // extended_master_secret is whether the master secret in this session was
  2623. // generated using EMS and thus isn't vulnerable to the Triple Handshake
  2624. // attack.
  2625. bool extended_master_secret:1;
  2626. // peer_sha256_valid is whether |peer_sha256| is valid.
  2627. bool peer_sha256_valid:1; // Non-zero if peer_sha256 is valid
  2628. // not_resumable is used to indicate that session resumption is disallowed.
  2629. bool not_resumable:1;
  2630. // ticket_age_add_valid is whether |ticket_age_add| is valid.
  2631. bool ticket_age_add_valid:1;
  2632. // is_server is whether this session was created by a server.
  2633. bool is_server:1;
  2634. private:
  2635. ~ssl_session_st();
  2636. friend void SSL_SESSION_free(SSL_SESSION *);
  2637. };
  2638. #endif // OPENSSL_HEADER_SSL_INTERNAL_H