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