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