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