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