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