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