2
0

statem_lib.c 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898
  1. /*
  2. * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  4. *
  5. * Licensed under the Apache License 2.0 (the "License"). You may not use
  6. * this file except in compliance with the License. You can obtain a copy
  7. * in the file LICENSE in the source distribution or at
  8. * https://www.openssl.org/source/license.html
  9. */
  10. #include <limits.h>
  11. #include <string.h>
  12. #include <stdio.h>
  13. #include "../ssl_local.h"
  14. #include "statem_local.h"
  15. #include "internal/cryptlib.h"
  16. #include "internal/ssl_unwrap.h"
  17. #include <openssl/buffer.h>
  18. #include <openssl/objects.h>
  19. #include <openssl/evp.h>
  20. #include <openssl/rsa.h>
  21. #include <openssl/x509.h>
  22. #include <openssl/trace.h>
  23. #include <openssl/encoder.h>
  24. /*
  25. * Map error codes to TLS/SSL alart types.
  26. */
  27. typedef struct x509err2alert_st {
  28. int x509err;
  29. int alert;
  30. } X509ERR2ALERT;
  31. /* Fixed value used in the ServerHello random field to identify an HRR */
  32. const unsigned char hrrrandom[] = {
  33. 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
  34. 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
  35. 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
  36. };
  37. int ossl_statem_set_mutator(SSL *s,
  38. ossl_statem_mutate_handshake_cb mutate_handshake_cb,
  39. ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb,
  40. void *mutatearg)
  41. {
  42. SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
  43. if (sc == NULL)
  44. return 0;
  45. sc->statem.mutate_handshake_cb = mutate_handshake_cb;
  46. sc->statem.mutatearg = mutatearg;
  47. sc->statem.finish_mutate_handshake_cb = finish_mutate_handshake_cb;
  48. return 1;
  49. }
  50. /*
  51. * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
  52. * SSL3_RT_CHANGE_CIPHER_SPEC)
  53. */
  54. int ssl3_do_write(SSL_CONNECTION *s, uint8_t type)
  55. {
  56. int ret;
  57. size_t written = 0;
  58. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  59. /*
  60. * If we're running the test suite then we may need to mutate the message
  61. * we've been asked to write. Does not happen in normal operation.
  62. */
  63. if (s->statem.mutate_handshake_cb != NULL
  64. && !s->statem.write_in_progress
  65. && type == SSL3_RT_HANDSHAKE
  66. && s->init_num >= SSL3_HM_HEADER_LENGTH) {
  67. unsigned char *msg;
  68. size_t msglen;
  69. if (!s->statem.mutate_handshake_cb((unsigned char *)s->init_buf->data,
  70. s->init_num,
  71. &msg, &msglen,
  72. s->statem.mutatearg))
  73. return -1;
  74. if (msglen < SSL3_HM_HEADER_LENGTH
  75. || !BUF_MEM_grow(s->init_buf, msglen))
  76. return -1;
  77. memcpy(s->init_buf->data, msg, msglen);
  78. s->init_num = msglen;
  79. s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
  80. s->statem.finish_mutate_handshake_cb(s->statem.mutatearg);
  81. s->statem.write_in_progress = 1;
  82. }
  83. ret = ssl3_write_bytes(ssl, type, &s->init_buf->data[s->init_off],
  84. s->init_num, &written);
  85. if (ret <= 0)
  86. return -1;
  87. if (type == SSL3_RT_HANDSHAKE)
  88. /*
  89. * should not be done for 'Hello Request's, but in that case we'll
  90. * ignore the result anyway
  91. * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
  92. */
  93. if (!SSL_CONNECTION_IS_TLS13(s)
  94. || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
  95. && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
  96. && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
  97. if (!ssl3_finish_mac(s,
  98. (unsigned char *)&s->init_buf->data[s->init_off],
  99. written))
  100. return -1;
  101. if (written == s->init_num) {
  102. s->statem.write_in_progress = 0;
  103. if (s->msg_callback)
  104. s->msg_callback(1, s->version, type, s->init_buf->data,
  105. (size_t)(s->init_off + s->init_num), ssl,
  106. s->msg_callback_arg);
  107. return 1;
  108. }
  109. s->init_off += written;
  110. s->init_num -= written;
  111. return 0;
  112. }
  113. int tls_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
  114. {
  115. size_t msglen;
  116. if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
  117. || !WPACKET_get_length(pkt, &msglen)
  118. || msglen > INT_MAX)
  119. return 0;
  120. s->init_num = (int)msglen;
  121. s->init_off = 0;
  122. return 1;
  123. }
  124. int tls_setup_handshake(SSL_CONNECTION *s)
  125. {
  126. int ver_min, ver_max, ok;
  127. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  128. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  129. if (!ssl3_init_finished_mac(s)) {
  130. /* SSLfatal() already called */
  131. return 0;
  132. }
  133. /* Reset any extension flags */
  134. memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
  135. if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
  136. SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
  137. return 0;
  138. }
  139. /* Sanity check that we have MD5-SHA1 if we need it */
  140. if (sctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
  141. int negotiated_minversion;
  142. int md5sha1_needed_maxversion = SSL_CONNECTION_IS_DTLS(s)
  143. ? DTLS1_VERSION : TLS1_1_VERSION;
  144. /* We don't have MD5-SHA1 - do we need it? */
  145. if (ssl_version_cmp(s, ver_max, md5sha1_needed_maxversion) <= 0) {
  146. SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
  147. SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
  148. "The max supported SSL/TLS version needs the"
  149. " MD5-SHA1 digest but it is not available"
  150. " in the loaded providers. Use (D)TLSv1.2 or"
  151. " above, or load different providers");
  152. return 0;
  153. }
  154. ok = 1;
  155. /* Don't allow TLSv1.1 or below to be negotiated */
  156. negotiated_minversion = SSL_CONNECTION_IS_DTLS(s) ?
  157. DTLS1_2_VERSION : TLS1_2_VERSION;
  158. if (ssl_version_cmp(s, ver_min, negotiated_minversion) < 0)
  159. ok = SSL_set_min_proto_version(ssl, negotiated_minversion);
  160. if (!ok) {
  161. /* Shouldn't happen */
  162. SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
  163. return 0;
  164. }
  165. }
  166. ok = 0;
  167. if (s->server) {
  168. STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
  169. int i;
  170. /*
  171. * Sanity check that the maximum version we accept has ciphers
  172. * enabled. For clients we do this check during construction of the
  173. * ClientHello.
  174. */
  175. for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
  176. const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
  177. int cipher_minprotover = SSL_CONNECTION_IS_DTLS(s)
  178. ? c->min_dtls : c->min_tls;
  179. int cipher_maxprotover = SSL_CONNECTION_IS_DTLS(s)
  180. ? c->max_dtls : c->max_tls;
  181. if (ssl_version_cmp(s, ver_max, cipher_minprotover) >= 0
  182. && ssl_version_cmp(s, ver_max, cipher_maxprotover) <= 0) {
  183. ok = 1;
  184. break;
  185. }
  186. }
  187. if (!ok) {
  188. SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
  189. SSL_R_NO_CIPHERS_AVAILABLE,
  190. "No ciphers enabled for max supported "
  191. "SSL/TLS version");
  192. return 0;
  193. }
  194. if (SSL_IS_FIRST_HANDSHAKE(s)) {
  195. /* N.B. s->session_ctx == s->ctx here */
  196. ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
  197. } else {
  198. /* N.B. s->ctx may not equal s->session_ctx */
  199. ssl_tsan_counter(sctx, &sctx->stats.sess_accept_renegotiate);
  200. s->s3.tmp.cert_request = 0;
  201. }
  202. } else {
  203. if (SSL_IS_FIRST_HANDSHAKE(s))
  204. ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
  205. else
  206. ssl_tsan_counter(s->session_ctx,
  207. &s->session_ctx->stats.sess_connect_renegotiate);
  208. /* mark client_random uninitialized */
  209. memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
  210. s->hit = 0;
  211. s->s3.tmp.cert_req = 0;
  212. if (SSL_CONNECTION_IS_DTLS(s))
  213. s->statem.use_timer = 1;
  214. }
  215. return 1;
  216. }
  217. /*
  218. * Size of the to-be-signed TLS13 data, without the hash size itself:
  219. * 64 bytes of value 32, 33 context bytes, 1 byte separator
  220. */
  221. #define TLS13_TBS_START_SIZE 64
  222. #define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
  223. static int get_cert_verify_tbs_data(SSL_CONNECTION *s, unsigned char *tls13tbs,
  224. void **hdata, size_t *hdatalen)
  225. {
  226. /* ASCII: "TLS 1.3, server CertificateVerify", in hex for EBCDIC compatibility */
  227. static const char servercontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x73\x65\x72"
  228. "\x76\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
  229. /* ASCII: "TLS 1.3, client CertificateVerify", in hex for EBCDIC compatibility */
  230. static const char clientcontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x63\x6c\x69"
  231. "\x65\x6e\x74\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
  232. if (SSL_CONNECTION_IS_TLS13(s)) {
  233. size_t hashlen;
  234. /* Set the first 64 bytes of to-be-signed data to octet 32 */
  235. memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
  236. /* This copies the 33 bytes of context plus the 0 separator byte */
  237. if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
  238. || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
  239. strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
  240. else
  241. strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
  242. /*
  243. * If we're currently reading then we need to use the saved handshake
  244. * hash value. We can't use the current handshake hash state because
  245. * that includes the CertVerify itself.
  246. */
  247. if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
  248. || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
  249. memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
  250. s->cert_verify_hash_len);
  251. hashlen = s->cert_verify_hash_len;
  252. } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
  253. EVP_MAX_MD_SIZE, &hashlen)) {
  254. /* SSLfatal() already called */
  255. return 0;
  256. }
  257. *hdata = tls13tbs;
  258. *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
  259. } else {
  260. size_t retlen;
  261. long retlen_l;
  262. retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
  263. if (retlen_l <= 0) {
  264. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  265. return 0;
  266. }
  267. *hdatalen = retlen;
  268. }
  269. return 1;
  270. }
  271. CON_FUNC_RETURN tls_construct_cert_verify(SSL_CONNECTION *s, WPACKET *pkt)
  272. {
  273. EVP_PKEY *pkey = NULL;
  274. const EVP_MD *md = NULL;
  275. EVP_MD_CTX *mctx = NULL;
  276. EVP_PKEY_CTX *pctx = NULL;
  277. size_t hdatalen = 0, siglen = 0;
  278. void *hdata;
  279. unsigned char *sig = NULL;
  280. unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
  281. const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
  282. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  283. if (lu == NULL || s->s3.tmp.cert == NULL) {
  284. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  285. goto err;
  286. }
  287. pkey = s->s3.tmp.cert->privatekey;
  288. if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
  289. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  290. goto err;
  291. }
  292. mctx = EVP_MD_CTX_new();
  293. if (mctx == NULL) {
  294. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  295. goto err;
  296. }
  297. /* Get the data to be signed */
  298. if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
  299. /* SSLfatal() already called */
  300. goto err;
  301. }
  302. if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
  303. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  304. goto err;
  305. }
  306. if (EVP_DigestSignInit_ex(mctx, &pctx,
  307. md == NULL ? NULL : EVP_MD_get0_name(md),
  308. sctx->libctx, sctx->propq, pkey,
  309. NULL) <= 0) {
  310. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  311. goto err;
  312. }
  313. if (lu->sig == EVP_PKEY_RSA_PSS) {
  314. if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
  315. || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
  316. RSA_PSS_SALTLEN_DIGEST) <= 0) {
  317. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  318. goto err;
  319. }
  320. }
  321. if (s->version == SSL3_VERSION) {
  322. /*
  323. * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
  324. * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
  325. */
  326. if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
  327. || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
  328. (int)s->session->master_key_length,
  329. s->session->master_key) <= 0
  330. || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
  331. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  332. goto err;
  333. }
  334. sig = OPENSSL_malloc(siglen);
  335. if (sig == NULL
  336. || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
  337. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  338. goto err;
  339. }
  340. } else {
  341. /*
  342. * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
  343. * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
  344. */
  345. if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
  346. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  347. goto err;
  348. }
  349. sig = OPENSSL_malloc(siglen);
  350. if (sig == NULL
  351. || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
  352. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  353. goto err;
  354. }
  355. }
  356. #ifndef OPENSSL_NO_GOST
  357. {
  358. int pktype = lu->sig;
  359. if (pktype == NID_id_GostR3410_2001
  360. || pktype == NID_id_GostR3410_2012_256
  361. || pktype == NID_id_GostR3410_2012_512)
  362. BUF_reverse(sig, NULL, siglen);
  363. }
  364. #endif
  365. if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
  366. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  367. goto err;
  368. }
  369. /* Digest cached records and discard handshake buffer */
  370. if (!ssl3_digest_cached_records(s, 0)) {
  371. /* SSLfatal() already called */
  372. goto err;
  373. }
  374. OPENSSL_free(sig);
  375. EVP_MD_CTX_free(mctx);
  376. return CON_FUNC_SUCCESS;
  377. err:
  378. OPENSSL_free(sig);
  379. EVP_MD_CTX_free(mctx);
  380. return CON_FUNC_ERROR;
  381. }
  382. MSG_PROCESS_RETURN tls_process_cert_verify(SSL_CONNECTION *s, PACKET *pkt)
  383. {
  384. EVP_PKEY *pkey = NULL;
  385. const unsigned char *data;
  386. #ifndef OPENSSL_NO_GOST
  387. unsigned char *gost_data = NULL;
  388. #endif
  389. MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
  390. int j;
  391. unsigned int len;
  392. const EVP_MD *md = NULL;
  393. size_t hdatalen = 0;
  394. void *hdata;
  395. unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
  396. EVP_MD_CTX *mctx = EVP_MD_CTX_new();
  397. EVP_PKEY_CTX *pctx = NULL;
  398. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  399. if (mctx == NULL) {
  400. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  401. goto err;
  402. }
  403. pkey = tls_get_peer_pkey(s);
  404. if (pkey == NULL) {
  405. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  406. goto err;
  407. }
  408. if (ssl_cert_lookup_by_pkey(pkey, NULL, sctx) == NULL) {
  409. SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
  410. SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
  411. goto err;
  412. }
  413. if (SSL_USE_SIGALGS(s)) {
  414. unsigned int sigalg;
  415. if (!PACKET_get_net_2(pkt, &sigalg)) {
  416. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
  417. goto err;
  418. }
  419. if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
  420. /* SSLfatal() already called */
  421. goto err;
  422. }
  423. } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
  424. SSLfatal(s, SSL_AD_INTERNAL_ERROR,
  425. SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
  426. goto err;
  427. }
  428. if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
  429. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  430. goto err;
  431. }
  432. if (SSL_USE_SIGALGS(s))
  433. OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
  434. md == NULL ? "n/a" : EVP_MD_get0_name(md));
  435. /* Check for broken implementations of GOST ciphersuites */
  436. /*
  437. * If key is GOST and len is exactly 64 or 128, it is signature without
  438. * length field (CryptoPro implementations at least till TLS 1.2)
  439. */
  440. #ifndef OPENSSL_NO_GOST
  441. if (!SSL_USE_SIGALGS(s)
  442. && ((PACKET_remaining(pkt) == 64
  443. && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
  444. || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
  445. || (PACKET_remaining(pkt) == 128
  446. && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
  447. len = PACKET_remaining(pkt);
  448. } else
  449. #endif
  450. if (!PACKET_get_net_2(pkt, &len)) {
  451. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  452. goto err;
  453. }
  454. if (!PACKET_get_bytes(pkt, &data, len)) {
  455. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  456. goto err;
  457. }
  458. if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
  459. /* SSLfatal() already called */
  460. goto err;
  461. }
  462. OSSL_TRACE1(TLS, "Using client verify alg %s\n",
  463. md == NULL ? "n/a" : EVP_MD_get0_name(md));
  464. if (EVP_DigestVerifyInit_ex(mctx, &pctx,
  465. md == NULL ? NULL : EVP_MD_get0_name(md),
  466. sctx->libctx, sctx->propq, pkey,
  467. NULL) <= 0) {
  468. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  469. goto err;
  470. }
  471. #ifndef OPENSSL_NO_GOST
  472. {
  473. int pktype = EVP_PKEY_get_id(pkey);
  474. if (pktype == NID_id_GostR3410_2001
  475. || pktype == NID_id_GostR3410_2012_256
  476. || pktype == NID_id_GostR3410_2012_512) {
  477. if ((gost_data = OPENSSL_malloc(len)) == NULL)
  478. goto err;
  479. BUF_reverse(gost_data, data, len);
  480. data = gost_data;
  481. }
  482. }
  483. #endif
  484. if (SSL_USE_PSS(s)) {
  485. if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
  486. || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
  487. RSA_PSS_SALTLEN_DIGEST) <= 0) {
  488. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  489. goto err;
  490. }
  491. }
  492. if (s->version == SSL3_VERSION) {
  493. if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
  494. || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
  495. (int)s->session->master_key_length,
  496. s->session->master_key) <= 0) {
  497. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
  498. goto err;
  499. }
  500. if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
  501. SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
  502. goto err;
  503. }
  504. } else {
  505. j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
  506. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  507. /* Ignore bad signatures when fuzzing */
  508. if (SSL_IS_QUIC_HANDSHAKE(s))
  509. j = 1;
  510. #endif
  511. if (j <= 0) {
  512. SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
  513. goto err;
  514. }
  515. }
  516. /*
  517. * In TLSv1.3 on the client side we make sure we prepare the client
  518. * certificate after the CertVerify instead of when we get the
  519. * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
  520. * comes *before* the Certificate message. In TLSv1.2 it comes after. We
  521. * want to make sure that SSL_get1_peer_certificate() will return the actual
  522. * server certificate from the client_cert_cb callback.
  523. */
  524. if (!s->server && SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
  525. ret = MSG_PROCESS_CONTINUE_PROCESSING;
  526. else
  527. ret = MSG_PROCESS_CONTINUE_READING;
  528. err:
  529. BIO_free(s->s3.handshake_buffer);
  530. s->s3.handshake_buffer = NULL;
  531. EVP_MD_CTX_free(mctx);
  532. #ifndef OPENSSL_NO_GOST
  533. OPENSSL_free(gost_data);
  534. #endif
  535. return ret;
  536. }
  537. CON_FUNC_RETURN tls_construct_finished(SSL_CONNECTION *s, WPACKET *pkt)
  538. {
  539. size_t finish_md_len;
  540. const char *sender;
  541. size_t slen;
  542. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  543. /* This is a real handshake so make sure we clean it up at the end */
  544. if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
  545. s->statem.cleanuphand = 1;
  546. /*
  547. * If we attempted to write early data or we're in middlebox compat mode
  548. * then we deferred changing the handshake write keys to the last possible
  549. * moment. If we didn't already do this when we sent the client certificate
  550. * then we need to do it now.
  551. */
  552. if (SSL_CONNECTION_IS_TLS13(s)
  553. && !s->server
  554. && (s->early_data_state != SSL_EARLY_DATA_NONE
  555. || (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
  556. && s->s3.tmp.cert_req == 0
  557. && (!ssl->method->ssl3_enc->change_cipher_state(s,
  558. SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
  559. /* SSLfatal() already called */
  560. return CON_FUNC_ERROR;
  561. }
  562. if (s->server) {
  563. sender = ssl->method->ssl3_enc->server_finished_label;
  564. slen = ssl->method->ssl3_enc->server_finished_label_len;
  565. } else {
  566. sender = ssl->method->ssl3_enc->client_finished_label;
  567. slen = ssl->method->ssl3_enc->client_finished_label_len;
  568. }
  569. finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s,
  570. sender, slen,
  571. s->s3.tmp.finish_md);
  572. if (finish_md_len == 0) {
  573. /* SSLfatal() already called */
  574. return CON_FUNC_ERROR;
  575. }
  576. s->s3.tmp.finish_md_len = finish_md_len;
  577. if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
  578. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  579. return CON_FUNC_ERROR;
  580. }
  581. /*
  582. * Log the master secret, if logging is enabled. We don't log it for
  583. * TLSv1.3: there's a different key schedule for that.
  584. */
  585. if (!SSL_CONNECTION_IS_TLS13(s)
  586. && !ssl_log_secret(s, MASTER_SECRET_LABEL, s->session->master_key,
  587. s->session->master_key_length)) {
  588. /* SSLfatal() already called */
  589. return CON_FUNC_ERROR;
  590. }
  591. /*
  592. * Copy the finished so we can use it for renegotiation checks
  593. */
  594. if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
  595. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  596. return CON_FUNC_ERROR;
  597. }
  598. if (!s->server) {
  599. memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
  600. finish_md_len);
  601. s->s3.previous_client_finished_len = finish_md_len;
  602. } else {
  603. memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
  604. finish_md_len);
  605. s->s3.previous_server_finished_len = finish_md_len;
  606. }
  607. return CON_FUNC_SUCCESS;
  608. }
  609. CON_FUNC_RETURN tls_construct_key_update(SSL_CONNECTION *s, WPACKET *pkt)
  610. {
  611. if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
  612. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  613. return CON_FUNC_ERROR;
  614. }
  615. s->key_update = SSL_KEY_UPDATE_NONE;
  616. return CON_FUNC_SUCCESS;
  617. }
  618. MSG_PROCESS_RETURN tls_process_key_update(SSL_CONNECTION *s, PACKET *pkt)
  619. {
  620. unsigned int updatetype;
  621. /*
  622. * A KeyUpdate message signals a key change so the end of the message must
  623. * be on a record boundary.
  624. */
  625. if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
  626. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
  627. return MSG_PROCESS_ERROR;
  628. }
  629. if (!PACKET_get_1(pkt, &updatetype)
  630. || PACKET_remaining(pkt) != 0) {
  631. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
  632. return MSG_PROCESS_ERROR;
  633. }
  634. /*
  635. * There are only two defined key update types. Fail if we get a value we
  636. * didn't recognise.
  637. */
  638. if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
  639. && updatetype != SSL_KEY_UPDATE_REQUESTED) {
  640. SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
  641. return MSG_PROCESS_ERROR;
  642. }
  643. /*
  644. * If we get a request for us to update our sending keys too then, we need
  645. * to additionally send a KeyUpdate message. However that message should
  646. * not also request an update (otherwise we get into an infinite loop).
  647. */
  648. if (updatetype == SSL_KEY_UPDATE_REQUESTED)
  649. s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
  650. if (!tls13_update_key(s, 0)) {
  651. /* SSLfatal() already called */
  652. return MSG_PROCESS_ERROR;
  653. }
  654. return MSG_PROCESS_FINISHED_READING;
  655. }
  656. /*
  657. * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
  658. * to far.
  659. */
  660. int ssl3_take_mac(SSL_CONNECTION *s)
  661. {
  662. const char *sender;
  663. size_t slen;
  664. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  665. if (!s->server) {
  666. sender = ssl->method->ssl3_enc->server_finished_label;
  667. slen = ssl->method->ssl3_enc->server_finished_label_len;
  668. } else {
  669. sender = ssl->method->ssl3_enc->client_finished_label;
  670. slen = ssl->method->ssl3_enc->client_finished_label_len;
  671. }
  672. s->s3.tmp.peer_finish_md_len =
  673. ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
  674. s->s3.tmp.peer_finish_md);
  675. if (s->s3.tmp.peer_finish_md_len == 0) {
  676. /* SSLfatal() already called */
  677. return 0;
  678. }
  679. return 1;
  680. }
  681. MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
  682. PACKET *pkt)
  683. {
  684. size_t remain;
  685. remain = PACKET_remaining(pkt);
  686. /*
  687. * 'Change Cipher Spec' is just a single byte, which should already have
  688. * been consumed by ssl_get_message() so there should be no bytes left,
  689. * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
  690. */
  691. if (SSL_CONNECTION_IS_DTLS(s)) {
  692. if ((s->version == DTLS1_BAD_VER
  693. && remain != DTLS1_CCS_HEADER_LENGTH + 1)
  694. || (s->version != DTLS1_BAD_VER
  695. && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
  696. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  697. return MSG_PROCESS_ERROR;
  698. }
  699. } else {
  700. if (remain != 0) {
  701. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  702. return MSG_PROCESS_ERROR;
  703. }
  704. }
  705. /* Check we have a cipher to change to */
  706. if (s->s3.tmp.new_cipher == NULL) {
  707. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
  708. return MSG_PROCESS_ERROR;
  709. }
  710. s->s3.change_cipher_spec = 1;
  711. if (!ssl3_do_change_cipher_spec(s)) {
  712. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  713. return MSG_PROCESS_ERROR;
  714. }
  715. if (SSL_CONNECTION_IS_DTLS(s)) {
  716. if (s->version == DTLS1_BAD_VER)
  717. s->d1->handshake_read_seq++;
  718. #ifndef OPENSSL_NO_SCTP
  719. /*
  720. * Remember that a CCS has been received, so that an old key of
  721. * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
  722. * SCTP is used
  723. */
  724. BIO_ctrl(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)),
  725. BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
  726. #endif
  727. }
  728. return MSG_PROCESS_CONTINUE_READING;
  729. }
  730. MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
  731. {
  732. size_t md_len;
  733. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  734. int was_first = SSL_IS_FIRST_HANDSHAKE(s);
  735. int ok;
  736. /* This is a real handshake so make sure we clean it up at the end */
  737. if (s->server) {
  738. /*
  739. * To get this far we must have read encrypted data from the client. We
  740. * no longer tolerate unencrypted alerts. This is ignored if less than
  741. * TLSv1.3
  742. */
  743. if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
  744. s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
  745. if (s->post_handshake_auth != SSL_PHA_REQUESTED)
  746. s->statem.cleanuphand = 1;
  747. if (SSL_CONNECTION_IS_TLS13(s)
  748. && !tls13_save_handshake_digest_for_pha(s)) {
  749. /* SSLfatal() already called */
  750. return MSG_PROCESS_ERROR;
  751. }
  752. }
  753. /*
  754. * In TLSv1.3 a Finished message signals a key change so the end of the
  755. * message must be on a record boundary.
  756. */
  757. if (SSL_CONNECTION_IS_TLS13(s)
  758. && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
  759. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
  760. return MSG_PROCESS_ERROR;
  761. }
  762. /* If this occurs, we have missed a message */
  763. if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
  764. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
  765. return MSG_PROCESS_ERROR;
  766. }
  767. s->s3.change_cipher_spec = 0;
  768. md_len = s->s3.tmp.peer_finish_md_len;
  769. if (md_len != PACKET_remaining(pkt)) {
  770. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
  771. return MSG_PROCESS_ERROR;
  772. }
  773. ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
  774. md_len);
  775. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  776. if (ok != 0) {
  777. if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
  778. ok = 0;
  779. }
  780. }
  781. #endif
  782. if (ok != 0) {
  783. SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
  784. return MSG_PROCESS_ERROR;
  785. }
  786. /*
  787. * Copy the finished so we can use it for renegotiation checks
  788. */
  789. if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
  790. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  791. return MSG_PROCESS_ERROR;
  792. }
  793. if (s->server) {
  794. memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
  795. md_len);
  796. s->s3.previous_client_finished_len = md_len;
  797. } else {
  798. memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
  799. md_len);
  800. s->s3.previous_server_finished_len = md_len;
  801. }
  802. /*
  803. * In TLS1.3 we also have to change cipher state and do any final processing
  804. * of the initial server flight (if we are a client)
  805. */
  806. if (SSL_CONNECTION_IS_TLS13(s)) {
  807. if (s->server) {
  808. if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
  809. !ssl->method->ssl3_enc->change_cipher_state(s,
  810. SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
  811. /* SSLfatal() already called */
  812. return MSG_PROCESS_ERROR;
  813. }
  814. } else {
  815. /* TLS 1.3 gets the secret size from the handshake md */
  816. size_t dummy;
  817. if (!ssl->method->ssl3_enc->generate_master_secret(s,
  818. s->master_secret, s->handshake_secret, 0,
  819. &dummy)) {
  820. /* SSLfatal() already called */
  821. return MSG_PROCESS_ERROR;
  822. }
  823. if (!ssl->method->ssl3_enc->change_cipher_state(s,
  824. SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
  825. /* SSLfatal() already called */
  826. return MSG_PROCESS_ERROR;
  827. }
  828. if (!tls_process_initial_server_flight(s)) {
  829. /* SSLfatal() already called */
  830. return MSG_PROCESS_ERROR;
  831. }
  832. }
  833. }
  834. if (was_first
  835. && !SSL_IS_FIRST_HANDSHAKE(s)
  836. && s->rlayer.rrlmethod->set_first_handshake != NULL)
  837. s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
  838. return MSG_PROCESS_FINISHED_READING;
  839. }
  840. CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
  841. {
  842. if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
  843. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  844. return CON_FUNC_ERROR;
  845. }
  846. return CON_FUNC_SUCCESS;
  847. }
  848. /* Add a certificate to the WPACKET */
  849. static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
  850. X509 *x, int chain, int for_comp)
  851. {
  852. int len;
  853. unsigned char *outbytes;
  854. int context = SSL_EXT_TLS1_3_CERTIFICATE;
  855. if (for_comp)
  856. context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
  857. len = i2d_X509(x, NULL);
  858. if (len < 0) {
  859. if (!for_comp)
  860. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
  861. return 0;
  862. }
  863. if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
  864. || i2d_X509(x, &outbytes) != len) {
  865. if (!for_comp)
  866. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  867. return 0;
  868. }
  869. if ((SSL_CONNECTION_IS_TLS13(s) || for_comp)
  870. && !tls_construct_extensions(s, pkt, context, x, chain)) {
  871. /* SSLfatal() already called */
  872. return 0;
  873. }
  874. return 1;
  875. }
  876. /* Add certificate chain to provided WPACKET */
  877. static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
  878. {
  879. int i, chain_count;
  880. X509 *x;
  881. STACK_OF(X509) *extra_certs;
  882. STACK_OF(X509) *chain = NULL;
  883. X509_STORE *chain_store;
  884. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  885. if (cpk == NULL || cpk->x509 == NULL)
  886. return 1;
  887. x = cpk->x509;
  888. /*
  889. * If we have a certificate specific chain use it, else use parent ctx.
  890. */
  891. if (cpk->chain != NULL)
  892. extra_certs = cpk->chain;
  893. else
  894. extra_certs = sctx->extra_certs;
  895. if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
  896. chain_store = NULL;
  897. else if (s->cert->chain_store)
  898. chain_store = s->cert->chain_store;
  899. else
  900. chain_store = sctx->cert_store;
  901. if (chain_store != NULL) {
  902. X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
  903. sctx->propq);
  904. if (xs_ctx == NULL) {
  905. if (!for_comp)
  906. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
  907. return 0;
  908. }
  909. if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
  910. X509_STORE_CTX_free(xs_ctx);
  911. if (!for_comp)
  912. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
  913. return 0;
  914. }
  915. /*
  916. * It is valid for the chain not to be complete (because normally we
  917. * don't include the root cert in the chain). Therefore we deliberately
  918. * ignore the error return from this call. We're not actually verifying
  919. * the cert - we're just building as much of the chain as we can
  920. */
  921. (void)X509_verify_cert(xs_ctx);
  922. /* Don't leave errors in the queue */
  923. ERR_clear_error();
  924. chain = X509_STORE_CTX_get0_chain(xs_ctx);
  925. i = ssl_security_cert_chain(s, chain, NULL, 0);
  926. if (i != 1) {
  927. #if 0
  928. /* Dummy error calls so mkerr generates them */
  929. ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
  930. ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
  931. ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
  932. #endif
  933. X509_STORE_CTX_free(xs_ctx);
  934. if (!for_comp)
  935. SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
  936. return 0;
  937. }
  938. chain_count = sk_X509_num(chain);
  939. for (i = 0; i < chain_count; i++) {
  940. x = sk_X509_value(chain, i);
  941. if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
  942. /* SSLfatal() already called */
  943. X509_STORE_CTX_free(xs_ctx);
  944. return 0;
  945. }
  946. }
  947. X509_STORE_CTX_free(xs_ctx);
  948. } else {
  949. i = ssl_security_cert_chain(s, extra_certs, x, 0);
  950. if (i != 1) {
  951. if (!for_comp)
  952. SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
  953. return 0;
  954. }
  955. if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
  956. /* SSLfatal() already called */
  957. return 0;
  958. }
  959. for (i = 0; i < sk_X509_num(extra_certs); i++) {
  960. x = sk_X509_value(extra_certs, i);
  961. if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
  962. /* SSLfatal() already called */
  963. return 0;
  964. }
  965. }
  966. }
  967. return 1;
  968. }
  969. EVP_PKEY* tls_get_peer_pkey(const SSL_CONNECTION *sc)
  970. {
  971. if (sc->session->peer_rpk != NULL)
  972. return sc->session->peer_rpk;
  973. if (sc->session->peer != NULL)
  974. return X509_get0_pubkey(sc->session->peer);
  975. return NULL;
  976. }
  977. int tls_process_rpk(SSL_CONNECTION *sc, PACKET *pkt, EVP_PKEY **peer_rpk)
  978. {
  979. EVP_PKEY *pkey = NULL;
  980. int ret = 0;
  981. RAW_EXTENSION *rawexts = NULL;
  982. PACKET extensions;
  983. PACKET context;
  984. unsigned long cert_len = 0, spki_len = 0;
  985. const unsigned char *spki, *spkistart;
  986. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
  987. /*-
  988. * ----------------------------
  989. * TLS 1.3 Certificate message:
  990. * ----------------------------
  991. * https://datatracker.ietf.org/doc/html/rfc8446#section-4.4.2
  992. *
  993. * enum {
  994. * X509(0),
  995. * RawPublicKey(2),
  996. * (255)
  997. * } CertificateType;
  998. *
  999. * struct {
  1000. * select (certificate_type) {
  1001. * case RawPublicKey:
  1002. * // From RFC 7250 ASN.1_subjectPublicKeyInfo
  1003. * opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
  1004. *
  1005. * case X509:
  1006. * opaque cert_data<1..2^24-1>;
  1007. * };
  1008. * Extension extensions<0..2^16-1>;
  1009. * } CertificateEntry;
  1010. *
  1011. * struct {
  1012. * opaque certificate_request_context<0..2^8-1>;
  1013. * CertificateEntry certificate_list<0..2^24-1>;
  1014. * } Certificate;
  1015. *
  1016. * The client MUST send a Certificate message if and only if the server
  1017. * has requested client authentication via a CertificateRequest message
  1018. * (Section 4.3.2). If the server requests client authentication but no
  1019. * suitable certificate is available, the client MUST send a Certificate
  1020. * message containing no certificates (i.e., with the "certificate_list"
  1021. * field having length 0).
  1022. *
  1023. * ----------------------------
  1024. * TLS 1.2 Certificate message:
  1025. * ----------------------------
  1026. * https://datatracker.ietf.org/doc/html/rfc7250#section-3
  1027. *
  1028. * opaque ASN.1Cert<1..2^24-1>;
  1029. *
  1030. * struct {
  1031. * select(certificate_type){
  1032. *
  1033. * // certificate type defined in this document.
  1034. * case RawPublicKey:
  1035. * opaque ASN.1_subjectPublicKeyInfo<1..2^24-1>;
  1036. *
  1037. * // X.509 certificate defined in RFC 5246
  1038. * case X.509:
  1039. * ASN.1Cert certificate_list<0..2^24-1>;
  1040. *
  1041. * // Additional certificate type based on
  1042. * // "TLS Certificate Types" subregistry
  1043. * };
  1044. * } Certificate;
  1045. *
  1046. * -------------
  1047. * Consequently:
  1048. * -------------
  1049. * After the (TLS 1.3 only) context octet string (1 byte length + data) the
  1050. * Certificate message has a 3-byte length that is zero in the client to
  1051. * server message when the client has no RPK to send. In that case, there
  1052. * are no (TLS 1.3 only) per-certificate extensions either, because the
  1053. * [CertificateEntry] list is empty.
  1054. *
  1055. * In the server to client direction, or when the client had an RPK to send,
  1056. * the TLS 1.3 message just prepends the length of the RPK+extensions,
  1057. * while TLS <= 1.2 sends just the RPK (octet-string).
  1058. *
  1059. * The context must be zero-length in the server to client direction, and
  1060. * must match the value recorded in the certificate request in the client
  1061. * to server direction.
  1062. */
  1063. if (SSL_CONNECTION_IS_TLS13(sc)) {
  1064. if (!PACKET_get_length_prefixed_1(pkt, &context)) {
  1065. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
  1066. goto err;
  1067. }
  1068. if (sc->server) {
  1069. if (sc->pha_context == NULL) {
  1070. if (PACKET_remaining(&context) != 0) {
  1071. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
  1072. goto err;
  1073. }
  1074. } else {
  1075. if (!PACKET_equal(&context, sc->pha_context, sc->pha_context_len)) {
  1076. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
  1077. goto err;
  1078. }
  1079. }
  1080. } else {
  1081. if (PACKET_remaining(&context) != 0) {
  1082. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
  1083. goto err;
  1084. }
  1085. }
  1086. }
  1087. if (!PACKET_get_net_3(pkt, &cert_len)
  1088. || PACKET_remaining(pkt) != cert_len) {
  1089. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  1090. goto err;
  1091. }
  1092. /*
  1093. * The list length may be zero when there is no RPK. In the case of TLS
  1094. * 1.2 this is actually the RPK length, which cannot be zero as specified,
  1095. * but that breaks the ability of the client to decline client auth. We
  1096. * overload the 0 RPK length to mean "no RPK". This interpretation is
  1097. * also used some other (reference?) implementations, but is not supported
  1098. * by the verbatim RFC7250 text.
  1099. */
  1100. if (cert_len == 0)
  1101. return 1;
  1102. if (SSL_CONNECTION_IS_TLS13(sc)) {
  1103. /*
  1104. * With TLS 1.3, a non-empty explicit-length RPK octet-string followed
  1105. * by a possibly empty extension block.
  1106. */
  1107. if (!PACKET_get_net_3(pkt, &spki_len)) {
  1108. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  1109. goto err;
  1110. }
  1111. if (spki_len == 0) {
  1112. /* empty RPK */
  1113. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_EMPTY_RAW_PUBLIC_KEY);
  1114. goto err;
  1115. }
  1116. } else {
  1117. spki_len = cert_len;
  1118. }
  1119. if (!PACKET_get_bytes(pkt, &spki, spki_len)) {
  1120. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  1121. goto err;
  1122. }
  1123. spkistart = spki;
  1124. if ((pkey = d2i_PUBKEY_ex(NULL, &spki, spki_len, sctx->libctx, sctx->propq)) == NULL
  1125. || spki != (spkistart + spki_len)) {
  1126. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  1127. goto err;
  1128. }
  1129. if (EVP_PKEY_missing_parameters(pkey)) {
  1130. SSLfatal(sc, SSL_AD_INTERNAL_ERROR,
  1131. SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
  1132. goto err;
  1133. }
  1134. /* Process the Extensions block */
  1135. if (SSL_CONNECTION_IS_TLS13(sc)) {
  1136. if (PACKET_remaining(pkt) != (cert_len - 3 - spki_len)) {
  1137. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
  1138. goto err;
  1139. }
  1140. if (!PACKET_as_length_prefixed_2(pkt, &extensions)
  1141. || PACKET_remaining(pkt) != 0) {
  1142. SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  1143. goto err;
  1144. }
  1145. if (!tls_collect_extensions(sc, &extensions, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
  1146. &rawexts, NULL, 1)) {
  1147. /* SSLfatal already called */
  1148. goto err;
  1149. }
  1150. /* chain index is always zero and fin always 1 for RPK */
  1151. if (!tls_parse_all_extensions(sc, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
  1152. rawexts, NULL, 0, 1)) {
  1153. /* SSLfatal already called */
  1154. goto err;
  1155. }
  1156. }
  1157. ret = 1;
  1158. if (peer_rpk != NULL) {
  1159. *peer_rpk = pkey;
  1160. pkey = NULL;
  1161. }
  1162. err:
  1163. OPENSSL_free(rawexts);
  1164. EVP_PKEY_free(pkey);
  1165. return ret;
  1166. }
  1167. unsigned long tls_output_rpk(SSL_CONNECTION *sc, WPACKET *pkt, CERT_PKEY *cpk)
  1168. {
  1169. int pdata_len = 0;
  1170. unsigned char *pdata = NULL;
  1171. X509_PUBKEY *xpk = NULL;
  1172. unsigned long ret = 0;
  1173. X509 *x509 = NULL;
  1174. if (cpk != NULL && cpk->x509 != NULL) {
  1175. x509 = cpk->x509;
  1176. /* Get the RPK from the certificate */
  1177. xpk = X509_get_X509_PUBKEY(cpk->x509);
  1178. if (xpk == NULL) {
  1179. SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1180. goto err;
  1181. }
  1182. pdata_len = i2d_X509_PUBKEY(xpk, &pdata);
  1183. } else if (cpk != NULL && cpk->privatekey != NULL) {
  1184. /* Get the RPK from the private key */
  1185. pdata_len = i2d_PUBKEY(cpk->privatekey, &pdata);
  1186. } else {
  1187. /* The server RPK is not optional */
  1188. if (sc->server) {
  1189. SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1190. goto err;
  1191. }
  1192. /* The client can send a zero length certificate list */
  1193. if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
  1194. SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1195. goto err;
  1196. }
  1197. return 1;
  1198. }
  1199. if (pdata_len <= 0) {
  1200. SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1201. goto err;
  1202. }
  1203. /*
  1204. * TLSv1.2 is _just_ the raw public key
  1205. * TLSv1.3 includes extensions, so there's a length wrapper
  1206. */
  1207. if (SSL_CONNECTION_IS_TLS13(sc)) {
  1208. if (!WPACKET_start_sub_packet_u24(pkt)) {
  1209. SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1210. goto err;
  1211. }
  1212. }
  1213. if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
  1214. SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1215. goto err;
  1216. }
  1217. if (SSL_CONNECTION_IS_TLS13(sc)) {
  1218. /*
  1219. * Only send extensions relevant to raw public keys. Until such
  1220. * extensions are defined, this will be an empty set of extensions.
  1221. * |x509| may be NULL, which raw public-key extensions need to handle.
  1222. */
  1223. if (!tls_construct_extensions(sc, pkt, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
  1224. x509, 0)) {
  1225. /* SSLfatal() already called */
  1226. goto err;
  1227. }
  1228. if (!WPACKET_close(pkt)) {
  1229. SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1230. goto err;
  1231. }
  1232. }
  1233. ret = 1;
  1234. err:
  1235. OPENSSL_free(pdata);
  1236. return ret;
  1237. }
  1238. unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
  1239. CERT_PKEY *cpk, int for_comp)
  1240. {
  1241. if (!WPACKET_start_sub_packet_u24(pkt)) {
  1242. if (!for_comp)
  1243. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1244. return 0;
  1245. }
  1246. if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
  1247. return 0;
  1248. if (!WPACKET_close(pkt)) {
  1249. if (!for_comp)
  1250. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1251. return 0;
  1252. }
  1253. return 1;
  1254. }
  1255. /*
  1256. * Tidy up after the end of a handshake. In the case of SCTP this may result
  1257. * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
  1258. * freed up as well.
  1259. */
  1260. WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
  1261. int clearbufs, int stop)
  1262. {
  1263. void (*cb) (const SSL *ssl, int type, int val) = NULL;
  1264. int cleanuphand = s->statem.cleanuphand;
  1265. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1266. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  1267. if (clearbufs) {
  1268. if (!SSL_CONNECTION_IS_DTLS(s)
  1269. #ifndef OPENSSL_NO_SCTP
  1270. /*
  1271. * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
  1272. * messages that require it. Therefore, DTLS procedures for retransmissions
  1273. * MUST NOT be used.
  1274. * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
  1275. */
  1276. || BIO_dgram_is_sctp(SSL_get_wbio(ssl))
  1277. #endif
  1278. ) {
  1279. /*
  1280. * We don't do this in DTLS over UDP because we may still need the init_buf
  1281. * in case there are any unexpected retransmits
  1282. */
  1283. BUF_MEM_free(s->init_buf);
  1284. s->init_buf = NULL;
  1285. }
  1286. if (!ssl_free_wbio_buffer(s)) {
  1287. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  1288. return WORK_ERROR;
  1289. }
  1290. s->init_num = 0;
  1291. }
  1292. if (SSL_CONNECTION_IS_TLS13(s) && !s->server
  1293. && s->post_handshake_auth == SSL_PHA_REQUESTED)
  1294. s->post_handshake_auth = SSL_PHA_EXT_SENT;
  1295. /*
  1296. * Only set if there was a Finished message and this isn't after a TLSv1.3
  1297. * post handshake exchange
  1298. */
  1299. if (cleanuphand) {
  1300. /* skipped if we just sent a HelloRequest */
  1301. s->renegotiate = 0;
  1302. s->new_session = 0;
  1303. s->statem.cleanuphand = 0;
  1304. s->ext.ticket_expected = 0;
  1305. ssl3_cleanup_key_block(s);
  1306. if (s->server) {
  1307. /*
  1308. * In TLSv1.3 we update the cache as part of constructing the
  1309. * NewSessionTicket
  1310. */
  1311. if (!SSL_CONNECTION_IS_TLS13(s))
  1312. ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
  1313. /* N.B. s->ctx may not equal s->session_ctx */
  1314. ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
  1315. s->handshake_func = ossl_statem_accept;
  1316. } else {
  1317. if (SSL_CONNECTION_IS_TLS13(s)) {
  1318. /*
  1319. * We encourage applications to only use TLSv1.3 tickets once,
  1320. * so we remove this one from the cache.
  1321. */
  1322. if ((s->session_ctx->session_cache_mode
  1323. & SSL_SESS_CACHE_CLIENT) != 0)
  1324. SSL_CTX_remove_session(s->session_ctx, s->session);
  1325. } else {
  1326. /*
  1327. * In TLSv1.3 we update the cache as part of processing the
  1328. * NewSessionTicket
  1329. */
  1330. ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
  1331. }
  1332. if (s->hit)
  1333. ssl_tsan_counter(s->session_ctx,
  1334. &s->session_ctx->stats.sess_hit);
  1335. s->handshake_func = ossl_statem_connect;
  1336. ssl_tsan_counter(s->session_ctx,
  1337. &s->session_ctx->stats.sess_connect_good);
  1338. }
  1339. if (SSL_CONNECTION_IS_DTLS(s)) {
  1340. /* done with handshaking */
  1341. s->d1->handshake_read_seq = 0;
  1342. s->d1->handshake_write_seq = 0;
  1343. s->d1->next_handshake_write_seq = 0;
  1344. dtls1_clear_received_buffer(s);
  1345. }
  1346. }
  1347. if (s->info_callback != NULL)
  1348. cb = s->info_callback;
  1349. else if (sctx->info_callback != NULL)
  1350. cb = sctx->info_callback;
  1351. /* The callback may expect us to not be in init at handshake done */
  1352. ossl_statem_set_in_init(s, 0);
  1353. if (cb != NULL) {
  1354. if (cleanuphand
  1355. || !SSL_CONNECTION_IS_TLS13(s)
  1356. || SSL_IS_FIRST_HANDSHAKE(s))
  1357. cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
  1358. }
  1359. if (!stop) {
  1360. /* If we've got more work to do we go back into init */
  1361. ossl_statem_set_in_init(s, 1);
  1362. return WORK_FINISHED_CONTINUE;
  1363. }
  1364. return WORK_FINISHED_STOP;
  1365. }
  1366. int tls_get_message_header(SSL_CONNECTION *s, int *mt)
  1367. {
  1368. /* s->init_num < SSL3_HM_HEADER_LENGTH */
  1369. int skip_message, i;
  1370. uint8_t recvd_type;
  1371. unsigned char *p;
  1372. size_t l, readbytes;
  1373. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1374. p = (unsigned char *)s->init_buf->data;
  1375. do {
  1376. while (s->init_num < SSL3_HM_HEADER_LENGTH) {
  1377. i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
  1378. &p[s->init_num],
  1379. SSL3_HM_HEADER_LENGTH - s->init_num,
  1380. 0, &readbytes);
  1381. if (i <= 0) {
  1382. s->rwstate = SSL_READING;
  1383. return 0;
  1384. }
  1385. if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1386. /*
  1387. * A ChangeCipherSpec must be a single byte and may not occur
  1388. * in the middle of a handshake message.
  1389. */
  1390. if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
  1391. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  1392. SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1393. return 0;
  1394. }
  1395. if (s->statem.hand_state == TLS_ST_BEFORE
  1396. && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
  1397. /*
  1398. * We are stateless and we received a CCS. Probably this is
  1399. * from a client between the first and second ClientHellos.
  1400. * We should ignore this, but return an error because we do
  1401. * not return success until we see the second ClientHello
  1402. * with a valid cookie.
  1403. */
  1404. return 0;
  1405. }
  1406. s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
  1407. s->init_num = readbytes - 1;
  1408. s->init_msg = s->init_buf->data;
  1409. s->s3.tmp.message_size = readbytes;
  1410. return 1;
  1411. } else if (recvd_type != SSL3_RT_HANDSHAKE) {
  1412. SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
  1413. SSL_R_CCS_RECEIVED_EARLY);
  1414. return 0;
  1415. }
  1416. s->init_num += readbytes;
  1417. }
  1418. skip_message = 0;
  1419. if (!s->server)
  1420. if (s->statem.hand_state != TLS_ST_OK
  1421. && p[0] == SSL3_MT_HELLO_REQUEST)
  1422. /*
  1423. * The server may always send 'Hello Request' messages --
  1424. * we are doing a handshake anyway now, so ignore them if
  1425. * their format is correct. Does not count for 'Finished'
  1426. * MAC.
  1427. */
  1428. if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
  1429. s->init_num = 0;
  1430. skip_message = 1;
  1431. if (s->msg_callback)
  1432. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  1433. p, SSL3_HM_HEADER_LENGTH, ssl,
  1434. s->msg_callback_arg);
  1435. }
  1436. } while (skip_message);
  1437. /* s->init_num == SSL3_HM_HEADER_LENGTH */
  1438. *mt = *p;
  1439. s->s3.tmp.message_type = *(p++);
  1440. if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
  1441. /*
  1442. * Only happens with SSLv3+ in an SSLv2 backward compatible
  1443. * ClientHello
  1444. *
  1445. * Total message size is the remaining record bytes to read
  1446. * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
  1447. */
  1448. l = s->rlayer.tlsrecs[0].length + SSL3_HM_HEADER_LENGTH;
  1449. s->s3.tmp.message_size = l;
  1450. s->init_msg = s->init_buf->data;
  1451. s->init_num = SSL3_HM_HEADER_LENGTH;
  1452. } else {
  1453. n2l3(p, l);
  1454. /* BUF_MEM_grow takes an 'int' parameter */
  1455. if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
  1456. SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
  1457. SSL_R_EXCESSIVE_MESSAGE_SIZE);
  1458. return 0;
  1459. }
  1460. s->s3.tmp.message_size = l;
  1461. s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
  1462. s->init_num = 0;
  1463. }
  1464. return 1;
  1465. }
  1466. int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
  1467. {
  1468. size_t n, readbytes;
  1469. unsigned char *p;
  1470. int i;
  1471. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1472. if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
  1473. /* We've already read everything in */
  1474. *len = (unsigned long)s->init_num;
  1475. return 1;
  1476. }
  1477. p = s->init_msg;
  1478. n = s->s3.tmp.message_size - s->init_num;
  1479. while (n > 0) {
  1480. i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
  1481. &p[s->init_num], n, 0, &readbytes);
  1482. if (i <= 0) {
  1483. s->rwstate = SSL_READING;
  1484. *len = 0;
  1485. return 0;
  1486. }
  1487. s->init_num += readbytes;
  1488. n -= readbytes;
  1489. }
  1490. /*
  1491. * If receiving Finished, record MAC of prior handshake messages for
  1492. * Finished verification.
  1493. */
  1494. if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
  1495. /* SSLfatal() already called */
  1496. *len = 0;
  1497. return 0;
  1498. }
  1499. /* Feed this message into MAC computation. */
  1500. if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
  1501. if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
  1502. s->init_num)) {
  1503. /* SSLfatal() already called */
  1504. *len = 0;
  1505. return 0;
  1506. }
  1507. if (s->msg_callback)
  1508. s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
  1509. (size_t)s->init_num, ssl, s->msg_callback_arg);
  1510. } else {
  1511. /*
  1512. * We defer feeding in the HRR until later. We'll do it as part of
  1513. * processing the message
  1514. * The TLsv1.3 handshake transcript stops at the ClientFinished
  1515. * message.
  1516. */
  1517. #define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
  1518. /* KeyUpdate and NewSessionTicket do not need to be added */
  1519. if (!SSL_CONNECTION_IS_TLS13(s)
  1520. || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
  1521. && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
  1522. if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
  1523. || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
  1524. || memcmp(hrrrandom,
  1525. s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
  1526. SSL3_RANDOM_SIZE) != 0) {
  1527. if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
  1528. s->init_num + SSL3_HM_HEADER_LENGTH)) {
  1529. /* SSLfatal() already called */
  1530. *len = 0;
  1531. return 0;
  1532. }
  1533. }
  1534. }
  1535. if (s->msg_callback)
  1536. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
  1537. (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ssl,
  1538. s->msg_callback_arg);
  1539. }
  1540. *len = s->init_num;
  1541. return 1;
  1542. }
  1543. static const X509ERR2ALERT x509table[] = {
  1544. {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
  1545. {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
  1546. {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
  1547. {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
  1548. {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
  1549. {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
  1550. {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
  1551. {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
  1552. {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
  1553. {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
  1554. {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
  1555. {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
  1556. {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
  1557. {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
  1558. {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
  1559. {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
  1560. {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
  1561. {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
  1562. {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
  1563. {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
  1564. {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
  1565. {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
  1566. {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
  1567. {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
  1568. {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
  1569. {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
  1570. {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
  1571. {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
  1572. {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
  1573. {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
  1574. {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
  1575. {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
  1576. {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
  1577. {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
  1578. {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
  1579. {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
  1580. {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
  1581. {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
  1582. {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
  1583. {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
  1584. /* Last entry; return this if we don't find the value above. */
  1585. {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
  1586. };
  1587. int ssl_x509err2alert(int x509err)
  1588. {
  1589. const X509ERR2ALERT *tp;
  1590. for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
  1591. if (tp->x509err == x509err)
  1592. break;
  1593. return tp->alert;
  1594. }
  1595. int ssl_allow_compression(SSL_CONNECTION *s)
  1596. {
  1597. if (s->options & SSL_OP_NO_COMPRESSION)
  1598. return 0;
  1599. return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
  1600. }
  1601. /*
  1602. * SSL/TLS/DTLS version comparison
  1603. *
  1604. * Returns
  1605. * 0 if versiona is equal to versionb
  1606. * 1 if versiona is greater than versionb
  1607. * -1 if versiona is less than versionb
  1608. */
  1609. int ssl_version_cmp(const SSL_CONNECTION *s, int versiona, int versionb)
  1610. {
  1611. int dtls = SSL_CONNECTION_IS_DTLS(s);
  1612. if (versiona == versionb)
  1613. return 0;
  1614. if (!dtls)
  1615. return versiona < versionb ? -1 : 1;
  1616. return DTLS_VERSION_LT(versiona, versionb) ? -1 : 1;
  1617. }
  1618. typedef struct {
  1619. int version;
  1620. const SSL_METHOD *(*cmeth) (void);
  1621. const SSL_METHOD *(*smeth) (void);
  1622. } version_info;
  1623. #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
  1624. # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
  1625. #endif
  1626. /* Must be in order high to low */
  1627. static const version_info tls_version_table[] = {
  1628. #ifndef OPENSSL_NO_TLS1_3
  1629. {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
  1630. #else
  1631. {TLS1_3_VERSION, NULL, NULL},
  1632. #endif
  1633. #ifndef OPENSSL_NO_TLS1_2
  1634. {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
  1635. #else
  1636. {TLS1_2_VERSION, NULL, NULL},
  1637. #endif
  1638. #ifndef OPENSSL_NO_TLS1_1
  1639. {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
  1640. #else
  1641. {TLS1_1_VERSION, NULL, NULL},
  1642. #endif
  1643. #ifndef OPENSSL_NO_TLS1
  1644. {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
  1645. #else
  1646. {TLS1_VERSION, NULL, NULL},
  1647. #endif
  1648. #ifndef OPENSSL_NO_SSL3
  1649. {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
  1650. #else
  1651. {SSL3_VERSION, NULL, NULL},
  1652. #endif
  1653. {0, NULL, NULL},
  1654. };
  1655. #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
  1656. # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
  1657. #endif
  1658. /* Must be in order high to low */
  1659. static const version_info dtls_version_table[] = {
  1660. #ifndef OPENSSL_NO_DTLS1_2
  1661. {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
  1662. #else
  1663. {DTLS1_2_VERSION, NULL, NULL},
  1664. #endif
  1665. #ifndef OPENSSL_NO_DTLS1
  1666. {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
  1667. {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
  1668. #else
  1669. {DTLS1_VERSION, NULL, NULL},
  1670. {DTLS1_BAD_VER, NULL, NULL},
  1671. #endif
  1672. {0, NULL, NULL},
  1673. };
  1674. /*
  1675. * ssl_method_error - Check whether an SSL_METHOD is enabled.
  1676. *
  1677. * @s: The SSL handle for the candidate method
  1678. * @method: the intended method.
  1679. *
  1680. * Returns 0 on success, or an SSL error reason on failure.
  1681. */
  1682. static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
  1683. {
  1684. int version = method->version;
  1685. if ((s->min_proto_version != 0 &&
  1686. ssl_version_cmp(s, version, s->min_proto_version) < 0) ||
  1687. ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
  1688. return SSL_R_VERSION_TOO_LOW;
  1689. if (s->max_proto_version != 0 &&
  1690. ssl_version_cmp(s, version, s->max_proto_version) > 0)
  1691. return SSL_R_VERSION_TOO_HIGH;
  1692. if ((s->options & method->mask) != 0)
  1693. return SSL_R_UNSUPPORTED_PROTOCOL;
  1694. if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
  1695. return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
  1696. return 0;
  1697. }
  1698. /*
  1699. * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
  1700. * certificate type, or has PSK or a certificate callback configured, or has
  1701. * a servername callback configure. Otherwise returns 0.
  1702. */
  1703. static int is_tls13_capable(const SSL_CONNECTION *s)
  1704. {
  1705. size_t i;
  1706. int curve;
  1707. SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
  1708. if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
  1709. return 0;
  1710. /*
  1711. * A servername callback can change the available certs, so if a servername
  1712. * cb is set then we just assume TLSv1.3 will be ok
  1713. */
  1714. if (sctx->ext.servername_cb != NULL
  1715. || s->session_ctx->ext.servername_cb != NULL)
  1716. return 1;
  1717. #ifndef OPENSSL_NO_PSK
  1718. if (s->psk_server_callback != NULL)
  1719. return 1;
  1720. #endif
  1721. if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
  1722. return 1;
  1723. /* All provider-based sig algs are required to support at least TLS1.3 */
  1724. for (i = 0; i < s->ssl_pkey_num; i++) {
  1725. /* Skip over certs disallowed for TLSv1.3 */
  1726. switch (i) {
  1727. case SSL_PKEY_DSA_SIGN:
  1728. case SSL_PKEY_GOST01:
  1729. case SSL_PKEY_GOST12_256:
  1730. case SSL_PKEY_GOST12_512:
  1731. continue;
  1732. default:
  1733. break;
  1734. }
  1735. if (!ssl_has_cert(s, i))
  1736. continue;
  1737. if (i != SSL_PKEY_ECC)
  1738. return 1;
  1739. /*
  1740. * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
  1741. * more restrictive so check that our sig algs are consistent with this
  1742. * EC cert. See section 4.2.3 of RFC8446.
  1743. */
  1744. curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
  1745. if (tls_check_sigalg_curve(s, curve))
  1746. return 1;
  1747. }
  1748. return 0;
  1749. }
  1750. /*
  1751. * ssl_version_supported - Check that the specified `version` is supported by
  1752. * `SSL *` instance
  1753. *
  1754. * @s: The SSL handle for the candidate method
  1755. * @version: Protocol version to test against
  1756. *
  1757. * Returns 1 when supported, otherwise 0
  1758. */
  1759. int ssl_version_supported(const SSL_CONNECTION *s, int version,
  1760. const SSL_METHOD **meth)
  1761. {
  1762. const version_info *vent;
  1763. const version_info *table;
  1764. switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
  1765. default:
  1766. /* Version should match method version for non-ANY method */
  1767. return ssl_version_cmp(s, version, s->version) == 0;
  1768. case TLS_ANY_VERSION:
  1769. table = tls_version_table;
  1770. break;
  1771. case DTLS_ANY_VERSION:
  1772. table = dtls_version_table;
  1773. break;
  1774. }
  1775. for (vent = table;
  1776. vent->version != 0 && ssl_version_cmp(s, version, vent->version) <= 0;
  1777. ++vent) {
  1778. const SSL_METHOD *(*thismeth)(void) = s->server ? vent->smeth
  1779. : vent->cmeth;
  1780. if (thismeth != NULL
  1781. && ssl_version_cmp(s, version, vent->version) == 0
  1782. && ssl_method_error(s, thismeth()) == 0
  1783. && (!s->server
  1784. || version != TLS1_3_VERSION
  1785. || is_tls13_capable(s))) {
  1786. if (meth != NULL)
  1787. *meth = thismeth();
  1788. return 1;
  1789. }
  1790. }
  1791. return 0;
  1792. }
  1793. /*
  1794. * ssl_check_version_downgrade - In response to RFC7507 SCSV version
  1795. * fallback indication from a client check whether we're using the highest
  1796. * supported protocol version.
  1797. *
  1798. * @s server SSL handle.
  1799. *
  1800. * Returns 1 when using the highest enabled version, 0 otherwise.
  1801. */
  1802. int ssl_check_version_downgrade(SSL_CONNECTION *s)
  1803. {
  1804. const version_info *vent;
  1805. const version_info *table;
  1806. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1807. /*
  1808. * Check that the current protocol is the highest enabled version
  1809. * (according to ssl->defltmethod, as version negotiation may have changed
  1810. * s->method).
  1811. */
  1812. if (s->version == ssl->defltmeth->version)
  1813. return 1;
  1814. /*
  1815. * Apparently we're using a version-flexible SSL_METHOD (not at its
  1816. * highest protocol version).
  1817. */
  1818. if (ssl->defltmeth->version == TLS_method()->version)
  1819. table = tls_version_table;
  1820. else if (ssl->defltmeth->version == DTLS_method()->version)
  1821. table = dtls_version_table;
  1822. else {
  1823. /* Unexpected state; fail closed. */
  1824. return 0;
  1825. }
  1826. for (vent = table; vent->version != 0; ++vent) {
  1827. if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
  1828. return s->version == vent->version;
  1829. }
  1830. return 0;
  1831. }
  1832. /*
  1833. * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
  1834. * protocols, provided the initial (D)TLS method is version-flexible. This
  1835. * function sanity-checks the proposed value and makes sure the method is
  1836. * version-flexible, then sets the limit if all is well.
  1837. *
  1838. * @method_version: The version of the current SSL_METHOD.
  1839. * @version: the intended limit.
  1840. * @bound: pointer to limit to be updated.
  1841. *
  1842. * Returns 1 on success, 0 on failure.
  1843. */
  1844. int ssl_set_version_bound(int method_version, int version, int *bound)
  1845. {
  1846. int valid_tls;
  1847. int valid_dtls;
  1848. if (version == 0) {
  1849. *bound = version;
  1850. return 1;
  1851. }
  1852. valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
  1853. valid_dtls =
  1854. /* We support client side pre-standardisation version of DTLS */
  1855. (version == DTLS1_BAD_VER)
  1856. || (DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL)
  1857. && DTLS_VERSION_GE(version, DTLS1_VERSION));
  1858. if (!valid_tls && !valid_dtls)
  1859. return 0;
  1860. /*-
  1861. * Restrict TLS methods to TLS protocol versions.
  1862. * Restrict DTLS methods to DTLS protocol versions.
  1863. * Note, DTLS version numbers are decreasing, use comparison macros.
  1864. *
  1865. * Note that for both lower-bounds we use explicit versions, not
  1866. * (D)TLS_MIN_VERSION. This is because we don't want to break user
  1867. * configurations. If the MIN (supported) version ever rises, the user's
  1868. * "floor" remains valid even if no longer available. We don't expect the
  1869. * MAX ceiling to ever get lower, so making that variable makes sense.
  1870. *
  1871. * We ignore attempts to set bounds on version-inflexible methods,
  1872. * returning success.
  1873. */
  1874. switch (method_version) {
  1875. default:
  1876. break;
  1877. case TLS_ANY_VERSION:
  1878. if (valid_tls)
  1879. *bound = version;
  1880. break;
  1881. case DTLS_ANY_VERSION:
  1882. if (valid_dtls)
  1883. *bound = version;
  1884. break;
  1885. }
  1886. return 1;
  1887. }
  1888. static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
  1889. {
  1890. if (vers == TLS1_2_VERSION
  1891. && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
  1892. *dgrd = DOWNGRADE_TO_1_2;
  1893. } else if (!SSL_CONNECTION_IS_DTLS(s)
  1894. && vers < TLS1_2_VERSION
  1895. /*
  1896. * We need to ensure that a server that disables TLSv1.2
  1897. * (creating a hole between TLSv1.3 and TLSv1.1) can still
  1898. * complete handshakes with clients that support TLSv1.2 and
  1899. * below. Therefore we do not enable the sentinel if TLSv1.3 is
  1900. * enabled and TLSv1.2 is not.
  1901. */
  1902. && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
  1903. *dgrd = DOWNGRADE_TO_1_1;
  1904. } else {
  1905. *dgrd = DOWNGRADE_NONE;
  1906. }
  1907. }
  1908. /*
  1909. * ssl_choose_server_version - Choose server (D)TLS version. Called when the
  1910. * client HELLO is received to select the final server protocol version and
  1911. * the version specific method.
  1912. *
  1913. * @s: server SSL handle.
  1914. *
  1915. * Returns 0 on success or an SSL error reason number on failure.
  1916. */
  1917. int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
  1918. DOWNGRADE *dgrd)
  1919. {
  1920. /*-
  1921. * With version-flexible methods we have an initial state with:
  1922. *
  1923. * s->method->version == (D)TLS_ANY_VERSION,
  1924. * s->version == (D)TLS_MAX_VERSION_INTERNAL.
  1925. *
  1926. * So we detect version-flexible methods via the method version, not the
  1927. * handle version.
  1928. */
  1929. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  1930. int server_version = ssl->method->version;
  1931. int client_version = hello->legacy_version;
  1932. const version_info *vent;
  1933. const version_info *table;
  1934. int disabled = 0;
  1935. RAW_EXTENSION *suppversions;
  1936. s->client_version = client_version;
  1937. switch (server_version) {
  1938. default:
  1939. if (!SSL_CONNECTION_IS_TLS13(s)) {
  1940. if (ssl_version_cmp(s, client_version, s->version) < 0)
  1941. return SSL_R_WRONG_SSL_VERSION;
  1942. *dgrd = DOWNGRADE_NONE;
  1943. /*
  1944. * If this SSL handle is not from a version flexible method we don't
  1945. * (and never did) check min/max FIPS or Suite B constraints. Hope
  1946. * that's OK. It is up to the caller to not choose fixed protocol
  1947. * versions they don't want. If not, then easy to fix, just return
  1948. * ssl_method_error(s, s->method)
  1949. */
  1950. return 0;
  1951. }
  1952. /*
  1953. * Fall through if we are TLSv1.3 already (this means we must be after
  1954. * a HelloRetryRequest
  1955. */
  1956. /* fall thru */
  1957. case TLS_ANY_VERSION:
  1958. table = tls_version_table;
  1959. break;
  1960. case DTLS_ANY_VERSION:
  1961. table = dtls_version_table;
  1962. break;
  1963. }
  1964. suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
  1965. /* If we did an HRR then supported versions is mandatory */
  1966. if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
  1967. return SSL_R_UNSUPPORTED_PROTOCOL;
  1968. if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
  1969. unsigned int candidate_vers = 0;
  1970. unsigned int best_vers = 0;
  1971. const SSL_METHOD *best_method = NULL;
  1972. PACKET versionslist;
  1973. suppversions->parsed = 1;
  1974. if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
  1975. /* Trailing or invalid data? */
  1976. return SSL_R_LENGTH_MISMATCH;
  1977. }
  1978. /*
  1979. * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
  1980. * The spec only requires servers to check that it isn't SSLv3:
  1981. * "Any endpoint receiving a Hello message with
  1982. * ClientHello.legacy_version or ServerHello.legacy_version set to
  1983. * 0x0300 MUST abort the handshake with a "protocol_version" alert."
  1984. * We are slightly stricter and require that it isn't SSLv3 or lower.
  1985. * We tolerate TLSv1 and TLSv1.1.
  1986. */
  1987. if (client_version <= SSL3_VERSION)
  1988. return SSL_R_BAD_LEGACY_VERSION;
  1989. while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
  1990. if (ssl_version_cmp(s, candidate_vers, best_vers) <= 0)
  1991. continue;
  1992. if (ssl_version_supported(s, candidate_vers, &best_method))
  1993. best_vers = candidate_vers;
  1994. }
  1995. if (PACKET_remaining(&versionslist) != 0) {
  1996. /* Trailing data? */
  1997. return SSL_R_LENGTH_MISMATCH;
  1998. }
  1999. if (best_vers > 0) {
  2000. if (s->hello_retry_request != SSL_HRR_NONE) {
  2001. /*
  2002. * This is after a HelloRetryRequest so we better check that we
  2003. * negotiated TLSv1.3
  2004. */
  2005. if (best_vers != TLS1_3_VERSION)
  2006. return SSL_R_UNSUPPORTED_PROTOCOL;
  2007. return 0;
  2008. }
  2009. check_for_downgrade(s, best_vers, dgrd);
  2010. s->version = best_vers;
  2011. ssl->method = best_method;
  2012. if (!ssl_set_record_protocol_version(s, best_vers))
  2013. return ERR_R_INTERNAL_ERROR;
  2014. return 0;
  2015. }
  2016. return SSL_R_UNSUPPORTED_PROTOCOL;
  2017. }
  2018. /*
  2019. * If the supported versions extension isn't present, then the highest
  2020. * version we can negotiate is TLSv1.2
  2021. */
  2022. if (ssl_version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
  2023. client_version = TLS1_2_VERSION;
  2024. /*
  2025. * No supported versions extension, so we just use the version supplied in
  2026. * the ClientHello.
  2027. */
  2028. for (vent = table; vent->version != 0; ++vent) {
  2029. const SSL_METHOD *method;
  2030. if (vent->smeth == NULL ||
  2031. ssl_version_cmp(s, client_version, vent->version) < 0)
  2032. continue;
  2033. method = vent->smeth();
  2034. if (ssl_method_error(s, method) == 0) {
  2035. check_for_downgrade(s, vent->version, dgrd);
  2036. s->version = vent->version;
  2037. ssl->method = method;
  2038. if (!ssl_set_record_protocol_version(s, s->version))
  2039. return ERR_R_INTERNAL_ERROR;
  2040. return 0;
  2041. }
  2042. disabled = 1;
  2043. }
  2044. return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
  2045. }
  2046. /*
  2047. * ssl_choose_client_version - Choose client (D)TLS version. Called when the
  2048. * server HELLO is received to select the final client protocol version and
  2049. * the version specific method.
  2050. *
  2051. * @s: client SSL handle.
  2052. * @version: The proposed version from the server's HELLO.
  2053. * @extensions: The extensions received
  2054. *
  2055. * Returns 1 on success or 0 on error.
  2056. */
  2057. int ssl_choose_client_version(SSL_CONNECTION *s, int version,
  2058. RAW_EXTENSION *extensions)
  2059. {
  2060. const version_info *vent;
  2061. const version_info *table;
  2062. int ret, ver_min, ver_max, real_max, origv;
  2063. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  2064. origv = s->version;
  2065. s->version = version;
  2066. /* This will overwrite s->version if the extension is present */
  2067. if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
  2068. SSL_EXT_TLS1_2_SERVER_HELLO
  2069. | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
  2070. NULL, 0)) {
  2071. s->version = origv;
  2072. return 0;
  2073. }
  2074. if (s->hello_retry_request != SSL_HRR_NONE
  2075. && s->version != TLS1_3_VERSION) {
  2076. s->version = origv;
  2077. SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
  2078. return 0;
  2079. }
  2080. switch (ssl->method->version) {
  2081. default:
  2082. if (s->version != ssl->method->version) {
  2083. s->version = origv;
  2084. SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
  2085. return 0;
  2086. }
  2087. /*
  2088. * If this SSL handle is not from a version flexible method we don't
  2089. * (and never did) check min/max, FIPS or Suite B constraints. Hope
  2090. * that's OK. It is up to the caller to not choose fixed protocol
  2091. * versions they don't want. If not, then easy to fix, just return
  2092. * ssl_method_error(s, s->method)
  2093. */
  2094. if (!ssl_set_record_protocol_version(s, s->version)) {
  2095. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2096. return 0;
  2097. }
  2098. return 1;
  2099. case TLS_ANY_VERSION:
  2100. table = tls_version_table;
  2101. break;
  2102. case DTLS_ANY_VERSION:
  2103. table = dtls_version_table;
  2104. break;
  2105. }
  2106. ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
  2107. if (ret != 0) {
  2108. s->version = origv;
  2109. SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
  2110. return 0;
  2111. }
  2112. if (ssl_version_cmp(s, s->version, ver_min) < 0
  2113. || ssl_version_cmp(s, s->version, ver_max) > 0) {
  2114. s->version = origv;
  2115. SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
  2116. return 0;
  2117. }
  2118. if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
  2119. real_max = ver_max;
  2120. /* Check for downgrades */
  2121. if (s->version == TLS1_2_VERSION && real_max > s->version) {
  2122. if (memcmp(tls12downgrade,
  2123. s->s3.server_random + SSL3_RANDOM_SIZE
  2124. - sizeof(tls12downgrade),
  2125. sizeof(tls12downgrade)) == 0) {
  2126. s->version = origv;
  2127. SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
  2128. SSL_R_INAPPROPRIATE_FALLBACK);
  2129. return 0;
  2130. }
  2131. } else if (!SSL_CONNECTION_IS_DTLS(s)
  2132. && s->version < TLS1_2_VERSION
  2133. && real_max > s->version) {
  2134. if (memcmp(tls11downgrade,
  2135. s->s3.server_random + SSL3_RANDOM_SIZE
  2136. - sizeof(tls11downgrade),
  2137. sizeof(tls11downgrade)) == 0) {
  2138. s->version = origv;
  2139. SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
  2140. SSL_R_INAPPROPRIATE_FALLBACK);
  2141. return 0;
  2142. }
  2143. }
  2144. for (vent = table; vent->version != 0; ++vent) {
  2145. if (vent->cmeth == NULL || s->version != vent->version)
  2146. continue;
  2147. ssl->method = vent->cmeth();
  2148. if (!ssl_set_record_protocol_version(s, s->version)) {
  2149. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2150. return 0;
  2151. }
  2152. return 1;
  2153. }
  2154. s->version = origv;
  2155. SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
  2156. return 0;
  2157. }
  2158. /*
  2159. * ssl_get_min_max_version - get minimum and maximum protocol version
  2160. * @s: The SSL connection
  2161. * @min_version: The minimum supported version
  2162. * @max_version: The maximum supported version
  2163. * @real_max: The highest version below the lowest compile time version hole
  2164. * where that hole lies above at least one run-time enabled
  2165. * protocol.
  2166. *
  2167. * Work out what version we should be using for the initial ClientHello if the
  2168. * version is initially (D)TLS_ANY_VERSION. We apply any explicit SSL_OP_NO_xxx
  2169. * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
  2170. * constraints and any floor imposed by the security level here,
  2171. * so we don't advertise the wrong protocol version to only reject the outcome later.
  2172. *
  2173. * Computing the right floor matters. If, e.g., TLS 1.0 and 1.2 are enabled,
  2174. * TLS 1.1 is disabled, but the security level, Suite-B and/or MinProtocol
  2175. * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
  2176. *
  2177. * Returns 0 on success or an SSL error reason number on failure. On failure
  2178. * min_version and max_version will also be set to 0.
  2179. */
  2180. int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
  2181. int *max_version, int *real_max)
  2182. {
  2183. int version, tmp_real_max;
  2184. int hole;
  2185. const SSL_METHOD *method;
  2186. const version_info *table;
  2187. const version_info *vent;
  2188. const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  2189. switch (ssl->method->version) {
  2190. default:
  2191. /*
  2192. * If this SSL handle is not from a version flexible method we don't
  2193. * (and never did) check min/max FIPS or Suite B constraints. Hope
  2194. * that's OK. It is up to the caller to not choose fixed protocol
  2195. * versions they don't want. If not, then easy to fix, just return
  2196. * ssl_method_error(s, s->method)
  2197. */
  2198. *min_version = *max_version = s->version;
  2199. /*
  2200. * Providing a real_max only makes sense where we're using a version
  2201. * flexible method.
  2202. */
  2203. if (!ossl_assert(real_max == NULL))
  2204. return ERR_R_INTERNAL_ERROR;
  2205. return 0;
  2206. case TLS_ANY_VERSION:
  2207. table = tls_version_table;
  2208. break;
  2209. case DTLS_ANY_VERSION:
  2210. table = dtls_version_table;
  2211. break;
  2212. }
  2213. /*
  2214. * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
  2215. * below X enabled. This is required in order to maintain the "version
  2216. * capability" vector contiguous. Any versions with a NULL client method
  2217. * (protocol version client is disabled at compile-time) is also a "hole".
  2218. *
  2219. * Our initial state is hole == 1, version == 0. That is, versions above
  2220. * the first version in the method table are disabled (a "hole" above
  2221. * the valid protocol entries) and we don't have a selected version yet.
  2222. *
  2223. * Whenever "hole == 1", and we hit an enabled method, its version becomes
  2224. * the selected version. We're no longer in a hole, so "hole" becomes 0.
  2225. *
  2226. * If "hole == 0" and we hit an enabled method, we support a contiguous
  2227. * range of at least two methods. If we hit a disabled method,
  2228. * then hole becomes true again, but nothing else changes yet,
  2229. * because all the remaining methods may be disabled too.
  2230. * If we again hit an enabled method after the new hole, it becomes
  2231. * selected, as we start from scratch.
  2232. */
  2233. *min_version = version = 0;
  2234. hole = 1;
  2235. if (real_max != NULL)
  2236. *real_max = 0;
  2237. tmp_real_max = 0;
  2238. for (vent = table; vent->version != 0; ++vent) {
  2239. /*
  2240. * A table entry with a NULL client method is still a hole in the
  2241. * "version capability" vector.
  2242. */
  2243. if (vent->cmeth == NULL) {
  2244. hole = 1;
  2245. tmp_real_max = 0;
  2246. continue;
  2247. }
  2248. method = vent->cmeth();
  2249. if (hole == 1 && tmp_real_max == 0)
  2250. tmp_real_max = vent->version;
  2251. if (ssl_method_error(s, method) != 0) {
  2252. hole = 1;
  2253. } else if (!hole) {
  2254. *min_version = method->version;
  2255. } else {
  2256. if (real_max != NULL && tmp_real_max != 0)
  2257. *real_max = tmp_real_max;
  2258. version = method->version;
  2259. *min_version = version;
  2260. hole = 0;
  2261. }
  2262. }
  2263. *max_version = version;
  2264. /* Fail if everything is disabled */
  2265. if (version == 0)
  2266. return SSL_R_NO_PROTOCOLS_AVAILABLE;
  2267. return 0;
  2268. }
  2269. /*
  2270. * ssl_set_client_hello_version - Work out what version we should be using for
  2271. * the initial ClientHello.legacy_version field.
  2272. *
  2273. * @s: client SSL handle.
  2274. *
  2275. * Returns 0 on success or an SSL error reason number on failure.
  2276. */
  2277. int ssl_set_client_hello_version(SSL_CONNECTION *s)
  2278. {
  2279. int ver_min, ver_max, ret;
  2280. /*
  2281. * In a renegotiation we always send the same client_version that we sent
  2282. * last time, regardless of which version we eventually negotiated.
  2283. */
  2284. if (!SSL_IS_FIRST_HANDSHAKE(s))
  2285. return 0;
  2286. ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
  2287. if (ret != 0)
  2288. return ret;
  2289. s->version = ver_max;
  2290. if (SSL_CONNECTION_IS_DTLS(s)) {
  2291. if (ver_max == DTLS1_BAD_VER) {
  2292. /*
  2293. * Even though this is technically before version negotiation,
  2294. * because we have asked for DTLS1_BAD_VER we will never negotiate
  2295. * anything else, and this has impacts on the record layer for when
  2296. * we read the ServerHello. So we need to tell the record layer
  2297. * about this immediately.
  2298. */
  2299. if (!ssl_set_record_protocol_version(s, ver_max))
  2300. return 0;
  2301. }
  2302. } else if (ver_max > TLS1_2_VERSION) {
  2303. /* TLS1.3 always uses TLS1.2 in the legacy_version field */
  2304. ver_max = TLS1_2_VERSION;
  2305. }
  2306. s->client_version = ver_max;
  2307. return 0;
  2308. }
  2309. /*
  2310. * Checks a list of |groups| to determine if the |group_id| is in it. If it is
  2311. * and |checkallow| is 1 then additionally check if the group is allowed to be
  2312. * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
  2313. * 1) or 0 otherwise.
  2314. */
  2315. int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
  2316. size_t num_groups, int checkallow)
  2317. {
  2318. size_t i;
  2319. if (groups == NULL || num_groups == 0)
  2320. return 0;
  2321. for (i = 0; i < num_groups; i++) {
  2322. uint16_t group = groups[i];
  2323. if (group_id == group
  2324. && (!checkallow
  2325. || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
  2326. return 1;
  2327. }
  2328. }
  2329. return 0;
  2330. }
  2331. /* Replace ClientHello1 in the transcript hash with a synthetic message */
  2332. int create_synthetic_message_hash(SSL_CONNECTION *s,
  2333. const unsigned char *hashval,
  2334. size_t hashlen, const unsigned char *hrr,
  2335. size_t hrrlen)
  2336. {
  2337. unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
  2338. unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
  2339. memset(msghdr, 0, sizeof(msghdr));
  2340. if (hashval == NULL) {
  2341. hashval = hashvaltmp;
  2342. hashlen = 0;
  2343. /* Get the hash of the initial ClientHello */
  2344. if (!ssl3_digest_cached_records(s, 0)
  2345. || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
  2346. &hashlen)) {
  2347. /* SSLfatal() already called */
  2348. return 0;
  2349. }
  2350. }
  2351. /* Reinitialise the transcript hash */
  2352. if (!ssl3_init_finished_mac(s)) {
  2353. /* SSLfatal() already called */
  2354. return 0;
  2355. }
  2356. /* Inject the synthetic message_hash message */
  2357. msghdr[0] = SSL3_MT_MESSAGE_HASH;
  2358. msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
  2359. if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
  2360. || !ssl3_finish_mac(s, hashval, hashlen)) {
  2361. /* SSLfatal() already called */
  2362. return 0;
  2363. }
  2364. /*
  2365. * Now re-inject the HRR and current message if appropriate (we just deleted
  2366. * it when we reinitialised the transcript hash above). Only necessary after
  2367. * receiving a ClientHello2 with a cookie.
  2368. */
  2369. if (hrr != NULL
  2370. && (!ssl3_finish_mac(s, hrr, hrrlen)
  2371. || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
  2372. s->s3.tmp.message_size
  2373. + SSL3_HM_HEADER_LENGTH))) {
  2374. /* SSLfatal() already called */
  2375. return 0;
  2376. }
  2377. return 1;
  2378. }
  2379. static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
  2380. {
  2381. return X509_NAME_cmp(*a, *b);
  2382. }
  2383. int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
  2384. {
  2385. STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
  2386. X509_NAME *xn = NULL;
  2387. PACKET cadns;
  2388. if (ca_sk == NULL) {
  2389. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
  2390. goto err;
  2391. }
  2392. /* get the CA RDNs */
  2393. if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
  2394. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  2395. goto err;
  2396. }
  2397. while (PACKET_remaining(&cadns)) {
  2398. const unsigned char *namestart, *namebytes;
  2399. unsigned int name_len;
  2400. if (!PACKET_get_net_2(&cadns, &name_len)
  2401. || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
  2402. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
  2403. goto err;
  2404. }
  2405. namestart = namebytes;
  2406. if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
  2407. SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
  2408. goto err;
  2409. }
  2410. if (namebytes != (namestart + name_len)) {
  2411. SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
  2412. goto err;
  2413. }
  2414. if (!sk_X509_NAME_push(ca_sk, xn)) {
  2415. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
  2416. goto err;
  2417. }
  2418. xn = NULL;
  2419. }
  2420. sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
  2421. s->s3.tmp.peer_ca_names = ca_sk;
  2422. return 1;
  2423. err:
  2424. sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
  2425. X509_NAME_free(xn);
  2426. return 0;
  2427. }
  2428. const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
  2429. {
  2430. const STACK_OF(X509_NAME) *ca_sk = NULL;
  2431. SSL *ssl = SSL_CONNECTION_GET_SSL(s);
  2432. if (s->server) {
  2433. ca_sk = SSL_get_client_CA_list(ssl);
  2434. if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
  2435. ca_sk = NULL;
  2436. }
  2437. if (ca_sk == NULL)
  2438. ca_sk = SSL_get0_CA_list(ssl);
  2439. return ca_sk;
  2440. }
  2441. int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
  2442. WPACKET *pkt)
  2443. {
  2444. /* Start sub-packet for client CA list */
  2445. if (!WPACKET_start_sub_packet_u16(pkt)) {
  2446. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2447. return 0;
  2448. }
  2449. if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
  2450. int i;
  2451. for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
  2452. unsigned char *namebytes;
  2453. X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
  2454. int namelen;
  2455. if (name == NULL
  2456. || (namelen = i2d_X509_NAME(name, NULL)) < 0
  2457. || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
  2458. &namebytes)
  2459. || i2d_X509_NAME(name, &namebytes) != namelen) {
  2460. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2461. return 0;
  2462. }
  2463. }
  2464. }
  2465. if (!WPACKET_close(pkt)) {
  2466. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2467. return 0;
  2468. }
  2469. return 1;
  2470. }
  2471. /* Create a buffer containing data to be signed for server key exchange */
  2472. size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
  2473. const void *param, size_t paramlen)
  2474. {
  2475. size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
  2476. unsigned char *tbs = OPENSSL_malloc(tbslen);
  2477. if (tbs == NULL) {
  2478. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
  2479. return 0;
  2480. }
  2481. memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
  2482. memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
  2483. memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
  2484. *ptbs = tbs;
  2485. return tbslen;
  2486. }
  2487. /*
  2488. * Saves the current handshake digest for Post-Handshake Auth,
  2489. * Done after ClientFinished is processed, done exactly once
  2490. */
  2491. int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
  2492. {
  2493. if (s->pha_dgst == NULL) {
  2494. if (!ssl3_digest_cached_records(s, 1))
  2495. /* SSLfatal() already called */
  2496. return 0;
  2497. s->pha_dgst = EVP_MD_CTX_new();
  2498. if (s->pha_dgst == NULL) {
  2499. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2500. return 0;
  2501. }
  2502. if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
  2503. s->s3.handshake_dgst)) {
  2504. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2505. EVP_MD_CTX_free(s->pha_dgst);
  2506. s->pha_dgst = NULL;
  2507. return 0;
  2508. }
  2509. }
  2510. return 1;
  2511. }
  2512. /*
  2513. * Restores the Post-Handshake Auth handshake digest
  2514. * Done just before sending/processing the Cert Request
  2515. */
  2516. int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
  2517. {
  2518. if (s->pha_dgst == NULL) {
  2519. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2520. return 0;
  2521. }
  2522. if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
  2523. s->pha_dgst)) {
  2524. SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2525. return 0;
  2526. }
  2527. return 1;
  2528. }
  2529. #ifndef OPENSSL_NO_COMP_ALG
  2530. MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
  2531. PACKET *pkt,
  2532. PACKET *tmppkt,
  2533. BUF_MEM *buf)
  2534. {
  2535. MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
  2536. int comp_alg;
  2537. COMP_METHOD *method = NULL;
  2538. COMP_CTX *comp = NULL;
  2539. size_t expected_length;
  2540. size_t comp_length;
  2541. int i;
  2542. int found = 0;
  2543. if (buf == NULL) {
  2544. SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
  2545. goto err;
  2546. }
  2547. if (!PACKET_get_net_2(pkt, (unsigned int*)&comp_alg)) {
  2548. SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
  2549. goto err;
  2550. }
  2551. /* If we have a prefs list, make sure the algorithm is in it */
  2552. if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
  2553. for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
  2554. if (sc->cert_comp_prefs[i] == comp_alg) {
  2555. found = 1;
  2556. break;
  2557. }
  2558. }
  2559. if (!found) {
  2560. SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
  2561. goto err;
  2562. }
  2563. }
  2564. if (!ossl_comp_has_alg(comp_alg)) {
  2565. SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
  2566. goto err;
  2567. }
  2568. switch (comp_alg) {
  2569. case TLSEXT_comp_cert_zlib:
  2570. method = COMP_zlib_oneshot();
  2571. break;
  2572. case TLSEXT_comp_cert_brotli:
  2573. method = COMP_brotli_oneshot();
  2574. break;
  2575. case TLSEXT_comp_cert_zstd:
  2576. method = COMP_zstd_oneshot();
  2577. break;
  2578. default:
  2579. SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
  2580. goto err;
  2581. }
  2582. if ((comp = COMP_CTX_new(method)) == NULL
  2583. || !PACKET_get_net_3_len(pkt, &expected_length)
  2584. || !PACKET_get_net_3_len(pkt, &comp_length)
  2585. || PACKET_remaining(pkt) != comp_length
  2586. || !BUF_MEM_grow(buf, expected_length)
  2587. || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
  2588. || COMP_expand_block(comp, (unsigned char *)buf->data, expected_length,
  2589. (unsigned char*)PACKET_data(pkt), comp_length) != (int)expected_length) {
  2590. SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
  2591. goto err;
  2592. }
  2593. ret = MSG_PROCESS_CONTINUE_PROCESSING;
  2594. err:
  2595. COMP_CTX_free(comp);
  2596. return ret;
  2597. }
  2598. #endif