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