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