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