1 /*
2 * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4 * Copyright 2005 Nokia. All rights reserved.
5 *
6 * Licensed under the Apache License 2.0 (the "License"). You may not use
7 * this file except in compliance with the License. You can obtain a copy
8 * in the file LICENSE in the source distribution or at
9 * https://www.openssl.org/source/license.html
10 */
11
12 #include "internal/e_os.h"
13
14 #include <stdio.h>
15 #include "../ssl_local.h"
16 #include "statem_local.h"
17 #include "internal/constant_time.h"
18 #include "internal/cryptlib.h"
19 #include "internal/ssl_unwrap.h"
20 #include <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 /*
2030 * Per RFC 4851, Section 3.2.2:
2031 * If the ClientHello contains both a Session ID and a PAC-Opaque in
2032 * the SessionTicket extension, and the server resumes the session
2033 * using the PAC-Opaque, it should echo the same Session ID in the
2034 * ServerHello.
2035 */
2036 if (clienthello->session_id_len > 0) {
2037 memcpy(s->session->session_id, clienthello->session_id,
2038 clienthello->session_id_len);
2039 s->session->session_id_length = clienthello->session_id_len;
2040 }
2041
2042 ciphers = NULL;
2043
2044 /* check if some cipher was preferred by call back */
2045 if (pref_cipher == NULL)
2046 pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,
2047 SSL_get_ciphers(ssl));
2048 if (pref_cipher == NULL) {
2049 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
2050 goto err;
2051 }
2052
2053 s->session->cipher = pref_cipher;
2054 sk_SSL_CIPHER_free(s->cipher_list);
2055 s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);
2056 sk_SSL_CIPHER_free(s->cipher_list_by_id);
2057 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);
2058 }
2059 }
2060
2061 /*
2062 * Worst case, we will use the NULL compression, but if we have other
2063 * options, we will now look for them. We have complen-1 compression
2064 * algorithms from the client, starting at q.
2065 */
2066 s->s3.tmp.new_compression = NULL;
2067 if (SSL_CONNECTION_IS_TLS13(s)) {
2068 /*
2069 * We already checked above that the NULL compression method appears in
2070 * the list. Now we check there aren't any others (which is illegal in
2071 * a TLSv1.3 ClientHello.
2072 */
2073 if (clienthello->compressions_len != 1) {
2074 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2075 SSL_R_INVALID_COMPRESSION_ALGORITHM);
2076 goto err;
2077 }
2078 }
2079 #ifndef OPENSSL_NO_COMP
2080 /* This only happens if we have a cache hit */
2081 else if (s->session->compress_meth != 0) {
2082 int m, comp_id = s->session->compress_meth;
2083 unsigned int k;
2084 /* Perform sanity checks on resumed compression algorithm */
2085 /* Can't disable compression */
2086 if (!ssl_allow_compression(s)) {
2087 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2088 SSL_R_INCONSISTENT_COMPRESSION);
2089 goto err;
2090 }
2091 /* Look for resumed compression method */
2092 for (m = 0; m < sk_SSL_COMP_num(sctx->comp_methods); m++) {
2093 comp = sk_SSL_COMP_value(sctx->comp_methods, m);
2094 if (comp_id == comp->id) {
2095 s->s3.tmp.new_compression = comp;
2096 break;
2097 }
2098 }
2099 if (s->s3.tmp.new_compression == NULL) {
2100 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2101 SSL_R_INVALID_COMPRESSION_ALGORITHM);
2102 goto err;
2103 }
2104 /* Look for resumed method in compression list */
2105 for (k = 0; k < clienthello->compressions_len; k++) {
2106 if (clienthello->compressions[k] == comp_id)
2107 break;
2108 }
2109 if (k >= clienthello->compressions_len) {
2110 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2111 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
2112 goto err;
2113 }
2114 } else if (s->hit) {
2115 comp = NULL;
2116 } else if (ssl_allow_compression(s) && sctx->comp_methods) {
2117 /* See if we have a match */
2118 int m, nn, v, done = 0;
2119 unsigned int o;
2120
2121 nn = sk_SSL_COMP_num(sctx->comp_methods);
2122 for (m = 0; m < nn; m++) {
2123 comp = sk_SSL_COMP_value(sctx->comp_methods, m);
2124 v = comp->id;
2125 for (o = 0; o < clienthello->compressions_len; o++) {
2126 if (v == clienthello->compressions[o]) {
2127 done = 1;
2128 break;
2129 }
2130 }
2131 if (done)
2132 break;
2133 }
2134 if (done)
2135 s->s3.tmp.new_compression = comp;
2136 else
2137 comp = NULL;
2138 }
2139 #else
2140 /*
2141 * If compression is disabled we'd better not try to resume a session
2142 * using compression.
2143 */
2144 if (s->session->compress_meth != 0) {
2145 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);
2146 goto err;
2147 }
2148 #endif
2149
2150 /*
2151 * Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher
2152 */
2153
2154 if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {
2155 sk_SSL_CIPHER_free(s->peer_ciphers);
2156 s->peer_ciphers = ciphers;
2157 if (ciphers == NULL) {
2158 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2159 goto err;
2160 }
2161 ciphers = NULL;
2162 }
2163
2164 if (!s->hit) {
2165 #ifdef OPENSSL_NO_COMP
2166 s->session->compress_meth = 0;
2167 #else
2168 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
2169 #endif
2170 }
2171
2172 sk_SSL_CIPHER_free(ciphers);
2173 sk_SSL_CIPHER_free(scsvs);
2174 OPENSSL_free(clienthello->pre_proc_exts);
2175 OPENSSL_free(s->clienthello);
2176 s->clienthello = NULL;
2177 return 1;
2178 err:
2179 sk_SSL_CIPHER_free(ciphers);
2180 sk_SSL_CIPHER_free(scsvs);
2181 OPENSSL_free(clienthello->pre_proc_exts);
2182 OPENSSL_free(s->clienthello);
2183 s->clienthello = NULL;
2184
2185 return 0;
2186 }
2187
2188 /*
2189 * Call the status request callback if needed. Upon success, returns 1.
2190 * Upon failure, returns 0.
2191 */
tls_handle_status_request(SSL_CONNECTION * s)2192 static int tls_handle_status_request(SSL_CONNECTION *s)
2193 {
2194 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2195
2196 s->ext.status_expected = 0;
2197
2198 /*
2199 * If status request then ask callback what to do. Note: this must be
2200 * called after servername callbacks in case the certificate has changed,
2201 * and must be called after the cipher has been chosen because this may
2202 * influence which certificate is sent
2203 */
2204 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && sctx != NULL
2205 && sctx->ext.status_cb != NULL) {
2206 int ret;
2207
2208 /* If no certificate can't return certificate status */
2209 if (s->s3.tmp.cert != NULL) {
2210 /*
2211 * Set current certificate to one we will use so SSL_get_certificate
2212 * et al can pick it up.
2213 */
2214 s->cert->key = s->s3.tmp.cert;
2215 ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),
2216 sctx->ext.status_arg);
2217 switch (ret) {
2218 /* We don't want to send a status request response */
2219 case SSL_TLSEXT_ERR_NOACK:
2220 s->ext.status_expected = 0;
2221 break;
2222 /* status request response should be sent */
2223 case SSL_TLSEXT_ERR_OK:
2224 if (s->ext.ocsp.resp)
2225 s->ext.status_expected = 1;
2226 break;
2227 /* something bad happened */
2228 case SSL_TLSEXT_ERR_ALERT_FATAL:
2229 default:
2230 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CLIENTHELLO_TLSEXT);
2231 return 0;
2232 }
2233 }
2234 }
2235
2236 return 1;
2237 }
2238
2239 /*
2240 * Call the alpn_select callback if needed. Upon success, returns 1.
2241 * Upon failure, returns 0.
2242 */
tls_handle_alpn(SSL_CONNECTION * s)2243 int tls_handle_alpn(SSL_CONNECTION *s)
2244 {
2245 const unsigned char *selected = NULL;
2246 unsigned char selected_len = 0;
2247 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2248
2249 if (sctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {
2250 int r = sctx->ext.alpn_select_cb(SSL_CONNECTION_GET_USER_SSL(s),
2251 &selected, &selected_len,
2252 s->s3.alpn_proposed,
2253 (unsigned int)s->s3.alpn_proposed_len,
2254 sctx->ext.alpn_select_cb_arg);
2255
2256 if (r == SSL_TLSEXT_ERR_OK) {
2257 OPENSSL_free(s->s3.alpn_selected);
2258 s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);
2259 if (s->s3.alpn_selected == NULL) {
2260 s->s3.alpn_selected_len = 0;
2261 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2262 return 0;
2263 }
2264 s->s3.alpn_selected_len = selected_len;
2265 #ifndef OPENSSL_NO_NEXTPROTONEG
2266 /* ALPN takes precedence over NPN. */
2267 s->s3.npn_seen = 0;
2268 #endif
2269
2270 /* Check ALPN is consistent with session */
2271 if (s->session->ext.alpn_selected == NULL
2272 || selected_len != s->session->ext.alpn_selected_len
2273 || memcmp(selected, s->session->ext.alpn_selected,
2274 selected_len)
2275 != 0) {
2276 /* Not consistent so can't be used for early_data */
2277 s->ext.early_data_ok = 0;
2278
2279 if (!s->hit) {
2280 /*
2281 * This is a new session and so alpn_selected should have
2282 * been initialised to NULL. We should update it with the
2283 * selected ALPN.
2284 */
2285 if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
2286 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2287 ERR_R_INTERNAL_ERROR);
2288 return 0;
2289 }
2290 s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2291 selected_len);
2292 if (s->session->ext.alpn_selected == NULL) {
2293 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2294 ERR_R_INTERNAL_ERROR);
2295 return 0;
2296 }
2297 s->session->ext.alpn_selected_len = selected_len;
2298 }
2299 }
2300
2301 return 1;
2302 } else if (r != SSL_TLSEXT_ERR_NOACK) {
2303 SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL,
2304 SSL_R_NO_APPLICATION_PROTOCOL);
2305 return 0;
2306 }
2307 /*
2308 * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2309 * present.
2310 */
2311 }
2312
2313 /* Check ALPN is consistent with session */
2314 if (s->session->ext.alpn_selected != NULL) {
2315 /* Not consistent so can't be used for early_data */
2316 s->ext.early_data_ok = 0;
2317 }
2318
2319 return 1;
2320 }
2321
tls_post_process_client_hello(SSL_CONNECTION * s,WORK_STATE wst)2322 WORK_STATE tls_post_process_client_hello(SSL_CONNECTION *s, WORK_STATE wst)
2323 {
2324 const SSL_CIPHER *cipher;
2325 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2326 SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
2327
2328 if (wst == WORK_MORE_A) {
2329 int rv = tls_early_post_process_client_hello(s);
2330 if (rv == 0) {
2331 /* SSLfatal() was already called */
2332 goto err;
2333 }
2334 if (rv < 0)
2335 return WORK_MORE_A;
2336 wst = WORK_MORE_B;
2337 }
2338 if (wst == WORK_MORE_B) {
2339 if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {
2340 /* Let cert callback update server certificates if required */
2341 if (!s->hit && s->cert->cert_cb != NULL) {
2342 int rv = s->cert->cert_cb(ussl, s->cert->cert_cb_arg);
2343
2344 if (rv == 0) {
2345 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CERT_CB_ERROR);
2346 goto err;
2347 }
2348 if (rv < 0) {
2349 s->rwstate = SSL_X509_LOOKUP;
2350 return WORK_MORE_B;
2351 }
2352 s->rwstate = SSL_NOTHING;
2353 }
2354
2355 /* In TLSv1.3 we selected the ciphersuite before resumption */
2356 if (!SSL_CONNECTION_IS_TLS13(s)) {
2357 cipher = ssl3_choose_cipher(s, s->peer_ciphers,
2358 SSL_get_ciphers(ssl));
2359
2360 if (cipher == NULL) {
2361 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2362 SSL_R_NO_SHARED_CIPHER);
2363 goto err;
2364 }
2365 s->s3.tmp.new_cipher = cipher;
2366 }
2367 if (!s->hit) {
2368 if (!tls_choose_sigalg(s, 1)) {
2369 /* SSLfatal already called */
2370 goto err;
2371 }
2372 /* check whether we should disable session resumption */
2373 if (s->not_resumable_session_cb != NULL)
2374 s->session->not_resumable = s->not_resumable_session_cb(ussl,
2375 ((s->s3.tmp.new_cipher->algorithm_mkey
2376 & (SSL_kDHE | SSL_kECDHE))
2377 != 0));
2378 if (s->session->not_resumable)
2379 /* do not send a session ticket */
2380 s->ext.ticket_expected = 0;
2381 }
2382 } else {
2383 /* Session-id reuse */
2384 s->s3.tmp.new_cipher = s->session->cipher;
2385 }
2386
2387 /*-
2388 * we now have the following setup.
2389 * client_random
2390 * cipher_list - our preferred list of ciphers
2391 * ciphers - the client's preferred list of ciphers
2392 * compression - basically ignored right now
2393 * ssl version is set - sslv3
2394 * s->session - The ssl session has been setup.
2395 * s->hit - session reuse flag
2396 * s->s3.tmp.new_cipher - the new cipher to use.
2397 */
2398
2399 /*
2400 * Call status_request callback if needed. Has to be done after the
2401 * certificate callbacks etc above.
2402 */
2403 if (!tls_handle_status_request(s)) {
2404 /* SSLfatal() already called */
2405 goto err;
2406 }
2407 /*
2408 * Call alpn_select callback if needed. Has to be done after SNI and
2409 * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2410 * we already did this because cipher negotiation happens earlier, and
2411 * we must handle ALPN before we decide whether to accept early_data.
2412 */
2413 if (!SSL_CONNECTION_IS_TLS13(s) && !tls_handle_alpn(s)) {
2414 /* SSLfatal() already called */
2415 goto err;
2416 }
2417
2418 wst = WORK_MORE_C;
2419 }
2420 #ifndef OPENSSL_NO_SRP
2421 if (wst == WORK_MORE_C) {
2422 int ret;
2423 if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
2424 /*
2425 * callback indicates further work to be done
2426 */
2427 s->rwstate = SSL_X509_LOOKUP;
2428 return WORK_MORE_C;
2429 }
2430 if (ret < 0) {
2431 /* SSLfatal() already called */
2432 goto err;
2433 }
2434 }
2435 #endif
2436
2437 return WORK_FINISHED_STOP;
2438 err:
2439 return WORK_ERROR;
2440 }
2441
tls_construct_server_hello(SSL_CONNECTION * s,WPACKET * pkt)2442 CON_FUNC_RETURN tls_construct_server_hello(SSL_CONNECTION *s, WPACKET *pkt)
2443 {
2444 int compm;
2445 size_t sl, len;
2446 int version;
2447 unsigned char *session_id;
2448 int usetls13 = SSL_CONNECTION_IS_TLS13(s)
2449 || s->hello_retry_request == SSL_HRR_PENDING;
2450
2451 version = usetls13 ? TLS1_2_VERSION : s->version;
2452 if (!WPACKET_put_bytes_u16(pkt, version)
2453 /*
2454 * Random stuff. Filling of the server_random takes place in
2455 * tls_process_client_hello()
2456 */
2457 || !WPACKET_memcpy(pkt,
2458 s->hello_retry_request == SSL_HRR_PENDING
2459 ? hrrrandom
2460 : s->s3.server_random,
2461 SSL3_RANDOM_SIZE)) {
2462 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2463 return CON_FUNC_ERROR;
2464 }
2465
2466 /*-
2467 * There are several cases for the session ID to send
2468 * back in the server hello:
2469 * - For session reuse from the session cache,
2470 * we send back the old session ID.
2471 * - If stateless session reuse (using a session ticket)
2472 * is successful, we send back the client's "session ID"
2473 * (which doesn't actually identify the session).
2474 * - If it is a new session, we send back the new
2475 * session ID.
2476 * - However, if we want the new session to be single-use,
2477 * we send back a 0-length session ID.
2478 * - In TLSv1.3 we echo back the session id sent to us by the client
2479 * regardless
2480 * s->hit is non-zero in either case of session reuse,
2481 * so the following won't overwrite an ID that we're supposed
2482 * to send back.
2483 */
2484 if (!(SSL_CONNECTION_GET_CTX(s)->session_cache_mode & SSL_SESS_CACHE_SERVER)
2485 && !s->hit)
2486 s->session->session_id_length = 0;
2487
2488 if (usetls13) {
2489 sl = s->tmp_session_id_len;
2490 session_id = s->tmp_session_id;
2491 } else {
2492 sl = s->session->session_id_length;
2493 session_id = s->session->session_id;
2494 }
2495
2496 if (sl > sizeof(s->session->session_id)) {
2497 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2498 return CON_FUNC_ERROR;
2499 }
2500
2501 /* set up the compression method */
2502 #ifdef OPENSSL_NO_COMP
2503 compm = 0;
2504 #else
2505 if (usetls13 || s->s3.tmp.new_compression == NULL)
2506 compm = 0;
2507 else
2508 compm = s->s3.tmp.new_compression->id;
2509 #endif
2510
2511 if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
2512 || !SSL_CONNECTION_GET_SSL(s)->method->put_cipher_by_char(s->s3.tmp.new_cipher,
2513 pkt, &len)
2514 || !WPACKET_put_bytes_u8(pkt, compm)) {
2515 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2516 return CON_FUNC_ERROR;
2517 }
2518
2519 if (!tls_construct_extensions(s, pkt,
2520 s->hello_retry_request == SSL_HRR_PENDING
2521 ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
2522 : (SSL_CONNECTION_IS_TLS13(s)
2523 ? SSL_EXT_TLS1_3_SERVER_HELLO
2524 : SSL_EXT_TLS1_2_SERVER_HELLO),
2525 NULL, 0)) {
2526 /* SSLfatal() already called */
2527 return CON_FUNC_ERROR;
2528 }
2529
2530 if (s->hello_retry_request == SSL_HRR_PENDING) {
2531 /* Ditch the session. We'll create a new one next time around */
2532 SSL_SESSION_free(s->session);
2533 s->session = NULL;
2534 s->hit = 0;
2535
2536 /*
2537 * Re-initialise the Transcript Hash. We're going to prepopulate it with
2538 * a synthetic message_hash in place of ClientHello1.
2539 */
2540 if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
2541 /* SSLfatal() already called */
2542 return CON_FUNC_ERROR;
2543 }
2544 } else if (!(s->verify_mode & SSL_VERIFY_PEER)
2545 && !ssl3_digest_cached_records(s, 0)) {
2546 /* SSLfatal() already called */;
2547 return CON_FUNC_ERROR;
2548 }
2549
2550 return CON_FUNC_SUCCESS;
2551 }
2552
tls_construct_server_done(SSL_CONNECTION * s,WPACKET * pkt)2553 CON_FUNC_RETURN tls_construct_server_done(SSL_CONNECTION *s, WPACKET *pkt)
2554 {
2555 if (!s->s3.tmp.cert_request) {
2556 if (!ssl3_digest_cached_records(s, 0)) {
2557 /* SSLfatal() already called */
2558 return CON_FUNC_ERROR;
2559 }
2560 }
2561 return CON_FUNC_SUCCESS;
2562 }
2563
tls_construct_server_key_exchange(SSL_CONNECTION * s,WPACKET * pkt)2564 CON_FUNC_RETURN tls_construct_server_key_exchange(SSL_CONNECTION *s,
2565 WPACKET *pkt)
2566 {
2567 EVP_PKEY *pkdh = NULL;
2568 unsigned char *encodedPoint = NULL;
2569 size_t encodedlen = 0;
2570 int curve_id = 0;
2571 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
2572 int i;
2573 unsigned long type;
2574 BIGNUM *r[4];
2575 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2576 EVP_PKEY_CTX *pctx = NULL;
2577 size_t paramlen, paramoffset;
2578 int freer = 0;
2579 CON_FUNC_RETURN ret = CON_FUNC_ERROR;
2580 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2581
2582 if (!WPACKET_get_total_written(pkt, ¶moffset)) {
2583 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2584 goto err;
2585 }
2586
2587 if (md_ctx == NULL) {
2588 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2589 goto err;
2590 }
2591
2592 type = s->s3.tmp.new_cipher->algorithm_mkey;
2593
2594 r[0] = r[1] = r[2] = r[3] = NULL;
2595 #ifndef OPENSSL_NO_PSK
2596 /* Plain PSK or RSAPSK nothing to do */
2597 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2598 } else
2599 #endif /* !OPENSSL_NO_PSK */
2600 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2601 CERT *cert = s->cert;
2602 EVP_PKEY *pkdhp = NULL;
2603
2604 if (s->cert->dh_tmp_auto) {
2605 pkdh = ssl_get_auto_dh(s);
2606 if (pkdh == NULL) {
2607 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2608 goto err;
2609 }
2610 pkdhp = pkdh;
2611 } else {
2612 pkdhp = cert->dh_tmp;
2613 }
2614 #if !defined(OPENSSL_NO_DEPRECATED_3_0)
2615 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2616 pkdh = ssl_dh_to_pkey(s->cert->dh_tmp_cb(SSL_CONNECTION_GET_USER_SSL(s),
2617 0, 1024));
2618 if (pkdh == NULL) {
2619 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2620 goto err;
2621 }
2622 pkdhp = pkdh;
2623 }
2624 #endif
2625 if (pkdhp == NULL) {
2626 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
2627 goto err;
2628 }
2629 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2630 EVP_PKEY_get_security_bits(pkdhp), 0, pkdhp)) {
2631 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);
2632 goto err;
2633 }
2634 if (s->s3.tmp.pkey != NULL) {
2635 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2636 goto err;
2637 }
2638
2639 s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);
2640 if (s->s3.tmp.pkey == NULL) {
2641 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2642 goto err;
2643 }
2644
2645 EVP_PKEY_free(pkdh);
2646 pkdh = NULL;
2647
2648 /* These BIGNUMs need to be freed when we're finished */
2649 freer = 1;
2650 if (!EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_P,
2651 &r[0])
2652 || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_G,
2653 &r[1])
2654 || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey,
2655 OSSL_PKEY_PARAM_PUB_KEY, &r[2])) {
2656 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2657 goto err;
2658 }
2659 } else if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2660
2661 if (s->s3.tmp.pkey != NULL) {
2662 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2663 goto err;
2664 }
2665
2666 /* Get NID of appropriate shared curve */
2667 curve_id = tls1_shared_group(s, -2);
2668 if (curve_id == 0) {
2669 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2670 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2671 goto err;
2672 }
2673 /* Cache the group used in the SSL_SESSION */
2674 s->session->kex_group = curve_id;
2675 /* Generate a new key for this curve */
2676 s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);
2677 if (s->s3.tmp.pkey == NULL) {
2678 /* SSLfatal() already called */
2679 goto err;
2680 }
2681
2682 /* Encode the public key. */
2683 encodedlen = EVP_PKEY_get1_encoded_public_key(s->s3.tmp.pkey,
2684 &encodedPoint);
2685 if (encodedlen == 0) {
2686 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
2687 goto err;
2688 }
2689
2690 /*
2691 * We'll generate the serverKeyExchange message explicitly so we
2692 * can set these to NULLs
2693 */
2694 r[0] = NULL;
2695 r[1] = NULL;
2696 r[2] = NULL;
2697 r[3] = NULL;
2698 } else
2699 #ifndef OPENSSL_NO_SRP
2700 if (type & SSL_kSRP) {
2701 if ((s->srp_ctx.N == NULL) || (s->srp_ctx.g == NULL) || (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2702 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_SRP_PARAM);
2703 goto err;
2704 }
2705 r[0] = s->srp_ctx.N;
2706 r[1] = s->srp_ctx.g;
2707 r[2] = s->srp_ctx.s;
2708 r[3] = s->srp_ctx.B;
2709 } else
2710 #endif
2711 {
2712 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2713 goto err;
2714 }
2715
2716 if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2717 || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2718 lu = NULL;
2719 } else if (lu == NULL) {
2720 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
2721 goto err;
2722 }
2723
2724 #ifndef OPENSSL_NO_PSK
2725 if (type & SSL_PSK) {
2726 size_t len = (s->cert->psk_identity_hint == NULL)
2727 ? 0
2728 : strlen(s->cert->psk_identity_hint);
2729
2730 /*
2731 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2732 * checked this when we set the identity hint - but just in case
2733 */
2734 if (len > PSK_MAX_IDENTITY_LEN
2735 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2736 len)) {
2737 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2738 goto err;
2739 }
2740 }
2741 #endif
2742
2743 for (i = 0; i < 4 && r[i] != NULL; i++) {
2744 unsigned char *binval;
2745 int res;
2746
2747 #ifndef OPENSSL_NO_SRP
2748 if ((i == 2) && (type & SSL_kSRP)) {
2749 res = WPACKET_start_sub_packet_u8(pkt);
2750 } else
2751 #endif
2752 res = WPACKET_start_sub_packet_u16(pkt);
2753
2754 if (!res) {
2755 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2756 goto err;
2757 }
2758
2759 /*-
2760 * for interoperability with some versions of the Microsoft TLS
2761 * stack, we need to zero pad the DHE pub key to the same length
2762 * as the prime
2763 */
2764 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2765 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2766
2767 if (len > 0) {
2768 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2769 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2770 goto err;
2771 }
2772 memset(binval, 0, len);
2773 }
2774 }
2775
2776 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2777 || !WPACKET_close(pkt)) {
2778 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2779 goto err;
2780 }
2781
2782 BN_bn2bin(r[i], binval);
2783 }
2784
2785 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2786 /*
2787 * We only support named (not generic) curves. In this situation, the
2788 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2789 * [1 byte length of encoded point], followed by the actual encoded
2790 * point itself
2791 */
2792 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2793 || !WPACKET_put_bytes_u8(pkt, 0)
2794 || !WPACKET_put_bytes_u8(pkt, curve_id)
2795 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2796 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2797 goto err;
2798 }
2799 OPENSSL_free(encodedPoint);
2800 encodedPoint = NULL;
2801 }
2802
2803 /* not anonymous */
2804 if (lu != NULL) {
2805 EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;
2806 const EVP_MD *md;
2807 unsigned char *sigbytes1, *sigbytes2, *tbs;
2808 size_t siglen = 0, tbslen;
2809
2810 if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
2811 /* Should never happen */
2812 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2813 goto err;
2814 }
2815 /* Get length of the parameters we have written above */
2816 if (!WPACKET_get_length(pkt, ¶mlen)) {
2817 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2818 goto err;
2819 }
2820 /* send signature algorithm */
2821 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2822 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2823 goto err;
2824 }
2825
2826 if (EVP_DigestSignInit_ex(md_ctx, &pctx,
2827 md == NULL ? NULL : EVP_MD_get0_name(md),
2828 sctx->libctx, sctx->propq, pkey,
2829 NULL)
2830 <= 0) {
2831 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2832 goto err;
2833 }
2834 if (lu->sig == EVP_PKEY_RSA_PSS) {
2835 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2836 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2837 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2838 goto err;
2839 }
2840 }
2841 tbslen = construct_key_exchange_tbs(s, &tbs,
2842 s->init_buf->data + paramoffset,
2843 paramlen);
2844 if (tbslen == 0) {
2845 /* SSLfatal() already called */
2846 goto err;
2847 }
2848
2849 if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <= 0
2850 || !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2851 || EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 0
2852 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2853 || sigbytes1 != sigbytes2) {
2854 OPENSSL_free(tbs);
2855 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2856 goto err;
2857 }
2858 OPENSSL_free(tbs);
2859 }
2860
2861 ret = CON_FUNC_SUCCESS;
2862 err:
2863 EVP_PKEY_free(pkdh);
2864 OPENSSL_free(encodedPoint);
2865 EVP_MD_CTX_free(md_ctx);
2866 if (freer) {
2867 BN_free(r[0]);
2868 BN_free(r[1]);
2869 BN_free(r[2]);
2870 BN_free(r[3]);
2871 }
2872 return ret;
2873 }
2874
tls_construct_certificate_request(SSL_CONNECTION * s,WPACKET * pkt)2875 CON_FUNC_RETURN tls_construct_certificate_request(SSL_CONNECTION *s,
2876 WPACKET *pkt)
2877 {
2878 if (SSL_CONNECTION_IS_TLS13(s)) {
2879 /* Send random context when doing post-handshake auth */
2880 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
2881 OPENSSL_free(s->pha_context);
2882 s->pha_context_len = 32;
2883 if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL) {
2884 s->pha_context_len = 0;
2885 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2886 return CON_FUNC_ERROR;
2887 }
2888 if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
2889 s->pha_context, s->pha_context_len, 0)
2890 <= 0
2891 || !WPACKET_sub_memcpy_u8(pkt, s->pha_context,
2892 s->pha_context_len)) {
2893 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2894 return CON_FUNC_ERROR;
2895 }
2896 /* reset the handshake hash back to just after the ClientFinished */
2897 if (!tls13_restore_handshake_digest_for_pha(s)) {
2898 /* SSLfatal() already called */
2899 return CON_FUNC_ERROR;
2900 }
2901 } else {
2902 if (!WPACKET_put_bytes_u8(pkt, 0)) {
2903 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2904 return CON_FUNC_ERROR;
2905 }
2906 }
2907
2908 if (!tls_construct_extensions(s, pkt,
2909 SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2910 0)) {
2911 /* SSLfatal() already called */
2912 return CON_FUNC_ERROR;
2913 }
2914 goto done;
2915 }
2916
2917 /* get the list of acceptable cert types */
2918 if (!WPACKET_start_sub_packet_u8(pkt)
2919 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2920 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2921 return CON_FUNC_ERROR;
2922 }
2923
2924 if (SSL_USE_SIGALGS(s)) {
2925 const uint16_t *psigs;
2926 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2927
2928 if (!WPACKET_start_sub_packet_u16(pkt)
2929 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2930 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2931 || !WPACKET_close(pkt)) {
2932 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2933 return CON_FUNC_ERROR;
2934 }
2935 }
2936
2937 if (!construct_ca_names(s, get_ca_names(s), pkt)) {
2938 /* SSLfatal() already called */
2939 return CON_FUNC_ERROR;
2940 }
2941
2942 done:
2943 s->certreqs_sent++;
2944 s->s3.tmp.cert_request = 1;
2945 return CON_FUNC_SUCCESS;
2946 }
2947
tls_process_cke_psk_preamble(SSL_CONNECTION * s,PACKET * pkt)2948 static int tls_process_cke_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)
2949 {
2950 #ifndef OPENSSL_NO_PSK
2951 unsigned char psk[PSK_MAX_PSK_LEN];
2952 size_t psklen;
2953 PACKET psk_identity;
2954
2955 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2956 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2957 return 0;
2958 }
2959 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2960 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DATA_LENGTH_TOO_LONG);
2961 return 0;
2962 }
2963 if (s->psk_server_callback == NULL) {
2964 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_SERVER_CB);
2965 return 0;
2966 }
2967
2968 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2969 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2970 return 0;
2971 }
2972
2973 psklen = s->psk_server_callback(SSL_CONNECTION_GET_USER_SSL(s),
2974 s->session->psk_identity,
2975 psk, sizeof(psk));
2976
2977 if (psklen > PSK_MAX_PSK_LEN) {
2978 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2979 return 0;
2980 } else if (psklen == 0) {
2981 /*
2982 * PSK related to the given identity not found
2983 */
2984 SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_R_PSK_IDENTITY_NOT_FOUND);
2985 return 0;
2986 }
2987
2988 OPENSSL_free(s->s3.tmp.psk);
2989 s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);
2990 OPENSSL_cleanse(psk, psklen);
2991
2992 if (s->s3.tmp.psk == NULL) {
2993 s->s3.tmp.psklen = 0;
2994 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2995 return 0;
2996 }
2997
2998 s->s3.tmp.psklen = psklen;
2999
3000 return 1;
3001 #else
3002 /* Should never happen */
3003 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3004 return 0;
3005 #endif
3006 }
3007
tls_process_cke_rsa(SSL_CONNECTION * s,PACKET * pkt)3008 static int tls_process_cke_rsa(SSL_CONNECTION *s, PACKET *pkt)
3009 {
3010 size_t outlen;
3011 PACKET enc_premaster;
3012 EVP_PKEY *rsa = NULL;
3013 unsigned char *rsa_decrypt = NULL;
3014 int ret = 0;
3015 EVP_PKEY_CTX *ctx = NULL;
3016 OSSL_PARAM params[3], *p = params;
3017 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3018
3019 rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
3020 if (rsa == NULL) {
3021 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_RSA_CERTIFICATE);
3022 return 0;
3023 }
3024
3025 /* SSLv3 and pre-standard DTLS omit the length bytes. */
3026 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
3027 enc_premaster = *pkt;
3028 } else {
3029 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
3030 || PACKET_remaining(pkt) != 0) {
3031 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3032 return 0;
3033 }
3034 }
3035
3036 outlen = SSL_MAX_MASTER_KEY_LENGTH;
3037 rsa_decrypt = OPENSSL_malloc(outlen);
3038 if (rsa_decrypt == NULL) {
3039 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3040 return 0;
3041 }
3042
3043 ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, rsa, sctx->propq);
3044 if (ctx == NULL) {
3045 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3046 goto err;
3047 }
3048
3049 /*
3050 * We must not leak whether a decryption failure occurs because of
3051 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
3052 * section 7.4.7.1). We use the special padding type
3053 * RSA_PKCS1_WITH_TLS_PADDING to do that. It will automatically decrypt the
3054 * RSA, check the padding and check that the client version is as expected
3055 * in the premaster secret. If any of that fails then the function appears
3056 * to return successfully but with a random result. The call below could
3057 * still fail if the input is publicly invalid.
3058 * See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
3059 */
3060 if (EVP_PKEY_decrypt_init(ctx) <= 0
3061 || EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {
3062 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3063 goto err;
3064 }
3065
3066 *p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,
3067 (unsigned int *)&s->client_version);
3068 if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)
3069 *p++ = OSSL_PARAM_construct_uint(
3070 OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,
3071 (unsigned int *)&s->version);
3072 *p++ = OSSL_PARAM_construct_end();
3073
3074 if (!EVP_PKEY_CTX_set_params(ctx, params)
3075 || EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,
3076 PACKET_data(&enc_premaster),
3077 PACKET_remaining(&enc_premaster))
3078 <= 0) {
3079 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3080 goto err;
3081 }
3082
3083 /*
3084 * This test should never fail (otherwise we should have failed above) but
3085 * we double check anyway.
3086 */
3087 if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {
3088 OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);
3089 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3090 goto err;
3091 }
3092
3093 /* Also cleanses rsa_decrypt (on success or failure) */
3094 if (!ssl_generate_master_secret(s, rsa_decrypt, outlen, 0)) {
3095 /* SSLfatal() already called */
3096 goto err;
3097 }
3098
3099 ret = 1;
3100 err:
3101 OPENSSL_free(rsa_decrypt);
3102 EVP_PKEY_CTX_free(ctx);
3103 return ret;
3104 }
3105
tls_process_cke_dhe(SSL_CONNECTION * s,PACKET * pkt)3106 static int tls_process_cke_dhe(SSL_CONNECTION *s, PACKET *pkt)
3107 {
3108 EVP_PKEY *skey = NULL;
3109 unsigned int i;
3110 const unsigned char *data;
3111 EVP_PKEY *ckey = NULL;
3112 int ret = 0;
3113
3114 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
3115 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
3116 goto err;
3117 }
3118 skey = s->s3.tmp.pkey;
3119 if (skey == NULL) {
3120 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
3121 goto err;
3122 }
3123
3124 if (PACKET_remaining(pkt) == 0L) {
3125 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_MISSING_TMP_DH_KEY);
3126 goto err;
3127 }
3128 if (!PACKET_get_bytes(pkt, &data, i)) {
3129 /* We already checked we have enough data */
3130 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3131 goto err;
3132 }
3133 ckey = EVP_PKEY_new();
3134 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
3135 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3136 goto err;
3137 }
3138
3139 if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3140 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
3141 goto err;
3142 }
3143
3144 if (ssl_derive(s, skey, ckey, 1) == 0) {
3145 /* SSLfatal() already called */
3146 goto err;
3147 }
3148
3149 ret = 1;
3150 EVP_PKEY_free(s->s3.tmp.pkey);
3151 s->s3.tmp.pkey = NULL;
3152 err:
3153 EVP_PKEY_free(ckey);
3154 return ret;
3155 }
3156
tls_process_cke_ecdhe(SSL_CONNECTION * s,PACKET * pkt)3157 static int tls_process_cke_ecdhe(SSL_CONNECTION *s, PACKET *pkt)
3158 {
3159 EVP_PKEY *skey = s->s3.tmp.pkey;
3160 EVP_PKEY *ckey = NULL;
3161 int ret = 0;
3162
3163 if (PACKET_remaining(pkt) == 0L) {
3164 /* We don't support ECDH client auth */
3165 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_TMP_ECDH_KEY);
3166 goto err;
3167 } else {
3168 unsigned int i;
3169 const unsigned char *data;
3170
3171 /*
3172 * Get client's public key from encoded point in the
3173 * ClientKeyExchange message.
3174 */
3175
3176 /* Get encoded point length */
3177 if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
3178 || PACKET_remaining(pkt) != 0) {
3179 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3180 goto err;
3181 }
3182 if (skey == NULL) {
3183 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_ECDH_KEY);
3184 goto err;
3185 }
3186
3187 ckey = EVP_PKEY_new();
3188 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3189 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3190 goto err;
3191 }
3192
3193 if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3194 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
3195 goto err;
3196 }
3197 }
3198
3199 if (ssl_derive(s, skey, ckey, 1) == 0) {
3200 /* SSLfatal() already called */
3201 goto err;
3202 }
3203
3204 ret = 1;
3205 EVP_PKEY_free(s->s3.tmp.pkey);
3206 s->s3.tmp.pkey = NULL;
3207 err:
3208 EVP_PKEY_free(ckey);
3209
3210 return ret;
3211 }
3212
tls_process_cke_srp(SSL_CONNECTION * s,PACKET * pkt)3213 static int tls_process_cke_srp(SSL_CONNECTION *s, PACKET *pkt)
3214 {
3215 #ifndef OPENSSL_NO_SRP
3216 unsigned int i;
3217 const unsigned char *data;
3218
3219 if (!PACKET_get_net_2(pkt, &i)
3220 || !PACKET_get_bytes(pkt, &data, i)) {
3221 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRP_A_LENGTH);
3222 return 0;
3223 }
3224 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3225 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
3226 return 0;
3227 }
3228 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3229 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRP_PARAMETERS);
3230 return 0;
3231 }
3232 OPENSSL_free(s->session->srp_username);
3233 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3234 if (s->session->srp_username == NULL) {
3235 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3236 return 0;
3237 }
3238
3239 if (!srp_generate_server_master_secret(s)) {
3240 /* SSLfatal() already called */
3241 return 0;
3242 }
3243
3244 return 1;
3245 #else
3246 /* Should never happen */
3247 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3248 return 0;
3249 #endif
3250 }
3251
tls_process_cke_gost(SSL_CONNECTION * s,PACKET * pkt)3252 static int tls_process_cke_gost(SSL_CONNECTION *s, PACKET *pkt)
3253 {
3254 #ifndef OPENSSL_NO_GOST
3255 EVP_PKEY_CTX *pkey_ctx;
3256 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3257 unsigned char premaster_secret[32];
3258 const unsigned char *start;
3259 size_t outlen = sizeof(premaster_secret), inlen;
3260 unsigned long alg_a;
3261 GOST_KX_MESSAGE *pKX = NULL;
3262 const unsigned char *ptr;
3263 int ret = 0;
3264 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3265
3266 /* Get our certificate private key */
3267 alg_a = s->s3.tmp.new_cipher->algorithm_auth;
3268 if (alg_a & SSL_aGOST12) {
3269 /*
3270 * New GOST ciphersuites have SSL_aGOST01 bit too
3271 */
3272 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3273 if (pk == NULL) {
3274 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3275 }
3276 if (pk == NULL) {
3277 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3278 }
3279 } else if (alg_a & SSL_aGOST01) {
3280 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3281 }
3282
3283 pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);
3284 if (pkey_ctx == NULL) {
3285 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3286 return 0;
3287 }
3288 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3289 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3290 goto err;
3291 }
3292 /*
3293 * If client certificate is present and is of the same type, maybe
3294 * use it for key exchange. Don't mind errors from
3295 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3296 * client certificate for authorization only.
3297 */
3298 client_pub_pkey = tls_get_peer_pkey(s);
3299 if (client_pub_pkey) {
3300 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3301 ERR_clear_error();
3302 }
3303
3304 ptr = PACKET_data(pkt);
3305 /* Some implementations provide extra data in the opaqueBlob
3306 * We have nothing to do with this blob so we just skip it */
3307 pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, PACKET_remaining(pkt));
3308 if (pKX == NULL
3309 || pKX->kxBlob == NULL
3310 || ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {
3311 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3312 goto err;
3313 }
3314
3315 if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {
3316 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3317 goto err;
3318 }
3319
3320 if (PACKET_remaining(pkt) != 0) {
3321 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3322 goto err;
3323 }
3324
3325 inlen = pKX->kxBlob->value.sequence->length;
3326 start = pKX->kxBlob->value.sequence->data;
3327
3328 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3329 inlen)
3330 <= 0) {
3331 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3332 goto err;
3333 }
3334 /* Generate master secret */
3335 if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {
3336 /* SSLfatal() already called */
3337 goto err;
3338 }
3339 /* Check if pubkey from client certificate was used */
3340 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3341 NULL)
3342 > 0)
3343 s->statem.no_cert_verify = 1;
3344
3345 ret = 1;
3346 err:
3347 EVP_PKEY_CTX_free(pkey_ctx);
3348 GOST_KX_MESSAGE_free(pKX);
3349 return ret;
3350 #else
3351 /* Should never happen */
3352 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3353 return 0;
3354 #endif
3355 }
3356
tls_process_cke_gost18(SSL_CONNECTION * s,PACKET * pkt)3357 static int tls_process_cke_gost18(SSL_CONNECTION *s, PACKET *pkt)
3358 {
3359 #ifndef OPENSSL_NO_GOST
3360 unsigned char rnd_dgst[32];
3361 EVP_PKEY_CTX *pkey_ctx = NULL;
3362 EVP_PKEY *pk = NULL;
3363 unsigned char premaster_secret[32];
3364 const unsigned char *start = NULL;
3365 size_t outlen = sizeof(premaster_secret), inlen = 0;
3366 int ret = 0;
3367 int cipher_nid = ossl_gost18_cke_cipher_nid(s);
3368 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3369
3370 if (cipher_nid == NID_undef) {
3371 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3372 return 0;
3373 }
3374
3375 if (ossl_gost_ukm(s, rnd_dgst) <= 0) {
3376 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3377 goto err;
3378 }
3379
3380 /* Get our certificate private key */
3381 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;
3382 if (pk == NULL) {
3383 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
3384 goto err;
3385 }
3386
3387 pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);
3388 if (pkey_ctx == NULL) {
3389 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3390 goto err;
3391 }
3392 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3393 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3394 goto err;
3395 }
3396
3397 /* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code depending on size */
3398 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3399 EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst)
3400 <= 0) {
3401 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3402 goto err;
3403 }
3404
3405 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3406 EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL)
3407 <= 0) {
3408 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3409 goto err;
3410 }
3411 inlen = PACKET_remaining(pkt);
3412 start = PACKET_data(pkt);
3413
3414 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3415 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3416 goto err;
3417 }
3418 /* Generate master secret */
3419 if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {
3420 /* SSLfatal() already called */
3421 goto err;
3422 }
3423 ret = 1;
3424
3425 err:
3426 EVP_PKEY_CTX_free(pkey_ctx);
3427 return ret;
3428 #else
3429 /* Should never happen */
3430 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3431 return 0;
3432 #endif
3433 }
3434
tls_process_client_key_exchange(SSL_CONNECTION * s,PACKET * pkt)3435 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL_CONNECTION *s,
3436 PACKET *pkt)
3437 {
3438 unsigned long alg_k;
3439
3440 alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3441
3442 /* For PSK parse and retrieve identity, obtain PSK key */
3443 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3444 /* SSLfatal() already called */
3445 goto err;
3446 }
3447
3448 if (alg_k & SSL_kPSK) {
3449 /* Identity extracted earlier: should be nothing left */
3450 if (PACKET_remaining(pkt) != 0) {
3451 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3452 goto err;
3453 }
3454 /* PSK handled by ssl_generate_master_secret */
3455 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3456 /* SSLfatal() already called */
3457 goto err;
3458 }
3459 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3460 if (!tls_process_cke_rsa(s, pkt)) {
3461 /* SSLfatal() already called */
3462 goto err;
3463 }
3464 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3465 if (!tls_process_cke_dhe(s, pkt)) {
3466 /* SSLfatal() already called */
3467 goto err;
3468 }
3469 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3470 if (!tls_process_cke_ecdhe(s, pkt)) {
3471 /* SSLfatal() already called */
3472 goto err;
3473 }
3474 } else if (alg_k & SSL_kSRP) {
3475 if (!tls_process_cke_srp(s, pkt)) {
3476 /* SSLfatal() already called */
3477 goto err;
3478 }
3479 } else if (alg_k & SSL_kGOST) {
3480 if (!tls_process_cke_gost(s, pkt)) {
3481 /* SSLfatal() already called */
3482 goto err;
3483 }
3484 } else if (alg_k & SSL_kGOST18) {
3485 if (!tls_process_cke_gost18(s, pkt)) {
3486 /* SSLfatal() already called */
3487 goto err;
3488 }
3489 } else {
3490 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
3491 goto err;
3492 }
3493
3494 return MSG_PROCESS_CONTINUE_PROCESSING;
3495 err:
3496 #ifndef OPENSSL_NO_PSK
3497 OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3498 s->s3.tmp.psk = NULL;
3499 s->s3.tmp.psklen = 0;
3500 #endif
3501 return MSG_PROCESS_ERROR;
3502 }
3503
tls_post_process_client_key_exchange(SSL_CONNECTION * s,WORK_STATE wst)3504 WORK_STATE tls_post_process_client_key_exchange(SSL_CONNECTION *s,
3505 WORK_STATE wst)
3506 {
3507 #ifndef OPENSSL_NO_SCTP
3508 if (wst == WORK_MORE_A) {
3509 if (SSL_CONNECTION_IS_DTLS(s)) {
3510 unsigned char sctpauthkey[64];
3511 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3512 size_t labellen;
3513 /*
3514 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3515 * used.
3516 */
3517 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3518 sizeof(DTLS1_SCTP_AUTH_LABEL));
3519
3520 /* Don't include the terminating zero. */
3521 labellen = sizeof(labelbuffer) - 1;
3522 if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3523 labellen += 1;
3524
3525 if (SSL_export_keying_material(SSL_CONNECTION_GET_SSL(s),
3526 sctpauthkey,
3527 sizeof(sctpauthkey), labelbuffer,
3528 labellen, NULL, 0,
3529 0)
3530 <= 0) {
3531 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3532 return WORK_ERROR;
3533 }
3534
3535 BIO_ctrl(s->wbio, BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3536 sizeof(sctpauthkey), sctpauthkey);
3537 }
3538 }
3539 #endif
3540
3541 if (s->statem.no_cert_verify || !received_client_cert(s)) {
3542 /*
3543 * No certificate verify or no peer certificate so we no longer need
3544 * the handshake_buffer
3545 */
3546 if (!ssl3_digest_cached_records(s, 0)) {
3547 /* SSLfatal() already called */
3548 return WORK_ERROR;
3549 }
3550 return WORK_FINISHED_CONTINUE;
3551 } else {
3552 if (!s->s3.handshake_buffer) {
3553 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3554 return WORK_ERROR;
3555 }
3556 /*
3557 * For sigalgs freeze the handshake buffer. If we support
3558 * extms we've done this already so this is a no-op
3559 */
3560 if (!ssl3_digest_cached_records(s, 1)) {
3561 /* SSLfatal() already called */
3562 return WORK_ERROR;
3563 }
3564 }
3565
3566 return WORK_FINISHED_CONTINUE;
3567 }
3568
tls_process_client_rpk(SSL_CONNECTION * sc,PACKET * pkt)3569 MSG_PROCESS_RETURN tls_process_client_rpk(SSL_CONNECTION *sc, PACKET *pkt)
3570 {
3571 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3572 SSL_SESSION *new_sess = NULL;
3573 EVP_PKEY *peer_rpk = NULL;
3574
3575 if (!tls_process_rpk(sc, pkt, &peer_rpk)) {
3576 /* SSLfatal already called */
3577 goto err;
3578 }
3579
3580 if (peer_rpk == NULL) {
3581 if ((sc->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
3582 && (sc->verify_mode & SSL_VERIFY_PEER)) {
3583 SSLfatal(sc, SSL_AD_CERTIFICATE_REQUIRED,
3584 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3585 goto err;
3586 }
3587 } else {
3588 if (ssl_verify_rpk(sc, peer_rpk) <= 0) {
3589 SSLfatal(sc, ssl_x509err2alert(sc->verify_result),
3590 SSL_R_CERTIFICATE_VERIFY_FAILED);
3591 goto err;
3592 }
3593 }
3594
3595 /*
3596 * Sessions must be immutable once they go into the session cache. Otherwise
3597 * we can get multi-thread problems. Therefore we don't "update" sessions,
3598 * we replace them with a duplicate. Here, we need to do this every time
3599 * a new RPK (or certificate) is received via post-handshake authentication,
3600 * as the session may have already gone into the session cache.
3601 */
3602
3603 if (sc->post_handshake_auth == SSL_PHA_REQUESTED) {
3604 if ((new_sess = ssl_session_dup(sc->session, 0)) == NULL) {
3605 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3606 goto err;
3607 }
3608
3609 SSL_SESSION_free(sc->session);
3610 sc->session = new_sess;
3611 }
3612
3613 /* Ensure there is no peer/peer_chain */
3614 X509_free(sc->session->peer);
3615 sc->session->peer = NULL;
3616 sk_X509_pop_free(sc->session->peer_chain, X509_free);
3617 sc->session->peer_chain = NULL;
3618 /* Save RPK */
3619 EVP_PKEY_free(sc->session->peer_rpk);
3620 sc->session->peer_rpk = peer_rpk;
3621 peer_rpk = NULL;
3622
3623 sc->session->verify_result = sc->verify_result;
3624
3625 /*
3626 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3627 * message
3628 */
3629 if (SSL_CONNECTION_IS_TLS13(sc)) {
3630 if (!ssl3_digest_cached_records(sc, 1)) {
3631 /* SSLfatal() already called */
3632 goto err;
3633 }
3634
3635 /* Save the current hash state for when we receive the CertificateVerify */
3636 if (!ssl_handshake_hash(sc, sc->cert_verify_hash,
3637 sizeof(sc->cert_verify_hash),
3638 &sc->cert_verify_hash_len)) {
3639 /* SSLfatal() already called */;
3640 goto err;
3641 }
3642
3643 /* resend session tickets */
3644 sc->sent_tickets = 0;
3645 }
3646
3647 ret = MSG_PROCESS_CONTINUE_READING;
3648
3649 err:
3650 EVP_PKEY_free(peer_rpk);
3651 return ret;
3652 }
3653
tls_process_client_certificate(SSL_CONNECTION * s,PACKET * pkt)3654 MSG_PROCESS_RETURN tls_process_client_certificate(SSL_CONNECTION *s,
3655 PACKET *pkt)
3656 {
3657 int i;
3658 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3659 X509 *x = NULL;
3660 unsigned long l;
3661 const unsigned char *certstart, *certbytes;
3662 STACK_OF(X509) *sk = NULL;
3663 PACKET spkt, context;
3664 size_t chainidx;
3665 SSL_SESSION *new_sess = NULL;
3666 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3667
3668 /*
3669 * To get this far we must have read encrypted data from the client. We no
3670 * longer tolerate unencrypted alerts. This is ignored if less than TLSv1.3
3671 */
3672 if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
3673 s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
3674
3675 if (s->ext.client_cert_type == TLSEXT_cert_type_rpk)
3676 return tls_process_client_rpk(s, pkt);
3677
3678 if (s->ext.client_cert_type != TLSEXT_cert_type_x509) {
3679 SSLfatal(s, SSL_AD_UNSUPPORTED_CERTIFICATE,
3680 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3681 goto err;
3682 }
3683
3684 if ((sk = sk_X509_new_null()) == NULL) {
3685 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3686 goto err;
3687 }
3688
3689 if (SSL_CONNECTION_IS_TLS13(s)
3690 && (!PACKET_get_length_prefixed_1(pkt, &context)
3691 || (s->pha_context == NULL && PACKET_remaining(&context) != 0)
3692 || (s->pha_context != NULL
3693 && !PACKET_equal(&context, s->pha_context,
3694 s->pha_context_len)))) {
3695 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
3696 goto err;
3697 }
3698
3699 if (!PACKET_get_length_prefixed_3(pkt, &spkt)
3700 || PACKET_remaining(pkt) != 0) {
3701 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3702 goto err;
3703 }
3704
3705 for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3706 if (!PACKET_get_net_3(&spkt, &l)
3707 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3708 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
3709 goto err;
3710 }
3711
3712 certstart = certbytes;
3713 x = X509_new_ex(sctx->libctx, sctx->propq);
3714 if (x == NULL) {
3715 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_X509_LIB);
3716 goto err;
3717 }
3718 if (d2i_X509(&x, (const unsigned char **)&certbytes, l) == NULL) {
3719 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
3720 goto err;
3721 }
3722
3723 if (certbytes != (certstart + l)) {
3724 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
3725 goto err;
3726 }
3727
3728 if (SSL_CONNECTION_IS_TLS13(s)) {
3729 RAW_EXTENSION *rawexts = NULL;
3730 PACKET extensions;
3731
3732 if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3733 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
3734 goto err;
3735 }
3736 if (!tls_collect_extensions(s, &extensions,
3737 SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3738 NULL, chainidx == 0)
3739 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3740 rawexts, x, chainidx,
3741 PACKET_remaining(&spkt) == 0)) {
3742 OPENSSL_free(rawexts);
3743 goto err;
3744 }
3745 OPENSSL_free(rawexts);
3746 }
3747
3748 if (!sk_X509_push(sk, x)) {
3749 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3750 goto err;
3751 }
3752 x = NULL;
3753 }
3754
3755 if (sk_X509_num(sk) <= 0) {
3756 /* TLS does not mind 0 certs returned */
3757 if (s->version == SSL3_VERSION) {
3758 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3759 SSL_R_NO_CERTIFICATES_RETURNED);
3760 goto err;
3761 }
3762 /* Fail for TLS only if we required a certificate */
3763 else if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3764 SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
3765 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3766 goto err;
3767 }
3768 /* No client certificate so digest cached records */
3769 if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3770 /* SSLfatal() already called */
3771 goto err;
3772 }
3773 } else {
3774 EVP_PKEY *pkey;
3775 i = ssl_verify_cert_chain(s, sk);
3776 if (i <= 0) {
3777 SSLfatal(s, ssl_x509err2alert(s->verify_result),
3778 SSL_R_CERTIFICATE_VERIFY_FAILED);
3779 goto err;
3780 }
3781 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3782 if (pkey == NULL) {
3783 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3784 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3785 goto err;
3786 }
3787 }
3788
3789 /*
3790 * Sessions must be immutable once they go into the session cache. Otherwise
3791 * we can get multi-thread problems. Therefore we don't "update" sessions,
3792 * we replace them with a duplicate. Here, we need to do this every time
3793 * a new certificate is received via post-handshake authentication, as the
3794 * session may have already gone into the session cache.
3795 */
3796
3797 if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
3798 if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
3799 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
3800 goto err;
3801 }
3802
3803 SSL_SESSION_free(s->session);
3804 s->session = new_sess;
3805 }
3806
3807 X509_free(s->session->peer);
3808 s->session->peer = sk_X509_shift(sk);
3809 s->session->verify_result = s->verify_result;
3810
3811 OSSL_STACK_OF_X509_free(s->session->peer_chain);
3812 s->session->peer_chain = sk;
3813 sk = NULL;
3814 /* Ensure there is no RPK */
3815 EVP_PKEY_free(s->session->peer_rpk);
3816 s->session->peer_rpk = NULL;
3817
3818 /*
3819 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3820 * message
3821 */
3822 if (SSL_CONNECTION_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3823 /* SSLfatal() already called */
3824 goto err;
3825 }
3826
3827 /*
3828 * Inconsistency alert: cert_chain does *not* include the peer's own
3829 * certificate, while we do include it in statem_clnt.c
3830 */
3831
3832 /* Save the current hash state for when we receive the CertificateVerify */
3833 if (SSL_CONNECTION_IS_TLS13(s)) {
3834 if (!ssl_handshake_hash(s, s->cert_verify_hash,
3835 sizeof(s->cert_verify_hash),
3836 &s->cert_verify_hash_len)) {
3837 /* SSLfatal() already called */
3838 goto err;
3839 }
3840
3841 /* Resend session tickets */
3842 s->sent_tickets = 0;
3843 }
3844
3845 ret = MSG_PROCESS_CONTINUE_READING;
3846
3847 err:
3848 X509_free(x);
3849 OSSL_STACK_OF_X509_free(sk);
3850 return ret;
3851 }
3852
3853 #ifndef OPENSSL_NO_COMP_ALG
tls_process_client_compressed_certificate(SSL_CONNECTION * sc,PACKET * pkt)3854 MSG_PROCESS_RETURN tls_process_client_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)
3855 {
3856 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3857 PACKET tmppkt;
3858 BUF_MEM *buf = BUF_MEM_new();
3859
3860 if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)
3861 ret = tls_process_client_certificate(sc, &tmppkt);
3862
3863 BUF_MEM_free(buf);
3864 return ret;
3865 }
3866 #endif
3867
tls_construct_server_certificate(SSL_CONNECTION * s,WPACKET * pkt)3868 CON_FUNC_RETURN tls_construct_server_certificate(SSL_CONNECTION *s, WPACKET *pkt)
3869 {
3870 CERT_PKEY *cpk = s->s3.tmp.cert;
3871
3872 if (cpk == NULL) {
3873 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3874 return CON_FUNC_ERROR;
3875 }
3876
3877 /*
3878 * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3879 * for the server Certificate message
3880 */
3881 if (SSL_CONNECTION_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
3882 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3883 return CON_FUNC_ERROR;
3884 }
3885 switch (s->ext.server_cert_type) {
3886 case TLSEXT_cert_type_rpk:
3887 if (!tls_output_rpk(s, pkt, cpk)) {
3888 /* SSLfatal() already called */
3889 return 0;
3890 }
3891 break;
3892 case TLSEXT_cert_type_x509:
3893 if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {
3894 /* SSLfatal() already called */
3895 return 0;
3896 }
3897 break;
3898 default:
3899 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3900 return 0;
3901 }
3902
3903 return CON_FUNC_SUCCESS;
3904 }
3905
3906 #ifndef OPENSSL_NO_COMP_ALG
tls_construct_server_compressed_certificate(SSL_CONNECTION * sc,WPACKET * pkt)3907 CON_FUNC_RETURN tls_construct_server_compressed_certificate(SSL_CONNECTION *sc, WPACKET *pkt)
3908 {
3909 int alg = get_compressed_certificate_alg(sc);
3910 OSSL_COMP_CERT *cc = sc->s3.tmp.cert->comp_cert[alg];
3911
3912 if (!ossl_assert(cc != NULL)) {
3913 SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3914 return 0;
3915 }
3916 /*
3917 * Server can't compress on-demand
3918 * Use pre-compressed certificate
3919 */
3920 if (!WPACKET_put_bytes_u16(pkt, alg)
3921 || !WPACKET_put_bytes_u24(pkt, cc->orig_len)
3922 || !WPACKET_start_sub_packet_u24(pkt)
3923 || !WPACKET_memcpy(pkt, cc->data, cc->len)
3924 || !WPACKET_close(pkt))
3925 return 0;
3926
3927 sc->s3.tmp.cert->cert_comp_used++;
3928 return 1;
3929 }
3930 #endif
3931
create_ticket_prequel(SSL_CONNECTION * s,WPACKET * pkt,uint32_t age_add,unsigned char * tick_nonce)3932 static int create_ticket_prequel(SSL_CONNECTION *s, WPACKET *pkt,
3933 uint32_t age_add, unsigned char *tick_nonce)
3934 {
3935 uint32_t timeout = (uint32_t)ossl_time2seconds(s->session->timeout);
3936
3937 /*
3938 * Ticket lifetime hint:
3939 * In TLSv1.3 we reset the "time" field above, and always specify the
3940 * timeout, limited to a 1 week period per RFC8446.
3941 * For TLSv1.2 this is advisory only and we leave this unspecified for
3942 * resumed session (for simplicity).
3943 */
3944 #define ONE_WEEK_SEC (7 * 24 * 60 * 60)
3945
3946 if (SSL_CONNECTION_IS_TLS13(s)) {
3947 if (ossl_time_compare(s->session->timeout,
3948 ossl_seconds2time(ONE_WEEK_SEC))
3949 > 0)
3950 timeout = ONE_WEEK_SEC;
3951 } else if (s->hit)
3952 timeout = 0;
3953
3954 if (!WPACKET_put_bytes_u32(pkt, timeout)) {
3955 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3956 return 0;
3957 }
3958
3959 if (SSL_CONNECTION_IS_TLS13(s)) {
3960 if (!WPACKET_put_bytes_u32(pkt, age_add)
3961 || !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {
3962 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3963 return 0;
3964 }
3965 }
3966
3967 /* Start the sub-packet for the actual ticket data */
3968 if (!WPACKET_start_sub_packet_u16(pkt)) {
3969 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3970 return 0;
3971 }
3972
3973 return 1;
3974 }
3975
construct_stateless_ticket(SSL_CONNECTION * s,WPACKET * pkt,uint32_t age_add,unsigned char * tick_nonce)3976 static CON_FUNC_RETURN construct_stateless_ticket(SSL_CONNECTION *s,
3977 WPACKET *pkt,
3978 uint32_t age_add,
3979 unsigned char *tick_nonce)
3980 {
3981 unsigned char *senc = NULL;
3982 EVP_CIPHER_CTX *ctx = NULL;
3983 SSL_HMAC *hctx = NULL;
3984 unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3985 const unsigned char *const_p;
3986 int len, slen_full, slen, lenfinal;
3987 SSL_SESSION *sess;
3988 size_t hlen;
3989 SSL_CTX *tctx = s->session_ctx;
3990 unsigned char iv[EVP_MAX_IV_LENGTH];
3991 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3992 int iv_len;
3993 CON_FUNC_RETURN ok = CON_FUNC_ERROR;
3994 size_t macoffset, macendoffset;
3995 SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
3996 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3997
3998 /* get session encoding length */
3999 slen_full = i2d_SSL_SESSION(s->session, NULL);
4000 /*
4001 * Some length values are 16 bits, so forget it if session is too
4002 * long
4003 */
4004 if (slen_full == 0 || slen_full > 0xFF00) {
4005 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4006 goto err;
4007 }
4008 senc = OPENSSL_malloc(slen_full);
4009 if (senc == NULL) {
4010 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4011 goto err;
4012 }
4013
4014 ctx = EVP_CIPHER_CTX_new();
4015 if (ctx == NULL) {
4016 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
4017 goto err;
4018 }
4019 hctx = ssl_hmac_new(tctx);
4020 if (hctx == NULL) {
4021 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
4022 goto err;
4023 }
4024
4025 p = senc;
4026 if (!i2d_SSL_SESSION(s->session, &p)) {
4027 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4028 goto err;
4029 }
4030
4031 /*
4032 * create a fresh copy (not shared with other threads) to clean up
4033 */
4034 const_p = senc;
4035 sess = d2i_SSL_SESSION_ex(NULL, &const_p, slen_full, sctx->libctx,
4036 sctx->propq);
4037 if (sess == NULL) {
4038 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4039 goto err;
4040 }
4041
4042 slen = i2d_SSL_SESSION(sess, NULL);
4043 if (slen == 0 || slen > slen_full) {
4044 /* shouldn't ever happen */
4045 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4046 SSL_SESSION_free(sess);
4047 goto err;
4048 }
4049 p = senc;
4050 if (!i2d_SSL_SESSION(sess, &p)) {
4051 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4052 SSL_SESSION_free(sess);
4053 goto err;
4054 }
4055 SSL_SESSION_free(sess);
4056
4057 /*
4058 * Initialize HMAC and cipher contexts. If callback present it does
4059 * all the work otherwise use generated values from parent ctx.
4060 */
4061 #ifndef OPENSSL_NO_DEPRECATED_3_0
4062 if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
4063 #else
4064 if (tctx->ext.ticket_key_evp_cb != NULL)
4065 #endif
4066 {
4067 int ret = 0;
4068
4069 if (tctx->ext.ticket_key_evp_cb != NULL)
4070 ret = tctx->ext.ticket_key_evp_cb(ssl, key_name, iv, ctx,
4071 ssl_hmac_get0_EVP_MAC_CTX(hctx),
4072 1);
4073 #ifndef OPENSSL_NO_DEPRECATED_3_0
4074 else if (tctx->ext.ticket_key_cb != NULL)
4075 /* if 0 is returned, write an empty ticket */
4076 ret = tctx->ext.ticket_key_cb(ssl, key_name, iv, ctx,
4077 ssl_hmac_get0_HMAC_CTX(hctx), 1);
4078 #endif
4079
4080 if (ret == 0) {
4081 /*
4082 * In TLSv1.2 we construct a 0 length ticket. In TLSv1.3 a 0
4083 * length ticket is not allowed so we abort construction of the
4084 * ticket
4085 */
4086 if (SSL_CONNECTION_IS_TLS13(s)) {
4087 ok = CON_FUNC_DONT_SEND;
4088 goto err;
4089 }
4090 /* Put timeout and length */
4091 if (!WPACKET_put_bytes_u32(pkt, 0)
4092 || !WPACKET_put_bytes_u16(pkt, 0)) {
4093 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4094 goto err;
4095 }
4096 OPENSSL_free(senc);
4097 EVP_CIPHER_CTX_free(ctx);
4098 ssl_hmac_free(hctx);
4099 return CON_FUNC_SUCCESS;
4100 }
4101 if (ret < 0) {
4102 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
4103 goto err;
4104 }
4105 iv_len = EVP_CIPHER_CTX_get_iv_length(ctx);
4106 if (iv_len < 0) {
4107 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4108 goto err;
4109 }
4110 } else {
4111 EVP_CIPHER *cipher = EVP_CIPHER_fetch(sctx->libctx, "AES-256-CBC",
4112 sctx->propq);
4113
4114 if (cipher == NULL) {
4115 /* Error is already recorded */
4116 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
4117 goto err;
4118 }
4119
4120 iv_len = EVP_CIPHER_get_iv_length(cipher);
4121 if (iv_len < 0
4122 || RAND_bytes_ex(sctx->libctx, iv, iv_len, 0) <= 0
4123 || !EVP_EncryptInit_ex(ctx, cipher, NULL,
4124 tctx->ext.secure->tick_aes_key, iv)
4125 || !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
4126 sizeof(tctx->ext.secure->tick_hmac_key),
4127 "SHA256")) {
4128 EVP_CIPHER_free(cipher);
4129 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4130 goto err;
4131 }
4132 EVP_CIPHER_free(cipher);
4133 memcpy(key_name, tctx->ext.tick_key_name,
4134 sizeof(tctx->ext.tick_key_name));
4135 }
4136
4137 if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4138 /* SSLfatal() already called */
4139 goto err;
4140 }
4141
4142 if (!WPACKET_get_total_written(pkt, &macoffset)
4143 /* Output key name */
4144 || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
4145 /* output IV */
4146 || !WPACKET_memcpy(pkt, iv, iv_len)
4147 || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
4148 &encdata1)
4149 /* Encrypt session data */
4150 || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
4151 || !WPACKET_allocate_bytes(pkt, len, &encdata2)
4152 || encdata1 != encdata2
4153 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
4154 || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
4155 || encdata1 + len != encdata2
4156 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
4157 || !WPACKET_get_total_written(pkt, &macendoffset)
4158 || !ssl_hmac_update(hctx,
4159 (unsigned char *)s->init_buf->data + macoffset,
4160 macendoffset - macoffset)
4161 || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
4162 || !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)
4163 || hlen > EVP_MAX_MD_SIZE
4164 || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
4165 || macdata1 != macdata2) {
4166 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4167 goto err;
4168 }
4169
4170 /* Close the sub-packet created by create_ticket_prequel() */
4171 if (!WPACKET_close(pkt)) {
4172 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4173 goto err;
4174 }
4175
4176 ok = CON_FUNC_SUCCESS;
4177 err:
4178 OPENSSL_free(senc);
4179 EVP_CIPHER_CTX_free(ctx);
4180 ssl_hmac_free(hctx);
4181 return ok;
4182 }
4183
construct_stateful_ticket(SSL_CONNECTION * s,WPACKET * pkt,uint32_t age_add,unsigned char * tick_nonce)4184 static int construct_stateful_ticket(SSL_CONNECTION *s, WPACKET *pkt,
4185 uint32_t age_add,
4186 unsigned char *tick_nonce)
4187 {
4188 if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4189 /* SSLfatal() already called */
4190 return 0;
4191 }
4192
4193 if (!WPACKET_memcpy(pkt, s->session->session_id,
4194 s->session->session_id_length)
4195 || !WPACKET_close(pkt)) {
4196 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4197 return 0;
4198 }
4199
4200 return 1;
4201 }
4202
tls_update_ticket_counts(SSL_CONNECTION * s)4203 static void tls_update_ticket_counts(SSL_CONNECTION *s)
4204 {
4205 /*
4206 * Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|
4207 * gets reset to 0 if we send more tickets following a post-handshake
4208 * auth, but |next_ticket_nonce| does not. If we're sending extra
4209 * tickets, decrement the count of pending extra tickets.
4210 */
4211 s->sent_tickets++;
4212 s->next_ticket_nonce++;
4213 if (s->ext.extra_tickets_expected > 0)
4214 s->ext.extra_tickets_expected--;
4215 }
4216
tls_construct_new_session_ticket(SSL_CONNECTION * s,WPACKET * pkt)4217 CON_FUNC_RETURN tls_construct_new_session_ticket(SSL_CONNECTION *s, WPACKET *pkt)
4218 {
4219 SSL_CTX *tctx = s->session_ctx;
4220 unsigned char tick_nonce[TICKET_NONCE_SIZE];
4221 union {
4222 unsigned char age_add_c[sizeof(uint32_t)];
4223 uint32_t age_add;
4224 } age_add_u;
4225 CON_FUNC_RETURN ret = CON_FUNC_ERROR;
4226
4227 age_add_u.age_add = 0;
4228
4229 if (SSL_CONNECTION_IS_TLS13(s)) {
4230 size_t i, hashlen;
4231 uint64_t nonce;
4232 /* ASCII: "resumption", in hex for EBCDIC compatibility */
4233 static const unsigned char nonce_label[] = { 0x72, 0x65, 0x73, 0x75, 0x6D,
4234 0x70, 0x74, 0x69, 0x6F, 0x6E };
4235 const EVP_MD *md = ssl_handshake_md(s);
4236 int hashleni = EVP_MD_get_size(md);
4237
4238 /* Ensure cast to size_t is safe */
4239 if (!ossl_assert(hashleni > 0)) {
4240 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4241 goto err;
4242 }
4243 hashlen = (size_t)hashleni;
4244
4245 /*
4246 * If we already sent one NewSessionTicket, or we resumed then
4247 * s->session may already be in a cache and so we must not modify it.
4248 * Instead we need to take a copy of it and modify that.
4249 */
4250 if (s->sent_tickets != 0 || s->hit) {
4251 SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);
4252
4253 if (new_sess == NULL) {
4254 /* SSLfatal already called */
4255 goto err;
4256 }
4257
4258 SSL_SESSION_free(s->session);
4259 s->session = new_sess;
4260 }
4261
4262 if (!ssl_generate_session_id(s, s->session)) {
4263 /* SSLfatal() already called */
4264 goto err;
4265 }
4266 if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
4267 age_add_u.age_add_c, sizeof(age_add_u), 0)
4268 <= 0) {
4269 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4270 goto err;
4271 }
4272 s->session->ext.tick_age_add = age_add_u.age_add;
4273
4274 nonce = s->next_ticket_nonce;
4275 for (i = TICKET_NONCE_SIZE; i > 0; i--) {
4276 tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);
4277 nonce >>= 8;
4278 }
4279
4280 if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
4281 nonce_label,
4282 sizeof(nonce_label),
4283 tick_nonce,
4284 TICKET_NONCE_SIZE,
4285 s->session->master_key,
4286 hashlen, 1)) {
4287 /* SSLfatal() already called */
4288 goto err;
4289 }
4290 s->session->master_key_length = hashlen;
4291
4292 s->session->time = ossl_time_now();
4293 ssl_session_calculate_timeout(s->session);
4294 if (s->s3.alpn_selected != NULL) {
4295 OPENSSL_free(s->session->ext.alpn_selected);
4296 s->session->ext.alpn_selected = OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);
4297 if (s->session->ext.alpn_selected == NULL) {
4298 s->session->ext.alpn_selected_len = 0;
4299 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4300 goto err;
4301 }
4302 s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
4303 }
4304 s->session->ext.max_early_data = s->max_early_data;
4305 }
4306
4307 if (tctx->generate_ticket_cb != NULL && tctx->generate_ticket_cb(SSL_CONNECTION_GET_USER_SSL(s), tctx->ticket_cb_data) == 0) {
4308 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4309 goto err;
4310 }
4311 /*
4312 * If we are using anti-replay protection then we behave as if
4313 * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
4314 * is no point in using full stateless tickets.
4315 */
4316 if (SSL_CONNECTION_IS_TLS13(s)
4317 && ((s->options & SSL_OP_NO_TICKET) != 0
4318 || (s->max_early_data > 0
4319 && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {
4320 if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {
4321 /* SSLfatal() already called */
4322 goto err;
4323 }
4324 } else {
4325 CON_FUNC_RETURN tmpret;
4326
4327 tmpret = construct_stateless_ticket(s, pkt, age_add_u.age_add,
4328 tick_nonce);
4329 if (tmpret != CON_FUNC_SUCCESS) {
4330 if (tmpret == CON_FUNC_DONT_SEND) {
4331 /* Non-fatal. Abort construction but continue */
4332 ret = CON_FUNC_DONT_SEND;
4333 /* We count this as a success so update the counts anwyay */
4334 tls_update_ticket_counts(s);
4335 }
4336 /* else SSLfatal() already called */
4337 goto err;
4338 }
4339 }
4340
4341 if (SSL_CONNECTION_IS_TLS13(s)) {
4342 if (!tls_construct_extensions(s, pkt,
4343 SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
4344 NULL, 0)) {
4345 /* SSLfatal() already called */
4346 goto err;
4347 }
4348 tls_update_ticket_counts(s);
4349 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
4350 }
4351
4352 ret = CON_FUNC_SUCCESS;
4353 err:
4354 return ret;
4355 }
4356
4357 /*
4358 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
4359 * create a separate message. Returns 1 on success or 0 on failure.
4360 */
tls_construct_cert_status_body(SSL_CONNECTION * s,WPACKET * pkt)4361 int tls_construct_cert_status_body(SSL_CONNECTION *s, WPACKET *pkt)
4362 {
4363 if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
4364 || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
4365 s->ext.ocsp.resp_len)) {
4366 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4367 return 0;
4368 }
4369
4370 return 1;
4371 }
4372
tls_construct_cert_status(SSL_CONNECTION * s,WPACKET * pkt)4373 CON_FUNC_RETURN tls_construct_cert_status(SSL_CONNECTION *s, WPACKET *pkt)
4374 {
4375 if (!tls_construct_cert_status_body(s, pkt)) {
4376 /* SSLfatal() already called */
4377 return CON_FUNC_ERROR;
4378 }
4379
4380 return CON_FUNC_SUCCESS;
4381 }
4382
4383 #ifndef OPENSSL_NO_NEXTPROTONEG
4384 /*
4385 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
4386 * It sets the next_proto member in s if found
4387 */
tls_process_next_proto(SSL_CONNECTION * s,PACKET * pkt)4388 MSG_PROCESS_RETURN tls_process_next_proto(SSL_CONNECTION *s, PACKET *pkt)
4389 {
4390 PACKET next_proto, padding;
4391 size_t next_proto_len;
4392
4393 /*-
4394 * The payload looks like:
4395 * uint8 proto_len;
4396 * uint8 proto[proto_len];
4397 * uint8 padding_len;
4398 * uint8 padding[padding_len];
4399 */
4400 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
4401 || !PACKET_get_length_prefixed_1(pkt, &padding)
4402 || PACKET_remaining(pkt) > 0) {
4403 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4404 return MSG_PROCESS_ERROR;
4405 }
4406
4407 if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
4408 s->ext.npn_len = 0;
4409 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4410 return MSG_PROCESS_ERROR;
4411 }
4412
4413 s->ext.npn_len = (unsigned char)next_proto_len;
4414
4415 return MSG_PROCESS_CONTINUE_READING;
4416 }
4417 #endif
4418
tls_construct_encrypted_extensions(SSL_CONNECTION * s,WPACKET * pkt)4419 static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,
4420 WPACKET *pkt)
4421 {
4422 if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
4423 NULL, 0)) {
4424 /* SSLfatal() already called */
4425 return CON_FUNC_ERROR;
4426 }
4427
4428 return CON_FUNC_SUCCESS;
4429 }
4430
tls_process_end_of_early_data(SSL_CONNECTION * s,PACKET * pkt)4431 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL_CONNECTION *s, PACKET *pkt)
4432 {
4433 if (PACKET_remaining(pkt) != 0) {
4434 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4435 return MSG_PROCESS_ERROR;
4436 }
4437
4438 if (s->early_data_state != SSL_EARLY_DATA_READING
4439 && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
4440 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4441 return MSG_PROCESS_ERROR;
4442 }
4443
4444 /*
4445 * EndOfEarlyData signals a key change so the end of the message must be on
4446 * a record boundary.
4447 */
4448 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
4449 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
4450 return MSG_PROCESS_ERROR;
4451 }
4452
4453 s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
4454 if (!SSL_CONNECTION_GET_SSL(s)->method->ssl3_enc->change_cipher_state(s,
4455 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
4456 /* SSLfatal() already called */
4457 return MSG_PROCESS_ERROR;
4458 }
4459
4460 return MSG_PROCESS_CONTINUE_READING;
4461 }
4462