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