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