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