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