statem_lib.c 96 KB

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