e0f3425c5af9b5423d105875ce05164164eca620
[openssl.git] / ssl / t1_lib.c
1 /* ssl/t1_lib.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include <openssl/objects.h>
114 #include <openssl/evp.h>
115 #include <openssl/hmac.h>
116 #include <openssl/ocsp.h>
117 #include <openssl/rand.h>
118 #include "ssl_locl.h"
119
120 const char tls1_version_str[]="TLSv1" OPENSSL_VERSION_PTEXT;
121
122 #ifndef OPENSSL_NO_TLSEXT
123 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
124                                 const unsigned char *sess_id, int sesslen,
125                                 SSL_SESSION **psess);
126 static int ssl_check_clienthello_tlsext_early(SSL *s);
127 int ssl_check_serverhello_tlsext(SSL *s);
128 #endif
129
130 SSL3_ENC_METHOD TLSv1_enc_data={
131         tls1_enc,
132         tls1_mac,
133         tls1_setup_key_block,
134         tls1_generate_master_secret,
135         tls1_change_cipher_state,
136         tls1_final_finish_mac,
137         TLS1_FINISH_MAC_LENGTH,
138         tls1_cert_verify_mac,
139         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
140         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
141         tls1_alert_code,
142         tls1_export_keying_material,
143         };
144
145 long tls1_default_timeout(void)
146         {
147         /* 2 hours, the 24 hours mentioned in the TLSv1 spec
148          * is way too long for http, the cache would over fill */
149         return(60*60*2);
150         }
151
152 int tls1_new(SSL *s)
153         {
154         if (!ssl3_new(s)) return(0);
155         s->method->ssl_clear(s);
156         return(1);
157         }
158
159 void tls1_free(SSL *s)
160         {
161 #ifndef OPENSSL_NO_TLSEXT
162         if (s->tlsext_session_ticket)
163                 {
164                 OPENSSL_free(s->tlsext_session_ticket);
165                 }
166 #endif /* OPENSSL_NO_TLSEXT */
167         ssl3_free(s);
168         }
169
170 void tls1_clear(SSL *s)
171         {
172         ssl3_clear(s);
173         s->version = s->method->version;
174         }
175
176 #ifndef OPENSSL_NO_EC
177
178 static int nid_list[] =
179         {
180                 NID_sect163k1, /* sect163k1 (1) */
181                 NID_sect163r1, /* sect163r1 (2) */
182                 NID_sect163r2, /* sect163r2 (3) */
183                 NID_sect193r1, /* sect193r1 (4) */ 
184                 NID_sect193r2, /* sect193r2 (5) */ 
185                 NID_sect233k1, /* sect233k1 (6) */
186                 NID_sect233r1, /* sect233r1 (7) */ 
187                 NID_sect239k1, /* sect239k1 (8) */ 
188                 NID_sect283k1, /* sect283k1 (9) */
189                 NID_sect283r1, /* sect283r1 (10) */ 
190                 NID_sect409k1, /* sect409k1 (11) */ 
191                 NID_sect409r1, /* sect409r1 (12) */
192                 NID_sect571k1, /* sect571k1 (13) */ 
193                 NID_sect571r1, /* sect571r1 (14) */ 
194                 NID_secp160k1, /* secp160k1 (15) */
195                 NID_secp160r1, /* secp160r1 (16) */ 
196                 NID_secp160r2, /* secp160r2 (17) */ 
197                 NID_secp192k1, /* secp192k1 (18) */
198                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
199                 NID_secp224k1, /* secp224k1 (20) */ 
200                 NID_secp224r1, /* secp224r1 (21) */
201                 NID_secp256k1, /* secp256k1 (22) */ 
202                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
203                 NID_secp384r1, /* secp384r1 (24) */
204                 NID_secp521r1  /* secp521r1 (25) */     
205         };
206
207
208 static const unsigned char ecformats_default[] = 
209         {
210         TLSEXT_ECPOINTFORMAT_uncompressed,
211         TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
212         TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
213         };
214
215 static const unsigned char eccurves_default[] =
216         {
217                 0,14, /* sect571r1 (14) */ 
218                 0,13, /* sect571k1 (13) */ 
219                 0,25, /* secp521r1 (25) */      
220                 0,11, /* sect409k1 (11) */ 
221                 0,12, /* sect409r1 (12) */
222                 0,24, /* secp384r1 (24) */
223                 0,9,  /* sect283k1 (9) */
224                 0,10, /* sect283r1 (10) */ 
225                 0,22, /* secp256k1 (22) */ 
226                 0,23, /* secp256r1 (23) */ 
227                 0,8,  /* sect239k1 (8) */ 
228                 0,6,  /* sect233k1 (6) */
229                 0,7,  /* sect233r1 (7) */ 
230                 0,20, /* secp224k1 (20) */ 
231                 0,21, /* secp224r1 (21) */
232                 0,4,  /* sect193r1 (4) */ 
233                 0,5,  /* sect193r2 (5) */ 
234                 0,18, /* secp192k1 (18) */
235                 0,19, /* secp192r1 (19) */ 
236                 0,1,  /* sect163k1 (1) */
237                 0,2,  /* sect163r1 (2) */
238                 0,3,  /* sect163r2 (3) */
239                 0,15, /* secp160k1 (15) */
240                 0,16, /* secp160r1 (16) */ 
241                 0,17, /* secp160r2 (17) */ 
242         };
243
244 static const unsigned char suiteb_curves[] =
245         {
246                 0, TLSEXT_curve_P_256,
247                 0, TLSEXT_curve_P_384
248         };
249
250 int tls1_ec_curve_id2nid(int curve_id)
251         {
252         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
253         if ((curve_id < 1) || ((unsigned int)curve_id >
254                                 sizeof(nid_list)/sizeof(nid_list[0])))
255                 return 0;
256         return nid_list[curve_id-1];
257         }
258
259 int tls1_ec_nid2curve_id(int nid)
260         {
261         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
262         switch (nid)
263                 {
264         case NID_sect163k1: /* sect163k1 (1) */
265                 return 1;
266         case NID_sect163r1: /* sect163r1 (2) */
267                 return 2;
268         case NID_sect163r2: /* sect163r2 (3) */
269                 return 3;
270         case NID_sect193r1: /* sect193r1 (4) */ 
271                 return 4;
272         case NID_sect193r2: /* sect193r2 (5) */ 
273                 return 5;
274         case NID_sect233k1: /* sect233k1 (6) */
275                 return 6;
276         case NID_sect233r1: /* sect233r1 (7) */ 
277                 return 7;
278         case NID_sect239k1: /* sect239k1 (8) */ 
279                 return 8;
280         case NID_sect283k1: /* sect283k1 (9) */
281                 return 9;
282         case NID_sect283r1: /* sect283r1 (10) */ 
283                 return 10;
284         case NID_sect409k1: /* sect409k1 (11) */ 
285                 return 11;
286         case NID_sect409r1: /* sect409r1 (12) */
287                 return 12;
288         case NID_sect571k1: /* sect571k1 (13) */ 
289                 return 13;
290         case NID_sect571r1: /* sect571r1 (14) */ 
291                 return 14;
292         case NID_secp160k1: /* secp160k1 (15) */
293                 return 15;
294         case NID_secp160r1: /* secp160r1 (16) */ 
295                 return 16;
296         case NID_secp160r2: /* secp160r2 (17) */ 
297                 return 17;
298         case NID_secp192k1: /* secp192k1 (18) */
299                 return 18;
300         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
301                 return 19;
302         case NID_secp224k1: /* secp224k1 (20) */ 
303                 return 20;
304         case NID_secp224r1: /* secp224r1 (21) */
305                 return 21;
306         case NID_secp256k1: /* secp256k1 (22) */ 
307                 return 22;
308         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
309                 return 23;
310         case NID_secp384r1: /* secp384r1 (24) */
311                 return 24;
312         case NID_secp521r1:  /* secp521r1 (25) */       
313                 return 25;
314         default:
315                 return 0;
316                 }
317         }
318 /* Get curves list, if "sess" is set return client curves otherwise
319  * preferred list
320  */
321 static void tls1_get_curvelist(SSL *s, int sess,
322                                         const unsigned char **pcurves,
323                                         size_t *pcurveslen)
324         {
325         if (sess)
326                 {
327                 *pcurves = s->session->tlsext_ellipticcurvelist;
328                 *pcurveslen = s->session->tlsext_ellipticcurvelist_length;
329                 return;
330                 }
331         /* For Suite B mode only include P-256, P-384 */
332         switch (tls1_suiteb(s))
333                 {
334         case SSL_CERT_FLAG_SUITEB_128_LOS:
335                 *pcurves = suiteb_curves;
336                 *pcurveslen = sizeof(suiteb_curves);
337                 break;
338
339         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
340                 *pcurves = suiteb_curves;
341                 *pcurveslen = 2;
342                 break;
343
344         case SSL_CERT_FLAG_SUITEB_192_LOS:
345                 *pcurves = suiteb_curves + 2;
346                 *pcurveslen = 2;
347                 break;
348         default:
349                 *pcurves = s->tlsext_ellipticcurvelist;
350                 *pcurveslen = s->tlsext_ellipticcurvelist_length;
351                 }
352         if (!*pcurves)
353                 {
354                 *pcurves = eccurves_default;
355                 *pcurveslen = sizeof(eccurves_default);
356                 }
357         }
358 /* Check a curve is one of our preferences */
359 int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
360         {
361         const unsigned char *curves;
362         size_t curveslen, i;
363         unsigned int suiteb_flags = tls1_suiteb(s);
364         if (len != 3 || p[0] != NAMED_CURVE_TYPE)
365                 return 0;
366         /* Check curve matches Suite B preferences */
367         if (suiteb_flags)
368                 {
369                 unsigned long cid = s->s3->tmp.new_cipher->id;
370                 if (p[1])
371                         return 0;
372                 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
373                         {
374                         if (p[2] != TLSEXT_curve_P_256)
375                                 return 0;
376                         }
377                 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
378                         {
379                         if (p[2] != TLSEXT_curve_P_384)
380                                 return 0;
381                         }
382                 else    /* Should never happen */
383                         return 0;
384                 }
385         tls1_get_curvelist(s, 0, &curves, &curveslen);
386         for (i = 0; i < curveslen; i += 2, curves += 2)
387                 {
388                 if (p[1] == curves[0] && p[2] == curves[1])
389                         return 1;
390                 }
391         return 0;
392         }
393
394 /* Return nth shared curve. If nmatch == -1 return number of
395  * matches. For nmatch == -2 return the NID of the curve to use for
396  * an EC tmp key.
397  */
398
399 int tls1_shared_curve(SSL *s, int nmatch)
400         {
401         const unsigned char *pref, *supp;
402         size_t preflen, supplen, i, j;
403         int k;
404         /* Can't do anything on client side */
405         if (s->server == 0)
406                 return -1;
407         if (nmatch == -2)
408                 {
409                 if (tls1_suiteb(s))
410                         {
411                         /* For Suite B ciphersuite determines curve: we 
412                          * already know these are acceptable due to previous
413                          * checks.
414                          */
415                         unsigned long cid = s->s3->tmp.new_cipher->id;
416                         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
417                                 return NID_X9_62_prime256v1; /* P-256 */
418                         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
419                                 return NID_secp384r1; /* P-384 */
420                         /* Should never happen */
421                         return NID_undef;
422                         }
423                 /* If not Suite B just return first preference shared curve */
424                 nmatch = 0;
425                 }
426         tls1_get_curvelist(s, !!(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
427                                 &supp, &supplen);
428         tls1_get_curvelist(s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
429                                 &pref, &preflen);
430         preflen /= 2;
431         supplen /= 2;
432         k = 0;
433         for (i = 0; i < preflen; i++, pref+=2)
434                 {
435                 const unsigned char *tsupp = supp;
436                 for (j = 0; j < supplen; j++, tsupp+=2)
437                         {
438                         if (pref[0] == tsupp[0] && pref[1] == tsupp[1])
439                                 {
440                                 if (nmatch == k)
441                                         {
442                                         int id = (pref[0] << 8) | pref[1];
443                                         return tls1_ec_curve_id2nid(id);
444                                         }
445                                 k++;
446                                 }
447                         }
448                 }
449         if (nmatch == -1)
450                 return k;
451         return 0;
452         }
453
454 int tls1_set_curves(unsigned char **pext, size_t *pextlen,
455                         int *curves, size_t ncurves)
456         {
457         unsigned char *clist, *p;
458         size_t i;
459         /* Bitmap of curves included to detect duplicates: only works
460          * while curve ids < 32 
461          */
462         unsigned long dup_list = 0;
463         clist = OPENSSL_malloc(ncurves * 2);
464         if (!clist)
465                 return 0;
466         for (i = 0, p = clist; i < ncurves; i++)
467                 {
468                 unsigned long idmask;
469                 int id;
470                 id = tls1_ec_nid2curve_id(curves[i]);
471                 idmask = 1L << id;
472                 if (!id || (dup_list & idmask))
473                         {
474                         OPENSSL_free(clist);
475                         return 0;
476                         }
477                 dup_list |= idmask;
478                 s2n(id, p);
479                 }
480         if (*pext)
481                 OPENSSL_free(*pext);
482         *pext = clist;
483         *pextlen = ncurves * 2;
484         return 1;
485         }
486
487 #define MAX_CURVELIST   25
488
489 typedef struct
490         {
491         size_t nidcnt;
492         int nid_arr[MAX_CURVELIST];
493         } nid_cb_st;
494
495 static int nid_cb(const char *elem, int len, void *arg)
496         {
497         nid_cb_st *narg = arg;
498         size_t i;
499         int nid;
500         char etmp[20];
501         if (narg->nidcnt == MAX_CURVELIST)
502                 return 0;
503         if (len > (int)(sizeof(etmp) - 1))
504                 return 0;
505         memcpy(etmp, elem, len);
506         etmp[len] = 0;
507         nid = EC_curve_nist2nid(etmp);
508         if (nid == NID_undef)
509                 nid = OBJ_sn2nid(etmp);
510         if (nid == NID_undef)
511                 nid = OBJ_ln2nid(etmp);
512         if (nid == NID_undef)
513                 return 0;
514         for (i = 0; i < narg->nidcnt; i++)
515                 if (narg->nid_arr[i] == nid)
516                         return 0;
517         narg->nid_arr[narg->nidcnt++] = nid;
518         return 1;
519         }
520 /* Set curves based on a colon separate list */
521 int tls1_set_curves_list(unsigned char **pext, size_t *pextlen, 
522                                 const char *str)
523         {
524         nid_cb_st ncb;
525         ncb.nidcnt = 0;
526         if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
527                 return 0;
528         if (pext == NULL)
529                 return 1;
530         return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
531         }
532 /* For an EC key set TLS id and required compression based on parameters */
533 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
534                                 EC_KEY *ec)
535         {
536         int is_prime, id;
537         const EC_GROUP *grp;
538         const EC_POINT *pt;
539         const EC_METHOD *meth;
540         if (!ec)
541                 return 0;
542         /* Determine if it is a prime field */
543         grp = EC_KEY_get0_group(ec);
544         pt = EC_KEY_get0_public_key(ec);
545         if (!grp || !pt)
546                 return 0;
547         meth = EC_GROUP_method_of(grp);
548         if (!meth)
549                 return 0;
550         if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
551                 is_prime = 1;
552         else
553                 is_prime = 0;
554         /* Determine curve ID */
555         id = EC_GROUP_get_curve_name(grp);
556         id = tls1_ec_nid2curve_id(id);
557         /* If we have an ID set it, otherwise set arbitrary explicit curve */
558         if (id)
559                 {
560                 curve_id[0] = 0;
561                 curve_id[1] = (unsigned char)id;
562                 }
563         else
564                 {
565                 curve_id[0] = 0xff;
566                 if (is_prime)
567                         curve_id[1] = 0x01;
568                 else
569                         curve_id[1] = 0x02;
570                 }
571         if (comp_id)
572                 {
573                 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
574                         {
575                         if (is_prime)
576                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
577                         else
578                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
579                         }
580                 else
581                         *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
582                 }
583         return 1;
584         }
585 /* Check an EC key is compatible with extensions */
586 static int tls1_check_ec_key(SSL *s,
587                         unsigned char *curve_id, unsigned char *comp_id)
588         {
589         const unsigned char *p;
590         size_t plen, i;
591         int j;
592         /* If point formats extension present check it, otherwise everything
593          * is supported (see RFC4492).
594          */
595         if (comp_id && s->session->tlsext_ecpointformatlist)
596                 {
597                 p = s->session->tlsext_ecpointformatlist;
598                 plen = s->session->tlsext_ecpointformatlist_length;
599                 for (i = 0; i < plen; i++, p++)
600                         {
601                         if (*comp_id == *p)
602                                 break;
603                         }
604                 if (i == plen)
605                         return 0;
606                 }
607         if (!curve_id)
608                 return 1;
609         /* Check curve is consistent with client and server preferences */
610         for (j = 0; j <= 1; j++)
611                 {
612                 tls1_get_curvelist(s, j, &p, &plen);
613                 for (i = 0; i < plen; i+=2, p+=2)
614                         {
615                         if (p[0] == curve_id[0] && p[1] == curve_id[1])
616                                 break;
617                         }
618                 if (i == plen)
619                         return 0;
620                 /* For clients can only check sent curve list */
621                 if (!s->server)
622                         return 1;
623                 }
624         return 1;
625         }
626
627 static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
628                                         size_t *pformatslen)
629         {
630         /* If we have a custom point format list use it otherwise
631          * use default */
632         if (s->tlsext_ecpointformatlist)
633                 {
634                 *pformats = s->tlsext_ecpointformatlist;
635                 *pformatslen = s->tlsext_ecpointformatlist_length;
636                 }
637         else
638                 {
639                 *pformats = ecformats_default;
640                 /* For Suite B we don't support char2 fields */
641                 if (tls1_suiteb(s))
642                         *pformatslen = sizeof(ecformats_default) - 1;
643                 else
644                         *pformatslen = sizeof(ecformats_default);
645                 }
646         }
647
648 /* Check cert parameters compatible with extensions: currently just checks
649  * EC certificates have compatible curves and compression.
650  */
651 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
652         {
653         unsigned char comp_id, curve_id[2];
654         EVP_PKEY *pkey;
655         int rv;
656         pkey = X509_get_pubkey(x);
657         if (!pkey)
658                 return 0;
659         /* If not EC nothing to do */
660         if (pkey->type != EVP_PKEY_EC)
661                 {
662                 EVP_PKEY_free(pkey);
663                 return 1;
664                 }
665         rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
666         EVP_PKEY_free(pkey);
667         if (!rv)
668                 return 0;
669         /* Can't check curve_id for client certs as we don't have a
670          * supported curves extension.
671          */
672         rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
673         if (!rv)
674                 return 0;
675         /* Special case for suite B. We *MUST* sign using SHA256+P-256 or
676          * SHA384+P-384, adjust digest if necessary.
677          */
678         if (set_ee_md && tls1_suiteb(s))
679                 {
680                 int check_md;
681                 size_t i;
682                 CERT *c = s->cert;
683                 if (curve_id[0])
684                         return 0;
685                 /* Check to see we have necessary signing algorithm */
686                 if (curve_id[1] == TLSEXT_curve_P_256)
687                         check_md = NID_ecdsa_with_SHA256;
688                 else if (curve_id[1] == TLSEXT_curve_P_384)
689                         check_md = NID_ecdsa_with_SHA384;
690                 else
691                         return 0; /* Should never happen */
692                 for (i = 0; i < c->shared_sigalgslen; i++)
693                         if (check_md == c->shared_sigalgs[i].signandhash_nid)
694                                 break;
695                 if (i == c->shared_sigalgslen)
696                         return 0;
697                 if (set_ee_md == 2)
698                         {
699                         if (check_md == NID_ecdsa_with_SHA256)
700                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
701                         else
702                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
703                         }
704                 }
705         return rv;
706         }
707 /* Check EC temporary key is compatible with client extensions */
708 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
709         {
710         unsigned char curve_id[2];
711         EC_KEY *ec = s->cert->ecdh_tmp;
712 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
713         /* Allow any curve: not just those peer supports */
714         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
715                 return 1;
716 #endif
717         /* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384,
718          * no other curves permitted.
719          */
720         if (tls1_suiteb(s))
721                 {
722                 /* Curve to check determined by ciphersuite */
723                 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
724                         curve_id[1] = TLSEXT_curve_P_256;
725                 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
726                         curve_id[1] = TLSEXT_curve_P_384;
727                 else
728                         return 0;
729                 curve_id[0] = 0;
730                 /* Check this curve is acceptable */
731                 if (!tls1_check_ec_key(s, curve_id, NULL))
732                         return 0;
733                 /* If auto or setting curve from callback assume OK */
734                 if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
735                         return 1;
736                 /* Otherwise check curve is acceptable */
737                 else 
738                         {
739                         unsigned char curve_tmp[2];
740                         if (!ec)
741                                 return 0;
742                         if (!tls1_set_ec_id(curve_tmp, NULL, ec))
743                                 return 0;
744                         if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
745                                 return 1;
746                         return 0;
747                         }
748                         
749                 }
750         if (s->cert->ecdh_tmp_auto)
751                 {
752                 /* Need a shared curve */
753                 if (tls1_shared_curve(s, 0))
754                         return 1;
755                 else return 0;
756                 }
757         if (!ec)
758                 {
759                 if (s->cert->ecdh_tmp_cb)
760                         return 1;
761                 else
762                         return 0;
763                 }
764         if (!tls1_set_ec_id(curve_id, NULL, ec))
765                 return 0;
766 /* Set this to allow use of invalid curves for testing */
767 #if 0
768         return 1;
769 #else
770         return tls1_check_ec_key(s, curve_id, NULL);
771 #endif
772         }
773
774 #endif /* OPENSSL_NO_EC */
775
776 #ifndef OPENSSL_NO_TLSEXT
777
778 /* List of supported signature algorithms and hashes. Should make this
779  * customisable at some point, for now include everything we support.
780  */
781
782 #ifdef OPENSSL_NO_RSA
783 #define tlsext_sigalg_rsa(md) /* */
784 #else
785 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
786 #endif
787
788 #ifdef OPENSSL_NO_DSA
789 #define tlsext_sigalg_dsa(md) /* */
790 #else
791 #define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
792 #endif
793
794 #ifdef OPENSSL_NO_ECDSA
795 #define tlsext_sigalg_ecdsa(md) /* */
796 #else
797 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
798 #endif
799
800 #define tlsext_sigalg(md) \
801                 tlsext_sigalg_rsa(md) \
802                 tlsext_sigalg_dsa(md) \
803                 tlsext_sigalg_ecdsa(md)
804
805 static unsigned char tls12_sigalgs[] = {
806 #ifndef OPENSSL_NO_SHA512
807         tlsext_sigalg(TLSEXT_hash_sha512)
808         tlsext_sigalg(TLSEXT_hash_sha384)
809 #endif
810 #ifndef OPENSSL_NO_SHA256
811         tlsext_sigalg(TLSEXT_hash_sha256)
812         tlsext_sigalg(TLSEXT_hash_sha224)
813 #endif
814 #ifndef OPENSSL_NO_SHA
815         tlsext_sigalg(TLSEXT_hash_sha1)
816 #endif
817 #ifndef OPENSSL_NO_MD5
818         tlsext_sigalg_rsa(TLSEXT_hash_md5)
819 #endif
820 };
821
822 static unsigned char suiteb_sigalgs[] = {
823         tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
824         tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
825 };
826
827 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
828         {
829         /* If Suite B mode use Suite B sigalgs only, ignore any other
830          * preferences.
831          */
832         switch (tls1_suiteb(s))
833                 {
834         case SSL_CERT_FLAG_SUITEB_128_LOS:
835                 *psigs = suiteb_sigalgs;
836                 return sizeof(suiteb_sigalgs);
837
838         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
839                 *psigs = suiteb_sigalgs;
840                 return 2;
841
842         case SSL_CERT_FLAG_SUITEB_192_LOS:
843                 *psigs = suiteb_sigalgs + 2;
844                 return 2;
845                 }
846
847         /* If server use client authentication sigalgs if not NULL */
848         if (s->server && s->cert->client_sigalgs)
849                 {
850                 *psigs = s->cert->client_sigalgs;
851                 return s->cert->client_sigalgslen;
852                 }
853         else if (s->cert->conf_sigalgs)
854                 {
855                 *psigs = s->cert->conf_sigalgs;
856                 return s->cert->conf_sigalgslen;
857                 }
858         else
859                 {
860                 *psigs = tls12_sigalgs;
861 #ifdef OPENSSL_FIPS
862                 /* If FIPS mode don't include MD5 which is last */
863                 if (FIPS_mode())
864                         return sizeof(tls12_sigalgs) - 2;
865                 else
866 #endif
867                         return sizeof(tls12_sigalgs);
868                 }
869         }
870 /* Check signature algorithm is consistent with sent supported signature
871  * algorithms and if so return relevant digest.
872  */
873 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
874                                 const unsigned char *sig, EVP_PKEY *pkey)
875         {
876         const unsigned char *sent_sigs;
877         size_t sent_sigslen, i;
878         int sigalg = tls12_get_sigid(pkey);
879         /* Should never happen */
880         if (sigalg == -1)
881                 return -1;
882         /* Check key type is consistent with signature */
883         if (sigalg != (int)sig[1])
884                 {
885                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
886                 return 0;
887                 }
888         if (pkey->type == EVP_PKEY_EC)
889                 {
890                 unsigned char curve_id[2], comp_id;
891                 /* Check compression and curve matches extensions */
892                 if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
893                         return 0;
894                 if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id))
895                         {
896                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_CURVE);
897                         return 0;
898                         }
899                 /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
900                 if (tls1_suiteb(s))
901                         {
902                         if (curve_id[0])
903                                 return 0;
904                         if (curve_id[1] == TLSEXT_curve_P_256)
905                                 {
906                                 if (sig[0] != TLSEXT_hash_sha256)
907                                         {
908                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
909                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
910                                         return 0;
911                                         }
912                                 }
913                         else if (curve_id[1] == TLSEXT_curve_P_384)
914                                 {
915                                 if (sig[0] != TLSEXT_hash_sha384)
916                                         {
917                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
918                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
919                                         return 0;
920                                         }
921                                 }
922                         else
923                                 return 0;
924                         }
925                 }
926         else if (tls1_suiteb(s))
927                 return 0;
928
929         /* Check signature matches a type we sent */
930         sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
931         for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
932                 {
933                 if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
934                         break;
935                 }
936         /* Allow fallback to SHA1 if not strict mode */
937         if (i == sent_sigslen && (sig[0] != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
938                 {
939                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
940                 return 0;
941                 }
942         *pmd = tls12_get_hash(sig[0]);
943         if (*pmd == NULL)
944                 {
945                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_UNKNOWN_DIGEST);
946                 return 0;
947                 }
948         /* Store the digest used so applications can retrieve it if they
949          * wish.
950          */
951         if (s->session && s->session->sess_cert)
952                 s->session->sess_cert->peer_key->digest = *pmd;
953         return 1;
954         }
955 /* Get a mask of disabled algorithms: an algorithm is disabled
956  * if it isn't supported or doesn't appear in supported signature
957  * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
958  * session and not global settings.
959  * 
960  */
961 void ssl_set_client_disabled(SSL *s)
962         {
963         CERT *c = s->cert;
964         const unsigned char *sigalgs;
965         size_t i, sigalgslen;
966         int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
967         c->mask_a = 0;
968         c->mask_k = 0;
969         /* If less than TLS 1.2 don't allow TLS 1.2 only ciphers */
970         if (TLS1_get_version(s) < TLS1_2_VERSION)
971                 c->mask_ssl = SSL_TLSV1_2;
972         else
973                 c->mask_ssl = 0;
974         /* Now go through all signature algorithms seeing if we support
975          * any for RSA, DSA, ECDSA. Do this for all versions not just
976          * TLS 1.2.
977          */
978         sigalgslen = tls12_get_psigalgs(s, &sigalgs);
979         for (i = 0; i < sigalgslen; i += 2, sigalgs += 2)
980                 {
981                 switch(sigalgs[1])
982                         {
983 #ifndef OPENSSL_NO_RSA
984                 case TLSEXT_signature_rsa:
985                         have_rsa = 1;
986                         break;
987 #endif
988 #ifndef OPENSSL_NO_DSA
989                 case TLSEXT_signature_dsa:
990                         have_dsa = 1;
991                         break;
992 #endif
993 #ifndef OPENSSL_NO_ECDSA
994                 case TLSEXT_signature_ecdsa:
995                         have_ecdsa = 1;
996                         break;
997 #endif
998                         }
999                 }
1000         /* Disable auth and static DH if we don't include any appropriate
1001          * signature algorithms.
1002          */
1003         if (!have_rsa)
1004                 {
1005                 c->mask_a |= SSL_aRSA;
1006                 c->mask_k |= SSL_kDHr|SSL_kECDHr;
1007                 }
1008         if (!have_dsa)
1009                 {
1010                 c->mask_a |= SSL_aDSS;
1011                 c->mask_k |= SSL_kDHd;
1012                 }
1013         if (!have_ecdsa)
1014                 {
1015                 c->mask_a |= SSL_aECDSA;
1016                 c->mask_k |= SSL_kECDHe;
1017                 }
1018 #ifndef OPENSSL_NO_KRB5
1019         if (!kssl_tgt_is_available(s->kssl_ctx))
1020                 {
1021                 c->mask_a |= SSL_aKRB5;
1022                 c->mask_k |= SSL_kKRB5;
1023                 }
1024 #endif
1025 #ifndef OPENSSL_NO_PSK
1026         /* with PSK there must be client callback set */
1027         if (!s->psk_client_callback)
1028                 {
1029                 c->mask_a |= SSL_aPSK;
1030                 c->mask_k |= SSL_kPSK;
1031                 }
1032 #endif /* OPENSSL_NO_PSK */
1033         c->valid = 1;
1034         }
1035
1036 /* byte_compare is a compare function for qsort(3) that compares bytes. */
1037 static int byte_compare(const void *in_a, const void *in_b)
1038         {
1039         unsigned char a = *((const unsigned char*) in_a);
1040         unsigned char b = *((const unsigned char*) in_b);
1041
1042         if (a > b)
1043                 return 1;
1044         else if (a < b)
1045                 return -1;
1046         return 0;
1047 }
1048
1049 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1050         {
1051         int extdatalen=0;
1052         unsigned char *ret = p;
1053 #ifndef OPENSSL_NO_EC
1054         /* See if we support any ECC ciphersuites */
1055         int using_ecc = 0;
1056         if (s->version != DTLS1_VERSION && s->version >= TLS1_VERSION)
1057                 {
1058                 int i;
1059                 unsigned long alg_k, alg_a;
1060                 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1061
1062                 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1063                         {
1064                         SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1065
1066                         alg_k = c->algorithm_mkey;
1067                         alg_a = c->algorithm_auth;
1068                         if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)
1069                                 || (alg_a & SSL_aECDSA)))
1070                                 {
1071                                 using_ecc = 1;
1072                                 break;
1073                                 }
1074                         }
1075                 }
1076 #endif
1077
1078         /* don't add extensions for SSLv3 unless doing secure renegotiation */
1079         if (s->client_version == SSL3_VERSION
1080                                         && !s->s3->send_connection_binding)
1081                 return p;
1082
1083         ret+=2;
1084
1085         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1086
1087         if (s->tlsext_hostname != NULL)
1088                 { 
1089                 /* Add TLS extension servername to the Client Hello message */
1090                 unsigned long size_str;
1091                 long lenmax; 
1092
1093                 /* check for enough space.
1094                    4 for the servername type and entension length
1095                    2 for servernamelist length
1096                    1 for the hostname type
1097                    2 for hostname length
1098                    + hostname length 
1099                 */
1100                    
1101                 if ((lenmax = limit - ret - 9) < 0 
1102                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
1103                         return NULL;
1104                         
1105                 /* extension type and length */
1106                 s2n(TLSEXT_TYPE_server_name,ret); 
1107                 s2n(size_str+5,ret);
1108                 
1109                 /* length of servername list */
1110                 s2n(size_str+3,ret);
1111         
1112                 /* hostname type, length and hostname */
1113                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
1114                 s2n(size_str,ret);
1115                 memcpy(ret, s->tlsext_hostname, size_str);
1116                 ret+=size_str;
1117                 }
1118
1119         /* Add RI if renegotiating */
1120         if (s->renegotiate)
1121           {
1122           int el;
1123           
1124           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
1125               {
1126               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1127               return NULL;
1128               }
1129
1130           if((limit - p - 4 - el) < 0) return NULL;
1131           
1132           s2n(TLSEXT_TYPE_renegotiate,ret);
1133           s2n(el,ret);
1134
1135           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
1136               {
1137               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1138               return NULL;
1139               }
1140
1141           ret += el;
1142         }
1143
1144 #ifndef OPENSSL_NO_SRP
1145         /* Add SRP username if there is one */
1146         if (s->srp_ctx.login != NULL)
1147                 { /* Add TLS extension SRP username to the Client Hello message */
1148
1149                 int login_len = strlen(s->srp_ctx.login);       
1150                 if (login_len > 255 || login_len == 0)
1151                         {
1152                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1153                         return NULL;
1154                         } 
1155
1156                 /* check for enough space.
1157                    4 for the srp type type and entension length
1158                    1 for the srp user identity
1159                    + srp user identity length 
1160                 */
1161                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
1162
1163                 /* fill in the extension */
1164                 s2n(TLSEXT_TYPE_srp,ret);
1165                 s2n(login_len+1,ret);
1166                 (*ret++) = (unsigned char) login_len;
1167                 memcpy(ret, s->srp_ctx.login, login_len);
1168                 ret+=login_len;
1169                 }
1170 #endif
1171
1172 #ifndef OPENSSL_NO_EC
1173         if (using_ecc)
1174                 {
1175                 /* Add TLS extension ECPointFormats to the ClientHello message */
1176                 long lenmax; 
1177                 const unsigned char *plist;
1178                 size_t plistlen;
1179
1180                 tls1_get_formatlist(s, &plist, &plistlen);
1181
1182                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1183                 if (plistlen > (size_t)lenmax) return NULL;
1184                 if (plistlen > 255)
1185                         {
1186                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1187                         return NULL;
1188                         }
1189                 
1190                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1191                 s2n(plistlen + 1,ret);
1192                 *(ret++) = (unsigned char)plistlen ;
1193                 memcpy(ret, plist, plistlen);
1194                 ret+=plistlen;
1195
1196                 /* Add TLS extension EllipticCurves to the ClientHello message */
1197                 plist = s->tlsext_ellipticcurvelist;
1198                 tls1_get_curvelist(s, 0, &plist, &plistlen);
1199
1200                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
1201                 if (plistlen > (size_t)lenmax) return NULL;
1202                 if (plistlen > 65532)
1203                         {
1204                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1205                         return NULL;
1206                         }
1207                 
1208                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
1209                 s2n(plistlen + 2, ret);
1210
1211                 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
1212                  * elliptic_curve_list, but the examples use two bytes.
1213                  * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
1214                  * resolves this to two bytes.
1215                  */
1216                 s2n(plistlen, ret);
1217                 memcpy(ret, plist, plistlen);
1218                 ret+=plistlen;
1219                 }
1220 #endif /* OPENSSL_NO_EC */
1221
1222         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
1223                 {
1224                 int ticklen;
1225                 if (!s->new_session && s->session && s->session->tlsext_tick)
1226                         ticklen = s->session->tlsext_ticklen;
1227                 else if (s->session && s->tlsext_session_ticket &&
1228                          s->tlsext_session_ticket->data)
1229                         {
1230                         ticklen = s->tlsext_session_ticket->length;
1231                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1232                         if (!s->session->tlsext_tick)
1233                                 return NULL;
1234                         memcpy(s->session->tlsext_tick,
1235                                s->tlsext_session_ticket->data,
1236                                ticklen);
1237                         s->session->tlsext_ticklen = ticklen;
1238                         }
1239                 else
1240                         ticklen = 0;
1241                 if (ticklen == 0 && s->tlsext_session_ticket &&
1242                     s->tlsext_session_ticket->data == NULL)
1243                         goto skip_ext;
1244                 /* Check for enough room 2 for extension type, 2 for len
1245                  * rest for ticket
1246                  */
1247                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1248                 s2n(TLSEXT_TYPE_session_ticket,ret); 
1249                 s2n(ticklen,ret);
1250                 if (ticklen)
1251                         {
1252                         memcpy(ret, s->session->tlsext_tick, ticklen);
1253                         ret += ticklen;
1254                         }
1255                 }
1256                 skip_ext:
1257
1258         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
1259                 {
1260                 size_t salglen;
1261                 const unsigned char *salg;
1262                 salglen = tls12_get_psigalgs(s, &salg);
1263                 if ((size_t)(limit - ret) < salglen + 6)
1264                         return NULL; 
1265                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1266                 s2n(salglen + 2, ret);
1267                 s2n(salglen, ret);
1268                 memcpy(ret, salg, salglen);
1269                 ret += salglen;
1270                 }
1271
1272 #ifdef TLSEXT_TYPE_opaque_prf_input
1273         if (s->s3->client_opaque_prf_input != NULL &&
1274             s->version != DTLS1_VERSION)
1275                 {
1276                 size_t col = s->s3->client_opaque_prf_input_len;
1277                 
1278                 if ((long)(limit - ret - 6 - col < 0))
1279                         return NULL;
1280                 if (col > 0xFFFD) /* can't happen */
1281                         return NULL;
1282
1283                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1284                 s2n(col + 2, ret);
1285                 s2n(col, ret);
1286                 memcpy(ret, s->s3->client_opaque_prf_input, col);
1287                 ret += col;
1288                 }
1289 #endif
1290
1291         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
1292             s->version != DTLS1_VERSION)
1293                 {
1294                 int i;
1295                 long extlen, idlen, itmp;
1296                 OCSP_RESPID *id;
1297
1298                 idlen = 0;
1299                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1300                         {
1301                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1302                         itmp = i2d_OCSP_RESPID(id, NULL);
1303                         if (itmp <= 0)
1304                                 return NULL;
1305                         idlen += itmp + 2;
1306                         }
1307
1308                 if (s->tlsext_ocsp_exts)
1309                         {
1310                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1311                         if (extlen < 0)
1312                                 return NULL;
1313                         }
1314                 else
1315                         extlen = 0;
1316                         
1317                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1318                 s2n(TLSEXT_TYPE_status_request, ret);
1319                 if (extlen + idlen > 0xFFF0)
1320                         return NULL;
1321                 s2n(extlen + idlen + 5, ret);
1322                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1323                 s2n(idlen, ret);
1324                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1325                         {
1326                         /* save position of id len */
1327                         unsigned char *q = ret;
1328                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1329                         /* skip over id len */
1330                         ret += 2;
1331                         itmp = i2d_OCSP_RESPID(id, &ret);
1332                         /* write id len */
1333                         s2n(itmp, q);
1334                         }
1335                 s2n(extlen, ret);
1336                 if (extlen > 0)
1337                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1338                 }
1339
1340 #ifndef OPENSSL_NO_HEARTBEATS
1341         /* Add Heartbeat extension */
1342         s2n(TLSEXT_TYPE_heartbeat,ret);
1343         s2n(1,ret);
1344         /* Set mode:
1345          * 1: peer may send requests
1346          * 2: peer not allowed to send requests
1347          */
1348         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1349                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1350         else
1351                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1352 #endif
1353
1354 #ifndef OPENSSL_NO_NEXTPROTONEG
1355         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1356                 {
1357                 /* The client advertises an emtpy extension to indicate its
1358                  * support for Next Protocol Negotiation */
1359                 if (limit - ret - 4 < 0)
1360                         return NULL;
1361                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1362                 s2n(0,ret);
1363                 }
1364 #endif
1365
1366         if(SSL_get_srtp_profiles(s))
1367                 {
1368                 int el;
1369
1370                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1371                 
1372                 if((limit - p - 4 - el) < 0) return NULL;
1373
1374                 s2n(TLSEXT_TYPE_use_srtp,ret);
1375                 s2n(el,ret);
1376
1377                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1378                         {
1379                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1380                         return NULL;
1381                         }
1382                 ret += el;
1383                 }
1384
1385         /* Add TLS extension Server_Authz_DataFormats to the ClientHello */
1386         /* 2 bytes for extension type */
1387         /* 2 bytes for extension length */
1388         /* 1 byte for the list length */
1389         /* 1 byte for the list (we only support audit proofs) */
1390         if (s->ctx->tlsext_authz_server_audit_proof_cb != NULL)
1391                 {
1392                 size_t lenmax;
1393                 const unsigned short ext_len = 2;
1394                 const unsigned char list_len = 1;
1395
1396                 if ((lenmax = limit - ret - 6) < 0) return NULL;
1397
1398                 s2n(TLSEXT_TYPE_server_authz, ret);
1399                 /* Extension length: 2 bytes */
1400                 s2n(ext_len, ret);
1401                 *(ret++) = list_len;
1402                 *(ret++) = TLSEXT_AUTHZDATAFORMAT_audit_proof;
1403                 }
1404
1405         if ((extdatalen = ret-p-2) == 0)
1406                 return p;
1407
1408         s2n(extdatalen,p);
1409         return ret;
1410         }
1411
1412 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1413         {
1414         int extdatalen=0;
1415         unsigned char *ret = p;
1416 #ifndef OPENSSL_NO_NEXTPROTONEG
1417         int next_proto_neg_seen;
1418 #endif
1419         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1420         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1421         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1422         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1423
1424         /* don't add extensions for SSLv3, unless doing secure renegotiation */
1425         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1426                 return p;
1427         
1428         ret+=2;
1429         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1430
1431         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1432                 { 
1433                 if ((long)(limit - ret - 4) < 0) return NULL; 
1434
1435                 s2n(TLSEXT_TYPE_server_name,ret);
1436                 s2n(0,ret);
1437                 }
1438
1439         if(s->s3->send_connection_binding)
1440         {
1441           int el;
1442           
1443           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1444               {
1445               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1446               return NULL;
1447               }
1448
1449           if((limit - p - 4 - el) < 0) return NULL;
1450           
1451           s2n(TLSEXT_TYPE_renegotiate,ret);
1452           s2n(el,ret);
1453
1454           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1455               {
1456               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1457               return NULL;
1458               }
1459
1460           ret += el;
1461         }
1462
1463 #ifndef OPENSSL_NO_EC
1464         if (using_ecc && s->version != DTLS1_VERSION)
1465                 {
1466                 const unsigned char *plist;
1467                 size_t plistlen;
1468                 /* Add TLS extension ECPointFormats to the ServerHello message */
1469                 long lenmax; 
1470
1471                 tls1_get_formatlist(s, &plist, &plistlen);
1472
1473                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1474                 if (plistlen > (size_t)lenmax) return NULL;
1475                 if (plistlen > 255)
1476                         {
1477                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1478                         return NULL;
1479                         }
1480                 
1481                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1482                 s2n(plistlen + 1,ret);
1483                 *(ret++) = (unsigned char) plistlen;
1484                 memcpy(ret, plist, plistlen);
1485                 ret+=plistlen;
1486
1487                 }
1488         /* Currently the server should not respond with a SupportedCurves extension */
1489 #endif /* OPENSSL_NO_EC */
1490
1491         if (s->tlsext_ticket_expected
1492                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
1493                 { 
1494                 if ((long)(limit - ret - 4) < 0) return NULL; 
1495                 s2n(TLSEXT_TYPE_session_ticket,ret);
1496                 s2n(0,ret);
1497                 }
1498
1499         if (s->tlsext_status_expected)
1500                 { 
1501                 if ((long)(limit - ret - 4) < 0) return NULL; 
1502                 s2n(TLSEXT_TYPE_status_request,ret);
1503                 s2n(0,ret);
1504                 }
1505
1506 #ifdef TLSEXT_TYPE_opaque_prf_input
1507         if (s->s3->server_opaque_prf_input != NULL &&
1508             s->version != DTLS1_VERSION)
1509                 {
1510                 size_t sol = s->s3->server_opaque_prf_input_len;
1511                 
1512                 if ((long)(limit - ret - 6 - sol) < 0)
1513                         return NULL;
1514                 if (sol > 0xFFFD) /* can't happen */
1515                         return NULL;
1516
1517                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1518                 s2n(sol + 2, ret);
1519                 s2n(sol, ret);
1520                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1521                 ret += sol;
1522                 }
1523 #endif
1524
1525         if(s->srtp_profile)
1526                 {
1527                 int el;
1528
1529                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1530                 
1531                 if((limit - p - 4 - el) < 0) return NULL;
1532
1533                 s2n(TLSEXT_TYPE_use_srtp,ret);
1534                 s2n(el,ret);
1535
1536                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1537                         {
1538                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1539                         return NULL;
1540                         }
1541                 ret+=el;
1542                 }
1543
1544         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1545                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1546                 { const unsigned char cryptopro_ext[36] = {
1547                         0xfd, 0xe8, /*65000*/
1548                         0x00, 0x20, /*32 bytes length*/
1549                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1550                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1551                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1552                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1553                         if (limit-ret<36) return NULL;
1554                         memcpy(ret,cryptopro_ext,36);
1555                         ret+=36;
1556
1557                 }
1558
1559 #ifndef OPENSSL_NO_HEARTBEATS
1560         /* Add Heartbeat extension if we've received one */
1561         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1562                 {
1563                 s2n(TLSEXT_TYPE_heartbeat,ret);
1564                 s2n(1,ret);
1565                 /* Set mode:
1566                  * 1: peer may send requests
1567                  * 2: peer not allowed to send requests
1568                  */
1569                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1570                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1571                 else
1572                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1573
1574                 }
1575 #endif
1576
1577 #ifndef OPENSSL_NO_NEXTPROTONEG
1578         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1579         s->s3->next_proto_neg_seen = 0;
1580         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1581                 {
1582                 const unsigned char *npa;
1583                 unsigned int npalen;
1584                 int r;
1585
1586                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1587                 if (r == SSL_TLSEXT_ERR_OK)
1588                         {
1589                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1590                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1591                         s2n(npalen,ret);
1592                         memcpy(ret, npa, npalen);
1593                         ret += npalen;
1594                         s->s3->next_proto_neg_seen = 1;
1595                         }
1596                 }
1597 #endif
1598
1599         /* If the client supports authz then see whether we have any to offer
1600          * to it. */
1601         if (s->s3->tlsext_authz_client_types_len)
1602                 {
1603                 size_t authz_length;
1604                 /* By now we already know the new cipher, so we can look ahead
1605                  * to see whether the cert we are going to send
1606                  * has any authz data attached to it. */
1607                 const unsigned char* authz = ssl_get_authz_data(s, &authz_length);
1608                 const unsigned char* const orig_authz = authz;
1609                 size_t i;
1610                 unsigned authz_count = 0;
1611
1612                 /* The authz data contains a number of the following structures:
1613                  *      uint8_t authz_type
1614                  *      uint16_t length
1615                  *      uint8_t data[length]
1616                  *
1617                  * First we walk over it to find the number of authz elements. */
1618                 for (i = 0; i < authz_length; i++)
1619                         {
1620                         unsigned short length;
1621                         unsigned char type;
1622
1623                         type = *(authz++);
1624                         if (memchr(s->s3->tlsext_authz_client_types,
1625                                    type,
1626                                    s->s3->tlsext_authz_client_types_len) != NULL)
1627                                 authz_count++;
1628
1629                         n2s(authz, length);
1630                         /* n2s increments authz by 2 */
1631                         i += 2;
1632                         authz += length;
1633                         i += length;
1634                         }
1635
1636                 if (authz_count)
1637                         {
1638                         /* Add TLS extension server_authz to the ServerHello message
1639                          * 2 bytes for extension type
1640                          * 2 bytes for extension length
1641                          * 1 byte for the list length
1642                          * n bytes for the list */
1643                         const unsigned short ext_len = 1 + authz_count;
1644
1645                         if ((long)(limit - ret - 4 - ext_len) < 0) return NULL;
1646                         s2n(TLSEXT_TYPE_server_authz, ret);
1647                         s2n(ext_len, ret);
1648                         *(ret++) = authz_count;
1649                         s->s3->tlsext_authz_promised_to_client = 1;
1650                         }
1651
1652                 authz = orig_authz;
1653                 for (i = 0; i < authz_length; i++)
1654                         {
1655                         unsigned short length;
1656                         unsigned char type;
1657
1658                         authz_count++;
1659                         type = *(authz++);
1660                         if (memchr(s->s3->tlsext_authz_client_types,
1661                                    type,
1662                                    s->s3->tlsext_authz_client_types_len) != NULL)
1663                                 *(ret++) = type;
1664                         n2s(authz, length);
1665                         /* n2s increments authz by 2 */
1666                         i += 2;
1667                         authz += length;
1668                         i += length;
1669                         }
1670                 }
1671
1672         if ((extdatalen = ret-p-2)== 0) 
1673                 return p;
1674
1675         s2n(extdatalen,p);
1676         return ret;
1677         }
1678
1679 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) 
1680         {       
1681         unsigned short type;
1682         unsigned short size;
1683         unsigned short len;
1684         unsigned char *data = *p;
1685         int renegotiate_seen = 0;
1686         size_t i;
1687
1688         s->servername_done = 0;
1689         s->tlsext_status_type = -1;
1690 #ifndef OPENSSL_NO_NEXTPROTONEG
1691         s->s3->next_proto_neg_seen = 0;
1692 #endif
1693
1694 #ifndef OPENSSL_NO_HEARTBEATS
1695         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1696                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1697 #endif
1698         /* Clear any signature algorithms extension received */
1699         if (s->cert->peer_sigalgs)
1700                 {
1701                 OPENSSL_free(s->cert->peer_sigalgs);
1702                 s->cert->peer_sigalgs = NULL;
1703                 }
1704         /* Clear any shared sigtnature algorithms */
1705         if (s->cert->shared_sigalgs)
1706                 {
1707                 OPENSSL_free(s->cert->shared_sigalgs);
1708                 s->cert->shared_sigalgs = NULL;
1709                 }
1710         /* Clear certificate digests and validity flags */
1711         for (i = 0; i < SSL_PKEY_NUM; i++)
1712                 {
1713                 s->cert->pkeys[i].digest = NULL;
1714                 s->cert->pkeys[i].valid_flags = 0;
1715                 }
1716
1717         if (data >= (d+n-2))
1718                 goto ri_check;
1719         n2s(data,len);
1720
1721         if (data > (d+n-len)) 
1722                 goto ri_check;
1723
1724         while (data <= (d+n-4))
1725                 {
1726                 n2s(data,type);
1727                 n2s(data,size);
1728
1729                 if (data+size > (d+n))
1730                         goto ri_check;
1731 #if 0
1732                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1733 #endif
1734                 if (s->tlsext_debug_cb)
1735                         s->tlsext_debug_cb(s, 0, type, data, size,
1736                                                 s->tlsext_debug_arg);
1737 /* The servername extension is treated as follows:
1738
1739    - Only the hostname type is supported with a maximum length of 255.
1740    - The servername is rejected if too long or if it contains zeros,
1741      in which case an fatal alert is generated.
1742    - The servername field is maintained together with the session cache.
1743    - When a session is resumed, the servername call back invoked in order
1744      to allow the application to position itself to the right context. 
1745    - The servername is acknowledged if it is new for a session or when 
1746      it is identical to a previously used for the same session. 
1747      Applications can control the behaviour.  They can at any time
1748      set a 'desirable' servername for a new SSL object. This can be the
1749      case for example with HTTPS when a Host: header field is received and
1750      a renegotiation is requested. In this case, a possible servername
1751      presented in the new client hello is only acknowledged if it matches
1752      the value of the Host: field. 
1753    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1754      if they provide for changing an explicit servername context for the session,
1755      i.e. when the session has been established with a servername extension. 
1756    - On session reconnect, the servername extension may be absent. 
1757
1758 */      
1759
1760                 if (type == TLSEXT_TYPE_server_name)
1761                         {
1762                         unsigned char *sdata;
1763                         int servname_type;
1764                         int dsize; 
1765                 
1766                         if (size < 2) 
1767                                 {
1768                                 *al = SSL_AD_DECODE_ERROR;
1769                                 return 0;
1770                                 }
1771                         n2s(data,dsize);  
1772                         size -= 2;
1773                         if (dsize > size  ) 
1774                                 {
1775                                 *al = SSL_AD_DECODE_ERROR;
1776                                 return 0;
1777                                 } 
1778
1779                         sdata = data;
1780                         while (dsize > 3) 
1781                                 {
1782                                 servname_type = *(sdata++); 
1783                                 n2s(sdata,len);
1784                                 dsize -= 3;
1785
1786                                 if (len > dsize) 
1787                                         {
1788                                         *al = SSL_AD_DECODE_ERROR;
1789                                         return 0;
1790                                         }
1791                                 if (s->servername_done == 0)
1792                                 switch (servname_type)
1793                                         {
1794                                 case TLSEXT_NAMETYPE_host_name:
1795                                         if (!s->hit)
1796                                                 {
1797                                                 if(s->session->tlsext_hostname)
1798                                                         {
1799                                                         *al = SSL_AD_DECODE_ERROR;
1800                                                         return 0;
1801                                                         }
1802                                                 if (len > TLSEXT_MAXLEN_host_name)
1803                                                         {
1804                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1805                                                         return 0;
1806                                                         }
1807                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
1808                                                         {
1809                                                         *al = TLS1_AD_INTERNAL_ERROR;
1810                                                         return 0;
1811                                                         }
1812                                                 memcpy(s->session->tlsext_hostname, sdata, len);
1813                                                 s->session->tlsext_hostname[len]='\0';
1814                                                 if (strlen(s->session->tlsext_hostname) != len) {
1815                                                         OPENSSL_free(s->session->tlsext_hostname);
1816                                                         s->session->tlsext_hostname = NULL;
1817                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1818                                                         return 0;
1819                                                 }
1820                                                 s->servername_done = 1; 
1821
1822                                                 }
1823                                         else 
1824                                                 s->servername_done = s->session->tlsext_hostname
1825                                                         && strlen(s->session->tlsext_hostname) == len 
1826                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
1827                                         
1828                                         break;
1829
1830                                 default:
1831                                         break;
1832                                         }
1833                                  
1834                                 dsize -= len;
1835                                 }
1836                         if (dsize != 0) 
1837                                 {
1838                                 *al = SSL_AD_DECODE_ERROR;
1839                                 return 0;
1840                                 }
1841
1842                         }
1843 #ifndef OPENSSL_NO_SRP
1844                 else if (type == TLSEXT_TYPE_srp)
1845                         {
1846                         if (size <= 0 || ((len = data[0])) != (size -1))
1847                                 {
1848                                 *al = SSL_AD_DECODE_ERROR;
1849                                 return 0;
1850                                 }
1851                         if (s->srp_ctx.login != NULL)
1852                                 {
1853                                 *al = SSL_AD_DECODE_ERROR;
1854                                 return 0;
1855                                 }
1856                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
1857                                 return -1;
1858                         memcpy(s->srp_ctx.login, &data[1], len);
1859                         s->srp_ctx.login[len]='\0';
1860   
1861                         if (strlen(s->srp_ctx.login) != len) 
1862                                 {
1863                                 *al = SSL_AD_DECODE_ERROR;
1864                                 return 0;
1865                                 }
1866                         }
1867 #endif
1868
1869 #ifndef OPENSSL_NO_EC
1870                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1871                      s->version != DTLS1_VERSION)
1872                         {
1873                         unsigned char *sdata = data;
1874                         int ecpointformatlist_length = *(sdata++);
1875
1876                         if (ecpointformatlist_length != size - 1 || 
1877                                 ecpointformatlist_length < 1)
1878                                 {
1879                                 *al = TLS1_AD_DECODE_ERROR;
1880                                 return 0;
1881                                 }
1882                         if (!s->hit)
1883                                 {
1884                                 if(s->session->tlsext_ecpointformatlist)
1885                                         {
1886                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
1887                                         s->session->tlsext_ecpointformatlist = NULL;
1888                                         }
1889                                 s->session->tlsext_ecpointformatlist_length = 0;
1890                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1891                                         {
1892                                         *al = TLS1_AD_INTERNAL_ERROR;
1893                                         return 0;
1894                                         }
1895                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1896                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1897                                 }
1898 #if 0
1899                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
1900                         sdata = s->session->tlsext_ecpointformatlist;
1901                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1902                                 fprintf(stderr,"%i ",*(sdata++));
1903                         fprintf(stderr,"\n");
1904 #endif
1905                         }
1906                 else if (type == TLSEXT_TYPE_elliptic_curves &&
1907                      s->version != DTLS1_VERSION)
1908                         {
1909                         unsigned char *sdata = data;
1910                         int ellipticcurvelist_length = (*(sdata++) << 8);
1911                         ellipticcurvelist_length += (*(sdata++));
1912
1913                         if (ellipticcurvelist_length != size - 2 ||
1914                                 ellipticcurvelist_length < 1)
1915                                 {
1916                                 *al = TLS1_AD_DECODE_ERROR;
1917                                 return 0;
1918                                 }
1919                         if (!s->hit)
1920                                 {
1921                                 if(s->session->tlsext_ellipticcurvelist)
1922                                         {
1923                                         *al = TLS1_AD_DECODE_ERROR;
1924                                         return 0;
1925                                         }
1926                                 s->session->tlsext_ellipticcurvelist_length = 0;
1927                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
1928                                         {
1929                                         *al = TLS1_AD_INTERNAL_ERROR;
1930                                         return 0;
1931                                         }
1932                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
1933                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
1934                                 }
1935 #if 0
1936                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
1937                         sdata = s->session->tlsext_ellipticcurvelist;
1938                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
1939                                 fprintf(stderr,"%i ",*(sdata++));
1940                         fprintf(stderr,"\n");
1941 #endif
1942                         }
1943 #endif /* OPENSSL_NO_EC */
1944 #ifdef TLSEXT_TYPE_opaque_prf_input
1945                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1946                      s->version != DTLS1_VERSION)
1947                         {
1948                         unsigned char *sdata = data;
1949
1950                         if (size < 2)
1951                                 {
1952                                 *al = SSL_AD_DECODE_ERROR;
1953                                 return 0;
1954                                 }
1955                         n2s(sdata, s->s3->client_opaque_prf_input_len);
1956                         if (s->s3->client_opaque_prf_input_len != size - 2)
1957                                 {
1958                                 *al = SSL_AD_DECODE_ERROR;
1959                                 return 0;
1960                                 }
1961
1962                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1963                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1964                         if (s->s3->client_opaque_prf_input_len == 0)
1965                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1966                         else
1967                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
1968                         if (s->s3->client_opaque_prf_input == NULL)
1969                                 {
1970                                 *al = TLS1_AD_INTERNAL_ERROR;
1971                                 return 0;
1972                                 }
1973                         }
1974 #endif
1975                 else if (type == TLSEXT_TYPE_session_ticket)
1976                         {
1977                         if (s->tls_session_ticket_ext_cb &&
1978                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1979                                 {
1980                                 *al = TLS1_AD_INTERNAL_ERROR;
1981                                 return 0;
1982                                 }
1983                         }
1984                 else if (type == TLSEXT_TYPE_renegotiate)
1985                         {
1986                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
1987                                 return 0;
1988                         renegotiate_seen = 1;
1989                         }
1990                 else if (type == TLSEXT_TYPE_signature_algorithms)
1991                         {
1992                         int dsize;
1993                         if (s->cert->peer_sigalgs || size < 2) 
1994                                 {
1995                                 *al = SSL_AD_DECODE_ERROR;
1996                                 return 0;
1997                                 }
1998                         n2s(data,dsize);
1999                         size -= 2;
2000                         if (dsize != size || dsize & 1 || !dsize) 
2001                                 {
2002                                 *al = SSL_AD_DECODE_ERROR;
2003                                 return 0;
2004                                 }
2005                         if (!tls1_process_sigalgs(s, data, dsize))
2006                                 {
2007                                 *al = SSL_AD_DECODE_ERROR;
2008                                 return 0;
2009                                 }
2010                         /* If sigalgs received and no shared algorithms fatal
2011                          * error.
2012                          */
2013                         if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
2014                                 {
2015                                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2016                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
2017                                 *al = SSL_AD_ILLEGAL_PARAMETER;
2018                                 return 0;
2019                                 }
2020                         }
2021                 else if (type == TLSEXT_TYPE_status_request &&
2022                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
2023                         {
2024                 
2025                         if (size < 5) 
2026                                 {
2027                                 *al = SSL_AD_DECODE_ERROR;
2028                                 return 0;
2029                                 }
2030
2031                         s->tlsext_status_type = *data++;
2032                         size--;
2033                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
2034                                 {
2035                                 const unsigned char *sdata;
2036                                 int dsize;
2037                                 /* Read in responder_id_list */
2038                                 n2s(data,dsize);
2039                                 size -= 2;
2040                                 if (dsize > size  ) 
2041                                         {
2042                                         *al = SSL_AD_DECODE_ERROR;
2043                                         return 0;
2044                                         }
2045                                 while (dsize > 0)
2046                                         {
2047                                         OCSP_RESPID *id;
2048                                         int idsize;
2049                                         if (dsize < 4)
2050                                                 {
2051                                                 *al = SSL_AD_DECODE_ERROR;
2052                                                 return 0;
2053                                                 }
2054                                         n2s(data, idsize);
2055                                         dsize -= 2 + idsize;
2056                                         size -= 2 + idsize;
2057                                         if (dsize < 0)
2058                                                 {
2059                                                 *al = SSL_AD_DECODE_ERROR;
2060                                                 return 0;
2061                                                 }
2062                                         sdata = data;
2063                                         data += idsize;
2064                                         id = d2i_OCSP_RESPID(NULL,
2065                                                                 &sdata, idsize);
2066                                         if (!id)
2067                                                 {
2068                                                 *al = SSL_AD_DECODE_ERROR;
2069                                                 return 0;
2070                                                 }
2071                                         if (data != sdata)
2072                                                 {
2073                                                 OCSP_RESPID_free(id);
2074                                                 *al = SSL_AD_DECODE_ERROR;
2075                                                 return 0;
2076                                                 }
2077                                         if (!s->tlsext_ocsp_ids
2078                                                 && !(s->tlsext_ocsp_ids =
2079                                                 sk_OCSP_RESPID_new_null()))
2080                                                 {
2081                                                 OCSP_RESPID_free(id);
2082                                                 *al = SSL_AD_INTERNAL_ERROR;
2083                                                 return 0;
2084                                                 }
2085                                         if (!sk_OCSP_RESPID_push(
2086                                                         s->tlsext_ocsp_ids, id))
2087                                                 {
2088                                                 OCSP_RESPID_free(id);
2089                                                 *al = SSL_AD_INTERNAL_ERROR;
2090                                                 return 0;
2091                                                 }
2092                                         }
2093
2094                                 /* Read in request_extensions */
2095                                 if (size < 2)
2096                                         {
2097                                         *al = SSL_AD_DECODE_ERROR;
2098                                         return 0;
2099                                         }
2100                                 n2s(data,dsize);
2101                                 size -= 2;
2102                                 if (dsize != size)
2103                                         {
2104                                         *al = SSL_AD_DECODE_ERROR;
2105                                         return 0;
2106                                         }
2107                                 sdata = data;
2108                                 if (dsize > 0)
2109                                         {
2110                                         if (s->tlsext_ocsp_exts)
2111                                                 {
2112                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2113                                                                            X509_EXTENSION_free);
2114                                                 }
2115
2116                                         s->tlsext_ocsp_exts =
2117                                                 d2i_X509_EXTENSIONS(NULL,
2118                                                         &sdata, dsize);
2119                                         if (!s->tlsext_ocsp_exts
2120                                                 || (data + dsize != sdata))
2121                                                 {
2122                                                 *al = SSL_AD_DECODE_ERROR;
2123                                                 return 0;
2124                                                 }
2125                                         }
2126                                 }
2127                                 /* We don't know what to do with any other type
2128                                 * so ignore it.
2129                                 */
2130                                 else
2131                                         s->tlsext_status_type = -1;
2132                         }
2133 #ifndef OPENSSL_NO_HEARTBEATS
2134                 else if (type == TLSEXT_TYPE_heartbeat)
2135                         {
2136                         switch(data[0])
2137                                 {
2138                                 case 0x01:      /* Client allows us to send HB requests */
2139                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2140                                                         break;
2141                                 case 0x02:      /* Client doesn't accept HB requests */
2142                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2143                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2144                                                         break;
2145                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2146                                                         return 0;
2147                                 }
2148                         }
2149 #endif
2150 #ifndef OPENSSL_NO_NEXTPROTONEG
2151                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2152                          s->s3->tmp.finish_md_len == 0)
2153                         {
2154                         /* We shouldn't accept this extension on a
2155                          * renegotiation.
2156                          *
2157                          * s->new_session will be set on renegotiation, but we
2158                          * probably shouldn't rely that it couldn't be set on
2159                          * the initial renegotation too in certain cases (when
2160                          * there's some other reason to disallow resuming an
2161                          * earlier session -- the current code won't be doing
2162                          * anything like that, but this might change).
2163
2164                          * A valid sign that there's been a previous handshake
2165                          * in this connection is if s->s3->tmp.finish_md_len >
2166                          * 0.  (We are talking about a check that will happen
2167                          * in the Hello protocol round, well before a new
2168                          * Finished message could have been computed.) */
2169                         s->s3->next_proto_neg_seen = 1;
2170                         }
2171 #endif
2172
2173                 /* session ticket processed earlier */
2174                 else if (type == TLSEXT_TYPE_use_srtp)
2175                         {
2176                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2177                                                               al))
2178                                 return 0;
2179                         }
2180
2181                 else if (type == TLSEXT_TYPE_server_authz)
2182                         {
2183                         unsigned char *sdata = data;
2184                         unsigned char server_authz_dataformatlist_length;
2185
2186                         if (size == 0)
2187                                 {
2188                                 *al = TLS1_AD_DECODE_ERROR;
2189                                 return 0;
2190                                 }
2191
2192                         server_authz_dataformatlist_length = *(sdata++);
2193
2194                         if (server_authz_dataformatlist_length != size - 1)
2195                                 {
2196                                 *al = TLS1_AD_DECODE_ERROR;
2197                                 return 0;
2198                                 }
2199
2200                         /* Successful session resumption uses the same authz
2201                          * information as the original session so we ignore this
2202                          * in the case of a session resumption. */
2203                         if (!s->hit)
2204                                 {
2205                                 if (s->s3->tlsext_authz_client_types != NULL)
2206                                         OPENSSL_free(s->s3->tlsext_authz_client_types);
2207                                 s->s3->tlsext_authz_client_types =
2208                                         OPENSSL_malloc(server_authz_dataformatlist_length);
2209                                 if (!s->s3->tlsext_authz_client_types)
2210                                         {
2211                                         *al = TLS1_AD_INTERNAL_ERROR;
2212                                         return 0;
2213                                         }
2214
2215                                 s->s3->tlsext_authz_client_types_len =
2216                                         server_authz_dataformatlist_length;
2217                                 memcpy(s->s3->tlsext_authz_client_types,
2218                                        sdata,
2219                                        server_authz_dataformatlist_length);
2220
2221                                 /* Sort the types in order to check for duplicates. */
2222                                 qsort(s->s3->tlsext_authz_client_types,
2223                                       server_authz_dataformatlist_length,
2224                                       1 /* element size */,
2225                                       byte_compare);
2226
2227                                 for (i = 0; i < server_authz_dataformatlist_length; i++)
2228                                         {
2229                                         if (i > 0 &&
2230                                             s->s3->tlsext_authz_client_types[i] ==
2231                                               s->s3->tlsext_authz_client_types[i-1])
2232                                                 {
2233                                                 *al = TLS1_AD_DECODE_ERROR;
2234                                                 return 0;
2235                                                 }
2236                                         }
2237                                 }
2238                         }
2239
2240                 data+=size;
2241                 }
2242
2243         *p = data;
2244
2245         ri_check:
2246
2247         /* Need RI if renegotiating */
2248
2249         if (!renegotiate_seen && s->renegotiate &&
2250                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2251                 {
2252                 *al = SSL_AD_HANDSHAKE_FAILURE;
2253                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2254                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2255                 return 0;
2256                 }
2257         /* If no signature algorithms extension set default values */
2258         if (!s->cert->peer_sigalgs)
2259                 ssl_cert_set_default_md(s->cert);
2260
2261         return 1;
2262         }
2263
2264 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2265         {
2266         int al = -1;
2267         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2268                 {
2269                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2270                 return 0;
2271                 }
2272
2273         if (ssl_check_clienthello_tlsext_early(s) <= 0) 
2274                 {
2275                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2276                 return 0;
2277                 }
2278         return 1;
2279 }
2280
2281 #ifndef OPENSSL_NO_NEXTPROTONEG
2282 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2283  * elements of zero length are allowed and the set of elements must exactly fill
2284  * the length of the block. */
2285 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2286         {
2287         unsigned int off = 0;
2288
2289         while (off < len)
2290                 {
2291                 if (d[off] == 0)
2292                         return 0;
2293                 off += d[off];
2294                 off++;
2295                 }
2296
2297         return off == len;
2298         }
2299 #endif
2300
2301 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2302         {
2303         unsigned short length;
2304         unsigned short type;
2305         unsigned short size;
2306         unsigned char *data = *p;
2307         int tlsext_servername = 0;
2308         int renegotiate_seen = 0;
2309
2310 #ifndef OPENSSL_NO_NEXTPROTONEG
2311         s->s3->next_proto_neg_seen = 0;
2312 #endif
2313
2314 #ifndef OPENSSL_NO_HEARTBEATS
2315         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2316                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2317 #endif
2318
2319         if (data >= (d+n-2))
2320                 goto ri_check;
2321
2322         n2s(data,length);
2323         if (data+length != d+n)
2324                 {
2325                 *al = SSL_AD_DECODE_ERROR;
2326                 return 0;
2327                 }
2328
2329         while(data <= (d+n-4))
2330                 {
2331                 n2s(data,type);
2332                 n2s(data,size);
2333
2334                 if (data+size > (d+n))
2335                         goto ri_check;
2336
2337                 if (s->tlsext_debug_cb)
2338                         s->tlsext_debug_cb(s, 1, type, data, size,
2339                                                 s->tlsext_debug_arg);
2340
2341                 if (type == TLSEXT_TYPE_server_name)
2342                         {
2343                         if (s->tlsext_hostname == NULL || size > 0)
2344                                 {
2345                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2346                                 return 0;
2347                                 }
2348                         tlsext_servername = 1;   
2349                         }
2350
2351 #ifndef OPENSSL_NO_EC
2352                 else if (type == TLSEXT_TYPE_ec_point_formats &&
2353                      s->version != DTLS1_VERSION)
2354                         {
2355                         unsigned char *sdata = data;
2356                         int ecpointformatlist_length = *(sdata++);
2357
2358                         if (ecpointformatlist_length != size - 1)
2359                                 {
2360                                 *al = TLS1_AD_DECODE_ERROR;
2361                                 return 0;
2362                                 }
2363                         s->session->tlsext_ecpointformatlist_length = 0;
2364                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2365                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2366                                 {
2367                                 *al = TLS1_AD_INTERNAL_ERROR;
2368                                 return 0;
2369                                 }
2370                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2371                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2372 #if 0
2373                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2374                         sdata = s->session->tlsext_ecpointformatlist;
2375                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2376                                 fprintf(stderr,"%i ",*(sdata++));
2377                         fprintf(stderr,"\n");
2378 #endif
2379                         }
2380 #endif /* OPENSSL_NO_EC */
2381
2382                 else if (type == TLSEXT_TYPE_session_ticket)
2383                         {
2384                         if (s->tls_session_ticket_ext_cb &&
2385                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2386                                 {
2387                                 *al = TLS1_AD_INTERNAL_ERROR;
2388                                 return 0;
2389                                 }
2390                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2391                                 || (size > 0))
2392                                 {
2393                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2394                                 return 0;
2395                                 }
2396                         s->tlsext_ticket_expected = 1;
2397                         }
2398 #ifdef TLSEXT_TYPE_opaque_prf_input
2399                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
2400                      s->version != DTLS1_VERSION)
2401                         {
2402                         unsigned char *sdata = data;
2403
2404                         if (size < 2)
2405                                 {
2406                                 *al = SSL_AD_DECODE_ERROR;
2407                                 return 0;
2408                                 }
2409                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2410                         if (s->s3->server_opaque_prf_input_len != size - 2)
2411                                 {
2412                                 *al = SSL_AD_DECODE_ERROR;
2413                                 return 0;
2414                                 }
2415                         
2416                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2417                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2418                         if (s->s3->server_opaque_prf_input_len == 0)
2419                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2420                         else
2421                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2422
2423                         if (s->s3->server_opaque_prf_input == NULL)
2424                                 {
2425                                 *al = TLS1_AD_INTERNAL_ERROR;
2426                                 return 0;
2427                                 }
2428                         }
2429 #endif
2430                 else if (type == TLSEXT_TYPE_status_request &&
2431                          s->version != DTLS1_VERSION)
2432                         {
2433                         /* MUST be empty and only sent if we've requested
2434                          * a status request message.
2435                          */ 
2436                         if ((s->tlsext_status_type == -1) || (size > 0))
2437                                 {
2438                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2439                                 return 0;
2440                                 }
2441                         /* Set flag to expect CertificateStatus message */
2442                         s->tlsext_status_expected = 1;
2443                         }
2444 #ifndef OPENSSL_NO_NEXTPROTONEG
2445                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2446                          s->s3->tmp.finish_md_len == 0)
2447                         {
2448                         unsigned char *selected;
2449                         unsigned char selected_len;
2450
2451                         /* We must have requested it. */
2452                         if ((s->ctx->next_proto_select_cb == NULL))
2453                                 {
2454                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2455                                 return 0;
2456                                 }
2457                         /* The data must be valid */
2458                         if (!ssl_next_proto_validate(data, size))
2459                                 {
2460                                 *al = TLS1_AD_DECODE_ERROR;
2461                                 return 0;
2462                                 }
2463                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2464                                 {
2465                                 *al = TLS1_AD_INTERNAL_ERROR;
2466                                 return 0;
2467                                 }
2468                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2469                         if (!s->next_proto_negotiated)
2470                                 {
2471                                 *al = TLS1_AD_INTERNAL_ERROR;
2472                                 return 0;
2473                                 }
2474                         memcpy(s->next_proto_negotiated, selected, selected_len);
2475                         s->next_proto_negotiated_len = selected_len;
2476                         s->s3->next_proto_neg_seen = 1;
2477                         }
2478 #endif
2479                 else if (type == TLSEXT_TYPE_renegotiate)
2480                         {
2481                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2482                                 return 0;
2483                         renegotiate_seen = 1;
2484                         }
2485 #ifndef OPENSSL_NO_HEARTBEATS
2486                 else if (type == TLSEXT_TYPE_heartbeat)
2487                         {
2488                         switch(data[0])
2489                                 {
2490                                 case 0x01:      /* Server allows us to send HB requests */
2491                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2492                                                         break;
2493                                 case 0x02:      /* Server doesn't accept HB requests */
2494                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2495                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2496                                                         break;
2497                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2498                                                         return 0;
2499                                 }
2500                         }
2501 #endif
2502                 else if (type == TLSEXT_TYPE_use_srtp)
2503                         {
2504                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2505                                                               al))
2506                                 return 0;
2507                         }
2508
2509                 else if (type == TLSEXT_TYPE_server_authz)
2510                         {
2511                         /* We only support audit proofs. It's an error to send
2512                          * an authz hello extension if the client
2513                          * didn't request a proof. */
2514                         unsigned char *sdata = data;
2515                         unsigned char server_authz_dataformatlist_length;
2516
2517                         if (!s->ctx->tlsext_authz_server_audit_proof_cb)
2518                                 {
2519                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2520                                 return 0;
2521                                 }
2522
2523                         if (!size)
2524                                 {
2525                                 *al = TLS1_AD_DECODE_ERROR;
2526                                 return 0;
2527                                 }
2528
2529                         server_authz_dataformatlist_length = *(sdata++);
2530                         if (server_authz_dataformatlist_length != size - 1)
2531                                 {
2532                                 *al = TLS1_AD_DECODE_ERROR;
2533                                 return 0;
2534                                 }
2535
2536                         /* We only support audit proofs, so a legal ServerHello
2537                          * authz list contains exactly one entry. */
2538                         if (server_authz_dataformatlist_length != 1 ||
2539                                 sdata[0] != TLSEXT_AUTHZDATAFORMAT_audit_proof)
2540                                 {
2541                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2542                                 return 0;
2543                                 }
2544
2545                         s->s3->tlsext_authz_server_promised = 1;
2546                         }
2547  
2548                 data += size;
2549                 }
2550
2551         if (data != d+n)
2552                 {
2553                 *al = SSL_AD_DECODE_ERROR;
2554                 return 0;
2555                 }
2556
2557         if (!s->hit && tlsext_servername == 1)
2558                 {
2559                 if (s->tlsext_hostname)
2560                         {
2561                         if (s->session->tlsext_hostname == NULL)
2562                                 {
2563                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2564                                 if (!s->session->tlsext_hostname)
2565                                         {
2566                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2567                                         return 0;
2568                                         }
2569                                 }
2570                         else 
2571                                 {
2572                                 *al = SSL_AD_DECODE_ERROR;
2573                                 return 0;
2574                                 }
2575                         }
2576                 }
2577
2578         *p = data;
2579
2580         ri_check:
2581
2582         /* Determine if we need to see RI. Strictly speaking if we want to
2583          * avoid an attack we should *always* see RI even on initial server
2584          * hello because the client doesn't see any renegotiation during an
2585          * attack. However this would mean we could not connect to any server
2586          * which doesn't support RI so for the immediate future tolerate RI
2587          * absence on initial connect only.
2588          */
2589         if (!renegotiate_seen
2590                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2591                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2592                 {
2593                 *al = SSL_AD_HANDSHAKE_FAILURE;
2594                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2595                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2596                 return 0;
2597                 }
2598
2599         return 1;
2600         }
2601
2602
2603 int ssl_prepare_clienthello_tlsext(SSL *s)
2604         {
2605
2606 #ifdef TLSEXT_TYPE_opaque_prf_input
2607         {
2608                 int r = 1;
2609         
2610                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2611                         {
2612                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2613                         if (!r)
2614                                 return -1;
2615                         }
2616
2617                 if (s->tlsext_opaque_prf_input != NULL)
2618                         {
2619                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2620                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2621
2622                         if (s->tlsext_opaque_prf_input_len == 0)
2623                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2624                         else
2625                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2626                         if (s->s3->client_opaque_prf_input == NULL)
2627                                 {
2628                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2629                                 return -1;
2630                                 }
2631                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2632                         }
2633
2634                 if (r == 2)
2635                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2636                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2637         }
2638 #endif
2639
2640         return 1;
2641         }
2642
2643 int ssl_prepare_serverhello_tlsext(SSL *s)
2644         {
2645         return 1;
2646         }
2647
2648 static int ssl_check_clienthello_tlsext_early(SSL *s)
2649         {
2650         int ret=SSL_TLSEXT_ERR_NOACK;
2651         int al = SSL_AD_UNRECOGNIZED_NAME;
2652
2653 #ifndef OPENSSL_NO_EC
2654         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2655          * ssl3_choose_cipher in s3_lib.c.
2656          */
2657         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2658          * ssl3_choose_cipher in s3_lib.c.
2659          */
2660 #endif
2661
2662         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2663                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2664         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2665                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2666
2667 #ifdef TLSEXT_TYPE_opaque_prf_input
2668         {
2669                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2670                  * but we might be sending an alert in response to the client hello,
2671                  * so this has to happen here in
2672                  * ssl_check_clienthello_tlsext_early(). */
2673
2674                 int r = 1;
2675         
2676                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2677                         {
2678                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2679                         if (!r)
2680                                 {
2681                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2682                                 al = SSL_AD_INTERNAL_ERROR;
2683                                 goto err;
2684                                 }
2685                         }
2686
2687                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2688                         OPENSSL_free(s->s3->server_opaque_prf_input);
2689                 s->s3->server_opaque_prf_input = NULL;
2690
2691                 if (s->tlsext_opaque_prf_input != NULL)
2692                         {
2693                         if (s->s3->client_opaque_prf_input != NULL &&
2694                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2695                                 {
2696                                 /* can only use this extension if we have a server opaque PRF input
2697                                  * of the same length as the client opaque PRF input! */
2698
2699                                 if (s->tlsext_opaque_prf_input_len == 0)
2700                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2701                                 else
2702                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2703                                 if (s->s3->server_opaque_prf_input == NULL)
2704                                         {
2705                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2706                                         al = SSL_AD_INTERNAL_ERROR;
2707                                         goto err;
2708                                         }
2709                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2710                                 }
2711                         }
2712
2713                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2714                         {
2715                         /* The callback wants to enforce use of the extension,
2716                          * but we can't do that with the client opaque PRF input;
2717                          * abort the handshake.
2718                          */
2719                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2720                         al = SSL_AD_HANDSHAKE_FAILURE;
2721                         }
2722         }
2723
2724  err:
2725 #endif
2726         switch (ret)
2727                 {
2728                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2729                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2730                         return -1;
2731
2732                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2733                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2734                         return 1; 
2735                                         
2736                 case SSL_TLSEXT_ERR_NOACK:
2737                         s->servername_done=0;
2738                         default:
2739                 return 1;
2740                 }
2741         }
2742
2743 int ssl_check_clienthello_tlsext_late(SSL *s)
2744         {
2745         int ret = SSL_TLSEXT_ERR_OK;
2746         int al;
2747
2748         /* If status request then ask callback what to do.
2749          * Note: this must be called after servername callbacks in case
2750          * the certificate has changed, and must be called after the cipher
2751          * has been chosen because this may influence which certificate is sent
2752          */
2753         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
2754                 {
2755                 int r;
2756                 CERT_PKEY *certpkey;
2757                 certpkey = ssl_get_server_send_pkey(s);
2758                 /* If no certificate can't return certificate status */
2759                 if (certpkey == NULL)
2760                         {
2761                         s->tlsext_status_expected = 0;
2762                         return 1;
2763                         }
2764                 /* Set current certificate to one we will use so
2765                  * SSL_get_certificate et al can pick it up.
2766                  */
2767                 s->cert->key = certpkey;
2768                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2769                 switch (r)
2770                         {
2771                         /* We don't want to send a status request response */
2772                         case SSL_TLSEXT_ERR_NOACK:
2773                                 s->tlsext_status_expected = 0;
2774                                 break;
2775                         /* status request response should be sent */
2776                         case SSL_TLSEXT_ERR_OK:
2777                                 if (s->tlsext_ocsp_resp)
2778                                         s->tlsext_status_expected = 1;
2779                                 else
2780                                         s->tlsext_status_expected = 0;
2781                                 break;
2782                         /* something bad happened */
2783                         case SSL_TLSEXT_ERR_ALERT_FATAL:
2784                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2785                                 al = SSL_AD_INTERNAL_ERROR;
2786                                 goto err;
2787                         }
2788                 }
2789         else
2790                 s->tlsext_status_expected = 0;
2791
2792  err:
2793         switch (ret)
2794                 {
2795                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2796                         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2797                         return -1;
2798
2799                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2800                         ssl3_send_alert(s, SSL3_AL_WARNING, al);
2801                         return 1; 
2802
2803                 default:
2804                         return 1;
2805                 }
2806         }
2807
2808 int ssl_check_serverhello_tlsext(SSL *s)
2809         {
2810         int ret=SSL_TLSEXT_ERR_NOACK;
2811         int al = SSL_AD_UNRECOGNIZED_NAME;
2812
2813 #ifndef OPENSSL_NO_EC
2814         /* If we are client and using an elliptic curve cryptography cipher
2815          * suite, then if server returns an EC point formats lists extension
2816          * it must contain uncompressed.
2817          */
2818         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2819         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2820         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
2821             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
2822             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
2823                 {
2824                 /* we are using an ECC cipher */
2825                 size_t i;
2826                 unsigned char *list;
2827                 int found_uncompressed = 0;
2828                 list = s->session->tlsext_ecpointformatlist;
2829                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2830                         {
2831                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
2832                                 {
2833                                 found_uncompressed = 1;
2834                                 break;
2835                                 }
2836                         }
2837                 if (!found_uncompressed)
2838                         {
2839                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2840                         return -1;
2841                         }
2842                 }
2843         ret = SSL_TLSEXT_ERR_OK;
2844 #endif /* OPENSSL_NO_EC */
2845
2846         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2847                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2848         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2849                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2850
2851 #ifdef TLSEXT_TYPE_opaque_prf_input
2852         if (s->s3->server_opaque_prf_input_len > 0)
2853                 {
2854                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
2855                  * So first verify that we really have a value from the server too. */
2856
2857                 if (s->s3->server_opaque_prf_input == NULL)
2858                         {
2859                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2860                         al = SSL_AD_HANDSHAKE_FAILURE;
2861                         }
2862                 
2863                 /* Anytime the server *has* sent an opaque PRF input, we need to check
2864                  * that we have a client opaque PRF input of the same size. */
2865                 if (s->s3->client_opaque_prf_input == NULL ||
2866                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
2867                         {
2868                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2869                         al = SSL_AD_ILLEGAL_PARAMETER;
2870                         }
2871                 }
2872 #endif
2873
2874         /* If we've requested certificate status and we wont get one
2875          * tell the callback
2876          */
2877         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
2878                         && s->ctx && s->ctx->tlsext_status_cb)
2879                 {
2880                 int r;
2881                 /* Set resp to NULL, resplen to -1 so callback knows
2882                  * there is no response.
2883                  */
2884                 if (s->tlsext_ocsp_resp)
2885                         {
2886                         OPENSSL_free(s->tlsext_ocsp_resp);
2887                         s->tlsext_ocsp_resp = NULL;
2888                         }
2889                 s->tlsext_ocsp_resplen = -1;
2890                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2891                 if (r == 0)
2892                         {
2893                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2894                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2895                         }
2896                 if (r < 0)
2897                         {
2898                         al = SSL_AD_INTERNAL_ERROR;
2899                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2900                         }
2901                 }
2902
2903         switch (ret)
2904                 {
2905                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2906                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2907                         return -1;
2908
2909                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2910                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2911                         return 1; 
2912                                         
2913                 case SSL_TLSEXT_ERR_NOACK:
2914                         s->servername_done=0;
2915                         default:
2916                 return 1;
2917                 }
2918         }
2919
2920 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2921         {
2922         int al = -1;
2923         if (s->version < SSL3_VERSION)
2924                 return 1;
2925         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
2926                 {
2927                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2928                 return 0;
2929                 }
2930
2931         if (ssl_check_serverhello_tlsext(s) <= 0) 
2932                 {
2933                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
2934                 return 0;
2935                 }
2936         return 1;
2937 }
2938
2939 /* Since the server cache lookup is done early on in the processing of the
2940  * ClientHello, and other operations depend on the result, we need to handle
2941  * any TLS session ticket extension at the same time.
2942  *
2943  *   session_id: points at the session ID in the ClientHello. This code will
2944  *       read past the end of this in order to parse out the session ticket
2945  *       extension, if any.
2946  *   len: the length of the session ID.
2947  *   limit: a pointer to the first byte after the ClientHello.
2948  *   ret: (output) on return, if a ticket was decrypted, then this is set to
2949  *       point to the resulting session.
2950  *
2951  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2952  * ciphersuite, in which case we have no use for session tickets and one will
2953  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2954  *
2955  * Returns:
2956  *   -1: fatal error, either from parsing or decrypting the ticket.
2957  *    0: no ticket was found (or was ignored, based on settings).
2958  *    1: a zero length extension was found, indicating that the client supports
2959  *       session tickets but doesn't currently have one to offer.
2960  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
2961  *       couldn't be decrypted because of a non-fatal error.
2962  *    3: a ticket was successfully decrypted and *ret was set.
2963  *
2964  * Side effects:
2965  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
2966  *   a new session ticket to the client because the client indicated support
2967  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
2968  *   a session ticket or we couldn't use the one it gave us, or if
2969  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
2970  *   Otherwise, s->tlsext_ticket_expected is set to 0.
2971  */
2972 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
2973                         const unsigned char *limit, SSL_SESSION **ret)
2974         {
2975         /* Point after session ID in client hello */
2976         const unsigned char *p = session_id + len;
2977         unsigned short i;
2978
2979         *ret = NULL;
2980         s->tlsext_ticket_expected = 0;
2981
2982         /* If tickets disabled behave as if no ticket present
2983          * to permit stateful resumption.
2984          */
2985         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
2986                 return 0;
2987         if ((s->version <= SSL3_VERSION) || !limit)
2988                 return 0;
2989         if (p >= limit)
2990                 return -1;
2991         /* Skip past DTLS cookie */
2992         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
2993                 {
2994                 i = *(p++);
2995                 p+= i;
2996                 if (p >= limit)
2997                         return -1;
2998                 }
2999         /* Skip past cipher list */
3000         n2s(p, i);
3001         p+= i;
3002         if (p >= limit)
3003                 return -1;
3004         /* Skip past compression algorithm list */
3005         i = *(p++);
3006         p += i;
3007         if (p > limit)
3008                 return -1;
3009         /* Now at start of extensions */
3010         if ((p + 2) >= limit)
3011                 return 0;
3012         n2s(p, i);
3013         while ((p + 4) <= limit)
3014                 {
3015                 unsigned short type, size;
3016                 n2s(p, type);
3017                 n2s(p, size);
3018                 if (p + size > limit)
3019                         return 0;
3020                 if (type == TLSEXT_TYPE_session_ticket)
3021                         {
3022                         int r;
3023                         if (size == 0)
3024                                 {
3025                                 /* The client will accept a ticket but doesn't
3026                                  * currently have one. */
3027                                 s->tlsext_ticket_expected = 1;
3028                                 return 1;
3029                                 }
3030                         if (s->tls_session_secret_cb)
3031                                 {
3032                                 /* Indicate that the ticket couldn't be
3033                                  * decrypted rather than generating the session
3034                                  * from ticket now, trigger abbreviated
3035                                  * handshake based on external mechanism to
3036                                  * calculate the master secret later. */
3037                                 return 2;
3038                                 }
3039                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3040                         switch (r)
3041                                 {
3042                                 case 2: /* ticket couldn't be decrypted */
3043                                         s->tlsext_ticket_expected = 1;
3044                                         return 2;
3045                                 case 3: /* ticket was decrypted */
3046                                         return r;
3047                                 case 4: /* ticket decrypted but need to renew */
3048                                         s->tlsext_ticket_expected = 1;
3049                                         return 3;
3050                                 default: /* fatal error */
3051                                         return -1;
3052                                 }
3053                         }
3054                 p += size;
3055                 }
3056         return 0;
3057         }
3058
3059 /* tls_decrypt_ticket attempts to decrypt a session ticket.
3060  *
3061  *   etick: points to the body of the session ticket extension.
3062  *   eticklen: the length of the session tickets extenion.
3063  *   sess_id: points at the session ID.
3064  *   sesslen: the length of the session ID.
3065  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3066  *       point to the resulting session.
3067  *
3068  * Returns:
3069  *   -1: fatal error, either from parsing or decrypting the ticket.
3070  *    2: the ticket couldn't be decrypted.
3071  *    3: a ticket was successfully decrypted and *psess was set.
3072  *    4: same as 3, but the ticket needs to be renewed.
3073  */
3074 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3075                                 const unsigned char *sess_id, int sesslen,
3076                                 SSL_SESSION **psess)
3077         {
3078         SSL_SESSION *sess;
3079         unsigned char *sdec;
3080         const unsigned char *p;
3081         int slen, mlen, renew_ticket = 0;
3082         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3083         HMAC_CTX hctx;
3084         EVP_CIPHER_CTX ctx;
3085         SSL_CTX *tctx = s->initial_ctx;
3086         /* Need at least keyname + iv + some encrypted data */
3087         if (eticklen < 48)
3088                 return 2;
3089         /* Initialize session ticket encryption and HMAC contexts */
3090         HMAC_CTX_init(&hctx);
3091         EVP_CIPHER_CTX_init(&ctx);
3092         if (tctx->tlsext_ticket_key_cb)
3093                 {
3094                 unsigned char *nctick = (unsigned char *)etick;
3095                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3096                                                         &ctx, &hctx, 0);
3097                 if (rv < 0)
3098                         return -1;
3099                 if (rv == 0)
3100                         return 2;
3101                 if (rv == 2)
3102                         renew_ticket = 1;
3103                 }
3104         else
3105                 {
3106                 /* Check key name matches */
3107                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3108                         return 2;
3109                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3110                                         tlsext_tick_md(), NULL);
3111                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,