67a3f86adcc6528a0ae3d3191d25df3dab92646a
[openssl.git] / ssl / t1_lib.c
1 /* ssl/t1_lib.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include <openssl/objects.h>
114 #include <openssl/evp.h>
115 #include <openssl/hmac.h>
116 #include <openssl/ocsp.h>
117 #include "ssl_locl.h"
118
119 const char tls1_version_str[]="TLSv1" OPENSSL_VERSION_PTEXT;
120
121 #ifndef OPENSSL_NO_TLSEXT
122 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
123                                 const unsigned char *sess_id, int sesslen,
124                                 SSL_SESSION **psess);
125 static int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize);
126 #endif
127
128 SSL3_ENC_METHOD TLSv1_enc_data={
129         tls1_enc,
130         tls1_mac,
131         tls1_setup_key_block,
132         tls1_generate_master_secret,
133         tls1_change_cipher_state,
134         tls1_final_finish_mac,
135         TLS1_FINISH_MAC_LENGTH,
136         tls1_cert_verify_mac,
137         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
138         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
139         tls1_alert_code,
140         };
141
142 long tls1_default_timeout(void)
143         {
144         /* 2 hours, the 24 hours mentioned in the TLSv1 spec
145          * is way too long for http, the cache would over fill */
146         return(60*60*2);
147         }
148
149 int tls1_new(SSL *s)
150         {
151         if (!ssl3_new(s)) return(0);
152         s->method->ssl_clear(s);
153         return(1);
154         }
155
156 void tls1_free(SSL *s)
157         {
158 #ifndef OPENSSL_NO_TLSEXT
159         if (s->tlsext_session_ticket)
160                 {
161                 OPENSSL_free(s->tlsext_session_ticket);
162                 }
163 #endif /* OPENSSL_NO_TLSEXT */
164         ssl3_free(s);
165         }
166
167 void tls1_clear(SSL *s)
168         {
169         ssl3_clear(s);
170         s->version = s->method->version;
171         }
172
173 #ifndef OPENSSL_NO_EC
174 static int nid_list[] =
175         {
176                 NID_sect163k1, /* sect163k1 (1) */
177                 NID_sect163r1, /* sect163r1 (2) */
178                 NID_sect163r2, /* sect163r2 (3) */
179                 NID_sect193r1, /* sect193r1 (4) */ 
180                 NID_sect193r2, /* sect193r2 (5) */ 
181                 NID_sect233k1, /* sect233k1 (6) */
182                 NID_sect233r1, /* sect233r1 (7) */ 
183                 NID_sect239k1, /* sect239k1 (8) */ 
184                 NID_sect283k1, /* sect283k1 (9) */
185                 NID_sect283r1, /* sect283r1 (10) */ 
186                 NID_sect409k1, /* sect409k1 (11) */ 
187                 NID_sect409r1, /* sect409r1 (12) */
188                 NID_sect571k1, /* sect571k1 (13) */ 
189                 NID_sect571r1, /* sect571r1 (14) */ 
190                 NID_secp160k1, /* secp160k1 (15) */
191                 NID_secp160r1, /* secp160r1 (16) */ 
192                 NID_secp160r2, /* secp160r2 (17) */ 
193                 NID_secp192k1, /* secp192k1 (18) */
194                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
195                 NID_secp224k1, /* secp224k1 (20) */ 
196                 NID_secp224r1, /* secp224r1 (21) */
197                 NID_secp256k1, /* secp256k1 (22) */ 
198                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
199                 NID_secp384r1, /* secp384r1 (24) */
200                 NID_secp521r1  /* secp521r1 (25) */     
201         };
202         
203 int tls1_ec_curve_id2nid(int curve_id)
204         {
205         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
206         if ((curve_id < 1) || ((unsigned int)curve_id >
207                                 sizeof(nid_list)/sizeof(nid_list[0])))
208                 return 0;
209         return nid_list[curve_id-1];
210         }
211
212 int tls1_ec_nid2curve_id(int nid)
213         {
214         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
215         switch (nid)
216                 {
217         case NID_sect163k1: /* sect163k1 (1) */
218                 return 1;
219         case NID_sect163r1: /* sect163r1 (2) */
220                 return 2;
221         case NID_sect163r2: /* sect163r2 (3) */
222                 return 3;
223         case NID_sect193r1: /* sect193r1 (4) */ 
224                 return 4;
225         case NID_sect193r2: /* sect193r2 (5) */ 
226                 return 5;
227         case NID_sect233k1: /* sect233k1 (6) */
228                 return 6;
229         case NID_sect233r1: /* sect233r1 (7) */ 
230                 return 7;
231         case NID_sect239k1: /* sect239k1 (8) */ 
232                 return 8;
233         case NID_sect283k1: /* sect283k1 (9) */
234                 return 9;
235         case NID_sect283r1: /* sect283r1 (10) */ 
236                 return 10;
237         case NID_sect409k1: /* sect409k1 (11) */ 
238                 return 11;
239         case NID_sect409r1: /* sect409r1 (12) */
240                 return 12;
241         case NID_sect571k1: /* sect571k1 (13) */ 
242                 return 13;
243         case NID_sect571r1: /* sect571r1 (14) */ 
244                 return 14;
245         case NID_secp160k1: /* secp160k1 (15) */
246                 return 15;
247         case NID_secp160r1: /* secp160r1 (16) */ 
248                 return 16;
249         case NID_secp160r2: /* secp160r2 (17) */ 
250                 return 17;
251         case NID_secp192k1: /* secp192k1 (18) */
252                 return 18;
253         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
254                 return 19;
255         case NID_secp224k1: /* secp224k1 (20) */ 
256                 return 20;
257         case NID_secp224r1: /* secp224r1 (21) */
258                 return 21;
259         case NID_secp256k1: /* secp256k1 (22) */ 
260                 return 22;
261         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
262                 return 23;
263         case NID_secp384r1: /* secp384r1 (24) */
264                 return 24;
265         case NID_secp521r1:  /* secp521r1 (25) */       
266                 return 25;
267         default:
268                 return 0;
269                 }
270         }
271 #endif /* OPENSSL_NO_EC */
272
273 #ifndef OPENSSL_NO_TLSEXT
274 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
275         {
276         int extdatalen=0;
277         unsigned char *ret = p;
278
279         /* don't add extensions for SSLv3 unless doing secure renegotiation */
280         if (s->client_version == SSL3_VERSION
281                                         && !s->s3->send_connection_binding)
282                 return p;
283
284         ret+=2;
285
286         if (ret>=limit) return NULL; /* this really never occurs, but ... */
287
288         if (s->tlsext_hostname != NULL)
289                 { 
290                 /* Add TLS extension servername to the Client Hello message */
291                 unsigned long size_str;
292                 long lenmax; 
293
294                 /* check for enough space.
295                    4 for the servername type and entension length
296                    2 for servernamelist length
297                    1 for the hostname type
298                    2 for hostname length
299                    + hostname length 
300                 */
301                    
302                 if ((lenmax = limit - ret - 9) < 0 
303                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
304                         return NULL;
305                         
306                 /* extension type and length */
307                 s2n(TLSEXT_TYPE_server_name,ret); 
308                 s2n(size_str+5,ret);
309                 
310                 /* length of servername list */
311                 s2n(size_str+3,ret);
312         
313                 /* hostname type, length and hostname */
314                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
315                 s2n(size_str,ret);
316                 memcpy(ret, s->tlsext_hostname, size_str);
317                 ret+=size_str;
318                 }
319
320         /* Add RI if renegotiating */
321         if (s->renegotiate)
322           {
323           int el;
324           
325           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
326               {
327               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
328               return NULL;
329               }
330
331           if((limit - p - 4 - el) < 0) return NULL;
332           
333           s2n(TLSEXT_TYPE_renegotiate,ret);
334           s2n(el,ret);
335
336           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
337               {
338               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
339               return NULL;
340               }
341
342           ret += el;
343         }
344
345 #ifndef OPENSSL_NO_SRP
346 #define MIN(x,y) (((x)<(y))?(x):(y))
347         /* we add SRP username the first time only if we have one! */
348         if (s->srp_ctx.login != NULL)
349                 {/* Add TLS extension SRP username to the Client Hello message */
350                 int login_len = MIN(strlen(s->srp_ctx.login) + 1, 255);
351                 long lenmax; 
352
353                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
354                 if (login_len > lenmax) return NULL;
355                 if (login_len > 255)
356                         {
357                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
358                         return NULL;
359                         }
360                 s2n(TLSEXT_TYPE_srp,ret);
361                 s2n(login_len+1,ret);
362
363                 (*ret++) = (unsigned char) MIN(strlen(s->srp_ctx.login), 254);
364                 memcpy(ret, s->srp_ctx.login, MIN(strlen(s->srp_ctx.login), 254));
365                 ret+=login_len;
366                 }
367 #endif
368
369 #ifndef OPENSSL_NO_EC
370         if (s->tlsext_ecpointformatlist != NULL &&
371             s->version != DTLS1_VERSION)
372                 {
373                 /* Add TLS extension ECPointFormats to the ClientHello message */
374                 long lenmax; 
375
376                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
377                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
378                 if (s->tlsext_ecpointformatlist_length > 255)
379                         {
380                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
381                         return NULL;
382                         }
383                 
384                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
385                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
386                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
387                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
388                 ret+=s->tlsext_ecpointformatlist_length;
389                 }
390         if (s->tlsext_ellipticcurvelist != NULL &&
391             s->version != DTLS1_VERSION)
392                 {
393                 /* Add TLS extension EllipticCurves to the ClientHello message */
394                 long lenmax; 
395
396                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
397                 if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL;
398                 if (s->tlsext_ellipticcurvelist_length > 65532)
399                         {
400                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
401                         return NULL;
402                         }
403                 
404                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
405                 s2n(s->tlsext_ellipticcurvelist_length + 2, ret);
406
407                 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
408                  * elliptic_curve_list, but the examples use two bytes.
409                  * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
410                  * resolves this to two bytes.
411                  */
412                 s2n(s->tlsext_ellipticcurvelist_length, ret);
413                 memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length);
414                 ret+=s->tlsext_ellipticcurvelist_length;
415                 }
416 #endif /* OPENSSL_NO_EC */
417
418         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
419                 {
420                 int ticklen;
421                 if (!s->new_session && s->session && s->session->tlsext_tick)
422                         ticklen = s->session->tlsext_ticklen;
423                 else if (s->session && s->tlsext_session_ticket &&
424                          s->tlsext_session_ticket->data)
425                         {
426                         ticklen = s->tlsext_session_ticket->length;
427                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
428                         if (!s->session->tlsext_tick)
429                                 return NULL;
430                         memcpy(s->session->tlsext_tick,
431                                s->tlsext_session_ticket->data,
432                                ticklen);
433                         s->session->tlsext_ticklen = ticklen;
434                         }
435                 else
436                         ticklen = 0;
437                 if (ticklen == 0 && s->tlsext_session_ticket &&
438                     s->tlsext_session_ticket->data == NULL)
439                         goto skip_ext;
440                 /* Check for enough room 2 for extension type, 2 for len
441                  * rest for ticket
442                  */
443                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
444                 s2n(TLSEXT_TYPE_session_ticket,ret); 
445                 s2n(ticklen,ret);
446                 if (ticklen)
447                         {
448                         memcpy(ret, s->session->tlsext_tick, ticklen);
449                         ret += ticklen;
450                         }
451                 }
452                 skip_ext:
453
454 #ifdef TLSEXT_TYPE_opaque_prf_input
455         if (s->s3->client_opaque_prf_input != NULL &&
456             s->version != DTLS1_VERSION)
457                 {
458                 size_t col = s->s3->client_opaque_prf_input_len;
459                 
460                 if ((long)(limit - ret - 6 - col < 0))
461                         return NULL;
462                 if (col > 0xFFFD) /* can't happen */
463                         return NULL;
464
465                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
466                 s2n(col + 2, ret);
467                 s2n(col, ret);
468                 memcpy(ret, s->s3->client_opaque_prf_input, col);
469                 ret += col;
470                 }
471 #endif
472
473         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
474             s->version != DTLS1_VERSION)
475                 {
476                 int i;
477                 long extlen, idlen, itmp;
478                 OCSP_RESPID *id;
479
480                 idlen = 0;
481                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
482                         {
483                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
484                         itmp = i2d_OCSP_RESPID(id, NULL);
485                         if (itmp <= 0)
486                                 return NULL;
487                         idlen += itmp + 2;
488                         }
489
490                 if (s->tlsext_ocsp_exts)
491                         {
492                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
493                         if (extlen < 0)
494                                 return NULL;
495                         }
496                 else
497                         extlen = 0;
498                         
499                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
500                 s2n(TLSEXT_TYPE_status_request, ret);
501                 if (extlen + idlen > 0xFFF0)
502                         return NULL;
503                 s2n(extlen + idlen + 5, ret);
504                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
505                 s2n(idlen, ret);
506                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
507                         {
508                         /* save position of id len */
509                         unsigned char *q = ret;
510                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
511                         /* skip over id len */
512                         ret += 2;
513                         itmp = i2d_OCSP_RESPID(id, &ret);
514                         /* write id len */
515                         s2n(itmp, q);
516                         }
517                 s2n(extlen, ret);
518                 if (extlen > 0)
519                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
520                 }
521
522 #ifndef OPENSSL_NO_NEXTPROTONEG
523         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
524                 {
525                 /* The client advertises an emtpy extension to indicate its
526                  * support for Next Protocol Negotiation */
527                 if (limit - ret - 4 < 0)
528                         return NULL;
529                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
530                 s2n(0,ret);
531                 }
532 #endif
533
534         if ((extdatalen = ret-p-2)== 0) 
535                 return p;
536
537         s2n(extdatalen,p);
538         return ret;
539         }
540
541 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
542         {
543         int extdatalen=0;
544         unsigned char *ret = p;
545 #ifndef OPENSSL_NO_NEXTPROTONEG
546         int next_proto_neg_seen;
547 #endif
548
549         /* don't add extensions for SSLv3, unless doing secure renegotiation */
550         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
551                 return p;
552         
553         ret+=2;
554         if (ret>=limit) return NULL; /* this really never occurs, but ... */
555
556         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
557                 { 
558                 if ((long)(limit - ret - 4) < 0) return NULL; 
559
560                 s2n(TLSEXT_TYPE_server_name,ret);
561                 s2n(0,ret);
562                 }
563
564         if(s->s3->send_connection_binding)
565         {
566           int el;
567           
568           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
569               {
570               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
571               return NULL;
572               }
573
574           if((limit - p - 4 - el) < 0) return NULL;
575           
576           s2n(TLSEXT_TYPE_renegotiate,ret);
577           s2n(el,ret);
578
579           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
580               {
581               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
582               return NULL;
583               }
584
585           ret += el;
586         }
587
588 #ifndef OPENSSL_NO_EC
589         if (s->tlsext_ecpointformatlist != NULL &&
590             s->version != DTLS1_VERSION)
591                 {
592                 /* Add TLS extension ECPointFormats to the ServerHello message */
593                 long lenmax; 
594
595                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
596                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
597                 if (s->tlsext_ecpointformatlist_length > 255)
598                         {
599                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
600                         return NULL;
601                         }
602                 
603                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
604                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
605                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
606                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
607                 ret+=s->tlsext_ecpointformatlist_length;
608
609                 }
610         /* Currently the server should not respond with a SupportedCurves extension */
611 #endif /* OPENSSL_NO_EC */
612
613         if (s->tlsext_ticket_expected
614                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
615                 { 
616                 if ((long)(limit - ret - 4) < 0) return NULL; 
617                 s2n(TLSEXT_TYPE_session_ticket,ret);
618                 s2n(0,ret);
619                 }
620
621         if (s->tlsext_status_expected)
622                 { 
623                 if ((long)(limit - ret - 4) < 0) return NULL; 
624                 s2n(TLSEXT_TYPE_status_request,ret);
625                 s2n(0,ret);
626                 }
627
628 #ifdef TLSEXT_TYPE_opaque_prf_input
629         if (s->s3->server_opaque_prf_input != NULL &&
630             s->version != DTLS1_VERSION)
631                 {
632                 size_t sol = s->s3->server_opaque_prf_input_len;
633                 
634                 if ((long)(limit - ret - 6 - sol) < 0)
635                         return NULL;
636                 if (sol > 0xFFFD) /* can't happen */
637                         return NULL;
638
639                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
640                 s2n(sol + 2, ret);
641                 s2n(sol, ret);
642                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
643                 ret += sol;
644                 }
645 #endif
646         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
647                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
648                 { const unsigned char cryptopro_ext[36] = {
649                         0xfd, 0xe8, /*65000*/
650                         0x00, 0x20, /*32 bytes length*/
651                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
652                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
653                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
654                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
655                         if (limit-ret<36) return NULL;
656                         memcpy(ret,cryptopro_ext,36);
657                         ret+=36;
658
659                 }
660
661 #ifndef OPENSSL_NO_NEXTPROTONEG
662         next_proto_neg_seen = s->s3->next_proto_neg_seen;
663         s->s3->next_proto_neg_seen = 0;
664         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
665                 {
666                 const unsigned char *npa;
667                 unsigned int npalen;
668                 int r;
669
670                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
671                 if (r == SSL_TLSEXT_ERR_OK)
672                         {
673                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
674                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
675                         s2n(npalen,ret);
676                         memcpy(ret, npa, npalen);
677                         ret += npalen;
678                         s->s3->next_proto_neg_seen = 1;
679                         }
680                 }
681 #endif
682
683         if ((extdatalen = ret-p-2)== 0) 
684                 return p;
685
686         s2n(extdatalen,p);
687         return ret;
688         }
689
690 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
691         {
692         unsigned short type;
693         unsigned short size;
694         unsigned short len;
695         unsigned char *data = *p;
696         int renegotiate_seen = 0;
697         int sigalg_seen = 0;
698
699         s->servername_done = 0;
700         s->tlsext_status_type = -1;
701
702         if (data >= (d+n-2))
703                 goto ri_check;
704         n2s(data,len);
705
706         if (data > (d+n-len)) 
707                 goto ri_check;
708
709         while (data <= (d+n-4))
710                 {
711                 n2s(data,type);
712                 n2s(data,size);
713
714                 if (data+size > (d+n))
715                         goto ri_check;
716 #if 0
717                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
718 #endif
719                 if (s->tlsext_debug_cb)
720                         s->tlsext_debug_cb(s, 0, type, data, size,
721                                                 s->tlsext_debug_arg);
722 /* The servername extension is treated as follows:
723
724    - Only the hostname type is supported with a maximum length of 255.
725    - The servername is rejected if too long or if it contains zeros,
726      in which case an fatal alert is generated.
727    - The servername field is maintained together with the session cache.
728    - When a session is resumed, the servername call back invoked in order
729      to allow the application to position itself to the right context. 
730    - The servername is acknowledged if it is new for a session or when 
731      it is identical to a previously used for the same session. 
732      Applications can control the behaviour.  They can at any time
733      set a 'desirable' servername for a new SSL object. This can be the
734      case for example with HTTPS when a Host: header field is received and
735      a renegotiation is requested. In this case, a possible servername
736      presented in the new client hello is only acknowledged if it matches
737      the value of the Host: field. 
738    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
739      if they provide for changing an explicit servername context for the session,
740      i.e. when the session has been established with a servername extension. 
741    - On session reconnect, the servername extension may be absent. 
742
743 */      
744
745                 if (type == TLSEXT_TYPE_server_name)
746                         {
747                         unsigned char *sdata;
748                         int servname_type;
749                         int dsize; 
750                 
751                         if (size < 2) 
752                                 {
753                                 *al = SSL_AD_DECODE_ERROR;
754                                 return 0;
755                                 }
756                         n2s(data,dsize);  
757                         size -= 2;
758                         if (dsize > size  ) 
759                                 {
760                                 *al = SSL_AD_DECODE_ERROR;
761                                 return 0;
762                                 } 
763
764                         sdata = data;
765                         while (dsize > 3) 
766                                 {
767                                 servname_type = *(sdata++); 
768                                 n2s(sdata,len);
769                                 dsize -= 3;
770
771                                 if (len > dsize) 
772                                         {
773                                         *al = SSL_AD_DECODE_ERROR;
774                                         return 0;
775                                         }
776                                 if (s->servername_done == 0)
777                                 switch (servname_type)
778                                         {
779                                 case TLSEXT_NAMETYPE_host_name:
780                                         if (!s->hit)
781                                                 {
782                                                 if(s->session->tlsext_hostname)
783                                                         {
784                                                         *al = SSL_AD_DECODE_ERROR;
785                                                         return 0;
786                                                         }
787                                                 if (len > TLSEXT_MAXLEN_host_name)
788                                                         {
789                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
790                                                         return 0;
791                                                         }
792                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
793                                                         {
794                                                         *al = TLS1_AD_INTERNAL_ERROR;
795                                                         return 0;
796                                                         }
797                                                 memcpy(s->session->tlsext_hostname, sdata, len);
798                                                 s->session->tlsext_hostname[len]='\0';
799                                                 if (strlen(s->session->tlsext_hostname) != len) {
800                                                         OPENSSL_free(s->session->tlsext_hostname);
801                                                         s->session->tlsext_hostname = NULL;
802                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
803                                                         return 0;
804                                                 }
805                                                 s->servername_done = 1; 
806
807                                                 }
808                                         else 
809                                                 s->servername_done = s->session->tlsext_hostname
810                                                         && strlen(s->session->tlsext_hostname) == len 
811                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
812                                         
813                                         break;
814
815                                 default:
816                                         break;
817                                         }
818                                  
819                                 dsize -= len;
820                                 }
821                         if (dsize != 0) 
822                                 {
823                                 *al = SSL_AD_DECODE_ERROR;
824                                 return 0;
825                                 }
826
827                         }
828 #ifndef OPENSSL_NO_SRP
829                 else if (type == TLSEXT_TYPE_srp)
830                         {
831                         if (size > 0)
832                                 {
833                                 len = data[0];
834                                 if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
835                                         return -1;
836                                 memcpy(s->srp_ctx.login, &data[1], len);
837                                 s->srp_ctx.login[len]='\0';  
838                                 }
839                         }
840 #endif
841
842 #ifndef OPENSSL_NO_EC
843                 else if (type == TLSEXT_TYPE_ec_point_formats &&
844                      s->version != DTLS1_VERSION)
845                         {
846                         unsigned char *sdata = data;
847                         int ecpointformatlist_length = *(sdata++);
848
849                         if (ecpointformatlist_length != size - 1)
850                                 {
851                                 *al = TLS1_AD_DECODE_ERROR;
852                                 return 0;
853                                 }
854                         if (!s->hit)
855                                 {
856                                 if(s->session->tlsext_ecpointformatlist)
857                                         {
858                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
859                                         s->session->tlsext_ecpointformatlist = NULL;
860                                         }
861                                 s->session->tlsext_ecpointformatlist_length = 0;
862                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
863                                         {
864                                         *al = TLS1_AD_INTERNAL_ERROR;
865                                         return 0;
866                                         }
867                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
868                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
869                                 }
870 #if 0
871                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
872                         sdata = s->session->tlsext_ecpointformatlist;
873                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
874                                 fprintf(stderr,"%i ",*(sdata++));
875                         fprintf(stderr,"\n");
876 #endif
877                         }
878                 else if (type == TLSEXT_TYPE_elliptic_curves &&
879                      s->version != DTLS1_VERSION)
880                         {
881                         unsigned char *sdata = data;
882                         int ellipticcurvelist_length = (*(sdata++) << 8);
883                         ellipticcurvelist_length += (*(sdata++));
884
885                         if (ellipticcurvelist_length != size - 2)
886                                 {
887                                 *al = TLS1_AD_DECODE_ERROR;
888                                 return 0;
889                                 }
890                         if (!s->hit)
891                                 {
892                                 if(s->session->tlsext_ellipticcurvelist)
893                                         {
894                                         *al = TLS1_AD_DECODE_ERROR;
895                                         return 0;
896                                         }
897                                 s->session->tlsext_ellipticcurvelist_length = 0;
898                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
899                                         {
900                                         *al = TLS1_AD_INTERNAL_ERROR;
901                                         return 0;
902                                         }
903                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
904                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
905                                 }
906 #if 0
907                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
908                         sdata = s->session->tlsext_ellipticcurvelist;
909                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
910                                 fprintf(stderr,"%i ",*(sdata++));
911                         fprintf(stderr,"\n");
912 #endif
913                         }
914 #endif /* OPENSSL_NO_EC */
915 #ifdef TLSEXT_TYPE_opaque_prf_input
916                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
917                      s->version != DTLS1_VERSION)
918                         {
919                         unsigned char *sdata = data;
920
921                         if (size < 2)
922                                 {
923                                 *al = SSL_AD_DECODE_ERROR;
924                                 return 0;
925                                 }
926                         n2s(sdata, s->s3->client_opaque_prf_input_len);
927                         if (s->s3->client_opaque_prf_input_len != size - 2)
928                                 {
929                                 *al = SSL_AD_DECODE_ERROR;
930                                 return 0;
931                                 }
932
933                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
934                                 OPENSSL_free(s->s3->client_opaque_prf_input);
935                         if (s->s3->client_opaque_prf_input_len == 0)
936                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
937                         else
938                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
939                         if (s->s3->client_opaque_prf_input == NULL)
940                                 {
941                                 *al = TLS1_AD_INTERNAL_ERROR;
942                                 return 0;
943                                 }
944                         }
945 #endif
946                 else if (type == TLSEXT_TYPE_session_ticket)
947                         {
948                         if (s->tls_session_ticket_ext_cb &&
949                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
950                                 {
951                                 *al = TLS1_AD_INTERNAL_ERROR;
952                                 return 0;
953                                 }
954                         }
955                 else if (type == TLSEXT_TYPE_renegotiate)
956                         {
957                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
958                                 return 0;
959                         renegotiate_seen = 1;
960                         }
961                 else if (type == TLSEXT_TYPE_signature_algorithms)
962                         {
963                         int dsize;
964                         if (sigalg_seen || size < 2) 
965                                 {
966                                 *al = SSL_AD_DECODE_ERROR;
967                                 return 0;
968                                 }
969                         sigalg_seen = 1;
970                         n2s(data,dsize);
971                         size -= 2;
972                         if (dsize != size || dsize & 1) 
973                                 {
974                                 *al = SSL_AD_DECODE_ERROR;
975                                 return 0;
976                                 }
977                         if (!tls1_process_sigalgs(s, data, dsize))
978                                 {
979                                 *al = SSL_AD_DECODE_ERROR;
980                                 return 0;
981                                 }
982                         }
983                 else if (type == TLSEXT_TYPE_status_request &&
984                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
985                         {
986                 
987                         if (size < 5) 
988                                 {
989                                 *al = SSL_AD_DECODE_ERROR;
990                                 return 0;
991                                 }
992
993                         s->tlsext_status_type = *data++;
994                         size--;
995                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
996                                 {
997                                 const unsigned char *sdata;
998                                 int dsize;
999                                 /* Read in responder_id_list */
1000                                 n2s(data,dsize);
1001                                 size -= 2;
1002                                 if (dsize > size  ) 
1003                                         {
1004                                         *al = SSL_AD_DECODE_ERROR;
1005                                         return 0;
1006                                         }
1007                                 while (dsize > 0)
1008                                         {
1009                                         OCSP_RESPID *id;
1010                                         int idsize;
1011                                         if (dsize < 4)
1012                                                 {
1013                                                 *al = SSL_AD_DECODE_ERROR;
1014                                                 return 0;
1015                                                 }
1016                                         n2s(data, idsize);
1017                                         dsize -= 2 + idsize;
1018                                         size -= 2 + idsize;
1019                                         if (dsize < 0)
1020                                                 {
1021                                                 *al = SSL_AD_DECODE_ERROR;
1022                                                 return 0;
1023                                                 }
1024                                         sdata = data;
1025                                         data += idsize;
1026                                         id = d2i_OCSP_RESPID(NULL,
1027                                                                 &sdata, idsize);
1028                                         if (!id)
1029                                                 {
1030                                                 *al = SSL_AD_DECODE_ERROR;
1031                                                 return 0;
1032                                                 }
1033                                         if (data != sdata)
1034                                                 {
1035                                                 OCSP_RESPID_free(id);
1036                                                 *al = SSL_AD_DECODE_ERROR;
1037                                                 return 0;
1038                                                 }
1039                                         if (!s->tlsext_ocsp_ids
1040                                                 && !(s->tlsext_ocsp_ids =
1041                                                 sk_OCSP_RESPID_new_null()))
1042                                                 {
1043                                                 OCSP_RESPID_free(id);
1044                                                 *al = SSL_AD_INTERNAL_ERROR;
1045                                                 return 0;
1046                                                 }
1047                                         if (!sk_OCSP_RESPID_push(
1048                                                         s->tlsext_ocsp_ids, id))
1049                                                 {
1050                                                 OCSP_RESPID_free(id);
1051                                                 *al = SSL_AD_INTERNAL_ERROR;
1052                                                 return 0;
1053                                                 }
1054                                         }
1055
1056                                 /* Read in request_extensions */
1057                                 if (size < 2)
1058                                         {
1059                                         *al = SSL_AD_DECODE_ERROR;
1060                                         return 0;
1061                                         }
1062                                 n2s(data,dsize);
1063                                 size -= 2;
1064                                 if (dsize != size)
1065                                         {
1066                                         *al = SSL_AD_DECODE_ERROR;
1067                                         return 0;
1068                                         }
1069                                 sdata = data;
1070                                 if (dsize > 0)
1071                                         {
1072                                         s->tlsext_ocsp_exts =
1073                                                 d2i_X509_EXTENSIONS(NULL,
1074                                                         &sdata, dsize);
1075                                         if (!s->tlsext_ocsp_exts
1076                                                 || (data + dsize != sdata))
1077                                                 {
1078                                                 *al = SSL_AD_DECODE_ERROR;
1079                                                 return 0;
1080                                                 }
1081                                         }
1082                                 }
1083                                 /* We don't know what to do with any other type
1084                                 * so ignore it.
1085                                 */
1086                                 else
1087                                         s->tlsext_status_type = -1;
1088                         }
1089 #ifndef OPENSSL_NO_NEXTPROTONEG
1090                 else if (type == TLSEXT_TYPE_next_proto_neg &&
1091                          s->s3->tmp.finish_md_len == 0)
1092                         {
1093                         /* We shouldn't accept this extension on a
1094                          * renegotiation.
1095                          *
1096                          * s->new_session will be set on renegotiation, but we
1097                          * probably shouldn't rely that it couldn't be set on
1098                          * the initial renegotation too in certain cases (when
1099                          * there's some other reason to disallow resuming an
1100                          * earlier session -- the current code won't be doing
1101                          * anything like that, but this might change).
1102
1103                          * A valid sign that there's been a previous handshake
1104                          * in this connection is if s->s3->tmp.finish_md_len >
1105                          * 0.  (We are talking about a check that will happen
1106                          * in the Hello protocol round, well before a new
1107                          * Finished message could have been computed.) */
1108                         s->s3->next_proto_neg_seen = 1;
1109                         }
1110 #endif
1111
1112                 /* session ticket processed earlier */
1113                 data+=size;
1114                 }
1115                                 
1116         *p = data;
1117
1118         ri_check:
1119
1120         /* Need RI if renegotiating */
1121
1122         if (!renegotiate_seen && s->renegotiate &&
1123                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1124                 {
1125                 *al = SSL_AD_HANDSHAKE_FAILURE;
1126                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,
1127                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1128                 return 0;
1129                 }
1130
1131         return 1;
1132         }
1133
1134 #ifndef OPENSSL_NO_NEXTPROTONEG
1135 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
1136  * elements of zero length are allowed and the set of elements must exactly fill
1137  * the length of the block. */
1138 static int ssl_next_proto_validate(unsigned char *d, unsigned len)
1139         {
1140         unsigned int off = 0;
1141
1142         while (off < len)
1143                 {
1144                 if (d[off] == 0)
1145                         return 0;
1146                 off += d[off];
1147                 off++;
1148                 }
1149
1150         return off == len;
1151         }
1152 #endif
1153
1154 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
1155         {
1156         unsigned short length;
1157         unsigned short type;
1158         unsigned short size;
1159         unsigned char *data = *p;
1160         int tlsext_servername = 0;
1161         int renegotiate_seen = 0;
1162
1163         if (data >= (d+n-2))
1164                 goto ri_check;
1165
1166         n2s(data,length);
1167         if (data+length != d+n)
1168                 {
1169                 *al = SSL_AD_DECODE_ERROR;
1170                 return 0;
1171                 }
1172
1173         while(data <= (d+n-4))
1174                 {
1175                 n2s(data,type);
1176                 n2s(data,size);
1177
1178                 if (data+size > (d+n))
1179                         goto ri_check;
1180
1181                 if (s->tlsext_debug_cb)
1182                         s->tlsext_debug_cb(s, 1, type, data, size,
1183                                                 s->tlsext_debug_arg);
1184
1185                 if (type == TLSEXT_TYPE_server_name)
1186                         {
1187                         if (s->tlsext_hostname == NULL || size > 0)
1188                                 {
1189                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
1190                                 return 0;
1191                                 }
1192                         tlsext_servername = 1;   
1193                         }
1194
1195 #ifndef OPENSSL_NO_EC
1196                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1197                      s->version != DTLS1_VERSION)
1198                         {
1199                         unsigned char *sdata = data;
1200                         int ecpointformatlist_length = *(sdata++);
1201
1202                         if (ecpointformatlist_length != size - 1)
1203                                 {
1204                                 *al = TLS1_AD_DECODE_ERROR;
1205                                 return 0;
1206                                 }
1207                         s->session->tlsext_ecpointformatlist_length = 0;
1208                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
1209                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1210                                 {
1211                                 *al = TLS1_AD_INTERNAL_ERROR;
1212                                 return 0;
1213                                 }
1214                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1215                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1216 #if 0
1217                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
1218                         sdata = s->session->tlsext_ecpointformatlist;
1219                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1220                                 fprintf(stderr,"%i ",*(sdata++));
1221                         fprintf(stderr,"\n");
1222 #endif
1223                         }
1224 #endif /* OPENSSL_NO_EC */
1225
1226                 else if (type == TLSEXT_TYPE_session_ticket)
1227                         {
1228                         if (s->tls_session_ticket_ext_cb &&
1229                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1230                                 {
1231                                 *al = TLS1_AD_INTERNAL_ERROR;
1232                                 return 0;
1233                                 }
1234                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
1235                                 || (size > 0))
1236                                 {
1237                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1238                                 return 0;
1239                                 }
1240                         s->tlsext_ticket_expected = 1;
1241                         }
1242 #ifdef TLSEXT_TYPE_opaque_prf_input
1243                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1244                      s->version != DTLS1_VERSION)
1245                         {
1246                         unsigned char *sdata = data;
1247
1248                         if (size < 2)
1249                                 {
1250                                 *al = SSL_AD_DECODE_ERROR;
1251                                 return 0;
1252                                 }
1253                         n2s(sdata, s->s3->server_opaque_prf_input_len);
1254                         if (s->s3->server_opaque_prf_input_len != size - 2)
1255                                 {
1256                                 *al = SSL_AD_DECODE_ERROR;
1257                                 return 0;
1258                                 }
1259                         
1260                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
1261                                 OPENSSL_free(s->s3->server_opaque_prf_input);
1262                         if (s->s3->server_opaque_prf_input_len == 0)
1263                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1264                         else
1265                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
1266
1267                         if (s->s3->server_opaque_prf_input == NULL)
1268                                 {
1269                                 *al = TLS1_AD_INTERNAL_ERROR;
1270                                 return 0;
1271                                 }
1272                         }
1273 #endif
1274                 else if (type == TLSEXT_TYPE_status_request &&
1275                          s->version != DTLS1_VERSION)
1276                         {
1277                         /* MUST be empty and only sent if we've requested
1278                          * a status request message.
1279                          */ 
1280                         if ((s->tlsext_status_type == -1) || (size > 0))
1281                                 {
1282                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1283                                 return 0;
1284                                 }
1285                         /* Set flag to expect CertificateStatus message */
1286                         s->tlsext_status_expected = 1;
1287                         }
1288 #ifndef OPENSSL_NO_NEXTPROTONEG
1289                 else if (type == TLSEXT_TYPE_next_proto_neg)
1290                         {
1291                         unsigned char *selected;
1292                         unsigned char selected_len;
1293
1294                         /* We must have requested it. */
1295                         if ((s->ctx->next_proto_select_cb == NULL))
1296                                 {
1297                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1298                                 return 0;
1299                                 }
1300                         /* The data must be valid */
1301                         if (!ssl_next_proto_validate(data, size))
1302                                 {
1303                                 *al = TLS1_AD_DECODE_ERROR;
1304                                 return 0;
1305                                 }
1306                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
1307                                 {
1308                                 *al = TLS1_AD_INTERNAL_ERROR;
1309                                 return 0;
1310                                 }
1311                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
1312                         if (!s->next_proto_negotiated)
1313                                 {
1314                                 *al = TLS1_AD_INTERNAL_ERROR;
1315                                 return 0;
1316                                 }
1317                         memcpy(s->next_proto_negotiated, selected, selected_len);
1318                         s->next_proto_negotiated_len = selected_len;
1319                         }
1320 #endif
1321                 else if (type == TLSEXT_TYPE_renegotiate)
1322                         {
1323                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
1324                                 return 0;
1325                         renegotiate_seen = 1;
1326                         }
1327                 data+=size;             
1328                 }
1329
1330         if (data != d+n)
1331                 {
1332                 *al = SSL_AD_DECODE_ERROR;
1333                 return 0;
1334                 }
1335
1336         if (!s->hit && tlsext_servername == 1)
1337                 {
1338                 if (s->tlsext_hostname)
1339                         {
1340                         if (s->session->tlsext_hostname == NULL)
1341                                 {
1342                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
1343                                 if (!s->session->tlsext_hostname)
1344                                         {
1345                                         *al = SSL_AD_UNRECOGNIZED_NAME;
1346                                         return 0;
1347                                         }
1348                                 }
1349                         else 
1350                                 {
1351                                 *al = SSL_AD_DECODE_ERROR;
1352                                 return 0;
1353                                 }
1354                         }
1355                 }
1356
1357         *p = data;
1358
1359         ri_check:
1360
1361         /* Determine if we need to see RI. Strictly speaking if we want to
1362          * avoid an attack we should *always* see RI even on initial server
1363          * hello because the client doesn't see any renegotiation during an
1364          * attack. However this would mean we could not connect to any server
1365          * which doesn't support RI so for the immediate future tolerate RI
1366          * absence on initial connect only.
1367          */
1368         if (!renegotiate_seen
1369                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
1370                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1371                 {
1372                 *al = SSL_AD_HANDSHAKE_FAILURE;
1373                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,
1374                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1375                 return 0;
1376                 }
1377
1378         return 1;
1379         }
1380
1381
1382 int ssl_prepare_clienthello_tlsext(SSL *s)
1383         {
1384 #ifndef OPENSSL_NO_EC
1385         /* If we are client and using an elliptic curve cryptography cipher suite, send the point formats 
1386          * and elliptic curves we support.
1387          */
1388         int using_ecc = 0;
1389         int i;
1390         unsigned char *j;
1391         unsigned long alg_k, alg_a;
1392         STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1393
1394         for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1395                 {
1396                 SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1397
1398                 alg_k = c->algorithm_mkey;
1399                 alg_a = c->algorithm_auth;
1400                 if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe) || (alg_a & SSL_aECDSA)))
1401                         {
1402                         using_ecc = 1;
1403                         break;
1404                         }
1405                 }
1406         using_ecc = using_ecc && (s->version >= TLS1_VERSION);
1407         if (using_ecc)
1408                 {
1409                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
1410                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
1411                         {
1412                         SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1413                         return -1;
1414                         }
1415                 s->tlsext_ecpointformatlist_length = 3;
1416                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
1417                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
1418                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
1419
1420                 /* we support all named elliptic curves in draft-ietf-tls-ecc-12 */
1421                 if (s->tlsext_ellipticcurvelist != NULL) OPENSSL_free(s->tlsext_ellipticcurvelist);
1422                 s->tlsext_ellipticcurvelist_length = sizeof(nid_list)/sizeof(nid_list[0]) * 2;
1423                 if ((s->tlsext_ellipticcurvelist = OPENSSL_malloc(s->tlsext_ellipticcurvelist_length)) == NULL)
1424                         {
1425                         s->tlsext_ellipticcurvelist_length = 0;
1426                         SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1427                         return -1;
1428                         }
1429                 for (i = 1, j = s->tlsext_ellipticcurvelist; (unsigned int)i <=
1430                                 sizeof(nid_list)/sizeof(nid_list[0]); i++)
1431                         s2n(i,j);
1432                 }
1433 #endif /* OPENSSL_NO_EC */
1434
1435 #ifdef TLSEXT_TYPE_opaque_prf_input
1436         {
1437                 int r = 1;
1438         
1439                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
1440                         {
1441                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
1442                         if (!r)
1443                                 return -1;
1444                         }
1445
1446                 if (s->tlsext_opaque_prf_input != NULL)
1447                         {
1448                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1449                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1450
1451                         if (s->tlsext_opaque_prf_input_len == 0)
1452                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1453                         else
1454                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
1455                         if (s->s3->client_opaque_prf_input == NULL)
1456                                 {
1457                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1458                                 return -1;
1459                                 }
1460                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1461                         }
1462
1463                 if (r == 2)
1464                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
1465                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1466         }
1467 #endif
1468
1469         return 1;
1470         }
1471
1472 int ssl_prepare_serverhello_tlsext(SSL *s)
1473         {
1474 #ifndef OPENSSL_NO_EC
1475         /* If we are server and using an ECC cipher suite, send the point formats we support 
1476          * if the client sent us an ECPointsFormat extension.  Note that the server is not
1477          * supposed to send an EllipticCurves extension.
1478          */
1479
1480         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1481         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1482         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1483         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1484         
1485         if (using_ecc)
1486                 {
1487                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
1488                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
1489                         {
1490                         SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1491                         return -1;
1492                         }
1493                 s->tlsext_ecpointformatlist_length = 3;
1494                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
1495                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
1496                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
1497                 }
1498 #endif /* OPENSSL_NO_EC */
1499
1500         return 1;
1501         }
1502
1503 int ssl_check_clienthello_tlsext(SSL *s)
1504         {
1505         int ret=SSL_TLSEXT_ERR_NOACK;
1506         int al = SSL_AD_UNRECOGNIZED_NAME;
1507
1508 #ifndef OPENSSL_NO_EC
1509         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
1510          * ssl3_choose_cipher in s3_lib.c.
1511          */
1512         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
1513          * ssl3_choose_cipher in s3_lib.c.
1514          */
1515 #endif
1516
1517         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
1518                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
1519         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
1520                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
1521
1522         /* If status request then ask callback what to do.
1523          * Note: this must be called after servername callbacks in case 
1524          * the certificate has changed.
1525          */
1526         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
1527                 {
1528                 int r;
1529                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
1530                 switch (r)
1531                         {
1532                         /* We don't want to send a status request response */
1533                         case SSL_TLSEXT_ERR_NOACK:
1534                                 s->tlsext_status_expected = 0;
1535                                 break;
1536                         /* status request response should be sent */
1537                         case SSL_TLSEXT_ERR_OK:
1538                                 if (s->tlsext_ocsp_resp)
1539                                         s->tlsext_status_expected = 1;
1540                                 else
1541                                         s->tlsext_status_expected = 0;
1542                                 break;
1543                         /* something bad happened */
1544                         case SSL_TLSEXT_ERR_ALERT_FATAL:
1545                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1546                                 al = SSL_AD_INTERNAL_ERROR;
1547                                 goto err;
1548                         }
1549                 }
1550         else
1551                 s->tlsext_status_expected = 0;
1552
1553 #ifdef TLSEXT_TYPE_opaque_prf_input
1554         {
1555                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
1556                  * but we might be sending an alert in response to the client hello,
1557                  * so this has to happen here in ssl_check_clienthello_tlsext(). */
1558
1559                 int r = 1;
1560         
1561                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
1562                         {
1563                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
1564                         if (!r)
1565                                 {
1566                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1567                                 al = SSL_AD_INTERNAL_ERROR;
1568                                 goto err;
1569                                 }
1570                         }
1571
1572                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
1573                         OPENSSL_free(s->s3->server_opaque_prf_input);
1574                 s->s3->server_opaque_prf_input = NULL;
1575
1576                 if (s->tlsext_opaque_prf_input != NULL)
1577                         {
1578                         if (s->s3->client_opaque_prf_input != NULL &&
1579                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
1580                                 {
1581                                 /* can only use this extension if we have a server opaque PRF input
1582                                  * of the same length as the client opaque PRF input! */
1583
1584                                 if (s->tlsext_opaque_prf_input_len == 0)
1585                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1586                                 else
1587                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
1588                                 if (s->s3->server_opaque_prf_input == NULL)
1589                                         {
1590                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1591                                         al = SSL_AD_INTERNAL_ERROR;
1592                                         goto err;
1593                                         }
1594                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1595                                 }
1596                         }
1597
1598                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
1599                         {
1600                         /* The callback wants to enforce use of the extension,
1601                          * but we can't do that with the client opaque PRF input;
1602                          * abort the handshake.
1603                          */
1604                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1605                         al = SSL_AD_HANDSHAKE_FAILURE;
1606                         }
1607         }
1608
1609 #endif
1610  err:
1611         switch (ret)
1612                 {
1613                 case SSL_TLSEXT_ERR_ALERT_FATAL:
1614                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
1615                         return -1;
1616
1617                 case SSL_TLSEXT_ERR_ALERT_WARNING:
1618                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
1619                         return 1; 
1620                                         
1621                 case SSL_TLSEXT_ERR_NOACK:
1622                         s->servername_done=0;
1623                         default:
1624                 return 1;
1625                 }
1626         }
1627
1628 int ssl_check_serverhello_tlsext(SSL *s)
1629         {
1630         int ret=SSL_TLSEXT_ERR_NOACK;
1631         int al = SSL_AD_UNRECOGNIZED_NAME;
1632
1633 #ifndef OPENSSL_NO_EC
1634         /* If we are client and using an elliptic curve cryptography cipher
1635          * suite, then if server returns an EC point formats lists extension
1636          * it must contain uncompressed.
1637          */
1638         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1639         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1640         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
1641             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
1642             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
1643                 {
1644                 /* we are using an ECC cipher */
1645                 size_t i;
1646                 unsigned char *list;
1647                 int found_uncompressed = 0;
1648                 list = s->session->tlsext_ecpointformatlist;
1649                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1650                         {
1651                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
1652                                 {
1653                                 found_uncompressed = 1;
1654                                 break;
1655                                 }
1656                         }
1657                 if (!found_uncompressed)
1658                         {
1659                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
1660                         return -1;
1661                         }
1662                 }
1663         ret = SSL_TLSEXT_ERR_OK;
1664 #endif /* OPENSSL_NO_EC */
1665
1666         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
1667                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
1668         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
1669                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
1670
1671 #ifdef TLSEXT_TYPE_opaque_prf_input
1672         if (s->s3->server_opaque_prf_input_len > 0)
1673                 {
1674                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
1675                  * So first verify that we really have a value from the server too. */
1676
1677                 if (s->s3->server_opaque_prf_input == NULL)
1678                         {
1679                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1680                         al = SSL_AD_HANDSHAKE_FAILURE;
1681                         }
1682                 
1683                 /* Anytime the server *has* sent an opaque PRF input, we need to check
1684                  * that we have a client opaque PRF input of the same size. */
1685                 if (s->s3->client_opaque_prf_input == NULL ||
1686                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
1687                         {
1688                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1689                         al = SSL_AD_ILLEGAL_PARAMETER;
1690                         }
1691                 }
1692 #endif
1693
1694         /* If we've requested certificate status and we wont get one
1695          * tell the callback
1696          */
1697         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
1698                         && s->ctx && s->ctx->tlsext_status_cb)
1699                 {
1700                 int r;
1701                 /* Set resp to NULL, resplen to -1 so callback knows
1702                  * there is no response.
1703                  */
1704                 if (s->tlsext_ocsp_resp)
1705                         {
1706                         OPENSSL_free(s->tlsext_ocsp_resp);
1707                         s->tlsext_ocsp_resp = NULL;
1708                         }
1709                 s->tlsext_ocsp_resplen = -1;
1710                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
1711                 if (r == 0)
1712                         {
1713                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1714                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1715                         }
1716                 if (r < 0)
1717                         {
1718                         al = SSL_AD_INTERNAL_ERROR;
1719                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1720                         }
1721                 }
1722
1723         switch (ret)
1724                 {
1725                 case SSL_TLSEXT_ERR_ALERT_FATAL:
1726                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
1727                         return -1;
1728
1729                 case SSL_TLSEXT_ERR_ALERT_WARNING:
1730                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
1731                         return 1; 
1732                                         
1733                 case SSL_TLSEXT_ERR_NOACK:
1734                         s->servername_done=0;
1735                         default:
1736                 return 1;
1737                 }
1738         }
1739
1740 /* Since the server cache lookup is done early on in the processing of client
1741  * hello and other operations depend on the result we need to handle any TLS
1742  * session ticket extension at the same time.
1743  */
1744
1745 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
1746                                 const unsigned char *limit, SSL_SESSION **ret)
1747         {
1748         /* Point after session ID in client hello */
1749         const unsigned char *p = session_id + len;
1750         unsigned short i;
1751
1752         /* If tickets disabled behave as if no ticket present
1753          * to permit stateful resumption.
1754          */
1755         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
1756                 return 1;
1757
1758         if ((s->version <= SSL3_VERSION) || !limit)
1759                 return 1;
1760         if (p >= limit)
1761                 return -1;
1762         /* Skip past DTLS cookie */
1763         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
1764                 {
1765                 i = *(p++);
1766                 p+= i;
1767                 if (p >= limit)
1768                         return -1;
1769                 }
1770         /* Skip past cipher list */
1771         n2s(p, i);
1772         p+= i;
1773         if (p >= limit)
1774                 return -1;
1775         /* Skip past compression algorithm list */
1776         i = *(p++);
1777         p += i;
1778         if (p > limit)
1779                 return -1;
1780         /* Now at start of extensions */
1781         if ((p + 2) >= limit)
1782                 return 1;
1783         n2s(p, i);
1784         while ((p + 4) <= limit)
1785                 {
1786                 unsigned short type, size;
1787                 n2s(p, type);
1788                 n2s(p, size);
1789                 if (p + size > limit)
1790                         return 1;
1791                 if (type == TLSEXT_TYPE_session_ticket)
1792                         {
1793                         /* If tickets disabled indicate cache miss which will
1794                          * trigger a full handshake
1795                          */
1796                         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
1797                                 return 1;
1798                         /* If zero length note client will accept a ticket
1799                          * and indicate cache miss to trigger full handshake
1800                          */
1801                         if (size == 0)
1802                                 {
1803                                 s->tlsext_ticket_expected = 1;
1804                                 return 0;       /* Cache miss */
1805                                 }
1806                         if (s->tls_session_secret_cb)
1807                                 {
1808                                 /* Indicate cache miss here and instead of
1809                                  * generating the session from ticket now,
1810                                  * trigger abbreviated handshake based on
1811                                  * external mechanism to calculate the master
1812                                  * secret later. */
1813                                 return 0;
1814                                 }
1815                         return tls_decrypt_ticket(s, p, size, session_id, len,
1816                                                                         ret);
1817                         }
1818                 p += size;
1819                 }
1820         return 1;
1821         }
1822
1823 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
1824                                 const unsigned char *sess_id, int sesslen,
1825                                 SSL_SESSION **psess)
1826         {
1827         SSL_SESSION *sess;
1828         unsigned char *sdec;
1829         const unsigned char *p;
1830         int slen, mlen, renew_ticket = 0;
1831         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
1832         HMAC_CTX hctx;
1833         EVP_CIPHER_CTX ctx;
1834         SSL_CTX *tctx = s->initial_ctx;
1835         /* Need at least keyname + iv + some encrypted data */
1836         if (eticklen < 48)
1837                 goto tickerr;
1838         /* Initialize session ticket encryption and HMAC contexts */
1839         HMAC_CTX_init(&hctx);
1840         EVP_CIPHER_CTX_init(&ctx);
1841         if (tctx->tlsext_ticket_key_cb)
1842                 {
1843                 unsigned char *nctick = (unsigned char *)etick;
1844                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
1845                                                         &ctx, &hctx, 0);
1846                 if (rv < 0)
1847                         return -1;
1848                 if (rv == 0)
1849                         goto tickerr;
1850                 if (rv == 2)
1851                         renew_ticket = 1;
1852                 }
1853         else
1854                 {
1855                 /* Check key name matches */
1856                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
1857                         goto tickerr;
1858                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
1859                                         tlsext_tick_md(), NULL);
1860                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
1861                                 tctx->tlsext_tick_aes_key, etick + 16);
1862                 }
1863         /* Attempt to process session ticket, first conduct sanity and
1864          * integrity checks on ticket.
1865          */
1866         mlen = HMAC_size(&hctx);
1867         if (mlen < 0)
1868                 {
1869                 EVP_CIPHER_CTX_cleanup(&ctx);
1870                 return -1;
1871                 }
1872         eticklen -= mlen;
1873         /* Check HMAC of encrypted ticket */
1874         HMAC_Update(&hctx, etick, eticklen);
1875         HMAC_Final(&hctx, tick_hmac, NULL);
1876         HMAC_CTX_cleanup(&hctx);
1877         if (memcmp(tick_hmac, etick + eticklen, mlen))
1878                 goto tickerr;
1879         /* Attempt to decrypt session data */
1880         /* Move p after IV to start of encrypted ticket, update length */
1881         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
1882         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
1883         sdec = OPENSSL_malloc(eticklen);
1884         if (!sdec)
1885                 {
1886                 EVP_CIPHER_CTX_cleanup(&ctx);
1887                 return -1;
1888                 }
1889         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
1890         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
1891                 goto tickerr;
1892         slen += mlen;
1893         EVP_CIPHER_CTX_cleanup(&ctx);
1894         p = sdec;
1895                 
1896         sess = d2i_SSL_SESSION(NULL, &p, slen);
1897         OPENSSL_free(sdec);
1898         if (sess)
1899                 {
1900                 /* The session ID if non-empty is used by some clients to
1901                  * detect that the ticket has been accepted. So we copy it to
1902                  * the session structure. If it is empty set length to zero
1903                  * as required by standard.
1904                  */
1905                 if (sesslen)
1906                         memcpy(sess->session_id, sess_id, sesslen);
1907                 sess->session_id_length = sesslen;
1908                 *psess = sess;
1909                 s->tlsext_ticket_expected = renew_ticket;
1910                 return 1;
1911                 }
1912         /* If session decrypt failure indicate a cache miss and set state to
1913          * send a new ticket
1914          */
1915         tickerr:        
1916         s->tlsext_ticket_expected = 1;
1917         return 0;
1918         }
1919
1920 /* Tables to translate from NIDs to TLS v1.2 ids */
1921
1922 typedef struct 
1923         {
1924         int nid;
1925         int id;
1926         } tls12_lookup;
1927
1928 static tls12_lookup tls12_md[] = {
1929 #ifndef OPENSSL_NO_MD5
1930         {NID_md5, TLSEXT_hash_md5},
1931 #endif
1932 #ifndef OPENSSL_NO_SHA
1933         {NID_sha1, TLSEXT_hash_sha1},
1934 #endif
1935 #ifndef OPENSSL_NO_SHA256
1936         {NID_sha224, TLSEXT_hash_sha224},
1937         {NID_sha256, TLSEXT_hash_sha256},
1938 #endif
1939 #ifndef OPENSSL_NO_SHA512
1940         {NID_sha384, TLSEXT_hash_sha384},
1941         {NID_sha512, TLSEXT_hash_sha512}
1942 #endif
1943 };
1944
1945 static tls12_lookup tls12_sig[] = {
1946 #ifndef OPENSSL_NO_RSA
1947         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
1948 #endif
1949 #ifndef OPENSSL_NO_RSA
1950         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
1951 #endif
1952 #ifndef OPENSSL_NO_ECDSA
1953         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
1954 #endif
1955 };
1956
1957 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
1958         {
1959         size_t i;
1960         for (i = 0; i < tlen; i++)
1961                 {
1962                 if (table[i].nid == nid)
1963                         return table[i].id;
1964                 }
1965         return -1;
1966         }
1967 #if 0
1968 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
1969         {
1970         size_t i;
1971         for (i = 0; i < tlen; i++)
1972                 {
1973                 if (table[i].id == id)
1974                         return table[i].nid;
1975                 }
1976         return -1;
1977         }
1978 #endif
1979 int tls12_get_sigandhash(unsigned char *p, EVP_PKEY *pk, const EVP_MD *md)
1980         {
1981         int sig_id, md_id;
1982         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
1983                                 sizeof(tls12_md)/sizeof(tls12_lookup));
1984         if (md_id == -1)
1985                 return 0;
1986         sig_id = tls12_find_id(pk->type, tls12_sig,
1987                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
1988         if (sig_id == -1)
1989                 return 0;
1990         p[0] = (unsigned char)md_id;
1991         p[1] = (unsigned char)sig_id;
1992         return 1;
1993         }
1994
1995 /* Set preferred digest for each key type */
1996
1997 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
1998         {
1999         int i, idx;
2000         const EVP_MD *md;
2001         CERT *c = s->cert;
2002         /* Extension ignored for TLS versions below 1.2 */
2003         if (s->version < TLS1_2_VERSION)
2004                 return 1;
2005
2006         c->pkeys[SSL_PKEY_DSA_SIGN].digest = NULL;
2007         c->pkeys[SSL_PKEY_RSA_SIGN].digest = NULL;
2008         c->pkeys[SSL_PKEY_RSA_ENC].digest = NULL;
2009         c->pkeys[SSL_PKEY_ECC].digest = NULL;
2010
2011         for (i = 0; i < dsize; i += 2)
2012                 {
2013                 unsigned char hash_alg = data[i], sig_alg = data[i+1];
2014
2015                 switch(sig_alg)
2016                         {
2017 #ifndef OPENSSL_NO_RSA
2018                         case TLSEXT_signature_rsa:
2019                         idx = SSL_PKEY_RSA_SIGN;
2020                         break;
2021 #endif
2022 #ifndef OPENSSL_NO_DSA
2023                         case TLSEXT_signature_dsa:
2024                         idx = SSL_PKEY_DSA_SIGN;
2025                         break;
2026 #endif
2027 #ifndef OPENSSL_NO_ECDSA
2028                         case TLSEXT_signature_ecdsa:
2029                         idx = SSL_PKEY_ECC;
2030                         break;
2031 #endif
2032                         default:
2033                         continue;
2034                         }
2035
2036                 if (c->pkeys[idx].digest)
2037                         continue;
2038
2039                 switch(hash_alg)
2040                         {
2041 #ifndef OPENSSL_NO_MD5
2042                         case TLSEXT_hash_md5:
2043                         md = EVP_md5();
2044                         break;
2045 #endif
2046 #ifndef OPENSSL_NO_SHA
2047                         case TLSEXT_hash_sha1:
2048                         md = EVP_sha1();
2049                         break;
2050 #endif
2051 #ifndef OPENSSL_NO_SHA256
2052                         case TLSEXT_hash_sha224:
2053                         md = EVP_sha224();
2054                         break;
2055
2056                         case TLSEXT_hash_sha256:
2057                         md = EVP_sha256();
2058                         break;
2059 #endif
2060 #ifndef OPENSSL_NO_SHA512
2061                         case TLSEXT_hash_sha384:
2062                         md = EVP_sha384();
2063                         break;
2064
2065                         case TLSEXT_hash_sha512:
2066                         md = EVP_sha512();
2067                         break;
2068 #endif
2069                         default:
2070                         continue;
2071
2072                         }
2073
2074                 c->pkeys[idx].digest = md;
2075                 if (idx == SSL_PKEY_RSA_SIGN)
2076                         c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
2077
2078                 }
2079
2080         /* Set any remaining keys to default values. NOTE: if alg is not
2081          * supported it stays as NULL.
2082          */
2083 #ifndef OPENSSL_NO_DSA
2084         if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
2085                 c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_dss1();
2086 #endif
2087 #ifndef OPENSSL_NO_RSA
2088         if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
2089                 {
2090                 c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
2091                 c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
2092                 }
2093 #endif
2094 #ifndef OPENSSL_NO_ECDSA
2095         if (!c->pkeys[SSL_PKEY_ECC].digest)
2096                 c->pkeys[SSL_PKEY_ECC].digest = EVP_ecdsa();
2097 #endif
2098         return 1;
2099         }
2100
2101 #endif