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