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