ecac97b3aa1c52afde1c952c3f70a9893d33f545
[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(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         return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
529         }
530 /* For an EC key set TLS id and required compression based on parameters */
531 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
532                                 EC_KEY *ec)
533         {
534         int is_prime, id;
535         const EC_GROUP *grp;
536         const EC_POINT *pt;
537         const EC_METHOD *meth;
538         if (!ec)
539                 return 0;
540         /* Determine if it is a prime field */
541         grp = EC_KEY_get0_group(ec);
542         pt = EC_KEY_get0_public_key(ec);
543         if (!grp || !pt)
544                 return 0;
545         meth = EC_GROUP_method_of(grp);
546         if (!meth)
547                 return 0;
548         if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
549                 is_prime = 1;
550         else
551                 is_prime = 0;
552         /* Determine curve ID */
553         id = EC_GROUP_get_curve_name(grp);
554         id = tls1_ec_nid2curve_id(id);
555         /* If we have an ID set it, otherwise set arbitrary explicit curve */
556         if (id)
557                 {
558                 curve_id[0] = 0;
559                 curve_id[1] = (unsigned char)id;
560                 }
561         else
562                 {
563                 curve_id[0] = 0xff;
564                 if (is_prime)
565                         curve_id[1] = 0x01;
566                 else
567                         curve_id[1] = 0x02;
568                 }
569         if (comp_id)
570                 {
571                 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
572                         {
573                         if (is_prime)
574                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
575                         else
576                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
577                         }
578                 else
579                         *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
580                 }
581         return 1;
582         }
583 /* Check an EC key is compatible with extensions */
584 static int tls1_check_ec_key(SSL *s,
585                         unsigned char *curve_id, unsigned char *comp_id)
586         {
587         const unsigned char *p;
588         size_t plen, i;
589         int j;
590         /* If point formats extension present check it, otherwise everything
591          * is supported (see RFC4492).
592          */
593         if (comp_id && s->session->tlsext_ecpointformatlist)
594                 {
595                 p = s->session->tlsext_ecpointformatlist;
596                 plen = s->session->tlsext_ecpointformatlist_length;
597                 for (i = 0; i < plen; i++, p++)
598                         {
599                         if (*comp_id == *p)
600                                 break;
601                         }
602                 if (i == plen)
603                         return 0;
604                 }
605         if (!curve_id)
606                 return 1;
607         /* Check curve is consistent with client and server preferences */
608         for (j = 0; j <= 1; j++)
609                 {
610                 tls1_get_curvelist(s, j, &p, &plen);
611                 for (i = 0; i < plen; i+=2, p+=2)
612                         {
613                         if (p[0] == curve_id[0] && p[1] == curve_id[1])
614                                 break;
615                         }
616                 if (i == plen)
617                         return 0;
618                 /* For clients can only check sent curve list */
619                 if (!s->server)
620                         return 1;
621                 }
622         return 1;
623         }
624
625 /* Check cert parameters compatible with extensions: currently just checks
626  * EC certificates have compatible curves and compression.
627  */
628 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
629         {
630         unsigned char comp_id, curve_id[2];
631         EVP_PKEY *pkey;
632         int rv;
633         pkey = X509_get_pubkey(x);
634         if (!pkey)
635                 return 0;
636         /* If not EC nothing to do */
637         if (pkey->type != EVP_PKEY_EC)
638                 {
639                 EVP_PKEY_free(pkey);
640                 return 1;
641                 }
642         rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
643         EVP_PKEY_free(pkey);
644         if (!rv)
645                 return 0;
646         /* Can't check curve_id for client certs as we don't have a
647          * supported curves extension.
648          */
649         rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
650         if (!rv)
651                 return 0;
652         /* Special case for suite B. We *MUST* sign using SHA256+P-256 or
653          * SHA384+P-384, adjust digest if necessary.
654          */
655         if (set_ee_md && tls1_suiteb(s))
656                 {
657                 int check_md;
658                 size_t i;
659                 CERT *c = s->cert;
660                 if (curve_id[0])
661                         return 0;
662                 /* Check to see we have necessary signing algorithm */
663                 if (curve_id[1] == TLSEXT_curve_P_256)
664                         check_md = NID_ecdsa_with_SHA256;
665                 else if (curve_id[1] == TLSEXT_curve_P_384)
666                         check_md = NID_ecdsa_with_SHA384;
667                 else
668                         return 0; /* Should never happen */
669                 for (i = 0; i < c->shared_sigalgslen; i++)
670                         if (check_md == c->shared_sigalgs[i].signandhash_nid)
671                                 break;
672                 if (i == c->shared_sigalgslen)
673                         return 0;
674                 if (set_ee_md == 2)
675                         {
676                         if (check_md == NID_ecdsa_with_SHA256)
677                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
678                         else
679                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
680                         }
681                 }
682         return rv;
683         }
684 /* Check EC temporary key is compatible with client extensions */
685 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
686         {
687         unsigned char curve_id[2];
688         EC_KEY *ec = s->cert->ecdh_tmp;
689         /* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384,
690          * no other curves permitted.
691          */
692         if (tls1_suiteb(s))
693                 {
694                 /* Curve to check determined by ciphersuite */
695                 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
696                         curve_id[1] = TLSEXT_curve_P_256;
697                 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
698                         curve_id[1] = TLSEXT_curve_P_384;
699                 else
700                         return 0;
701                 curve_id[0] = 0;
702                 /* Check this curve is acceptable */
703                 if (!tls1_check_ec_key(s, curve_id, NULL))
704                         return 0;
705                 /* If auto or setting curve from callback assume OK */
706                 if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
707                         return 1;
708                 /* Otherwise check curve is acceptable */
709                 else 
710                         {
711                         unsigned char curve_tmp[2];
712                         if (!ec)
713                                 return 0;
714                         if (!tls1_set_ec_id(curve_tmp, NULL, ec))
715                                 return 0;
716                         if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
717                                 return 1;
718                         return 0;
719                         }
720                         
721                 }
722         if (s->cert->ecdh_tmp_auto)
723                 {
724                 /* Need a shared curve */
725                 if (tls1_shared_curve(s, 0))
726                         return 1;
727                 else return 0;
728                 }
729         if (!ec)
730                 {
731                 if (s->cert->ecdh_tmp_cb)
732                         return 1;
733                 else
734                         return 0;
735                 }
736         if (!tls1_set_ec_id(curve_id, NULL, ec))
737                 return 0;
738 /* Set this to allow use of invalid curves for testing */
739 #if 0
740         return 1;
741 #else
742         return tls1_check_ec_key(s, curve_id, NULL);
743 #endif
744         }
745
746 #endif /* OPENSSL_NO_EC */
747
748 #ifndef OPENSSL_NO_TLSEXT
749
750 /* List of supported signature algorithms and hashes. Should make this
751  * customisable at some point, for now include everything we support.
752  */
753
754 #ifdef OPENSSL_NO_RSA
755 #define tlsext_sigalg_rsa(md) /* */
756 #else
757 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
758 #endif
759
760 #ifdef OPENSSL_NO_DSA
761 #define tlsext_sigalg_dsa(md) /* */
762 #else
763 #define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
764 #endif
765
766 #ifdef OPENSSL_NO_ECDSA
767 #define tlsext_sigalg_ecdsa(md) /* */
768 #else
769 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
770 #endif
771
772 #define tlsext_sigalg(md) \
773                 tlsext_sigalg_rsa(md) \
774                 tlsext_sigalg_dsa(md) \
775                 tlsext_sigalg_ecdsa(md)
776
777 static unsigned char tls12_sigalgs[] = {
778 #ifndef OPENSSL_NO_SHA512
779         tlsext_sigalg(TLSEXT_hash_sha512)
780         tlsext_sigalg(TLSEXT_hash_sha384)
781 #endif
782 #ifndef OPENSSL_NO_SHA256
783         tlsext_sigalg(TLSEXT_hash_sha256)
784         tlsext_sigalg(TLSEXT_hash_sha224)
785 #endif
786 #ifndef OPENSSL_NO_SHA
787         tlsext_sigalg(TLSEXT_hash_sha1)
788 #endif
789 #ifndef OPENSSL_NO_MD5
790         tlsext_sigalg_rsa(TLSEXT_hash_md5)
791 #endif
792 };
793
794 static unsigned char suiteb_sigalgs[] = {
795         tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
796         tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
797 };
798
799 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
800         {
801         /* If Suite B mode use Suite B sigalgs only, ignore any other
802          * preferences.
803          */
804         switch (tls1_suiteb(s))
805                 {
806         case SSL_CERT_FLAG_SUITEB_128_LOS:
807                 *psigs = suiteb_sigalgs;
808                 return sizeof(suiteb_sigalgs);
809
810         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
811                 *psigs = suiteb_sigalgs;
812                 return 2;
813
814         case SSL_CERT_FLAG_SUITEB_192_LOS:
815                 *psigs = suiteb_sigalgs + 2;
816                 return 2;
817                 }
818
819         /* If server use client authentication sigalgs if not NULL */
820         if (s->server && s->cert->client_sigalgs)
821                 {
822                 *psigs = s->cert->client_sigalgs;
823                 return s->cert->client_sigalgslen;
824                 }
825         else if (s->cert->conf_sigalgs)
826                 {
827                 *psigs = s->cert->conf_sigalgs;
828                 return s->cert->conf_sigalgslen;
829                 }
830         else
831                 {
832                 *psigs = tls12_sigalgs;
833 #ifdef OPENSSL_FIPS
834                 /* If FIPS mode don't include MD5 which is last */
835                 if (FIPS_mode())
836                         return sizeof(tls12_sigalgs) - 2;
837                 else
838 #endif
839                         return sizeof(tls12_sigalgs);
840                 }
841         }
842 /* Check signature algorithm is consistent with sent supported signature
843  * algorithms and if so return relevant digest.
844  */
845 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
846                                 const unsigned char *sig, EVP_PKEY *pkey)
847         {
848         const unsigned char *sent_sigs;
849         size_t sent_sigslen, i;
850         int sigalg = tls12_get_sigid(pkey);
851         /* Should never happen */
852         if (sigalg == -1)
853                 return -1;
854         /* Check key type is consistent with signature */
855         if (sigalg != (int)sig[1])
856                 {
857                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
858                 return 0;
859                 }
860         if (pkey->type == EVP_PKEY_EC)
861                 {
862                 unsigned char curve_id[2], comp_id;
863                 /* Check compression and curve matches extensions */
864                 if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
865                         return 0;
866                 if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id))
867                         return 0;
868                 /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
869                 if (tls1_suiteb(s))
870                         {
871                         if (curve_id[0])
872                                 return 0;
873                         if (curve_id[1] == TLSEXT_curve_P_256)
874                                 {
875                                 if (sig[0] != TLSEXT_hash_sha256)
876                                         {
877                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
878                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
879                                         return 0;
880                                         }
881                                 }
882                         else if (curve_id[1] == TLSEXT_curve_P_384)
883                                 {
884                                 if (sig[0] != TLSEXT_hash_sha384)
885                                         {
886                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
887                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
888                                         return 0;
889                                         }
890                                 }
891                         else
892                                 return 0;
893                         }
894                 }
895         else if (tls1_suiteb(s))
896                 return 0;
897
898         /* Check signature matches a type we sent */
899         sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
900         for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
901                 {
902                 if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
903                         break;
904                 }
905         /* Allow fallback to SHA1 if not strict mode */
906         if (i == sent_sigslen && (sig[0] != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
907                 {
908                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
909                 return 0;
910                 }
911         *pmd = tls12_get_hash(sig[0]);
912         if (*pmd == NULL)
913                 {
914                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_UNKNOWN_DIGEST);
915                 return 0;
916                 }
917         return 1;
918         }
919 /* Get a mask of disabled algorithms: an algorithm is disabled
920  * if it isn't supported or doesn't appear in supported signature
921  * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
922  * session and not global settings.
923  * 
924  */
925 void ssl_set_client_disabled(SSL *s)
926         {
927         CERT *c = s->cert;
928         const unsigned char *sigalgs;
929         size_t i, sigalgslen;
930         int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
931         c->mask_a = 0;
932         c->mask_k = 0;
933         /* If less than TLS 1.2 don't allow TLS 1.2 only ciphers */
934         if (TLS1_get_version(s) < TLS1_2_VERSION)
935                 c->mask_ssl = SSL_TLSV1_2;
936         else
937                 c->mask_ssl = 0;
938         /* Now go through all signature algorithms seeing if we support
939          * any for RSA, DSA, ECDSA. Do this for all versions not just
940          * TLS 1.2.
941          */
942         sigalgslen = tls12_get_psigalgs(s, &sigalgs);
943         for (i = 0; i < sigalgslen; i += 2, sigalgs += 2)
944                 {
945                 switch(sigalgs[1])
946                         {
947 #ifndef OPENSSL_NO_RSA
948                 case TLSEXT_signature_rsa:
949                         have_rsa = 1;
950                         break;
951 #endif
952 #ifndef OPENSSL_NO_DSA
953                 case TLSEXT_signature_dsa:
954                         have_dsa = 1;
955                         break;
956 #endif
957 #ifndef OPENSSL_NO_ECDSA
958                 case TLSEXT_signature_ecdsa:
959                         have_ecdsa = 1;
960                         break;
961 #endif
962                         }
963                 }
964         /* Disable auth and static DH if we don't include any appropriate
965          * signature algorithms.
966          */
967         if (!have_rsa)
968                 {
969                 c->mask_a |= SSL_aRSA;
970                 c->mask_k |= SSL_kDHr|SSL_kECDHr;
971                 }
972         if (!have_dsa)
973                 {
974                 c->mask_a |= SSL_aDSS;
975                 c->mask_k |= SSL_kDHd;
976                 }
977         if (!have_ecdsa)
978                 {
979                 c->mask_a |= SSL_aECDSA;
980                 c->mask_k |= SSL_kECDHe;
981                 }
982 #ifndef OPENSSL_NO_KRB5
983         if (!kssl_tgt_is_available(s->kssl_ctx))
984                 {
985                 c->mask_a |= SSL_aKRB5;
986                 c->mask_k |= SSL_kKRB5;
987                 }
988 #endif
989 #ifndef OPENSSL_NO_PSK
990         /* with PSK there must be client callback set */
991         if (!s->psk_client_callback)
992                 {
993                 c->mask_a |= SSL_aPSK;
994                 c->mask_k |= SSL_kPSK;
995                 }
996 #endif /* OPENSSL_NO_PSK */
997         c->valid = 1;
998         }
999
1000 /* byte_compare is a compare function for qsort(3) that compares bytes. */
1001 static int byte_compare(const void *in_a, const void *in_b)
1002         {
1003         unsigned char a = *((const unsigned char*) in_a);
1004         unsigned char b = *((const unsigned char*) in_b);
1005
1006         if (a > b)
1007                 return 1;
1008         else if (a < b)
1009                 return -1;
1010         return 0;
1011 }
1012
1013 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1014         {
1015         int extdatalen=0;
1016         unsigned char *ret = p;
1017 #ifndef OPENSSL_NO_EC
1018         /* See if we support any ECC ciphersuites */
1019         int using_ecc = 0;
1020         if (s->version != DTLS1_VERSION && s->version >= TLS1_VERSION)
1021                 {
1022                 int i;
1023                 unsigned long alg_k, alg_a;
1024                 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1025
1026                 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1027                         {
1028                         SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1029
1030                         alg_k = c->algorithm_mkey;
1031                         alg_a = c->algorithm_auth;
1032                         if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)
1033                                 || (alg_a & SSL_aECDSA)))
1034                                 {
1035                                 using_ecc = 1;
1036                                 break;
1037                                 }
1038                         }
1039                 }
1040 #endif
1041
1042         /* don't add extensions for SSLv3 unless doing secure renegotiation */
1043         if (s->client_version == SSL3_VERSION
1044                                         && !s->s3->send_connection_binding)
1045                 return p;
1046
1047         ret+=2;
1048
1049         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1050
1051         if (s->tlsext_hostname != NULL)
1052                 { 
1053                 /* Add TLS extension servername to the Client Hello message */
1054                 unsigned long size_str;
1055                 long lenmax; 
1056
1057                 /* check for enough space.
1058                    4 for the servername type and entension length
1059                    2 for servernamelist length
1060                    1 for the hostname type
1061                    2 for hostname length
1062                    + hostname length 
1063                 */
1064                    
1065                 if ((lenmax = limit - ret - 9) < 0 
1066                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
1067                         return NULL;
1068                         
1069                 /* extension type and length */
1070                 s2n(TLSEXT_TYPE_server_name,ret); 
1071                 s2n(size_str+5,ret);
1072                 
1073                 /* length of servername list */
1074                 s2n(size_str+3,ret);
1075         
1076                 /* hostname type, length and hostname */
1077                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
1078                 s2n(size_str,ret);
1079                 memcpy(ret, s->tlsext_hostname, size_str);
1080                 ret+=size_str;
1081                 }
1082
1083         /* Add RI if renegotiating */
1084         if (s->renegotiate)
1085           {
1086           int el;
1087           
1088           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
1089               {
1090               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1091               return NULL;
1092               }
1093
1094           if((limit - p - 4 - el) < 0) return NULL;
1095           
1096           s2n(TLSEXT_TYPE_renegotiate,ret);
1097           s2n(el,ret);
1098
1099           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
1100               {
1101               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1102               return NULL;
1103               }
1104
1105           ret += el;
1106         }
1107
1108 #ifndef OPENSSL_NO_SRP
1109         /* Add SRP username if there is one */
1110         if (s->srp_ctx.login != NULL)
1111                 { /* Add TLS extension SRP username to the Client Hello message */
1112
1113                 int login_len = strlen(s->srp_ctx.login);       
1114                 if (login_len > 255 || login_len == 0)
1115                         {
1116                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1117                         return NULL;
1118                         } 
1119
1120                 /* check for enough space.
1121                    4 for the srp type type and entension length
1122                    1 for the srp user identity
1123                    + srp user identity length 
1124                 */
1125                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
1126
1127                 /* fill in the extension */
1128                 s2n(TLSEXT_TYPE_srp,ret);
1129                 s2n(login_len+1,ret);
1130                 (*ret++) = (unsigned char) login_len;
1131                 memcpy(ret, s->srp_ctx.login, login_len);
1132                 ret+=login_len;
1133                 }
1134 #endif
1135
1136 #ifndef OPENSSL_NO_EC
1137         if (using_ecc)
1138                 {
1139                 /* Add TLS extension ECPointFormats to the ClientHello message */
1140                 long lenmax; 
1141                 const unsigned char *plist;
1142                 size_t plistlen;
1143                 /* If we have a custom point format list use it otherwise
1144                  * use default */
1145                 plist = s->tlsext_ecpointformatlist;
1146                 if (plist)
1147                         plistlen = s->tlsext_ecpointformatlist_length;
1148                 else
1149                         {
1150                         plist = ecformats_default;
1151                         plistlen = sizeof(ecformats_default);
1152                         }
1153
1154                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1155                 if (plistlen > (size_t)lenmax) return NULL;
1156                 if (plistlen > 255)
1157                         {
1158                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1159                         return NULL;
1160                         }
1161                 
1162                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1163                 s2n(plistlen + 1,ret);
1164                 *(ret++) = (unsigned char)plistlen ;
1165                 memcpy(ret, plist, plistlen);
1166                 ret+=plistlen;
1167
1168                 /* Add TLS extension EllipticCurves to the ClientHello message */
1169                 plist = s->tlsext_ellipticcurvelist;
1170                 tls1_get_curvelist(s, 0, &plist, &plistlen);
1171
1172                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
1173                 if (plistlen > (size_t)lenmax) return NULL;
1174                 if (plistlen > 65532)
1175                         {
1176                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1177                         return NULL;
1178                         }
1179                 
1180                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
1181                 s2n(plistlen + 2, ret);
1182
1183                 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
1184                  * elliptic_curve_list, but the examples use two bytes.
1185                  * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
1186                  * resolves this to two bytes.
1187                  */
1188                 s2n(plistlen, ret);
1189                 memcpy(ret, plist, plistlen);
1190                 ret+=plistlen;
1191                 }
1192 #endif /* OPENSSL_NO_EC */
1193
1194         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
1195                 {
1196                 int ticklen;
1197                 if (!s->new_session && s->session && s->session->tlsext_tick)
1198                         ticklen = s->session->tlsext_ticklen;
1199                 else if (s->session && s->tlsext_session_ticket &&
1200                          s->tlsext_session_ticket->data)
1201                         {
1202                         ticklen = s->tlsext_session_ticket->length;
1203                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1204                         if (!s->session->tlsext_tick)
1205                                 return NULL;
1206                         memcpy(s->session->tlsext_tick,
1207                                s->tlsext_session_ticket->data,
1208                                ticklen);
1209                         s->session->tlsext_ticklen = ticklen;
1210                         }
1211                 else
1212                         ticklen = 0;
1213                 if (ticklen == 0 && s->tlsext_session_ticket &&
1214                     s->tlsext_session_ticket->data == NULL)
1215                         goto skip_ext;
1216                 /* Check for enough room 2 for extension type, 2 for len
1217                  * rest for ticket
1218                  */
1219                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1220                 s2n(TLSEXT_TYPE_session_ticket,ret); 
1221                 s2n(ticklen,ret);
1222                 if (ticklen)
1223                         {
1224                         memcpy(ret, s->session->tlsext_tick, ticklen);
1225                         ret += ticklen;
1226                         }
1227                 }
1228                 skip_ext:
1229
1230         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
1231                 {
1232                 size_t salglen;
1233                 const unsigned char *salg;
1234                 salglen = tls12_get_psigalgs(s, &salg);
1235                 if ((size_t)(limit - ret) < salglen + 6)
1236                         return NULL; 
1237                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1238                 s2n(salglen + 2, ret);
1239                 s2n(salglen, ret);
1240                 memcpy(ret, salg, salglen);
1241                 ret += salglen;
1242                 }
1243
1244 #ifdef TLSEXT_TYPE_opaque_prf_input
1245         if (s->s3->client_opaque_prf_input != NULL &&
1246             s->version != DTLS1_VERSION)
1247                 {
1248                 size_t col = s->s3->client_opaque_prf_input_len;
1249                 
1250                 if ((long)(limit - ret - 6 - col < 0))
1251                         return NULL;
1252                 if (col > 0xFFFD) /* can't happen */
1253                         return NULL;
1254
1255                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1256                 s2n(col + 2, ret);
1257                 s2n(col, ret);
1258                 memcpy(ret, s->s3->client_opaque_prf_input, col);
1259                 ret += col;
1260                 }
1261 #endif
1262
1263         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
1264             s->version != DTLS1_VERSION)
1265                 {
1266                 int i;
1267                 long extlen, idlen, itmp;
1268                 OCSP_RESPID *id;
1269
1270                 idlen = 0;
1271                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1272                         {
1273                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1274                         itmp = i2d_OCSP_RESPID(id, NULL);
1275                         if (itmp <= 0)
1276                                 return NULL;
1277                         idlen += itmp + 2;
1278                         }
1279
1280                 if (s->tlsext_ocsp_exts)
1281                         {
1282                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1283                         if (extlen < 0)
1284                                 return NULL;
1285                         }
1286                 else
1287                         extlen = 0;
1288                         
1289                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1290                 s2n(TLSEXT_TYPE_status_request, ret);
1291                 if (extlen + idlen > 0xFFF0)
1292                         return NULL;
1293                 s2n(extlen + idlen + 5, ret);
1294                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1295                 s2n(idlen, ret);
1296                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1297                         {
1298                         /* save position of id len */
1299                         unsigned char *q = ret;
1300                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1301                         /* skip over id len */
1302                         ret += 2;
1303                         itmp = i2d_OCSP_RESPID(id, &ret);
1304                         /* write id len */
1305                         s2n(itmp, q);
1306                         }
1307                 s2n(extlen, ret);
1308                 if (extlen > 0)
1309                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1310                 }
1311
1312 #ifndef OPENSSL_NO_HEARTBEATS
1313         /* Add Heartbeat extension */
1314         s2n(TLSEXT_TYPE_heartbeat,ret);
1315         s2n(1,ret);
1316         /* Set mode:
1317          * 1: peer may send requests
1318          * 2: peer not allowed to send requests
1319          */
1320         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1321                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1322         else
1323                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1324 #endif
1325
1326 #ifndef OPENSSL_NO_NEXTPROTONEG
1327         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1328                 {
1329                 /* The client advertises an emtpy extension to indicate its
1330                  * support for Next Protocol Negotiation */
1331                 if (limit - ret - 4 < 0)
1332                         return NULL;
1333                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1334                 s2n(0,ret);
1335                 }
1336 #endif
1337
1338         if(SSL_get_srtp_profiles(s))
1339                 {
1340                 int el;
1341
1342                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1343                 
1344                 if((limit - p - 4 - el) < 0) return NULL;
1345
1346                 s2n(TLSEXT_TYPE_use_srtp,ret);
1347                 s2n(el,ret);
1348
1349                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1350                         {
1351                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1352                         return NULL;
1353                         }
1354                 ret += el;
1355                 }
1356
1357         /* Add TLS extension Server_Authz_DataFormats to the ClientHello */
1358         /* 2 bytes for extension type */
1359         /* 2 bytes for extension length */
1360         /* 1 byte for the list length */
1361         /* 1 byte for the list (we only support audit proofs) */
1362         if (s->ctx->tlsext_authz_server_audit_proof_cb != NULL)
1363                 {
1364                 size_t lenmax;
1365                 const unsigned short ext_len = 2;
1366                 const unsigned char list_len = 1;
1367
1368                 if ((lenmax = limit - ret - 6) < 0) return NULL;
1369
1370                 s2n(TLSEXT_TYPE_server_authz, ret);
1371                 /* Extension length: 2 bytes */
1372                 s2n(ext_len, ret);
1373                 *(ret++) = list_len;
1374                 *(ret++) = TLSEXT_AUTHZDATAFORMAT_audit_proof;
1375                 }
1376
1377         if ((extdatalen = ret-p-2) == 0)
1378                 return p;
1379
1380         s2n(extdatalen,p);
1381         return ret;
1382         }
1383
1384 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1385         {
1386         int extdatalen=0;
1387         unsigned char *ret = p;
1388 #ifndef OPENSSL_NO_NEXTPROTONEG
1389         int next_proto_neg_seen;
1390 #endif
1391
1392         /* don't add extensions for SSLv3, unless doing secure renegotiation */
1393         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1394                 return p;
1395         
1396         ret+=2;
1397         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1398
1399         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1400                 { 
1401                 if ((long)(limit - ret - 4) < 0) return NULL; 
1402
1403                 s2n(TLSEXT_TYPE_server_name,ret);
1404                 s2n(0,ret);
1405                 }
1406
1407         if(s->s3->send_connection_binding)
1408         {
1409           int el;
1410           
1411           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1412               {
1413               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1414               return NULL;
1415               }
1416
1417           if((limit - p - 4 - el) < 0) return NULL;
1418           
1419           s2n(TLSEXT_TYPE_renegotiate,ret);
1420           s2n(el,ret);
1421
1422           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1423               {
1424               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1425               return NULL;
1426               }
1427
1428           ret += el;
1429         }
1430
1431 #ifndef OPENSSL_NO_EC
1432         if (s->tlsext_ecpointformatlist != NULL &&
1433             s->version != DTLS1_VERSION)
1434                 {
1435                 /* Add TLS extension ECPointFormats to the ServerHello message */
1436                 long lenmax; 
1437
1438                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1439                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
1440                 if (s->tlsext_ecpointformatlist_length > 255)
1441                         {
1442                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1443                         return NULL;
1444                         }
1445                 
1446                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1447                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
1448                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
1449                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
1450                 ret+=s->tlsext_ecpointformatlist_length;
1451
1452                 }
1453         /* Currently the server should not respond with a SupportedCurves extension */
1454 #endif /* OPENSSL_NO_EC */
1455
1456         if (s->tlsext_ticket_expected
1457                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
1458                 { 
1459                 if ((long)(limit - ret - 4) < 0) return NULL; 
1460                 s2n(TLSEXT_TYPE_session_ticket,ret);
1461                 s2n(0,ret);
1462                 }
1463
1464         if (s->tlsext_status_expected)
1465                 { 
1466                 if ((long)(limit - ret - 4) < 0) return NULL; 
1467                 s2n(TLSEXT_TYPE_status_request,ret);
1468                 s2n(0,ret);
1469                 }
1470
1471 #ifdef TLSEXT_TYPE_opaque_prf_input
1472         if (s->s3->server_opaque_prf_input != NULL &&
1473             s->version != DTLS1_VERSION)
1474                 {
1475                 size_t sol = s->s3->server_opaque_prf_input_len;
1476                 
1477                 if ((long)(limit - ret - 6 - sol) < 0)
1478                         return NULL;
1479                 if (sol > 0xFFFD) /* can't happen */
1480                         return NULL;
1481
1482                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1483                 s2n(sol + 2, ret);
1484                 s2n(sol, ret);
1485                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1486                 ret += sol;
1487                 }
1488 #endif
1489
1490         if(s->srtp_profile)
1491                 {
1492                 int el;
1493
1494                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1495                 
1496                 if((limit - p - 4 - el) < 0) return NULL;
1497
1498                 s2n(TLSEXT_TYPE_use_srtp,ret);
1499                 s2n(el,ret);
1500
1501                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1502                         {
1503                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1504                         return NULL;
1505                         }
1506                 ret+=el;
1507                 }
1508
1509         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1510                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1511                 { const unsigned char cryptopro_ext[36] = {
1512                         0xfd, 0xe8, /*65000*/
1513                         0x00, 0x20, /*32 bytes length*/
1514                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1515                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1516                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1517                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1518                         if (limit-ret<36) return NULL;
1519                         memcpy(ret,cryptopro_ext,36);
1520                         ret+=36;
1521
1522                 }
1523
1524 #ifndef OPENSSL_NO_HEARTBEATS
1525         /* Add Heartbeat extension if we've received one */
1526         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1527                 {
1528                 s2n(TLSEXT_TYPE_heartbeat,ret);
1529                 s2n(1,ret);
1530                 /* Set mode:
1531                  * 1: peer may send requests
1532                  * 2: peer not allowed to send requests
1533                  */
1534                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1535                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1536                 else
1537                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1538
1539                 }
1540 #endif
1541
1542 #ifndef OPENSSL_NO_NEXTPROTONEG
1543         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1544         s->s3->next_proto_neg_seen = 0;
1545         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1546                 {
1547                 const unsigned char *npa;
1548                 unsigned int npalen;
1549                 int r;
1550
1551                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1552                 if (r == SSL_TLSEXT_ERR_OK)
1553                         {
1554                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1555                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1556                         s2n(npalen,ret);
1557                         memcpy(ret, npa, npalen);
1558                         ret += npalen;
1559                         s->s3->next_proto_neg_seen = 1;
1560                         }
1561                 }
1562 #endif
1563
1564         /* If the client supports authz then see whether we have any to offer
1565          * to it. */
1566         if (s->s3->tlsext_authz_client_types_len)
1567                 {
1568                 size_t authz_length;
1569                 /* By now we already know the new cipher, so we can look ahead
1570                  * to see whether the cert we are going to send
1571                  * has any authz data attached to it. */
1572                 const unsigned char* authz = ssl_get_authz_data(s, &authz_length);
1573                 const unsigned char* const orig_authz = authz;
1574                 size_t i;
1575                 unsigned authz_count = 0;
1576
1577                 /* The authz data contains a number of the following structures:
1578                  *      uint8_t authz_type
1579                  *      uint16_t length
1580                  *      uint8_t data[length]
1581                  *
1582                  * First we walk over it to find the number of authz elements. */
1583                 for (i = 0; i < authz_length; i++)
1584                         {
1585                         unsigned short length;
1586                         unsigned char type;
1587
1588                         type = *(authz++);
1589                         if (memchr(s->s3->tlsext_authz_client_types,
1590                                    type,
1591                                    s->s3->tlsext_authz_client_types_len) != NULL)
1592                                 authz_count++;
1593
1594                         n2s(authz, length);
1595                         /* n2s increments authz by 2 */
1596                         i += 2;
1597                         authz += length;
1598                         i += length;
1599                         }
1600
1601                 if (authz_count)
1602                         {
1603                         /* Add TLS extension server_authz to the ServerHello message
1604                          * 2 bytes for extension type
1605                          * 2 bytes for extension length
1606                          * 1 byte for the list length
1607                          * n bytes for the list */
1608                         const unsigned short ext_len = 1 + authz_count;
1609
1610                         if ((long)(limit - ret - 4 - ext_len) < 0) return NULL;
1611                         s2n(TLSEXT_TYPE_server_authz, ret);
1612                         s2n(ext_len, ret);
1613                         *(ret++) = authz_count;
1614                         s->s3->tlsext_authz_promised_to_client = 1;
1615                         }
1616
1617                 authz = orig_authz;
1618                 for (i = 0; i < authz_length; i++)
1619                         {
1620                         unsigned short length;
1621                         unsigned char type;
1622
1623                         authz_count++;
1624                         type = *(authz++);
1625                         if (memchr(s->s3->tlsext_authz_client_types,
1626                                    type,
1627                                    s->s3->tlsext_authz_client_types_len) != NULL)
1628                                 *(ret++) = type;
1629                         n2s(authz, length);
1630                         /* n2s increments authz by 2 */
1631                         i += 2;
1632                         authz += length;
1633                         i += length;
1634                         }
1635                 }
1636
1637         if ((extdatalen = ret-p-2)== 0) 
1638                 return p;
1639
1640         s2n(extdatalen,p);
1641         return ret;
1642         }
1643
1644 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) 
1645         {       
1646         unsigned short type;
1647         unsigned short size;
1648         unsigned short len;
1649         unsigned char *data = *p;
1650         int renegotiate_seen = 0;
1651         size_t i;
1652
1653         s->servername_done = 0;
1654         s->tlsext_status_type = -1;
1655 #ifndef OPENSSL_NO_NEXTPROTONEG
1656         s->s3->next_proto_neg_seen = 0;
1657 #endif
1658
1659 #ifndef OPENSSL_NO_HEARTBEATS
1660         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1661                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1662 #endif
1663         /* Clear any signature algorithms extension received */
1664         if (s->cert->peer_sigalgs)
1665                 {
1666                 OPENSSL_free(s->cert->peer_sigalgs);
1667                 s->cert->peer_sigalgs = NULL;
1668                 }
1669         /* Clear any shared sigtnature algorithms */
1670         if (s->cert->shared_sigalgs)
1671                 {
1672                 OPENSSL_free(s->cert->shared_sigalgs);
1673                 s->cert->shared_sigalgs = NULL;
1674                 }
1675         /* Clear certificate digests and validity flags */
1676         for (i = 0; i < SSL_PKEY_NUM; i++)
1677                 {
1678                 s->cert->pkeys[i].digest = NULL;
1679                 s->cert->pkeys[i].valid_flags = 0;
1680                 }
1681
1682         if (data >= (d+n-2))
1683                 goto ri_check;
1684         n2s(data,len);
1685
1686         if (data > (d+n-len)) 
1687                 goto ri_check;
1688
1689         while (data <= (d+n-4))
1690                 {
1691                 n2s(data,type);
1692                 n2s(data,size);
1693
1694                 if (data+size > (d+n))
1695                         goto ri_check;
1696 #if 0
1697                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1698 #endif
1699                 if (s->tlsext_debug_cb)
1700                         s->tlsext_debug_cb(s, 0, type, data, size,
1701                                                 s->tlsext_debug_arg);
1702 /* The servername extension is treated as follows:
1703
1704    - Only the hostname type is supported with a maximum length of 255.
1705    - The servername is rejected if too long or if it contains zeros,
1706      in which case an fatal alert is generated.
1707    - The servername field is maintained together with the session cache.
1708    - When a session is resumed, the servername call back invoked in order
1709      to allow the application to position itself to the right context. 
1710    - The servername is acknowledged if it is new for a session or when 
1711      it is identical to a previously used for the same session. 
1712      Applications can control the behaviour.  They can at any time
1713      set a 'desirable' servername for a new SSL object. This can be the
1714      case for example with HTTPS when a Host: header field is received and
1715      a renegotiation is requested. In this case, a possible servername
1716      presented in the new client hello is only acknowledged if it matches
1717      the value of the Host: field. 
1718    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1719      if they provide for changing an explicit servername context for the session,
1720      i.e. when the session has been established with a servername extension. 
1721    - On session reconnect, the servername extension may be absent. 
1722
1723 */      
1724
1725                 if (type == TLSEXT_TYPE_server_name)
1726                         {
1727                         unsigned char *sdata;
1728                         int servname_type;
1729                         int dsize; 
1730                 
1731                         if (size < 2) 
1732                                 {
1733                                 *al = SSL_AD_DECODE_ERROR;
1734                                 return 0;
1735                                 }
1736                         n2s(data,dsize);  
1737                         size -= 2;
1738                         if (dsize > size  ) 
1739                                 {
1740                                 *al = SSL_AD_DECODE_ERROR;
1741                                 return 0;
1742                                 } 
1743
1744                         sdata = data;
1745                         while (dsize > 3) 
1746                                 {
1747                                 servname_type = *(sdata++); 
1748                                 n2s(sdata,len);
1749                                 dsize -= 3;
1750
1751                                 if (len > dsize) 
1752                                         {
1753                                         *al = SSL_AD_DECODE_ERROR;
1754                                         return 0;
1755                                         }
1756                                 if (s->servername_done == 0)
1757                                 switch (servname_type)
1758                                         {
1759                                 case TLSEXT_NAMETYPE_host_name:
1760                                         if (!s->hit)
1761                                                 {
1762                                                 if(s->session->tlsext_hostname)
1763                                                         {
1764                                                         *al = SSL_AD_DECODE_ERROR;
1765                                                         return 0;
1766                                                         }
1767                                                 if (len > TLSEXT_MAXLEN_host_name)
1768                                                         {
1769                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1770                                                         return 0;
1771                                                         }
1772                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
1773                                                         {
1774                                                         *al = TLS1_AD_INTERNAL_ERROR;
1775                                                         return 0;
1776                                                         }
1777                                                 memcpy(s->session->tlsext_hostname, sdata, len);
1778                                                 s->session->tlsext_hostname[len]='\0';
1779                                                 if (strlen(s->session->tlsext_hostname) != len) {
1780                                                         OPENSSL_free(s->session->tlsext_hostname);
1781                                                         s->session->tlsext_hostname = NULL;
1782                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1783                                                         return 0;
1784                                                 }
1785                                                 s->servername_done = 1; 
1786
1787                                                 }
1788                                         else 
1789                                                 s->servername_done = s->session->tlsext_hostname
1790                                                         && strlen(s->session->tlsext_hostname) == len 
1791                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
1792                                         
1793                                         break;
1794
1795                                 default:
1796                                         break;
1797                                         }
1798                                  
1799                                 dsize -= len;
1800                                 }
1801                         if (dsize != 0) 
1802                                 {
1803                                 *al = SSL_AD_DECODE_ERROR;
1804                                 return 0;
1805                                 }
1806
1807                         }
1808 #ifndef OPENSSL_NO_SRP
1809                 else if (type == TLSEXT_TYPE_srp)
1810                         {
1811                         if (size <= 0 || ((len = data[0])) != (size -1))
1812                                 {
1813                                 *al = SSL_AD_DECODE_ERROR;
1814                                 return 0;
1815                                 }
1816                         if (s->srp_ctx.login != NULL)
1817                                 {
1818                                 *al = SSL_AD_DECODE_ERROR;
1819                                 return 0;
1820                                 }
1821                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
1822                                 return -1;
1823                         memcpy(s->srp_ctx.login, &data[1], len);
1824                         s->srp_ctx.login[len]='\0';
1825   
1826                         if (strlen(s->srp_ctx.login) != len) 
1827                                 {
1828                                 *al = SSL_AD_DECODE_ERROR;
1829                                 return 0;
1830                                 }
1831                         }
1832 #endif
1833
1834 #ifndef OPENSSL_NO_EC
1835                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1836                      s->version != DTLS1_VERSION)
1837                         {
1838                         unsigned char *sdata = data;
1839                         int ecpointformatlist_length = *(sdata++);
1840
1841                         if (ecpointformatlist_length != size - 1)
1842                                 {
1843                                 *al = TLS1_AD_DECODE_ERROR;
1844                                 return 0;
1845                                 }
1846                         if (!s->hit)
1847                                 {
1848                                 if(s->session->tlsext_ecpointformatlist)
1849                                         {
1850                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
1851                                         s->session->tlsext_ecpointformatlist = NULL;
1852                                         }
1853                                 s->session->tlsext_ecpointformatlist_length = 0;
1854                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1855                                         {
1856                                         *al = TLS1_AD_INTERNAL_ERROR;
1857                                         return 0;
1858                                         }
1859                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1860                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1861                                 }
1862 #if 0
1863                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
1864                         sdata = s->session->tlsext_ecpointformatlist;
1865                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1866                                 fprintf(stderr,"%i ",*(sdata++));
1867                         fprintf(stderr,"\n");
1868 #endif
1869                         }
1870                 else if (type == TLSEXT_TYPE_elliptic_curves &&
1871                      s->version != DTLS1_VERSION)
1872                         {
1873                         unsigned char *sdata = data;
1874                         int ellipticcurvelist_length = (*(sdata++) << 8);
1875                         ellipticcurvelist_length += (*(sdata++));
1876
1877                         if (ellipticcurvelist_length != size - 2)
1878                                 {
1879                                 *al = TLS1_AD_DECODE_ERROR;
1880                                 return 0;
1881                                 }
1882                         if (!s->hit)
1883                                 {
1884                                 if(s->session->tlsext_ellipticcurvelist)
1885                                         {
1886                                         *al = TLS1_AD_DECODE_ERROR;
1887                                         return 0;
1888                                         }
1889                                 s->session->tlsext_ellipticcurvelist_length = 0;
1890                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
1891                                         {
1892                                         *al = TLS1_AD_INTERNAL_ERROR;
1893                                         return 0;
1894                                         }
1895                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
1896                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
1897                                 }
1898 #if 0
1899                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
1900                         sdata = s->session->tlsext_ellipticcurvelist;
1901                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
1902                                 fprintf(stderr,"%i ",*(sdata++));
1903                         fprintf(stderr,"\n");
1904 #endif
1905                         }
1906 #endif /* OPENSSL_NO_EC */
1907 #ifdef TLSEXT_TYPE_opaque_prf_input
1908                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1909                      s->version != DTLS1_VERSION)
1910                         {
1911                         unsigned char *sdata = data;
1912
1913                         if (size < 2)
1914                                 {
1915                                 *al = SSL_AD_DECODE_ERROR;
1916                                 return 0;
1917                                 }
1918                         n2s(sdata, s->s3->client_opaque_prf_input_len);
1919                         if (s->s3->client_opaque_prf_input_len != size - 2)
1920                                 {
1921                                 *al = SSL_AD_DECODE_ERROR;
1922                                 return 0;
1923                                 }
1924
1925                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1926                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1927                         if (s->s3->client_opaque_prf_input_len == 0)
1928                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1929                         else
1930                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
1931                         if (s->s3->client_opaque_prf_input == NULL)
1932                                 {
1933                                 *al = TLS1_AD_INTERNAL_ERROR;
1934                                 return 0;
1935                                 }
1936                         }
1937 #endif
1938                 else if (type == TLSEXT_TYPE_session_ticket)
1939                         {
1940                         if (s->tls_session_ticket_ext_cb &&
1941                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1942                                 {
1943                                 *al = TLS1_AD_INTERNAL_ERROR;
1944                                 return 0;
1945                                 }
1946                         }
1947                 else if (type == TLSEXT_TYPE_renegotiate)
1948                         {
1949                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
1950                                 return 0;
1951                         renegotiate_seen = 1;
1952                         }
1953                 else if (type == TLSEXT_TYPE_signature_algorithms)
1954                         {
1955                         int dsize;
1956                         if (s->cert->peer_sigalgs || size < 2) 
1957                                 {
1958                                 *al = SSL_AD_DECODE_ERROR;
1959                                 return 0;
1960                                 }
1961                         n2s(data,dsize);
1962                         size -= 2;
1963                         if (dsize != size || dsize & 1 || !dsize) 
1964                                 {
1965                                 *al = SSL_AD_DECODE_ERROR;
1966                                 return 0;
1967                                 }
1968                         if (!tls1_process_sigalgs(s, data, dsize))
1969                                 {
1970                                 *al = SSL_AD_DECODE_ERROR;
1971                                 return 0;
1972                                 }
1973                         /* If sigalgs received and no shared algorithms fatal
1974                          * error.
1975                          */
1976                         if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
1977                                 {
1978                                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
1979                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
1980                                 *al = SSL_AD_ILLEGAL_PARAMETER;
1981                                 return 0;
1982                                 }
1983                         }
1984                 else if (type == TLSEXT_TYPE_status_request &&
1985                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
1986                         {
1987                 
1988                         if (size < 5) 
1989                                 {
1990                                 *al = SSL_AD_DECODE_ERROR;
1991                                 return 0;
1992                                 }
1993
1994                         s->tlsext_status_type = *data++;
1995                         size--;
1996                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1997                                 {
1998                                 const unsigned char *sdata;
1999                                 int dsize;
2000                                 /* Read in responder_id_list */
2001                                 n2s(data,dsize);
2002                                 size -= 2;
2003                                 if (dsize > size  ) 
2004                                         {
2005                                         *al = SSL_AD_DECODE_ERROR;
2006                                         return 0;
2007                                         }
2008                                 while (dsize > 0)
2009                                         {
2010                                         OCSP_RESPID *id;
2011                                         int idsize;
2012                                         if (dsize < 4)
2013                                                 {
2014                                                 *al = SSL_AD_DECODE_ERROR;
2015                                                 return 0;
2016                                                 }
2017                                         n2s(data, idsize);
2018                                         dsize -= 2 + idsize;
2019                                         size -= 2 + idsize;
2020                                         if (dsize < 0)
2021                                                 {
2022                                                 *al = SSL_AD_DECODE_ERROR;
2023                                                 return 0;
2024                                                 }
2025                                         sdata = data;
2026                                         data += idsize;
2027                                         id = d2i_OCSP_RESPID(NULL,
2028                                                                 &sdata, idsize);
2029                                         if (!id)
2030                                                 {
2031                                                 *al = SSL_AD_DECODE_ERROR;
2032                                                 return 0;
2033                                                 }
2034                                         if (data != sdata)
2035                                                 {
2036                                                 OCSP_RESPID_free(id);
2037                                                 *al = SSL_AD_DECODE_ERROR;
2038                                                 return 0;
2039                                                 }
2040                                         if (!s->tlsext_ocsp_ids
2041                                                 && !(s->tlsext_ocsp_ids =
2042                                                 sk_OCSP_RESPID_new_null()))
2043                                                 {
2044                                                 OCSP_RESPID_free(id);
2045                                                 *al = SSL_AD_INTERNAL_ERROR;
2046                                                 return 0;
2047                                                 }
2048                                         if (!sk_OCSP_RESPID_push(
2049                                                         s->tlsext_ocsp_ids, id))
2050                                                 {
2051                                                 OCSP_RESPID_free(id);
2052                                                 *al = SSL_AD_INTERNAL_ERROR;
2053                                                 return 0;
2054                                                 }
2055                                         }
2056
2057                                 /* Read in request_extensions */
2058                                 if (size < 2)
2059                                         {
2060                                         *al = SSL_AD_DECODE_ERROR;
2061                                         return 0;
2062                                         }
2063                                 n2s(data,dsize);
2064                                 size -= 2;
2065                                 if (dsize != size)
2066                                         {
2067                                         *al = SSL_AD_DECODE_ERROR;
2068                                         return 0;
2069                                         }
2070                                 sdata = data;
2071                                 if (dsize > 0)
2072                                         {
2073                                         if (s->tlsext_ocsp_exts)
2074                                                 {
2075                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2076                                                                            X509_EXTENSION_free);
2077                                                 }
2078
2079                                         s->tlsext_ocsp_exts =
2080                                                 d2i_X509_EXTENSIONS(NULL,
2081                                                         &sdata, dsize);
2082                                         if (!s->tlsext_ocsp_exts
2083                                                 || (data + dsize != sdata))
2084                                                 {
2085                                                 *al = SSL_AD_DECODE_ERROR;
2086                                                 return 0;
2087                                                 }
2088                                         }
2089                                 }
2090                                 /* We don't know what to do with any other type
2091                                 * so ignore it.
2092                                 */
2093                                 else
2094                                         s->tlsext_status_type = -1;
2095                         }
2096 #ifndef OPENSSL_NO_HEARTBEATS
2097                 else if (type == TLSEXT_TYPE_heartbeat)
2098                         {
2099                         switch(data[0])
2100                                 {
2101                                 case 0x01:      /* Client allows us to send HB requests */
2102                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2103                                                         break;
2104                                 case 0x02:      /* Client doesn't accept HB requests */
2105                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2106                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2107                                                         break;
2108                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2109                                                         return 0;
2110                                 }
2111                         }
2112 #endif
2113 #ifndef OPENSSL_NO_NEXTPROTONEG
2114                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2115                          s->s3->tmp.finish_md_len == 0)
2116                         {
2117                         /* We shouldn't accept this extension on a
2118                          * renegotiation.
2119                          *
2120                          * s->new_session will be set on renegotiation, but we
2121                          * probably shouldn't rely that it couldn't be set on
2122                          * the initial renegotation too in certain cases (when
2123                          * there's some other reason to disallow resuming an
2124                          * earlier session -- the current code won't be doing
2125                          * anything like that, but this might change).
2126
2127                          * A valid sign that there's been a previous handshake
2128                          * in this connection is if s->s3->tmp.finish_md_len >
2129                          * 0.  (We are talking about a check that will happen
2130                          * in the Hello protocol round, well before a new
2131                          * Finished message could have been computed.) */
2132                         s->s3->next_proto_neg_seen = 1;
2133                         }
2134 #endif
2135
2136                 /* session ticket processed earlier */
2137                 else if (type == TLSEXT_TYPE_use_srtp)
2138                         {
2139                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2140                                                               al))
2141                                 return 0;
2142                         }
2143
2144                 else if (type == TLSEXT_TYPE_server_authz)
2145                         {
2146                         unsigned char *sdata = data;
2147                         unsigned char server_authz_dataformatlist_length;
2148
2149                         if (size == 0)
2150                                 {
2151                                 *al = TLS1_AD_DECODE_ERROR;
2152                                 return 0;
2153                                 }
2154
2155                         server_authz_dataformatlist_length = *(sdata++);
2156
2157                         if (server_authz_dataformatlist_length != size - 1)
2158                                 {
2159                                 *al = TLS1_AD_DECODE_ERROR;
2160                                 return 0;
2161                                 }
2162
2163                         /* Successful session resumption uses the same authz
2164                          * information as the original session so we ignore this
2165                          * in the case of a session resumption. */
2166                         if (!s->hit)
2167                                 {
2168                                 if (s->s3->tlsext_authz_client_types != NULL)
2169                                         OPENSSL_free(s->s3->tlsext_authz_client_types);
2170                                 s->s3->tlsext_authz_client_types =
2171                                         OPENSSL_malloc(server_authz_dataformatlist_length);
2172                                 if (!s->s3->tlsext_authz_client_types)
2173                                         {
2174                                         *al = TLS1_AD_INTERNAL_ERROR;
2175                                         return 0;
2176                                         }
2177
2178                                 s->s3->tlsext_authz_client_types_len =
2179                                         server_authz_dataformatlist_length;
2180                                 memcpy(s->s3->tlsext_authz_client_types,
2181                                        sdata,
2182                                        server_authz_dataformatlist_length);
2183
2184                                 /* Sort the types in order to check for duplicates. */
2185                                 qsort(s->s3->tlsext_authz_client_types,
2186                                       server_authz_dataformatlist_length,
2187                                       1 /* element size */,
2188                                       byte_compare);
2189
2190                                 for (i = 0; i < server_authz_dataformatlist_length; i++)
2191                                         {
2192                                         if (i > 0 &&
2193                                             s->s3->tlsext_authz_client_types[i] ==
2194                                               s->s3->tlsext_authz_client_types[i-1])
2195                                                 {
2196                                                 *al = TLS1_AD_DECODE_ERROR;
2197                                                 return 0;
2198                                                 }
2199                                         }
2200                                 }
2201                         }
2202
2203                 data+=size;
2204                 }
2205
2206         *p = data;
2207
2208         ri_check:
2209
2210         /* Need RI if renegotiating */
2211
2212         if (!renegotiate_seen && s->renegotiate &&
2213                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2214                 {
2215                 *al = SSL_AD_HANDSHAKE_FAILURE;
2216                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2217                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2218                 return 0;
2219                 }
2220         /* If no signature algorithms extension set default values */
2221         if (!s->cert->peer_sigalgs)
2222                 ssl_cert_set_default_md(s->cert);
2223
2224         return 1;
2225         }
2226
2227 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2228         {
2229         int al = -1;
2230         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2231                 {
2232                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2233                 return 0;
2234                 }
2235
2236         if (ssl_check_clienthello_tlsext(s) <= 0) 
2237                 {
2238                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2239                 return 0;
2240                 }
2241         return 1;
2242 }
2243
2244 #ifndef OPENSSL_NO_NEXTPROTONEG
2245 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2246  * elements of zero length are allowed and the set of elements must exactly fill
2247  * the length of the block. */
2248 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2249         {
2250         unsigned int off = 0;
2251
2252         while (off < len)
2253                 {
2254                 if (d[off] == 0)
2255                         return 0;
2256                 off += d[off];
2257                 off++;
2258                 }
2259
2260         return off == len;
2261         }
2262 #endif
2263
2264 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2265         {
2266         unsigned short length;
2267         unsigned short type;
2268         unsigned short size;
2269         unsigned char *data = *p;
2270         int tlsext_servername = 0;
2271         int renegotiate_seen = 0;
2272
2273 #ifndef OPENSSL_NO_NEXTPROTONEG
2274         s->s3->next_proto_neg_seen = 0;
2275 #endif
2276
2277 #ifndef OPENSSL_NO_HEARTBEATS
2278         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2279                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2280 #endif
2281
2282         if (data >= (d+n-2))
2283                 goto ri_check;
2284
2285         n2s(data,length);
2286         if (data+length != d+n)
2287                 {
2288                 *al = SSL_AD_DECODE_ERROR;
2289                 return 0;
2290                 }
2291
2292         while(data <= (d+n-4))
2293                 {
2294                 n2s(data,type);
2295                 n2s(data,size);
2296
2297                 if (data+size > (d+n))
2298                         goto ri_check;
2299
2300                 if (s->tlsext_debug_cb)
2301                         s->tlsext_debug_cb(s, 1, type, data, size,
2302                                                 s->tlsext_debug_arg);
2303
2304                 if (type == TLSEXT_TYPE_server_name)
2305                         {
2306                         if (s->tlsext_hostname == NULL || size > 0)
2307                                 {
2308                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2309                                 return 0;
2310                                 }
2311                         tlsext_servername = 1;   
2312                         }
2313
2314 #ifndef OPENSSL_NO_EC
2315                 else if (type == TLSEXT_TYPE_ec_point_formats &&
2316                      s->version != DTLS1_VERSION)
2317                         {
2318                         unsigned char *sdata = data;
2319                         int ecpointformatlist_length = *(sdata++);
2320
2321                         if (ecpointformatlist_length != size - 1)
2322                                 {
2323                                 *al = TLS1_AD_DECODE_ERROR;
2324                                 return 0;
2325                                 }
2326                         s->session->tlsext_ecpointformatlist_length = 0;
2327                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2328                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2329                                 {
2330                                 *al = TLS1_AD_INTERNAL_ERROR;
2331                                 return 0;
2332                                 }
2333                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2334                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2335 #if 0
2336                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2337                         sdata = s->session->tlsext_ecpointformatlist;
2338                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2339                                 fprintf(stderr,"%i ",*(sdata++));
2340                         fprintf(stderr,"\n");
2341 #endif
2342                         }
2343 #endif /* OPENSSL_NO_EC */
2344
2345                 else if (type == TLSEXT_TYPE_session_ticket)
2346                         {
2347                         if (s->tls_session_ticket_ext_cb &&
2348                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2349                                 {
2350                                 *al = TLS1_AD_INTERNAL_ERROR;
2351                                 return 0;
2352                                 }
2353                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2354                                 || (size > 0))
2355                                 {
2356                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2357                                 return 0;
2358                                 }
2359                         s->tlsext_ticket_expected = 1;
2360                         }
2361 #ifdef TLSEXT_TYPE_opaque_prf_input
2362                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
2363                      s->version != DTLS1_VERSION)
2364                         {
2365                         unsigned char *sdata = data;
2366
2367                         if (size < 2)
2368                                 {
2369                                 *al = SSL_AD_DECODE_ERROR;
2370                                 return 0;
2371                                 }
2372                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2373                         if (s->s3->server_opaque_prf_input_len != size - 2)
2374                                 {
2375                                 *al = SSL_AD_DECODE_ERROR;
2376                                 return 0;
2377                                 }
2378                         
2379                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2380                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2381                         if (s->s3->server_opaque_prf_input_len == 0)
2382                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2383                         else
2384                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2385
2386                         if (s->s3->server_opaque_prf_input == NULL)
2387                                 {
2388                                 *al = TLS1_AD_INTERNAL_ERROR;
2389                                 return 0;
2390                                 }
2391                         }
2392 #endif
2393                 else if (type == TLSEXT_TYPE_status_request &&
2394                          s->version != DTLS1_VERSION)
2395                         {
2396                         /* MUST be empty and only sent if we've requested
2397                          * a status request message.
2398                          */ 
2399                         if ((s->tlsext_status_type == -1) || (size > 0))
2400                                 {
2401                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2402                                 return 0;
2403                                 }
2404                         /* Set flag to expect CertificateStatus message */
2405                         s->tlsext_status_expected = 1;
2406                         }
2407 #ifndef OPENSSL_NO_NEXTPROTONEG
2408                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2409                          s->s3->tmp.finish_md_len == 0)
2410                         {
2411                         unsigned char *selected;
2412                         unsigned char selected_len;
2413
2414                         /* We must have requested it. */
2415                         if ((s->ctx->next_proto_select_cb == NULL))
2416                                 {
2417                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2418                                 return 0;
2419                                 }
2420                         /* The data must be valid */
2421                         if (!ssl_next_proto_validate(data, size))
2422                                 {
2423                                 *al = TLS1_AD_DECODE_ERROR;
2424                                 return 0;
2425                                 }
2426                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2427                                 {
2428                                 *al = TLS1_AD_INTERNAL_ERROR;
2429                                 return 0;
2430                                 }
2431                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2432                         if (!s->next_proto_negotiated)
2433                                 {
2434                                 *al = TLS1_AD_INTERNAL_ERROR;
2435                                 return 0;
2436                                 }
2437                         memcpy(s->next_proto_negotiated, selected, selected_len);
2438                         s->next_proto_negotiated_len = selected_len;
2439                         s->s3->next_proto_neg_seen = 1;
2440                         }
2441 #endif
2442                 else if (type == TLSEXT_TYPE_renegotiate)
2443                         {
2444                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2445                                 return 0;
2446                         renegotiate_seen = 1;
2447                         }
2448 #ifndef OPENSSL_NO_HEARTBEATS
2449                 else if (type == TLSEXT_TYPE_heartbeat)
2450                         {
2451                         switch(data[0])
2452                                 {
2453                                 case 0x01:      /* Server allows us to send HB requests */
2454                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2455                                                         break;
2456                                 case 0x02:      /* Server doesn't accept HB requests */
2457                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2458                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2459                                                         break;
2460                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2461                                                         return 0;
2462                                 }
2463                         }
2464 #endif
2465                 else if (type == TLSEXT_TYPE_use_srtp)
2466                         {
2467                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2468                                                               al))
2469                                 return 0;
2470                         }
2471
2472                 else if (type == TLSEXT_TYPE_server_authz)
2473                         {
2474                         /* We only support audit proofs. It's an error to send
2475                          * an authz hello extension if the client
2476                          * didn't request a proof. */
2477                         unsigned char *sdata = data;
2478                         unsigned char server_authz_dataformatlist_length;
2479
2480                         if (!s->ctx->tlsext_authz_server_audit_proof_cb)
2481                                 {
2482                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2483                                 return 0;
2484                                 }
2485
2486                         if (!size)
2487                                 {
2488                                 *al = TLS1_AD_DECODE_ERROR;
2489                                 return 0;
2490                                 }
2491
2492                         server_authz_dataformatlist_length = *(sdata++);
2493                         if (server_authz_dataformatlist_length != size - 1)
2494                                 {
2495                                 *al = TLS1_AD_DECODE_ERROR;
2496                                 return 0;
2497                                 }
2498
2499                         /* We only support audit proofs, so a legal ServerHello
2500                          * authz list contains exactly one entry. */
2501                         if (server_authz_dataformatlist_length != 1 ||
2502                                 sdata[0] != TLSEXT_AUTHZDATAFORMAT_audit_proof)
2503                                 {
2504                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2505                                 return 0;
2506                                 }
2507
2508                         s->s3->tlsext_authz_server_promised = 1;
2509                         }
2510  
2511                 data += size;
2512                 }
2513
2514         if (data != d+n)
2515                 {
2516                 *al = SSL_AD_DECODE_ERROR;
2517                 return 0;
2518                 }
2519
2520         if (!s->hit && tlsext_servername == 1)
2521                 {
2522                 if (s->tlsext_hostname)
2523                         {
2524                         if (s->session->tlsext_hostname == NULL)
2525                                 {
2526                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2527                                 if (!s->session->tlsext_hostname)
2528                                         {
2529                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2530                                         return 0;
2531                                         }
2532                                 }
2533                         else 
2534                                 {
2535                                 *al = SSL_AD_DECODE_ERROR;
2536                                 return 0;
2537                                 }
2538                         }
2539                 }
2540
2541         *p = data;
2542
2543         ri_check:
2544
2545         /* Determine if we need to see RI. Strictly speaking if we want to
2546          * avoid an attack we should *always* see RI even on initial server
2547          * hello because the client doesn't see any renegotiation during an
2548          * attack. However this would mean we could not connect to any server
2549          * which doesn't support RI so for the immediate future tolerate RI
2550          * absence on initial connect only.
2551          */
2552         if (!renegotiate_seen
2553                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2554                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2555                 {
2556                 *al = SSL_AD_HANDSHAKE_FAILURE;
2557                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2558                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2559                 return 0;
2560                 }
2561
2562         return 1;
2563         }
2564
2565
2566 int ssl_prepare_clienthello_tlsext(SSL *s)
2567         {
2568
2569 #ifdef TLSEXT_TYPE_opaque_prf_input
2570         {
2571                 int r = 1;
2572         
2573                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2574                         {
2575                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2576                         if (!r)
2577                                 return -1;
2578                         }
2579
2580                 if (s->tlsext_opaque_prf_input != NULL)
2581                         {
2582                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2583                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2584
2585                         if (s->tlsext_opaque_prf_input_len == 0)
2586                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2587                         else
2588                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2589                         if (s->s3->client_opaque_prf_input == NULL)
2590                                 {
2591                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2592                                 return -1;
2593                                 }
2594                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2595                         }
2596
2597                 if (r == 2)
2598                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2599                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2600         }
2601 #endif
2602
2603         return 1;
2604         }
2605
2606 int ssl_prepare_serverhello_tlsext(SSL *s)
2607         {
2608 #ifndef OPENSSL_NO_EC
2609         /* If we are server and using an ECC cipher suite, send the point formats we support 
2610          * if the client sent us an ECPointsFormat extension.  Note that the server is not
2611          * supposed to send an EllipticCurves extension.
2612          */
2613
2614         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2615         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2616         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
2617         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
2618         
2619         if (using_ecc)
2620                 {
2621                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
2622                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
2623                         {
2624                         SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2625                         return -1;
2626                         }
2627                 s->tlsext_ecpointformatlist_length = 3;
2628                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
2629                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
2630                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
2631                 }
2632 #endif /* OPENSSL_NO_EC */
2633
2634         return 1;
2635         }
2636
2637 static int ssl_check_clienthello_tlsext(SSL *s)
2638         {
2639         int ret=SSL_TLSEXT_ERR_NOACK;
2640         int al = SSL_AD_UNRECOGNIZED_NAME;
2641
2642 #ifndef OPENSSL_NO_EC
2643         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2644          * ssl3_choose_cipher in s3_lib.c.
2645          */
2646         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2647          * ssl3_choose_cipher in s3_lib.c.
2648          */
2649 #endif
2650
2651         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2652                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2653         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2654                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2655
2656         /* If status request then ask callback what to do.
2657          * Note: this must be called after servername callbacks in case 
2658          * the certificate has changed.
2659          */
2660         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
2661                 {
2662                 int r;
2663                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2664                 switch (r)
2665                         {
2666                         /* We don't want to send a status request response */
2667                         case SSL_TLSEXT_ERR_NOACK:
2668                                 s->tlsext_status_expected = 0;
2669                                 break;
2670                         /* status request response should be sent */
2671                         case SSL_TLSEXT_ERR_OK:
2672                                 if (s->tlsext_ocsp_resp)
2673                                         s->tlsext_status_expected = 1;
2674                                 else
2675                                         s->tlsext_status_expected = 0;
2676                                 break;
2677                         /* something bad happened */
2678                         case SSL_TLSEXT_ERR_ALERT_FATAL:
2679                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2680                                 al = SSL_AD_INTERNAL_ERROR;
2681                                 goto err;
2682                         }
2683                 }
2684         else
2685                 s->tlsext_status_expected = 0;
2686
2687 #ifdef TLSEXT_TYPE_opaque_prf_input
2688         {
2689                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2690                  * but we might be sending an alert in response to the client hello,
2691                  * so this has to happen here in ssl_check_clienthello_tlsext(). */
2692
2693                 int r = 1;
2694         
2695                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2696                         {
2697                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2698                         if (!r)
2699                                 {
2700                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2701                                 al = SSL_AD_INTERNAL_ERROR;
2702                                 goto err;
2703                                 }
2704                         }
2705
2706                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2707                         OPENSSL_free(s->s3->server_opaque_prf_input);
2708                 s->s3->server_opaque_prf_input = NULL;
2709
2710                 if (s->tlsext_opaque_prf_input != NULL)
2711                         {
2712                         if (s->s3->client_opaque_prf_input != NULL &&
2713                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2714                                 {
2715                                 /* can only use this extension if we have a server opaque PRF input
2716                                  * of the same length as the client opaque PRF input! */
2717
2718                                 if (s->tlsext_opaque_prf_input_len == 0)
2719                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2720                                 else
2721                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2722                                 if (s->s3->server_opaque_prf_input == NULL)
2723                                         {
2724                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2725                                         al = SSL_AD_INTERNAL_ERROR;
2726                                         goto err;
2727                                         }
2728                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2729                                 }
2730                         }
2731
2732                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2733                         {
2734                         /* The callback wants to enforce use of the extension,
2735                          * but we can't do that with the client opaque PRF input;
2736                          * abort the handshake.
2737                          */
2738                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2739                         al = SSL_AD_HANDSHAKE_FAILURE;
2740                         }
2741         }
2742
2743 #endif
2744  err:
2745         switch (ret)
2746                 {
2747                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2748                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2749                         return -1;
2750
2751                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2752                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2753                         return 1; 
2754                                         
2755                 case SSL_TLSEXT_ERR_NOACK:
2756                         s->servername_done=0;
2757                         default:
2758                 return 1;
2759                 }
2760         }
2761
2762 int ssl_check_serverhello_tlsext(SSL *s)
2763         {
2764         int ret=SSL_TLSEXT_ERR_NOACK;
2765         int al = SSL_AD_UNRECOGNIZED_NAME;
2766
2767 #ifndef OPENSSL_NO_EC
2768         /* If we are client and using an elliptic curve cryptography cipher
2769          * suite, then if server returns an EC point formats lists extension
2770          * it must contain uncompressed.
2771          */
2772         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2773         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2774         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
2775             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
2776             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
2777                 {
2778                 /* we are using an ECC cipher */
2779                 size_t i;
2780                 unsigned char *list;
2781                 int found_uncompressed = 0;
2782                 list = s->session->tlsext_ecpointformatlist;
2783                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2784                         {
2785                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
2786                                 {
2787                                 found_uncompressed = 1;
2788                                 break;
2789                                 }
2790                         }
2791                 if (!found_uncompressed)
2792                         {
2793                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2794                         return -1;
2795                         }
2796                 }
2797         ret = SSL_TLSEXT_ERR_OK;
2798 #endif /* OPENSSL_NO_EC */
2799
2800         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2801                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2802         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2803                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2804
2805 #ifdef TLSEXT_TYPE_opaque_prf_input
2806         if (s->s3->server_opaque_prf_input_len > 0)
2807                 {
2808                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
2809                  * So first verify that we really have a value from the server too. */
2810
2811                 if (s->s3->server_opaque_prf_input == NULL)
2812                         {
2813                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2814                         al = SSL_AD_HANDSHAKE_FAILURE;
2815                         }
2816                 
2817                 /* Anytime the server *has* sent an opaque PRF input, we need to check
2818                  * that we have a client opaque PRF input of the same size. */
2819                 if (s->s3->client_opaque_prf_input == NULL ||
2820                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
2821                         {
2822                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2823                         al = SSL_AD_ILLEGAL_PARAMETER;
2824                         }
2825                 }
2826 #endif
2827
2828         /* If we've requested certificate status and we wont get one
2829          * tell the callback
2830          */
2831         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
2832                         && s->ctx && s->ctx->tlsext_status_cb)
2833                 {
2834                 int r;
2835                 /* Set resp to NULL, resplen to -1 so callback knows
2836                  * there is no response.
2837                  */
2838                 if (s->tlsext_ocsp_resp)
2839                         {
2840                         OPENSSL_free(s->tlsext_ocsp_resp);
2841                         s->tlsext_ocsp_resp = NULL;
2842                         }
2843                 s->tlsext_ocsp_resplen = -1;
2844                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2845                 if (r == 0)
2846                         {
2847                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2848                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2849                         }
2850                 if (r < 0)
2851                         {
2852                         al = SSL_AD_INTERNAL_ERROR;
2853                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2854                         }
2855                 }
2856
2857         switch (ret)
2858                 {
2859                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2860                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2861                         return -1;
2862
2863                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2864                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2865                         return 1; 
2866                                         
2867                 case SSL_TLSEXT_ERR_NOACK:
2868                         s->servername_done=0;
2869                         default:
2870                 return 1;
2871                 }
2872         }
2873
2874 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2875         {
2876         int al = -1;
2877         if (s->version < SSL3_VERSION)
2878                 return 1;
2879         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
2880                 {
2881                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2882                 return 0;
2883                 }
2884
2885         if (ssl_check_serverhello_tlsext(s) <= 0) 
2886                 {
2887                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
2888                 return 0;
2889                 }
2890         return 1;
2891 }
2892
2893 /* Since the server cache lookup is done early on in the processing of the
2894  * ClientHello, and other operations depend on the result, we need to handle
2895  * any TLS session ticket extension at the same time.
2896  *
2897  *   session_id: points at the session ID in the ClientHello. This code will
2898  *       read past the end of this in order to parse out the session ticket
2899  *       extension, if any.
2900  *   len: the length of the session ID.
2901  *   limit: a pointer to the first byte after the ClientHello.
2902  *   ret: (output) on return, if a ticket was decrypted, then this is set to
2903  *       point to the resulting session.
2904  *
2905  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2906  * ciphersuite, in which case we have no use for session tickets and one will
2907  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2908  *
2909  * Returns:
2910  *   -1: fatal error, either from parsing or decrypting the ticket.
2911  *    0: no ticket was found (or was ignored, based on settings).
2912  *    1: a zero length extension was found, indicating that the client supports
2913  *       session tickets but doesn't currently have one to offer.
2914  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
2915  *       couldn't be decrypted because of a non-fatal error.
2916  *    3: a ticket was successfully decrypted and *ret was set.
2917  *
2918  * Side effects:
2919  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
2920  *   a new session ticket to the client because the client indicated support
2921  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
2922  *   a session ticket or we couldn't use the one it gave us, or if
2923  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
2924  *   Otherwise, s->tlsext_ticket_expected is set to 0.
2925  */
2926 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
2927                         const unsigned char *limit, SSL_SESSION **ret)
2928         {
2929         /* Point after session ID in client hello */
2930         const unsigned char *p = session_id + len;
2931         unsigned short i;
2932
2933         *ret = NULL;
2934         s->tlsext_ticket_expected = 0;
2935
2936         /* If tickets disabled behave as if no ticket present
2937          * to permit stateful resumption.
2938          */
2939         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
2940                 return 0;
2941         if ((s->version <= SSL3_VERSION) || !limit)
2942                 return 0;
2943         if (p >= limit)
2944                 return -1;
2945         /* Skip past DTLS cookie */
2946         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
2947                 {
2948                 i = *(p++);
2949                 p+= i;
2950                 if (p >= limit)
2951                         return -1;
2952                 }
2953         /* Skip past cipher list */
2954         n2s(p, i);
2955         p+= i;
2956         if (p >= limit)
2957                 return -1;
2958         /* Skip past compression algorithm list */
2959         i = *(p++);
2960         p += i;
2961         if (p > limit)
2962                 return -1;
2963         /* Now at start of extensions */
2964         if ((p + 2) >= limit)
2965                 return 0;
2966         n2s(p, i);
2967         while ((p + 4) <= limit)
2968                 {
2969                 unsigned short type, size;
2970                 n2s(p, type);
2971                 n2s(p, size);
2972                 if (p + size > limit)
2973                         return 0;
2974                 if (type == TLSEXT_TYPE_session_ticket)
2975                         {
2976                         int r;
2977                         if (size == 0)
2978                                 {
2979                                 /* The client will accept a ticket but doesn't
2980                                  * currently have one. */
2981                                 s->tlsext_ticket_expected = 1;
2982                                 return 1;
2983                                 }
2984                         if (s->tls_session_secret_cb)
2985                                 {
2986                                 /* Indicate that the ticket couldn't be
2987                                  * decrypted rather than generating the session
2988                                  * from ticket now, trigger abbreviated
2989                                  * handshake based on external mechanism to
2990                                  * calculate the master secret later. */
2991                                 return 2;
2992                                 }
2993                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
2994                         switch (r)
2995                                 {
2996                                 case 2: /* ticket couldn't be decrypted */
2997                                         s->tlsext_ticket_expected = 1;
2998                                         return 2;
2999                                 case 3: /* ticket was decrypted */
3000                                         return r;
3001                                 case 4: /* ticket decrypted but need to renew */
3002                                         s->tlsext_ticket_expected = 1;
3003                                         return 3;
3004                                 default: /* fatal error */
3005                                         return -1;
3006                                 }
3007                         }
3008                 p += size;
3009                 }
3010         return 0;
3011         }
3012
3013 /* tls_decrypt_ticket attempts to decrypt a session ticket.
3014  *
3015  *   etick: points to the body of the session ticket extension.
3016  *   eticklen: the length of the session tickets extenion.
3017  *   sess_id: points at the session ID.
3018  *   sesslen: the length of the session ID.
3019  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3020  *       point to the resulting session.
3021  *
3022  * Returns:
3023  *   -1: fatal error, either from parsing or decrypting the ticket.
3024  *    2: the ticket couldn't be decrypted.
3025  *    3: a ticket was successfully decrypted and *psess was set.
3026  *    4: same as 3, but the ticket needs to be renewed.
3027  */
3028 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3029                                 const unsigned char *sess_id, int sesslen,
3030                                 SSL_SESSION **psess)
3031         {
3032         SSL_SESSION *sess;
3033         unsigned char *sdec;
3034         const unsigned char *p;
3035         int slen, mlen, renew_ticket = 0;
3036         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3037         HMAC_CTX hctx;
3038         EVP_CIPHER_CTX ctx;
3039         SSL_CTX *tctx = s->initial_ctx;
3040         /* Need at least keyname + iv + some encrypted data */
3041         if (eticklen < 48)
3042                 return 2;
3043         /* Initialize session ticket encryption and HMAC contexts */