Use enc_flags when deciding protocol variations.
[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 != DTLS1_VERSION && s->version >= TLS1_VERSION)
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             s->version != DTLS1_VERSION)
1317                 {
1318                 size_t col = s->s3->client_opaque_prf_input_len;
1319                 
1320                 if ((long)(limit - ret - 6 - col < 0))
1321                         return NULL;
1322                 if (col > 0xFFFD) /* can't happen */
1323                         return NULL;
1324
1325                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1326                 s2n(col + 2, ret);
1327                 s2n(col, ret);
1328                 memcpy(ret, s->s3->client_opaque_prf_input, col);
1329                 ret += col;
1330                 }
1331 #endif
1332
1333         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
1334             s->version != DTLS1_VERSION)
1335                 {
1336                 int i;
1337                 long extlen, idlen, itmp;
1338                 OCSP_RESPID *id;
1339
1340                 idlen = 0;
1341                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1342                         {
1343                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1344                         itmp = i2d_OCSP_RESPID(id, NULL);
1345                         if (itmp <= 0)
1346                                 return NULL;
1347                         idlen += itmp + 2;
1348                         }
1349
1350                 if (s->tlsext_ocsp_exts)
1351                         {
1352                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1353                         if (extlen < 0)
1354                                 return NULL;
1355                         }
1356                 else
1357                         extlen = 0;
1358                         
1359                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1360                 s2n(TLSEXT_TYPE_status_request, ret);
1361                 if (extlen + idlen > 0xFFF0)
1362                         return NULL;
1363                 s2n(extlen + idlen + 5, ret);
1364                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1365                 s2n(idlen, ret);
1366                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1367                         {
1368                         /* save position of id len */
1369                         unsigned char *q = ret;
1370                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1371                         /* skip over id len */
1372                         ret += 2;
1373                         itmp = i2d_OCSP_RESPID(id, &ret);
1374                         /* write id len */
1375                         s2n(itmp, q);
1376                         }
1377                 s2n(extlen, ret);
1378                 if (extlen > 0)
1379                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1380                 }
1381
1382 #ifndef OPENSSL_NO_HEARTBEATS
1383         /* Add Heartbeat extension */
1384         s2n(TLSEXT_TYPE_heartbeat,ret);
1385         s2n(1,ret);
1386         /* Set mode:
1387          * 1: peer may send requests
1388          * 2: peer not allowed to send requests
1389          */
1390         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1391                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1392         else
1393                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1394 #endif
1395
1396 #ifndef OPENSSL_NO_NEXTPROTONEG
1397         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1398                 {
1399                 /* The client advertises an emtpy extension to indicate its
1400                  * support for Next Protocol Negotiation */
1401                 if (limit - ret - 4 < 0)
1402                         return NULL;
1403                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1404                 s2n(0,ret);
1405                 }
1406 #endif
1407
1408         if(SSL_get_srtp_profiles(s))
1409                 {
1410                 int el;
1411
1412                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1413                 
1414                 if((limit - p - 4 - el) < 0) return NULL;
1415
1416                 s2n(TLSEXT_TYPE_use_srtp,ret);
1417                 s2n(el,ret);
1418
1419                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1420                         {
1421                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1422                         return NULL;
1423                         }
1424                 ret += el;
1425                 }
1426
1427         /* Add TLS extension Server_Authz_DataFormats to the ClientHello */
1428         /* 2 bytes for extension type */
1429         /* 2 bytes for extension length */
1430         /* 1 byte for the list length */
1431         /* 1 byte for the list (we only support audit proofs) */
1432         if (s->ctx->tlsext_authz_server_audit_proof_cb != NULL)
1433                 {
1434                 const unsigned short ext_len = 2;
1435                 const unsigned char list_len = 1;
1436
1437                 if (limit < ret + 6)
1438                         return NULL;
1439
1440                 s2n(TLSEXT_TYPE_server_authz, ret);
1441                 /* Extension length: 2 bytes */
1442                 s2n(ext_len, ret);
1443                 *(ret++) = list_len;
1444                 *(ret++) = TLSEXT_AUTHZDATAFORMAT_audit_proof;
1445                 }
1446
1447         if ((extdatalen = ret-p-2) == 0)
1448                 return p;
1449
1450         s2n(extdatalen,p);
1451         return ret;
1452         }
1453
1454 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1455         {
1456         int extdatalen=0;
1457         unsigned char *ret = p;
1458 #ifndef OPENSSL_NO_NEXTPROTONEG
1459         int next_proto_neg_seen;
1460 #endif
1461         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1462         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1463         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1464         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1465
1466         /* don't add extensions for SSLv3, unless doing secure renegotiation */
1467         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1468                 return p;
1469         
1470         ret+=2;
1471         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1472
1473         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1474                 { 
1475                 if ((long)(limit - ret - 4) < 0) return NULL; 
1476
1477                 s2n(TLSEXT_TYPE_server_name,ret);
1478                 s2n(0,ret);
1479                 }
1480
1481         if(s->s3->send_connection_binding)
1482         {
1483           int el;
1484           
1485           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1486               {
1487               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1488               return NULL;
1489               }
1490
1491           if((limit - p - 4 - el) < 0) return NULL;
1492           
1493           s2n(TLSEXT_TYPE_renegotiate,ret);
1494           s2n(el,ret);
1495
1496           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1497               {
1498               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1499               return NULL;
1500               }
1501
1502           ret += el;
1503         }
1504
1505 #ifndef OPENSSL_NO_EC
1506         if (using_ecc && s->version != DTLS1_VERSION)
1507                 {
1508                 const unsigned char *plist;
1509                 size_t plistlen;
1510                 /* Add TLS extension ECPointFormats to the ServerHello message */
1511                 long lenmax; 
1512
1513                 tls1_get_formatlist(s, &plist, &plistlen);
1514
1515                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1516                 if (plistlen > (size_t)lenmax) return NULL;
1517                 if (plistlen > 255)
1518                         {
1519                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1520                         return NULL;
1521                         }
1522                 
1523                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1524                 s2n(plistlen + 1,ret);
1525                 *(ret++) = (unsigned char) plistlen;
1526                 memcpy(ret, plist, plistlen);
1527                 ret+=plistlen;
1528
1529                 }
1530         /* Currently the server should not respond with a SupportedCurves extension */
1531 #endif /* OPENSSL_NO_EC */
1532
1533         if (s->tlsext_ticket_expected
1534                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
1535                 { 
1536                 if ((long)(limit - ret - 4) < 0) return NULL; 
1537                 s2n(TLSEXT_TYPE_session_ticket,ret);
1538                 s2n(0,ret);
1539                 }
1540
1541         if (s->tlsext_status_expected)
1542                 { 
1543                 if ((long)(limit - ret - 4) < 0) return NULL; 
1544                 s2n(TLSEXT_TYPE_status_request,ret);
1545                 s2n(0,ret);
1546                 }
1547
1548 #ifdef TLSEXT_TYPE_opaque_prf_input
1549         if (s->s3->server_opaque_prf_input != NULL &&
1550             s->version != DTLS1_VERSION)
1551                 {
1552                 size_t sol = s->s3->server_opaque_prf_input_len;
1553                 
1554                 if ((long)(limit - ret - 6 - sol) < 0)
1555                         return NULL;
1556                 if (sol > 0xFFFD) /* can't happen */
1557                         return NULL;
1558
1559                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1560                 s2n(sol + 2, ret);
1561                 s2n(sol, ret);
1562                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1563                 ret += sol;
1564                 }
1565 #endif
1566
1567         if(s->srtp_profile)
1568                 {
1569                 int el;
1570
1571                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1572                 
1573                 if((limit - p - 4 - el) < 0) return NULL;
1574
1575                 s2n(TLSEXT_TYPE_use_srtp,ret);
1576                 s2n(el,ret);
1577
1578                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1579                         {
1580                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1581                         return NULL;
1582                         }
1583                 ret+=el;
1584                 }
1585
1586         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1587                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1588                 { const unsigned char cryptopro_ext[36] = {
1589                         0xfd, 0xe8, /*65000*/
1590                         0x00, 0x20, /*32 bytes length*/
1591                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1592                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1593                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1594                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1595                         if (limit-ret<36) return NULL;
1596                         memcpy(ret,cryptopro_ext,36);
1597                         ret+=36;
1598
1599                 }
1600
1601 #ifndef OPENSSL_NO_HEARTBEATS
1602         /* Add Heartbeat extension if we've received one */
1603         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1604                 {
1605                 s2n(TLSEXT_TYPE_heartbeat,ret);
1606                 s2n(1,ret);
1607                 /* Set mode:
1608                  * 1: peer may send requests
1609                  * 2: peer not allowed to send requests
1610                  */
1611                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1612                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1613                 else
1614                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1615
1616                 }
1617 #endif
1618
1619 #ifndef OPENSSL_NO_NEXTPROTONEG
1620         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1621         s->s3->next_proto_neg_seen = 0;
1622         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1623                 {
1624                 const unsigned char *npa;
1625                 unsigned int npalen;
1626                 int r;
1627
1628                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1629                 if (r == SSL_TLSEXT_ERR_OK)
1630                         {
1631                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1632                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1633                         s2n(npalen,ret);
1634                         memcpy(ret, npa, npalen);
1635                         ret += npalen;
1636                         s->s3->next_proto_neg_seen = 1;
1637                         }
1638                 }
1639 #endif
1640
1641         /* If the client supports authz then see whether we have any to offer
1642          * to it. */
1643         if (s->s3->tlsext_authz_client_types_len)
1644                 {
1645                 size_t authz_length;
1646                 /* By now we already know the new cipher, so we can look ahead
1647                  * to see whether the cert we are going to send
1648                  * has any authz data attached to it. */
1649                 const unsigned char* authz = ssl_get_authz_data(s, &authz_length);
1650                 const unsigned char* const orig_authz = authz;
1651                 size_t i;
1652                 unsigned authz_count = 0;
1653
1654                 /* The authz data contains a number of the following structures:
1655                  *      uint8_t authz_type
1656                  *      uint16_t length
1657                  *      uint8_t data[length]
1658                  *
1659                  * First we walk over it to find the number of authz elements. */
1660                 for (i = 0; i < authz_length; i++)
1661                         {
1662                         unsigned short length;
1663                         unsigned char type;
1664
1665                         type = *(authz++);
1666                         if (memchr(s->s3->tlsext_authz_client_types,
1667                                    type,
1668                                    s->s3->tlsext_authz_client_types_len) != NULL)
1669                                 authz_count++;
1670
1671                         n2s(authz, length);
1672                         /* n2s increments authz by 2 */
1673                         i += 2;
1674                         authz += length;
1675                         i += length;
1676                         }
1677
1678                 if (authz_count)
1679                         {
1680                         /* Add TLS extension server_authz to the ServerHello message
1681                          * 2 bytes for extension type
1682                          * 2 bytes for extension length
1683                          * 1 byte for the list length
1684                          * n bytes for the list */
1685                         const unsigned short ext_len = 1 + authz_count;
1686
1687                         if ((long)(limit - ret - 4 - ext_len) < 0) return NULL;
1688                         s2n(TLSEXT_TYPE_server_authz, ret);
1689                         s2n(ext_len, ret);
1690                         *(ret++) = authz_count;
1691                         s->s3->tlsext_authz_promised_to_client = 1;
1692                         }
1693
1694                 authz = orig_authz;
1695                 for (i = 0; i < authz_length; i++)
1696                         {
1697                         unsigned short length;
1698                         unsigned char type;
1699
1700                         authz_count++;
1701                         type = *(authz++);
1702                         if (memchr(s->s3->tlsext_authz_client_types,
1703                                    type,
1704                                    s->s3->tlsext_authz_client_types_len) != NULL)
1705                                 *(ret++) = type;
1706                         n2s(authz, length);
1707                         /* n2s increments authz by 2 */
1708                         i += 2;
1709                         authz += length;
1710                         i += length;
1711                         }
1712                 }
1713
1714         if ((extdatalen = ret-p-2)== 0) 
1715                 return p;
1716
1717         s2n(extdatalen,p);
1718         return ret;
1719         }
1720
1721 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) 
1722         {       
1723         unsigned short type;
1724         unsigned short size;
1725         unsigned short len;
1726         unsigned char *data = *p;
1727         int renegotiate_seen = 0;
1728         size_t i;
1729
1730         s->servername_done = 0;
1731         s->tlsext_status_type = -1;
1732 #ifndef OPENSSL_NO_NEXTPROTONEG
1733         s->s3->next_proto_neg_seen = 0;
1734 #endif
1735
1736 #ifndef OPENSSL_NO_HEARTBEATS
1737         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1738                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1739 #endif
1740         /* Clear any signature algorithms extension received */
1741         if (s->cert->peer_sigalgs)
1742                 {
1743                 OPENSSL_free(s->cert->peer_sigalgs);
1744                 s->cert->peer_sigalgs = NULL;
1745                 }
1746         /* Clear any shared sigtnature algorithms */
1747         if (s->cert->shared_sigalgs)
1748                 {
1749                 OPENSSL_free(s->cert->shared_sigalgs);
1750                 s->cert->shared_sigalgs = NULL;
1751                 }
1752         /* Clear certificate digests and validity flags */
1753         for (i = 0; i < SSL_PKEY_NUM; i++)
1754                 {
1755                 s->cert->pkeys[i].digest = NULL;
1756                 s->cert->pkeys[i].valid_flags = 0;
1757                 }
1758
1759         if (data >= (d+n-2))
1760                 goto ri_check;
1761         n2s(data,len);
1762
1763         if (data > (d+n-len)) 
1764                 goto ri_check;
1765
1766         while (data <= (d+n-4))
1767                 {
1768                 n2s(data,type);
1769                 n2s(data,size);
1770
1771                 if (data+size > (d+n))
1772                         goto ri_check;
1773 #if 0
1774                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1775 #endif
1776                 if (s->tlsext_debug_cb)
1777                         s->tlsext_debug_cb(s, 0, type, data, size,
1778                                                 s->tlsext_debug_arg);
1779 /* The servername extension is treated as follows:
1780
1781    - Only the hostname type is supported with a maximum length of 255.
1782    - The servername is rejected if too long or if it contains zeros,
1783      in which case an fatal alert is generated.
1784    - The servername field is maintained together with the session cache.
1785    - When a session is resumed, the servername call back invoked in order
1786      to allow the application to position itself to the right context. 
1787    - The servername is acknowledged if it is new for a session or when 
1788      it is identical to a previously used for the same session. 
1789      Applications can control the behaviour.  They can at any time
1790      set a 'desirable' servername for a new SSL object. This can be the
1791      case for example with HTTPS when a Host: header field is received and
1792      a renegotiation is requested. In this case, a possible servername
1793      presented in the new client hello is only acknowledged if it matches
1794      the value of the Host: field. 
1795    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1796      if they provide for changing an explicit servername context for the session,
1797      i.e. when the session has been established with a servername extension. 
1798    - On session reconnect, the servername extension may be absent. 
1799
1800 */      
1801
1802                 if (type == TLSEXT_TYPE_server_name)
1803                         {
1804                         unsigned char *sdata;
1805                         int servname_type;
1806                         int dsize; 
1807                 
1808                         if (size < 2) 
1809                                 {
1810                                 *al = SSL_AD_DECODE_ERROR;
1811                                 return 0;
1812                                 }
1813                         n2s(data,dsize);  
1814                         size -= 2;
1815                         if (dsize > size  ) 
1816                                 {
1817                                 *al = SSL_AD_DECODE_ERROR;
1818                                 return 0;
1819                                 } 
1820
1821                         sdata = data;
1822                         while (dsize > 3) 
1823                                 {
1824                                 servname_type = *(sdata++); 
1825                                 n2s(sdata,len);
1826                                 dsize -= 3;
1827
1828                                 if (len > dsize) 
1829                                         {
1830                                         *al = SSL_AD_DECODE_ERROR;
1831                                         return 0;
1832                                         }
1833                                 if (s->servername_done == 0)
1834                                 switch (servname_type)
1835                                         {
1836                                 case TLSEXT_NAMETYPE_host_name:
1837                                         if (!s->hit)
1838                                                 {
1839                                                 if(s->session->tlsext_hostname)
1840                                                         {
1841                                                         *al = SSL_AD_DECODE_ERROR;
1842                                                         return 0;
1843                                                         }
1844                                                 if (len > TLSEXT_MAXLEN_host_name)
1845                                                         {
1846                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1847                                                         return 0;
1848                                                         }
1849                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
1850                                                         {
1851                                                         *al = TLS1_AD_INTERNAL_ERROR;
1852                                                         return 0;
1853                                                         }
1854                                                 memcpy(s->session->tlsext_hostname, sdata, len);
1855                                                 s->session->tlsext_hostname[len]='\0';
1856                                                 if (strlen(s->session->tlsext_hostname) != len) {
1857                                                         OPENSSL_free(s->session->tlsext_hostname);
1858                                                         s->session->tlsext_hostname = NULL;
1859                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1860                                                         return 0;
1861                                                 }
1862                                                 s->servername_done = 1; 
1863
1864                                                 }
1865                                         else 
1866                                                 s->servername_done = s->session->tlsext_hostname
1867                                                         && strlen(s->session->tlsext_hostname) == len 
1868                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
1869                                         
1870                                         break;
1871
1872                                 default:
1873                                         break;
1874                                         }
1875                                  
1876                                 dsize -= len;
1877                                 }
1878                         if (dsize != 0) 
1879                                 {
1880                                 *al = SSL_AD_DECODE_ERROR;
1881                                 return 0;
1882                                 }
1883
1884                         }
1885 #ifndef OPENSSL_NO_SRP
1886                 else if (type == TLSEXT_TYPE_srp)
1887                         {
1888                         if (size <= 0 || ((len = data[0])) != (size -1))
1889                                 {
1890                                 *al = SSL_AD_DECODE_ERROR;
1891                                 return 0;
1892                                 }
1893                         if (s->srp_ctx.login != NULL)
1894                                 {
1895                                 *al = SSL_AD_DECODE_ERROR;
1896                                 return 0;
1897                                 }
1898                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
1899                                 return -1;
1900                         memcpy(s->srp_ctx.login, &data[1], len);
1901                         s->srp_ctx.login[len]='\0';
1902   
1903                         if (strlen(s->srp_ctx.login) != len) 
1904                                 {
1905                                 *al = SSL_AD_DECODE_ERROR;
1906                                 return 0;
1907                                 }
1908                         }
1909 #endif
1910
1911 #ifndef OPENSSL_NO_EC
1912                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1913                      s->version != DTLS1_VERSION)
1914                         {
1915                         unsigned char *sdata = data;
1916                         int ecpointformatlist_length = *(sdata++);
1917
1918                         if (ecpointformatlist_length != size - 1 || 
1919                                 ecpointformatlist_length < 1)
1920                                 {
1921                                 *al = TLS1_AD_DECODE_ERROR;
1922                                 return 0;
1923                                 }
1924                         if (!s->hit)
1925                                 {
1926                                 if(s->session->tlsext_ecpointformatlist)
1927                                         {
1928                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
1929                                         s->session->tlsext_ecpointformatlist = NULL;
1930                                         }
1931                                 s->session->tlsext_ecpointformatlist_length = 0;
1932                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1933                                         {
1934                                         *al = TLS1_AD_INTERNAL_ERROR;
1935                                         return 0;
1936                                         }
1937                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1938                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1939                                 }
1940 #if 0
1941                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
1942                         sdata = s->session->tlsext_ecpointformatlist;
1943                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1944                                 fprintf(stderr,"%i ",*(sdata++));
1945                         fprintf(stderr,"\n");
1946 #endif
1947                         }
1948                 else if (type == TLSEXT_TYPE_elliptic_curves &&
1949                      s->version != DTLS1_VERSION)
1950                         {
1951                         unsigned char *sdata = data;
1952                         int ellipticcurvelist_length = (*(sdata++) << 8);
1953                         ellipticcurvelist_length += (*(sdata++));
1954
1955                         if (ellipticcurvelist_length != size - 2 ||
1956                                 ellipticcurvelist_length < 1)
1957                                 {
1958                                 *al = TLS1_AD_DECODE_ERROR;
1959                                 return 0;
1960                                 }
1961                         if (!s->hit)
1962                                 {
1963                                 if(s->session->tlsext_ellipticcurvelist)
1964                                         {
1965                                         *al = TLS1_AD_DECODE_ERROR;
1966                                         return 0;
1967                                         }
1968                                 s->session->tlsext_ellipticcurvelist_length = 0;
1969                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
1970                                         {
1971                                         *al = TLS1_AD_INTERNAL_ERROR;
1972                                         return 0;
1973                                         }
1974                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
1975                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
1976                                 }
1977 #if 0
1978                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
1979                         sdata = s->session->tlsext_ellipticcurvelist;
1980                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
1981                                 fprintf(stderr,"%i ",*(sdata++));
1982                         fprintf(stderr,"\n");
1983 #endif
1984                         }
1985 #endif /* OPENSSL_NO_EC */
1986 #ifdef TLSEXT_TYPE_opaque_prf_input
1987                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1988                      s->version != DTLS1_VERSION)
1989                         {
1990                         unsigned char *sdata = data;
1991
1992                         if (size < 2)
1993                                 {
1994                                 *al = SSL_AD_DECODE_ERROR;
1995                                 return 0;
1996                                 }
1997                         n2s(sdata, s->s3->client_opaque_prf_input_len);
1998                         if (s->s3->client_opaque_prf_input_len != size - 2)
1999                                 {
2000                                 *al = SSL_AD_DECODE_ERROR;
2001                                 return 0;
2002                                 }
2003
2004                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2005                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2006                         if (s->s3->client_opaque_prf_input_len == 0)
2007                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2008                         else
2009                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2010                         if (s->s3->client_opaque_prf_input == NULL)
2011                                 {
2012                                 *al = TLS1_AD_INTERNAL_ERROR;
2013                                 return 0;
2014                                 }
2015                         }
2016 #endif
2017                 else if (type == TLSEXT_TYPE_session_ticket)
2018                         {
2019                         if (s->tls_session_ticket_ext_cb &&
2020                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2021                                 {
2022                                 *al = TLS1_AD_INTERNAL_ERROR;
2023                                 return 0;
2024                                 }
2025                         }
2026                 else if (type == TLSEXT_TYPE_renegotiate)
2027                         {
2028                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2029                                 return 0;
2030                         renegotiate_seen = 1;
2031                         }
2032                 else if (type == TLSEXT_TYPE_signature_algorithms)
2033                         {
2034                         int dsize;
2035                         if (s->cert->peer_sigalgs || size < 2) 
2036                                 {
2037                                 *al = SSL_AD_DECODE_ERROR;
2038                                 return 0;
2039                                 }
2040                         n2s(data,dsize);
2041                         size -= 2;
2042                         if (dsize != size || dsize & 1 || !dsize) 
2043                                 {
2044                                 *al = SSL_AD_DECODE_ERROR;
2045                                 return 0;
2046                                 }
2047                         if (!tls1_process_sigalgs(s, data, dsize))
2048                                 {
2049                                 *al = SSL_AD_DECODE_ERROR;
2050                                 return 0;
2051                                 }
2052                         /* If sigalgs received and no shared algorithms fatal
2053                          * error.
2054                          */
2055                         if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
2056                                 {
2057                                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2058                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
2059                                 *al = SSL_AD_ILLEGAL_PARAMETER;
2060                                 return 0;
2061                                 }
2062                         }
2063                 else if (type == TLSEXT_TYPE_status_request &&
2064                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
2065                         {
2066                 
2067                         if (size < 5) 
2068                                 {
2069                                 *al = SSL_AD_DECODE_ERROR;
2070                                 return 0;
2071                                 }
2072
2073                         s->tlsext_status_type = *data++;
2074                         size--;
2075                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
2076                                 {
2077                                 const unsigned char *sdata;
2078                                 int dsize;
2079                                 /* Read in responder_id_list */
2080                                 n2s(data,dsize);
2081                                 size -= 2;
2082                                 if (dsize > size  ) 
2083                                         {
2084                                         *al = SSL_AD_DECODE_ERROR;
2085                                         return 0;
2086                                         }
2087                                 while (dsize > 0)
2088                                         {
2089                                         OCSP_RESPID *id;
2090                                         int idsize;
2091                                         if (dsize < 4)
2092                                                 {
2093                                                 *al = SSL_AD_DECODE_ERROR;
2094                                                 return 0;
2095                                                 }
2096                                         n2s(data, idsize);
2097                                         dsize -= 2 + idsize;
2098                                         size -= 2 + idsize;
2099                                         if (dsize < 0)
2100                                                 {
2101                                                 *al = SSL_AD_DECODE_ERROR;
2102                                                 return 0;
2103                                                 }
2104                                         sdata = data;
2105                                         data += idsize;
2106                                         id = d2i_OCSP_RESPID(NULL,
2107                                                                 &sdata, idsize);
2108                                         if (!id)
2109                                                 {
2110                                                 *al = SSL_AD_DECODE_ERROR;
2111                                                 return 0;
2112                                                 }
2113                                         if (data != sdata)
2114                                                 {
2115                                                 OCSP_RESPID_free(id);
2116                                                 *al = SSL_AD_DECODE_ERROR;
2117                                                 return 0;
2118                                                 }
2119                                         if (!s->tlsext_ocsp_ids
2120                                                 && !(s->tlsext_ocsp_ids =
2121                                                 sk_OCSP_RESPID_new_null()))
2122                                                 {
2123                                                 OCSP_RESPID_free(id);
2124                                                 *al = SSL_AD_INTERNAL_ERROR;
2125                                                 return 0;
2126                                                 }
2127                                         if (!sk_OCSP_RESPID_push(
2128                                                         s->tlsext_ocsp_ids, id))
2129                                                 {
2130                                                 OCSP_RESPID_free(id);
2131                                                 *al = SSL_AD_INTERNAL_ERROR;
2132                                                 return 0;
2133                                                 }
2134                                         }
2135
2136                                 /* Read in request_extensions */
2137                                 if (size < 2)
2138                                         {
2139                                         *al = SSL_AD_DECODE_ERROR;
2140                                         return 0;
2141                                         }
2142                                 n2s(data,dsize);
2143                                 size -= 2;
2144                                 if (dsize != size)
2145                                         {
2146                                         *al = SSL_AD_DECODE_ERROR;
2147                                         return 0;
2148                                         }
2149                                 sdata = data;
2150                                 if (dsize > 0)
2151                                         {
2152                                         if (s->tlsext_ocsp_exts)
2153                                                 {
2154                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2155                                                                            X509_EXTENSION_free);
2156                                                 }
2157
2158                                         s->tlsext_ocsp_exts =
2159                                                 d2i_X509_EXTENSIONS(NULL,
2160                                                         &sdata, dsize);
2161                                         if (!s->tlsext_ocsp_exts
2162                                                 || (data + dsize != sdata))
2163                                                 {
2164                                                 *al = SSL_AD_DECODE_ERROR;
2165                                                 return 0;
2166                                                 }
2167                                         }
2168                                 }
2169                                 /* We don't know what to do with any other type
2170                                 * so ignore it.
2171                                 */
2172                                 else
2173                                         s->tlsext_status_type = -1;
2174                         }
2175 #ifndef OPENSSL_NO_HEARTBEATS
2176                 else if (type == TLSEXT_TYPE_heartbeat)
2177                         {
2178                         switch(data[0])
2179                                 {
2180                                 case 0x01:      /* Client allows us to send HB requests */
2181                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2182                                                         break;
2183                                 case 0x02:      /* Client doesn't accept HB requests */
2184                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2185                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2186                                                         break;
2187                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2188                                                         return 0;
2189                                 }
2190                         }
2191 #endif
2192 #ifndef OPENSSL_NO_NEXTPROTONEG
2193                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2194                          s->s3->tmp.finish_md_len == 0)
2195                         {
2196                         /* We shouldn't accept this extension on a
2197                          * renegotiation.
2198                          *
2199                          * s->new_session will be set on renegotiation, but we
2200                          * probably shouldn't rely that it couldn't be set on
2201                          * the initial renegotation too in certain cases (when
2202                          * there's some other reason to disallow resuming an
2203                          * earlier session -- the current code won't be doing
2204                          * anything like that, but this might change).
2205
2206                          * A valid sign that there's been a previous handshake
2207                          * in this connection is if s->s3->tmp.finish_md_len >
2208                          * 0.  (We are talking about a check that will happen
2209                          * in the Hello protocol round, well before a new
2210                          * Finished message could have been computed.) */
2211                         s->s3->next_proto_neg_seen = 1;
2212                         }
2213 #endif
2214
2215                 /* session ticket processed earlier */
2216                 else if (type == TLSEXT_TYPE_use_srtp)
2217                         {
2218                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2219                                                               al))
2220                                 return 0;
2221                         }
2222
2223                 else if (type == TLSEXT_TYPE_server_authz)
2224                         {
2225                         unsigned char *sdata = data;
2226                         unsigned char server_authz_dataformatlist_length;
2227
2228                         if (size == 0)
2229                                 {
2230                                 *al = TLS1_AD_DECODE_ERROR;
2231                                 return 0;
2232                                 }
2233
2234                         server_authz_dataformatlist_length = *(sdata++);
2235
2236                         if (server_authz_dataformatlist_length != size - 1)
2237                                 {
2238                                 *al = TLS1_AD_DECODE_ERROR;
2239                                 return 0;
2240                                 }
2241
2242                         /* Successful session resumption uses the same authz
2243                          * information as the original session so we ignore this
2244                          * in the case of a session resumption. */
2245                         if (!s->hit)
2246                                 {
2247                                 if (s->s3->tlsext_authz_client_types != NULL)
2248                                         OPENSSL_free(s->s3->tlsext_authz_client_types);
2249                                 s->s3->tlsext_authz_client_types =
2250                                         OPENSSL_malloc(server_authz_dataformatlist_length);
2251                                 if (!s->s3->tlsext_authz_client_types)
2252                                         {
2253                                         *al = TLS1_AD_INTERNAL_ERROR;
2254                                         return 0;
2255                                         }
2256
2257                                 s->s3->tlsext_authz_client_types_len =
2258                                         server_authz_dataformatlist_length;
2259                                 memcpy(s->s3->tlsext_authz_client_types,
2260                                        sdata,
2261                                        server_authz_dataformatlist_length);
2262
2263                                 /* Sort the types in order to check for duplicates. */
2264                                 qsort(s->s3->tlsext_authz_client_types,
2265                                       server_authz_dataformatlist_length,
2266                                       1 /* element size */,
2267                                       byte_compare);
2268
2269                                 for (i = 0; i < server_authz_dataformatlist_length; i++)
2270                                         {
2271                                         if (i > 0 &&
2272                                             s->s3->tlsext_authz_client_types[i] ==
2273                                               s->s3->tlsext_authz_client_types[i-1])
2274                                                 {
2275                                                 *al = TLS1_AD_DECODE_ERROR;
2276                                                 return 0;
2277                                                 }
2278                                         }
2279                                 }
2280                         }
2281
2282                 data+=size;
2283                 }
2284
2285         *p = data;
2286
2287         ri_check:
2288
2289         /* Need RI if renegotiating */
2290
2291         if (!renegotiate_seen && s->renegotiate &&
2292                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2293                 {
2294                 *al = SSL_AD_HANDSHAKE_FAILURE;
2295                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2296                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2297                 return 0;
2298                 }
2299         /* If no signature algorithms extension set default values */
2300         if (!s->cert->peer_sigalgs)
2301                 ssl_cert_set_default_md(s->cert);
2302
2303         return 1;
2304         }
2305
2306 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2307         {
2308         int al = -1;
2309         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2310                 {
2311                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2312                 return 0;
2313                 }
2314
2315         if (ssl_check_clienthello_tlsext_early(s) <= 0) 
2316                 {
2317                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2318                 return 0;
2319                 }
2320         return 1;
2321 }
2322
2323 #ifndef OPENSSL_NO_NEXTPROTONEG
2324 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2325  * elements of zero length are allowed and the set of elements must exactly fill
2326  * the length of the block. */
2327 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2328         {
2329         unsigned int off = 0;
2330
2331         while (off < len)
2332                 {
2333                 if (d[off] == 0)
2334                         return 0;
2335                 off += d[off];
2336                 off++;
2337                 }
2338
2339         return off == len;
2340         }
2341 #endif
2342
2343 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2344         {
2345         unsigned short length;
2346         unsigned short type;
2347         unsigned short size;
2348         unsigned char *data = *p;
2349         int tlsext_servername = 0;
2350         int renegotiate_seen = 0;
2351
2352 #ifndef OPENSSL_NO_NEXTPROTONEG
2353         s->s3->next_proto_neg_seen = 0;
2354 #endif
2355
2356 #ifndef OPENSSL_NO_HEARTBEATS
2357         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2358                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2359 #endif
2360
2361         if (data >= (d+n-2))
2362                 goto ri_check;
2363
2364         n2s(data,length);
2365         if (data+length != d+n)
2366                 {
2367                 *al = SSL_AD_DECODE_ERROR;
2368                 return 0;
2369                 }
2370
2371         while(data <= (d+n-4))
2372                 {
2373                 n2s(data,type);
2374                 n2s(data,size);
2375
2376                 if (data+size > (d+n))
2377                         goto ri_check;
2378
2379                 if (s->tlsext_debug_cb)
2380                         s->tlsext_debug_cb(s, 1, type, data, size,
2381                                                 s->tlsext_debug_arg);
2382
2383                 if (type == TLSEXT_TYPE_server_name)
2384                         {
2385                         if (s->tlsext_hostname == NULL || size > 0)
2386                                 {
2387                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2388                                 return 0;
2389                                 }
2390                         tlsext_servername = 1;   
2391                         }
2392
2393 #ifndef OPENSSL_NO_EC
2394                 else if (type == TLSEXT_TYPE_ec_point_formats &&
2395                      s->version != DTLS1_VERSION)
2396                         {
2397                         unsigned char *sdata = data;
2398                         int ecpointformatlist_length = *(sdata++);
2399
2400                         if (ecpointformatlist_length != size - 1)
2401                                 {
2402                                 *al = TLS1_AD_DECODE_ERROR;
2403                                 return 0;
2404                                 }
2405                         s->session->tlsext_ecpointformatlist_length = 0;
2406                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2407                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2408                                 {
2409                                 *al = TLS1_AD_INTERNAL_ERROR;
2410                                 return 0;
2411                                 }
2412                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2413                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2414 #if 0
2415                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2416                         sdata = s->session->tlsext_ecpointformatlist;
2417                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2418                                 fprintf(stderr,"%i ",*(sdata++));
2419                         fprintf(stderr,"\n");
2420 #endif
2421                         }
2422 #endif /* OPENSSL_NO_EC */
2423
2424                 else if (type == TLSEXT_TYPE_session_ticket)
2425                         {
2426                         if (s->tls_session_ticket_ext_cb &&
2427                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2428                                 {
2429                                 *al = TLS1_AD_INTERNAL_ERROR;
2430                                 return 0;
2431                                 }
2432                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2433                                 || (size > 0))
2434                                 {
2435                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2436                                 return 0;
2437                                 }
2438                         s->tlsext_ticket_expected = 1;
2439                         }
2440 #ifdef TLSEXT_TYPE_opaque_prf_input
2441                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
2442                      s->version != DTLS1_VERSION)
2443                         {
2444                         unsigned char *sdata = data;
2445
2446                         if (size < 2)
2447                                 {
2448                                 *al = SSL_AD_DECODE_ERROR;
2449                                 return 0;
2450                                 }
2451                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2452                         if (s->s3->server_opaque_prf_input_len != size - 2)
2453                                 {
2454                                 *al = SSL_AD_DECODE_ERROR;
2455                                 return 0;
2456                                 }
2457                         
2458                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2459                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2460                         if (s->s3->server_opaque_prf_input_len == 0)
2461                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2462                         else
2463                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2464
2465                         if (s->s3->server_opaque_prf_input == NULL)
2466                                 {
2467                                 *al = TLS1_AD_INTERNAL_ERROR;
2468                                 return 0;
2469                                 }
2470                         }
2471 #endif
2472                 else if (type == TLSEXT_TYPE_status_request &&
2473                          s->version != DTLS1_VERSION)
2474                         {
2475                         /* MUST be empty and only sent if we've requested
2476                          * a status request message.
2477                          */ 
2478                         if ((s->tlsext_status_type == -1) || (size > 0))
2479                                 {
2480                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2481                                 return 0;
2482                                 }
2483                         /* Set flag to expect CertificateStatus message */
2484                         s->tlsext_status_expected = 1;
2485                         }
2486 #ifndef OPENSSL_NO_NEXTPROTONEG
2487                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2488                          s->s3->tmp.finish_md_len == 0)
2489                         {
2490                         unsigned char *selected;
2491                         unsigned char selected_len;
2492
2493                         /* We must have requested it. */
2494                         if (s->ctx->next_proto_select_cb == NULL)
2495                                 {
2496                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2497                                 return 0;
2498                                 }
2499                         /* The data must be valid */
2500                         if (!ssl_next_proto_validate(data, size))
2501                                 {
2502                                 *al = TLS1_AD_DECODE_ERROR;
2503                                 return 0;
2504                                 }
2505                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2506                                 {
2507                                 *al = TLS1_AD_INTERNAL_ERROR;
2508                                 return 0;
2509                                 }
2510                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2511                         if (!s->next_proto_negotiated)
2512                                 {
2513                                 *al = TLS1_AD_INTERNAL_ERROR;
2514                                 return 0;
2515                                 }
2516                         memcpy(s->next_proto_negotiated, selected, selected_len);
2517                         s->next_proto_negotiated_len = selected_len;
2518                         s->s3->next_proto_neg_seen = 1;
2519                         }
2520 #endif
2521                 else if (type == TLSEXT_TYPE_renegotiate)
2522                         {
2523                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2524                                 return 0;
2525                         renegotiate_seen = 1;
2526                         }
2527 #ifndef OPENSSL_NO_HEARTBEATS
2528                 else if (type == TLSEXT_TYPE_heartbeat)
2529                         {
2530                         switch(data[0])
2531                                 {
2532                                 case 0x01:      /* Server allows us to send HB requests */
2533                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2534                                                         break;
2535                                 case 0x02:      /* Server doesn't accept HB requests */
2536                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2537                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2538                                                         break;
2539                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2540                                                         return 0;
2541                                 }
2542                         }
2543 #endif
2544                 else if (type == TLSEXT_TYPE_use_srtp)
2545                         {
2546                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2547                                                               al))
2548                                 return 0;
2549                         }
2550
2551                 else if (type == TLSEXT_TYPE_server_authz)
2552                         {
2553                         /* We only support audit proofs. It's an error to send
2554                          * an authz hello extension if the client
2555                          * didn't request a proof. */
2556                         unsigned char *sdata = data;
2557                         unsigned char server_authz_dataformatlist_length;
2558
2559                         if (!s->ctx->tlsext_authz_server_audit_proof_cb)
2560                                 {
2561                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2562                                 return 0;
2563                                 }
2564
2565                         if (!size)
2566                                 {
2567                                 *al = TLS1_AD_DECODE_ERROR;
2568                                 return 0;
2569                                 }
2570
2571                         server_authz_dataformatlist_length = *(sdata++);
2572                         if (server_authz_dataformatlist_length != size - 1)
2573                                 {
2574                                 *al = TLS1_AD_DECODE_ERROR;
2575                                 return 0;
2576                                 }
2577
2578                         /* We only support audit proofs, so a legal ServerHello
2579                          * authz list contains exactly one entry. */
2580                         if (server_authz_dataformatlist_length != 1 ||
2581                                 sdata[0] != TLSEXT_AUTHZDATAFORMAT_audit_proof)
2582                                 {
2583                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2584                                 return 0;
2585                                 }
2586
2587                         s->s3->tlsext_authz_server_promised = 1;
2588                         }
2589  
2590                 data += size;
2591                 }
2592
2593         if (data != d+n)
2594                 {
2595                 *al = SSL_AD_DECODE_ERROR;
2596                 return 0;
2597                 }
2598
2599         if (!s->hit && tlsext_servername == 1)
2600                 {
2601                 if (s->tlsext_hostname)
2602                         {
2603                         if (s->session->tlsext_hostname == NULL)
2604                                 {
2605                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2606                                 if (!s->session->tlsext_hostname)
2607                                         {
2608                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2609                                         return 0;
2610                                         }
2611                                 }
2612                         else 
2613                                 {
2614                                 *al = SSL_AD_DECODE_ERROR;
2615                                 return 0;
2616                                 }
2617                         }
2618                 }
2619
2620         *p = data;
2621
2622         ri_check:
2623
2624         /* Determine if we need to see RI. Strictly speaking if we want to
2625          * avoid an attack we should *always* see RI even on initial server
2626          * hello because the client doesn't see any renegotiation during an
2627          * attack. However this would mean we could not connect to any server
2628          * which doesn't support RI so for the immediate future tolerate RI
2629          * absence on initial connect only.
2630          */
2631         if (!renegotiate_seen
2632                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2633                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2634                 {
2635                 *al = SSL_AD_HANDSHAKE_FAILURE;
2636                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2637                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2638                 return 0;
2639                 }
2640
2641         return 1;
2642         }
2643
2644
2645 int ssl_prepare_clienthello_tlsext(SSL *s)
2646         {
2647
2648 #ifdef TLSEXT_TYPE_opaque_prf_input
2649         {
2650                 int r = 1;
2651         
2652                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2653                         {
2654                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2655                         if (!r)
2656                                 return -1;
2657                         }
2658
2659                 if (s->tlsext_opaque_prf_input != NULL)
2660                         {
2661                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2662                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2663
2664                         if (s->tlsext_opaque_prf_input_len == 0)
2665                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2666                         else
2667                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2668                         if (s->s3->client_opaque_prf_input == NULL)
2669                                 {
2670                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2671                                 return -1;
2672                                 }
2673                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2674                         }
2675
2676                 if (r == 2)
2677                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2678                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2679         }
2680 #endif
2681
2682         return 1;
2683         }
2684
2685 int ssl_prepare_serverhello_tlsext(SSL *s)
2686         {
2687         return 1;
2688         }
2689
2690 static int ssl_check_clienthello_tlsext_early(SSL *s)
2691         {
2692         int ret=SSL_TLSEXT_ERR_NOACK;
2693         int al = SSL_AD_UNRECOGNIZED_NAME;
2694
2695 #ifndef OPENSSL_NO_EC
2696         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2697          * ssl3_choose_cipher in s3_lib.c.
2698          */
2699         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2700          * ssl3_choose_cipher in s3_lib.c.
2701          */
2702 #endif
2703
2704         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2705                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2706         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2707                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2708
2709 #ifdef TLSEXT_TYPE_opaque_prf_input
2710         {
2711                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2712                  * but we might be sending an alert in response to the client hello,
2713                  * so this has to happen here in
2714                  * ssl_check_clienthello_tlsext_early(). */
2715
2716                 int r = 1;
2717         
2718                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2719                         {
2720                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2721                         if (!r)
2722                                 {
2723                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2724                                 al = SSL_AD_INTERNAL_ERROR;
2725                                 goto err;
2726                                 }
2727                         }
2728
2729                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2730                         OPENSSL_free(s->s3->server_opaque_prf_input);
2731                 s->s3->server_opaque_prf_input = NULL;
2732
2733                 if (s->tlsext_opaque_prf_input != NULL)
2734                         {
2735                         if (s->s3->client_opaque_prf_input != NULL &&
2736                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2737                                 {
2738                                 /* can only use this extension if we have a server opaque PRF input
2739                                  * of the same length as the client opaque PRF input! */
2740
2741                                 if (s->tlsext_opaque_prf_input_len == 0)
2742                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2743                                 else
2744                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2745                                 if (s->s3->server_opaque_prf_input == NULL)
2746                                         {
2747                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2748                                         al = SSL_AD_INTERNAL_ERROR;
2749                                         goto err;
2750                                         }
2751                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2752                                 }
2753                         }
2754
2755                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2756                         {
2757                         /* The callback wants to enforce use of the extension,
2758                          * but we can't do that with the client opaque PRF input;
2759                          * abort the handshake.
2760                          */
2761                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2762                         al = SSL_AD_HANDSHAKE_FAILURE;
2763                         }
2764         }
2765
2766  err:
2767 #endif
2768         switch (ret)
2769                 {
2770                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2771                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2772                         return -1;
2773
2774                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2775                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2776                         return 1; 
2777                                         
2778                 case SSL_TLSEXT_ERR_NOACK:
2779                         s->servername_done=0;
2780                         default:
2781                 return 1;
2782                 }
2783         }
2784
2785 int ssl_check_clienthello_tlsext_late(SSL *s)
2786         {
2787         int ret = SSL_TLSEXT_ERR_OK;
2788         int al;
2789
2790         /* If status request then ask callback what to do.
2791          * Note: this must be called after servername callbacks in case
2792          * the certificate has changed, and must be called after the cipher
2793          * has been chosen because this may influence which certificate is sent
2794          */
2795         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
2796                 {
2797                 int r;
2798                 CERT_PKEY *certpkey;
2799                 certpkey = ssl_get_server_send_pkey(s);
2800                 /* If no certificate can't return certificate status */
2801                 if (certpkey == NULL)
2802                         {
2803                         s->tlsext_status_expected = 0;
2804                         return 1;
2805                         }
2806                 /* Set current certificate to one we will use so
2807                  * SSL_get_certificate et al can pick it up.
2808                  */
2809                 s->cert->key = certpkey;
2810                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2811                 switch (r)
2812                         {
2813                         /* We don't want to send a status request response */
2814                         case SSL_TLSEXT_ERR_NOACK:
2815                                 s->tlsext_status_expected = 0;
2816                                 break;
2817                         /* status request response should be sent */
2818                         case SSL_TLSEXT_ERR_OK:
2819                                 if (s->tlsext_ocsp_resp)
2820                                         s->tlsext_status_expected = 1;
2821                                 else
2822                                         s->tlsext_status_expected = 0;
2823                                 break;
2824                         /* something bad happened */
2825                         case SSL_TLSEXT_ERR_ALERT_FATAL:
2826                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2827                                 al = SSL_AD_INTERNAL_ERROR;
2828                                 goto err;
2829                         }
2830                 }
2831         else
2832                 s->tlsext_status_expected = 0;
2833
2834  err:
2835         switch (ret)
2836                 {
2837                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2838                         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2839                         return -1;
2840
2841                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2842                         ssl3_send_alert(s, SSL3_AL_WARNING, al);
2843                         return 1; 
2844
2845                 default:
2846                         return 1;
2847                 }
2848         }
2849
2850 int ssl_check_serverhello_tlsext(SSL *s)
2851         {
2852         int ret=SSL_TLSEXT_ERR_NOACK;
2853         int al = SSL_AD_UNRECOGNIZED_NAME;
2854
2855 #ifndef OPENSSL_NO_EC
2856         /* If we are client and using an elliptic curve cryptography cipher
2857          * suite, then if server returns an EC point formats lists extension
2858          * it must contain uncompressed.
2859          */
2860         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2861         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2862         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
2863             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
2864             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
2865                 {
2866                 /* we are using an ECC cipher */
2867                 size_t i;
2868                 unsigned char *list;
2869                 int found_uncompressed = 0;
2870                 list = s->session->tlsext_ecpointformatlist;
2871                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2872                         {
2873                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
2874                                 {
2875                                 found_uncompressed = 1;
2876                                 break;
2877                                 }
2878                         }
2879                 if (!found_uncompressed)
2880                         {
2881                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2882                         return -1;
2883                         }
2884                 }
2885         ret = SSL_TLSEXT_ERR_OK;
2886 #endif /* OPENSSL_NO_EC */
2887
2888         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2889                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2890         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2891                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2892
2893 #ifdef TLSEXT_TYPE_opaque_prf_input
2894         if (s->s3->server_opaque_prf_input_len > 0)
2895                 {
2896                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
2897                  * So first verify that we really have a value from the server too. */
2898
2899                 if (s->s3->server_opaque_prf_input == NULL)
2900                         {
2901                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2902                         al = SSL_AD_HANDSHAKE_FAILURE;
2903                         }
2904                 
2905                 /* Anytime the server *has* sent an opaque PRF input, we need to check
2906                  * that we have a client opaque PRF input of the same size. */
2907                 if (s->s3->client_opaque_prf_input == NULL ||
2908                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
2909                         {
2910                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2911                         al = SSL_AD_ILLEGAL_PARAMETER;
2912                         }
2913                 }
2914 #endif
2915
2916         /* If we've requested certificate status and we wont get one
2917          * tell the callback
2918          */
2919         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
2920                         && s->ctx && s->ctx->tlsext_status_cb)
2921                 {
2922                 int r;
2923                 /* Set resp to NULL, resplen to -1 so callback knows
2924                  * there is no response.
2925                  */
2926                 if (s->tlsext_ocsp_resp)
2927                         {
2928                         OPENSSL_free(s->tlsext_ocsp_resp);
2929                         s->tlsext_ocsp_resp = NULL;
2930                         }
2931                 s->tlsext_ocsp_resplen = -1;
2932                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2933                 if (r == 0)
2934                         {
2935                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2936                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2937                         }
2938                 if (r < 0)
2939                         {
2940                         al = SSL_AD_INTERNAL_ERROR;
2941                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2942                         }
2943                 }
2944
2945         switch (ret)
2946                 {
2947                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2948                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2949                         return -1;
2950
2951                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2952                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2953                         return 1; 
2954                                         
2955                 case SSL_TLSEXT_ERR_NOACK:
2956                         s->servername_done=0;
2957                         default:
2958                 return 1;
2959                 }
2960         }
2961
2962 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2963         {
2964         int al = -1;
2965         if (s->version < SSL3_VERSION)
2966                 return 1;
2967         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
2968                 {
2969                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2970                 return 0;
2971                 }
2972
2973         if (ssl_check_serverhello_tlsext(s) <= 0) 
2974                 {
2975                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
2976                 return 0;
2977                 }
2978         return 1;
2979 }
2980
2981 /* Since the server cache lookup is done early on in the processing of the
2982  * ClientHello, and other operations depend on the result, we need to handle
2983  * any TLS session ticket extension at the same time.
2984  *
2985  *   session_id: points at the session ID in the ClientHello. This code will
2986  *       read past the end of this in order to parse out the session ticket
2987  *       extension, if any.
2988  *   len: the length of the session ID.
2989  *   limit: a pointer to the first byte after the ClientHello.
2990  *   ret: (output) on return, if a ticket was decrypted, then this is set to
2991  *       point to the resulting session.
2992  *
2993  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2994  * ciphersuite, in which case we have no use for session tickets and one will
2995  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2996  *
2997  * Returns:
2998  *   -1: fatal error, either from parsing or decrypting the ticket.
2999  *    0: no ticket was found (or was ignored, based on settings).
3000  *    1: a zero length extension was found, indicating that the client supports
3001  *       session tickets but doesn't currently have one to offer.
3002  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
3003  *       couldn't be decrypted because of a non-fatal error.
3004  *    3: a ticket was successfully decrypted and *ret was set.
3005  *
3006  * Side effects:
3007  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3008  *   a new session ticket to the client because the client indicated support
3009  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3010  *   a session ticket or we couldn't use the one it gave us, or if
3011  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3012  *   Otherwise, s->tlsext_ticket_expected is set to 0.
3013  */
3014 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3015                         const unsigned char *limit, SSL_SESSION **ret)
3016         {
3017         /* Point after session ID in client hello */
3018         const unsigned char *p = session_id + len;
3019         unsigned short i;
3020
3021         *ret = NULL;
3022         s->tlsext_ticket_expected = 0;
3023
3024         /* If tickets disabled behave as if no ticket present
3025          * to permit stateful resumption.
3026          */
3027         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
3028                 return 0;
3029         if ((s->version <= SSL3_VERSION) || !limit)
3030                 return 0;
3031         if (p >= limit)
3032                 return -1;
3033         /* Skip past DTLS cookie */
3034         if (SSL_IS_DTLS(s))
3035                 {
3036                 i = *(p++);
3037                 p+= i;
3038                 if (p >= limit)
3039                         return -1;
3040                 }
3041         /* Skip past cipher list */
3042         n2s(p, i);
3043         p+= i;
3044         if (p >= limit)
3045                 return -1;
3046         /* Skip past compression algorithm list */
3047         i = *(p++);
3048         p += i;
3049         if (p > limit)
3050                 return -1;
3051         /* Now at start of extensions */
3052         if ((p + 2) >= limit)
3053                 return 0;
3054         n2s(p, i);
3055         while ((p + 4) <= limit)
3056                 {
3057                 unsigned short type, size;
3058                 n2s(p, type);
3059                 n2s(p, size);
3060                 if (p + size > limit)
3061                         return 0;
3062                 if (type == TLSEXT_TYPE_session_ticket)
3063                         {
3064                         int r;
3065                         if (size == 0)
3066                                 {
3067                                 /* The client will accept a ticket but doesn't
3068                                  * currently have one. */
3069                                 s->tlsext_ticket_expected = 1;
3070                                 return 1;
3071                                 }
3072                         if (s->tls_session_secret_cb)
3073                                 {
3074                                 /* Indicate that the ticket couldn't be
3075                                  * decrypted rather than generating the session
3076                                  * from ticket now, trigger abbreviated
3077                                  * handshake based on external mechanism to
3078                                  * calculate the master secret later. */
3079                                 return 2;
3080                                 }
3081                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3082                         switch (r)
3083                                 {
3084                                 case 2: /* ticket couldn't be decrypted */
3085                                         s->tlsext_ticket_expected = 1;
3086                                         return 2;
3087                                 case 3: /* ticket was decrypted */
3088                                         return r;
3089                                 case 4: /* ticket decrypted but need to renew */
3090                                         s->tlsext_ticket_expected = 1;
3091                                         return 3;
3092                                 default: /* fatal error */
3093                                         return -1;
3094                                 }
3095                         }
3096                 p += size;
3097                 }
3098         return 0;
3099         }
3100
3101 /* tls_decrypt_ticket attempts to decrypt a session ticket.
3102  *
3103  *   etick: points to the body of the session ticket extension.
3104  *   eticklen: the length of the session tickets extenion.
3105  *   sess_id: points at the session ID.
3106  *   sesslen: the length of the session ID.
3107  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3108  *       point to the resulting session.
3109  *
3110  * Returns:
3111  *   -1: fatal error, either from parsing or decrypting the ticket.
3112  *    2: the ticket couldn't be decrypted.
3113  *    3: a ticket was successfully decrypted and *psess was set.
3114  *    4: same as 3, but the ticket needs to be renewed.
3115  */
3116 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3117                                 const unsigned char *sess_id, int sesslen,
3118                                 SSL_SESSION **psess)
3119         {
3120         SSL_SESSION *sess;
3121         unsigned char *sdec;
3122         const unsigned char *p;
3123         int slen, mlen, renew_ticket = 0;
3124         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3125         HMAC_CTX hctx;
3126         EVP_CIPHER_CTX ctx;
3127         SSL_CTX *tctx = s->initial_ctx;
3128         /* Need at least keyname + iv + some encrypted data */
3129         if (eticklen < 48)
3130                 return 2;
3131         /* Initialize session ticket encryption and HMAC contexts */
3132         HMAC_CTX_init(&hctx);
3133         EVP_CIPHER_CTX_init(&ctx);
3134         if (tctx->tlsext_ticket_key_cb)
3135                 {
3136                 unsigned char *nctick = (unsigned char *)etick;
3137                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3138                                                         &ctx, &hctx, 0);
3139                 if (rv < 0)
3140                         return -1;
3141                 if (rv == 0)
3142                         return 2;
3143                 if (rv == 2)
3144                         renew_ticket = 1;
3145                 }
3146         else
3147                 {
3148                 /* Check key name matches */
3149                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3150                         return 2;
3151                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3152                                         tlsext_tick_md(), NULL);
3153                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3154                                 tctx->tlsext_tick_aes_key, etick + 16);
3155                 }
3156         /* Attempt to process session ticket, first conduct sanity and
3157          * integrity checks on ticket.
3158          */
3159         mlen = HMAC_size(&hctx);
3160         if (mlen < 0)
3161                 {
3162                 EVP_CIPHER_CTX_cleanup(&ctx);
3163                 return -1;
3164                 }
3165         eticklen -= mlen;
3166         /* Check HMAC of encrypted ticket */
3167         HMAC_Update(&hctx, etick, eticklen);
3168         HMAC_Final(&hctx, tick_hmac, NULL);
3169         HMAC_CTX_cleanup(&hctx);
3170         if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
3171                 return 2;
3172         /* Attempt to decrypt session data */
3173         /* Move p after IV to start of encrypted ticket, update length */
3174         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3175         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3176         sdec = OPENSSL_malloc(eticklen);
3177         if (!sdec)
3178                 {
3179                 EVP_CIPHER_CTX_cleanup(&ctx);
3180                 return -1;
3181                 }
3182         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
3183         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
3184                 return 2;
3185         slen += mlen;
3186         EVP_CIPHER_CTX_cleanup(&ctx);
3187         p = sdec;
3188
3189         sess = d2i_SSL_SESSION(NULL, &p, slen);
3190         OPENSSL_free(sdec);
3191         if (sess)
3192                 {
3193                 /* The session ID, if non-empty, is used by some clients to
3194                  * detect that the ticket has been accepted. So we copy it to
3195                  * the session structure. If it is empty set length to zero
3196                  * as required by standard.
3197                  */
3198                 if (sesslen)
3199                         memcpy(sess->session_id, sess_id, sesslen);
3200                 sess->session_id_length = sesslen;
3201                 *psess = sess;
3202                 if (renew_ticket)
3203                         return 4;
3204                 else
3205                         return 3;
3206                 }
3207         ERR_clear_error();
3208         /* For session parse failure, indicate that we need to send a new
3209          * ticket. */
3210         return 2;
3211         }
3212
3213 /* Tables to translate from NIDs to TLS v1.2 ids */
3214
3215 typedef struct 
3216         {
3217         int nid;
3218         int id;
3219         } tls12_lookup;
3220
3221 static tls12_lookup tls12_md[] = {
3222         {NID_md5, TLSEXT_hash_md5},
3223         {NID_sha1, TLSEXT_hash_sha1},
3224         {NID_sha224, TLSEXT_hash_sha224},
3225         {NID_sha256, TLSEXT_hash_sha256},
3226         {NID_sha384, TLSEXT_hash_sha384},
3227         {NID_sha512, TLSEXT_hash_sha512}
3228 };
3229
3230 static tls12_lookup tls12_sig[] = {
3231         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3232         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3233         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3234 };
3235
3236 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3237         {
3238         size_t i;
3239         for (i = 0; i < tlen; i++)
3240                 {
3241                 if (table[i].nid == nid)
3242                         return table[i].id;
3243                 }
3244         return -1;
3245         }
3246
3247 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3248         {
3249         size_t i;
3250         for (i = 0; i < tlen; i++)
3251                 {
3252                 if ((table[i].id) == id)
3253                         return table[i].nid;
3254                 }
3255         return NID_undef;
3256         }
3257
3258 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
3259         {
3260         int sig_id, md_id;
3261         if (!md)
3262                 return 0;
3263         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3264                                 sizeof(tls12_md)/sizeof(tls12_lookup));
3265         if (md_id == -1)
3266                 return 0;
3267         sig_id = tls12_get_sigid(pk);
3268         if (sig_id == -1)
3269                 return 0;
3270         p[0] = (unsigned char)md_id;
3271         p[1] = (unsigned char)sig_id;
3272         return 1;
3273         }
3274
3275 int tls12_get_sigid(const EVP_PKEY *pk)
3276         {
3277         return tls12_find_id(pk->type, tls12_sig,
3278                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
3279         }
3280
3281 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3282         {
3283         switch(hash_alg)
3284                 {
3285 #ifndef OPENSSL_NO_MD5
3286                 case TLSEXT_hash_md5:
3287 #ifdef OPENSSL_FIPS
3288                 if (FIPS_mode())
3289                         return NULL;
3290 #endif
3291                 return EVP_md5();
3292 #endif
3293 #ifndef OPENSSL_NO_SHA
3294                 case TLSEXT_hash_sha1:
3295                 return EVP_sha1();
3296 #endif
3297 #ifndef OPENSSL_NO_SHA256
3298                 case TLSEXT_hash_sha224:
3299                 return EVP_sha224();
3300
3301                 case TLSEXT_hash_sha256:
3302                 return EVP_sha256();
3303 #endif
3304 #ifndef OPENSSL_NO_SHA512
3305                 case TLSEXT_hash_sha384:
3306                 return EVP_sha384();
3307
3308                 case TLSEXT_hash_sha512:
3309                 return EVP_sha512();
3310 #endif
3311                 default:
3312                 return NULL;
3313
3314                 }
3315         }
3316
3317 static int tls12_get_pkey_idx(unsigned char sig_alg)
3318         {
3319         switch(sig_alg)
3320                 {
3321 #ifndef OPENSSL_NO_RSA
3322         case TLSEXT_signature_rsa:
3323                 return SSL_PKEY_RSA_SIGN;
3324 #endif
3325 #ifndef OPENSSL_NO_DSA
3326         case TLSEXT_signature_dsa:
3327                 return SSL_PKEY_DSA_SIGN;
3328 #endif
3329 #ifndef OPENSSL_NO_ECDSA
3330         case TLSEXT_signature_ecdsa:
3331                 return SSL_PKEY_ECC;
3332 #endif
3333                 }
3334         return -1;
3335         }
3336
3337 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3338 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3339                         int *psignhash_nid, const unsigned char *data)
3340         {
3341         int sign_nid = 0, hash_nid = 0;
3342         if (!phash_nid && !psign_nid && !psignhash_nid)
3343                 return;
3344         if (phash_nid || psignhash_nid)
3345                 {
3346                 hash_nid = tls12_find_nid(data[0], tls12_md,
3347                                         sizeof(tls12_md)/sizeof(tls12_lookup));
3348                 if (phash_nid)
3349                         *phash_nid = hash_nid;
3350                 }
3351         if (psign_nid || psignhash_nid)
3352                 {
3353                 sign_nid = tls12_find_nid(data[1], tls12_sig,
3354                                         sizeof(tls12_sig)/sizeof(tls12_lookup));
3355                 if (psign_nid)
3356                         *psign_nid = sign_nid;
3357                 }
3358         if (psignhash_nid)
3359                 {
3360                 if (sign_nid && hash_nid)
3361                         OBJ_find_sigid_by_algs(psignhash_nid,
3362                                                         hash_nid, sign_nid);
3363                 else
3364                         *psignhash_nid = NID_undef;
3365                 }
3366         }
3367 /* Given preference and allowed sigalgs set shared sigalgs */
3368 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3369                                 const unsigned char *pref, size_t preflen,
3370                                 const unsigned char *allow, size_t allowlen)
3371         {
3372         const unsigned char *ptmp, *atmp;
3373         size_t i, j, nmatch = 0;
3374         for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
3375                 {
3376                 /* Skip disabled hashes or signature algorithms */
3377                 if (tls12_get_hash(ptmp[0]) == NULL)
3378                         continue;
3379                 if (tls12_get_pkey_idx(ptmp[1]) == -1)
3380                         continue;
3381                 for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
3382                         {
3383                         if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
3384                                 {
3385                                 nmatch++;
3386                                 if (shsig)
3387                                         {
3388                                         shsig->rhash = ptmp[0];
3389                                         shsig->rsign = ptmp[1];
3390                                         tls1_lookup_sigalg(&shsig->hash_nid,
3391                                                 &shsig->sign_nid,
3392                                                 &shsig->signandhash_nid,
3393                                                 ptmp);
3394                                         shsig++;
3395                                         }
3396                                 break;
3397                                 }
3398                         }
3399                 }
3400         return nmatch;
3401         }
3402
3403 /* Set shared signature algorithms for SSL structures */
3404 static int tls1_set_shared_sigalgs(SSL *s)
3405         {
3406         const unsigned char *pref, *allow, *conf;
3407         size_t preflen, allowlen, conflen;
3408         size_t nmatch;
3409         TLS_SIGALGS *salgs = NULL;
3410         CERT *c = s->cert;
3411         unsigned int is_suiteb = tls1_suiteb(s);
3412         /* If client use client signature algorithms if not NULL */
3413         if (!s->server && c->client_sigalgs && !is_suiteb)
3414                 {
3415                 conf = c->client_sigalgs;
3416                 conflen = c->client_sigalgslen;
3417                 }
3418         else if (c->conf_sigalgs && !is_suiteb)
3419                 {
3420                 conf = c->conf_sigalgs;
3421                 conflen = c->conf_sigalgslen;
3422                 }
3423         else
3424                 conflen = tls12_get_psigalgs(s, &conf);
3425         if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb)
3426                 {
3427                 pref = conf;
3428                 preflen = conflen;
3429                 allow = c->peer_sigalgs;
3430                 allowlen = c->peer_sigalgslen;
3431                 }
3432         else
3433                 {
3434                 allow = conf;
3435                 allowlen = conflen;
3436                 pref = c->peer_sigalgs;
3437                 preflen = c->peer_sigalgslen;
3438                 }
3439         nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3440         if (!nmatch)
3441                 return 1;
3442         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3443         if (!salgs)
3444                 return 0;
3445         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3446         c->shared_sigalgs = salgs;
3447         c->shared_sigalgslen = nmatch;
3448         return 1;
3449         }
3450                 
3451
3452 /* Set preferred digest for each key type */
3453
3454 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
3455         {
3456         int idx;
3457         size_t i;
3458         const EVP_MD *md;
3459         CERT *c = s->cert;
3460         TLS_SIGALGS *sigptr;
3461         /* Extension ignored for inappropriate versions */
3462         if (!SSL_USE_SIGALGS(s))
3463                 return 1;
3464         /* Should never happen */
3465         if (!c)
3466                 return 0;
3467
3468         c->peer_sigalgs = OPENSSL_malloc(dsize);
3469         if (!c->peer_sigalgs)
3470                 return 0;
3471         c->peer_sigalgslen = dsize;
3472         memcpy(c->peer_sigalgs, data, dsize);
3473
3474         tls1_set_shared_sigalgs(s);
3475
3476 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3477         if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
3478                 {
3479                 /* Use first set signature preference to force message
3480                  * digest, ignoring any peer preferences.
3481                  */
3482                 const unsigned char *sigs = NULL;
3483                 if (s->server)
3484                         sigs = c->conf_sigalgs;
3485                 else
3486                         sigs = c->client_sigalgs;
3487                 if (sigs)
3488                         {
3489                         idx = tls12_get_pkey_idx(sigs[1]);
3490                         md = tls12_get_hash(sigs[0]);
3491                         c->pkeys[idx].digest = md;
3492                         c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3493                         if (idx == SSL_PKEY_RSA_SIGN)
3494                                 {
3495                                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3496                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3497                                 }
3498                         }
3499                 }
3500 #endif
3501
3502         for (i = 0, sigptr = c->shared_sigalgs;
3503                         i < c->shared_sigalgslen; i++, sigptr++)
3504                 {
3505                 idx = tls12_get_pkey_idx(sigptr->rsign);
3506                 if (idx > 0 && c->pkeys[idx].digest == NULL)
3507                         {
3508                         md = tls12_get_hash(sigptr->rhash);
3509                         c->pkeys[idx].digest = md;
3510                         c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3511                         if (idx == SSL_PKEY_RSA_SIGN)
3512                                 {
3513                                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3514                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3515                                 }
3516                         }
3517
3518                 }
3519         /* In strict mode leave unset digests as NULL to indicate we can't
3520          * use the certificate for signing.
3521          */
3522         if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
3523                 {
3524                 /* Set any remaining keys to default values. NOTE: if alg is
3525                  * not supported it stays as NULL.