statem_lib.c 96 KB

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