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