t1_lib.c revision 340704
1/* ssl/t1_lib.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58/* ====================================================================
59 * Copyright (c) 1998-2018 The OpenSSL Project.  All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 *    notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 *    notice, this list of conditions and the following disclaimer in
70 *    the documentation and/or other materials provided with the
71 *    distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 *    software must display the following acknowledgment:
75 *    "This product includes software developed by the OpenSSL Project
76 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 *    endorse or promote products derived from this software without
80 *    prior written permission. For written permission, please contact
81 *    openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 *    nor may "OpenSSL" appear in their names without prior written
85 *    permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 *    acknowledgment:
89 *    "This product includes software developed by the OpenSSL Project
90 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com).  This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112#include <stdio.h>
113#include <openssl/objects.h>
114#include <openssl/evp.h>
115#include <openssl/hmac.h>
116#ifndef OPENSSL_NO_EC
117#ifdef OPENSSL_NO_EC2M
118# include <openssl/ec.h>
119#endif
120#endif
121#include <openssl/ocsp.h>
122#include <openssl/rand.h>
123#include "ssl_locl.h"
124
125const char tls1_version_str[] = "TLSv1" OPENSSL_VERSION_PTEXT;
126
127#ifndef OPENSSL_NO_TLSEXT
128static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
129                              const unsigned char *sess_id, int sesslen,
130                              SSL_SESSION **psess);
131static int ssl_check_clienthello_tlsext_early(SSL *s);
132int ssl_check_serverhello_tlsext(SSL *s);
133#endif
134
135#define CHECKLEN(curr, val, limit) \
136    (((curr) >= (limit)) || (size_t)((limit) - (curr)) < (size_t)(val))
137
138SSL3_ENC_METHOD TLSv1_enc_data = {
139    tls1_enc,
140    tls1_mac,
141    tls1_setup_key_block,
142    tls1_generate_master_secret,
143    tls1_change_cipher_state,
144    tls1_final_finish_mac,
145    TLS1_FINISH_MAC_LENGTH,
146    tls1_cert_verify_mac,
147    TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
148    TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
149    tls1_alert_code,
150    tls1_export_keying_material,
151    0,
152    SSL3_HM_HEADER_LENGTH,
153    ssl3_set_handshake_header,
154    ssl3_handshake_write
155};
156
157SSL3_ENC_METHOD TLSv1_1_enc_data = {
158    tls1_enc,
159    tls1_mac,
160    tls1_setup_key_block,
161    tls1_generate_master_secret,
162    tls1_change_cipher_state,
163    tls1_final_finish_mac,
164    TLS1_FINISH_MAC_LENGTH,
165    tls1_cert_verify_mac,
166    TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
167    TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
168    tls1_alert_code,
169    tls1_export_keying_material,
170    SSL_ENC_FLAG_EXPLICIT_IV,
171    SSL3_HM_HEADER_LENGTH,
172    ssl3_set_handshake_header,
173    ssl3_handshake_write
174};
175
176SSL3_ENC_METHOD TLSv1_2_enc_data = {
177    tls1_enc,
178    tls1_mac,
179    tls1_setup_key_block,
180    tls1_generate_master_secret,
181    tls1_change_cipher_state,
182    tls1_final_finish_mac,
183    TLS1_FINISH_MAC_LENGTH,
184    tls1_cert_verify_mac,
185    TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
186    TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
187    tls1_alert_code,
188    tls1_export_keying_material,
189    SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
190        | SSL_ENC_FLAG_TLS1_2_CIPHERS,
191    SSL3_HM_HEADER_LENGTH,
192    ssl3_set_handshake_header,
193    ssl3_handshake_write
194};
195
196long tls1_default_timeout(void)
197{
198    /*
199     * 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for
200     * http, the cache would over fill
201     */
202    return (60 * 60 * 2);
203}
204
205int tls1_new(SSL *s)
206{
207    if (!ssl3_new(s))
208        return (0);
209    s->method->ssl_clear(s);
210    return (1);
211}
212
213void tls1_free(SSL *s)
214{
215#ifndef OPENSSL_NO_TLSEXT
216    if (s->tlsext_session_ticket) {
217        OPENSSL_free(s->tlsext_session_ticket);
218    }
219#endif                          /* OPENSSL_NO_TLSEXT */
220    ssl3_free(s);
221}
222
223void tls1_clear(SSL *s)
224{
225    ssl3_clear(s);
226    s->version = s->method->version;
227}
228
229#ifndef OPENSSL_NO_EC
230
231static int nid_list[] = {
232    NID_sect163k1,              /* sect163k1 (1) */
233    NID_sect163r1,              /* sect163r1 (2) */
234    NID_sect163r2,              /* sect163r2 (3) */
235    NID_sect193r1,              /* sect193r1 (4) */
236    NID_sect193r2,              /* sect193r2 (5) */
237    NID_sect233k1,              /* sect233k1 (6) */
238    NID_sect233r1,              /* sect233r1 (7) */
239    NID_sect239k1,              /* sect239k1 (8) */
240    NID_sect283k1,              /* sect283k1 (9) */
241    NID_sect283r1,              /* sect283r1 (10) */
242    NID_sect409k1,              /* sect409k1 (11) */
243    NID_sect409r1,              /* sect409r1 (12) */
244    NID_sect571k1,              /* sect571k1 (13) */
245    NID_sect571r1,              /* sect571r1 (14) */
246    NID_secp160k1,              /* secp160k1 (15) */
247    NID_secp160r1,              /* secp160r1 (16) */
248    NID_secp160r2,              /* secp160r2 (17) */
249    NID_secp192k1,              /* secp192k1 (18) */
250    NID_X9_62_prime192v1,       /* secp192r1 (19) */
251    NID_secp224k1,              /* secp224k1 (20) */
252    NID_secp224r1,              /* secp224r1 (21) */
253    NID_secp256k1,              /* secp256k1 (22) */
254    NID_X9_62_prime256v1,       /* secp256r1 (23) */
255    NID_secp384r1,              /* secp384r1 (24) */
256    NID_secp521r1,              /* secp521r1 (25) */
257    NID_brainpoolP256r1,        /* brainpoolP256r1 (26) */
258    NID_brainpoolP384r1,        /* brainpoolP384r1 (27) */
259    NID_brainpoolP512r1         /* brainpool512r1 (28) */
260};
261
262static const unsigned char ecformats_default[] = {
263    TLSEXT_ECPOINTFORMAT_uncompressed,
264    TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
265    TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
266};
267
268/* The client's default curves / the server's 'auto' curves. */
269static const unsigned char eccurves_auto[] = {
270    /* Prefer P-256 which has the fastest and most secure implementations. */
271    0, 23,                      /* secp256r1 (23) */
272    /* Other >= 256-bit prime curves. */
273    0, 25,                      /* secp521r1 (25) */
274    0, 28,                      /* brainpool512r1 (28) */
275    0, 27,                      /* brainpoolP384r1 (27) */
276    0, 24,                      /* secp384r1 (24) */
277    0, 26,                      /* brainpoolP256r1 (26) */
278    0, 22,                      /* secp256k1 (22) */
279# ifndef OPENSSL_NO_EC2M
280    /* >= 256-bit binary curves. */
281    0, 14,                      /* sect571r1 (14) */
282    0, 13,                      /* sect571k1 (13) */
283    0, 11,                      /* sect409k1 (11) */
284    0, 12,                      /* sect409r1 (12) */
285    0, 9,                       /* sect283k1 (9) */
286    0, 10,                      /* sect283r1 (10) */
287# endif
288};
289
290static const unsigned char eccurves_all[] = {
291    /* Prefer P-256 which has the fastest and most secure implementations. */
292    0, 23,                      /* secp256r1 (23) */
293    /* Other >= 256-bit prime curves. */
294    0, 25,                      /* secp521r1 (25) */
295    0, 28,                      /* brainpool512r1 (28) */
296    0, 27,                      /* brainpoolP384r1 (27) */
297    0, 24,                      /* secp384r1 (24) */
298    0, 26,                      /* brainpoolP256r1 (26) */
299    0, 22,                      /* secp256k1 (22) */
300# ifndef OPENSSL_NO_EC2M
301    /* >= 256-bit binary curves. */
302    0, 14,                      /* sect571r1 (14) */
303    0, 13,                      /* sect571k1 (13) */
304    0, 11,                      /* sect409k1 (11) */
305    0, 12,                      /* sect409r1 (12) */
306    0, 9,                       /* sect283k1 (9) */
307    0, 10,                      /* sect283r1 (10) */
308# endif
309    /*
310     * Remaining curves disabled by default but still permitted if set
311     * via an explicit callback or parameters.
312     */
313    0, 20,                      /* secp224k1 (20) */
314    0, 21,                      /* secp224r1 (21) */
315    0, 18,                      /* secp192k1 (18) */
316    0, 19,                      /* secp192r1 (19) */
317    0, 15,                      /* secp160k1 (15) */
318    0, 16,                      /* secp160r1 (16) */
319    0, 17,                      /* secp160r2 (17) */
320# ifndef OPENSSL_NO_EC2M
321    0, 8,                       /* sect239k1 (8) */
322    0, 6,                       /* sect233k1 (6) */
323    0, 7,                       /* sect233r1 (7) */
324    0, 4,                       /* sect193r1 (4) */
325    0, 5,                       /* sect193r2 (5) */
326    0, 1,                       /* sect163k1 (1) */
327    0, 2,                       /* sect163r1 (2) */
328    0, 3,                       /* sect163r2 (3) */
329# endif
330};
331
332static const unsigned char suiteb_curves[] = {
333    0, TLSEXT_curve_P_256,
334    0, TLSEXT_curve_P_384
335};
336
337# ifdef OPENSSL_FIPS
338/* Brainpool not allowed in FIPS mode */
339static const unsigned char fips_curves_default[] = {
340#  ifndef OPENSSL_NO_EC2M
341    0, 14,                      /* sect571r1 (14) */
342    0, 13,                      /* sect571k1 (13) */
343#  endif
344    0, 25,                      /* secp521r1 (25) */
345#  ifndef OPENSSL_NO_EC2M
346    0, 11,                      /* sect409k1 (11) */
347    0, 12,                      /* sect409r1 (12) */
348#  endif
349    0, 24,                      /* secp384r1 (24) */
350#  ifndef OPENSSL_NO_EC2M
351    0, 9,                       /* sect283k1 (9) */
352    0, 10,                      /* sect283r1 (10) */
353#  endif
354    0, 22,                      /* secp256k1 (22) */
355    0, 23,                      /* secp256r1 (23) */
356#  ifndef OPENSSL_NO_EC2M
357    0, 8,                       /* sect239k1 (8) */
358    0, 6,                       /* sect233k1 (6) */
359    0, 7,                       /* sect233r1 (7) */
360#  endif
361    0, 20,                      /* secp224k1 (20) */
362    0, 21,                      /* secp224r1 (21) */
363#  ifndef OPENSSL_NO_EC2M
364    0, 4,                       /* sect193r1 (4) */
365    0, 5,                       /* sect193r2 (5) */
366#  endif
367    0, 18,                      /* secp192k1 (18) */
368    0, 19,                      /* secp192r1 (19) */
369#  ifndef OPENSSL_NO_EC2M
370    0, 1,                       /* sect163k1 (1) */
371    0, 2,                       /* sect163r1 (2) */
372    0, 3,                       /* sect163r2 (3) */
373#  endif
374    0, 15,                      /* secp160k1 (15) */
375    0, 16,                      /* secp160r1 (16) */
376    0, 17,                      /* secp160r2 (17) */
377};
378# endif
379
380int tls1_ec_curve_id2nid(int curve_id)
381{
382    /* ECC curves from RFC 4492 and RFC 7027 */
383    if ((curve_id < 1) || ((unsigned int)curve_id >
384                           sizeof(nid_list) / sizeof(nid_list[0])))
385        return 0;
386    return nid_list[curve_id - 1];
387}
388
389int tls1_ec_nid2curve_id(int nid)
390{
391    /* ECC curves from RFC 4492 and RFC 7027 */
392    switch (nid) {
393    case NID_sect163k1:        /* sect163k1 (1) */
394        return 1;
395    case NID_sect163r1:        /* sect163r1 (2) */
396        return 2;
397    case NID_sect163r2:        /* sect163r2 (3) */
398        return 3;
399    case NID_sect193r1:        /* sect193r1 (4) */
400        return 4;
401    case NID_sect193r2:        /* sect193r2 (5) */
402        return 5;
403    case NID_sect233k1:        /* sect233k1 (6) */
404        return 6;
405    case NID_sect233r1:        /* sect233r1 (7) */
406        return 7;
407    case NID_sect239k1:        /* sect239k1 (8) */
408        return 8;
409    case NID_sect283k1:        /* sect283k1 (9) */
410        return 9;
411    case NID_sect283r1:        /* sect283r1 (10) */
412        return 10;
413    case NID_sect409k1:        /* sect409k1 (11) */
414        return 11;
415    case NID_sect409r1:        /* sect409r1 (12) */
416        return 12;
417    case NID_sect571k1:        /* sect571k1 (13) */
418        return 13;
419    case NID_sect571r1:        /* sect571r1 (14) */
420        return 14;
421    case NID_secp160k1:        /* secp160k1 (15) */
422        return 15;
423    case NID_secp160r1:        /* secp160r1 (16) */
424        return 16;
425    case NID_secp160r2:        /* secp160r2 (17) */
426        return 17;
427    case NID_secp192k1:        /* secp192k1 (18) */
428        return 18;
429    case NID_X9_62_prime192v1: /* secp192r1 (19) */
430        return 19;
431    case NID_secp224k1:        /* secp224k1 (20) */
432        return 20;
433    case NID_secp224r1:        /* secp224r1 (21) */
434        return 21;
435    case NID_secp256k1:        /* secp256k1 (22) */
436        return 22;
437    case NID_X9_62_prime256v1: /* secp256r1 (23) */
438        return 23;
439    case NID_secp384r1:        /* secp384r1 (24) */
440        return 24;
441    case NID_secp521r1:        /* secp521r1 (25) */
442        return 25;
443    case NID_brainpoolP256r1:  /* brainpoolP256r1 (26) */
444        return 26;
445    case NID_brainpoolP384r1:  /* brainpoolP384r1 (27) */
446        return 27;
447    case NID_brainpoolP512r1:  /* brainpool512r1 (28) */
448        return 28;
449    default:
450        return 0;
451    }
452}
453
454/*
455 * Get curves list, if "sess" is set return client curves otherwise
456 * preferred list.
457 * Sets |num_curves| to the number of curves in the list, i.e.,
458 * the length of |pcurves| is 2 * num_curves.
459 * Returns 1 on success and 0 if the client curves list has invalid format.
460 * The latter indicates an internal error: we should not be accepting such
461 * lists in the first place.
462 * TODO(emilia): we should really be storing the curves list in explicitly
463 * parsed form instead. (However, this would affect binary compatibility
464 * so cannot happen in the 1.0.x series.)
465 */
466static int tls1_get_curvelist(SSL *s, int sess,
467                              const unsigned char **pcurves,
468                              size_t *num_curves)
469{
470    size_t pcurveslen = 0;
471    if (sess) {
472        *pcurves = s->session->tlsext_ellipticcurvelist;
473        pcurveslen = s->session->tlsext_ellipticcurvelist_length;
474    } else {
475        /* For Suite B mode only include P-256, P-384 */
476        switch (tls1_suiteb(s)) {
477        case SSL_CERT_FLAG_SUITEB_128_LOS:
478            *pcurves = suiteb_curves;
479            pcurveslen = sizeof(suiteb_curves);
480            break;
481
482        case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
483            *pcurves = suiteb_curves;
484            pcurveslen = 2;
485            break;
486
487        case SSL_CERT_FLAG_SUITEB_192_LOS:
488            *pcurves = suiteb_curves + 2;
489            pcurveslen = 2;
490            break;
491        default:
492            *pcurves = s->tlsext_ellipticcurvelist;
493            pcurveslen = s->tlsext_ellipticcurvelist_length;
494        }
495        if (!*pcurves) {
496# ifdef OPENSSL_FIPS
497            if (FIPS_mode()) {
498                *pcurves = fips_curves_default;
499                pcurveslen = sizeof(fips_curves_default);
500            } else
501# endif
502            {
503                if (!s->server
504# ifndef OPENSSL_NO_ECDH
505                        || s->cert->ecdh_tmp_auto
506# endif
507                    ) {
508                    *pcurves = eccurves_auto;
509                    pcurveslen = sizeof(eccurves_auto);
510                } else {
511                    *pcurves = eccurves_all;
512                    pcurveslen = sizeof(eccurves_all);
513                }
514            }
515        }
516    }
517    /* We do not allow odd length arrays to enter the system. */
518    if (pcurveslen & 1) {
519        SSLerr(SSL_F_TLS1_GET_CURVELIST, ERR_R_INTERNAL_ERROR);
520        *num_curves = 0;
521        return 0;
522    } else {
523        *num_curves = pcurveslen / 2;
524        return 1;
525    }
526}
527
528/* Check a curve is one of our preferences */
529int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
530{
531    const unsigned char *curves;
532    size_t num_curves, i;
533    unsigned int suiteb_flags = tls1_suiteb(s);
534    if (len != 3 || p[0] != NAMED_CURVE_TYPE)
535        return 0;
536    /* Check curve matches Suite B preferences */
537    if (suiteb_flags) {
538        unsigned long cid = s->s3->tmp.new_cipher->id;
539        if (p[1])
540            return 0;
541        if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
542            if (p[2] != TLSEXT_curve_P_256)
543                return 0;
544        } else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
545            if (p[2] != TLSEXT_curve_P_384)
546                return 0;
547        } else                  /* Should never happen */
548            return 0;
549    }
550    if (!tls1_get_curvelist(s, 0, &curves, &num_curves))
551        return 0;
552    for (i = 0; i < num_curves; i++, curves += 2) {
553        if (p[1] == curves[0] && p[2] == curves[1])
554            return 1;
555    }
556    return 0;
557}
558
559/*-
560 * Return |nmatch|th shared curve or NID_undef if there is no match.
561 * For nmatch == -1, return number of  matches
562 * For nmatch == -2, return the NID of the curve to use for
563 * an EC tmp key, or NID_undef if there is no match.
564 */
565int tls1_shared_curve(SSL *s, int nmatch)
566{
567    const unsigned char *pref, *supp;
568    size_t num_pref, num_supp, i, j;
569    int k;
570    /* Can't do anything on client side */
571    if (s->server == 0)
572        return -1;
573    if (nmatch == -2) {
574        if (tls1_suiteb(s)) {
575            /*
576             * For Suite B ciphersuite determines curve: we already know
577             * these are acceptable due to previous checks.
578             */
579            unsigned long cid = s->s3->tmp.new_cipher->id;
580            if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
581                return NID_X9_62_prime256v1; /* P-256 */
582            if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
583                return NID_secp384r1; /* P-384 */
584            /* Should never happen */
585            return NID_undef;
586        }
587        /* If not Suite B just return first preference shared curve */
588        nmatch = 0;
589    }
590    /*
591     * Avoid truncation. tls1_get_curvelist takes an int
592     * but s->options is a long...
593     */
594    if (!tls1_get_curvelist
595        (s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0, &supp,
596         &num_supp))
597        /* In practice, NID_undef == 0 but let's be precise. */
598        return nmatch == -1 ? 0 : NID_undef;
599    if (!tls1_get_curvelist
600        (s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE), &pref,
601         &num_pref))
602        return nmatch == -1 ? 0 : NID_undef;
603
604    /*
605     * If the client didn't send the elliptic_curves extension all of them
606     * are allowed.
607     */
608    if (num_supp == 0 && (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0) {
609        supp = eccurves_all;
610        num_supp = sizeof(eccurves_all) / 2;
611    } else if (num_pref == 0 &&
612        (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) == 0) {
613        pref = eccurves_all;
614        num_pref = sizeof(eccurves_all) / 2;
615    }
616
617    k = 0;
618    for (i = 0; i < num_pref; i++, pref += 2) {
619        const unsigned char *tsupp = supp;
620        for (j = 0; j < num_supp; j++, tsupp += 2) {
621            if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) {
622                if (nmatch == k) {
623                    int id = (pref[0] << 8) | pref[1];
624                    return tls1_ec_curve_id2nid(id);
625                }
626                k++;
627            }
628        }
629    }
630    if (nmatch == -1)
631        return k;
632    /* Out of range (nmatch > k). */
633    return NID_undef;
634}
635
636int tls1_set_curves(unsigned char **pext, size_t *pextlen,
637                    int *curves, size_t ncurves)
638{
639    unsigned char *clist, *p;
640    size_t i;
641    /*
642     * Bitmap of curves included to detect duplicates: only works while curve
643     * ids < 32
644     */
645    unsigned long dup_list = 0;
646# ifdef OPENSSL_NO_EC2M
647    EC_GROUP *curve;
648# endif
649
650    clist = OPENSSL_malloc(ncurves * 2);
651    if (!clist)
652        return 0;
653    for (i = 0, p = clist; i < ncurves; i++) {
654        unsigned long idmask;
655        int id;
656        id = tls1_ec_nid2curve_id(curves[i]);
657# ifdef OPENSSL_FIPS
658        /* NB: 25 is last curve ID supported by FIPS module */
659        if (FIPS_mode() && id > 25) {
660            OPENSSL_free(clist);
661            return 0;
662        }
663# endif
664# ifdef OPENSSL_NO_EC2M
665        curve = EC_GROUP_new_by_curve_name(curves[i]);
666        if (!curve || EC_METHOD_get_field_type(EC_GROUP_method_of(curve))
667            == NID_X9_62_characteristic_two_field) {
668            if (curve)
669                EC_GROUP_free(curve);
670            OPENSSL_free(clist);
671            return 0;
672        } else
673            EC_GROUP_free(curve);
674# endif
675        idmask = 1L << id;
676        if (!id || (dup_list & idmask)) {
677            OPENSSL_free(clist);
678            return 0;
679        }
680        dup_list |= idmask;
681        s2n(id, p);
682    }
683    if (*pext)
684        OPENSSL_free(*pext);
685    *pext = clist;
686    *pextlen = ncurves * 2;
687    return 1;
688}
689
690# define MAX_CURVELIST   28
691
692typedef struct {
693    size_t nidcnt;
694    int nid_arr[MAX_CURVELIST];
695} nid_cb_st;
696
697static int nid_cb(const char *elem, int len, void *arg)
698{
699    nid_cb_st *narg = arg;
700    size_t i;
701    int nid;
702    char etmp[20];
703    if (elem == NULL)
704        return 0;
705    if (narg->nidcnt == MAX_CURVELIST)
706        return 0;
707    if (len > (int)(sizeof(etmp) - 1))
708        return 0;
709    memcpy(etmp, elem, len);
710    etmp[len] = 0;
711    nid = EC_curve_nist2nid(etmp);
712    if (nid == NID_undef)
713        nid = OBJ_sn2nid(etmp);
714    if (nid == NID_undef)
715        nid = OBJ_ln2nid(etmp);
716    if (nid == NID_undef)
717        return 0;
718    for (i = 0; i < narg->nidcnt; i++)
719        if (narg->nid_arr[i] == nid)
720            return 0;
721    narg->nid_arr[narg->nidcnt++] = nid;
722    return 1;
723}
724
725/* Set curves based on a colon separate list */
726int tls1_set_curves_list(unsigned char **pext, size_t *pextlen,
727                         const char *str)
728{
729    nid_cb_st ncb;
730    ncb.nidcnt = 0;
731    if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
732        return 0;
733    if (pext == NULL)
734        return 1;
735    return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
736}
737
738/* For an EC key set TLS id and required compression based on parameters */
739static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
740                          EC_KEY *ec)
741{
742    int is_prime, id;
743    const EC_GROUP *grp;
744    const EC_METHOD *meth;
745    if (!ec)
746        return 0;
747    /* Determine if it is a prime field */
748    grp = EC_KEY_get0_group(ec);
749    if (!grp)
750        return 0;
751    meth = EC_GROUP_method_of(grp);
752    if (!meth)
753        return 0;
754    if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
755        is_prime = 1;
756    else
757        is_prime = 0;
758    /* Determine curve ID */
759    id = EC_GROUP_get_curve_name(grp);
760    id = tls1_ec_nid2curve_id(id);
761    /* If we have an ID set it, otherwise set arbitrary explicit curve */
762    if (id) {
763        curve_id[0] = 0;
764        curve_id[1] = (unsigned char)id;
765    } else {
766        curve_id[0] = 0xff;
767        if (is_prime)
768            curve_id[1] = 0x01;
769        else
770            curve_id[1] = 0x02;
771    }
772    if (comp_id) {
773        if (EC_KEY_get0_public_key(ec) == NULL)
774            return 0;
775        if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED) {
776            if (is_prime)
777                *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
778            else
779                *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
780        } else
781            *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
782    }
783    return 1;
784}
785
786/* Check an EC key is compatible with extensions */
787static int tls1_check_ec_key(SSL *s,
788                             unsigned char *curve_id, unsigned char *comp_id)
789{
790    const unsigned char *pformats, *pcurves;
791    size_t num_formats, num_curves, i;
792    int j;
793    /*
794     * If point formats extension present check it, otherwise everything is
795     * supported (see RFC4492).
796     */
797    if (comp_id && s->session->tlsext_ecpointformatlist) {
798        pformats = s->session->tlsext_ecpointformatlist;
799        num_formats = s->session->tlsext_ecpointformatlist_length;
800        for (i = 0; i < num_formats; i++, pformats++) {
801            if (*comp_id == *pformats)
802                break;
803        }
804        if (i == num_formats)
805            return 0;
806    }
807    if (!curve_id)
808        return 1;
809    /* Check curve is consistent with client and server preferences */
810    for (j = 0; j <= 1; j++) {
811        if (!tls1_get_curvelist(s, j, &pcurves, &num_curves))
812            return 0;
813        if (j == 1 && num_curves == 0) {
814            /*
815             * If we've not received any curves then skip this check.
816             * RFC 4492 does not require the supported elliptic curves extension
817             * so if it is not sent we can just choose any curve.
818             * It is invalid to send an empty list in the elliptic curves
819             * extension, so num_curves == 0 always means no extension.
820             */
821            break;
822        }
823        for (i = 0; i < num_curves; i++, pcurves += 2) {
824            if (pcurves[0] == curve_id[0] && pcurves[1] == curve_id[1])
825                break;
826        }
827        if (i == num_curves)
828            return 0;
829        /* For clients can only check sent curve list */
830        if (!s->server)
831            return 1;
832    }
833    return 1;
834}
835
836static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
837                                size_t *num_formats)
838{
839    /*
840     * If we have a custom point format list use it otherwise use default
841     */
842    if (s->tlsext_ecpointformatlist) {
843        *pformats = s->tlsext_ecpointformatlist;
844        *num_formats = s->tlsext_ecpointformatlist_length;
845    } else {
846        *pformats = ecformats_default;
847        /* For Suite B we don't support char2 fields */
848        if (tls1_suiteb(s))
849            *num_formats = sizeof(ecformats_default) - 1;
850        else
851            *num_formats = sizeof(ecformats_default);
852    }
853}
854
855/*
856 * Check cert parameters compatible with extensions: currently just checks EC
857 * certificates have compatible curves and compression.
858 */
859static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
860{
861    unsigned char comp_id, curve_id[2];
862    EVP_PKEY *pkey;
863    int rv;
864    pkey = X509_get_pubkey(x);
865    if (!pkey)
866        return 0;
867    /* If not EC nothing to do */
868    if (pkey->type != EVP_PKEY_EC) {
869        EVP_PKEY_free(pkey);
870        return 1;
871    }
872    rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
873    EVP_PKEY_free(pkey);
874    if (!rv)
875        return 0;
876    /*
877     * Can't check curve_id for client certs as we don't have a supported
878     * curves extension.
879     */
880    rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
881    if (!rv)
882        return 0;
883    /*
884     * Special case for suite B. We *MUST* sign using SHA256+P-256 or
885     * SHA384+P-384, adjust digest if necessary.
886     */
887    if (set_ee_md && tls1_suiteb(s)) {
888        int check_md;
889        size_t i;
890        CERT *c = s->cert;
891        if (curve_id[0])
892            return 0;
893        /* Check to see we have necessary signing algorithm */
894        if (curve_id[1] == TLSEXT_curve_P_256)
895            check_md = NID_ecdsa_with_SHA256;
896        else if (curve_id[1] == TLSEXT_curve_P_384)
897            check_md = NID_ecdsa_with_SHA384;
898        else
899            return 0;           /* Should never happen */
900        for (i = 0; i < c->shared_sigalgslen; i++)
901            if (check_md == c->shared_sigalgs[i].signandhash_nid)
902                break;
903        if (i == c->shared_sigalgslen)
904            return 0;
905        if (set_ee_md == 2) {
906            if (check_md == NID_ecdsa_with_SHA256)
907                c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
908            else
909                c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
910        }
911    }
912    return rv;
913}
914
915# ifndef OPENSSL_NO_ECDH
916/* Check EC temporary key is compatible with client extensions */
917int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
918{
919    unsigned char curve_id[2];
920    EC_KEY *ec = s->cert->ecdh_tmp;
921#  ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
922    /* Allow any curve: not just those peer supports */
923    if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
924        return 1;
925#  endif
926    /*
927     * If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
928     * curves permitted.
929     */
930    if (tls1_suiteb(s)) {
931        /* Curve to check determined by ciphersuite */
932        if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
933            curve_id[1] = TLSEXT_curve_P_256;
934        else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
935            curve_id[1] = TLSEXT_curve_P_384;
936        else
937            return 0;
938        curve_id[0] = 0;
939        /* Check this curve is acceptable */
940        if (!tls1_check_ec_key(s, curve_id, NULL))
941            return 0;
942        /* If auto or setting curve from callback assume OK */
943        if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
944            return 1;
945        /* Otherwise check curve is acceptable */
946        else {
947            unsigned char curve_tmp[2];
948            if (!ec)
949                return 0;
950            if (!tls1_set_ec_id(curve_tmp, NULL, ec))
951                return 0;
952            if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
953                return 1;
954            return 0;
955        }
956
957    }
958    if (s->cert->ecdh_tmp_auto) {
959        /* Need a shared curve */
960        if (tls1_shared_curve(s, 0))
961            return 1;
962        else
963            return 0;
964    }
965    if (!ec) {
966        if (s->cert->ecdh_tmp_cb)
967            return 1;
968        else
969            return 0;
970    }
971    if (!tls1_set_ec_id(curve_id, NULL, ec))
972        return 0;
973/* Set this to allow use of invalid curves for testing */
974#  if 0
975    return 1;
976#  else
977    return tls1_check_ec_key(s, curve_id, NULL);
978#  endif
979}
980# endif                         /* OPENSSL_NO_ECDH */
981
982#else
983
984static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
985{
986    return 1;
987}
988
989#endif                          /* OPENSSL_NO_EC */
990
991#ifndef OPENSSL_NO_TLSEXT
992
993/*
994 * List of supported signature algorithms and hashes. Should make this
995 * customisable at some point, for now include everything we support.
996 */
997
998# ifdef OPENSSL_NO_RSA
999#  define tlsext_sigalg_rsa(md) /* */
1000# else
1001#  define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
1002# endif
1003
1004# ifdef OPENSSL_NO_DSA
1005#  define tlsext_sigalg_dsa(md) /* */
1006# else
1007#  define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
1008# endif
1009
1010# ifdef OPENSSL_NO_ECDSA
1011#  define tlsext_sigalg_ecdsa(md)
1012                                /* */
1013# else
1014#  define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
1015# endif
1016
1017# define tlsext_sigalg(md) \
1018                tlsext_sigalg_rsa(md) \
1019                tlsext_sigalg_dsa(md) \
1020                tlsext_sigalg_ecdsa(md)
1021
1022static unsigned char tls12_sigalgs[] = {
1023# ifndef OPENSSL_NO_SHA512
1024    tlsext_sigalg(TLSEXT_hash_sha512)
1025        tlsext_sigalg(TLSEXT_hash_sha384)
1026# endif
1027# ifndef OPENSSL_NO_SHA256
1028        tlsext_sigalg(TLSEXT_hash_sha256)
1029        tlsext_sigalg(TLSEXT_hash_sha224)
1030# endif
1031# ifndef OPENSSL_NO_SHA
1032        tlsext_sigalg(TLSEXT_hash_sha1)
1033# endif
1034};
1035
1036# ifndef OPENSSL_NO_ECDSA
1037static unsigned char suiteb_sigalgs[] = {
1038    tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
1039        tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
1040};
1041# endif
1042size_t tls12_get_psigalgs(SSL *s, int sent, const unsigned char **psigs)
1043{
1044    /*
1045     * If Suite B mode use Suite B sigalgs only, ignore any other
1046     * preferences.
1047     */
1048# ifndef OPENSSL_NO_EC
1049    switch (tls1_suiteb(s)) {
1050    case SSL_CERT_FLAG_SUITEB_128_LOS:
1051        *psigs = suiteb_sigalgs;
1052        return sizeof(suiteb_sigalgs);
1053
1054    case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
1055        *psigs = suiteb_sigalgs;
1056        return 2;
1057
1058    case SSL_CERT_FLAG_SUITEB_192_LOS:
1059        *psigs = suiteb_sigalgs + 2;
1060        return 2;
1061    }
1062# endif
1063    /* If server use client authentication sigalgs if not NULL */
1064    if (s->server == sent && s->cert->client_sigalgs) {
1065        *psigs = s->cert->client_sigalgs;
1066        return s->cert->client_sigalgslen;
1067    } else if (s->cert->conf_sigalgs) {
1068        *psigs = s->cert->conf_sigalgs;
1069        return s->cert->conf_sigalgslen;
1070    } else {
1071        *psigs = tls12_sigalgs;
1072        return sizeof(tls12_sigalgs);
1073    }
1074}
1075
1076/*
1077 * Check signature algorithm is consistent with sent supported signature
1078 * algorithms and if so return relevant digest.
1079 */
1080int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
1081                            const unsigned char *sig, EVP_PKEY *pkey)
1082{
1083    const unsigned char *sent_sigs;
1084    size_t sent_sigslen, i;
1085    int sigalg = tls12_get_sigid(pkey);
1086    /* Should never happen */
1087    if (sigalg == -1)
1088        return -1;
1089    /* Check key type is consistent with signature */
1090    if (sigalg != (int)sig[1]) {
1091        SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
1092        return 0;
1093    }
1094# ifndef OPENSSL_NO_EC
1095    if (pkey->type == EVP_PKEY_EC) {
1096        unsigned char curve_id[2], comp_id;
1097        /* Check compression and curve matches extensions */
1098        if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
1099            return 0;
1100        if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id)) {
1101            SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
1102            return 0;
1103        }
1104        /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
1105        if (tls1_suiteb(s)) {
1106            if (curve_id[0])
1107                return 0;
1108            if (curve_id[1] == TLSEXT_curve_P_256) {
1109                if (sig[0] != TLSEXT_hash_sha256) {
1110                    SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1111                           SSL_R_ILLEGAL_SUITEB_DIGEST);
1112                    return 0;
1113                }
1114            } else if (curve_id[1] == TLSEXT_curve_P_384) {
1115                if (sig[0] != TLSEXT_hash_sha384) {
1116                    SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1117                           SSL_R_ILLEGAL_SUITEB_DIGEST);
1118                    return 0;
1119                }
1120            } else
1121                return 0;
1122        }
1123    } else if (tls1_suiteb(s))
1124        return 0;
1125# endif
1126
1127    /* Check signature matches a type we sent */
1128    sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
1129    for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) {
1130        if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
1131            break;
1132    }
1133    /* Allow fallback to SHA1 if not strict mode */
1134    if (i == sent_sigslen
1135        && (sig[0] != TLSEXT_hash_sha1
1136            || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
1137        SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
1138        return 0;
1139    }
1140    *pmd = tls12_get_hash(sig[0]);
1141    if (*pmd == NULL) {
1142        SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_UNKNOWN_DIGEST);
1143        return 0;
1144    }
1145    /*
1146     * Store the digest used so applications can retrieve it if they wish.
1147     */
1148    if (s->session && s->session->sess_cert)
1149        s->session->sess_cert->peer_key->digest = *pmd;
1150    return 1;
1151}
1152
1153/*
1154 * Get a mask of disabled algorithms: an algorithm is disabled if it isn't
1155 * supported or doesn't appear in supported signature algorithms. Unlike
1156 * ssl_cipher_get_disabled this applies to a specific session and not global
1157 * settings.
1158 */
1159void ssl_set_client_disabled(SSL *s)
1160{
1161    CERT *c = s->cert;
1162    const unsigned char *sigalgs;
1163    size_t i, sigalgslen;
1164    int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
1165    c->mask_a = 0;
1166    c->mask_k = 0;
1167    /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
1168    if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
1169        c->mask_ssl = SSL_TLSV1_2;
1170    else
1171        c->mask_ssl = 0;
1172    /*
1173     * Now go through all signature algorithms seeing if we support any for
1174     * RSA, DSA, ECDSA. Do this for all versions not just TLS 1.2.
1175     */
1176    sigalgslen = tls12_get_psigalgs(s, 1, &sigalgs);
1177    for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) {
1178        switch (sigalgs[1]) {
1179# ifndef OPENSSL_NO_RSA
1180        case TLSEXT_signature_rsa:
1181            have_rsa = 1;
1182            break;
1183# endif
1184# ifndef OPENSSL_NO_DSA
1185        case TLSEXT_signature_dsa:
1186            have_dsa = 1;
1187            break;
1188# endif
1189# ifndef OPENSSL_NO_ECDSA
1190        case TLSEXT_signature_ecdsa:
1191            have_ecdsa = 1;
1192            break;
1193# endif
1194        }
1195    }
1196    /*
1197     * Disable auth and static DH if we don't include any appropriate
1198     * signature algorithms.
1199     */
1200    if (!have_rsa) {
1201        c->mask_a |= SSL_aRSA;
1202        c->mask_k |= SSL_kDHr | SSL_kECDHr;
1203    }
1204    if (!have_dsa) {
1205        c->mask_a |= SSL_aDSS;
1206        c->mask_k |= SSL_kDHd;
1207    }
1208    if (!have_ecdsa) {
1209        c->mask_a |= SSL_aECDSA;
1210        c->mask_k |= SSL_kECDHe;
1211    }
1212# ifndef OPENSSL_NO_KRB5
1213    if (!kssl_tgt_is_available(s->kssl_ctx)) {
1214        c->mask_a |= SSL_aKRB5;
1215        c->mask_k |= SSL_kKRB5;
1216    }
1217# endif
1218# ifndef OPENSSL_NO_PSK
1219    /* with PSK there must be client callback set */
1220    if (!s->psk_client_callback) {
1221        c->mask_a |= SSL_aPSK;
1222        c->mask_k |= SSL_kPSK;
1223    }
1224# endif                         /* OPENSSL_NO_PSK */
1225# ifndef OPENSSL_NO_SRP
1226    if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
1227        c->mask_a |= SSL_aSRP;
1228        c->mask_k |= SSL_kSRP;
1229    }
1230# endif
1231    c->valid = 1;
1232}
1233
1234unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf,
1235                                          unsigned char *limit, int *al)
1236{
1237    int extdatalen = 0;
1238    unsigned char *orig = buf;
1239    unsigned char *ret = buf;
1240# ifndef OPENSSL_NO_EC
1241    /* See if we support any ECC ciphersuites */
1242    int using_ecc = 0;
1243    if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) {
1244        int i;
1245        unsigned long alg_k, alg_a;
1246        STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1247
1248        for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) {
1249            SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1250
1251            alg_k = c->algorithm_mkey;
1252            alg_a = c->algorithm_auth;
1253            if ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)
1254                 || (alg_a & SSL_aECDSA))) {
1255                using_ecc = 1;
1256                break;
1257            }
1258        }
1259    }
1260# endif
1261
1262    /* don't add extensions for SSLv3 unless doing secure renegotiation */
1263    if (s->client_version == SSL3_VERSION && !s->s3->send_connection_binding)
1264        return orig;
1265
1266    ret += 2;
1267
1268    if (ret >= limit)
1269        return NULL;            /* this really never occurs, but ... */
1270
1271    if (s->tlsext_hostname != NULL) {
1272        /* Add TLS extension servername to the Client Hello message */
1273        size_t size_str;
1274
1275        /*-
1276         * check for enough space.
1277         * 4 for the servername type and entension length
1278         * 2 for servernamelist length
1279         * 1 for the hostname type
1280         * 2 for hostname length
1281         * + hostname length
1282         */
1283        size_str = strlen(s->tlsext_hostname);
1284        if (CHECKLEN(ret, 9 + size_str, limit))
1285            return NULL;
1286
1287        /* extension type and length */
1288        s2n(TLSEXT_TYPE_server_name, ret);
1289        s2n(size_str + 5, ret);
1290
1291        /* length of servername list */
1292        s2n(size_str + 3, ret);
1293
1294        /* hostname type, length and hostname */
1295        *(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name;
1296        s2n(size_str, ret);
1297        memcpy(ret, s->tlsext_hostname, size_str);
1298        ret += size_str;
1299    }
1300
1301    /* Add RI if renegotiating */
1302    if (s->renegotiate) {
1303        int el;
1304
1305        if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) {
1306            SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1307            return NULL;
1308        }
1309
1310        if ((limit - ret - 4 - el) < 0)
1311            return NULL;
1312
1313        s2n(TLSEXT_TYPE_renegotiate, ret);
1314        s2n(el, ret);
1315
1316        if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) {
1317            SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1318            return NULL;
1319        }
1320
1321        ret += el;
1322    }
1323# ifndef OPENSSL_NO_SRP
1324    /* Add SRP username if there is one */
1325    if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the
1326                                     * Client Hello message */
1327
1328        size_t login_len = strlen(s->srp_ctx.login);
1329        if (login_len > 255 || login_len == 0) {
1330            SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1331            return NULL;
1332        }
1333
1334        /*-
1335         * check for enough space.
1336         * 4 for the srp type type and entension length
1337         * 1 for the srp user identity
1338         * + srp user identity length
1339         */
1340        if (CHECKLEN(ret, 5 + login_len, limit))
1341            return NULL;
1342
1343        /* fill in the extension */
1344        s2n(TLSEXT_TYPE_srp, ret);
1345        s2n(login_len + 1, ret);
1346        (*ret++) = (unsigned char)login_len;
1347        memcpy(ret, s->srp_ctx.login, login_len);
1348        ret += login_len;
1349    }
1350# endif
1351
1352# ifndef OPENSSL_NO_EC
1353    if (using_ecc) {
1354        /*
1355         * Add TLS extension ECPointFormats to the ClientHello message
1356         */
1357        const unsigned char *pcurves, *pformats;
1358        size_t num_curves, num_formats, curves_list_len;
1359
1360        tls1_get_formatlist(s, &pformats, &num_formats);
1361
1362        if (num_formats > 255) {
1363            SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1364            return NULL;
1365        }
1366        /*-
1367         * check for enough space.
1368         * 4 bytes for the ec point formats type and extension length
1369         * 1 byte for the length of the formats
1370         * + formats length
1371         */
1372        if (CHECKLEN(ret, 5 + num_formats, limit))
1373            return NULL;
1374
1375        s2n(TLSEXT_TYPE_ec_point_formats, ret);
1376        /* The point format list has 1-byte length. */
1377        s2n(num_formats + 1, ret);
1378        *(ret++) = (unsigned char)num_formats;
1379        memcpy(ret, pformats, num_formats);
1380        ret += num_formats;
1381
1382        /*
1383         * Add TLS extension EllipticCurves to the ClientHello message
1384         */
1385        pcurves = s->tlsext_ellipticcurvelist;
1386        if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves))
1387            return NULL;
1388
1389        if (num_curves > 65532 / 2) {
1390            SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1391            return NULL;
1392        }
1393        curves_list_len = 2 * num_curves;
1394        /*-
1395         * check for enough space.
1396         * 4 bytes for the ec curves type and extension length
1397         * 2 bytes for the curve list length
1398         * + curve list length
1399         */
1400        if (CHECKLEN(ret, 6 + curves_list_len, limit))
1401            return NULL;
1402
1403        s2n(TLSEXT_TYPE_elliptic_curves, ret);
1404        s2n(curves_list_len + 2, ret);
1405        s2n(curves_list_len, ret);
1406        memcpy(ret, pcurves, curves_list_len);
1407        ret += curves_list_len;
1408    }
1409# endif                         /* OPENSSL_NO_EC */
1410
1411    if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
1412        size_t ticklen;
1413        if (!s->new_session && s->session && s->session->tlsext_tick)
1414            ticklen = s->session->tlsext_ticklen;
1415        else if (s->session && s->tlsext_session_ticket &&
1416                 s->tlsext_session_ticket->data) {
1417            ticklen = s->tlsext_session_ticket->length;
1418            s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1419            if (!s->session->tlsext_tick)
1420                return NULL;
1421            memcpy(s->session->tlsext_tick,
1422                   s->tlsext_session_ticket->data, ticklen);
1423            s->session->tlsext_ticklen = ticklen;
1424        } else
1425            ticklen = 0;
1426        if (ticklen == 0 && s->tlsext_session_ticket &&
1427            s->tlsext_session_ticket->data == NULL)
1428            goto skip_ext;
1429        /*
1430         * Check for enough room 2 for extension type, 2 for len rest for
1431         * ticket
1432         */
1433        if (CHECKLEN(ret, 4 + ticklen, limit))
1434            return NULL;
1435        s2n(TLSEXT_TYPE_session_ticket, ret);
1436        s2n(ticklen, ret);
1437        if (ticklen > 0) {
1438            memcpy(ret, s->session->tlsext_tick, ticklen);
1439            ret += ticklen;
1440        }
1441    }
1442 skip_ext:
1443
1444    if (SSL_CLIENT_USE_SIGALGS(s)) {
1445        size_t salglen;
1446        const unsigned char *salg;
1447        salglen = tls12_get_psigalgs(s, 1, &salg);
1448
1449        /*-
1450         * check for enough space.
1451         * 4 bytes for the sigalgs type and extension length
1452         * 2 bytes for the sigalg list length
1453         * + sigalg list length
1454         */
1455        if (CHECKLEN(ret, salglen + 6, limit))
1456            return NULL;
1457        s2n(TLSEXT_TYPE_signature_algorithms, ret);
1458        s2n(salglen + 2, ret);
1459        s2n(salglen, ret);
1460        memcpy(ret, salg, salglen);
1461        ret += salglen;
1462    }
1463# ifdef TLSEXT_TYPE_opaque_prf_input
1464    if (s->s3->client_opaque_prf_input != NULL) {
1465        size_t col = s->s3->client_opaque_prf_input_len;
1466
1467        if ((long)(limit - ret - 6 - col < 0))
1468            return NULL;
1469        if (col > 0xFFFD)       /* can't happen */
1470            return NULL;
1471
1472        s2n(TLSEXT_TYPE_opaque_prf_input, ret);
1473        s2n(col + 2, ret);
1474        s2n(col, ret);
1475        memcpy(ret, s->s3->client_opaque_prf_input, col);
1476        ret += col;
1477    }
1478# endif
1479
1480    if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
1481        int i;
1482        size_t extlen, idlen;
1483        int lentmp;
1484        OCSP_RESPID *id;
1485
1486        idlen = 0;
1487        for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
1488            id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1489            lentmp = i2d_OCSP_RESPID(id, NULL);
1490            if (lentmp <= 0)
1491                return NULL;
1492            idlen += (size_t)lentmp + 2;
1493        }
1494
1495        if (s->tlsext_ocsp_exts) {
1496            lentmp = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1497            if (lentmp < 0)
1498                return NULL;
1499            extlen = (size_t)lentmp;
1500        } else
1501            extlen = 0;
1502
1503        if (extlen + idlen > 0xFFF0)
1504            return NULL;
1505        /*
1506         * 2 bytes for status request type
1507         * 2 bytes for status request len
1508         * 1 byte for OCSP request type
1509         * 2 bytes for length of ids
1510         * 2 bytes for length of extensions
1511         * + length of ids
1512         * + length of extensions
1513         */
1514        if (CHECKLEN(ret, 9 + idlen + extlen, limit))
1515            return NULL;
1516
1517        s2n(TLSEXT_TYPE_status_request, ret);
1518        s2n(extlen + idlen + 5, ret);
1519        *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1520        s2n(idlen, ret);
1521        for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
1522            /* save position of id len */
1523            unsigned char *q = ret;
1524            id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1525            /* skip over id len */
1526            ret += 2;
1527            lentmp = i2d_OCSP_RESPID(id, &ret);
1528            /* write id len */
1529            s2n(lentmp, q);
1530        }
1531        s2n(extlen, ret);
1532        if (extlen > 0)
1533            i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1534    }
1535# ifndef OPENSSL_NO_HEARTBEATS
1536    /* Add Heartbeat extension */
1537
1538    /*-
1539     * check for enough space.
1540     * 4 bytes for the heartbeat ext type and extension length
1541     * 1 byte for the mode
1542     */
1543    if (CHECKLEN(ret, 5, limit))
1544        return NULL;
1545
1546    s2n(TLSEXT_TYPE_heartbeat, ret);
1547    s2n(1, ret);
1548    /*-
1549     * Set mode:
1550     * 1: peer may send requests
1551     * 2: peer not allowed to send requests
1552     */
1553    if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1554        *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1555    else
1556        *(ret++) = SSL_TLSEXT_HB_ENABLED;
1557# endif
1558
1559# ifndef OPENSSL_NO_NEXTPROTONEG
1560    if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) {
1561        /*
1562         * The client advertises an emtpy extension to indicate its support
1563         * for Next Protocol Negotiation
1564         */
1565
1566        /*-
1567         * check for enough space.
1568         * 4 bytes for the NPN ext type and extension length
1569         */
1570        if (CHECKLEN(ret, 4, limit))
1571            return NULL;
1572        s2n(TLSEXT_TYPE_next_proto_neg, ret);
1573        s2n(0, ret);
1574    }
1575# endif
1576
1577    if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) {
1578        /*-
1579         * check for enough space.
1580         * 4 bytes for the ALPN type and extension length
1581         * 2 bytes for the ALPN protocol list length
1582         * + ALPN protocol list length
1583         */
1584        if (CHECKLEN(ret, 6 + s->alpn_client_proto_list_len, limit))
1585            return NULL;
1586        s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
1587        s2n(2 + s->alpn_client_proto_list_len, ret);
1588        s2n(s->alpn_client_proto_list_len, ret);
1589        memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len);
1590        ret += s->alpn_client_proto_list_len;
1591        s->cert->alpn_sent = 1;
1592    }
1593# ifndef OPENSSL_NO_SRTP
1594    if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) {
1595        int el;
1596
1597        ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1598
1599        /*-
1600         * check for enough space.
1601         * 4 bytes for the SRTP type and extension length
1602         * + SRTP profiles length
1603         */
1604        if (CHECKLEN(ret, 4 + el, limit))
1605            return NULL;
1606
1607        s2n(TLSEXT_TYPE_use_srtp, ret);
1608        s2n(el, ret);
1609
1610        if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) {
1611            SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1612            return NULL;
1613        }
1614        ret += el;
1615    }
1616# endif
1617    custom_ext_init(&s->cert->cli_ext);
1618    /* Add custom TLS Extensions to ClientHello */
1619    if (!custom_ext_add(s, 0, &ret, limit, al))
1620        return NULL;
1621
1622    /*
1623     * Add padding to workaround bugs in F5 terminators. See
1624     * https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this
1625     * code works out the length of all existing extensions it MUST always
1626     * appear last.
1627     */
1628    if (s->options & SSL_OP_TLSEXT_PADDING) {
1629        int hlen = ret - (unsigned char *)s->init_buf->data;
1630        /*
1631         * The code in s23_clnt.c to build ClientHello messages includes the
1632         * 5-byte record header in the buffer, while the code in s3_clnt.c
1633         * does not.
1634         */
1635        if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
1636            hlen -= 5;
1637        if (hlen > 0xff && hlen < 0x200) {
1638            hlen = 0x200 - hlen;
1639            if (hlen >= 4)
1640                hlen -= 4;
1641            else
1642                hlen = 0;
1643
1644            /*-
1645             * check for enough space. Strictly speaking we know we've already
1646             * got enough space because to get here the message size is < 0x200,
1647             * but we know that we've allocated far more than that in the buffer
1648             * - but for consistency and robustness we're going to check anyway.
1649             *
1650             * 4 bytes for the padding type and extension length
1651             * + padding length
1652             */
1653            if (CHECKLEN(ret, 4 + hlen, limit))
1654                return NULL;
1655            s2n(TLSEXT_TYPE_padding, ret);
1656            s2n(hlen, ret);
1657            memset(ret, 0, hlen);
1658            ret += hlen;
1659        }
1660    }
1661
1662    if ((extdatalen = ret - orig - 2) == 0)
1663        return orig;
1664
1665    s2n(extdatalen, orig);
1666    return ret;
1667}
1668
1669unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,
1670                                          unsigned char *limit, int *al)
1671{
1672    int extdatalen = 0;
1673    unsigned char *orig = buf;
1674    unsigned char *ret = buf;
1675# ifndef OPENSSL_NO_NEXTPROTONEG
1676    int next_proto_neg_seen;
1677# endif
1678# ifndef OPENSSL_NO_EC
1679    unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1680    unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1681    int using_ecc = (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
1682        || (alg_a & SSL_aECDSA);
1683    using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1684# endif
1685    /*
1686     * don't add extensions for SSLv3, unless doing secure renegotiation
1687     */
1688    if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1689        return orig;
1690
1691    ret += 2;
1692    if (ret >= limit)
1693        return NULL;            /* this really never occurs, but ... */
1694
1695    if (!s->hit && s->servername_done == 1
1696        && s->session->tlsext_hostname != NULL) {
1697        if ((long)(limit - ret - 4) < 0)
1698            return NULL;
1699
1700        s2n(TLSEXT_TYPE_server_name, ret);
1701        s2n(0, ret);
1702    }
1703
1704    if (s->s3->send_connection_binding) {
1705        int el;
1706
1707        if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) {
1708            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1709            return NULL;
1710        }
1711
1712        /*-
1713         * check for enough space.
1714         * 4 bytes for the reneg type and extension length
1715         * + reneg data length
1716         */
1717        if (CHECKLEN(ret, 4 + el, limit))
1718            return NULL;
1719
1720        s2n(TLSEXT_TYPE_renegotiate, ret);
1721        s2n(el, ret);
1722
1723        if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) {
1724            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1725            return NULL;
1726        }
1727
1728        ret += el;
1729    }
1730# ifndef OPENSSL_NO_EC
1731    if (using_ecc) {
1732        const unsigned char *plist;
1733        size_t plistlen;
1734        /*
1735         * Add TLS extension ECPointFormats to the ServerHello message
1736         */
1737
1738        tls1_get_formatlist(s, &plist, &plistlen);
1739
1740        if (plistlen > 255) {
1741            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1742            return NULL;
1743        }
1744
1745        /*-
1746         * check for enough space.
1747         * 4 bytes for the ec points format type and extension length
1748         * 1 byte for the points format list length
1749         * + length of points format list
1750         */
1751        if (CHECKLEN(ret, 5 + plistlen, limit))
1752            return NULL;
1753
1754        s2n(TLSEXT_TYPE_ec_point_formats, ret);
1755        s2n(plistlen + 1, ret);
1756        *(ret++) = (unsigned char)plistlen;
1757        memcpy(ret, plist, plistlen);
1758        ret += plistlen;
1759
1760    }
1761    /*
1762     * Currently the server should not respond with a SupportedCurves
1763     * extension
1764     */
1765# endif                         /* OPENSSL_NO_EC */
1766
1767    if (s->tlsext_ticket_expected && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
1768        /*-
1769         * check for enough space.
1770         * 4 bytes for the Ticket type and extension length
1771         */
1772        if (CHECKLEN(ret, 4, limit))
1773            return NULL;
1774        s2n(TLSEXT_TYPE_session_ticket, ret);
1775        s2n(0, ret);
1776    } else {
1777        /* if we don't add the above TLSEXT, we can't add a session ticket later */
1778        s->tlsext_ticket_expected = 0;
1779    }
1780
1781    if (s->tlsext_status_expected) {
1782        /*-
1783         * check for enough space.
1784         * 4 bytes for the Status request type and extension length
1785         */
1786        if (CHECKLEN(ret, 4, limit))
1787            return NULL;
1788        s2n(TLSEXT_TYPE_status_request, ret);
1789        s2n(0, ret);
1790    }
1791# ifdef TLSEXT_TYPE_opaque_prf_input
1792    if (s->s3->server_opaque_prf_input != NULL) {
1793        size_t sol = s->s3->server_opaque_prf_input_len;
1794
1795        if ((long)(limit - ret - 6 - sol) < 0)
1796            return NULL;
1797        if (sol > 0xFFFD)       /* can't happen */
1798            return NULL;
1799
1800        s2n(TLSEXT_TYPE_opaque_prf_input, ret);
1801        s2n(sol + 2, ret);
1802        s2n(sol, ret);
1803        memcpy(ret, s->s3->server_opaque_prf_input, sol);
1804        ret += sol;
1805    }
1806# endif
1807
1808# ifndef OPENSSL_NO_SRTP
1809    if (SSL_IS_DTLS(s) && s->srtp_profile) {
1810        int el;
1811
1812        ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1813
1814        /*-
1815         * check for enough space.
1816         * 4 bytes for the SRTP profiles type and extension length
1817         * + length of the SRTP profiles list
1818         */
1819        if (CHECKLEN(ret, 4 + el, limit))
1820            return NULL;
1821
1822        s2n(TLSEXT_TYPE_use_srtp, ret);
1823        s2n(el, ret);
1824
1825        if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) {
1826            SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1827            return NULL;
1828        }
1829        ret += el;
1830    }
1831# endif
1832
1833    if (((s->s3->tmp.new_cipher->id & 0xFFFF) == 0x80
1834         || (s->s3->tmp.new_cipher->id & 0xFFFF) == 0x81)
1835        && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) {
1836        const unsigned char cryptopro_ext[36] = {
1837            0xfd, 0xe8,         /* 65000 */
1838            0x00, 0x20,         /* 32 bytes length */
1839            0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1840            0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1841            0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1842            0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1843        };
1844
1845        /* check for enough space. */
1846        if (CHECKLEN(ret, sizeof(cryptopro_ext), limit))
1847            return NULL;
1848        memcpy(ret, cryptopro_ext, sizeof(cryptopro_ext));
1849        ret += sizeof(cryptopro_ext);
1850
1851    }
1852# ifndef OPENSSL_NO_HEARTBEATS
1853    /* Add Heartbeat extension if we've received one */
1854    if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) {
1855        /*-
1856         * check for enough space.
1857         * 4 bytes for the Heartbeat type and extension length
1858         * 1 byte for the mode
1859         */
1860        if (CHECKLEN(ret, 5, limit))
1861            return NULL;
1862        s2n(TLSEXT_TYPE_heartbeat, ret);
1863        s2n(1, ret);
1864        /*-
1865         * Set mode:
1866         * 1: peer may send requests
1867         * 2: peer not allowed to send requests
1868         */
1869        if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1870            *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1871        else
1872            *(ret++) = SSL_TLSEXT_HB_ENABLED;
1873
1874    }
1875# endif
1876
1877# ifndef OPENSSL_NO_NEXTPROTONEG
1878    next_proto_neg_seen = s->s3->next_proto_neg_seen;
1879    s->s3->next_proto_neg_seen = 0;
1880    if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) {
1881        const unsigned char *npa;
1882        unsigned int npalen;
1883        int r;
1884
1885        r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,
1886                                              s->
1887                                              ctx->next_protos_advertised_cb_arg);
1888        if (r == SSL_TLSEXT_ERR_OK) {
1889            /*-
1890             * check for enough space.
1891             * 4 bytes for the NPN type and extension length
1892             * + length of protocols list
1893             */
1894            if (CHECKLEN(ret, 4 + npalen, limit))
1895                return NULL;
1896            s2n(TLSEXT_TYPE_next_proto_neg, ret);
1897            s2n(npalen, ret);
1898            memcpy(ret, npa, npalen);
1899            ret += npalen;
1900            s->s3->next_proto_neg_seen = 1;
1901        }
1902    }
1903# endif
1904    if (!custom_ext_add(s, 1, &ret, limit, al))
1905        return NULL;
1906
1907    if (s->s3->alpn_selected) {
1908        const unsigned char *selected = s->s3->alpn_selected;
1909        size_t len = s->s3->alpn_selected_len;
1910
1911        /*-
1912         * check for enough space.
1913         * 4 bytes for the ALPN type and extension length
1914         * 2 bytes for ALPN data length
1915         * 1 byte for selected protocol length
1916         * + length of the selected protocol
1917         */
1918        if (CHECKLEN(ret, 7 + len, limit))
1919            return NULL;
1920        s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
1921        s2n(3 + len, ret);
1922        s2n(1 + len, ret);
1923        *ret++ = (unsigned char)len;
1924        memcpy(ret, selected, len);
1925        ret += len;
1926    }
1927
1928    if ((extdatalen = ret - orig - 2) == 0)
1929        return orig;
1930
1931    s2n(extdatalen, orig);
1932    return ret;
1933}
1934
1935# ifndef OPENSSL_NO_EC
1936/*-
1937 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1938 * SecureTransport using the TLS extension block in |d|, of length |n|.
1939 * Safari, since 10.6, sends exactly these extensions, in this order:
1940 *   SNI,
1941 *   elliptic_curves
1942 *   ec_point_formats
1943 *
1944 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1945 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1946 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1947 * 10.8..10.8.3 (which don't work).
1948 */
1949static void ssl_check_for_safari(SSL *s, const unsigned char *data,
1950                                 const unsigned char *limit)
1951{
1952    unsigned short type, size;
1953    static const unsigned char kSafariExtensionsBlock[] = {
1954        0x00, 0x0a,             /* elliptic_curves extension */
1955        0x00, 0x08,             /* 8 bytes */
1956        0x00, 0x06,             /* 6 bytes of curve ids */
1957        0x00, 0x17,             /* P-256 */
1958        0x00, 0x18,             /* P-384 */
1959        0x00, 0x19,             /* P-521 */
1960
1961        0x00, 0x0b,             /* ec_point_formats */
1962        0x00, 0x02,             /* 2 bytes */
1963        0x01,                   /* 1 point format */
1964        0x00,                   /* uncompressed */
1965    };
1966
1967    /* The following is only present in TLS 1.2 */
1968    static const unsigned char kSafariTLS12ExtensionsBlock[] = {
1969        0x00, 0x0d,             /* signature_algorithms */
1970        0x00, 0x0c,             /* 12 bytes */
1971        0x00, 0x0a,             /* 10 bytes */
1972        0x05, 0x01,             /* SHA-384/RSA */
1973        0x04, 0x01,             /* SHA-256/RSA */
1974        0x02, 0x01,             /* SHA-1/RSA */
1975        0x04, 0x03,             /* SHA-256/ECDSA */
1976        0x02, 0x03,             /* SHA-1/ECDSA */
1977    };
1978
1979    if (limit - data <= 2)
1980        return;
1981    data += 2;
1982
1983    if (limit - data < 4)
1984        return;
1985    n2s(data, type);
1986    n2s(data, size);
1987
1988    if (type != TLSEXT_TYPE_server_name)
1989        return;
1990
1991    if (limit - data < size)
1992        return;
1993    data += size;
1994
1995    if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
1996        const size_t len1 = sizeof(kSafariExtensionsBlock);
1997        const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
1998
1999        if (limit - data != (int)(len1 + len2))
2000            return;
2001        if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
2002            return;
2003        if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
2004            return;
2005    } else {
2006        const size_t len = sizeof(kSafariExtensionsBlock);
2007
2008        if (limit - data != (int)(len))
2009            return;
2010        if (memcmp(data, kSafariExtensionsBlock, len) != 0)
2011            return;
2012    }
2013
2014    s->s3->is_probably_safari = 1;
2015}
2016# endif                         /* !OPENSSL_NO_EC */
2017
2018/*
2019 * tls1_alpn_handle_client_hello is called to save the ALPN extension in a
2020 * ClientHello.  data: the contents of the extension, not including the type
2021 * and length.  data_len: the number of bytes in |data| al: a pointer to the
2022 * alert value to send in the event of a non-zero return.  returns: 0 on
2023 * success.
2024 */
2025static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
2026                                         unsigned data_len, int *al)
2027{
2028    unsigned i;
2029    unsigned proto_len;
2030
2031    if (data_len < 2)
2032        goto parse_error;
2033
2034    /*
2035     * data should contain a uint16 length followed by a series of 8-bit,
2036     * length-prefixed strings.
2037     */
2038    i = ((unsigned)data[0]) << 8 | ((unsigned)data[1]);
2039    data_len -= 2;
2040    data += 2;
2041    if (data_len != i)
2042        goto parse_error;
2043
2044    if (data_len < 2)
2045        goto parse_error;
2046
2047    for (i = 0; i < data_len;) {
2048        proto_len = data[i];
2049        i++;
2050
2051        if (proto_len == 0)
2052            goto parse_error;
2053
2054        if (i + proto_len < i || i + proto_len > data_len)
2055            goto parse_error;
2056
2057        i += proto_len;
2058    }
2059
2060    if (s->cert->alpn_proposed != NULL)
2061        OPENSSL_free(s->cert->alpn_proposed);
2062    s->cert->alpn_proposed = OPENSSL_malloc(data_len);
2063    if (s->cert->alpn_proposed == NULL) {
2064        *al = SSL_AD_INTERNAL_ERROR;
2065        return -1;
2066    }
2067    memcpy(s->cert->alpn_proposed, data, data_len);
2068    s->cert->alpn_proposed_len = data_len;
2069    return 0;
2070
2071 parse_error:
2072    *al = SSL_AD_DECODE_ERROR;
2073    return -1;
2074}
2075
2076/*
2077 * Process the ALPN extension in a ClientHello.
2078 * al: a pointer to the alert value to send in the event of a failure.
2079 * returns 1 on success, 0 on failure: al set only on failure
2080 */
2081static int tls1_alpn_handle_client_hello_late(SSL *s, int *al)
2082{
2083    const unsigned char *selected = NULL;
2084    unsigned char selected_len = 0;
2085
2086    if (s->ctx->alpn_select_cb != NULL && s->cert->alpn_proposed != NULL) {
2087        int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
2088                                       s->cert->alpn_proposed,
2089                                       s->cert->alpn_proposed_len,
2090                                       s->ctx->alpn_select_cb_arg);
2091
2092        if (r == SSL_TLSEXT_ERR_OK) {
2093            OPENSSL_free(s->s3->alpn_selected);
2094            s->s3->alpn_selected = OPENSSL_malloc(selected_len);
2095            if (s->s3->alpn_selected == NULL) {
2096                *al = SSL_AD_INTERNAL_ERROR;
2097                return 0;
2098            }
2099            memcpy(s->s3->alpn_selected, selected, selected_len);
2100            s->s3->alpn_selected_len = selected_len;
2101# ifndef OPENSSL_NO_NEXTPROTONEG
2102            /* ALPN takes precedence over NPN. */
2103            s->s3->next_proto_neg_seen = 0;
2104# endif
2105        }
2106    }
2107
2108    return 1;
2109}
2110
2111static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p,
2112                                       unsigned char *limit, int *al)
2113{
2114    unsigned short type;
2115    unsigned short size;
2116    unsigned short len;
2117    unsigned char *data = *p;
2118    int renegotiate_seen = 0;
2119
2120    s->servername_done = 0;
2121    s->tlsext_status_type = -1;
2122# ifndef OPENSSL_NO_NEXTPROTONEG
2123    s->s3->next_proto_neg_seen = 0;
2124# endif
2125
2126    if (s->s3->alpn_selected) {
2127        OPENSSL_free(s->s3->alpn_selected);
2128        s->s3->alpn_selected = NULL;
2129    }
2130    s->s3->alpn_selected_len = 0;
2131    if (s->cert->alpn_proposed) {
2132        OPENSSL_free(s->cert->alpn_proposed);
2133        s->cert->alpn_proposed = NULL;
2134    }
2135    s->cert->alpn_proposed_len = 0;
2136# ifndef OPENSSL_NO_HEARTBEATS
2137    s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2138                             SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2139# endif
2140
2141# ifndef OPENSSL_NO_EC
2142    if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
2143        ssl_check_for_safari(s, data, limit);
2144# endif                         /* !OPENSSL_NO_EC */
2145
2146    /* Clear any signature algorithms extension received */
2147    if (s->cert->peer_sigalgs) {
2148        OPENSSL_free(s->cert->peer_sigalgs);
2149        s->cert->peer_sigalgs = NULL;
2150    }
2151# ifndef OPENSSL_NO_SRP
2152    if (s->srp_ctx.login != NULL) {
2153        OPENSSL_free(s->srp_ctx.login);
2154        s->srp_ctx.login = NULL;
2155    }
2156# endif
2157
2158    s->srtp_profile = NULL;
2159
2160    if (data == limit)
2161        goto ri_check;
2162
2163    if (limit - data < 2)
2164        goto err;
2165
2166    n2s(data, len);
2167
2168    if (limit - data != len)
2169        goto err;
2170
2171    while (limit - data >= 4) {
2172        n2s(data, type);
2173        n2s(data, size);
2174
2175        if (limit - data < size)
2176            goto err;
2177# if 0
2178        fprintf(stderr, "Received extension type %d size %d\n", type, size);
2179# endif
2180        if (s->tlsext_debug_cb)
2181            s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg);
2182/*-
2183 * The servername extension is treated as follows:
2184 *
2185 * - Only the hostname type is supported with a maximum length of 255.
2186 * - The servername is rejected if too long or if it contains zeros,
2187 *   in which case an fatal alert is generated.
2188 * - The servername field is maintained together with the session cache.
2189 * - When a session is resumed, the servername call back invoked in order
2190 *   to allow the application to position itself to the right context.
2191 * - The servername is acknowledged if it is new for a session or when
2192 *   it is identical to a previously used for the same session.
2193 *   Applications can control the behaviour.  They can at any time
2194 *   set a 'desirable' servername for a new SSL object. This can be the
2195 *   case for example with HTTPS when a Host: header field is received and
2196 *   a renegotiation is requested. In this case, a possible servername
2197 *   presented in the new client hello is only acknowledged if it matches
2198 *   the value of the Host: field.
2199 * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2200 *   if they provide for changing an explicit servername context for the
2201 *   session, i.e. when the session has been established with a servername
2202 *   extension.
2203 * - On session reconnect, the servername extension may be absent.
2204 *
2205 */
2206
2207        if (type == TLSEXT_TYPE_server_name) {
2208            unsigned char *sdata;
2209            int servname_type;
2210            int dsize;
2211
2212            if (size < 2)
2213                goto err;
2214            n2s(data, dsize);
2215            size -= 2;
2216            if (dsize > size)
2217                goto err;
2218
2219            sdata = data;
2220            while (dsize > 3) {
2221                servname_type = *(sdata++);
2222                n2s(sdata, len);
2223                dsize -= 3;
2224
2225                if (len > dsize)
2226                    goto err;
2227
2228                if (s->servername_done == 0)
2229                    switch (servname_type) {
2230                    case TLSEXT_NAMETYPE_host_name:
2231                        if (!s->hit) {
2232                            if (s->session->tlsext_hostname)
2233                                goto err;
2234
2235                            if (len > TLSEXT_MAXLEN_host_name) {
2236                                *al = TLS1_AD_UNRECOGNIZED_NAME;
2237                                return 0;
2238                            }
2239                            if ((s->session->tlsext_hostname =
2240                                 OPENSSL_malloc(len + 1)) == NULL) {
2241                                *al = TLS1_AD_INTERNAL_ERROR;
2242                                return 0;
2243                            }
2244                            memcpy(s->session->tlsext_hostname, sdata, len);
2245                            s->session->tlsext_hostname[len] = '\0';
2246                            if (strlen(s->session->tlsext_hostname) != len) {
2247                                OPENSSL_free(s->session->tlsext_hostname);
2248                                s->session->tlsext_hostname = NULL;
2249                                *al = TLS1_AD_UNRECOGNIZED_NAME;
2250                                return 0;
2251                            }
2252                            s->servername_done = 1;
2253
2254                        } else
2255                            s->servername_done = s->session->tlsext_hostname
2256                                && strlen(s->session->tlsext_hostname) == len
2257                                && strncmp(s->session->tlsext_hostname,
2258                                           (char *)sdata, len) == 0;
2259
2260                        break;
2261
2262                    default:
2263                        break;
2264                    }
2265
2266                dsize -= len;
2267            }
2268            if (dsize != 0)
2269                goto err;
2270
2271        }
2272# ifndef OPENSSL_NO_SRP
2273        else if (type == TLSEXT_TYPE_srp) {
2274            if (size == 0 || ((len = data[0])) != (size - 1))
2275                goto err;
2276            if (s->srp_ctx.login != NULL)
2277                goto err;
2278            if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL)
2279                return -1;
2280            memcpy(s->srp_ctx.login, &data[1], len);
2281            s->srp_ctx.login[len] = '\0';
2282
2283            if (strlen(s->srp_ctx.login) != len)
2284                goto err;
2285        }
2286# endif
2287
2288# ifndef OPENSSL_NO_EC
2289        else if (type == TLSEXT_TYPE_ec_point_formats) {
2290            unsigned char *sdata = data;
2291            int ecpointformatlist_length;
2292
2293            if (size == 0)
2294                goto err;
2295
2296            ecpointformatlist_length = *(sdata++);
2297            if (ecpointformatlist_length != size - 1 ||
2298                ecpointformatlist_length < 1)
2299                goto err;
2300            if (!s->hit) {
2301                if (s->session->tlsext_ecpointformatlist) {
2302                    OPENSSL_free(s->session->tlsext_ecpointformatlist);
2303                    s->session->tlsext_ecpointformatlist = NULL;
2304                }
2305                s->session->tlsext_ecpointformatlist_length = 0;
2306                if ((s->session->tlsext_ecpointformatlist =
2307                     OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
2308                    *al = TLS1_AD_INTERNAL_ERROR;
2309                    return 0;
2310                }
2311                s->session->tlsext_ecpointformatlist_length =
2312                    ecpointformatlist_length;
2313                memcpy(s->session->tlsext_ecpointformatlist, sdata,
2314                       ecpointformatlist_length);
2315            }
2316#  if 0
2317            fprintf(stderr,
2318                    "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ",
2319                    s->session->tlsext_ecpointformatlist_length);
2320            sdata = s->session->tlsext_ecpointformatlist;
2321            for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2322                fprintf(stderr, "%i ", *(sdata++));
2323            fprintf(stderr, "\n");
2324#  endif
2325        } else if (type == TLSEXT_TYPE_elliptic_curves) {
2326            unsigned char *sdata = data;
2327            int ellipticcurvelist_length = (*(sdata++) << 8);
2328            ellipticcurvelist_length += (*(sdata++));
2329
2330            if (ellipticcurvelist_length != size - 2 ||
2331                ellipticcurvelist_length < 1 ||
2332                /* Each NamedCurve is 2 bytes. */
2333                ellipticcurvelist_length & 1)
2334                    goto err;
2335
2336            if (!s->hit) {
2337                if (s->session->tlsext_ellipticcurvelist)
2338                    goto err;
2339
2340                s->session->tlsext_ellipticcurvelist_length = 0;
2341                if ((s->session->tlsext_ellipticcurvelist =
2342                     OPENSSL_malloc(ellipticcurvelist_length)) == NULL) {
2343                    *al = TLS1_AD_INTERNAL_ERROR;
2344                    return 0;
2345                }
2346                s->session->tlsext_ellipticcurvelist_length =
2347                    ellipticcurvelist_length;
2348                memcpy(s->session->tlsext_ellipticcurvelist, sdata,
2349                       ellipticcurvelist_length);
2350            }
2351#  if 0
2352            fprintf(stderr,
2353                    "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ",
2354                    s->session->tlsext_ellipticcurvelist_length);
2355            sdata = s->session->tlsext_ellipticcurvelist;
2356            for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2357                fprintf(stderr, "%i ", *(sdata++));
2358            fprintf(stderr, "\n");
2359#  endif
2360        }
2361# endif                         /* OPENSSL_NO_EC */
2362# ifdef TLSEXT_TYPE_opaque_prf_input
2363        else if (type == TLSEXT_TYPE_opaque_prf_input) {
2364            unsigned char *sdata = data;
2365
2366            if (size < 2) {
2367                *al = SSL_AD_DECODE_ERROR;
2368                return 0;
2369            }
2370            n2s(sdata, s->s3->client_opaque_prf_input_len);
2371            if (s->s3->client_opaque_prf_input_len != size - 2) {
2372                *al = SSL_AD_DECODE_ERROR;
2373                return 0;
2374            }
2375
2376            if (s->s3->client_opaque_prf_input != NULL) {
2377                /* shouldn't really happen */
2378                OPENSSL_free(s->s3->client_opaque_prf_input);
2379            }
2380
2381            /* dummy byte just to get non-NULL */
2382            if (s->s3->client_opaque_prf_input_len == 0)
2383                s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
2384            else
2385                s->s3->client_opaque_prf_input =
2386                    BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2387            if (s->s3->client_opaque_prf_input == NULL) {
2388                *al = TLS1_AD_INTERNAL_ERROR;
2389                return 0;
2390            }
2391        }
2392# endif
2393        else if (type == TLSEXT_TYPE_session_ticket) {
2394            if (s->tls_session_ticket_ext_cb &&
2395                !s->tls_session_ticket_ext_cb(s, data, size,
2396                                              s->tls_session_ticket_ext_cb_arg))
2397            {
2398                *al = TLS1_AD_INTERNAL_ERROR;
2399                return 0;
2400            }
2401        } else if (type == TLSEXT_TYPE_renegotiate) {
2402            if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2403                return 0;
2404            renegotiate_seen = 1;
2405        } else if (type == TLSEXT_TYPE_signature_algorithms) {
2406            int dsize;
2407            if (s->cert->peer_sigalgs || size < 2)
2408                goto err;
2409            n2s(data, dsize);
2410            size -= 2;
2411            if (dsize != size || dsize & 1 || !dsize)
2412                goto err;
2413            if (!tls1_save_sigalgs(s, data, dsize))
2414                goto err;
2415        } else if (type == TLSEXT_TYPE_status_request && !s->hit) {
2416            if (size < 5)
2417                goto err;
2418
2419            s->tlsext_status_type = *data++;
2420            size--;
2421            if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
2422                const unsigned char *sdata;
2423                int dsize;
2424                /* Read in responder_id_list */
2425                n2s(data, dsize);
2426                size -= 2;
2427                if (dsize > size)
2428                    goto err;
2429
2430                /*
2431                 * We remove any OCSP_RESPIDs from a previous handshake
2432                 * to prevent unbounded memory growth - CVE-2016-6304
2433                 */
2434                sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids,
2435                                        OCSP_RESPID_free);
2436                if (dsize > 0) {
2437                    s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null();
2438                    if (s->tlsext_ocsp_ids == NULL) {
2439                        *al = SSL_AD_INTERNAL_ERROR;
2440                        return 0;
2441                    }
2442                } else {
2443                    s->tlsext_ocsp_ids = NULL;
2444                }
2445
2446                while (dsize > 0) {
2447                    OCSP_RESPID *id;
2448                    int idsize;
2449                    if (dsize < 4)
2450                        goto err;
2451                    n2s(data, idsize);
2452                    dsize -= 2 + idsize;
2453                    size -= 2 + idsize;
2454                    if (dsize < 0)
2455                        goto err;
2456                    sdata = data;
2457                    data += idsize;
2458                    id = d2i_OCSP_RESPID(NULL, &sdata, idsize);
2459                    if (!id)
2460                        goto err;
2461                    if (data != sdata) {
2462                        OCSP_RESPID_free(id);
2463                        goto err;
2464                    }
2465                    if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
2466                        OCSP_RESPID_free(id);
2467                        *al = SSL_AD_INTERNAL_ERROR;
2468                        return 0;
2469                    }
2470                }
2471
2472                /* Read in request_extensions */
2473                if (size < 2)
2474                    goto err;
2475                n2s(data, dsize);
2476                size -= 2;
2477                if (dsize != size)
2478                    goto err;
2479                sdata = data;
2480                if (dsize > 0) {
2481                    if (s->tlsext_ocsp_exts) {
2482                        sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2483                                                   X509_EXTENSION_free);
2484                    }
2485
2486                    s->tlsext_ocsp_exts =
2487                        d2i_X509_EXTENSIONS(NULL, &sdata, dsize);
2488                    if (!s->tlsext_ocsp_exts || (data + dsize != sdata))
2489                        goto err;
2490                }
2491            }
2492            /*
2493             * We don't know what to do with any other type * so ignore it.
2494             */
2495            else
2496                s->tlsext_status_type = -1;
2497        }
2498# ifndef OPENSSL_NO_HEARTBEATS
2499        else if (type == TLSEXT_TYPE_heartbeat) {
2500            switch (data[0]) {
2501            case 0x01:         /* Client allows us to send HB requests */
2502                s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2503                break;
2504            case 0x02:         /* Client doesn't accept HB requests */
2505                s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2506                s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2507                break;
2508            default:
2509                *al = SSL_AD_ILLEGAL_PARAMETER;
2510                return 0;
2511            }
2512        }
2513# endif
2514# ifndef OPENSSL_NO_NEXTPROTONEG
2515        else if (type == TLSEXT_TYPE_next_proto_neg &&
2516                 s->s3->tmp.finish_md_len == 0) {
2517            /*-
2518             * We shouldn't accept this extension on a
2519             * renegotiation.
2520             *
2521             * s->new_session will be set on renegotiation, but we
2522             * probably shouldn't rely that it couldn't be set on
2523             * the initial renegotation too in certain cases (when
2524             * there's some other reason to disallow resuming an
2525             * earlier session -- the current code won't be doing
2526             * anything like that, but this might change).
2527             *
2528             * A valid sign that there's been a previous handshake
2529             * in this connection is if s->s3->tmp.finish_md_len >
2530             * 0.  (We are talking about a check that will happen
2531             * in the Hello protocol round, well before a new
2532             * Finished message could have been computed.)
2533             */
2534            s->s3->next_proto_neg_seen = 1;
2535        }
2536# endif
2537
2538        else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2539                 s->s3->tmp.finish_md_len == 0) {
2540            if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2541                return 0;
2542        }
2543
2544        /* session ticket processed earlier */
2545# ifndef OPENSSL_NO_SRTP
2546        else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
2547                 && type == TLSEXT_TYPE_use_srtp) {
2548            if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al))
2549                return 0;
2550        }
2551# endif
2552
2553        data += size;
2554    }
2555
2556    /* Spurious data on the end */
2557    if (data != limit)
2558        goto err;
2559
2560    *p = data;
2561
2562 ri_check:
2563
2564    /* Need RI if renegotiating */
2565
2566    if (!renegotiate_seen && s->renegotiate &&
2567        !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
2568        *al = SSL_AD_HANDSHAKE_FAILURE;
2569        SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2570               SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2571        return 0;
2572    }
2573
2574    return 1;
2575err:
2576    *al = SSL_AD_DECODE_ERROR;
2577    return 0;
2578}
2579
2580/*
2581 * Parse any custom extensions found.  "data" is the start of the extension data
2582 * and "limit" is the end of the record. TODO: add strict syntax checking.
2583 */
2584
2585static int ssl_scan_clienthello_custom_tlsext(SSL *s,
2586                                              const unsigned char *data,
2587                                              const unsigned char *limit,
2588                                              int *al)
2589{
2590    unsigned short type, size, len;
2591    /* If resumed session or no custom extensions nothing to do */
2592    if (s->hit || s->cert->srv_ext.meths_count == 0)
2593        return 1;
2594
2595    if (limit - data <= 2)
2596        return 1;
2597    n2s(data, len);
2598
2599    if (limit - data < len)
2600        return 1;
2601
2602    while (limit - data >= 4) {
2603        n2s(data, type);
2604        n2s(data, size);
2605
2606        if (limit - data < size)
2607            return 1;
2608        if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0)
2609            return 0;
2610
2611        data += size;
2612    }
2613
2614    return 1;
2615}
2616
2617int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p,
2618                                 unsigned char *limit)
2619{
2620    int al = -1;
2621    unsigned char *ptmp = *p;
2622    /*
2623     * Internally supported extensions are parsed first so SNI can be handled
2624     * before custom extensions. An application processing SNI will typically
2625     * switch the parent context using SSL_set_SSL_CTX and custom extensions
2626     * need to be handled by the new SSL_CTX structure.
2627     */
2628    if (ssl_scan_clienthello_tlsext(s, p, limit, &al) <= 0) {
2629        ssl3_send_alert(s, SSL3_AL_FATAL, al);
2630        return 0;
2631    }
2632
2633    if (ssl_check_clienthello_tlsext_early(s) <= 0) {
2634        SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_CLIENTHELLO_TLSEXT);
2635        return 0;
2636    }
2637
2638    custom_ext_init(&s->cert->srv_ext);
2639    if (ssl_scan_clienthello_custom_tlsext(s, ptmp, limit, &al) <= 0) {
2640        ssl3_send_alert(s, SSL3_AL_FATAL, al);
2641        return 0;
2642    }
2643
2644    return 1;
2645}
2646
2647# ifndef OPENSSL_NO_NEXTPROTONEG
2648/*
2649 * ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2650 * elements of zero length are allowed and the set of elements must exactly
2651 * fill the length of the block.
2652 */
2653static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2654{
2655    unsigned int off = 0;
2656
2657    while (off < len) {
2658        if (d[off] == 0)
2659            return 0;
2660        off += d[off];
2661        off++;
2662    }
2663
2664    return off == len;
2665}
2666# endif
2667
2668static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p,
2669                                       unsigned char *d, int n, int *al)
2670{
2671    unsigned short length;
2672    unsigned short type;
2673    unsigned short size;
2674    unsigned char *data = *p;
2675    int tlsext_servername = 0;
2676    int renegotiate_seen = 0;
2677
2678# ifndef OPENSSL_NO_NEXTPROTONEG
2679    s->s3->next_proto_neg_seen = 0;
2680# endif
2681    s->tlsext_ticket_expected = 0;
2682
2683    if (s->s3->alpn_selected) {
2684        OPENSSL_free(s->s3->alpn_selected);
2685        s->s3->alpn_selected = NULL;
2686    }
2687# ifndef OPENSSL_NO_HEARTBEATS
2688    s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2689                             SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2690# endif
2691
2692    if ((d + n) - data <= 2)
2693        goto ri_check;
2694
2695    n2s(data, length);
2696    if ((d + n) - data != length) {
2697        *al = SSL_AD_DECODE_ERROR;
2698        return 0;
2699    }
2700
2701    while ((d + n) - data >= 4) {
2702        n2s(data, type);
2703        n2s(data, size);
2704
2705        if ((d + n) - data < size)
2706            goto ri_check;
2707
2708        if (s->tlsext_debug_cb)
2709            s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg);
2710
2711        if (type == TLSEXT_TYPE_server_name) {
2712            if (s->tlsext_hostname == NULL || size > 0) {
2713                *al = TLS1_AD_UNRECOGNIZED_NAME;
2714                return 0;
2715            }
2716            tlsext_servername = 1;
2717        }
2718# ifndef OPENSSL_NO_EC
2719        else if (type == TLSEXT_TYPE_ec_point_formats) {
2720            unsigned char *sdata = data;
2721            int ecpointformatlist_length;
2722
2723            if (size == 0) {
2724                *al = TLS1_AD_DECODE_ERROR;
2725                return 0;
2726            }
2727
2728            ecpointformatlist_length = *(sdata++);
2729            if (ecpointformatlist_length != size - 1) {
2730                *al = TLS1_AD_DECODE_ERROR;
2731                return 0;
2732            }
2733            if (!s->hit) {
2734                s->session->tlsext_ecpointformatlist_length = 0;
2735                if (s->session->tlsext_ecpointformatlist != NULL)
2736                    OPENSSL_free(s->session->tlsext_ecpointformatlist);
2737                if ((s->session->tlsext_ecpointformatlist =
2738                     OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
2739                    *al = TLS1_AD_INTERNAL_ERROR;
2740                    return 0;
2741                }
2742                s->session->tlsext_ecpointformatlist_length =
2743                    ecpointformatlist_length;
2744                memcpy(s->session->tlsext_ecpointformatlist, sdata,
2745                       ecpointformatlist_length);
2746            }
2747#  if 0
2748            fprintf(stderr,
2749                    "ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2750            sdata = s->session->tlsext_ecpointformatlist;
2751            for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2752                fprintf(stderr, "%i ", *(sdata++));
2753            fprintf(stderr, "\n");
2754#  endif
2755        }
2756# endif                         /* OPENSSL_NO_EC */
2757
2758        else if (type == TLSEXT_TYPE_session_ticket) {
2759            if (s->tls_session_ticket_ext_cb &&
2760                !s->tls_session_ticket_ext_cb(s, data, size,
2761                                              s->tls_session_ticket_ext_cb_arg))
2762            {
2763                *al = TLS1_AD_INTERNAL_ERROR;
2764                return 0;
2765            }
2766            if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2767                || (size > 0)) {
2768                *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2769                return 0;
2770            }
2771            s->tlsext_ticket_expected = 1;
2772        }
2773# ifdef TLSEXT_TYPE_opaque_prf_input
2774        else if (type == TLSEXT_TYPE_opaque_prf_input) {
2775            unsigned char *sdata = data;
2776
2777            if (size < 2) {
2778                *al = SSL_AD_DECODE_ERROR;
2779                return 0;
2780            }
2781            n2s(sdata, s->s3->server_opaque_prf_input_len);
2782            if (s->s3->server_opaque_prf_input_len != size - 2) {
2783                *al = SSL_AD_DECODE_ERROR;
2784                return 0;
2785            }
2786
2787            if (s->s3->server_opaque_prf_input != NULL) {
2788                /* shouldn't really happen */
2789                OPENSSL_free(s->s3->server_opaque_prf_input);
2790            }
2791            if (s->s3->server_opaque_prf_input_len == 0) {
2792                /* dummy byte just to get non-NULL */
2793                s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
2794            } else {
2795                s->s3->server_opaque_prf_input =
2796                    BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2797            }
2798
2799            if (s->s3->server_opaque_prf_input == NULL) {
2800                *al = TLS1_AD_INTERNAL_ERROR;
2801                return 0;
2802            }
2803        }
2804# endif
2805        else if (type == TLSEXT_TYPE_status_request) {
2806            /*
2807             * MUST be empty and only sent if we've requested a status
2808             * request message.
2809             */
2810            if ((s->tlsext_status_type == -1) || (size > 0)) {
2811                *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2812                return 0;
2813            }
2814            /* Set flag to expect CertificateStatus message */
2815            s->tlsext_status_expected = 1;
2816        }
2817# ifndef OPENSSL_NO_NEXTPROTONEG
2818        else if (type == TLSEXT_TYPE_next_proto_neg &&
2819                 s->s3->tmp.finish_md_len == 0) {
2820            unsigned char *selected;
2821            unsigned char selected_len;
2822
2823            /* We must have requested it. */
2824            if (s->ctx->next_proto_select_cb == NULL) {
2825                *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2826                return 0;
2827            }
2828            /* The data must be valid */
2829            if (!ssl_next_proto_validate(data, size)) {
2830                *al = TLS1_AD_DECODE_ERROR;
2831                return 0;
2832            }
2833            if (s->
2834                ctx->next_proto_select_cb(s, &selected, &selected_len, data,
2835                                          size,
2836                                          s->ctx->next_proto_select_cb_arg) !=
2837                SSL_TLSEXT_ERR_OK) {
2838                *al = TLS1_AD_INTERNAL_ERROR;
2839                return 0;
2840            }
2841            /*
2842             * Could be non-NULL if server has sent multiple NPN extensions in
2843             * a single Serverhello
2844             */
2845            OPENSSL_free(s->next_proto_negotiated);
2846            s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2847            if (!s->next_proto_negotiated) {
2848                *al = TLS1_AD_INTERNAL_ERROR;
2849                return 0;
2850            }
2851            memcpy(s->next_proto_negotiated, selected, selected_len);
2852            s->next_proto_negotiated_len = selected_len;
2853            s->s3->next_proto_neg_seen = 1;
2854        }
2855# endif
2856
2857        else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) {
2858            unsigned len;
2859
2860            /* We must have requested it. */
2861            if (!s->cert->alpn_sent) {
2862                *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2863                return 0;
2864            }
2865            if (size < 4) {
2866                *al = TLS1_AD_DECODE_ERROR;
2867                return 0;
2868            }
2869            /*-
2870             * The extension data consists of:
2871             *   uint16 list_length
2872             *   uint8 proto_length;
2873             *   uint8 proto[proto_length];
2874             */
2875            len = data[0];
2876            len <<= 8;
2877            len |= data[1];
2878            if (len != (unsigned)size - 2) {
2879                *al = TLS1_AD_DECODE_ERROR;
2880                return 0;
2881            }
2882            len = data[2];
2883            if (len != (unsigned)size - 3) {
2884                *al = TLS1_AD_DECODE_ERROR;
2885                return 0;
2886            }
2887            if (s->s3->alpn_selected)
2888                OPENSSL_free(s->s3->alpn_selected);
2889            s->s3->alpn_selected = OPENSSL_malloc(len);
2890            if (!s->s3->alpn_selected) {
2891                *al = TLS1_AD_INTERNAL_ERROR;
2892                return 0;
2893            }
2894            memcpy(s->s3->alpn_selected, data + 3, len);
2895            s->s3->alpn_selected_len = len;
2896        }
2897
2898        else if (type == TLSEXT_TYPE_renegotiate) {
2899            if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2900                return 0;
2901            renegotiate_seen = 1;
2902        }
2903# ifndef OPENSSL_NO_HEARTBEATS
2904        else if (type == TLSEXT_TYPE_heartbeat) {
2905            switch (data[0]) {
2906            case 0x01:         /* Server allows us to send HB requests */
2907                s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2908                break;
2909            case 0x02:         /* Server doesn't accept HB requests */
2910                s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2911                s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2912                break;
2913            default:
2914                *al = SSL_AD_ILLEGAL_PARAMETER;
2915                return 0;
2916            }
2917        }
2918# endif
2919# ifndef OPENSSL_NO_SRTP
2920        else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) {
2921            if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al))
2922                return 0;
2923        }
2924# endif
2925        /*
2926         * If this extension type was not otherwise handled, but matches a
2927         * custom_cli_ext_record, then send it to the c callback
2928         */
2929        else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2930            return 0;
2931
2932        data += size;
2933    }
2934
2935    if (data != d + n) {
2936        *al = SSL_AD_DECODE_ERROR;
2937        return 0;
2938    }
2939
2940    if (!s->hit && tlsext_servername == 1) {
2941        if (s->tlsext_hostname) {
2942            if (s->session->tlsext_hostname == NULL) {
2943                s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
2944                if (!s->session->tlsext_hostname) {
2945                    *al = SSL_AD_UNRECOGNIZED_NAME;
2946                    return 0;
2947                }
2948            } else {
2949                *al = SSL_AD_DECODE_ERROR;
2950                return 0;
2951            }
2952        }
2953    }
2954
2955    *p = data;
2956
2957 ri_check:
2958
2959    /*
2960     * Determine if we need to see RI. Strictly speaking if we want to avoid
2961     * an attack we should *always* see RI even on initial server hello
2962     * because the client doesn't see any renegotiation during an attack.
2963     * However this would mean we could not connect to any server which
2964     * doesn't support RI so for the immediate future tolerate RI absence on
2965     * initial connect only.
2966     */
2967    if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2968        && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
2969        *al = SSL_AD_HANDSHAKE_FAILURE;
2970        SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2971               SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2972        return 0;
2973    }
2974
2975    return 1;
2976}
2977
2978int ssl_prepare_clienthello_tlsext(SSL *s)
2979{
2980
2981# ifdef TLSEXT_TYPE_opaque_prf_input
2982    {
2983        int r = 1;
2984
2985        if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
2986            r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
2987                                                         s->
2988                                                         ctx->tlsext_opaque_prf_input_callback_arg);
2989            if (!r)
2990                return -1;
2991        }
2992
2993        if (s->tlsext_opaque_prf_input != NULL) {
2994            if (s->s3->client_opaque_prf_input != NULL) {
2995                /* shouldn't really happen */
2996                OPENSSL_free(s->s3->client_opaque_prf_input);
2997            }
2998
2999            if (s->tlsext_opaque_prf_input_len == 0) {
3000                /* dummy byte just to get non-NULL */
3001                s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
3002            } else {
3003                s->s3->client_opaque_prf_input =
3004                    BUF_memdup(s->tlsext_opaque_prf_input,
3005                               s->tlsext_opaque_prf_input_len);
3006            }
3007            if (s->s3->client_opaque_prf_input == NULL) {
3008                SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,
3009                       ERR_R_MALLOC_FAILURE);
3010                return -1;
3011            }
3012            s->s3->client_opaque_prf_input_len =
3013                s->tlsext_opaque_prf_input_len;
3014        }
3015
3016        if (r == 2)
3017            /*
3018             * at callback's request, insist on receiving an appropriate
3019             * server opaque PRF input
3020             */
3021            s->s3->server_opaque_prf_input_len =
3022                s->tlsext_opaque_prf_input_len;
3023    }
3024# endif
3025
3026    s->cert->alpn_sent = 0;
3027    return 1;
3028}
3029
3030int ssl_prepare_serverhello_tlsext(SSL *s)
3031{
3032    return 1;
3033}
3034
3035static int ssl_check_clienthello_tlsext_early(SSL *s)
3036{
3037    int ret = SSL_TLSEXT_ERR_NOACK;
3038    int al = SSL_AD_UNRECOGNIZED_NAME;
3039
3040# ifndef OPENSSL_NO_EC
3041    /*
3042     * The handling of the ECPointFormats extension is done elsewhere, namely
3043     * in ssl3_choose_cipher in s3_lib.c.
3044     */
3045    /*
3046     * The handling of the EllipticCurves extension is done elsewhere, namely
3047     * in ssl3_choose_cipher in s3_lib.c.
3048     */
3049# endif
3050
3051    if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
3052        ret =
3053            s->ctx->tlsext_servername_callback(s, &al,
3054                                               s->ctx->tlsext_servername_arg);
3055    else if (s->initial_ctx != NULL
3056             && s->initial_ctx->tlsext_servername_callback != 0)
3057        ret =
3058            s->initial_ctx->tlsext_servername_callback(s, &al,
3059                                                       s->
3060                                                       initial_ctx->tlsext_servername_arg);
3061
3062# ifdef TLSEXT_TYPE_opaque_prf_input
3063    {
3064        /*
3065         * This sort of belongs into ssl_prepare_serverhello_tlsext(), but we
3066         * might be sending an alert in response to the client hello, so this
3067         * has to happen here in ssl_check_clienthello_tlsext_early().
3068         */
3069
3070        int r = 1;
3071
3072        if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
3073            r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
3074                                                         s->
3075                                                         ctx->tlsext_opaque_prf_input_callback_arg);
3076            if (!r) {
3077                ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3078                al = SSL_AD_INTERNAL_ERROR;
3079                goto err;
3080            }
3081        }
3082
3083        if (s->s3->server_opaque_prf_input != NULL) {
3084            /* shouldn't really happen */
3085            OPENSSL_free(s->s3->server_opaque_prf_input);
3086        }
3087        s->s3->server_opaque_prf_input = NULL;
3088
3089        if (s->tlsext_opaque_prf_input != NULL) {
3090            if (s->s3->client_opaque_prf_input != NULL &&
3091                s->s3->client_opaque_prf_input_len ==
3092                s->tlsext_opaque_prf_input_len) {
3093                /*
3094                 * can only use this extension if we have a server opaque PRF
3095                 * input of the same length as the client opaque PRF input!
3096                 */
3097
3098                if (s->tlsext_opaque_prf_input_len == 0) {
3099                    /* dummy byte just to get non-NULL */
3100                    s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
3101                } else {
3102                    s->s3->server_opaque_prf_input =
3103                        BUF_memdup(s->tlsext_opaque_prf_input,
3104                                   s->tlsext_opaque_prf_input_len);
3105                }
3106                if (s->s3->server_opaque_prf_input == NULL) {
3107                    ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3108                    al = SSL_AD_INTERNAL_ERROR;
3109                    goto err;
3110                }
3111                s->s3->server_opaque_prf_input_len =
3112                    s->tlsext_opaque_prf_input_len;
3113            }
3114        }
3115
3116        if (r == 2 && s->s3->server_opaque_prf_input == NULL) {
3117            /*
3118             * The callback wants to enforce use of the extension, but we
3119             * can't do that with the client opaque PRF input; abort the
3120             * handshake.
3121             */
3122            ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3123            al = SSL_AD_HANDSHAKE_FAILURE;
3124        }
3125    }
3126
3127 err:
3128# endif
3129    switch (ret) {
3130    case SSL_TLSEXT_ERR_ALERT_FATAL:
3131        ssl3_send_alert(s, SSL3_AL_FATAL, al);
3132        return -1;
3133
3134    case SSL_TLSEXT_ERR_ALERT_WARNING:
3135        ssl3_send_alert(s, SSL3_AL_WARNING, al);
3136        return 1;
3137
3138    case SSL_TLSEXT_ERR_NOACK:
3139        s->servername_done = 0;
3140    default:
3141        return 1;
3142    }
3143}
3144
3145int tls1_set_server_sigalgs(SSL *s)
3146{
3147    int al;
3148    size_t i;
3149    /* Clear any shared sigtnature algorithms */
3150    if (s->cert->shared_sigalgs) {
3151        OPENSSL_free(s->cert->shared_sigalgs);
3152        s->cert->shared_sigalgs = NULL;
3153        s->cert->shared_sigalgslen = 0;
3154    }
3155    /* Clear certificate digests and validity flags */
3156    for (i = 0; i < SSL_PKEY_NUM; i++) {
3157        s->cert->pkeys[i].digest = NULL;
3158        s->cert->pkeys[i].valid_flags = 0;
3159    }
3160
3161    /* If sigalgs received process it. */
3162    if (s->cert->peer_sigalgs) {
3163        if (!tls1_process_sigalgs(s)) {
3164            SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
3165            al = SSL_AD_INTERNAL_ERROR;
3166            goto err;
3167        }
3168        /* Fatal error is no shared signature algorithms */
3169        if (!s->cert->shared_sigalgs) {
3170            SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3171                   SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
3172            al = SSL_AD_HANDSHAKE_FAILURE;
3173            goto err;
3174        }
3175    } else
3176        ssl_cert_set_default_md(s->cert);
3177    return 1;
3178 err:
3179    ssl3_send_alert(s, SSL3_AL_FATAL, al);
3180    return 0;
3181}
3182
3183/*
3184 * Upon success, returns 1.
3185 * Upon failure, returns 0 and sets |al| to the appropriate fatal alert.
3186 */
3187int ssl_check_clienthello_tlsext_late(SSL *s, int *al)
3188{
3189
3190    /*
3191     * If status request then ask callback what to do. Note: this must be
3192     * called after servername callbacks in case the certificate has changed,
3193     * and must be called after the cipher has been chosen because this may
3194     * influence which certificate is sent
3195     */
3196    if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) {
3197        int ret;
3198        CERT_PKEY *certpkey;
3199        certpkey = ssl_get_server_send_pkey(s);
3200        /* If no certificate can't return certificate status */
3201        if (certpkey != NULL) {
3202            /*
3203             * Set current certificate to one we will use so SSL_get_certificate
3204             * et al can pick it up.
3205             */
3206            s->cert->key = certpkey;
3207            ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3208            switch (ret) {
3209                /* We don't want to send a status request response */
3210            case SSL_TLSEXT_ERR_NOACK:
3211                s->tlsext_status_expected = 0;
3212                break;
3213                /* status request response should be sent */
3214            case SSL_TLSEXT_ERR_OK:
3215                if (s->tlsext_ocsp_resp)
3216                    s->tlsext_status_expected = 1;
3217                break;
3218                /* something bad happened */
3219            case SSL_TLSEXT_ERR_ALERT_FATAL:
3220            default:
3221                *al = SSL_AD_INTERNAL_ERROR;
3222                return 0;
3223            }
3224        }
3225    }
3226
3227    if (!tls1_alpn_handle_client_hello_late(s, al)) {
3228        return 0;
3229    }
3230
3231    return 1;
3232}
3233
3234int ssl_check_serverhello_tlsext(SSL *s)
3235{
3236    int ret = SSL_TLSEXT_ERR_NOACK;
3237    int al = SSL_AD_UNRECOGNIZED_NAME;
3238
3239# ifndef OPENSSL_NO_EC
3240    /*
3241     * If we are client and using an elliptic curve cryptography cipher
3242     * suite, then if server returns an EC point formats lists extension it
3243     * must contain uncompressed.
3244     */
3245    unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3246    unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3247    if ((s->tlsext_ecpointformatlist != NULL)
3248        && (s->tlsext_ecpointformatlist_length > 0)
3249        && (s->session->tlsext_ecpointformatlist != NULL)
3250        && (s->session->tlsext_ecpointformatlist_length > 0)
3251        && ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
3252            || (alg_a & SSL_aECDSA))) {
3253        /* we are using an ECC cipher */
3254        size_t i;
3255        unsigned char *list;
3256        int found_uncompressed = 0;
3257        list = s->session->tlsext_ecpointformatlist;
3258        for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) {
3259            if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) {
3260                found_uncompressed = 1;
3261                break;
3262            }
3263        }
3264        if (!found_uncompressed) {
3265            SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,
3266                   SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
3267            return -1;
3268        }
3269    }
3270    ret = SSL_TLSEXT_ERR_OK;
3271# endif                         /* OPENSSL_NO_EC */
3272
3273    if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
3274        ret =
3275            s->ctx->tlsext_servername_callback(s, &al,
3276                                               s->ctx->tlsext_servername_arg);
3277    else if (s->initial_ctx != NULL
3278             && s->initial_ctx->tlsext_servername_callback != 0)
3279        ret =
3280            s->initial_ctx->tlsext_servername_callback(s, &al,
3281                                                       s->
3282                                                       initial_ctx->tlsext_servername_arg);
3283
3284# ifdef TLSEXT_TYPE_opaque_prf_input
3285    if (s->s3->server_opaque_prf_input_len > 0) {
3286        /*
3287         * This case may indicate that we, as a client, want to insist on
3288         * using opaque PRF inputs. So first verify that we really have a
3289         * value from the server too.
3290         */
3291
3292        if (s->s3->server_opaque_prf_input == NULL) {
3293            ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3294            al = SSL_AD_HANDSHAKE_FAILURE;
3295        }
3296
3297        /*
3298         * Anytime the server *has* sent an opaque PRF input, we need to
3299         * check that we have a client opaque PRF input of the same size.
3300         */
3301        if (s->s3->client_opaque_prf_input == NULL ||
3302            s->s3->client_opaque_prf_input_len !=
3303            s->s3->server_opaque_prf_input_len) {
3304            ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3305            al = SSL_AD_ILLEGAL_PARAMETER;
3306        }
3307    }
3308# endif
3309
3310    OPENSSL_free(s->tlsext_ocsp_resp);
3311    s->tlsext_ocsp_resp = NULL;
3312    s->tlsext_ocsp_resplen = -1;
3313    /*
3314     * If we've requested certificate status and we wont get one tell the
3315     * callback
3316     */
3317    if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
3318        && !(s->hit) && s->ctx && s->ctx->tlsext_status_cb) {
3319        int r;
3320        /*
3321         * Call callback with resp == NULL and resplen == -1 so callback
3322         * knows there is no response
3323         */
3324        r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3325        if (r == 0) {
3326            al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
3327            ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3328        }
3329        if (r < 0) {
3330            al = SSL_AD_INTERNAL_ERROR;
3331            ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3332        }
3333    }
3334
3335    switch (ret) {
3336    case SSL_TLSEXT_ERR_ALERT_FATAL:
3337        ssl3_send_alert(s, SSL3_AL_FATAL, al);
3338        return -1;
3339
3340    case SSL_TLSEXT_ERR_ALERT_WARNING:
3341        ssl3_send_alert(s, SSL3_AL_WARNING, al);
3342        return 1;
3343
3344    case SSL_TLSEXT_ERR_NOACK:
3345        s->servername_done = 0;
3346    default:
3347        return 1;
3348    }
3349}
3350
3351int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d,
3352                                 int n)
3353{
3354    int al = -1;
3355    if (s->version < SSL3_VERSION)
3356        return 1;
3357    if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) {
3358        ssl3_send_alert(s, SSL3_AL_FATAL, al);
3359        return 0;
3360    }
3361
3362    if (ssl_check_serverhello_tlsext(s) <= 0) {
3363        SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_SERVERHELLO_TLSEXT);
3364        return 0;
3365    }
3366    return 1;
3367}
3368
3369/*-
3370 * Since the server cache lookup is done early on in the processing of the
3371 * ClientHello, and other operations depend on the result, we need to handle
3372 * any TLS session ticket extension at the same time.
3373 *
3374 *   session_id: points at the session ID in the ClientHello. This code will
3375 *       read past the end of this in order to parse out the session ticket
3376 *       extension, if any.
3377 *   len: the length of the session ID.
3378 *   limit: a pointer to the first byte after the ClientHello.
3379 *   ret: (output) on return, if a ticket was decrypted, then this is set to
3380 *       point to the resulting session.
3381 *
3382 * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
3383 * ciphersuite, in which case we have no use for session tickets and one will
3384 * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
3385 *
3386 * Returns:
3387 *   -1: fatal error, either from parsing or decrypting the ticket.
3388 *    0: no ticket was found (or was ignored, based on settings).
3389 *    1: a zero length extension was found, indicating that the client supports
3390 *       session tickets but doesn't currently have one to offer.
3391 *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
3392 *       couldn't be decrypted because of a non-fatal error.
3393 *    3: a ticket was successfully decrypted and *ret was set.
3394 *
3395 * Side effects:
3396 *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3397 *   a new session ticket to the client because the client indicated support
3398 *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3399 *   a session ticket or we couldn't use the one it gave us, or if
3400 *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3401 *   Otherwise, s->tlsext_ticket_expected is set to 0.
3402 */
3403int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3404                        const unsigned char *limit, SSL_SESSION **ret)
3405{
3406    /* Point after session ID in client hello */
3407    const unsigned char *p = session_id + len;
3408    unsigned short i;
3409
3410    *ret = NULL;
3411    s->tlsext_ticket_expected = 0;
3412
3413    /*
3414     * If tickets disabled behave as if no ticket present to permit stateful
3415     * resumption.
3416     */
3417    if (SSL_get_options(s) & SSL_OP_NO_TICKET)
3418        return 0;
3419    if ((s->version <= SSL3_VERSION) || !limit)
3420        return 0;
3421    if (p >= limit)
3422        return -1;
3423    /* Skip past DTLS cookie */
3424    if (SSL_IS_DTLS(s)) {
3425        i = *(p++);
3426
3427        if (limit - p <= i)
3428            return -1;
3429
3430        p += i;
3431    }
3432    /* Skip past cipher list */
3433    n2s(p, i);
3434    if (limit - p <= i)
3435        return -1;
3436    p += i;
3437
3438    /* Skip past compression algorithm list */
3439    i = *(p++);
3440    if (limit - p < i)
3441        return -1;
3442    p += i;
3443
3444    /* Now at start of extensions */
3445    if (limit - p <= 2)
3446        return 0;
3447    n2s(p, i);
3448    while (limit - p >= 4) {
3449        unsigned short type, size;
3450        n2s(p, type);
3451        n2s(p, size);
3452        if (limit - p < size)
3453            return 0;
3454        if (type == TLSEXT_TYPE_session_ticket) {
3455            int r;
3456            if (size == 0) {
3457                /*
3458                 * The client will accept a ticket but doesn't currently have
3459                 * one.
3460                 */
3461                s->tlsext_ticket_expected = 1;
3462                return 1;
3463            }
3464            if (s->tls_session_secret_cb) {
3465                /*
3466                 * Indicate that the ticket couldn't be decrypted rather than
3467                 * generating the session from ticket now, trigger
3468                 * abbreviated handshake based on external mechanism to
3469                 * calculate the master secret later.
3470                 */
3471                return 2;
3472            }
3473            r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3474            switch (r) {
3475            case 2:            /* ticket couldn't be decrypted */
3476                s->tlsext_ticket_expected = 1;
3477                return 2;
3478            case 3:            /* ticket was decrypted */
3479                return r;
3480            case 4:            /* ticket decrypted but need to renew */
3481                s->tlsext_ticket_expected = 1;
3482                return 3;
3483            default:           /* fatal error */
3484                return -1;
3485            }
3486        }
3487        p += size;
3488    }
3489    return 0;
3490}
3491
3492/*-
3493 * tls_decrypt_ticket attempts to decrypt a session ticket.
3494 *
3495 *   etick: points to the body of the session ticket extension.
3496 *   eticklen: the length of the session tickets extenion.
3497 *   sess_id: points at the session ID.
3498 *   sesslen: the length of the session ID.
3499 *   psess: (output) on return, if a ticket was decrypted, then this is set to
3500 *       point to the resulting session.
3501 *
3502 * Returns:
3503 *   -1: fatal error, either from parsing or decrypting the ticket.
3504 *    2: the ticket couldn't be decrypted.
3505 *    3: a ticket was successfully decrypted and *psess was set.
3506 *    4: same as 3, but the ticket needs to be renewed.
3507 */
3508static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
3509                              int eticklen, const unsigned char *sess_id,
3510                              int sesslen, SSL_SESSION **psess)
3511{
3512    SSL_SESSION *sess;
3513    unsigned char *sdec;
3514    const unsigned char *p;
3515    int slen, mlen, renew_ticket = 0;
3516    unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3517    HMAC_CTX hctx;
3518    EVP_CIPHER_CTX ctx;
3519    SSL_CTX *tctx = s->initial_ctx;
3520
3521    /* Need at least keyname + iv */
3522    if (eticklen < 16 + EVP_MAX_IV_LENGTH)
3523        return 2;
3524
3525    /* Initialize session ticket encryption and HMAC contexts */
3526    HMAC_CTX_init(&hctx);
3527    EVP_CIPHER_CTX_init(&ctx);
3528    if (tctx->tlsext_ticket_key_cb) {
3529        unsigned char *nctick = (unsigned char *)etick;
3530        int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3531                                            &ctx, &hctx, 0);
3532        if (rv < 0)
3533            goto err;
3534        if (rv == 0) {
3535            HMAC_CTX_cleanup(&hctx);
3536            EVP_CIPHER_CTX_cleanup(&ctx);
3537            return 2;
3538        }
3539        if (rv == 2)
3540            renew_ticket = 1;
3541    } else {
3542        /* Check key name matches */
3543        if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3544            return 2;
3545        if (HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3546                         tlsext_tick_md(), NULL) <= 0
3547                || EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3548                                      tctx->tlsext_tick_aes_key,
3549                                      etick + 16) <= 0) {
3550            goto err;
3551       }
3552    }
3553    /*
3554     * Attempt to process session ticket, first conduct sanity and integrity
3555     * checks on ticket.
3556     */
3557    mlen = HMAC_size(&hctx);
3558    if (mlen < 0) {
3559        goto err;
3560    }
3561    /* Sanity check ticket length: must exceed keyname + IV + HMAC */
3562    if (eticklen <= 16 + EVP_CIPHER_CTX_iv_length(&ctx) + mlen) {
3563        HMAC_CTX_cleanup(&hctx);
3564        EVP_CIPHER_CTX_cleanup(&ctx);
3565        return 2;
3566    }
3567
3568    eticklen -= mlen;
3569    /* Check HMAC of encrypted ticket */
3570    if (HMAC_Update(&hctx, etick, eticklen) <= 0
3571            || HMAC_Final(&hctx, tick_hmac, NULL) <= 0) {
3572        goto err;
3573    }
3574    HMAC_CTX_cleanup(&hctx);
3575    if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
3576        EVP_CIPHER_CTX_cleanup(&ctx);
3577        return 2;
3578    }
3579    /* Attempt to decrypt session data */
3580    /* Move p after IV to start of encrypted ticket, update length */
3581    p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3582    eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3583    sdec = OPENSSL_malloc(eticklen);
3584    if (sdec == NULL
3585            || EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen) <= 0) {
3586        EVP_CIPHER_CTX_cleanup(&ctx);
3587        OPENSSL_free(sdec);
3588        return -1;
3589    }
3590    if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) {
3591        EVP_CIPHER_CTX_cleanup(&ctx);
3592        OPENSSL_free(sdec);
3593        return 2;
3594    }
3595    slen += mlen;
3596    EVP_CIPHER_CTX_cleanup(&ctx);
3597    p = sdec;
3598
3599    sess = d2i_SSL_SESSION(NULL, &p, slen);
3600    slen -= p - sdec;
3601    OPENSSL_free(sdec);
3602    if (sess) {
3603        /* Some additional consistency checks */
3604        if (slen != 0 || sess->session_id_length != 0) {
3605            SSL_SESSION_free(sess);
3606            return 2;
3607        }
3608        /*
3609         * The session ID, if non-empty, is used by some clients to detect
3610         * that the ticket has been accepted. So we copy it to the session
3611         * structure. If it is empty set length to zero as required by
3612         * standard.
3613         */
3614        if (sesslen)
3615            memcpy(sess->session_id, sess_id, sesslen);
3616        sess->session_id_length = sesslen;
3617        *psess = sess;
3618        if (renew_ticket)
3619            return 4;
3620        else
3621            return 3;
3622    }
3623    ERR_clear_error();
3624    /*
3625     * For session parse failure, indicate that we need to send a new ticket.
3626     */
3627    return 2;
3628err:
3629    EVP_CIPHER_CTX_cleanup(&ctx);
3630    HMAC_CTX_cleanup(&hctx);
3631    return -1;
3632}
3633
3634/* Tables to translate from NIDs to TLS v1.2 ids */
3635
3636typedef struct {
3637    int nid;
3638    int id;
3639} tls12_lookup;
3640
3641static tls12_lookup tls12_md[] = {
3642    {NID_md5, TLSEXT_hash_md5},
3643    {NID_sha1, TLSEXT_hash_sha1},
3644    {NID_sha224, TLSEXT_hash_sha224},
3645    {NID_sha256, TLSEXT_hash_sha256},
3646    {NID_sha384, TLSEXT_hash_sha384},
3647    {NID_sha512, TLSEXT_hash_sha512}
3648};
3649
3650static tls12_lookup tls12_sig[] = {
3651    {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3652    {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3653    {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3654};
3655
3656static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3657{
3658    size_t i;
3659    for (i = 0; i < tlen; i++) {
3660        if (table[i].nid == nid)
3661            return table[i].id;
3662    }
3663    return -1;
3664}
3665
3666static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3667{
3668    size_t i;
3669    for (i = 0; i < tlen; i++) {
3670        if ((table[i].id) == id)
3671            return table[i].nid;
3672    }
3673    return NID_undef;
3674}
3675
3676int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk,
3677                         const EVP_MD *md)
3678{
3679    int sig_id, md_id;
3680    if (!md)
3681        return 0;
3682    md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3683                          sizeof(tls12_md) / sizeof(tls12_lookup));
3684    if (md_id == -1)
3685        return 0;
3686    sig_id = tls12_get_sigid(pk);
3687    if (sig_id == -1)
3688        return 0;
3689    p[0] = (unsigned char)md_id;
3690    p[1] = (unsigned char)sig_id;
3691    return 1;
3692}
3693
3694int tls12_get_sigid(const EVP_PKEY *pk)
3695{
3696    return tls12_find_id(pk->type, tls12_sig,
3697                         sizeof(tls12_sig) / sizeof(tls12_lookup));
3698}
3699
3700const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3701{
3702    switch (hash_alg) {
3703# ifndef OPENSSL_NO_MD5
3704    case TLSEXT_hash_md5:
3705#  ifdef OPENSSL_FIPS
3706        if (FIPS_mode())
3707            return NULL;
3708#  endif
3709        return EVP_md5();
3710# endif
3711# ifndef OPENSSL_NO_SHA
3712    case TLSEXT_hash_sha1:
3713        return EVP_sha1();
3714# endif
3715# ifndef OPENSSL_NO_SHA256
3716    case TLSEXT_hash_sha224:
3717        return EVP_sha224();
3718
3719    case TLSEXT_hash_sha256:
3720        return EVP_sha256();
3721# endif
3722# ifndef OPENSSL_NO_SHA512
3723    case TLSEXT_hash_sha384:
3724        return EVP_sha384();
3725
3726    case TLSEXT_hash_sha512:
3727        return EVP_sha512();
3728# endif
3729    default:
3730        return NULL;
3731
3732    }
3733}
3734
3735static int tls12_get_pkey_idx(unsigned char sig_alg)
3736{
3737    switch (sig_alg) {
3738# ifndef OPENSSL_NO_RSA
3739    case TLSEXT_signature_rsa:
3740        return SSL_PKEY_RSA_SIGN;
3741# endif
3742# ifndef OPENSSL_NO_DSA
3743    case TLSEXT_signature_dsa:
3744        return SSL_PKEY_DSA_SIGN;
3745# endif
3746# ifndef OPENSSL_NO_ECDSA
3747    case TLSEXT_signature_ecdsa:
3748        return SSL_PKEY_ECC;
3749# endif
3750    }
3751    return -1;
3752}
3753
3754/* Convert TLS 1.2 signature algorithm extension values into NIDs */
3755static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3756                               int *psignhash_nid, const unsigned char *data)
3757{
3758    int sign_nid = NID_undef, hash_nid = NID_undef;
3759    if (!phash_nid && !psign_nid && !psignhash_nid)
3760        return;
3761    if (phash_nid || psignhash_nid) {
3762        hash_nid = tls12_find_nid(data[0], tls12_md,
3763                                  sizeof(tls12_md) / sizeof(tls12_lookup));
3764        if (phash_nid)
3765            *phash_nid = hash_nid;
3766    }
3767    if (psign_nid || psignhash_nid) {
3768        sign_nid = tls12_find_nid(data[1], tls12_sig,
3769                                  sizeof(tls12_sig) / sizeof(tls12_lookup));
3770        if (psign_nid)
3771            *psign_nid = sign_nid;
3772    }
3773    if (psignhash_nid) {
3774        if (sign_nid == NID_undef || hash_nid == NID_undef
3775                || OBJ_find_sigid_by_algs(psignhash_nid, hash_nid,
3776                                          sign_nid) <= 0)
3777            *psignhash_nid = NID_undef;
3778    }
3779}
3780
3781/* Given preference and allowed sigalgs set shared sigalgs */
3782static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3783                                   const unsigned char *pref, size_t preflen,
3784                                   const unsigned char *allow,
3785                                   size_t allowlen)
3786{
3787    const unsigned char *ptmp, *atmp;
3788    size_t i, j, nmatch = 0;
3789    for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) {
3790        /* Skip disabled hashes or signature algorithms */
3791        if (tls12_get_hash(ptmp[0]) == NULL)
3792            continue;
3793        if (tls12_get_pkey_idx(ptmp[1]) == -1)
3794            continue;
3795        for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) {
3796            if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) {
3797                nmatch++;
3798                if (shsig) {
3799                    shsig->rhash = ptmp[0];
3800                    shsig->rsign = ptmp[1];
3801                    tls1_lookup_sigalg(&shsig->hash_nid,
3802                                       &shsig->sign_nid,
3803                                       &shsig->signandhash_nid, ptmp);
3804                    shsig++;
3805                }
3806                break;
3807            }
3808        }
3809    }
3810    return nmatch;
3811}
3812
3813/* Set shared signature algorithms for SSL structures */
3814static int tls1_set_shared_sigalgs(SSL *s)
3815{
3816    const unsigned char *pref, *allow, *conf;
3817    size_t preflen, allowlen, conflen;
3818    size_t nmatch;
3819    TLS_SIGALGS *salgs = NULL;
3820    CERT *c = s->cert;
3821    unsigned int is_suiteb = tls1_suiteb(s);
3822    if (c->shared_sigalgs) {
3823        OPENSSL_free(c->shared_sigalgs);
3824        c->shared_sigalgs = NULL;
3825        c->shared_sigalgslen = 0;
3826    }
3827    /* If client use client signature algorithms if not NULL */
3828    if (!s->server && c->client_sigalgs && !is_suiteb) {
3829        conf = c->client_sigalgs;
3830        conflen = c->client_sigalgslen;
3831    } else if (c->conf_sigalgs && !is_suiteb) {
3832        conf = c->conf_sigalgs;
3833        conflen = c->conf_sigalgslen;
3834    } else
3835        conflen = tls12_get_psigalgs(s, 0, &conf);
3836    if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
3837        pref = conf;
3838        preflen = conflen;
3839        allow = c->peer_sigalgs;
3840        allowlen = c->peer_sigalgslen;
3841    } else {
3842        allow = conf;
3843        allowlen = conflen;
3844        pref = c->peer_sigalgs;
3845        preflen = c->peer_sigalgslen;
3846    }
3847    nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3848    if (nmatch) {
3849        salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3850        if (!salgs)
3851            return 0;
3852        nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3853    } else {
3854        salgs = NULL;
3855    }
3856    c->shared_sigalgs = salgs;
3857    c->shared_sigalgslen = nmatch;
3858    return 1;
3859}
3860
3861/* Set preferred digest for each key type */
3862
3863int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
3864{
3865    CERT *c = s->cert;
3866    /* Extension ignored for inappropriate versions */
3867    if (!SSL_USE_SIGALGS(s))
3868        return 1;
3869    /* Should never happen */
3870    if (!c)
3871        return 0;
3872
3873    if (c->peer_sigalgs)
3874        OPENSSL_free(c->peer_sigalgs);
3875    c->peer_sigalgs = OPENSSL_malloc(dsize);
3876    if (!c->peer_sigalgs)
3877        return 0;
3878    c->peer_sigalgslen = dsize;
3879    memcpy(c->peer_sigalgs, data, dsize);
3880    return 1;
3881}
3882
3883int tls1_process_sigalgs(SSL *s)
3884{
3885    int idx;
3886    size_t i;
3887    const EVP_MD *md;
3888    CERT *c = s->cert;
3889    TLS_SIGALGS *sigptr;
3890    if (!tls1_set_shared_sigalgs(s))
3891        return 0;
3892
3893# ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3894    if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
3895        /*
3896         * Use first set signature preference to force message digest,
3897         * ignoring any peer preferences.
3898         */
3899        const unsigned char *sigs = NULL;
3900        if (s->server)
3901            sigs = c->conf_sigalgs;
3902        else
3903            sigs = c->client_sigalgs;
3904        if (sigs) {
3905            idx = tls12_get_pkey_idx(sigs[1]);
3906            md = tls12_get_hash(sigs[0]);
3907            c->pkeys[idx].digest = md;
3908            c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3909            if (idx == SSL_PKEY_RSA_SIGN) {
3910                c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
3911                    CERT_PKEY_EXPLICIT_SIGN;
3912                c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3913            }
3914        }
3915    }
3916# endif
3917
3918    for (i = 0, sigptr = c->shared_sigalgs;
3919         i < c->shared_sigalgslen; i++, sigptr++) {
3920        idx = tls12_get_pkey_idx(sigptr->rsign);
3921        if (idx > 0 && c->pkeys[idx].digest == NULL) {
3922            md = tls12_get_hash(sigptr->rhash);
3923            c->pkeys[idx].digest = md;
3924            c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3925            if (idx == SSL_PKEY_RSA_SIGN) {
3926                c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
3927                    CERT_PKEY_EXPLICIT_SIGN;
3928                c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3929            }
3930        }
3931
3932    }
3933    /*
3934     * In strict mode leave unset digests as NULL to indicate we can't use
3935     * the certificate for signing.
3936     */
3937    if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
3938        /*
3939         * Set any remaining keys to default values. NOTE: if alg is not
3940         * supported it stays as NULL.
3941         */
3942# ifndef OPENSSL_NO_DSA
3943        if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3944            c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3945# endif
3946# ifndef OPENSSL_NO_RSA
3947        if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest) {
3948            c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3949            c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3950        }
3951# endif
3952# ifndef OPENSSL_NO_ECDSA
3953        if (!c->pkeys[SSL_PKEY_ECC].digest)
3954            c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3955# endif
3956    }
3957    return 1;
3958}
3959
3960int SSL_get_sigalgs(SSL *s, int idx,
3961                    int *psign, int *phash, int *psignhash,
3962                    unsigned char *rsig, unsigned char *rhash)
3963{
3964    const unsigned char *psig = s->cert->peer_sigalgs;
3965    if (psig == NULL)
3966        return 0;
3967    if (idx >= 0) {
3968        idx <<= 1;
3969        if (idx >= (int)s->cert->peer_sigalgslen)
3970            return 0;
3971        psig += idx;
3972        if (rhash)
3973            *rhash = psig[0];
3974        if (rsig)
3975            *rsig = psig[1];
3976        tls1_lookup_sigalg(phash, psign, psignhash, psig);
3977    }
3978    return s->cert->peer_sigalgslen / 2;
3979}
3980
3981int SSL_get_shared_sigalgs(SSL *s, int idx,
3982                           int *psign, int *phash, int *psignhash,
3983                           unsigned char *rsig, unsigned char *rhash)
3984{
3985    TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3986    if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3987        return 0;
3988    shsigalgs += idx;
3989    if (phash)
3990        *phash = shsigalgs->hash_nid;
3991    if (psign)
3992        *psign = shsigalgs->sign_nid;
3993    if (psignhash)
3994        *psignhash = shsigalgs->signandhash_nid;
3995    if (rsig)
3996        *rsig = shsigalgs->rsign;
3997    if (rhash)
3998        *rhash = shsigalgs->rhash;
3999    return s->cert->shared_sigalgslen;
4000}
4001
4002# ifndef OPENSSL_NO_HEARTBEATS
4003int tls1_process_heartbeat(SSL *s)
4004{
4005    unsigned char *p = &s->s3->rrec.data[0], *pl;
4006    unsigned short hbtype;
4007    unsigned int payload;
4008    unsigned int padding = 16;  /* Use minimum padding */
4009
4010    if (s->msg_callback)
4011        s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
4012                        &s->s3->rrec.data[0], s->s3->rrec.length,
4013                        s, s->msg_callback_arg);
4014
4015    /* Read type and payload length first */
4016    if (1 + 2 + 16 > s->s3->rrec.length)
4017        return 0;               /* silently discard */
4018    hbtype = *p++;
4019    n2s(p, payload);
4020    if (1 + 2 + payload + 16 > s->s3->rrec.length)
4021        return 0;               /* silently discard per RFC 6520 sec. 4 */
4022    pl = p;
4023
4024    if (hbtype == TLS1_HB_REQUEST) {
4025        unsigned char *buffer, *bp;
4026        int r;
4027
4028        /*
4029         * Allocate memory for the response, size is 1 bytes message type,
4030         * plus 2 bytes payload length, plus payload, plus padding
4031         */
4032        buffer = OPENSSL_malloc(1 + 2 + payload + padding);
4033        if (buffer == NULL)
4034            return -1;
4035        bp = buffer;
4036
4037        /* Enter response type, length and copy payload */
4038        *bp++ = TLS1_HB_RESPONSE;
4039        s2n(payload, bp);
4040        memcpy(bp, pl, payload);
4041        bp += payload;
4042        /* Random padding */
4043        if (RAND_bytes(bp, padding) <= 0) {
4044            OPENSSL_free(buffer);
4045            return -1;
4046        }
4047
4048        r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer,
4049                             3 + payload + padding);
4050
4051        if (r >= 0 && s->msg_callback)
4052            s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
4053                            buffer, 3 + payload + padding,
4054                            s, s->msg_callback_arg);
4055
4056        OPENSSL_free(buffer);
4057
4058        if (r < 0)
4059            return r;
4060    } else if (hbtype == TLS1_HB_RESPONSE) {
4061        unsigned int seq;
4062
4063        /*
4064         * We only send sequence numbers (2 bytes unsigned int), and 16
4065         * random bytes, so we just try to read the sequence number
4066         */
4067        n2s(pl, seq);
4068
4069        if (payload == 18 && seq == s->tlsext_hb_seq) {
4070            s->tlsext_hb_seq++;
4071            s->tlsext_hb_pending = 0;
4072        }
4073    }
4074
4075    return 0;
4076}
4077
4078int tls1_heartbeat(SSL *s)
4079{
4080    unsigned char *buf, *p;
4081    int ret = -1;
4082    unsigned int payload = 18;  /* Sequence number + random bytes */
4083    unsigned int padding = 16;  /* Use minimum padding */
4084
4085    /* Only send if peer supports and accepts HB requests... */
4086    if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
4087        s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
4088        SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
4089        return -1;
4090    }
4091
4092    /* ...and there is none in flight yet... */
4093    if (s->tlsext_hb_pending) {
4094        SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
4095        return -1;
4096    }
4097
4098    /* ...and no handshake in progress. */
4099    if (SSL_in_init(s) || s->in_handshake) {
4100        SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
4101        return -1;
4102    }
4103
4104    /*
4105     * Check if padding is too long, payload and padding must not exceed 2^14
4106     * - 3 = 16381 bytes in total.
4107     */
4108    OPENSSL_assert(payload + padding <= 16381);
4109
4110    /*-
4111     * Create HeartBeat message, we just use a sequence number
4112     * as payload to distuingish different messages and add
4113     * some random stuff.
4114     *  - Message Type, 1 byte
4115     *  - Payload Length, 2 bytes (unsigned int)
4116     *  - Payload, the sequence number (2 bytes uint)
4117     *  - Payload, random bytes (16 bytes uint)
4118     *  - Padding
4119     */
4120    buf = OPENSSL_malloc(1 + 2 + payload + padding);
4121    if (buf == NULL)
4122        return -1;
4123    p = buf;
4124    /* Message Type */
4125    *p++ = TLS1_HB_REQUEST;
4126    /* Payload length (18 bytes here) */
4127    s2n(payload, p);
4128    /* Sequence number */
4129    s2n(s->tlsext_hb_seq, p);
4130    /* 16 random bytes */
4131    if (RAND_bytes(p, 16) <= 0) {
4132        SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
4133        goto err;
4134    }
4135    p += 16;
4136    /* Random padding */
4137    if (RAND_bytes(p, padding) <= 0) {
4138        SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
4139        goto err;
4140    }
4141
4142    ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
4143    if (ret >= 0) {
4144        if (s->msg_callback)
4145            s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
4146                            buf, 3 + payload + padding,
4147                            s, s->msg_callback_arg);
4148
4149        s->tlsext_hb_pending = 1;
4150    }
4151
4152err:
4153    OPENSSL_free(buf);
4154
4155    return ret;
4156}
4157# endif
4158
4159# define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
4160
4161typedef struct {
4162    size_t sigalgcnt;
4163    int sigalgs[MAX_SIGALGLEN];
4164} sig_cb_st;
4165
4166static int sig_cb(const char *elem, int len, void *arg)
4167{
4168    sig_cb_st *sarg = arg;
4169    size_t i;
4170    char etmp[20], *p;
4171    int sig_alg, hash_alg;
4172    if (elem == NULL)
4173        return 0;
4174    if (sarg->sigalgcnt == MAX_SIGALGLEN)
4175        return 0;
4176    if (len > (int)(sizeof(etmp) - 1))
4177        return 0;
4178    memcpy(etmp, elem, len);
4179    etmp[len] = 0;
4180    p = strchr(etmp, '+');
4181    if (!p)
4182        return 0;
4183    *p = 0;
4184    p++;
4185    if (!*p)
4186        return 0;
4187
4188    if (!strcmp(etmp, "RSA"))
4189        sig_alg = EVP_PKEY_RSA;
4190    else if (!strcmp(etmp, "DSA"))
4191        sig_alg = EVP_PKEY_DSA;
4192    else if (!strcmp(etmp, "ECDSA"))
4193        sig_alg = EVP_PKEY_EC;
4194    else
4195        return 0;
4196
4197    hash_alg = OBJ_sn2nid(p);
4198    if (hash_alg == NID_undef)
4199        hash_alg = OBJ_ln2nid(p);
4200    if (hash_alg == NID_undef)
4201        return 0;
4202
4203    for (i = 0; i < sarg->sigalgcnt; i += 2) {
4204        if (sarg->sigalgs[i] == sig_alg && sarg->sigalgs[i + 1] == hash_alg)
4205            return 0;
4206    }
4207    sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
4208    sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
4209    return 1;
4210}
4211
4212/*
4213 * Set suppored signature algorithms based on a colon separated list of the
4214 * form sig+hash e.g. RSA+SHA512:DSA+SHA512
4215 */
4216int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
4217{
4218    sig_cb_st sig;
4219    sig.sigalgcnt = 0;
4220    if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
4221        return 0;
4222    if (c == NULL)
4223        return 1;
4224    return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
4225}
4226
4227int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen,
4228                     int client)
4229{
4230    unsigned char *sigalgs, *sptr;
4231    int rhash, rsign;
4232    size_t i;
4233    if (salglen & 1)
4234        return 0;
4235    sigalgs = OPENSSL_malloc(salglen);
4236    if (sigalgs == NULL)
4237        return 0;
4238    for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
4239        rhash = tls12_find_id(*psig_nids++, tls12_md,
4240                              sizeof(tls12_md) / sizeof(tls12_lookup));
4241        rsign = tls12_find_id(*psig_nids++, tls12_sig,
4242                              sizeof(tls12_sig) / sizeof(tls12_lookup));
4243
4244        if (rhash == -1 || rsign == -1)
4245            goto err;
4246        *sptr++ = rhash;
4247        *sptr++ = rsign;
4248    }
4249
4250    if (client) {
4251        if (c->client_sigalgs)
4252            OPENSSL_free(c->client_sigalgs);
4253        c->client_sigalgs = sigalgs;
4254        c->client_sigalgslen = salglen;
4255    } else {
4256        if (c->conf_sigalgs)
4257            OPENSSL_free(c->conf_sigalgs);
4258        c->conf_sigalgs = sigalgs;
4259        c->conf_sigalgslen = salglen;
4260    }
4261
4262    return 1;
4263
4264 err:
4265    OPENSSL_free(sigalgs);
4266    return 0;
4267}
4268
4269static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
4270{
4271    int sig_nid;
4272    size_t i;
4273    if (default_nid == -1)
4274        return 1;
4275    sig_nid = X509_get_signature_nid(x);
4276    if (default_nid)
4277        return sig_nid == default_nid ? 1 : 0;
4278    for (i = 0; i < c->shared_sigalgslen; i++)
4279        if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
4280            return 1;
4281    return 0;
4282}
4283
4284/* Check to see if a certificate issuer name matches list of CA names */
4285static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
4286{
4287    X509_NAME *nm;
4288    int i;
4289    nm = X509_get_issuer_name(x);
4290    for (i = 0; i < sk_X509_NAME_num(names); i++) {
4291        if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
4292            return 1;
4293    }
4294    return 0;
4295}
4296
4297/*
4298 * Check certificate chain is consistent with TLS extensions and is usable by
4299 * server. This servers two purposes: it allows users to check chains before
4300 * passing them to the server and it allows the server to check chains before
4301 * attempting to use them.
4302 */
4303
4304/* Flags which need to be set for a certificate when stict mode not set */
4305
4306# define CERT_PKEY_VALID_FLAGS \
4307        (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
4308/* Strict mode flags */
4309# define CERT_PKEY_STRICT_FLAGS \
4310         (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
4311         | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
4312
4313int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
4314                     int idx)
4315{
4316    int i;
4317    int rv = 0;
4318    int check_flags = 0, strict_mode;
4319    CERT_PKEY *cpk = NULL;
4320    CERT *c = s->cert;
4321    unsigned int suiteb_flags = tls1_suiteb(s);
4322    /* idx == -1 means checking server chains */
4323    if (idx != -1) {
4324        /* idx == -2 means checking client certificate chains */
4325        if (idx == -2) {
4326            cpk = c->key;
4327            idx = cpk - c->pkeys;
4328        } else
4329            cpk = c->pkeys + idx;
4330        x = cpk->x509;
4331        pk = cpk->privatekey;
4332        chain = cpk->chain;
4333        strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
4334        /* If no cert or key, forget it */
4335        if (!x || !pk)
4336            goto end;
4337# ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
4338        /* Allow any certificate to pass test */
4339        if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
4340            rv = CERT_PKEY_STRICT_FLAGS | CERT_PKEY_EXPLICIT_SIGN |
4341                CERT_PKEY_VALID | CERT_PKEY_SIGN;
4342            cpk->valid_flags = rv;
4343            return rv;
4344        }
4345# endif
4346    } else {
4347        if (!x || !pk)
4348            return 0;
4349        idx = ssl_cert_type(x, pk);
4350        if (idx == -1)
4351            return 0;
4352        cpk = c->pkeys + idx;
4353        if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
4354            check_flags = CERT_PKEY_STRICT_FLAGS;
4355        else
4356            check_flags = CERT_PKEY_VALID_FLAGS;
4357        strict_mode = 1;
4358    }
4359
4360    if (suiteb_flags) {
4361        int ok;
4362        if (check_flags)
4363            check_flags |= CERT_PKEY_SUITEB;
4364        ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
4365        if (ok == X509_V_OK)
4366            rv |= CERT_PKEY_SUITEB;
4367        else if (!check_flags)
4368            goto end;
4369    }
4370
4371    /*
4372     * Check all signature algorithms are consistent with signature
4373     * algorithms extension if TLS 1.2 or later and strict mode.
4374     */
4375    if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
4376        int default_nid;
4377        unsigned char rsign = 0;
4378        if (c->peer_sigalgs)
4379            default_nid = 0;
4380        /* If no sigalgs extension use defaults from RFC5246 */
4381        else {
4382            switch (idx) {
4383            case SSL_PKEY_RSA_ENC:
4384            case SSL_PKEY_RSA_SIGN:
4385            case SSL_PKEY_DH_RSA:
4386                rsign = TLSEXT_signature_rsa;
4387                default_nid = NID_sha1WithRSAEncryption;
4388                break;
4389
4390            case SSL_PKEY_DSA_SIGN:
4391            case SSL_PKEY_DH_DSA:
4392                rsign = TLSEXT_signature_dsa;
4393                default_nid = NID_dsaWithSHA1;
4394                break;
4395
4396            case SSL_PKEY_ECC:
4397                rsign = TLSEXT_signature_ecdsa;
4398                default_nid = NID_ecdsa_with_SHA1;
4399                break;
4400
4401            default:
4402                default_nid = -1;
4403                break;
4404            }
4405        }
4406        /*
4407         * If peer sent no signature algorithms extension and we have set
4408         * preferred signature algorithms check we support sha1.
4409         */
4410        if (default_nid > 0 && c->conf_sigalgs) {
4411            size_t j;
4412            const unsigned char *p = c->conf_sigalgs;
4413            for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2) {
4414                if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
4415                    break;
4416            }
4417            if (j == c->conf_sigalgslen) {
4418                if (check_flags)
4419                    goto skip_sigs;
4420                else
4421                    goto end;
4422            }
4423        }
4424        /* Check signature algorithm of each cert in chain */
4425        if (!tls1_check_sig_alg(c, x, default_nid)) {
4426            if (!check_flags)
4427                goto end;
4428        } else
4429            rv |= CERT_PKEY_EE_SIGNATURE;
4430        rv |= CERT_PKEY_CA_SIGNATURE;
4431        for (i = 0; i < sk_X509_num(chain); i++) {
4432            if (!tls1_check_sig_alg(c, sk_X509_value(chain, i), default_nid)) {
4433                if (check_flags) {
4434                    rv &= ~CERT_PKEY_CA_SIGNATURE;
4435                    break;
4436                } else
4437                    goto end;
4438            }
4439        }
4440    }
4441    /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
4442    else if (check_flags)
4443        rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
4444 skip_sigs:
4445    /* Check cert parameters are consistent */
4446    if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
4447        rv |= CERT_PKEY_EE_PARAM;
4448    else if (!check_flags)
4449        goto end;
4450    if (!s->server)
4451        rv |= CERT_PKEY_CA_PARAM;
4452    /* In strict mode check rest of chain too */
4453    else if (strict_mode) {
4454        rv |= CERT_PKEY_CA_PARAM;
4455        for (i = 0; i < sk_X509_num(chain); i++) {
4456            X509 *ca = sk_X509_value(chain, i);
4457            if (!tls1_check_cert_param(s, ca, 0)) {
4458                if (check_flags) {
4459                    rv &= ~CERT_PKEY_CA_PARAM;
4460                    break;
4461                } else
4462                    goto end;
4463            }
4464        }
4465    }
4466    if (!s->server && strict_mode) {
4467        STACK_OF(X509_NAME) *ca_dn;
4468        int check_type = 0;
4469        switch (pk->type) {
4470        case EVP_PKEY_RSA:
4471            check_type = TLS_CT_RSA_SIGN;
4472            break;
4473        case EVP_PKEY_DSA:
4474            check_type = TLS_CT_DSS_SIGN;
4475            break;
4476        case EVP_PKEY_EC:
4477            check_type = TLS_CT_ECDSA_SIGN;
4478            break;
4479        case EVP_PKEY_DH:
4480        case EVP_PKEY_DHX:
4481            {
4482                int cert_type = X509_certificate_type(x, pk);
4483                if (cert_type & EVP_PKS_RSA)
4484                    check_type = TLS_CT_RSA_FIXED_DH;
4485                if (cert_type & EVP_PKS_DSA)
4486                    check_type = TLS_CT_DSS_FIXED_DH;
4487            }
4488        }
4489        if (check_type) {
4490            const unsigned char *ctypes;
4491            int ctypelen;
4492            if (c->ctypes) {
4493                ctypes = c->ctypes;
4494                ctypelen = (int)c->ctype_num;
4495            } else {
4496                ctypes = (unsigned char *)s->s3->tmp.ctype;
4497                ctypelen = s->s3->tmp.ctype_num;
4498            }
4499            for (i = 0; i < ctypelen; i++) {
4500                if (ctypes[i] == check_type) {
4501                    rv |= CERT_PKEY_CERT_TYPE;
4502                    break;
4503                }
4504            }
4505            if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4506                goto end;
4507        } else
4508            rv |= CERT_PKEY_CERT_TYPE;
4509
4510        ca_dn = s->s3->tmp.ca_names;
4511
4512        if (!sk_X509_NAME_num(ca_dn))
4513            rv |= CERT_PKEY_ISSUER_NAME;
4514
4515        if (!(rv & CERT_PKEY_ISSUER_NAME)) {
4516            if (ssl_check_ca_name(ca_dn, x))
4517                rv |= CERT_PKEY_ISSUER_NAME;
4518        }
4519        if (!(rv & CERT_PKEY_ISSUER_NAME)) {
4520            for (i = 0; i < sk_X509_num(chain); i++) {
4521                X509 *xtmp = sk_X509_value(chain, i);
4522                if (ssl_check_ca_name(ca_dn, xtmp)) {
4523                    rv |= CERT_PKEY_ISSUER_NAME;
4524                    break;
4525                }
4526            }
4527        }
4528        if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4529            goto end;
4530    } else
4531        rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
4532
4533    if (!check_flags || (rv & check_flags) == check_flags)
4534        rv |= CERT_PKEY_VALID;
4535
4536 end:
4537
4538    if (TLS1_get_version(s) >= TLS1_2_VERSION) {
4539        if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4540            rv |= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
4541        else if (cpk->digest)
4542            rv |= CERT_PKEY_SIGN;
4543    } else
4544        rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
4545
4546    /*
4547     * When checking a CERT_PKEY structure all flags are irrelevant if the
4548     * chain is invalid.
4549     */
4550    if (!check_flags) {
4551        if (rv & CERT_PKEY_VALID)
4552            cpk->valid_flags = rv;
4553        else {
4554            /* Preserve explicit sign flag, clear rest */
4555            cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4556            return 0;
4557        }
4558    }
4559    return rv;
4560}
4561
4562/* Set validity of certificates in an SSL structure */
4563void tls1_set_cert_validity(SSL *s)
4564{
4565    tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4566    tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4567    tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4568    tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4569    tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4570    tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4571}
4572
4573/* User level utiity function to check a chain is suitable */
4574int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4575{
4576    return tls1_check_chain(s, x, pk, chain, -1);
4577}
4578
4579#endif
4580