]> git.ipfire.org Git - thirdparty/openssl.git/blob - ssl/statem/statem_srvr.c
make EVP_PKEY opaque
[thirdparty/openssl.git] / ssl / statem / statem_srvr.c
1 /* ssl/statem/statem_srvr.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58 /* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111 /* ====================================================================
112 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113 *
114 * Portions of the attached software ("Contribution") are developed by
115 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116 *
117 * The Contribution is licensed pursuant to the OpenSSL open source
118 * license provided above.
119 *
120 * ECC cipher suite support in OpenSSL originally written by
121 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122 *
123 */
124 /* ====================================================================
125 * Copyright 2005 Nokia. All rights reserved.
126 *
127 * The portions of the attached software ("Contribution") is developed by
128 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129 * license.
130 *
131 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133 * support (see RFC 4279) to OpenSSL.
134 *
135 * No patent licenses or other rights except those expressly stated in
136 * the OpenSSL open source license shall be deemed granted or received
137 * expressly, by implication, estoppel, or otherwise.
138 *
139 * No assurances are provided by Nokia that the Contribution does not
140 * infringe the patent or other intellectual property rights of any third
141 * party or that the license provides you with all the necessary rights
142 * to make use of the Contribution.
143 *
144 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148 * OTHERWISE.
149 */
150
151
152 #include <stdio.h>
153 #include "../ssl_locl.h"
154 #include "statem_locl.h"
155 #include "internal/constant_time_locl.h"
156 #include <openssl/buffer.h>
157 #include <openssl/rand.h>
158 #include <openssl/objects.h>
159 #include <openssl/evp.h>
160 #include <openssl/hmac.h>
161 #include <openssl/x509.h>
162 #ifndef OPENSSL_NO_DH
163 # include <openssl/dh.h>
164 #endif
165 #include <openssl/bn.h>
166 #include <openssl/md5.h>
167
168 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
169 PACKET *cipher_suites,
170 STACK_OF(SSL_CIPHER) **skp,
171 int sslv2format, int *al);
172
173 /*
174 * server_read_transition() encapsulates the logic for the allowed handshake
175 * state transitions when the server is reading messages from the client. The
176 * message type that the client has sent is provided in |mt|. The current state
177 * is in |s->statem.hand_state|.
178 *
179 * Valid return values are:
180 * 1: Success (transition allowed)
181 * 0: Error (transition not allowed)
182 */
183 int ossl_statem_server_read_transition(SSL *s, int mt)
184 {
185 OSSL_STATEM *st = &s->statem;
186
187 switch(st->hand_state) {
188 case TLS_ST_BEFORE:
189 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
190 if (mt == SSL3_MT_CLIENT_HELLO) {
191 st->hand_state = TLS_ST_SR_CLNT_HELLO;
192 return 1;
193 }
194 break;
195
196 case TLS_ST_SW_SRVR_DONE:
197 /*
198 * If we get a CKE message after a ServerDone then either
199 * 1) We didn't request a Certificate
200 * OR
201 * 2) If we did request one then
202 * a) We allow no Certificate to be returned
203 * AND
204 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
205 * list if we requested a certificate)
206 */
207 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE
208 && (!s->s3->tmp.cert_request
209 || (!((s->verify_mode & SSL_VERIFY_PEER) &&
210 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
211 && (s->version == SSL3_VERSION)))) {
212 st->hand_state = TLS_ST_SR_KEY_EXCH;
213 return 1;
214 } else if (s->s3->tmp.cert_request) {
215 if (mt == SSL3_MT_CERTIFICATE) {
216 st->hand_state = TLS_ST_SR_CERT;
217 return 1;
218 }
219 }
220 break;
221
222 case TLS_ST_SR_CERT:
223 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
224 st->hand_state = TLS_ST_SR_KEY_EXCH;
225 return 1;
226 }
227 break;
228
229 case TLS_ST_SR_KEY_EXCH:
230 /*
231 * We should only process a CertificateVerify message if we have
232 * received a Certificate from the client. If so then |s->session->peer|
233 * will be non NULL. In some instances a CertificateVerify message is
234 * not required even if the peer has sent a Certificate (e.g. such as in
235 * the case of static DH). In that case |st->no_cert_verify| should be
236 * set.
237 */
238 if (s->session->peer == NULL || st->no_cert_verify) {
239 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
240 /*
241 * For the ECDH ciphersuites when the client sends its ECDH
242 * pub key in a certificate, the CertificateVerify message is
243 * not sent. Also for GOST ciphersuites when the client uses
244 * its key from the certificate for key exchange.
245 */
246 st->hand_state = TLS_ST_SR_CHANGE;
247 return 1;
248 }
249 } else {
250 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
251 st->hand_state = TLS_ST_SR_CERT_VRFY;
252 return 1;
253 }
254 }
255 break;
256
257 case TLS_ST_SR_CERT_VRFY:
258 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
259 st->hand_state = TLS_ST_SR_CHANGE;
260 return 1;
261 }
262 break;
263
264 case TLS_ST_SR_CHANGE:
265 #ifndef OPENSSL_NO_NEXTPROTONEG
266 if (s->s3->next_proto_neg_seen) {
267 if (mt == SSL3_MT_NEXT_PROTO) {
268 st->hand_state = TLS_ST_SR_NEXT_PROTO;
269 return 1;
270 }
271 } else {
272 #endif
273 if (mt == SSL3_MT_FINISHED) {
274 st->hand_state = TLS_ST_SR_FINISHED;
275 return 1;
276 }
277 #ifndef OPENSSL_NO_NEXTPROTONEG
278 }
279 #endif
280 break;
281
282 #ifndef OPENSSL_NO_NEXTPROTONEG
283 case TLS_ST_SR_NEXT_PROTO:
284 if (mt == SSL3_MT_FINISHED) {
285 st->hand_state = TLS_ST_SR_FINISHED;
286 return 1;
287 }
288 break;
289 #endif
290
291 case TLS_ST_SW_FINISHED:
292 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
293 st->hand_state = TLS_ST_SR_CHANGE;
294 return 1;
295 }
296 break;
297
298 default:
299 break;
300 }
301
302 /* No valid transition found */
303 return 0;
304 }
305
306 /*
307 * Should we send a ServerKeyExchange message?
308 *
309 * Valid return values are:
310 * 1: Yes
311 * 0: No
312 */
313 static int send_server_key_exchange(SSL *s)
314 {
315 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
316
317 /*
318 * only send a ServerKeyExchange if DH or fortezza but we have a
319 * sign only certificate PSK: may send PSK identity hints For
320 * ECC ciphersuites, we send a serverKeyExchange message only if
321 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
322 * the server certificate contains the server's public key for
323 * key exchange.
324 */
325 if (alg_k & (SSL_kDHE|SSL_kECDHE)
326 /*
327 * PSK: send ServerKeyExchange if PSK identity hint if
328 * provided
329 */
330 #ifndef OPENSSL_NO_PSK
331 /* Only send SKE if we have identity hint for plain PSK */
332 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
333 && s->cert->psk_identity_hint)
334 /* For other PSK always send SKE */
335 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
336 #endif
337 #ifndef OPENSSL_NO_SRP
338 /* SRP: send ServerKeyExchange */
339 || (alg_k & SSL_kSRP)
340 #endif
341 ) {
342 return 1;
343 }
344
345 return 0;
346 }
347
348 /*
349 * Should we send a CertificateRequest message?
350 *
351 * Valid return values are:
352 * 1: Yes
353 * 0: No
354 */
355 static int send_certificate_request(SSL *s)
356 {
357 if (
358 /* don't request cert unless asked for it: */
359 s->verify_mode & SSL_VERIFY_PEER
360 /*
361 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
362 * during re-negotiation:
363 */
364 && ((s->session->peer == NULL) ||
365 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
366 /*
367 * never request cert in anonymous ciphersuites (see
368 * section "Certificate request" in SSL 3 drafts and in
369 * RFC 2246):
370 */
371 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
372 /*
373 * ... except when the application insists on
374 * verification (against the specs, but s3_clnt.c accepts
375 * this for SSL 3)
376 */
377 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
378 /* don't request certificate for SRP auth */
379 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
380 /*
381 * With normal PSK Certificates and Certificate Requests
382 * are omitted
383 */
384 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
385 return 1;
386 }
387
388 return 0;
389 }
390
391 /*
392 * server_write_transition() works out what handshake state to move to next
393 * when the server is writing messages to be sent to the client.
394 */
395 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
396 {
397 OSSL_STATEM *st = &s->statem;
398
399 switch(st->hand_state) {
400 case TLS_ST_BEFORE:
401 /* Just go straight to trying to read from the client */;
402 return WRITE_TRAN_FINISHED;
403
404 case TLS_ST_OK:
405 /* We must be trying to renegotiate */
406 st->hand_state = TLS_ST_SW_HELLO_REQ;
407 return WRITE_TRAN_CONTINUE;
408
409 case TLS_ST_SW_HELLO_REQ:
410 st->hand_state = TLS_ST_OK;
411 ossl_statem_set_in_init(s, 0);
412 return WRITE_TRAN_CONTINUE;
413
414 case TLS_ST_SR_CLNT_HELLO:
415 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
416 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
417 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
418 else
419 st->hand_state = TLS_ST_SW_SRVR_HELLO;
420 return WRITE_TRAN_CONTINUE;
421
422 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
423 return WRITE_TRAN_FINISHED;
424
425 case TLS_ST_SW_SRVR_HELLO:
426 if (s->hit) {
427 if (s->tlsext_ticket_expected)
428 st->hand_state = TLS_ST_SW_SESSION_TICKET;
429 else
430 st->hand_state = TLS_ST_SW_CHANGE;
431 } else {
432 /* Check if it is anon DH or anon ECDH, */
433 /* normal PSK or SRP */
434 if (!(s->s3->tmp.new_cipher->algorithm_auth &
435 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
436 st->hand_state = TLS_ST_SW_CERT;
437 } else if (send_server_key_exchange(s)) {
438 st->hand_state = TLS_ST_SW_KEY_EXCH;
439 } else if (send_certificate_request(s)) {
440 st->hand_state = TLS_ST_SW_CERT_REQ;
441 } else {
442 st->hand_state = TLS_ST_SW_SRVR_DONE;
443 }
444 }
445 return WRITE_TRAN_CONTINUE;
446
447 case TLS_ST_SW_CERT:
448 if (s->tlsext_status_expected) {
449 st->hand_state = TLS_ST_SW_CERT_STATUS;
450 return WRITE_TRAN_CONTINUE;
451 }
452 /* Fall through */
453
454 case TLS_ST_SW_CERT_STATUS:
455 if (send_server_key_exchange(s)) {
456 st->hand_state = TLS_ST_SW_KEY_EXCH;
457 return WRITE_TRAN_CONTINUE;
458 }
459 /* Fall through */
460
461 case TLS_ST_SW_KEY_EXCH:
462 if (send_certificate_request(s)) {
463 st->hand_state = TLS_ST_SW_CERT_REQ;
464 return WRITE_TRAN_CONTINUE;
465 }
466 /* Fall through */
467
468 case TLS_ST_SW_CERT_REQ:
469 st->hand_state = TLS_ST_SW_SRVR_DONE;
470 return WRITE_TRAN_CONTINUE;
471
472 case TLS_ST_SW_SRVR_DONE:
473 return WRITE_TRAN_FINISHED;
474
475 case TLS_ST_SR_FINISHED:
476 if (s->hit) {
477 st->hand_state = TLS_ST_OK;
478 ossl_statem_set_in_init(s, 0);
479 return WRITE_TRAN_CONTINUE;
480 } else if (s->tlsext_ticket_expected) {
481 st->hand_state = TLS_ST_SW_SESSION_TICKET;
482 } else {
483 st->hand_state = TLS_ST_SW_CHANGE;
484 }
485 return WRITE_TRAN_CONTINUE;
486
487 case TLS_ST_SW_SESSION_TICKET:
488 st->hand_state = TLS_ST_SW_CHANGE;
489 return WRITE_TRAN_CONTINUE;
490
491 case TLS_ST_SW_CHANGE:
492 st->hand_state = TLS_ST_SW_FINISHED;
493 return WRITE_TRAN_CONTINUE;
494
495 case TLS_ST_SW_FINISHED:
496 if (s->hit) {
497 return WRITE_TRAN_FINISHED;
498 }
499 st->hand_state = TLS_ST_OK;
500 ossl_statem_set_in_init(s, 0);
501 return WRITE_TRAN_CONTINUE;
502
503 default:
504 /* Shouldn't happen */
505 return WRITE_TRAN_ERROR;
506 }
507 }
508
509 /*
510 * Perform any pre work that needs to be done prior to sending a message from
511 * the server to the client.
512 */
513 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
514 {
515 OSSL_STATEM *st = &s->statem;
516
517 switch(st->hand_state) {
518 case TLS_ST_SW_HELLO_REQ:
519 s->shutdown = 0;
520 if (SSL_IS_DTLS(s))
521 dtls1_clear_record_buffer(s);
522 break;
523
524 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
525 s->shutdown = 0;
526 if (SSL_IS_DTLS(s)) {
527 dtls1_clear_record_buffer(s);
528 /* We don't buffer this message so don't use the timer */
529 st->use_timer = 0;
530 }
531 break;
532
533 case TLS_ST_SW_SRVR_HELLO:
534 if (SSL_IS_DTLS(s)) {
535 /*
536 * Messages we write from now on should be bufferred and
537 * retransmitted if necessary, so we need to use the timer now
538 */
539 st->use_timer = 1;
540 }
541 break;
542
543 case TLS_ST_SW_SRVR_DONE:
544 #ifndef OPENSSL_NO_SCTP
545 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
546 return dtls_wait_for_dry(s);
547 #endif
548 return WORK_FINISHED_CONTINUE;
549
550 case TLS_ST_SW_SESSION_TICKET:
551 if (SSL_IS_DTLS(s)) {
552 /*
553 * We're into the last flight. We don't retransmit the last flight
554 * unless we need to, so we don't use the timer
555 */
556 st->use_timer = 0;
557 }
558 break;
559
560 case TLS_ST_SW_CHANGE:
561 s->session->cipher = s->s3->tmp.new_cipher;
562 if (!s->method->ssl3_enc->setup_key_block(s)) {
563 ossl_statem_set_error(s);
564 return WORK_ERROR;
565 }
566 if (SSL_IS_DTLS(s)) {
567 /*
568 * We're into the last flight. We don't retransmit the last flight
569 * unless we need to, so we don't use the timer. This might have
570 * already been set to 0 if we sent a NewSessionTicket message,
571 * but we'll set it again here in case we didn't.
572 */
573 st->use_timer = 0;
574 }
575 return WORK_FINISHED_CONTINUE;
576
577 case TLS_ST_OK:
578 return tls_finish_handshake(s, wst);
579
580 default:
581 /* No pre work to be done */
582 break;
583 }
584
585 return WORK_FINISHED_CONTINUE;
586 }
587
588 /*
589 * Perform any work that needs to be done after sending a message from the
590 * server to the client.
591 */
592 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
593 {
594 OSSL_STATEM *st = &s->statem;
595
596 s->init_num = 0;
597
598 switch(st->hand_state) {
599 case TLS_ST_SW_HELLO_REQ:
600 if (statem_flush(s) != 1)
601 return WORK_MORE_A;
602 ssl3_init_finished_mac(s);
603 break;
604
605 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
606 if (statem_flush(s) != 1)
607 return WORK_MORE_A;
608 /* HelloVerifyRequest resets Finished MAC */
609 if (s->version != DTLS1_BAD_VER)
610 ssl3_init_finished_mac(s);
611 /*
612 * The next message should be another ClientHello which we need to
613 * treat like it was the first packet
614 */
615 s->first_packet = 1;
616 break;
617
618 case TLS_ST_SW_SRVR_HELLO:
619 #ifndef OPENSSL_NO_SCTP
620 if (SSL_IS_DTLS(s) && s->hit) {
621 unsigned char sctpauthkey[64];
622 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
623
624 /*
625 * Add new shared key for SCTP-Auth, will be ignored if no
626 * SCTP used.
627 */
628 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
629 sizeof(DTLS1_SCTP_AUTH_LABEL));
630
631 if (SSL_export_keying_material(s, sctpauthkey,
632 sizeof(sctpauthkey), labelbuffer,
633 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
634 ossl_statem_set_error(s);
635 return WORK_ERROR;
636 }
637
638 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
639 sizeof(sctpauthkey), sctpauthkey);
640 }
641 #endif
642 break;
643
644 case TLS_ST_SW_CHANGE:
645 #ifndef OPENSSL_NO_SCTP
646 if (SSL_IS_DTLS(s) && !s->hit) {
647 /*
648 * Change to new shared key of SCTP-Auth, will be ignored if
649 * no SCTP used.
650 */
651 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
652 0, NULL);
653 }
654 #endif
655 if (!s->method->ssl3_enc->change_cipher_state(s,
656 SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
657 ossl_statem_set_error(s);
658 return WORK_ERROR;
659 }
660
661 if (SSL_IS_DTLS(s))
662 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
663 break;
664
665 case TLS_ST_SW_SRVR_DONE:
666 if (statem_flush(s) != 1)
667 return WORK_MORE_A;
668 break;
669
670 case TLS_ST_SW_FINISHED:
671 if (statem_flush(s) != 1)
672 return WORK_MORE_A;
673 #ifndef OPENSSL_NO_SCTP
674 if (SSL_IS_DTLS(s) && s->hit) {
675 /*
676 * Change to new shared key of SCTP-Auth, will be ignored if
677 * no SCTP used.
678 */
679 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
680 0, NULL);
681 }
682 #endif
683 break;
684
685 default:
686 /* No post work to be done */
687 break;
688 }
689
690 return WORK_FINISHED_CONTINUE;
691 }
692
693 /*
694 * Construct a message to be sent from the server to the client.
695 *
696 * Valid return values are:
697 * 1: Success
698 * 0: Error
699 */
700 int ossl_statem_server_construct_message(SSL *s)
701 {
702 OSSL_STATEM *st = &s->statem;
703
704 switch(st->hand_state) {
705 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
706 return dtls_construct_hello_verify_request(s);
707
708 case TLS_ST_SW_HELLO_REQ:
709 return tls_construct_hello_request(s);
710
711 case TLS_ST_SW_SRVR_HELLO:
712 return tls_construct_server_hello(s);
713
714 case TLS_ST_SW_CERT:
715 return tls_construct_server_certificate(s);
716
717 case TLS_ST_SW_KEY_EXCH:
718 return tls_construct_server_key_exchange(s);
719
720 case TLS_ST_SW_CERT_REQ:
721 return tls_construct_certificate_request(s);
722
723 case TLS_ST_SW_SRVR_DONE:
724 return tls_construct_server_done(s);
725
726 case TLS_ST_SW_SESSION_TICKET:
727 return tls_construct_new_session_ticket(s);
728
729 case TLS_ST_SW_CERT_STATUS:
730 return tls_construct_cert_status(s);
731
732 case TLS_ST_SW_CHANGE:
733 if (SSL_IS_DTLS(s))
734 return dtls_construct_change_cipher_spec(s);
735 else
736 return tls_construct_change_cipher_spec(s);
737
738 case TLS_ST_SW_FINISHED:
739 return tls_construct_finished(s,
740 s->method->
741 ssl3_enc->server_finished_label,
742 s->method->
743 ssl3_enc->server_finished_label_len);
744
745 default:
746 /* Shouldn't happen */
747 break;
748 }
749
750 return 0;
751 }
752
753 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
754 #define NEXT_PROTO_MAX_LENGTH 514
755
756 /*
757 * Returns the maximum allowed length for the current message that we are
758 * reading. Excludes the message header.
759 */
760 unsigned long ossl_statem_server_max_message_size(SSL *s)
761 {
762 OSSL_STATEM *st = &s->statem;
763
764 switch(st->hand_state) {
765 case TLS_ST_SR_CLNT_HELLO:
766 return SSL3_RT_MAX_PLAIN_LENGTH;
767
768 case TLS_ST_SR_CERT:
769 return s->max_cert_list;
770
771 case TLS_ST_SR_KEY_EXCH:
772 return CLIENT_KEY_EXCH_MAX_LENGTH;
773
774 case TLS_ST_SR_CERT_VRFY:
775 return SSL3_RT_MAX_PLAIN_LENGTH;
776
777 #ifndef OPENSSL_NO_NEXTPROTONEG
778 case TLS_ST_SR_NEXT_PROTO:
779 return NEXT_PROTO_MAX_LENGTH;
780 #endif
781
782 case TLS_ST_SR_CHANGE:
783 return CCS_MAX_LENGTH;
784
785 case TLS_ST_SR_FINISHED:
786 return FINISHED_MAX_LENGTH;
787
788 default:
789 /* Shouldn't happen */
790 break;
791 }
792
793 return 0;
794 }
795
796 /*
797 * Process a message that the server has received from the client.
798 */
799 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
800 {
801 OSSL_STATEM *st = &s->statem;
802
803 switch(st->hand_state) {
804 case TLS_ST_SR_CLNT_HELLO:
805 return tls_process_client_hello(s, pkt);
806
807 case TLS_ST_SR_CERT:
808 return tls_process_client_certificate(s, pkt);
809
810 case TLS_ST_SR_KEY_EXCH:
811 return tls_process_client_key_exchange(s, pkt);
812
813 case TLS_ST_SR_CERT_VRFY:
814 return tls_process_cert_verify(s, pkt);
815
816 #ifndef OPENSSL_NO_NEXTPROTONEG
817 case TLS_ST_SR_NEXT_PROTO:
818 return tls_process_next_proto(s, pkt);
819 #endif
820
821 case TLS_ST_SR_CHANGE:
822 return tls_process_change_cipher_spec(s, pkt);
823
824 case TLS_ST_SR_FINISHED:
825 return tls_process_finished(s, pkt);
826
827 default:
828 /* Shouldn't happen */
829 break;
830 }
831
832 return MSG_PROCESS_ERROR;
833 }
834
835 /*
836 * Perform any further processing required following the receipt of a message
837 * from the client
838 */
839 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
840 {
841 OSSL_STATEM *st = &s->statem;
842
843 switch(st->hand_state) {
844 case TLS_ST_SR_CLNT_HELLO:
845 return tls_post_process_client_hello(s, wst);
846
847 case TLS_ST_SR_KEY_EXCH:
848 return tls_post_process_client_key_exchange(s, wst);
849
850 case TLS_ST_SR_CERT_VRFY:
851 #ifndef OPENSSL_NO_SCTP
852 if ( /* Is this SCTP? */
853 BIO_dgram_is_sctp(SSL_get_wbio(s))
854 /* Are we renegotiating? */
855 && s->renegotiate
856 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
857 s->s3->in_read_app_data = 2;
858 s->rwstate = SSL_READING;
859 BIO_clear_retry_flags(SSL_get_rbio(s));
860 BIO_set_retry_read(SSL_get_rbio(s));
861 ossl_statem_set_sctp_read_sock(s, 1);
862 return WORK_MORE_A;
863 } else {
864 ossl_statem_set_sctp_read_sock(s, 0);
865 }
866 #endif
867 return WORK_FINISHED_CONTINUE;
868
869 default:
870 break;
871 }
872
873 /* Shouldn't happen */
874 return WORK_ERROR;
875 }
876
877 #ifndef OPENSSL_NO_SRP
878 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
879 {
880 int ret = SSL_ERROR_NONE;
881
882 *al = SSL_AD_UNRECOGNIZED_NAME;
883
884 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
885 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
886 if (s->srp_ctx.login == NULL) {
887 /*
888 * RFC 5054 says SHOULD reject, we do so if There is no srp
889 * login name
890 */
891 ret = SSL3_AL_FATAL;
892 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
893 } else {
894 ret = SSL_srp_server_param_with_username(s, al);
895 }
896 }
897 return ret;
898 }
899 #endif
900
901 int tls_construct_hello_request(SSL *s)
902 {
903 if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
904 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
905 ossl_statem_set_error(s);
906 return 0;
907 }
908
909 return 1;
910 }
911
912 unsigned int dtls_raw_hello_verify_request(unsigned char *buf,
913 unsigned char *cookie,
914 unsigned char cookie_len)
915 {
916 unsigned int msg_len;
917 unsigned char *p;
918
919 p = buf;
920 /* Always use DTLS 1.0 version: see RFC 6347 */
921 *(p++) = DTLS1_VERSION >> 8;
922 *(p++) = DTLS1_VERSION & 0xFF;
923
924 *(p++) = (unsigned char)cookie_len;
925 memcpy(p, cookie, cookie_len);
926 p += cookie_len;
927 msg_len = p - buf;
928
929 return msg_len;
930 }
931
932 int dtls_construct_hello_verify_request(SSL *s)
933 {
934 unsigned int len;
935 unsigned char *buf;
936
937 buf = (unsigned char *)s->init_buf->data;
938
939 if (s->ctx->app_gen_cookie_cb == NULL ||
940 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
941 &(s->d1->cookie_len)) == 0 ||
942 s->d1->cookie_len > 255) {
943 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
944 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
945 ossl_statem_set_error(s);
946 return 0;
947 }
948
949 len = dtls_raw_hello_verify_request(&buf[DTLS1_HM_HEADER_LENGTH],
950 s->d1->cookie, s->d1->cookie_len);
951
952 dtls1_set_message_header(s, buf, DTLS1_MT_HELLO_VERIFY_REQUEST, len, 0,
953 len);
954 len += DTLS1_HM_HEADER_LENGTH;
955
956 /* number of bytes to write */
957 s->init_num = len;
958 s->init_off = 0;
959
960 return 1;
961 }
962
963 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
964 {
965 int i, al = SSL_AD_INTERNAL_ERROR;
966 unsigned int j, complen = 0;
967 unsigned long id;
968 const SSL_CIPHER *c;
969 #ifndef OPENSSL_NO_COMP
970 SSL_COMP *comp = NULL;
971 #endif
972 STACK_OF(SSL_CIPHER) *ciphers = NULL;
973 int protverr;
974 /* |cookie| will only be initialized for DTLS. */
975 PACKET session_id, cipher_suites, compression, extensions, cookie;
976 int is_v2_record;
977
978 is_v2_record = RECORD_LAYER_is_sslv2_record(&s->rlayer);
979
980 PACKET_null_init(&cookie);
981 /* First lets get s->client_version set correctly */
982 if (is_v2_record) {
983 unsigned int version;
984 unsigned int mt;
985 /*-
986 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
987 * header is sent directly on the wire, not wrapped as a TLS
988 * record. Our record layer just processes the message length and passes
989 * the rest right through. Its format is:
990 * Byte Content
991 * 0-1 msg_length - decoded by the record layer
992 * 2 msg_type - s->init_msg points here
993 * 3-4 version
994 * 5-6 cipher_spec_length
995 * 7-8 session_id_length
996 * 9-10 challenge_length
997 * ... ...
998 */
999
1000 if (!PACKET_get_1(pkt, &mt)
1001 || mt != SSL2_MT_CLIENT_HELLO) {
1002 /*
1003 * Should never happen. We should have tested this in the record
1004 * layer in order to have determined that this is a SSLv2 record
1005 * in the first place
1006 */
1007 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1008 goto err;
1009 }
1010
1011 if (!PACKET_get_net_2(pkt, &version)) {
1012 /* No protocol version supplied! */
1013 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1014 goto err;
1015 }
1016 if (version == 0x0002) {
1017 /* This is real SSLv2. We don't support it. */
1018 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1019 goto err;
1020 } else if ((version & 0xff00) == (SSL3_VERSION_MAJOR << 8)) {
1021 /* SSLv3/TLS */
1022 s->client_version = version;
1023 } else {
1024 /* No idea what protocol this is */
1025 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1026 goto err;
1027 }
1028 } else {
1029 /*
1030 * use version from inside client hello, not from record header (may
1031 * differ: see RFC 2246, Appendix E, second paragraph)
1032 */
1033 if(!PACKET_get_net_2(pkt, (unsigned int *)&s->client_version)) {
1034 al = SSL_AD_DECODE_ERROR;
1035 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1036 goto f_err;
1037 }
1038 }
1039
1040 /*
1041 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1042 * versions are potentially compatible. Version negotiation comes later.
1043 */
1044 if (!SSL_IS_DTLS(s)) {
1045 protverr = ssl_choose_server_version(s);
1046 } else if (s->method->version != DTLS_ANY_VERSION &&
1047 DTLS_VERSION_LT(s->client_version, s->version)) {
1048 protverr = SSL_R_VERSION_TOO_LOW;
1049 } else {
1050 protverr = 0;
1051 }
1052
1053 if (protverr) {
1054 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, protverr);
1055 if ((!s->enc_write_ctx && !s->write_hash)) {
1056 /*
1057 * similar to ssl3_get_record, send alert using remote version
1058 * number
1059 */
1060 s->version = s->client_version;
1061 }
1062 al = SSL_AD_PROTOCOL_VERSION;
1063 goto f_err;
1064 }
1065
1066 /* Parse the message and load client random. */
1067 if (is_v2_record) {
1068 /*
1069 * Handle an SSLv2 backwards compatible ClientHello
1070 * Note, this is only for SSLv3+ using the backward compatible format.
1071 * Real SSLv2 is not supported, and is rejected above.
1072 */
1073 unsigned int cipher_len, session_id_len, challenge_len;
1074 PACKET challenge;
1075
1076 if (!PACKET_get_net_2(pkt, &cipher_len)
1077 || !PACKET_get_net_2(pkt, &session_id_len)
1078 || !PACKET_get_net_2(pkt, &challenge_len)) {
1079 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1080 SSL_R_RECORD_LENGTH_MISMATCH);
1081 al = SSL_AD_DECODE_ERROR;
1082 goto f_err;
1083 }
1084
1085 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1086 al = SSL_AD_DECODE_ERROR;
1087 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1088 goto f_err;
1089 }
1090
1091 if (!PACKET_get_sub_packet(pkt, &cipher_suites, cipher_len)
1092 || !PACKET_get_sub_packet(pkt, &session_id, session_id_len)
1093 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1094 /* No extensions. */
1095 || PACKET_remaining(pkt) != 0) {
1096 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1097 SSL_R_RECORD_LENGTH_MISMATCH);
1098 al = SSL_AD_DECODE_ERROR;
1099 goto f_err;
1100 }
1101
1102 /* Load the client random */
1103 challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE :
1104 challenge_len;
1105 memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1106 if (!PACKET_copy_bytes(&challenge,
1107 s->s3->client_random + SSL3_RANDOM_SIZE -
1108 challenge_len, challenge_len)) {
1109 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1110 al = SSL_AD_INTERNAL_ERROR;
1111 goto f_err;
1112 }
1113
1114 PACKET_null_init(&compression);
1115 PACKET_null_init(&extensions);
1116 } else {
1117 /* Regular ClientHello. */
1118 if (!PACKET_copy_bytes(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)
1119 || !PACKET_get_length_prefixed_1(pkt, &session_id)) {
1120 al = SSL_AD_DECODE_ERROR;
1121 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1122 goto f_err;
1123 }
1124
1125 if (PACKET_remaining(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1126 al = SSL_AD_DECODE_ERROR;
1127 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1128 goto f_err;
1129 }
1130
1131 if (SSL_IS_DTLS(s)) {
1132 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1133 al = SSL_AD_DECODE_ERROR;
1134 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1135 goto f_err;
1136 }
1137 /*
1138 * If we require cookies and this ClientHello doesn't contain one,
1139 * just return since we do not want to allocate any memory yet.
1140 * So check cookie length...
1141 */
1142 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1143 if (PACKET_remaining(&cookie) == 0)
1144 return 1;
1145 }
1146 }
1147
1148 if (!PACKET_get_length_prefixed_2(pkt, &cipher_suites)
1149 || !PACKET_get_length_prefixed_1(pkt, &compression)) {
1150 al = SSL_AD_DECODE_ERROR;
1151 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1152 goto f_err;
1153 }
1154 /* Could be empty. */
1155 extensions = *pkt;
1156 }
1157
1158 s->hit = 0;
1159
1160 /*
1161 * We don't allow resumption in a backwards compatible ClientHello.
1162 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1163 *
1164 * Versions before 0.9.7 always allow clients to resume sessions in
1165 * renegotiation. 0.9.7 and later allow this by default, but optionally
1166 * ignore resumption requests with flag
1167 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1168 * than a change to default behavior so that applications relying on
1169 * this for security won't even compile against older library versions).
1170 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1171 * request renegotiation but not a new session (s->new_session remains
1172 * unset): for servers, this essentially just means that the
1173 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1174 * ignored.
1175 */
1176 if (is_v2_record ||
1177 (s->new_session &&
1178 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1179 if (!ssl_get_new_session(s, 1))
1180 goto err;
1181 } else {
1182 i = ssl_get_prev_session(s, &extensions, &session_id);
1183 /*
1184 * Only resume if the session's version matches the negotiated
1185 * version.
1186 * RFC 5246 does not provide much useful advice on resumption
1187 * with a different protocol version. It doesn't forbid it but
1188 * the sanity of such behaviour would be questionable.
1189 * In practice, clients do not accept a version mismatch and
1190 * will abort the handshake with an error.
1191 */
1192 if (i == 1 && s->version == s->session->ssl_version) {
1193 /* previous session */
1194 s->hit = 1;
1195 } else if (i == -1) {
1196 goto err;
1197 } else {
1198 /* i == 0 */
1199 if (!ssl_get_new_session(s, 1))
1200 goto err;
1201 }
1202 }
1203
1204 if (SSL_IS_DTLS(s)) {
1205 /* Empty cookie was already handled above by returning early. */
1206 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1207 if (s->ctx->app_verify_cookie_cb != NULL) {
1208 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
1209 PACKET_remaining(&cookie)) == 0) {
1210 al = SSL_AD_HANDSHAKE_FAILURE;
1211 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1212 SSL_R_COOKIE_MISMATCH);
1213 goto f_err;
1214 /* else cookie verification succeeded */
1215 }
1216 /* default verification */
1217 } else if (!PACKET_equal(&cookie, s->d1->cookie,
1218 s->d1->cookie_len)) {
1219 al = SSL_AD_HANDSHAKE_FAILURE;
1220 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1221 goto f_err;
1222 }
1223 s->d1->cookie_verified = 1;
1224 }
1225 if (s->method->version == DTLS_ANY_VERSION) {
1226 protverr = ssl_choose_server_version(s);
1227 if (protverr != 0) {
1228 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, protverr);
1229 s->version = s->client_version;
1230 al = SSL_AD_PROTOCOL_VERSION;
1231 goto f_err;
1232 }
1233 s->session->ssl_version = s->version;
1234 }
1235 }
1236
1237 if (ssl_bytes_to_cipher_list(s, &cipher_suites, &(ciphers),
1238 is_v2_record, &al) == NULL) {
1239 goto f_err;
1240 }
1241
1242 /* If it is a hit, check that the cipher is in the list */
1243 if (s->hit) {
1244 j = 0;
1245 id = s->session->cipher->id;
1246
1247 #ifdef CIPHER_DEBUG
1248 fprintf(stderr, "client sent %d ciphers\n",
1249 sk_SSL_CIPHER_num(ciphers));
1250 #endif
1251 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1252 c = sk_SSL_CIPHER_value(ciphers, i);
1253 #ifdef CIPHER_DEBUG
1254 fprintf(stderr, "client [%2d of %2d]:%s\n",
1255 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1256 #endif
1257 if (c->id == id) {
1258 j = 1;
1259 break;
1260 }
1261 }
1262 if (j == 0) {
1263 /*
1264 * we need to have the cipher in the cipher list if we are asked
1265 * to reuse it
1266 */
1267 al = SSL_AD_ILLEGAL_PARAMETER;
1268 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1269 SSL_R_REQUIRED_CIPHER_MISSING);
1270 goto f_err;
1271 }
1272 }
1273
1274 complen = PACKET_remaining(&compression);
1275 for (j = 0; j < complen; j++) {
1276 if (PACKET_data(&compression)[j] == 0)
1277 break;
1278 }
1279
1280 if (j >= complen) {
1281 /* no compress */
1282 al = SSL_AD_DECODE_ERROR;
1283 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1284 goto f_err;
1285 }
1286
1287 /* TLS extensions */
1288 if (s->version >= SSL3_VERSION) {
1289 if (!ssl_parse_clienthello_tlsext(s, &extensions)) {
1290 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1291 goto err;
1292 }
1293 }
1294
1295 /*
1296 * Check if we want to use external pre-shared secret for this handshake
1297 * for not reused session only. We need to generate server_random before
1298 * calling tls_session_secret_cb in order to allow SessionTicket
1299 * processing to use it in key derivation.
1300 */
1301 {
1302 unsigned char *pos;
1303 pos = s->s3->server_random;
1304 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1305 goto f_err;
1306 }
1307 }
1308
1309 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1310 const SSL_CIPHER *pref_cipher = NULL;
1311
1312 s->session->master_key_length = sizeof(s->session->master_key);
1313 if (s->tls_session_secret_cb(s, s->session->master_key,
1314 &s->session->master_key_length, ciphers,
1315 &pref_cipher,
1316 s->tls_session_secret_cb_arg)) {
1317 s->hit = 1;
1318 s->session->ciphers = ciphers;
1319 s->session->verify_result = X509_V_OK;
1320
1321 ciphers = NULL;
1322
1323 /* check if some cipher was preferred by call back */
1324 pref_cipher =
1325 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1326 s->
1327 session->ciphers,
1328 SSL_get_ciphers
1329 (s));
1330 if (pref_cipher == NULL) {
1331 al = SSL_AD_HANDSHAKE_FAILURE;
1332 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1333 goto f_err;
1334 }
1335
1336 s->session->cipher = pref_cipher;
1337 sk_SSL_CIPHER_free(s->cipher_list);
1338 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1339 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1340 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1341 }
1342 }
1343
1344 /*
1345 * Worst case, we will use the NULL compression, but if we have other
1346 * options, we will now look for them. We have complen-1 compression
1347 * algorithms from the client, starting at q.
1348 */
1349 s->s3->tmp.new_compression = NULL;
1350 #ifndef OPENSSL_NO_COMP
1351 /* This only happens if we have a cache hit */
1352 if (s->session->compress_meth != 0) {
1353 int m, comp_id = s->session->compress_meth;
1354 unsigned int k;
1355 /* Perform sanity checks on resumed compression algorithm */
1356 /* Can't disable compression */
1357 if (!ssl_allow_compression(s)) {
1358 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1359 SSL_R_INCONSISTENT_COMPRESSION);
1360 goto f_err;
1361 }
1362 /* Look for resumed compression method */
1363 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1364 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1365 if (comp_id == comp->id) {
1366 s->s3->tmp.new_compression = comp;
1367 break;
1368 }
1369 }
1370 if (s->s3->tmp.new_compression == NULL) {
1371 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1372 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1373 goto f_err;
1374 }
1375 /* Look for resumed method in compression list */
1376 for (k = 0; k < complen; k++) {
1377 if (PACKET_data(&compression)[k] == comp_id)
1378 break;
1379 }
1380 if (k >= complen) {
1381 al = SSL_AD_ILLEGAL_PARAMETER;
1382 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1383 SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1384 goto f_err;
1385 }
1386 } else if (s->hit)
1387 comp = NULL;
1388 else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1389 /* See if we have a match */
1390 int m, nn, v, done = 0;
1391 unsigned int o;
1392
1393 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1394 for (m = 0; m < nn; m++) {
1395 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1396 v = comp->id;
1397 for (o = 0; o < complen; o++) {
1398 if (v == PACKET_data(&compression)[o]) {
1399 done = 1;
1400 break;
1401 }
1402 }
1403 if (done)
1404 break;
1405 }
1406 if (done)
1407 s->s3->tmp.new_compression = comp;
1408 else
1409 comp = NULL;
1410 }
1411 #else
1412 /*
1413 * If compression is disabled we'd better not try to resume a session
1414 * using compression.
1415 */
1416 if (s->session->compress_meth != 0) {
1417 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1418 goto f_err;
1419 }
1420 #endif
1421
1422 /*
1423 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1424 */
1425
1426 if (!s->hit) {
1427 #ifdef OPENSSL_NO_COMP
1428 s->session->compress_meth = 0;
1429 #else
1430 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1431 #endif
1432 sk_SSL_CIPHER_free(s->session->ciphers);
1433 s->session->ciphers = ciphers;
1434 if (ciphers == NULL) {
1435 al = SSL_AD_INTERNAL_ERROR;
1436 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1437 goto f_err;
1438 }
1439 ciphers = NULL;
1440 if (!tls1_set_server_sigalgs(s)) {
1441 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1442 goto err;
1443 }
1444 }
1445
1446 sk_SSL_CIPHER_free(ciphers);
1447 return MSG_PROCESS_CONTINUE_PROCESSING;
1448 f_err:
1449 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1450 err:
1451 ossl_statem_set_error(s);
1452
1453 sk_SSL_CIPHER_free(ciphers);
1454 return MSG_PROCESS_ERROR;
1455
1456 }
1457
1458 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1459 {
1460 int al = SSL_AD_HANDSHAKE_FAILURE;
1461 const SSL_CIPHER *cipher;
1462
1463 if (wst == WORK_MORE_A) {
1464 if (!s->hit) {
1465 /* Let cert callback update server certificates if required */
1466 if (s->cert->cert_cb) {
1467 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1468 if (rv == 0) {
1469 al = SSL_AD_INTERNAL_ERROR;
1470 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1471 goto f_err;
1472 }
1473 if (rv < 0) {
1474 s->rwstate = SSL_X509_LOOKUP;
1475 return WORK_MORE_A;
1476 }
1477 s->rwstate = SSL_NOTHING;
1478 }
1479 cipher = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1480
1481 if (cipher == NULL) {
1482 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1483 goto f_err;
1484 }
1485 s->s3->tmp.new_cipher = cipher;
1486 /* check whether we should disable session resumption */
1487 if (s->not_resumable_session_cb != NULL)
1488 s->session->not_resumable = s->not_resumable_session_cb(s,
1489 ((cipher->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1490 if (s->session->not_resumable)
1491 /* do not send a session ticket */
1492 s->tlsext_ticket_expected = 0;
1493 } else {
1494 /* Session-id reuse */
1495 s->s3->tmp.new_cipher = s->session->cipher;
1496 }
1497
1498 if (!(s->verify_mode & SSL_VERIFY_PEER)) {
1499 if (!ssl3_digest_cached_records(s, 0)) {
1500 al = SSL_AD_INTERNAL_ERROR;
1501 goto f_err;
1502 }
1503 }
1504
1505 /*-
1506 * we now have the following setup.
1507 * client_random
1508 * cipher_list - our prefered list of ciphers
1509 * ciphers - the clients prefered list of ciphers
1510 * compression - basically ignored right now
1511 * ssl version is set - sslv3
1512 * s->session - The ssl session has been setup.
1513 * s->hit - session reuse flag
1514 * s->s3->tmp.new_cipher- the new cipher to use.
1515 */
1516
1517 /* Handles TLS extensions that we couldn't check earlier */
1518 if (s->version >= SSL3_VERSION) {
1519 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1520 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1521 SSL_R_CLIENTHELLO_TLSEXT);
1522 goto f_err;
1523 }
1524 }
1525
1526 wst = WORK_MORE_B;
1527 }
1528 #ifndef OPENSSL_NO_SRP
1529 if (wst == WORK_MORE_B) {
1530 int ret;
1531 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
1532 /*
1533 * callback indicates further work to be done
1534 */
1535 s->rwstate = SSL_X509_LOOKUP;
1536 return WORK_MORE_B;
1537 }
1538 if (ret != SSL_ERROR_NONE) {
1539 /*
1540 * This is not really an error but the only means to for
1541 * a client to detect whether srp is supported.
1542 */
1543 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
1544 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1545 SSL_R_CLIENTHELLO_TLSEXT);
1546 goto f_err;
1547 }
1548 }
1549 #endif
1550 s->renegotiate = 2;
1551
1552 return WORK_FINISHED_STOP;
1553 f_err:
1554 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1555 ossl_statem_set_error(s);
1556 return WORK_ERROR;
1557 }
1558
1559 int tls_construct_server_hello(SSL *s)
1560 {
1561 unsigned char *buf;
1562 unsigned char *p, *d;
1563 int i, sl;
1564 int al = 0;
1565 unsigned long l;
1566
1567 buf = (unsigned char *)s->init_buf->data;
1568
1569 /* Do the message type and length last */
1570 d = p = ssl_handshake_start(s);
1571
1572 *(p++) = s->version >> 8;
1573 *(p++) = s->version & 0xff;
1574
1575 /*
1576 * Random stuff. Filling of the server_random takes place in
1577 * tls_process_client_hello()
1578 */
1579 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1580 p += SSL3_RANDOM_SIZE;
1581
1582 /*-
1583 * There are several cases for the session ID to send
1584 * back in the server hello:
1585 * - For session reuse from the session cache,
1586 * we send back the old session ID.
1587 * - If stateless session reuse (using a session ticket)
1588 * is successful, we send back the client's "session ID"
1589 * (which doesn't actually identify the session).
1590 * - If it is a new session, we send back the new
1591 * session ID.
1592 * - However, if we want the new session to be single-use,
1593 * we send back a 0-length session ID.
1594 * s->hit is non-zero in either case of session reuse,
1595 * so the following won't overwrite an ID that we're supposed
1596 * to send back.
1597 */
1598 if (s->session->not_resumable ||
1599 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1600 && !s->hit))
1601 s->session->session_id_length = 0;
1602
1603 sl = s->session->session_id_length;
1604 if (sl > (int)sizeof(s->session->session_id)) {
1605 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1606 ossl_statem_set_error(s);
1607 return 0;
1608 }
1609 *(p++) = sl;
1610 memcpy(p, s->session->session_id, sl);
1611 p += sl;
1612
1613 /* put the cipher */
1614 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1615 p += i;
1616
1617 /* put the compression method */
1618 #ifdef OPENSSL_NO_COMP
1619 *(p++) = 0;
1620 #else
1621 if (s->s3->tmp.new_compression == NULL)
1622 *(p++) = 0;
1623 else
1624 *(p++) = s->s3->tmp.new_compression->id;
1625 #endif
1626
1627 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1628 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1629 ossl_statem_set_error(s);
1630 return 0;
1631 }
1632 if ((p =
1633 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1634 &al)) == NULL) {
1635 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1636 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1637 ossl_statem_set_error(s);
1638 return 0;
1639 }
1640
1641 /* do the header */
1642 l = (p - d);
1643 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1644 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1645 ossl_statem_set_error(s);
1646 return 0;
1647 }
1648
1649 return 1;
1650 }
1651
1652 int tls_construct_server_done(SSL *s)
1653 {
1654 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1655 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1656 ossl_statem_set_error(s);
1657 return 0;
1658 }
1659
1660 if (!s->s3->tmp.cert_request) {
1661 if (!ssl3_digest_cached_records(s, 0)) {
1662 ossl_statem_set_error(s);
1663 }
1664 }
1665
1666 return 1;
1667 }
1668
1669 int tls_construct_server_key_exchange(SSL *s)
1670 {
1671 #ifndef OPENSSL_NO_DH
1672 EVP_PKEY *pkdh = NULL;
1673 #endif
1674 #ifndef OPENSSL_NO_EC
1675 unsigned char *encodedPoint = NULL;
1676 int encodedlen = 0;
1677 int curve_id = 0;
1678 #endif
1679 EVP_PKEY *pkey;
1680 const EVP_MD *md = NULL;
1681 unsigned char *p, *d;
1682 int al, i;
1683 unsigned long type;
1684 int n;
1685 BIGNUM *r[4];
1686 int nr[4], kn;
1687 BUF_MEM *buf;
1688 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1689
1690 if (md_ctx == NULL) {
1691 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1692 al = SSL_AD_INTERNAL_ERROR;
1693 goto f_err;
1694 }
1695
1696 type = s->s3->tmp.new_cipher->algorithm_mkey;
1697
1698 buf = s->init_buf;
1699
1700 r[0] = r[1] = r[2] = r[3] = NULL;
1701 n = 0;
1702 #ifndef OPENSSL_NO_PSK
1703 if (type & SSL_PSK) {
1704 /*
1705 * reserve size for record length and PSK identity hint
1706 */
1707 n += 2;
1708 if (s->cert->psk_identity_hint)
1709 n += strlen(s->cert->psk_identity_hint);
1710 }
1711 /* Plain PSK or RSAPSK nothing to do */
1712 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1713 } else
1714 #endif /* !OPENSSL_NO_PSK */
1715 #ifndef OPENSSL_NO_DH
1716 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1717 CERT *cert = s->cert;
1718
1719 EVP_PKEY *pkdhp = NULL;
1720 DH *dh;
1721
1722 if (s->cert->dh_tmp_auto) {
1723 DH *dhp = ssl_get_auto_dh(s);
1724 pkdh = EVP_PKEY_new();
1725 if (pkdh == NULL || dhp == NULL) {
1726 DH_free(dhp);
1727 al = SSL_AD_INTERNAL_ERROR;
1728 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1729 ERR_R_INTERNAL_ERROR);
1730 goto f_err;
1731 }
1732 EVP_PKEY_assign_DH(pkdh, dhp);
1733 pkdhp = pkdh;
1734 } else {
1735 pkdhp = cert->dh_tmp;
1736 }
1737 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
1738 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
1739 pkdh = ssl_dh_to_pkey(dhp);
1740 if (pkdh == NULL) {
1741 al = SSL_AD_INTERNAL_ERROR;
1742 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1743 ERR_R_INTERNAL_ERROR);
1744 goto f_err;
1745 }
1746 pkdhp = pkdh;
1747 }
1748 if (pkdhp == NULL) {
1749 al = SSL_AD_HANDSHAKE_FAILURE;
1750 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1751 SSL_R_MISSING_TMP_DH_KEY);
1752 goto f_err;
1753 }
1754 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1755 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
1756 al = SSL_AD_HANDSHAKE_FAILURE;
1757 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1758 SSL_R_DH_KEY_TOO_SMALL);
1759 goto f_err;
1760 }
1761 if (s->s3->tmp.pkey != NULL) {
1762 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1763 ERR_R_INTERNAL_ERROR);
1764 goto err;
1765 }
1766
1767 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp, NID_undef);
1768
1769 if (s->s3->tmp.pkey == NULL) {
1770 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
1771 goto err;
1772 }
1773
1774 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
1775
1776 EVP_PKEY_free(pkdh);
1777 pkdh = NULL;
1778
1779 r[0] = dh->p;
1780 r[1] = dh->g;
1781 r[2] = dh->pub_key;
1782 } else
1783 #endif
1784 #ifndef OPENSSL_NO_EC
1785 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1786 int nid;
1787
1788 if (s->s3->tmp.pkey != NULL) {
1789 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1790 ERR_R_INTERNAL_ERROR);
1791 goto err;
1792 }
1793
1794 /* Get NID of appropriate shared curve */
1795 nid = tls1_shared_curve(s, -2);
1796 curve_id = tls1_ec_nid2curve_id(nid);
1797 if (curve_id == 0) {
1798 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1799 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1800 goto err;
1801 }
1802 s->s3->tmp.pkey = ssl_generate_pkey(NULL, nid);
1803 /* Generate a new key for this curve */
1804 if (s->s3->tmp.pkey == NULL) {
1805 al = SSL_AD_INTERNAL_ERROR;
1806 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
1807 goto f_err;
1808 }
1809
1810 /* Encode the public key. */
1811 encodedlen = EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(s->s3->tmp.pkey),
1812 POINT_CONVERSION_UNCOMPRESSED,
1813 &encodedPoint, NULL);
1814
1815 if (encodedlen == 0) {
1816 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
1817 goto err;
1818 }
1819
1820 /*
1821 * We only support named (not generic) curves in ECDH ephemeral key
1822 * exchanges. In this situation, we need four additional bytes to
1823 * encode the entire ServerECDHParams structure.
1824 */
1825 n += 4 + encodedlen;
1826
1827 /*
1828 * We'll generate the serverKeyExchange message explicitly so we
1829 * can set these to NULLs
1830 */
1831 r[0] = NULL;
1832 r[1] = NULL;
1833 r[2] = NULL;
1834 r[3] = NULL;
1835 } else
1836 #endif /* !OPENSSL_NO_EC */
1837 #ifndef OPENSSL_NO_SRP
1838 if (type & SSL_kSRP) {
1839 if ((s->srp_ctx.N == NULL) ||
1840 (s->srp_ctx.g == NULL) ||
1841 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1842 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1843 SSL_R_MISSING_SRP_PARAM);
1844 goto err;
1845 }
1846 r[0] = s->srp_ctx.N;
1847 r[1] = s->srp_ctx.g;
1848 r[2] = s->srp_ctx.s;
1849 r[3] = s->srp_ctx.B;
1850 } else
1851 #endif
1852 {
1853 al = SSL_AD_HANDSHAKE_FAILURE;
1854 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1855 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1856 goto f_err;
1857 }
1858 for (i = 0; i < 4 && r[i] != NULL; i++) {
1859 nr[i] = BN_num_bytes(r[i]);
1860 #ifndef OPENSSL_NO_SRP
1861 if ((i == 2) && (type & SSL_kSRP))
1862 n += 1 + nr[i];
1863 else
1864 #endif
1865 n += 2 + nr[i];
1866 }
1867
1868 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1869 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1870 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1871 == NULL) {
1872 al = SSL_AD_DECODE_ERROR;
1873 goto f_err;
1874 }
1875 kn = EVP_PKEY_size(pkey);
1876 } else {
1877 pkey = NULL;
1878 kn = 0;
1879 }
1880
1881 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1882 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1883 goto err;
1884 }
1885 d = p = ssl_handshake_start(s);
1886
1887 #ifndef OPENSSL_NO_PSK
1888 if (type & SSL_PSK) {
1889 /* copy PSK identity hint */
1890 if (s->cert->psk_identity_hint) {
1891 s2n(strlen(s->cert->psk_identity_hint), p);
1892 strncpy((char *)p, s->cert->psk_identity_hint,
1893 strlen(s->cert->psk_identity_hint));
1894 p += strlen(s->cert->psk_identity_hint);
1895 } else {
1896 s2n(0, p);
1897 }
1898 }
1899 #endif
1900
1901 for (i = 0; i < 4 && r[i] != NULL; i++) {
1902 #ifndef OPENSSL_NO_SRP
1903 if ((i == 2) && (type & SSL_kSRP)) {
1904 *p = nr[i];
1905 p++;
1906 } else
1907 #endif
1908 s2n(nr[i], p);
1909 BN_bn2bin(r[i], p);
1910 p += nr[i];
1911 }
1912
1913 #ifndef OPENSSL_NO_EC
1914 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1915 /*
1916 * XXX: For now, we only support named (not generic) curves. In
1917 * this situation, the serverKeyExchange message has: [1 byte
1918 * CurveType], [2 byte CurveName] [1 byte length of encoded
1919 * point], followed by the actual encoded point itself
1920 */
1921 *p = NAMED_CURVE_TYPE;
1922 p += 1;
1923 *p = 0;
1924 p += 1;
1925 *p = curve_id;
1926 p += 1;
1927 *p = encodedlen;
1928 p += 1;
1929 memcpy(p, encodedPoint, encodedlen);
1930 OPENSSL_free(encodedPoint);
1931 encodedPoint = NULL;
1932 p += encodedlen;
1933 }
1934 #endif
1935
1936 /* not anonymous */
1937 if (pkey != NULL) {
1938 /*
1939 * n is the length of the params, they start at &(d[4]) and p
1940 * points to the space at the end.
1941 */
1942 if (md) {
1943 /* send signature algorithm */
1944 if (SSL_USE_SIGALGS(s)) {
1945 if (!tls12_get_sigandhash(p, pkey, md)) {
1946 /* Should never happen */
1947 al = SSL_AD_INTERNAL_ERROR;
1948 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1949 ERR_R_INTERNAL_ERROR);
1950 goto f_err;
1951 }
1952 p += 2;
1953 }
1954 #ifdef SSL_DEBUG
1955 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1956 #endif
1957 if (EVP_SignInit_ex(md_ctx, md, NULL) <= 0
1958 || EVP_SignUpdate(md_ctx, &(s->s3->client_random[0]),
1959 SSL3_RANDOM_SIZE) <= 0
1960 || EVP_SignUpdate(md_ctx, &(s->s3->server_random[0]),
1961 SSL3_RANDOM_SIZE) <= 0
1962 || EVP_SignUpdate(md_ctx, d, n) <= 0
1963 || EVP_SignFinal(md_ctx, &(p[2]),
1964 (unsigned int *)&i, pkey) <= 0) {
1965 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1966 al = SSL_AD_INTERNAL_ERROR;
1967 goto f_err;
1968 }
1969 s2n(i, p);
1970 n += i + 2;
1971 if (SSL_USE_SIGALGS(s))
1972 n += 2;
1973 } else {
1974 /* Is this error check actually needed? */
1975 al = SSL_AD_HANDSHAKE_FAILURE;
1976 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1977 SSL_R_UNKNOWN_PKEY_TYPE);
1978 goto f_err;
1979 }
1980 }
1981
1982 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
1983 al = SSL_AD_HANDSHAKE_FAILURE;
1984 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1985 goto f_err;
1986 }
1987
1988 EVP_MD_CTX_free(md_ctx);
1989 return 1;
1990 f_err:
1991 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1992 err:
1993 #ifndef OPENSSL_NO_DH
1994 EVP_PKEY_free(pkdh);
1995 #endif
1996 #ifndef OPENSSL_NO_EC
1997 OPENSSL_free(encodedPoint);
1998 #endif
1999 EVP_MD_CTX_free(md_ctx);
2000 ossl_statem_set_error(s);
2001 return 0;
2002 }
2003
2004 int tls_construct_certificate_request(SSL *s)
2005 {
2006 unsigned char *p, *d;
2007 int i, j, nl, off, n;
2008 STACK_OF(X509_NAME) *sk = NULL;
2009 X509_NAME *name;
2010 BUF_MEM *buf;
2011
2012 buf = s->init_buf;
2013
2014 d = p = ssl_handshake_start(s);
2015
2016 /* get the list of acceptable cert types */
2017 p++;
2018 n = ssl3_get_req_cert_type(s, p);
2019 d[0] = n;
2020 p += n;
2021 n++;
2022
2023 if (SSL_USE_SIGALGS(s)) {
2024 const unsigned char *psigs;
2025 unsigned char *etmp = p;
2026 nl = tls12_get_psigalgs(s, &psigs);
2027 /* Skip over length for now */
2028 p += 2;
2029 nl = tls12_copy_sigalgs(s, p, psigs, nl);
2030 /* Now fill in length */
2031 s2n(nl, etmp);
2032 p += nl;
2033 n += nl + 2;
2034 }
2035
2036 off = n;
2037 p += 2;
2038 n += 2;
2039
2040 sk = SSL_get_client_CA_list(s);
2041 nl = 0;
2042 if (sk != NULL) {
2043 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2044 name = sk_X509_NAME_value(sk, i);
2045 j = i2d_X509_NAME(name, NULL);
2046 if (!BUF_MEM_grow_clean
2047 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2048 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2049 ERR_R_BUF_LIB);
2050 goto err;
2051 }
2052 p = ssl_handshake_start(s) + n;
2053 s2n(j, p);
2054 i2d_X509_NAME(name, &p);
2055 n += 2 + j;
2056 nl += 2 + j;
2057 }
2058 }
2059 /* else no CA names */
2060 p = ssl_handshake_start(s) + off;
2061 s2n(nl, p);
2062
2063 if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2064 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2065 goto err;
2066 }
2067
2068 s->s3->tmp.cert_request = 1;
2069
2070 return 1;
2071 err:
2072 ossl_statem_set_error(s);
2073 return 0;
2074 }
2075
2076 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
2077 {
2078 int al;
2079 unsigned int i;
2080 unsigned long alg_k;
2081 #ifndef OPENSSL_NO_RSA
2082 RSA *rsa = NULL;
2083 #endif
2084 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2085 EVP_PKEY *ckey = NULL;
2086 #endif
2087 PACKET enc_premaster;
2088 unsigned char *data, *rsa_decrypt = NULL;
2089
2090 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2091
2092 #ifndef OPENSSL_NO_PSK
2093 /* For PSK parse and retrieve identity, obtain PSK key */
2094 if (alg_k & SSL_PSK) {
2095 unsigned char psk[PSK_MAX_PSK_LEN];
2096 size_t psklen;
2097 PACKET psk_identity;
2098
2099 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2100 al = SSL_AD_DECODE_ERROR;
2101 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2102 goto f_err;
2103 }
2104 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2105 al = SSL_AD_DECODE_ERROR;
2106 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2107 SSL_R_DATA_LENGTH_TOO_LONG);
2108 goto f_err;
2109 }
2110 if (s->psk_server_callback == NULL) {
2111 al = SSL_AD_INTERNAL_ERROR;
2112 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2113 SSL_R_PSK_NO_SERVER_CB);
2114 goto f_err;
2115 }
2116
2117 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2118 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2119 al = SSL_AD_INTERNAL_ERROR;
2120 goto f_err;
2121 }
2122
2123 psklen = s->psk_server_callback(s, s->session->psk_identity,
2124 psk, sizeof(psk));
2125
2126 if (psklen > PSK_MAX_PSK_LEN) {
2127 al = SSL_AD_INTERNAL_ERROR;
2128 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2129 goto f_err;
2130 } else if (psklen == 0) {
2131 /*
2132 * PSK related to the given identity not found
2133 */
2134 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2135 SSL_R_PSK_IDENTITY_NOT_FOUND);
2136 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2137 goto f_err;
2138 }
2139
2140 OPENSSL_free(s->s3->tmp.psk);
2141 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2142 OPENSSL_cleanse(psk, psklen);
2143
2144 if (s->s3->tmp.psk == NULL) {
2145 al = SSL_AD_INTERNAL_ERROR;
2146 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2147 goto f_err;
2148 }
2149
2150 s->s3->tmp.psklen = psklen;
2151 }
2152 if (alg_k & SSL_kPSK) {
2153 /* Identity extracted earlier: should be nothing left */
2154 if (PACKET_remaining(pkt) != 0) {
2155 al = SSL_AD_HANDSHAKE_FAILURE;
2156 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2157 goto f_err;
2158 }
2159 /* PSK handled by ssl_generate_master_secret */
2160 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
2161 al = SSL_AD_INTERNAL_ERROR;
2162 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2163 goto f_err;
2164 }
2165 } else
2166 #endif
2167 #ifndef OPENSSL_NO_RSA
2168 if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2169 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2170 int decrypt_len;
2171 unsigned char decrypt_good, version_good;
2172 size_t j;
2173
2174 /* FIX THIS UP EAY EAY EAY EAY */
2175 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey);
2176 if (rsa == NULL) {
2177 al = SSL_AD_HANDSHAKE_FAILURE;
2178 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2179 SSL_R_MISSING_RSA_CERTIFICATE);
2180 goto f_err;
2181 }
2182
2183 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2184 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2185 enc_premaster = *pkt;
2186 } else {
2187 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2188 || PACKET_remaining(pkt) != 0) {
2189 al = SSL_AD_DECODE_ERROR;
2190 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2191 SSL_R_LENGTH_MISMATCH);
2192 goto f_err;
2193 }
2194 }
2195
2196 /*
2197 * We want to be sure that the plaintext buffer size makes it safe to
2198 * iterate over the entire size of a premaster secret
2199 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2200 * their ciphertext cannot accommodate a premaster secret anyway.
2201 */
2202 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2203 al = SSL_AD_INTERNAL_ERROR;
2204 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2205 RSA_R_KEY_SIZE_TOO_SMALL);
2206 goto f_err;
2207 }
2208
2209 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2210 if (rsa_decrypt == NULL) {
2211 al = SSL_AD_INTERNAL_ERROR;
2212 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2213 goto f_err;
2214 }
2215
2216 /*
2217 * We must not leak whether a decryption failure occurs because of
2218 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2219 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2220 * generates a random premaster secret for the case that the decrypt
2221 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2222 */
2223
2224 if (RAND_bytes(rand_premaster_secret,
2225 sizeof(rand_premaster_secret)) <= 0) {
2226 goto err;
2227 }
2228
2229 decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
2230 PACKET_data(&enc_premaster),
2231 rsa_decrypt, rsa, RSA_PKCS1_PADDING);
2232 ERR_clear_error();
2233
2234 /*
2235 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2236 * be 0xff if so and zero otherwise.
2237 */
2238 decrypt_good =
2239 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2240
2241 /*
2242 * If the version in the decrypted pre-master secret is correct then
2243 * version_good will be 0xff, otherwise it'll be zero. The
2244 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2245 * (http://eprint.iacr.org/2003/052/) exploits the version number
2246 * check as a "bad version oracle". Thus version checks are done in
2247 * constant time and are treated like any other decryption error.
2248 */
2249 version_good =
2250 constant_time_eq_8(rsa_decrypt[0],
2251 (unsigned)(s->client_version >> 8));
2252 version_good &=
2253 constant_time_eq_8(rsa_decrypt[1],
2254 (unsigned)(s->client_version & 0xff));
2255
2256 /*
2257 * The premaster secret must contain the same version number as the
2258 * ClientHello to detect version rollback attacks (strangely, the
2259 * protocol does not offer such protection for DH ciphersuites).
2260 * However, buggy clients exist that send the negotiated protocol
2261 * version instead if the server does not support the requested
2262 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2263 * clients.
2264 */
2265 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2266 unsigned char workaround_good;
2267 workaround_good =
2268 constant_time_eq_8(rsa_decrypt[0], (unsigned)(s->version >> 8));
2269 workaround_good &=
2270 constant_time_eq_8(rsa_decrypt[1],
2271 (unsigned)(s->version & 0xff));
2272 version_good |= workaround_good;
2273 }
2274
2275 /*
2276 * Both decryption and version must be good for decrypt_good to
2277 * remain non-zero (0xff).
2278 */
2279 decrypt_good &= version_good;
2280
2281 /*
2282 * Now copy rand_premaster_secret over from p using
2283 * decrypt_good_mask. If decryption failed, then p does not
2284 * contain valid plaintext, however, a check above guarantees
2285 * it is still sufficiently large to read from.
2286 */
2287 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2288 rsa_decrypt[j] =
2289 constant_time_select_8(decrypt_good, rsa_decrypt[j],
2290 rand_premaster_secret[j]);
2291 }
2292
2293 if (!ssl_generate_master_secret(s, rsa_decrypt,
2294 sizeof(rand_premaster_secret), 0)) {
2295 al = SSL_AD_INTERNAL_ERROR;
2296 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2297 goto f_err;
2298 }
2299 OPENSSL_free(rsa_decrypt);
2300 rsa_decrypt = NULL;
2301 } else
2302 #endif
2303 #ifndef OPENSSL_NO_DH
2304 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2305 EVP_PKEY *skey = NULL;
2306 DH *cdh;
2307
2308 if (!PACKET_get_net_2(pkt, &i)) {
2309 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2310 al = SSL_AD_HANDSHAKE_FAILURE;
2311 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2312 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2313 goto f_err;
2314 }
2315 i = 0;
2316 }
2317 if (PACKET_remaining(pkt) != i) {
2318 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2319 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2320 goto err;
2321 }
2322 skey = s->s3->tmp.pkey;
2323 if (skey == NULL) {
2324 al = SSL_AD_HANDSHAKE_FAILURE;
2325 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2326 SSL_R_MISSING_TMP_DH_KEY);
2327 goto f_err;
2328 }
2329
2330 if (PACKET_remaining(pkt) == 0L) {
2331 al = SSL_AD_HANDSHAKE_FAILURE;
2332 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2333 SSL_R_MISSING_TMP_DH_KEY);
2334 goto f_err;
2335 }
2336 if (!PACKET_get_bytes(pkt, &data, i)) {
2337 /* We already checked we have enough data */
2338 al = SSL_AD_INTERNAL_ERROR;
2339 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2340 ERR_R_INTERNAL_ERROR);
2341 goto f_err;
2342 }
2343 ckey = EVP_PKEY_new();
2344 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2345 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2346 goto err;
2347 }
2348 cdh = EVP_PKEY_get0_DH(ckey);
2349 cdh->pub_key = BN_bin2bn(data, i, NULL);
2350 if (cdh->pub_key == NULL) {
2351 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2352 goto err;
2353 }
2354
2355 if (ssl_derive(s, skey, ckey) == 0) {
2356 al = SSL_AD_INTERNAL_ERROR;
2357 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2358 goto f_err;
2359 }
2360
2361 EVP_PKEY_free(ckey);
2362 ckey = NULL;
2363
2364 } else
2365 #endif
2366
2367 #ifndef OPENSSL_NO_EC
2368 if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2369 EVP_PKEY *skey = NULL;
2370
2371 /* Let's get server private key and group information */
2372 if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2373 /* use the certificate */
2374 skey = s->cert->pkeys[SSL_PKEY_ECC].privatekey;
2375 } else {
2376 /*
2377 * use the ephermeral values we saved when generating the
2378 * ServerKeyExchange msg.
2379 */
2380 skey = s->s3->tmp.pkey;
2381 }
2382
2383 if (PACKET_remaining(pkt) == 0L) {
2384 /* We don't support ECDH client auth */
2385 al = SSL_AD_HANDSHAKE_FAILURE;
2386 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2387 SSL_R_MISSING_TMP_ECDH_KEY);
2388 goto f_err;
2389 } else {
2390 /*
2391 * Get client's public key from encoded point in the
2392 * ClientKeyExchange message.
2393 */
2394
2395 /* Get encoded point length */
2396 if (!PACKET_get_1(pkt, &i)) {
2397 al = SSL_AD_DECODE_ERROR;
2398 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2399 SSL_R_LENGTH_MISMATCH);
2400 goto f_err;
2401 }
2402 if (!PACKET_get_bytes(pkt, &data, i)
2403 || PACKET_remaining(pkt) != 0) {
2404 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2405 goto err;
2406 }
2407 ckey = EVP_PKEY_new();
2408 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2409 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EVP_LIB);
2410 goto err;
2411 }
2412 if (EC_KEY_oct2key(EVP_PKEY_get0_EC_KEY(ckey), data, i,
2413 NULL) == 0) {
2414 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2415 goto err;
2416 }
2417 }
2418
2419 if (ssl_derive(s, skey, ckey) == 0) {
2420 al = SSL_AD_INTERNAL_ERROR;
2421 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2422 goto f_err;
2423 }
2424
2425 EVP_PKEY_free(ckey);
2426 ckey = NULL;
2427
2428 return MSG_PROCESS_CONTINUE_PROCESSING;
2429 } else
2430 #endif
2431 #ifndef OPENSSL_NO_SRP
2432 if (alg_k & SSL_kSRP) {
2433 if (!PACKET_get_net_2(pkt, &i)
2434 || !PACKET_get_bytes(pkt, &data, i)) {
2435 al = SSL_AD_DECODE_ERROR;
2436 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH);
2437 goto f_err;
2438 }
2439 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2440 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2441 goto err;
2442 }
2443 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2444 || BN_is_zero(s->srp_ctx.A)) {
2445 al = SSL_AD_ILLEGAL_PARAMETER;
2446 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2447 SSL_R_BAD_SRP_PARAMETERS);
2448 goto f_err;
2449 }
2450 OPENSSL_free(s->session->srp_username);
2451 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2452 if (s->session->srp_username == NULL) {
2453 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2454 goto err;
2455 }
2456
2457 if (!srp_generate_server_master_secret(s)) {
2458 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2459 goto err;
2460 }
2461 } else
2462 #endif /* OPENSSL_NO_SRP */
2463 #ifndef OPENSSL_NO_GOST
2464 if (alg_k & SSL_kGOST) {
2465 EVP_PKEY_CTX *pkey_ctx;
2466 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2467 unsigned char premaster_secret[32], *start;
2468 size_t outlen = 32, inlen;
2469 unsigned long alg_a;
2470 int Ttag, Tclass;
2471 long Tlen;
2472 long sess_key_len;
2473
2474 /* Get our certificate private key */
2475 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2476 if (alg_a & SSL_aGOST12) {
2477 /*
2478 * New GOST ciphersuites have SSL_aGOST01 bit too
2479 */
2480 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2481 if (pk == NULL) {
2482 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2483 }
2484 if (pk == NULL) {
2485 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2486 }
2487 } else if (alg_a & SSL_aGOST01) {
2488 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2489 }
2490
2491 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2492 if (pkey_ctx == NULL) {
2493 al = SSL_AD_INTERNAL_ERROR;
2494 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2495 goto f_err;
2496 }
2497 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2498 al = SSL_AD_INTERNAL_ERROR;
2499 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2500 goto f_err;
2501 }
2502 /*
2503 * If client certificate is present and is of the same type, maybe
2504 * use it for key exchange. Don't mind errors from
2505 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2506 * client certificate for authorization only.
2507 */
2508 client_pub_pkey = X509_get0_pubkey(s->session->peer);
2509 if (client_pub_pkey) {
2510 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2511 ERR_clear_error();
2512 }
2513 /* Decrypt session key */
2514 sess_key_len = PACKET_remaining(pkt);
2515 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
2516 al = SSL_AD_INTERNAL_ERROR;
2517 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2518 goto gerr;
2519 }
2520 if (ASN1_get_object ((const unsigned char **)&data, &Tlen, &Ttag,
2521 &Tclass, sess_key_len) != V_ASN1_CONSTRUCTED
2522 || Ttag != V_ASN1_SEQUENCE
2523 || Tclass != V_ASN1_UNIVERSAL) {
2524 al = SSL_AD_DECODE_ERROR;
2525 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2526 SSL_R_DECRYPTION_FAILED);
2527 goto gerr;
2528 }
2529 start = data;
2530 inlen = Tlen;
2531 if (EVP_PKEY_decrypt
2532 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2533 al = SSL_AD_DECODE_ERROR;
2534 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2535 SSL_R_DECRYPTION_FAILED);
2536 goto gerr;
2537 }
2538 /* Generate master secret */
2539 if (!ssl_generate_master_secret(s, premaster_secret,
2540 sizeof(premaster_secret), 0)) {
2541 al = SSL_AD_INTERNAL_ERROR;
2542 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2543 goto gerr;
2544 }
2545 /* Check if pubkey from client certificate was used */
2546 if (EVP_PKEY_CTX_ctrl
2547 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2548 s->statem.no_cert_verify = 1;
2549
2550 EVP_PKEY_CTX_free(pkey_ctx);
2551 return MSG_PROCESS_CONTINUE_PROCESSING;
2552 gerr:
2553 EVP_PKEY_CTX_free(pkey_ctx);
2554 goto f_err;
2555 } else
2556 #endif
2557 {
2558 al = SSL_AD_HANDSHAKE_FAILURE;
2559 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2560 goto f_err;
2561 }
2562
2563 return MSG_PROCESS_CONTINUE_PROCESSING;
2564 f_err:
2565 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2566 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2567 err:
2568 #endif
2569 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2570 EVP_PKEY_free(ckey);
2571 #endif
2572 OPENSSL_free(rsa_decrypt);
2573 #ifndef OPENSSL_NO_PSK
2574 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2575 s->s3->tmp.psk = NULL;
2576 #endif
2577 ossl_statem_set_error(s);
2578 return MSG_PROCESS_ERROR;
2579 }
2580
2581 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
2582 {
2583 #ifndef OPENSSL_NO_SCTP
2584 if (wst == WORK_MORE_A) {
2585 if (SSL_IS_DTLS(s)) {
2586 unsigned char sctpauthkey[64];
2587 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2588 /*
2589 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2590 * used.
2591 */
2592 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2593 sizeof(DTLS1_SCTP_AUTH_LABEL));
2594
2595 if (SSL_export_keying_material(s, sctpauthkey,
2596 sizeof(sctpauthkey), labelbuffer,
2597 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
2598 ossl_statem_set_error(s);
2599 return WORK_ERROR;;
2600 }
2601
2602 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2603 sizeof(sctpauthkey), sctpauthkey);
2604 }
2605 wst = WORK_MORE_B;
2606 }
2607
2608 if ((wst == WORK_MORE_B)
2609 /* Is this SCTP? */
2610 && BIO_dgram_is_sctp(SSL_get_wbio(s))
2611 /* Are we renegotiating? */
2612 && s->renegotiate
2613 /* Are we going to skip the CertificateVerify? */
2614 && (s->session->peer == NULL || s->statem.no_cert_verify)
2615 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
2616 s->s3->in_read_app_data = 2;
2617 s->rwstate = SSL_READING;
2618 BIO_clear_retry_flags(SSL_get_rbio(s));
2619 BIO_set_retry_read(SSL_get_rbio(s));
2620 ossl_statem_set_sctp_read_sock(s, 1);
2621 return WORK_MORE_B;
2622 } else {
2623 ossl_statem_set_sctp_read_sock(s, 0);
2624 }
2625 #endif
2626
2627 if (s->statem.no_cert_verify) {
2628 /* No certificate verify so we no longer need the handshake_buffer */
2629 BIO_free(s->s3->handshake_buffer);
2630 s->s3->handshake_buffer = NULL;
2631 return WORK_FINISHED_CONTINUE;
2632 } else {
2633 if (!s->session->peer) {
2634 /* No peer certificate so we no longer need the handshake_buffer */
2635 BIO_free(s->s3->handshake_buffer);
2636 return WORK_FINISHED_CONTINUE;
2637 }
2638 if (!s->s3->handshake_buffer) {
2639 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
2640 ERR_R_INTERNAL_ERROR);
2641 ossl_statem_set_error(s);
2642 return WORK_ERROR;
2643 }
2644 /*
2645 * For sigalgs freeze the handshake buffer. If we support
2646 * extms we've done this already so this is a no-op
2647 */
2648 if (!ssl3_digest_cached_records(s, 1)) {
2649 ossl_statem_set_error(s);
2650 return WORK_ERROR;
2651 }
2652 }
2653
2654 return WORK_FINISHED_CONTINUE;
2655 }
2656
2657 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
2658 {
2659 EVP_PKEY *pkey = NULL;
2660 unsigned char *sig, *data;
2661 int al, ret = MSG_PROCESS_ERROR;
2662 int type = 0, j;
2663 unsigned int len;
2664 X509 *peer;
2665 const EVP_MD *md = NULL;
2666 long hdatalen = 0;
2667 void *hdata;
2668
2669 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2670
2671 if (mctx == NULL) {
2672 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
2673 al = SSL_AD_INTERNAL_ERROR;
2674 goto f_err;
2675 }
2676
2677 peer = s->session->peer;
2678 pkey = X509_get0_pubkey(peer);
2679 type = X509_certificate_type(peer, pkey);
2680
2681 if (!(type & EVP_PKT_SIGN)) {
2682 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
2683 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2684 al = SSL_AD_ILLEGAL_PARAMETER;
2685 goto f_err;
2686 }
2687
2688 /* Check for broken implementations of GOST ciphersuites */
2689 /*
2690 * If key is GOST and n is exactly 64, it is bare signature without
2691 * length field (CryptoPro implementations at least till CSP 4.0)
2692 */
2693 #ifndef OPENSSL_NO_GOST
2694 if (PACKET_remaining(pkt) == 64
2695 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
2696 len = 64;
2697 } else
2698 #endif
2699 {
2700 if (SSL_USE_SIGALGS(s)) {
2701 int rv;
2702
2703 if (!PACKET_get_bytes(pkt, &sig, 2)) {
2704 al = SSL_AD_DECODE_ERROR;
2705 goto f_err;
2706 }
2707 rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
2708 if (rv == -1) {
2709 al = SSL_AD_INTERNAL_ERROR;
2710 goto f_err;
2711 } else if (rv == 0) {
2712 al = SSL_AD_DECODE_ERROR;
2713 goto f_err;
2714 }
2715 #ifdef SSL_DEBUG
2716 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2717 #endif
2718 } else {
2719 /* Use default digest for this key type */
2720 int idx = ssl_cert_type(NULL, pkey);
2721 if (idx >= 0)
2722 md = s->s3->tmp.md[idx];
2723 if (md == NULL) {
2724 al = SSL_AD_INTERNAL_ERROR;
2725 goto f_err;
2726 }
2727 }
2728
2729 if (!PACKET_get_net_2(pkt, &len)) {
2730 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2731 al = SSL_AD_DECODE_ERROR;
2732 goto f_err;
2733 }
2734 }
2735 j = EVP_PKEY_size(pkey);
2736 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
2737 || (PACKET_remaining(pkt) == 0)) {
2738 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2739 al = SSL_AD_DECODE_ERROR;
2740 goto f_err;
2741 }
2742 if (!PACKET_get_bytes(pkt, &data, len)) {
2743 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2744 al = SSL_AD_DECODE_ERROR;
2745 goto f_err;
2746 }
2747
2748 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2749 if (hdatalen <= 0) {
2750 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2751 al = SSL_AD_INTERNAL_ERROR;
2752 goto f_err;
2753 }
2754 #ifdef SSL_DEBUG
2755 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
2756 #endif
2757 if (!EVP_VerifyInit_ex(mctx, md, NULL)
2758 || !EVP_VerifyUpdate(mctx, hdata, hdatalen)) {
2759 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2760 al = SSL_AD_INTERNAL_ERROR;
2761 goto f_err;
2762 }
2763
2764 #ifndef OPENSSL_NO_GOST
2765 {
2766 int pktype = EVP_PKEY_id(pkey);
2767 if (pktype == NID_id_GostR3410_2001
2768 || pktype == NID_id_GostR3410_2012_256
2769 || pktype == NID_id_GostR3410_2012_512)
2770 BUF_reverse(data, NULL, len);
2771 }
2772 #endif
2773
2774 if (s->version == SSL3_VERSION
2775 && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2776 s->session->master_key_length,
2777 s->session->master_key)) {
2778 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2779 al = SSL_AD_INTERNAL_ERROR;
2780 goto f_err;
2781 }
2782
2783 if (EVP_VerifyFinal(mctx, data, len, pkey) <= 0) {
2784 al = SSL_AD_DECRYPT_ERROR;
2785 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2786 goto f_err;
2787 }
2788
2789 ret = MSG_PROCESS_CONTINUE_PROCESSING;
2790 if (0) {
2791 f_err:
2792 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2793 ossl_statem_set_error(s);
2794 }
2795 BIO_free(s->s3->handshake_buffer);
2796 s->s3->handshake_buffer = NULL;
2797 EVP_MD_CTX_free(mctx);
2798 return ret;
2799 }
2800
2801 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
2802 {
2803 int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
2804 X509 *x = NULL;
2805 unsigned long l, llen;
2806 const unsigned char *certstart;
2807 unsigned char *certbytes;
2808 STACK_OF(X509) *sk = NULL;
2809 PACKET spkt;
2810
2811 if ((sk = sk_X509_new_null()) == NULL) {
2812 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2813 goto f_err;
2814 }
2815
2816 if (!PACKET_get_net_3(pkt, &llen)
2817 || !PACKET_get_sub_packet(pkt, &spkt, llen)
2818 || PACKET_remaining(pkt) != 0) {
2819 al = SSL_AD_DECODE_ERROR;
2820 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
2821 goto f_err;
2822 }
2823
2824 while (PACKET_remaining(&spkt) > 0) {
2825 if (!PACKET_get_net_3(&spkt, &l)
2826 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
2827 al = SSL_AD_DECODE_ERROR;
2828 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2829 SSL_R_CERT_LENGTH_MISMATCH);
2830 goto f_err;
2831 }
2832
2833 certstart = certbytes;
2834 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
2835 if (x == NULL) {
2836 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
2837 goto f_err;
2838 }
2839 if (certbytes != (certstart + l)) {
2840 al = SSL_AD_DECODE_ERROR;
2841 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2842 SSL_R_CERT_LENGTH_MISMATCH);
2843 goto f_err;
2844 }
2845 if (!sk_X509_push(sk, x)) {
2846 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2847 goto f_err;
2848 }
2849 x = NULL;
2850 }
2851
2852 if (sk_X509_num(sk) <= 0) {
2853 /* TLS does not mind 0 certs returned */
2854 if (s->version == SSL3_VERSION) {
2855 al = SSL_AD_HANDSHAKE_FAILURE;
2856 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2857 SSL_R_NO_CERTIFICATES_RETURNED);
2858 goto f_err;
2859 }
2860 /* Fail for TLS only if we required a certificate */
2861 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2862 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2863 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2864 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2865 al = SSL_AD_HANDSHAKE_FAILURE;
2866 goto f_err;
2867 }
2868 /* No client certificate so digest cached records */
2869 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
2870 goto f_err;
2871 }
2872 } else {
2873 EVP_PKEY *pkey;
2874 i = ssl_verify_cert_chain(s, sk);
2875 if (i <= 0) {
2876 al = ssl_verify_alarm_type(s->verify_result);
2877 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2878 SSL_R_CERTIFICATE_VERIFY_FAILED);
2879 goto f_err;
2880 }
2881 if (i > 1) {
2882 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
2883 al = SSL_AD_HANDSHAKE_FAILURE;
2884 goto f_err;
2885 }
2886 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
2887 if (pkey == NULL) {
2888 al = SSL3_AD_HANDSHAKE_FAILURE;
2889 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2890 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
2891 goto f_err;
2892 }
2893 }
2894
2895 X509_free(s->session->peer);
2896 s->session->peer = sk_X509_shift(sk);
2897 s->session->verify_result = s->verify_result;
2898
2899 sk_X509_pop_free(s->session->peer_chain, X509_free);
2900 s->session->peer_chain = sk;
2901 /*
2902 * Inconsistency alert: cert_chain does *not* include the peer's own
2903 * certificate, while we do include it in s3_clnt.c
2904 */
2905 sk = NULL;
2906 ret = MSG_PROCESS_CONTINUE_READING;
2907 goto done;
2908
2909 f_err:
2910 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2911 ossl_statem_set_error(s);
2912 done:
2913 X509_free(x);
2914 sk_X509_pop_free(sk, X509_free);
2915 return ret;
2916 }
2917
2918 int tls_construct_server_certificate(SSL *s)
2919 {
2920 CERT_PKEY *cpk;
2921
2922 cpk = ssl_get_server_send_pkey(s);
2923 if (cpk == NULL) {
2924 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2925 ossl_statem_set_error(s);
2926 return 0;
2927 }
2928
2929 if (!ssl3_output_cert_chain(s, cpk)) {
2930 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2931 ossl_statem_set_error(s);
2932 return 0;
2933 }
2934
2935 return 1;
2936 }
2937
2938 int tls_construct_new_session_ticket(SSL *s)
2939 {
2940 unsigned char *senc = NULL;
2941 EVP_CIPHER_CTX *ctx;
2942 HMAC_CTX *hctx = NULL;
2943 unsigned char *p, *macstart;
2944 const unsigned char *const_p;
2945 int len, slen_full, slen;
2946 SSL_SESSION *sess;
2947 unsigned int hlen;
2948 SSL_CTX *tctx = s->initial_ctx;
2949 unsigned char iv[EVP_MAX_IV_LENGTH];
2950 unsigned char key_name[16];
2951
2952 /* get session encoding length */
2953 slen_full = i2d_SSL_SESSION(s->session, NULL);
2954 /*
2955 * Some length values are 16 bits, so forget it if session is too
2956 * long
2957 */
2958 if (slen_full == 0 || slen_full > 0xFF00) {
2959 ossl_statem_set_error(s);
2960 return 0;
2961 }
2962 senc = OPENSSL_malloc(slen_full);
2963 if (senc == NULL) {
2964 ossl_statem_set_error(s);
2965 return 0;
2966 }
2967
2968 ctx = EVP_CIPHER_CTX_new();
2969 hctx = HMAC_CTX_new();
2970
2971 p = senc;
2972 if (!i2d_SSL_SESSION(s->session, &p))
2973 goto err;
2974
2975 /*
2976 * create a fresh copy (not shared with other threads) to clean up
2977 */
2978 const_p = senc;
2979 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2980 if (sess == NULL)
2981 goto err;
2982 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
2983
2984 slen = i2d_SSL_SESSION(sess, NULL);
2985 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
2986 SSL_SESSION_free(sess);
2987 goto err;
2988 }
2989 p = senc;
2990 if (!i2d_SSL_SESSION(sess, &p)) {
2991 SSL_SESSION_free(sess);
2992 goto err;
2993 }
2994 SSL_SESSION_free(sess);
2995
2996 /*-
2997 * Grow buffer if need be: the length calculation is as
2998 * follows handshake_header_length +
2999 * 4 (ticket lifetime hint) + 2 (ticket length) +
3000 * 16 (key name) + max_iv_len (iv length) +
3001 * session_length + max_enc_block_size (max encrypted session
3002 * length) + max_md_size (HMAC).
3003 */
3004 if (!BUF_MEM_grow(s->init_buf,
3005 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3006 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3007 goto err;
3008
3009 p = ssl_handshake_start(s);
3010 /*
3011 * Initialize HMAC and cipher contexts. If callback present it does
3012 * all the work otherwise use generated values from parent ctx.
3013 */
3014 if (tctx->tlsext_ticket_key_cb) {
3015 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, ctx, hctx, 1) < 0)
3016 goto err;
3017 } else {
3018 if (RAND_bytes(iv, 16) <= 0)
3019 goto err;
3020 if (!EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL,
3021 tctx->tlsext_tick_aes_key, iv))
3022 goto err;
3023 if (!HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, 16,
3024 EVP_sha256(), NULL))
3025 goto err;
3026 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3027 }
3028
3029 /*
3030 * Ticket lifetime hint (advisory only): We leave this unspecified
3031 * for resumed session (for simplicity), and guess that tickets for
3032 * new sessions will live as long as their sessions.
3033 */
3034 l2n(s->hit ? 0 : s->session->timeout, p);
3035
3036 /* Skip ticket length for now */
3037 p += 2;
3038 /* Output key name */
3039 macstart = p;
3040 memcpy(p, key_name, 16);
3041 p += 16;
3042 /* output IV */
3043 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(ctx));
3044 p += EVP_CIPHER_CTX_iv_length(ctx);
3045 /* Encrypt session data */
3046 if (!EVP_EncryptUpdate(ctx, p, &len, senc, slen))
3047 goto err;
3048 p += len;
3049 if (!EVP_EncryptFinal(ctx, p, &len))
3050 goto err;
3051 p += len;
3052
3053 if (!HMAC_Update(hctx, macstart, p - macstart))
3054 goto err;
3055 if (!HMAC_Final(hctx, p, &hlen))
3056 goto err;
3057
3058 EVP_CIPHER_CTX_free(ctx);
3059 HMAC_CTX_free(hctx);
3060 ctx = NULL;
3061 hctx = NULL;
3062
3063 p += hlen;
3064 /* Now write out lengths: p points to end of data written */
3065 /* Total length */
3066 len = p - ssl_handshake_start(s);
3067 /* Skip ticket lifetime hint */
3068 p = ssl_handshake_start(s) + 4;
3069 s2n(len - 6, p);
3070 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3071 goto err;
3072 OPENSSL_free(senc);
3073
3074 return 1;
3075 err:
3076 OPENSSL_free(senc);
3077 EVP_CIPHER_CTX_free(ctx);
3078 HMAC_CTX_free(hctx);
3079 ossl_statem_set_error(s);
3080 return 0;
3081 }
3082
3083 int tls_construct_cert_status(SSL *s)
3084 {
3085 unsigned char *p;
3086 /*-
3087 * Grow buffer if need be: the length calculation is as
3088 * follows 1 (message type) + 3 (message length) +
3089 * 1 (ocsp response type) + 3 (ocsp response length)
3090 * + (ocsp response)
3091 */
3092 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3093 ossl_statem_set_error(s);
3094 return 0;
3095 }
3096
3097 p = (unsigned char *)s->init_buf->data;
3098
3099 /* do the header */
3100 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3101 /* message length */
3102 l2n3(s->tlsext_ocsp_resplen + 4, p);
3103 /* status type */
3104 *(p++) = s->tlsext_status_type;
3105 /* length of OCSP response */
3106 l2n3(s->tlsext_ocsp_resplen, p);
3107 /* actual response */
3108 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3109 /* number of bytes to write */
3110 s->init_num = 8 + s->tlsext_ocsp_resplen;
3111 s->init_off = 0;
3112
3113 return 1;
3114 }
3115
3116 #ifndef OPENSSL_NO_NEXTPROTONEG
3117 /*
3118 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3119 * It sets the next_proto member in s if found
3120 */
3121 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3122 {
3123 PACKET next_proto, padding;
3124 size_t next_proto_len;
3125
3126 /*-
3127 * The payload looks like:
3128 * uint8 proto_len;
3129 * uint8 proto[proto_len];
3130 * uint8 padding_len;
3131 * uint8 padding[padding_len];
3132 */
3133 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3134 || !PACKET_get_length_prefixed_1(pkt, &padding)
3135 || PACKET_remaining(pkt) > 0) {
3136 SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3137 goto err;
3138 }
3139
3140 if (!PACKET_memdup(&next_proto, &s->next_proto_negotiated,
3141 &next_proto_len)) {
3142 s->next_proto_negotiated_len = 0;
3143 goto err;
3144 }
3145
3146 s->next_proto_negotiated_len = (unsigned char)next_proto_len;
3147
3148 return MSG_PROCESS_CONTINUE_READING;
3149 err:
3150 ossl_statem_set_error(s);
3151 return MSG_PROCESS_ERROR;
3152 }
3153 #endif
3154
3155 #define SSLV2_CIPHER_LEN 3
3156
3157 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
3158 PACKET *cipher_suites,
3159 STACK_OF(SSL_CIPHER) **skp,
3160 int sslv2format, int *al
3161 )
3162 {
3163 const SSL_CIPHER *c;
3164 STACK_OF(SSL_CIPHER) *sk;
3165 int n;
3166 /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
3167 unsigned char cipher[SSLV2_CIPHER_LEN];
3168
3169 s->s3->send_connection_binding = 0;
3170
3171 n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
3172
3173 if (PACKET_remaining(cipher_suites) == 0) {
3174 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
3175 *al = SSL_AD_ILLEGAL_PARAMETER;
3176 return NULL;
3177 }
3178
3179 if (PACKET_remaining(cipher_suites) % n != 0) {
3180 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3181 SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3182 *al = SSL_AD_DECODE_ERROR;
3183 return NULL;
3184 }
3185
3186 if ((skp == NULL) || (*skp == NULL)) {
3187 sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3188 if(sk == NULL) {
3189 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3190 *al = SSL_AD_INTERNAL_ERROR;
3191 return NULL;
3192 }
3193 } else {
3194 sk = *skp;
3195 sk_SSL_CIPHER_zero(sk);
3196 }
3197
3198 if (!PACKET_memdup(cipher_suites, &s->s3->tmp.ciphers_raw,
3199 &s->s3->tmp.ciphers_rawlen)) {
3200 *al = SSL_AD_INTERNAL_ERROR;
3201 goto err;
3202 }
3203
3204 while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
3205 /*
3206 * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
3207 * first byte set to zero, while true SSLv2 ciphers have a non-zero
3208 * first byte. We don't support any true SSLv2 ciphers, so skip them.
3209 */
3210 if (sslv2format && cipher[0] != '\0')
3211 continue;
3212
3213 /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3214 if ((cipher[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3215 (cipher[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3216 /* SCSV fatal if renegotiating */
3217 if (s->renegotiate) {
3218 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3219 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3220 *al = SSL_AD_HANDSHAKE_FAILURE;
3221 goto err;
3222 }
3223 s->s3->send_connection_binding = 1;
3224 #ifdef OPENSSL_RI_DEBUG
3225 fprintf(stderr, "SCSV received by server\n");
3226 #endif
3227 continue;
3228 }
3229
3230 /* Check for TLS_FALLBACK_SCSV */
3231 if ((cipher[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3232 (cipher[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3233 /*
3234 * The SCSV indicates that the client previously tried a higher
3235 * version. Fail if the current version is an unexpected
3236 * downgrade.
3237 */
3238 if (!ssl_check_version_downgrade(s)) {
3239 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3240 SSL_R_INAPPROPRIATE_FALLBACK);
3241 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
3242 goto err;
3243 }
3244 continue;
3245 }
3246
3247 /* For SSLv2-compat, ignore leading 0-byte. */
3248 c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher);
3249 if (c != NULL) {
3250 if (!sk_SSL_CIPHER_push(sk, c)) {
3251 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3252 *al = SSL_AD_INTERNAL_ERROR;
3253 goto err;
3254 }
3255 }
3256 }
3257 if (PACKET_remaining(cipher_suites) > 0) {
3258 *al = SSL_AD_INTERNAL_ERROR;
3259 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_INTERNAL_ERROR);
3260 goto err;
3261 }
3262
3263 if (skp != NULL)
3264 *skp = sk;
3265 return (sk);
3266 err:
3267 if ((skp == NULL) || (*skp == NULL))
3268 sk_SSL_CIPHER_free(sk);
3269 return NULL;
3270 }