Alert to use is now defined in spec: update code
[oweals/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 #include <stdio.h>
60 #include <openssl/objects.h>
61 #include <openssl/evp.h>
62 #include <openssl/hmac.h>
63 #include <openssl/ocsp.h>
64 #include "ssl_locl.h"
65
66 const char tls1_version_str[]="TLSv1" OPENSSL_VERSION_PTEXT;
67
68 #ifndef OPENSSL_NO_TLSEXT
69 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
70                                 const unsigned char *sess_id, int sesslen,
71                                 SSL_SESSION **psess);
72 #endif
73
74 SSL3_ENC_METHOD TLSv1_enc_data={
75         tls1_enc,
76         tls1_mac,
77         tls1_setup_key_block,
78         tls1_generate_master_secret,
79         tls1_change_cipher_state,
80         tls1_final_finish_mac,
81         TLS1_FINISH_MAC_LENGTH,
82         tls1_cert_verify_mac,
83         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
84         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
85         tls1_alert_code,
86         };
87
88 long tls1_default_timeout(void)
89         {
90         /* 2 hours, the 24 hours mentioned in the TLSv1 spec
91          * is way too long for http, the cache would over fill */
92         return(60*60*2);
93         }
94
95 IMPLEMENT_tls1_meth_func(tlsv1_base_method,
96                         ssl_undefined_function,
97                         ssl_undefined_function,
98                         ssl_bad_method)
99
100 int tls1_new(SSL *s)
101         {
102         if (!ssl3_new(s)) return(0);
103         s->method->ssl_clear(s);
104         return(1);
105         }
106
107 void tls1_free(SSL *s)
108         {
109         ssl3_free(s);
110         }
111
112 void tls1_clear(SSL *s)
113         {
114         ssl3_clear(s);
115         s->version=TLS1_VERSION;
116         }
117
118 #if 0
119 long tls1_ctrl(SSL *s, int cmd, long larg, char *parg)
120         {
121         return(0);
122         }
123
124 long tls1_callback_ctrl(SSL *s, int cmd, void *(*fp)())
125         {
126         return(0);
127         }
128 #endif
129
130 #ifndef OPENSSL_NO_TLSEXT
131 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
132         {
133         int extdatalen=0;
134         unsigned char *ret = p;
135
136         /* don't add extensions for SSLv3 unless doing secure renegotiation */
137         if (s->client_version == SSL3_VERSION
138                                         && !s->s3->send_connection_binding)
139                 return p;
140
141         ret+=2;
142
143         if (ret>=limit) return NULL; /* this really never occurs, but ... */
144
145         if (s->tlsext_hostname != NULL)
146                 { 
147                 /* Add TLS extension servername to the Client Hello message */
148                 unsigned long size_str;
149                 long lenmax; 
150
151                 /* check for enough space.
152                    4 for the servername type and entension length
153                    2 for servernamelist length
154                    1 for the hostname type
155                    2 for hostname length
156                    + hostname length 
157                 */
158                    
159                 if ((lenmax = limit - ret - 9) < 0 
160                 || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
161                         return NULL;
162                         
163                 /* extension type and length */
164                 s2n(TLSEXT_TYPE_server_name,ret); 
165                 s2n(size_str+5,ret);
166                 
167                 /* length of servername list */
168                 s2n(size_str+3,ret);
169         
170                 /* hostname type, length and hostname */
171                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
172                 s2n(size_str,ret);
173                 memcpy(ret, s->tlsext_hostname, size_str);
174                 ret+=size_str;
175
176                 }
177         
178         /* Add the renegotiation option: TODOEKR switch */
179         {
180           int el;
181           
182           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
183               {
184               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
185               return NULL;
186               }
187
188           if((limit - p - 4 - el) < 0) return NULL;
189           
190           s2n(TLSEXT_TYPE_renegotiate,ret);
191           s2n(el,ret);
192
193           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
194               {
195               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
196               return NULL;
197               }
198
199           ret += el;
200         }
201
202            
203         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
204                 {
205                 int ticklen;
206                 if (!s->new_session && s->session && s->session->tlsext_tick)
207                         ticklen = s->session->tlsext_ticklen;
208                 else
209                         ticklen = 0;
210                 /* Check for enough room 2 for extension type, 2 for len
211                  * rest for ticket
212                  */
213                 if (limit - ret - 4 - ticklen < 0)
214                         return NULL;
215                 s2n(TLSEXT_TYPE_session_ticket,ret); 
216                 s2n(ticklen,ret);
217                 if (ticklen)
218                         {
219                         memcpy(ret, s->session->tlsext_tick, ticklen);
220                         ret += ticklen;
221                         }
222                 }
223
224         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
225             s->version != DTLS1_VERSION)
226                 {
227                 int i;
228                 long extlen, idlen, itmp;
229                 OCSP_RESPID *id;
230
231                 idlen = 0;
232                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
233                         {
234                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
235                         itmp = i2d_OCSP_RESPID(id, NULL);
236                         if (itmp <= 0)
237                                 return NULL;
238                         idlen += itmp + 2;
239                         }
240
241                 if (s->tlsext_ocsp_exts)
242                         {
243                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
244                         if (extlen < 0)
245                                 return NULL;
246                         }
247                 else
248                         extlen = 0;
249                         
250                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
251                 s2n(TLSEXT_TYPE_status_request, ret);
252                 if (extlen + idlen > 0xFFF0)
253                         return NULL;
254                 s2n(extlen + idlen + 5, ret);
255                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
256                 s2n(idlen, ret);
257                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
258                         {
259                         /* save position of id len */
260                         unsigned char *q = ret;
261                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
262                         /* skip over id len */
263                         ret += 2;
264                         itmp = i2d_OCSP_RESPID(id, &ret);
265                         /* write id len */
266                         s2n(itmp, q);
267                         }
268                 s2n(extlen, ret);
269                 if (extlen > 0)
270                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
271                 }
272
273         if ((extdatalen = ret-p-2)== 0) 
274                 return p;
275
276         s2n(extdatalen,p);
277         return ret;
278         }
279
280 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
281         {
282         int extdatalen=0;
283         unsigned char *ret = p;
284
285         /* don't add extensions for SSLv3, unless doing secure renegotiation */
286         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
287                 return p;
288         
289         ret+=2;
290         if (ret>=limit) return NULL; /* this really never occurs, but ... */
291
292         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
293                 { 
294                 if (limit - ret - 4 < 0) return NULL; 
295
296                 s2n(TLSEXT_TYPE_server_name,ret);
297                 s2n(0,ret);
298                 }
299
300         if(s->s3->send_connection_binding)
301         {
302           int el;
303           
304           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
305               {
306               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
307               return NULL;
308               }
309
310           if((limit - p - 4 - el) < 0) return NULL;
311           
312           s2n(TLSEXT_TYPE_renegotiate,ret);
313           s2n(el,ret);
314
315           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
316               {
317               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
318               return NULL;
319               }
320
321           ret += el;
322         }
323         
324         if (s->tlsext_ticket_expected
325                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
326                 { 
327                 if (limit - ret - 4 < 0) return NULL; 
328                 s2n(TLSEXT_TYPE_session_ticket,ret);
329                 s2n(0,ret);
330                 }
331
332         if (s->tlsext_status_expected)
333                 { 
334                 if ((long)(limit - ret - 4) < 0) return NULL; 
335                 s2n(TLSEXT_TYPE_status_request,ret);
336                 s2n(0,ret);
337                 }
338
339         if ((extdatalen = ret-p-2)== 0) 
340                 return p;
341
342         s2n(extdatalen,p);
343         return ret;
344         }
345
346 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
347         {
348         unsigned short type;
349         unsigned short size;
350         unsigned short len;
351         unsigned char *data = *p;
352         int renegotiate_seen = 0;
353
354         s->servername_done = 0;
355         s->tlsext_status_type = -1;
356
357         if (data >= (d+n-2))
358                 goto ri_check;
359
360         n2s(data,len);
361
362         if (data > (d+n-len)) 
363                 goto ri_check;
364
365         while (data <= (d+n-4))
366                 {
367                 n2s(data,type);
368                 n2s(data,size);
369
370                 if (data+size > (d+n))
371                         goto ri_check;
372
373                 if (s->tlsext_debug_cb)
374                         s->tlsext_debug_cb(s, 0, type, data, size,
375                                                 s->tlsext_debug_arg);
376 /* The servername extension is treated as follows:
377
378    - Only the hostname type is supported with a maximum length of 255.
379    - The servername is rejected if too long or if it contains zeros,
380      in which case an fatal alert is generated.
381    - The servername field is maintained together with the session cache.
382    - When a session is resumed, the servername call back invoked in order
383      to allow the application to position itself to the right context. 
384    - The servername is acknowledged if it is new for a session or when 
385      it is identical to a previously used for the same session. 
386      Applications can control the behaviour.  They can at any time
387      set a 'desirable' servername for a new SSL object. This can be the
388      case for example with HTTPS when a Host: header field is received and
389      a renegotiation is requested. In this case, a possible servername
390      presented in the new client hello is only acknowledged if it matches
391      the value of the Host: field. 
392    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
393      if they provide for changing an explicit servername context for the session,
394      i.e. when the session has been established with a servername extension. 
395    - On session reconnect, the servername extension may be absent. 
396
397 */      
398
399                 if (type == TLSEXT_TYPE_server_name)
400                         {
401                         unsigned char *sdata;
402                         int servname_type;
403                         int dsize; 
404                 
405                         if (size < 2) 
406                                 {
407                                 *al = SSL_AD_DECODE_ERROR;
408                                 return 0;
409                                 }
410                         n2s(data,dsize);  
411                         size -= 2;
412                         if (dsize > size  ) 
413                                 {
414                                 *al = SSL_AD_DECODE_ERROR;
415                                 return 0;
416                                 } 
417
418                         sdata = data;
419                         while (dsize > 3) 
420                                 {
421                                 servname_type = *(sdata++); 
422                                 n2s(sdata,len);
423                                 dsize -= 3;
424
425                                 if (len > dsize) 
426                                         {
427                                         *al = SSL_AD_DECODE_ERROR;
428                                         return 0;
429                                         }
430                                 if (s->servername_done == 0)
431                                 switch (servname_type)
432                                         {
433                                 case TLSEXT_NAMETYPE_host_name:
434                                         if (s->session->tlsext_hostname == NULL)
435                                                 {
436                                                 if (len > TLSEXT_MAXLEN_host_name || 
437                                                         ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL))
438                                                         {
439                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
440                                                         return 0;
441                                                         }
442                                                 memcpy(s->session->tlsext_hostname, sdata, len);
443                                                 s->session->tlsext_hostname[len]='\0';
444                                                 if (strlen(s->session->tlsext_hostname) != len) {
445                                                         OPENSSL_free(s->session->tlsext_hostname);
446                                                         s->session->tlsext_hostname = NULL;
447                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
448                                                         return 0;
449                                                 }
450                                                 s->servername_done = 1; 
451
452                                                 }
453                                         else 
454                                                 s->servername_done = strlen(s->session->tlsext_hostname) == len 
455                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
456                                         
457                                         break;
458
459                                 default:
460                                         break;
461                                         }
462                                  
463                                 dsize -= len;
464                                 }
465                         if (dsize != 0) 
466                                 {
467                                 *al = SSL_AD_DECODE_ERROR;
468                                 return 0;
469                                 }
470
471                         }
472                 else if (type == TLSEXT_TYPE_renegotiate)
473                         {
474                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
475                                 return 0;
476                         renegotiate_seen = 1;
477                         }
478                 else if (type == TLSEXT_TYPE_status_request &&
479                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
480                         {
481                 
482                         if (size < 5) 
483                                 {
484                                 *al = SSL_AD_DECODE_ERROR;
485                                 return 0;
486                                 }
487
488                         s->tlsext_status_type = *data++;
489                         size--;
490                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
491                                 {
492                                 const unsigned char *sdata;
493                                 int dsize;
494                                 /* Read in responder_id_list */
495                                 n2s(data,dsize);
496                                 size -= 2;
497                                 if (dsize > size  ) 
498                                         {
499                                         *al = SSL_AD_DECODE_ERROR;
500                                         return 0;
501                                         }
502                                 while (dsize > 0)
503                                         {
504                                         OCSP_RESPID *id;
505                                         int idsize;
506                                         if (dsize < 4)
507                                                 {
508                                                 *al = SSL_AD_DECODE_ERROR;
509                                                 return 0;
510                                                 }
511                                         n2s(data, idsize);
512                                         dsize -= 2 + idsize;
513                                         if (dsize < 0)
514                                                 {
515                                                 *al = SSL_AD_DECODE_ERROR;
516                                                 return 0;
517                                                 }
518                                         sdata = data;
519                                         data += idsize;
520                                         id = d2i_OCSP_RESPID(NULL,
521                                                                 &sdata, idsize);
522                                         if (!id)
523                                                 {
524                                                 *al = SSL_AD_DECODE_ERROR;
525                                                 return 0;
526                                                 }
527                                         if (data != sdata)
528                                                 {
529                                                 OCSP_RESPID_free(id);
530                                                 *al = SSL_AD_DECODE_ERROR;
531                                                 return 0;
532                                                 }
533                                         if (!s->tlsext_ocsp_ids
534                                                 && !(s->tlsext_ocsp_ids =
535                                                 sk_OCSP_RESPID_new_null()))
536                                                 {
537                                                 OCSP_RESPID_free(id);
538                                                 *al = SSL_AD_INTERNAL_ERROR;
539                                                 return 0;
540                                                 }
541                                         if (!sk_OCSP_RESPID_push(
542                                                         s->tlsext_ocsp_ids, id))
543                                                 {
544                                                 OCSP_RESPID_free(id);
545                                                 *al = SSL_AD_INTERNAL_ERROR;
546                                                 return 0;
547                                                 }
548                                         }
549
550                                 /* Read in request_extensions */
551                                 n2s(data,dsize);
552                                 size -= 2;
553                                 if (dsize > size) 
554                                         {
555                                         *al = SSL_AD_DECODE_ERROR;
556                                         return 0;
557                                         }
558                                 sdata = data;
559                                 if (dsize > 0)
560                                         {
561                                         s->tlsext_ocsp_exts =
562                                                 d2i_X509_EXTENSIONS(NULL,
563                                                         &sdata, dsize);
564                                         if (!s->tlsext_ocsp_exts
565                                                 || (data + dsize != sdata))
566                                                 {
567                                                 *al = SSL_AD_DECODE_ERROR;
568                                                 return 0;
569                                                 }
570                                         }
571                                 }
572                                 /* We don't know what to do with any other type
573                                 * so ignore it.
574                                 */
575                                 else
576                                         s->tlsext_status_type = -1;
577                         }
578
579                 /* session ticket processed earlier */
580
581                 data+=size;             
582                 }
583         *p = data;
584
585         ri_check:
586
587         /* Need RI if renegotiating */
588
589         if (!renegotiate_seen && s->new_session &&
590                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
591                 {
592                 *al = SSL_AD_HANDSHAKE_FAILURE;
593                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,
594                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
595                 return 0;
596                 }
597
598         return 1;
599         }
600
601 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
602         {
603         unsigned short type;
604         unsigned short size;
605         unsigned short len;  
606         unsigned char *data = *p;
607         int tlsext_servername = 0;
608         int renegotiate_seen = 0;
609
610         if (data >= (d+n-2))
611                 goto ri_check;
612
613         n2s(data,len);
614
615         while(data <= (d+n-4))
616                 {
617                 n2s(data,type);
618                 n2s(data,size);
619
620                 if (data+size > (d+n))
621                         goto ri_check;
622
623                 if (s->tlsext_debug_cb)
624                         s->tlsext_debug_cb(s, 1, type, data, size,
625                                                 s->tlsext_debug_arg);
626
627                 if (type == TLSEXT_TYPE_server_name)
628                         {
629                         if (s->tlsext_hostname == NULL || size > 0)
630                                 {
631                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
632                                 return 0;
633                                 }
634                         tlsext_servername = 1;   
635                         }
636                 else if (type == TLSEXT_TYPE_session_ticket)
637                         {
638                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
639                                 || (size > 0))
640                                 {
641                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
642                                 return 0;
643                                 }
644                         s->tlsext_ticket_expected = 1;
645                         }
646                 else if (type == TLSEXT_TYPE_status_request &&
647                          s->version != DTLS1_VERSION)
648                         {
649                         /* MUST be empty and only sent if we've requested
650                          * a status request message.
651                          */ 
652                         if ((s->tlsext_status_type == -1) || (size > 0))
653                                 {
654                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
655                                 return 0;
656                                 }
657                         /* Set flag to expect CertificateStatus message */
658                         s->tlsext_status_expected = 1;
659                         }
660                 else if (type == TLSEXT_TYPE_renegotiate)
661                         {
662                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
663                                 return 0;
664                         renegotiate_seen = 1;
665                         }
666                 data+=size;             
667                 }
668
669         if (data != d+n)
670                 {
671                 *al = SSL_AD_DECODE_ERROR;
672                 return 0;
673                 }
674
675         if (!s->hit && tlsext_servername == 1)
676                 {
677                 if (s->tlsext_hostname)
678                         {
679                         if (s->session->tlsext_hostname == NULL)
680                                 {
681                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
682                                 if (!s->session->tlsext_hostname)
683                                         {
684                                         *al = SSL_AD_UNRECOGNIZED_NAME;
685                                         return 0;
686                                         }
687                                 }
688                         else 
689                                 {
690                                 *al = SSL_AD_DECODE_ERROR;
691                                 return 0;
692                                 }
693                         }
694                 }
695
696         *p = data;
697
698         ri_check:
699
700         /* Determine if we need to see RI. Strictly speaking if we want to
701          * avoid an attack we should *always* see RI even on initial server
702          * hello because the client doesn't see any renegotiation during an
703          * attack. However this would mean we could not connect to any server
704          * which doesn't support RI so for the immediate future tolerate RI
705          * absence on initial connect only.
706          */
707         if (!renegotiate_seen && 
708                 (s->new_session || !(s->options & SSL_OP_LEGACY_SERVER_CONNECT))
709                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
710                 {
711                 *al = SSL_AD_HANDSHAKE_FAILURE;
712                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,
713                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
714                 return 0;
715                 }
716
717         return 1;
718         }
719
720 int ssl_check_clienthello_tlsext(SSL *s)
721         {
722         int ret=SSL_TLSEXT_ERR_NOACK;
723         int al = SSL_AD_UNRECOGNIZED_NAME;
724
725         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
726                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
727         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
728                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
729
730         /* If status request then ask callback what to do.
731          * Note: this must be called after servername callbacks in case 
732          * the certificate has changed.
733          */
734         if ((s->tlsext_status_type != -1) && s->ctx->tlsext_status_cb)
735                 {
736                 int r;
737                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
738                 switch (r)
739                         {
740                         /* We don't want to send a status request response */
741                         case SSL_TLSEXT_ERR_NOACK:
742                                 s->tlsext_status_expected = 0;
743                                 break;
744                         /* status request response should be sent */
745                         case SSL_TLSEXT_ERR_OK:
746                                 if (s->tlsext_ocsp_resp)
747                                         s->tlsext_status_expected = 1;
748                                 else
749                                         s->tlsext_status_expected = 0;
750                                 break;
751                         /* something bad happened */
752                         case SSL_TLSEXT_ERR_ALERT_FATAL:
753                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
754                                 al = SSL_AD_INTERNAL_ERROR;
755                                 goto err;
756                         }
757                 }
758         else
759                 s->tlsext_status_expected = 0;
760         err:
761         switch (ret)
762                 {
763                 case SSL_TLSEXT_ERR_ALERT_FATAL:
764                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
765                         return -1;
766
767                 case SSL_TLSEXT_ERR_ALERT_WARNING:
768                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
769                         return 1; 
770                                         
771                 case SSL_TLSEXT_ERR_NOACK:
772                         s->servername_done=0;
773                         default:
774                 return 1;
775                 }
776         }
777
778 int ssl_check_serverhello_tlsext(SSL *s)
779         {
780         int ret=SSL_TLSEXT_ERR_NOACK;
781         int al = SSL_AD_UNRECOGNIZED_NAME;
782
783         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
784                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
785         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
786                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
787
788         /* If we've requested certificate status and we wont get one
789          * tell the callback
790          */
791         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
792                         && s->ctx->tlsext_status_cb)
793                 {
794                 int r;
795                 /* Set resp to NULL, resplen to -1 so callback knows
796                  * there is no response.
797                  */
798                 if (s->tlsext_ocsp_resp)
799                         {
800                         OPENSSL_free(s->tlsext_ocsp_resp);
801                         s->tlsext_ocsp_resp = NULL;
802                         }
803                 s->tlsext_ocsp_resplen = -1;
804                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
805                 if (r == 0)
806                         {
807                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
808                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
809                         }
810                 if (r < 0)
811                         {
812                         al = SSL_AD_INTERNAL_ERROR;
813                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
814                         }
815                 }
816
817         switch (ret)
818                 {
819                 case SSL_TLSEXT_ERR_ALERT_FATAL:
820                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
821                         return -1;
822
823                 case SSL_TLSEXT_ERR_ALERT_WARNING:
824                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
825                         return 1; 
826                                         
827                 case SSL_TLSEXT_ERR_NOACK:
828                         s->servername_done=0;
829                         default:
830                 return 1;
831                 }
832         }
833
834 /* Since the server cache lookup is done early on in the processing of client
835  * hello and other operations depend on the result we need to handle any TLS
836  * session ticket extension at the same time.
837  */
838
839 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
840                                 const unsigned char *limit, SSL_SESSION **ret)
841         {
842         /* Point after session ID in client hello */
843         const unsigned char *p = session_id + len;
844         unsigned short i;
845
846         /* If tickets disabled behave as if no ticket present
847          * to permit stateful resumption.
848          */
849         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
850                 return 1;
851
852         if ((s->version <= SSL3_VERSION) || !limit)
853                 return 1;
854         if (p >= limit)
855                 return -1;
856         /* Skip past DTLS cookie */
857         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
858                 {
859                 i = *(p++);
860                 p+= i;
861                 if (p >= limit)
862                         return -1;
863                 }
864         /* Skip past cipher list */
865         n2s(p, i);
866         p+= i;
867         if (p >= limit)
868                 return -1;
869         /* Skip past compression algorithm list */
870         i = *(p++);
871         p += i;
872         if (p > limit)
873                 return -1;
874         /* Now at start of extensions */
875         if ((p + 2) >= limit)
876                 return 1;
877         n2s(p, i);
878         while ((p + 4) <= limit)
879                 {
880                 unsigned short type, size;
881                 n2s(p, type);
882                 n2s(p, size);
883                 if (p + size > limit)
884                         return 1;
885                 if (type == TLSEXT_TYPE_session_ticket)
886                         {
887                         /* If zero length note client will accept a ticket
888                          * and indicate cache miss to trigger full handshake
889                          */
890                         if (size == 0)
891                                 {
892                                 s->tlsext_ticket_expected = 1;
893                                 return 0;       /* Cache miss */
894                                 }
895                         return tls_decrypt_ticket(s, p, size, session_id, len,
896                                                                         ret);
897                         }
898                 p += size;
899                 }
900         return 1;
901         }
902
903 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
904                                 const unsigned char *sess_id, int sesslen,
905                                 SSL_SESSION **psess)
906         {
907         SSL_SESSION *sess;
908         unsigned char *sdec;
909         const unsigned char *p;
910         int slen, mlen, renew_ticket = 0;
911         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
912         HMAC_CTX hctx;
913         EVP_CIPHER_CTX ctx;
914         SSL_CTX *tctx = s->initial_ctx;
915         /* Need at least keyname + iv + some encrypted data */
916         if (eticklen < 48)
917                 goto tickerr;
918         /* Initialize session ticket encryption and HMAC contexts */
919         HMAC_CTX_init(&hctx);
920         EVP_CIPHER_CTX_init(&ctx);
921         if (tctx->tlsext_ticket_key_cb)
922                 {
923                 unsigned char *nctick = (unsigned char *)etick;
924                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
925                                                         &ctx, &hctx, 0);
926                 if (rv < 0)
927                         return -1;
928                 if (rv == 0)
929                         goto tickerr;
930                 if (rv == 2)
931                         renew_ticket = 1;
932                 }
933         else
934                 {
935                 /* Check key name matches */
936                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
937                         goto tickerr;
938                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
939                                         tlsext_tick_md(), NULL);
940                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
941                                 tctx->tlsext_tick_aes_key, etick + 16);
942                 }
943         /* Attempt to process session ticket, first conduct sanity and
944          * integrity checks on ticket.
945          */
946         mlen = HMAC_size(&hctx);
947         eticklen -= mlen;
948         /* Check HMAC of encrypted ticket */
949         HMAC_Update(&hctx, etick, eticklen);
950         HMAC_Final(&hctx, tick_hmac, NULL);
951         HMAC_CTX_cleanup(&hctx);
952         if (memcmp(tick_hmac, etick + eticklen, mlen))
953                 goto tickerr;
954         /* Attempt to decrypt session data */
955         /* Move p after IV to start of encrypted ticket, update length */
956         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
957         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
958         sdec = OPENSSL_malloc(eticklen);
959         if (!sdec)
960                 {
961                 EVP_CIPHER_CTX_cleanup(&ctx);
962                 return -1;
963                 }
964         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
965         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
966                 goto tickerr;
967         slen += mlen;
968         EVP_CIPHER_CTX_cleanup(&ctx);
969         p = sdec;
970                 
971         sess = d2i_SSL_SESSION(NULL, &p, slen);
972         OPENSSL_free(sdec);
973         if (sess)
974                 {
975                 /* The session ID if non-empty is used by some clients to
976                  * detect that the ticket has been accepted. So we copy it to
977                  * the session structure. If it is empty set length to zero
978                  * as required by standard.
979                  */
980                 if (sesslen)
981                         memcpy(sess->session_id, sess_id, sesslen);
982                 sess->session_id_length = sesslen;
983                 *psess = sess;
984                 s->tlsext_ticket_expected = renew_ticket;
985                 return 1;
986                 }
987         /* If session decrypt failure indicate a cache miss and set state to
988          * send a new ticket
989          */
990         tickerr:        
991         s->tlsext_ticket_expected = 1;
992         return 0;
993         }
994
995 #endif