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