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