]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssl/ssl/t1_lib.c
Merge OpenSSL 1.0.2i.
[FreeBSD/FreeBSD.git] / crypto / openssl / 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         if ((long)(limit - ret - 7 - extlen - idlen) < 0)
1483             return NULL;
1484         s2n(TLSEXT_TYPE_status_request, ret);
1485         if (extlen + idlen > 0xFFF0)
1486             return NULL;
1487         s2n(extlen + idlen + 5, ret);
1488         *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1489         s2n(idlen, ret);
1490         for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
1491             /* save position of id len */
1492             unsigned char *q = ret;
1493             id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1494             /* skip over id len */
1495             ret += 2;
1496             itmp = i2d_OCSP_RESPID(id, &ret);
1497             /* write id len */
1498             s2n(itmp, q);
1499         }
1500         s2n(extlen, ret);
1501         if (extlen > 0)
1502             i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1503     }
1504 # ifndef OPENSSL_NO_HEARTBEATS
1505     /* Add Heartbeat extension */
1506     if ((limit - ret - 4 - 1) < 0)
1507         return NULL;
1508     s2n(TLSEXT_TYPE_heartbeat, ret);
1509     s2n(1, ret);
1510     /*-
1511      * Set mode:
1512      * 1: peer may send requests
1513      * 2: peer not allowed to send requests
1514      */
1515     if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1516         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1517     else
1518         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1519 # endif
1520
1521 # ifndef OPENSSL_NO_NEXTPROTONEG
1522     if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) {
1523         /*
1524          * The client advertises an emtpy extension to indicate its support
1525          * for Next Protocol Negotiation
1526          */
1527         if (limit - ret - 4 < 0)
1528             return NULL;
1529         s2n(TLSEXT_TYPE_next_proto_neg, ret);
1530         s2n(0, ret);
1531     }
1532 # endif
1533
1534     if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) {
1535         if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
1536             return NULL;
1537         s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
1538         s2n(2 + s->alpn_client_proto_list_len, ret);
1539         s2n(s->alpn_client_proto_list_len, ret);
1540         memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len);
1541         ret += s->alpn_client_proto_list_len;
1542         s->cert->alpn_sent = 1;
1543     }
1544 # ifndef OPENSSL_NO_SRTP
1545     if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) {
1546         int el;
1547
1548         ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1549
1550         if ((limit - ret - 4 - el) < 0)
1551             return NULL;
1552
1553         s2n(TLSEXT_TYPE_use_srtp, ret);
1554         s2n(el, ret);
1555
1556         if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) {
1557             SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1558             return NULL;
1559         }
1560         ret += el;
1561     }
1562 # endif
1563     custom_ext_init(&s->cert->cli_ext);
1564     /* Add custom TLS Extensions to ClientHello */
1565     if (!custom_ext_add(s, 0, &ret, limit, al))
1566         return NULL;
1567
1568     /*
1569      * Add padding to workaround bugs in F5 terminators. See
1570      * https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this
1571      * code works out the length of all existing extensions it MUST always
1572      * appear last.
1573      */
1574     if (s->options & SSL_OP_TLSEXT_PADDING) {
1575         int hlen = ret - (unsigned char *)s->init_buf->data;
1576         /*
1577          * The code in s23_clnt.c to build ClientHello messages includes the
1578          * 5-byte record header in the buffer, while the code in s3_clnt.c
1579          * does not.
1580          */
1581         if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
1582             hlen -= 5;
1583         if (hlen > 0xff && hlen < 0x200) {
1584             hlen = 0x200 - hlen;
1585             if (hlen >= 4)
1586                 hlen -= 4;
1587             else
1588                 hlen = 0;
1589
1590             s2n(TLSEXT_TYPE_padding, ret);
1591             s2n(hlen, ret);
1592             memset(ret, 0, hlen);
1593             ret += hlen;
1594         }
1595     }
1596
1597     if ((extdatalen = ret - orig - 2) == 0)
1598         return orig;
1599
1600     s2n(extdatalen, orig);
1601     return ret;
1602 }
1603
1604 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,
1605                                           unsigned char *limit, int *al)
1606 {
1607     int extdatalen = 0;
1608     unsigned char *orig = buf;
1609     unsigned char *ret = buf;
1610 # ifndef OPENSSL_NO_NEXTPROTONEG
1611     int next_proto_neg_seen;
1612 # endif
1613 # ifndef OPENSSL_NO_EC
1614     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1615     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1616     int using_ecc = (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
1617         || (alg_a & SSL_aECDSA);
1618     using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1619 # endif
1620     /*
1621      * don't add extensions for SSLv3, unless doing secure renegotiation
1622      */
1623     if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1624         return orig;
1625
1626     ret += 2;
1627     if (ret >= limit)
1628         return NULL;            /* this really never occurs, but ... */
1629
1630     if (!s->hit && s->servername_done == 1
1631         && s->session->tlsext_hostname != NULL) {
1632         if ((long)(limit - ret - 4) < 0)
1633             return NULL;
1634
1635         s2n(TLSEXT_TYPE_server_name, ret);
1636         s2n(0, ret);
1637     }
1638
1639     if (s->s3->send_connection_binding) {
1640         int el;
1641
1642         if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) {
1643             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1644             return NULL;
1645         }
1646
1647         if ((limit - ret - 4 - el) < 0)
1648             return NULL;
1649
1650         s2n(TLSEXT_TYPE_renegotiate, ret);
1651         s2n(el, ret);
1652
1653         if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) {
1654             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1655             return NULL;
1656         }
1657
1658         ret += el;
1659     }
1660 # ifndef OPENSSL_NO_EC
1661     if (using_ecc) {
1662         const unsigned char *plist;
1663         size_t plistlen;
1664         /*
1665          * Add TLS extension ECPointFormats to the ServerHello message
1666          */
1667         long lenmax;
1668
1669         tls1_get_formatlist(s, &plist, &plistlen);
1670
1671         if ((lenmax = limit - ret - 5) < 0)
1672             return NULL;
1673         if (plistlen > (size_t)lenmax)
1674             return NULL;
1675         if (plistlen > 255) {
1676             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1677             return NULL;
1678         }
1679
1680         s2n(TLSEXT_TYPE_ec_point_formats, ret);
1681         s2n(plistlen + 1, ret);
1682         *(ret++) = (unsigned char)plistlen;
1683         memcpy(ret, plist, plistlen);
1684         ret += plistlen;
1685
1686     }
1687     /*
1688      * Currently the server should not respond with a SupportedCurves
1689      * extension
1690      */
1691 # endif                         /* OPENSSL_NO_EC */
1692
1693     if (s->tlsext_ticket_expected && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) {
1694         if ((long)(limit - ret - 4) < 0)
1695             return NULL;
1696         s2n(TLSEXT_TYPE_session_ticket, ret);
1697         s2n(0, ret);
1698     }
1699
1700     if (s->tlsext_status_expected) {
1701         if ((long)(limit - ret - 4) < 0)
1702             return NULL;
1703         s2n(TLSEXT_TYPE_status_request, ret);
1704         s2n(0, ret);
1705     }
1706 # ifdef TLSEXT_TYPE_opaque_prf_input
1707     if (s->s3->server_opaque_prf_input != NULL) {
1708         size_t sol = s->s3->server_opaque_prf_input_len;
1709
1710         if ((long)(limit - ret - 6 - sol) < 0)
1711             return NULL;
1712         if (sol > 0xFFFD)       /* can't happen */
1713             return NULL;
1714
1715         s2n(TLSEXT_TYPE_opaque_prf_input, ret);
1716         s2n(sol + 2, ret);
1717         s2n(sol, ret);
1718         memcpy(ret, s->s3->server_opaque_prf_input, sol);
1719         ret += sol;
1720     }
1721 # endif
1722
1723 # ifndef OPENSSL_NO_SRTP
1724     if (SSL_IS_DTLS(s) && s->srtp_profile) {
1725         int el;
1726
1727         ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1728
1729         if ((limit - ret - 4 - el) < 0)
1730             return NULL;
1731
1732         s2n(TLSEXT_TYPE_use_srtp, ret);
1733         s2n(el, ret);
1734
1735         if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) {
1736             SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1737             return NULL;
1738         }
1739         ret += el;
1740     }
1741 # endif
1742
1743     if (((s->s3->tmp.new_cipher->id & 0xFFFF) == 0x80
1744          || (s->s3->tmp.new_cipher->id & 0xFFFF) == 0x81)
1745         && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) {
1746         const unsigned char cryptopro_ext[36] = {
1747             0xfd, 0xe8,         /* 65000 */
1748             0x00, 0x20,         /* 32 bytes length */
1749             0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1750             0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1751             0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1752             0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1753         };
1754         if (limit - ret < 36)
1755             return NULL;
1756         memcpy(ret, cryptopro_ext, 36);
1757         ret += 36;
1758
1759     }
1760 # ifndef OPENSSL_NO_HEARTBEATS
1761     /* Add Heartbeat extension if we've received one */
1762     if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) {
1763         if ((limit - ret - 4 - 1) < 0)
1764             return NULL;
1765         s2n(TLSEXT_TYPE_heartbeat, ret);
1766         s2n(1, ret);
1767         /*-
1768          * Set mode:
1769          * 1: peer may send requests
1770          * 2: peer not allowed to send requests
1771          */
1772         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1773             *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1774         else
1775             *(ret++) = SSL_TLSEXT_HB_ENABLED;
1776
1777     }
1778 # endif
1779
1780 # ifndef OPENSSL_NO_NEXTPROTONEG
1781     next_proto_neg_seen = s->s3->next_proto_neg_seen;
1782     s->s3->next_proto_neg_seen = 0;
1783     if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) {
1784         const unsigned char *npa;
1785         unsigned int npalen;
1786         int r;
1787
1788         r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,
1789                                               s->
1790                                               ctx->next_protos_advertised_cb_arg);
1791         if (r == SSL_TLSEXT_ERR_OK) {
1792             if ((long)(limit - ret - 4 - npalen) < 0)
1793                 return NULL;
1794             s2n(TLSEXT_TYPE_next_proto_neg, ret);
1795             s2n(npalen, ret);
1796             memcpy(ret, npa, npalen);
1797             ret += npalen;
1798             s->s3->next_proto_neg_seen = 1;
1799         }
1800     }
1801 # endif
1802     if (!custom_ext_add(s, 1, &ret, limit, al))
1803         return NULL;
1804
1805     if (s->s3->alpn_selected) {
1806         const unsigned char *selected = s->s3->alpn_selected;
1807         unsigned len = s->s3->alpn_selected_len;
1808
1809         if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
1810             return NULL;
1811         s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
1812         s2n(3 + len, ret);
1813         s2n(1 + len, ret);
1814         *ret++ = len;
1815         memcpy(ret, selected, len);
1816         ret += len;
1817     }
1818
1819     if ((extdatalen = ret - orig - 2) == 0)
1820         return orig;
1821
1822     s2n(extdatalen, orig);
1823     return ret;
1824 }
1825
1826 # ifndef OPENSSL_NO_EC
1827 /*-
1828  * ssl_check_for_safari attempts to fingerprint Safari using OS X
1829  * SecureTransport using the TLS extension block in |d|, of length |n|.
1830  * Safari, since 10.6, sends exactly these extensions, in this order:
1831  *   SNI,
1832  *   elliptic_curves
1833  *   ec_point_formats
1834  *
1835  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1836  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1837  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1838  * 10.8..10.8.3 (which don't work).
1839  */
1840 static void ssl_check_for_safari(SSL *s, const unsigned char *data,
1841                                  const unsigned char *limit)
1842 {
1843     unsigned short type, size;
1844     static const unsigned char kSafariExtensionsBlock[] = {
1845         0x00, 0x0a,             /* elliptic_curves extension */
1846         0x00, 0x08,             /* 8 bytes */
1847         0x00, 0x06,             /* 6 bytes of curve ids */
1848         0x00, 0x17,             /* P-256 */
1849         0x00, 0x18,             /* P-384 */
1850         0x00, 0x19,             /* P-521 */
1851
1852         0x00, 0x0b,             /* ec_point_formats */
1853         0x00, 0x02,             /* 2 bytes */
1854         0x01,                   /* 1 point format */
1855         0x00,                   /* uncompressed */
1856     };
1857
1858     /* The following is only present in TLS 1.2 */
1859     static const unsigned char kSafariTLS12ExtensionsBlock[] = {
1860         0x00, 0x0d,             /* signature_algorithms */
1861         0x00, 0x0c,             /* 12 bytes */
1862         0x00, 0x0a,             /* 10 bytes */
1863         0x05, 0x01,             /* SHA-384/RSA */
1864         0x04, 0x01,             /* SHA-256/RSA */
1865         0x02, 0x01,             /* SHA-1/RSA */
1866         0x04, 0x03,             /* SHA-256/ECDSA */
1867         0x02, 0x03,             /* SHA-1/ECDSA */
1868     };
1869
1870     if (limit - data <= 2)
1871         return;
1872     data += 2;
1873
1874     if (limit - data < 4)
1875         return;
1876     n2s(data, type);
1877     n2s(data, size);
1878
1879     if (type != TLSEXT_TYPE_server_name)
1880         return;
1881
1882     if (limit - data < size)
1883         return;
1884     data += size;
1885
1886     if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
1887         const size_t len1 = sizeof(kSafariExtensionsBlock);
1888         const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
1889
1890         if (limit - data != (int)(len1 + len2))
1891             return;
1892         if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
1893             return;
1894         if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
1895             return;
1896     } else {
1897         const size_t len = sizeof(kSafariExtensionsBlock);
1898
1899         if (limit - data != (int)(len))
1900             return;
1901         if (memcmp(data, kSafariExtensionsBlock, len) != 0)
1902             return;
1903     }
1904
1905     s->s3->is_probably_safari = 1;
1906 }
1907 # endif                         /* !OPENSSL_NO_EC */
1908
1909 /*
1910  * tls1_alpn_handle_client_hello is called to save the ALPN extension in a
1911  * ClientHello.  data: the contents of the extension, not including the type
1912  * and length.  data_len: the number of bytes in |data| al: a pointer to the
1913  * alert value to send in the event of a non-zero return.  returns: 0 on
1914  * success.
1915  */
1916 static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
1917                                          unsigned data_len, int *al)
1918 {
1919     unsigned i;
1920     unsigned proto_len;
1921
1922     if (data_len < 2)
1923         goto parse_error;
1924
1925     /*
1926      * data should contain a uint16 length followed by a series of 8-bit,
1927      * length-prefixed strings.
1928      */
1929     i = ((unsigned)data[0]) << 8 | ((unsigned)data[1]);
1930     data_len -= 2;
1931     data += 2;
1932     if (data_len != i)
1933         goto parse_error;
1934
1935     if (data_len < 2)
1936         goto parse_error;
1937
1938     for (i = 0; i < data_len;) {
1939         proto_len = data[i];
1940         i++;
1941
1942         if (proto_len == 0)
1943             goto parse_error;
1944
1945         if (i + proto_len < i || i + proto_len > data_len)
1946             goto parse_error;
1947
1948         i += proto_len;
1949     }
1950
1951     if (s->cert->alpn_proposed != NULL)
1952         OPENSSL_free(s->cert->alpn_proposed);
1953     s->cert->alpn_proposed = OPENSSL_malloc(data_len);
1954     if (s->cert->alpn_proposed == NULL) {
1955         *al = SSL_AD_INTERNAL_ERROR;
1956         return -1;
1957     }
1958     memcpy(s->cert->alpn_proposed, data, data_len);
1959     s->cert->alpn_proposed_len = data_len;
1960     return 0;
1961
1962  parse_error:
1963     *al = SSL_AD_DECODE_ERROR;
1964     return -1;
1965 }
1966
1967 /*
1968  * Process the ALPN extension in a ClientHello.
1969  * ret: a pointer to the TLSEXT return value: SSL_TLSEXT_ERR_*
1970  * al: a pointer to the alert value to send in the event of a failure.
1971  * returns 1 on success, 0 on failure: al/ret set only on failure
1972  */
1973 static int tls1_alpn_handle_client_hello_late(SSL *s, int *ret, int *al)
1974 {
1975     const unsigned char *selected = NULL;
1976     unsigned char selected_len = 0;
1977
1978     if (s->ctx->alpn_select_cb != NULL && s->cert->alpn_proposed != NULL) {
1979         int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
1980                                        s->cert->alpn_proposed,
1981                                        s->cert->alpn_proposed_len,
1982                                        s->ctx->alpn_select_cb_arg);
1983
1984         if (r == SSL_TLSEXT_ERR_OK) {
1985             OPENSSL_free(s->s3->alpn_selected);
1986             s->s3->alpn_selected = OPENSSL_malloc(selected_len);
1987             if (s->s3->alpn_selected == NULL) {
1988                 *al = SSL_AD_INTERNAL_ERROR;
1989                 *ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1990                 return 0;
1991             }
1992             memcpy(s->s3->alpn_selected, selected, selected_len);
1993             s->s3->alpn_selected_len = selected_len;
1994 # ifndef OPENSSL_NO_NEXTPROTONEG
1995             /* ALPN takes precedence over NPN. */
1996             s->s3->next_proto_neg_seen = 0;
1997 # endif
1998         }
1999     }
2000
2001     return 1;
2002 }
2003
2004 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p,
2005                                        unsigned char *limit, int *al)
2006 {
2007     unsigned short type;
2008     unsigned short size;
2009     unsigned short len;
2010     unsigned char *data = *p;
2011     int renegotiate_seen = 0;
2012
2013     s->servername_done = 0;
2014     s->tlsext_status_type = -1;
2015 # ifndef OPENSSL_NO_NEXTPROTONEG
2016     s->s3->next_proto_neg_seen = 0;
2017 # endif
2018
2019     if (s->s3->alpn_selected) {
2020         OPENSSL_free(s->s3->alpn_selected);
2021         s->s3->alpn_selected = NULL;
2022     }
2023     s->s3->alpn_selected_len = 0;
2024     if (s->cert->alpn_proposed) {
2025         OPENSSL_free(s->cert->alpn_proposed);
2026         s->cert->alpn_proposed = NULL;
2027     }
2028     s->cert->alpn_proposed_len = 0;
2029 # ifndef OPENSSL_NO_HEARTBEATS
2030     s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2031                              SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2032 # endif
2033
2034 # ifndef OPENSSL_NO_EC
2035     if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
2036         ssl_check_for_safari(s, data, limit);
2037 # endif                         /* !OPENSSL_NO_EC */
2038
2039     /* Clear any signature algorithms extension received */
2040     if (s->cert->peer_sigalgs) {
2041         OPENSSL_free(s->cert->peer_sigalgs);
2042         s->cert->peer_sigalgs = NULL;
2043     }
2044 # ifndef OPENSSL_NO_SRP
2045     if (s->srp_ctx.login != NULL) {
2046         OPENSSL_free(s->srp_ctx.login);
2047         s->srp_ctx.login = NULL;
2048     }
2049 # endif
2050
2051     s->srtp_profile = NULL;
2052
2053     if (data == limit)
2054         goto ri_check;
2055
2056     if (limit - data < 2)
2057         goto err;
2058
2059     n2s(data, len);
2060
2061     if (limit - data != len)
2062         goto err;
2063
2064     while (limit - data >= 4) {
2065         n2s(data, type);
2066         n2s(data, size);
2067
2068         if (limit - data < size)
2069             goto err;
2070 # if 0
2071         fprintf(stderr, "Received extension type %d size %d\n", type, size);
2072 # endif
2073         if (s->tlsext_debug_cb)
2074             s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg);
2075 /*-
2076  * The servername extension is treated as follows:
2077  *
2078  * - Only the hostname type is supported with a maximum length of 255.
2079  * - The servername is rejected if too long or if it contains zeros,
2080  *   in which case an fatal alert is generated.
2081  * - The servername field is maintained together with the session cache.
2082  * - When a session is resumed, the servername call back invoked in order
2083  *   to allow the application to position itself to the right context.
2084  * - The servername is acknowledged if it is new for a session or when
2085  *   it is identical to a previously used for the same session.
2086  *   Applications can control the behaviour.  They can at any time
2087  *   set a 'desirable' servername for a new SSL object. This can be the
2088  *   case for example with HTTPS when a Host: header field is received and
2089  *   a renegotiation is requested. In this case, a possible servername
2090  *   presented in the new client hello is only acknowledged if it matches
2091  *   the value of the Host: field.
2092  * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2093  *   if they provide for changing an explicit servername context for the
2094  *   session, i.e. when the session has been established with a servername
2095  *   extension.
2096  * - On session reconnect, the servername extension may be absent.
2097  *
2098  */
2099
2100         if (type == TLSEXT_TYPE_server_name) {
2101             unsigned char *sdata;
2102             int servname_type;
2103             int dsize;
2104
2105             if (size < 2)
2106                 goto err;
2107             n2s(data, dsize);
2108             size -= 2;
2109             if (dsize > size)
2110                 goto err;
2111
2112             sdata = data;
2113             while (dsize > 3) {
2114                 servname_type = *(sdata++);
2115                 n2s(sdata, len);
2116                 dsize -= 3;
2117
2118                 if (len > dsize)
2119                     goto err;
2120
2121                 if (s->servername_done == 0)
2122                     switch (servname_type) {
2123                     case TLSEXT_NAMETYPE_host_name:
2124                         if (!s->hit) {
2125                             if (s->session->tlsext_hostname)
2126                                 goto err;
2127
2128                             if (len > TLSEXT_MAXLEN_host_name) {
2129                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2130                                 return 0;
2131                             }
2132                             if ((s->session->tlsext_hostname =
2133                                  OPENSSL_malloc(len + 1)) == NULL) {
2134                                 *al = TLS1_AD_INTERNAL_ERROR;
2135                                 return 0;
2136                             }
2137                             memcpy(s->session->tlsext_hostname, sdata, len);
2138                             s->session->tlsext_hostname[len] = '\0';
2139                             if (strlen(s->session->tlsext_hostname) != len) {
2140                                 OPENSSL_free(s->session->tlsext_hostname);
2141                                 s->session->tlsext_hostname = NULL;
2142                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2143                                 return 0;
2144                             }
2145                             s->servername_done = 1;
2146
2147                         } else
2148                             s->servername_done = s->session->tlsext_hostname
2149                                 && strlen(s->session->tlsext_hostname) == len
2150                                 && strncmp(s->session->tlsext_hostname,
2151                                            (char *)sdata, len) == 0;
2152
2153                         break;
2154
2155                     default:
2156                         break;
2157                     }
2158
2159                 dsize -= len;
2160             }
2161             if (dsize != 0)
2162                 goto err;
2163
2164         }
2165 # ifndef OPENSSL_NO_SRP
2166         else if (type == TLSEXT_TYPE_srp) {
2167             if (size == 0 || ((len = data[0])) != (size - 1))
2168                 goto err;
2169             if (s->srp_ctx.login != NULL)
2170                 goto err;
2171             if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL)
2172                 return -1;
2173             memcpy(s->srp_ctx.login, &data[1], len);
2174             s->srp_ctx.login[len] = '\0';
2175
2176             if (strlen(s->srp_ctx.login) != len)
2177                 goto err;
2178         }
2179 # endif
2180
2181 # ifndef OPENSSL_NO_EC
2182         else if (type == TLSEXT_TYPE_ec_point_formats) {
2183             unsigned char *sdata = data;
2184             int ecpointformatlist_length = *(sdata++);
2185
2186             if (ecpointformatlist_length != size - 1 ||
2187                 ecpointformatlist_length < 1)
2188                 goto err;
2189             if (!s->hit) {
2190                 if (s->session->tlsext_ecpointformatlist) {
2191                     OPENSSL_free(s->session->tlsext_ecpointformatlist);
2192                     s->session->tlsext_ecpointformatlist = NULL;
2193                 }
2194                 s->session->tlsext_ecpointformatlist_length = 0;
2195                 if ((s->session->tlsext_ecpointformatlist =
2196                      OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
2197                     *al = TLS1_AD_INTERNAL_ERROR;
2198                     return 0;
2199                 }
2200                 s->session->tlsext_ecpointformatlist_length =
2201                     ecpointformatlist_length;
2202                 memcpy(s->session->tlsext_ecpointformatlist, sdata,
2203                        ecpointformatlist_length);
2204             }
2205 #  if 0
2206             fprintf(stderr,
2207                     "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ",
2208                     s->session->tlsext_ecpointformatlist_length);
2209             sdata = s->session->tlsext_ecpointformatlist;
2210             for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2211                 fprintf(stderr, "%i ", *(sdata++));
2212             fprintf(stderr, "\n");
2213 #  endif
2214         } else if (type == TLSEXT_TYPE_elliptic_curves) {
2215             unsigned char *sdata = data;
2216             int ellipticcurvelist_length = (*(sdata++) << 8);
2217             ellipticcurvelist_length += (*(sdata++));
2218
2219             if (ellipticcurvelist_length != size - 2 ||
2220                 ellipticcurvelist_length < 1 ||
2221                 /* Each NamedCurve is 2 bytes. */
2222                 ellipticcurvelist_length & 1)
2223                     goto err;
2224
2225             if (!s->hit) {
2226                 if (s->session->tlsext_ellipticcurvelist)
2227                     goto err;
2228
2229                 s->session->tlsext_ellipticcurvelist_length = 0;
2230                 if ((s->session->tlsext_ellipticcurvelist =
2231                      OPENSSL_malloc(ellipticcurvelist_length)) == NULL) {
2232                     *al = TLS1_AD_INTERNAL_ERROR;
2233                     return 0;
2234                 }
2235                 s->session->tlsext_ellipticcurvelist_length =
2236                     ellipticcurvelist_length;
2237                 memcpy(s->session->tlsext_ellipticcurvelist, sdata,
2238                        ellipticcurvelist_length);
2239             }
2240 #  if 0
2241             fprintf(stderr,
2242                     "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ",
2243                     s->session->tlsext_ellipticcurvelist_length);
2244             sdata = s->session->tlsext_ellipticcurvelist;
2245             for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2246                 fprintf(stderr, "%i ", *(sdata++));
2247             fprintf(stderr, "\n");
2248 #  endif
2249         }
2250 # endif                         /* OPENSSL_NO_EC */
2251 # ifdef TLSEXT_TYPE_opaque_prf_input
2252         else if (type == TLSEXT_TYPE_opaque_prf_input) {
2253             unsigned char *sdata = data;
2254
2255             if (size < 2) {
2256                 *al = SSL_AD_DECODE_ERROR;
2257                 return 0;
2258             }
2259             n2s(sdata, s->s3->client_opaque_prf_input_len);
2260             if (s->s3->client_opaque_prf_input_len != size - 2) {
2261                 *al = SSL_AD_DECODE_ERROR;
2262                 return 0;
2263             }
2264
2265             if (s->s3->client_opaque_prf_input != NULL) {
2266                 /* shouldn't really happen */
2267                 OPENSSL_free(s->s3->client_opaque_prf_input);
2268             }
2269
2270             /* dummy byte just to get non-NULL */
2271             if (s->s3->client_opaque_prf_input_len == 0)
2272                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
2273             else
2274                 s->s3->client_opaque_prf_input =
2275                     BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2276             if (s->s3->client_opaque_prf_input == NULL) {
2277                 *al = TLS1_AD_INTERNAL_ERROR;
2278                 return 0;
2279             }
2280         }
2281 # endif
2282         else if (type == TLSEXT_TYPE_session_ticket) {
2283             if (s->tls_session_ticket_ext_cb &&
2284                 !s->tls_session_ticket_ext_cb(s, data, size,
2285                                               s->tls_session_ticket_ext_cb_arg))
2286             {
2287                 *al = TLS1_AD_INTERNAL_ERROR;
2288                 return 0;
2289             }
2290         } else if (type == TLSEXT_TYPE_renegotiate) {
2291             if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2292                 return 0;
2293             renegotiate_seen = 1;
2294         } else if (type == TLSEXT_TYPE_signature_algorithms) {
2295             int dsize;
2296             if (s->cert->peer_sigalgs || size < 2)
2297                 goto err;
2298             n2s(data, dsize);
2299             size -= 2;
2300             if (dsize != size || dsize & 1 || !dsize)
2301                 goto err;
2302             if (!tls1_save_sigalgs(s, data, dsize))
2303                 goto err;
2304         } else if (type == TLSEXT_TYPE_status_request) {
2305
2306             if (size < 5)
2307                 goto err;
2308
2309             s->tlsext_status_type = *data++;
2310             size--;
2311             if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
2312                 const unsigned char *sdata;
2313                 int dsize;
2314                 /* Read in responder_id_list */
2315                 n2s(data, dsize);
2316                 size -= 2;
2317                 if (dsize > size)
2318                     goto err;
2319
2320                 /*
2321                  * We remove any OCSP_RESPIDs from a previous handshake
2322                  * to prevent unbounded memory growth - CVE-2016-6304
2323                  */
2324                 sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids,
2325                                         OCSP_RESPID_free);
2326                 if (dsize > 0) {
2327                     s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null();
2328                     if (s->tlsext_ocsp_ids == NULL) {
2329                         *al = SSL_AD_INTERNAL_ERROR;
2330                         return 0;
2331                     }
2332                 } else {
2333                     s->tlsext_ocsp_ids = NULL;
2334                 }
2335
2336                 while (dsize > 0) {
2337                     OCSP_RESPID *id;
2338                     int idsize;
2339                     if (dsize < 4)
2340                         goto err;
2341                     n2s(data, idsize);
2342                     dsize -= 2 + idsize;
2343                     size -= 2 + idsize;
2344                     if (dsize < 0)
2345                         goto err;
2346                     sdata = data;
2347                     data += idsize;
2348                     id = d2i_OCSP_RESPID(NULL, &sdata, idsize);
2349                     if (!id)
2350                         goto err;
2351                     if (data != sdata) {
2352                         OCSP_RESPID_free(id);
2353                         goto err;
2354                     }
2355                     if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
2356                         OCSP_RESPID_free(id);
2357                         *al = SSL_AD_INTERNAL_ERROR;
2358                         return 0;
2359                     }
2360                 }
2361
2362                 /* Read in request_extensions */
2363                 if (size < 2)
2364                     goto err;
2365                 n2s(data, dsize);
2366                 size -= 2;
2367                 if (dsize != size)
2368                     goto err;
2369                 sdata = data;
2370                 if (dsize > 0) {
2371                     if (s->tlsext_ocsp_exts) {
2372                         sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2373                                                    X509_EXTENSION_free);
2374                     }
2375
2376                     s->tlsext_ocsp_exts =
2377                         d2i_X509_EXTENSIONS(NULL, &sdata, dsize);
2378                     if (!s->tlsext_ocsp_exts || (data + dsize != sdata))
2379                         goto err;
2380                 }
2381             }
2382             /*
2383              * We don't know what to do with any other type * so ignore it.
2384              */
2385             else
2386                 s->tlsext_status_type = -1;
2387         }
2388 # ifndef OPENSSL_NO_HEARTBEATS
2389         else if (type == TLSEXT_TYPE_heartbeat) {
2390             switch (data[0]) {
2391             case 0x01:         /* Client allows us to send HB requests */
2392                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2393                 break;
2394             case 0x02:         /* Client doesn't accept HB requests */
2395                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2396                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2397                 break;
2398             default:
2399                 *al = SSL_AD_ILLEGAL_PARAMETER;
2400                 return 0;
2401             }
2402         }
2403 # endif
2404 # ifndef OPENSSL_NO_NEXTPROTONEG
2405         else if (type == TLSEXT_TYPE_next_proto_neg &&
2406                  s->s3->tmp.finish_md_len == 0) {
2407             /*-
2408              * We shouldn't accept this extension on a
2409              * renegotiation.
2410              *
2411              * s->new_session will be set on renegotiation, but we
2412              * probably shouldn't rely that it couldn't be set on
2413              * the initial renegotation too in certain cases (when
2414              * there's some other reason to disallow resuming an
2415              * earlier session -- the current code won't be doing
2416              * anything like that, but this might change).
2417              *
2418              * A valid sign that there's been a previous handshake
2419              * in this connection is if s->s3->tmp.finish_md_len >
2420              * 0.  (We are talking about a check that will happen
2421              * in the Hello protocol round, well before a new
2422              * Finished message could have been computed.)
2423              */
2424             s->s3->next_proto_neg_seen = 1;
2425         }
2426 # endif
2427
2428         else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2429                  s->s3->tmp.finish_md_len == 0) {
2430             if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2431                 return 0;
2432         }
2433
2434         /* session ticket processed earlier */
2435 # ifndef OPENSSL_NO_SRTP
2436         else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
2437                  && type == TLSEXT_TYPE_use_srtp) {
2438             if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al))
2439                 return 0;
2440         }
2441 # endif
2442
2443         data += size;
2444     }
2445
2446     /* Spurious data on the end */
2447     if (data != limit)
2448         goto err;
2449
2450     *p = data;
2451
2452  ri_check:
2453
2454     /* Need RI if renegotiating */
2455
2456     if (!renegotiate_seen && s->renegotiate &&
2457         !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
2458         *al = SSL_AD_HANDSHAKE_FAILURE;
2459         SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2460                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2461         return 0;
2462     }
2463
2464     return 1;
2465 err:
2466     *al = SSL_AD_DECODE_ERROR;
2467     return 0;
2468 }
2469
2470 /*
2471  * Parse any custom extensions found.  "data" is the start of the extension data
2472  * and "limit" is the end of the record. TODO: add strict syntax checking.
2473  */
2474
2475 static int ssl_scan_clienthello_custom_tlsext(SSL *s,
2476                                               const unsigned char *data,
2477                                               const unsigned char *limit,
2478                                               int *al)
2479 {
2480     unsigned short type, size, len;
2481     /* If resumed session or no custom extensions nothing to do */
2482     if (s->hit || s->cert->srv_ext.meths_count == 0)
2483         return 1;
2484
2485     if (limit - data <= 2)
2486         return 1;
2487     n2s(data, len);
2488
2489     if (limit - data < len)
2490         return 1;
2491
2492     while (limit - data >= 4) {
2493         n2s(data, type);
2494         n2s(data, size);
2495
2496         if (limit - data < size)
2497             return 1;
2498         if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0)
2499             return 0;
2500
2501         data += size;
2502     }
2503
2504     return 1;
2505 }
2506
2507 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p,
2508                                  unsigned char *limit)
2509 {
2510     int al = -1;
2511     unsigned char *ptmp = *p;
2512     /*
2513      * Internally supported extensions are parsed first so SNI can be handled
2514      * before custom extensions. An application processing SNI will typically
2515      * switch the parent context using SSL_set_SSL_CTX and custom extensions
2516      * need to be handled by the new SSL_CTX structure.
2517      */
2518     if (ssl_scan_clienthello_tlsext(s, p, limit, &al) <= 0) {
2519         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2520         return 0;
2521     }
2522
2523     if (ssl_check_clienthello_tlsext_early(s) <= 0) {
2524         SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_CLIENTHELLO_TLSEXT);
2525         return 0;
2526     }
2527
2528     custom_ext_init(&s->cert->srv_ext);
2529     if (ssl_scan_clienthello_custom_tlsext(s, ptmp, limit, &al) <= 0) {
2530         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2531         return 0;
2532     }
2533
2534     return 1;
2535 }
2536
2537 # ifndef OPENSSL_NO_NEXTPROTONEG
2538 /*
2539  * ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2540  * elements of zero length are allowed and the set of elements must exactly
2541  * fill the length of the block.
2542  */
2543 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2544 {
2545     unsigned int off = 0;
2546
2547     while (off < len) {
2548         if (d[off] == 0)
2549             return 0;
2550         off += d[off];
2551         off++;
2552     }
2553
2554     return off == len;
2555 }
2556 # endif
2557
2558 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p,
2559                                        unsigned char *d, int n, int *al)
2560 {
2561     unsigned short length;
2562     unsigned short type;
2563     unsigned short size;
2564     unsigned char *data = *p;
2565     int tlsext_servername = 0;
2566     int renegotiate_seen = 0;
2567
2568 # ifndef OPENSSL_NO_NEXTPROTONEG
2569     s->s3->next_proto_neg_seen = 0;
2570 # endif
2571     s->tlsext_ticket_expected = 0;
2572
2573     if (s->s3->alpn_selected) {
2574         OPENSSL_free(s->s3->alpn_selected);
2575         s->s3->alpn_selected = NULL;
2576     }
2577 # ifndef OPENSSL_NO_HEARTBEATS
2578     s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2579                              SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2580 # endif
2581
2582     if ((d + n) - data <= 2)
2583         goto ri_check;
2584
2585     n2s(data, length);
2586     if ((d + n) - data != length) {
2587         *al = SSL_AD_DECODE_ERROR;
2588         return 0;
2589     }
2590
2591     while ((d + n) - data >= 4) {
2592         n2s(data, type);
2593         n2s(data, size);
2594
2595         if ((d + n) - data < size)
2596             goto ri_check;
2597
2598         if (s->tlsext_debug_cb)
2599             s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg);
2600
2601         if (type == TLSEXT_TYPE_server_name) {
2602             if (s->tlsext_hostname == NULL || size > 0) {
2603                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2604                 return 0;
2605             }
2606             tlsext_servername = 1;
2607         }
2608 # ifndef OPENSSL_NO_EC
2609         else if (type == TLSEXT_TYPE_ec_point_formats) {
2610             unsigned char *sdata = data;
2611             int ecpointformatlist_length = *(sdata++);
2612
2613             if (ecpointformatlist_length != size - 1) {
2614                 *al = TLS1_AD_DECODE_ERROR;
2615                 return 0;
2616             }
2617             if (!s->hit) {
2618                 s->session->tlsext_ecpointformatlist_length = 0;
2619                 if (s->session->tlsext_ecpointformatlist != NULL)
2620                     OPENSSL_free(s->session->tlsext_ecpointformatlist);
2621                 if ((s->session->tlsext_ecpointformatlist =
2622                      OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
2623                     *al = TLS1_AD_INTERNAL_ERROR;
2624                     return 0;
2625                 }
2626                 s->session->tlsext_ecpointformatlist_length =
2627                     ecpointformatlist_length;
2628                 memcpy(s->session->tlsext_ecpointformatlist, sdata,
2629                        ecpointformatlist_length);
2630             }
2631 #  if 0
2632             fprintf(stderr,
2633                     "ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2634             sdata = s->session->tlsext_ecpointformatlist;
2635             for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2636                 fprintf(stderr, "%i ", *(sdata++));
2637             fprintf(stderr, "\n");
2638 #  endif
2639         }
2640 # endif                         /* OPENSSL_NO_EC */
2641
2642         else if (type == TLSEXT_TYPE_session_ticket) {
2643             if (s->tls_session_ticket_ext_cb &&
2644                 !s->tls_session_ticket_ext_cb(s, data, size,
2645                                               s->tls_session_ticket_ext_cb_arg))
2646             {
2647                 *al = TLS1_AD_INTERNAL_ERROR;
2648                 return 0;
2649             }
2650             if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2651                 || (size > 0)) {
2652                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2653                 return 0;
2654             }
2655             s->tlsext_ticket_expected = 1;
2656         }
2657 # ifdef TLSEXT_TYPE_opaque_prf_input
2658         else if (type == TLSEXT_TYPE_opaque_prf_input) {
2659             unsigned char *sdata = data;
2660
2661             if (size < 2) {
2662                 *al = SSL_AD_DECODE_ERROR;
2663                 return 0;
2664             }
2665             n2s(sdata, s->s3->server_opaque_prf_input_len);
2666             if (s->s3->server_opaque_prf_input_len != size - 2) {
2667                 *al = SSL_AD_DECODE_ERROR;
2668                 return 0;
2669             }
2670
2671             if (s->s3->server_opaque_prf_input != NULL) {
2672                 /* shouldn't really happen */
2673                 OPENSSL_free(s->s3->server_opaque_prf_input);
2674             }
2675             if (s->s3->server_opaque_prf_input_len == 0) {
2676                 /* dummy byte just to get non-NULL */
2677                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
2678             } else {
2679                 s->s3->server_opaque_prf_input =
2680                     BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2681             }
2682
2683             if (s->s3->server_opaque_prf_input == NULL) {
2684                 *al = TLS1_AD_INTERNAL_ERROR;
2685                 return 0;
2686             }
2687         }
2688 # endif
2689         else if (type == TLSEXT_TYPE_status_request) {
2690             /*
2691              * MUST be empty and only sent if we've requested a status
2692              * request message.
2693              */
2694             if ((s->tlsext_status_type == -1) || (size > 0)) {
2695                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2696                 return 0;
2697             }
2698             /* Set flag to expect CertificateStatus message */
2699             s->tlsext_status_expected = 1;
2700         }
2701 # ifndef OPENSSL_NO_NEXTPROTONEG
2702         else if (type == TLSEXT_TYPE_next_proto_neg &&
2703                  s->s3->tmp.finish_md_len == 0) {
2704             unsigned char *selected;
2705             unsigned char selected_len;
2706
2707             /* We must have requested it. */
2708             if (s->ctx->next_proto_select_cb == NULL) {
2709                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2710                 return 0;
2711             }
2712             /* The data must be valid */
2713             if (!ssl_next_proto_validate(data, size)) {
2714                 *al = TLS1_AD_DECODE_ERROR;
2715                 return 0;
2716             }
2717             if (s->
2718                 ctx->next_proto_select_cb(s, &selected, &selected_len, data,
2719                                           size,
2720                                           s->ctx->next_proto_select_cb_arg) !=
2721                 SSL_TLSEXT_ERR_OK) {
2722                 *al = TLS1_AD_INTERNAL_ERROR;
2723                 return 0;
2724             }
2725             /*
2726              * Could be non-NULL if server has sent multiple NPN extensions in
2727              * a single Serverhello
2728              */
2729             OPENSSL_free(s->next_proto_negotiated);
2730             s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2731             if (!s->next_proto_negotiated) {
2732                 *al = TLS1_AD_INTERNAL_ERROR;
2733                 return 0;
2734             }
2735             memcpy(s->next_proto_negotiated, selected, selected_len);
2736             s->next_proto_negotiated_len = selected_len;
2737             s->s3->next_proto_neg_seen = 1;
2738         }
2739 # endif
2740
2741         else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) {
2742             unsigned len;
2743
2744             /* We must have requested it. */
2745             if (!s->cert->alpn_sent) {
2746                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2747                 return 0;
2748             }
2749             if (size < 4) {
2750                 *al = TLS1_AD_DECODE_ERROR;
2751                 return 0;
2752             }
2753             /*-
2754              * The extension data consists of:
2755              *   uint16 list_length
2756              *   uint8 proto_length;
2757              *   uint8 proto[proto_length];
2758              */
2759             len = data[0];
2760             len <<= 8;
2761             len |= data[1];
2762             if (len != (unsigned)size - 2) {
2763                 *al = TLS1_AD_DECODE_ERROR;
2764                 return 0;
2765             }
2766             len = data[2];
2767             if (len != (unsigned)size - 3) {
2768                 *al = TLS1_AD_DECODE_ERROR;
2769                 return 0;
2770             }
2771             if (s->s3->alpn_selected)
2772                 OPENSSL_free(s->s3->alpn_selected);
2773             s->s3->alpn_selected = OPENSSL_malloc(len);
2774             if (!s->s3->alpn_selected) {
2775                 *al = TLS1_AD_INTERNAL_ERROR;
2776                 return 0;
2777             }
2778             memcpy(s->s3->alpn_selected, data + 3, len);
2779             s->s3->alpn_selected_len = len;
2780         }
2781
2782         else if (type == TLSEXT_TYPE_renegotiate) {
2783             if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2784                 return 0;
2785             renegotiate_seen = 1;
2786         }
2787 # ifndef OPENSSL_NO_HEARTBEATS
2788         else if (type == TLSEXT_TYPE_heartbeat) {
2789             switch (data[0]) {
2790             case 0x01:         /* Server allows us to send HB requests */
2791                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2792                 break;
2793             case 0x02:         /* Server doesn't accept HB requests */
2794                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2795                 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2796                 break;
2797             default:
2798                 *al = SSL_AD_ILLEGAL_PARAMETER;
2799                 return 0;
2800             }
2801         }
2802 # endif
2803 # ifndef OPENSSL_NO_SRTP
2804         else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) {
2805             if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al))
2806                 return 0;
2807         }
2808 # endif
2809         /*
2810          * If this extension type was not otherwise handled, but matches a
2811          * custom_cli_ext_record, then send it to the c callback
2812          */
2813         else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2814             return 0;
2815
2816         data += size;
2817     }
2818
2819     if (data != d + n) {
2820         *al = SSL_AD_DECODE_ERROR;
2821         return 0;
2822     }
2823
2824     if (!s->hit && tlsext_servername == 1) {
2825         if (s->tlsext_hostname) {
2826             if (s->session->tlsext_hostname == NULL) {
2827                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
2828                 if (!s->session->tlsext_hostname) {
2829                     *al = SSL_AD_UNRECOGNIZED_NAME;
2830                     return 0;
2831                 }
2832             } else {
2833                 *al = SSL_AD_DECODE_ERROR;
2834                 return 0;
2835             }
2836         }
2837     }
2838
2839     *p = data;
2840
2841  ri_check:
2842
2843     /*
2844      * Determine if we need to see RI. Strictly speaking if we want to avoid
2845      * an attack we should *always* see RI even on initial server hello
2846      * because the client doesn't see any renegotiation during an attack.
2847      * However this would mean we could not connect to any server which
2848      * doesn't support RI so for the immediate future tolerate RI absence on
2849      * initial connect only.
2850      */
2851     if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2852         && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
2853         *al = SSL_AD_HANDSHAKE_FAILURE;
2854         SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2855                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2856         return 0;
2857     }
2858
2859     return 1;
2860 }
2861
2862 int ssl_prepare_clienthello_tlsext(SSL *s)
2863 {
2864
2865 # ifdef TLSEXT_TYPE_opaque_prf_input
2866     {
2867         int r = 1;
2868
2869         if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
2870             r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
2871                                                          s->
2872                                                          ctx->tlsext_opaque_prf_input_callback_arg);
2873             if (!r)
2874                 return -1;
2875         }
2876
2877         if (s->tlsext_opaque_prf_input != NULL) {
2878             if (s->s3->client_opaque_prf_input != NULL) {
2879                 /* shouldn't really happen */
2880                 OPENSSL_free(s->s3->client_opaque_prf_input);
2881             }
2882
2883             if (s->tlsext_opaque_prf_input_len == 0) {
2884                 /* dummy byte just to get non-NULL */
2885                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
2886             } else {
2887                 s->s3->client_opaque_prf_input =
2888                     BUF_memdup(s->tlsext_opaque_prf_input,
2889                                s->tlsext_opaque_prf_input_len);
2890             }
2891             if (s->s3->client_opaque_prf_input == NULL) {
2892                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,
2893                        ERR_R_MALLOC_FAILURE);
2894                 return -1;
2895             }
2896             s->s3->client_opaque_prf_input_len =
2897                 s->tlsext_opaque_prf_input_len;
2898         }
2899
2900         if (r == 2)
2901             /*
2902              * at callback's request, insist on receiving an appropriate
2903              * server opaque PRF input
2904              */
2905             s->s3->server_opaque_prf_input_len =
2906                 s->tlsext_opaque_prf_input_len;
2907     }
2908 # endif
2909
2910     s->cert->alpn_sent = 0;
2911     return 1;
2912 }
2913
2914 int ssl_prepare_serverhello_tlsext(SSL *s)
2915 {
2916     return 1;
2917 }
2918
2919 static int ssl_check_clienthello_tlsext_early(SSL *s)
2920 {
2921     int ret = SSL_TLSEXT_ERR_NOACK;
2922     int al = SSL_AD_UNRECOGNIZED_NAME;
2923
2924 # ifndef OPENSSL_NO_EC
2925     /*
2926      * The handling of the ECPointFormats extension is done elsewhere, namely
2927      * in ssl3_choose_cipher in s3_lib.c.
2928      */
2929     /*
2930      * The handling of the EllipticCurves extension is done elsewhere, namely
2931      * in ssl3_choose_cipher in s3_lib.c.
2932      */
2933 # endif
2934
2935     if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
2936         ret =
2937             s->ctx->tlsext_servername_callback(s, &al,
2938                                                s->ctx->tlsext_servername_arg);
2939     else if (s->initial_ctx != NULL
2940              && s->initial_ctx->tlsext_servername_callback != 0)
2941         ret =
2942             s->initial_ctx->tlsext_servername_callback(s, &al,
2943                                                        s->
2944                                                        initial_ctx->tlsext_servername_arg);
2945
2946 # ifdef TLSEXT_TYPE_opaque_prf_input
2947     {
2948         /*
2949          * This sort of belongs into ssl_prepare_serverhello_tlsext(), but we
2950          * might be sending an alert in response to the client hello, so this
2951          * has to happen here in ssl_check_clienthello_tlsext_early().
2952          */
2953
2954         int r = 1;
2955
2956         if (s->ctx->tlsext_opaque_prf_input_callback != 0) {
2957             r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0,
2958                                                          s->
2959                                                          ctx->tlsext_opaque_prf_input_callback_arg);
2960             if (!r) {
2961                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2962                 al = SSL_AD_INTERNAL_ERROR;
2963                 goto err;
2964             }
2965         }
2966
2967         if (s->s3->server_opaque_prf_input != NULL) {
2968             /* shouldn't really happen */
2969             OPENSSL_free(s->s3->server_opaque_prf_input);
2970         }
2971         s->s3->server_opaque_prf_input = NULL;
2972
2973         if (s->tlsext_opaque_prf_input != NULL) {
2974             if (s->s3->client_opaque_prf_input != NULL &&
2975                 s->s3->client_opaque_prf_input_len ==
2976                 s->tlsext_opaque_prf_input_len) {
2977                 /*
2978                  * can only use this extension if we have a server opaque PRF
2979                  * input of the same length as the client opaque PRF input!
2980                  */
2981
2982                 if (s->tlsext_opaque_prf_input_len == 0) {
2983                     /* dummy byte just to get non-NULL */
2984                     s->s3->server_opaque_prf_input = OPENSSL_malloc(1);
2985                 } else {
2986                     s->s3->server_opaque_prf_input =
2987                         BUF_memdup(s->tlsext_opaque_prf_input,
2988                                    s->tlsext_opaque_prf_input_len);
2989                 }
2990                 if (s->s3->server_opaque_prf_input == NULL) {
2991                     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2992                     al = SSL_AD_INTERNAL_ERROR;
2993                     goto err;
2994                 }
2995                 s->s3->server_opaque_prf_input_len =
2996                     s->tlsext_opaque_prf_input_len;
2997             }
2998         }
2999
3000         if (r == 2 && s->s3->server_opaque_prf_input == NULL) {
3001             /*
3002              * The callback wants to enforce use of the extension, but we
3003              * can't do that with the client opaque PRF input; abort the
3004              * handshake.
3005              */
3006             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3007             al = SSL_AD_HANDSHAKE_FAILURE;
3008         }
3009     }
3010
3011  err:
3012 # endif
3013     switch (ret) {
3014     case SSL_TLSEXT_ERR_ALERT_FATAL:
3015         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3016         return -1;
3017
3018     case SSL_TLSEXT_ERR_ALERT_WARNING:
3019         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3020         return 1;
3021
3022     case SSL_TLSEXT_ERR_NOACK:
3023         s->servername_done = 0;
3024     default:
3025         return 1;
3026     }
3027 }
3028
3029 int tls1_set_server_sigalgs(SSL *s)
3030 {
3031     int al;
3032     size_t i;
3033     /* Clear any shared sigtnature algorithms */
3034     if (s->cert->shared_sigalgs) {
3035         OPENSSL_free(s->cert->shared_sigalgs);
3036         s->cert->shared_sigalgs = NULL;
3037         s->cert->shared_sigalgslen = 0;
3038     }
3039     /* Clear certificate digests and validity flags */
3040     for (i = 0; i < SSL_PKEY_NUM; i++) {
3041         s->cert->pkeys[i].digest = NULL;
3042         s->cert->pkeys[i].valid_flags = 0;
3043     }
3044
3045     /* If sigalgs received process it. */
3046     if (s->cert->peer_sigalgs) {
3047         if (!tls1_process_sigalgs(s)) {
3048             SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
3049             al = SSL_AD_INTERNAL_ERROR;
3050             goto err;
3051         }
3052         /* Fatal error is no shared signature algorithms */
3053         if (!s->cert->shared_sigalgs) {
3054             SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
3055                    SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
3056             al = SSL_AD_ILLEGAL_PARAMETER;
3057             goto err;
3058         }
3059     } else
3060         ssl_cert_set_default_md(s->cert);
3061     return 1;
3062  err:
3063     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3064     return 0;
3065 }
3066
3067 int ssl_check_clienthello_tlsext_late(SSL *s)
3068 {
3069     int ret = SSL_TLSEXT_ERR_OK;
3070     int al;
3071
3072     /*
3073      * If status request then ask callback what to do. Note: this must be
3074      * called after servername callbacks in case the certificate has changed,
3075      * and must be called after the cipher has been chosen because this may
3076      * influence which certificate is sent
3077      */
3078     if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) {
3079         int r;
3080         CERT_PKEY *certpkey;
3081         certpkey = ssl_get_server_send_pkey(s);
3082         /* If no certificate can't return certificate status */
3083         if (certpkey == NULL) {
3084             s->tlsext_status_expected = 0;
3085             return 1;
3086         }
3087         /*
3088          * Set current certificate to one we will use so SSL_get_certificate
3089          * et al can pick it up.
3090          */
3091         s->cert->key = certpkey;
3092         r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3093         switch (r) {
3094             /* We don't want to send a status request response */
3095         case SSL_TLSEXT_ERR_NOACK:
3096             s->tlsext_status_expected = 0;
3097             break;
3098             /* status request response should be sent */
3099         case SSL_TLSEXT_ERR_OK:
3100             if (s->tlsext_ocsp_resp)
3101                 s->tlsext_status_expected = 1;
3102             else
3103                 s->tlsext_status_expected = 0;
3104             break;
3105             /* something bad happened */
3106         case SSL_TLSEXT_ERR_ALERT_FATAL:
3107             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3108             al = SSL_AD_INTERNAL_ERROR;
3109             goto err;
3110         }
3111     } else
3112         s->tlsext_status_expected = 0;
3113
3114     if (!tls1_alpn_handle_client_hello_late(s, &ret, &al)) {
3115         goto err;
3116     }
3117
3118  err:
3119     switch (ret) {
3120     case SSL_TLSEXT_ERR_ALERT_FATAL:
3121         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3122         return -1;
3123
3124     case SSL_TLSEXT_ERR_ALERT_WARNING:
3125         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3126         return 1;
3127
3128     default:
3129         return 1;
3130     }
3131 }
3132
3133 int ssl_check_serverhello_tlsext(SSL *s)
3134 {
3135     int ret = SSL_TLSEXT_ERR_NOACK;
3136     int al = SSL_AD_UNRECOGNIZED_NAME;
3137
3138 # ifndef OPENSSL_NO_EC
3139     /*
3140      * If we are client and using an elliptic curve cryptography cipher
3141      * suite, then if server returns an EC point formats lists extension it
3142      * must contain uncompressed.
3143      */
3144     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3145     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3146     if ((s->tlsext_ecpointformatlist != NULL)
3147         && (s->tlsext_ecpointformatlist_length > 0)
3148         && (s->session->tlsext_ecpointformatlist != NULL)
3149         && (s->session->tlsext_ecpointformatlist_length > 0)
3150         && ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe))
3151             || (alg_a & SSL_aECDSA))) {
3152         /* we are using an ECC cipher */
3153         size_t i;
3154         unsigned char *list;
3155         int found_uncompressed = 0;
3156         list = s->session->tlsext_ecpointformatlist;
3157         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) {
3158             if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) {
3159                 found_uncompressed = 1;
3160                 break;
3161             }
3162         }
3163         if (!found_uncompressed) {
3164             SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,
3165                    SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
3166             return -1;
3167         }
3168     }
3169     ret = SSL_TLSEXT_ERR_OK;
3170 # endif                         /* OPENSSL_NO_EC */
3171
3172     if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
3173         ret =
3174             s->ctx->tlsext_servername_callback(s, &al,
3175                                                s->ctx->tlsext_servername_arg);
3176     else if (s->initial_ctx != NULL
3177              && s->initial_ctx->tlsext_servername_callback != 0)
3178         ret =
3179             s->initial_ctx->tlsext_servername_callback(s, &al,
3180                                                        s->
3181                                                        initial_ctx->tlsext_servername_arg);
3182
3183 # ifdef TLSEXT_TYPE_opaque_prf_input
3184     if (s->s3->server_opaque_prf_input_len > 0) {
3185         /*
3186          * This case may indicate that we, as a client, want to insist on
3187          * using opaque PRF inputs. So first verify that we really have a
3188          * value from the server too.
3189          */
3190
3191         if (s->s3->server_opaque_prf_input == NULL) {
3192             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3193             al = SSL_AD_HANDSHAKE_FAILURE;
3194         }
3195
3196         /*
3197          * Anytime the server *has* sent an opaque PRF input, we need to
3198          * check that we have a client opaque PRF input of the same size.
3199          */
3200         if (s->s3->client_opaque_prf_input == NULL ||
3201             s->s3->client_opaque_prf_input_len !=
3202             s->s3->server_opaque_prf_input_len) {
3203             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3204             al = SSL_AD_ILLEGAL_PARAMETER;
3205         }
3206     }
3207 # endif
3208
3209     OPENSSL_free(s->tlsext_ocsp_resp);
3210     s->tlsext_ocsp_resp = NULL;
3211     s->tlsext_ocsp_resplen = -1;
3212     /*
3213      * If we've requested certificate status and we wont get one tell the
3214      * callback
3215      */
3216     if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
3217         && !(s->hit) && s->ctx && s->ctx->tlsext_status_cb) {
3218         int r;
3219         /*
3220          * Call callback with resp == NULL and resplen == -1 so callback
3221          * knows there is no response
3222          */
3223         r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3224         if (r == 0) {
3225             al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
3226             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3227         }
3228         if (r < 0) {
3229             al = SSL_AD_INTERNAL_ERROR;
3230             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3231         }
3232     }
3233
3234     switch (ret) {
3235     case SSL_TLSEXT_ERR_ALERT_FATAL:
3236         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3237         return -1;
3238
3239     case SSL_TLSEXT_ERR_ALERT_WARNING:
3240         ssl3_send_alert(s, SSL3_AL_WARNING, al);
3241         return 1;
3242
3243     case SSL_TLSEXT_ERR_NOACK:
3244         s->servername_done = 0;
3245     default:
3246         return 1;
3247     }
3248 }
3249
3250 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d,
3251                                  int n)
3252 {
3253     int al = -1;
3254     if (s->version < SSL3_VERSION)
3255         return 1;
3256     if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) {
3257         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3258         return 0;
3259     }
3260
3261     if (ssl_check_serverhello_tlsext(s) <= 0) {
3262         SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_SERVERHELLO_TLSEXT);
3263         return 0;
3264     }
3265     return 1;
3266 }
3267
3268 /*-
3269  * Since the server cache lookup is done early on in the processing of the
3270  * ClientHello, and other operations depend on the result, we need to handle
3271  * any TLS session ticket extension at the same time.
3272  *
3273  *   session_id: points at the session ID in the ClientHello. This code will
3274  *       read past the end of this in order to parse out the session ticket
3275  *       extension, if any.
3276  *   len: the length of the session ID.
3277  *   limit: a pointer to the first byte after the ClientHello.
3278  *   ret: (output) on return, if a ticket was decrypted, then this is set to
3279  *       point to the resulting session.
3280  *
3281  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
3282  * ciphersuite, in which case we have no use for session tickets and one will
3283  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
3284  *
3285  * Returns:
3286  *   -1: fatal error, either from parsing or decrypting the ticket.
3287  *    0: no ticket was found (or was ignored, based on settings).
3288  *    1: a zero length extension was found, indicating that the client supports
3289  *       session tickets but doesn't currently have one to offer.
3290  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
3291  *       couldn't be decrypted because of a non-fatal error.
3292  *    3: a ticket was successfully decrypted and *ret was set.
3293  *
3294  * Side effects:
3295  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3296  *   a new session ticket to the client because the client indicated support
3297  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3298  *   a session ticket or we couldn't use the one it gave us, or if
3299  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3300  *   Otherwise, s->tlsext_ticket_expected is set to 0.
3301  */
3302 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3303                         const unsigned char *limit, SSL_SESSION **ret)
3304 {
3305     /* Point after session ID in client hello */
3306     const unsigned char *p = session_id + len;
3307     unsigned short i;
3308
3309     *ret = NULL;
3310     s->tlsext_ticket_expected = 0;
3311
3312     /*
3313      * If tickets disabled behave as if no ticket present to permit stateful
3314      * resumption.
3315      */
3316     if (SSL_get_options(s) & SSL_OP_NO_TICKET)
3317         return 0;
3318     if ((s->version <= SSL3_VERSION) || !limit)
3319         return 0;
3320     if (p >= limit)
3321         return -1;
3322     /* Skip past DTLS cookie */
3323     if (SSL_IS_DTLS(s)) {
3324         i = *(p++);
3325
3326         if (limit - p <= i)
3327             return -1;
3328
3329         p += i;
3330     }
3331     /* Skip past cipher list */
3332     n2s(p, i);
3333     if (limit - p <= i)
3334         return -1;
3335     p += i;
3336
3337     /* Skip past compression algorithm list */
3338     i = *(p++);
3339     if (limit - p < i)
3340         return -1;
3341     p += i;
3342
3343     /* Now at start of extensions */
3344     if (limit - p <= 2)
3345         return 0;
3346     n2s(p, i);
3347     while (limit - p >= 4) {
3348         unsigned short type, size;
3349         n2s(p, type);
3350         n2s(p, size);
3351         if (limit - p < size)
3352             return 0;
3353         if (type == TLSEXT_TYPE_session_ticket) {
3354             int r;
3355             if (size == 0) {
3356                 /*
3357                  * The client will accept a ticket but doesn't currently have
3358                  * one.
3359                  */
3360                 s->tlsext_ticket_expected = 1;
3361                 return 1;
3362             }
3363             if (s->tls_session_secret_cb) {
3364                 /*
3365                  * Indicate that the ticket couldn't be decrypted rather than
3366                  * generating the session from ticket now, trigger
3367                  * abbreviated handshake based on external mechanism to
3368                  * calculate the master secret later.
3369                  */
3370                 return 2;
3371             }
3372             r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3373             switch (r) {
3374             case 2:            /* ticket couldn't be decrypted */
3375                 s->tlsext_ticket_expected = 1;
3376                 return 2;
3377             case 3:            /* ticket was decrypted */
3378                 return r;
3379             case 4:            /* ticket decrypted but need to renew */
3380                 s->tlsext_ticket_expected = 1;
3381                 return 3;
3382             default:           /* fatal error */
3383                 return -1;
3384             }
3385         }
3386         p += size;
3387     }
3388     return 0;
3389 }
3390
3391 /*-
3392  * tls_decrypt_ticket attempts to decrypt a session ticket.
3393  *
3394  *   etick: points to the body of the session ticket extension.
3395  *   eticklen: the length of the session tickets extenion.
3396  *   sess_id: points at the session ID.
3397  *   sesslen: the length of the session ID.
3398  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3399  *       point to the resulting session.
3400  *
3401  * Returns:
3402  *   -1: fatal error, either from parsing or decrypting the ticket.
3403  *    2: the ticket couldn't be decrypted.
3404  *    3: a ticket was successfully decrypted and *psess was set.
3405  *    4: same as 3, but the ticket needs to be renewed.
3406  */
3407 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
3408                               int eticklen, const unsigned char *sess_id,
3409                               int sesslen, SSL_SESSION **psess)
3410 {
3411     SSL_SESSION *sess;
3412     unsigned char *sdec;
3413     const unsigned char *p;
3414     int slen, mlen, renew_ticket = 0;
3415     unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3416     HMAC_CTX hctx;
3417     EVP_CIPHER_CTX ctx;
3418     SSL_CTX *tctx = s->initial_ctx;
3419
3420     /* Initialize session ticket encryption and HMAC contexts */
3421     HMAC_CTX_init(&hctx);
3422     EVP_CIPHER_CTX_init(&ctx);
3423     if (tctx->tlsext_ticket_key_cb) {
3424         unsigned char *nctick = (unsigned char *)etick;
3425         int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3426                                             &ctx, &hctx, 0);
3427         if (rv < 0)
3428             return -1;
3429         if (rv == 0)
3430             return 2;
3431         if (rv == 2)
3432             renew_ticket = 1;
3433     } else {
3434         /* Check key name matches */
3435         if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3436             return 2;
3437         if (HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3438                          tlsext_tick_md(), NULL) <= 0
3439                 || EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3440                                       tctx->tlsext_tick_aes_key,
3441                                       etick + 16) <= 0) {
3442             goto err;
3443        }
3444     }
3445     /*
3446      * Attempt to process session ticket, first conduct sanity and integrity
3447      * checks on ticket.
3448      */
3449     mlen = HMAC_size(&hctx);
3450     if (mlen < 0) {
3451         goto err;
3452     }
3453     /* Sanity check ticket length: must exceed keyname + IV + HMAC */
3454     if (eticklen <= 16 + EVP_CIPHER_CTX_iv_length(&ctx) + mlen) {
3455         HMAC_CTX_cleanup(&hctx);
3456         EVP_CIPHER_CTX_cleanup(&ctx);
3457         return 2;
3458     }
3459
3460     eticklen -= mlen;
3461     /* Check HMAC of encrypted ticket */
3462     if (HMAC_Update(&hctx, etick, eticklen) <= 0
3463             || HMAC_Final(&hctx, tick_hmac, NULL) <= 0) {
3464         goto err;
3465     }
3466     HMAC_CTX_cleanup(&hctx);
3467     if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
3468         EVP_CIPHER_CTX_cleanup(&ctx);
3469         return 2;
3470     }
3471     /* Attempt to decrypt session data */
3472     /* Move p after IV to start of encrypted ticket, update length */
3473     p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3474     eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3475     sdec = OPENSSL_malloc(eticklen);
3476     if (sdec == NULL
3477             || EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen) <= 0) {
3478         EVP_CIPHER_CTX_cleanup(&ctx);
3479         OPENSSL_free(sdec);
3480         return -1;
3481     }
3482     if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) {
3483         EVP_CIPHER_CTX_cleanup(&ctx);
3484         OPENSSL_free(sdec);
3485         return 2;
3486     }
3487     slen += mlen;
3488     EVP_CIPHER_CTX_cleanup(&ctx);
3489     p = sdec;
3490
3491     sess = d2i_SSL_SESSION(NULL, &p, slen);
3492     OPENSSL_free(sdec);
3493     if (sess) {
3494         /*
3495          * The session ID, if non-empty, is used by some clients to detect
3496          * that the ticket has been accepted. So we copy it to the session
3497          * structure. If it is empty set length to zero as required by
3498          * standard.
3499          */
3500         if (sesslen)
3501             memcpy(sess->session_id, sess_id, sesslen);
3502         sess->session_id_length = sesslen;
3503         *psess = sess;
3504         if (renew_ticket)
3505             return 4;
3506         else
3507             return 3;
3508     }
3509     ERR_clear_error();
3510     /*
3511      * For session parse failure, indicate that we need to send a new ticket.
3512      */
3513     return 2;
3514 err:
3515     EVP_CIPHER_CTX_cleanup(&ctx);
3516     HMAC_CTX_cleanup(&hctx);
3517     return -1;
3518 }
3519
3520 /* Tables to translate from NIDs to TLS v1.2 ids */
3521
3522 typedef struct {
3523     int nid;
3524     int id;
3525 } tls12_lookup;
3526
3527 static tls12_lookup tls12_md[] = {
3528     {NID_md5, TLSEXT_hash_md5},
3529     {NID_sha1, TLSEXT_hash_sha1},
3530     {NID_sha224, TLSEXT_hash_sha224},
3531     {NID_sha256, TLSEXT_hash_sha256},
3532     {NID_sha384, TLSEXT_hash_sha384},
3533     {NID_sha512, TLSEXT_hash_sha512}
3534 };
3535
3536 static tls12_lookup tls12_sig[] = {
3537     {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3538     {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3539     {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3540 };
3541
3542 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3543 {
3544     size_t i;
3545     for (i = 0; i < tlen; i++) {
3546         if (table[i].nid == nid)
3547             return table[i].id;
3548     }
3549     return -1;
3550 }
3551
3552 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3553 {
3554     size_t i;
3555     for (i = 0; i < tlen; i++) {
3556         if ((table[i].id) == id)
3557             return table[i].nid;
3558     }
3559     return NID_undef;
3560 }
3561
3562 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk,
3563                          const EVP_MD *md)
3564 {
3565     int sig_id, md_id;
3566     if (!md)
3567         return 0;
3568     md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3569                           sizeof(tls12_md) / sizeof(tls12_lookup));
3570     if (md_id == -1)
3571         return 0;
3572     sig_id = tls12_get_sigid(pk);
3573     if (sig_id == -1)
3574         return 0;
3575     p[0] = (unsigned char)md_id;
3576     p[1] = (unsigned char)sig_id;
3577     return 1;
3578 }
3579
3580 int tls12_get_sigid(const EVP_PKEY *pk)
3581 {
3582     return tls12_find_id(pk->type, tls12_sig,
3583                          sizeof(tls12_sig) / sizeof(tls12_lookup));
3584 }
3585
3586 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3587 {
3588     switch (hash_alg) {
3589 # ifndef OPENSSL_NO_MD5
3590     case TLSEXT_hash_md5:
3591 #  ifdef OPENSSL_FIPS
3592         if (FIPS_mode())
3593             return NULL;
3594 #  endif
3595         return EVP_md5();
3596 # endif
3597 # ifndef OPENSSL_NO_SHA
3598     case TLSEXT_hash_sha1:
3599         return EVP_sha1();
3600 # endif
3601 # ifndef OPENSSL_NO_SHA256
3602     case TLSEXT_hash_sha224:
3603         return EVP_sha224();
3604
3605     case TLSEXT_hash_sha256:
3606         return EVP_sha256();
3607 # endif
3608 # ifndef OPENSSL_NO_SHA512
3609     case TLSEXT_hash_sha384:
3610         return EVP_sha384();
3611
3612     case TLSEXT_hash_sha512:
3613         return EVP_sha512();
3614 # endif
3615     default:
3616         return NULL;
3617
3618     }
3619 }
3620
3621 static int tls12_get_pkey_idx(unsigned char sig_alg)
3622 {
3623     switch (sig_alg) {
3624 # ifndef OPENSSL_NO_RSA
3625     case TLSEXT_signature_rsa:
3626         return SSL_PKEY_RSA_SIGN;
3627 # endif
3628 # ifndef OPENSSL_NO_DSA
3629     case TLSEXT_signature_dsa:
3630         return SSL_PKEY_DSA_SIGN;
3631 # endif
3632 # ifndef OPENSSL_NO_ECDSA
3633     case TLSEXT_signature_ecdsa:
3634         return SSL_PKEY_ECC;
3635 # endif
3636     }
3637     return -1;
3638 }
3639
3640 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3641 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3642                                int *psignhash_nid, const unsigned char *data)
3643 {
3644     int sign_nid = NID_undef, hash_nid = NID_undef;
3645     if (!phash_nid && !psign_nid && !psignhash_nid)
3646         return;
3647     if (phash_nid || psignhash_nid) {
3648         hash_nid = tls12_find_nid(data[0], tls12_md,
3649                                   sizeof(tls12_md) / sizeof(tls12_lookup));
3650         if (phash_nid)
3651             *phash_nid = hash_nid;
3652     }
3653     if (psign_nid || psignhash_nid) {
3654         sign_nid = tls12_find_nid(data[1], tls12_sig,
3655                                   sizeof(tls12_sig) / sizeof(tls12_lookup));
3656         if (psign_nid)
3657             *psign_nid = sign_nid;
3658     }
3659     if (psignhash_nid) {
3660         if (sign_nid == NID_undef || hash_nid == NID_undef
3661                 || OBJ_find_sigid_by_algs(psignhash_nid, hash_nid,
3662                                           sign_nid) <= 0)
3663             *psignhash_nid = NID_undef;
3664     }
3665 }
3666
3667 /* Given preference and allowed sigalgs set shared sigalgs */
3668 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3669                                    const unsigned char *pref, size_t preflen,
3670                                    const unsigned char *allow,
3671                                    size_t allowlen)
3672 {
3673     const unsigned char *ptmp, *atmp;
3674     size_t i, j, nmatch = 0;
3675     for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) {
3676         /* Skip disabled hashes or signature algorithms */
3677         if (tls12_get_hash(ptmp[0]) == NULL)
3678             continue;
3679         if (tls12_get_pkey_idx(ptmp[1]) == -1)
3680             continue;
3681         for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) {
3682             if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) {
3683                 nmatch++;
3684                 if (shsig) {
3685                     shsig->rhash = ptmp[0];
3686                     shsig->rsign = ptmp[1];
3687                     tls1_lookup_sigalg(&shsig->hash_nid,
3688                                        &shsig->sign_nid,
3689                                        &shsig->signandhash_nid, ptmp);
3690                     shsig++;
3691                 }
3692                 break;
3693             }
3694         }
3695     }
3696     return nmatch;
3697 }
3698
3699 /* Set shared signature algorithms for SSL structures */
3700 static int tls1_set_shared_sigalgs(SSL *s)
3701 {
3702     const unsigned char *pref, *allow, *conf;
3703     size_t preflen, allowlen, conflen;
3704     size_t nmatch;
3705     TLS_SIGALGS *salgs = NULL;
3706     CERT *c = s->cert;
3707     unsigned int is_suiteb = tls1_suiteb(s);
3708     if (c->shared_sigalgs) {
3709         OPENSSL_free(c->shared_sigalgs);
3710         c->shared_sigalgs = NULL;
3711         c->shared_sigalgslen = 0;
3712     }
3713     /* If client use client signature algorithms if not NULL */
3714     if (!s->server && c->client_sigalgs && !is_suiteb) {
3715         conf = c->client_sigalgs;
3716         conflen = c->client_sigalgslen;
3717     } else if (c->conf_sigalgs && !is_suiteb) {
3718         conf = c->conf_sigalgs;
3719         conflen = c->conf_sigalgslen;
3720     } else
3721         conflen = tls12_get_psigalgs(s, &conf);
3722     if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
3723         pref = conf;
3724         preflen = conflen;
3725         allow = c->peer_sigalgs;
3726         allowlen = c->peer_sigalgslen;
3727     } else {
3728         allow = conf;
3729         allowlen = conflen;
3730         pref = c->peer_sigalgs;
3731         preflen = c->peer_sigalgslen;
3732     }
3733     nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3734     if (nmatch) {
3735         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3736         if (!salgs)
3737             return 0;
3738         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3739     } else {
3740         salgs = NULL;
3741     }
3742     c->shared_sigalgs = salgs;
3743     c->shared_sigalgslen = nmatch;
3744     return 1;
3745 }
3746
3747 /* Set preferred digest for each key type */
3748
3749 int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
3750 {
3751     CERT *c = s->cert;
3752     /* Extension ignored for inappropriate versions */
3753     if (!SSL_USE_SIGALGS(s))
3754         return 1;
3755     /* Should never happen */
3756     if (!c)
3757         return 0;
3758
3759     if (c->peer_sigalgs)
3760         OPENSSL_free(c->peer_sigalgs);
3761     c->peer_sigalgs = OPENSSL_malloc(dsize);
3762     if (!c->peer_sigalgs)
3763         return 0;
3764     c->peer_sigalgslen = dsize;
3765     memcpy(c->peer_sigalgs, data, dsize);
3766     return 1;
3767 }
3768
3769 int tls1_process_sigalgs(SSL *s)
3770 {
3771     int idx;
3772     size_t i;
3773     const EVP_MD *md;
3774     CERT *c = s->cert;
3775     TLS_SIGALGS *sigptr;
3776     if (!tls1_set_shared_sigalgs(s))
3777         return 0;
3778
3779 # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3780     if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
3781         /*
3782          * Use first set signature preference to force message digest,
3783          * ignoring any peer preferences.
3784          */
3785         const unsigned char *sigs = NULL;
3786         if (s->server)
3787             sigs = c->conf_sigalgs;
3788         else
3789             sigs = c->client_sigalgs;
3790         if (sigs) {
3791             idx = tls12_get_pkey_idx(sigs[1]);
3792             md = tls12_get_hash(sigs[0]);
3793             c->pkeys[idx].digest = md;
3794             c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3795             if (idx == SSL_PKEY_RSA_SIGN) {
3796                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
3797                     CERT_PKEY_EXPLICIT_SIGN;
3798                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3799             }
3800         }
3801     }
3802 # endif
3803
3804     for (i = 0, sigptr = c->shared_sigalgs;
3805          i < c->shared_sigalgslen; i++, sigptr++) {
3806         idx = tls12_get_pkey_idx(sigptr->rsign);
3807         if (idx > 0 && c->pkeys[idx].digest == NULL) {
3808             md = tls12_get_hash(sigptr->rhash);
3809             c->pkeys[idx].digest = md;
3810             c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3811             if (idx == SSL_PKEY_RSA_SIGN) {
3812                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
3813                     CERT_PKEY_EXPLICIT_SIGN;
3814                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3815             }
3816         }
3817
3818     }
3819     /*
3820      * In strict mode leave unset digests as NULL to indicate we can't use
3821      * the certificate for signing.
3822      */
3823     if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
3824         /*
3825          * Set any remaining keys to default values. NOTE: if alg is not
3826          * supported it stays as NULL.
3827          */
3828 # ifndef OPENSSL_NO_DSA
3829         if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3830             c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3831 # endif
3832 # ifndef OPENSSL_NO_RSA
3833         if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest) {
3834             c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3835             c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3836         }
3837 # endif
3838 # ifndef OPENSSL_NO_ECDSA
3839         if (!c->pkeys[SSL_PKEY_ECC].digest)
3840             c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3841 # endif
3842     }
3843     return 1;
3844 }
3845
3846 int SSL_get_sigalgs(SSL *s, int idx,
3847                     int *psign, int *phash, int *psignhash,
3848                     unsigned char *rsig, unsigned char *rhash)
3849 {
3850     const unsigned char *psig = s->cert->peer_sigalgs;
3851     if (psig == NULL)
3852         return 0;
3853     if (idx >= 0) {
3854         idx <<= 1;
3855         if (idx >= (int)s->cert->peer_sigalgslen)
3856             return 0;
3857         psig += idx;
3858         if (rhash)
3859             *rhash = psig[0];
3860         if (rsig)
3861             *rsig = psig[1];
3862         tls1_lookup_sigalg(phash, psign, psignhash, psig);
3863     }
3864     return s->cert->peer_sigalgslen / 2;
3865 }
3866
3867 int SSL_get_shared_sigalgs(SSL *s, int idx,
3868                            int *psign, int *phash, int *psignhash,
3869                            unsigned char *rsig, unsigned char *rhash)
3870 {
3871     TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3872     if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3873         return 0;
3874     shsigalgs += idx;
3875     if (phash)
3876         *phash = shsigalgs->hash_nid;
3877     if (psign)
3878         *psign = shsigalgs->sign_nid;
3879     if (psignhash)
3880         *psignhash = shsigalgs->signandhash_nid;
3881     if (rsig)
3882         *rsig = shsigalgs->rsign;
3883     if (rhash)
3884         *rhash = shsigalgs->rhash;
3885     return s->cert->shared_sigalgslen;
3886 }
3887
3888 # ifndef OPENSSL_NO_HEARTBEATS
3889 int tls1_process_heartbeat(SSL *s)
3890 {
3891     unsigned char *p = &s->s3->rrec.data[0], *pl;
3892     unsigned short hbtype;
3893     unsigned int payload;
3894     unsigned int padding = 16;  /* Use minimum padding */
3895
3896     if (s->msg_callback)
3897         s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
3898                         &s->s3->rrec.data[0], s->s3->rrec.length,
3899                         s, s->msg_callback_arg);
3900
3901     /* Read type and payload length first */
3902     if (1 + 2 + 16 > s->s3->rrec.length)
3903         return 0;               /* silently discard */
3904     hbtype = *p++;
3905     n2s(p, payload);
3906     if (1 + 2 + payload + 16 > s->s3->rrec.length)
3907         return 0;               /* silently discard per RFC 6520 sec. 4 */
3908     pl = p;
3909
3910     if (hbtype == TLS1_HB_REQUEST) {
3911         unsigned char *buffer, *bp;
3912         int r;
3913
3914         /*
3915          * Allocate memory for the response, size is 1 bytes message type,
3916          * plus 2 bytes payload length, plus payload, plus padding
3917          */
3918         buffer = OPENSSL_malloc(1 + 2 + payload + padding);
3919         if (buffer == NULL)
3920             return -1;
3921         bp = buffer;
3922
3923         /* Enter response type, length and copy payload */
3924         *bp++ = TLS1_HB_RESPONSE;
3925         s2n(payload, bp);
3926         memcpy(bp, pl, payload);
3927         bp += payload;
3928         /* Random padding */
3929         if (RAND_bytes(bp, padding) <= 0) {
3930             OPENSSL_free(buffer);
3931             return -1;
3932         }
3933
3934         r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer,
3935                              3 + payload + padding);
3936
3937         if (r >= 0 && s->msg_callback)
3938             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3939                             buffer, 3 + payload + padding,
3940                             s, s->msg_callback_arg);
3941
3942         OPENSSL_free(buffer);
3943
3944         if (r < 0)
3945             return r;
3946     } else if (hbtype == TLS1_HB_RESPONSE) {
3947         unsigned int seq;
3948
3949         /*
3950          * We only send sequence numbers (2 bytes unsigned int), and 16
3951          * random bytes, so we just try to read the sequence number
3952          */
3953         n2s(pl, seq);
3954
3955         if (payload == 18 && seq == s->tlsext_hb_seq) {
3956             s->tlsext_hb_seq++;
3957             s->tlsext_hb_pending = 0;
3958         }
3959     }
3960
3961     return 0;
3962 }
3963
3964 int tls1_heartbeat(SSL *s)
3965 {
3966     unsigned char *buf, *p;
3967     int ret = -1;
3968     unsigned int payload = 18;  /* Sequence number + random bytes */
3969     unsigned int padding = 16;  /* Use minimum padding */
3970
3971     /* Only send if peer supports and accepts HB requests... */
3972     if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
3973         s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
3974         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
3975         return -1;
3976     }
3977
3978     /* ...and there is none in flight yet... */
3979     if (s->tlsext_hb_pending) {
3980         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
3981         return -1;
3982     }
3983
3984     /* ...and no handshake in progress. */
3985     if (SSL_in_init(s) || s->in_handshake) {
3986         SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
3987         return -1;
3988     }
3989
3990     /*
3991      * Check if padding is too long, payload and padding must not exceed 2^14
3992      * - 3 = 16381 bytes in total.
3993      */
3994     OPENSSL_assert(payload + padding <= 16381);
3995
3996     /*-
3997      * Create HeartBeat message, we just use a sequence number
3998      * as payload to distuingish different messages and add
3999      * some random stuff.
4000      *  - Message Type, 1 byte
4001      *  - Payload Length, 2 bytes (unsigned int)
4002      *  - Payload, the sequence number (2 bytes uint)
4003      *  - Payload, random bytes (16 bytes uint)
4004      *  - Padding
4005      */
4006     buf = OPENSSL_malloc(1 + 2 + payload + padding);
4007     if (buf == NULL)
4008         return -1;
4009     p = buf;
4010     /* Message Type */
4011     *p++ = TLS1_HB_REQUEST;
4012     /* Payload length (18 bytes here) */
4013     s2n(payload, p);
4014     /* Sequence number */
4015     s2n(s->tlsext_hb_seq, p);
4016     /* 16 random bytes */
4017     if (RAND_bytes(p, 16) <= 0) {
4018         SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
4019         goto err;
4020     }
4021     p += 16;
4022     /* Random padding */
4023     if (RAND_bytes(p, padding) <= 0) {
4024         SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
4025         goto err;
4026     }
4027
4028     ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
4029     if (ret >= 0) {
4030         if (s->msg_callback)
4031             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
4032                             buf, 3 + payload + padding,
4033                             s, s->msg_callback_arg);
4034
4035         s->tlsext_hb_pending = 1;
4036     }
4037
4038 err:
4039     OPENSSL_free(buf);
4040
4041     return ret;
4042 }
4043 # endif
4044
4045 # define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
4046
4047 typedef struct {
4048     size_t sigalgcnt;
4049     int sigalgs[MAX_SIGALGLEN];
4050 } sig_cb_st;
4051
4052 static int sig_cb(const char *elem, int len, void *arg)
4053 {
4054     sig_cb_st *sarg = arg;
4055     size_t i;
4056     char etmp[20], *p;
4057     int sig_alg, hash_alg;
4058     if (elem == NULL)
4059         return 0;
4060     if (sarg->sigalgcnt == MAX_SIGALGLEN)
4061         return 0;
4062     if (len > (int)(sizeof(etmp) - 1))
4063         return 0;
4064     memcpy(etmp, elem, len);
4065     etmp[len] = 0;
4066     p = strchr(etmp, '+');
4067     if (!p)
4068         return 0;
4069     *p = 0;
4070     p++;
4071     if (!*p)
4072         return 0;
4073
4074     if (!strcmp(etmp, "RSA"))
4075         sig_alg = EVP_PKEY_RSA;
4076     else if (!strcmp(etmp, "DSA"))
4077         sig_alg = EVP_PKEY_DSA;
4078     else if (!strcmp(etmp, "ECDSA"))
4079         sig_alg = EVP_PKEY_EC;
4080     else
4081         return 0;
4082
4083     hash_alg = OBJ_sn2nid(p);
4084     if (hash_alg == NID_undef)
4085         hash_alg = OBJ_ln2nid(p);
4086     if (hash_alg == NID_undef)
4087         return 0;
4088
4089     for (i = 0; i < sarg->sigalgcnt; i += 2) {
4090         if (sarg->sigalgs[i] == sig_alg && sarg->sigalgs[i + 1] == hash_alg)
4091             return 0;
4092     }
4093     sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
4094     sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
4095     return 1;
4096 }
4097
4098 /*
4099  * Set suppored signature algorithms based on a colon separated list of the
4100  * form sig+hash e.g. RSA+SHA512:DSA+SHA512
4101  */
4102 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
4103 {
4104     sig_cb_st sig;
4105     sig.sigalgcnt = 0;
4106     if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
4107         return 0;
4108     if (c == NULL)
4109         return 1;
4110     return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
4111 }
4112
4113 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen,
4114                      int client)
4115 {
4116     unsigned char *sigalgs, *sptr;
4117     int rhash, rsign;
4118     size_t i;
4119     if (salglen & 1)
4120         return 0;
4121     sigalgs = OPENSSL_malloc(salglen);
4122     if (sigalgs == NULL)
4123         return 0;
4124     for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
4125         rhash = tls12_find_id(*psig_nids++, tls12_md,
4126                               sizeof(tls12_md) / sizeof(tls12_lookup));
4127         rsign = tls12_find_id(*psig_nids++, tls12_sig,
4128                               sizeof(tls12_sig) / sizeof(tls12_lookup));
4129
4130         if (rhash == -1 || rsign == -1)
4131             goto err;
4132         *sptr++ = rhash;
4133         *sptr++ = rsign;
4134     }
4135
4136     if (client) {
4137         if (c->client_sigalgs)
4138             OPENSSL_free(c->client_sigalgs);
4139         c->client_sigalgs = sigalgs;
4140         c->client_sigalgslen = salglen;
4141     } else {
4142         if (c->conf_sigalgs)
4143             OPENSSL_free(c->conf_sigalgs);
4144         c->conf_sigalgs = sigalgs;
4145         c->conf_sigalgslen = salglen;
4146     }
4147
4148     return 1;
4149
4150  err:
4151     OPENSSL_free(sigalgs);
4152     return 0;
4153 }
4154
4155 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
4156 {
4157     int sig_nid;
4158     size_t i;
4159     if (default_nid == -1)
4160         return 1;
4161     sig_nid = X509_get_signature_nid(x);
4162     if (default_nid)
4163         return sig_nid == default_nid ? 1 : 0;
4164     for (i = 0; i < c->shared_sigalgslen; i++)
4165         if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
4166             return 1;
4167     return 0;
4168 }
4169
4170 /* Check to see if a certificate issuer name matches list of CA names */
4171 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
4172 {
4173     X509_NAME *nm;
4174     int i;
4175     nm = X509_get_issuer_name(x);
4176     for (i = 0; i < sk_X509_NAME_num(names); i++) {
4177         if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
4178             return 1;
4179     }
4180     return 0;
4181 }
4182
4183 /*
4184  * Check certificate chain is consistent with TLS extensions and is usable by
4185  * server. This servers two purposes: it allows users to check chains before
4186  * passing them to the server and it allows the server to check chains before
4187  * attempting to use them.
4188  */
4189
4190 /* Flags which need to be set for a certificate when stict mode not set */
4191
4192 # define CERT_PKEY_VALID_FLAGS \
4193         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
4194 /* Strict mode flags */
4195 # define CERT_PKEY_STRICT_FLAGS \
4196          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
4197          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
4198
4199 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
4200                      int idx)
4201 {
4202     int i;
4203     int rv = 0;
4204     int check_flags = 0, strict_mode;
4205     CERT_PKEY *cpk = NULL;
4206     CERT *c = s->cert;
4207     unsigned int suiteb_flags = tls1_suiteb(s);
4208     /* idx == -1 means checking server chains */
4209     if (idx != -1) {
4210         /* idx == -2 means checking client certificate chains */
4211         if (idx == -2) {
4212             cpk = c->key;
4213             idx = cpk - c->pkeys;
4214         } else
4215             cpk = c->pkeys + idx;
4216         x = cpk->x509;
4217         pk = cpk->privatekey;
4218         chain = cpk->chain;
4219         strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
4220         /* If no cert or key, forget it */
4221         if (!x || !pk)
4222             goto end;
4223 # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
4224         /* Allow any certificate to pass test */
4225         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
4226             rv = CERT_PKEY_STRICT_FLAGS | CERT_PKEY_EXPLICIT_SIGN |
4227                 CERT_PKEY_VALID | CERT_PKEY_SIGN;
4228             cpk->valid_flags = rv;
4229             return rv;
4230         }
4231 # endif
4232     } else {
4233         if (!x || !pk)
4234             return 0;
4235         idx = ssl_cert_type(x, pk);
4236         if (idx == -1)
4237             return 0;
4238         cpk = c->pkeys + idx;
4239         if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
4240             check_flags = CERT_PKEY_STRICT_FLAGS;
4241         else
4242             check_flags = CERT_PKEY_VALID_FLAGS;
4243         strict_mode = 1;
4244     }
4245
4246     if (suiteb_flags) {
4247         int ok;
4248         if (check_flags)
4249             check_flags |= CERT_PKEY_SUITEB;
4250         ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
4251         if (ok == X509_V_OK)
4252             rv |= CERT_PKEY_SUITEB;
4253         else if (!check_flags)
4254             goto end;
4255     }
4256
4257     /*
4258      * Check all signature algorithms are consistent with signature
4259      * algorithms extension if TLS 1.2 or later and strict mode.
4260      */
4261     if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
4262         int default_nid;
4263         unsigned char rsign = 0;
4264         if (c->peer_sigalgs)
4265             default_nid = 0;
4266         /* If no sigalgs extension use defaults from RFC5246 */
4267         else {
4268             switch (idx) {
4269             case SSL_PKEY_RSA_ENC:
4270             case SSL_PKEY_RSA_SIGN:
4271             case SSL_PKEY_DH_RSA:
4272                 rsign = TLSEXT_signature_rsa;
4273                 default_nid = NID_sha1WithRSAEncryption;
4274                 break;
4275
4276             case SSL_PKEY_DSA_SIGN:
4277             case SSL_PKEY_DH_DSA:
4278                 rsign = TLSEXT_signature_dsa;
4279                 default_nid = NID_dsaWithSHA1;
4280                 break;
4281
4282             case SSL_PKEY_ECC:
4283                 rsign = TLSEXT_signature_ecdsa;
4284                 default_nid = NID_ecdsa_with_SHA1;
4285                 break;
4286
4287             default:
4288                 default_nid = -1;
4289                 break;
4290             }
4291         }
4292         /*
4293          * If peer sent no signature algorithms extension and we have set
4294          * preferred signature algorithms check we support sha1.
4295          */
4296         if (default_nid > 0 && c->conf_sigalgs) {
4297             size_t j;
4298             const unsigned char *p = c->conf_sigalgs;
4299             for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2) {
4300                 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
4301                     break;
4302             }
4303             if (j == c->conf_sigalgslen) {
4304                 if (check_flags)
4305                     goto skip_sigs;
4306                 else
4307                     goto end;
4308             }
4309         }
4310         /* Check signature algorithm of each cert in chain */
4311         if (!tls1_check_sig_alg(c, x, default_nid)) {
4312             if (!check_flags)
4313                 goto end;
4314         } else
4315             rv |= CERT_PKEY_EE_SIGNATURE;
4316         rv |= CERT_PKEY_CA_SIGNATURE;
4317         for (i = 0; i < sk_X509_num(chain); i++) {
4318             if (!tls1_check_sig_alg(c, sk_X509_value(chain, i), default_nid)) {
4319                 if (check_flags) {
4320                     rv &= ~CERT_PKEY_CA_SIGNATURE;
4321                     break;
4322                 } else
4323                     goto end;
4324             }
4325         }
4326     }
4327     /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
4328     else if (check_flags)
4329         rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
4330  skip_sigs:
4331     /* Check cert parameters are consistent */
4332     if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
4333         rv |= CERT_PKEY_EE_PARAM;
4334     else if (!check_flags)
4335         goto end;
4336     if (!s->server)
4337         rv |= CERT_PKEY_CA_PARAM;
4338     /* In strict mode check rest of chain too */
4339     else if (strict_mode) {
4340         rv |= CERT_PKEY_CA_PARAM;
4341         for (i = 0; i < sk_X509_num(chain); i++) {
4342             X509 *ca = sk_X509_value(chain, i);
4343             if (!tls1_check_cert_param(s, ca, 0)) {
4344                 if (check_flags) {
4345                     rv &= ~CERT_PKEY_CA_PARAM;
4346                     break;
4347                 } else
4348                     goto end;
4349             }
4350         }
4351     }
4352     if (!s->server && strict_mode) {
4353         STACK_OF(X509_NAME) *ca_dn;
4354         int check_type = 0;
4355         switch (pk->type) {
4356         case EVP_PKEY_RSA:
4357             check_type = TLS_CT_RSA_SIGN;
4358             break;
4359         case EVP_PKEY_DSA:
4360             check_type = TLS_CT_DSS_SIGN;
4361             break;
4362         case EVP_PKEY_EC:
4363             check_type = TLS_CT_ECDSA_SIGN;
4364             break;
4365         case EVP_PKEY_DH:
4366         case EVP_PKEY_DHX:
4367             {
4368                 int cert_type = X509_certificate_type(x, pk);
4369                 if (cert_type & EVP_PKS_RSA)
4370                     check_type = TLS_CT_RSA_FIXED_DH;
4371                 if (cert_type & EVP_PKS_DSA)
4372                     check_type = TLS_CT_DSS_FIXED_DH;
4373             }
4374         }
4375         if (check_type) {
4376             const unsigned char *ctypes;
4377             int ctypelen;
4378             if (c->ctypes) {
4379                 ctypes = c->ctypes;
4380                 ctypelen = (int)c->ctype_num;
4381             } else {
4382                 ctypes = (unsigned char *)s->s3->tmp.ctype;
4383                 ctypelen = s->s3->tmp.ctype_num;
4384             }
4385             for (i = 0; i < ctypelen; i++) {
4386                 if (ctypes[i] == check_type) {
4387                     rv |= CERT_PKEY_CERT_TYPE;
4388                     break;
4389                 }
4390             }
4391             if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4392                 goto end;
4393         } else
4394             rv |= CERT_PKEY_CERT_TYPE;
4395
4396         ca_dn = s->s3->tmp.ca_names;
4397
4398         if (!sk_X509_NAME_num(ca_dn))
4399             rv |= CERT_PKEY_ISSUER_NAME;
4400
4401         if (!(rv & CERT_PKEY_ISSUER_NAME)) {
4402             if (ssl_check_ca_name(ca_dn, x))
4403                 rv |= CERT_PKEY_ISSUER_NAME;
4404         }
4405         if (!(rv & CERT_PKEY_ISSUER_NAME)) {
4406             for (i = 0; i < sk_X509_num(chain); i++) {
4407                 X509 *xtmp = sk_X509_value(chain, i);
4408                 if (ssl_check_ca_name(ca_dn, xtmp)) {
4409                     rv |= CERT_PKEY_ISSUER_NAME;
4410                     break;
4411                 }
4412             }
4413         }
4414         if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4415             goto end;
4416     } else
4417         rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
4418
4419     if (!check_flags || (rv & check_flags) == check_flags)
4420         rv |= CERT_PKEY_VALID;
4421
4422  end:
4423
4424     if (TLS1_get_version(s) >= TLS1_2_VERSION) {
4425         if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4426             rv |= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
4427         else if (cpk->digest)
4428             rv |= CERT_PKEY_SIGN;
4429     } else
4430         rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
4431
4432     /*
4433      * When checking a CERT_PKEY structure all flags are irrelevant if the
4434      * chain is invalid.
4435      */
4436     if (!check_flags) {
4437         if (rv & CERT_PKEY_VALID)
4438             cpk->valid_flags = rv;
4439         else {
4440             /* Preserve explicit sign flag, clear rest */
4441             cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4442             return 0;
4443         }
4444     }
4445     return rv;
4446 }
4447
4448 /* Set validity of certificates in an SSL structure */
4449 void tls1_set_cert_validity(SSL *s)
4450 {
4451     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4452     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4453     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4454     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4455     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4456     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4457 }
4458
4459 /* User level utiity function to check a chain is suitable */
4460 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4461 {
4462     return tls1_check_chain(s, x, pk, chain, -1);
4463 }
4464
4465 #endif