18430ea315015151f07addc596a32e82cb22419e
[openssl.git] / ssl / statem / statem_clnt.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12  *
13  * Portions of the attached software ("Contribution") are developed by
14  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
15  *
16  * The Contribution is licensed pursuant to the OpenSSL open source
17  * license provided above.
18  *
19  * ECC cipher suite support in OpenSSL originally written by
20  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
21  *
22  */
23 /* ====================================================================
24  * Copyright 2005 Nokia. All rights reserved.
25  *
26  * The portions of the attached software ("Contribution") is developed by
27  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
28  * license.
29  *
30  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
31  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
32  * support (see RFC 4279) to OpenSSL.
33  *
34  * No patent licenses or other rights except those expressly stated in
35  * the OpenSSL open source license shall be deemed granted or received
36  * expressly, by implication, estoppel, or otherwise.
37  *
38  * No assurances are provided by Nokia that the Contribution does not
39  * infringe the patent or other intellectual property rights of any third
40  * party or that the license provides you with all the necessary rights
41  * to make use of the Contribution.
42  *
43  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
44  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
45  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
46  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
47  * OTHERWISE.
48  */
49
50 #include <stdio.h>
51 #include "../ssl_locl.h"
52 #include "statem_locl.h"
53 #include <openssl/buffer.h>
54 #include <openssl/rand.h>
55 #include <openssl/objects.h>
56 #include <openssl/evp.h>
57 #include <openssl/md5.h>
58 #include <openssl/dh.h>
59 #include <openssl/bn.h>
60 #include <openssl/engine.h>
61
62 static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL *s, PACKET *pkt);
63
64 static ossl_inline int cert_req_allowed(SSL *s);
65 static int key_exchange_expected(SSL *s);
66 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b);
67 static int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk,
68                                     WPACKET *pkt);
69
70 /*
71  * Is a CertificateRequest message allowed at the moment or not?
72  *
73  *  Return values are:
74  *  1: Yes
75  *  0: No
76  */
77 static ossl_inline int cert_req_allowed(SSL *s)
78 {
79     /* TLS does not like anon-DH with client cert */
80     if ((s->version > SSL3_VERSION
81          && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL))
82         || (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aSRP | SSL_aPSK)))
83         return 0;
84
85     return 1;
86 }
87
88 /*
89  * Should we expect the ServerKeyExchange message or not?
90  *
91  *  Return values are:
92  *  1: Yes
93  *  0: No
94  */
95 static int key_exchange_expected(SSL *s)
96 {
97     long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
98
99     /*
100      * Can't skip server key exchange if this is an ephemeral
101      * ciphersuite or for SRP
102      */
103     if (alg_k & (SSL_kDHE | SSL_kECDHE | SSL_kDHEPSK | SSL_kECDHEPSK
104                  | SSL_kSRP)) {
105         return 1;
106     }
107
108     return 0;
109 }
110
111 /*
112  * ossl_statem_client_read_transition() encapsulates the logic for the allowed
113  * handshake state transitions when a TLS1.3 client is reading messages from the
114  * server. The message type that the server has sent is provided in |mt|. The
115  * current state is in |s->statem.hand_state|.
116  *
117  * Return values are 1 for success (transition allowed) and  0 on error
118  * (transition not allowed)
119  */
120 static int ossl_statem_client13_read_transition(SSL *s, int mt)
121 {
122     OSSL_STATEM *st = &s->statem;
123
124     /*
125      * TODO(TLS1.3): This is still based on the TLSv1.2 state machine. Over time
126      * we will update this to look more like real TLSv1.3
127      */
128
129     /*
130      * Note: There is no case for TLS_ST_CW_CLNT_HELLO, because we haven't
131      * yet negotiated TLSv1.3 at that point so that is handled by
132      * ossl_statem_client_read_transition()
133      */
134
135     switch (st->hand_state) {
136     default:
137         break;
138
139     case TLS_ST_CR_SRVR_HELLO:
140         if (mt == SSL3_MT_ENCRYPTED_EXTENSIONS) {
141             st->hand_state = TLS_ST_CR_ENCRYPTED_EXTENSIONS;
142             return 1;
143         }
144         break;
145
146     case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
147         if (s->hit) {
148             if (mt == SSL3_MT_FINISHED) {
149                 st->hand_state = TLS_ST_CR_FINISHED;
150                 return 1;
151             }
152         } else {
153             if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
154                 st->hand_state = TLS_ST_CR_CERT_REQ;
155                 return 1;
156             }
157             if (mt == SSL3_MT_CERTIFICATE) {
158                 st->hand_state = TLS_ST_CR_CERT;
159                 return 1;
160             }
161         }
162         break;
163
164     case TLS_ST_CR_CERT_REQ:
165         if (mt == SSL3_MT_CERTIFICATE) {
166             st->hand_state = TLS_ST_CR_CERT;
167             return 1;
168         }
169         break;
170
171     case TLS_ST_CR_CERT:
172         /*
173          * The CertificateStatus message is optional even if
174          * |tlsext_status_expected| is set
175          */
176         if (s->tlsext_status_expected && mt == SSL3_MT_CERTIFICATE_STATUS) {
177             st->hand_state = TLS_ST_CR_CERT_STATUS;
178             return 1;
179         }
180         /* Fall through */
181
182     case TLS_ST_CR_CERT_STATUS:
183         if (mt == SSL3_MT_FINISHED) {
184             st->hand_state = TLS_ST_CR_FINISHED;
185             return 1;
186         }
187         break;
188
189     }
190
191     /* No valid transition found */
192     return 0;
193 }
194
195 /*
196  * ossl_statem_client_read_transition() encapsulates the logic for the allowed
197  * handshake state transitions when the client is reading messages from the
198  * server. The message type that the server has sent is provided in |mt|. The
199  * current state is in |s->statem.hand_state|.
200  *
201  * Return values are 1 for success (transition allowed) and  0 on error
202  * (transition not allowed)
203  */
204 int ossl_statem_client_read_transition(SSL *s, int mt)
205 {
206     OSSL_STATEM *st = &s->statem;
207     int ske_expected;
208
209     /*
210      * Note that after a ClientHello we don't know what version we are going
211      * to negotiate yet, so we don't take this branch until later
212      */
213     if (SSL_IS_TLS13(s)) {
214         if (!ossl_statem_client13_read_transition(s, mt))
215             goto err;
216         return 1;
217     }
218
219     switch (st->hand_state) {
220     default:
221         break;
222
223     case TLS_ST_CW_CLNT_HELLO:
224         if (mt == SSL3_MT_SERVER_HELLO) {
225             st->hand_state = TLS_ST_CR_SRVR_HELLO;
226             return 1;
227         }
228
229         if (SSL_IS_DTLS(s)) {
230             if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
231                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
232                 return 1;
233             }
234         }
235         break;
236
237     case TLS_ST_CR_SRVR_HELLO:
238         if (s->hit) {
239             if (s->tlsext_ticket_expected) {
240                 if (mt == SSL3_MT_NEWSESSION_TICKET) {
241                     st->hand_state = TLS_ST_CR_SESSION_TICKET;
242                     return 1;
243                 }
244             } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
245                 st->hand_state = TLS_ST_CR_CHANGE;
246                 return 1;
247             }
248         } else {
249             if (SSL_IS_DTLS(s) && mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
250                 st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
251                 return 1;
252             } else if (s->version >= TLS1_VERSION
253                        && s->tls_session_secret_cb != NULL
254                        && s->session->tlsext_tick != NULL
255                        && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
256                 /*
257                  * Normally, we can tell if the server is resuming the session
258                  * from the session ID. EAP-FAST (RFC 4851), however, relies on
259                  * the next server message after the ServerHello to determine if
260                  * the server is resuming.
261                  */
262                 s->hit = 1;
263                 st->hand_state = TLS_ST_CR_CHANGE;
264                 return 1;
265             } else if (!(s->s3->tmp.new_cipher->algorithm_auth
266                          & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
267                 if (mt == SSL3_MT_CERTIFICATE) {
268                     st->hand_state = TLS_ST_CR_CERT;
269                     return 1;
270                 }
271             } else {
272                 ske_expected = key_exchange_expected(s);
273                 /* SKE is optional for some PSK ciphersuites */
274                 if (ske_expected
275                     || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)
276                         && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
277                     if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
278                         st->hand_state = TLS_ST_CR_KEY_EXCH;
279                         return 1;
280                     }
281                 } else if (mt == SSL3_MT_CERTIFICATE_REQUEST
282                            && cert_req_allowed(s)) {
283                     st->hand_state = TLS_ST_CR_CERT_REQ;
284                     return 1;
285                 } else if (mt == SSL3_MT_SERVER_DONE) {
286                     st->hand_state = TLS_ST_CR_SRVR_DONE;
287                     return 1;
288                 }
289             }
290         }
291         break;
292
293     case TLS_ST_CR_CERT:
294         /*
295          * The CertificateStatus message is optional even if
296          * |tlsext_status_expected| is set
297          */
298         if (s->tlsext_status_expected && mt == SSL3_MT_CERTIFICATE_STATUS) {
299             st->hand_state = TLS_ST_CR_CERT_STATUS;
300             return 1;
301         }
302         /* Fall through */
303
304     case TLS_ST_CR_CERT_STATUS:
305         ske_expected = key_exchange_expected(s);
306         /* SKE is optional for some PSK ciphersuites */
307         if (ske_expected || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)
308                              && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
309             if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
310                 st->hand_state = TLS_ST_CR_KEY_EXCH;
311                 return 1;
312             }
313             goto err;
314         }
315         /* Fall through */
316
317     case TLS_ST_CR_KEY_EXCH:
318         if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
319             if (cert_req_allowed(s)) {
320                 st->hand_state = TLS_ST_CR_CERT_REQ;
321                 return 1;
322             }
323             goto err;
324         }
325         /* Fall through */
326
327     case TLS_ST_CR_CERT_REQ:
328         if (mt == SSL3_MT_SERVER_DONE) {
329             st->hand_state = TLS_ST_CR_SRVR_DONE;
330             return 1;
331         }
332         break;
333
334     case TLS_ST_CW_FINISHED:
335         if (s->tlsext_ticket_expected) {
336             if (mt == SSL3_MT_NEWSESSION_TICKET) {
337                 st->hand_state = TLS_ST_CR_SESSION_TICKET;
338                 return 1;
339             }
340         } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
341             st->hand_state = TLS_ST_CR_CHANGE;
342             return 1;
343         }
344         break;
345
346     case TLS_ST_CR_SESSION_TICKET:
347         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
348             st->hand_state = TLS_ST_CR_CHANGE;
349             return 1;
350         }
351         break;
352
353     case TLS_ST_CR_CHANGE:
354         if (mt == SSL3_MT_FINISHED) {
355             st->hand_state = TLS_ST_CR_FINISHED;
356             return 1;
357         }
358         break;
359     }
360
361  err:
362     /* No valid transition found */
363     ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
364     SSLerr(SSL_F_OSSL_STATEM_CLIENT_READ_TRANSITION, SSL_R_UNEXPECTED_MESSAGE);
365     return 0;
366 }
367
368 /*
369  * ossl_statem_client13_write_transition() works out what handshake state to
370  * move to next when the TLSv1.3 client is writing messages to be sent to the
371  * server.
372  */
373 static WRITE_TRAN ossl_statem_client13_write_transition(SSL *s)
374 {
375     OSSL_STATEM *st = &s->statem;
376
377     /*
378      * TODO(TLS1.3): This is still based on the TLSv1.2 state machine. Over time
379      * we will update this to look more like real TLSv1.3
380      */
381
382     /*
383      * Note: There are no cases for TLS_ST_BEFORE or TLS_ST_CW_CLNT_HELLO,
384      * because we haven't negotiated TLSv1.3 yet at that point. They are
385      * handled by ossl_statem_client_write_transition().
386      */
387     switch (st->hand_state) {
388     default:
389         /* Shouldn't happen */
390         return WRITE_TRAN_ERROR;
391
392     case TLS_ST_CR_FINISHED:
393         st->hand_state = (s->s3->tmp.cert_req != 0) ? TLS_ST_CW_CERT
394                                                     : TLS_ST_CW_FINISHED;
395         return WRITE_TRAN_CONTINUE;
396
397     case TLS_ST_CW_CERT:
398         /* If a non-empty Certificate we also send CertificateVerify */
399         st->hand_state = (s->s3->tmp.cert_req == 1) ? TLS_ST_CW_CERT_VRFY
400                                                     : TLS_ST_CW_FINISHED;
401         return WRITE_TRAN_CONTINUE;
402
403     case TLS_ST_CW_CERT_VRFY:
404         st->hand_state = TLS_ST_CW_FINISHED;
405         return WRITE_TRAN_CONTINUE;
406
407     case TLS_ST_CW_FINISHED:
408         st->hand_state = TLS_ST_OK;
409         ossl_statem_set_in_init(s, 0);
410         return WRITE_TRAN_CONTINUE;
411     }
412 }
413
414 /*
415  * ossl_statem_client_write_transition() works out what handshake state to
416  * move to next when the client is writing messages to be sent to the server.
417  */
418 WRITE_TRAN ossl_statem_client_write_transition(SSL *s)
419 {
420     OSSL_STATEM *st = &s->statem;
421
422     /*
423      * Note that immediately before/after a ClientHello we don't know what
424      * version we are going to negotiate yet, so we don't take this branch until
425      * later
426      */
427     if (SSL_IS_TLS13(s))
428         return ossl_statem_client13_write_transition(s);
429
430     switch (st->hand_state) {
431     default:
432         /* Shouldn't happen */
433         return WRITE_TRAN_ERROR;
434
435     case TLS_ST_OK:
436         /* Renegotiation - fall through */
437     case TLS_ST_BEFORE:
438         st->hand_state = TLS_ST_CW_CLNT_HELLO;
439         return WRITE_TRAN_CONTINUE;
440
441     case TLS_ST_CW_CLNT_HELLO:
442         /*
443          * No transition at the end of writing because we don't know what
444          * we will be sent
445          */
446         return WRITE_TRAN_FINISHED;
447
448     case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
449         st->hand_state = TLS_ST_CW_CLNT_HELLO;
450         return WRITE_TRAN_CONTINUE;
451
452     case TLS_ST_CR_SRVR_DONE:
453         if (s->s3->tmp.cert_req)
454             st->hand_state = TLS_ST_CW_CERT;
455         else
456             st->hand_state = TLS_ST_CW_KEY_EXCH;
457         return WRITE_TRAN_CONTINUE;
458
459     case TLS_ST_CW_CERT:
460         st->hand_state = TLS_ST_CW_KEY_EXCH;
461         return WRITE_TRAN_CONTINUE;
462
463     case TLS_ST_CW_KEY_EXCH:
464         /*
465          * For TLS, cert_req is set to 2, so a cert chain of nothing is
466          * sent, but no verify packet is sent
467          */
468         /*
469          * XXX: For now, we do not support client authentication in ECDH
470          * cipher suites with ECDH (rather than ECDSA) certificates. We
471          * need to skip the certificate verify message when client's
472          * ECDH public key is sent inside the client certificate.
473          */
474         if (s->s3->tmp.cert_req == 1) {
475             st->hand_state = TLS_ST_CW_CERT_VRFY;
476         } else {
477             st->hand_state = TLS_ST_CW_CHANGE;
478         }
479         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
480             st->hand_state = TLS_ST_CW_CHANGE;
481         }
482         return WRITE_TRAN_CONTINUE;
483
484     case TLS_ST_CW_CERT_VRFY:
485         st->hand_state = TLS_ST_CW_CHANGE;
486         return WRITE_TRAN_CONTINUE;
487
488     case TLS_ST_CW_CHANGE:
489 #if defined(OPENSSL_NO_NEXTPROTONEG)
490         st->hand_state = TLS_ST_CW_FINISHED;
491 #else
492         if (!SSL_IS_DTLS(s) && s->s3->next_proto_neg_seen)
493             st->hand_state = TLS_ST_CW_NEXT_PROTO;
494         else
495             st->hand_state = TLS_ST_CW_FINISHED;
496 #endif
497         return WRITE_TRAN_CONTINUE;
498
499 #if !defined(OPENSSL_NO_NEXTPROTONEG)
500     case TLS_ST_CW_NEXT_PROTO:
501         st->hand_state = TLS_ST_CW_FINISHED;
502         return WRITE_TRAN_CONTINUE;
503 #endif
504
505     case TLS_ST_CW_FINISHED:
506         if (s->hit) {
507             st->hand_state = TLS_ST_OK;
508             ossl_statem_set_in_init(s, 0);
509             return WRITE_TRAN_CONTINUE;
510         } else {
511             return WRITE_TRAN_FINISHED;
512         }
513
514     case TLS_ST_CR_FINISHED:
515         if (s->hit) {
516             st->hand_state = TLS_ST_CW_CHANGE;
517             return WRITE_TRAN_CONTINUE;
518         } else {
519             st->hand_state = TLS_ST_OK;
520             ossl_statem_set_in_init(s, 0);
521             return WRITE_TRAN_CONTINUE;
522         }
523     }
524 }
525
526 /*
527  * Perform any pre work that needs to be done prior to sending a message from
528  * the client to the server.
529  */
530 WORK_STATE ossl_statem_client_pre_work(SSL *s, WORK_STATE wst)
531 {
532     OSSL_STATEM *st = &s->statem;
533
534     switch (st->hand_state) {
535     default:
536         /* No pre work to be done */
537         break;
538
539     case TLS_ST_CW_CLNT_HELLO:
540         s->shutdown = 0;
541         if (SSL_IS_DTLS(s)) {
542             /* every DTLS ClientHello resets Finished MAC */
543             if (!ssl3_init_finished_mac(s)) {
544                 ossl_statem_set_error(s);
545                 return WORK_ERROR;
546             }
547         }
548         break;
549
550     case TLS_ST_CW_CHANGE:
551         if (SSL_IS_DTLS(s)) {
552             if (s->hit) {
553                 /*
554                  * We're into the last flight so we don't retransmit these
555                  * messages unless we need to.
556                  */
557                 st->use_timer = 0;
558             }
559 #ifndef OPENSSL_NO_SCTP
560             if (BIO_dgram_is_sctp(SSL_get_wbio(s)))
561                 return dtls_wait_for_dry(s);
562 #endif
563         }
564         break;
565
566     case TLS_ST_OK:
567         return tls_finish_handshake(s, wst);
568     }
569
570     return WORK_FINISHED_CONTINUE;
571 }
572
573 /*
574  * Perform any work that needs to be done after sending a message from the
575  * client to the server.
576  */
577 WORK_STATE ossl_statem_client_post_work(SSL *s, WORK_STATE wst)
578 {
579     OSSL_STATEM *st = &s->statem;
580
581     s->init_num = 0;
582
583     switch (st->hand_state) {
584     default:
585         /* No post work to be done */
586         break;
587
588     case TLS_ST_CW_CLNT_HELLO:
589         if (wst == WORK_MORE_A && statem_flush(s) != 1)
590             return WORK_MORE_A;
591
592         if (SSL_IS_DTLS(s)) {
593             /* Treat the next message as the first packet */
594             s->first_packet = 1;
595         }
596         break;
597
598     case TLS_ST_CW_KEY_EXCH:
599         if (tls_client_key_exchange_post_work(s) == 0)
600             return WORK_ERROR;
601         break;
602
603     case TLS_ST_CW_CHANGE:
604         s->session->cipher = s->s3->tmp.new_cipher;
605 #ifdef OPENSSL_NO_COMP
606         s->session->compress_meth = 0;
607 #else
608         if (s->s3->tmp.new_compression == NULL)
609             s->session->compress_meth = 0;
610         else
611             s->session->compress_meth = s->s3->tmp.new_compression->id;
612 #endif
613         if (!s->method->ssl3_enc->setup_key_block(s))
614             return WORK_ERROR;
615
616         if (!s->method->ssl3_enc->change_cipher_state(s,
617                                                       SSL3_CHANGE_CIPHER_CLIENT_WRITE))
618             return WORK_ERROR;
619
620         if (SSL_IS_DTLS(s)) {
621 #ifndef OPENSSL_NO_SCTP
622             if (s->hit) {
623                 /*
624                  * Change to new shared key of SCTP-Auth, will be ignored if
625                  * no SCTP used.
626                  */
627                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
628                          0, NULL);
629             }
630 #endif
631
632             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
633         }
634         break;
635
636     case TLS_ST_CW_FINISHED:
637 #ifndef OPENSSL_NO_SCTP
638         if (wst == WORK_MORE_A && SSL_IS_DTLS(s) && s->hit == 0) {
639             /*
640              * Change to new shared key of SCTP-Auth, will be ignored if
641              * no SCTP used.
642              */
643             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
644                      0, NULL);
645         }
646 #endif
647         if (statem_flush(s) != 1)
648             return WORK_MORE_B;
649
650         if (SSL_IS_TLS13(s)) {
651             if (!s->method->ssl3_enc->change_cipher_state(s,
652                         SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_WRITE))
653             return WORK_ERROR;
654         }
655         break;
656     }
657
658     return WORK_FINISHED_CONTINUE;
659 }
660
661 /*
662  * Get the message construction function and message type for sending from the
663  * client
664  *
665  * Valid return values are:
666  *   1: Success
667  *   0: Error
668  */
669 int ossl_statem_client_construct_message(SSL *s, WPACKET *pkt,
670                                          confunc_f *confunc, int *mt)
671 {
672     OSSL_STATEM *st = &s->statem;
673
674     switch (st->hand_state) {
675     default:
676         /* Shouldn't happen */
677         return 0;
678
679     case TLS_ST_CW_CHANGE:
680         if (SSL_IS_DTLS(s))
681             *confunc = dtls_construct_change_cipher_spec;
682         else
683             *confunc = tls_construct_change_cipher_spec;
684         *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
685         break;
686
687     case TLS_ST_CW_CLNT_HELLO:
688         *confunc = tls_construct_client_hello;
689         *mt = SSL3_MT_CLIENT_HELLO;
690         break;
691
692     case TLS_ST_CW_CERT:
693         *confunc = tls_construct_client_certificate;
694         *mt = SSL3_MT_CERTIFICATE;
695         break;
696
697     case TLS_ST_CW_KEY_EXCH:
698         *confunc = tls_construct_client_key_exchange;
699         *mt = SSL3_MT_CLIENT_KEY_EXCHANGE;
700         break;
701
702     case TLS_ST_CW_CERT_VRFY:
703         *confunc = tls_construct_client_verify;
704         *mt = SSL3_MT_CERTIFICATE_VERIFY;
705         break;
706
707 #if !defined(OPENSSL_NO_NEXTPROTONEG)
708     case TLS_ST_CW_NEXT_PROTO:
709         *confunc = tls_construct_next_proto;
710         *mt = SSL3_MT_NEXT_PROTO;
711         break;
712 #endif
713     case TLS_ST_CW_FINISHED:
714         *confunc = tls_construct_finished;
715         *mt = SSL3_MT_FINISHED;
716         break;
717     }
718
719     return 1;
720 }
721
722 /*
723  * Returns the maximum allowed length for the current message that we are
724  * reading. Excludes the message header.
725  */
726 size_t ossl_statem_client_max_message_size(SSL *s)
727 {
728     OSSL_STATEM *st = &s->statem;
729
730     switch (st->hand_state) {
731     default:
732         /* Shouldn't happen */
733         return 0;
734
735     case TLS_ST_CR_SRVR_HELLO:
736         return SERVER_HELLO_MAX_LENGTH;
737
738     case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
739         return HELLO_VERIFY_REQUEST_MAX_LENGTH;
740
741     case TLS_ST_CR_CERT:
742         return s->max_cert_list;
743
744     case TLS_ST_CR_CERT_STATUS:
745         return SSL3_RT_MAX_PLAIN_LENGTH;
746
747     case TLS_ST_CR_KEY_EXCH:
748         return SERVER_KEY_EXCH_MAX_LENGTH;
749
750     case TLS_ST_CR_CERT_REQ:
751         /*
752          * Set to s->max_cert_list for compatibility with previous releases. In
753          * practice these messages can get quite long if servers are configured
754          * to provide a long list of acceptable CAs
755          */
756         return s->max_cert_list;
757
758     case TLS_ST_CR_SRVR_DONE:
759         return SERVER_HELLO_DONE_MAX_LENGTH;
760
761     case TLS_ST_CR_CHANGE:
762         if (s->version == DTLS1_BAD_VER)
763             return 3;
764         return CCS_MAX_LENGTH;
765
766     case TLS_ST_CR_SESSION_TICKET:
767         return SSL3_RT_MAX_PLAIN_LENGTH;
768
769     case TLS_ST_CR_FINISHED:
770         return FINISHED_MAX_LENGTH;
771
772     case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
773         return ENCRYPTED_EXTENSIONS_MAX_LENGTH;
774     }
775 }
776
777 /*
778  * Process a message that the client has been received from the server.
779  */
780 MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL *s, PACKET *pkt)
781 {
782     OSSL_STATEM *st = &s->statem;
783
784     switch (st->hand_state) {
785     default:
786         /* Shouldn't happen */
787         return MSG_PROCESS_ERROR;
788
789     case TLS_ST_CR_SRVR_HELLO:
790         return tls_process_server_hello(s, pkt);
791
792     case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
793         return dtls_process_hello_verify(s, pkt);
794
795     case TLS_ST_CR_CERT:
796         return tls_process_server_certificate(s, pkt);
797
798     case TLS_ST_CR_CERT_STATUS:
799         return tls_process_cert_status(s, pkt);
800
801     case TLS_ST_CR_KEY_EXCH:
802         return tls_process_key_exchange(s, pkt);
803
804     case TLS_ST_CR_CERT_REQ:
805         return tls_process_certificate_request(s, pkt);
806
807     case TLS_ST_CR_SRVR_DONE:
808         return tls_process_server_done(s, pkt);
809
810     case TLS_ST_CR_CHANGE:
811         return tls_process_change_cipher_spec(s, pkt);
812
813     case TLS_ST_CR_SESSION_TICKET:
814         return tls_process_new_session_ticket(s, pkt);
815
816     case TLS_ST_CR_FINISHED:
817         return tls_process_finished(s, pkt);
818
819     case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
820         return tls_process_encrypted_extensions(s, pkt);
821     }
822 }
823
824 /*
825  * Perform any further processing required following the receipt of a message
826  * from the server
827  */
828 WORK_STATE ossl_statem_client_post_process_message(SSL *s, WORK_STATE wst)
829 {
830     OSSL_STATEM *st = &s->statem;
831
832     switch (st->hand_state) {
833     default:
834         /* Shouldn't happen */
835         return WORK_ERROR;
836
837     case TLS_ST_CR_CERT_REQ:
838         return tls_prepare_client_certificate(s, wst);
839
840 #ifndef OPENSSL_NO_SCTP
841     case TLS_ST_CR_SRVR_DONE:
842         /* We only get here if we are using SCTP and we are renegotiating */
843         if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
844             s->s3->in_read_app_data = 2;
845             s->rwstate = SSL_READING;
846             BIO_clear_retry_flags(SSL_get_rbio(s));
847             BIO_set_retry_read(SSL_get_rbio(s));
848             ossl_statem_set_sctp_read_sock(s, 1);
849             return WORK_MORE_A;
850         }
851         ossl_statem_set_sctp_read_sock(s, 0);
852         return WORK_FINISHED_STOP;
853 #endif
854     }
855 }
856
857 int tls_construct_client_hello(SSL *s, WPACKET *pkt)
858 {
859     unsigned char *p;
860     size_t sess_id_len;
861     int i, protverr;
862     int al = SSL_AD_HANDSHAKE_FAILURE;
863 #ifndef OPENSSL_NO_COMP
864     SSL_COMP *comp;
865 #endif
866     SSL_SESSION *sess = s->session;
867
868     if (!WPACKET_set_max_size(pkt, SSL3_RT_MAX_PLAIN_LENGTH)) {
869         /* Should not happen */
870         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
871         return 0;
872     }
873
874     /* Work out what SSL/TLS/DTLS version to use */
875     protverr = ssl_set_client_hello_version(s);
876     if (protverr != 0) {
877         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, protverr);
878         return 0;
879     }
880
881     if ((sess == NULL) || !ssl_version_supported(s, sess->ssl_version) ||
882         /*
883          * In the case of EAP-FAST, we can have a pre-shared
884          * "ticket" without a session ID.
885          */
886         (!sess->session_id_length && !sess->tlsext_tick) ||
887         (sess->not_resumable)) {
888         if (!ssl_get_new_session(s, 0))
889             return 0;
890     }
891     /* else use the pre-loaded session */
892
893     p = s->s3->client_random;
894
895     /*
896      * for DTLS if client_random is initialized, reuse it, we are
897      * required to use same upon reply to HelloVerify
898      */
899     if (SSL_IS_DTLS(s)) {
900         size_t idx;
901         i = 1;
902         for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {
903             if (p[idx]) {
904                 i = 0;
905                 break;
906             }
907         }
908     } else
909         i = 1;
910
911     if (i && ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)) <= 0)
912         return 0;
913
914     /*-
915      * version indicates the negotiated version: for example from
916      * an SSLv2/v3 compatible client hello). The client_version
917      * field is the maximum version we permit and it is also
918      * used in RSA encrypted premaster secrets. Some servers can
919      * choke if we initially report a higher version then
920      * renegotiate to a lower one in the premaster secret. This
921      * didn't happen with TLS 1.0 as most servers supported it
922      * but it can with TLS 1.1 or later if the server only supports
923      * 1.0.
924      *
925      * Possible scenario with previous logic:
926      *      1. Client hello indicates TLS 1.2
927      *      2. Server hello says TLS 1.0
928      *      3. RSA encrypted premaster secret uses 1.2.
929      *      4. Handshake proceeds using TLS 1.0.
930      *      5. Server sends hello request to renegotiate.
931      *      6. Client hello indicates TLS v1.0 as we now
932      *         know that is maximum server supports.
933      *      7. Server chokes on RSA encrypted premaster secret
934      *         containing version 1.0.
935      *
936      * For interoperability it should be OK to always use the
937      * maximum version we support in client hello and then rely
938      * on the checking of version to ensure the servers isn't
939      * being inconsistent: for example initially negotiating with
940      * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
941      * client_version in client hello and not resetting it to
942      * the negotiated version.
943      *
944      * For TLS 1.3 we always set the ClientHello version to 1.2 and rely on the
945      * supported_versions extension for the real supported versions.
946      */
947     if (!WPACKET_put_bytes_u16(pkt, s->client_version)
948             || !WPACKET_memcpy(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)) {
949         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
950         return 0;
951     }
952
953     /* Session ID */
954     if (s->new_session)
955         sess_id_len = 0;
956     else
957         sess_id_len = s->session->session_id_length;
958     if (sess_id_len > sizeof(s->session->session_id)
959             || !WPACKET_start_sub_packet_u8(pkt)
960             || (sess_id_len != 0 && !WPACKET_memcpy(pkt, s->session->session_id,
961                                                     sess_id_len))
962             || !WPACKET_close(pkt)) {
963         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
964         return 0;
965     }
966
967     /* cookie stuff for DTLS */
968     if (SSL_IS_DTLS(s)) {
969         if (s->d1->cookie_len > sizeof(s->d1->cookie)
970                 || !WPACKET_sub_memcpy_u8(pkt, s->d1->cookie,
971                                           s->d1->cookie_len)) {
972             SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
973             return 0;
974         }
975     }
976
977     /* Ciphers supported */
978     if (!WPACKET_start_sub_packet_u16(pkt)) {
979         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
980         return 0;
981     }
982     /* ssl_cipher_list_to_bytes() raises SSLerr if appropriate */
983     if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), pkt))
984         return 0;
985     if (!WPACKET_close(pkt)) {
986         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
987         return 0;
988     }
989
990     /* COMPRESSION */
991     if (!WPACKET_start_sub_packet_u8(pkt)) {
992         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
993         return 0;
994     }
995 #ifndef OPENSSL_NO_COMP
996     if (ssl_allow_compression(s) && s->ctx->comp_methods) {
997         int compnum = sk_SSL_COMP_num(s->ctx->comp_methods);
998         for (i = 0; i < compnum; i++) {
999             comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
1000             if (!WPACKET_put_bytes_u8(pkt, comp->id)) {
1001                 SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1002                 return 0;
1003             }
1004         }
1005     }
1006 #endif
1007     /* Add the NULL method */
1008     if (!WPACKET_put_bytes_u8(pkt, 0) || !WPACKET_close(pkt)) {
1009         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1010         return 0;
1011     }
1012
1013     /* TLS extensions */
1014     if (!tls_construct_extensions(s, pkt, EXT_CLIENT_HELLO, &al)) {
1015         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1016         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1017         return 0;
1018     }
1019
1020     return 1;
1021 }
1022
1023 MSG_PROCESS_RETURN dtls_process_hello_verify(SSL *s, PACKET *pkt)
1024 {
1025     int al;
1026     size_t cookie_len;
1027     PACKET cookiepkt;
1028
1029     if (!PACKET_forward(pkt, 2)
1030         || !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {
1031         al = SSL_AD_DECODE_ERROR;
1032         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
1033         goto f_err;
1034     }
1035
1036     cookie_len = PACKET_remaining(&cookiepkt);
1037     if (cookie_len > sizeof(s->d1->cookie)) {
1038         al = SSL_AD_ILLEGAL_PARAMETER;
1039         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_TOO_LONG);
1040         goto f_err;
1041     }
1042
1043     if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {
1044         al = SSL_AD_DECODE_ERROR;
1045         SSLerr(SSL_F_DTLS_PROCESS_HELLO_VERIFY, SSL_R_LENGTH_MISMATCH);
1046         goto f_err;
1047     }
1048     s->d1->cookie_len = cookie_len;
1049
1050     return MSG_PROCESS_FINISHED_READING;
1051  f_err:
1052     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1053     ossl_statem_set_error(s);
1054     return MSG_PROCESS_ERROR;
1055 }
1056
1057 MSG_PROCESS_RETURN tls_process_server_hello(SSL *s, PACKET *pkt)
1058 {
1059     STACK_OF(SSL_CIPHER) *sk;
1060     const SSL_CIPHER *c;
1061     PACKET session_id, extpkt;
1062     size_t session_id_len;
1063     const unsigned char *cipherchars;
1064     int i, al = SSL_AD_INTERNAL_ERROR;
1065     unsigned int compression;
1066     unsigned int sversion;
1067     unsigned int context;
1068     int protverr;
1069     RAW_EXTENSION *extensions = NULL;
1070 #ifndef OPENSSL_NO_COMP
1071     SSL_COMP *comp;
1072 #endif
1073
1074     if (!PACKET_get_net_2(pkt, &sversion)) {
1075         al = SSL_AD_DECODE_ERROR;
1076         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1077         goto f_err;
1078     }
1079
1080     protverr = ssl_choose_client_version(s, sversion);
1081     if (protverr != 0) {
1082         al = SSL_AD_PROTOCOL_VERSION;
1083         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, protverr);
1084         goto f_err;
1085     }
1086
1087     /* load the server hello data */
1088     /* load the server random */
1089     if (!PACKET_copy_bytes(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
1090         al = SSL_AD_DECODE_ERROR;
1091         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1092         goto f_err;
1093     }
1094
1095     s->hit = 0;
1096
1097     /* Get the session-id. */
1098     if (!SSL_IS_TLS13(s)) {
1099         if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
1100             al = SSL_AD_DECODE_ERROR;
1101             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1102             goto f_err;
1103         }
1104         session_id_len = PACKET_remaining(&session_id);
1105         if (session_id_len > sizeof s->session->session_id
1106             || session_id_len > SSL3_SESSION_ID_SIZE) {
1107             al = SSL_AD_ILLEGAL_PARAMETER;
1108             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1109                    SSL_R_SSL3_SESSION_ID_TOO_LONG);
1110             goto f_err;
1111         }
1112     } else {
1113         session_id_len = 0;
1114     }
1115
1116     if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
1117         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1118         al = SSL_AD_DECODE_ERROR;
1119         goto f_err;
1120     }
1121
1122     /*
1123      * Check if we can resume the session based on external pre-shared secret.
1124      * EAP-FAST (RFC 4851) supports two types of session resumption.
1125      * Resumption based on server-side state works with session IDs.
1126      * Resumption based on pre-shared Protected Access Credentials (PACs)
1127      * works by overriding the SessionTicket extension at the application
1128      * layer, and does not send a session ID. (We do not know whether EAP-FAST
1129      * servers would honour the session ID.) Therefore, the session ID alone
1130      * is not a reliable indicator of session resumption, so we first check if
1131      * we can resume, and later peek at the next handshake message to see if the
1132      * server wants to resume.
1133      */
1134     if (s->version >= TLS1_VERSION && !SSL_IS_TLS13(s)
1135             && s->tls_session_secret_cb != NULL && s->session->tlsext_tick) {
1136         const SSL_CIPHER *pref_cipher = NULL;
1137         /*
1138          * s->session->master_key_length is a size_t, but this is an int for
1139          * backwards compat reasons
1140          */
1141         int master_key_length;
1142         master_key_length = sizeof(s->session->master_key);
1143         if (s->tls_session_secret_cb(s, s->session->master_key,
1144                                      &master_key_length,
1145                                      NULL, &pref_cipher,
1146                                      s->tls_session_secret_cb_arg)
1147                  && master_key_length > 0) {
1148             s->session->master_key_length = master_key_length;
1149             s->session->cipher = pref_cipher ?
1150                 pref_cipher : ssl_get_cipher_by_char(s, cipherchars);
1151         } else {
1152             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1153             al = SSL_AD_INTERNAL_ERROR;
1154             goto f_err;
1155         }
1156     }
1157
1158     if (session_id_len != 0 && session_id_len == s->session->session_id_length
1159         && memcmp(PACKET_data(&session_id), s->session->session_id,
1160                   session_id_len) == 0) {
1161         if (s->sid_ctx_length != s->session->sid_ctx_length
1162             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
1163             /* actually a client application bug */
1164             al = SSL_AD_ILLEGAL_PARAMETER;
1165             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1166                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1167             goto f_err;
1168         }
1169         s->hit = 1;
1170     } else {
1171         /*
1172          * If we were trying for session-id reuse but the server
1173          * didn't echo the ID, make a new SSL_SESSION.
1174          * In the case of EAP-FAST and PAC, we do not send a session ID,
1175          * so the PAC-based session secret is always preserved. It'll be
1176          * overwritten if the server refuses resumption.
1177          */
1178         if (s->session->session_id_length > 0) {
1179             s->ctx->stats.sess_miss++;
1180             if (!ssl_get_new_session(s, 0)) {
1181                 goto f_err;
1182             }
1183         }
1184
1185         s->session->ssl_version = s->version;
1186         s->session->session_id_length = session_id_len;
1187         /* session_id_len could be 0 */
1188         memcpy(s->session->session_id, PACKET_data(&session_id),
1189                session_id_len);
1190     }
1191
1192     /* Session version and negotiated protocol version should match */
1193     if (s->version != s->session->ssl_version) {
1194         al = SSL_AD_PROTOCOL_VERSION;
1195
1196         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1197                SSL_R_SSL_SESSION_VERSION_MISMATCH);
1198         goto f_err;
1199     }
1200
1201     c = ssl_get_cipher_by_char(s, cipherchars);
1202     if (c == NULL) {
1203         /* unknown cipher */
1204         al = SSL_AD_ILLEGAL_PARAMETER;
1205         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
1206         goto f_err;
1207     }
1208     /*
1209      * Now that we know the version, update the check to see if it's an allowed
1210      * version.
1211      */
1212     s->s3->tmp.min_ver = s->version;
1213     s->s3->tmp.max_ver = s->version;
1214     /*
1215      * If it is a disabled cipher we either didn't send it in client hello,
1216      * or it's not allowed for the selected protocol. So we return an error.
1217      */
1218     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
1219         al = SSL_AD_ILLEGAL_PARAMETER;
1220         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1221         goto f_err;
1222     }
1223
1224     sk = ssl_get_ciphers_by_id(s);
1225     i = sk_SSL_CIPHER_find(sk, c);
1226     if (i < 0) {
1227         /* we did not say we would use this cipher */
1228         al = SSL_AD_ILLEGAL_PARAMETER;
1229         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1230         goto f_err;
1231     }
1232
1233     /*
1234      * Depending on the session caching (internal/external), the cipher
1235      * and/or cipher_id values may not be set. Make sure that cipher_id is
1236      * set and use it for comparison.
1237      */
1238     if (s->session->cipher)
1239         s->session->cipher_id = s->session->cipher->id;
1240     if (s->hit && (s->session->cipher_id != c->id)) {
1241         al = SSL_AD_ILLEGAL_PARAMETER;
1242         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1243                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1244         goto f_err;
1245     }
1246     s->s3->tmp.new_cipher = c;
1247     /* lets get the compression algorithm */
1248     /* COMPRESSION */
1249     if (!SSL_IS_TLS13(s)) {
1250         if (!PACKET_get_1(pkt, &compression)) {
1251             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1252             al = SSL_AD_DECODE_ERROR;
1253             goto f_err;
1254         }
1255     } else {
1256         compression = 0;
1257     }
1258
1259 #ifdef OPENSSL_NO_COMP
1260     if (compression != 0) {
1261         al = SSL_AD_ILLEGAL_PARAMETER;
1262         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1263                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1264         goto f_err;
1265     }
1266     /*
1267      * If compression is disabled we'd better not try to resume a session
1268      * using compression.
1269      */
1270     if (s->session->compress_meth != 0) {
1271         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1272         goto f_err;
1273     }
1274 #else
1275     if (s->hit && compression != s->session->compress_meth) {
1276         al = SSL_AD_ILLEGAL_PARAMETER;
1277         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1278                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1279         goto f_err;
1280     }
1281     if (compression == 0)
1282         comp = NULL;
1283     else if (!ssl_allow_compression(s)) {
1284         al = SSL_AD_ILLEGAL_PARAMETER;
1285         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1286         goto f_err;
1287     } else {
1288         comp = ssl3_comp_find(s->ctx->comp_methods, compression);
1289     }
1290
1291     if (compression != 0 && comp == NULL) {
1292         al = SSL_AD_ILLEGAL_PARAMETER;
1293         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1294                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1295         goto f_err;
1296     } else {
1297         s->s3->tmp.new_compression = comp;
1298     }
1299 #endif
1300
1301     /* TLS extensions */
1302     if (PACKET_remaining(pkt) == 0) {
1303         PACKET_null_init(&extpkt);
1304     } else if (!PACKET_as_length_prefixed_2(pkt, &extpkt)) {
1305         al = SSL_AD_DECODE_ERROR;
1306         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_BAD_LENGTH);
1307         goto f_err;
1308     }
1309
1310     context = SSL_IS_TLS13(s) ? EXT_TLS1_3_SERVER_HELLO
1311                               : EXT_TLS1_2_SERVER_HELLO;
1312     if (!tls_collect_extensions(s, &extpkt, context, &extensions, &al)
1313             || !tls_parse_all_extensions(s, context, extensions, &al))
1314         goto f_err;
1315
1316 #ifndef OPENSSL_NO_SCTP
1317     if (SSL_IS_DTLS(s) && s->hit) {
1318         unsigned char sctpauthkey[64];
1319         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1320
1321         /*
1322          * Add new shared key for SCTP-Auth, will be ignored if
1323          * no SCTP used.
1324          */
1325         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1326                sizeof(DTLS1_SCTP_AUTH_LABEL));
1327
1328         if (SSL_export_keying_material(s, sctpauthkey,
1329                                        sizeof(sctpauthkey),
1330                                        labelbuffer,
1331                                        sizeof(labelbuffer), NULL, 0, 0) <= 0)
1332             goto err;
1333
1334         BIO_ctrl(SSL_get_wbio(s),
1335                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1336                  sizeof(sctpauthkey), sctpauthkey);
1337     }
1338 #endif
1339
1340     /*
1341      * In TLSv1.3 we have some post-processing to change cipher state, otherwise
1342      * we're done with this message
1343      */
1344     if (SSL_IS_TLS13(s)
1345             && (!s->method->ssl3_enc->setup_key_block(s)
1346                 || !s->method->ssl3_enc->change_cipher_state(s,
1347                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE)
1348                 || !s->method->ssl3_enc->change_cipher_state(s,
1349                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_READ))) {
1350         al = SSL_AD_INTERNAL_ERROR;
1351         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_CANNOT_CHANGE_CIPHER);
1352         goto f_err;
1353     }
1354
1355     OPENSSL_free(extensions);
1356     return MSG_PROCESS_CONTINUE_READING;
1357  f_err:
1358     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1359     ossl_statem_set_error(s);
1360     OPENSSL_free(extensions);
1361     return MSG_PROCESS_ERROR;
1362 }
1363
1364 MSG_PROCESS_RETURN tls_process_server_certificate(SSL *s, PACKET *pkt)
1365 {
1366     int al, i, ret = MSG_PROCESS_ERROR, exp_idx;
1367     unsigned long cert_list_len, cert_len;
1368     X509 *x = NULL;
1369     const unsigned char *certstart, *certbytes;
1370     STACK_OF(X509) *sk = NULL;
1371     EVP_PKEY *pkey = NULL;
1372
1373     if ((sk = sk_X509_new_null()) == NULL) {
1374         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1375         goto err;
1376     }
1377
1378     if (!PACKET_get_net_3(pkt, &cert_list_len)
1379         || PACKET_remaining(pkt) != cert_list_len) {
1380         al = SSL_AD_DECODE_ERROR;
1381         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1382         goto f_err;
1383     }
1384     while (PACKET_remaining(pkt)) {
1385         if (!PACKET_get_net_3(pkt, &cert_len)
1386             || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
1387             al = SSL_AD_DECODE_ERROR;
1388             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1389                    SSL_R_CERT_LENGTH_MISMATCH);
1390             goto f_err;
1391         }
1392
1393         certstart = certbytes;
1394         x = d2i_X509(NULL, (const unsigned char **)&certbytes, cert_len);
1395         if (x == NULL) {
1396             al = SSL_AD_BAD_CERTIFICATE;
1397             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1398             goto f_err;
1399         }
1400         if (certbytes != (certstart + cert_len)) {
1401             al = SSL_AD_DECODE_ERROR;
1402             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1403                    SSL_R_CERT_LENGTH_MISMATCH);
1404             goto f_err;
1405         }
1406         if (!sk_X509_push(sk, x)) {
1407             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1408             goto err;
1409         }
1410         x = NULL;
1411     }
1412
1413     i = ssl_verify_cert_chain(s, sk);
1414     /*
1415      * The documented interface is that SSL_VERIFY_PEER should be set in order
1416      * for client side verification of the server certificate to take place.
1417      * However, historically the code has only checked that *any* flag is set
1418      * to cause server verification to take place. Use of the other flags makes
1419      * no sense in client mode. An attempt to clean up the semantics was
1420      * reverted because at least one application *only* set
1421      * SSL_VERIFY_FAIL_IF_NO_PEER_CERT. Prior to the clean up this still caused
1422      * server verification to take place, after the clean up it silently did
1423      * nothing. SSL_CTX_set_verify()/SSL_set_verify() cannot validate the flags
1424      * sent to them because they are void functions. Therefore, we now use the
1425      * (less clean) historic behaviour of performing validation if any flag is
1426      * set. The *documented* interface remains the same.
1427      */
1428     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
1429         al = ssl_verify_alarm_type(s->verify_result);
1430         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1431                SSL_R_CERTIFICATE_VERIFY_FAILED);
1432         goto f_err;
1433     }
1434     ERR_clear_error();          /* but we keep s->verify_result */
1435     if (i > 1) {
1436         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, i);
1437         al = SSL_AD_HANDSHAKE_FAILURE;
1438         goto f_err;
1439     }
1440
1441     s->session->peer_chain = sk;
1442     /*
1443      * Inconsistency alert: cert_chain does include the peer's certificate,
1444      * which we don't include in statem_srvr.c
1445      */
1446     x = sk_X509_value(sk, 0);
1447     sk = NULL;
1448     /*
1449      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1450      */
1451
1452     pkey = X509_get0_pubkey(x);
1453
1454     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1455         x = NULL;
1456         al = SSL3_AL_FATAL;
1457         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1458                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1459         goto f_err;
1460     }
1461
1462     i = ssl_cert_type(x, pkey);
1463     if (i < 0) {
1464         x = NULL;
1465         al = SSL3_AL_FATAL;
1466         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1467                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1468         goto f_err;
1469     }
1470
1471     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1472     if (exp_idx >= 0 && i != exp_idx
1473         && (exp_idx != SSL_PKEY_GOST_EC ||
1474             (i != SSL_PKEY_GOST12_512 && i != SSL_PKEY_GOST12_256
1475              && i != SSL_PKEY_GOST01))) {
1476         x = NULL;
1477         al = SSL_AD_ILLEGAL_PARAMETER;
1478         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1479                SSL_R_WRONG_CERTIFICATE_TYPE);
1480         goto f_err;
1481     }
1482     s->session->peer_type = i;
1483
1484     X509_free(s->session->peer);
1485     X509_up_ref(x);
1486     s->session->peer = x;
1487     s->session->verify_result = s->verify_result;
1488
1489     x = NULL;
1490     ret = MSG_PROCESS_CONTINUE_READING;
1491     goto done;
1492
1493  f_err:
1494     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1495  err:
1496     ossl_statem_set_error(s);
1497  done:
1498     X509_free(x);
1499     sk_X509_pop_free(sk, X509_free);
1500     return ret;
1501 }
1502
1503 static int tls_process_ske_psk_preamble(SSL *s, PACKET *pkt, int *al)
1504 {
1505 #ifndef OPENSSL_NO_PSK
1506     PACKET psk_identity_hint;
1507
1508     /* PSK ciphersuites are preceded by an identity hint */
1509
1510     if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
1511         *al = SSL_AD_DECODE_ERROR;
1512         SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH);
1513         return 0;
1514     }
1515
1516     /*
1517      * Store PSK identity hint for later use, hint is used in
1518      * tls_construct_client_key_exchange.  Assume that the maximum length of
1519      * a PSK identity hint can be as long as the maximum length of a PSK
1520      * identity.
1521      */
1522     if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
1523         *al = SSL_AD_HANDSHAKE_FAILURE;
1524         SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG);
1525         return 0;
1526     }
1527
1528     if (PACKET_remaining(&psk_identity_hint) == 0) {
1529         OPENSSL_free(s->session->psk_identity_hint);
1530         s->session->psk_identity_hint = NULL;
1531     } else if (!PACKET_strndup(&psk_identity_hint,
1532                                &s->session->psk_identity_hint)) {
1533         *al = SSL_AD_INTERNAL_ERROR;
1534         return 0;
1535     }
1536
1537     return 1;
1538 #else
1539     SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
1540     *al = SSL_AD_INTERNAL_ERROR;
1541     return 0;
1542 #endif
1543 }
1544
1545 static int tls_process_ske_srp(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1546 {
1547 #ifndef OPENSSL_NO_SRP
1548     PACKET prime, generator, salt, server_pub;
1549
1550     if (!PACKET_get_length_prefixed_2(pkt, &prime)
1551         || !PACKET_get_length_prefixed_2(pkt, &generator)
1552         || !PACKET_get_length_prefixed_1(pkt, &salt)
1553         || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
1554         *al = SSL_AD_DECODE_ERROR;
1555         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, SSL_R_LENGTH_MISMATCH);
1556         return 0;
1557     }
1558
1559     /* TODO(size_t): Convert BN_bin2bn() calls */
1560     if ((s->srp_ctx.N =
1561          BN_bin2bn(PACKET_data(&prime),
1562                    (int)PACKET_remaining(&prime), NULL)) == NULL
1563         || (s->srp_ctx.g =
1564             BN_bin2bn(PACKET_data(&generator),
1565                       (int)PACKET_remaining(&generator), NULL)) == NULL
1566         || (s->srp_ctx.s =
1567             BN_bin2bn(PACKET_data(&salt),
1568                       (int)PACKET_remaining(&salt), NULL)) == NULL
1569         || (s->srp_ctx.B =
1570             BN_bin2bn(PACKET_data(&server_pub),
1571                       (int)PACKET_remaining(&server_pub), NULL)) == NULL) {
1572         *al = SSL_AD_INTERNAL_ERROR;
1573         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, ERR_R_BN_LIB);
1574         return 0;
1575     }
1576
1577     if (!srp_verify_server_param(s, al)) {
1578         *al = SSL_AD_DECODE_ERROR;
1579         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, SSL_R_BAD_SRP_PARAMETERS);
1580         return 0;
1581     }
1582
1583     /* We must check if there is a certificate */
1584     if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
1585         *pkey = X509_get0_pubkey(s->session->peer);
1586
1587     return 1;
1588 #else
1589     SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, ERR_R_INTERNAL_ERROR);
1590     *al = SSL_AD_INTERNAL_ERROR;
1591     return 0;
1592 #endif
1593 }
1594
1595 static int tls_process_ske_dhe(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1596 {
1597 #ifndef OPENSSL_NO_DH
1598     PACKET prime, generator, pub_key;
1599     EVP_PKEY *peer_tmp = NULL;
1600
1601     DH *dh = NULL;
1602     BIGNUM *p = NULL, *g = NULL, *bnpub_key = NULL;
1603
1604     if (!PACKET_get_length_prefixed_2(pkt, &prime)
1605         || !PACKET_get_length_prefixed_2(pkt, &generator)
1606         || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
1607         *al = SSL_AD_DECODE_ERROR;
1608         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_LENGTH_MISMATCH);
1609         return 0;
1610     }
1611
1612     peer_tmp = EVP_PKEY_new();
1613     dh = DH_new();
1614
1615     if (peer_tmp == NULL || dh == NULL) {
1616         *al = SSL_AD_INTERNAL_ERROR;
1617         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_MALLOC_FAILURE);
1618         goto err;
1619     }
1620
1621     /* TODO(size_t): Convert these calls */
1622     p = BN_bin2bn(PACKET_data(&prime), (int)PACKET_remaining(&prime), NULL);
1623     g = BN_bin2bn(PACKET_data(&generator), (int)PACKET_remaining(&generator),
1624                   NULL);
1625     bnpub_key = BN_bin2bn(PACKET_data(&pub_key),
1626                           (int)PACKET_remaining(&pub_key), NULL);
1627     if (p == NULL || g == NULL || bnpub_key == NULL) {
1628         *al = SSL_AD_INTERNAL_ERROR;
1629         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1630         goto err;
1631     }
1632
1633     if (BN_is_zero(p) || BN_is_zero(g) || BN_is_zero(bnpub_key)) {
1634         *al = SSL_AD_DECODE_ERROR;
1635         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_BAD_DH_VALUE);
1636         goto err;
1637     }
1638
1639     if (!DH_set0_pqg(dh, p, NULL, g)) {
1640         *al = SSL_AD_INTERNAL_ERROR;
1641         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1642         goto err;
1643     }
1644     p = g = NULL;
1645
1646     if (!DH_set0_key(dh, bnpub_key, NULL)) {
1647         *al = SSL_AD_INTERNAL_ERROR;
1648         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1649         goto err;
1650     }
1651     bnpub_key = NULL;
1652
1653     if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1654         *al = SSL_AD_HANDSHAKE_FAILURE;
1655         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_DH_KEY_TOO_SMALL);
1656         goto err;
1657     }
1658
1659     if (EVP_PKEY_assign_DH(peer_tmp, dh) == 0) {
1660         *al = SSL_AD_INTERNAL_ERROR;
1661         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_EVP_LIB);
1662         goto err;
1663     }
1664
1665     s->s3->peer_tmp = peer_tmp;
1666
1667     /*
1668      * FIXME: This makes assumptions about which ciphersuites come with
1669      * public keys. We should have a less ad-hoc way of doing this
1670      */
1671     if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
1672         *pkey = X509_get0_pubkey(s->session->peer);
1673     /* else anonymous DH, so no certificate or pkey. */
1674
1675     return 1;
1676
1677  err:
1678     BN_free(p);
1679     BN_free(g);
1680     BN_free(bnpub_key);
1681     DH_free(dh);
1682     EVP_PKEY_free(peer_tmp);
1683
1684     return 0;
1685 #else
1686     SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_INTERNAL_ERROR);
1687     *al = SSL_AD_INTERNAL_ERROR;
1688     return 0;
1689 #endif
1690 }
1691
1692 static int tls_process_ske_ecdhe(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1693 {
1694 #ifndef OPENSSL_NO_EC
1695     PACKET encoded_pt;
1696     const unsigned char *ecparams;
1697     int curve_nid;
1698     unsigned int curve_flags;
1699     EVP_PKEY_CTX *pctx = NULL;
1700
1701     /*
1702      * Extract elliptic curve parameters and the server's ephemeral ECDH
1703      * public key. For now we only support named (not generic) curves and
1704      * ECParameters in this case is just three bytes.
1705      */
1706     if (!PACKET_get_bytes(pkt, &ecparams, 3)) {
1707         *al = SSL_AD_DECODE_ERROR;
1708         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_LENGTH_TOO_SHORT);
1709         return 0;
1710     }
1711     /*
1712      * Check curve is one of our preferences, if not server has sent an
1713      * invalid curve. ECParameters is 3 bytes.
1714      */
1715     if (!tls1_check_curve(s, ecparams, 3)) {
1716         *al = SSL_AD_DECODE_ERROR;
1717         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_WRONG_CURVE);
1718         return 0;
1719     }
1720
1721     curve_nid = tls1_ec_curve_id2nid(*(ecparams + 2), &curve_flags);
1722
1723     if (curve_nid == 0) {
1724         *al = SSL_AD_INTERNAL_ERROR;
1725         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE,
1726                SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1727         return 0;
1728     }
1729
1730     if ((curve_flags & TLS_CURVE_TYPE) == TLS_CURVE_CUSTOM) {
1731         EVP_PKEY *key = EVP_PKEY_new();
1732
1733         if (key == NULL || !EVP_PKEY_set_type(key, curve_nid)) {
1734             *al = SSL_AD_INTERNAL_ERROR;
1735             SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_EVP_LIB);
1736             EVP_PKEY_free(key);
1737             return 0;
1738         }
1739         s->s3->peer_tmp = key;
1740     } else {
1741         /* Set up EVP_PKEY with named curve as parameters */
1742         pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
1743         if (pctx == NULL
1744             || EVP_PKEY_paramgen_init(pctx) <= 0
1745             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, curve_nid) <= 0
1746             || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
1747             *al = SSL_AD_INTERNAL_ERROR;
1748             SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_EVP_LIB);
1749             EVP_PKEY_CTX_free(pctx);
1750             return 0;
1751         }
1752         EVP_PKEY_CTX_free(pctx);
1753         pctx = NULL;
1754     }
1755
1756     if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
1757         *al = SSL_AD_DECODE_ERROR;
1758         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_LENGTH_MISMATCH);
1759         return 0;
1760     }
1761
1762     if (!EVP_PKEY_set1_tls_encodedpoint(s->s3->peer_tmp,
1763                                         PACKET_data(&encoded_pt),
1764                                         PACKET_remaining(&encoded_pt))) {
1765         *al = SSL_AD_DECODE_ERROR;
1766         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_BAD_ECPOINT);
1767         return 0;
1768     }
1769
1770     /*
1771      * The ECC/TLS specification does not mention the use of DSA to sign
1772      * ECParameters in the server key exchange message. We do support RSA
1773      * and ECDSA.
1774      */
1775     if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aECDSA)
1776         *pkey = X509_get0_pubkey(s->session->peer);
1777     else if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aRSA)
1778         *pkey = X509_get0_pubkey(s->session->peer);
1779     /* else anonymous ECDH, so no certificate or pkey. */
1780
1781     return 1;
1782 #else
1783     SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_INTERNAL_ERROR);
1784     *al = SSL_AD_INTERNAL_ERROR;
1785     return 0;
1786 #endif
1787 }
1788
1789 MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
1790 {
1791     int al = -1;
1792     long alg_k;
1793     EVP_PKEY *pkey = NULL;
1794     PACKET save_param_start, signature;
1795
1796     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1797
1798     save_param_start = *pkt;
1799
1800 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1801     EVP_PKEY_free(s->s3->peer_tmp);
1802     s->s3->peer_tmp = NULL;
1803 #endif
1804
1805     if (alg_k & SSL_PSK) {
1806         if (!tls_process_ske_psk_preamble(s, pkt, &al))
1807             goto err;
1808     }
1809
1810     /* Nothing else to do for plain PSK or RSAPSK */
1811     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1812     } else if (alg_k & SSL_kSRP) {
1813         if (!tls_process_ske_srp(s, pkt, &pkey, &al))
1814             goto err;
1815     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1816         if (!tls_process_ske_dhe(s, pkt, &pkey, &al))
1817             goto err;
1818     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1819         if (!tls_process_ske_ecdhe(s, pkt, &pkey, &al))
1820             goto err;
1821     } else if (alg_k) {
1822         al = SSL_AD_UNEXPECTED_MESSAGE;
1823         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1824         goto err;
1825     }
1826
1827     /* if it was signed, check the signature */
1828     if (pkey != NULL) {
1829         PACKET params;
1830         int maxsig;
1831         const EVP_MD *md = NULL;
1832         EVP_MD_CTX *md_ctx;
1833
1834         /*
1835          * |pkt| now points to the beginning of the signature, so the difference
1836          * equals the length of the parameters.
1837          */
1838         if (!PACKET_get_sub_packet(&save_param_start, &params,
1839                                    PACKET_remaining(&save_param_start) -
1840                                    PACKET_remaining(pkt))) {
1841             al = SSL_AD_INTERNAL_ERROR;
1842             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1843             goto err;
1844         }
1845
1846         if (SSL_USE_SIGALGS(s)) {
1847             const unsigned char *sigalgs;
1848             int rv;
1849             if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
1850                 al = SSL_AD_DECODE_ERROR;
1851                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1852                 goto err;
1853             }
1854             rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
1855             if (rv == -1) {
1856                 al = SSL_AD_INTERNAL_ERROR;
1857                 goto err;
1858             } else if (rv == 0) {
1859                 al = SSL_AD_DECODE_ERROR;
1860                 goto err;
1861             }
1862 #ifdef SSL_DEBUG
1863             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1864 #endif
1865         } else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
1866             md = EVP_md5_sha1();
1867         } else {
1868             md = EVP_sha1();
1869         }
1870
1871         if (!PACKET_get_length_prefixed_2(pkt, &signature)
1872             || PACKET_remaining(pkt) != 0) {
1873             al = SSL_AD_DECODE_ERROR;
1874             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1875             goto err;
1876         }
1877         maxsig = EVP_PKEY_size(pkey);
1878         if (maxsig < 0) {
1879             al = SSL_AD_INTERNAL_ERROR;
1880             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1881             goto err;
1882         }
1883
1884         /*
1885          * Check signature length
1886          */
1887         if (PACKET_remaining(&signature) > (size_t)maxsig) {
1888             /* wrong packet length */
1889             al = SSL_AD_DECODE_ERROR;
1890             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1891                    SSL_R_WRONG_SIGNATURE_LENGTH);
1892             goto err;
1893         }
1894
1895         md_ctx = EVP_MD_CTX_new();
1896         if (md_ctx == NULL) {
1897             al = SSL_AD_INTERNAL_ERROR;
1898             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1899             goto err;
1900         }
1901
1902         if (EVP_VerifyInit_ex(md_ctx, md, NULL) <= 0
1903             || EVP_VerifyUpdate(md_ctx, &(s->s3->client_random[0]),
1904                                 SSL3_RANDOM_SIZE) <= 0
1905             || EVP_VerifyUpdate(md_ctx, &(s->s3->server_random[0]),
1906                                 SSL3_RANDOM_SIZE) <= 0
1907             || EVP_VerifyUpdate(md_ctx, PACKET_data(&params),
1908                                 PACKET_remaining(&params)) <= 0) {
1909             EVP_MD_CTX_free(md_ctx);
1910             al = SSL_AD_INTERNAL_ERROR;
1911             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1912             goto err;
1913         }
1914         /* TODO(size_t): Convert this call */
1915         if (EVP_VerifyFinal(md_ctx, PACKET_data(&signature),
1916                             (unsigned int)PACKET_remaining(&signature),
1917                             pkey) <= 0) {
1918             /* bad signature */
1919             EVP_MD_CTX_free(md_ctx);
1920             al = SSL_AD_DECRYPT_ERROR;
1921             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1922             goto err;
1923         }
1924         EVP_MD_CTX_free(md_ctx);
1925     } else {
1926         /* aNULL, aSRP or PSK do not need public keys */
1927         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1928             && !(alg_k & SSL_PSK)) {
1929             /* Might be wrong key type, check it */
1930             if (ssl3_check_cert_and_algorithm(s)) {
1931                 /* Otherwise this shouldn't happen */
1932                 al = SSL_AD_INTERNAL_ERROR;
1933                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1934             } else {
1935                 al = SSL_AD_DECODE_ERROR;
1936             }
1937             goto err;
1938         }
1939         /* still data left over */
1940         if (PACKET_remaining(pkt) != 0) {
1941             al = SSL_AD_DECODE_ERROR;
1942             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1943             goto err;
1944         }
1945     }
1946
1947     return MSG_PROCESS_CONTINUE_READING;
1948  err:
1949     if (al != -1)
1950         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1951     ossl_statem_set_error(s);
1952     return MSG_PROCESS_ERROR;
1953 }
1954
1955 MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
1956 {
1957     int ret = MSG_PROCESS_ERROR;
1958     unsigned int list_len, ctype_num, i, name_len;
1959     X509_NAME *xn = NULL;
1960     const unsigned char *data;
1961     const unsigned char *namestart, *namebytes;
1962     STACK_OF(X509_NAME) *ca_sk = NULL;
1963
1964     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1965         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1966         goto err;
1967     }
1968
1969     /* get the certificate types */
1970     if (!PACKET_get_1(pkt, &ctype_num)
1971         || !PACKET_get_bytes(pkt, &data, ctype_num)) {
1972         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1973         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1974         goto err;
1975     }
1976     OPENSSL_free(s->cert->ctypes);
1977     s->cert->ctypes = NULL;
1978     if (ctype_num > SSL3_CT_NUMBER) {
1979         /* If we exceed static buffer copy all to cert structure */
1980         s->cert->ctypes = OPENSSL_malloc(ctype_num);
1981         if (s->cert->ctypes == NULL) {
1982             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1983             goto err;
1984         }
1985         memcpy(s->cert->ctypes, data, ctype_num);
1986         s->cert->ctype_num = ctype_num;
1987         ctype_num = SSL3_CT_NUMBER;
1988     }
1989     for (i = 0; i < ctype_num; i++)
1990         s->s3->tmp.ctype[i] = data[i];
1991
1992     if (SSL_USE_SIGALGS(s)) {
1993         if (!PACKET_get_net_2(pkt, &list_len)
1994             || !PACKET_get_bytes(pkt, &data, list_len)) {
1995             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1996             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1997                    SSL_R_LENGTH_MISMATCH);
1998             goto err;
1999         }
2000
2001         /* Clear certificate digests and validity flags */
2002         for (i = 0; i < SSL_PKEY_NUM; i++) {
2003             s->s3->tmp.md[i] = NULL;
2004             s->s3->tmp.valid_flags[i] = 0;
2005         }
2006         if ((list_len & 1) || !tls1_save_sigalgs(s, data, list_len)) {
2007             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2008             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2009                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2010             goto err;
2011         }
2012         if (!tls1_process_sigalgs(s)) {
2013             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2014             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2015             goto err;
2016         }
2017     } else {
2018         ssl_set_default_md(s);
2019     }
2020
2021     /* get the CA RDNs */
2022     if (!PACKET_get_net_2(pkt, &list_len)
2023         || PACKET_remaining(pkt) != list_len) {
2024         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2025         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
2026         goto err;
2027     }
2028
2029     while (PACKET_remaining(pkt)) {
2030         if (!PACKET_get_net_2(pkt, &name_len)
2031             || !PACKET_get_bytes(pkt, &namebytes, name_len)) {
2032             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2033             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2034                    SSL_R_LENGTH_MISMATCH);
2035             goto err;
2036         }
2037
2038         namestart = namebytes;
2039
2040         if ((xn = d2i_X509_NAME(NULL, (const unsigned char **)&namebytes,
2041                                 name_len)) == NULL) {
2042             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2043             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
2044             goto err;
2045         }
2046
2047         if (namebytes != (namestart + name_len)) {
2048             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2049             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2050                    SSL_R_CA_DN_LENGTH_MISMATCH);
2051             goto err;
2052         }
2053         if (!sk_X509_NAME_push(ca_sk, xn)) {
2054             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2055             goto err;
2056         }
2057         xn = NULL;
2058     }
2059
2060     /* we should setup a certificate to return.... */
2061     s->s3->tmp.cert_req = 1;
2062     s->s3->tmp.ctype_num = ctype_num;
2063     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
2064     s->s3->tmp.ca_names = ca_sk;
2065     ca_sk = NULL;
2066
2067     ret = MSG_PROCESS_CONTINUE_PROCESSING;
2068     goto done;
2069  err:
2070     ossl_statem_set_error(s);
2071  done:
2072     X509_NAME_free(xn);
2073     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2074     return ret;
2075 }
2076
2077 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2078 {
2079     return (X509_NAME_cmp(*a, *b));
2080 }
2081
2082 MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
2083 {
2084     int al;
2085     unsigned int ticklen;
2086     unsigned long ticket_lifetime_hint;
2087     unsigned int sess_len;
2088
2089     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
2090         || !PACKET_get_net_2(pkt, &ticklen)
2091         || PACKET_remaining(pkt) != ticklen) {
2092         al = SSL_AD_DECODE_ERROR;
2093         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2094         goto f_err;
2095     }
2096
2097     /* Server is allowed to change its mind and send an empty ticket. */
2098     if (ticklen == 0)
2099         return MSG_PROCESS_CONTINUE_READING;
2100
2101     if (s->session->session_id_length > 0) {
2102         int i = s->session_ctx->session_cache_mode;
2103         SSL_SESSION *new_sess;
2104         /*
2105          * We reused an existing session, so we need to replace it with a new
2106          * one
2107          */
2108         if (i & SSL_SESS_CACHE_CLIENT) {
2109             /*
2110              * Remove the old session from the cache. We carry on if this fails
2111              */
2112             SSL_CTX_remove_session(s->session_ctx, s->session);
2113         }
2114
2115         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2116             al = SSL_AD_INTERNAL_ERROR;
2117             SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2118             goto f_err;
2119         }
2120
2121         SSL_SESSION_free(s->session);
2122         s->session = new_sess;
2123     }
2124
2125     OPENSSL_free(s->session->tlsext_tick);
2126     s->session->tlsext_ticklen = 0;
2127
2128     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2129     if (s->session->tlsext_tick == NULL) {
2130         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2131         goto err;
2132     }
2133     if (!PACKET_copy_bytes(pkt, s->session->tlsext_tick, ticklen)) {
2134         al = SSL_AD_DECODE_ERROR;
2135         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2136         goto f_err;
2137     }
2138
2139     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
2140     s->session->tlsext_ticklen = ticklen;
2141     /*
2142      * There are two ways to detect a resumed ticket session. One is to set
2143      * an appropriate session ID and then the server must return a match in
2144      * ServerHello. This allows the normal client session ID matching to work
2145      * and we know much earlier that the ticket has been accepted. The
2146      * other way is to set zero length session ID when the ticket is
2147      * presented and rely on the handshake to determine session resumption.
2148      * We choose the former approach because this fits in with assumptions
2149      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
2150      * SHA256 is disabled) hash of the ticket.
2151      */
2152     /*
2153      * TODO(size_t): we use sess_len here because EVP_Digest expects an int
2154      * but s->session->session_id_length is a size_t
2155      */
2156     if (!EVP_Digest(s->session->tlsext_tick, ticklen,
2157                     s->session->session_id, &sess_len,
2158                     EVP_sha256(), NULL)) {
2159         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_EVP_LIB);
2160         goto err;
2161     }
2162     s->session->session_id_length = sess_len;
2163     return MSG_PROCESS_CONTINUE_READING;
2164  f_err:
2165     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2166  err:
2167     ossl_statem_set_error(s);
2168     return MSG_PROCESS_ERROR;
2169 }
2170
2171 MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
2172 {
2173     int al;
2174     size_t resplen;
2175     unsigned int type;
2176
2177     if (!PACKET_get_1(pkt, &type)
2178         || type != TLSEXT_STATUSTYPE_ocsp) {
2179         al = SSL_AD_DECODE_ERROR;
2180         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
2181         goto f_err;
2182     }
2183     if (!PACKET_get_net_3_len(pkt, &resplen)
2184         || PACKET_remaining(pkt) != resplen) {
2185         al = SSL_AD_DECODE_ERROR;
2186         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2187         goto f_err;
2188     }
2189     s->tlsext_ocsp_resp = OPENSSL_malloc(resplen);
2190     if (s->tlsext_ocsp_resp == NULL) {
2191         al = SSL_AD_INTERNAL_ERROR;
2192         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2193         goto f_err;
2194     }
2195     if (!PACKET_copy_bytes(pkt, s->tlsext_ocsp_resp, resplen)) {
2196         al = SSL_AD_DECODE_ERROR;
2197         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2198         goto f_err;
2199     }
2200     s->tlsext_ocsp_resplen = resplen;
2201     return MSG_PROCESS_CONTINUE_READING;
2202  f_err:
2203     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2204     ossl_statem_set_error(s);
2205     return MSG_PROCESS_ERROR;
2206 }
2207
2208 /*
2209  * Perform miscellaneous checks and processing after we have received the
2210  * server's initial flight. In TLS1.3 this is after the Server Finished message.
2211  * In <=TLS1.2 this is after the ServerDone message. Returns 1 on success or 0
2212  * on failure.
2213  */
2214 int tls_process_initial_server_flight(SSL *s, int *al)
2215 {
2216     /*
2217      * at this point we check that we have the required stuff from
2218      * the server
2219      */
2220     if (!ssl3_check_cert_and_algorithm(s)) {
2221         *al = SSL_AD_HANDSHAKE_FAILURE;
2222         return 0;
2223     }
2224
2225     /*
2226      * Call the ocsp status callback if needed. The |tlsext_ocsp_resp| and
2227      * |tlsext_ocsp_resplen| values will be set if we actually received a status
2228      * message, or NULL and -1 otherwise
2229      */
2230     if (s->tlsext_status_type != TLSEXT_STATUSTYPE_nothing
2231             && s->ctx->tlsext_status_cb != NULL) {
2232         int ret;
2233         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2234         if (ret == 0) {
2235             *al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2236             SSLerr(SSL_F_TLS_PROCESS_INITIAL_SERVER_FLIGHT,
2237                    SSL_R_INVALID_STATUS_RESPONSE);
2238             return 0;
2239         }
2240         if (ret < 0) {
2241             *al = SSL_AD_INTERNAL_ERROR;
2242             SSLerr(SSL_F_TLS_PROCESS_INITIAL_SERVER_FLIGHT,
2243                    ERR_R_MALLOC_FAILURE);
2244             return 0;
2245         }
2246     }
2247 #ifndef OPENSSL_NO_CT
2248     if (s->ct_validation_callback != NULL) {
2249         /* Note we validate the SCTs whether or not we abort on error */
2250         if (!ssl_validate_ct(s) && (s->verify_mode & SSL_VERIFY_PEER)) {
2251             *al = SSL_AD_HANDSHAKE_FAILURE;
2252             return 0;
2253         }
2254     }
2255 #endif
2256
2257     return 1;
2258 }
2259
2260 MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
2261 {
2262     int al = SSL_AD_INTERNAL_ERROR;
2263
2264     if (PACKET_remaining(pkt) > 0) {
2265         /* should contain no data */
2266         al = SSL_AD_DECODE_ERROR;
2267         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2268         goto err;
2269     }
2270 #ifndef OPENSSL_NO_SRP
2271     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2272         if (SRP_Calc_A_param(s) <= 0) {
2273             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
2274             goto err;
2275         }
2276     }
2277 #endif
2278
2279     /*
2280      * Error queue messages are generated directly by this function
2281      */
2282     if (!tls_process_initial_server_flight(s, &al))
2283         goto err;
2284
2285 #ifndef OPENSSL_NO_SCTP
2286     /* Only applies to renegotiation */
2287     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
2288         && s->renegotiate != 0)
2289         return MSG_PROCESS_CONTINUE_PROCESSING;
2290     else
2291 #endif
2292         return MSG_PROCESS_FINISHED_READING;
2293
2294  err:
2295     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2296     ossl_statem_set_error(s);
2297     return MSG_PROCESS_ERROR;
2298 }
2299
2300 static int tls_construct_cke_psk_preamble(SSL *s, WPACKET *pkt, int *al)
2301 {
2302 #ifndef OPENSSL_NO_PSK
2303     int ret = 0;
2304     /*
2305      * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2306      * \0-terminated identity. The last byte is for us for simulating
2307      * strnlen.
2308      */
2309     char identity[PSK_MAX_IDENTITY_LEN + 1];
2310     size_t identitylen = 0;
2311     unsigned char psk[PSK_MAX_PSK_LEN];
2312     unsigned char *tmppsk = NULL;
2313     char *tmpidentity = NULL;
2314     size_t psklen = 0;
2315
2316     if (s->psk_client_callback == NULL) {
2317         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_CLIENT_CB);
2318         *al = SSL_AD_INTERNAL_ERROR;
2319         goto err;
2320     }
2321
2322     memset(identity, 0, sizeof(identity));
2323
2324     psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2325                                     identity, sizeof(identity) - 1,
2326                                     psk, sizeof(psk));
2327
2328     if (psklen > PSK_MAX_PSK_LEN) {
2329         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2330         *al = SSL_AD_HANDSHAKE_FAILURE;
2331         goto err;
2332     } else if (psklen == 0) {
2333         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE,
2334                SSL_R_PSK_IDENTITY_NOT_FOUND);
2335         *al = SSL_AD_HANDSHAKE_FAILURE;
2336         goto err;
2337     }
2338
2339     identitylen = strlen(identity);
2340     if (identitylen > PSK_MAX_IDENTITY_LEN) {
2341         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2342         *al = SSL_AD_HANDSHAKE_FAILURE;
2343         goto err;
2344     }
2345
2346     tmppsk = OPENSSL_memdup(psk, psklen);
2347     tmpidentity = OPENSSL_strdup(identity);
2348     if (tmppsk == NULL || tmpidentity == NULL) {
2349         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2350         *al = SSL_AD_INTERNAL_ERROR;
2351         goto err;
2352     }
2353
2354     OPENSSL_free(s->s3->tmp.psk);
2355     s->s3->tmp.psk = tmppsk;
2356     s->s3->tmp.psklen = psklen;
2357     tmppsk = NULL;
2358     OPENSSL_free(s->session->psk_identity);
2359     s->session->psk_identity = tmpidentity;
2360     tmpidentity = NULL;
2361
2362     if (!WPACKET_sub_memcpy_u16(pkt, identity, identitylen))  {
2363         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2364         *al = SSL_AD_INTERNAL_ERROR;
2365         goto err;
2366     }
2367
2368     ret = 1;
2369
2370  err:
2371     OPENSSL_cleanse(psk, psklen);
2372     OPENSSL_cleanse(identity, sizeof(identity));
2373     OPENSSL_clear_free(tmppsk, psklen);
2374     OPENSSL_clear_free(tmpidentity, identitylen);
2375
2376     return ret;
2377 #else
2378     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2379     *al = SSL_AD_INTERNAL_ERROR;
2380     return 0;
2381 #endif
2382 }
2383
2384 static int tls_construct_cke_rsa(SSL *s, WPACKET *pkt, int *al)
2385 {
2386 #ifndef OPENSSL_NO_RSA
2387     unsigned char *encdata = NULL;
2388     EVP_PKEY *pkey = NULL;
2389     EVP_PKEY_CTX *pctx = NULL;
2390     size_t enclen;
2391     unsigned char *pms = NULL;
2392     size_t pmslen = 0;
2393
2394     if (s->session->peer == NULL) {
2395         /*
2396          * We should always have a server certificate with SSL_kRSA.
2397          */
2398         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2399         return 0;
2400     }
2401
2402     pkey = X509_get0_pubkey(s->session->peer);
2403     if (EVP_PKEY_get0_RSA(pkey) == NULL) {
2404         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2405         return 0;
2406     }
2407
2408     pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2409     pms = OPENSSL_malloc(pmslen);
2410     if (pms == NULL) {
2411         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_MALLOC_FAILURE);
2412         *al = SSL_AD_INTERNAL_ERROR;
2413         return 0;
2414     }
2415
2416     pms[0] = s->client_version >> 8;
2417     pms[1] = s->client_version & 0xff;
2418     /* TODO(size_t): Convert this function */
2419     if (RAND_bytes(pms + 2, (int)(pmslen - 2)) <= 0) {
2420         goto err;
2421     }
2422
2423     /* Fix buf for TLS and beyond */
2424     if (s->version > SSL3_VERSION && !WPACKET_start_sub_packet_u16(pkt)) {
2425         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2426         goto err;
2427     }
2428     pctx = EVP_PKEY_CTX_new(pkey, NULL);
2429     if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 0
2430         || EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {
2431         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_EVP_LIB);
2432         goto err;
2433     }
2434     if (!WPACKET_allocate_bytes(pkt, enclen, &encdata)
2435             || EVP_PKEY_encrypt(pctx, encdata, &enclen, pms, pmslen) <= 0) {
2436         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, SSL_R_BAD_RSA_ENCRYPT);
2437         goto err;
2438     }
2439     EVP_PKEY_CTX_free(pctx);
2440     pctx = NULL;
2441 # ifdef PKCS1_CHECK
2442     if (s->options & SSL_OP_PKCS1_CHECK_1)
2443         (*p)[1]++;
2444     if (s->options & SSL_OP_PKCS1_CHECK_2)
2445         tmp_buf[0] = 0x70;
2446 # endif
2447
2448     /* Fix buf for TLS and beyond */
2449     if (s->version > SSL3_VERSION && !WPACKET_close(pkt)) {
2450         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2451         goto err;
2452     }
2453
2454     s->s3->tmp.pms = pms;
2455     s->s3->tmp.pmslen = pmslen;
2456
2457     return 1;
2458  err:
2459     OPENSSL_clear_free(pms, pmslen);
2460     EVP_PKEY_CTX_free(pctx);
2461
2462     return 0;
2463 #else
2464     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2465     *al = SSL_AD_INTERNAL_ERROR;
2466     return 0;
2467 #endif
2468 }
2469
2470 static int tls_construct_cke_dhe(SSL *s, WPACKET *pkt, int *al)
2471 {
2472 #ifndef OPENSSL_NO_DH
2473     DH *dh_clnt = NULL;
2474     const BIGNUM *pub_key;
2475     EVP_PKEY *ckey = NULL, *skey = NULL;
2476     unsigned char *keybytes = NULL;
2477
2478     skey = s->s3->peer_tmp;
2479     if (skey == NULL)
2480         goto err;
2481
2482     ckey = ssl_generate_pkey(skey);
2483     if (ckey == NULL)
2484         goto err;
2485
2486     dh_clnt = EVP_PKEY_get0_DH(ckey);
2487
2488     if (dh_clnt == NULL || ssl_derive(s, ckey, skey, 0) == 0)
2489         goto err;
2490
2491     /* send off the data */
2492     DH_get0_key(dh_clnt, &pub_key, NULL);
2493     if (!WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(pub_key), &keybytes))
2494         goto err;
2495
2496     BN_bn2bin(pub_key, keybytes);
2497     EVP_PKEY_free(ckey);
2498
2499     return 1;
2500  err:
2501     EVP_PKEY_free(ckey);
2502 #endif
2503     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
2504     *al = SSL_AD_INTERNAL_ERROR;
2505     return 0;
2506 }
2507
2508 static int tls_construct_cke_ecdhe(SSL *s, WPACKET *pkt, int *al)
2509 {
2510 #ifndef OPENSSL_NO_EC
2511     unsigned char *encodedPoint = NULL;
2512     size_t encoded_pt_len = 0;
2513     EVP_PKEY *ckey = NULL, *skey = NULL;
2514     int ret = 0;
2515
2516     skey = s->s3->peer_tmp;
2517     if (skey == NULL) {
2518         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2519         return 0;
2520     }
2521
2522     ckey = ssl_generate_pkey(skey);
2523     if (ckey == NULL) {
2524         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_MALLOC_FAILURE);
2525         goto err;
2526     }
2527
2528     if (ssl_derive(s, ckey, skey, 0) == 0) {
2529         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);
2530         goto err;
2531     }
2532
2533     /* Generate encoding of client key */
2534     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);
2535
2536     if (encoded_pt_len == 0) {
2537         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);
2538         goto err;
2539     }
2540
2541     if (!WPACKET_sub_memcpy_u8(pkt, encodedPoint, encoded_pt_len)) {
2542         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2543         goto err;
2544     }
2545
2546     ret = 1;
2547  err:
2548     OPENSSL_free(encodedPoint);
2549     EVP_PKEY_free(ckey);
2550     return ret;
2551 #else
2552     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2553     *al = SSL_AD_INTERNAL_ERROR;
2554     return 0;
2555 #endif
2556 }
2557
2558 static int tls_construct_cke_gost(SSL *s, WPACKET *pkt, int *al)
2559 {
2560 #ifndef OPENSSL_NO_GOST
2561     /* GOST key exchange message creation */
2562     EVP_PKEY_CTX *pkey_ctx = NULL;
2563     X509 *peer_cert;
2564     size_t msglen;
2565     unsigned int md_len;
2566     unsigned char shared_ukm[32], tmp[256];
2567     EVP_MD_CTX *ukm_hash = NULL;
2568     int dgst_nid = NID_id_GostR3411_94;
2569     unsigned char *pms = NULL;
2570     size_t pmslen = 0;
2571
2572     if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
2573         dgst_nid = NID_id_GostR3411_2012_256;
2574
2575     /*
2576      * Get server sertificate PKEY and create ctx from it
2577      */
2578     peer_cert = s->session->peer;
2579     if (!peer_cert) {
2580         *al = SSL_AD_HANDSHAKE_FAILURE;
2581         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST,
2582                SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2583         return 0;
2584     }
2585
2586     pkey_ctx = EVP_PKEY_CTX_new(X509_get0_pubkey(peer_cert), NULL);
2587     if (pkey_ctx == NULL) {
2588         *al = SSL_AD_INTERNAL_ERROR;
2589         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);
2590         return 0;
2591     }
2592     /*
2593      * If we have send a certificate, and certificate key
2594      * parameters match those of server certificate, use
2595      * certificate key for key exchange
2596      */
2597
2598     /* Otherwise, generate ephemeral key pair */
2599     pmslen = 32;
2600     pms = OPENSSL_malloc(pmslen);
2601     if (pms == NULL) {
2602         *al = SSL_AD_INTERNAL_ERROR;
2603         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);
2604         goto err;
2605     }
2606
2607     if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2608         /* Generate session key
2609          * TODO(size_t): Convert this function
2610          */
2611         || RAND_bytes(pms, (int)pmslen) <= 0) {
2612         *al = SSL_AD_INTERNAL_ERROR;
2613         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2614         goto err;
2615     };
2616     /*
2617      * Compute shared IV and store it in algorithm-specific context
2618      * data
2619      */
2620     ukm_hash = EVP_MD_CTX_new();
2621     if (ukm_hash == NULL
2622         || EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 0
2623         || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2624                             SSL3_RANDOM_SIZE) <= 0
2625         || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2626                             SSL3_RANDOM_SIZE) <= 0
2627         || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2628         *al = SSL_AD_INTERNAL_ERROR;
2629         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2630         goto err;
2631     }
2632     EVP_MD_CTX_free(ukm_hash);
2633     ukm_hash = NULL;
2634     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2635                           EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2636         *al = SSL_AD_INTERNAL_ERROR;
2637         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);
2638         goto err;
2639     }
2640     /* Make GOST keytransport blob message */
2641     /*
2642      * Encapsulate it into sequence
2643      */
2644     msglen = 255;
2645     if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
2646         *al = SSL_AD_INTERNAL_ERROR;
2647         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);
2648         goto err;
2649     }
2650
2651     if (!WPACKET_put_bytes_u8(pkt, V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)
2652             || (msglen >= 0x80 && !WPACKET_put_bytes_u8(pkt, 0x81))
2653             || !WPACKET_sub_memcpy_u8(pkt, tmp, msglen)) {
2654         *al = SSL_AD_INTERNAL_ERROR;
2655         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2656         goto err;
2657     }
2658
2659     EVP_PKEY_CTX_free(pkey_ctx);
2660     s->s3->tmp.pms = pms;
2661     s->s3->tmp.pmslen = pmslen;
2662
2663     return 1;
2664  err:
2665     EVP_PKEY_CTX_free(pkey_ctx);
2666     OPENSSL_clear_free(pms, pmslen);
2667     EVP_MD_CTX_free(ukm_hash);
2668     return 0;
2669 #else
2670     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2671     *al = SSL_AD_INTERNAL_ERROR;
2672     return 0;
2673 #endif
2674 }
2675
2676 static int tls_construct_cke_srp(SSL *s, WPACKET *pkt, int *al)
2677 {
2678 #ifndef OPENSSL_NO_SRP
2679     unsigned char *abytes = NULL;
2680
2681     if (s->srp_ctx.A == NULL
2682             || !WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(s->srp_ctx.A),
2683                                                &abytes)) {
2684         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_INTERNAL_ERROR);
2685         return 0;
2686     }
2687     BN_bn2bin(s->srp_ctx.A, abytes);
2688
2689     OPENSSL_free(s->session->srp_username);
2690     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2691     if (s->session->srp_username == NULL) {
2692         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_MALLOC_FAILURE);
2693         return 0;
2694     }
2695
2696     return 1;
2697 #else
2698     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_INTERNAL_ERROR);
2699     *al = SSL_AD_INTERNAL_ERROR;
2700     return 0;
2701 #endif
2702 }
2703
2704 int tls_construct_client_key_exchange(SSL *s, WPACKET *pkt)
2705 {
2706     unsigned long alg_k;
2707     int al = -1;
2708
2709     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2710
2711     if ((alg_k & SSL_PSK)
2712         && !tls_construct_cke_psk_preamble(s, pkt, &al))
2713         goto err;
2714
2715     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2716         if (!tls_construct_cke_rsa(s, pkt, &al))
2717             goto err;
2718     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2719         if (!tls_construct_cke_dhe(s, pkt, &al))
2720             goto err;
2721     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2722         if (!tls_construct_cke_ecdhe(s, pkt, &al))
2723             goto err;
2724     } else if (alg_k & SSL_kGOST) {
2725         if (!tls_construct_cke_gost(s, pkt, &al))
2726             goto err;
2727     } else if (alg_k & SSL_kSRP) {
2728         if (!tls_construct_cke_srp(s, pkt, &al))
2729             goto err;
2730     } else if (!(alg_k & SSL_kPSK)) {
2731         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2732         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2733         goto err;
2734     }
2735
2736     return 1;
2737  err:
2738     if (al != -1)
2739         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2740     OPENSSL_clear_free(s->s3->tmp.pms, s->s3->tmp.pmslen);
2741     s->s3->tmp.pms = NULL;
2742 #ifndef OPENSSL_NO_PSK
2743     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2744     s->s3->tmp.psk = NULL;
2745 #endif
2746     return 0;
2747 }
2748
2749 int tls_client_key_exchange_post_work(SSL *s)
2750 {
2751     unsigned char *pms = NULL;
2752     size_t pmslen = 0;
2753
2754     pms = s->s3->tmp.pms;
2755     pmslen = s->s3->tmp.pmslen;
2756
2757 #ifndef OPENSSL_NO_SRP
2758     /* Check for SRP */
2759     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2760         if (!srp_generate_client_master_secret(s)) {
2761             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2762                    ERR_R_INTERNAL_ERROR);
2763             goto err;
2764         }
2765         return 1;
2766     }
2767 #endif
2768
2769     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2770         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2771         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2772         goto err;
2773     }
2774     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2775         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2776         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2777         /* ssl_generate_master_secret frees the pms even on error */
2778         pms = NULL;
2779         pmslen = 0;
2780         goto err;
2781     }
2782     pms = NULL;
2783     pmslen = 0;
2784
2785 #ifndef OPENSSL_NO_SCTP
2786     if (SSL_IS_DTLS(s)) {
2787         unsigned char sctpauthkey[64];
2788         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2789
2790         /*
2791          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2792          * used.
2793          */
2794         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2795                sizeof(DTLS1_SCTP_AUTH_LABEL));
2796
2797         if (SSL_export_keying_material(s, sctpauthkey,
2798                                        sizeof(sctpauthkey), labelbuffer,
2799                                        sizeof(labelbuffer), NULL, 0, 0) <= 0)
2800             goto err;
2801
2802         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2803                  sizeof(sctpauthkey), sctpauthkey);
2804     }
2805 #endif
2806
2807     return 1;
2808  err:
2809     OPENSSL_clear_free(pms, pmslen);
2810     s->s3->tmp.pms = NULL;
2811     return 0;
2812 }
2813
2814 int tls_construct_client_verify(SSL *s, WPACKET *pkt)
2815 {
2816     EVP_PKEY *pkey;
2817     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2818     EVP_MD_CTX *mctx = NULL;
2819     unsigned u = 0;
2820     long hdatalen = 0;
2821     void *hdata;
2822     unsigned char *sig = NULL;
2823
2824     mctx = EVP_MD_CTX_new();
2825     if (mctx == NULL) {
2826         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2827         goto err;
2828     }
2829     pkey = s->cert->key->privatekey;
2830
2831     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2832     if (hdatalen <= 0) {
2833         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2834         goto err;
2835     }
2836
2837     if (SSL_USE_SIGALGS(s)&& !tls12_get_sigandhash(pkt, pkey, md)) {
2838         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2839         goto err;
2840     }
2841 #ifdef SSL_DEBUG
2842     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
2843 #endif
2844     sig = OPENSSL_malloc(EVP_PKEY_size(pkey));
2845     if (sig == NULL) {
2846         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2847         goto err;
2848     }
2849     if (!EVP_SignInit_ex(mctx, md, NULL)
2850         || !EVP_SignUpdate(mctx, hdata, hdatalen)
2851         || (s->version == SSL3_VERSION
2852             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2853                                 (int)s->session->master_key_length,
2854                                 s->session->master_key))
2855         || !EVP_SignFinal(mctx, sig, &u, pkey)) {
2856         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2857         goto err;
2858     }
2859 #ifndef OPENSSL_NO_GOST
2860     {
2861         int pktype = EVP_PKEY_id(pkey);
2862         if (pktype == NID_id_GostR3410_2001
2863             || pktype == NID_id_GostR3410_2012_256
2864             || pktype == NID_id_GostR3410_2012_512)
2865             BUF_reverse(sig, NULL, u);
2866     }
2867 #endif
2868
2869     if (!WPACKET_sub_memcpy_u16(pkt, sig, u)) {
2870         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2871         goto err;
2872     }
2873
2874     /* Digest cached records and discard handshake buffer */
2875     if (!ssl3_digest_cached_records(s, 0))
2876         goto err;
2877
2878     OPENSSL_free(sig);
2879     EVP_MD_CTX_free(mctx);
2880     return 1;
2881  err:
2882     OPENSSL_free(sig);
2883     EVP_MD_CTX_free(mctx);
2884     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2885     return 0;
2886 }
2887
2888 /*
2889  * Check a certificate can be used for client authentication. Currently check
2890  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
2891  * certificates can be used and optionally checks suitability for Suite B.
2892  */
2893 static int ssl3_check_client_certificate(SSL *s)
2894 {
2895     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2896         return 0;
2897     /* If no suitable signature algorithm can't use certificate */
2898     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
2899         return 0;
2900     /*
2901      * If strict mode check suitability of chain before using it. This also
2902      * adjusts suite B digest if necessary.
2903      */
2904     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2905         !tls1_check_chain(s, NULL, NULL, NULL, -2))
2906         return 0;
2907     return 1;
2908 }
2909
2910 WORK_STATE tls_prepare_client_certificate(SSL *s, WORK_STATE wst)
2911 {
2912     X509 *x509 = NULL;
2913     EVP_PKEY *pkey = NULL;
2914     int i;
2915
2916     if (wst == WORK_MORE_A) {
2917         /* Let cert callback update client certificates if required */
2918         if (s->cert->cert_cb) {
2919             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2920             if (i < 0) {
2921                 s->rwstate = SSL_X509_LOOKUP;
2922                 return WORK_MORE_A;
2923             }
2924             if (i == 0) {
2925                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2926                 ossl_statem_set_error(s);
2927                 return 0;
2928             }
2929             s->rwstate = SSL_NOTHING;
2930         }
2931         if (ssl3_check_client_certificate(s))
2932             return WORK_FINISHED_CONTINUE;
2933
2934         /* Fall through to WORK_MORE_B */
2935         wst = WORK_MORE_B;
2936     }
2937
2938     /* We need to get a client cert */
2939     if (wst == WORK_MORE_B) {
2940         /*
2941          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
2942          * return(-1); We then get retied later
2943          */
2944         i = ssl_do_client_cert_cb(s, &x509, &pkey);
2945         if (i < 0) {
2946             s->rwstate = SSL_X509_LOOKUP;
2947             return WORK_MORE_B;
2948         }
2949         s->rwstate = SSL_NOTHING;
2950         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2951             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
2952                 i = 0;
2953         } else if (i == 1) {
2954             i = 0;
2955             SSLerr(SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE,
2956                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2957         }
2958
2959         X509_free(x509);
2960         EVP_PKEY_free(pkey);
2961         if (i && !ssl3_check_client_certificate(s))
2962             i = 0;
2963         if (i == 0) {
2964             if (s->version == SSL3_VERSION) {
2965                 s->s3->tmp.cert_req = 0;
2966                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
2967                 return WORK_FINISHED_CONTINUE;
2968             } else {
2969                 s->s3->tmp.cert_req = 2;
2970                 if (!ssl3_digest_cached_records(s, 0)) {
2971                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2972                     ossl_statem_set_error(s);
2973                     return 0;
2974                 }
2975             }
2976         }
2977
2978         return WORK_FINISHED_CONTINUE;
2979     }
2980
2981     /* Shouldn't ever get here */
2982     return WORK_ERROR;
2983 }
2984
2985 int tls_construct_client_certificate(SSL *s, WPACKET *pkt)
2986 {
2987     if (!ssl3_output_cert_chain(s, pkt,
2988                                (s->s3->tmp.cert_req == 2) ? NULL
2989                                                           : s->cert->key)) {
2990         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2991         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2992         return 0;
2993     }
2994
2995     return 1;
2996 }
2997
2998 #define has_bits(i,m)   (((i)&(m)) == (m))
2999
3000 int ssl3_check_cert_and_algorithm(SSL *s)
3001 {
3002     int i;
3003 #ifndef OPENSSL_NO_EC
3004     int idx;
3005 #endif
3006     long alg_k, alg_a;
3007     EVP_PKEY *pkey = NULL;
3008     int al = SSL_AD_HANDSHAKE_FAILURE;
3009
3010     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3011     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3012
3013     /* we don't have a certificate */
3014     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
3015         return (1);
3016
3017     /* This is the passed certificate */
3018
3019 #ifndef OPENSSL_NO_EC
3020     idx = s->session->peer_type;
3021     if (idx == SSL_PKEY_ECC) {
3022         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
3023             /* check failed */
3024             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
3025             goto f_err;
3026         } else {
3027             return 1;
3028         }
3029     } else if (alg_a & SSL_aECDSA) {
3030         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3031                SSL_R_MISSING_ECDSA_SIGNING_CERT);
3032         goto f_err;
3033     }
3034 #endif
3035     pkey = X509_get0_pubkey(s->session->peer);
3036     i = X509_certificate_type(s->session->peer, pkey);
3037
3038     /* Check that we have a certificate if we require one */
3039     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
3040         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3041                SSL_R_MISSING_RSA_SIGNING_CERT);
3042         goto f_err;
3043     }
3044 #ifndef OPENSSL_NO_DSA
3045     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
3046         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3047                SSL_R_MISSING_DSA_SIGNING_CERT);
3048         goto f_err;
3049     }
3050 #endif
3051 #ifndef OPENSSL_NO_RSA
3052     if (alg_k & (SSL_kRSA | SSL_kRSAPSK) &&
3053         !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3054         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3055                SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3056         goto f_err;
3057     }
3058 #endif
3059 #ifndef OPENSSL_NO_DH
3060     if ((alg_k & SSL_kDHE) && (s->s3->peer_tmp == NULL)) {
3061         al = SSL_AD_INTERNAL_ERROR;
3062         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3063         goto f_err;
3064     }
3065 #endif
3066
3067     return (1);
3068  f_err:
3069     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3070     return (0);
3071 }
3072
3073 #ifndef OPENSSL_NO_NEXTPROTONEG
3074 int tls_construct_next_proto(SSL *s, WPACKET *pkt)
3075 {
3076     size_t len, padding_len;
3077     unsigned char *padding = NULL;
3078
3079     len = s->next_proto_negotiated_len;
3080     padding_len = 32 - ((len + 2) % 32);
3081
3082     if (!WPACKET_sub_memcpy_u8(pkt, s->next_proto_negotiated, len)
3083             || !WPACKET_sub_allocate_bytes_u8(pkt, padding_len, &padding)) {
3084         SSLerr(SSL_F_TLS_CONSTRUCT_NEXT_PROTO, ERR_R_INTERNAL_ERROR);
3085         goto err;
3086     }
3087
3088     memset(padding, 0, padding_len);
3089
3090     return 1;
3091  err:
3092     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3093     return 0;
3094 }
3095 #endif
3096
3097 static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL *s, PACKET *pkt)
3098 {
3099     int al = SSL_AD_INTERNAL_ERROR;
3100     PACKET extensions;
3101     RAW_EXTENSION *rawexts = NULL;
3102
3103     if (!PACKET_as_length_prefixed_2(pkt, &extensions)) {
3104         al = SSL_AD_DECODE_ERROR;
3105         SSLerr(SSL_F_TLS_PROCESS_ENCRYPTED_EXTENSIONS, SSL_R_LENGTH_MISMATCH);
3106         goto err;
3107     }
3108
3109     /*
3110      * TODO(TLS1.3): For now we are processing Encrypted Extensions and
3111      * Certificate extensions as part of this one message. Later we need to
3112      * split out the Certificate extensions into the Certificate message
3113      */
3114     if (!tls_collect_extensions(s, &extensions,
3115                                 EXT_TLS1_3_ENCRYPTED_EXTENSIONS
3116                                     | EXT_TLS1_3_CERTIFICATE,
3117                                 &rawexts, &al)
3118             || !tls_parse_all_extensions(s,
3119                                          EXT_TLS1_3_ENCRYPTED_EXTENSIONS
3120                                             | EXT_TLS1_3_CERTIFICATE,
3121                                          rawexts, &al))
3122         goto err;
3123
3124     OPENSSL_free(rawexts);
3125     return MSG_PROCESS_CONTINUE_READING;
3126
3127  err:
3128     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3129     ossl_statem_set_error(s);
3130     OPENSSL_free(rawexts);
3131     return MSG_PROCESS_ERROR;
3132 }
3133
3134 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3135 {
3136     int i = 0;
3137 #ifndef OPENSSL_NO_ENGINE
3138     if (s->ctx->client_cert_engine) {
3139         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3140                                         SSL_get_client_CA_list(s),
3141                                         px509, ppkey, NULL, NULL, NULL);
3142         if (i != 0)
3143             return i;
3144     }
3145 #endif
3146     if (s->ctx->client_cert_cb)
3147         i = s->ctx->client_cert_cb(s, px509, ppkey);
3148     return i;
3149 }
3150
3151 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk, WPACKET *pkt)
3152 {
3153     int i;
3154     size_t totlen = 0, len, maxlen;
3155     int empty_reneg_info_scsv = !s->renegotiate;
3156     /* Set disabled masks for this session */
3157     ssl_set_client_disabled(s);
3158
3159     if (sk == NULL)
3160         return (0);
3161
3162 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
3163 # if OPENSSL_MAX_TLS1_2_CIPHER_LENGTH < 6
3164 #  error Max cipher length too short
3165 # endif
3166     /*
3167      * Some servers hang if client hello > 256 bytes as hack workaround
3168      * chop number of supported ciphers to keep it well below this if we
3169      * use TLS v1.2
3170      */
3171     if (TLS1_get_version(s) >= TLS1_2_VERSION)
3172         maxlen = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
3173     else
3174 #endif
3175         /* Maximum length that can be stored in 2 bytes. Length must be even */
3176         maxlen = 0xfffe;
3177
3178     if (empty_reneg_info_scsv)
3179         maxlen -= 2;
3180     if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV)
3181         maxlen -= 2;
3182
3183     for (i = 0; i < sk_SSL_CIPHER_num(sk) && totlen < maxlen; i++) {
3184         const SSL_CIPHER *c;
3185
3186         c = sk_SSL_CIPHER_value(sk, i);
3187         /* Skip disabled ciphers */
3188         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
3189             continue;
3190
3191         if (!s->method->put_cipher_by_char(c, pkt, &len)) {
3192             SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3193             return 0;
3194         }
3195
3196         totlen += len;
3197     }
3198
3199     if (totlen == 0) {
3200         SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, SSL_R_NO_CIPHERS_AVAILABLE);
3201         return 0;
3202     }
3203
3204     if (totlen != 0) {
3205         if (empty_reneg_info_scsv) {
3206             static SSL_CIPHER scsv = {
3207                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3208             };
3209             if (!s->method->put_cipher_by_char(&scsv, pkt, &len)) {
3210                 SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3211                 return 0;
3212             }
3213         }
3214         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
3215             static SSL_CIPHER scsv = {
3216                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3217             };
3218             if (!s->method->put_cipher_by_char(&scsv, pkt, &len)) {
3219                 SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3220                 return 0;
3221             }
3222         }
3223     }
3224
3225     return 1;
3226 }