internal.h 138 KB

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