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