Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

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