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