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