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