cded5b96ec68a4643e8da8a3a61b22055c3a2cea
[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;
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     int protverr;
1068 #ifndef OPENSSL_NO_COMP
1069     SSL_COMP *comp;
1070 #endif
1071
1072     if (!PACKET_get_net_2(pkt, &sversion)) {
1073         al = SSL_AD_DECODE_ERROR;
1074         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1075         goto f_err;
1076     }
1077
1078     protverr = ssl_choose_client_version(s, sversion);
1079     if (protverr != 0) {
1080         al = SSL_AD_PROTOCOL_VERSION;
1081         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, protverr);
1082         goto f_err;
1083     }
1084
1085     /* load the server hello data */
1086     /* load the server random */
1087     if (!PACKET_copy_bytes(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
1088         al = SSL_AD_DECODE_ERROR;
1089         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1090         goto f_err;
1091     }
1092
1093     s->hit = 0;
1094
1095     /* Get the session-id. */
1096     if (!SSL_IS_TLS13(s)) {
1097         if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
1098             al = SSL_AD_DECODE_ERROR;
1099             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1100             goto f_err;
1101         }
1102         session_id_len = PACKET_remaining(&session_id);
1103         if (session_id_len > sizeof s->session->session_id
1104             || session_id_len > SSL3_SESSION_ID_SIZE) {
1105             al = SSL_AD_ILLEGAL_PARAMETER;
1106             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1107                    SSL_R_SSL3_SESSION_ID_TOO_LONG);
1108             goto f_err;
1109         }
1110     } else {
1111         session_id_len = 0;
1112     }
1113
1114     if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
1115         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1116         al = SSL_AD_DECODE_ERROR;
1117         goto f_err;
1118     }
1119
1120     /*
1121      * Check if we can resume the session based on external pre-shared secret.
1122      * EAP-FAST (RFC 4851) supports two types of session resumption.
1123      * Resumption based on server-side state works with session IDs.
1124      * Resumption based on pre-shared Protected Access Credentials (PACs)
1125      * works by overriding the SessionTicket extension at the application
1126      * layer, and does not send a session ID. (We do not know whether EAP-FAST
1127      * servers would honour the session ID.) Therefore, the session ID alone
1128      * is not a reliable indicator of session resumption, so we first check if
1129      * we can resume, and later peek at the next handshake message to see if the
1130      * server wants to resume.
1131      */
1132     if (s->version >= TLS1_VERSION && !SSL_IS_TLS13(s)
1133             && s->tls_session_secret_cb && s->session->tlsext_tick) {
1134         const SSL_CIPHER *pref_cipher = NULL;
1135         /*
1136          * s->session->master_key_length is a size_t, but this is an int for
1137          * backwards compat reasons
1138          */
1139         int master_key_length;
1140         master_key_length = sizeof(s->session->master_key);
1141         if (s->tls_session_secret_cb(s, s->session->master_key,
1142                                      &master_key_length,
1143                                      NULL, &pref_cipher,
1144                                      s->tls_session_secret_cb_arg)
1145                  && master_key_length > 0) {
1146             s->session->master_key_length = master_key_length;
1147             s->session->cipher = pref_cipher ?
1148                 pref_cipher : ssl_get_cipher_by_char(s, cipherchars);
1149         } else {
1150             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1151             al = SSL_AD_INTERNAL_ERROR;
1152             goto f_err;
1153         }
1154     }
1155
1156     if (session_id_len != 0 && session_id_len == s->session->session_id_length
1157         && memcmp(PACKET_data(&session_id), s->session->session_id,
1158                   session_id_len) == 0) {
1159         if (s->sid_ctx_length != s->session->sid_ctx_length
1160             || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
1161             /* actually a client application bug */
1162             al = SSL_AD_ILLEGAL_PARAMETER;
1163             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1164                    SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1165             goto f_err;
1166         }
1167         s->hit = 1;
1168     } else {
1169         /*
1170          * If we were trying for session-id reuse but the server
1171          * didn't echo the ID, make a new SSL_SESSION.
1172          * In the case of EAP-FAST and PAC, we do not send a session ID,
1173          * so the PAC-based session secret is always preserved. It'll be
1174          * overwritten if the server refuses resumption.
1175          */
1176         if (s->session->session_id_length > 0) {
1177             s->ctx->stats.sess_miss++;
1178             if (!ssl_get_new_session(s, 0)) {
1179                 goto f_err;
1180             }
1181         }
1182
1183         s->session->ssl_version = s->version;
1184         s->session->session_id_length = session_id_len;
1185         /* session_id_len could be 0 */
1186         memcpy(s->session->session_id, PACKET_data(&session_id),
1187                session_id_len);
1188     }
1189
1190     /* Session version and negotiated protocol version should match */
1191     if (s->version != s->session->ssl_version) {
1192         al = SSL_AD_PROTOCOL_VERSION;
1193
1194         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1195                SSL_R_SSL_SESSION_VERSION_MISMATCH);
1196         goto f_err;
1197     }
1198
1199     c = ssl_get_cipher_by_char(s, cipherchars);
1200     if (c == NULL) {
1201         /* unknown cipher */
1202         al = SSL_AD_ILLEGAL_PARAMETER;
1203         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
1204         goto f_err;
1205     }
1206     /*
1207      * Now that we know the version, update the check to see if it's an allowed
1208      * version.
1209      */
1210     s->s3->tmp.min_ver = s->version;
1211     s->s3->tmp.max_ver = s->version;
1212     /*
1213      * If it is a disabled cipher we either didn't send it in client hello,
1214      * or it's not allowed for the selected protocol. So we return an error.
1215      */
1216     if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) {
1217         al = SSL_AD_ILLEGAL_PARAMETER;
1218         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1219         goto f_err;
1220     }
1221
1222     sk = ssl_get_ciphers_by_id(s);
1223     i = sk_SSL_CIPHER_find(sk, c);
1224     if (i < 0) {
1225         /* we did not say we would use this cipher */
1226         al = SSL_AD_ILLEGAL_PARAMETER;
1227         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
1228         goto f_err;
1229     }
1230
1231     /*
1232      * Depending on the session caching (internal/external), the cipher
1233      * and/or cipher_id values may not be set. Make sure that cipher_id is
1234      * set and use it for comparison.
1235      */
1236     if (s->session->cipher)
1237         s->session->cipher_id = s->session->cipher->id;
1238     if (s->hit && (s->session->cipher_id != c->id)) {
1239         al = SSL_AD_ILLEGAL_PARAMETER;
1240         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1241                SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1242         goto f_err;
1243     }
1244     s->s3->tmp.new_cipher = c;
1245     /* lets get the compression algorithm */
1246     /* COMPRESSION */
1247     if (!SSL_IS_TLS13(s)) {
1248         if (!PACKET_get_1(pkt, &compression)) {
1249             SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_LENGTH_MISMATCH);
1250             al = SSL_AD_DECODE_ERROR;
1251             goto f_err;
1252         }
1253     } else {
1254         compression = 0;
1255     }
1256
1257 #ifdef OPENSSL_NO_COMP
1258     if (compression != 0) {
1259         al = SSL_AD_ILLEGAL_PARAMETER;
1260         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1261                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1262         goto f_err;
1263     }
1264     /*
1265      * If compression is disabled we'd better not try to resume a session
1266      * using compression.
1267      */
1268     if (s->session->compress_meth != 0) {
1269         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1270         goto f_err;
1271     }
1272 #else
1273     if (s->hit && compression != s->session->compress_meth) {
1274         al = SSL_AD_ILLEGAL_PARAMETER;
1275         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1276                SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1277         goto f_err;
1278     }
1279     if (compression == 0)
1280         comp = NULL;
1281     else if (!ssl_allow_compression(s)) {
1282         al = SSL_AD_ILLEGAL_PARAMETER;
1283         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1284         goto f_err;
1285     } else {
1286         comp = ssl3_comp_find(s->ctx->comp_methods, compression);
1287     }
1288
1289     if (compression != 0 && comp == NULL) {
1290         al = SSL_AD_ILLEGAL_PARAMETER;
1291         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO,
1292                SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1293         goto f_err;
1294     } else {
1295         s->s3->tmp.new_compression = comp;
1296     }
1297 #endif
1298
1299     /* TLS extensions */
1300     if (!ssl_parse_serverhello_tlsext(s, pkt)) {
1301         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1302         goto err;
1303     }
1304
1305     if (PACKET_remaining(pkt) != 0) {
1306         /* wrong packet length */
1307         al = SSL_AD_DECODE_ERROR;
1308         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1309         goto f_err;
1310     }
1311 #ifndef OPENSSL_NO_SCTP
1312     if (SSL_IS_DTLS(s) && s->hit) {
1313         unsigned char sctpauthkey[64];
1314         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1315
1316         /*
1317          * Add new shared key for SCTP-Auth, will be ignored if
1318          * no SCTP used.
1319          */
1320         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1321                sizeof(DTLS1_SCTP_AUTH_LABEL));
1322
1323         if (SSL_export_keying_material(s, sctpauthkey,
1324                                        sizeof(sctpauthkey),
1325                                        labelbuffer,
1326                                        sizeof(labelbuffer), NULL, 0, 0) <= 0)
1327             goto err;
1328
1329         BIO_ctrl(SSL_get_wbio(s),
1330                  BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1331                  sizeof(sctpauthkey), sctpauthkey);
1332     }
1333 #endif
1334
1335     /*
1336      * In TLSv1.3 we have some post-processing to change cipher state, otherwise
1337      * we're done with this message
1338      */
1339     if (SSL_IS_TLS13(s)
1340             && (!s->method->ssl3_enc->setup_key_block(s)
1341                 || !s->method->ssl3_enc->change_cipher_state(s,
1342                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE)
1343                 || !s->method->ssl3_enc->change_cipher_state(s,
1344                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_READ))) {
1345         al = SSL_AD_INTERNAL_ERROR;
1346         SSLerr(SSL_F_TLS_PROCESS_SERVER_HELLO, SSL_R_CANNOT_CHANGE_CIPHER);
1347         goto f_err;
1348     }
1349
1350     return MSG_PROCESS_CONTINUE_READING;
1351  f_err:
1352     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1353  err:
1354     ossl_statem_set_error(s);
1355     return MSG_PROCESS_ERROR;
1356 }
1357
1358 MSG_PROCESS_RETURN tls_process_server_certificate(SSL *s, PACKET *pkt)
1359 {
1360     int al, i, ret = MSG_PROCESS_ERROR, exp_idx;
1361     unsigned long cert_list_len, cert_len;
1362     X509 *x = NULL;
1363     const unsigned char *certstart, *certbytes;
1364     STACK_OF(X509) *sk = NULL;
1365     EVP_PKEY *pkey = NULL;
1366
1367     if ((sk = sk_X509_new_null()) == NULL) {
1368         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1369         goto err;
1370     }
1371
1372     if (!PACKET_get_net_3(pkt, &cert_list_len)
1373         || PACKET_remaining(pkt) != cert_list_len) {
1374         al = SSL_AD_DECODE_ERROR;
1375         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1376         goto f_err;
1377     }
1378     while (PACKET_remaining(pkt)) {
1379         if (!PACKET_get_net_3(pkt, &cert_len)
1380             || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
1381             al = SSL_AD_DECODE_ERROR;
1382             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1383                    SSL_R_CERT_LENGTH_MISMATCH);
1384             goto f_err;
1385         }
1386
1387         certstart = certbytes;
1388         x = d2i_X509(NULL, (const unsigned char **)&certbytes, cert_len);
1389         if (x == NULL) {
1390             al = SSL_AD_BAD_CERTIFICATE;
1391             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1392             goto f_err;
1393         }
1394         if (certbytes != (certstart + cert_len)) {
1395             al = SSL_AD_DECODE_ERROR;
1396             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1397                    SSL_R_CERT_LENGTH_MISMATCH);
1398             goto f_err;
1399         }
1400         if (!sk_X509_push(sk, x)) {
1401             SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1402             goto err;
1403         }
1404         x = NULL;
1405     }
1406
1407     i = ssl_verify_cert_chain(s, sk);
1408     /*
1409      * The documented interface is that SSL_VERIFY_PEER should be set in order
1410      * for client side verification of the server certificate to take place.
1411      * However, historically the code has only checked that *any* flag is set
1412      * to cause server verification to take place. Use of the other flags makes
1413      * no sense in client mode. An attempt to clean up the semantics was
1414      * reverted because at least one application *only* set
1415      * SSL_VERIFY_FAIL_IF_NO_PEER_CERT. Prior to the clean up this still caused
1416      * server verification to take place, after the clean up it silently did
1417      * nothing. SSL_CTX_set_verify()/SSL_set_verify() cannot validate the flags
1418      * sent to them because they are void functions. Therefore, we now use the
1419      * (less clean) historic behaviour of performing validation if any flag is
1420      * set. The *documented* interface remains the same.
1421      */
1422     if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
1423         al = ssl_verify_alarm_type(s->verify_result);
1424         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1425                SSL_R_CERTIFICATE_VERIFY_FAILED);
1426         goto f_err;
1427     }
1428     ERR_clear_error();          /* but we keep s->verify_result */
1429     if (i > 1) {
1430         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, i);
1431         al = SSL_AD_HANDSHAKE_FAILURE;
1432         goto f_err;
1433     }
1434
1435     s->session->peer_chain = sk;
1436     /*
1437      * Inconsistency alert: cert_chain does include the peer's certificate,
1438      * which we don't include in statem_srvr.c
1439      */
1440     x = sk_X509_value(sk, 0);
1441     sk = NULL;
1442     /*
1443      * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1444      */
1445
1446     pkey = X509_get0_pubkey(x);
1447
1448     if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1449         x = NULL;
1450         al = SSL3_AL_FATAL;
1451         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1452                SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1453         goto f_err;
1454     }
1455
1456     i = ssl_cert_type(x, pkey);
1457     if (i < 0) {
1458         x = NULL;
1459         al = SSL3_AL_FATAL;
1460         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1461                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1462         goto f_err;
1463     }
1464
1465     exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1466     if (exp_idx >= 0 && i != exp_idx
1467         && (exp_idx != SSL_PKEY_GOST_EC ||
1468             (i != SSL_PKEY_GOST12_512 && i != SSL_PKEY_GOST12_256
1469              && i != SSL_PKEY_GOST01))) {
1470         x = NULL;
1471         al = SSL_AD_ILLEGAL_PARAMETER;
1472         SSLerr(SSL_F_TLS_PROCESS_SERVER_CERTIFICATE,
1473                SSL_R_WRONG_CERTIFICATE_TYPE);
1474         goto f_err;
1475     }
1476     s->session->peer_type = i;
1477
1478     X509_free(s->session->peer);
1479     X509_up_ref(x);
1480     s->session->peer = x;
1481     s->session->verify_result = s->verify_result;
1482
1483     x = NULL;
1484     ret = MSG_PROCESS_CONTINUE_READING;
1485     goto done;
1486
1487  f_err:
1488     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1489  err:
1490     ossl_statem_set_error(s);
1491  done:
1492     X509_free(x);
1493     sk_X509_pop_free(sk, X509_free);
1494     return ret;
1495 }
1496
1497 static int tls_process_ske_psk_preamble(SSL *s, PACKET *pkt, int *al)
1498 {
1499 #ifndef OPENSSL_NO_PSK
1500     PACKET psk_identity_hint;
1501
1502     /* PSK ciphersuites are preceded by an identity hint */
1503
1504     if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
1505         *al = SSL_AD_DECODE_ERROR;
1506         SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH);
1507         return 0;
1508     }
1509
1510     /*
1511      * Store PSK identity hint for later use, hint is used in
1512      * tls_construct_client_key_exchange.  Assume that the maximum length of
1513      * a PSK identity hint can be as long as the maximum length of a PSK
1514      * identity.
1515      */
1516     if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
1517         *al = SSL_AD_HANDSHAKE_FAILURE;
1518         SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG);
1519         return 0;
1520     }
1521
1522     if (PACKET_remaining(&psk_identity_hint) == 0) {
1523         OPENSSL_free(s->session->psk_identity_hint);
1524         s->session->psk_identity_hint = NULL;
1525     } else if (!PACKET_strndup(&psk_identity_hint,
1526                                &s->session->psk_identity_hint)) {
1527         *al = SSL_AD_INTERNAL_ERROR;
1528         return 0;
1529     }
1530
1531     return 1;
1532 #else
1533     SSLerr(SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
1534     *al = SSL_AD_INTERNAL_ERROR;
1535     return 0;
1536 #endif
1537 }
1538
1539 static int tls_process_ske_srp(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1540 {
1541 #ifndef OPENSSL_NO_SRP
1542     PACKET prime, generator, salt, server_pub;
1543
1544     if (!PACKET_get_length_prefixed_2(pkt, &prime)
1545         || !PACKET_get_length_prefixed_2(pkt, &generator)
1546         || !PACKET_get_length_prefixed_1(pkt, &salt)
1547         || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
1548         *al = SSL_AD_DECODE_ERROR;
1549         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, SSL_R_LENGTH_MISMATCH);
1550         return 0;
1551     }
1552
1553     /* TODO(size_t): Convert BN_bin2bn() calls */
1554     if ((s->srp_ctx.N =
1555          BN_bin2bn(PACKET_data(&prime),
1556                    (int)PACKET_remaining(&prime), NULL)) == NULL
1557         || (s->srp_ctx.g =
1558             BN_bin2bn(PACKET_data(&generator),
1559                       (int)PACKET_remaining(&generator), NULL)) == NULL
1560         || (s->srp_ctx.s =
1561             BN_bin2bn(PACKET_data(&salt),
1562                       (int)PACKET_remaining(&salt), NULL)) == NULL
1563         || (s->srp_ctx.B =
1564             BN_bin2bn(PACKET_data(&server_pub),
1565                       (int)PACKET_remaining(&server_pub), NULL)) == NULL) {
1566         *al = SSL_AD_INTERNAL_ERROR;
1567         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, ERR_R_BN_LIB);
1568         return 0;
1569     }
1570
1571     if (!srp_verify_server_param(s, al)) {
1572         *al = SSL_AD_DECODE_ERROR;
1573         SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, SSL_R_BAD_SRP_PARAMETERS);
1574         return 0;
1575     }
1576
1577     /* We must check if there is a certificate */
1578     if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
1579         *pkey = X509_get0_pubkey(s->session->peer);
1580
1581     return 1;
1582 #else
1583     SSLerr(SSL_F_TLS_PROCESS_SKE_SRP, ERR_R_INTERNAL_ERROR);
1584     *al = SSL_AD_INTERNAL_ERROR;
1585     return 0;
1586 #endif
1587 }
1588
1589 static int tls_process_ske_dhe(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1590 {
1591 #ifndef OPENSSL_NO_DH
1592     PACKET prime, generator, pub_key;
1593     EVP_PKEY *peer_tmp = NULL;
1594
1595     DH *dh = NULL;
1596     BIGNUM *p = NULL, *g = NULL, *bnpub_key = NULL;
1597
1598     if (!PACKET_get_length_prefixed_2(pkt, &prime)
1599         || !PACKET_get_length_prefixed_2(pkt, &generator)
1600         || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
1601         *al = SSL_AD_DECODE_ERROR;
1602         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_LENGTH_MISMATCH);
1603         return 0;
1604     }
1605
1606     peer_tmp = EVP_PKEY_new();
1607     dh = DH_new();
1608
1609     if (peer_tmp == NULL || dh == NULL) {
1610         *al = SSL_AD_INTERNAL_ERROR;
1611         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_MALLOC_FAILURE);
1612         goto err;
1613     }
1614
1615     /* TODO(size_t): Convert these calls */
1616     p = BN_bin2bn(PACKET_data(&prime), (int)PACKET_remaining(&prime), NULL);
1617     g = BN_bin2bn(PACKET_data(&generator), (int)PACKET_remaining(&generator),
1618                   NULL);
1619     bnpub_key = BN_bin2bn(PACKET_data(&pub_key),
1620                           (int)PACKET_remaining(&pub_key), NULL);
1621     if (p == NULL || g == NULL || bnpub_key == NULL) {
1622         *al = SSL_AD_INTERNAL_ERROR;
1623         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1624         goto err;
1625     }
1626
1627     if (BN_is_zero(p) || BN_is_zero(g) || BN_is_zero(bnpub_key)) {
1628         *al = SSL_AD_DECODE_ERROR;
1629         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_BAD_DH_VALUE);
1630         goto err;
1631     }
1632
1633     if (!DH_set0_pqg(dh, p, NULL, g)) {
1634         *al = SSL_AD_INTERNAL_ERROR;
1635         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1636         goto err;
1637     }
1638     p = g = NULL;
1639
1640     if (!DH_set0_key(dh, bnpub_key, NULL)) {
1641         *al = SSL_AD_INTERNAL_ERROR;
1642         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_BN_LIB);
1643         goto err;
1644     }
1645     bnpub_key = NULL;
1646
1647     if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) {
1648         *al = SSL_AD_HANDSHAKE_FAILURE;
1649         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, SSL_R_DH_KEY_TOO_SMALL);
1650         goto err;
1651     }
1652
1653     if (EVP_PKEY_assign_DH(peer_tmp, dh) == 0) {
1654         *al = SSL_AD_INTERNAL_ERROR;
1655         SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_EVP_LIB);
1656         goto err;
1657     }
1658
1659     s->s3->peer_tmp = peer_tmp;
1660
1661     /*
1662      * FIXME: This makes assumptions about which ciphersuites come with
1663      * public keys. We should have a less ad-hoc way of doing this
1664      */
1665     if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
1666         *pkey = X509_get0_pubkey(s->session->peer);
1667     /* else anonymous DH, so no certificate or pkey. */
1668
1669     return 1;
1670
1671  err:
1672     BN_free(p);
1673     BN_free(g);
1674     BN_free(bnpub_key);
1675     DH_free(dh);
1676     EVP_PKEY_free(peer_tmp);
1677
1678     return 0;
1679 #else
1680     SSLerr(SSL_F_TLS_PROCESS_SKE_DHE, ERR_R_INTERNAL_ERROR);
1681     *al = SSL_AD_INTERNAL_ERROR;
1682     return 0;
1683 #endif
1684 }
1685
1686 static int tls_process_ske_ecdhe(SSL *s, PACKET *pkt, EVP_PKEY **pkey, int *al)
1687 {
1688 #ifndef OPENSSL_NO_EC
1689     PACKET encoded_pt;
1690     const unsigned char *ecparams;
1691     int curve_nid;
1692     unsigned int curve_flags;
1693     EVP_PKEY_CTX *pctx = NULL;
1694
1695     /*
1696      * Extract elliptic curve parameters and the server's ephemeral ECDH
1697      * public key. For now we only support named (not generic) curves and
1698      * ECParameters in this case is just three bytes.
1699      */
1700     if (!PACKET_get_bytes(pkt, &ecparams, 3)) {
1701         *al = SSL_AD_DECODE_ERROR;
1702         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_LENGTH_TOO_SHORT);
1703         return 0;
1704     }
1705     /*
1706      * Check curve is one of our preferences, if not server has sent an
1707      * invalid curve. ECParameters is 3 bytes.
1708      */
1709     if (!tls1_check_curve(s, ecparams, 3)) {
1710         *al = SSL_AD_DECODE_ERROR;
1711         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_WRONG_CURVE);
1712         return 0;
1713     }
1714
1715     curve_nid = tls1_ec_curve_id2nid(*(ecparams + 2), &curve_flags);
1716
1717     if (curve_nid == 0) {
1718         *al = SSL_AD_INTERNAL_ERROR;
1719         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE,
1720                SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1721         return 0;
1722     }
1723
1724     if ((curve_flags & TLS_CURVE_TYPE) == TLS_CURVE_CUSTOM) {
1725         EVP_PKEY *key = EVP_PKEY_new();
1726
1727         if (key == NULL || !EVP_PKEY_set_type(key, curve_nid)) {
1728             *al = SSL_AD_INTERNAL_ERROR;
1729             SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_EVP_LIB);
1730             EVP_PKEY_free(key);
1731             return 0;
1732         }
1733         s->s3->peer_tmp = key;
1734     } else {
1735         /* Set up EVP_PKEY with named curve as parameters */
1736         pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
1737         if (pctx == NULL
1738             || EVP_PKEY_paramgen_init(pctx) <= 0
1739             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, curve_nid) <= 0
1740             || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
1741             *al = SSL_AD_INTERNAL_ERROR;
1742             SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_EVP_LIB);
1743             EVP_PKEY_CTX_free(pctx);
1744             return 0;
1745         }
1746         EVP_PKEY_CTX_free(pctx);
1747         pctx = NULL;
1748     }
1749
1750     if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
1751         *al = SSL_AD_DECODE_ERROR;
1752         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_LENGTH_MISMATCH);
1753         return 0;
1754     }
1755
1756     if (!EVP_PKEY_set1_tls_encodedpoint(s->s3->peer_tmp,
1757                                         PACKET_data(&encoded_pt),
1758                                         PACKET_remaining(&encoded_pt))) {
1759         *al = SSL_AD_DECODE_ERROR;
1760         SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, SSL_R_BAD_ECPOINT);
1761         return 0;
1762     }
1763
1764     /*
1765      * The ECC/TLS specification does not mention the use of DSA to sign
1766      * ECParameters in the server key exchange message. We do support RSA
1767      * and ECDSA.
1768      */
1769     if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aECDSA)
1770         *pkey = X509_get0_pubkey(s->session->peer);
1771     else if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aRSA)
1772         *pkey = X509_get0_pubkey(s->session->peer);
1773     /* else anonymous ECDH, so no certificate or pkey. */
1774
1775     return 1;
1776 #else
1777     SSLerr(SSL_F_TLS_PROCESS_SKE_ECDHE, ERR_R_INTERNAL_ERROR);
1778     *al = SSL_AD_INTERNAL_ERROR;
1779     return 0;
1780 #endif
1781 }
1782
1783 MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
1784 {
1785     int al = -1;
1786     long alg_k;
1787     EVP_PKEY *pkey = NULL;
1788     PACKET save_param_start, signature;
1789
1790     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1791
1792     save_param_start = *pkt;
1793
1794 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1795     EVP_PKEY_free(s->s3->peer_tmp);
1796     s->s3->peer_tmp = NULL;
1797 #endif
1798
1799     if (alg_k & SSL_PSK) {
1800         if (!tls_process_ske_psk_preamble(s, pkt, &al))
1801             goto err;
1802     }
1803
1804     /* Nothing else to do for plain PSK or RSAPSK */
1805     if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
1806     } else if (alg_k & SSL_kSRP) {
1807         if (!tls_process_ske_srp(s, pkt, &pkey, &al))
1808             goto err;
1809     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
1810         if (!tls_process_ske_dhe(s, pkt, &pkey, &al))
1811             goto err;
1812     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
1813         if (!tls_process_ske_ecdhe(s, pkt, &pkey, &al))
1814             goto err;
1815     } else if (alg_k) {
1816         al = SSL_AD_UNEXPECTED_MESSAGE;
1817         SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1818         goto err;
1819     }
1820
1821     /* if it was signed, check the signature */
1822     if (pkey != NULL) {
1823         PACKET params;
1824         int maxsig;
1825         const EVP_MD *md = NULL;
1826         EVP_MD_CTX *md_ctx;
1827
1828         /*
1829          * |pkt| now points to the beginning of the signature, so the difference
1830          * equals the length of the parameters.
1831          */
1832         if (!PACKET_get_sub_packet(&save_param_start, &params,
1833                                    PACKET_remaining(&save_param_start) -
1834                                    PACKET_remaining(pkt))) {
1835             al = SSL_AD_INTERNAL_ERROR;
1836             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1837             goto err;
1838         }
1839
1840         if (SSL_USE_SIGALGS(s)) {
1841             const unsigned char *sigalgs;
1842             int rv;
1843             if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
1844                 al = SSL_AD_DECODE_ERROR;
1845                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1846                 goto err;
1847             }
1848             rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
1849             if (rv == -1) {
1850                 al = SSL_AD_INTERNAL_ERROR;
1851                 goto err;
1852             } else if (rv == 0) {
1853                 al = SSL_AD_DECODE_ERROR;
1854                 goto err;
1855             }
1856 #ifdef SSL_DEBUG
1857             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1858 #endif
1859         } else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
1860             md = EVP_md5_sha1();
1861         } else {
1862             md = EVP_sha1();
1863         }
1864
1865         if (!PACKET_get_length_prefixed_2(pkt, &signature)
1866             || PACKET_remaining(pkt) != 0) {
1867             al = SSL_AD_DECODE_ERROR;
1868             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
1869             goto err;
1870         }
1871         maxsig = EVP_PKEY_size(pkey);
1872         if (maxsig < 0) {
1873             al = SSL_AD_INTERNAL_ERROR;
1874             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1875             goto err;
1876         }
1877
1878         /*
1879          * Check signature length
1880          */
1881         if (PACKET_remaining(&signature) > (size_t)maxsig) {
1882             /* wrong packet length */
1883             al = SSL_AD_DECODE_ERROR;
1884             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
1885                    SSL_R_WRONG_SIGNATURE_LENGTH);
1886             goto err;
1887         }
1888
1889         md_ctx = EVP_MD_CTX_new();
1890         if (md_ctx == NULL) {
1891             al = SSL_AD_INTERNAL_ERROR;
1892             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1893             goto err;
1894         }
1895
1896         if (EVP_VerifyInit_ex(md_ctx, md, NULL) <= 0
1897             || EVP_VerifyUpdate(md_ctx, &(s->s3->client_random[0]),
1898                                 SSL3_RANDOM_SIZE) <= 0
1899             || EVP_VerifyUpdate(md_ctx, &(s->s3->server_random[0]),
1900                                 SSL3_RANDOM_SIZE) <= 0
1901             || EVP_VerifyUpdate(md_ctx, PACKET_data(&params),
1902                                 PACKET_remaining(&params)) <= 0) {
1903             EVP_MD_CTX_free(md_ctx);
1904             al = SSL_AD_INTERNAL_ERROR;
1905             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
1906             goto err;
1907         }
1908         /* TODO(size_t): Convert this call */
1909         if (EVP_VerifyFinal(md_ctx, PACKET_data(&signature),
1910                             (unsigned int)PACKET_remaining(&signature),
1911                             pkey) <= 0) {
1912             /* bad signature */
1913             EVP_MD_CTX_free(md_ctx);
1914             al = SSL_AD_DECRYPT_ERROR;
1915             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1916             goto err;
1917         }
1918         EVP_MD_CTX_free(md_ctx);
1919     } else {
1920         /* aNULL, aSRP or PSK do not need public keys */
1921         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1922             && !(alg_k & SSL_PSK)) {
1923             /* Might be wrong key type, check it */
1924             if (ssl3_check_cert_and_algorithm(s)) {
1925                 /* Otherwise this shouldn't happen */
1926                 al = SSL_AD_INTERNAL_ERROR;
1927                 SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1928             } else {
1929                 al = SSL_AD_DECODE_ERROR;
1930             }
1931             goto err;
1932         }
1933         /* still data left over */
1934         if (PACKET_remaining(pkt) != 0) {
1935             al = SSL_AD_DECODE_ERROR;
1936             SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1937             goto err;
1938         }
1939     }
1940
1941     return MSG_PROCESS_CONTINUE_READING;
1942  err:
1943     if (al != -1)
1944         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1945     ossl_statem_set_error(s);
1946     return MSG_PROCESS_ERROR;
1947 }
1948
1949 MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)
1950 {
1951     int ret = MSG_PROCESS_ERROR;
1952     unsigned int list_len, ctype_num, i, name_len;
1953     X509_NAME *xn = NULL;
1954     const unsigned char *data;
1955     const unsigned char *namestart, *namebytes;
1956     STACK_OF(X509_NAME) *ca_sk = NULL;
1957
1958     if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1959         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1960         goto err;
1961     }
1962
1963     /* get the certificate types */
1964     if (!PACKET_get_1(pkt, &ctype_num)
1965         || !PACKET_get_bytes(pkt, &data, ctype_num)) {
1966         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1967         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
1968         goto err;
1969     }
1970     OPENSSL_free(s->cert->ctypes);
1971     s->cert->ctypes = NULL;
1972     if (ctype_num > SSL3_CT_NUMBER) {
1973         /* If we exceed static buffer copy all to cert structure */
1974         s->cert->ctypes = OPENSSL_malloc(ctype_num);
1975         if (s->cert->ctypes == NULL) {
1976             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
1977             goto err;
1978         }
1979         memcpy(s->cert->ctypes, data, ctype_num);
1980         s->cert->ctype_num = ctype_num;
1981         ctype_num = SSL3_CT_NUMBER;
1982     }
1983     for (i = 0; i < ctype_num; i++)
1984         s->s3->tmp.ctype[i] = data[i];
1985
1986     if (SSL_USE_SIGALGS(s)) {
1987         if (!PACKET_get_net_2(pkt, &list_len)
1988             || !PACKET_get_bytes(pkt, &data, list_len)) {
1989             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1990             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
1991                    SSL_R_LENGTH_MISMATCH);
1992             goto err;
1993         }
1994
1995         /* Clear certificate digests and validity flags */
1996         for (i = 0; i < SSL_PKEY_NUM; i++) {
1997             s->s3->tmp.md[i] = NULL;
1998             s->s3->tmp.valid_flags[i] = 0;
1999         }
2000         if ((list_len & 1) || !tls1_save_sigalgs(s, data, list_len)) {
2001             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2002             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2003                    SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2004             goto err;
2005         }
2006         if (!tls1_process_sigalgs(s)) {
2007             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2008             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2009             goto err;
2010         }
2011     } else {
2012         ssl_set_default_md(s);
2013     }
2014
2015     /* get the CA RDNs */
2016     if (!PACKET_get_net_2(pkt, &list_len)
2017         || PACKET_remaining(pkt) != list_len) {
2018         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2019         SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
2020         goto err;
2021     }
2022
2023     while (PACKET_remaining(pkt)) {
2024         if (!PACKET_get_net_2(pkt, &name_len)
2025             || !PACKET_get_bytes(pkt, &namebytes, name_len)) {
2026             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2027             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2028                    SSL_R_LENGTH_MISMATCH);
2029             goto err;
2030         }
2031
2032         namestart = namebytes;
2033
2034         if ((xn = d2i_X509_NAME(NULL, (const unsigned char **)&namebytes,
2035                                 name_len)) == NULL) {
2036             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2037             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
2038             goto err;
2039         }
2040
2041         if (namebytes != (namestart + name_len)) {
2042             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2043             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST,
2044                    SSL_R_CA_DN_LENGTH_MISMATCH);
2045             goto err;
2046         }
2047         if (!sk_X509_NAME_push(ca_sk, xn)) {
2048             SSLerr(SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2049             goto err;
2050         }
2051         xn = NULL;
2052     }
2053
2054     /* we should setup a certificate to return.... */
2055     s->s3->tmp.cert_req = 1;
2056     s->s3->tmp.ctype_num = ctype_num;
2057     sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
2058     s->s3->tmp.ca_names = ca_sk;
2059     ca_sk = NULL;
2060
2061     ret = MSG_PROCESS_CONTINUE_PROCESSING;
2062     goto done;
2063  err:
2064     ossl_statem_set_error(s);
2065  done:
2066     X509_NAME_free(xn);
2067     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2068     return ret;
2069 }
2070
2071 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2072 {
2073     return (X509_NAME_cmp(*a, *b));
2074 }
2075
2076 MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL *s, PACKET *pkt)
2077 {
2078     int al;
2079     unsigned int ticklen;
2080     unsigned long ticket_lifetime_hint;
2081     unsigned int sess_len;
2082
2083     if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
2084         || !PACKET_get_net_2(pkt, &ticklen)
2085         || PACKET_remaining(pkt) != ticklen) {
2086         al = SSL_AD_DECODE_ERROR;
2087         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2088         goto f_err;
2089     }
2090
2091     /* Server is allowed to change its mind and send an empty ticket. */
2092     if (ticklen == 0)
2093         return MSG_PROCESS_CONTINUE_READING;
2094
2095     if (s->session->session_id_length > 0) {
2096         int i = s->session_ctx->session_cache_mode;
2097         SSL_SESSION *new_sess;
2098         /*
2099          * We reused an existing session, so we need to replace it with a new
2100          * one
2101          */
2102         if (i & SSL_SESS_CACHE_CLIENT) {
2103             /*
2104              * Remove the old session from the cache. We carry on if this fails
2105              */
2106             SSL_CTX_remove_session(s->session_ctx, s->session);
2107         }
2108
2109         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2110             al = SSL_AD_INTERNAL_ERROR;
2111             SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2112             goto f_err;
2113         }
2114
2115         SSL_SESSION_free(s->session);
2116         s->session = new_sess;
2117     }
2118
2119     OPENSSL_free(s->session->tlsext_tick);
2120     s->session->tlsext_ticklen = 0;
2121
2122     s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2123     if (s->session->tlsext_tick == NULL) {
2124         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2125         goto err;
2126     }
2127     if (!PACKET_copy_bytes(pkt, s->session->tlsext_tick, ticklen)) {
2128         al = SSL_AD_DECODE_ERROR;
2129         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2130         goto f_err;
2131     }
2132
2133     s->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
2134     s->session->tlsext_ticklen = ticklen;
2135     /*
2136      * There are two ways to detect a resumed ticket session. One is to set
2137      * an appropriate session ID and then the server must return a match in
2138      * ServerHello. This allows the normal client session ID matching to work
2139      * and we know much earlier that the ticket has been accepted. The
2140      * other way is to set zero length session ID when the ticket is
2141      * presented and rely on the handshake to determine session resumption.
2142      * We choose the former approach because this fits in with assumptions
2143      * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
2144      * SHA256 is disabled) hash of the ticket.
2145      */
2146     /*
2147      * TODO(size_t): we use sess_len here because EVP_Digest expects an int
2148      * but s->session->session_id_length is a size_t
2149      */
2150     if (!EVP_Digest(s->session->tlsext_tick, ticklen,
2151                     s->session->session_id, &sess_len,
2152                     EVP_sha256(), NULL)) {
2153         SSLerr(SSL_F_TLS_PROCESS_NEW_SESSION_TICKET, ERR_R_EVP_LIB);
2154         goto err;
2155     }
2156     s->session->session_id_length = sess_len;
2157     return MSG_PROCESS_CONTINUE_READING;
2158  f_err:
2159     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2160  err:
2161     ossl_statem_set_error(s);
2162     return MSG_PROCESS_ERROR;
2163 }
2164
2165 MSG_PROCESS_RETURN tls_process_cert_status(SSL *s, PACKET *pkt)
2166 {
2167     int al;
2168     size_t resplen;
2169     unsigned int type;
2170
2171     if (!PACKET_get_1(pkt, &type)
2172         || type != TLSEXT_STATUSTYPE_ocsp) {
2173         al = SSL_AD_DECODE_ERROR;
2174         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
2175         goto f_err;
2176     }
2177     if (!PACKET_get_net_3_len(pkt, &resplen)
2178         || PACKET_remaining(pkt) != resplen) {
2179         al = SSL_AD_DECODE_ERROR;
2180         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2181         goto f_err;
2182     }
2183     s->tlsext_ocsp_resp = OPENSSL_malloc(resplen);
2184     if (s->tlsext_ocsp_resp == NULL) {
2185         al = SSL_AD_INTERNAL_ERROR;
2186         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2187         goto f_err;
2188     }
2189     if (!PACKET_copy_bytes(pkt, s->tlsext_ocsp_resp, resplen)) {
2190         al = SSL_AD_DECODE_ERROR;
2191         SSLerr(SSL_F_TLS_PROCESS_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2192         goto f_err;
2193     }
2194     s->tlsext_ocsp_resplen = resplen;
2195     return MSG_PROCESS_CONTINUE_READING;
2196  f_err:
2197     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2198     ossl_statem_set_error(s);
2199     return MSG_PROCESS_ERROR;
2200 }
2201
2202 /*
2203  * Perform miscellaneous checks and processing after we have received the
2204  * server's initial flight. In TLS1.3 this is after the Server Finished message.
2205  * In <=TLS1.2 this is after the ServerDone message. Returns 1 on success or 0
2206  * on failure.
2207  */
2208 int tls_process_initial_server_flight(SSL *s, int *al)
2209 {
2210     /*
2211      * at this point we check that we have the required stuff from
2212      * the server
2213      */
2214     if (!ssl3_check_cert_and_algorithm(s)) {
2215         *al = SSL_AD_HANDSHAKE_FAILURE;
2216         return 0;
2217     }
2218
2219     /*
2220      * Call the ocsp status callback if needed. The |tlsext_ocsp_resp| and
2221      * |tlsext_ocsp_resplen| values will be set if we actually received a status
2222      * message, or NULL and -1 otherwise
2223      */
2224     if (s->tlsext_status_type != -1 && s->ctx->tlsext_status_cb != NULL) {
2225         int ret;
2226         ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2227         if (ret == 0) {
2228             *al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2229             SSLerr(SSL_F_TLS_PROCESS_INITIAL_SERVER_FLIGHT,
2230                    SSL_R_INVALID_STATUS_RESPONSE);
2231             return 0;
2232         }
2233         if (ret < 0) {
2234             *al = SSL_AD_INTERNAL_ERROR;
2235             SSLerr(SSL_F_TLS_PROCESS_INITIAL_SERVER_FLIGHT,
2236                    ERR_R_MALLOC_FAILURE);
2237             return 0;
2238         }
2239     }
2240 #ifndef OPENSSL_NO_CT
2241     if (s->ct_validation_callback != NULL) {
2242         /* Note we validate the SCTs whether or not we abort on error */
2243         if (!ssl_validate_ct(s) && (s->verify_mode & SSL_VERIFY_PEER)) {
2244             *al = SSL_AD_HANDSHAKE_FAILURE;
2245             return 0;
2246         }
2247     }
2248 #endif
2249
2250     return 1;
2251 }
2252
2253 MSG_PROCESS_RETURN tls_process_server_done(SSL *s, PACKET *pkt)
2254 {
2255     int al = SSL_AD_INTERNAL_ERROR;
2256
2257     if (PACKET_remaining(pkt) > 0) {
2258         /* should contain no data */
2259         al = SSL_AD_DECODE_ERROR;
2260         SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2261         goto err;
2262     }
2263 #ifndef OPENSSL_NO_SRP
2264     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2265         if (SRP_Calc_A_param(s) <= 0) {
2266             SSLerr(SSL_F_TLS_PROCESS_SERVER_DONE, SSL_R_SRP_A_CALC);
2267             goto err;
2268         }
2269     }
2270 #endif
2271
2272     /*
2273      * Error queue messages are generated directly by this function
2274      */
2275     if (!tls_process_initial_server_flight(s, &al))
2276         goto err;
2277
2278 #ifndef OPENSSL_NO_SCTP
2279     /* Only applies to renegotiation */
2280     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))
2281         && s->renegotiate != 0)
2282         return MSG_PROCESS_CONTINUE_PROCESSING;
2283     else
2284 #endif
2285         return MSG_PROCESS_FINISHED_READING;
2286
2287  err:
2288     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2289     ossl_statem_set_error(s);
2290     return MSG_PROCESS_ERROR;
2291 }
2292
2293 static int tls_construct_cke_psk_preamble(SSL *s, WPACKET *pkt, int *al)
2294 {
2295 #ifndef OPENSSL_NO_PSK
2296     int ret = 0;
2297     /*
2298      * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2299      * \0-terminated identity. The last byte is for us for simulating
2300      * strnlen.
2301      */
2302     char identity[PSK_MAX_IDENTITY_LEN + 1];
2303     size_t identitylen = 0;
2304     unsigned char psk[PSK_MAX_PSK_LEN];
2305     unsigned char *tmppsk = NULL;
2306     char *tmpidentity = NULL;
2307     size_t psklen = 0;
2308
2309     if (s->psk_client_callback == NULL) {
2310         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_CLIENT_CB);
2311         *al = SSL_AD_INTERNAL_ERROR;
2312         goto err;
2313     }
2314
2315     memset(identity, 0, sizeof(identity));
2316
2317     psklen = s->psk_client_callback(s, s->session->psk_identity_hint,
2318                                     identity, sizeof(identity) - 1,
2319                                     psk, sizeof(psk));
2320
2321     if (psklen > PSK_MAX_PSK_LEN) {
2322         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2323         *al = SSL_AD_HANDSHAKE_FAILURE;
2324         goto err;
2325     } else if (psklen == 0) {
2326         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE,
2327                SSL_R_PSK_IDENTITY_NOT_FOUND);
2328         *al = SSL_AD_HANDSHAKE_FAILURE;
2329         goto err;
2330     }
2331
2332     identitylen = strlen(identity);
2333     if (identitylen > PSK_MAX_IDENTITY_LEN) {
2334         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2335         *al = SSL_AD_HANDSHAKE_FAILURE;
2336         goto err;
2337     }
2338
2339     tmppsk = OPENSSL_memdup(psk, psklen);
2340     tmpidentity = OPENSSL_strdup(identity);
2341     if (tmppsk == NULL || tmpidentity == NULL) {
2342         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2343         *al = SSL_AD_INTERNAL_ERROR;
2344         goto err;
2345     }
2346
2347     OPENSSL_free(s->s3->tmp.psk);
2348     s->s3->tmp.psk = tmppsk;
2349     s->s3->tmp.psklen = psklen;
2350     tmppsk = NULL;
2351     OPENSSL_free(s->session->psk_identity);
2352     s->session->psk_identity = tmpidentity;
2353     tmpidentity = NULL;
2354
2355     if (!WPACKET_sub_memcpy_u16(pkt, identity, identitylen))  {
2356         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2357         *al = SSL_AD_INTERNAL_ERROR;
2358         goto err;
2359     }
2360
2361     ret = 1;
2362
2363  err:
2364     OPENSSL_cleanse(psk, psklen);
2365     OPENSSL_cleanse(identity, sizeof(identity));
2366     OPENSSL_clear_free(tmppsk, psklen);
2367     OPENSSL_clear_free(tmpidentity, identitylen);
2368
2369     return ret;
2370 #else
2371     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2372     *al = SSL_AD_INTERNAL_ERROR;
2373     return 0;
2374 #endif
2375 }
2376
2377 static int tls_construct_cke_rsa(SSL *s, WPACKET *pkt, int *al)
2378 {
2379 #ifndef OPENSSL_NO_RSA
2380     unsigned char *encdata = NULL;
2381     EVP_PKEY *pkey = NULL;
2382     EVP_PKEY_CTX *pctx = NULL;
2383     size_t enclen;
2384     unsigned char *pms = NULL;
2385     size_t pmslen = 0;
2386
2387     if (s->session->peer == NULL) {
2388         /*
2389          * We should always have a server certificate with SSL_kRSA.
2390          */
2391         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2392         return 0;
2393     }
2394
2395     pkey = X509_get0_pubkey(s->session->peer);
2396     if (EVP_PKEY_get0_RSA(pkey) == NULL) {
2397         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2398         return 0;
2399     }
2400
2401     pmslen = SSL_MAX_MASTER_KEY_LENGTH;
2402     pms = OPENSSL_malloc(pmslen);
2403     if (pms == NULL) {
2404         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_MALLOC_FAILURE);
2405         *al = SSL_AD_INTERNAL_ERROR;
2406         return 0;
2407     }
2408
2409     pms[0] = s->client_version >> 8;
2410     pms[1] = s->client_version & 0xff;
2411     /* TODO(size_t): Convert this function */
2412     if (RAND_bytes(pms + 2, (int)(pmslen - 2)) <= 0) {
2413         goto err;
2414     }
2415
2416     /* Fix buf for TLS and beyond */
2417     if (s->version > SSL3_VERSION && !WPACKET_start_sub_packet_u16(pkt)) {
2418         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2419         goto err;
2420     }
2421     pctx = EVP_PKEY_CTX_new(pkey, NULL);
2422     if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 0
2423         || EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {
2424         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_EVP_LIB);
2425         goto err;
2426     }
2427     if (!WPACKET_allocate_bytes(pkt, enclen, &encdata)
2428             || EVP_PKEY_encrypt(pctx, encdata, &enclen, pms, pmslen) <= 0) {
2429         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, SSL_R_BAD_RSA_ENCRYPT);
2430         goto err;
2431     }
2432     EVP_PKEY_CTX_free(pctx);
2433     pctx = NULL;
2434 # ifdef PKCS1_CHECK
2435     if (s->options & SSL_OP_PKCS1_CHECK_1)
2436         (*p)[1]++;
2437     if (s->options & SSL_OP_PKCS1_CHECK_2)
2438         tmp_buf[0] = 0x70;
2439 # endif
2440
2441     /* Fix buf for TLS and beyond */
2442     if (s->version > SSL3_VERSION && !WPACKET_close(pkt)) {
2443         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2444         goto err;
2445     }
2446
2447     s->s3->tmp.pms = pms;
2448     s->s3->tmp.pmslen = pmslen;
2449
2450     return 1;
2451  err:
2452     OPENSSL_clear_free(pms, pmslen);
2453     EVP_PKEY_CTX_free(pctx);
2454
2455     return 0;
2456 #else
2457     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_RSA, ERR_R_INTERNAL_ERROR);
2458     *al = SSL_AD_INTERNAL_ERROR;
2459     return 0;
2460 #endif
2461 }
2462
2463 static int tls_construct_cke_dhe(SSL *s, WPACKET *pkt, int *al)
2464 {
2465 #ifndef OPENSSL_NO_DH
2466     DH *dh_clnt = NULL;
2467     const BIGNUM *pub_key;
2468     EVP_PKEY *ckey = NULL, *skey = NULL;
2469     unsigned char *keybytes = NULL;
2470
2471     skey = s->s3->peer_tmp;
2472     if (skey == NULL)
2473         goto err;
2474
2475     ckey = ssl_generate_pkey(skey);
2476     if (ckey == NULL)
2477         goto err;
2478
2479     dh_clnt = EVP_PKEY_get0_DH(ckey);
2480
2481     if (dh_clnt == NULL || ssl_derive(s, ckey, skey, 0) == 0)
2482         goto err;
2483
2484     /* send off the data */
2485     DH_get0_key(dh_clnt, &pub_key, NULL);
2486     if (!WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(pub_key), &keybytes))
2487         goto err;
2488
2489     BN_bn2bin(pub_key, keybytes);
2490     EVP_PKEY_free(ckey);
2491
2492     return 1;
2493  err:
2494     EVP_PKEY_free(ckey);
2495 #endif
2496     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
2497     *al = SSL_AD_INTERNAL_ERROR;
2498     return 0;
2499 }
2500
2501 static int tls_construct_cke_ecdhe(SSL *s, WPACKET *pkt, int *al)
2502 {
2503 #ifndef OPENSSL_NO_EC
2504     unsigned char *encodedPoint = NULL;
2505     size_t encoded_pt_len = 0;
2506     EVP_PKEY *ckey = NULL, *skey = NULL;
2507     int ret = 0;
2508
2509     skey = s->s3->peer_tmp;
2510     if (skey == NULL) {
2511         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2512         return 0;
2513     }
2514
2515     ckey = ssl_generate_pkey(skey);
2516     if (ckey == NULL) {
2517         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_MALLOC_FAILURE);
2518         goto err;
2519     }
2520
2521     if (ssl_derive(s, ckey, skey, 0) == 0) {
2522         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);
2523         goto err;
2524     }
2525
2526     /* Generate encoding of client key */
2527     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);
2528
2529     if (encoded_pt_len == 0) {
2530         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);
2531         goto err;
2532     }
2533
2534     if (!WPACKET_sub_memcpy_u8(pkt, encodedPoint, encoded_pt_len)) {
2535         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2536         goto err;
2537     }
2538
2539     ret = 1;
2540  err:
2541     OPENSSL_free(encodedPoint);
2542     EVP_PKEY_free(ckey);
2543     return ret;
2544 #else
2545     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2546     *al = SSL_AD_INTERNAL_ERROR;
2547     return 0;
2548 #endif
2549 }
2550
2551 static int tls_construct_cke_gost(SSL *s, WPACKET *pkt, int *al)
2552 {
2553 #ifndef OPENSSL_NO_GOST
2554     /* GOST key exchange message creation */
2555     EVP_PKEY_CTX *pkey_ctx = NULL;
2556     X509 *peer_cert;
2557     size_t msglen;
2558     unsigned int md_len;
2559     unsigned char shared_ukm[32], tmp[256];
2560     EVP_MD_CTX *ukm_hash = NULL;
2561     int dgst_nid = NID_id_GostR3411_94;
2562     unsigned char *pms = NULL;
2563     size_t pmslen = 0;
2564
2565     if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
2566         dgst_nid = NID_id_GostR3411_2012_256;
2567
2568     /*
2569      * Get server sertificate PKEY and create ctx from it
2570      */
2571     peer_cert = s->session->peer;
2572     if (!peer_cert) {
2573         *al = SSL_AD_HANDSHAKE_FAILURE;
2574         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST,
2575                SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2576         return 0;
2577     }
2578
2579     pkey_ctx = EVP_PKEY_CTX_new(X509_get0_pubkey(peer_cert), NULL);
2580     if (pkey_ctx == NULL) {
2581         *al = SSL_AD_INTERNAL_ERROR;
2582         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);
2583         return 0;
2584     }
2585     /*
2586      * If we have send a certificate, and certificate key
2587      * parameters match those of server certificate, use
2588      * certificate key for key exchange
2589      */
2590
2591     /* Otherwise, generate ephemeral key pair */
2592     pmslen = 32;
2593     pms = OPENSSL_malloc(pmslen);
2594     if (pms == NULL) {
2595         *al = SSL_AD_INTERNAL_ERROR;
2596         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);
2597         goto err;
2598     }
2599
2600     if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0
2601         /* Generate session key
2602          * TODO(size_t): Convert this function
2603          */
2604         || RAND_bytes(pms, (int)pmslen) <= 0) {
2605         *al = SSL_AD_INTERNAL_ERROR;
2606         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2607         goto err;
2608     };
2609     /*
2610      * Compute shared IV and store it in algorithm-specific context
2611      * data
2612      */
2613     ukm_hash = EVP_MD_CTX_new();
2614     if (ukm_hash == NULL
2615         || EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 0
2616         || EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2617                             SSL3_RANDOM_SIZE) <= 0
2618         || EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2619                             SSL3_RANDOM_SIZE) <= 0
2620         || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
2621         *al = SSL_AD_INTERNAL_ERROR;
2622         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2623         goto err;
2624     }
2625     EVP_MD_CTX_free(ukm_hash);
2626     ukm_hash = NULL;
2627     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2628                           EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2629         *al = SSL_AD_INTERNAL_ERROR;
2630         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);
2631         goto err;
2632     }
2633     /* Make GOST keytransport blob message */
2634     /*
2635      * Encapsulate it into sequence
2636      */
2637     msglen = 255;
2638     if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
2639         *al = SSL_AD_INTERNAL_ERROR;
2640         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);
2641         goto err;
2642     }
2643
2644     if (!WPACKET_put_bytes_u8(pkt, V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)
2645             || (msglen >= 0x80 && !WPACKET_put_bytes_u8(pkt, 0x81))
2646             || !WPACKET_sub_memcpy_u8(pkt, tmp, msglen)) {
2647         *al = SSL_AD_INTERNAL_ERROR;
2648         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2649         goto err;
2650     }
2651
2652     EVP_PKEY_CTX_free(pkey_ctx);
2653     s->s3->tmp.pms = pms;
2654     s->s3->tmp.pmslen = pmslen;
2655
2656     return 1;
2657  err:
2658     EVP_PKEY_CTX_free(pkey_ctx);
2659     OPENSSL_clear_free(pms, pmslen);
2660     EVP_MD_CTX_free(ukm_hash);
2661     return 0;
2662 #else
2663     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);
2664     *al = SSL_AD_INTERNAL_ERROR;
2665     return 0;
2666 #endif
2667 }
2668
2669 static int tls_construct_cke_srp(SSL *s, WPACKET *pkt, int *al)
2670 {
2671 #ifndef OPENSSL_NO_SRP
2672     unsigned char *abytes = NULL;
2673
2674     if (s->srp_ctx.A == NULL
2675             || !WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(s->srp_ctx.A),
2676                                                &abytes)) {
2677         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_INTERNAL_ERROR);
2678         return 0;
2679     }
2680     BN_bn2bin(s->srp_ctx.A, abytes);
2681
2682     OPENSSL_free(s->session->srp_username);
2683     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2684     if (s->session->srp_username == NULL) {
2685         SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_MALLOC_FAILURE);
2686         return 0;
2687     }
2688
2689     return 1;
2690 #else
2691     SSLerr(SSL_F_TLS_CONSTRUCT_CKE_SRP, ERR_R_INTERNAL_ERROR);
2692     *al = SSL_AD_INTERNAL_ERROR;
2693     return 0;
2694 #endif
2695 }
2696
2697 int tls_construct_client_key_exchange(SSL *s, WPACKET *pkt)
2698 {
2699     unsigned long alg_k;
2700     int al = -1;
2701
2702     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2703
2704     if ((alg_k & SSL_PSK)
2705         && !tls_construct_cke_psk_preamble(s, pkt, &al))
2706         goto err;
2707
2708     if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2709         if (!tls_construct_cke_rsa(s, pkt, &al))
2710             goto err;
2711     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2712         if (!tls_construct_cke_dhe(s, pkt, &al))
2713             goto err;
2714     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2715         if (!tls_construct_cke_ecdhe(s, pkt, &al))
2716             goto err;
2717     } else if (alg_k & SSL_kGOST) {
2718         if (!tls_construct_cke_gost(s, pkt, &al))
2719             goto err;
2720     } else if (alg_k & SSL_kSRP) {
2721         if (!tls_construct_cke_srp(s, pkt, &al))
2722             goto err;
2723     } else if (!(alg_k & SSL_kPSK)) {
2724         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2725         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2726         goto err;
2727     }
2728
2729     return 1;
2730  err:
2731     if (al != -1)
2732         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2733     OPENSSL_clear_free(s->s3->tmp.pms, s->s3->tmp.pmslen);
2734     s->s3->tmp.pms = NULL;
2735 #ifndef OPENSSL_NO_PSK
2736     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2737     s->s3->tmp.psk = NULL;
2738 #endif
2739     return 0;
2740 }
2741
2742 int tls_client_key_exchange_post_work(SSL *s)
2743 {
2744     unsigned char *pms = NULL;
2745     size_t pmslen = 0;
2746
2747     pms = s->s3->tmp.pms;
2748     pmslen = s->s3->tmp.pmslen;
2749
2750 #ifndef OPENSSL_NO_SRP
2751     /* Check for SRP */
2752     if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
2753         if (!srp_generate_client_master_secret(s)) {
2754             SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK,
2755                    ERR_R_INTERNAL_ERROR);
2756             goto err;
2757         }
2758         return 1;
2759     }
2760 #endif
2761
2762     if (pms == NULL && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2763         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2764         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_MALLOC_FAILURE);
2765         goto err;
2766     }
2767     if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
2768         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2769         SSLerr(SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK, ERR_R_INTERNAL_ERROR);
2770         /* ssl_generate_master_secret frees the pms even on error */
2771         pms = NULL;
2772         pmslen = 0;
2773         goto err;
2774     }
2775     pms = NULL;
2776     pmslen = 0;
2777
2778 #ifndef OPENSSL_NO_SCTP
2779     if (SSL_IS_DTLS(s)) {
2780         unsigned char sctpauthkey[64];
2781         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2782
2783         /*
2784          * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2785          * used.
2786          */
2787         memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2788                sizeof(DTLS1_SCTP_AUTH_LABEL));
2789
2790         if (SSL_export_keying_material(s, sctpauthkey,
2791                                        sizeof(sctpauthkey), labelbuffer,
2792                                        sizeof(labelbuffer), NULL, 0, 0) <= 0)
2793             goto err;
2794
2795         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2796                  sizeof(sctpauthkey), sctpauthkey);
2797     }
2798 #endif
2799
2800     return 1;
2801  err:
2802     OPENSSL_clear_free(pms, pmslen);
2803     s->s3->tmp.pms = NULL;
2804     return 0;
2805 }
2806
2807 int tls_construct_client_verify(SSL *s, WPACKET *pkt)
2808 {
2809     EVP_PKEY *pkey;
2810     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
2811     EVP_MD_CTX *mctx = NULL;
2812     unsigned u = 0;
2813     long hdatalen = 0;
2814     void *hdata;
2815     unsigned char *sig = NULL;
2816
2817     mctx = EVP_MD_CTX_new();
2818     if (mctx == NULL) {
2819         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2820         goto err;
2821     }
2822     pkey = s->cert->key->privatekey;
2823
2824     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2825     if (hdatalen <= 0) {
2826         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2827         goto err;
2828     }
2829
2830     if (SSL_USE_SIGALGS(s)&& !tls12_get_sigandhash(pkt, pkey, md)) {
2831         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2832         goto err;
2833     }
2834 #ifdef SSL_DEBUG
2835     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
2836 #endif
2837     sig = OPENSSL_malloc(EVP_PKEY_size(pkey));
2838     if (sig == NULL) {
2839         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_MALLOC_FAILURE);
2840         goto err;
2841     }
2842     if (!EVP_SignInit_ex(mctx, md, NULL)
2843         || !EVP_SignUpdate(mctx, hdata, hdatalen)
2844         || (s->version == SSL3_VERSION
2845             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2846                                 (int)s->session->master_key_length,
2847                                 s->session->master_key))
2848         || !EVP_SignFinal(mctx, sig, &u, pkey)) {
2849         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_EVP_LIB);
2850         goto err;
2851     }
2852 #ifndef OPENSSL_NO_GOST
2853     {
2854         int pktype = EVP_PKEY_id(pkey);
2855         if (pktype == NID_id_GostR3410_2001
2856             || pktype == NID_id_GostR3410_2012_256
2857             || pktype == NID_id_GostR3410_2012_512)
2858             BUF_reverse(sig, NULL, u);
2859     }
2860 #endif
2861
2862     if (!WPACKET_sub_memcpy_u16(pkt, sig, u)) {
2863         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
2864         goto err;
2865     }
2866
2867     /* Digest cached records and discard handshake buffer */
2868     if (!ssl3_digest_cached_records(s, 0))
2869         goto err;
2870
2871     OPENSSL_free(sig);
2872     EVP_MD_CTX_free(mctx);
2873     return 1;
2874  err:
2875     OPENSSL_free(sig);
2876     EVP_MD_CTX_free(mctx);
2877     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2878     return 0;
2879 }
2880
2881 /*
2882  * Check a certificate can be used for client authentication. Currently check
2883  * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
2884  * certificates can be used and optionally checks suitability for Suite B.
2885  */
2886 static int ssl3_check_client_certificate(SSL *s)
2887 {
2888     if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2889         return 0;
2890     /* If no suitable signature algorithm can't use certificate */
2891     if (SSL_USE_SIGALGS(s) && !s->s3->tmp.md[s->cert->key - s->cert->pkeys])
2892         return 0;
2893     /*
2894      * If strict mode check suitability of chain before using it. This also
2895      * adjusts suite B digest if necessary.
2896      */
2897     if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2898         !tls1_check_chain(s, NULL, NULL, NULL, -2))
2899         return 0;
2900     return 1;
2901 }
2902
2903 WORK_STATE tls_prepare_client_certificate(SSL *s, WORK_STATE wst)
2904 {
2905     X509 *x509 = NULL;
2906     EVP_PKEY *pkey = NULL;
2907     int i;
2908
2909     if (wst == WORK_MORE_A) {
2910         /* Let cert callback update client certificates if required */
2911         if (s->cert->cert_cb) {
2912             i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2913             if (i < 0) {
2914                 s->rwstate = SSL_X509_LOOKUP;
2915                 return WORK_MORE_A;
2916             }
2917             if (i == 0) {
2918                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2919                 ossl_statem_set_error(s);
2920                 return 0;
2921             }
2922             s->rwstate = SSL_NOTHING;
2923         }
2924         if (ssl3_check_client_certificate(s))
2925             return WORK_FINISHED_CONTINUE;
2926
2927         /* Fall through to WORK_MORE_B */
2928         wst = WORK_MORE_B;
2929     }
2930
2931     /* We need to get a client cert */
2932     if (wst == WORK_MORE_B) {
2933         /*
2934          * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
2935          * return(-1); We then get retied later
2936          */
2937         i = ssl_do_client_cert_cb(s, &x509, &pkey);
2938         if (i < 0) {
2939             s->rwstate = SSL_X509_LOOKUP;
2940             return WORK_MORE_B;
2941         }
2942         s->rwstate = SSL_NOTHING;
2943         if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2944             if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
2945                 i = 0;
2946         } else if (i == 1) {
2947             i = 0;
2948             SSLerr(SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE,
2949                    SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2950         }
2951
2952         X509_free(x509);
2953         EVP_PKEY_free(pkey);
2954         if (i && !ssl3_check_client_certificate(s))
2955             i = 0;
2956         if (i == 0) {
2957             if (s->version == SSL3_VERSION) {
2958                 s->s3->tmp.cert_req = 0;
2959                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
2960                 return WORK_FINISHED_CONTINUE;
2961             } else {
2962                 s->s3->tmp.cert_req = 2;
2963                 if (!ssl3_digest_cached_records(s, 0)) {
2964                     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2965                     ossl_statem_set_error(s);
2966                     return 0;
2967                 }
2968             }
2969         }
2970
2971         return WORK_FINISHED_CONTINUE;
2972     }
2973
2974     /* Shouldn't ever get here */
2975     return WORK_ERROR;
2976 }
2977
2978 int tls_construct_client_certificate(SSL *s, WPACKET *pkt)
2979 {
2980     if (!ssl3_output_cert_chain(s, pkt,
2981                                (s->s3->tmp.cert_req == 2) ? NULL
2982                                                           : s->cert->key)) {
2983         SSLerr(SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2984         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2985         return 0;
2986     }
2987
2988     return 1;
2989 }
2990
2991 #define has_bits(i,m)   (((i)&(m)) == (m))
2992
2993 int ssl3_check_cert_and_algorithm(SSL *s)
2994 {
2995     int i;
2996 #ifndef OPENSSL_NO_EC
2997     int idx;
2998 #endif
2999     long alg_k, alg_a;
3000     EVP_PKEY *pkey = NULL;
3001     int al = SSL_AD_HANDSHAKE_FAILURE;
3002
3003     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3004     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3005
3006     /* we don't have a certificate */
3007     if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK))
3008         return (1);
3009
3010     /* This is the passed certificate */
3011
3012 #ifndef OPENSSL_NO_EC
3013     idx = s->session->peer_type;
3014     if (idx == SSL_PKEY_ECC) {
3015         if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s) == 0) {
3016             /* check failed */
3017             SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
3018             goto f_err;
3019         } else {
3020             return 1;
3021         }
3022     } else if (alg_a & SSL_aECDSA) {
3023         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3024                SSL_R_MISSING_ECDSA_SIGNING_CERT);
3025         goto f_err;
3026     }
3027 #endif
3028     pkey = X509_get0_pubkey(s->session->peer);
3029     i = X509_certificate_type(s->session->peer, pkey);
3030
3031     /* Check that we have a certificate if we require one */
3032     if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
3033         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3034                SSL_R_MISSING_RSA_SIGNING_CERT);
3035         goto f_err;
3036     }
3037 #ifndef OPENSSL_NO_DSA
3038     else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
3039         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3040                SSL_R_MISSING_DSA_SIGNING_CERT);
3041         goto f_err;
3042     }
3043 #endif
3044 #ifndef OPENSSL_NO_RSA
3045     if (alg_k & (SSL_kRSA | SSL_kRSAPSK) &&
3046         !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3047         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3048                SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3049         goto f_err;
3050     }
3051 #endif
3052 #ifndef OPENSSL_NO_DH
3053     if ((alg_k & SSL_kDHE) && (s->s3->peer_tmp == NULL)) {
3054         al = SSL_AD_INTERNAL_ERROR;
3055         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3056         goto f_err;
3057     }
3058 #endif
3059
3060     return (1);
3061  f_err:
3062     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3063     return (0);
3064 }
3065
3066 #ifndef OPENSSL_NO_NEXTPROTONEG
3067 int tls_construct_next_proto(SSL *s, WPACKET *pkt)
3068 {
3069     size_t len, padding_len;
3070     unsigned char *padding = NULL;
3071
3072     len = s->next_proto_negotiated_len;
3073     padding_len = 32 - ((len + 2) % 32);
3074
3075     if (!WPACKET_sub_memcpy_u8(pkt, s->next_proto_negotiated, len)
3076             || !WPACKET_sub_allocate_bytes_u8(pkt, padding_len, &padding)) {
3077         SSLerr(SSL_F_TLS_CONSTRUCT_NEXT_PROTO, ERR_R_INTERNAL_ERROR);
3078         goto err;
3079     }
3080
3081     memset(padding, 0, padding_len);
3082
3083     return 1;
3084  err:
3085     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3086     return 0;
3087 }
3088 #endif
3089
3090 static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL *s, PACKET *pkt)
3091 {
3092     int al = SSL_AD_INTERNAL_ERROR;
3093     PACKET extensions;
3094
3095     /* TODO(TLS1.3): We need to process these extensions. For now ignore them */
3096     if (!PACKET_as_length_prefixed_2(pkt, &extensions)) {
3097         al = SSL_AD_DECODE_ERROR;
3098         SSLerr(SSL_F_TLS_PROCESS_ENCRYPTED_EXTENSIONS, SSL_R_LENGTH_MISMATCH);
3099         goto err;
3100     }
3101
3102     return MSG_PROCESS_CONTINUE_READING;
3103
3104  err:
3105     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3106     ossl_statem_set_error(s);
3107     return MSG_PROCESS_ERROR;
3108 }
3109
3110 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3111 {
3112     int i = 0;
3113 #ifndef OPENSSL_NO_ENGINE
3114     if (s->ctx->client_cert_engine) {
3115         i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3116                                         SSL_get_client_CA_list(s),
3117                                         px509, ppkey, NULL, NULL, NULL);
3118         if (i != 0)
3119             return i;
3120     }
3121 #endif
3122     if (s->ctx->client_cert_cb)
3123         i = s->ctx->client_cert_cb(s, px509, ppkey);
3124     return i;
3125 }
3126
3127 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk, WPACKET *pkt)
3128 {
3129     int i;
3130     size_t totlen = 0, len, maxlen;
3131     int empty_reneg_info_scsv = !s->renegotiate;
3132     /* Set disabled masks for this session */
3133     ssl_set_client_disabled(s);
3134
3135     if (sk == NULL)
3136         return (0);
3137
3138 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
3139 # if OPENSSL_MAX_TLS1_2_CIPHER_LENGTH < 6
3140 #  error Max cipher length too short
3141 # endif
3142     /*
3143      * Some servers hang if client hello > 256 bytes as hack workaround
3144      * chop number of supported ciphers to keep it well below this if we
3145      * use TLS v1.2
3146      */
3147     if (TLS1_get_version(s) >= TLS1_2_VERSION)
3148         maxlen = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
3149     else
3150 #endif
3151         /* Maximum length that can be stored in 2 bytes. Length must be even */
3152         maxlen = 0xfffe;
3153
3154     if (empty_reneg_info_scsv)
3155         maxlen -= 2;
3156     if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV)
3157         maxlen -= 2;
3158
3159     for (i = 0; i < sk_SSL_CIPHER_num(sk) && totlen < maxlen; i++) {
3160         const SSL_CIPHER *c;
3161
3162         c = sk_SSL_CIPHER_value(sk, i);
3163         /* Skip disabled ciphers */
3164         if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED))
3165             continue;
3166
3167         if (!s->method->put_cipher_by_char(c, pkt, &len)) {
3168             SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3169             return 0;
3170         }
3171
3172         totlen += len;
3173     }
3174
3175     if (totlen == 0) {
3176         SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, SSL_R_NO_CIPHERS_AVAILABLE);
3177         return 0;
3178     }
3179
3180     if (totlen != 0) {
3181         if (empty_reneg_info_scsv) {
3182             static SSL_CIPHER scsv = {
3183                 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3184             };
3185             if (!s->method->put_cipher_by_char(&scsv, pkt, &len)) {
3186                 SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3187                 return 0;
3188             }
3189         }
3190         if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
3191             static SSL_CIPHER scsv = {
3192                 0, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
3193             };
3194             if (!s->method->put_cipher_by_char(&scsv, pkt, &len)) {
3195                 SSLerr(SSL_F_SSL_CIPHER_LIST_TO_BYTES, ERR_R_INTERNAL_ERROR);
3196                 return 0;
3197             }
3198         }
3199     }
3200
3201     return 1;
3202 }