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