internal.h 122 KB

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