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