2
0

statem_lib.c 84 KB

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