232ab4ea5701b740729df7cf3017e7dc6336fe24
[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 "ssl_locl.h"
117
118 const char tls1_version_str[]="TLSv1" OPENSSL_VERSION_PTEXT;
119
120 #ifndef OPENSSL_NO_TLSEXT
121 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
122                                 const unsigned char *sess_id, int sesslen,
123                                 SSL_SESSION **psess);
124 #endif
125
126 SSL3_ENC_METHOD TLSv1_enc_data={
127         tls1_enc,
128         tls1_mac,
129         tls1_setup_key_block,
130         tls1_generate_master_secret,
131         tls1_change_cipher_state,
132         tls1_final_finish_mac,
133         TLS1_FINISH_MAC_LENGTH,
134         tls1_cert_verify_mac,
135         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
136         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
137         tls1_alert_code,
138         };
139
140 long tls1_default_timeout(void)
141         {
142         /* 2 hours, the 24 hours mentioned in the TLSv1 spec
143          * is way too long for http, the cache would over fill */
144         return(60*60*2);
145         }
146
147 int tls1_new(SSL *s)
148         {
149         if (!ssl3_new(s)) return(0);
150         s->method->ssl_clear(s);
151         return(1);
152         }
153
154 void tls1_free(SSL *s)
155         {
156         ssl3_free(s);
157         }
158
159 void tls1_clear(SSL *s)
160         {
161         ssl3_clear(s);
162         s->version=TLS1_VERSION;
163         }
164
165 #ifndef OPENSSL_NO_EC
166 static int nid_list[] =
167         {
168                 NID_sect163k1, /* sect163k1 (1) */
169                 NID_sect163r1, /* sect163r1 (2) */
170                 NID_sect163r2, /* sect163r2 (3) */
171                 NID_sect193r1, /* sect193r1 (4) */ 
172                 NID_sect193r2, /* sect193r2 (5) */ 
173                 NID_sect233k1, /* sect233k1 (6) */
174                 NID_sect233r1, /* sect233r1 (7) */ 
175                 NID_sect239k1, /* sect239k1 (8) */ 
176                 NID_sect283k1, /* sect283k1 (9) */
177                 NID_sect283r1, /* sect283r1 (10) */ 
178                 NID_sect409k1, /* sect409k1 (11) */ 
179                 NID_sect409r1, /* sect409r1 (12) */
180                 NID_sect571k1, /* sect571k1 (13) */ 
181                 NID_sect571r1, /* sect571r1 (14) */ 
182                 NID_secp160k1, /* secp160k1 (15) */
183                 NID_secp160r1, /* secp160r1 (16) */ 
184                 NID_secp160r2, /* secp160r2 (17) */ 
185                 NID_secp192k1, /* secp192k1 (18) */
186                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
187                 NID_secp224k1, /* secp224k1 (20) */ 
188                 NID_secp224r1, /* secp224r1 (21) */
189                 NID_secp256k1, /* secp256k1 (22) */ 
190                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
191                 NID_secp384r1, /* secp384r1 (24) */
192                 NID_secp521r1  /* secp521r1 (25) */     
193         };
194         
195 int tls1_ec_curve_id2nid(int curve_id)
196         {
197         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
198         if ((curve_id < 1) || (curve_id > sizeof(nid_list)/sizeof(nid_list[0]))) return 0;
199         return nid_list[curve_id-1];
200         }
201
202 int tls1_ec_nid2curve_id(int nid)
203         {
204         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
205         switch (nid)
206                 {
207         case NID_sect163k1: /* sect163k1 (1) */
208                 return 1;
209         case NID_sect163r1: /* sect163r1 (2) */
210                 return 2;
211         case NID_sect163r2: /* sect163r2 (3) */
212                 return 3;
213         case NID_sect193r1: /* sect193r1 (4) */ 
214                 return 4;
215         case NID_sect193r2: /* sect193r2 (5) */ 
216                 return 5;
217         case NID_sect233k1: /* sect233k1 (6) */
218                 return 6;
219         case NID_sect233r1: /* sect233r1 (7) */ 
220                 return 7;
221         case NID_sect239k1: /* sect239k1 (8) */ 
222                 return 8;
223         case NID_sect283k1: /* sect283k1 (9) */
224                 return 9;
225         case NID_sect283r1: /* sect283r1 (10) */ 
226                 return 10;
227         case NID_sect409k1: /* sect409k1 (11) */ 
228                 return 11;
229         case NID_sect409r1: /* sect409r1 (12) */
230                 return 12;
231         case NID_sect571k1: /* sect571k1 (13) */ 
232                 return 13;
233         case NID_sect571r1: /* sect571r1 (14) */ 
234                 return 14;
235         case NID_secp160k1: /* secp160k1 (15) */
236                 return 15;
237         case NID_secp160r1: /* secp160r1 (16) */ 
238                 return 16;
239         case NID_secp160r2: /* secp160r2 (17) */ 
240                 return 17;
241         case NID_secp192k1: /* secp192k1 (18) */
242                 return 18;
243         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
244                 return 19;
245         case NID_secp224k1: /* secp224k1 (20) */ 
246                 return 20;
247         case NID_secp224r1: /* secp224r1 (21) */
248                 return 21;
249         case NID_secp256k1: /* secp256k1 (22) */ 
250                 return 22;
251         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
252                 return 23;
253         case NID_secp384r1: /* secp384r1 (24) */
254                 return 24;
255         case NID_secp521r1:  /* secp521r1 (25) */       
256                 return 25;
257         default:
258                 return 0;
259                 }
260         }
261 #endif /* OPENSSL_NO_EC */
262
263 #ifndef OPENSSL_NO_TLSEXT
264 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
265         {
266         int extdatalen=0;
267         unsigned char *ret = p;
268
269         ret+=2;
270
271         if (ret>=limit) return NULL; /* this really never occurs, but ... */
272
273         if (s->tlsext_hostname != NULL)
274                 { 
275                 /* Add TLS extension servername to the Client Hello message */
276                 unsigned long size_str;
277                 long lenmax; 
278
279                 /* check for enough space.
280                    4 for the servername type and entension length
281                    2 for servernamelist length
282                    1 for the hostname type
283                    2 for hostname length
284                    + hostname length 
285                 */
286                    
287                 if ((lenmax = limit - p - 9) < 0 
288                 || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
289                         return NULL;
290                         
291                 /* extension type and length */
292                 s2n(TLSEXT_TYPE_server_name,ret); 
293                 s2n(size_str+5,ret);
294                 
295                 /* length of servername list */
296                 s2n(size_str+3,ret);
297         
298                 /* hostname type, length and hostname */
299                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
300                 s2n(size_str,ret);
301                 memcpy(ret, s->tlsext_hostname, size_str);
302                 ret+=size_str;
303
304                 }
305 #ifndef OPENSSL_NO_EC
306         if (s->tlsext_ecpointformatlist != NULL)
307                 {
308                 /* Add TLS extension ECPointFormats to the ClientHello message */
309                 long lenmax; 
310
311                 if ((lenmax = limit - p - 5) < 0) return NULL; 
312                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
313                 if (s->tlsext_ecpointformatlist_length > 255)
314                         {
315                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
316                         return NULL;
317                         }
318                 
319                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
320                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
321                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
322                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
323                 ret+=s->tlsext_ecpointformatlist_length;
324                 }
325         if (s->tlsext_ellipticcurvelist != NULL)
326                 {
327                 /* Add TLS extension EllipticCurves to the ClientHello message */
328                 long lenmax; 
329
330                 if ((lenmax = limit - p - 6) < 0) return NULL; 
331                 if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL;
332                 if (s->tlsext_ellipticcurvelist_length > 65532)
333                         {
334                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
335                         return NULL;
336                         }
337                 
338                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
339                 s2n(s->tlsext_ellipticcurvelist_length + 2, ret);
340
341                 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
342                  * elliptic_curve_list, but the examples use two bytes.
343                  * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
344                  * resolves this to two bytes.
345                  */
346                 s2n(s->tlsext_ellipticcurvelist_length, ret);
347                 memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length);
348                 ret+=s->tlsext_ellipticcurvelist_length;
349                 }
350 #endif /* OPENSSL_NO_EC */
351
352         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
353                 {
354                 int ticklen;
355                 if (s->session && s->session->tlsext_tick)
356                         ticklen = s->session->tlsext_ticklen;
357                 else
358                         ticklen = 0;
359                 /* Check for enough room 2 for extension type, 2 for len
360                  * rest for ticket
361                  */
362                 if (limit - p - 4 - ticklen < 0)
363                         return NULL;
364                 s2n(TLSEXT_TYPE_session_ticket,ret); 
365                 s2n(ticklen,ret);
366                 if (ticklen)
367                         {
368                         memcpy(ret, s->session->tlsext_tick, ticklen);
369                         ret += ticklen;
370                         }
371                 }
372
373         if ((extdatalen = ret-p-2)== 0) 
374                 return p;
375
376         s2n(extdatalen,p);
377         return ret;
378         }
379
380 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
381         {
382         int extdatalen=0;
383         unsigned char *ret = p;
384
385         ret+=2;
386         if (ret>=limit) return NULL; /* this really never occurs, but ... */
387
388         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
389                 { 
390                 if (limit - p - 4 < 0) return NULL; 
391
392                 s2n(TLSEXT_TYPE_server_name,ret);
393                 s2n(0,ret);
394                 }
395 #ifndef OPENSSL_NO_EC
396         if (s->tlsext_ecpointformatlist != NULL)
397                 {
398                 /* Add TLS extension ECPointFormats to the ServerHello message */
399                 long lenmax; 
400
401                 if ((lenmax = limit - p - 5) < 0) return NULL; 
402                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
403                 if (s->tlsext_ecpointformatlist_length > 255)
404                         {
405                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
406                         return NULL;
407                         }
408                 
409                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
410                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
411                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
412                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
413                 ret+=s->tlsext_ecpointformatlist_length;
414
415                 }
416         /* Currently the server should not respond with a SupportedCurves extension */
417 #endif /* OPENSSL_NO_EC */
418         
419         if (s->tlsext_ticket_expected
420                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
421                 { 
422                 if (limit - p - 4 < 0) return NULL; 
423                 s2n(TLSEXT_TYPE_session_ticket,ret);
424                 s2n(0,ret);
425                 }
426                 
427         if ((extdatalen = ret-p-2)== 0) 
428                 return p;
429
430         s2n(extdatalen,p);
431         return ret;
432         }
433
434 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
435         {
436         unsigned short type;
437         unsigned short size;
438         unsigned short len;
439         unsigned char *data = *p;
440         s->servername_done = 0;
441
442         if (data >= (d+n-2))
443                 return 1;
444         n2s(data,len);
445
446         if (data > (d+n-len)) 
447                 return 1;
448
449         while (data <= (d+n-4))
450                 {
451                 n2s(data,type);
452                 n2s(data,size);
453
454                 if (data+size > (d+n))
455                         return 1;
456
457                 if (s->tlsext_debug_cb)
458                         s->tlsext_debug_cb(s, 0, type, data, size,
459                                                 s->tlsext_debug_arg);
460 /* The servername extension is treated as follows:
461
462    - Only the hostname type is supported with a maximum length of 255.
463    - The servername is rejected if too long or if it contains zeros,
464      in which case an fatal alert is generated.
465    - The servername field is maintained together with the session cache.
466    - When a session is resumed, the servername call back invoked in order
467      to allow the application to position itself to the right context. 
468    - The servername is acknowledged if it is new for a session or when 
469      it is identical to a previously used for the same session. 
470      Applications can control the behaviour.  They can at any time
471      set a 'desirable' servername for a new SSL object. This can be the
472      case for example with HTTPS when a Host: header field is received and
473      a renegotiation is requested. In this case, a possible servername
474      presented in the new client hello is only acknowledged if it matches
475      the value of the Host: field. 
476    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
477      if they provide for changing an explicit servername context for the session,
478      i.e. when the session has been established with a servername extension. 
479    - On session reconnect, the servername extension may be absent. 
480
481 */      
482
483                 if (type == TLSEXT_TYPE_server_name)
484                         {
485                         unsigned char *sdata;
486                         int servname_type;
487                         int dsize; 
488                 
489                         if (size < 2) 
490                                 {
491                                 *al = SSL_AD_DECODE_ERROR;
492                                 return 0;
493                                 }
494                         n2s(data,dsize);  
495                         size -= 2;
496                         if (dsize > size  ) 
497                                 {
498                                 *al = SSL_AD_DECODE_ERROR;
499                                 return 0;
500                                 } 
501
502                         sdata = data;
503                         while (dsize > 3) 
504                                 {
505                                 servname_type = *(sdata++); 
506                                 n2s(sdata,len);
507                                 dsize -= 3;
508
509                                 if (len > dsize) 
510                                         {
511                                         *al = SSL_AD_DECODE_ERROR;
512                                         return 0;
513                                         }
514                                 if (s->servername_done == 0)
515                                 switch (servname_type)
516                                         {
517                                 case TLSEXT_NAMETYPE_host_name:
518                                         if (s->session->tlsext_hostname == NULL)
519                                                 {
520                                                 if (len > TLSEXT_MAXLEN_host_name || 
521                                                         ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL))
522                                                         {
523                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
524                                                         return 0;
525                                                         }
526                                                 memcpy(s->session->tlsext_hostname, sdata, len);
527                                                 s->session->tlsext_hostname[len]='\0';
528                                                 if (strlen(s->session->tlsext_hostname) != len) {
529                                                         OPENSSL_free(s->session->tlsext_hostname);
530                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
531                                                         return 0;
532                                                 }
533                                                 s->servername_done = 1; 
534
535                                                 }
536                                         else 
537                                                 s->servername_done = strlen(s->session->tlsext_hostname) == len 
538                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
539                                         
540                                         break;
541
542                                 default:
543                                         break;
544                                         }
545                                  
546                                 dsize -= len;
547                                 }
548                         if (dsize != 0) 
549                                 {
550                                 *al = SSL_AD_DECODE_ERROR;
551                                 return 0;
552                                 }
553
554                         }
555
556 #ifndef OPENSSL_NO_EC
557                 else if (type == TLSEXT_TYPE_ec_point_formats)
558                         {
559                         unsigned char *sdata = data;
560                         int ecpointformatlist_length = *(sdata++);
561
562                         if (ecpointformatlist_length != size - 1)
563                                 {
564                                 *al = TLS1_AD_DECODE_ERROR;
565                                 return 0;
566                                 }
567                         s->session->tlsext_ecpointformatlist_length = 0;
568                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
569                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
570                                 {
571                                 *al = TLS1_AD_INTERNAL_ERROR;
572                                 return 0;
573                                 }
574                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
575                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
576 #if 0
577                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
578                         sdata = s->session->tlsext_ecpointformatlist;
579                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
580                                 fprintf(stderr,"%i ",*(sdata++));
581                         fprintf(stderr,"\n");
582 #endif
583                         }
584                 else if (type == TLSEXT_TYPE_elliptic_curves)
585                         {
586                         unsigned char *sdata = data;
587                         int ellipticcurvelist_length = (*(sdata++) << 8);
588                         ellipticcurvelist_length += (*(sdata++));
589
590                         if (ellipticcurvelist_length != size - 2)
591                                 {
592                                 *al = TLS1_AD_DECODE_ERROR;
593                                 return 0;
594                                 }
595                         s->session->tlsext_ellipticcurvelist_length = 0;
596                         if (s->session->tlsext_ellipticcurvelist != NULL) OPENSSL_free(s->session->tlsext_ellipticcurvelist);
597                         if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
598                                 {
599                                 *al = TLS1_AD_INTERNAL_ERROR;
600                                 return 0;
601                                 }
602                         s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
603                         memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
604 #if 0
605                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
606                         sdata = s->session->tlsext_ellipticcurvelist;
607                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
608                                 fprintf(stderr,"%i ",*(sdata++));
609                         fprintf(stderr,"\n");
610 #endif
611                         }
612 #endif /* OPENSSL_NO_EC */
613                 /* session ticket processed earlier */
614                 data+=size;
615                 }
616                                 
617         *p = data;
618         return 1;
619         }
620
621 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
622         {
623         unsigned short type;
624         unsigned short size;
625         unsigned short len;  
626         unsigned char *data = *p;
627
628         int tlsext_servername = 0;
629
630         if (data >= (d+n-2))
631                 return 1;
632
633         n2s(data,len);
634
635         while(data <= (d+n-4))
636                 {
637                 n2s(data,type);
638                 n2s(data,size);
639
640                 if (data+size > (d+n))
641                         return 1;
642
643                 if (s->tlsext_debug_cb)
644                         s->tlsext_debug_cb(s, 1, type, data, size,
645                                                 s->tlsext_debug_arg);
646
647                 if (type == TLSEXT_TYPE_server_name)
648                         {
649                         if (s->tlsext_hostname == NULL || size > 0)
650                                 {
651                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
652                                 return 0;
653                                 }
654                         tlsext_servername = 1;   
655                         }
656
657 #ifndef OPENSSL_NO_EC
658                 else if (type == TLSEXT_TYPE_ec_point_formats)
659                         {
660                         unsigned char *sdata = data;
661                         int ecpointformatlist_length = *(sdata++);
662
663                         if (ecpointformatlist_length != size - 1)
664                                 {
665                                 *al = TLS1_AD_DECODE_ERROR;
666                                 return 0;
667                                 }
668                         s->session->tlsext_ecpointformatlist_length = 0;
669                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
670                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
671                                 {
672                                 *al = TLS1_AD_INTERNAL_ERROR;
673                                 return 0;
674                                 }
675                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
676                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
677 #if 0
678                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
679                         sdata = s->session->tlsext_ecpointformatlist;
680                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
681                                 fprintf(stderr,"%i ",*(sdata++));
682                         fprintf(stderr,"\n");
683 #endif
684                         }
685 #endif /* OPENSSL_NO_EC */
686
687                 else if (type == TLSEXT_TYPE_session_ticket)
688                         {
689                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
690                                 || (size > 0))
691                                 {
692                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
693                                 return 0;
694                                 }
695                         s->tlsext_ticket_expected = 1;
696                         }
697                 data+=size;             
698                 }
699
700         if (data != d+n)
701                 {
702                 *al = SSL_AD_DECODE_ERROR;
703                 return 0;
704                 }
705
706         if (!s->hit && tlsext_servername == 1)
707                 {
708                 if (s->tlsext_hostname)
709                         {
710                         if (s->session->tlsext_hostname == NULL)
711                                 {
712                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
713                                 if (!s->session->tlsext_hostname)
714                                         {
715                                         *al = SSL_AD_UNRECOGNIZED_NAME;
716                                         return 0;
717                                         }
718                                 }
719                         else 
720                                 {
721                                 *al = SSL_AD_DECODE_ERROR;
722                                 return 0;
723                                 }
724                         }
725                 }
726
727         *p = data;
728         return 1;
729         }
730
731
732 int ssl_prepare_clienthello_tlsext(SSL *s)
733         {
734 #ifndef OPENSSL_NO_EC
735         /* If we are client and using an elliptic curve cryptography cipher suite, send the point formats 
736          * and elliptic curves we support.
737          */
738         int using_ecc = 0;
739         int i;
740         unsigned char *j;
741         unsigned long alg_k, alg_a;
742         STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
743
744         for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
745                 {
746                 SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
747
748                 alg_k = c->algorithm_mkey;
749                 alg_a = c->algorithm_auth;
750                 if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe) || (alg_a & SSL_aECDSA)))
751                         {
752                         using_ecc = 1;
753                         break;
754                         }
755                 }
756         using_ecc = using_ecc && (s->version == TLS1_VERSION);
757         if (using_ecc)
758                 {
759                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
760                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
761                         {
762                         SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
763                         return -1;
764                         }
765                 s->tlsext_ecpointformatlist_length = 3;
766                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
767                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
768                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
769
770                 /* we support all named elliptic curves in draft-ietf-tls-ecc-12 */
771                 if (s->tlsext_ellipticcurvelist != NULL) OPENSSL_free(s->tlsext_ellipticcurvelist);
772                 s->tlsext_ellipticcurvelist_length = sizeof(nid_list)/sizeof(nid_list[0]) * 2;
773                 if ((s->tlsext_ellipticcurvelist = OPENSSL_malloc(s->tlsext_ellipticcurvelist_length)) == NULL)
774                         {
775                         s->tlsext_ellipticcurvelist_length = 0;
776                         SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
777                         return -1;
778                         }
779                 for (i = 1, j = s->tlsext_ellipticcurvelist; i <= sizeof(nid_list)/sizeof(nid_list[0]); i++)
780                         s2n(i,j);
781                 }
782 #endif /* OPENSSL_NO_EC */
783         return 1;
784         }
785
786 int ssl_prepare_serverhello_tlsext(SSL *s)
787         {
788 #ifndef OPENSSL_NO_EC
789         /* If we are server and using an ECC cipher suite, send the point formats we support 
790          * if the client sent us an ECPointsFormat extension.  Note that the server is not
791          * supposed to send an EllipticCurves extension.
792          */
793
794         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
795         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
796         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
797         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
798         
799         if (using_ecc)
800                 {
801                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
802                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
803                         {
804                         SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
805                         return -1;
806                         }
807                 s->tlsext_ecpointformatlist_length = 3;
808                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
809                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
810                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
811                 }
812 #endif /* OPENSSL_NO_EC */
813         return 1;
814         }
815
816 int ssl_check_clienthello_tlsext(SSL *s)
817         {
818         int ret=SSL_TLSEXT_ERR_NOACK;
819         int al = SSL_AD_UNRECOGNIZED_NAME;
820
821 #ifndef OPENSSL_NO_EC
822         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
823          * ssl3_choose_cipher in s3_lib.c.
824          */
825         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
826          * ssl3_choose_cipher in s3_lib.c.
827          */
828 #endif
829
830         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
831                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
832         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
833                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
834
835         switch (ret)
836                 {
837                 case SSL_TLSEXT_ERR_ALERT_FATAL:
838                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
839                         return -1;
840
841                 case SSL_TLSEXT_ERR_ALERT_WARNING:
842                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
843                         return 1; 
844                                         
845                 case SSL_TLSEXT_ERR_NOACK:
846                         s->servername_done=0;
847                         default:
848                 return 1;
849                 }
850         }
851
852 int ssl_check_serverhello_tlsext(SSL *s)
853         {
854         int ret=SSL_TLSEXT_ERR_NOACK;
855         int al = SSL_AD_UNRECOGNIZED_NAME;
856
857 #ifndef OPENSSL_NO_EC
858         /* If we are client and using an elliptic curve cryptography cipher suite, then server
859          * must return a an EC point formats lists containing uncompressed.
860          */
861         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
862         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
863         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
864             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
865                 {
866                 /* we are using an ECC cipher */
867                 size_t i;
868                 unsigned char *list;
869                 int found_uncompressed = 0;
870                 if ((s->session->tlsext_ecpointformatlist == NULL) || (s->session->tlsext_ecpointformatlist_length == 0))
871                         {
872                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
873                         return -1;
874                         }
875                 list = s->session->tlsext_ecpointformatlist;
876                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
877                         {
878                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
879                                 {
880                                 found_uncompressed = 1;
881                                 break;
882                                 }
883                         }
884                 if (!found_uncompressed)
885                         {
886                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
887                         return -1;
888                         }
889                 }
890         ret = SSL_TLSEXT_ERR_OK;
891 #endif /* OPENSSL_NO_EC */
892
893         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
894                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
895         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
896                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
897
898         switch (ret)
899                 {
900                 case SSL_TLSEXT_ERR_ALERT_FATAL:
901                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
902                         return -1;
903
904                 case SSL_TLSEXT_ERR_ALERT_WARNING:
905                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
906                         return 1; 
907                                         
908                 case SSL_TLSEXT_ERR_NOACK:
909                         s->servername_done=0;
910                         default:
911                 return 1;
912                 }
913         }
914
915 /* Since the server cache lookup is done early on in the processing of client
916  * hello and other operations depend on the result we need to handle any TLS
917  * session ticket extension at the same time.
918  */
919
920 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
921                                 const unsigned char *limit, SSL_SESSION **ret)
922         {
923         /* Point after session ID in client hello */
924         const unsigned char *p = session_id + len;
925         unsigned short i;
926         if ((s->version <= SSL3_VERSION) || !limit)
927                 return 1;
928         if (p >= limit)
929                 return -1;
930         /* Skip past cipher list */
931         n2s(p, i);
932         p+= i;
933         if (p >= limit)
934                 return -1;
935         /* Skip past compression algorithm list */
936         i = *(p++);
937         p += i;
938         if (p > limit)
939                 return -1;
940         /* Now at start of extensions */
941         if ((p + 2) >= limit)
942                 return 1;
943         n2s(p, i);
944         while ((p + 4) <= limit)
945                 {
946                 unsigned short type, size;
947                 n2s(p, type);
948                 n2s(p, size);
949                 if (p + size > limit)
950                         return 1;
951                 if (type == TLSEXT_TYPE_session_ticket)
952                         {
953                         /* If tickets disabled indicate cache miss which will
954                          * trigger a full handshake
955                          */
956                         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
957                                 return 0;
958                         /* If zero length not client will accept a ticket
959                          * and indicate cache miss to trigger full handshake
960                          */
961                         if (size == 0)
962                                 {
963                                 s->tlsext_ticket_expected = 1;
964                                 return 0;       /* Cache miss */
965                                 }
966                         return tls_decrypt_ticket(s, p, size, session_id, len,
967                                                                         ret);
968                         }
969                 p += size;
970                 }
971         return 1;
972         }
973
974 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
975                                 const unsigned char *sess_id, int sesslen,
976                                 SSL_SESSION **psess)
977         {
978         SSL_SESSION *sess;
979         unsigned char *sdec;
980         const unsigned char *p;
981         int slen, mlen;
982         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
983         HMAC_CTX hctx;
984         EVP_CIPHER_CTX ctx;
985         /* Attempt to process session ticket, first conduct sanity and
986          * integrity checks on ticket.
987          */
988         mlen = EVP_MD_size(EVP_sha1());
989         eticklen -= mlen;
990         /* Need at least keyname + iv + some encrypted data */
991         if (eticklen < 48)
992                 goto tickerr;
993         /* Check key name matches */
994         if (memcmp(etick, s->ctx->tlsext_tick_key_name, 16))
995                 goto tickerr;
996         /* Check HMAC of encrypted ticket */
997         HMAC_CTX_init(&hctx);
998         HMAC_Init_ex(&hctx, s->ctx->tlsext_tick_hmac_key, 16,
999                                 EVP_sha1(), NULL);
1000         HMAC_Update(&hctx, etick, eticklen);
1001         HMAC_Final(&hctx, tick_hmac, NULL);
1002         HMAC_CTX_cleanup(&hctx);
1003         if (memcmp(tick_hmac, etick + eticklen, mlen))
1004                 goto tickerr;
1005         /* Set p to start of IV */
1006         p = etick + 16;
1007         EVP_CIPHER_CTX_init(&ctx);
1008         /* Attempt to decrypt session data */
1009         EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
1010                                         s->ctx->tlsext_tick_aes_key, p);
1011         /* Move p after IV to start of encrypted ticket, update length */
1012         p += 16;
1013         eticklen -= 32;
1014         sdec = OPENSSL_malloc(eticklen);
1015         if (!sdec)
1016                 {
1017                 EVP_CIPHER_CTX_cleanup(&ctx);
1018                 return -1;
1019                 }
1020         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
1021         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
1022                 goto tickerr;
1023         slen += mlen;
1024         EVP_CIPHER_CTX_cleanup(&ctx);
1025         p = sdec;
1026                 
1027         sess = d2i_SSL_SESSION(NULL, &p, slen);
1028         OPENSSL_free(sdec);
1029         if (sess)
1030                 {
1031                 /* The session ID if non-empty is used by some clients to
1032                  * detect that the ticket has been accepted. So we copy it to
1033                  * the session structure. If it is empty set length to zero
1034                  * as required by standard.
1035                  */
1036                 if (sesslen)
1037                         memcpy(sess->session_id, sess_id, sesslen);
1038                 sess->session_id_length = sesslen;
1039                 *psess = sess;
1040                 return 1;
1041                 }
1042         /* If session decrypt failure indicate a cache miss and set state to
1043          * send a new ticket
1044          */
1045         tickerr:        
1046         s->tlsext_ticket_expected = 1;
1047         return 0;
1048         }
1049
1050 #endif