01804458fa11ddefc89b25a7095488659589ec44
[openssl.git] / ssl / statem / statem_lib.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  * ECC cipher suite support in OpenSSL originally developed by
13  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
14  */
15
16 #include <limits.h>
17 #include <string.h>
18 #include <stdio.h>
19 #include "../ssl_locl.h"
20 #include "statem_locl.h"
21 #include <openssl/buffer.h>
22 #include <openssl/objects.h>
23 #include <openssl/evp.h>
24 #include <openssl/x509.h>
25
26 /*
27  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
28  * SSL3_RT_CHANGE_CIPHER_SPEC)
29  */
30 int ssl3_do_write(SSL *s, int type)
31 {
32     int ret;
33     size_t written = 0;
34
35     ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
36                            s->init_num, &written);
37     if (ret < 0)
38         return (-1);
39     if (type == SSL3_RT_HANDSHAKE)
40         /*
41          * should not be done for 'Hello Request's, but in that case we'll
42          * ignore the result anyway
43          */
44         if (!ssl3_finish_mac(s,
45                              (unsigned char *)&s->init_buf->data[s->init_off],
46                              written))
47             return -1;
48
49     if (written == s->init_num) {
50         if (s->msg_callback)
51             s->msg_callback(1, s->version, type, s->init_buf->data,
52                             (size_t)(s->init_off + s->init_num), s,
53                             s->msg_callback_arg);
54         return (1);
55     }
56     s->init_off += written;
57     s->init_num -= written;
58     return (0);
59 }
60
61 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
62 {
63     size_t msglen;
64
65     if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
66             || !WPACKET_get_length(pkt, &msglen)
67             || msglen > INT_MAX)
68         return 0;
69     s->init_num = (int)msglen;
70     s->init_off = 0;
71
72     return 1;
73 }
74
75 int tls_setup_handshake(SSL *s)
76 {
77     if (!ssl3_init_finished_mac(s))
78         return 0;
79
80     if (s->server) {
81         if (SSL_IS_FIRST_HANDSHAKE(s)) {
82             s->ctx->stats.sess_accept++;
83         } else if (!s->s3->send_connection_binding &&
84                    !(s->options &
85                      SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
86             /*
87              * Server attempting to renegotiate with client that doesn't
88              * support secure renegotiation.
89              */
90             SSLerr(SSL_F_TLS_SETUP_HANDSHAKE,
91                    SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
92             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
93             return 0;
94         } else {
95             s->ctx->stats.sess_accept_renegotiate++;
96
97             s->s3->tmp.cert_request = 0;
98         }
99     } else {
100         if (SSL_IS_FIRST_HANDSHAKE(s))
101             s->ctx->stats.sess_connect++;
102         else
103             s->ctx->stats.sess_connect_renegotiate++;
104
105         /* mark client_random uninitialized */
106         memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
107         s->hit = 0;
108
109         s->s3->tmp.cert_req = 0;
110
111         if (SSL_IS_DTLS(s))
112             s->statem.use_timer = 1;
113     }
114
115     return 1;
116 }
117
118 /*
119  * Size of the to-be-signed TLS13 data, without the hash size itself:
120  * 64 bytes of value 32, 33 context bytes, 1 byte separator
121  */
122 #define TLS13_TBS_START_SIZE            64
123 #define TLS13_TBS_PREAMBLE_SIZE         (TLS13_TBS_START_SIZE + 33 + 1)
124
125 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
126                                     void **hdata, size_t *hdatalen)
127 {
128     static const char *servercontext = "TLS 1.3, server CertificateVerify";
129     static const char *clientcontext = "TLS 1.3, client CertificateVerify";
130
131     if (SSL_IS_TLS13(s)) {
132         size_t hashlen;
133
134         /* Set the first 64 bytes of to-be-signed data to octet 32 */
135         memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
136         /* This copies the 33 bytes of context plus the 0 separator byte */
137         if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
138                  || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
139             strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
140         else
141             strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
142
143         /*
144          * If we're currently reading then we need to use the saved handshake
145          * hash value. We can't use the current handshake hash state because
146          * that includes the CertVerify itself.
147          */
148         if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
149                 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
150             memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
151                    s->cert_verify_hash_len);
152             hashlen = s->cert_verify_hash_len;
153         } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
154                                        EVP_MAX_MD_SIZE, &hashlen)) {
155             return 0;
156         }
157
158         *hdata = tls13tbs;
159         *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
160     } else {
161         size_t retlen;
162
163         retlen = BIO_get_mem_data(s->s3->handshake_buffer, hdata);
164         if (retlen <= 0)
165             return 0;
166         *hdatalen = retlen;
167     }
168
169     return 1;
170 }
171
172 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
173 {
174     EVP_PKEY *pkey = NULL;
175     const EVP_MD *md = NULL;
176     EVP_MD_CTX *mctx = NULL;
177     EVP_PKEY_CTX *pctx = NULL;
178     size_t hdatalen = 0, siglen = 0;
179     void *hdata;
180     unsigned char *sig = NULL;
181     unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
182     const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
183
184     if (lu == NULL || s->s3->tmp.cert == NULL) {
185         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
186         goto err;
187     }
188     pkey = s->s3->tmp.cert->privatekey;
189     md = ssl_md(lu->hash_idx);
190
191     if (pkey == NULL || md == NULL) {
192         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
193         goto err;
194     }
195
196     mctx = EVP_MD_CTX_new();
197     if (mctx == NULL) {
198         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
199         goto err;
200     }
201
202     /* Get the data to be signed */
203     if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
204         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
205         goto err;
206     }
207
208     if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
209         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
210         goto err;
211     }
212     siglen = EVP_PKEY_size(pkey);
213     sig = OPENSSL_malloc(siglen);
214     if (sig == NULL) {
215         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
216         goto err;
217     }
218
219     if (EVP_DigestSignInit(mctx, &pctx, md, NULL, pkey) <= 0
220             || EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0) {
221         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
222         goto err;
223     }
224
225     if (lu->sig == EVP_PKEY_RSA_PSS) {
226         if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
227             || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
228                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
229             SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
230             goto err;
231         }
232     } else if (s->version == SSL3_VERSION) {
233         if (!EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
234                              (int)s->session->master_key_length,
235                              s->session->master_key)) {
236             SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
237             goto err;
238         }
239     }
240
241     if (EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
242         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
243         goto err;
244     }
245
246 #ifndef OPENSSL_NO_GOST
247     {
248         int pktype = lu->sig;
249
250         if (pktype == NID_id_GostR3410_2001
251             || pktype == NID_id_GostR3410_2012_256
252             || pktype == NID_id_GostR3410_2012_512)
253             BUF_reverse(sig, NULL, siglen);
254     }
255 #endif
256
257     if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
258         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
259         goto err;
260     }
261
262     /* Digest cached records and discard handshake buffer */
263     if (!ssl3_digest_cached_records(s, 0))
264         goto err;
265
266     OPENSSL_free(sig);
267     EVP_MD_CTX_free(mctx);
268     return 1;
269  err:
270     OPENSSL_free(sig);
271     EVP_MD_CTX_free(mctx);
272     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
273     return 0;
274 }
275
276 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
277 {
278     EVP_PKEY *pkey = NULL;
279     const unsigned char *data;
280 #ifndef OPENSSL_NO_GOST
281     unsigned char *gost_data = NULL;
282 #endif
283     int al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
284     int type = 0, j;
285     unsigned int len;
286     X509 *peer;
287     const EVP_MD *md = NULL;
288     size_t hdatalen = 0;
289     void *hdata;
290     unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
291     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
292     EVP_PKEY_CTX *pctx = NULL;
293
294     if (mctx == NULL) {
295         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
296         goto f_err;
297     }
298
299     peer = s->session->peer;
300     pkey = X509_get0_pubkey(peer);
301     if (pkey == NULL) {
302         al = SSL_AD_INTERNAL_ERROR;
303         goto f_err;
304     }
305
306     type = X509_certificate_type(peer, pkey);
307
308     if (!(type & EVP_PKT_SIGN)) {
309         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
310                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
311         al = SSL_AD_ILLEGAL_PARAMETER;
312         goto f_err;
313     }
314
315     /* Check for broken implementations of GOST ciphersuites */
316     /*
317      * If key is GOST and n is exactly 64, it is bare signature without
318      * length field (CryptoPro implementations at least till CSP 4.0)
319      */
320 #ifndef OPENSSL_NO_GOST
321     if (PACKET_remaining(pkt) == 64
322         && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
323         len = 64;
324     } else
325 #endif
326     {
327         if (SSL_USE_SIGALGS(s)) {
328             int rv;
329             unsigned int sigalg;
330
331             if (!PACKET_get_net_2(pkt, &sigalg)) {
332                 al = SSL_AD_DECODE_ERROR;
333                 goto f_err;
334             }
335             rv = tls12_check_peer_sigalg(s, sigalg, pkey);
336             if (rv == -1) {
337                 goto f_err;
338             } else if (rv == 0) {
339                 al = SSL_AD_DECODE_ERROR;
340                 goto f_err;
341             }
342 #ifdef SSL_DEBUG
343             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
344 #endif
345         } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
346                 al = SSL_AD_INTERNAL_ERROR;
347                 goto f_err;
348         }
349
350         md = ssl_md(s->s3->tmp.peer_sigalg->hash_idx);
351
352         if (!PACKET_get_net_2(pkt, &len)) {
353             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
354             al = SSL_AD_DECODE_ERROR;
355             goto f_err;
356         }
357     }
358     j = EVP_PKEY_size(pkey);
359     if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
360         || (PACKET_remaining(pkt) == 0)) {
361         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
362         al = SSL_AD_DECODE_ERROR;
363         goto f_err;
364     }
365     if (!PACKET_get_bytes(pkt, &data, len)) {
366         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
367         al = SSL_AD_DECODE_ERROR;
368         goto f_err;
369     }
370
371     if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
372         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
373         goto f_err;
374     }
375
376 #ifdef SSL_DEBUG
377     fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
378 #endif
379     if (EVP_DigestVerifyInit(mctx, &pctx, md, NULL, pkey) <= 0
380             || EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0) {
381         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
382         goto f_err;
383     }
384 #ifndef OPENSSL_NO_GOST
385     {
386         int pktype = EVP_PKEY_id(pkey);
387         if (pktype == NID_id_GostR3410_2001
388             || pktype == NID_id_GostR3410_2012_256
389             || pktype == NID_id_GostR3410_2012_512) {
390             if ((gost_data = OPENSSL_malloc(len)) == NULL) {
391                 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
392                 goto f_err;
393             }
394             BUF_reverse(gost_data, data, len);
395             data = gost_data;
396         }
397     }
398 #endif
399
400     if (SSL_USE_PSS(s)) {
401         if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
402             || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
403                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
404             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
405             goto f_err;
406         }
407     } else if (s->version == SSL3_VERSION
408         && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
409                             (int)s->session->master_key_length,
410                             s->session->master_key)) {
411         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
412         goto f_err;
413     }
414
415     if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
416         al = SSL_AD_DECRYPT_ERROR;
417         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
418         goto f_err;
419     }
420
421     ret = MSG_PROCESS_CONTINUE_READING;
422     if (0) {
423  f_err:
424         ssl3_send_alert(s, SSL3_AL_FATAL, al);
425         ossl_statem_set_error(s);
426     }
427     BIO_free(s->s3->handshake_buffer);
428     s->s3->handshake_buffer = NULL;
429     EVP_MD_CTX_free(mctx);
430 #ifndef OPENSSL_NO_GOST
431     OPENSSL_free(gost_data);
432 #endif
433     return ret;
434 }
435
436 int tls_construct_finished(SSL *s, WPACKET *pkt)
437 {
438     size_t finish_md_len;
439     const char *sender;
440     size_t slen;
441
442     /* This is a real handshake so make sure we clean it up at the end */
443     if (!s->server)
444         s->statem.cleanuphand = 1;
445
446     /*
447      * We only change the keys if we didn't already do this when we sent the
448      * client certificate
449      */
450     if (SSL_IS_TLS13(s)
451             && !s->server
452             && s->s3->tmp.cert_req == 0
453             && (!s->method->ssl3_enc->change_cipher_state(s,
454                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
455         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
456         goto err;
457     }
458
459     if (s->server) {
460         sender = s->method->ssl3_enc->server_finished_label;
461         slen = s->method->ssl3_enc->server_finished_label_len;
462     } else {
463         sender = s->method->ssl3_enc->client_finished_label;
464         slen = s->method->ssl3_enc->client_finished_label_len;
465     }
466
467     finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
468                                                           sender, slen,
469                                                           s->s3->tmp.finish_md);
470     if (finish_md_len == 0) {
471         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
472         goto err;
473     }
474
475     s->s3->tmp.finish_md_len = finish_md_len;
476
477     if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
478         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
479         goto err;
480     }
481
482     /*
483      * Log the master secret, if logging is enabled. We don't log it for
484      * TLSv1.3: there's a different key schedule for that.
485      */
486     if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
487                                             s->session->master_key,
488                                             s->session->master_key_length))
489         return 0;
490
491     /*
492      * Copy the finished so we can use it for renegotiation checks
493      */
494     if (!s->server) {
495         OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
496         memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
497                finish_md_len);
498         s->s3->previous_client_finished_len = finish_md_len;
499     } else {
500         OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
501         memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
502                finish_md_len);
503         s->s3->previous_server_finished_len = finish_md_len;
504     }
505
506     return 1;
507  err:
508     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
509     return 0;
510 }
511
512 int tls_construct_key_update(SSL *s, WPACKET *pkt)
513 {
514     if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
515         SSLerr(SSL_F_TLS_CONSTRUCT_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
516         goto err;
517     }
518
519     s->key_update = SSL_KEY_UPDATE_NONE;
520     return 1;
521
522  err:
523     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
524     return 0;
525 }
526
527 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
528 {
529     int al;
530     unsigned int updatetype;
531
532     s->key_update_count++;
533     if (s->key_update_count > MAX_KEY_UPDATE_MESSAGES) {
534         al = SSL_AD_ILLEGAL_PARAMETER;
535         SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_TOO_MANY_KEY_UPDATES);
536         goto err;
537     }
538
539     /*
540      * A KeyUpdate message signals a key change so the end of the message must
541      * be on a record boundary.
542      */
543     if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
544         al = SSL_AD_UNEXPECTED_MESSAGE;
545         SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_NOT_ON_RECORD_BOUNDARY);
546         goto err;
547     }
548
549     if (!PACKET_get_1(pkt, &updatetype)
550             || PACKET_remaining(pkt) != 0
551             || (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
552                 && updatetype != SSL_KEY_UPDATE_REQUESTED)) {
553         al = SSL_AD_DECODE_ERROR;
554         SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, SSL_R_BAD_KEY_UPDATE);
555         goto err;
556     }
557
558     /*
559      * If we get a request for us to update our sending keys too then, we need
560      * to additionally send a KeyUpdate message. However that message should
561      * not also request an update (otherwise we get into an infinite loop).
562      */
563     if (updatetype == SSL_KEY_UPDATE_REQUESTED)
564         s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
565
566     if (!tls13_update_key(s, 0)) {
567         al = SSL_AD_INTERNAL_ERROR;
568         SSLerr(SSL_F_TLS_PROCESS_KEY_UPDATE, ERR_R_INTERNAL_ERROR);
569         goto err;
570     }
571
572     return MSG_PROCESS_FINISHED_READING;
573  err:
574     ssl3_send_alert(s, SSL3_AL_FATAL, al);
575     ossl_statem_set_error(s);
576     return MSG_PROCESS_ERROR;
577 }
578
579 #ifndef OPENSSL_NO_NEXTPROTONEG
580 /*
581  * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
582  * to far.
583  */
584 static void ssl3_take_mac(SSL *s)
585 {
586     const char *sender;
587     size_t slen;
588     /*
589      * If no new cipher setup return immediately: other functions will set
590      * the appropriate error.
591      */
592     if (s->s3->tmp.new_cipher == NULL)
593         return;
594     if (!s->server) {
595         sender = s->method->ssl3_enc->server_finished_label;
596         slen = s->method->ssl3_enc->server_finished_label_len;
597     } else {
598         sender = s->method->ssl3_enc->client_finished_label;
599         slen = s->method->ssl3_enc->client_finished_label_len;
600     }
601
602     s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
603                                                                           sender,
604                                                                           slen,
605                                                                           s->s3->tmp.peer_finish_md);
606 }
607 #endif
608
609 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
610 {
611     int al;
612     size_t remain;
613
614     remain = PACKET_remaining(pkt);
615     /*
616      * 'Change Cipher Spec' is just a single byte, which should already have
617      * been consumed by ssl_get_message() so there should be no bytes left,
618      * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
619      */
620     if (SSL_IS_DTLS(s)) {
621         if ((s->version == DTLS1_BAD_VER
622              && remain != DTLS1_CCS_HEADER_LENGTH + 1)
623             || (s->version != DTLS1_BAD_VER
624                 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
625             al = SSL_AD_ILLEGAL_PARAMETER;
626             SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
627                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
628             goto f_err;
629         }
630     } else {
631         if (remain != 0) {
632             al = SSL_AD_ILLEGAL_PARAMETER;
633             SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
634                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
635             goto f_err;
636         }
637     }
638
639     /* Check we have a cipher to change to */
640     if (s->s3->tmp.new_cipher == NULL) {
641         al = SSL_AD_UNEXPECTED_MESSAGE;
642         SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
643         goto f_err;
644     }
645
646     s->s3->change_cipher_spec = 1;
647     if (!ssl3_do_change_cipher_spec(s)) {
648         al = SSL_AD_INTERNAL_ERROR;
649         SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
650         goto f_err;
651     }
652
653     if (SSL_IS_DTLS(s)) {
654         dtls1_reset_seq_numbers(s, SSL3_CC_READ);
655
656         if (s->version == DTLS1_BAD_VER)
657             s->d1->handshake_read_seq++;
658
659 #ifndef OPENSSL_NO_SCTP
660         /*
661          * Remember that a CCS has been received, so that an old key of
662          * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
663          * SCTP is used
664          */
665         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
666 #endif
667     }
668
669     return MSG_PROCESS_CONTINUE_READING;
670  f_err:
671     ssl3_send_alert(s, SSL3_AL_FATAL, al);
672     ossl_statem_set_error(s);
673     return MSG_PROCESS_ERROR;
674 }
675
676 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
677 {
678     int al = SSL_AD_INTERNAL_ERROR;
679     size_t md_len;
680
681
682     /* This is a real handshake so make sure we clean it up at the end */
683     if (s->server)
684         s->statem.cleanuphand = 1;
685
686     /*
687      * In TLSv1.3 a Finished message signals a key change so the end of the
688      * message must be on a record boundary.
689      */
690     if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
691         al = SSL_AD_UNEXPECTED_MESSAGE;
692         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_NOT_ON_RECORD_BOUNDARY);
693         goto f_err;
694     }
695
696     /* If this occurs, we have missed a message */
697     if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
698         al = SSL_AD_UNEXPECTED_MESSAGE;
699         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
700         goto f_err;
701     }
702     s->s3->change_cipher_spec = 0;
703
704     md_len = s->s3->tmp.peer_finish_md_len;
705
706     if (md_len != PACKET_remaining(pkt)) {
707         al = SSL_AD_DECODE_ERROR;
708         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
709         goto f_err;
710     }
711
712     if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
713                       md_len) != 0) {
714         al = SSL_AD_DECRYPT_ERROR;
715         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
716         goto f_err;
717     }
718
719     /*
720      * Copy the finished so we can use it for renegotiation checks
721      */
722     if (s->server) {
723         OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
724         memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
725                md_len);
726         s->s3->previous_client_finished_len = md_len;
727     } else {
728         OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
729         memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
730                md_len);
731         s->s3->previous_server_finished_len = md_len;
732     }
733
734     /*
735      * In TLS1.3 we also have to change cipher state and do any final processing
736      * of the initial server flight (if we are a client)
737      */
738     if (SSL_IS_TLS13(s)) {
739         if (s->server) {
740             if (!s->method->ssl3_enc->change_cipher_state(s,
741                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
742                 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
743                 goto f_err;
744             }
745         } else {
746             if (!s->method->ssl3_enc->generate_master_secret(s,
747                     s->master_secret, s->handshake_secret, 0,
748                     &s->session->master_key_length)) {
749                 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
750                 goto f_err;
751             }
752             if (!s->method->ssl3_enc->change_cipher_state(s,
753                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
754                 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
755                 goto f_err;
756             }
757             if (!tls_process_initial_server_flight(s, &al))
758                 goto f_err;
759         }
760     }
761
762     return MSG_PROCESS_FINISHED_READING;
763  f_err:
764     ssl3_send_alert(s, SSL3_AL_FATAL, al);
765     ossl_statem_set_error(s);
766     return MSG_PROCESS_ERROR;
767 }
768
769 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
770 {
771     if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
772         SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
773         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
774         return 0;
775     }
776
777     return 1;
778 }
779
780 /* Add a certificate to the WPACKET */
781 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain,
782                                    int *al)
783 {
784     int len;
785     unsigned char *outbytes;
786
787     len = i2d_X509(x, NULL);
788     if (len < 0) {
789         SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_BUF_LIB);
790         *al = SSL_AD_INTERNAL_ERROR;
791         return 0;
792     }
793     if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
794             || i2d_X509(x, &outbytes) != len) {
795         SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_INTERNAL_ERROR);
796         *al = SSL_AD_INTERNAL_ERROR;
797         return 0;
798     }
799
800     if (SSL_IS_TLS13(s)
801             && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
802                                          chain, al))
803         return 0;
804
805     return 1;
806 }
807
808 /* Add certificate chain to provided WPACKET */
809 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk, int *al)
810 {
811     int i, chain_count;
812     X509 *x;
813     STACK_OF(X509) *extra_certs;
814     STACK_OF(X509) *chain = NULL;
815     X509_STORE *chain_store;
816     int tmpal = SSL_AD_INTERNAL_ERROR;
817
818     if (cpk == NULL || cpk->x509 == NULL)
819         return 1;
820
821     x = cpk->x509;
822
823     /*
824      * If we have a certificate specific chain use it, else use parent ctx.
825      */
826     if (cpk->chain != NULL)
827         extra_certs = cpk->chain;
828     else
829         extra_certs = s->ctx->extra_certs;
830
831     if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
832         chain_store = NULL;
833     else if (s->cert->chain_store)
834         chain_store = s->cert->chain_store;
835     else
836         chain_store = s->ctx->cert_store;
837
838     if (chain_store != NULL) {
839         X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
840
841         if (xs_ctx == NULL) {
842             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
843             goto err;
844         }
845         if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
846             X509_STORE_CTX_free(xs_ctx);
847             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
848             goto err;
849         }
850         /*
851          * It is valid for the chain not to be complete (because normally we
852          * don't include the root cert in the chain). Therefore we deliberately
853          * ignore the error return from this call. We're not actually verifying
854          * the cert - we're just building as much of the chain as we can
855          */
856         (void)X509_verify_cert(xs_ctx);
857         /* Don't leave errors in the queue */
858         ERR_clear_error();
859         chain = X509_STORE_CTX_get0_chain(xs_ctx);
860         i = ssl_security_cert_chain(s, chain, NULL, 0);
861         if (i != 1) {
862 #if 0
863             /* Dummy error calls so mkerr generates them */
864             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
865             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
866             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
867 #endif
868             X509_STORE_CTX_free(xs_ctx);
869             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
870             goto err;
871         }
872         chain_count = sk_X509_num(chain);
873         for (i = 0; i < chain_count; i++) {
874             x = sk_X509_value(chain, i);
875
876             if (!ssl_add_cert_to_wpacket(s, pkt, x, i, &tmpal)) {
877                 X509_STORE_CTX_free(xs_ctx);
878                 goto err;
879             }
880         }
881         X509_STORE_CTX_free(xs_ctx);
882     } else {
883         i = ssl_security_cert_chain(s, extra_certs, x, 0);
884         if (i != 1) {
885             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
886             goto err;
887         }
888         if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, &tmpal))
889             goto err;
890         for (i = 0; i < sk_X509_num(extra_certs); i++) {
891             x = sk_X509_value(extra_certs, i);
892             if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, &tmpal))
893                 goto err;
894         }
895     }
896     return 1;
897
898  err:
899     *al = tmpal;
900     return 0;
901 }
902
903 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk,
904                                      int *al)
905 {
906     int tmpal = SSL_AD_INTERNAL_ERROR;
907
908     if (!WPACKET_start_sub_packet_u24(pkt)
909             || !ssl_add_cert_chain(s, pkt, cpk, &tmpal)
910             || !WPACKET_close(pkt)) {
911         SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
912         *al = tmpal;
913         return 0;
914     }
915     return 1;
916 }
917
918 /*
919  * Tidy up after the end of a handshake. In the case of SCTP this may result
920  * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
921  * freed up as well.
922  */
923 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs)
924 {
925     void (*cb) (const SSL *ssl, int type, int val) = NULL;
926
927 #ifndef OPENSSL_NO_SCTP
928     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
929         WORK_STATE ret;
930         ret = dtls_wait_for_dry(s);
931         if (ret != WORK_FINISHED_CONTINUE)
932             return ret;
933     }
934 #endif
935
936     if (clearbufs) {
937         if (!SSL_IS_DTLS(s)) {
938             /*
939              * We don't do this in DTLS because we may still need the init_buf
940              * in case there are any unexpected retransmits
941              */
942             BUF_MEM_free(s->init_buf);
943             s->init_buf = NULL;
944         }
945         ssl_free_wbio_buffer(s);
946         s->init_num = 0;
947     }
948
949     if (s->statem.cleanuphand) {
950         /* skipped if we just sent a HelloRequest */
951         s->renegotiate = 0;
952         s->new_session = 0;
953         s->statem.cleanuphand = 0;
954
955         ssl3_cleanup_key_block(s);
956
957         if (s->server) {
958             ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
959
960             s->ctx->stats.sess_accept_good++;
961             s->handshake_func = ossl_statem_accept;
962         } else {
963             ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
964             if (s->hit)
965                 s->ctx->stats.sess_hit++;
966
967             s->handshake_func = ossl_statem_connect;
968             s->ctx->stats.sess_connect_good++;
969         }
970
971         if (s->info_callback != NULL)
972             cb = s->info_callback;
973         else if (s->ctx->info_callback != NULL)
974             cb = s->ctx->info_callback;
975
976         if (cb != NULL)
977             cb(s, SSL_CB_HANDSHAKE_DONE, 1);
978
979         if (SSL_IS_DTLS(s)) {
980             /* done with handshaking */
981             s->d1->handshake_read_seq = 0;
982             s->d1->handshake_write_seq = 0;
983             s->d1->next_handshake_write_seq = 0;
984             dtls1_clear_received_buffer(s);
985         }
986     }
987
988     /*
989      * If we've not cleared the buffers its because we've got more work to do,
990      * so continue.
991      */
992     if (!clearbufs)
993         return WORK_FINISHED_CONTINUE;
994
995     ossl_statem_set_in_init(s, 0);
996     return WORK_FINISHED_STOP;
997 }
998
999 int tls_get_message_header(SSL *s, int *mt)
1000 {
1001     /* s->init_num < SSL3_HM_HEADER_LENGTH */
1002     int skip_message, i, recvd_type, al;
1003     unsigned char *p;
1004     size_t l, readbytes;
1005
1006     p = (unsigned char *)s->init_buf->data;
1007
1008     do {
1009         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1010             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1011                                           &p[s->init_num],
1012                                           SSL3_HM_HEADER_LENGTH - s->init_num,
1013                                           0, &readbytes);
1014             if (i <= 0) {
1015                 s->rwstate = SSL_READING;
1016                 return 0;
1017             }
1018             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1019                 /*
1020                  * A ChangeCipherSpec must be a single byte and may not occur
1021                  * in the middle of a handshake message.
1022                  */
1023                 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1024                     al = SSL_AD_UNEXPECTED_MESSAGE;
1025                     SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
1026                            SSL_R_BAD_CHANGE_CIPHER_SPEC);
1027                     goto f_err;
1028                 }
1029                 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1030                 s->init_num = readbytes - 1;
1031                 s->init_msg = s->init_buf->data;
1032                 s->s3->tmp.message_size = readbytes;
1033                 return 1;
1034             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1035                 al = SSL_AD_UNEXPECTED_MESSAGE;
1036                 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
1037                 goto f_err;
1038             }
1039             s->init_num += readbytes;
1040         }
1041
1042         skip_message = 0;
1043         if (!s->server)
1044             if (s->statem.hand_state != TLS_ST_OK
1045                     && p[0] == SSL3_MT_HELLO_REQUEST)
1046                 /*
1047                  * The server may always send 'Hello Request' messages --
1048                  * we are doing a handshake anyway now, so ignore them if
1049                  * their format is correct. Does not count for 'Finished'
1050                  * MAC.
1051                  */
1052                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1053                     s->init_num = 0;
1054                     skip_message = 1;
1055
1056                     if (s->msg_callback)
1057                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1058                                         p, SSL3_HM_HEADER_LENGTH, s,
1059                                         s->msg_callback_arg);
1060                 }
1061     } while (skip_message);
1062     /* s->init_num == SSL3_HM_HEADER_LENGTH */
1063
1064     *mt = *p;
1065     s->s3->tmp.message_type = *(p++);
1066
1067     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1068         /*
1069          * Only happens with SSLv3+ in an SSLv2 backward compatible
1070          * ClientHello
1071          *
1072          * Total message size is the remaining record bytes to read
1073          * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1074          */
1075         l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1076             + SSL3_HM_HEADER_LENGTH;
1077         s->s3->tmp.message_size = l;
1078
1079         s->init_msg = s->init_buf->data;
1080         s->init_num = SSL3_HM_HEADER_LENGTH;
1081     } else {
1082         n2l3(p, l);
1083         /* BUF_MEM_grow takes an 'int' parameter */
1084         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1085             al = SSL_AD_ILLEGAL_PARAMETER;
1086             SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1087             goto f_err;
1088         }
1089         s->s3->tmp.message_size = l;
1090
1091         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1092         s->init_num = 0;
1093     }
1094
1095     return 1;
1096  f_err:
1097     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1098     return 0;
1099 }
1100
1101 int tls_get_message_body(SSL *s, size_t *len)
1102 {
1103     size_t n, readbytes;
1104     unsigned char *p;
1105     int i;
1106
1107     if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1108         /* We've already read everything in */
1109         *len = (unsigned long)s->init_num;
1110         return 1;
1111     }
1112
1113     p = s->init_msg;
1114     n = s->s3->tmp.message_size - s->init_num;
1115     while (n > 0) {
1116         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1117                                       &p[s->init_num], n, 0, &readbytes);
1118         if (i <= 0) {
1119             s->rwstate = SSL_READING;
1120             *len = 0;
1121             return 0;
1122         }
1123         s->init_num += readbytes;
1124         n -= readbytes;
1125     }
1126
1127 #ifndef OPENSSL_NO_NEXTPROTONEG
1128     /*
1129      * If receiving Finished, record MAC of prior handshake messages for
1130      * Finished verification.
1131      */
1132     if (*s->init_buf->data == SSL3_MT_FINISHED)
1133         ssl3_take_mac(s);
1134 #endif
1135
1136     /* Feed this message into MAC computation. */
1137     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1138         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1139                              s->init_num)) {
1140             SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1141             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1142             *len = 0;
1143             return 0;
1144         }
1145         if (s->msg_callback)
1146             s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1147                             (size_t)s->init_num, s, s->msg_callback_arg);
1148     } else {
1149         /*
1150          * We defer feeding in the HRR until later. We'll do it as part of
1151          * processing the message
1152          */
1153         if (s->s3->tmp.message_type != SSL3_MT_HELLO_RETRY_REQUEST
1154                 && !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1155                                     s->init_num + SSL3_HM_HEADER_LENGTH)) {
1156             SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
1157             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1158             *len = 0;
1159             return 0;
1160         }
1161         if (s->msg_callback)
1162             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1163                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1164                             s->msg_callback_arg);
1165     }
1166
1167     *len = s->init_num;
1168     return 1;
1169 }
1170
1171 int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
1172 {
1173     if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
1174         return -1;
1175
1176     switch (EVP_PKEY_id(pk)) {
1177     default:
1178         return -1;
1179     case EVP_PKEY_RSA:
1180         return SSL_PKEY_RSA;
1181     case EVP_PKEY_DSA:
1182         return SSL_PKEY_DSA_SIGN;
1183 #ifndef OPENSSL_NO_EC
1184     case EVP_PKEY_EC:
1185         return SSL_PKEY_ECC;
1186 #endif
1187 #ifndef OPENSSL_NO_GOST
1188     case NID_id_GostR3410_2001:
1189         return SSL_PKEY_GOST01;
1190     case NID_id_GostR3410_2012_256:
1191         return SSL_PKEY_GOST12_256;
1192     case NID_id_GostR3410_2012_512:
1193         return SSL_PKEY_GOST12_512;
1194 #endif
1195     }
1196 }
1197
1198 int ssl_verify_alarm_type(long type)
1199 {
1200     int al;
1201
1202     switch (type) {
1203     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1204     case X509_V_ERR_UNABLE_TO_GET_CRL:
1205     case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1206         al = SSL_AD_UNKNOWN_CA;
1207         break;
1208     case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1209     case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1210     case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1211     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1212     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1213     case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1214     case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1215     case X509_V_ERR_CERT_NOT_YET_VALID:
1216     case X509_V_ERR_CRL_NOT_YET_VALID:
1217     case X509_V_ERR_CERT_UNTRUSTED:
1218     case X509_V_ERR_CERT_REJECTED:
1219     case X509_V_ERR_HOSTNAME_MISMATCH:
1220     case X509_V_ERR_EMAIL_MISMATCH:
1221     case X509_V_ERR_IP_ADDRESS_MISMATCH:
1222     case X509_V_ERR_DANE_NO_MATCH:
1223     case X509_V_ERR_EE_KEY_TOO_SMALL:
1224     case X509_V_ERR_CA_KEY_TOO_SMALL:
1225     case X509_V_ERR_CA_MD_TOO_WEAK:
1226         al = SSL_AD_BAD_CERTIFICATE;
1227         break;
1228     case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1229     case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1230         al = SSL_AD_DECRYPT_ERROR;
1231         break;
1232     case X509_V_ERR_CERT_HAS_EXPIRED:
1233     case X509_V_ERR_CRL_HAS_EXPIRED:
1234         al = SSL_AD_CERTIFICATE_EXPIRED;
1235         break;
1236     case X509_V_ERR_CERT_REVOKED:
1237         al = SSL_AD_CERTIFICATE_REVOKED;
1238         break;
1239     case X509_V_ERR_UNSPECIFIED:
1240     case X509_V_ERR_OUT_OF_MEM:
1241     case X509_V_ERR_INVALID_CALL:
1242     case X509_V_ERR_STORE_LOOKUP:
1243         al = SSL_AD_INTERNAL_ERROR;
1244         break;
1245     case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1246     case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1247     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1248     case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1249     case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1250     case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1251     case X509_V_ERR_INVALID_CA:
1252         al = SSL_AD_UNKNOWN_CA;
1253         break;
1254     case X509_V_ERR_APPLICATION_VERIFICATION:
1255         al = SSL_AD_HANDSHAKE_FAILURE;
1256         break;
1257     case X509_V_ERR_INVALID_PURPOSE:
1258         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1259         break;
1260     default:
1261         al = SSL_AD_CERTIFICATE_UNKNOWN;
1262         break;
1263     }
1264     return (al);
1265 }
1266
1267 int ssl_allow_compression(SSL *s)
1268 {
1269     if (s->options & SSL_OP_NO_COMPRESSION)
1270         return 0;
1271     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1272 }
1273
1274 static int version_cmp(const SSL *s, int a, int b)
1275 {
1276     int dtls = SSL_IS_DTLS(s);
1277
1278     if (a == b)
1279         return 0;
1280     if (!dtls)
1281         return a < b ? -1 : 1;
1282     return DTLS_VERSION_LT(a, b) ? -1 : 1;
1283 }
1284
1285 typedef struct {
1286     int version;
1287     const SSL_METHOD *(*cmeth) (void);
1288     const SSL_METHOD *(*smeth) (void);
1289 } version_info;
1290
1291 #if TLS_MAX_VERSION != TLS1_3_VERSION
1292 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1293 #endif
1294
1295 /* Must be in order high to low */
1296 static const version_info tls_version_table[] = {
1297 #ifndef OPENSSL_NO_TLS1_3
1298     {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1299 #else
1300     {TLS1_3_VERSION, NULL, NULL},
1301 #endif
1302 #ifndef OPENSSL_NO_TLS1_2
1303     {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1304 #else
1305     {TLS1_2_VERSION, NULL, NULL},
1306 #endif
1307 #ifndef OPENSSL_NO_TLS1_1
1308     {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1309 #else
1310     {TLS1_1_VERSION, NULL, NULL},
1311 #endif
1312 #ifndef OPENSSL_NO_TLS1
1313     {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1314 #else
1315     {TLS1_VERSION, NULL, NULL},
1316 #endif
1317 #ifndef OPENSSL_NO_SSL3
1318     {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1319 #else
1320     {SSL3_VERSION, NULL, NULL},
1321 #endif
1322     {0, NULL, NULL},
1323 };
1324
1325 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1326 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1327 #endif
1328
1329 /* Must be in order high to low */
1330 static const version_info dtls_version_table[] = {
1331 #ifndef OPENSSL_NO_DTLS1_2
1332     {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1333 #else
1334     {DTLS1_2_VERSION, NULL, NULL},
1335 #endif
1336 #ifndef OPENSSL_NO_DTLS1
1337     {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1338     {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1339 #else
1340     {DTLS1_VERSION, NULL, NULL},
1341     {DTLS1_BAD_VER, NULL, NULL},
1342 #endif
1343     {0, NULL, NULL},
1344 };
1345
1346 /*
1347  * ssl_method_error - Check whether an SSL_METHOD is enabled.
1348  *
1349  * @s: The SSL handle for the candidate method
1350  * @method: the intended method.
1351  *
1352  * Returns 0 on success, or an SSL error reason on failure.
1353  */
1354 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1355 {
1356     int version = method->version;
1357
1358     if ((s->min_proto_version != 0 &&
1359          version_cmp(s, version, s->min_proto_version) < 0) ||
1360         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1361         return SSL_R_VERSION_TOO_LOW;
1362
1363     if (s->max_proto_version != 0 &&
1364         version_cmp(s, version, s->max_proto_version) > 0)
1365         return SSL_R_VERSION_TOO_HIGH;
1366
1367     if ((s->options & method->mask) != 0)
1368         return SSL_R_UNSUPPORTED_PROTOCOL;
1369     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1370         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1371
1372     return 0;
1373 }
1374
1375 /*
1376  * ssl_version_supported - Check that the specified `version` is supported by
1377  * `SSL *` instance
1378  *
1379  * @s: The SSL handle for the candidate method
1380  * @version: Protocol version to test against
1381  *
1382  * Returns 1 when supported, otherwise 0
1383  */
1384 int ssl_version_supported(const SSL *s, int version)
1385 {
1386     const version_info *vent;
1387     const version_info *table;
1388
1389     switch (s->method->version) {
1390     default:
1391         /* Version should match method version for non-ANY method */
1392         return version_cmp(s, version, s->version) == 0;
1393     case TLS_ANY_VERSION:
1394         table = tls_version_table;
1395         break;
1396     case DTLS_ANY_VERSION:
1397         table = dtls_version_table;
1398         break;
1399     }
1400
1401     for (vent = table;
1402          vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1403          ++vent) {
1404         if (vent->cmeth != NULL &&
1405             version_cmp(s, version, vent->version) == 0 &&
1406             ssl_method_error(s, vent->cmeth()) == 0) {
1407             return 1;
1408         }
1409     }
1410     return 0;
1411 }
1412
1413 /*
1414  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1415  * fallback indication from a client check whether we're using the highest
1416  * supported protocol version.
1417  *
1418  * @s server SSL handle.
1419  *
1420  * Returns 1 when using the highest enabled version, 0 otherwise.
1421  */
1422 int ssl_check_version_downgrade(SSL *s)
1423 {
1424     const version_info *vent;
1425     const version_info *table;
1426
1427     /*
1428      * Check that the current protocol is the highest enabled version
1429      * (according to s->ctx->method, as version negotiation may have changed
1430      * s->method).
1431      */
1432     if (s->version == s->ctx->method->version)
1433         return 1;
1434
1435     /*
1436      * Apparently we're using a version-flexible SSL_METHOD (not at its
1437      * highest protocol version).
1438      */
1439     if (s->ctx->method->version == TLS_method()->version)
1440         table = tls_version_table;
1441     else if (s->ctx->method->version == DTLS_method()->version)
1442         table = dtls_version_table;
1443     else {
1444         /* Unexpected state; fail closed. */
1445         return 0;
1446     }
1447
1448     for (vent = table; vent->version != 0; ++vent) {
1449         if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1450             return s->version == vent->version;
1451     }
1452     return 0;
1453 }
1454
1455 /*
1456  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1457  * protocols, provided the initial (D)TLS method is version-flexible.  This
1458  * function sanity-checks the proposed value and makes sure the method is
1459  * version-flexible, then sets the limit if all is well.
1460  *
1461  * @method_version: The version of the current SSL_METHOD.
1462  * @version: the intended limit.
1463  * @bound: pointer to limit to be updated.
1464  *
1465  * Returns 1 on success, 0 on failure.
1466  */
1467 int ssl_set_version_bound(int method_version, int version, int *bound)
1468 {
1469     if (version == 0) {
1470         *bound = version;
1471         return 1;
1472     }
1473
1474     /*-
1475      * Restrict TLS methods to TLS protocol versions.
1476      * Restrict DTLS methods to DTLS protocol versions.
1477      * Note, DTLS version numbers are decreasing, use comparison macros.
1478      *
1479      * Note that for both lower-bounds we use explicit versions, not
1480      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
1481      * configurations.  If the MIN (supported) version ever rises, the user's
1482      * "floor" remains valid even if no longer available.  We don't expect the
1483      * MAX ceiling to ever get lower, so making that variable makes sense.
1484      */
1485     switch (method_version) {
1486     default:
1487         /*
1488          * XXX For fixed version methods, should we always fail and not set any
1489          * bounds, always succeed and not set any bounds, or set the bounds and
1490          * arrange to fail later if they are not met?  At present fixed-version
1491          * methods are not subject to controls that disable individual protocol
1492          * versions.
1493          */
1494         return 0;
1495
1496     case TLS_ANY_VERSION:
1497         if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1498             return 0;
1499         break;
1500
1501     case DTLS_ANY_VERSION:
1502         if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1503             DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1504             return 0;
1505         break;
1506     }
1507
1508     *bound = version;
1509     return 1;
1510 }
1511
1512 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1513 {
1514     if (vers == TLS1_2_VERSION
1515             && ssl_version_supported(s, TLS1_3_VERSION)) {
1516         *dgrd = DOWNGRADE_TO_1_2;
1517     } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1518             && (ssl_version_supported(s, TLS1_2_VERSION)
1519                 || ssl_version_supported(s, TLS1_3_VERSION))) {
1520         *dgrd = DOWNGRADE_TO_1_1;
1521     } else {
1522         *dgrd = DOWNGRADE_NONE;
1523     }
1524 }
1525
1526 /*
1527  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
1528  * client HELLO is received to select the final server protocol version and
1529  * the version specific method.
1530  *
1531  * @s: server SSL handle.
1532  *
1533  * Returns 0 on success or an SSL error reason number on failure.
1534  */
1535 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1536 {
1537     /*-
1538      * With version-flexible methods we have an initial state with:
1539      *
1540      *   s->method->version == (D)TLS_ANY_VERSION,
1541      *   s->version == (D)TLS_MAX_VERSION.
1542      *
1543      * So we detect version-flexible methods via the method version, not the
1544      * handle version.
1545      */
1546     int server_version = s->method->version;
1547     int client_version = hello->legacy_version;
1548     const version_info *vent;
1549     const version_info *table;
1550     int disabled = 0;
1551     RAW_EXTENSION *suppversions;
1552
1553     s->client_version = client_version;
1554
1555     switch (server_version) {
1556     default:
1557         if (!SSL_IS_TLS13(s)) {
1558             if (version_cmp(s, client_version, s->version) < 0)
1559                 return SSL_R_WRONG_SSL_VERSION;
1560             *dgrd = DOWNGRADE_NONE;
1561             /*
1562              * If this SSL handle is not from a version flexible method we don't
1563              * (and never did) check min/max FIPS or Suite B constraints.  Hope
1564              * that's OK.  It is up to the caller to not choose fixed protocol
1565              * versions they don't want.  If not, then easy to fix, just return
1566              * ssl_method_error(s, s->method)
1567              */
1568             return 0;
1569         }
1570         /*
1571          * Fall through if we are TLSv1.3 already (this means we must be after
1572          * a HelloRetryRequest
1573          */
1574     case TLS_ANY_VERSION:
1575         table = tls_version_table;
1576         break;
1577     case DTLS_ANY_VERSION:
1578         table = dtls_version_table;
1579         break;
1580     }
1581
1582     suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1583
1584     if (suppversions->present && !SSL_IS_DTLS(s)) {
1585         unsigned int candidate_vers = 0;
1586         unsigned int best_vers = 0;
1587         const SSL_METHOD *best_method = NULL;
1588         PACKET versionslist;
1589
1590         suppversions->parsed = 1;
1591
1592         if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1593             /* Trailing or invalid data? */
1594             return SSL_R_LENGTH_MISMATCH;
1595         }
1596
1597         while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1598             /* TODO(TLS1.3): Remove this before release */
1599             if (candidate_vers == TLS1_3_VERSION_DRAFT)
1600                 candidate_vers = TLS1_3_VERSION;
1601             /*
1602              * TODO(TLS1.3): There is some discussion on the TLS list about
1603              * whether to ignore versions <TLS1.2 in supported_versions. At the
1604              * moment we honour them if present. To be reviewed later
1605              */
1606             if (version_cmp(s, candidate_vers, best_vers) <= 0)
1607                 continue;
1608             for (vent = table;
1609                  vent->version != 0 && vent->version != (int)candidate_vers;
1610                  ++vent)
1611                 continue;
1612             if (vent->version != 0 && vent->smeth != NULL) {
1613                 const SSL_METHOD *method;
1614
1615                 method = vent->smeth();
1616                 if (ssl_method_error(s, method) == 0) {
1617                     best_vers = candidate_vers;
1618                     best_method = method;
1619                 }
1620             }
1621         }
1622         if (PACKET_remaining(&versionslist) != 0) {
1623             /* Trailing data? */
1624             return SSL_R_LENGTH_MISMATCH;
1625         }
1626
1627         if (best_vers > 0) {
1628             if (SSL_IS_TLS13(s)) {
1629                 /*
1630                  * We get here if this is after a HelloRetryRequest. In this
1631                  * case we just check that we still negotiated TLSv1.3
1632                  */
1633                 if (best_vers != TLS1_3_VERSION)
1634                     return SSL_R_UNSUPPORTED_PROTOCOL;
1635                 return 0;
1636             }
1637             check_for_downgrade(s, best_vers, dgrd);
1638             s->version = best_vers;
1639             s->method = best_method;
1640             return 0;
1641         }
1642         return SSL_R_UNSUPPORTED_PROTOCOL;
1643     }
1644
1645     /*
1646      * If the supported versions extension isn't present, then the highest
1647      * version we can negotiate is TLSv1.2
1648      */
1649     if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1650         client_version = TLS1_2_VERSION;
1651
1652     /*
1653      * No supported versions extension, so we just use the version supplied in
1654      * the ClientHello.
1655      */
1656     for (vent = table; vent->version != 0; ++vent) {
1657         const SSL_METHOD *method;
1658
1659         if (vent->smeth == NULL ||
1660             version_cmp(s, client_version, vent->version) < 0)
1661             continue;
1662         method = vent->smeth();
1663         if (ssl_method_error(s, method) == 0) {
1664             check_for_downgrade(s, vent->version, dgrd);
1665             s->version = vent->version;
1666             s->method = method;
1667             return 0;
1668         }
1669         disabled = 1;
1670     }
1671     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1672 }
1673
1674 /*
1675  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
1676  * server HELLO is received to select the final client protocol version and
1677  * the version specific method.
1678  *
1679  * @s: client SSL handle.
1680  * @version: The proposed version from the server's HELLO.
1681  * @checkdgrd: Whether to check the downgrade sentinels in the server_random
1682  * @al: Where to store any alert value that may be generated
1683  *
1684  * Returns 0 on success or an SSL error reason number on failure.
1685  */
1686 int ssl_choose_client_version(SSL *s, int version, int checkdgrd, int *al)
1687 {
1688     const version_info *vent;
1689     const version_info *table;
1690     int highver = 0;
1691
1692     /* TODO(TLS1.3): Remove this before release */
1693     if (version == TLS1_3_VERSION_DRAFT)
1694         version = TLS1_3_VERSION;
1695
1696     if (s->hello_retry_request && version != TLS1_3_VERSION) {
1697         *al = SSL_AD_PROTOCOL_VERSION;
1698         return SSL_R_WRONG_SSL_VERSION;
1699     }
1700
1701     switch (s->method->version) {
1702     default:
1703         if (version != s->version) {
1704             *al = SSL_AD_PROTOCOL_VERSION;
1705             return SSL_R_WRONG_SSL_VERSION;
1706         }
1707         /*
1708          * If this SSL handle is not from a version flexible method we don't
1709          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
1710          * that's OK.  It is up to the caller to not choose fixed protocol
1711          * versions they don't want.  If not, then easy to fix, just return
1712          * ssl_method_error(s, s->method)
1713          */
1714         return 0;
1715     case TLS_ANY_VERSION:
1716         table = tls_version_table;
1717         break;
1718     case DTLS_ANY_VERSION:
1719         table = dtls_version_table;
1720         break;
1721     }
1722
1723     for (vent = table; vent->version != 0; ++vent) {
1724         const SSL_METHOD *method;
1725         int err;
1726
1727         if (vent->cmeth == NULL)
1728             continue;
1729
1730         if (highver != 0 && version != vent->version)
1731             continue;
1732
1733         method = vent->cmeth();
1734         err = ssl_method_error(s, method);
1735         if (err != 0) {
1736             if (version == vent->version) {
1737                 *al = SSL_AD_PROTOCOL_VERSION;
1738                 return err;
1739             }
1740
1741             continue;
1742         }
1743         if (highver == 0)
1744             highver = vent->version;
1745
1746         if (version != vent->version)
1747             continue;
1748
1749 #ifndef OPENSSL_NO_TLS13DOWNGRADE
1750         /* Check for downgrades */
1751         if (checkdgrd) {
1752             if (version == TLS1_2_VERSION && highver > version) {
1753                 if (memcmp(tls12downgrade,
1754                            s->s3->server_random + SSL3_RANDOM_SIZE
1755                                                 - sizeof(tls12downgrade),
1756                            sizeof(tls12downgrade)) == 0) {
1757                     *al = SSL_AD_ILLEGAL_PARAMETER;
1758                     return SSL_R_INAPPROPRIATE_FALLBACK;
1759                 }
1760             } else if (!SSL_IS_DTLS(s)
1761                        && version < TLS1_2_VERSION
1762                        && highver > version) {
1763                 if (memcmp(tls11downgrade,
1764                            s->s3->server_random + SSL3_RANDOM_SIZE
1765                                                 - sizeof(tls11downgrade),
1766                            sizeof(tls11downgrade)) == 0) {
1767                     *al = SSL_AD_ILLEGAL_PARAMETER;
1768                     return SSL_R_INAPPROPRIATE_FALLBACK;
1769                 }
1770             }
1771         }
1772 #endif
1773
1774         s->method = method;
1775         s->version = version;
1776         return 0;
1777     }
1778
1779     *al = SSL_AD_PROTOCOL_VERSION;
1780     return SSL_R_UNSUPPORTED_PROTOCOL;
1781 }
1782
1783 /*
1784  * ssl_get_client_min_max_version - get minimum and maximum client version
1785  * @s: The SSL connection
1786  * @min_version: The minimum supported version
1787  * @max_version: The maximum supported version
1788  *
1789  * Work out what version we should be using for the initial ClientHello if the
1790  * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
1791  * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1792  * constraints and any floor imposed by the security level here,
1793  * so we don't advertise the wrong protocol version to only reject the outcome later.
1794  *
1795  * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
1796  * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
1797  * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1798  *
1799  * Returns 0 on success or an SSL error reason number on failure.  On failure
1800  * min_version and max_version will also be set to 0.
1801  */
1802 int ssl_get_client_min_max_version(const SSL *s, int *min_version,
1803                                    int *max_version)
1804 {
1805     int version;
1806     int hole;
1807     const SSL_METHOD *single = NULL;
1808     const SSL_METHOD *method;
1809     const version_info *table;
1810     const version_info *vent;
1811
1812     switch (s->method->version) {
1813     default:
1814         /*
1815          * If this SSL handle is not from a version flexible method we don't
1816          * (and never did) check min/max FIPS or Suite B constraints.  Hope
1817          * that's OK.  It is up to the caller to not choose fixed protocol
1818          * versions they don't want.  If not, then easy to fix, just return
1819          * ssl_method_error(s, s->method)
1820          */
1821         *min_version = *max_version = s->version;
1822         return 0;
1823     case TLS_ANY_VERSION:
1824         table = tls_version_table;
1825         break;
1826     case DTLS_ANY_VERSION:
1827         table = dtls_version_table;
1828         break;
1829     }
1830
1831     /*
1832      * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1833      * below X enabled. This is required in order to maintain the "version
1834      * capability" vector contiguous. Any versions with a NULL client method
1835      * (protocol version client is disabled at compile-time) is also a "hole".
1836      *
1837      * Our initial state is hole == 1, version == 0.  That is, versions above
1838      * the first version in the method table are disabled (a "hole" above
1839      * the valid protocol entries) and we don't have a selected version yet.
1840      *
1841      * Whenever "hole == 1", and we hit an enabled method, its version becomes
1842      * the selected version, and the method becomes a candidate "single"
1843      * method.  We're no longer in a hole, so "hole" becomes 0.
1844      *
1845      * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1846      * as we support a contiguous range of at least two methods.  If we hit
1847      * a disabled method, then hole becomes true again, but nothing else
1848      * changes yet, because all the remaining methods may be disabled too.
1849      * If we again hit an enabled method after the new hole, it becomes
1850      * selected, as we start from scratch.
1851      */
1852     *min_version = version = 0;
1853     hole = 1;
1854     for (vent = table; vent->version != 0; ++vent) {
1855         /*
1856          * A table entry with a NULL client method is still a hole in the
1857          * "version capability" vector.
1858          */
1859         if (vent->cmeth == NULL) {
1860             hole = 1;
1861             continue;
1862         }
1863         method = vent->cmeth();
1864         if (ssl_method_error(s, method) != 0) {
1865             hole = 1;
1866         } else if (!hole) {
1867             single = NULL;
1868             *min_version = method->version;
1869         } else {
1870             version = (single = method)->version;
1871             *min_version = version;
1872             hole = 0;
1873         }
1874     }
1875
1876     *max_version = version;
1877
1878     /* Fail if everything is disabled */
1879     if (version == 0)
1880         return SSL_R_NO_PROTOCOLS_AVAILABLE;
1881
1882     return 0;
1883 }
1884
1885 /*
1886  * ssl_set_client_hello_version - Work out what version we should be using for
1887  * the initial ClientHello.legacy_version field.
1888  *
1889  * @s: client SSL handle.
1890  *
1891  * Returns 0 on success or an SSL error reason number on failure.
1892  */
1893 int ssl_set_client_hello_version(SSL *s)
1894 {
1895     int ver_min, ver_max, ret;
1896
1897     ret = ssl_get_client_min_max_version(s, &ver_min, &ver_max);
1898
1899     if (ret != 0)
1900         return ret;
1901
1902     s->version = ver_max;
1903
1904     /* TLS1.3 always uses TLS1.2 in the legacy_version field */
1905     if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
1906         ver_max = TLS1_2_VERSION;
1907
1908     s->client_version = ver_max;
1909     return 0;
1910 }
1911
1912 /*
1913  * Checks a list of |groups| to determine if the |group_id| is in it. If it is
1914  * and |checkallow| is 1 then additionally check if the group is allowed to be
1915  * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
1916  * 1) or 0 otherwise.
1917  */
1918 #ifndef OPENSSL_NO_EC
1919 int check_in_list(SSL *s, unsigned int group_id, const unsigned char *groups,
1920                   size_t num_groups, int checkallow)
1921 {
1922     size_t i;
1923
1924     if (groups == NULL || num_groups == 0)
1925         return 0;
1926
1927     for (i = 0; i < num_groups; i++, groups += 2) {
1928         unsigned int share_id = (groups[0] << 8) | (groups[1]);
1929
1930         if (group_id == share_id
1931                 && (!checkallow
1932                     || tls_curve_allowed(s, groups, SSL_SECOP_CURVE_CHECK))) {
1933             return 1;
1934         }
1935     }
1936
1937     return 0;
1938 }
1939 #endif
1940
1941 /* Replace ClientHello1 in the transcript hash with a synthetic message */
1942 int create_synthetic_message_hash(SSL *s)
1943 {
1944     unsigned char hashval[EVP_MAX_MD_SIZE];
1945     size_t hashlen = 0;
1946     unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
1947
1948     memset(msghdr, 0, sizeof(msghdr));
1949
1950     /* Get the hash of the initial ClientHello */
1951     if (!ssl3_digest_cached_records(s, 0)
1952             || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
1953         SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
1954         return 0;
1955     }
1956
1957     /* Reinitialise the transcript hash */
1958     if (!ssl3_init_finished_mac(s))
1959         return 0;
1960
1961     /* Inject the synthetic message_hash message */
1962     msghdr[0] = SSL3_MT_MESSAGE_HASH;
1963     msghdr[SSL3_HM_HEADER_LENGTH - 1] = hashlen;
1964     if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
1965             || !ssl3_finish_mac(s, hashval, hashlen)) {
1966         SSLerr(SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH, ERR_R_INTERNAL_ERROR);
1967         return 0;
1968     }
1969
1970     return 1;
1971 }
1972
1973 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
1974 {
1975     return X509_NAME_cmp(*a, *b);
1976 }
1977
1978 int parse_ca_names(SSL *s, PACKET *pkt, int *al)
1979 {
1980     STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
1981     X509_NAME *xn = NULL;
1982     PACKET cadns;
1983
1984     if (ca_sk == NULL) {
1985         SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
1986         goto decerr;
1987     }
1988     /* get the CA RDNs */
1989     if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
1990         *al = SSL_AD_DECODE_ERROR;
1991         SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
1992         goto decerr;
1993     }
1994
1995     while (PACKET_remaining(&cadns)) {
1996         const unsigned char *namestart, *namebytes;
1997         unsigned int name_len;
1998
1999         if (!PACKET_get_net_2(&cadns, &name_len)
2000             || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2001             SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_LENGTH_MISMATCH);
2002             goto decerr;
2003         }
2004
2005         namestart = namebytes;
2006         if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2007             SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_ASN1_LIB);
2008             goto decerr;
2009         }
2010         if (namebytes != (namestart + name_len)) {
2011             SSLerr(SSL_F_PARSE_CA_NAMES, SSL_R_CA_DN_LENGTH_MISMATCH);
2012             goto decerr;
2013         }
2014
2015         if (!sk_X509_NAME_push(ca_sk, xn)) {
2016             SSLerr(SSL_F_PARSE_CA_NAMES, ERR_R_MALLOC_FAILURE);
2017             *al = SSL_AD_INTERNAL_ERROR;
2018             goto err;
2019         }
2020         xn = NULL;
2021     }
2022
2023     sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
2024     s->s3->tmp.peer_ca_names = ca_sk;
2025
2026     return 1;
2027
2028  decerr:
2029     *al = SSL_AD_DECODE_ERROR;
2030  err:
2031     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2032     X509_NAME_free(xn);
2033     return 0;
2034 }
2035
2036 int construct_ca_names(SSL *s, WPACKET *pkt)
2037 {
2038     const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
2039
2040     /* Start sub-packet for client CA list */
2041     if (!WPACKET_start_sub_packet_u16(pkt))
2042         return 0;
2043
2044     if (ca_sk != NULL) {
2045         int i;
2046
2047         for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2048             unsigned char *namebytes;
2049             X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2050             int namelen;
2051
2052             if (name == NULL
2053                     || (namelen = i2d_X509_NAME(name, NULL)) < 0
2054                     || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2055                                                        &namebytes)
2056                     || i2d_X509_NAME(name, &namebytes) != namelen) {
2057                 return 0;
2058             }
2059         }
2060     }
2061
2062     if (!WPACKET_close(pkt))
2063         return 0;
2064
2065     return 1;
2066 }