Various custom extension fixes.
[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         /* Clear observed custom extensions */
1864         s->s3->tlsext_custom_types_count = 0;
1865         if (s->s3->tlsext_custom_types != NULL)
1866                 {
1867                 OPENSSL_free(s->s3->tlsext_custom_types);
1868                 s->s3->tlsext_custom_types = NULL;
1869                 }               
1870
1871 #ifndef OPENSSL_NO_HEARTBEATS
1872         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1873                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1874 #endif
1875
1876 #ifndef OPENSSL_NO_EC
1877         if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1878                 ssl_check_for_safari(s, data, d, n);
1879 #endif /* !OPENSSL_NO_EC */
1880
1881         /* Clear any signature algorithms extension received */
1882         if (s->cert->peer_sigalgs)
1883                 {
1884                 OPENSSL_free(s->cert->peer_sigalgs);
1885                 s->cert->peer_sigalgs = NULL;
1886                 }
1887         /* Clear any shared sigtnature algorithms */
1888         if (s->cert->shared_sigalgs)
1889                 {
1890                 OPENSSL_free(s->cert->shared_sigalgs);
1891                 s->cert->shared_sigalgs = NULL;
1892                 }
1893         /* Clear certificate digests and validity flags */
1894         for (i = 0; i < SSL_PKEY_NUM; i++)
1895                 {
1896                 s->cert->pkeys[i].digest = NULL;
1897                 s->cert->pkeys[i].valid_flags = 0;
1898                 }
1899
1900         if (data >= (d+n-2))
1901                 goto ri_check;
1902         n2s(data,len);
1903
1904         if (data > (d+n-len)) 
1905                 goto ri_check;
1906
1907         while (data <= (d+n-4))
1908                 {
1909                 n2s(data,type);
1910                 n2s(data,size);
1911
1912                 if (data+size > (d+n))
1913                         goto ri_check;
1914 #if 0
1915                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1916 #endif
1917                 if (s->tlsext_debug_cb)
1918                         s->tlsext_debug_cb(s, 0, type, data, size,
1919                                                 s->tlsext_debug_arg);
1920 /* The servername extension is treated as follows:
1921
1922    - Only the hostname type is supported with a maximum length of 255.
1923    - The servername is rejected if too long or if it contains zeros,
1924      in which case an fatal alert is generated.
1925    - The servername field is maintained together with the session cache.
1926    - When a session is resumed, the servername call back invoked in order
1927      to allow the application to position itself to the right context. 
1928    - The servername is acknowledged if it is new for a session or when 
1929      it is identical to a previously used for the same session. 
1930      Applications can control the behaviour.  They can at any time
1931      set a 'desirable' servername for a new SSL object. This can be the
1932      case for example with HTTPS when a Host: header field is received and
1933      a renegotiation is requested. In this case, a possible servername
1934      presented in the new client hello is only acknowledged if it matches
1935      the value of the Host: field. 
1936    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1937      if they provide for changing an explicit servername context for the session,
1938      i.e. when the session has been established with a servername extension. 
1939    - On session reconnect, the servername extension may be absent. 
1940
1941 */      
1942
1943                 if (type == TLSEXT_TYPE_server_name)
1944                         {
1945                         unsigned char *sdata;
1946                         int servname_type;
1947                         int dsize; 
1948                 
1949                         if (size < 2) 
1950                                 {
1951                                 *al = SSL_AD_DECODE_ERROR;
1952                                 return 0;
1953                                 }
1954                         n2s(data,dsize);  
1955                         size -= 2;
1956                         if (dsize > size  ) 
1957                                 {
1958                                 *al = SSL_AD_DECODE_ERROR;
1959                                 return 0;
1960                                 } 
1961
1962                         sdata = data;
1963                         while (dsize > 3) 
1964                                 {
1965                                 servname_type = *(sdata++); 
1966                                 n2s(sdata,len);
1967                                 dsize -= 3;
1968
1969                                 if (len > dsize) 
1970                                         {
1971                                         *al = SSL_AD_DECODE_ERROR;
1972                                         return 0;
1973                                         }
1974                                 if (s->servername_done == 0)
1975                                 switch (servname_type)
1976                                         {
1977                                 case TLSEXT_NAMETYPE_host_name:
1978                                         if (!s->hit)
1979                                                 {
1980                                                 if(s->session->tlsext_hostname)
1981                                                         {
1982                                                         *al = SSL_AD_DECODE_ERROR;
1983                                                         return 0;
1984                                                         }
1985                                                 if (len > TLSEXT_MAXLEN_host_name)
1986                                                         {
1987                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1988                                                         return 0;
1989                                                         }
1990                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
1991                                                         {
1992                                                         *al = TLS1_AD_INTERNAL_ERROR;
1993                                                         return 0;
1994                                                         }
1995                                                 memcpy(s->session->tlsext_hostname, sdata, len);
1996                                                 s->session->tlsext_hostname[len]='\0';
1997                                                 if (strlen(s->session->tlsext_hostname) != len) {
1998                                                         OPENSSL_free(s->session->tlsext_hostname);
1999                                                         s->session->tlsext_hostname = NULL;
2000                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
2001                                                         return 0;
2002                                                 }
2003                                                 s->servername_done = 1; 
2004
2005                                                 }
2006                                         else 
2007                                                 s->servername_done = s->session->tlsext_hostname
2008                                                         && strlen(s->session->tlsext_hostname) == len 
2009                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
2010                                         
2011                                         break;
2012
2013                                 default:
2014                                         break;
2015                                         }
2016                                  
2017                                 dsize -= len;
2018                                 }
2019                         if (dsize != 0) 
2020                                 {
2021                                 *al = SSL_AD_DECODE_ERROR;
2022                                 return 0;
2023                                 }
2024
2025                         }
2026 #ifndef OPENSSL_NO_SRP
2027                 else if (type == TLSEXT_TYPE_srp)
2028                         {
2029                         if (size <= 0 || ((len = data[0])) != (size -1))
2030                                 {
2031                                 *al = SSL_AD_DECODE_ERROR;
2032                                 return 0;
2033                                 }
2034                         if (s->srp_ctx.login != NULL)
2035                                 {
2036                                 *al = SSL_AD_DECODE_ERROR;
2037                                 return 0;
2038                                 }
2039                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
2040                                 return -1;
2041                         memcpy(s->srp_ctx.login, &data[1], len);
2042                         s->srp_ctx.login[len]='\0';
2043   
2044                         if (strlen(s->srp_ctx.login) != len) 
2045                                 {
2046                                 *al = SSL_AD_DECODE_ERROR;
2047                                 return 0;
2048                                 }
2049                         }
2050 #endif
2051
2052 #ifndef OPENSSL_NO_EC
2053                 else if (type == TLSEXT_TYPE_ec_point_formats &&
2054                      s->version != DTLS1_VERSION)
2055                         {
2056                         unsigned char *sdata = data;
2057                         int ecpointformatlist_length = *(sdata++);
2058
2059                         if (ecpointformatlist_length != size - 1 || 
2060                                 ecpointformatlist_length < 1)
2061                                 {
2062                                 *al = TLS1_AD_DECODE_ERROR;
2063                                 return 0;
2064                                 }
2065                         if (!s->hit)
2066                                 {
2067                                 if(s->session->tlsext_ecpointformatlist)
2068                                         {
2069                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
2070                                         s->session->tlsext_ecpointformatlist = NULL;
2071                                         }
2072                                 s->session->tlsext_ecpointformatlist_length = 0;
2073                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2074                                         {
2075                                         *al = TLS1_AD_INTERNAL_ERROR;
2076                                         return 0;
2077                                         }
2078                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2079                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2080                                 }
2081 #if 0
2082                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
2083                         sdata = s->session->tlsext_ecpointformatlist;
2084                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2085                                 fprintf(stderr,"%i ",*(sdata++));
2086                         fprintf(stderr,"\n");
2087 #endif
2088                         }
2089                 else if (type == TLSEXT_TYPE_elliptic_curves &&
2090                      s->version != DTLS1_VERSION)
2091                         {
2092                         unsigned char *sdata = data;
2093                         int ellipticcurvelist_length = (*(sdata++) << 8);
2094                         ellipticcurvelist_length += (*(sdata++));
2095
2096                         if (ellipticcurvelist_length != size - 2 ||
2097                                 ellipticcurvelist_length < 1)
2098                                 {
2099                                 *al = TLS1_AD_DECODE_ERROR;
2100                                 return 0;
2101                                 }
2102                         if (!s->hit)
2103                                 {
2104                                 if(s->session->tlsext_ellipticcurvelist)
2105                                         {
2106                                         *al = TLS1_AD_DECODE_ERROR;
2107                                         return 0;
2108                                         }
2109                                 s->session->tlsext_ellipticcurvelist_length = 0;
2110                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
2111                                         {
2112                                         *al = TLS1_AD_INTERNAL_ERROR;
2113                                         return 0;
2114                                         }
2115                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
2116                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
2117                                 }
2118 #if 0
2119                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
2120                         sdata = s->session->tlsext_ellipticcurvelist;
2121                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2122                                 fprintf(stderr,"%i ",*(sdata++));
2123                         fprintf(stderr,"\n");
2124 #endif
2125                         }
2126 #endif /* OPENSSL_NO_EC */
2127 #ifdef TLSEXT_TYPE_opaque_prf_input
2128                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
2129                      s->version != DTLS1_VERSION)
2130                         {
2131                         unsigned char *sdata = data;
2132
2133                         if (size < 2)
2134                                 {
2135                                 *al = SSL_AD_DECODE_ERROR;
2136                                 return 0;
2137                                 }
2138                         n2s(sdata, s->s3->client_opaque_prf_input_len);
2139                         if (s->s3->client_opaque_prf_input_len != size - 2)
2140                                 {
2141                                 *al = SSL_AD_DECODE_ERROR;
2142                                 return 0;
2143                                 }
2144
2145                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2146                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2147                         if (s->s3->client_opaque_prf_input_len == 0)
2148                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2149                         else
2150                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2151                         if (s->s3->client_opaque_prf_input == NULL)
2152                                 {
2153                                 *al = TLS1_AD_INTERNAL_ERROR;
2154                                 return 0;
2155                                 }
2156                         }
2157 #endif
2158                 else if (type == TLSEXT_TYPE_session_ticket)
2159                         {
2160                         if (s->tls_session_ticket_ext_cb &&
2161                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2162                                 {
2163                                 *al = TLS1_AD_INTERNAL_ERROR;
2164                                 return 0;
2165                                 }
2166                         }
2167                 else if (type == TLSEXT_TYPE_renegotiate)
2168                         {
2169                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2170                                 return 0;
2171                         renegotiate_seen = 1;
2172                         }
2173                 else if (type == TLSEXT_TYPE_signature_algorithms)
2174                         {
2175                         int dsize;
2176                         if (s->cert->peer_sigalgs || size < 2) 
2177                                 {
2178                                 *al = SSL_AD_DECODE_ERROR;
2179                                 return 0;
2180                                 }
2181                         n2s(data,dsize);
2182                         size -= 2;
2183                         if (dsize != size || dsize & 1 || !dsize) 
2184                                 {
2185                                 *al = SSL_AD_DECODE_ERROR;
2186                                 return 0;
2187                                 }
2188                         if (!tls1_process_sigalgs(s, data, dsize))
2189                                 {
2190                                 *al = SSL_AD_DECODE_ERROR;
2191                                 return 0;
2192                                 }
2193                         /* If sigalgs received and no shared algorithms fatal
2194                          * error.
2195                          */
2196                         if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
2197                                 {
2198                                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2199                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
2200                                 *al = SSL_AD_ILLEGAL_PARAMETER;
2201                                 return 0;
2202                                 }
2203                         }
2204                 else if (type == TLSEXT_TYPE_status_request &&
2205                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
2206                         {
2207                 
2208                         if (size < 5) 
2209                                 {
2210                                 *al = SSL_AD_DECODE_ERROR;
2211                                 return 0;
2212                                 }
2213
2214                         s->tlsext_status_type = *data++;
2215                         size--;
2216                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
2217                                 {
2218                                 const unsigned char *sdata;
2219                                 int dsize;
2220                                 /* Read in responder_id_list */
2221                                 n2s(data,dsize);
2222                                 size -= 2;
2223                                 if (dsize > size  ) 
2224                                         {
2225                                         *al = SSL_AD_DECODE_ERROR;
2226                                         return 0;
2227                                         }
2228                                 while (dsize > 0)
2229                                         {
2230                                         OCSP_RESPID *id;
2231                                         int idsize;
2232                                         if (dsize < 4)
2233                                                 {
2234                                                 *al = SSL_AD_DECODE_ERROR;
2235                                                 return 0;
2236                                                 }
2237                                         n2s(data, idsize);
2238                                         dsize -= 2 + idsize;
2239                                         size -= 2 + idsize;
2240                                         if (dsize < 0)
2241                                                 {
2242                                                 *al = SSL_AD_DECODE_ERROR;
2243                                                 return 0;
2244                                                 }
2245                                         sdata = data;
2246                                         data += idsize;
2247                                         id = d2i_OCSP_RESPID(NULL,
2248                                                                 &sdata, idsize);
2249                                         if (!id)
2250                                                 {
2251                                                 *al = SSL_AD_DECODE_ERROR;
2252                                                 return 0;
2253                                                 }
2254                                         if (data != sdata)
2255                                                 {
2256                                                 OCSP_RESPID_free(id);
2257                                                 *al = SSL_AD_DECODE_ERROR;
2258                                                 return 0;
2259                                                 }
2260                                         if (!s->tlsext_ocsp_ids
2261                                                 && !(s->tlsext_ocsp_ids =
2262                                                 sk_OCSP_RESPID_new_null()))
2263                                                 {
2264                                                 OCSP_RESPID_free(id);
2265                                                 *al = SSL_AD_INTERNAL_ERROR;
2266                                                 return 0;
2267                                                 }
2268                                         if (!sk_OCSP_RESPID_push(
2269                                                         s->tlsext_ocsp_ids, id))
2270                                                 {
2271                                                 OCSP_RESPID_free(id);
2272                                                 *al = SSL_AD_INTERNAL_ERROR;
2273                                                 return 0;
2274                                                 }
2275                                         }
2276
2277                                 /* Read in request_extensions */
2278                                 if (size < 2)
2279                                         {
2280                                         *al = SSL_AD_DECODE_ERROR;
2281                                         return 0;
2282                                         }
2283                                 n2s(data,dsize);
2284                                 size -= 2;
2285                                 if (dsize != size)
2286                                         {
2287                                         *al = SSL_AD_DECODE_ERROR;
2288                                         return 0;
2289                                         }
2290                                 sdata = data;
2291                                 if (dsize > 0)
2292                                         {
2293                                         if (s->tlsext_ocsp_exts)
2294                                                 {
2295                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2296                                                                            X509_EXTENSION_free);
2297                                                 }
2298
2299                                         s->tlsext_ocsp_exts =
2300                                                 d2i_X509_EXTENSIONS(NULL,
2301                                                         &sdata, dsize);
2302                                         if (!s->tlsext_ocsp_exts
2303                                                 || (data + dsize != sdata))
2304                                                 {
2305                                                 *al = SSL_AD_DECODE_ERROR;
2306                                                 return 0;
2307                                                 }
2308                                         }
2309                                 }
2310                                 /* We don't know what to do with any other type
2311                                 * so ignore it.
2312                                 */
2313                                 else
2314                                         s->tlsext_status_type = -1;
2315                         }
2316 #ifndef OPENSSL_NO_HEARTBEATS
2317                 else if (type == TLSEXT_TYPE_heartbeat)
2318                         {
2319                         switch(data[0])
2320                                 {
2321                                 case 0x01:      /* Client allows us to send HB requests */
2322                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2323                                                         break;
2324                                 case 0x02:      /* Client doesn't accept HB requests */
2325                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2326                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2327                                                         break;
2328                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2329                                                         return 0;
2330                                 }
2331                         }
2332 #endif
2333 #ifndef OPENSSL_NO_NEXTPROTONEG
2334                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2335                          s->s3->tmp.finish_md_len == 0)
2336                         {
2337                         /* We shouldn't accept this extension on a
2338                          * renegotiation.
2339                          *
2340                          * s->new_session will be set on renegotiation, but we
2341                          * probably shouldn't rely that it couldn't be set on
2342                          * the initial renegotation too in certain cases (when
2343                          * there's some other reason to disallow resuming an
2344                          * earlier session -- the current code won't be doing
2345                          * anything like that, but this might change).
2346
2347                          * A valid sign that there's been a previous handshake
2348                          * in this connection is if s->s3->tmp.finish_md_len >
2349                          * 0.  (We are talking about a check that will happen
2350                          * in the Hello protocol round, well before a new
2351                          * Finished message could have been computed.) */
2352                         s->s3->next_proto_neg_seen = 1;
2353                         }
2354 #endif
2355
2356                 /* session ticket processed earlier */
2357                 else if (type == TLSEXT_TYPE_use_srtp)
2358                         {
2359                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2360                                                               al))
2361                                 return 0;
2362                         }
2363
2364                 else if (type == TLSEXT_TYPE_server_authz)
2365                         {
2366                         unsigned char *sdata = data;
2367                         unsigned char server_authz_dataformatlist_length;
2368
2369                         if (size == 0)
2370                                 {
2371                                 *al = TLS1_AD_DECODE_ERROR;
2372                                 return 0;
2373                                 }
2374
2375                         server_authz_dataformatlist_length = *(sdata++);
2376
2377                         if (server_authz_dataformatlist_length != size - 1)
2378                                 {
2379                                 *al = TLS1_AD_DECODE_ERROR;
2380                                 return 0;
2381                                 }
2382
2383                         /* Successful session resumption uses the same authz
2384                          * information as the original session so we ignore this
2385                          * in the case of a session resumption. */
2386                         if (!s->hit)
2387                                 {
2388                                 if (s->s3->tlsext_authz_client_types != NULL)
2389                                         OPENSSL_free(s->s3->tlsext_authz_client_types);
2390                                 s->s3->tlsext_authz_client_types =
2391                                         OPENSSL_malloc(server_authz_dataformatlist_length);
2392                                 if (!s->s3->tlsext_authz_client_types)
2393                                         {
2394                                         *al = TLS1_AD_INTERNAL_ERROR;
2395                                         return 0;
2396                                         }
2397
2398                                 s->s3->tlsext_authz_client_types_len =
2399                                         server_authz_dataformatlist_length;
2400                                 memcpy(s->s3->tlsext_authz_client_types,
2401                                        sdata,
2402                                        server_authz_dataformatlist_length);
2403
2404                                 /* Sort the types in order to check for duplicates. */
2405                                 qsort(s->s3->tlsext_authz_client_types,
2406                                       server_authz_dataformatlist_length,
2407                                       1 /* element size */,
2408                                       byte_compare);
2409
2410                                 for (i = 0; i < server_authz_dataformatlist_length; i++)
2411                                         {
2412                                         if (i > 0 &&
2413                                             s->s3->tlsext_authz_client_types[i] ==
2414                                               s->s3->tlsext_authz_client_types[i-1])
2415                                                 {
2416                                                 *al = TLS1_AD_DECODE_ERROR;
2417                                                 return 0;
2418                                                 }
2419                                         }
2420                                 }
2421                         }
2422
2423                 /* If this ClientHello extension was unhandled and this is 
2424                  * a nonresumed connection, check whether the extension is a 
2425                  * custom TLS Extension (has a custom_srv_ext_record), and if
2426                  * so call the callback and record the extension number so that
2427                  * an appropriate ServerHello may be later returned.
2428                  */
2429                 else if (!s->hit && s->ctx->custom_srv_ext_records_count)
2430                         {
2431                         custom_srv_ext_record *record;
2432
2433                         for (i=0; i < s->ctx->custom_srv_ext_records_count; i++)
2434                                 {
2435                                 record = &s->ctx->custom_srv_ext_records[i];
2436                                 if (type == record->ext_type)
2437                                         {
2438                                         size_t j;
2439
2440                                         /* Error on duplicate TLS Extensions */
2441                                         for (j = 0; j < s->s3->tlsext_custom_types_count; j++)
2442                                                 {
2443                                                 if (type == s->s3->tlsext_custom_types[j])
2444                                                         {
2445                                                         *al = TLS1_AD_DECODE_ERROR;
2446                                                         return 0;
2447                                                         }
2448                                                 }
2449
2450                                         /* NULL callback still notes the extension */ 
2451                                         if (record->fn1 && !record->fn1(s, type, data, size, al, record->arg))
2452                                                 return 0;
2453                                                 
2454                                         /* Add the (non-duplicated) entry */
2455                                         s->s3->tlsext_custom_types_count++;
2456                                         s->s3->tlsext_custom_types = OPENSSL_realloc(
2457                                                         s->s3->tlsext_custom_types,
2458                                                         s->s3->tlsext_custom_types_count * 2);
2459                                         if (s->s3->tlsext_custom_types == NULL)
2460                                                 {
2461                                                 s->s3->tlsext_custom_types = 0;
2462                                                 *al = TLS1_AD_INTERNAL_ERROR;
2463                                                 return 0;
2464                                                 }
2465                                         s->s3->tlsext_custom_types[
2466                                                         s->s3->tlsext_custom_types_count - 1] = type;
2467                                         }                                               
2468                                 }
2469                         }
2470
2471                 data+=size;
2472                 }
2473
2474         *p = data;
2475
2476         ri_check:
2477
2478         /* Need RI if renegotiating */
2479
2480         if (!renegotiate_seen && s->renegotiate &&
2481                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2482                 {
2483                 *al = SSL_AD_HANDSHAKE_FAILURE;
2484                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2485                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2486                 return 0;
2487                 }
2488         /* If no signature algorithms extension set default values */
2489         if (!s->cert->peer_sigalgs)
2490                 ssl_cert_set_default_md(s->cert);
2491
2492         return 1;
2493         }
2494
2495 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2496         {
2497         int al = -1;
2498         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2499                 {
2500                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2501                 return 0;
2502                 }
2503
2504         if (ssl_check_clienthello_tlsext_early(s) <= 0) 
2505                 {
2506                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2507                 return 0;
2508                 }
2509         return 1;
2510 }
2511
2512 #ifndef OPENSSL_NO_NEXTPROTONEG
2513 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2514  * elements of zero length are allowed and the set of elements must exactly fill
2515  * the length of the block. */
2516 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2517         {
2518         unsigned int off = 0;
2519
2520         while (off < len)
2521                 {
2522                 if (d[off] == 0)
2523                         return 0;
2524                 off += d[off];
2525                 off++;
2526                 }
2527
2528         return off == len;
2529         }
2530 #endif
2531
2532 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2533         {
2534         unsigned short length;
2535         unsigned short type;
2536         unsigned short size;
2537         unsigned char *data = *p;
2538         int tlsext_servername = 0;
2539         int renegotiate_seen = 0;
2540
2541 #ifndef OPENSSL_NO_NEXTPROTONEG
2542         s->s3->next_proto_neg_seen = 0;
2543 #endif
2544
2545 #ifndef OPENSSL_NO_HEARTBEATS
2546         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2547                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2548 #endif
2549
2550         if (data >= (d+n-2))
2551                 goto ri_check;
2552
2553         n2s(data,length);
2554         if (data+length != d+n)
2555                 {
2556                 *al = SSL_AD_DECODE_ERROR;
2557                 return 0;
2558                 }
2559
2560         while(data <= (d+n-4))
2561                 {
2562                 n2s(data,type);
2563                 n2s(data,size);
2564
2565                 if (data+size > (d+n))
2566                         goto ri_check;
2567
2568                 if (s->tlsext_debug_cb)
2569                         s->tlsext_debug_cb(s, 1, type, data, size,
2570                                                 s->tlsext_debug_arg);
2571
2572                 if (type == TLSEXT_TYPE_server_name)
2573                         {
2574                         if (s->tlsext_hostname == NULL || size > 0)
2575                                 {
2576                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2577                                 return 0;
2578                                 }
2579                         tlsext_servername = 1;   
2580                         }
2581
2582 #ifndef OPENSSL_NO_EC
2583                 else if (type == TLSEXT_TYPE_ec_point_formats &&
2584                      s->version != DTLS1_VERSION)
2585                         {
2586                         unsigned char *sdata = data;
2587                         int ecpointformatlist_length = *(sdata++);
2588
2589                         if (ecpointformatlist_length != size - 1)
2590                                 {
2591                                 *al = TLS1_AD_DECODE_ERROR;
2592                                 return 0;
2593                                 }
2594                         s->session->tlsext_ecpointformatlist_length = 0;
2595                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2596                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2597                                 {
2598                                 *al = TLS1_AD_INTERNAL_ERROR;
2599                                 return 0;
2600                                 }
2601                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2602                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2603 #if 0
2604                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2605                         sdata = s->session->tlsext_ecpointformatlist;
2606                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2607                                 fprintf(stderr,"%i ",*(sdata++));
2608                         fprintf(stderr,"\n");
2609 #endif
2610                         }
2611 #endif /* OPENSSL_NO_EC */
2612
2613                 else if (type == TLSEXT_TYPE_session_ticket)
2614                         {
2615                         if (s->tls_session_ticket_ext_cb &&
2616                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2617                                 {
2618                                 *al = TLS1_AD_INTERNAL_ERROR;
2619                                 return 0;
2620                                 }
2621                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2622                                 || (size > 0))
2623                                 {
2624                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2625                                 return 0;
2626                                 }
2627                         s->tlsext_ticket_expected = 1;
2628                         }
2629 #ifdef TLSEXT_TYPE_opaque_prf_input
2630                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
2631                      s->version != DTLS1_VERSION)
2632                         {
2633                         unsigned char *sdata = data;
2634
2635                         if (size < 2)
2636                                 {
2637                                 *al = SSL_AD_DECODE_ERROR;
2638                                 return 0;
2639                                 }
2640                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2641                         if (s->s3->server_opaque_prf_input_len != size - 2)
2642                                 {
2643                                 *al = SSL_AD_DECODE_ERROR;
2644                                 return 0;
2645                                 }
2646                         
2647                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2648                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2649                         if (s->s3->server_opaque_prf_input_len == 0)
2650                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2651                         else
2652                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2653
2654                         if (s->s3->server_opaque_prf_input == NULL)
2655                                 {
2656                                 *al = TLS1_AD_INTERNAL_ERROR;
2657                                 return 0;
2658                                 }
2659                         }
2660 #endif
2661                 else if (type == TLSEXT_TYPE_status_request &&
2662                          s->version != DTLS1_VERSION)
2663                         {
2664                         /* MUST be empty and only sent if we've requested
2665                          * a status request message.
2666                          */ 
2667                         if ((s->tlsext_status_type == -1) || (size > 0))
2668                                 {
2669                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2670                                 return 0;
2671                                 }
2672                         /* Set flag to expect CertificateStatus message */
2673                         s->tlsext_status_expected = 1;
2674                         }
2675 #ifndef OPENSSL_NO_NEXTPROTONEG
2676                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2677                          s->s3->tmp.finish_md_len == 0)
2678                         {
2679                         unsigned char *selected;
2680                         unsigned char selected_len;
2681
2682                         /* We must have requested it. */
2683                         if (s->ctx->next_proto_select_cb == NULL)
2684                                 {
2685                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2686                                 return 0;
2687                                 }
2688                         /* The data must be valid */
2689                         if (!ssl_next_proto_validate(data, size))
2690                                 {
2691                                 *al = TLS1_AD_DECODE_ERROR;
2692                                 return 0;
2693                                 }
2694                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2695                                 {
2696                                 *al = TLS1_AD_INTERNAL_ERROR;
2697                                 return 0;
2698                                 }
2699                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2700                         if (!s->next_proto_negotiated)
2701                                 {
2702                                 *al = TLS1_AD_INTERNAL_ERROR;
2703                                 return 0;
2704                                 }
2705                         memcpy(s->next_proto_negotiated, selected, selected_len);
2706                         s->next_proto_negotiated_len = selected_len;
2707                         s->s3->next_proto_neg_seen = 1;
2708                         }
2709 #endif
2710                 else if (type == TLSEXT_TYPE_renegotiate)
2711                         {
2712                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2713                                 return 0;
2714                         renegotiate_seen = 1;
2715                         }
2716 #ifndef OPENSSL_NO_HEARTBEATS
2717                 else if (type == TLSEXT_TYPE_heartbeat)
2718                         {
2719                         switch(data[0])
2720                                 {
2721                                 case 0x01:      /* Server allows us to send HB requests */
2722                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2723                                                         break;
2724                                 case 0x02:      /* Server doesn't accept HB requests */
2725                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2726                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2727                                                         break;
2728                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2729                                                         return 0;
2730                                 }
2731                         }
2732 #endif
2733                 else if (type == TLSEXT_TYPE_use_srtp)
2734                         {
2735                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2736                                                               al))
2737                                 return 0;
2738                         }
2739
2740                 else if (type == TLSEXT_TYPE_server_authz)
2741                         {
2742                         /* We only support audit proofs. It's an error to send
2743                          * an authz hello extension if the client
2744                          * didn't request a proof. */
2745                         unsigned char *sdata = data;
2746                         unsigned char server_authz_dataformatlist_length;
2747
2748                         if (!s->ctx->tlsext_authz_server_audit_proof_cb)
2749                                 {
2750                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2751                                 return 0;
2752                                 }
2753
2754                         if (!size)
2755                                 {
2756                                 *al = TLS1_AD_DECODE_ERROR;
2757                                 return 0;
2758                                 }
2759
2760                         server_authz_dataformatlist_length = *(sdata++);
2761                         if (server_authz_dataformatlist_length != size - 1)
2762                                 {
2763                                 *al = TLS1_AD_DECODE_ERROR;
2764                                 return 0;
2765                                 }
2766
2767                         /* We only support audit proofs, so a legal ServerHello
2768                          * authz list contains exactly one entry. */
2769                         if (server_authz_dataformatlist_length != 1 ||
2770                                 sdata[0] != TLSEXT_AUTHZDATAFORMAT_audit_proof)
2771                                 {
2772                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2773                                 return 0;
2774                                 }
2775
2776                         s->s3->tlsext_authz_server_promised = 1;
2777                         }
2778
2779                 /* If this extension type was not otherwise handled, but 
2780                  * matches a custom_cli_ext_record, then send it to the c
2781                  * callback */
2782                 else if (s->ctx->custom_cli_ext_records_count)
2783                         {
2784                         size_t i;
2785                         custom_cli_ext_record* record;
2786
2787                         for (i = 0; i < s->ctx->custom_cli_ext_records_count; i++)
2788                                 {
2789                                 record = &s->ctx->custom_cli_ext_records[i];
2790                                 if (record->ext_type == type)
2791                                         {
2792                                         if (record->fn2 && !record->fn2(s, type, data, size, al, record->arg))
2793                                                 return 0;
2794                                         break;
2795                                         }
2796                                 }                       
2797                         }
2798  
2799                 data += size;
2800                 }
2801
2802         if (data != d+n)
2803                 {
2804                 *al = SSL_AD_DECODE_ERROR;
2805                 return 0;
2806                 }
2807
2808         if (!s->hit && tlsext_servername == 1)
2809                 {
2810                 if (s->tlsext_hostname)
2811                         {
2812                         if (s->session->tlsext_hostname == NULL)
2813                                 {
2814                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2815                                 if (!s->session->tlsext_hostname)
2816                                         {
2817                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2818                                         return 0;
2819                                         }
2820                                 }
2821                         else 
2822                                 {
2823                                 *al = SSL_AD_DECODE_ERROR;
2824                                 return 0;
2825                                 }
2826                         }
2827                 }
2828
2829         *p = data;
2830
2831         ri_check:
2832
2833         /* Determine if we need to see RI. Strictly speaking if we want to
2834          * avoid an attack we should *always* see RI even on initial server
2835          * hello because the client doesn't see any renegotiation during an
2836          * attack. However this would mean we could not connect to any server
2837          * which doesn't support RI so for the immediate future tolerate RI
2838          * absence on initial connect only.
2839          */
2840         if (!renegotiate_seen
2841                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2842                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2843                 {
2844                 *al = SSL_AD_HANDSHAKE_FAILURE;
2845                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2846                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2847                 return 0;
2848                 }
2849
2850         return 1;
2851         }
2852
2853
2854 int ssl_prepare_clienthello_tlsext(SSL *s)
2855         {
2856
2857 #ifdef TLSEXT_TYPE_opaque_prf_input
2858         {
2859                 int r = 1;
2860         
2861                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2862                         {
2863                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2864                         if (!r)
2865                                 return -1;
2866                         }
2867
2868                 if (s->tlsext_opaque_prf_input != NULL)
2869                         {
2870                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2871                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2872
2873                         if (s->tlsext_opaque_prf_input_len == 0)
2874                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2875                         else
2876                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2877                         if (s->s3->client_opaque_prf_input == NULL)
2878                                 {
2879                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2880                                 return -1;
2881                                 }
2882                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2883                         }
2884
2885                 if (r == 2)
2886                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2887                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2888         }
2889 #endif
2890
2891         return 1;
2892         }
2893
2894 int ssl_prepare_serverhello_tlsext(SSL *s)
2895         {
2896         return 1;
2897         }
2898
2899 static int ssl_check_clienthello_tlsext_early(SSL *s)
2900         {
2901         int ret=SSL_TLSEXT_ERR_NOACK;
2902         int al = SSL_AD_UNRECOGNIZED_NAME;
2903
2904 #ifndef OPENSSL_NO_EC
2905         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2906          * ssl3_choose_cipher in s3_lib.c.
2907          */
2908         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2909          * ssl3_choose_cipher in s3_lib.c.
2910          */
2911 #endif
2912
2913         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2914                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2915         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2916                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2917
2918 #ifdef TLSEXT_TYPE_opaque_prf_input
2919         {
2920                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2921                  * but we might be sending an alert in response to the client hello,
2922                  * so this has to happen here in
2923                  * ssl_check_clienthello_tlsext_early(). */
2924
2925                 int r = 1;
2926         
2927                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2928                         {
2929                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2930                         if (!r)
2931                                 {
2932                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2933                                 al = SSL_AD_INTERNAL_ERROR;
2934                                 goto err;
2935                                 }
2936                         }
2937
2938                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2939                         OPENSSL_free(s->s3->server_opaque_prf_input);
2940                 s->s3->server_opaque_prf_input = NULL;
2941
2942                 if (s->tlsext_opaque_prf_input != NULL)
2943                         {
2944                         if (s->s3->client_opaque_prf_input != NULL &&
2945                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2946                                 {
2947                                 /* can only use this extension if we have a server opaque PRF input
2948                                  * of the same length as the client opaque PRF input! */
2949
2950                                 if (s->tlsext_opaque_prf_input_len == 0)
2951                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2952                                 else
2953                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2954                                 if (s->s3->server_opaque_prf_input == NULL)
2955                                         {
2956                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2957                                         al = SSL_AD_INTERNAL_ERROR;
2958                                         goto err;
2959                                         }
2960                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2961                                 }
2962                         }
2963
2964                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2965                         {
2966                         /* The callback wants to enforce use of the extension,
2967                          * but we can't do that with the client opaque PRF input;
2968                          * abort the handshake.
2969                          */
2970                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2971                         al = SSL_AD_HANDSHAKE_FAILURE;
2972                         }
2973         }
2974
2975  err:
2976 #endif
2977         switch (ret)
2978                 {
2979                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2980                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2981                         return -1;
2982
2983                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2984                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2985                         return 1; 
2986                                         
2987                 case SSL_TLSEXT_ERR_NOACK:
2988                         s->servername_done=0;
2989                         default:
2990                 return 1;
2991                 }
2992         }
2993
2994 int ssl_check_clienthello_tlsext_late(SSL *s)
2995         {
2996         int ret = SSL_TLSEXT_ERR_OK;
2997         int al;
2998
2999         /* If status request then ask callback what to do.
3000          * Note: this must be called after servername callbacks in case
3001          * the certificate has changed, and must be called after the cipher
3002          * has been chosen because this may influence which certificate is sent
3003          */
3004         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
3005                 {
3006                 int r;
3007                 CERT_PKEY *certpkey;
3008                 certpkey = ssl_get_server_send_pkey(s);
3009                 /* If no certificate can't return certificate status */
3010                 if (certpkey == NULL)
3011                         {
3012                         s->tlsext_status_expected = 0;
3013                         return 1;
3014                         }
3015                 /* Set current certificate to one we will use so
3016                  * SSL_get_certificate et al can pick it up.
3017                  */
3018                 s->cert->key = certpkey;
3019                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3020                 switch (r)