Fix session handling.
[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_ecdsa,
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 #ifndef OPENSSL_NO_NEXTPROTONEG
621         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
622                 {
623                 /* The client advertises an emtpy extension to indicate its
624                  * support for Next Protocol Negotiation */
625                 if (limit - ret - 4 < 0)
626                         return NULL;
627                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
628                 s2n(0,ret);
629                 }
630 #endif
631
632         if ((extdatalen = ret-p-2)== 0) 
633                 return p;
634
635         s2n(extdatalen,p);
636         return ret;
637         }
638
639 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
640         {
641         int extdatalen=0;
642         unsigned char *ret = p;
643 #ifndef OPENSSL_NO_NEXTPROTONEG
644         int next_proto_neg_seen;
645 #endif
646
647         /* don't add extensions for SSLv3, unless doing secure renegotiation */
648         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
649                 return p;
650         
651         ret+=2;
652         if (ret>=limit) return NULL; /* this really never occurs, but ... */
653
654         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
655                 { 
656                 if ((long)(limit - ret - 4) < 0) return NULL; 
657
658                 s2n(TLSEXT_TYPE_server_name,ret);
659                 s2n(0,ret);
660                 }
661
662         if(s->s3->send_connection_binding)
663         {
664           int el;
665           
666           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
667               {
668               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
669               return NULL;
670               }
671
672           if((limit - p - 4 - el) < 0) return NULL;
673           
674           s2n(TLSEXT_TYPE_renegotiate,ret);
675           s2n(el,ret);
676
677           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
678               {
679               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
680               return NULL;
681               }
682
683           ret += el;
684         }
685
686 #ifndef OPENSSL_NO_EC
687         if (s->tlsext_ecpointformatlist != NULL &&
688             s->version != DTLS1_VERSION)
689                 {
690                 /* Add TLS extension ECPointFormats to the ServerHello message */
691                 long lenmax; 
692
693                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
694                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
695                 if (s->tlsext_ecpointformatlist_length > 255)
696                         {
697                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
698                         return NULL;
699                         }
700                 
701                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
702                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
703                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
704                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
705                 ret+=s->tlsext_ecpointformatlist_length;
706
707                 }
708         /* Currently the server should not respond with a SupportedCurves extension */
709 #endif /* OPENSSL_NO_EC */
710
711         if (s->tlsext_ticket_expected
712                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
713                 { 
714                 if ((long)(limit - ret - 4) < 0) return NULL; 
715                 s2n(TLSEXT_TYPE_session_ticket,ret);
716                 s2n(0,ret);
717                 }
718
719         if (s->tlsext_status_expected)
720                 { 
721                 if ((long)(limit - ret - 4) < 0) return NULL; 
722                 s2n(TLSEXT_TYPE_status_request,ret);
723                 s2n(0,ret);
724                 }
725
726 #ifdef TLSEXT_TYPE_opaque_prf_input
727         if (s->s3->server_opaque_prf_input != NULL &&
728             s->version != DTLS1_VERSION)
729                 {
730                 size_t sol = s->s3->server_opaque_prf_input_len;
731                 
732                 if ((long)(limit - ret - 6 - sol) < 0)
733                         return NULL;
734                 if (sol > 0xFFFD) /* can't happen */
735                         return NULL;
736
737                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
738                 s2n(sol + 2, ret);
739                 s2n(sol, ret);
740                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
741                 ret += sol;
742                 }
743 #endif
744         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
745                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
746                 { const unsigned char cryptopro_ext[36] = {
747                         0xfd, 0xe8, /*65000*/
748                         0x00, 0x20, /*32 bytes length*/
749                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
750                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
751                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
752                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
753                         if (limit-ret<36) return NULL;
754                         memcpy(ret,cryptopro_ext,36);
755                         ret+=36;
756
757                 }
758
759 #ifndef OPENSSL_NO_NEXTPROTONEG
760         next_proto_neg_seen = s->s3->next_proto_neg_seen;
761         s->s3->next_proto_neg_seen = 0;
762         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
763                 {
764                 const unsigned char *npa;
765                 unsigned int npalen;
766                 int r;
767
768                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
769                 if (r == SSL_TLSEXT_ERR_OK)
770                         {
771                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
772                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
773                         s2n(npalen,ret);
774                         memcpy(ret, npa, npalen);
775                         ret += npalen;
776                         s->s3->next_proto_neg_seen = 1;
777                         }
778                 }
779 #endif
780
781         if ((extdatalen = ret-p-2)== 0) 
782                 return p;
783
784         s2n(extdatalen,p);
785         return ret;
786         }
787
788 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
789         {
790         unsigned short type;
791         unsigned short size;
792         unsigned short len;
793         unsigned char *data = *p;
794         int renegotiate_seen = 0;
795         int sigalg_seen = 0;
796
797         s->servername_done = 0;
798         s->tlsext_status_type = -1;
799
800         if (data >= (d+n-2))
801                 goto ri_check;
802         n2s(data,len);
803
804         if (data > (d+n-len)) 
805                 goto ri_check;
806
807         while (data <= (d+n-4))
808                 {
809                 n2s(data,type);
810                 n2s(data,size);
811
812                 if (data+size > (d+n))
813                         goto ri_check;
814 #if 0
815                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
816 #endif
817                 if (s->tlsext_debug_cb)
818                         s->tlsext_debug_cb(s, 0, type, data, size,
819                                                 s->tlsext_debug_arg);
820 /* The servername extension is treated as follows:
821
822    - Only the hostname type is supported with a maximum length of 255.
823    - The servername is rejected if too long or if it contains zeros,
824      in which case an fatal alert is generated.
825    - The servername field is maintained together with the session cache.
826    - When a session is resumed, the servername call back invoked in order
827      to allow the application to position itself to the right context. 
828    - The servername is acknowledged if it is new for a session or when 
829      it is identical to a previously used for the same session. 
830      Applications can control the behaviour.  They can at any time
831      set a 'desirable' servername for a new SSL object. This can be the
832      case for example with HTTPS when a Host: header field is received and
833      a renegotiation is requested. In this case, a possible servername
834      presented in the new client hello is only acknowledged if it matches
835      the value of the Host: field. 
836    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
837      if they provide for changing an explicit servername context for the session,
838      i.e. when the session has been established with a servername extension. 
839    - On session reconnect, the servername extension may be absent. 
840
841 */      
842
843                 if (type == TLSEXT_TYPE_server_name)
844                         {
845                         unsigned char *sdata;
846                         int servname_type;
847                         int dsize; 
848                 
849                         if (size < 2) 
850                                 {
851                                 *al = SSL_AD_DECODE_ERROR;
852                                 return 0;
853                                 }
854                         n2s(data,dsize);  
855                         size -= 2;
856                         if (dsize > size  ) 
857                                 {
858                                 *al = SSL_AD_DECODE_ERROR;
859                                 return 0;
860                                 } 
861
862                         sdata = data;
863                         while (dsize > 3) 
864                                 {
865                                 servname_type = *(sdata++); 
866                                 n2s(sdata,len);
867                                 dsize -= 3;
868
869                                 if (len > dsize) 
870                                         {
871                                         *al = SSL_AD_DECODE_ERROR;
872                                         return 0;
873                                         }
874                                 if (s->servername_done == 0)
875                                 switch (servname_type)
876                                         {
877                                 case TLSEXT_NAMETYPE_host_name:
878                                         if (!s->hit)
879                                                 {
880                                                 if(s->session->tlsext_hostname)
881                                                         {
882                                                         *al = SSL_AD_DECODE_ERROR;
883                                                         return 0;
884                                                         }
885                                                 if (len > TLSEXT_MAXLEN_host_name)
886                                                         {
887                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
888                                                         return 0;
889                                                         }
890                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
891                                                         {
892                                                         *al = TLS1_AD_INTERNAL_ERROR;
893                                                         return 0;
894                                                         }
895                                                 memcpy(s->session->tlsext_hostname, sdata, len);
896                                                 s->session->tlsext_hostname[len]='\0';
897                                                 if (strlen(s->session->tlsext_hostname) != len) {
898                                                         OPENSSL_free(s->session->tlsext_hostname);
899                                                         s->session->tlsext_hostname = NULL;
900                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
901                                                         return 0;
902                                                 }
903                                                 s->servername_done = 1; 
904
905                                                 }
906                                         else 
907                                                 s->servername_done = s->session->tlsext_hostname
908                                                         && strlen(s->session->tlsext_hostname) == len 
909                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
910                                         
911                                         break;
912
913                                 default:
914                                         break;
915                                         }
916                                  
917                                 dsize -= len;
918                                 }
919                         if (dsize != 0) 
920                                 {
921                                 *al = SSL_AD_DECODE_ERROR;
922                                 return 0;
923                                 }
924
925                         }
926 #ifndef OPENSSL_NO_SRP
927                 else if (type == TLSEXT_TYPE_srp)
928                         {
929                         if (size > 0)
930                                 {
931                                 len = data[0];
932                                 if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
933                                         return -1;
934                                 memcpy(s->srp_ctx.login, &data[1], len);
935                                 s->srp_ctx.login[len]='\0';  
936                                 }
937                         }
938 #endif
939
940 #ifndef OPENSSL_NO_EC
941                 else if (type == TLSEXT_TYPE_ec_point_formats &&
942                      s->version != DTLS1_VERSION)
943                         {
944                         unsigned char *sdata = data;
945                         int ecpointformatlist_length = *(sdata++);
946
947                         if (ecpointformatlist_length != size - 1)
948                                 {
949                                 *al = TLS1_AD_DECODE_ERROR;
950                                 return 0;
951                                 }
952                         if (!s->hit)
953                                 {
954                                 if(s->session->tlsext_ecpointformatlist)
955                                         {
956                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
957                                         s->session->tlsext_ecpointformatlist = NULL;
958                                         }
959                                 s->session->tlsext_ecpointformatlist_length = 0;
960                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
961                                         {
962                                         *al = TLS1_AD_INTERNAL_ERROR;
963                                         return 0;
964                                         }
965                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
966                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
967                                 }
968 #if 0
969                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
970                         sdata = s->session->tlsext_ecpointformatlist;
971                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
972                                 fprintf(stderr,"%i ",*(sdata++));
973                         fprintf(stderr,"\n");
974 #endif
975                         }
976                 else if (type == TLSEXT_TYPE_elliptic_curves &&
977                      s->version != DTLS1_VERSION)
978                         {
979                         unsigned char *sdata = data;
980                         int ellipticcurvelist_length = (*(sdata++) << 8);
981                         ellipticcurvelist_length += (*(sdata++));
982
983                         if (ellipticcurvelist_length != size - 2)
984                                 {
985                                 *al = TLS1_AD_DECODE_ERROR;
986                                 return 0;
987                                 }
988                         if (!s->hit)
989                                 {
990                                 if(s->session->tlsext_ellipticcurvelist)
991                                         {
992                                         *al = TLS1_AD_DECODE_ERROR;
993                                         return 0;
994                                         }
995                                 s->session->tlsext_ellipticcurvelist_length = 0;
996                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
997                                         {
998                                         *al = TLS1_AD_INTERNAL_ERROR;
999                                         return 0;
1000                                         }
1001                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
1002                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
1003                                 }
1004 #if 0
1005                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
1006                         sdata = s->session->tlsext_ellipticcurvelist;
1007                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
1008                                 fprintf(stderr,"%i ",*(sdata++));
1009                         fprintf(stderr,"\n");
1010 #endif
1011                         }
1012 #endif /* OPENSSL_NO_EC */
1013 #ifdef TLSEXT_TYPE_opaque_prf_input
1014                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1015                      s->version != DTLS1_VERSION)
1016                         {
1017                         unsigned char *sdata = data;
1018
1019                         if (size < 2)
1020                                 {
1021                                 *al = SSL_AD_DECODE_ERROR;
1022                                 return 0;
1023                                 }
1024                         n2s(sdata, s->s3->client_opaque_prf_input_len);
1025                         if (s->s3->client_opaque_prf_input_len != size - 2)
1026                                 {
1027                                 *al = SSL_AD_DECODE_ERROR;
1028                                 return 0;
1029                                 }
1030
1031                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1032                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1033                         if (s->s3->client_opaque_prf_input_len == 0)
1034                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1035                         else
1036                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
1037                         if (s->s3->client_opaque_prf_input == NULL)
1038                                 {
1039                                 *al = TLS1_AD_INTERNAL_ERROR;
1040                                 return 0;
1041                                 }
1042                         }
1043 #endif
1044                 else if (type == TLSEXT_TYPE_session_ticket)
1045                         {
1046                         if (s->tls_session_ticket_ext_cb &&
1047                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1048                                 {
1049                                 *al = TLS1_AD_INTERNAL_ERROR;
1050                                 return 0;
1051                                 }
1052                         }
1053                 else if (type == TLSEXT_TYPE_renegotiate)
1054                         {
1055                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
1056                                 return 0;
1057                         renegotiate_seen = 1;
1058                         }
1059                 else if (type == TLSEXT_TYPE_signature_algorithms)
1060                         {
1061                         int dsize;
1062                         if (sigalg_seen || size < 2) 
1063                                 {
1064                                 *al = SSL_AD_DECODE_ERROR;
1065                                 return 0;
1066                                 }
1067                         sigalg_seen = 1;
1068                         n2s(data,dsize);
1069                         size -= 2;
1070                         if (dsize != size || dsize & 1) 
1071                                 {
1072                                 *al = SSL_AD_DECODE_ERROR;
1073                                 return 0;
1074                                 }
1075                         if (!tls1_process_sigalgs(s, data, dsize))
1076                                 {
1077                                 *al = SSL_AD_DECODE_ERROR;
1078                                 return 0;
1079                                 }
1080                         }
1081                 else if (type == TLSEXT_TYPE_status_request &&
1082                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
1083                         {
1084                 
1085                         if (size < 5) 
1086                                 {
1087                                 *al = SSL_AD_DECODE_ERROR;
1088                                 return 0;
1089                                 }
1090
1091                         s->tlsext_status_type = *data++;
1092                         size--;
1093                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1094                                 {
1095                                 const unsigned char *sdata;
1096                                 int dsize;
1097                                 /* Read in responder_id_list */
1098                                 n2s(data,dsize);
1099                                 size -= 2;
1100                                 if (dsize > size  ) 
1101                                         {
1102                                         *al = SSL_AD_DECODE_ERROR;
1103                                         return 0;
1104                                         }
1105                                 while (dsize > 0)
1106                                         {
1107                                         OCSP_RESPID *id;
1108                                         int idsize;
1109                                         if (dsize < 4)
1110                                                 {
1111                                                 *al = SSL_AD_DECODE_ERROR;
1112                                                 return 0;
1113                                                 }
1114                                         n2s(data, idsize);
1115                                         dsize -= 2 + idsize;
1116                                         size -= 2 + idsize;
1117                                         if (dsize < 0)
1118                                                 {
1119                                                 *al = SSL_AD_DECODE_ERROR;
1120                                                 return 0;
1121                                                 }
1122                                         sdata = data;
1123                                         data += idsize;
1124                                         id = d2i_OCSP_RESPID(NULL,
1125                                                                 &sdata, idsize);
1126                                         if (!id)
1127                                                 {
1128                                                 *al = SSL_AD_DECODE_ERROR;
1129                                                 return 0;
1130                                                 }
1131                                         if (data != sdata)
1132                                                 {
1133                                                 OCSP_RESPID_free(id);
1134                                                 *al = SSL_AD_DECODE_ERROR;
1135                                                 return 0;
1136                                                 }
1137                                         if (!s->tlsext_ocsp_ids
1138                                                 && !(s->tlsext_ocsp_ids =
1139                                                 sk_OCSP_RESPID_new_null()))
1140                                                 {
1141                                                 OCSP_RESPID_free(id);
1142                                                 *al = SSL_AD_INTERNAL_ERROR;
1143                                                 return 0;
1144                                                 }
1145                                         if (!sk_OCSP_RESPID_push(
1146                                                         s->tlsext_ocsp_ids, id))
1147                                                 {
1148                                                 OCSP_RESPID_free(id);
1149                                                 *al = SSL_AD_INTERNAL_ERROR;
1150                                                 return 0;
1151                                                 }
1152                                         }
1153
1154                                 /* Read in request_extensions */
1155                                 if (size < 2)
1156                                         {
1157                                         *al = SSL_AD_DECODE_ERROR;
1158                                         return 0;
1159                                         }
1160                                 n2s(data,dsize);
1161                                 size -= 2;
1162                                 if (dsize != size)
1163                                         {
1164                                         *al = SSL_AD_DECODE_ERROR;
1165                                         return 0;
1166                                         }
1167                                 sdata = data;
1168                                 if (dsize > 0)
1169                                         {
1170                                         s->tlsext_ocsp_exts =
1171                                                 d2i_X509_EXTENSIONS(NULL,
1172                                                         &sdata, dsize);
1173                                         if (!s->tlsext_ocsp_exts
1174                                                 || (data + dsize != sdata))
1175                                                 {
1176                                                 *al = SSL_AD_DECODE_ERROR;
1177                                                 return 0;
1178                                                 }
1179                                         }
1180                                 }
1181                                 /* We don't know what to do with any other type
1182                                 * so ignore it.
1183                                 */
1184                                 else
1185                                         s->tlsext_status_type = -1;
1186                         }
1187 #ifndef OPENSSL_NO_NEXTPROTONEG
1188                 else if (type == TLSEXT_TYPE_next_proto_neg &&
1189                          s->s3->tmp.finish_md_len == 0)
1190                         {
1191                         /* We shouldn't accept this extension on a
1192                          * renegotiation.
1193                          *
1194                          * s->new_session will be set on renegotiation, but we
1195                          * probably shouldn't rely that it couldn't be set on
1196                          * the initial renegotation too in certain cases (when
1197                          * there's some other reason to disallow resuming an
1198                          * earlier session -- the current code won't be doing
1199                          * anything like that, but this might change).
1200
1201                          * A valid sign that there's been a previous handshake
1202                          * in this connection is if s->s3->tmp.finish_md_len >
1203                          * 0.  (We are talking about a check that will happen
1204                          * in the Hello protocol round, well before a new
1205                          * Finished message could have been computed.) */
1206                         s->s3->next_proto_neg_seen = 1;
1207                         }
1208 #endif
1209
1210                 /* session ticket processed earlier */
1211                 data+=size;
1212                 }
1213                                 
1214         *p = data;
1215
1216         ri_check:
1217
1218         /* Need RI if renegotiating */
1219
1220         if (!renegotiate_seen && s->renegotiate &&
1221                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1222                 {
1223                 *al = SSL_AD_HANDSHAKE_FAILURE;
1224                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,
1225                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1226                 return 0;
1227                 }
1228
1229         return 1;
1230         }
1231
1232 #ifndef OPENSSL_NO_NEXTPROTONEG
1233 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
1234  * elements of zero length are allowed and the set of elements must exactly fill
1235  * the length of the block. */
1236 static int ssl_next_proto_validate(unsigned char *d, unsigned len)
1237         {
1238         unsigned int off = 0;
1239
1240         while (off < len)
1241                 {
1242                 if (d[off] == 0)
1243                         return 0;
1244                 off += d[off];
1245                 off++;
1246                 }
1247
1248         return off == len;
1249         }
1250 #endif
1251
1252 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
1253         {
1254         unsigned short length;
1255         unsigned short type;
1256         unsigned short size;
1257         unsigned char *data = *p;
1258         int tlsext_servername = 0;
1259         int renegotiate_seen = 0;
1260
1261         if (data >= (d+n-2))
1262                 goto ri_check;
1263
1264         n2s(data,length);
1265         if (data+length != d+n)
1266                 {
1267                 *al = SSL_AD_DECODE_ERROR;
1268                 return 0;
1269                 }
1270
1271         while(data <= (d+n-4))
1272                 {
1273                 n2s(data,type);
1274                 n2s(data,size);
1275
1276                 if (data+size > (d+n))
1277                         goto ri_check;
1278
1279                 if (s->tlsext_debug_cb)
1280                         s->tlsext_debug_cb(s, 1, type, data, size,
1281                                                 s->tlsext_debug_arg);
1282
1283                 if (type == TLSEXT_TYPE_server_name)
1284                         {
1285                         if (s->tlsext_hostname == NULL || size > 0)
1286                                 {
1287                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
1288                                 return 0;
1289                                 }
1290                         tlsext_servername = 1;   
1291                         }
1292
1293 #ifndef OPENSSL_NO_EC
1294                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1295                      s->version != DTLS1_VERSION)
1296                         {
1297                         unsigned char *sdata = data;
1298                         int ecpointformatlist_length = *(sdata++);
1299
1300                         if (ecpointformatlist_length != size - 1)
1301                                 {
1302                                 *al = TLS1_AD_DECODE_ERROR;
1303                                 return 0;
1304                                 }
1305                         s->session->tlsext_ecpointformatlist_length = 0;
1306                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
1307                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1308                                 {
1309                                 *al = TLS1_AD_INTERNAL_ERROR;
1310                                 return 0;
1311                                 }
1312                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1313                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1314 #if 0
1315                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
1316                         sdata = s->session->tlsext_ecpointformatlist;
1317                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1318                                 fprintf(stderr,"%i ",*(sdata++));
1319                         fprintf(stderr,"\n");
1320 #endif
1321                         }
1322 #endif /* OPENSSL_NO_EC */
1323
1324                 else if (type == TLSEXT_TYPE_session_ticket)
1325                         {
1326                         if (s->tls_session_ticket_ext_cb &&
1327                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1328                                 {
1329                                 *al = TLS1_AD_INTERNAL_ERROR;
1330                                 return 0;
1331                                 }
1332                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
1333                                 || (size > 0))
1334                                 {
1335                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1336                                 return 0;
1337                                 }
1338                         s->tlsext_ticket_expected = 1;
1339                         }
1340 #ifdef TLSEXT_TYPE_opaque_prf_input
1341                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1342                      s->version != DTLS1_VERSION)
1343                         {
1344                         unsigned char *sdata = data;
1345
1346                         if (size < 2)
1347                                 {
1348                                 *al = SSL_AD_DECODE_ERROR;
1349                                 return 0;
1350                                 }
1351                         n2s(sdata, s->s3->server_opaque_prf_input_len);
1352                         if (s->s3->server_opaque_prf_input_len != size - 2)
1353                                 {
1354                                 *al = SSL_AD_DECODE_ERROR;
1355                                 return 0;
1356                                 }
1357                         
1358                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
1359                                 OPENSSL_free(s->s3->server_opaque_prf_input);
1360                         if (s->s3->server_opaque_prf_input_len == 0)
1361                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1362                         else
1363                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
1364
1365                         if (s->s3->server_opaque_prf_input == NULL)
1366                                 {
1367                                 *al = TLS1_AD_INTERNAL_ERROR;
1368                                 return 0;
1369                                 }
1370                         }
1371 #endif
1372                 else if (type == TLSEXT_TYPE_status_request &&
1373                          s->version != DTLS1_VERSION)
1374                         {
1375                         /* MUST be empty and only sent if we've requested
1376                          * a status request message.
1377                          */ 
1378                         if ((s->tlsext_status_type == -1) || (size > 0))
1379                                 {
1380                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1381                                 return 0;
1382                                 }
1383                         /* Set flag to expect CertificateStatus message */
1384                         s->tlsext_status_expected = 1;
1385                         }
1386 #ifndef OPENSSL_NO_NEXTPROTONEG
1387                 else if (type == TLSEXT_TYPE_next_proto_neg)
1388                         {
1389                         unsigned char *selected;
1390                         unsigned char selected_len;
1391
1392                         /* We must have requested it. */
1393                         if ((s->ctx->next_proto_select_cb == NULL))
1394                                 {
1395                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1396                                 return 0;
1397                                 }
1398                         /* The data must be valid */
1399                         if (!ssl_next_proto_validate(data, size))
1400                                 {
1401                                 *al = TLS1_AD_DECODE_ERROR;
1402                                 return 0;
1403                                 }
1404                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
1405                                 {
1406                                 *al = TLS1_AD_INTERNAL_ERROR;
1407                                 return 0;
1408                                 }
1409                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
1410                         if (!s->next_proto_negotiated)
1411                                 {
1412                                 *al = TLS1_AD_INTERNAL_ERROR;
1413                                 return 0;
1414                                 }
1415                         memcpy(s->next_proto_negotiated, selected, selected_len);
1416                         s->next_proto_negotiated_len = selected_len;
1417                         }
1418 #endif
1419                 else if (type == TLSEXT_TYPE_renegotiate)
1420                         {
1421                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
1422                                 return 0;
1423                         renegotiate_seen = 1;
1424                         }
1425                 data+=size;             
1426                 }
1427
1428         if (data != d+n)
1429                 {
1430                 *al = SSL_AD_DECODE_ERROR;
1431                 return 0;
1432                 }
1433
1434         if (!s->hit && tlsext_servername == 1)
1435                 {
1436                 if (s->tlsext_hostname)
1437                         {
1438                         if (s->session->tlsext_hostname == NULL)
1439                                 {
1440                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
1441                                 if (!s->session->tlsext_hostname)
1442                                         {
1443                                         *al = SSL_AD_UNRECOGNIZED_NAME;
1444                                         return 0;
1445                                         }
1446                                 }
1447                         else 
1448                                 {
1449                                 *al = SSL_AD_DECODE_ERROR;
1450                                 return 0;
1451                                 }
1452                         }
1453                 }
1454
1455         *p = data;
1456
1457         ri_check:
1458
1459         /* Determine if we need to see RI. Strictly speaking if we want to
1460          * avoid an attack we should *always* see RI even on initial server
1461          * hello because the client doesn't see any renegotiation during an
1462          * attack. However this would mean we could not connect to any server
1463          * which doesn't support RI so for the immediate future tolerate RI
1464          * absence on initial connect only.
1465          */
1466         if (!renegotiate_seen
1467                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
1468                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1469                 {
1470                 *al = SSL_AD_HANDSHAKE_FAILURE;
1471                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,
1472                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1473                 return 0;
1474                 }
1475
1476         return 1;
1477         }
1478
1479
1480 int ssl_prepare_clienthello_tlsext(SSL *s)
1481         {
1482 #ifndef OPENSSL_NO_EC
1483         /* If we are client and using an elliptic curve cryptography cipher suite, send the point formats 
1484          * and elliptic curves we support.
1485          */
1486         int using_ecc = 0;
1487         int i;
1488         unsigned char *j;
1489         unsigned long alg_k, alg_a;
1490         STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1491
1492         for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1493                 {
1494                 SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1495
1496                 alg_k = c->algorithm_mkey;
1497                 alg_a = c->algorithm_auth;
1498                 if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe) || (alg_a & SSL_aECDSA)))
1499                         {
1500                         using_ecc = 1;
1501                         break;
1502                         }
1503                 }
1504         using_ecc = using_ecc && (s->version >= TLS1_VERSION);
1505         if (using_ecc)
1506                 {
1507                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
1508                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
1509                         {
1510                         SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1511                         return -1;
1512                         }
1513                 s->tlsext_ecpointformatlist_length = 3;
1514                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
1515                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
1516                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
1517
1518                 /* we support all named elliptic curves in draft-ietf-tls-ecc-12 */
1519                 if (s->tlsext_ellipticcurvelist != NULL) OPENSSL_free(s->tlsext_ellipticcurvelist);
1520                 s->tlsext_ellipticcurvelist_length = sizeof(pref_list)/sizeof(pref_list[0]) * 2;
1521                 if ((s->tlsext_ellipticcurvelist = OPENSSL_malloc(s->tlsext_ellipticcurvelist_length)) == NULL)
1522                         {
1523                         s->tlsext_ellipticcurvelist_length = 0;
1524                         SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1525                         return -1;
1526                         }
1527                 for (i = 0, j = s->tlsext_ellipticcurvelist; (unsigned int)i <
1528                                 sizeof(pref_list)/sizeof(pref_list[0]); i++)
1529                         {
1530                         int id = tls1_ec_nid2curve_id(pref_list[i]);
1531                         s2n(id,j);
1532                         }
1533                 }
1534 #endif /* OPENSSL_NO_EC */
1535
1536 #ifdef TLSEXT_TYPE_opaque_prf_input
1537         {
1538                 int r = 1;
1539         
1540                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
1541                         {
1542                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
1543                         if (!r)
1544                                 return -1;
1545                         }
1546
1547                 if (s->tlsext_opaque_prf_input != NULL)
1548                         {
1549                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1550                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1551
1552                         if (s->tlsext_opaque_prf_input_len == 0)
1553                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1554                         else
1555                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
1556                         if (s->s3->client_opaque_prf_input == NULL)
1557                                 {
1558                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1559                                 return -1;
1560                                 }
1561                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1562                         }
1563
1564                 if (r == 2)
1565                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
1566                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1567         }
1568 #endif
1569
1570         return 1;
1571         }
1572
1573 int ssl_prepare_serverhello_tlsext(SSL *s)
1574         {
1575 #ifndef OPENSSL_NO_EC
1576         /* If we are server and using an ECC cipher suite, send the point formats we support 
1577          * if the client sent us an ECPointsFormat extension.  Note that the server is not
1578          * supposed to send an EllipticCurves extension.
1579          */
1580
1581         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1582         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1583         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1584         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1585         
1586         if (using_ecc)
1587                 {
1588                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
1589                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
1590                         {
1591                         SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1592                         return -1;
1593                         }
1594                 s->tlsext_ecpointformatlist_length = 3;
1595                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
1596                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
1597                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
1598                 }
1599 #endif /* OPENSSL_NO_EC */
1600
1601         return 1;
1602         }
1603
1604 int ssl_check_clienthello_tlsext(SSL *s)
1605         {
1606         int ret=SSL_TLSEXT_ERR_NOACK;
1607         int al = SSL_AD_UNRECOGNIZED_NAME;
1608
1609 #ifndef OPENSSL_NO_EC
1610         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
1611          * ssl3_choose_cipher in s3_lib.c.
1612          */
1613         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
1614          * ssl3_choose_cipher in s3_lib.c.
1615          */
1616 #endif
1617
1618         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
1619                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
1620         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
1621                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
1622
1623         /* If status request then ask callback what to do.
1624          * Note: this must be called after servername callbacks in case 
1625          * the certificate has changed.
1626          */
1627         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
1628                 {
1629                 int r;
1630                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
1631                 switch (r)
1632                         {
1633                         /* We don't want to send a status request response */
1634                         case SSL_TLSEXT_ERR_NOACK:
1635                                 s->tlsext_status_expected = 0;
1636                                 break;
1637                         /* status request response should be sent */
1638                         case SSL_TLSEXT_ERR_OK:
1639                                 if (s->tlsext_ocsp_resp)
1640                                         s->tlsext_status_expected = 1;
1641                                 else
1642                                         s->tlsext_status_expected = 0;
1643                                 break;
1644                         /* something bad happened */
1645                         case SSL_TLSEXT_ERR_ALERT_FATAL:
1646                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1647                                 al = SSL_AD_INTERNAL_ERROR;
1648                                 goto err;
1649                         }
1650                 }
1651         else
1652                 s->tlsext_status_expected = 0;
1653
1654 #ifdef TLSEXT_TYPE_opaque_prf_input
1655         {
1656                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
1657                  * but we might be sending an alert in response to the client hello,
1658                  * so this has to happen here in ssl_check_clienthello_tlsext(). */
1659
1660                 int r = 1;
1661         
1662                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
1663                         {
1664                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
1665                         if (!r)
1666                                 {
1667                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1668                                 al = SSL_AD_INTERNAL_ERROR;
1669                                 goto err;
1670                                 }
1671                         }
1672
1673                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
1674                         OPENSSL_free(s->s3->server_opaque_prf_input);
1675                 s->s3->server_opaque_prf_input = NULL;
1676
1677                 if (s->tlsext_opaque_prf_input != NULL)
1678                         {
1679                         if (s->s3->client_opaque_prf_input != NULL &&
1680                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
1681                                 {
1682                                 /* can only use this extension if we have a server opaque PRF input
1683                                  * of the same length as the client opaque PRF input! */
1684
1685                                 if (s->tlsext_opaque_prf_input_len == 0)
1686                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1687                                 else
1688                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
1689                                 if (s->s3->server_opaque_prf_input == NULL)
1690                                         {
1691                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1692                                         al = SSL_AD_INTERNAL_ERROR;
1693                                         goto err;
1694                                         }
1695                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1696                                 }
1697                         }
1698
1699                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
1700                         {
1701                         /* The callback wants to enforce use of the extension,
1702                          * but we can't do that with the client opaque PRF input;
1703                          * abort the handshake.
1704                          */
1705                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1706                         al = SSL_AD_HANDSHAKE_FAILURE;
1707                         }
1708         }
1709
1710 #endif
1711  err:
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 int ssl_check_serverhello_tlsext(SSL *s)
1730         {
1731         int ret=SSL_TLSEXT_ERR_NOACK;
1732         int al = SSL_AD_UNRECOGNIZED_NAME;
1733
1734 #ifndef OPENSSL_NO_EC
1735         /* If we are client and using an elliptic curve cryptography cipher
1736          * suite, then if server returns an EC point formats lists extension
1737          * it must contain uncompressed.
1738          */
1739         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1740         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1741         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
1742             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
1743             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
1744                 {
1745                 /* we are using an ECC cipher */
1746                 size_t i;
1747                 unsigned char *list;
1748                 int found_uncompressed = 0;
1749                 list = s->session->tlsext_ecpointformatlist;
1750                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1751                         {
1752                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
1753                                 {
1754                                 found_uncompressed = 1;
1755                                 break;
1756                                 }
1757                         }
1758                 if (!found_uncompressed)
1759                         {
1760                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
1761                         return -1;
1762                         }
1763                 }
1764         ret = SSL_TLSEXT_ERR_OK;
1765 #endif /* OPENSSL_NO_EC */
1766
1767         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
1768                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
1769         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
1770                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
1771
1772 #ifdef TLSEXT_TYPE_opaque_prf_input
1773         if (s->s3->server_opaque_prf_input_len > 0)
1774                 {
1775                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
1776                  * So first verify that we really have a value from the server too. */
1777
1778                 if (s->s3->server_opaque_prf_input == NULL)
1779                         {
1780                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1781                         al = SSL_AD_HANDSHAKE_FAILURE;
1782                         }
1783                 
1784                 /* Anytime the server *has* sent an opaque PRF input, we need to check
1785                  * that we have a client opaque PRF input of the same size. */
1786                 if (s->s3->client_opaque_prf_input == NULL ||
1787                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
1788                         {
1789                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1790                         al = SSL_AD_ILLEGAL_PARAMETER;
1791                         }
1792                 }
1793 #endif
1794
1795         /* If we've requested certificate status and we wont get one
1796          * tell the callback
1797          */
1798         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
1799                         && s->ctx && s->ctx->tlsext_status_cb)
1800                 {
1801                 int r;
1802                 /* Set resp to NULL, resplen to -1 so callback knows
1803                  * there is no response.
1804                  */
1805                 if (s->tlsext_ocsp_resp)
1806                         {
1807                         OPENSSL_free(s->tlsext_ocsp_resp);
1808                         s->tlsext_ocsp_resp = NULL;
1809                         }
1810                 s->tlsext_ocsp_resplen = -1;
1811                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
1812                 if (r == 0)
1813                         {
1814                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1815                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1816                         }
1817                 if (r < 0)
1818                         {
1819                         al = SSL_AD_INTERNAL_ERROR;
1820                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1821                         }
1822                 }
1823
1824         switch (ret)
1825                 {
1826                 case SSL_TLSEXT_ERR_ALERT_FATAL:
1827                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
1828                         return -1;
1829
1830                 case SSL_TLSEXT_ERR_ALERT_WARNING:
1831                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
1832                         return 1; 
1833                                         
1834                 case SSL_TLSEXT_ERR_NOACK:
1835                         s->servername_done=0;
1836                         default:
1837                 return 1;
1838                 }
1839         }
1840
1841 /* Since the server cache lookup is done early on in the processing of the
1842  * ClientHello, and other operations depend on the result, we need to handle
1843  * any TLS session ticket extension at the same time.
1844  *
1845  *   session_id: points at the session ID in the ClientHello. This code will
1846  *       read past the end of this in order to parse out the session ticket
1847  *       extension, if any.
1848  *   len: the length of the session ID.
1849  *   limit: a pointer to the first byte after the ClientHello.
1850  *   ret: (output) on return, if a ticket was decrypted, then this is set to
1851  *       point to the resulting session.
1852  *
1853  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
1854  * ciphersuite, in which case we have no use for session tickets and one will
1855  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
1856  *
1857  * Returns:
1858  *   -1: fatal error, either from parsing or decrypting the ticket.
1859  *    0: no ticket was found (or was ignored, based on settings).
1860  *    1: a zero length extension was found, indicating that the client supports
1861  *       session tickets but doesn't currently have one to offer.
1862  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
1863  *       couldn't be decrypted because of a non-fatal error.
1864  *    3: a ticket was successfully decrypted and *ret was set.
1865  *
1866  * Side effects:
1867  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
1868  *   a new session ticket to the client because the client indicated support
1869  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
1870  *   a session ticket or we couldn't use the one it gave us, or if
1871  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
1872  *   Otherwise, s->tlsext_ticket_expected is set to 0.
1873  */
1874 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
1875                         const unsigned char *limit, SSL_SESSION **ret)
1876         {
1877         /* Point after session ID in client hello */
1878         const unsigned char *p = session_id + len;
1879         unsigned short i;
1880
1881         *ret = NULL;
1882         s->tlsext_ticket_expected = 0;
1883
1884         /* If tickets disabled behave as if no ticket present
1885          * to permit stateful resumption.
1886          */
1887         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
1888                 return 0;
1889         if ((s->version <= SSL3_VERSION) || !limit)
1890                 return 0;
1891         if (p >= limit)
1892                 return -1;
1893         /* Skip past DTLS cookie */
1894         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
1895                 {
1896                 i = *(p++);
1897                 p+= i;
1898                 if (p >= limit)
1899                         return -1;
1900                 }
1901         /* Skip past cipher list */
1902         n2s(p, i);
1903         p+= i;
1904         if (p >= limit)
1905                 return -1;
1906         /* Skip past compression algorithm list */
1907         i = *(p++);
1908         p += i;
1909         if (p > limit)
1910                 return -1;
1911         /* Now at start of extensions */
1912         if ((p + 2) >= limit)
1913                 return 0;
1914         n2s(p, i);
1915         while ((p + 4) <= limit)
1916                 {
1917                 unsigned short type, size;
1918                 n2s(p, type);
1919                 n2s(p, size);
1920                 if (p + size > limit)
1921                         return 0;
1922                 if (type == TLSEXT_TYPE_session_ticket)
1923                         {
1924                         int r;
1925                         if (size == 0)
1926                                 {
1927                                 /* The client will accept a ticket but doesn't
1928                                  * currently have one. */
1929                                 s->tlsext_ticket_expected = 1;
1930                                 return 1;
1931                                 }
1932                         if (s->tls_session_secret_cb)
1933                                 {
1934                                 /* Indicate that the ticket couldn't be
1935                                  * decrypted rather than generating the session
1936                                  * from ticket now, trigger abbreviated
1937                                  * handshake based on external mechanism to
1938                                  * calculate the master secret later. */
1939                                 return 2;
1940                                 }
1941                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
1942                         switch (r)
1943                                 {
1944                                 case 2: /* ticket couldn't be decrypted */
1945                                         s->tlsext_ticket_expected = 1;
1946                                         return 2;
1947                                 case 3: /* ticket was decrypted */
1948                                         return r;
1949                                 case 4: /* ticket decrypted but need to renew */
1950                                         s->tlsext_ticket_expected = 1;
1951                                         return 3;
1952                                 default: /* fatal error */
1953                                         return -1;
1954                                 }
1955                         }
1956                 p += size;
1957                 }
1958         return 0;
1959         }
1960
1961 /* tls_decrypt_ticket attempts to decrypt a session ticket.
1962  *
1963  *   etick: points to the body of the session ticket extension.
1964  *   eticklen: the length of the session tickets extenion.
1965  *   sess_id: points at the session ID.
1966  *   sesslen: the length of the session ID.
1967  *   psess: (output) on return, if a ticket was decrypted, then this is set to
1968  *       point to the resulting session.
1969  *
1970  * Returns:
1971  *   -1: fatal error, either from parsing or decrypting the ticket.
1972  *    2: the ticket couldn't be decrypted.
1973  *    3: a ticket was successfully decrypted and *psess was set.
1974  *    4: same as 3, but the ticket needs to be renewed.
1975  */
1976 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
1977                                 const unsigned char *sess_id, int sesslen,
1978                                 SSL_SESSION **psess)
1979         {
1980         SSL_SESSION *sess;
1981         unsigned char *sdec;
1982         const unsigned char *p;
1983         int slen, mlen, renew_ticket = 0;
1984         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
1985         HMAC_CTX hctx;
1986         EVP_CIPHER_CTX ctx;
1987         SSL_CTX *tctx = s->initial_ctx;
1988         /* Need at least keyname + iv + some encrypted data */
1989         if (eticklen < 48)
1990                 return 2;
1991         /* Initialize session ticket encryption and HMAC contexts */
1992         HMAC_CTX_init(&hctx);
1993         EVP_CIPHER_CTX_init(&ctx);
1994         if (tctx->tlsext_ticket_key_cb)
1995                 {
1996                 unsigned char *nctick = (unsigned char *)etick;
1997                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
1998                                                         &ctx, &hctx, 0);
1999                 if (rv < 0)
2000                         return -1;
2001                 if (rv == 0)
2002                         return 2;
2003                 if (rv == 2)
2004                         renew_ticket = 1;
2005                 }
2006         else
2007                 {
2008                 /* Check key name matches */
2009                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
2010                         return 2;
2011                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2012                                         tlsext_tick_md(), NULL);
2013                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2014                                 tctx->tlsext_tick_aes_key, etick + 16);
2015                 }
2016         /* Attempt to process session ticket, first conduct sanity and
2017          * integrity checks on ticket.
2018          */
2019         mlen = HMAC_size(&hctx);
2020         if (mlen < 0)
2021                 {
2022                 EVP_CIPHER_CTX_cleanup(&ctx);
2023                 return -1;
2024                 }
2025         eticklen -= mlen;
2026         /* Check HMAC of encrypted ticket */
2027         HMAC_Update(&hctx, etick, eticklen);
2028         HMAC_Final(&hctx, tick_hmac, NULL);
2029         HMAC_CTX_cleanup(&hctx);
2030         if (memcmp(tick_hmac, etick + eticklen, mlen))
2031                 return 2;
2032         /* Attempt to decrypt session data */
2033         /* Move p after IV to start of encrypted ticket, update length */
2034         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2035         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2036         sdec = OPENSSL_malloc(eticklen);
2037         if (!sdec)
2038                 {
2039                 EVP_CIPHER_CTX_cleanup(&ctx);
2040                 return -1;
2041                 }
2042         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
2043         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
2044                 return 2;
2045         slen += mlen;
2046         EVP_CIPHER_CTX_cleanup(&ctx);
2047         p = sdec;
2048
2049         sess = d2i_SSL_SESSION(NULL, &p, slen);
2050         OPENSSL_free(sdec);
2051         if (sess)
2052                 {
2053                 /* The session ID, if non-empty, is used by some clients to
2054                  * detect that the ticket has been accepted. So we copy it to
2055                  * the session structure. If it is empty set length to zero
2056                  * as required by standard.
2057                  */
2058                 if (sesslen)
2059                         memcpy(sess->session_id, sess_id, sesslen);
2060                 sess->session_id_length = sesslen;
2061                 *psess = sess;
2062                 if (renew_ticket)
2063                         return 4;
2064                 else
2065                         return 3;
2066                 }
2067         ERR_clear_error();
2068         /* For session parse failure, indicate that we need to send a new
2069          * ticket. */
2070         return 2;
2071         }
2072
2073 /* Tables to translate from NIDs to TLS v1.2 ids */
2074
2075 typedef struct 
2076         {
2077         int nid;
2078         int id;
2079         } tls12_lookup;
2080
2081 static tls12_lookup tls12_md[] = {
2082 #ifndef OPENSSL_NO_MD5
2083         {NID_md5, TLSEXT_hash_md5},
2084 #endif
2085 #ifndef OPENSSL_NO_SHA
2086         {NID_sha1, TLSEXT_hash_sha1},
2087 #endif
2088 #ifndef OPENSSL_NO_SHA256
2089         {NID_sha224, TLSEXT_hash_sha224},
2090         {NID_sha256, TLSEXT_hash_sha256},
2091 #endif
2092 #ifndef OPENSSL_NO_SHA512
2093         {NID_sha384, TLSEXT_hash_sha384},
2094         {NID_sha512, TLSEXT_hash_sha512}
2095 #endif
2096 };
2097
2098 static tls12_lookup tls12_sig[] = {
2099 #ifndef OPENSSL_NO_RSA
2100         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
2101 #endif
2102 #ifndef OPENSSL_NO_RSA
2103         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
2104 #endif
2105 #ifndef OPENSSL_NO_ECDSA
2106         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
2107 #endif
2108 };
2109
2110 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
2111         {
2112         size_t i;
2113         for (i = 0; i < tlen; i++)
2114                 {
2115                 if (table[i].nid == nid)
2116                         return table[i].id;
2117                 }
2118         return -1;
2119         }
2120 #if 0
2121 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
2122         {
2123         size_t i;
2124         for (i = 0; i < tlen; i++)
2125                 {
2126                 if (table[i].id == id)
2127                         return table[i].nid;
2128                 }
2129         return -1;
2130         }
2131 #endif
2132
2133 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
2134         {
2135         int sig_id, md_id;
2136         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
2137                                 sizeof(tls12_md)/sizeof(tls12_lookup));
2138         if (md_id == -1)
2139                 return 0;
2140         sig_id = tls12_get_sigid(pk);
2141         if (sig_id == -1)
2142                 return 0;
2143         p[0] = (unsigned char)md_id;
2144         p[1] = (unsigned char)sig_id;
2145         return 1;
2146         }
2147
2148 int tls12_get_sigid(const EVP_PKEY *pk)
2149         {
2150         return tls12_find_id(pk->type, tls12_sig,
2151                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
2152         }
2153
2154 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
2155         {
2156         switch(hash_alg)
2157                 {
2158 #ifndef OPENSSL_NO_MD5
2159                 case TLSEXT_hash_md5:
2160 #ifdef OPENSSL_FIPS
2161                 if (FIPS_mode())
2162                         return NULL;
2163 #endif
2164                 return EVP_md5();
2165 #endif
2166 #ifndef OPENSSL_NO_SHA
2167                 case TLSEXT_hash_sha1:
2168                 return EVP_sha1();
2169 #endif
2170 #ifndef OPENSSL_NO_SHA256
2171                 case TLSEXT_hash_sha224:
2172                 return EVP_sha224();
2173
2174                 case TLSEXT_hash_sha256:
2175                 return EVP_sha256();
2176 #endif
2177 #ifndef OPENSSL_NO_SHA512
2178                 case TLSEXT_hash_sha384:
2179                 return EVP_sha384();
2180
2181                 case TLSEXT_hash_sha512:
2182                 return EVP_sha512();
2183 #endif
2184                 default:
2185                 return NULL;
2186
2187                 }
2188         }
2189
2190 /* Set preferred digest for each key type */
2191
2192 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
2193         {
2194         int i, idx;
2195         const EVP_MD *md;
2196         CERT *c = s->cert;
2197         /* Extension ignored for TLS versions below 1.2 */
2198         if (TLS1_get_version(s) < TLS1_2_VERSION)
2199                 return 1;
2200         /* Should never happen */
2201         if (!c)
2202                 return 0;
2203
2204         c->pkeys[SSL_PKEY_DSA_SIGN].digest = NULL;
2205         c->pkeys[SSL_PKEY_RSA_SIGN].digest = NULL;
2206         c->pkeys[SSL_PKEY_RSA_ENC].digest = NULL;
2207         c->pkeys[SSL_PKEY_ECC].digest = NULL;
2208
2209         for (i = 0; i < dsize; i += 2)
2210                 {
2211                 unsigned char hash_alg = data[i], sig_alg = data[i+1];
2212
2213                 switch(sig_alg)
2214                         {
2215 #ifndef OPENSSL_NO_RSA
2216                         case TLSEXT_signature_rsa:
2217                         idx = SSL_PKEY_RSA_SIGN;
2218                         break;
2219 #endif
2220 #ifndef OPENSSL_NO_DSA
2221                         case TLSEXT_signature_dsa:
2222                         idx = SSL_PKEY_DSA_SIGN;
2223                         break;
2224 #endif
2225 #ifndef OPENSSL_NO_ECDSA
2226                         case TLSEXT_signature_ecdsa:
2227                         idx = SSL_PKEY_ECC;
2228                         break;
2229 #endif
2230                         default:
2231                         continue;
2232                         }
2233
2234                 if (c->pkeys[idx].digest == NULL)
2235                         {
2236                         md = tls12_get_hash(hash_alg);
2237                         if (md)
2238                                 {
2239                                 c->pkeys[idx].digest = md;
2240                                 if (idx == SSL_PKEY_RSA_SIGN)
2241                                         c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
2242                                 }
2243                         }
2244
2245                 }
2246
2247
2248         /* Set any remaining keys to default values. NOTE: if alg is not
2249          * supported it stays as NULL.
2250          */
2251 #ifndef OPENSSL_NO_DSA
2252         if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
2253                 c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_dss1();
2254 #endif
2255 #ifndef OPENSSL_NO_RSA
2256         if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
2257                 {
2258                 c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
2259                 c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
2260                 }
2261 #endif
2262 #ifndef OPENSSL_NO_ECDSA
2263         if (!c->pkeys[SSL_PKEY_ECC].digest)
2264                 c->pkeys[SSL_PKEY_ECC].digest = EVP_ecdsa();
2265 #endif
2266         return 1;
2267         }
2268
2269 #endif