Debian Codegraph @

debian/rust-vendor/openssl-src/openssl/ssl/statem/statem_srvr.c

raw
1 /*
2 * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4 * Copyright 2005 Nokia. All rights reserved.
5 *
6 * Licensed under the Apache License 2.0 (the "License"). You may not use
7 * this file except in compliance with the License. You can obtain a copy
8 * in the file LICENSE in the source distribution or at
9 * https://www.openssl.org/source/license.html
10 */
11
12 #include "internal/e_os.h"
13
14 #include <stdio.h>
15 #include "../ssl_local.h"
16 #include "statem_local.h"
17 #include "internal/constant_time.h"
18 #include "internal/cryptlib.h"
19 #include "internal/ssl_unwrap.h"
20 #include "internal/sizes.h"
21 #include <openssl/buffer.h>
22 #include <openssl/rand.h>
23 #include <openssl/objects.h>
24 #include <openssl/evp.h>
25 #include <openssl/x509.h>
26 #include <openssl/dh.h>
27 #include <openssl/rsa.h>
28 #include <openssl/bn.h>
29 #include <openssl/md5.h>
30 #include <openssl/trace.h>
31 #include <openssl/core_names.h>
32 #include <openssl/asn1t.h>
33 #include <openssl/comp.h>
34 #include "internal/comp.h"
35 #include <openssl/ocsp.h>
36
37 #define TICKET_NONCE_SIZE 8
38
39 typedef struct {
40 ASN1_TYPE *kxBlob;
41 ASN1_TYPE *opaqueBlob;
42 } GOST_KX_MESSAGE;
43
44 DECLARE_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
45
46 ASN1_SEQUENCE(GOST_KX_MESSAGE) = {
47 ASN1_SIMPLE(GOST_KX_MESSAGE, kxBlob, ASN1_ANY),
48 ASN1_OPT(GOST_KX_MESSAGE, opaqueBlob, ASN1_ANY),
49 } ASN1_SEQUENCE_END(GOST_KX_MESSAGE)
50
51 IMPLEMENT_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
52
53 static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,
54 WPACKET *pkt);
55
56 static ossl_inline int received_client_cert(const SSL_CONNECTION *sc)
57 {
58 return sc->session->peer_rpk != NULL || sc->session->peer != NULL;
59 }
60
61 /*
62 * ossl_statem_server13_read_transition() encapsulates the logic for the allowed
63 * handshake state transitions when a TLSv1.3 server is reading messages from
64 * the client. The message type that the client has sent is provided in |mt|.
65 * The current state is in |s->statem.hand_state|.
66 *
67 * Return values are 1 for success (transition allowed) and 0 on error
68 * (transition not allowed)
69 */
70 static int ossl_statem_server13_read_transition(SSL_CONNECTION *s, int mt)
71 {
72 OSSL_STATEM *st = &s->statem;
73
74 /*
75 * Note: There is no case for TLS_ST_BEFORE because at that stage we have
76 * not negotiated TLSv1.3 yet, so that case is handled by
77 * ossl_statem_server_read_transition()
78 */
79 switch (st->hand_state) {
80 default:
81 break;
82
83 case TLS_ST_EARLY_DATA:
84 if (s->hello_retry_request == SSL_HRR_PENDING) {
85 if (mt == SSL3_MT_CLIENT_HELLO) {
86 st->hand_state = TLS_ST_SR_CLNT_HELLO;
87 return 1;
88 }
89 break;
90 } else if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED
91 && !SSL_NO_EOED(s)) {
92 if (mt == SSL3_MT_END_OF_EARLY_DATA) {
93 st->hand_state = TLS_ST_SR_END_OF_EARLY_DATA;
94 return 1;
95 }
96 break;
97 }
98 /* Fall through */
99
100 case TLS_ST_SR_END_OF_EARLY_DATA:
101 case TLS_ST_SW_FINISHED:
102 if (s->s3.tmp.cert_request) {
103 if (mt == SSL3_MT_CERTIFICATE) {
104 st->hand_state = TLS_ST_SR_CERT;
105 return 1;
106 }
107 #ifndef OPENSSL_NO_COMP_ALG
108 if (mt == SSL3_MT_COMPRESSED_CERTIFICATE
109 && s->ext.compress_certificate_sent) {
110 st->hand_state = TLS_ST_SR_COMP_CERT;
111 return 1;
112 }
113 #endif
114 } else {
115 if (mt == SSL3_MT_FINISHED) {
116 st->hand_state = TLS_ST_SR_FINISHED;
117 return 1;
118 }
119 }
120 break;
121
122 case TLS_ST_SR_COMP_CERT:
123 case TLS_ST_SR_CERT:
124 if (!received_client_cert(s)) {
125 if (mt == SSL3_MT_FINISHED) {
126 st->hand_state = TLS_ST_SR_FINISHED;
127 return 1;
128 }
129 } else {
130 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
131 st->hand_state = TLS_ST_SR_CERT_VRFY;
132 return 1;
133 }
134 }
135 break;
136
137 case TLS_ST_SR_CERT_VRFY:
138 if (mt == SSL3_MT_FINISHED) {
139 st->hand_state = TLS_ST_SR_FINISHED;
140 return 1;
141 }
142 break;
143
144 case TLS_ST_OK:
145 /*
146 * Its never ok to start processing handshake messages in the middle of
147 * early data (i.e. before we've received the end of early data alert)
148 */
149 if (s->early_data_state == SSL_EARLY_DATA_READING)
150 break;
151
152 if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
153 if (mt == SSL3_MT_CERTIFICATE) {
154 st->hand_state = TLS_ST_SR_CERT;
155 return 1;
156 }
157 #ifndef OPENSSL_NO_COMP_ALG
158 if (mt == SSL3_MT_COMPRESSED_CERTIFICATE
159 && s->ext.compress_certificate_sent) {
160 st->hand_state = TLS_ST_SR_COMP_CERT;
161 return 1;
162 }
163 #endif
164 }
165
166 if (mt == SSL3_MT_KEY_UPDATE && !SSL_IS_QUIC_HANDSHAKE(s)) {
167 st->hand_state = TLS_ST_SR_KEY_UPDATE;
168 return 1;
169 }
170 break;
171 }
172
173 /* No valid transition found */
174 return 0;
175 }
176
177 /*
178 * ossl_statem_server_read_transition() encapsulates the logic for the allowed
179 * handshake state transitions when the server is reading messages from the
180 * client. The message type that the client has sent is provided in |mt|. The
181 * current state is in |s->statem.hand_state|.
182 *
183 * Return values are 1 for success (transition allowed) and 0 on error
184 * (transition not allowed)
185 */
186 int ossl_statem_server_read_transition(SSL_CONNECTION *s, int mt)
187 {
188 OSSL_STATEM *st = &s->statem;
189
190 if (SSL_CONNECTION_IS_TLS13(s)) {
191 if (!ossl_statem_server13_read_transition(s, mt))
192 goto err;
193 return 1;
194 }
195
196 switch (st->hand_state) {
197 default:
198 break;
199
200 case TLS_ST_BEFORE:
201 case TLS_ST_OK:
202 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
203 if (mt == SSL3_MT_CLIENT_HELLO) {
204 st->hand_state = TLS_ST_SR_CLNT_HELLO;
205 return 1;
206 }
207 break;
208
209 case TLS_ST_SW_SRVR_DONE:
210 /*
211 * If we get a CKE message after a ServerDone then either
212 * 1) We didn't request a Certificate
213 * OR
214 * 2) If we did request one then
215 * a) We allow no Certificate to be returned
216 * AND
217 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
218 * list if we requested a certificate)
219 */
220 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
221 if (s->s3.tmp.cert_request) {
222 if (s->version == SSL3_VERSION) {
223 if ((s->verify_mode & SSL_VERIFY_PEER)
224 && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
225 /*
226 * This isn't an unexpected message as such - we're just
227 * not going to accept it because we require a client
228 * cert.
229 */
230 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
231 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
232 return 0;
233 }
234 st->hand_state = TLS_ST_SR_KEY_EXCH;
235 return 1;
236 }
237 } else {
238 st->hand_state = TLS_ST_SR_KEY_EXCH;
239 return 1;
240 }
241 } else if (s->s3.tmp.cert_request) {
242 if (mt == SSL3_MT_CERTIFICATE) {
243 st->hand_state = TLS_ST_SR_CERT;
244 return 1;
245 }
246 }
247 break;
248
249 case TLS_ST_SR_CERT:
250 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
251 st->hand_state = TLS_ST_SR_KEY_EXCH;
252 return 1;
253 }
254 break;
255
256 case TLS_ST_SR_KEY_EXCH:
257 /*
258 * We should only process a CertificateVerify message if we have
259 * received a Certificate from the client. If so then |s->session->peer|
260 * will be non NULL. In some instances a CertificateVerify message is
261 * not required even if the peer has sent a Certificate (e.g. such as in
262 * the case of static DH). In that case |st->no_cert_verify| should be
263 * set.
264 */
265 if (!received_client_cert(s) || st->no_cert_verify) {
266 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
267 /*
268 * For the ECDH ciphersuites when the client sends its ECDH
269 * pub key in a certificate, the CertificateVerify message is
270 * not sent. Also for GOST ciphersuites when the client uses
271 * its key from the certificate for key exchange.
272 */
273 st->hand_state = TLS_ST_SR_CHANGE;
274 return 1;
275 }
276 } else {
277 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
278 st->hand_state = TLS_ST_SR_CERT_VRFY;
279 return 1;
280 }
281 }
282 break;
283
284 case TLS_ST_SR_CERT_VRFY:
285 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
286 st->hand_state = TLS_ST_SR_CHANGE;
287 return 1;
288 }
289 break;
290
291 case TLS_ST_SR_CHANGE:
292 #ifndef OPENSSL_NO_NEXTPROTONEG
293 if (s->s3.npn_seen) {
294 if (mt == SSL3_MT_NEXT_PROTO) {
295 st->hand_state = TLS_ST_SR_NEXT_PROTO;
296 return 1;
297 }
298 } else {
299 #endif
300 if (mt == SSL3_MT_FINISHED) {
301 st->hand_state = TLS_ST_SR_FINISHED;
302 return 1;
303 }
304 #ifndef OPENSSL_NO_NEXTPROTONEG
305 }
306 #endif
307 break;
308
309 #ifndef OPENSSL_NO_NEXTPROTONEG
310 case TLS_ST_SR_NEXT_PROTO:
311 if (mt == SSL3_MT_FINISHED) {
312 st->hand_state = TLS_ST_SR_FINISHED;
313 return 1;
314 }
315 break;
316 #endif
317
318 case TLS_ST_SW_FINISHED:
319 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
320 st->hand_state = TLS_ST_SR_CHANGE;
321 return 1;
322 }
323 break;
324 }
325
326 err:
327 /* No valid transition found */
328 if (SSL_CONNECTION_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
329 BIO *rbio;
330
331 /*
332 * CCS messages don't have a message sequence number so this is probably
333 * because of an out-of-order CCS. We'll just drop it.
334 */
335 s->init_num = 0;
336 s->rwstate = SSL_READING;
337 rbio = SSL_get_rbio(SSL_CONNECTION_GET_SSL(s));
338 BIO_clear_retry_flags(rbio);
339 BIO_set_retry_read(rbio);
340 return 0;
341 }
342 SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
343 return 0;
344 }
345
346 /*
347 * Should we send a ServerKeyExchange message?
348 *
349 * Valid return values are:
350 * 1: Yes
351 * 0: No
352 */
353 static int send_server_key_exchange(SSL_CONNECTION *s)
354 {
355 unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
356
357 /*
358 * only send a ServerKeyExchange if DH or fortezza but we have a
359 * sign only certificate PSK: may send PSK identity hints For
360 * ECC ciphersuites, we send a serverKeyExchange message only if
361 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
362 * the server certificate contains the server's public key for
363 * key exchange.
364 */
365 if (alg_k & (SSL_kDHE | SSL_kECDHE)
366 /*
367 * PSK: send ServerKeyExchange if PSK identity hint if
368 * provided
369 */
370 #ifndef OPENSSL_NO_PSK
371 /* Only send SKE if we have identity hint for plain PSK */
372 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
373 && s->cert->psk_identity_hint)
374 /* For other PSK always send SKE */
375 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
376 #endif
377 #ifndef OPENSSL_NO_SRP
378 /* SRP: send ServerKeyExchange */
379 || (alg_k & SSL_kSRP)
380 #endif
381 ) {
382 return 1;
383 }
384
385 return 0;
386 }
387
388 /*
389 * Used to determine if we should send a CompressedCertificate message
390 *
391 * Returns the algorithm to use, TLSEXT_comp_cert_none means no compression
392 */
393 static int get_compressed_certificate_alg(SSL_CONNECTION *sc)
394 {
395 #ifndef OPENSSL_NO_COMP_ALG
396 int *alg = sc->ext.compress_certificate_from_peer;
397
398 if (sc->s3.tmp.cert == NULL)
399 return TLSEXT_comp_cert_none;
400
401 for (; *alg != TLSEXT_comp_cert_none; alg++) {
402 if (sc->s3.tmp.cert->comp_cert[*alg] != NULL)
403 return *alg;
404 }
405 #endif
406 return TLSEXT_comp_cert_none;
407 }
408
409 /*
410 * Should we send a CertificateRequest message?
411 *
412 * Valid return values are:
413 * 1: Yes
414 * 0: No
415 */
416 int send_certificate_request(SSL_CONNECTION *s)
417 {
418 if (
419 /* don't request cert unless asked for it: */
420 s->verify_mode & SSL_VERIFY_PEER
421 /*
422 * don't request if post-handshake-only unless doing
423 * post-handshake in TLSv1.3:
424 */
425 && (!SSL_CONNECTION_IS_TLS13(s)
426 || !(s->verify_mode & SSL_VERIFY_POST_HANDSHAKE)
427 || s->post_handshake_auth == SSL_PHA_REQUEST_PENDING)
428 /*
429 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
430 * a second time:
431 */
432 && (s->certreqs_sent < 1 || !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
433 /*
434 * never request cert in anonymous ciphersuites (see
435 * section "Certificate request" in SSL 3 drafts and in
436 * RFC 2246):
437 */
438 && (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL)
439 /*
440 * ... except when the application insists on
441 * verification (against the specs, but statem_clnt.c accepts
442 * this for SSL 3)
443 */
444 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
445 /* don't request certificate for SRP auth */
446 && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aSRP)
447 /*
448 * With normal PSK Certificates and Certificate Requests
449 * are omitted
450 */
451 && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
452 return 1;
453 }
454
455 return 0;
456 }
457
458 /*
459 * Get the OCSP response for the certificate from the chain identified
460 * chainidx.
461 * If no OCSP response could be found NULL is returned.
462 */
463 OCSP_RESPONSE *ossl_get_ocsp_response(SSL_CONNECTION *s, int chainidx)
464 {
465 OCSP_RESPONSE *resp = NULL;
466 #ifndef OPENSSL_NO_OCSP
467 int i = 0, num = 0;
468 unsigned int len;
469 X509 *x = NULL;
470 STACK_OF(X509) *chain_certs = NULL;
471 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
472 OCSP_BASICRESP *bs = NULL;
473 OCSP_SINGLERESP *sr = NULL;
474 OCSP_CERTID *cid = NULL;
475 OCSP_CERTID *sr_cert_id = NULL;
476 ASN1_OBJECT *cert_id_md_oid;
477 char cert_id_md_txt[OSSL_MAX_NAME_SIZE];
478 EVP_MD *cert_id_md;
479 ASN1_INTEGER *respSerial;
480 ASN1_OCTET_STRING *respIssuerNameHash = NULL;
481 ASN1_OCTET_STRING *certIssuerNameHash = NULL;
482 const X509_NAME *certIssuerName;
483 unsigned char md[EVP_MAX_MD_SIZE];
484 const ASN1_INTEGER *certSerial;
485 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
486
487 /*
488 * In TLSv1.3 the caller gives the index of the certificate for which the
489 * status message should be created.
490 * Prior to TLSv1.3 the chain index is 0 and the body should contain only
491 * the status of the server certificate itself.
492 */
493 SSL_get0_chain_certs(ssl, &chain_certs);
494
495 /*
496 * If the certificate chain was built, get the status message for the
497 * requested certificate specified by chainidx.
498 * SSL_get0_chain_certs provides certificate chain except the server cert.
499 *
500 * if chainidx = 0 the server certificate is requested
501 * if chainidx > 0 an intermediate certificate is requested
502 */
503 if (chainidx == 0)
504 x = SSL_get_certificate(ssl);
505 else
506 x = sk_X509_value(chain_certs, chainidx - 1);
507 if (x == NULL)
508 return NULL;
509
510 /* for a selfsigned certificate there will be no OCSP response */
511 if (X509_self_signed(x, 0))
512 return NULL;
513
514 if ((resp = sk_OCSP_RESPONSE_value(s->ext.ocsp.resp_ex, chainidx)) != NULL) {
515 /*
516 * Find the corresponding single OCSP response by comparing the current
517 * certificate's serial number, and the hash of the current certificate's
518 * issuer name, to the serial number and issuer name hash in each OCSP
519 * response received.
520 */
521 if (OCSP_response_status(resp) == OCSP_RESPONSE_STATUS_SUCCESSFUL) {
522 /*
523 * Set a mark for the error queue here to be able to ignore errors
524 * happening because of test cases.
525 */
526 ERR_set_mark();
527 bs = OCSP_response_get1_basic(resp);
528 if (bs != NULL && (sr = OCSP_resp_get0(bs, 0)) != NULL) {
529 /* use the first single response to get the algorithm used */
530 cid = (OCSP_CERTID *)OCSP_SINGLERESP_get0_id(sr);
531
532 /* determine the md algorithm which was used to create cert id */
533 OCSP_id_get0_info(&respIssuerNameHash, &cert_id_md_oid, NULL, &respSerial, cid);
534 if (cert_id_md_oid != NULL) {
535 OBJ_obj2txt(cert_id_md_txt, sizeof(cert_id_md_txt), cert_id_md_oid, 0);
536 cert_id_md = EVP_MD_fetch(sctx->libctx, cert_id_md_txt, sctx->propq);
537 } else {
538 cert_id_md = EVP_MD_fetch(sctx->libctx, SN_sha1, sctx->propq);
539 }
540
541 if (cert_id_md == NULL) {
542 OCSP_BASICRESP_free(bs);
543 ERR_clear_last_mark();
544 return NULL;
545 }
546
547 /* get serial number and issuer name hash of the certificate from the chain */
548 certSerial = X509_get0_serialNumber(x);
549 certIssuerName = X509_get_issuer_name(x);
550 certIssuerNameHash = ASN1_OCTET_STRING_new();
551 if (!X509_NAME_digest(certIssuerName, cert_id_md, md, &len) || !(ASN1_OCTET_STRING_set(certIssuerNameHash, md, len))) {
552 ASN1_OCTET_STRING_free(certIssuerNameHash);
553 OCSP_BASICRESP_free(bs);
554 EVP_MD_free(cert_id_md);
555 ERR_clear_last_mark();
556 return NULL;
557 }
558
559 num = OCSP_resp_count(bs);
560 for (i = 0; i < num; i++) {
561 sr = OCSP_resp_get0(bs, i);
562
563 /*
564 * get the CertID from the OCSP response to compare it with the information
565 * from the certificate
566 */
567 sr_cert_id = (OCSP_CERTID *)OCSP_SINGLERESP_get0_id(sr);
568
569 OCSP_id_get0_info(&respIssuerNameHash, NULL, NULL, &respSerial, sr_cert_id);
570
571 if (!ASN1_INTEGER_cmp(certSerial, respSerial) && !ASN1_OCTET_STRING_cmp(certIssuerNameHash, respIssuerNameHash))
572 break;
573 }
574
575 ASN1_OCTET_STRING_free(certIssuerNameHash);
576 OCSP_BASICRESP_free(bs);
577 EVP_MD_free(cert_id_md);
578
579 /*
580 * if we did not find the right single response we return NULL here
581 */
582 if (i == num)
583 resp = NULL;
584 } else {
585 OCSP_BASICRESP_free(bs);
586 }
587
588 /*
589 * in a test case a response without a basic response is used the error set
590 * could be ignored here
591 */
592 ERR_pop_to_mark();
593 }
594 }
595 #endif
596
597 return resp;
598 }
599
600 static int do_compressed_cert(SSL_CONNECTION *sc)
601 {
602 /* If we negotiated RPK, we won't attempt to compress it */
603 return sc->ext.server_cert_type == TLSEXT_cert_type_x509
604 && get_compressed_certificate_alg(sc) != TLSEXT_comp_cert_none;
605 }
606
607 /*
608 * ossl_statem_server13_write_transition() works out what handshake state to
609 * move to next when a TLSv1.3 server is writing messages to be sent to the
610 * client.
611 */
612 static WRITE_TRAN ossl_statem_server13_write_transition(SSL_CONNECTION *s)
613 {
614 OSSL_STATEM *st = &s->statem;
615
616 /*
617 * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
618 * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
619 */
620
621 switch (st->hand_state) {
622 default:
623 /* Shouldn't happen */
624 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
625 return WRITE_TRAN_ERROR;
626
627 case TLS_ST_OK:
628 if (s->key_update != SSL_KEY_UPDATE_NONE) {
629 st->hand_state = TLS_ST_SW_KEY_UPDATE;
630 return WRITE_TRAN_CONTINUE;
631 }
632 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
633 st->hand_state = TLS_ST_SW_CERT_REQ;
634 return WRITE_TRAN_CONTINUE;
635 }
636 if (s->ext.extra_tickets_expected > 0) {
637 st->hand_state = TLS_ST_SW_SESSION_TICKET;
638 return WRITE_TRAN_CONTINUE;
639 }
640 /* Try to read from the client instead */
641 return WRITE_TRAN_FINISHED;
642
643 case TLS_ST_SR_CLNT_HELLO:
644 st->hand_state = TLS_ST_SW_SRVR_HELLO;
645 return WRITE_TRAN_CONTINUE;
646
647 case TLS_ST_SW_SRVR_HELLO:
648 if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
649 && s->hello_retry_request != SSL_HRR_COMPLETE)
650 st->hand_state = TLS_ST_SW_CHANGE;
651 else if (s->hello_retry_request == SSL_HRR_PENDING)
652 st->hand_state = TLS_ST_EARLY_DATA;
653 else
654 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
655 return WRITE_TRAN_CONTINUE;
656
657 case TLS_ST_SW_CHANGE:
658 if (s->hello_retry_request == SSL_HRR_PENDING)
659 st->hand_state = TLS_ST_EARLY_DATA;
660 else
661 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
662 return WRITE_TRAN_CONTINUE;
663
664 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
665 if (s->hit)
666 st->hand_state = TLS_ST_SW_FINISHED;
667 else if (send_certificate_request(s))
668 st->hand_state = TLS_ST_SW_CERT_REQ;
669 else if (do_compressed_cert(s))
670 st->hand_state = TLS_ST_SW_COMP_CERT;
671 else
672 st->hand_state = TLS_ST_SW_CERT;
673
674 return WRITE_TRAN_CONTINUE;
675
676 case TLS_ST_SW_CERT_REQ:
677 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
678 s->post_handshake_auth = SSL_PHA_REQUESTED;
679 st->hand_state = TLS_ST_OK;
680 } else if (do_compressed_cert(s)) {
681 st->hand_state = TLS_ST_SW_COMP_CERT;
682 } else {
683 st->hand_state = TLS_ST_SW_CERT;
684 }
685 return WRITE_TRAN_CONTINUE;
686
687 case TLS_ST_SW_COMP_CERT:
688 case TLS_ST_SW_CERT:
689 st->hand_state = TLS_ST_SW_CERT_VRFY;
690 return WRITE_TRAN_CONTINUE;
691
692 case TLS_ST_SW_CERT_VRFY:
693 st->hand_state = TLS_ST_SW_FINISHED;
694 return WRITE_TRAN_CONTINUE;
695
696 case TLS_ST_SW_FINISHED:
697 st->hand_state = TLS_ST_EARLY_DATA;
698 s->ts_msg_write = ossl_time_now();
699 return WRITE_TRAN_CONTINUE;
700
701 case TLS_ST_EARLY_DATA:
702 return WRITE_TRAN_FINISHED;
703
704 case TLS_ST_SR_FINISHED:
705 s->ts_msg_read = ossl_time_now();
706 /*
707 * Technically we have finished the handshake at this point, but we're
708 * going to remain "in_init" for now and write out any session tickets
709 * immediately.
710 */
711 if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
712 s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
713 } else if (!s->ext.ticket_expected) {
714 /*
715 * If we're not going to renew the ticket then we just finish the
716 * handshake at this point.
717 */
718 st->hand_state = TLS_ST_OK;
719 return WRITE_TRAN_CONTINUE;
720 }
721 if (s->num_tickets > s->sent_tickets)
722 st->hand_state = TLS_ST_SW_SESSION_TICKET;
723 else
724 st->hand_state = TLS_ST_OK;
725 return WRITE_TRAN_CONTINUE;
726
727 case TLS_ST_SR_KEY_UPDATE:
728 case TLS_ST_SW_KEY_UPDATE:
729 st->hand_state = TLS_ST_OK;
730 return WRITE_TRAN_CONTINUE;
731
732 case TLS_ST_SW_SESSION_TICKET:
733 /* In a resumption we only ever send a maximum of one new ticket.
734 * Following an initial handshake we send the number of tickets we have
735 * been configured for.
736 */
737 if (!SSL_IS_FIRST_HANDSHAKE(s) && s->ext.extra_tickets_expected > 0) {
738 return WRITE_TRAN_CONTINUE;
739 } else if (s->hit || s->num_tickets <= s->sent_tickets) {
740 /* We've written enough tickets out. */
741 st->hand_state = TLS_ST_OK;
742 }
743 return WRITE_TRAN_CONTINUE;
744 }
745 }
746
747 /*
748 * ossl_statem_server_write_transition() works out what handshake state to move
749 * to next when the server is writing messages to be sent to the client.
750 */
751 WRITE_TRAN ossl_statem_server_write_transition(SSL_CONNECTION *s)
752 {
753 OSSL_STATEM *st = &s->statem;
754
755 /*
756 * Note that before the ClientHello we don't know what version we are going
757 * to negotiate yet, so we don't take this branch until later
758 */
759
760 if (SSL_CONNECTION_IS_TLS13(s))
761 return ossl_statem_server13_write_transition(s);
762
763 switch (st->hand_state) {
764 default:
765 /* Shouldn't happen */
766 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
767 return WRITE_TRAN_ERROR;
768
769 case TLS_ST_OK:
770 if (st->request_state == TLS_ST_SW_HELLO_REQ) {
771 /* We must be trying to renegotiate */
772 st->hand_state = TLS_ST_SW_HELLO_REQ;
773 st->request_state = TLS_ST_BEFORE;
774 return WRITE_TRAN_CONTINUE;
775 }
776 /* Must be an incoming ClientHello */
777 if (!tls_setup_handshake(s)) {
778 /* SSLfatal() already called */
779 return WRITE_TRAN_ERROR;
780 }
781 /* Fall through */
782
783 case TLS_ST_BEFORE:
784 /* Just go straight to trying to read from the client */
785 return WRITE_TRAN_FINISHED;
786
787 case TLS_ST_SW_HELLO_REQ:
788 st->hand_state = TLS_ST_OK;
789 return WRITE_TRAN_CONTINUE;
790
791 case TLS_ST_SR_CLNT_HELLO:
792 if (SSL_CONNECTION_IS_DTLS(s) && !s->d1->cookie_verified
793 && (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE)) {
794 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
795 } else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
796 /* We must have rejected the renegotiation */
797 st->hand_state = TLS_ST_OK;
798 return WRITE_TRAN_CONTINUE;
799 } else {
800 st->hand_state = TLS_ST_SW_SRVR_HELLO;
801 }
802 return WRITE_TRAN_CONTINUE;
803
804 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
805 return WRITE_TRAN_FINISHED;
806
807 case TLS_ST_SW_SRVR_HELLO:
808 if (s->hit) {
809 if (s->ext.ticket_expected)
810 st->hand_state = TLS_ST_SW_SESSION_TICKET;
811 else
812 st->hand_state = TLS_ST_SW_CHANGE;
813 } else {
814 /* Check if it is anon DH or anon ECDH, */
815 /* normal PSK or SRP */
816 if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
817 st->hand_state = TLS_ST_SW_CERT;
818 } else if (send_server_key_exchange(s)) {
819 st->hand_state = TLS_ST_SW_KEY_EXCH;
820 } else if (send_certificate_request(s)) {
821 st->hand_state = TLS_ST_SW_CERT_REQ;
822 } else {
823 st->hand_state = TLS_ST_SW_SRVR_DONE;
824 }
825 }
826 return WRITE_TRAN_CONTINUE;
827
828 case TLS_ST_SW_CERT:
829 if (s->ext.status_expected) {
830 st->hand_state = TLS_ST_SW_CERT_STATUS;
831 return WRITE_TRAN_CONTINUE;
832 }
833 /* Fall through */
834
835 case TLS_ST_SW_CERT_STATUS:
836 if (send_server_key_exchange(s)) {
837 st->hand_state = TLS_ST_SW_KEY_EXCH;
838 return WRITE_TRAN_CONTINUE;
839 }
840 /* Fall through */
841
842 case TLS_ST_SW_KEY_EXCH:
843 if (send_certificate_request(s)) {
844 st->hand_state = TLS_ST_SW_CERT_REQ;
845 return WRITE_TRAN_CONTINUE;
846 }
847 /* Fall through */
848
849 case TLS_ST_SW_CERT_REQ:
850 st->hand_state = TLS_ST_SW_SRVR_DONE;
851 return WRITE_TRAN_CONTINUE;
852
853 case TLS_ST_SW_SRVR_DONE:
854 s->ts_msg_write = ossl_time_now();
855 return WRITE_TRAN_FINISHED;
856
857 case TLS_ST_SR_FINISHED:
858 s->ts_msg_read = ossl_time_now();
859 if (s->hit) {
860 st->hand_state = TLS_ST_OK;
861 return WRITE_TRAN_CONTINUE;
862 } else if (s->ext.ticket_expected) {
863 st->hand_state = TLS_ST_SW_SESSION_TICKET;
864 } else {
865 st->hand_state = TLS_ST_SW_CHANGE;
866 }
867 return WRITE_TRAN_CONTINUE;
868
869 case TLS_ST_SW_SESSION_TICKET:
870 st->hand_state = TLS_ST_SW_CHANGE;
871 return WRITE_TRAN_CONTINUE;
872
873 case TLS_ST_SW_CHANGE:
874 st->hand_state = TLS_ST_SW_FINISHED;
875 return WRITE_TRAN_CONTINUE;
876
877 case TLS_ST_SW_FINISHED:
878 if (s->hit) {
879 return WRITE_TRAN_FINISHED;
880 }
881 st->hand_state = TLS_ST_OK;
882 return WRITE_TRAN_CONTINUE;
883 }
884 }
885
886 /*
887 * Perform any pre work that needs to be done prior to sending a message from
888 * the server to the client.
889 */
890 WORK_STATE ossl_statem_server_pre_work(SSL_CONNECTION *s, WORK_STATE wst)
891 {
892 OSSL_STATEM *st = &s->statem;
893 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
894
895 switch (st->hand_state) {
896 default:
897 /* No pre work to be done */
898 break;
899
900 case TLS_ST_SW_HELLO_REQ:
901 s->shutdown = 0;
902 if (SSL_CONNECTION_IS_DTLS(s))
903 dtls1_clear_sent_buffer(s);
904 break;
905
906 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
907 s->shutdown = 0;
908 if (SSL_CONNECTION_IS_DTLS(s)) {
909 dtls1_clear_sent_buffer(s);
910 /* We don't buffer this message so don't use the timer */
911 st->use_timer = 0;
912 }
913 break;
914
915 case TLS_ST_SW_SRVR_HELLO:
916 if (SSL_CONNECTION_IS_DTLS(s)) {
917 /*
918 * Messages we write from now on should be buffered and
919 * retransmitted if necessary, so we need to use the timer now
920 */
921 st->use_timer = 1;
922 }
923 break;
924
925 case TLS_ST_SW_SRVR_DONE:
926 #ifndef OPENSSL_NO_SCTP
927 if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
928 /* Calls SSLfatal() as required */
929 return dtls_wait_for_dry(s);
930 }
931 #endif
932 return WORK_FINISHED_CONTINUE;
933
934 case TLS_ST_SW_SESSION_TICKET:
935 if (SSL_CONNECTION_IS_TLS13(s) && s->sent_tickets == 0
936 && s->ext.extra_tickets_expected == 0) {
937 /*
938 * Actually this is the end of the handshake, but we're going
939 * straight into writing the session ticket out. So we finish off
940 * the handshake, but keep the various buffers active.
941 *
942 * Calls SSLfatal as required.
943 */
944 return tls_finish_handshake(s, wst, 0, 0);
945 }
946 if (SSL_CONNECTION_IS_DTLS(s)) {
947 /*
948 * We're into the last flight. We don't retransmit the last flight
949 * unless we need to, so we don't use the timer
950 */
951 st->use_timer = 0;
952 }
953 break;
954
955 case TLS_ST_SW_CHANGE:
956 if (SSL_CONNECTION_IS_TLS13(s))
957 break;
958 /* Writes to s->session are only safe for initial handshakes */
959 if (s->session->cipher == NULL) {
960 s->session->cipher = s->s3.tmp.new_cipher;
961 } else if (s->session->cipher != s->s3.tmp.new_cipher) {
962 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
963 return WORK_ERROR;
964 }
965 if (!ssl->method->ssl3_enc->setup_key_block(s)) {
966 /* SSLfatal() already called */
967 return WORK_ERROR;
968 }
969 if (SSL_CONNECTION_IS_DTLS(s)) {
970 /*
971 * We're into the last flight. We don't retransmit the last flight
972 * unless we need to, so we don't use the timer. This might have
973 * already been set to 0 if we sent a NewSessionTicket message,
974 * but we'll set it again here in case we didn't.
975 */
976 st->use_timer = 0;
977 }
978 return WORK_FINISHED_CONTINUE;
979
980 case TLS_ST_EARLY_DATA:
981 if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING
982 && (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
983 return WORK_FINISHED_CONTINUE;
984
985 /*
986 * In QUIC with 0-RTT we just carry on when otherwise we would stop
987 * to allow the server to read early data
988 */
989 if (SSL_NO_EOED(s) && s->ext.early_data == SSL_EARLY_DATA_ACCEPTED
990 && s->early_data_state != SSL_EARLY_DATA_FINISHED_READING) {
991 s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
992 if (!ssl->method->ssl3_enc->change_cipher_state(s, SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
993 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
994 return WORK_ERROR;
995 }
996 return WORK_FINISHED_SWAP;
997 }
998 /* Fall through */
999
1000 case TLS_ST_OK:
1001 /* Calls SSLfatal() as required */
1002 return tls_finish_handshake(s, wst, 1, 1);
1003 }
1004
1005 return WORK_FINISHED_CONTINUE;
1006 }
1007
1008 static ossl_inline int conn_is_closed(void)
1009 {
1010 switch (get_last_sys_error()) {
1011 #if defined(EPIPE)
1012 case EPIPE:
1013 return 1;
1014 #endif
1015 #if defined(ECONNRESET)
1016 case ECONNRESET:
1017 return 1;
1018 #endif
1019 #if defined(WSAECONNRESET)
1020 case WSAECONNRESET:
1021 return 1;
1022 #endif
1023 default:
1024 return 0;
1025 }
1026 }
1027
1028 /*
1029 * Perform any work that needs to be done after sending a message from the
1030 * server to the client.
1031 */
1032 WORK_STATE ossl_statem_server_post_work(SSL_CONNECTION *s, WORK_STATE wst)
1033 {
1034 OSSL_STATEM *st = &s->statem;
1035 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1036
1037 s->init_num = 0;
1038
1039 switch (st->hand_state) {
1040 default:
1041 /* No post work to be done */
1042 break;
1043
1044 case TLS_ST_SW_HELLO_REQ:
1045 if (statem_flush(s) != 1)
1046 return WORK_MORE_A;
1047 if (!ssl3_init_finished_mac(s)) {
1048 /* SSLfatal() already called */
1049 return WORK_ERROR;
1050 }
1051 break;
1052
1053 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1054 if (statem_flush(s) != 1)
1055 return WORK_MORE_A;
1056 /* HelloVerifyRequest resets Finished MAC */
1057 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
1058 /* SSLfatal() already called */
1059 return WORK_ERROR;
1060 }
1061 /*
1062 * The next message should be another ClientHello which we need to
1063 * treat like it was the first packet
1064 */
1065 s->first_packet = 1;
1066 break;
1067
1068 case TLS_ST_SW_SRVR_HELLO:
1069 if (SSL_CONNECTION_IS_TLS13(s)
1070 && s->hello_retry_request == SSL_HRR_PENDING) {
1071 if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0
1072 && statem_flush(s) != 1)
1073 return WORK_MORE_A;
1074 break;
1075 }
1076 #ifndef OPENSSL_NO_SCTP
1077 if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {
1078 unsigned char sctpauthkey[64];
1079 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1080 size_t labellen;
1081
1082 /*
1083 * Add new shared key for SCTP-Auth, will be ignored if no
1084 * SCTP used.
1085 */
1086 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1087 sizeof(DTLS1_SCTP_AUTH_LABEL));
1088
1089 /* Don't include the terminating zero. */
1090 labellen = sizeof(labelbuffer) - 1;
1091 if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
1092 labellen += 1;
1093
1094 if (SSL_export_keying_material(ssl, sctpauthkey,
1095 sizeof(sctpauthkey), labelbuffer,
1096 labellen, NULL, 0,
1097 0)
1098 <= 0) {
1099 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1100 return WORK_ERROR;
1101 }
1102
1103 BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1104 sizeof(sctpauthkey), sctpauthkey);
1105 }
1106 #endif
1107 if (!SSL_CONNECTION_IS_TLS13(s)
1108 || ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
1109 && s->hello_retry_request != SSL_HRR_COMPLETE))
1110 break;
1111 /* Fall through */
1112
1113 case TLS_ST_SW_CHANGE:
1114 if (s->hello_retry_request == SSL_HRR_PENDING) {
1115 if (!statem_flush(s))
1116 return WORK_MORE_A;
1117 break;
1118 }
1119
1120 if (SSL_CONNECTION_IS_TLS13(s)) {
1121 if (!ssl->method->ssl3_enc->setup_key_block(s)
1122 || !tls13_store_handshake_traffic_hash(s)
1123 || !ssl->method->ssl3_enc->change_cipher_state(s,
1124 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
1125 /* SSLfatal() already called */
1126 return WORK_ERROR;
1127 }
1128
1129 if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
1130 && !ssl->method->ssl3_enc->change_cipher_state(s,
1131 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
1132 /* SSLfatal() already called */
1133 return WORK_ERROR;
1134 }
1135 /*
1136 * We don't yet know whether the next record we are going to receive
1137 * is an unencrypted alert, an encrypted alert, or an encrypted
1138 * handshake message. We temporarily tolerate unencrypted alerts.
1139 */
1140 if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
1141 s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 1);
1142 break;
1143 }
1144
1145 #ifndef OPENSSL_NO_SCTP
1146 if (SSL_CONNECTION_IS_DTLS(s) && !s->hit) {
1147 /*
1148 * Change to new shared key of SCTP-Auth, will be ignored if
1149 * no SCTP used.
1150 */
1151 BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
1152 0, NULL);
1153 }
1154 #endif
1155 if (!ssl->method->ssl3_enc->change_cipher_state(s,
1156 SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
1157 /* SSLfatal() already called */
1158 return WORK_ERROR;
1159 }
1160 break;
1161
1162 case TLS_ST_SW_SRVR_DONE:
1163 if (statem_flush(s) != 1)
1164 return WORK_MORE_A;
1165 break;
1166
1167 case TLS_ST_SW_FINISHED:
1168 if (statem_flush(s) != 1)
1169 return WORK_MORE_A;
1170 #ifndef OPENSSL_NO_SCTP
1171 if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {
1172 /*
1173 * Change to new shared key of SCTP-Auth, will be ignored if
1174 * no SCTP used.
1175 */
1176 BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
1177 0, NULL);
1178 }
1179 #endif
1180 if (SSL_CONNECTION_IS_TLS13(s)) {
1181 /* TLS 1.3 gets the secret size from the handshake md */
1182 size_t dummy;
1183 if (!ssl->method->ssl3_enc->generate_master_secret(s,
1184 s->master_secret, s->handshake_secret, 0,
1185 &dummy)
1186 || !tls13_store_server_finished_hash(s)
1187 || !ssl->method->ssl3_enc->change_cipher_state(s,
1188 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
1189 /* SSLfatal() already called */
1190 return WORK_ERROR;
1191 }
1192 break;
1193
1194 case TLS_ST_SW_CERT_REQ:
1195 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
1196 if (statem_flush(s) != 1)
1197 return WORK_MORE_A;
1198 } else {
1199 if (!SSL_CONNECTION_IS_TLS13(s)
1200 || (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
1201 s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
1202 }
1203 break;
1204
1205 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1206 if (!s->hit && !send_certificate_request(s)) {
1207 if (!SSL_CONNECTION_IS_TLS13(s)
1208 || (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
1209 s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
1210 }
1211 break;
1212
1213 case TLS_ST_SW_KEY_UPDATE:
1214 if (statem_flush(s) != 1)
1215 return WORK_MORE_A;
1216 if (!tls13_update_key(s, 1)) {
1217 /* SSLfatal() already called */
1218 return WORK_ERROR;
1219 }
1220 break;
1221
1222 case TLS_ST_SW_SESSION_TICKET:
1223 clear_sys_error();
1224 if (SSL_CONNECTION_IS_TLS13(s) && statem_flush(s) != 1) {
1225 if (SSL_get_error(ssl, 0) == SSL_ERROR_SYSCALL
1226 && conn_is_closed()) {
1227 /*
1228 * We ignore connection closed errors in TLSv1.3 when sending a
1229 * NewSessionTicket and behave as if we were successful. This is
1230 * so that we are still able to read data sent to us by a client
1231 * that closes soon after the end of the handshake without
1232 * waiting to read our post-handshake NewSessionTickets.
1233 */
1234 s->rwstate = SSL_NOTHING;
1235 break;
1236 }
1237
1238 return WORK_MORE_A;
1239 }
1240 break;
1241 }
1242
1243 return WORK_FINISHED_CONTINUE;
1244 }
1245
1246 /*
1247 * Get the message construction function and message type for sending from the
1248 * server
1249 *
1250 * Valid return values are:
1251 * 1: Success
1252 * 0: Error
1253 */
1254 int ossl_statem_server_construct_message(SSL_CONNECTION *s,
1255 confunc_f *confunc, int *mt)
1256 {
1257 OSSL_STATEM *st = &s->statem;
1258
1259 switch (st->hand_state) {
1260 default:
1261 /* Shouldn't happen */
1262 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
1263 return 0;
1264
1265 case TLS_ST_SW_CHANGE:
1266 if (SSL_CONNECTION_IS_DTLS(s))
1267 *confunc = dtls_construct_change_cipher_spec;
1268 else
1269 *confunc = tls_construct_change_cipher_spec;
1270 *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1271 break;
1272
1273 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1274 *confunc = dtls_construct_hello_verify_request;
1275 *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
1276 break;
1277
1278 case TLS_ST_SW_HELLO_REQ:
1279 /* No construction function needed */
1280 *confunc = NULL;
1281 *mt = SSL3_MT_HELLO_REQUEST;
1282 break;
1283
1284 case TLS_ST_SW_SRVR_HELLO:
1285 *confunc = tls_construct_server_hello;
1286 *mt = SSL3_MT_SERVER_HELLO;
1287 break;
1288
1289 case TLS_ST_SW_CERT:
1290 *confunc = tls_construct_server_certificate;
1291 *mt = SSL3_MT_CERTIFICATE;
1292 break;
1293
1294 #ifndef OPENSSL_NO_COMP_ALG
1295 case TLS_ST_SW_COMP_CERT:
1296 *confunc = tls_construct_server_compressed_certificate;
1297 *mt = SSL3_MT_COMPRESSED_CERTIFICATE;
1298 break;
1299 #endif
1300
1301 case TLS_ST_SW_CERT_VRFY:
1302 *confunc = tls_construct_cert_verify;
1303 *mt = SSL3_MT_CERTIFICATE_VERIFY;
1304 break;
1305
1306 case TLS_ST_SW_KEY_EXCH:
1307 *confunc = tls_construct_server_key_exchange;
1308 *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
1309 break;
1310
1311 case TLS_ST_SW_CERT_REQ:
1312 *confunc = tls_construct_certificate_request;
1313 *mt = SSL3_MT_CERTIFICATE_REQUEST;
1314 break;
1315
1316 case TLS_ST_SW_SRVR_DONE:
1317 *confunc = tls_construct_server_done;
1318 *mt = SSL3_MT_SERVER_DONE;
1319 break;
1320
1321 case TLS_ST_SW_SESSION_TICKET:
1322 *confunc = tls_construct_new_session_ticket;
1323 *mt = SSL3_MT_NEWSESSION_TICKET;
1324 break;
1325
1326 case TLS_ST_SW_CERT_STATUS:
1327 *confunc = tls_construct_cert_status;
1328 *mt = SSL3_MT_CERTIFICATE_STATUS;
1329 break;
1330
1331 case TLS_ST_SW_FINISHED:
1332 *confunc = tls_construct_finished;
1333 *mt = SSL3_MT_FINISHED;
1334 break;
1335
1336 case TLS_ST_EARLY_DATA:
1337 *confunc = NULL;
1338 *mt = SSL3_MT_DUMMY;
1339 break;
1340
1341 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1342 *confunc = tls_construct_encrypted_extensions;
1343 *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
1344 break;
1345
1346 case TLS_ST_SW_KEY_UPDATE:
1347 *confunc = tls_construct_key_update;
1348 *mt = SSL3_MT_KEY_UPDATE;
1349 break;
1350 }
1351
1352 return 1;
1353 }
1354
1355 /*
1356 * Maximum size (excluding the Handshake header) of a ClientHello message,
1357 * calculated as follows:
1358 *
1359 * 2 + # client_version
1360 * 32 + # only valid length for random
1361 * 1 + # length of session_id
1362 * 32 + # maximum size for session_id
1363 * 2 + # length of cipher suites
1364 * 2^16-2 + # maximum length of cipher suites array
1365 * 1 + # length of compression_methods
1366 * 2^8-1 + # maximum length of compression methods
1367 * 2 + # length of extensions
1368 * 2^16-1 # maximum length of extensions
1369 */
1370 #define CLIENT_HELLO_MAX_LENGTH 131396
1371
1372 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
1373 #define NEXT_PROTO_MAX_LENGTH 514
1374
1375 /*
1376 * Returns the maximum allowed length for the current message that we are
1377 * reading. Excludes the message header.
1378 */
1379 size_t ossl_statem_server_max_message_size(SSL_CONNECTION *s)
1380 {
1381 OSSL_STATEM *st = &s->statem;
1382
1383 switch (st->hand_state) {
1384 default:
1385 /* Shouldn't happen */
1386 return 0;
1387
1388 case TLS_ST_SR_CLNT_HELLO:
1389 return CLIENT_HELLO_MAX_LENGTH;
1390
1391 case TLS_ST_SR_END_OF_EARLY_DATA:
1392 return END_OF_EARLY_DATA_MAX_LENGTH;
1393
1394 case TLS_ST_SR_COMP_CERT:
1395 case TLS_ST_SR_CERT:
1396 return s->max_cert_list;
1397
1398 case TLS_ST_SR_KEY_EXCH:
1399 return CLIENT_KEY_EXCH_MAX_LENGTH;
1400
1401 case TLS_ST_SR_CERT_VRFY:
1402 return CERTIFICATE_VERIFY_MAX_LENGTH;
1403
1404 #ifndef OPENSSL_NO_NEXTPROTONEG
1405 case TLS_ST_SR_NEXT_PROTO:
1406 return NEXT_PROTO_MAX_LENGTH;
1407 #endif
1408
1409 case TLS_ST_SR_CHANGE:
1410 return CCS_MAX_LENGTH;
1411
1412 case TLS_ST_SR_FINISHED:
1413 return FINISHED_MAX_LENGTH;
1414
1415 case TLS_ST_SR_KEY_UPDATE:
1416 return KEY_UPDATE_MAX_LENGTH;
1417 }
1418 }
1419
1420 /*
1421 * Process a message that the server has received from the client.
1422 */
1423 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL_CONNECTION *s,
1424 PACKET *pkt)
1425 {
1426 OSSL_STATEM *st = &s->statem;
1427
1428 switch (st->hand_state) {
1429 default:
1430 /* Shouldn't happen */
1431 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1432 return MSG_PROCESS_ERROR;
1433
1434 case TLS_ST_SR_CLNT_HELLO:
1435 return tls_process_client_hello(s, pkt);
1436
1437 case TLS_ST_SR_END_OF_EARLY_DATA:
1438 return tls_process_end_of_early_data(s, pkt);
1439
1440 case TLS_ST_SR_CERT:
1441 return tls_process_client_certificate(s, pkt);
1442
1443 #ifndef OPENSSL_NO_COMP_ALG
1444 case TLS_ST_SR_COMP_CERT:
1445 return tls_process_client_compressed_certificate(s, pkt);
1446 #endif
1447
1448 case TLS_ST_SR_KEY_EXCH:
1449 return tls_process_client_key_exchange(s, pkt);
1450
1451 case TLS_ST_SR_CERT_VRFY:
1452 return tls_process_cert_verify(s, pkt);
1453
1454 #ifndef OPENSSL_NO_NEXTPROTONEG
1455 case TLS_ST_SR_NEXT_PROTO:
1456 return tls_process_next_proto(s, pkt);
1457 #endif
1458
1459 case TLS_ST_SR_CHANGE:
1460 return tls_process_change_cipher_spec(s, pkt);
1461
1462 case TLS_ST_SR_FINISHED:
1463 return tls_process_finished(s, pkt);
1464
1465 case TLS_ST_SR_KEY_UPDATE:
1466 return tls_process_key_update(s, pkt);
1467 }
1468 }
1469
1470 /*
1471 * Perform any further processing required following the receipt of a message
1472 * from the client
1473 */
1474 WORK_STATE ossl_statem_server_post_process_message(SSL_CONNECTION *s,
1475 WORK_STATE wst)
1476 {
1477 OSSL_STATEM *st = &s->statem;
1478
1479 switch (st->hand_state) {
1480 default:
1481 /* Shouldn't happen */
1482 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1483 return WORK_ERROR;
1484
1485 case TLS_ST_SR_CLNT_HELLO:
1486 return tls_post_process_client_hello(s, wst);
1487
1488 case TLS_ST_SR_KEY_EXCH:
1489 return tls_post_process_client_key_exchange(s, wst);
1490 }
1491 }
1492
1493 #ifndef OPENSSL_NO_SRP
1494 /* Returns 1 on success, 0 for retryable error, -1 for fatal error */
1495 static int ssl_check_srp_ext_ClientHello(SSL_CONNECTION *s)
1496 {
1497 int ret;
1498 int al = SSL_AD_UNRECOGNIZED_NAME;
1499
1500 if ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) && (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1501 if (s->srp_ctx.login == NULL) {
1502 /*
1503 * RFC 5054 says SHOULD reject, we do so if There is no srp
1504 * login name
1505 */
1506 SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
1507 SSL_R_PSK_IDENTITY_NOT_FOUND);
1508 return -1;
1509 } else {
1510 ret = ssl_srp_server_param_with_username_intern(s, &al);
1511 if (ret < 0)
1512 return 0;
1513 if (ret == SSL3_AL_FATAL) {
1514 SSLfatal(s, al,
1515 al == SSL_AD_UNKNOWN_PSK_IDENTITY
1516 ? SSL_R_PSK_IDENTITY_NOT_FOUND
1517 : SSL_R_CLIENTHELLO_TLSEXT);
1518 return -1;
1519 }
1520 }
1521 }
1522 return 1;
1523 }
1524 #endif
1525
1526 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1527 size_t cookie_len)
1528 {
1529 /* Always use DTLS 1.0 version: see RFC 6347 */
1530 if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1531 || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1532 return 0;
1533
1534 return 1;
1535 }
1536
1537 CON_FUNC_RETURN dtls_construct_hello_verify_request(SSL_CONNECTION *s,
1538 WPACKET *pkt)
1539 {
1540 unsigned int cookie_leni;
1541 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1542
1543 if (sctx->app_gen_cookie_cb == NULL
1544 || sctx->app_gen_cookie_cb(SSL_CONNECTION_GET_USER_SSL(s), s->d1->cookie,
1545 &cookie_leni)
1546 == 0
1547 || cookie_leni > DTLS1_COOKIE_LENGTH) {
1548 SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1549 return CON_FUNC_ERROR;
1550 }
1551 s->d1->cookie_len = cookie_leni;
1552
1553 if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1554 s->d1->cookie_len)) {
1555 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
1556 return CON_FUNC_ERROR;
1557 }
1558
1559 return CON_FUNC_SUCCESS;
1560 }
1561
1562 /*-
1563 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1564 * SecureTransport using the TLS extension block in |hello|.
1565 * Safari, since 10.6, sends exactly these extensions, in this order:
1566 * SNI,
1567 * elliptic_curves
1568 * ec_point_formats
1569 * signature_algorithms (for TLSv1.2 only)
1570 *
1571 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1572 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1573 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1574 * 10.8..10.8.3 (which don't work).
1575 */
1576 static void ssl_check_for_safari(SSL_CONNECTION *s,
1577 const CLIENTHELLO_MSG *hello)
1578 {
1579 static const unsigned char kSafariExtensionsBlock[] = {
1580 0x00,
1581 0x0a, /* elliptic_curves extension */
1582 0x00,
1583 0x08, /* 8 bytes */
1584 0x00,
1585 0x06, /* 6 bytes of curve ids */
1586 0x00,
1587 0x17, /* P-256 */
1588 0x00,
1589 0x18, /* P-384 */
1590 0x00,
1591 0x19, /* P-521 */
1592
1593 0x00,
1594 0x0b, /* ec_point_formats */
1595 0x00,
1596 0x02, /* 2 bytes */
1597 0x01, /* 1 point format */
1598 0x00, /* uncompressed */
1599 /* The following is only present in TLS 1.2 */
1600 0x00,
1601 0x0d, /* signature_algorithms */
1602 0x00,
1603 0x0c, /* 12 bytes */
1604 0x00,
1605 0x0a, /* 10 bytes */
1606 0x05,
1607 0x01, /* SHA-384/RSA */
1608 0x04,
1609 0x01, /* SHA-256/RSA */
1610 0x02,
1611 0x01, /* SHA-1/RSA */
1612 0x04,
1613 0x03, /* SHA-256/ECDSA */
1614 0x02,
1615 0x03, /* SHA-1/ECDSA */
1616 };
1617 /* Length of the common prefix (first two extensions). */
1618 static const size_t kSafariCommonExtensionsLength = 18;
1619 unsigned int type;
1620 PACKET sni, tmppkt;
1621 size_t ext_len;
1622
1623 tmppkt = hello->extensions;
1624
1625 if (!PACKET_forward(&tmppkt, 2)
1626 || !PACKET_get_net_2(&tmppkt, &type)
1627 || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1628 return;
1629 }
1630
1631 if (type != TLSEXT_TYPE_server_name)
1632 return;
1633
1634 ext_len = TLS1_get_client_version(
1635 SSL_CONNECTION_GET_SSL(s))
1636 >= TLS1_2_VERSION
1637 ? sizeof(kSafariExtensionsBlock)
1638 : kSafariCommonExtensionsLength;
1639
1640 s->s3.is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1641 ext_len);
1642 }
1643
1644 #define RENEG_OPTIONS_OK(options) \
1645 ((options & SSL_OP_NO_RENEGOTIATION) == 0 \
1646 && (options & SSL_OP_ALLOW_CLIENT_RENEGOTIATION) != 0)
1647
1648 MSG_PROCESS_RETURN tls_process_client_hello(SSL_CONNECTION *s, PACKET *pkt)
1649 {
1650 /* |cookie| will only be initialized for DTLS. */
1651 PACKET session_id, compression, extensions, cookie;
1652 static const unsigned char null_compression = 0;
1653 CLIENTHELLO_MSG *clienthello = NULL;
1654
1655 /* Check if this is actually an unexpected renegotiation ClientHello */
1656 if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1657 if (!ossl_assert(!SSL_CONNECTION_IS_TLS13(s))) {
1658 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1659 goto err;
1660 }
1661 if (!RENEG_OPTIONS_OK(s->options)
1662 || (!s->s3.send_connection_binding
1663 && (s->options
1664 & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
1665 == 0)) {
1666 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1667 return MSG_PROCESS_FINISHED_READING;
1668 }
1669 s->renegotiate = 1;
1670 s->new_session = 1;
1671 }
1672
1673 clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1674 if (clienthello == NULL) {
1675 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1676 goto err;
1677 }
1678
1679 /*
1680 * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1681 */
1682 clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1683 PACKET_null_init(&cookie);
1684
1685 if (clienthello->isv2) {
1686 unsigned int mt;
1687
1688 if (!SSL_IS_FIRST_HANDSHAKE(s)
1689 || s->hello_retry_request != SSL_HRR_NONE) {
1690 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1691 goto err;
1692 }
1693
1694 /*-
1695 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1696 * header is sent directly on the wire, not wrapped as a TLS
1697 * record. Our record layer just processes the message length and passes
1698 * the rest right through. Its format is:
1699 * Byte Content
1700 * 0-1 msg_length - decoded by the record layer
1701 * 2 msg_type - s->init_msg points here
1702 * 3-4 version
1703 * 5-6 cipher_spec_length
1704 * 7-8 session_id_length
1705 * 9-10 challenge_length
1706 * ... ...
1707 */
1708
1709 if (!PACKET_get_1(pkt, &mt)
1710 || mt != SSL2_MT_CLIENT_HELLO) {
1711 /*
1712 * Should never happen. We should have tested this in the record
1713 * layer in order to have determined that this is an SSLv2 record
1714 * in the first place
1715 */
1716 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1717 goto err;
1718 }
1719 }
1720
1721 if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1722 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1723 goto err;
1724 }
1725
1726 /* Parse the message and load client random. */
1727 if (clienthello->isv2) {
1728 /*
1729 * Handle an SSLv2 backwards compatible ClientHello
1730 * Note, this is only for SSLv3+ using the backward compatible format.
1731 * Real SSLv2 is not supported, and is rejected below.
1732 */
1733 unsigned int ciphersuite_len, session_id_len, challenge_len;
1734 PACKET challenge;
1735
1736 if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1737 || !PACKET_get_net_2(pkt, &session_id_len)
1738 || !PACKET_get_net_2(pkt, &challenge_len)) {
1739 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);
1740 goto err;
1741 }
1742
1743 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1744 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_MISMATCH);
1745 goto err;
1746 }
1747
1748 if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1749 ciphersuite_len)
1750 || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1751 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1752 /* No extensions. */
1753 || PACKET_remaining(pkt) != 0) {
1754 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);
1755 goto err;
1756 }
1757 clienthello->session_id_len = session_id_len;
1758
1759 /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1760 * here rather than sizeof(clienthello->random) because that is the limit
1761 * for SSLv3 and it is fixed. It won't change even if
1762 * sizeof(clienthello->random) does.
1763 */
1764 challenge_len = challenge_len > SSL3_RANDOM_SIZE
1765 ? SSL3_RANDOM_SIZE
1766 : challenge_len;
1767 memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1768 if (!PACKET_copy_bytes(&challenge,
1769 clienthello->random + SSL3_RANDOM_SIZE - challenge_len, challenge_len)
1770 /* Advertise only null compression. */
1771 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1772 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1773 goto err;
1774 }
1775
1776 PACKET_null_init(&clienthello->extensions);
1777 } else {
1778 /* Regular ClientHello. */
1779 if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1780 || !PACKET_get_length_prefixed_1(pkt, &session_id)
1781 || !PACKET_copy_all(&session_id, clienthello->session_id,
1782 SSL_MAX_SSL_SESSION_ID_LENGTH,
1783 &clienthello->session_id_len)) {
1784 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1785 goto err;
1786 }
1787
1788 if (SSL_CONNECTION_IS_DTLS(s)) {
1789 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1790 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1791 goto err;
1792 }
1793 if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1794 DTLS1_COOKIE_LENGTH,
1795 &clienthello->dtls_cookie_len)) {
1796 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1797 goto err;
1798 }
1799 /*
1800 * If we require cookies and this ClientHello doesn't contain one,
1801 * just return since we do not want to allocate any memory yet.
1802 * So check cookie length...
1803 */
1804 if (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE) {
1805 if (clienthello->dtls_cookie_len == 0) {
1806 OPENSSL_free(clienthello);
1807 return MSG_PROCESS_FINISHED_READING;
1808 }
1809 }
1810 }
1811
1812 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1813 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1814 goto err;
1815 }
1816
1817 if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1818 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1819 goto err;
1820 }
1821
1822 /* Could be empty. */
1823 if (PACKET_remaining(pkt) == 0) {
1824 PACKET_null_init(&clienthello->extensions);
1825 } else {
1826 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1827 || PACKET_remaining(pkt) != 0) {
1828 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1829 goto err;
1830 }
1831 }
1832 }
1833
1834 if (!PACKET_copy_all(&compression, clienthello->compressions,
1835 MAX_COMPRESSIONS_SIZE,
1836 &clienthello->compressions_len)) {
1837 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1838 goto err;
1839 }
1840
1841 /* Preserve the raw extensions PACKET for later use */
1842 extensions = clienthello->extensions;
1843 if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1844 &clienthello->pre_proc_exts,
1845 &clienthello->pre_proc_exts_len, 1)) {
1846 /* SSLfatal already been called */
1847 goto err;
1848 }
1849 s->clienthello = clienthello;
1850
1851 return MSG_PROCESS_CONTINUE_PROCESSING;
1852
1853 err:
1854 if (clienthello != NULL)
1855 OPENSSL_free(clienthello->pre_proc_exts);
1856 OPENSSL_free(clienthello);
1857
1858 return MSG_PROCESS_ERROR;
1859 }
1860
1861 static int tls_early_post_process_client_hello(SSL_CONNECTION *s)
1862 {
1863 unsigned int j;
1864 int i, al = SSL_AD_INTERNAL_ERROR;
1865 int protverr;
1866 unsigned long id;
1867 #ifndef OPENSSL_NO_COMP
1868 SSL_COMP *comp = NULL;
1869 #endif
1870 const SSL_CIPHER *c;
1871 STACK_OF(SSL_CIPHER) *ciphers = NULL;
1872 STACK_OF(SSL_CIPHER) *scsvs = NULL;
1873 CLIENTHELLO_MSG *clienthello = s->clienthello;
1874 DOWNGRADE dgrd = DOWNGRADE_NONE;
1875 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1876 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1877 SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1878
1879 /* Finished parsing the ClientHello, now we can start processing it */
1880 /* Give the ClientHello callback a crack at things */
1881 if (sctx->client_hello_cb != NULL) {
1882 /* A failure in the ClientHello callback terminates the connection. */
1883 switch (sctx->client_hello_cb(ussl, &al, sctx->client_hello_cb_arg)) {
1884 case SSL_CLIENT_HELLO_SUCCESS:
1885 break;
1886 case SSL_CLIENT_HELLO_RETRY:
1887 s->rwstate = SSL_CLIENT_HELLO_CB;
1888 return -1;
1889 case SSL_CLIENT_HELLO_ERROR:
1890 default:
1891 SSLfatal(s, al, SSL_R_CALLBACK_FAILED);
1892 goto err;
1893 }
1894 }
1895
1896 /* Set up the client_random */
1897 memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE);
1898
1899 /* Choose the version */
1900
1901 if (clienthello->isv2) {
1902 if (clienthello->legacy_version == SSL2_VERSION
1903 || (clienthello->legacy_version & 0xff00)
1904 != (SSL3_VERSION_MAJOR << 8)) {
1905 /*
1906 * This is real SSLv2 or something completely unknown. We don't
1907 * support it.
1908 */
1909 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNKNOWN_PROTOCOL);
1910 goto err;
1911 }
1912 /* SSLv3/TLS */
1913 s->client_version = clienthello->legacy_version;
1914 }
1915
1916 /* Choose the server SSL/TLS/DTLS version. */
1917 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1918
1919 if (protverr) {
1920 if (SSL_IS_FIRST_HANDSHAKE(s)) {
1921 /* like ssl3_get_record, send alert using remote version number */
1922 s->version = s->client_version = clienthello->legacy_version;
1923 }
1924 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);
1925 goto err;
1926 }
1927
1928 /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1929 if (SSL_CONNECTION_IS_TLS13(s)
1930 && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1931 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
1932 goto err;
1933 }
1934
1935 if (SSL_CONNECTION_IS_DTLS(s)) {
1936 /* Empty cookie was already handled above by returning early. */
1937 if (SSL_get_options(ssl) & SSL_OP_COOKIE_EXCHANGE) {
1938 if (sctx->app_verify_cookie_cb != NULL) {
1939 if (sctx->app_verify_cookie_cb(ussl, clienthello->dtls_cookie,
1940 (unsigned int)clienthello->dtls_cookie_len)
1941 == 0) {
1942 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1943 SSL_R_COOKIE_MISMATCH);
1944 goto err;
1945 /* else cookie verification succeeded */
1946 }
1947 /* default verification */
1948 } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1949 || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1950 s->d1->cookie_len)
1951 != 0) {
1952 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_COOKIE_MISMATCH);
1953 goto err;
1954 }
1955 s->d1->cookie_verified = 1;
1956 }
1957 }
1958
1959 s->hit = 0;
1960
1961 if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1962 clienthello->isv2)
1963 || !ossl_bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers,
1964 &scsvs, clienthello->isv2, 1)) {
1965 /* SSLfatal() already called */
1966 goto err;
1967 }
1968
1969 s->s3.send_connection_binding = 0;
1970 /* Check what signalling cipher-suite values were received. */
1971 if (scsvs != NULL) {
1972 for (i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1973 c = sk_SSL_CIPHER_value(scsvs, i);
1974 if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1975 if (s->renegotiate) {
1976 /* SCSV is fatal if renegotiating */
1977 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1978 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1979 goto err;
1980 }
1981 s->s3.send_connection_binding = 1;
1982 } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV && !ssl_check_version_downgrade(s)) {
1983 /*
1984 * This SCSV indicates that the client previously tried
1985 * a higher version. We should fail if the current version
1986 * is an unexpected downgrade, as that indicates that the first
1987 * connection may have been tampered with in order to trigger
1988 * an insecure downgrade.
1989 */
1990 SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,
1991 SSL_R_INAPPROPRIATE_FALLBACK);
1992 goto err;
1993 }
1994 }
1995 }
1996
1997 /* For TLSv1.3 we must select the ciphersuite *before* session resumption */
1998 if (SSL_CONNECTION_IS_TLS13(s)) {
1999 const SSL_CIPHER *cipher = ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(ssl));
2000
2001 if (cipher == NULL) {
2002 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
2003 goto err;
2004 }
2005 if (s->hello_retry_request == SSL_HRR_PENDING
2006 && (s->s3.tmp.new_cipher == NULL
2007 || s->s3.tmp.new_cipher->id != cipher->id)) {
2008 /*
2009 * A previous HRR picked a different ciphersuite to the one we
2010 * just selected. Something must have changed.
2011 */
2012 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_CIPHER);
2013 goto err;
2014 }
2015 s->s3.tmp.new_cipher = cipher;
2016 }
2017
2018 /* We need to do this before getting the session */
2019 if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
2020 SSL_EXT_CLIENT_HELLO,
2021 clienthello->pre_proc_exts, NULL, 0)) {
2022 /* SSLfatal() already called */
2023 goto err;
2024 }
2025
2026 /*
2027 * We don't allow resumption in a backwards compatible ClientHello.
2028 * In TLS1.1+, session_id MUST be empty.
2029 *
2030 * Versions before 0.9.7 always allow clients to resume sessions in
2031 * renegotiation. 0.9.7 and later allow this by default, but optionally
2032 * ignore resumption requests with flag
2033 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
2034 * than a change to default behavior so that applications relying on
2035 * this for security won't even compile against older library versions).
2036 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
2037 * request renegotiation but not a new session (s->new_session remains
2038 * unset): for servers, this essentially just means that the
2039 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
2040 * ignored.
2041 */
2042 if (clienthello->isv2 || (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
2043 if (!ssl_get_new_session(s, 1)) {
2044 /* SSLfatal() already called */
2045 goto err;
2046 }
2047 } else {
2048 i = ssl_get_prev_session(s, clienthello);
2049 if (i == 1) {
2050 /* previous session */
2051 s->hit = 1;
2052 } else if (i == -1) {
2053 /* SSLfatal() already called */
2054 goto err;
2055 } else {
2056 /* i == 0 */
2057 if (!ssl_get_new_session(s, 1)) {
2058 /* SSLfatal() already called */
2059 goto err;
2060 }
2061 }
2062 }
2063
2064 if (SSL_CONNECTION_IS_TLS13(s)) {
2065 memcpy(s->tmp_session_id, s->clienthello->session_id,
2066 s->clienthello->session_id_len);
2067 s->tmp_session_id_len = s->clienthello->session_id_len;
2068 }
2069
2070 /*
2071 * If it is a hit, check that the cipher is in the list. In TLSv1.3 we check
2072 * ciphersuite compatibility with the session as part of resumption.
2073 */
2074 if (!SSL_CONNECTION_IS_TLS13(s) && s->hit) {
2075 j = 0;
2076 id = s->session->cipher->id;
2077
2078 OSSL_TRACE_BEGIN(TLS_CIPHER)
2079 {
2080 BIO_printf(trc_out, "client sent %d ciphers\n",
2081 sk_SSL_CIPHER_num(ciphers));
2082 }
2083 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2084 c = sk_SSL_CIPHER_value(ciphers, i);
2085 if (trc_out != NULL)
2086 BIO_printf(trc_out, "client [%2d of %2d]:%s\n", i,
2087 sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
2088 if (c->id == id) {
2089 j = 1;
2090 break;
2091 }
2092 }
2093 if (j == 0) {
2094 /*
2095 * we need to have the cipher in the cipher list if we are asked
2096 * to reuse it
2097 */
2098 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2099 SSL_R_REQUIRED_CIPHER_MISSING);
2100 OSSL_TRACE_CANCEL(TLS_CIPHER);
2101 goto err;
2102 }
2103 OSSL_TRACE_END(TLS_CIPHER);
2104 }
2105
2106 /* At least one compression method must be preset. */
2107 if (clienthello->compressions_len == 0) {
2108 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_NO_COMPRESSION_SPECIFIED);
2109 goto err;
2110 }
2111 /* Make sure at least the null compression is supported. */
2112 if (memchr(clienthello->compressions, 0,
2113 clienthello->compressions_len)
2114 == NULL) {
2115 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2116 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
2117 goto err;
2118 }
2119
2120 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
2121 ssl_check_for_safari(s, clienthello);
2122
2123 /* TLS extensions */
2124 if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
2125 clienthello->pre_proc_exts, NULL, 0, 1)) {
2126 /* SSLfatal() already called */
2127 goto err;
2128 }
2129
2130 /*
2131 * Check if we want to use external pre-shared secret for this handshake
2132 * for not reused session only. We need to generate server_random before
2133 * calling tls_session_secret_cb in order to allow SessionTicket
2134 * processing to use it in key derivation.
2135 */
2136 {
2137 unsigned char *pos;
2138 pos = s->s3.server_random;
2139 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
2140 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2141 goto err;
2142 }
2143 }
2144
2145 if (!s->hit && !tls1_set_server_sigalgs(s)) {
2146 /* SSLfatal() already called */
2147 goto err;
2148 }
2149
2150 if (!s->hit
2151 && s->version >= TLS1_VERSION
2152 && !SSL_CONNECTION_IS_TLS13(s)
2153 && !SSL_CONNECTION_IS_DTLS(s)
2154 && s->ext.session_secret_cb != NULL) {
2155 const SSL_CIPHER *pref_cipher = NULL;
2156 /*
2157 * s->session->master_key_length is a size_t, but this is an int for
2158 * backwards compat reasons
2159 */
2160 int master_key_length;
2161
2162 master_key_length = sizeof(s->session->master_key);
2163 if (s->ext.session_secret_cb(ussl, s->session->master_key,
2164 &master_key_length, ciphers,
2165 &pref_cipher,
2166 s->ext.session_secret_cb_arg)
2167 && master_key_length > 0) {
2168 s->session->master_key_length = master_key_length;
2169 s->hit = 1;
2170 s->peer_ciphers = ciphers;
2171 s->session->verify_result = X509_V_OK;
2172
2173 /*
2174 * Per RFC 4851, Section 3.2.2:
2175 * If the ClientHello contains both a Session ID and a PAC-Opaque in
2176 * the SessionTicket extension, and the server resumes the session
2177 * using the PAC-Opaque, it should echo the same Session ID in the
2178 * ServerHello.
2179 */
2180 if (clienthello->session_id_len > 0) {
2181 memcpy(s->session->session_id, clienthello->session_id,
2182 clienthello->session_id_len);
2183 s->session->session_id_length = clienthello->session_id_len;
2184 }
2185
2186 ciphers = NULL;
2187
2188 /* check if some cipher was preferred by call back */
2189 if (pref_cipher == NULL)
2190 pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,
2191 SSL_get_ciphers(ssl));
2192 if (pref_cipher == NULL) {
2193 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
2194 goto err;
2195 }
2196
2197 s->session->cipher = pref_cipher;
2198 sk_SSL_CIPHER_free(s->cipher_list);
2199 s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);
2200 sk_SSL_CIPHER_free(s->cipher_list_by_id);
2201 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);
2202 }
2203 }
2204
2205 /*
2206 * Worst case, we will use the NULL compression, but if we have other
2207 * options, we will now look for them. We have complen-1 compression
2208 * algorithms from the client, starting at q.
2209 */
2210 s->s3.tmp.new_compression = NULL;
2211 if (SSL_CONNECTION_IS_TLS13(s)) {
2212 /*
2213 * We already checked above that the NULL compression method appears in
2214 * the list. Now we check there aren't any others (which is illegal in
2215 * a TLSv1.3 ClientHello.
2216 */
2217 if (clienthello->compressions_len != 1) {
2218 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2219 SSL_R_INVALID_COMPRESSION_ALGORITHM);
2220 goto err;
2221 }
2222 }
2223 #ifndef OPENSSL_NO_COMP
2224 /* This only happens if we have a cache hit */
2225 else if (s->session->compress_meth != 0) {
2226 int m, comp_id = s->session->compress_meth;
2227 unsigned int k;
2228 /* Perform sanity checks on resumed compression algorithm */
2229 /* Can't disable compression */
2230 if (!ssl_allow_compression(s)) {
2231 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2232 SSL_R_INCONSISTENT_COMPRESSION);
2233 goto err;
2234 }
2235 /* Look for resumed compression method */
2236 for (m = 0; m < sk_SSL_COMP_num(sctx->comp_methods); m++) {
2237 comp = sk_SSL_COMP_value(sctx->comp_methods, m);
2238 if (comp_id == comp->id) {
2239 s->s3.tmp.new_compression = comp;
2240 break;
2241 }
2242 }
2243 if (s->s3.tmp.new_compression == NULL) {
2244 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2245 SSL_R_INVALID_COMPRESSION_ALGORITHM);
2246 goto err;
2247 }
2248 /* Look for resumed method in compression list */
2249 for (k = 0; k < clienthello->compressions_len; k++) {
2250 if (clienthello->compressions[k] == comp_id)
2251 break;
2252 }
2253 if (k >= clienthello->compressions_len) {
2254 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2255 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
2256 goto err;
2257 }
2258 } else if (s->hit) {
2259 comp = NULL;
2260 } else if (ssl_allow_compression(s) && sctx->comp_methods) {
2261 /* See if we have a match */
2262 int m, nn, v, done = 0;
2263 unsigned int o;
2264
2265 nn = sk_SSL_COMP_num(sctx->comp_methods);
2266 for (m = 0; m < nn; m++) {
2267 comp = sk_SSL_COMP_value(sctx->comp_methods, m);
2268 v = comp->id;
2269 for (o = 0; o < clienthello->compressions_len; o++) {
2270 if (v == clienthello->compressions[o]) {
2271 done = 1;
2272 break;
2273 }
2274 }
2275 if (done)
2276 break;
2277 }
2278 if (done)
2279 s->s3.tmp.new_compression = comp;
2280 else
2281 comp = NULL;
2282 }
2283 #else
2284 /*
2285 * If compression is disabled we'd better not try to resume a session
2286 * using compression.
2287 */
2288 if (s->session->compress_meth != 0) {
2289 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);
2290 goto err;
2291 }
2292 #endif
2293
2294 /*
2295 * Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher
2296 */
2297
2298 if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {
2299 sk_SSL_CIPHER_free(s->peer_ciphers);
2300 s->peer_ciphers = ciphers;
2301 if (ciphers == NULL) {
2302 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2303 goto err;
2304 }
2305 ciphers = NULL;
2306 }
2307
2308 if (!s->hit) {
2309 #ifdef OPENSSL_NO_COMP
2310 s->session->compress_meth = 0;
2311 #else
2312 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
2313 #endif
2314 }
2315
2316 sk_SSL_CIPHER_free(ciphers);
2317 sk_SSL_CIPHER_free(scsvs);
2318 OPENSSL_free(clienthello->pre_proc_exts);
2319 OPENSSL_free(s->clienthello);
2320 s->clienthello = NULL;
2321 return 1;
2322 err:
2323 sk_SSL_CIPHER_free(ciphers);
2324 sk_SSL_CIPHER_free(scsvs);
2325 OPENSSL_free(clienthello->pre_proc_exts);
2326 OPENSSL_free(s->clienthello);
2327 s->clienthello = NULL;
2328
2329 return 0;
2330 }
2331
2332 /*
2333 * Call the status request callback if needed. Upon success, returns 1.
2334 * Upon failure, returns 0.
2335 */
2336 static int tls_handle_status_request(SSL_CONNECTION *s)
2337 {
2338 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2339
2340 s->ext.status_expected = 0;
2341
2342 /*
2343 * If status request then ask callback what to do. Note: this must be
2344 * called after servername callbacks in case the certificate has changed,
2345 * and must be called after the cipher has been chosen because this may
2346 * influence which certificate is sent
2347 */
2348 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && sctx != NULL
2349 && sctx->ext.status_cb != NULL) {
2350 int ret;
2351
2352 /* If no certificate can't return certificate status */
2353 if (s->s3.tmp.cert != NULL) {
2354 /*
2355 * Set current certificate to one we will use so SSL_get_certificate
2356 * et al can pick it up.
2357 */
2358 s->cert->key = s->s3.tmp.cert;
2359 ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),
2360 sctx->ext.status_arg);
2361 switch (ret) {
2362 /* We don't want to send a status request response */
2363 case SSL_TLSEXT_ERR_NOACK:
2364 s->ext.status_expected = 0;
2365 break;
2366 /* status request response should be sent */
2367 case SSL_TLSEXT_ERR_OK:
2368 #ifndef OPENSSL_NO_OCSP
2369 if (s->ext.ocsp.resp_ex != NULL
2370 && sk_OCSP_RESPONSE_num(s->ext.ocsp.resp_ex) > 0)
2371 s->ext.status_expected = 1;
2372 #endif
2373 break;
2374 /* something bad happened */
2375 case SSL_TLSEXT_ERR_ALERT_FATAL:
2376 default:
2377 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CLIENTHELLO_TLSEXT);
2378 return 0;
2379 }
2380 }
2381 }
2382
2383 return 1;
2384 }
2385
2386 /*
2387 * Call the alpn_select callback if needed. Upon success, returns 1.
2388 * Upon failure, returns 0.
2389 */
2390 int tls_handle_alpn(SSL_CONNECTION *s)
2391 {
2392 const unsigned char *selected = NULL;
2393 unsigned char selected_len = 0;
2394 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2395
2396 if (sctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {
2397 int r = sctx->ext.alpn_select_cb(SSL_CONNECTION_GET_USER_SSL(s),
2398 &selected, &selected_len,
2399 s->s3.alpn_proposed,
2400 (unsigned int)s->s3.alpn_proposed_len,
2401 sctx->ext.alpn_select_cb_arg);
2402
2403 if (r == SSL_TLSEXT_ERR_OK) {
2404 OPENSSL_free(s->s3.alpn_selected);
2405 s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);
2406 if (s->s3.alpn_selected == NULL) {
2407 s->s3.alpn_selected_len = 0;
2408 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2409 return 0;
2410 }
2411 s->s3.alpn_selected_len = selected_len;
2412 #ifndef OPENSSL_NO_NEXTPROTONEG
2413 /* ALPN takes precedence over NPN. */
2414 s->s3.npn_seen = 0;
2415 #endif
2416
2417 /* Check ALPN is consistent with session */
2418 if (s->session->ext.alpn_selected == NULL
2419 || selected_len != s->session->ext.alpn_selected_len
2420 || memcmp(selected, s->session->ext.alpn_selected,
2421 selected_len)
2422 != 0) {
2423 /* Not consistent so can't be used for early_data */
2424 s->ext.early_data_ok = 0;
2425
2426 if (!s->hit) {
2427 /*
2428 * This is a new session and so alpn_selected should have
2429 * been initialised to NULL. We should update it with the
2430 * selected ALPN.
2431 */
2432 if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
2433 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2434 ERR_R_INTERNAL_ERROR);
2435 return 0;
2436 }
2437 s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2438 selected_len);
2439 if (s->session->ext.alpn_selected == NULL) {
2440 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2441 ERR_R_INTERNAL_ERROR);
2442 return 0;
2443 }
2444 s->session->ext.alpn_selected_len = selected_len;
2445 }
2446 }
2447
2448 return 1;
2449 } else if (r != SSL_TLSEXT_ERR_NOACK) {
2450 SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL,
2451 SSL_R_NO_APPLICATION_PROTOCOL);
2452 return 0;
2453 }
2454 /*
2455 * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2456 * present.
2457 */
2458 }
2459
2460 /* Check ALPN is consistent with session */
2461 if (s->session->ext.alpn_selected != NULL) {
2462 /* Not consistent so can't be used for early_data */
2463 s->ext.early_data_ok = 0;
2464 }
2465
2466 return 1;
2467 }
2468
2469 WORK_STATE tls_post_process_client_hello(SSL_CONNECTION *s, WORK_STATE wst)
2470 {
2471 const SSL_CIPHER *cipher;
2472 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2473 SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
2474
2475 if (wst == WORK_MORE_A) {
2476 int rv = tls_early_post_process_client_hello(s);
2477
2478 if (rv == 0) {
2479 /* SSLfatal() was already called */
2480 goto err;
2481 }
2482 if (rv < 0)
2483 return WORK_MORE_A;
2484 wst = WORK_MORE_B;
2485 }
2486 if (wst == WORK_MORE_B) {
2487 if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {
2488 /* Let cert callback update server certificates if required */
2489 if (!s->hit && s->cert->cert_cb != NULL) {
2490 int rv = s->cert->cert_cb(ussl, s->cert->cert_cb_arg);
2491
2492 if (rv == 0) {
2493 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CERT_CB_ERROR);
2494 goto err;
2495 }
2496 if (rv < 0) {
2497 s->rwstate = SSL_X509_LOOKUP;
2498 return WORK_MORE_B;
2499 }
2500 s->rwstate = SSL_NOTHING;
2501 }
2502
2503 /* In TLSv1.3 we selected the ciphersuite before resumption */
2504 if (!SSL_CONNECTION_IS_TLS13(s)) {
2505 cipher = ssl3_choose_cipher(s, s->peer_ciphers,
2506 SSL_get_ciphers(ssl));
2507
2508 if (cipher == NULL) {
2509 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2510 SSL_R_NO_SHARED_CIPHER);
2511 goto err;
2512 }
2513 s->s3.tmp.new_cipher = cipher;
2514 }
2515 if (!s->hit) {
2516 if (!tls_choose_sigalg(s, 1)) {
2517 /* SSLfatal already called */
2518 goto err;
2519 }
2520 /* check whether we should disable session resumption */
2521 if (s->not_resumable_session_cb != NULL)
2522 s->session->not_resumable = s->not_resumable_session_cb(ussl,
2523 ((s->s3.tmp.new_cipher->algorithm_mkey
2524 & (SSL_kDHE | SSL_kECDHE))
2525 != 0));
2526 if (s->session->not_resumable)
2527 /* do not send a session ticket */
2528 s->ext.ticket_expected = 0;
2529 }
2530 } else {
2531 /* Session-id reuse */
2532 s->s3.tmp.new_cipher = s->session->cipher;
2533 }
2534
2535 /*-
2536 * we now have the following setup.
2537 * client_random
2538 * cipher_list - our preferred list of ciphers
2539 * ciphers - the client's preferred list of ciphers
2540 * compression - basically ignored right now
2541 * ssl version is set - sslv3
2542 * s->session - The ssl session has been setup.
2543 * s->hit - session reuse flag
2544 * s->s3.tmp.new_cipher - the new cipher to use.
2545 */
2546
2547 /*
2548 * Call status_request callback if needed. Has to be done after the
2549 * certificate callbacks etc above.
2550 */
2551 if (!tls_handle_status_request(s)) {
2552 /* SSLfatal() already called */
2553 goto err;
2554 }
2555 /*
2556 * Call alpn_select callback if needed. Has to be done after SNI and
2557 * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2558 * we already did this because cipher negotiation happens earlier, and
2559 * we must handle ALPN before we decide whether to accept early_data.
2560 */
2561 if (!SSL_CONNECTION_IS_TLS13(s) && !tls_handle_alpn(s)) {
2562 /* SSLfatal() already called */
2563 goto err;
2564 }
2565
2566 wst = WORK_MORE_C;
2567 }
2568 #ifndef OPENSSL_NO_SRP
2569 if (wst == WORK_MORE_C) {
2570 int ret;
2571 if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
2572 /*
2573 * callback indicates further work to be done
2574 */
2575 s->rwstate = SSL_X509_LOOKUP;
2576 return WORK_MORE_C;
2577 }
2578 if (ret < 0) {
2579 /* SSLfatal() already called */
2580 goto err;
2581 }
2582 }
2583 #endif
2584
2585 return WORK_FINISHED_STOP;
2586 err:
2587 return WORK_ERROR;
2588 }
2589
2590 CON_FUNC_RETURN tls_construct_server_hello(SSL_CONNECTION *s, WPACKET *pkt)
2591 {
2592 int compm;
2593 size_t sl, len;
2594 int version;
2595 unsigned char *session_id;
2596 int usetls13 = SSL_CONNECTION_IS_TLS13(s)
2597 || s->hello_retry_request == SSL_HRR_PENDING;
2598
2599 version = usetls13 ? TLS1_2_VERSION : s->version;
2600 if (!WPACKET_put_bytes_u16(pkt, version)
2601 /*
2602 * Random stuff. Filling of the server_random takes place in
2603 * tls_process_client_hello()
2604 */
2605 || !WPACKET_memcpy(pkt,
2606 s->hello_retry_request == SSL_HRR_PENDING
2607 ? hrrrandom
2608 : s->s3.server_random,
2609 SSL3_RANDOM_SIZE)) {
2610 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2611 return CON_FUNC_ERROR;
2612 }
2613
2614 /*-
2615 * There are several cases for the session ID to send
2616 * back in the server hello:
2617 * - For session reuse from the session cache,
2618 * we send back the old session ID.
2619 * - If stateless session reuse (using a session ticket)
2620 * is successful, we send back the client's "session ID"
2621 * (which doesn't actually identify the session).
2622 * - If it is a new session, we send back the new
2623 * session ID.
2624 * - However, if we want the new session to be single-use,
2625 * we send back a 0-length session ID.
2626 * - In TLSv1.3 we echo back the session id sent to us by the client
2627 * regardless
2628 * s->hit is non-zero in either case of session reuse,
2629 * so the following won't overwrite an ID that we're supposed
2630 * to send back.
2631 */
2632 if (!(SSL_CONNECTION_GET_CTX(s)->session_cache_mode & SSL_SESS_CACHE_SERVER)
2633 && !s->hit)
2634 s->session->session_id_length = 0;
2635
2636 if (usetls13) {
2637 sl = s->tmp_session_id_len;
2638 session_id = s->tmp_session_id;
2639 } else {
2640 sl = s->session->session_id_length;
2641 session_id = s->session->session_id;
2642 }
2643
2644 if (sl > sizeof(s->session->session_id)) {
2645 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2646 return CON_FUNC_ERROR;
2647 }
2648
2649 /* set up the compression method */
2650 #ifdef OPENSSL_NO_COMP
2651 compm = 0;
2652 #else
2653 if (usetls13 || s->s3.tmp.new_compression == NULL)
2654 compm = 0;
2655 else
2656 compm = s->s3.tmp.new_compression->id;
2657 #endif
2658
2659 if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
2660 || !SSL_CONNECTION_GET_SSL(s)->method->put_cipher_by_char(s->s3.tmp.new_cipher,
2661 pkt, &len)
2662 || !WPACKET_put_bytes_u8(pkt, compm)) {
2663 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2664 return CON_FUNC_ERROR;
2665 }
2666
2667 if (!tls_construct_extensions(s, pkt,
2668 s->hello_retry_request == SSL_HRR_PENDING
2669 ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
2670 : (SSL_CONNECTION_IS_TLS13(s)
2671 ? SSL_EXT_TLS1_3_SERVER_HELLO
2672 : SSL_EXT_TLS1_2_SERVER_HELLO),
2673 NULL, 0)) {
2674 /* SSLfatal() already called */
2675 return CON_FUNC_ERROR;
2676 }
2677
2678 if (s->hello_retry_request == SSL_HRR_PENDING) {
2679 /* Ditch the session. We'll create a new one next time around */
2680 SSL_SESSION_free(s->session);
2681 s->session = NULL;
2682 s->hit = 0;
2683
2684 /*
2685 * Re-initialise the Transcript Hash. We're going to prepopulate it with
2686 * a synthetic message_hash in place of ClientHello1.
2687 */
2688 if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
2689 /* SSLfatal() already called */
2690 return CON_FUNC_ERROR;
2691 }
2692 } else if (!(s->verify_mode & SSL_VERIFY_PEER)
2693 && !ssl3_digest_cached_records(s, 0)) {
2694 /* SSLfatal() already called */;
2695 return CON_FUNC_ERROR;
2696 }
2697
2698 return CON_FUNC_SUCCESS;
2699 }
2700
2701 CON_FUNC_RETURN tls_construct_server_done(SSL_CONNECTION *s, WPACKET *pkt)
2702 {
2703 if (!s->s3.tmp.cert_request) {
2704 if (!ssl3_digest_cached_records(s, 0)) {
2705 /* SSLfatal() already called */
2706 return CON_FUNC_ERROR;
2707 }
2708 }
2709 return CON_FUNC_SUCCESS;
2710 }
2711
2712 CON_FUNC_RETURN tls_construct_server_key_exchange(SSL_CONNECTION *s,
2713 WPACKET *pkt)
2714 {
2715 EVP_PKEY *pkdh = NULL;
2716 unsigned char *encodedPoint = NULL;
2717 size_t encodedlen = 0;
2718 int curve_id = 0;
2719 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
2720 int i;
2721 unsigned long type;
2722 BIGNUM *r[4];
2723 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2724 EVP_PKEY_CTX *pctx = NULL;
2725 size_t paramlen, paramoffset;
2726 int freer = 0;
2727 CON_FUNC_RETURN ret = CON_FUNC_ERROR;
2728 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2729
2730 if (!WPACKET_get_total_written(pkt, &paramoffset)) {
2731 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2732 goto err;
2733 }
2734
2735 if (md_ctx == NULL) {
2736 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2737 goto err;
2738 }
2739
2740 type = s->s3.tmp.new_cipher->algorithm_mkey;
2741
2742 r[0] = r[1] = r[2] = r[3] = NULL;
2743 #ifndef OPENSSL_NO_PSK
2744 /* Plain PSK or RSAPSK nothing to do */
2745 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2746 } else
2747 #endif /* !OPENSSL_NO_PSK */
2748 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2749 CERT *cert = s->cert;
2750 EVP_PKEY *pkdhp = NULL;
2751
2752 if (s->cert->dh_tmp_auto) {
2753 pkdh = ssl_get_auto_dh(s);
2754 if (pkdh == NULL) {
2755 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2756 goto err;
2757 }
2758 pkdhp = pkdh;
2759 } else {
2760 pkdhp = cert->dh_tmp;
2761 }
2762 #if !defined(OPENSSL_NO_DEPRECATED_3_0)
2763 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2764 pkdh = ssl_dh_to_pkey(s->cert->dh_tmp_cb(SSL_CONNECTION_GET_USER_SSL(s),
2765 0, 1024));
2766 if (pkdh == NULL) {
2767 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2768 goto err;
2769 }
2770 pkdhp = pkdh;
2771 }
2772 #endif
2773 if (pkdhp == NULL) {
2774 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
2775 goto err;
2776 }
2777 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2778 EVP_PKEY_get_security_bits(pkdhp), 0, pkdhp)) {
2779 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);
2780 goto err;
2781 }
2782 if (s->s3.tmp.pkey != NULL) {
2783 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2784 goto err;
2785 }
2786
2787 s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);
2788 if (s->s3.tmp.pkey == NULL) {
2789 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2790 goto err;
2791 }
2792
2793 EVP_PKEY_free(pkdh);
2794 pkdh = NULL;
2795
2796 /* These BIGNUMs need to be freed when we're finished */
2797 freer = 1;
2798 if (!EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_P,
2799 &r[0])
2800 || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_G,
2801 &r[1])
2802 || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey,
2803 OSSL_PKEY_PARAM_PUB_KEY, &r[2])) {
2804 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2805 goto err;
2806 }
2807 } else if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2808
2809 if (s->s3.tmp.pkey != NULL) {
2810 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2811 goto err;
2812 }
2813
2814 /* Get NID of appropriate shared curve */
2815 curve_id = tls1_shared_group(s, -2);
2816 if (curve_id == 0) {
2817 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2818 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2819 goto err;
2820 }
2821 /* Cache the group used in the SSL_SESSION */
2822 s->session->kex_group = curve_id;
2823 /* Generate a new key for this curve */
2824 s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);
2825 if (s->s3.tmp.pkey == NULL) {
2826 /* SSLfatal() already called */
2827 goto err;
2828 }
2829
2830 /* Encode the public key. */
2831 encodedlen = EVP_PKEY_get1_encoded_public_key(s->s3.tmp.pkey,
2832 &encodedPoint);
2833 if (encodedlen == 0) {
2834 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
2835 goto err;
2836 }
2837
2838 /*
2839 * We'll generate the serverKeyExchange message explicitly so we
2840 * can set these to NULLs
2841 */
2842 r[0] = NULL;
2843 r[1] = NULL;
2844 r[2] = NULL;
2845 r[3] = NULL;
2846 } else
2847 #ifndef OPENSSL_NO_SRP
2848 if (type & SSL_kSRP) {
2849 if ((s->srp_ctx.N == NULL) || (s->srp_ctx.g == NULL) || (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2850 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_SRP_PARAM);
2851 goto err;
2852 }
2853 r[0] = s->srp_ctx.N;
2854 r[1] = s->srp_ctx.g;
2855 r[2] = s->srp_ctx.s;
2856 r[3] = s->srp_ctx.B;
2857 } else
2858 #endif
2859 {
2860 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2861 goto err;
2862 }
2863
2864 if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2865 || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2866 lu = NULL;
2867 } else if (lu == NULL) {
2868 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
2869 goto err;
2870 }
2871
2872 #ifndef OPENSSL_NO_PSK
2873 if (type & SSL_PSK) {
2874 size_t len = (s->cert->psk_identity_hint == NULL)
2875 ? 0
2876 : strlen(s->cert->psk_identity_hint);
2877
2878 /*
2879 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2880 * checked this when we set the identity hint - but just in case
2881 */
2882 if (len > PSK_MAX_IDENTITY_LEN
2883 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2884 len)) {
2885 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2886 goto err;
2887 }
2888 }
2889 #endif
2890
2891 for (i = 0; i < 4 && r[i] != NULL; i++) {
2892 unsigned char *binval;
2893 int res;
2894
2895 #ifndef OPENSSL_NO_SRP
2896 if ((i == 2) && (type & SSL_kSRP)) {
2897 res = WPACKET_start_sub_packet_u8(pkt);
2898 } else
2899 #endif
2900 res = WPACKET_start_sub_packet_u16(pkt);
2901
2902 if (!res) {
2903 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2904 goto err;
2905 }
2906
2907 /*-
2908 * for interoperability with some versions of the Microsoft TLS
2909 * stack, we need to zero pad the DHE pub key to the same length
2910 * as the prime
2911 */
2912 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2913 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2914
2915 if (len > 0) {
2916 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2917 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2918 goto err;
2919 }
2920 memset(binval, 0, len);
2921 }
2922 }
2923
2924 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2925 || !WPACKET_close(pkt)) {
2926 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2927 goto err;
2928 }
2929
2930 BN_bn2bin(r[i], binval);
2931 }
2932
2933 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2934 /*
2935 * We only support named (not generic) curves. In this situation, the
2936 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2937 * [1 byte length of encoded point], followed by the actual encoded
2938 * point itself
2939 */
2940 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2941 || !WPACKET_put_bytes_u8(pkt, 0)
2942 || !WPACKET_put_bytes_u8(pkt, curve_id)
2943 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2944 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2945 goto err;
2946 }
2947 OPENSSL_free(encodedPoint);
2948 encodedPoint = NULL;
2949 }
2950
2951 /* not anonymous */
2952 if (lu != NULL) {
2953 EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;
2954 const EVP_MD *md;
2955 unsigned char *sigbytes1, *sigbytes2, *tbs;
2956 size_t siglen = 0, tbslen;
2957
2958 if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
2959 /* Should never happen */
2960 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2961 goto err;
2962 }
2963 /* Get length of the parameters we have written above */
2964 if (!WPACKET_get_length(pkt, &paramlen)) {
2965 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2966 goto err;
2967 }
2968 /* send signature algorithm */
2969 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2970 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2971 goto err;
2972 }
2973
2974 if (EVP_DigestSignInit_ex(md_ctx, &pctx,
2975 md == NULL ? NULL : EVP_MD_get0_name(md),
2976 sctx->libctx, sctx->propq, pkey,
2977 NULL)
2978 <= 0) {
2979 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2980 goto err;
2981 }
2982 if (lu->sig == EVP_PKEY_RSA_PSS) {
2983 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2984 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2985 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2986 goto err;
2987 }
2988 }
2989 tbslen = construct_key_exchange_tbs(s, &tbs,
2990 s->init_buf->data + paramoffset,
2991 paramlen);
2992 if (tbslen == 0) {
2993 /* SSLfatal() already called */
2994 goto err;
2995 }
2996
2997 if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <= 0
2998 || !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2999 || EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 0
3000 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
3001 || sigbytes1 != sigbytes2) {
3002 OPENSSL_free(tbs);
3003 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3004 goto err;
3005 }
3006 OPENSSL_free(tbs);
3007 }
3008
3009 ret = CON_FUNC_SUCCESS;
3010 err:
3011 EVP_PKEY_free(pkdh);
3012 OPENSSL_free(encodedPoint);
3013 EVP_MD_CTX_free(md_ctx);
3014 if (freer) {
3015 BN_free(r[0]);
3016 BN_free(r[1]);
3017 BN_free(r[2]);
3018 BN_free(r[3]);
3019 }
3020 return ret;
3021 }
3022
3023 CON_FUNC_RETURN tls_construct_certificate_request(SSL_CONNECTION *s,
3024 WPACKET *pkt)
3025 {
3026 if (SSL_CONNECTION_IS_TLS13(s)) {
3027 /* Send random context when doing post-handshake auth */
3028 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
3029 OPENSSL_free(s->pha_context);
3030 s->pha_context_len = 32;
3031 if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL) {
3032 s->pha_context_len = 0;
3033 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3034 return CON_FUNC_ERROR;
3035 }
3036 if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
3037 s->pha_context, s->pha_context_len, 0)
3038 <= 0
3039 || !WPACKET_sub_memcpy_u8(pkt, s->pha_context,
3040 s->pha_context_len)) {
3041 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3042 return CON_FUNC_ERROR;
3043 }
3044 /* reset the handshake hash back to just after the ClientFinished */
3045 if (!tls13_restore_handshake_digest_for_pha(s)) {
3046 /* SSLfatal() already called */
3047 return CON_FUNC_ERROR;
3048 }
3049 } else {
3050 if (!WPACKET_put_bytes_u8(pkt, 0)) {
3051 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3052 return CON_FUNC_ERROR;
3053 }
3054 }
3055
3056 if (!tls_construct_extensions(s, pkt,
3057 SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
3058 0)) {
3059 /* SSLfatal() already called */
3060 return CON_FUNC_ERROR;
3061 }
3062 goto done;
3063 }
3064
3065 /* get the list of acceptable cert types */
3066 if (!WPACKET_start_sub_packet_u8(pkt)
3067 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
3068 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3069 return CON_FUNC_ERROR;
3070 }
3071
3072 if (SSL_USE_SIGALGS(s)) {
3073 const uint16_t *psigs;
3074 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
3075
3076 if (!WPACKET_start_sub_packet_u16(pkt)
3077 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
3078 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
3079 || !WPACKET_close(pkt)) {
3080 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3081 return CON_FUNC_ERROR;
3082 }
3083 }
3084
3085 if (!construct_ca_names(s, get_ca_names(s), pkt)) {
3086 /* SSLfatal() already called */
3087 return CON_FUNC_ERROR;
3088 }
3089
3090 done:
3091 s->certreqs_sent++;
3092 s->s3.tmp.cert_request = 1;
3093 return CON_FUNC_SUCCESS;
3094 }
3095
3096 static int tls_process_cke_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)
3097 {
3098 #ifndef OPENSSL_NO_PSK
3099 unsigned char psk[PSK_MAX_PSK_LEN];
3100 size_t psklen;
3101 PACKET psk_identity;
3102
3103 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
3104 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3105 return 0;
3106 }
3107 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
3108 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DATA_LENGTH_TOO_LONG);
3109 return 0;
3110 }
3111 if (s->psk_server_callback == NULL) {
3112 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_SERVER_CB);
3113 return 0;
3114 }
3115
3116 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
3117 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3118 return 0;
3119 }
3120
3121 psklen = s->psk_server_callback(SSL_CONNECTION_GET_USER_SSL(s),
3122 s->session->psk_identity,
3123 psk, sizeof(psk));
3124
3125 if (psklen > PSK_MAX_PSK_LEN) {
3126 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3127 return 0;
3128 } else if (psklen == 0) {
3129 /*
3130 * PSK related to the given identity not found
3131 */
3132 SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_R_PSK_IDENTITY_NOT_FOUND);
3133 return 0;
3134 }
3135
3136 OPENSSL_free(s->s3.tmp.psk);
3137 s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);
3138 OPENSSL_cleanse(psk, psklen);
3139
3140 if (s->s3.tmp.psk == NULL) {
3141 s->s3.tmp.psklen = 0;
3142 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3143 return 0;
3144 }
3145
3146 s->s3.tmp.psklen = psklen;
3147
3148 return 1;
3149 #else
3150 /* Should never happen */
3151 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3152 return 0;
3153 #endif
3154 }
3155
3156 static int tls_process_cke_rsa(SSL_CONNECTION *s, PACKET *pkt)
3157 {
3158 size_t outlen;
3159 PACKET enc_premaster;
3160 EVP_PKEY *rsa = NULL;
3161 unsigned char *rsa_decrypt = NULL;
3162 int ret = 0;
3163 EVP_PKEY_CTX *ctx = NULL;
3164 OSSL_PARAM params[3], *p = params;
3165 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3166
3167 rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
3168 if (rsa == NULL) {
3169 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_RSA_CERTIFICATE);
3170 return 0;
3171 }
3172
3173 /* SSLv3 and pre-standard DTLS omit the length bytes. */
3174 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
3175 enc_premaster = *pkt;
3176 } else {
3177 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
3178 || PACKET_remaining(pkt) != 0) {
3179 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3180 return 0;
3181 }
3182 }
3183
3184 outlen = SSL_MAX_MASTER_KEY_LENGTH;
3185 rsa_decrypt = OPENSSL_malloc(outlen);
3186 if (rsa_decrypt == NULL) {
3187 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3188 return 0;
3189 }
3190
3191 ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, rsa, sctx->propq);
3192 if (ctx == NULL) {
3193 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3194 goto err;
3195 }
3196
3197 /*
3198 * We must not leak whether a decryption failure occurs because of
3199 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
3200 * section 7.4.7.1). We use the special padding type
3201 * RSA_PKCS1_WITH_TLS_PADDING to do that. It will automatically decrypt the
3202 * RSA, check the padding and check that the client version is as expected
3203 * in the premaster secret. If any of that fails then the function appears
3204 * to return successfully but with a random result. The call below could
3205 * still fail if the input is publicly invalid.
3206 * See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
3207 */
3208 if (EVP_PKEY_decrypt_init(ctx) <= 0
3209 || EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {
3210 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3211 goto err;
3212 }
3213
3214 *p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,
3215 (unsigned int *)&s->client_version);
3216 if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)
3217 *p++ = OSSL_PARAM_construct_uint(
3218 OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,
3219 (unsigned int *)&s->version);
3220 *p++ = OSSL_PARAM_construct_end();
3221
3222 if (!EVP_PKEY_CTX_set_params(ctx, params)
3223 || EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,
3224 PACKET_data(&enc_premaster),
3225 PACKET_remaining(&enc_premaster))
3226 <= 0) {
3227 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3228 goto err;
3229 }
3230
3231 /*
3232 * This test should never fail (otherwise we should have failed above) but
3233 * we double check anyway.
3234 */
3235 if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {
3236 OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);
3237 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3238 goto err;
3239 }
3240
3241 /* Also cleanses rsa_decrypt (on success or failure) */
3242 if (!ssl_generate_master_secret(s, rsa_decrypt, outlen, 0)) {
3243 /* SSLfatal() already called */
3244 goto err;
3245 }
3246
3247 ret = 1;
3248 err:
3249 OPENSSL_free(rsa_decrypt);
3250 EVP_PKEY_CTX_free(ctx);
3251 return ret;
3252 }
3253
3254 static int tls_process_cke_dhe(SSL_CONNECTION *s, PACKET *pkt)
3255 {
3256 EVP_PKEY *skey = NULL;
3257 unsigned int i;
3258 const unsigned char *data;
3259 EVP_PKEY *ckey = NULL;
3260 int ret = 0;
3261
3262 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
3263 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
3264 goto err;
3265 }
3266 skey = s->s3.tmp.pkey;
3267 if (skey == NULL) {
3268 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
3269 goto err;
3270 }
3271
3272 if (PACKET_remaining(pkt) == 0L) {
3273 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_MISSING_TMP_DH_KEY);
3274 goto err;
3275 }
3276 if (!PACKET_get_bytes(pkt, &data, i)) {
3277 /* We already checked we have enough data */
3278 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3279 goto err;
3280 }
3281 ckey = EVP_PKEY_new();
3282 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
3283 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3284 goto err;
3285 }
3286
3287 if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3288 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
3289 goto err;
3290 }
3291
3292 if (ssl_derive(s, skey, ckey, 1) == 0) {
3293 /* SSLfatal() already called */
3294 goto err;
3295 }
3296
3297 ret = 1;
3298 EVP_PKEY_free(s->s3.tmp.pkey);
3299 s->s3.tmp.pkey = NULL;
3300 err:
3301 EVP_PKEY_free(ckey);
3302 return ret;
3303 }
3304
3305 static int tls_process_cke_ecdhe(SSL_CONNECTION *s, PACKET *pkt)
3306 {
3307 EVP_PKEY *skey = s->s3.tmp.pkey;
3308 EVP_PKEY *ckey = NULL;
3309 int ret = 0;
3310
3311 if (PACKET_remaining(pkt) == 0L) {
3312 /* We don't support ECDH client auth */
3313 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_TMP_ECDH_KEY);
3314 goto err;
3315 } else {
3316 unsigned int i;
3317 const unsigned char *data;
3318
3319 /*
3320 * Get client's public key from encoded point in the
3321 * ClientKeyExchange message.
3322 */
3323
3324 /*
3325 * Get encoded point length
3326 * empty key should be handled here
3327 */
3328 if (!PACKET_get_1(pkt, &i) || i == 0 || !PACKET_get_bytes(pkt, &data, i)
3329 || PACKET_remaining(pkt) != 0) {
3330 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3331 goto err;
3332 }
3333 if (skey == NULL) {
3334 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_ECDH_KEY);
3335 goto err;
3336 }
3337
3338 ckey = EVP_PKEY_new();
3339 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3340 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3341 goto err;
3342 }
3343
3344 if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3345 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
3346 goto err;
3347 }
3348 }
3349
3350 if (ssl_derive(s, skey, ckey, 1) == 0) {
3351 /* SSLfatal() already called */
3352 goto err;
3353 }
3354
3355 ret = 1;
3356 EVP_PKEY_free(s->s3.tmp.pkey);
3357 s->s3.tmp.pkey = NULL;
3358 err:
3359 EVP_PKEY_free(ckey);
3360
3361 return ret;
3362 }
3363
3364 static int tls_process_cke_srp(SSL_CONNECTION *s, PACKET *pkt)
3365 {
3366 #ifndef OPENSSL_NO_SRP
3367 unsigned int i;
3368 const unsigned char *data;
3369
3370 if (!PACKET_get_net_2(pkt, &i)
3371 || !PACKET_get_bytes(pkt, &data, i)) {
3372 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRP_A_LENGTH);
3373 return 0;
3374 }
3375 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3376 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
3377 return 0;
3378 }
3379 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3380 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRP_PARAMETERS);
3381 return 0;
3382 }
3383 OPENSSL_free(s->session->srp_username);
3384 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3385 if (s->session->srp_username == NULL) {
3386 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3387 return 0;
3388 }
3389
3390 if (!srp_generate_server_master_secret(s)) {
3391 /* SSLfatal() already called */
3392 return 0;
3393 }
3394
3395 return 1;
3396 #else
3397 /* Should never happen */
3398 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3399 return 0;
3400 #endif
3401 }
3402
3403 static int tls_process_cke_gost(SSL_CONNECTION *s, PACKET *pkt)
3404 {
3405 #ifndef OPENSSL_NO_GOST
3406 EVP_PKEY_CTX *pkey_ctx;
3407 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3408 unsigned char premaster_secret[32];
3409 const unsigned char *start;
3410 size_t outlen = sizeof(premaster_secret), inlen;
3411 unsigned long alg_a;
3412 GOST_KX_MESSAGE *pKX = NULL;
3413 const unsigned char *ptr;
3414 int ret = 0;
3415 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3416
3417 /* Get our certificate private key */
3418 alg_a = s->s3.tmp.new_cipher->algorithm_auth;
3419 if (alg_a & SSL_aGOST12) {
3420 /*
3421 * New GOST ciphersuites have SSL_aGOST01 bit too
3422 */
3423 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3424 if (pk == NULL) {
3425 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3426 }
3427 if (pk == NULL) {
3428 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3429 }
3430 } else if (alg_a & SSL_aGOST01) {
3431 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3432 }
3433
3434 pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);
3435 if (pkey_ctx == NULL) {
3436 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3437 return 0;
3438 }
3439 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3440 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3441 goto err;
3442 }
3443 /*
3444 * If client certificate is present and is of the same type, maybe
3445 * use it for key exchange. Don't mind errors from
3446 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3447 * client certificate for authorization only.
3448 */
3449 client_pub_pkey = tls_get_peer_pkey(s);
3450 if (client_pub_pkey) {
3451 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3452 ERR_clear_error();
3453 }
3454
3455 ptr = PACKET_data(pkt);
3456 /* Some implementations provide extra data in the opaqueBlob
3457 * We have nothing to do with this blob so we just skip it */
3458 pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, (long)PACKET_remaining(pkt));
3459 if (pKX == NULL
3460 || pKX->kxBlob == NULL
3461 || ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {
3462 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3463 goto err;
3464 }
3465
3466 if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {
3467 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3468 goto err;
3469 }
3470
3471 if (PACKET_remaining(pkt) != 0) {
3472 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3473 goto err;
3474 }
3475
3476 inlen = pKX->kxBlob->value.sequence->length;
3477 start = pKX->kxBlob->value.sequence->data;
3478
3479 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3480 inlen)
3481 <= 0) {
3482 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3483 goto err;
3484 }
3485 /* Generate master secret */
3486 if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {
3487 /* SSLfatal() already called */
3488 goto err;
3489 }
3490 /* Check if pubkey from client certificate was used */
3491 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3492 NULL)
3493 > 0)
3494 s->statem.no_cert_verify = 1;
3495
3496 ret = 1;
3497 err:
3498 EVP_PKEY_CTX_free(pkey_ctx);
3499 GOST_KX_MESSAGE_free(pKX);
3500 return ret;
3501 #else
3502 /* Should never happen */
3503 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3504 return 0;
3505 #endif
3506 }
3507
3508 static int tls_process_cke_gost18(SSL_CONNECTION *s, PACKET *pkt)
3509 {
3510 #ifndef OPENSSL_NO_GOST
3511 unsigned char rnd_dgst[32];
3512 EVP_PKEY_CTX *pkey_ctx = NULL;
3513 EVP_PKEY *pk = NULL;
3514 unsigned char premaster_secret[32];
3515 const unsigned char *start = NULL;
3516 size_t outlen = sizeof(premaster_secret), inlen = 0;
3517 int ret = 0;
3518 int cipher_nid = ossl_gost18_cke_cipher_nid(s);
3519 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3520
3521 if (cipher_nid == NID_undef) {
3522 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3523 return 0;
3524 }
3525
3526 if (ossl_gost_ukm(s, rnd_dgst) <= 0) {
3527 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3528 goto err;
3529 }
3530
3531 /* Get our certificate private key */
3532 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey != NULL ? s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey : s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3533 if (pk == NULL) {
3534 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
3535 goto err;
3536 }
3537
3538 pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);
3539 if (pkey_ctx == NULL) {
3540 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3541 goto err;
3542 }
3543 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3544 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3545 goto err;
3546 }
3547
3548 /* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code depending on size */
3549 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3550 EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst)
3551 <= 0) {
3552 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3553 goto err;
3554 }
3555
3556 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3557 EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL)
3558 <= 0) {
3559 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3560 goto err;
3561 }
3562 inlen = PACKET_remaining(pkt);
3563 start = PACKET_data(pkt);
3564
3565 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3566 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3567 goto err;
3568 }
3569 /* Generate master secret */
3570 if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {
3571 /* SSLfatal() already called */
3572 goto err;
3573 }
3574 ret = 1;
3575
3576 err:
3577 EVP_PKEY_CTX_free(pkey_ctx);
3578 return ret;
3579 #else
3580 /* Should never happen */
3581 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3582 return 0;
3583 #endif
3584 }
3585
3586 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL_CONNECTION *s,
3587 PACKET *pkt)
3588 {
3589 unsigned long alg_k;
3590
3591 alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3592
3593 /* For PSK parse and retrieve identity, obtain PSK key */
3594 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3595 /* SSLfatal() already called */
3596 goto err;
3597 }
3598
3599 if (alg_k & SSL_kPSK) {
3600 /* Identity extracted earlier: should be nothing left */
3601 if (PACKET_remaining(pkt) != 0) {
3602 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3603 goto err;
3604 }
3605 /* PSK handled by ssl_generate_master_secret */
3606 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3607 /* SSLfatal() already called */
3608 goto err;
3609 }
3610 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3611 if (!tls_process_cke_rsa(s, pkt)) {
3612 /* SSLfatal() already called */
3613 goto err;
3614 }
3615 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3616 if (!tls_process_cke_dhe(s, pkt)) {
3617 /* SSLfatal() already called */
3618 goto err;
3619 }
3620 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3621 if (!tls_process_cke_ecdhe(s, pkt)) {
3622 /* SSLfatal() already called */
3623 goto err;
3624 }
3625 } else if (alg_k & SSL_kSRP) {
3626 if (!tls_process_cke_srp(s, pkt)) {
3627 /* SSLfatal() already called */
3628 goto err;
3629 }
3630 } else if (alg_k & SSL_kGOST) {
3631 if (!tls_process_cke_gost(s, pkt)) {
3632 /* SSLfatal() already called */
3633 goto err;
3634 }
3635 } else if (alg_k & SSL_kGOST18) {
3636 if (!tls_process_cke_gost18(s, pkt)) {
3637 /* SSLfatal() already called */
3638 goto err;
3639 }
3640 } else {
3641 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
3642 goto err;
3643 }
3644
3645 return MSG_PROCESS_CONTINUE_PROCESSING;
3646 err:
3647 #ifndef OPENSSL_NO_PSK
3648 OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3649 s->s3.tmp.psk = NULL;
3650 s->s3.tmp.psklen = 0;
3651 #endif
3652 return MSG_PROCESS_ERROR;
3653 }
3654
3655 WORK_STATE tls_post_process_client_key_exchange(SSL_CONNECTION *s,
3656 WORK_STATE wst)
3657 {
3658 #ifndef OPENSSL_NO_SCTP
3659 if (wst == WORK_MORE_A) {
3660 if (SSL_CONNECTION_IS_DTLS(s)) {
3661 unsigned char sctpauthkey[64];
3662 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3663 size_t labellen;
3664 /*
3665 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3666 * used.
3667 */
3668 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3669 sizeof(DTLS1_SCTP_AUTH_LABEL));
3670
3671 /* Don't include the terminating zero. */
3672 labellen = sizeof(labelbuffer) - 1;
3673 if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3674 labellen += 1;
3675
3676 if (SSL_export_keying_material(SSL_CONNECTION_GET_SSL(s),
3677 sctpauthkey,
3678 sizeof(sctpauthkey), labelbuffer,
3679 labellen, NULL, 0,
3680 0)
3681 <= 0) {
3682 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3683 return WORK_ERROR;
3684 }
3685
3686 BIO_ctrl(s->wbio, BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3687 sizeof(sctpauthkey), sctpauthkey);
3688 }
3689 }
3690 #endif
3691
3692 if (s->statem.no_cert_verify || !received_client_cert(s)) {
3693 /*
3694 * No certificate verify or no peer certificate so we no longer need
3695 * the handshake_buffer
3696 */
3697 if (!ssl3_digest_cached_records(s, 0)) {
3698 /* SSLfatal() already called */
3699 return WORK_ERROR;
3700 }
3701 return WORK_FINISHED_CONTINUE;
3702 } else {
3703 if (!s->s3.handshake_buffer) {
3704 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3705 return WORK_ERROR;
3706 }
3707 /*
3708 * For sigalgs freeze the handshake buffer. If we support
3709 * extms we've done this already so this is a no-op
3710 */
3711 if (!ssl3_digest_cached_records(s, 1)) {
3712 /* SSLfatal() already called */
3713 return WORK_ERROR;
3714 }
3715 }
3716
3717 return WORK_FINISHED_CONTINUE;
3718 }
3719
3720 MSG_PROCESS_RETURN tls_process_client_rpk(SSL_CONNECTION *sc, PACKET *pkt)
3721 {
3722 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3723 SSL_SESSION *new_sess = NULL;
3724 EVP_PKEY *peer_rpk = NULL;
3725
3726 if (!tls_process_rpk(sc, pkt, &peer_rpk)) {
3727 /* SSLfatal already called */
3728 goto err;
3729 }
3730
3731 if (peer_rpk == NULL) {
3732 if ((sc->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
3733 && (sc->verify_mode & SSL_VERIFY_PEER)) {
3734 SSLfatal(sc, SSL_AD_CERTIFICATE_REQUIRED,
3735 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3736 goto err;
3737 }
3738 } else {
3739 if (ssl_verify_rpk(sc, peer_rpk) <= 0) {
3740 SSLfatal(sc, ssl_x509err2alert(sc->verify_result),
3741 SSL_R_CERTIFICATE_VERIFY_FAILED);
3742 goto err;
3743 }
3744 }
3745
3746 /*
3747 * Sessions must be immutable once they go into the session cache. Otherwise
3748 * we can get multi-thread problems. Therefore we don't "update" sessions,
3749 * we replace them with a duplicate. Here, we need to do this every time
3750 * a new RPK (or certificate) is received via post-handshake authentication,
3751 * as the session may have already gone into the session cache.
3752 */
3753
3754 if (sc->post_handshake_auth == SSL_PHA_REQUESTED) {
3755 if ((new_sess = ssl_session_dup(sc->session, 0)) == NULL) {
3756 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3757 goto err;
3758 }
3759
3760 SSL_SESSION_free(sc->session);
3761 sc->session = new_sess;
3762 }
3763
3764 /* Ensure there is no peer/peer_chain */
3765 X509_free(sc->session->peer);
3766 sc->session->peer = NULL;
3767 sk_X509_pop_free(sc->session->peer_chain, X509_free);
3768 sc->session->peer_chain = NULL;
3769 /* Save RPK */
3770 EVP_PKEY_free(sc->session->peer_rpk);
3771 sc->session->peer_rpk = peer_rpk;
3772 peer_rpk = NULL;
3773
3774 sc->session->verify_result = sc->verify_result;
3775
3776 /*
3777 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3778 * message
3779 */
3780 if (SSL_CONNECTION_IS_TLS13(sc)) {
3781 if (!ssl3_digest_cached_records(sc, 1)) {
3782 /* SSLfatal() already called */
3783 goto err;
3784 }
3785
3786 /* Save the current hash state for when we receive the CertificateVerify */
3787 if (!ssl_handshake_hash(sc, sc->cert_verify_hash,
3788 sizeof(sc->cert_verify_hash),
3789 &sc->cert_verify_hash_len)) {
3790 /* SSLfatal() already called */;
3791 goto err;
3792 }
3793
3794 /* resend session tickets */
3795 sc->sent_tickets = 0;
3796 }
3797
3798 ret = MSG_PROCESS_CONTINUE_READING;
3799
3800 err:
3801 EVP_PKEY_free(peer_rpk);
3802 return ret;
3803 }
3804
3805 MSG_PROCESS_RETURN tls_process_client_certificate(SSL_CONNECTION *s,
3806 PACKET *pkt)
3807 {
3808 int i;
3809 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3810 X509 *x = NULL;
3811 unsigned long l;
3812 const unsigned char *certstart, *certbytes;
3813 STACK_OF(X509) *sk = NULL;
3814 PACKET spkt, context;
3815 size_t chainidx;
3816 SSL_SESSION *new_sess = NULL;
3817 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3818
3819 /*
3820 * To get this far we must have read encrypted data from the client. We no
3821 * longer tolerate unencrypted alerts. This is ignored if less than TLSv1.3
3822 */
3823 if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
3824 s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
3825
3826 if (s->ext.client_cert_type == TLSEXT_cert_type_rpk)
3827 return tls_process_client_rpk(s, pkt);
3828
3829 if (s->ext.client_cert_type != TLSEXT_cert_type_x509) {
3830 SSLfatal(s, SSL_AD_UNSUPPORTED_CERTIFICATE,
3831 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3832 goto err;
3833 }
3834
3835 if ((sk = sk_X509_new_null()) == NULL) {
3836 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3837 goto err;
3838 }
3839
3840 if (SSL_CONNECTION_IS_TLS13(s)
3841 && (!PACKET_get_length_prefixed_1(pkt, &context)
3842 || (s->pha_context == NULL && PACKET_remaining(&context) != 0)
3843 || (s->pha_context != NULL
3844 && !PACKET_equal(&context, s->pha_context,
3845 s->pha_context_len)))) {
3846 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
3847 goto err;
3848 }
3849
3850 if (!PACKET_get_length_prefixed_3(pkt, &spkt)
3851 || PACKET_remaining(pkt) != 0) {
3852 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3853 goto err;
3854 }
3855
3856 for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3857 if (!PACKET_get_net_3(&spkt, &l)
3858 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3859 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
3860 goto err;
3861 }
3862
3863 certstart = certbytes;
3864 x = X509_new_ex(sctx->libctx, sctx->propq);
3865 if (x == NULL) {
3866 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_X509_LIB);
3867 goto err;
3868 }
3869 if (d2i_X509(&x, (const unsigned char **)&certbytes, l) == NULL) {
3870 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
3871 goto err;
3872 }
3873
3874 if (certbytes != (certstart + l)) {
3875 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
3876 goto err;
3877 }
3878
3879 if (SSL_CONNECTION_IS_TLS13(s)) {
3880 RAW_EXTENSION *rawexts = NULL;
3881 PACKET extensions;
3882
3883 if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3884 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
3885 goto err;
3886 }
3887 if (!tls_collect_extensions(s, &extensions,
3888 SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3889 NULL, chainidx == 0)
3890 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3891 rawexts, x, chainidx,
3892 PACKET_remaining(&spkt) == 0)) {
3893 OPENSSL_free(rawexts);
3894 goto err;
3895 }
3896 OPENSSL_free(rawexts);
3897 }
3898
3899 if (!sk_X509_push(sk, x)) {
3900 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3901 goto err;
3902 }
3903 x = NULL;
3904 }
3905
3906 if (sk_X509_num(sk) <= 0) {
3907 /* TLS does not mind 0 certs returned */
3908 if (s->version == SSL3_VERSION) {
3909 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3910 SSL_R_NO_CERTIFICATES_RETURNED);
3911 goto err;
3912 }
3913 /* Fail for TLS only if we required a certificate */
3914 else if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3915 SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
3916 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3917 goto err;
3918 }
3919 /* No client certificate so digest cached records */
3920 if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3921 /* SSLfatal() already called */
3922 goto err;
3923 }
3924 } else {
3925 EVP_PKEY *pkey;
3926 i = ssl_verify_cert_chain(s, sk);
3927 if (i <= 0) {
3928 SSLfatal(s, ssl_x509err2alert(s->verify_result),
3929 SSL_R_CERTIFICATE_VERIFY_FAILED);
3930 goto err;
3931 }
3932 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3933 if (pkey == NULL) {
3934 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3935 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3936 goto err;
3937 }
3938 }
3939
3940 /*
3941 * Sessions must be immutable once they go into the session cache. Otherwise
3942 * we can get multi-thread problems. Therefore we don't "update" sessions,
3943 * we replace them with a duplicate. Here, we need to do this every time
3944 * a new certificate is received via post-handshake authentication, as the
3945 * session may have already gone into the session cache.
3946 */
3947
3948 if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
3949 if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
3950 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
3951 goto err;
3952 }
3953
3954 SSL_SESSION_free(s->session);
3955 s->session = new_sess;
3956 }
3957
3958 X509_free(s->session->peer);
3959 s->session->peer = sk_X509_shift(sk);
3960 s->session->verify_result = s->verify_result;
3961
3962 OSSL_STACK_OF_X509_free(s->session->peer_chain);
3963 s->session->peer_chain = sk;
3964 sk = NULL;
3965 /* Ensure there is no RPK */
3966 EVP_PKEY_free(s->session->peer_rpk);
3967 s->session->peer_rpk = NULL;
3968
3969 /*
3970 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3971 * message
3972 */
3973 if (SSL_CONNECTION_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3974 /* SSLfatal() already called */
3975 goto err;
3976 }
3977
3978 /*
3979 * Inconsistency alert: cert_chain does *not* include the peer's own
3980 * certificate, while we do include it in statem_clnt.c
3981 */
3982
3983 /* Save the current hash state for when we receive the CertificateVerify */
3984 if (SSL_CONNECTION_IS_TLS13(s)) {
3985 if (!ssl_handshake_hash(s, s->cert_verify_hash,
3986 sizeof(s->cert_verify_hash),
3987 &s->cert_verify_hash_len)) {
3988 /* SSLfatal() already called */
3989 goto err;
3990 }
3991
3992 /* Resend session tickets */
3993 s->sent_tickets = 0;
3994 }
3995
3996 ret = MSG_PROCESS_CONTINUE_READING;
3997
3998 err:
3999 X509_free(x);
4000 OSSL_STACK_OF_X509_free(sk);
4001 return ret;
4002 }
4003
4004 #ifndef OPENSSL_NO_COMP_ALG
4005 MSG_PROCESS_RETURN tls_process_client_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)
4006 {
4007 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
4008 PACKET tmppkt;
4009 BUF_MEM *buf = BUF_MEM_new();
4010
4011 if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)
4012 ret = tls_process_client_certificate(sc, &tmppkt);
4013
4014 BUF_MEM_free(buf);
4015 return ret;
4016 }
4017 #endif
4018
4019 CON_FUNC_RETURN tls_construct_server_certificate(SSL_CONNECTION *s, WPACKET *pkt)
4020 {
4021 CERT_PKEY *cpk = s->s3.tmp.cert;
4022
4023 if (cpk == NULL) {
4024 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4025 return CON_FUNC_ERROR;
4026 }
4027
4028 /*
4029 * In TLSv1.3 the certificate chain is always preceded by a 0 length context
4030 * for the server Certificate message
4031 */
4032 if (SSL_CONNECTION_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
4033 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4034 return CON_FUNC_ERROR;
4035 }
4036 switch (s->ext.server_cert_type) {
4037 case TLSEXT_cert_type_rpk:
4038 if (!tls_output_rpk(s, pkt, cpk)) {
4039 /* SSLfatal() already called */
4040 return 0;
4041 }
4042 break;
4043 case TLSEXT_cert_type_x509:
4044 if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {
4045 /* SSLfatal() already called */
4046 return 0;
4047 }
4048 break;
4049 default:
4050 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4051 return 0;
4052 }
4053
4054 return CON_FUNC_SUCCESS;
4055 }
4056
4057 #ifndef OPENSSL_NO_COMP_ALG
4058 CON_FUNC_RETURN tls_construct_server_compressed_certificate(SSL_CONNECTION *sc, WPACKET *pkt)
4059 {
4060 int alg = get_compressed_certificate_alg(sc);
4061 OSSL_COMP_CERT *cc = sc->s3.tmp.cert->comp_cert[alg];
4062
4063 if (!ossl_assert(cc != NULL)) {
4064 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4065 return 0;
4066 }
4067 /*
4068 * Server can't compress on-demand
4069 * Use pre-compressed certificate
4070 */
4071 if (!WPACKET_put_bytes_u16(pkt, alg)
4072 || !WPACKET_put_bytes_u24(pkt, cc->orig_len)
4073 || !WPACKET_start_sub_packet_u24(pkt)
4074 || !WPACKET_memcpy(pkt, cc->data, cc->len)
4075 || !WPACKET_close(pkt))
4076 return 0;
4077
4078 sc->s3.tmp.cert->cert_comp_used++;
4079 return 1;
4080 }
4081 #endif
4082
4083 static int create_ticket_prequel(SSL_CONNECTION *s, WPACKET *pkt,
4084 uint32_t age_add, unsigned char *tick_nonce)
4085 {
4086 uint32_t timeout = (uint32_t)ossl_time2seconds(s->session->timeout);
4087
4088 /*
4089 * Ticket lifetime hint:
4090 * In TLSv1.3 we reset the "time" field above, and always specify the
4091 * timeout, limited to a 1 week period per RFC8446.
4092 * For TLSv1.2 this is advisory only and we leave this unspecified for
4093 * resumed session (for simplicity).
4094 */
4095 #define ONE_WEEK_SEC (7 * 24 * 60 * 60)
4096
4097 if (SSL_CONNECTION_IS_TLS13(s)) {
4098 if (ossl_time_compare(s->session->timeout,
4099 ossl_seconds2time(ONE_WEEK_SEC))
4100 > 0)
4101 timeout = ONE_WEEK_SEC;
4102 } else if (s->hit)
4103 timeout = 0;
4104
4105 if (!WPACKET_put_bytes_u32(pkt, timeout)) {
4106 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4107 return 0;
4108 }
4109
4110 if (SSL_CONNECTION_IS_TLS13(s)) {
4111 if (!WPACKET_put_bytes_u32(pkt, age_add)
4112 || !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {
4113 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4114 return 0;
4115 }
4116 }
4117
4118 /* Start the sub-packet for the actual ticket data */
4119 if (!WPACKET_start_sub_packet_u16(pkt)) {
4120 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4121 return 0;
4122 }
4123
4124 return 1;
4125 }
4126
4127 static CON_FUNC_RETURN construct_stateless_ticket(SSL_CONNECTION *s,
4128 WPACKET *pkt,
4129 uint32_t age_add,
4130 unsigned char *tick_nonce)
4131 {
4132 unsigned char *senc = NULL;
4133 EVP_CIPHER_CTX *ctx = NULL;
4134 SSL_HMAC *hctx = NULL;
4135 unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
4136 const unsigned char *const_p;
4137 int len, slen_full, slen, lenfinal;
4138 SSL_SESSION *sess;
4139 size_t hlen;
4140 SSL_CTX *tctx = s->session_ctx;
4141 unsigned char iv[EVP_MAX_IV_LENGTH];
4142 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
4143 int iv_len;
4144 CON_FUNC_RETURN ok = CON_FUNC_ERROR;
4145 size_t macoffset, macendoffset;
4146 SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
4147 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
4148
4149 /* get session encoding length */
4150 slen_full = i2d_SSL_SESSION(s->session, NULL);
4151 /*
4152 * Some length values are 16 bits, so forget it if session is too
4153 * long
4154 */
4155 if (slen_full == 0 || slen_full > 0xFF00) {
4156 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4157 goto err;
4158 }
4159 senc = OPENSSL_malloc(slen_full);
4160 if (senc == NULL) {
4161 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4162 goto err;
4163 }
4164
4165 ctx = EVP_CIPHER_CTX_new();
4166 if (ctx == NULL) {
4167 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
4168 goto err;
4169 }
4170 hctx = ssl_hmac_new(tctx);
4171 if (hctx == NULL) {
4172 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
4173 goto err;
4174 }
4175
4176 p = senc;
4177 if (!i2d_SSL_SESSION(s->session, &p)) {
4178 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4179 goto err;
4180 }
4181
4182 /*
4183 * create a fresh copy (not shared with other threads) to clean up
4184 */
4185 const_p = senc;
4186 sess = d2i_SSL_SESSION_ex(NULL, &const_p, slen_full, sctx->libctx,
4187 sctx->propq);
4188 if (sess == NULL) {
4189 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4190 goto err;
4191 }
4192
4193 slen = i2d_SSL_SESSION(sess, NULL);
4194 if (slen == 0 || slen > slen_full) {
4195 /* shouldn't ever happen */
4196 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4197 SSL_SESSION_free(sess);
4198 goto err;
4199 }
4200 p = senc;
4201 if (!i2d_SSL_SESSION(sess, &p)) {
4202 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4203 SSL_SESSION_free(sess);
4204 goto err;
4205 }
4206 SSL_SESSION_free(sess);
4207
4208 /*
4209 * Initialize HMAC and cipher contexts. If callback present it does
4210 * all the work otherwise use generated values from parent ctx.
4211 */
4212 #ifndef OPENSSL_NO_DEPRECATED_3_0
4213 if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
4214 #else
4215 if (tctx->ext.ticket_key_evp_cb != NULL)
4216 #endif
4217 {
4218 int ret = 0;
4219
4220 if (tctx->ext.ticket_key_evp_cb != NULL)
4221 ret = tctx->ext.ticket_key_evp_cb(ssl, key_name, iv, ctx,
4222 ssl_hmac_get0_EVP_MAC_CTX(hctx),
4223 1);
4224 #ifndef OPENSSL_NO_DEPRECATED_3_0
4225 else if (tctx->ext.ticket_key_cb != NULL)
4226 /* if 0 is returned, write an empty ticket */
4227 ret = tctx->ext.ticket_key_cb(ssl, key_name, iv, ctx,
4228 ssl_hmac_get0_HMAC_CTX(hctx), 1);
4229 #endif
4230
4231 if (ret == 0) {
4232 /*
4233 * In TLSv1.2 we construct a 0 length ticket. In TLSv1.3 a 0
4234 * length ticket is not allowed so we abort construction of the
4235 * ticket
4236 */
4237 if (SSL_CONNECTION_IS_TLS13(s)) {
4238 ok = CON_FUNC_DONT_SEND;
4239 goto err;
4240 }
4241 /* Put timeout and length */
4242 if (!WPACKET_put_bytes_u32(pkt, 0)
4243 || !WPACKET_put_bytes_u16(pkt, 0)) {
4244 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4245 goto err;
4246 }
4247 OPENSSL_free(senc);
4248 EVP_CIPHER_CTX_free(ctx);
4249 ssl_hmac_free(hctx);
4250 return CON_FUNC_SUCCESS;
4251 }
4252 if (ret < 0) {
4253 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
4254 goto err;
4255 }
4256 iv_len = EVP_CIPHER_CTX_get_iv_length(ctx);
4257 if (iv_len < 0) {
4258 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4259 goto err;
4260 }
4261 } else {
4262 EVP_CIPHER *cipher = EVP_CIPHER_fetch(sctx->libctx, "AES-256-CBC",
4263 sctx->propq);
4264
4265 if (cipher == NULL) {
4266 /* Error is already recorded */
4267 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
4268 goto err;
4269 }
4270
4271 iv_len = EVP_CIPHER_get_iv_length(cipher);
4272 if (iv_len < 0
4273 || RAND_bytes_ex(sctx->libctx, iv, iv_len, 0) <= 0
4274 || !EVP_EncryptInit_ex(ctx, cipher, NULL,
4275 tctx->ext.secure->tick_aes_key, iv)
4276 || !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
4277 sizeof(tctx->ext.secure->tick_hmac_key),
4278 "SHA256")) {
4279 EVP_CIPHER_free(cipher);
4280 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4281 goto err;
4282 }
4283 EVP_CIPHER_free(cipher);
4284 memcpy(key_name, tctx->ext.tick_key_name,
4285 sizeof(tctx->ext.tick_key_name));
4286 }
4287
4288 if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4289 /* SSLfatal() already called */
4290 goto err;
4291 }
4292
4293 if (!WPACKET_get_total_written(pkt, &macoffset)
4294 /* Output key name */
4295 || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
4296 /* output IV */
4297 || !WPACKET_memcpy(pkt, iv, iv_len)
4298 || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
4299 &encdata1)
4300 /* Encrypt session data */
4301 || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
4302 || !WPACKET_allocate_bytes(pkt, len, &encdata2)
4303 || encdata1 != encdata2
4304 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
4305 || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
4306 || encdata1 + len != encdata2
4307 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
4308 || !WPACKET_get_total_written(pkt, &macendoffset)
4309 || !ssl_hmac_update(hctx,
4310 (unsigned char *)s->init_buf->data + macoffset,
4311 macendoffset - macoffset)
4312 || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
4313 || !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)
4314 || hlen > EVP_MAX_MD_SIZE
4315 || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
4316 || macdata1 != macdata2) {
4317 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4318 goto err;
4319 }
4320
4321 /* Close the sub-packet created by create_ticket_prequel() */
4322 if (!WPACKET_close(pkt)) {
4323 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4324 goto err;
4325 }
4326
4327 ok = CON_FUNC_SUCCESS;
4328 err:
4329 OPENSSL_free(senc);
4330 EVP_CIPHER_CTX_free(ctx);
4331 ssl_hmac_free(hctx);
4332 return ok;
4333 }
4334
4335 static int construct_stateful_ticket(SSL_CONNECTION *s, WPACKET *pkt,
4336 uint32_t age_add,
4337 unsigned char *tick_nonce)
4338 {
4339 if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4340 /* SSLfatal() already called */
4341 return 0;
4342 }
4343
4344 if (!WPACKET_memcpy(pkt, s->session->session_id,
4345 s->session->session_id_length)
4346 || !WPACKET_close(pkt)) {
4347 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4348 return 0;
4349 }
4350
4351 return 1;
4352 }
4353
4354 static void tls_update_ticket_counts(SSL_CONNECTION *s)
4355 {
4356 /*
4357 * Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|
4358 * gets reset to 0 if we send more tickets following a post-handshake
4359 * auth, but |next_ticket_nonce| does not. If we're sending extra
4360 * tickets, decrement the count of pending extra tickets.
4361 */
4362 s->sent_tickets++;
4363 s->next_ticket_nonce++;
4364 if (s->ext.extra_tickets_expected > 0)
4365 s->ext.extra_tickets_expected--;
4366 }
4367
4368 CON_FUNC_RETURN tls_construct_new_session_ticket(SSL_CONNECTION *s, WPACKET *pkt)
4369 {
4370 SSL_CTX *tctx = s->session_ctx;
4371 unsigned char tick_nonce[TICKET_NONCE_SIZE];
4372 union {
4373 unsigned char age_add_c[sizeof(uint32_t)];
4374 uint32_t age_add;
4375 } age_add_u;
4376 CON_FUNC_RETURN ret = CON_FUNC_ERROR;
4377
4378 age_add_u.age_add = 0;
4379
4380 if (SSL_CONNECTION_IS_TLS13(s)) {
4381 size_t i, hashlen;
4382 uint64_t nonce;
4383 /* ASCII: "resumption", in hex for EBCDIC compatibility */
4384 static const unsigned char nonce_label[] = { 0x72, 0x65, 0x73, 0x75, 0x6D,
4385 0x70, 0x74, 0x69, 0x6F, 0x6E };
4386 const EVP_MD *md = ssl_handshake_md(s);
4387 int hashleni = EVP_MD_get_size(md);
4388
4389 /* Ensure cast to size_t is safe */
4390 if (!ossl_assert(hashleni > 0)) {
4391 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4392 goto err;
4393 }
4394 hashlen = (size_t)hashleni;
4395
4396 /*
4397 * If we already sent one NewSessionTicket, or we resumed then
4398 * s->session may already be in a cache and so we must not modify it.
4399 * Instead we need to take a copy of it and modify that.
4400 */
4401 if (s->sent_tickets != 0 || s->hit) {
4402 SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);
4403
4404 if (new_sess == NULL) {
4405 /* SSLfatal already called */
4406 goto err;
4407 }
4408
4409 SSL_SESSION_free(s->session);
4410 s->session = new_sess;
4411 }
4412
4413 if (!ssl_generate_session_id(s, s->session)) {
4414 /* SSLfatal() already called */
4415 goto err;
4416 }
4417 if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
4418 age_add_u.age_add_c, sizeof(age_add_u), 0)
4419 <= 0) {
4420 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4421 goto err;
4422 }
4423 s->session->ext.tick_age_add = age_add_u.age_add;
4424
4425 nonce = s->next_ticket_nonce;
4426 for (i = TICKET_NONCE_SIZE; i > 0; i--) {
4427 tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);
4428 nonce >>= 8;
4429 }
4430
4431 if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
4432 nonce_label,
4433 sizeof(nonce_label),
4434 tick_nonce,
4435 TICKET_NONCE_SIZE,
4436 s->session->master_key,
4437 hashlen, 1)) {
4438 /* SSLfatal() already called */
4439 goto err;
4440 }
4441 s->session->master_key_length = hashlen;
4442
4443 s->session->time = ossl_time_now();
4444 ssl_session_calculate_timeout(s->session);
4445 if (s->s3.alpn_selected != NULL) {
4446 OPENSSL_free(s->session->ext.alpn_selected);
4447 s->session->ext.alpn_selected = OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);
4448 if (s->session->ext.alpn_selected == NULL) {
4449 s->session->ext.alpn_selected_len = 0;
4450 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4451 goto err;
4452 }
4453 s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
4454 }
4455 s->session->ext.max_early_data = s->max_early_data;
4456 }
4457
4458 if (tctx->generate_ticket_cb != NULL && tctx->generate_ticket_cb(SSL_CONNECTION_GET_USER_SSL(s), tctx->ticket_cb_data) == 0) {
4459 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4460 goto err;
4461 }
4462 /*
4463 * If we are using anti-replay protection then we behave as if
4464 * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
4465 * is no point in using full stateless tickets.
4466 */
4467 if (SSL_CONNECTION_IS_TLS13(s)
4468 && ((s->options & SSL_OP_NO_TICKET) != 0
4469 || (s->max_early_data > 0
4470 && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {
4471 if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {
4472 /* SSLfatal() already called */
4473 goto err;
4474 }
4475 } else {
4476 CON_FUNC_RETURN tmpret;
4477
4478 tmpret = construct_stateless_ticket(s, pkt, age_add_u.age_add,
4479 tick_nonce);
4480 if (tmpret != CON_FUNC_SUCCESS) {
4481 if (tmpret == CON_FUNC_DONT_SEND) {
4482 /* Non-fatal. Abort construction but continue */
4483 ret = CON_FUNC_DONT_SEND;
4484 /* We count this as a success so update the counts anwyay */
4485 tls_update_ticket_counts(s);
4486 }
4487 /* else SSLfatal() already called */
4488 goto err;
4489 }
4490 }
4491
4492 if (SSL_CONNECTION_IS_TLS13(s)) {
4493 if (!tls_construct_extensions(s, pkt,
4494 SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
4495 NULL, 0)) {
4496 /* SSLfatal() already called */
4497 goto err;
4498 }
4499 tls_update_ticket_counts(s);
4500 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
4501 }
4502
4503 ret = CON_FUNC_SUCCESS;
4504 err:
4505 return ret;
4506 }
4507
4508 /*
4509 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
4510 * create a separate message. Returns 1 on success or 0 on failure.
4511 */
4512 int tls_construct_cert_status_body(SSL_CONNECTION *s, OCSP_RESPONSE *resp, WPACKET *pkt)
4513 {
4514 unsigned char *respder = NULL;
4515 int resplen = 0;
4516
4517 if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)) {
4518 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4519 return 0;
4520 }
4521
4522 #ifndef OPENSSL_NO_OCSP
4523 resplen = i2d_OCSP_RESPONSE(resp, &respder);
4524 #endif
4525
4526 if (!WPACKET_sub_memcpy_u24(pkt, respder, resplen)) {
4527 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4528 OPENSSL_free(respder);
4529 return 0;
4530 }
4531
4532 OPENSSL_free(respder);
4533 return 1;
4534 }
4535
4536 CON_FUNC_RETURN tls_construct_cert_status(SSL_CONNECTION *s, WPACKET *pkt)
4537 {
4538 OCSP_RESPONSE *resp;
4539
4540 resp = ossl_get_ocsp_response(s, 0);
4541
4542 if (resp == NULL)
4543 return CON_FUNC_DONT_SEND;
4544
4545 if (!tls_construct_cert_status_body(s, resp, pkt)) {
4546 /* SSLfatal() already called */
4547 return CON_FUNC_ERROR;
4548 }
4549
4550 return CON_FUNC_SUCCESS;
4551 }
4552
4553 #ifndef OPENSSL_NO_NEXTPROTONEG
4554 /*
4555 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
4556 * It sets the next_proto member in s if found
4557 */
4558 MSG_PROCESS_RETURN tls_process_next_proto(SSL_CONNECTION *s, PACKET *pkt)
4559 {
4560 PACKET next_proto, padding;
4561 size_t next_proto_len;
4562
4563 /*-
4564 * The payload looks like:
4565 * uint8 proto_len;
4566 * uint8 proto[proto_len];
4567 * uint8 padding_len;
4568 * uint8 padding[padding_len];
4569 */
4570 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
4571 || !PACKET_get_length_prefixed_1(pkt, &padding)
4572 || PACKET_remaining(pkt) > 0) {
4573 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4574 return MSG_PROCESS_ERROR;
4575 }
4576
4577 if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
4578 s->ext.npn_len = 0;
4579 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4580 return MSG_PROCESS_ERROR;
4581 }
4582
4583 s->ext.npn_len = (unsigned char)next_proto_len;
4584
4585 return MSG_PROCESS_CONTINUE_READING;
4586 }
4587 #endif
4588
4589 static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,
4590 WPACKET *pkt)
4591 {
4592 if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
4593 NULL, 0)) {
4594 /* SSLfatal() already called */
4595 return CON_FUNC_ERROR;
4596 }
4597
4598 return CON_FUNC_SUCCESS;
4599 }
4600
4601 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL_CONNECTION *s, PACKET *pkt)
4602 {
4603 if (PACKET_remaining(pkt) != 0) {
4604 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4605 return MSG_PROCESS_ERROR;
4606 }
4607
4608 if (s->early_data_state != SSL_EARLY_DATA_READING
4609 && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
4610 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4611 return MSG_PROCESS_ERROR;
4612 }
4613
4614 /*
4615 * EndOfEarlyData signals a key change so the end of the message must be on
4616 * a record boundary.
4617 */
4618 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
4619 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
4620 return MSG_PROCESS_ERROR;
4621 }
4622
4623 s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
4624 if (!SSL_CONNECTION_GET_SSL(s)->method->ssl3_enc->change_cipher_state(s,
4625 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
4626 /* SSLfatal() already called */
4627 return MSG_PROCESS_ERROR;
4628 }
4629
4630 return MSG_PROCESS_CONTINUE_READING;
4631 }