120b2779321dba6d5404c6646761db5b02c33b2a
[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_construct_finished(SSL *s, WPACKET *pkt)
76 {
77     size_t finish_md_len;
78     const char *sender;
79     size_t slen;
80
81     if (s->server) {
82         sender = s->method->ssl3_enc->server_finished_label;
83         slen = s->method->ssl3_enc->server_finished_label_len;
84     } else {
85         sender = s->method->ssl3_enc->client_finished_label;
86         slen = s->method->ssl3_enc->client_finished_label_len;
87     }
88
89     finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
90                                                           sender, slen,
91                                                           s->s3->tmp.finish_md);
92     if (finish_md_len == 0) {
93         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
94         goto err;
95     }
96
97     s->s3->tmp.finish_md_len = finish_md_len;
98
99     if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
100         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
101         goto err;
102     }
103
104     /*
105      * Copy the finished so we can use it for renegotiation checks
106      */
107     if (!s->server) {
108         OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
109         memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
110                finish_md_len);
111         s->s3->previous_client_finished_len = finish_md_len;
112     } else {
113         OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
114         memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
115                finish_md_len);
116         s->s3->previous_server_finished_len = finish_md_len;
117     }
118
119     return 1;
120  err:
121     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
122     return 0;
123 }
124
125 #ifndef OPENSSL_NO_NEXTPROTONEG
126 /*
127  * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
128  * to far.
129  */
130 static void ssl3_take_mac(SSL *s)
131 {
132     const char *sender;
133     size_t slen;
134     /*
135      * If no new cipher setup return immediately: other functions will set
136      * the appropriate error.
137      */
138     if (s->s3->tmp.new_cipher == NULL)
139         return;
140     if (!s->server) {
141         sender = s->method->ssl3_enc->server_finished_label;
142         slen = s->method->ssl3_enc->server_finished_label_len;
143     } else {
144         sender = s->method->ssl3_enc->client_finished_label;
145         slen = s->method->ssl3_enc->client_finished_label_len;
146     }
147
148     s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
149                                                                           sender,
150                                                                           slen,
151                                                                           s->s3->tmp.peer_finish_md);
152 }
153 #endif
154
155 static int compare_extensions(const void *p1, const void *p2)
156 {
157     const RAW_EXTENSION *e1 = (const RAW_EXTENSION *)p1;
158     const RAW_EXTENSION *e2 = (const RAW_EXTENSION *)p2;
159
160     if (e1->type < e2->type)
161         return -1;
162     else if (e1->type > e2->type)
163         return 1;
164
165     return 0;
166 }
167
168 /*
169  * Gather a list of all the extensions. We don't actually process the content
170  * of the extensions yet, except to check their types.
171  *
172  * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
173  * more than one extension of the same type in a ClientHello or ServerHello.
174  * This function returns 1 if all extensions are unique and we have parsed their
175  * types, and 0 if the extensions contain duplicates, could not be successfully
176  * parsed, or an internal error occurred.
177  */
178 int tls_collect_extensions(PACKET *packet, RAW_EXTENSION **res,
179                              size_t *numfound, int *ad)
180 {
181     PACKET extensions = *packet;
182     size_t num_extensions = 0, i = 0;
183     RAW_EXTENSION *raw_extensions = NULL;
184
185     /* First pass: count the extensions. */
186     while (PACKET_remaining(&extensions) > 0) {
187         unsigned int type;
188         PACKET extension;
189
190         if (!PACKET_get_net_2(&extensions, &type) ||
191             !PACKET_get_length_prefixed_2(&extensions, &extension)) {
192             *ad = SSL_AD_DECODE_ERROR;
193             goto err;
194         }
195         num_extensions++;
196     }
197
198     if (num_extensions > 0) {
199         raw_extensions = OPENSSL_malloc(sizeof(*raw_extensions)
200                                         * num_extensions);
201         if (raw_extensions == NULL) {
202             *ad = SSL_AD_INTERNAL_ERROR;
203             SSLerr(SSL_F_TLS_PARSE_RAW_EXTENSIONS, ERR_R_MALLOC_FAILURE);
204             goto err;
205         }
206
207         /* Second pass: gather the extension types. */
208         for (i = 0; i < num_extensions; i++) {
209             if (!PACKET_get_net_2(packet, &raw_extensions[i].type) ||
210                 !PACKET_get_length_prefixed_2(packet,
211                                               &raw_extensions[i].data)) {
212                 /* This should not happen. */
213                 *ad = SSL_AD_INTERNAL_ERROR;
214                 SSLerr(SSL_F_TLS_PARSE_RAW_EXTENSIONS, ERR_R_INTERNAL_ERROR);
215                 goto err;
216             }
217         }
218
219         if (PACKET_remaining(packet) != 0) {
220             *ad = SSL_AD_DECODE_ERROR;
221             SSLerr(SSL_F_TLS_PARSE_RAW_EXTENSIONS, SSL_R_LENGTH_MISMATCH);
222             goto err;
223         }
224         /* Sort the extensions and make sure there are no duplicates. */
225         qsort(raw_extensions, num_extensions, sizeof(*raw_extensions),
226               compare_extensions);
227         for (i = 1; i < num_extensions; i++) {
228             if (raw_extensions[i - 1].type == raw_extensions[i].type) {
229                 *ad = SSL_AD_DECODE_ERROR;
230                 goto err;
231             }
232         }
233     }
234
235     *res = raw_extensions;
236     *numfound = num_extensions;
237     return 1;
238
239  err:
240     OPENSSL_free(raw_extensions);
241     return 0;
242 }
243
244
245
246 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
247 {
248     int al;
249     size_t remain;
250
251     remain = PACKET_remaining(pkt);
252     /*
253      * 'Change Cipher Spec' is just a single byte, which should already have
254      * been consumed by ssl_get_message() so there should be no bytes left,
255      * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
256      */
257     if (SSL_IS_DTLS(s)) {
258         if ((s->version == DTLS1_BAD_VER
259              && remain != DTLS1_CCS_HEADER_LENGTH + 1)
260             || (s->version != DTLS1_BAD_VER
261                 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
262             al = SSL_AD_ILLEGAL_PARAMETER;
263             SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
264                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
265             goto f_err;
266         }
267     } else {
268         if (remain != 0) {
269             al = SSL_AD_ILLEGAL_PARAMETER;
270             SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
271                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
272             goto f_err;
273         }
274     }
275
276     /* Check we have a cipher to change to */
277     if (s->s3->tmp.new_cipher == NULL) {
278         al = SSL_AD_UNEXPECTED_MESSAGE;
279         SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
280         goto f_err;
281     }
282
283     s->s3->change_cipher_spec = 1;
284     if (!ssl3_do_change_cipher_spec(s)) {
285         al = SSL_AD_INTERNAL_ERROR;
286         SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
287         goto f_err;
288     }
289
290     if (SSL_IS_DTLS(s)) {
291         dtls1_reset_seq_numbers(s, SSL3_CC_READ);
292
293         if (s->version == DTLS1_BAD_VER)
294             s->d1->handshake_read_seq++;
295
296 #ifndef OPENSSL_NO_SCTP
297         /*
298          * Remember that a CCS has been received, so that an old key of
299          * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
300          * SCTP is used
301          */
302         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
303 #endif
304     }
305
306     return MSG_PROCESS_CONTINUE_READING;
307  f_err:
308     ssl3_send_alert(s, SSL3_AL_FATAL, al);
309     ossl_statem_set_error(s);
310     return MSG_PROCESS_ERROR;
311 }
312
313 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
314 {
315     int al;
316     size_t md_len;
317
318     /* If this occurs, we have missed a message */
319     if (!s->s3->change_cipher_spec) {
320         al = SSL_AD_UNEXPECTED_MESSAGE;
321         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
322         goto f_err;
323     }
324     s->s3->change_cipher_spec = 0;
325
326     md_len = s->s3->tmp.peer_finish_md_len;
327
328     if (md_len != PACKET_remaining(pkt)) {
329         al = SSL_AD_DECODE_ERROR;
330         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
331         goto f_err;
332     }
333
334     if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
335                       md_len) != 0) {
336         al = SSL_AD_DECRYPT_ERROR;
337         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
338         goto f_err;
339     }
340
341     /*
342      * Copy the finished so we can use it for renegotiation checks
343      */
344     if (s->server) {
345         OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
346         memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
347                md_len);
348         s->s3->previous_client_finished_len = md_len;
349     } else {
350         OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
351         memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
352                md_len);
353         s->s3->previous_server_finished_len = md_len;
354     }
355
356     return MSG_PROCESS_FINISHED_READING;
357  f_err:
358     ssl3_send_alert(s, SSL3_AL_FATAL, al);
359     ossl_statem_set_error(s);
360     return MSG_PROCESS_ERROR;
361 }
362
363 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
364 {
365     if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
366         SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
367         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
368         return 0;
369     }
370
371     return 1;
372 }
373
374 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
375 {
376     if (!WPACKET_start_sub_packet_u24(pkt)
377             || !ssl_add_cert_chain(s, pkt, cpk)
378             || !WPACKET_close(pkt)) {
379         SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
380         return 0;
381     }
382     return 1;
383 }
384
385 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst)
386 {
387     void (*cb) (const SSL *ssl, int type, int val) = NULL;
388
389 #ifndef OPENSSL_NO_SCTP
390     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
391         WORK_STATE ret;
392         ret = dtls_wait_for_dry(s);
393         if (ret != WORK_FINISHED_CONTINUE)
394             return ret;
395     }
396 #endif
397
398     /* clean a few things up */
399     ssl3_cleanup_key_block(s);
400
401     if (!SSL_IS_DTLS(s)) {
402         /*
403          * We don't do this in DTLS because we may still need the init_buf
404          * in case there are any unexpected retransmits
405          */
406         BUF_MEM_free(s->init_buf);
407         s->init_buf = NULL;
408     }
409
410     ssl_free_wbio_buffer(s);
411
412     s->init_num = 0;
413
414     if (!s->server || s->renegotiate == 2) {
415         /* skipped if we just sent a HelloRequest */
416         s->renegotiate = 0;
417         s->new_session = 0;
418
419         if (s->server) {
420             ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
421
422             s->ctx->stats.sess_accept_good++;
423             s->handshake_func = ossl_statem_accept;
424         } else {
425             ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
426             if (s->hit)
427                 s->ctx->stats.sess_hit++;
428
429             s->handshake_func = ossl_statem_connect;
430             s->ctx->stats.sess_connect_good++;
431         }
432
433         if (s->info_callback != NULL)
434             cb = s->info_callback;
435         else if (s->ctx->info_callback != NULL)
436             cb = s->ctx->info_callback;
437
438         if (cb != NULL)
439             cb(s, SSL_CB_HANDSHAKE_DONE, 1);
440
441         if (SSL_IS_DTLS(s)) {
442             /* done with handshaking */
443             s->d1->handshake_read_seq = 0;
444             s->d1->handshake_write_seq = 0;
445             s->d1->next_handshake_write_seq = 0;
446             dtls1_clear_received_buffer(s);
447         }
448     }
449
450     return WORK_FINISHED_STOP;
451 }
452
453 int tls_get_message_header(SSL *s, int *mt)
454 {
455     /* s->init_num < SSL3_HM_HEADER_LENGTH */
456     int skip_message, i, recvd_type, al;
457     unsigned char *p;
458     size_t l, readbytes;
459
460     p = (unsigned char *)s->init_buf->data;
461
462     do {
463         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
464             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
465                                           &p[s->init_num],
466                                           SSL3_HM_HEADER_LENGTH - s->init_num,
467                                           0, &readbytes);
468             if (i <= 0) {
469                 s->rwstate = SSL_READING;
470                 return 0;
471             }
472             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
473                 /*
474                  * A ChangeCipherSpec must be a single byte and may not occur
475                  * in the middle of a handshake message.
476                  */
477                 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
478                     al = SSL_AD_UNEXPECTED_MESSAGE;
479                     SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
480                            SSL_R_BAD_CHANGE_CIPHER_SPEC);
481                     goto f_err;
482                 }
483                 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
484                 s->init_num = readbytes - 1;
485                 s->init_msg = s->init_buf->data;
486                 s->s3->tmp.message_size = readbytes;
487                 return 1;
488             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
489                 al = SSL_AD_UNEXPECTED_MESSAGE;
490                 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
491                 goto f_err;
492             }
493             s->init_num += readbytes;
494         }
495
496         skip_message = 0;
497         if (!s->server)
498             if (p[0] == SSL3_MT_HELLO_REQUEST)
499                 /*
500                  * The server may always send 'Hello Request' messages --
501                  * we are doing a handshake anyway now, so ignore them if
502                  * their format is correct. Does not count for 'Finished'
503                  * MAC.
504                  */
505                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
506                     s->init_num = 0;
507                     skip_message = 1;
508
509                     if (s->msg_callback)
510                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
511                                         p, SSL3_HM_HEADER_LENGTH, s,
512                                         s->msg_callback_arg);
513                 }
514     } while (skip_message);
515     /* s->init_num == SSL3_HM_HEADER_LENGTH */
516
517     *mt = *p;
518     s->s3->tmp.message_type = *(p++);
519
520     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
521         /*
522          * Only happens with SSLv3+ in an SSLv2 backward compatible
523          * ClientHello
524          *
525          * Total message size is the remaining record bytes to read
526          * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
527          */
528         l = RECORD_LAYER_get_rrec_length(&s->rlayer)
529             + SSL3_HM_HEADER_LENGTH;
530         s->s3->tmp.message_size = l;
531
532         s->init_msg = s->init_buf->data;
533         s->init_num = SSL3_HM_HEADER_LENGTH;
534     } else {
535         n2l3(p, l);
536         /* BUF_MEM_grow takes an 'int' parameter */
537         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
538             al = SSL_AD_ILLEGAL_PARAMETER;
539             SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
540             goto f_err;
541         }
542         s->s3->tmp.message_size = l;
543
544         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
545         s->init_num = 0;
546     }
547
548     return 1;
549  f_err:
550     ssl3_send_alert(s, SSL3_AL_FATAL, al);
551     return 0;
552 }
553
554 int tls_get_message_body(SSL *s, size_t *len)
555 {
556     size_t n, readbytes;
557     unsigned char *p;
558     int i;
559
560     if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
561         /* We've already read everything in */
562         *len = (unsigned long)s->init_num;
563         return 1;
564     }
565
566     p = s->init_msg;
567     n = s->s3->tmp.message_size - s->init_num;
568     while (n > 0) {
569         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
570                                       &p[s->init_num], n, 0, &readbytes);
571         if (i <= 0) {
572             s->rwstate = SSL_READING;
573             *len = 0;
574             return 0;
575         }
576         s->init_num += readbytes;
577         n -= readbytes;
578     }
579
580 #ifndef OPENSSL_NO_NEXTPROTONEG
581     /*
582      * If receiving Finished, record MAC of prior handshake messages for
583      * Finished verification.
584      */
585     if (*s->init_buf->data == SSL3_MT_FINISHED)
586         ssl3_take_mac(s);
587 #endif
588
589     /* Feed this message into MAC computation. */
590     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
591         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
592                              s->init_num)) {
593             SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
594             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
595             *len = 0;
596             return 0;
597         }
598         if (s->msg_callback)
599             s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
600                             (size_t)s->init_num, s, s->msg_callback_arg);
601     } else {
602         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
603                              s->init_num + SSL3_HM_HEADER_LENGTH)) {
604             SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
605             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
606             *len = 0;
607             return 0;
608         }
609         if (s->msg_callback)
610             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
611                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
612                             s->msg_callback_arg);
613     }
614
615     *len = s->init_num;
616     return 1;
617 }
618
619 int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
620 {
621     if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
622         return -1;
623
624     switch (EVP_PKEY_id(pk)) {
625     default:
626         return -1;
627     case EVP_PKEY_RSA:
628         return SSL_PKEY_RSA_ENC;
629     case EVP_PKEY_DSA:
630         return SSL_PKEY_DSA_SIGN;
631 #ifndef OPENSSL_NO_EC
632     case EVP_PKEY_EC:
633         return SSL_PKEY_ECC;
634 #endif
635 #ifndef OPENSSL_NO_GOST
636     case NID_id_GostR3410_2001:
637         return SSL_PKEY_GOST01;
638     case NID_id_GostR3410_2012_256:
639         return SSL_PKEY_GOST12_256;
640     case NID_id_GostR3410_2012_512:
641         return SSL_PKEY_GOST12_512;
642 #endif
643     }
644 }
645
646 int ssl_verify_alarm_type(long type)
647 {
648     int al;
649
650     switch (type) {
651     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
652     case X509_V_ERR_UNABLE_TO_GET_CRL:
653     case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
654         al = SSL_AD_UNKNOWN_CA;
655         break;
656     case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
657     case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
658     case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
659     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
660     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
661     case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
662     case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
663     case X509_V_ERR_CERT_NOT_YET_VALID:
664     case X509_V_ERR_CRL_NOT_YET_VALID:
665     case X509_V_ERR_CERT_UNTRUSTED:
666     case X509_V_ERR_CERT_REJECTED:
667     case X509_V_ERR_HOSTNAME_MISMATCH:
668     case X509_V_ERR_EMAIL_MISMATCH:
669     case X509_V_ERR_IP_ADDRESS_MISMATCH:
670     case X509_V_ERR_DANE_NO_MATCH:
671     case X509_V_ERR_EE_KEY_TOO_SMALL:
672     case X509_V_ERR_CA_KEY_TOO_SMALL:
673     case X509_V_ERR_CA_MD_TOO_WEAK:
674         al = SSL_AD_BAD_CERTIFICATE;
675         break;
676     case X509_V_ERR_CERT_SIGNATURE_FAILURE:
677     case X509_V_ERR_CRL_SIGNATURE_FAILURE:
678         al = SSL_AD_DECRYPT_ERROR;
679         break;
680     case X509_V_ERR_CERT_HAS_EXPIRED:
681     case X509_V_ERR_CRL_HAS_EXPIRED:
682         al = SSL_AD_CERTIFICATE_EXPIRED;
683         break;
684     case X509_V_ERR_CERT_REVOKED:
685         al = SSL_AD_CERTIFICATE_REVOKED;
686         break;
687     case X509_V_ERR_UNSPECIFIED:
688     case X509_V_ERR_OUT_OF_MEM:
689     case X509_V_ERR_INVALID_CALL:
690     case X509_V_ERR_STORE_LOOKUP:
691         al = SSL_AD_INTERNAL_ERROR;
692         break;
693     case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
694     case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
695     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
696     case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
697     case X509_V_ERR_CERT_CHAIN_TOO_LONG:
698     case X509_V_ERR_PATH_LENGTH_EXCEEDED:
699     case X509_V_ERR_INVALID_CA:
700         al = SSL_AD_UNKNOWN_CA;
701         break;
702     case X509_V_ERR_APPLICATION_VERIFICATION:
703         al = SSL_AD_HANDSHAKE_FAILURE;
704         break;
705     case X509_V_ERR_INVALID_PURPOSE:
706         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
707         break;
708     default:
709         al = SSL_AD_CERTIFICATE_UNKNOWN;
710         break;
711     }
712     return (al);
713 }
714
715 int ssl_allow_compression(SSL *s)
716 {
717     if (s->options & SSL_OP_NO_COMPRESSION)
718         return 0;
719     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
720 }
721
722 static int version_cmp(const SSL *s, int a, int b)
723 {
724     int dtls = SSL_IS_DTLS(s);
725
726     if (a == b)
727         return 0;
728     if (!dtls)
729         return a < b ? -1 : 1;
730     return DTLS_VERSION_LT(a, b) ? -1 : 1;
731 }
732
733 typedef struct {
734     int version;
735     const SSL_METHOD *(*cmeth) (void);
736     const SSL_METHOD *(*smeth) (void);
737 } version_info;
738
739 #if TLS_MAX_VERSION != TLS1_3_VERSION
740 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
741 #endif
742
743 static const version_info tls_version_table[] = {
744 #ifndef OPENSSL_NO_TLS1_3
745     {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
746 #else
747     {TLS1_3_VERSION, NULL, NULL},
748 #endif
749 #ifndef OPENSSL_NO_TLS1_2
750     {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
751 #else
752     {TLS1_2_VERSION, NULL, NULL},
753 #endif
754 #ifndef OPENSSL_NO_TLS1_1
755     {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
756 #else
757     {TLS1_1_VERSION, NULL, NULL},
758 #endif
759 #ifndef OPENSSL_NO_TLS1
760     {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
761 #else
762     {TLS1_VERSION, NULL, NULL},
763 #endif
764 #ifndef OPENSSL_NO_SSL3
765     {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
766 #else
767     {SSL3_VERSION, NULL, NULL},
768 #endif
769     {0, NULL, NULL},
770 };
771
772 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
773 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
774 #endif
775
776 static const version_info dtls_version_table[] = {
777 #ifndef OPENSSL_NO_DTLS1_2
778     {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
779 #else
780     {DTLS1_2_VERSION, NULL, NULL},
781 #endif
782 #ifndef OPENSSL_NO_DTLS1
783     {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
784     {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
785 #else
786     {DTLS1_VERSION, NULL, NULL},
787     {DTLS1_BAD_VER, NULL, NULL},
788 #endif
789     {0, NULL, NULL},
790 };
791
792 /*
793  * ssl_method_error - Check whether an SSL_METHOD is enabled.
794  *
795  * @s: The SSL handle for the candidate method
796  * @method: the intended method.
797  *
798  * Returns 0 on success, or an SSL error reason on failure.
799  */
800 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
801 {
802     int version = method->version;
803
804     if ((s->min_proto_version != 0 &&
805          version_cmp(s, version, s->min_proto_version) < 0) ||
806         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
807         return SSL_R_VERSION_TOO_LOW;
808
809     if (s->max_proto_version != 0 &&
810         version_cmp(s, version, s->max_proto_version) > 0)
811         return SSL_R_VERSION_TOO_HIGH;
812
813     if ((s->options & method->mask) != 0)
814         return SSL_R_UNSUPPORTED_PROTOCOL;
815     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
816         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
817     else if ((method->flags & SSL_METHOD_NO_FIPS) != 0 && FIPS_mode())
818         return SSL_R_AT_LEAST_TLS_1_0_NEEDED_IN_FIPS_MODE;
819
820     return 0;
821 }
822
823 /*
824  * ssl_version_supported - Check that the specified `version` is supported by
825  * `SSL *` instance
826  *
827  * @s: The SSL handle for the candidate method
828  * @version: Protocol version to test against
829  *
830  * Returns 1 when supported, otherwise 0
831  */
832 int ssl_version_supported(const SSL *s, int version)
833 {
834     const version_info *vent;
835     const version_info *table;
836
837     switch (s->method->version) {
838     default:
839         /* Version should match method version for non-ANY method */
840         return version_cmp(s, version, s->version) == 0;
841     case TLS_ANY_VERSION:
842         table = tls_version_table;
843         break;
844     case DTLS_ANY_VERSION:
845         table = dtls_version_table;
846         break;
847     }
848
849     for (vent = table;
850          vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
851          ++vent) {
852         if (vent->cmeth != NULL &&
853             version_cmp(s, version, vent->version) == 0 &&
854             ssl_method_error(s, vent->cmeth()) == 0) {
855             return 1;
856         }
857     }
858     return 0;
859 }
860
861 /*
862  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
863  * fallback indication from a client check whether we're using the highest
864  * supported protocol version.
865  *
866  * @s server SSL handle.
867  *
868  * Returns 1 when using the highest enabled version, 0 otherwise.
869  */
870 int ssl_check_version_downgrade(SSL *s)
871 {
872     const version_info *vent;
873     const version_info *table;
874
875     /*
876      * Check that the current protocol is the highest enabled version
877      * (according to s->ctx->method, as version negotiation may have changed
878      * s->method).
879      */
880     if (s->version == s->ctx->method->version)
881         return 1;
882
883     /*
884      * Apparently we're using a version-flexible SSL_METHOD (not at its
885      * highest protocol version).
886      */
887     if (s->ctx->method->version == TLS_method()->version)
888         table = tls_version_table;
889     else if (s->ctx->method->version == DTLS_method()->version)
890         table = dtls_version_table;
891     else {
892         /* Unexpected state; fail closed. */
893         return 0;
894     }
895
896     for (vent = table; vent->version != 0; ++vent) {
897         if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
898             return s->version == vent->version;
899     }
900     return 0;
901 }
902
903 /*
904  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
905  * protocols, provided the initial (D)TLS method is version-flexible.  This
906  * function sanity-checks the proposed value and makes sure the method is
907  * version-flexible, then sets the limit if all is well.
908  *
909  * @method_version: The version of the current SSL_METHOD.
910  * @version: the intended limit.
911  * @bound: pointer to limit to be updated.
912  *
913  * Returns 1 on success, 0 on failure.
914  */
915 int ssl_set_version_bound(int method_version, int version, int *bound)
916 {
917     if (version == 0) {
918         *bound = version;
919         return 1;
920     }
921
922     /*-
923      * Restrict TLS methods to TLS protocol versions.
924      * Restrict DTLS methods to DTLS protocol versions.
925      * Note, DTLS version numbers are decreasing, use comparison macros.
926      *
927      * Note that for both lower-bounds we use explicit versions, not
928      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
929      * configurations.  If the MIN (supported) version ever rises, the user's
930      * "floor" remains valid even if no longer available.  We don't expect the
931      * MAX ceiling to ever get lower, so making that variable makes sense.
932      */
933     switch (method_version) {
934     default:
935         /*
936          * XXX For fixed version methods, should we always fail and not set any
937          * bounds, always succeed and not set any bounds, or set the bounds and
938          * arrange to fail later if they are not met?  At present fixed-version
939          * methods are not subject to controls that disable individual protocol
940          * versions.
941          */
942         return 0;
943
944     case TLS_ANY_VERSION:
945         if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
946             return 0;
947         break;
948
949     case DTLS_ANY_VERSION:
950         if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
951             DTLS_VERSION_LT(version, DTLS1_BAD_VER))
952             return 0;
953         break;
954     }
955
956     *bound = version;
957     return 1;
958 }
959
960 /*
961  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
962  * client HELLO is received to select the final server protocol version and
963  * the version specific method.
964  *
965  * @s: server SSL handle.
966  *
967  * Returns 0 on success or an SSL error reason number on failure.
968  */
969 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello)
970 {
971     /*-
972      * With version-flexible methods we have an initial state with:
973      *
974      *   s->method->version == (D)TLS_ANY_VERSION,
975      *   s->version == (D)TLS_MAX_VERSION.
976      *
977      * So we detect version-flexible methods via the method version, not the
978      * handle version.
979      */
980     int server_version = s->method->version;
981     int client_version = hello->version;
982     const version_info *vent;
983     const version_info *table;
984     int disabled = 0;
985
986     s->client_version = client_version;
987
988     switch (server_version) {
989     default:
990         if (version_cmp(s, client_version, s->version) < 0)
991             return SSL_R_WRONG_SSL_VERSION;
992         /*
993          * If this SSL handle is not from a version flexible method we don't
994          * (and never did) check min/max FIPS or Suite B constraints.  Hope
995          * that's OK.  It is up to the caller to not choose fixed protocol
996          * versions they don't want.  If not, then easy to fix, just return
997          * ssl_method_error(s, s->method)
998          */
999         return 0;
1000     case TLS_ANY_VERSION:
1001         table = tls_version_table;
1002         break;
1003     case DTLS_ANY_VERSION:
1004         table = dtls_version_table;
1005         break;
1006     }
1007
1008     for (vent = table; vent->version != 0; ++vent) {
1009         const SSL_METHOD *method;
1010
1011         if (vent->smeth == NULL ||
1012             version_cmp(s, client_version, vent->version) < 0)
1013             continue;
1014         method = vent->smeth();
1015         if (ssl_method_error(s, method) == 0) {
1016             s->version = vent->version;
1017             s->method = method;
1018             return 0;
1019         }
1020         disabled = 1;
1021     }
1022     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1023 }
1024
1025 /*
1026  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
1027  * server HELLO is received to select the final client protocol version and
1028  * the version specific method.
1029  *
1030  * @s: client SSL handle.
1031  * @version: The proposed version from the server's HELLO.
1032  *
1033  * Returns 0 on success or an SSL error reason number on failure.
1034  */
1035 int ssl_choose_client_version(SSL *s, int version)
1036 {
1037     const version_info *vent;
1038     const version_info *table;
1039
1040     switch (s->method->version) {
1041     default:
1042         if (version != s->version)
1043             return SSL_R_WRONG_SSL_VERSION;
1044         /*
1045          * If this SSL handle is not from a version flexible method we don't
1046          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
1047          * that's OK.  It is up to the caller to not choose fixed protocol
1048          * versions they don't want.  If not, then easy to fix, just return
1049          * ssl_method_error(s, s->method)
1050          */
1051         return 0;
1052     case TLS_ANY_VERSION:
1053         table = tls_version_table;
1054         break;
1055     case DTLS_ANY_VERSION:
1056         table = dtls_version_table;
1057         break;
1058     }
1059
1060     for (vent = table; vent->version != 0; ++vent) {
1061         const SSL_METHOD *method;
1062         int err;
1063
1064         if (version != vent->version)
1065             continue;
1066         if (vent->cmeth == NULL)
1067             break;
1068         method = vent->cmeth();
1069         err = ssl_method_error(s, method);
1070         if (err != 0)
1071             return err;
1072         s->method = method;
1073         s->version = version;
1074         return 0;
1075     }
1076
1077     return SSL_R_UNSUPPORTED_PROTOCOL;
1078 }
1079
1080 /*
1081  * ssl_get_client_min_max_version - get minimum and maximum client version
1082  * @s: The SSL connection
1083  * @min_version: The minimum supported version
1084  * @max_version: The maximum supported version
1085  *
1086  * Work out what version we should be using for the initial ClientHello if the
1087  * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
1088  * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1089  * or FIPS_mode() constraints and any floor imposed by the security level here,
1090  * so we don't advertise the wrong protocol version to only reject the outcome later.
1091  *
1092  * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
1093  * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
1094  * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1095  *
1096  * Returns 0 on success or an SSL error reason number on failure.  On failure
1097  * min_version and max_version will also be set to 0.
1098  */
1099 int ssl_get_client_min_max_version(const SSL *s, int *min_version,
1100                                    int *max_version)
1101 {
1102     int version;
1103     int hole;
1104     const SSL_METHOD *single = NULL;
1105     const SSL_METHOD *method;
1106     const version_info *table;
1107     const version_info *vent;
1108
1109     switch (s->method->version) {
1110     default:
1111         /*
1112          * If this SSL handle is not from a version flexible method we don't
1113          * (and never did) check min/max FIPS or Suite B constraints.  Hope
1114          * that's OK.  It is up to the caller to not choose fixed protocol
1115          * versions they don't want.  If not, then easy to fix, just return
1116          * ssl_method_error(s, s->method)
1117          */
1118         *min_version = *max_version = s->version;
1119         return 0;
1120     case TLS_ANY_VERSION:
1121         table = tls_version_table;
1122         break;
1123     case DTLS_ANY_VERSION:
1124         table = dtls_version_table;
1125         break;
1126     }
1127
1128     /*
1129      * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1130      * below X enabled. This is required in order to maintain the "version
1131      * capability" vector contiguous. Any versions with a NULL client method
1132      * (protocol version client is disabled at compile-time) is also a "hole".
1133      *
1134      * Our initial state is hole == 1, version == 0.  That is, versions above
1135      * the first version in the method table are disabled (a "hole" above
1136      * the valid protocol entries) and we don't have a selected version yet.
1137      *
1138      * Whenever "hole == 1", and we hit an enabled method, its version becomes
1139      * the selected version, and the method becomes a candidate "single"
1140      * method.  We're no longer in a hole, so "hole" becomes 0.
1141      *
1142      * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1143      * as we support a contiguous range of at least two methods.  If we hit
1144      * a disabled method, then hole becomes true again, but nothing else
1145      * changes yet, because all the remaining methods may be disabled too.
1146      * If we again hit an enabled method after the new hole, it becomes
1147      * selected, as we start from scratch.
1148      */
1149     *min_version = version = 0;
1150     hole = 1;
1151     for (vent = table; vent->version != 0; ++vent) {
1152         /*
1153          * A table entry with a NULL client method is still a hole in the
1154          * "version capability" vector.
1155          */
1156         if (vent->cmeth == NULL) {
1157             hole = 1;
1158             continue;
1159         }
1160         method = vent->cmeth();
1161         if (ssl_method_error(s, method) != 0) {
1162             hole = 1;
1163         } else if (!hole) {
1164             single = NULL;
1165             *min_version = method->version;
1166         } else {
1167             version = (single = method)->version;
1168             *min_version = version;
1169             hole = 0;
1170         }
1171     }
1172
1173     *max_version = version;
1174
1175     /* Fail if everything is disabled */
1176     if (version == 0)
1177         return SSL_R_NO_PROTOCOLS_AVAILABLE;
1178
1179     return 0;
1180 }
1181
1182 /*
1183  * ssl_set_client_hello_version - Work out what version we should be using for
1184  * the initial ClientHello.
1185  *
1186  * @s: client SSL handle.
1187  *
1188  * Returns 0 on success or an SSL error reason number on failure.
1189  */
1190 int ssl_set_client_hello_version(SSL *s)
1191 {
1192     int ver_min, ver_max, ret;
1193
1194     ret = ssl_get_client_min_max_version(s, &ver_min, &ver_max);
1195
1196     if (ret != 0)
1197         return ret;
1198
1199     s->client_version = s->version = ver_max;
1200     return 0;
1201 }