33afdeba33e5def24274e8d0ca39c5e18809bfc6
[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 <openssl/rand.h>
118 #include "ssl_locl.h"
119
120 const char tls1_version_str[]="TLSv1" OPENSSL_VERSION_PTEXT;
121
122 #ifndef OPENSSL_NO_TLSEXT
123 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
124                                 const unsigned char *sess_id, int sesslen,
125                                 SSL_SESSION **psess);
126 #endif
127
128 SSL3_ENC_METHOD TLSv1_enc_data={
129         tls1_enc,
130         tls1_mac,
131         tls1_setup_key_block,
132         tls1_generate_master_secret,
133         tls1_change_cipher_state,
134         tls1_final_finish_mac,
135         TLS1_FINISH_MAC_LENGTH,
136         tls1_cert_verify_mac,
137         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
138         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
139         tls1_alert_code,
140         tls1_export_keying_material,
141         };
142
143 long tls1_default_timeout(void)
144         {
145         /* 2 hours, the 24 hours mentioned in the TLSv1 spec
146          * is way too long for http, the cache would over fill */
147         return(60*60*2);
148         }
149
150 int tls1_new(SSL *s)
151         {
152         if (!ssl3_new(s)) return(0);
153         s->method->ssl_clear(s);
154         return(1);
155         }
156
157 void tls1_free(SSL *s)
158         {
159 #ifndef OPENSSL_NO_TLSEXT
160         if (s->tlsext_session_ticket)
161                 {
162                 OPENSSL_free(s->tlsext_session_ticket);
163                 }
164 #endif /* OPENSSL_NO_TLSEXT */
165         ssl3_free(s);
166         }
167
168 void tls1_clear(SSL *s)
169         {
170         ssl3_clear(s);
171         s->version = s->method->version;
172         }
173
174 #ifndef OPENSSL_NO_EC
175
176 static int nid_list[] =
177         {
178                 NID_sect163k1, /* sect163k1 (1) */
179                 NID_sect163r1, /* sect163r1 (2) */
180                 NID_sect163r2, /* sect163r2 (3) */
181                 NID_sect193r1, /* sect193r1 (4) */ 
182                 NID_sect193r2, /* sect193r2 (5) */ 
183                 NID_sect233k1, /* sect233k1 (6) */
184                 NID_sect233r1, /* sect233r1 (7) */ 
185                 NID_sect239k1, /* sect239k1 (8) */ 
186                 NID_sect283k1, /* sect283k1 (9) */
187                 NID_sect283r1, /* sect283r1 (10) */ 
188                 NID_sect409k1, /* sect409k1 (11) */ 
189                 NID_sect409r1, /* sect409r1 (12) */
190                 NID_sect571k1, /* sect571k1 (13) */ 
191                 NID_sect571r1, /* sect571r1 (14) */ 
192                 NID_secp160k1, /* secp160k1 (15) */
193                 NID_secp160r1, /* secp160r1 (16) */ 
194                 NID_secp160r2, /* secp160r2 (17) */ 
195                 NID_secp192k1, /* secp192k1 (18) */
196                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
197                 NID_secp224k1, /* secp224k1 (20) */ 
198                 NID_secp224r1, /* secp224r1 (21) */
199                 NID_secp256k1, /* secp256k1 (22) */ 
200                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
201                 NID_secp384r1, /* secp384r1 (24) */
202                 NID_secp521r1  /* secp521r1 (25) */     
203         };
204
205 static int pref_list[] =
206         {
207                 NID_sect571r1, /* sect571r1 (14) */ 
208                 NID_sect571k1, /* sect571k1 (13) */ 
209                 NID_secp521r1, /* secp521r1 (25) */     
210                 NID_sect409k1, /* sect409k1 (11) */ 
211                 NID_sect409r1, /* sect409r1 (12) */
212                 NID_secp384r1, /* secp384r1 (24) */
213                 NID_sect283k1, /* sect283k1 (9) */
214                 NID_sect283r1, /* sect283r1 (10) */ 
215                 NID_secp256k1, /* secp256k1 (22) */ 
216                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
217                 NID_sect239k1, /* sect239k1 (8) */ 
218                 NID_sect233k1, /* sect233k1 (6) */
219                 NID_sect233r1, /* sect233r1 (7) */ 
220                 NID_secp224k1, /* secp224k1 (20) */ 
221                 NID_secp224r1, /* secp224r1 (21) */
222                 NID_sect193r1, /* sect193r1 (4) */ 
223                 NID_sect193r2, /* sect193r2 (5) */ 
224                 NID_secp192k1, /* secp192k1 (18) */
225                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
226                 NID_sect163k1, /* sect163k1 (1) */
227                 NID_sect163r1, /* sect163r1 (2) */
228                 NID_sect163r2, /* sect163r2 (3) */
229                 NID_secp160k1, /* secp160k1 (15) */
230                 NID_secp160r1, /* secp160r1 (16) */ 
231                 NID_secp160r2, /* secp160r2 (17) */ 
232         };
233
234 int tls1_ec_curve_id2nid(int curve_id)
235         {
236         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
237         if ((curve_id < 1) || ((unsigned int)curve_id >
238                                 sizeof(nid_list)/sizeof(nid_list[0])))
239                 return 0;
240         return nid_list[curve_id-1];
241         }
242
243 int tls1_ec_nid2curve_id(int nid)
244         {
245         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
246         switch (nid)
247                 {
248         case NID_sect163k1: /* sect163k1 (1) */
249                 return 1;
250         case NID_sect163r1: /* sect163r1 (2) */
251                 return 2;
252         case NID_sect163r2: /* sect163r2 (3) */
253                 return 3;
254         case NID_sect193r1: /* sect193r1 (4) */ 
255                 return 4;
256         case NID_sect193r2: /* sect193r2 (5) */ 
257                 return 5;
258         case NID_sect233k1: /* sect233k1 (6) */
259                 return 6;
260         case NID_sect233r1: /* sect233r1 (7) */ 
261                 return 7;
262         case NID_sect239k1: /* sect239k1 (8) */ 
263                 return 8;
264         case NID_sect283k1: /* sect283k1 (9) */
265                 return 9;
266         case NID_sect283r1: /* sect283r1 (10) */ 
267                 return 10;
268         case NID_sect409k1: /* sect409k1 (11) */ 
269                 return 11;
270         case NID_sect409r1: /* sect409r1 (12) */
271                 return 12;
272         case NID_sect571k1: /* sect571k1 (13) */ 
273                 return 13;
274         case NID_sect571r1: /* sect571r1 (14) */ 
275                 return 14;
276         case NID_secp160k1: /* secp160k1 (15) */
277                 return 15;
278         case NID_secp160r1: /* secp160r1 (16) */ 
279                 return 16;
280         case NID_secp160r2: /* secp160r2 (17) */ 
281                 return 17;
282         case NID_secp192k1: /* secp192k1 (18) */
283                 return 18;
284         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
285                 return 19;
286         case NID_secp224k1: /* secp224k1 (20) */ 
287                 return 20;
288         case NID_secp224r1: /* secp224r1 (21) */
289                 return 21;
290         case NID_secp256k1: /* secp256k1 (22) */ 
291                 return 22;
292         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
293                 return 23;
294         case NID_secp384r1: /* secp384r1 (24) */
295                 return 24;
296         case NID_secp521r1:  /* secp521r1 (25) */       
297                 return 25;
298         default:
299                 return 0;
300                 }
301         }
302 #endif /* OPENSSL_NO_EC */
303
304 #ifndef OPENSSL_NO_TLSEXT
305
306 /* List of supported signature algorithms and hashes. Should make this
307  * customisable at some point, for now include everything we support.
308  */
309
310 #ifdef OPENSSL_NO_RSA
311 #define tlsext_sigalg_rsa(md) /* */
312 #else
313 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
314 #endif
315
316 #ifdef OPENSSL_NO_DSA
317 #define tlsext_sigalg_dsa(md) /* */
318 #else
319 #define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
320 #endif
321
322 #ifdef OPENSSL_NO_ECDSA
323 #define tlsext_sigalg_ecdsa(md) /* */
324 #else
325 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
326 #endif
327
328 #define tlsext_sigalg(md) \
329                 tlsext_sigalg_rsa(md) \
330                 tlsext_sigalg_dsa(md) \
331                 tlsext_sigalg_ecdsa(md)
332
333 static unsigned char tls12_sigalgs[] = {
334 #ifndef OPENSSL_NO_SHA512
335         tlsext_sigalg(TLSEXT_hash_sha512)
336         tlsext_sigalg(TLSEXT_hash_sha384)
337 #endif
338 #ifndef OPENSSL_NO_SHA256
339         tlsext_sigalg(TLSEXT_hash_sha256)
340         tlsext_sigalg(TLSEXT_hash_sha224)
341 #endif
342 #ifndef OPENSSL_NO_SHA
343         tlsext_sigalg(TLSEXT_hash_sha1)
344 #endif
345 };
346
347 int tls12_get_req_sig_algs(SSL *s, unsigned char *p)
348         {
349         size_t slen = sizeof(tls12_sigalgs);
350         if (p)
351                 memcpy(p, tls12_sigalgs, slen);
352         return (int)slen;
353         }
354
355 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
356         {
357         int extdatalen=0;
358         unsigned char *ret = p;
359
360         /* don't add extensions for SSLv3 unless doing secure renegotiation */
361         if (s->client_version == SSL3_VERSION
362                                         && !s->s3->send_connection_binding)
363                 return p;
364
365         ret+=2;
366
367         if (ret>=limit) return NULL; /* this really never occurs, but ... */
368
369         if (s->tlsext_hostname != NULL)
370                 { 
371                 /* Add TLS extension servername to the Client Hello message */
372                 unsigned long size_str;
373                 long lenmax; 
374
375                 /* check for enough space.
376                    4 for the servername type and entension length
377                    2 for servernamelist length
378                    1 for the hostname type
379                    2 for hostname length
380                    + hostname length 
381                 */
382                    
383                 if ((lenmax = limit - ret - 9) < 0 
384                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
385                         return NULL;
386                         
387                 /* extension type and length */
388                 s2n(TLSEXT_TYPE_server_name,ret); 
389                 s2n(size_str+5,ret);
390                 
391                 /* length of servername list */
392                 s2n(size_str+3,ret);
393         
394                 /* hostname type, length and hostname */
395                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
396                 s2n(size_str,ret);
397                 memcpy(ret, s->tlsext_hostname, size_str);
398                 ret+=size_str;
399                 }
400
401         /* Add RI if renegotiating */
402         if (s->renegotiate)
403           {
404           int el;
405           
406           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
407               {
408               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
409               return NULL;
410               }
411
412           if((limit - p - 4 - el) < 0) return NULL;
413           
414           s2n(TLSEXT_TYPE_renegotiate,ret);
415           s2n(el,ret);
416
417           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
418               {
419               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
420               return NULL;
421               }
422
423           ret += el;
424         }
425
426 #ifndef OPENSSL_NO_SRP
427         /* Add SRP username if there is one */
428         if (s->srp_ctx.login != NULL)
429                 { /* Add TLS extension SRP username to the Client Hello message */
430
431                 int login_len = strlen(s->srp_ctx.login);       
432                 if (login_len > 255 || login_len == 0)
433                         {
434                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
435                         return NULL;
436                         } 
437
438                 /* check for enough space.
439                    4 for the srp type type and entension length
440                    1 for the srp user identity
441                    + srp user identity length 
442                 */
443                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
444
445                 /* fill in the extension */
446                 s2n(TLSEXT_TYPE_srp,ret);
447                 s2n(login_len+1,ret);
448                 (*ret++) = (unsigned char) login_len;
449                 memcpy(ret, s->srp_ctx.login, login_len);
450                 ret+=login_len;
451                 }
452 #endif
453
454 #ifndef OPENSSL_NO_EC
455         if (s->tlsext_ecpointformatlist != NULL &&
456             s->version != DTLS1_VERSION)
457                 {
458                 /* Add TLS extension ECPointFormats to the ClientHello message */
459                 long lenmax; 
460
461                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
462                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
463                 if (s->tlsext_ecpointformatlist_length > 255)
464                         {
465                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
466                         return NULL;
467                         }
468                 
469                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
470                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
471                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
472                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
473                 ret+=s->tlsext_ecpointformatlist_length;
474                 }
475         if (s->tlsext_ellipticcurvelist != NULL &&
476             s->version != DTLS1_VERSION)
477                 {
478                 /* Add TLS extension EllipticCurves to the ClientHello message */
479                 long lenmax; 
480
481                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
482                 if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL;
483                 if (s->tlsext_ellipticcurvelist_length > 65532)
484                         {
485                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
486                         return NULL;
487                         }
488                 
489                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
490                 s2n(s->tlsext_ellipticcurvelist_length + 2, ret);
491
492                 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
493                  * elliptic_curve_list, but the examples use two bytes.
494                  * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
495                  * resolves this to two bytes.
496                  */
497                 s2n(s->tlsext_ellipticcurvelist_length, ret);
498                 memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length);
499                 ret+=s->tlsext_ellipticcurvelist_length;
500                 }
501 #endif /* OPENSSL_NO_EC */
502
503         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
504                 {
505                 int ticklen;
506                 if (!s->new_session && s->session && s->session->tlsext_tick)
507                         ticklen = s->session->tlsext_ticklen;
508                 else if (s->session && s->tlsext_session_ticket &&
509                          s->tlsext_session_ticket->data)
510                         {
511                         ticklen = s->tlsext_session_ticket->length;
512                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
513                         if (!s->session->tlsext_tick)
514                                 return NULL;
515                         memcpy(s->session->tlsext_tick,
516                                s->tlsext_session_ticket->data,
517                                ticklen);
518                         s->session->tlsext_ticklen = ticklen;
519                         }
520                 else
521                         ticklen = 0;
522                 if (ticklen == 0 && s->tlsext_session_ticket &&
523                     s->tlsext_session_ticket->data == NULL)
524                         goto skip_ext;
525                 /* Check for enough room 2 for extension type, 2 for len
526                  * rest for ticket
527                  */
528                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
529                 s2n(TLSEXT_TYPE_session_ticket,ret); 
530                 s2n(ticklen,ret);
531                 if (ticklen)
532                         {
533                         memcpy(ret, s->session->tlsext_tick, ticklen);
534                         ret += ticklen;
535                         }
536                 }
537                 skip_ext:
538
539         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
540                 {
541                 if ((size_t)(limit - ret) < sizeof(tls12_sigalgs) + 6)
542                         return NULL; 
543                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
544                 s2n(sizeof(tls12_sigalgs) + 2, ret);
545                 s2n(sizeof(tls12_sigalgs), ret);
546                 memcpy(ret, tls12_sigalgs, sizeof(tls12_sigalgs));
547                 ret += sizeof(tls12_sigalgs);
548                 }
549
550 #ifdef TLSEXT_TYPE_opaque_prf_input
551         if (s->s3->client_opaque_prf_input != NULL &&
552             s->version != DTLS1_VERSION)
553                 {
554                 size_t col = s->s3->client_opaque_prf_input_len;
555                 
556                 if ((long)(limit - ret - 6 - col < 0))
557                         return NULL;
558                 if (col > 0xFFFD) /* can't happen */
559                         return NULL;
560
561                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
562                 s2n(col + 2, ret);
563                 s2n(col, ret);
564                 memcpy(ret, s->s3->client_opaque_prf_input, col);
565                 ret += col;
566                 }
567 #endif
568
569         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
570             s->version != DTLS1_VERSION)
571                 {
572                 int i;
573                 long extlen, idlen, itmp;
574                 OCSP_RESPID *id;
575
576                 idlen = 0;
577                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
578                         {
579                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
580                         itmp = i2d_OCSP_RESPID(id, NULL);
581                         if (itmp <= 0)
582                                 return NULL;
583                         idlen += itmp + 2;
584                         }
585
586                 if (s->tlsext_ocsp_exts)
587                         {
588                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
589                         if (extlen < 0)
590                                 return NULL;
591                         }
592                 else
593                         extlen = 0;
594                         
595                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
596                 s2n(TLSEXT_TYPE_status_request, ret);
597                 if (extlen + idlen > 0xFFF0)
598                         return NULL;
599                 s2n(extlen + idlen + 5, ret);
600                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
601                 s2n(idlen, ret);
602                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
603                         {
604                         /* save position of id len */
605                         unsigned char *q = ret;
606                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
607                         /* skip over id len */
608                         ret += 2;
609                         itmp = i2d_OCSP_RESPID(id, &ret);
610                         /* write id len */
611                         s2n(itmp, q);
612                         }
613                 s2n(extlen, ret);
614                 if (extlen > 0)
615                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
616                 }
617
618 #ifndef OPENSSL_NO_HEARTBEATS
619         /* Add Heartbeat extension */
620         s2n(TLSEXT_TYPE_heartbeat,ret);
621         s2n(1,ret);
622         /* Set mode:
623          * 1: peer may send requests
624          * 2: peer not allowed to send requests
625          */
626         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
627                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
628         else
629                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
630 #endif
631
632 #ifndef OPENSSL_NO_NEXTPROTONEG
633         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
634                 {
635                 /* The client advertises an emtpy extension to indicate its
636                  * support for Next Protocol Negotiation */
637                 if (limit - ret - 4 < 0)
638                         return NULL;
639                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
640                 s2n(0,ret);
641                 }
642 #endif
643
644 #ifndef OPENSSL_NO_SRTP
645         if(SSL_get_srtp_profiles(s))
646                 {
647                 int el;
648
649                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
650                 
651                 if((limit - p - 4 - el) < 0) return NULL;
652
653                 s2n(TLSEXT_TYPE_use_srtp,ret);
654                 s2n(el,ret);
655
656                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
657                         {
658                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
659                         return NULL;
660                         }
661                 ret += el;
662                 }
663 #endif
664
665         if ((extdatalen = ret-p-2)== 0) 
666                 return p;
667
668         s2n(extdatalen,p);
669         return ret;
670         }
671
672 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
673         {
674         int extdatalen=0;
675         unsigned char *ret = p;
676 #ifndef OPENSSL_NO_NEXTPROTONEG
677         int next_proto_neg_seen;
678 #endif
679
680         /* don't add extensions for SSLv3, unless doing secure renegotiation */
681         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
682                 return p;
683         
684         ret+=2;
685         if (ret>=limit) return NULL; /* this really never occurs, but ... */
686
687         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
688                 { 
689                 if ((long)(limit - ret - 4) < 0) return NULL; 
690
691                 s2n(TLSEXT_TYPE_server_name,ret);
692                 s2n(0,ret);
693                 }
694
695         if(s->s3->send_connection_binding)
696         {
697           int el;
698           
699           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
700               {
701               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
702               return NULL;
703               }
704
705           if((limit - p - 4 - el) < 0) return NULL;
706           
707           s2n(TLSEXT_TYPE_renegotiate,ret);
708           s2n(el,ret);
709
710           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
711               {
712               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
713               return NULL;
714               }
715
716           ret += el;
717         }
718
719 #ifndef OPENSSL_NO_EC
720         if (s->tlsext_ecpointformatlist != NULL &&
721             s->version != DTLS1_VERSION)
722                 {
723                 /* Add TLS extension ECPointFormats to the ServerHello message */
724                 long lenmax; 
725
726                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
727                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
728                 if (s->tlsext_ecpointformatlist_length > 255)
729                         {
730                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
731                         return NULL;
732                         }
733                 
734                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
735                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
736                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
737                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
738                 ret+=s->tlsext_ecpointformatlist_length;
739
740                 }
741         /* Currently the server should not respond with a SupportedCurves extension */
742 #endif /* OPENSSL_NO_EC */
743
744         if (s->tlsext_ticket_expected
745                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
746                 { 
747                 if ((long)(limit - ret - 4) < 0) return NULL; 
748                 s2n(TLSEXT_TYPE_session_ticket,ret);
749                 s2n(0,ret);
750                 }
751
752         if (s->tlsext_status_expected)
753                 { 
754                 if ((long)(limit - ret - 4) < 0) return NULL; 
755                 s2n(TLSEXT_TYPE_status_request,ret);
756                 s2n(0,ret);
757                 }
758
759 #ifdef TLSEXT_TYPE_opaque_prf_input
760         if (s->s3->server_opaque_prf_input != NULL &&
761             s->version != DTLS1_VERSION)
762                 {
763                 size_t sol = s->s3->server_opaque_prf_input_len;
764                 
765                 if ((long)(limit - ret - 6 - sol) < 0)
766                         return NULL;
767                 if (sol > 0xFFFD) /* can't happen */
768                         return NULL;
769
770                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
771                 s2n(sol + 2, ret);
772                 s2n(sol, ret);
773                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
774                 ret += sol;
775                 }
776 #endif
777
778 #ifndef OPENSSL_NO_SRTP
779         if(s->srtp_profile)
780                 {
781                 int el;
782
783                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
784                 
785                 if((limit - p - 4 - el) < 0) return NULL;
786
787                 s2n(TLSEXT_TYPE_use_srtp,ret);
788                 s2n(el,ret);
789
790                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
791                         {
792                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
793                         return NULL;
794                         }
795                 ret+=el;
796                 }
797 #endif
798
799         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
800                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
801                 { const unsigned char cryptopro_ext[36] = {
802                         0xfd, 0xe8, /*65000*/
803                         0x00, 0x20, /*32 bytes length*/
804                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
805                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
806                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
807                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
808                         if (limit-ret<36) return NULL;
809                         memcpy(ret,cryptopro_ext,36);
810                         ret+=36;
811
812                 }
813
814 #ifndef OPENSSL_NO_HEARTBEATS
815         /* Add Heartbeat extension if we've received one */
816         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
817                 {
818                 s2n(TLSEXT_TYPE_heartbeat,ret);
819                 s2n(1,ret);
820                 /* Set mode:
821                  * 1: peer may send requests
822                  * 2: peer not allowed to send requests
823                  */
824                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
825                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
826                 else
827                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
828
829                 }
830 #endif
831
832 #ifndef OPENSSL_NO_NEXTPROTONEG
833         next_proto_neg_seen = s->s3->next_proto_neg_seen;
834         s->s3->next_proto_neg_seen = 0;
835         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
836                 {
837                 const unsigned char *npa;
838                 unsigned int npalen;
839                 int r;
840
841                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
842                 if (r == SSL_TLSEXT_ERR_OK)
843                         {
844                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
845                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
846                         s2n(npalen,ret);
847                         memcpy(ret, npa, npalen);
848                         ret += npalen;
849                         s->s3->next_proto_neg_seen = 1;
850                         }
851                 }
852 #endif
853
854         if ((extdatalen = ret-p-2)== 0) 
855                 return p;
856
857         s2n(extdatalen,p);
858         return ret;
859         }
860
861 #ifndef OPENSSL_NO_EC
862 /* ssl_check_for_safari attempts to fingerprint Safari using OS X
863  * SecureTransport using the TLS extension block in |d|, of length |n|.
864  * Safari, since 10.6, sends exactly these extensions, in this order:
865  *   SNI,
866  *   elliptic_curves
867  *   ec_point_formats
868  *
869  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
870  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
871  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
872  * 10.8..10.8.3 (which don't work).
873  */
874 static void ssl_check_for_safari(SSL *s, const unsigned char *data, const unsigned char *d, int n) {
875         unsigned short type, size;
876         static const unsigned char kSafariExtensionsBlock[] = {
877                 0x00, 0x0a,  /* elliptic_curves extension */
878                 0x00, 0x08,  /* 8 bytes */
879                 0x00, 0x06,  /* 6 bytes of curve ids */
880                 0x00, 0x17,  /* P-256 */
881                 0x00, 0x18,  /* P-384 */
882                 0x00, 0x19,  /* P-521 */
883
884                 0x00, 0x0b,  /* ec_point_formats */
885                 0x00, 0x02,  /* 2 bytes */
886                 0x01,        /* 1 point format */
887                 0x00,        /* uncompressed */
888         };
889
890         /* The following is only present in TLS 1.2 */
891         static const unsigned char kSafariTLS12ExtensionsBlock[] = {
892                 0x00, 0x0d,  /* signature_algorithms */
893                 0x00, 0x0c,  /* 12 bytes */
894                 0x00, 0x0a,  /* 10 bytes */
895                 0x05, 0x01,  /* SHA-384/RSA */
896                 0x04, 0x01,  /* SHA-256/RSA */
897                 0x02, 0x01,  /* SHA-1/RSA */
898                 0x04, 0x03,  /* SHA-256/ECDSA */
899                 0x02, 0x03,  /* SHA-1/ECDSA */
900         };
901
902         if (data >= (d+n-2))
903                 return;
904         data += 2;
905
906         if (data > (d+n-4))
907                 return;
908         n2s(data,type);
909         n2s(data,size);
910
911         if (type != TLSEXT_TYPE_server_name)
912                 return;
913
914         if (data+size > d+n)
915                 return;
916         data += size;
917
918         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
919                 {
920                 const size_t len1 = sizeof(kSafariExtensionsBlock);
921                 const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
922
923                 if (data + len1 + len2 != d+n)
924                         return;
925                 if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
926                         return;
927                 if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
928                         return;
929                 }
930         else
931                 {
932                 const size_t len = sizeof(kSafariExtensionsBlock);
933
934                 if (data + len != d+n)
935                         return;
936                 if (memcmp(data, kSafariExtensionsBlock, len) != 0)
937                         return;
938                 }
939
940         s->s3->is_probably_safari = 1;
941 }
942 #endif /* !OPENSSL_NO_EC */
943
944 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
945         {
946         unsigned short type;
947         unsigned short size;
948         unsigned short len;
949         unsigned char *data = *p;
950         int renegotiate_seen = 0;
951         int sigalg_seen = 0;
952
953         s->servername_done = 0;
954         s->tlsext_status_type = -1;
955 #ifndef OPENSSL_NO_NEXTPROTONEG
956         s->s3->next_proto_neg_seen = 0;
957 #endif
958
959 #ifndef OPENSSL_NO_HEARTBEATS
960         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
961                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
962 #endif
963
964 #ifndef OPENSSL_NO_EC
965         if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
966                 ssl_check_for_safari(s, data, d, n);
967 #endif /* !OPENSSL_NO_EC */
968
969         if (data >= (d+n-2))
970                 goto ri_check;
971         n2s(data,len);
972
973         if (data > (d+n-len)) 
974                 goto ri_check;
975
976         while (data <= (d+n-4))
977                 {
978                 n2s(data,type);
979                 n2s(data,size);
980
981                 if (data+size > (d+n))
982                         goto ri_check;
983 #if 0
984                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
985 #endif
986                 if (s->tlsext_debug_cb)
987                         s->tlsext_debug_cb(s, 0, type, data, size,
988                                                 s->tlsext_debug_arg);
989 /* The servername extension is treated as follows:
990
991    - Only the hostname type is supported with a maximum length of 255.
992    - The servername is rejected if too long or if it contains zeros,
993      in which case an fatal alert is generated.
994    - The servername field is maintained together with the session cache.
995    - When a session is resumed, the servername call back invoked in order
996      to allow the application to position itself to the right context. 
997    - The servername is acknowledged if it is new for a session or when 
998      it is identical to a previously used for the same session. 
999      Applications can control the behaviour.  They can at any time
1000      set a 'desirable' servername for a new SSL object. This can be the
1001      case for example with HTTPS when a Host: header field is received and
1002      a renegotiation is requested. In this case, a possible servername
1003      presented in the new client hello is only acknowledged if it matches
1004      the value of the Host: field. 
1005    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1006      if they provide for changing an explicit servername context for the session,
1007      i.e. when the session has been established with a servername extension. 
1008    - On session reconnect, the servername extension may be absent. 
1009
1010 */      
1011
1012                 if (type == TLSEXT_TYPE_server_name)
1013                         {
1014                         unsigned char *sdata;
1015                         int servname_type;
1016                         int dsize; 
1017                 
1018                         if (size < 2) 
1019                                 {
1020                                 *al = SSL_AD_DECODE_ERROR;
1021                                 return 0;
1022                                 }
1023                         n2s(data,dsize);  
1024                         size -= 2;
1025                         if (dsize > size  ) 
1026                                 {
1027                                 *al = SSL_AD_DECODE_ERROR;
1028                                 return 0;
1029                                 } 
1030
1031                         sdata = data;
1032                         while (dsize > 3) 
1033                                 {
1034                                 servname_type = *(sdata++); 
1035                                 n2s(sdata,len);
1036                                 dsize -= 3;
1037
1038                                 if (len > dsize) 
1039                                         {
1040                                         *al = SSL_AD_DECODE_ERROR;
1041                                         return 0;
1042                                         }
1043                                 if (s->servername_done == 0)
1044                                 switch (servname_type)
1045                                         {
1046                                 case TLSEXT_NAMETYPE_host_name:
1047                                         if (!s->hit)
1048                                                 {
1049                                                 if(s->session->tlsext_hostname)
1050                                                         {
1051                                                         *al = SSL_AD_DECODE_ERROR;
1052                                                         return 0;
1053                                                         }
1054                                                 if (len > TLSEXT_MAXLEN_host_name)
1055                                                         {
1056                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1057                                                         return 0;
1058                                                         }
1059                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
1060                                                         {
1061                                                         *al = TLS1_AD_INTERNAL_ERROR;
1062                                                         return 0;
1063                                                         }
1064                                                 memcpy(s->session->tlsext_hostname, sdata, len);
1065                                                 s->session->tlsext_hostname[len]='\0';
1066                                                 if (strlen(s->session->tlsext_hostname) != len) {
1067                                                         OPENSSL_free(s->session->tlsext_hostname);
1068                                                         s->session->tlsext_hostname = NULL;
1069                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1070                                                         return 0;
1071                                                 }
1072                                                 s->servername_done = 1; 
1073
1074                                                 }
1075                                         else 
1076                                                 s->servername_done = s->session->tlsext_hostname
1077                                                         && strlen(s->session->tlsext_hostname) == len 
1078                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
1079                                         
1080                                         break;
1081
1082                                 default:
1083                                         break;
1084                                         }
1085                                  
1086                                 dsize -= len;
1087                                 }
1088                         if (dsize != 0) 
1089                                 {
1090                                 *al = SSL_AD_DECODE_ERROR;
1091                                 return 0;
1092                                 }
1093
1094                         }
1095 #ifndef OPENSSL_NO_SRP
1096                 else if (type == TLSEXT_TYPE_srp)
1097                         {
1098                         if (size <= 0 || ((len = data[0])) != (size -1))
1099                                 {
1100                                 *al = SSL_AD_DECODE_ERROR;
1101                                 return 0;
1102                                 }
1103                         if (s->srp_ctx.login != NULL)
1104                                 {
1105                                 *al = SSL_AD_DECODE_ERROR;
1106                                 return 0;
1107                                 }
1108                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
1109                                 return -1;
1110                         memcpy(s->srp_ctx.login, &data[1], len);
1111                         s->srp_ctx.login[len]='\0';
1112   
1113                         if (strlen(s->srp_ctx.login) != len) 
1114                                 {
1115                                 *al = SSL_AD_DECODE_ERROR;
1116                                 return 0;
1117                                 }
1118                         }
1119 #endif
1120
1121 #ifndef OPENSSL_NO_EC
1122                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1123                      s->version != DTLS1_VERSION)
1124                         {
1125                         unsigned char *sdata = data;
1126                         int ecpointformatlist_length = *(sdata++);
1127
1128                         if (ecpointformatlist_length != size - 1)
1129                                 {
1130                                 *al = TLS1_AD_DECODE_ERROR;
1131                                 return 0;
1132                                 }
1133                         if (!s->hit)
1134                                 {
1135                                 if(s->session->tlsext_ecpointformatlist)
1136                                         {
1137                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
1138                                         s->session->tlsext_ecpointformatlist = NULL;
1139                                         }
1140                                 s->session->tlsext_ecpointformatlist_length = 0;
1141                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1142                                         {
1143                                         *al = TLS1_AD_INTERNAL_ERROR;
1144                                         return 0;
1145                                         }
1146                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1147                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1148                                 }
1149 #if 0
1150                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
1151                         sdata = s->session->tlsext_ecpointformatlist;
1152                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1153                                 fprintf(stderr,"%i ",*(sdata++));
1154                         fprintf(stderr,"\n");
1155 #endif
1156                         }
1157                 else if (type == TLSEXT_TYPE_elliptic_curves &&
1158                      s->version != DTLS1_VERSION)
1159                         {
1160                         unsigned char *sdata = data;
1161                         int ellipticcurvelist_length = (*(sdata++) << 8);
1162                         ellipticcurvelist_length += (*(sdata++));
1163
1164                         if (ellipticcurvelist_length != size - 2 ||
1165                                 ellipticcurvelist_length < 1)
1166                                 {
1167                                 *al = TLS1_AD_DECODE_ERROR;
1168                                 return 0;
1169                                 }
1170                         if (!s->hit)
1171                                 {
1172                                 if(s->session->tlsext_ellipticcurvelist)
1173                                         {
1174                                         *al = TLS1_AD_DECODE_ERROR;
1175                                         return 0;
1176                                         }
1177                                 s->session->tlsext_ellipticcurvelist_length = 0;
1178                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
1179                                         {
1180                                         *al = TLS1_AD_INTERNAL_ERROR;
1181                                         return 0;
1182                                         }
1183                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
1184                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
1185                                 }
1186 #if 0
1187                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
1188                         sdata = s->session->tlsext_ellipticcurvelist;
1189                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
1190                                 fprintf(stderr,"%i ",*(sdata++));
1191                         fprintf(stderr,"\n");
1192 #endif
1193                         }
1194 #endif /* OPENSSL_NO_EC */
1195 #ifdef TLSEXT_TYPE_opaque_prf_input
1196                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1197                      s->version != DTLS1_VERSION)
1198                         {
1199                         unsigned char *sdata = data;
1200
1201                         if (size < 2)
1202                                 {
1203                                 *al = SSL_AD_DECODE_ERROR;
1204                                 return 0;
1205                                 }
1206                         n2s(sdata, s->s3->client_opaque_prf_input_len);
1207                         if (s->s3->client_opaque_prf_input_len != size - 2)
1208                                 {
1209                                 *al = SSL_AD_DECODE_ERROR;
1210                                 return 0;
1211                                 }
1212
1213                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1214                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1215                         if (s->s3->client_opaque_prf_input_len == 0)
1216                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1217                         else
1218                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
1219                         if (s->s3->client_opaque_prf_input == NULL)
1220                                 {
1221                                 *al = TLS1_AD_INTERNAL_ERROR;
1222                                 return 0;
1223                                 }
1224                         }
1225 #endif
1226                 else if (type == TLSEXT_TYPE_session_ticket)
1227                         {
1228                         if (s->tls_session_ticket_ext_cb &&
1229                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1230                                 {
1231                                 *al = TLS1_AD_INTERNAL_ERROR;
1232                                 return 0;
1233                                 }
1234                         }
1235                 else if (type == TLSEXT_TYPE_renegotiate)
1236                         {
1237                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
1238                                 return 0;
1239                         renegotiate_seen = 1;
1240                         }
1241                 else if (type == TLSEXT_TYPE_signature_algorithms)
1242                         {
1243                         int dsize;
1244                         if (sigalg_seen || size < 2) 
1245                                 {
1246                                 *al = SSL_AD_DECODE_ERROR;
1247                                 return 0;
1248                                 }
1249                         sigalg_seen = 1;
1250                         n2s(data,dsize);
1251                         size -= 2;
1252                         if (dsize != size || dsize & 1) 
1253                                 {
1254                                 *al = SSL_AD_DECODE_ERROR;
1255                                 return 0;
1256                                 }
1257                         if (!tls1_process_sigalgs(s, data, dsize))
1258                                 {
1259                                 *al = SSL_AD_DECODE_ERROR;
1260                                 return 0;
1261                                 }
1262                         }
1263                 else if (type == TLSEXT_TYPE_status_request &&
1264                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
1265                         {
1266                 
1267                         if (size < 5) 
1268                                 {
1269                                 *al = SSL_AD_DECODE_ERROR;
1270                                 return 0;
1271                                 }
1272
1273                         s->tlsext_status_type = *data++;
1274                         size--;
1275                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1276                                 {
1277                                 const unsigned char *sdata;
1278                                 int dsize;
1279                                 /* Read in responder_id_list */
1280                                 n2s(data,dsize);
1281                                 size -= 2;
1282                                 if (dsize > size  ) 
1283                                         {
1284                                         *al = SSL_AD_DECODE_ERROR;
1285                                         return 0;
1286                                         }
1287                                 while (dsize > 0)
1288                                         {
1289                                         OCSP_RESPID *id;
1290                                         int idsize;
1291                                         if (dsize < 4)
1292                                                 {
1293                                                 *al = SSL_AD_DECODE_ERROR;
1294                                                 return 0;
1295                                                 }
1296                                         n2s(data, idsize);
1297                                         dsize -= 2 + idsize;
1298                                         size -= 2 + idsize;
1299                                         if (dsize < 0)
1300                                                 {
1301                                                 *al = SSL_AD_DECODE_ERROR;
1302                                                 return 0;
1303                                                 }
1304                                         sdata = data;
1305                                         data += idsize;
1306                                         id = d2i_OCSP_RESPID(NULL,
1307                                                                 &sdata, idsize);
1308                                         if (!id)
1309                                                 {
1310                                                 *al = SSL_AD_DECODE_ERROR;
1311                                                 return 0;
1312                                                 }
1313                                         if (data != sdata)
1314                                                 {
1315                                                 OCSP_RESPID_free(id);
1316                                                 *al = SSL_AD_DECODE_ERROR;
1317                                                 return 0;
1318                                                 }
1319                                         if (!s->tlsext_ocsp_ids
1320                                                 && !(s->tlsext_ocsp_ids =
1321                                                 sk_OCSP_RESPID_new_null()))
1322                                                 {
1323                                                 OCSP_RESPID_free(id);
1324                                                 *al = SSL_AD_INTERNAL_ERROR;
1325                                                 return 0;
1326                                                 }
1327                                         if (!sk_OCSP_RESPID_push(
1328                                                         s->tlsext_ocsp_ids, id))
1329                                                 {
1330                                                 OCSP_RESPID_free(id);
1331                                                 *al = SSL_AD_INTERNAL_ERROR;
1332                                                 return 0;
1333                                                 }
1334                                         }
1335
1336                                 /* Read in request_extensions */
1337                                 if (size < 2)
1338                                         {
1339                                         *al = SSL_AD_DECODE_ERROR;
1340                                         return 0;
1341                                         }
1342                                 n2s(data,dsize);
1343                                 size -= 2;
1344                                 if (dsize != size)
1345                                         {
1346                                         *al = SSL_AD_DECODE_ERROR;
1347                                         return 0;
1348                                         }
1349                                 sdata = data;
1350                                 if (dsize > 0)
1351                                         {
1352                                         if (s->tlsext_ocsp_exts)
1353                                                 {
1354                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
1355                                                                            X509_EXTENSION_free);
1356                                                 }
1357
1358                                         s->tlsext_ocsp_exts =
1359                                                 d2i_X509_EXTENSIONS(NULL,
1360                                                         &sdata, dsize);
1361                                         if (!s->tlsext_ocsp_exts
1362                                                 || (data + dsize != sdata))
1363                                                 {
1364                                                 *al = SSL_AD_DECODE_ERROR;
1365                                                 return 0;
1366                                                 }
1367                                         }
1368                                 }
1369                                 /* We don't know what to do with any other type
1370                                 * so ignore it.
1371                                 */
1372                                 else
1373                                         s->tlsext_status_type = -1;
1374                         }
1375 #ifndef OPENSSL_NO_HEARTBEATS
1376                 else if (type == TLSEXT_TYPE_heartbeat)
1377                         {
1378                         switch(data[0])
1379                                 {
1380                                 case 0x01:      /* Client allows us to send HB requests */
1381                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1382                                                         break;
1383                                 case 0x02:      /* Client doesn't accept HB requests */
1384                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1385                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1386                                                         break;
1387                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
1388                                                         return 0;
1389                                 }
1390                         }
1391 #endif
1392 #ifndef OPENSSL_NO_NEXTPROTONEG
1393                 else if (type == TLSEXT_TYPE_next_proto_neg &&
1394                          s->s3->tmp.finish_md_len == 0)
1395                         {
1396                         /* We shouldn't accept this extension on a
1397                          * renegotiation.
1398                          *
1399                          * s->new_session will be set on renegotiation, but we
1400                          * probably shouldn't rely that it couldn't be set on
1401                          * the initial renegotation too in certain cases (when
1402                          * there's some other reason to disallow resuming an
1403                          * earlier session -- the current code won't be doing
1404                          * anything like that, but this might change).
1405
1406                          * A valid sign that there's been a previous handshake
1407                          * in this connection is if s->s3->tmp.finish_md_len >
1408                          * 0.  (We are talking about a check that will happen
1409                          * in the Hello protocol round, well before a new
1410                          * Finished message could have been computed.) */
1411                         s->s3->next_proto_neg_seen = 1;
1412                         }
1413 #endif
1414
1415                 /* session ticket processed earlier */
1416 #ifndef OPENSSL_NO_SRTP
1417                 else if (type == TLSEXT_TYPE_use_srtp)
1418                         {
1419                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
1420                                                               al))
1421                                 return 0;
1422                         }
1423 #endif
1424
1425                 data+=size;
1426                 }
1427                                 
1428         *p = data;
1429
1430         ri_check:
1431
1432         /* Need RI if renegotiating */
1433
1434         if (!renegotiate_seen && s->renegotiate &&
1435                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1436                 {
1437                 *al = SSL_AD_HANDSHAKE_FAILURE;
1438                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,
1439                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1440                 return 0;
1441                 }
1442
1443         return 1;
1444         }
1445
1446 #ifndef OPENSSL_NO_NEXTPROTONEG
1447 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
1448  * elements of zero length are allowed and the set of elements must exactly fill
1449  * the length of the block. */
1450 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
1451         {
1452         unsigned int off = 0;
1453
1454         while (off < len)
1455                 {
1456                 if (d[off] == 0)
1457                         return 0;
1458                 off += d[off];
1459                 off++;
1460                 }
1461
1462         return off == len;
1463         }
1464 #endif
1465
1466 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
1467         {
1468         unsigned short length;
1469         unsigned short type;
1470         unsigned short size;
1471         unsigned char *data = *p;
1472         int tlsext_servername = 0;
1473         int renegotiate_seen = 0;
1474
1475 #ifndef OPENSSL_NO_NEXTPROTONEG
1476         s->s3->next_proto_neg_seen = 0;
1477 #endif
1478
1479 #ifndef OPENSSL_NO_HEARTBEATS
1480         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1481                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1482 #endif
1483
1484         if (data >= (d+n-2))
1485                 goto ri_check;
1486
1487         n2s(data,length);
1488         if (data+length != d+n)
1489                 {
1490                 *al = SSL_AD_DECODE_ERROR;
1491                 return 0;
1492                 }
1493
1494         while(data <= (d+n-4))
1495                 {
1496                 n2s(data,type);
1497                 n2s(data,size);
1498
1499                 if (data+size > (d+n))
1500                         goto ri_check;
1501
1502                 if (s->tlsext_debug_cb)
1503                         s->tlsext_debug_cb(s, 1, type, data, size,
1504                                                 s->tlsext_debug_arg);
1505
1506                 if (type == TLSEXT_TYPE_server_name)
1507                         {
1508                         if (s->tlsext_hostname == NULL || size > 0)
1509                                 {
1510                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
1511                                 return 0;
1512                                 }
1513                         tlsext_servername = 1;   
1514                         }
1515
1516 #ifndef OPENSSL_NO_EC
1517                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1518                      s->version != DTLS1_VERSION)
1519                         {
1520                         unsigned char *sdata = data;
1521                         int ecpointformatlist_length = *(sdata++);
1522
1523                         if (ecpointformatlist_length != size - 1 || 
1524                                 ecpointformatlist_length < 1)
1525                                 {
1526                                 *al = TLS1_AD_DECODE_ERROR;
1527                                 return 0;
1528                                 }
1529                         s->session->tlsext_ecpointformatlist_length = 0;
1530                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
1531                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1532                                 {
1533                                 *al = TLS1_AD_INTERNAL_ERROR;
1534                                 return 0;
1535                                 }
1536                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1537                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1538 #if 0
1539                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
1540                         sdata = s->session->tlsext_ecpointformatlist;
1541                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1542                                 fprintf(stderr,"%i ",*(sdata++));
1543                         fprintf(stderr,"\n");
1544 #endif
1545                         }
1546 #endif /* OPENSSL_NO_EC */
1547
1548                 else if (type == TLSEXT_TYPE_session_ticket)
1549                         {
1550                         if (s->tls_session_ticket_ext_cb &&
1551                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1552                                 {
1553                                 *al = TLS1_AD_INTERNAL_ERROR;
1554                                 return 0;
1555                                 }
1556                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
1557                                 || (size > 0))
1558                                 {
1559                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1560                                 return 0;
1561                                 }
1562                         s->tlsext_ticket_expected = 1;
1563                         }
1564 #ifdef TLSEXT_TYPE_opaque_prf_input
1565                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1566                      s->version != DTLS1_VERSION)
1567                         {
1568                         unsigned char *sdata = data;
1569
1570                         if (size < 2)
1571                                 {
1572                                 *al = SSL_AD_DECODE_ERROR;
1573                                 return 0;
1574                                 }
1575                         n2s(sdata, s->s3->server_opaque_prf_input_len);
1576                         if (s->s3->server_opaque_prf_input_len != size - 2)
1577                                 {
1578                                 *al = SSL_AD_DECODE_ERROR;
1579                                 return 0;
1580                                 }
1581                         
1582                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
1583                                 OPENSSL_free(s->s3->server_opaque_prf_input);
1584                         if (s->s3->server_opaque_prf_input_len == 0)
1585                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1586                         else
1587                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
1588
1589                         if (s->s3->server_opaque_prf_input == NULL)
1590                                 {
1591                                 *al = TLS1_AD_INTERNAL_ERROR;
1592                                 return 0;
1593                                 }
1594                         }
1595 #endif
1596                 else if (type == TLSEXT_TYPE_status_request &&
1597                          s->version != DTLS1_VERSION)
1598                         {
1599                         /* MUST be empty and only sent if we've requested
1600                          * a status request message.
1601                          */ 
1602                         if ((s->tlsext_status_type == -1) || (size > 0))
1603                                 {
1604                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1605                                 return 0;
1606                                 }
1607                         /* Set flag to expect CertificateStatus message */
1608                         s->tlsext_status_expected = 1;
1609                         }
1610 #ifndef OPENSSL_NO_NEXTPROTONEG
1611                 else if (type == TLSEXT_TYPE_next_proto_neg &&
1612                          s->s3->tmp.finish_md_len == 0)
1613                         {
1614                         unsigned char *selected;
1615                         unsigned char selected_len;
1616
1617                         /* We must have requested it. */
1618                         if (s->ctx->next_proto_select_cb == NULL)
1619                                 {
1620                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
1621                                 return 0;
1622                                 }
1623                         /* The data must be valid */
1624                         if (!ssl_next_proto_validate(data, size))
1625                                 {
1626                                 *al = TLS1_AD_DECODE_ERROR;
1627                                 return 0;
1628                                 }
1629                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
1630                                 {
1631                                 *al = TLS1_AD_INTERNAL_ERROR;
1632                                 return 0;
1633                                 }
1634                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
1635                         if (!s->next_proto_negotiated)
1636                                 {
1637                                 *al = TLS1_AD_INTERNAL_ERROR;
1638                                 return 0;
1639                                 }
1640                         memcpy(s->next_proto_negotiated, selected, selected_len);
1641                         s->next_proto_negotiated_len = selected_len;
1642                         s->s3->next_proto_neg_seen = 1;
1643                         }
1644 #endif
1645                 else if (type == TLSEXT_TYPE_renegotiate)
1646                         {
1647                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
1648                                 return 0;
1649                         renegotiate_seen = 1;
1650                         }
1651 #ifndef OPENSSL_NO_HEARTBEATS
1652                 else if (type == TLSEXT_TYPE_heartbeat)
1653                         {
1654                         switch(data[0])
1655                                 {
1656                                 case 0x01:      /* Server allows us to send HB requests */
1657                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1658                                                         break;
1659                                 case 0x02:      /* Server doesn't accept HB requests */
1660                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
1661                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1662                                                         break;
1663                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
1664                                                         return 0;
1665                                 }
1666                         }
1667 #endif
1668 #ifndef OPENSSL_NO_SRTP
1669                 else if (type == TLSEXT_TYPE_use_srtp)
1670                         {
1671                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
1672                                                               al))
1673                                 return 0;
1674                         }
1675 #endif
1676
1677                 data+=size;             
1678                 }
1679
1680         if (data != d+n)
1681                 {
1682                 *al = SSL_AD_DECODE_ERROR;
1683                 return 0;
1684                 }
1685
1686         if (!s->hit && tlsext_servername == 1)
1687                 {
1688                 if (s->tlsext_hostname)
1689                         {
1690                         if (s->session->tlsext_hostname == NULL)
1691                                 {
1692                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
1693                                 if (!s->session->tlsext_hostname)
1694                                         {
1695                                         *al = SSL_AD_UNRECOGNIZED_NAME;
1696                                         return 0;
1697                                         }
1698                                 }
1699                         else 
1700                                 {
1701                                 *al = SSL_AD_DECODE_ERROR;
1702                                 return 0;
1703                                 }
1704                         }
1705                 }
1706
1707         *p = data;
1708
1709         ri_check:
1710
1711         /* Determine if we need to see RI. Strictly speaking if we want to
1712          * avoid an attack we should *always* see RI even on initial server
1713          * hello because the client doesn't see any renegotiation during an
1714          * attack. However this would mean we could not connect to any server
1715          * which doesn't support RI so for the immediate future tolerate RI
1716          * absence on initial connect only.
1717          */
1718         if (!renegotiate_seen
1719                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
1720                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1721                 {
1722                 *al = SSL_AD_HANDSHAKE_FAILURE;
1723                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,
1724                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1725                 return 0;
1726                 }
1727
1728         return 1;
1729         }
1730
1731
1732 int ssl_prepare_clienthello_tlsext(SSL *s)
1733         {
1734 #ifndef OPENSSL_NO_EC
1735         /* If we are client and using an elliptic curve cryptography cipher suite, send the point formats 
1736          * and elliptic curves we support.
1737          */
1738         int using_ecc = 0;
1739         int i;
1740         unsigned char *j;
1741         unsigned long alg_k, alg_a;
1742         STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1743
1744         for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1745                 {
1746                 SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1747
1748                 alg_k = c->algorithm_mkey;
1749                 alg_a = c->algorithm_auth;
1750                 if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe) || (alg_a & SSL_aECDSA)))
1751                         {
1752                         using_ecc = 1;
1753                         break;
1754                         }
1755                 }
1756         using_ecc = using_ecc && (s->version >= TLS1_VERSION);
1757         if (using_ecc)
1758                 {
1759                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
1760                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
1761                         {
1762                         SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1763                         return -1;
1764                         }
1765                 s->tlsext_ecpointformatlist_length = 3;
1766                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
1767                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
1768                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
1769
1770                 /* we support all named elliptic curves in draft-ietf-tls-ecc-12 */
1771                 if (s->tlsext_ellipticcurvelist != NULL) OPENSSL_free(s->tlsext_ellipticcurvelist);
1772                 s->tlsext_ellipticcurvelist_length = sizeof(pref_list)/sizeof(pref_list[0]) * 2;
1773                 if ((s->tlsext_ellipticcurvelist = OPENSSL_malloc(s->tlsext_ellipticcurvelist_length)) == NULL)
1774                         {
1775                         s->tlsext_ellipticcurvelist_length = 0;
1776                         SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1777                         return -1;
1778                         }
1779                 for (i = 0, j = s->tlsext_ellipticcurvelist; (unsigned int)i <
1780                                 sizeof(pref_list)/sizeof(pref_list[0]); i++)
1781                         {
1782                         int id = tls1_ec_nid2curve_id(pref_list[i]);
1783                         s2n(id,j);
1784                         }
1785                 }
1786 #endif /* OPENSSL_NO_EC */
1787
1788 #ifdef TLSEXT_TYPE_opaque_prf_input
1789         {
1790                 int r = 1;
1791         
1792                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
1793                         {
1794                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
1795                         if (!r)
1796                                 return -1;
1797                         }
1798
1799                 if (s->tlsext_opaque_prf_input != NULL)
1800                         {
1801                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1802                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1803
1804                         if (s->tlsext_opaque_prf_input_len == 0)
1805                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1806                         else
1807                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
1808                         if (s->s3->client_opaque_prf_input == NULL)
1809                                 {
1810                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1811                                 return -1;
1812                                 }
1813                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1814                         }
1815
1816                 if (r == 2)
1817                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
1818                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1819         }
1820 #endif
1821
1822         return 1;
1823         }
1824
1825 int ssl_prepare_serverhello_tlsext(SSL *s)
1826         {
1827 #ifndef OPENSSL_NO_EC
1828         /* If we are server and using an ECC cipher suite, send the point formats we support 
1829          * if the client sent us an ECPointsFormat extension.  Note that the server is not
1830          * supposed to send an EllipticCurves extension.
1831          */
1832
1833         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1834         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1835         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1836         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1837         
1838         if (using_ecc)
1839                 {
1840                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
1841                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
1842                         {
1843                         SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
1844                         return -1;
1845                         }
1846                 s->tlsext_ecpointformatlist_length = 3;
1847                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
1848                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
1849                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
1850                 }
1851 #endif /* OPENSSL_NO_EC */
1852
1853         return 1;
1854         }
1855
1856 int ssl_check_clienthello_tlsext_early(SSL *s)
1857         {
1858         int ret=SSL_TLSEXT_ERR_NOACK;
1859         int al = SSL_AD_UNRECOGNIZED_NAME;
1860
1861 #ifndef OPENSSL_NO_EC
1862         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
1863          * ssl3_choose_cipher in s3_lib.c.
1864          */
1865         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
1866          * ssl3_choose_cipher in s3_lib.c.
1867          */
1868 #endif
1869
1870         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
1871                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
1872         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
1873                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
1874
1875 #ifdef TLSEXT_TYPE_opaque_prf_input
1876         {
1877                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
1878                  * but we might be sending an alert in response to the client hello,
1879                  * so this has to happen here in
1880                  * ssl_check_clienthello_tlsext_early(). */
1881
1882                 int r = 1;
1883         
1884                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
1885                         {
1886                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
1887                         if (!r)
1888                                 {
1889                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1890                                 al = SSL_AD_INTERNAL_ERROR;
1891                                 goto err;
1892                                 }
1893                         }
1894
1895                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
1896                         OPENSSL_free(s->s3->server_opaque_prf_input);
1897                 s->s3->server_opaque_prf_input = NULL;
1898
1899                 if (s->tlsext_opaque_prf_input != NULL)
1900                         {
1901                         if (s->s3->client_opaque_prf_input != NULL &&
1902                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
1903                                 {
1904                                 /* can only use this extension if we have a server opaque PRF input
1905                                  * of the same length as the client opaque PRF input! */
1906
1907                                 if (s->tlsext_opaque_prf_input_len == 0)
1908                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1909                                 else
1910                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
1911                                 if (s->s3->server_opaque_prf_input == NULL)
1912                                         {
1913                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1914                                         al = SSL_AD_INTERNAL_ERROR;
1915                                         goto err;
1916                                         }
1917                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
1918                                 }
1919                         }
1920
1921                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
1922                         {
1923                         /* The callback wants to enforce use of the extension,
1924                          * but we can't do that with the client opaque PRF input;
1925                          * abort the handshake.
1926                          */
1927                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1928                         al = SSL_AD_HANDSHAKE_FAILURE;
1929                         }
1930         }
1931
1932  err:
1933 #endif
1934         switch (ret)
1935                 {
1936                 case SSL_TLSEXT_ERR_ALERT_FATAL:
1937                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
1938                         return -1;
1939
1940                 case SSL_TLSEXT_ERR_ALERT_WARNING:
1941                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
1942                         return 1; 
1943                                         
1944                 case SSL_TLSEXT_ERR_NOACK:
1945                         s->servername_done=0;
1946                         default:
1947                 return 1;
1948                 }
1949         }
1950
1951 int ssl_check_clienthello_tlsext_late(SSL *s)
1952         {
1953         int ret = SSL_TLSEXT_ERR_OK;
1954         int al;
1955
1956         /* If status request then ask callback what to do.
1957          * Note: this must be called after servername callbacks in case 
1958          * the certificate has changed, and must be called after the cipher
1959          * has been chosen because this may influence which certificate is sent
1960          */
1961         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
1962                 {
1963                 int r;
1964                 CERT_PKEY *certpkey;
1965                 certpkey = ssl_get_server_send_pkey(s);
1966                 /* If no certificate can't return certificate status */
1967                 if (certpkey == NULL)
1968                         {
1969                         s->tlsext_status_expected = 0;
1970                         return 1;
1971                         }
1972                 /* Set current certificate to one we will use so
1973                  * SSL_get_certificate et al can pick it up.
1974                  */
1975                 s->cert->key = certpkey;
1976                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
1977                 switch (r)
1978                         {
1979                         /* We don't want to send a status request response */
1980                         case SSL_TLSEXT_ERR_NOACK:
1981                                 s->tlsext_status_expected = 0;
1982                                 break;
1983                         /* status request response should be sent */
1984                         case SSL_TLSEXT_ERR_OK:
1985                                 if (s->tlsext_ocsp_resp)
1986                                         s->tlsext_status_expected = 1;
1987                                 else
1988                                         s->tlsext_status_expected = 0;
1989                                 break;
1990                         /* something bad happened */
1991                         case SSL_TLSEXT_ERR_ALERT_FATAL:
1992                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
1993                                 al = SSL_AD_INTERNAL_ERROR;
1994                                 goto err;
1995                         }
1996                 }
1997         else
1998                 s->tlsext_status_expected = 0;
1999
2000  err:
2001         switch (ret)
2002                 {
2003                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2004                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2005                         return -1;
2006
2007                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2008                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2009                         return 1; 
2010
2011                 default:
2012                         return 1;
2013                 }
2014         }
2015
2016 int ssl_check_serverhello_tlsext(SSL *s)
2017         {
2018         int ret=SSL_TLSEXT_ERR_NOACK;
2019         int al = SSL_AD_UNRECOGNIZED_NAME;
2020
2021 #ifndef OPENSSL_NO_EC
2022         /* If we are client and using an elliptic curve cryptography cipher
2023          * suite, then if server returns an EC point formats lists extension
2024          * it must contain uncompressed.
2025          */
2026         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2027         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2028         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
2029             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
2030             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
2031                 {
2032                 /* we are using an ECC cipher */
2033                 size_t i;
2034                 unsigned char *list;
2035                 int found_uncompressed = 0;
2036                 list = s->session->tlsext_ecpointformatlist;
2037                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2038                         {
2039                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
2040                                 {
2041                                 found_uncompressed = 1;
2042                                 break;
2043                                 }
2044                         }
2045                 if (!found_uncompressed)
2046                         {
2047                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2048                         return -1;
2049                         }
2050                 }
2051         ret = SSL_TLSEXT_ERR_OK;
2052 #endif /* OPENSSL_NO_EC */
2053
2054         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2055                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2056         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2057                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2058
2059 #ifdef TLSEXT_TYPE_opaque_prf_input
2060         if (s->s3->server_opaque_prf_input_len > 0)
2061                 {
2062                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
2063                  * So first verify that we really have a value from the server too. */
2064
2065                 if (s->s3->server_opaque_prf_input == NULL)
2066                         {
2067                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2068                         al = SSL_AD_HANDSHAKE_FAILURE;
2069                         }
2070                 
2071                 /* Anytime the server *has* sent an opaque PRF input, we need to check
2072                  * that we have a client opaque PRF input of the same size. */
2073                 if (s->s3->client_opaque_prf_input == NULL ||
2074                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
2075                         {
2076                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2077                         al = SSL_AD_ILLEGAL_PARAMETER;
2078                         }
2079                 }
2080 #endif
2081
2082         /* If we've requested certificate status and we wont get one
2083          * tell the callback
2084          */
2085         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
2086                         && s->ctx && s->ctx->tlsext_status_cb)
2087                 {
2088                 int r;
2089                 /* Set resp to NULL, resplen to -1 so callback knows
2090                  * there is no response.
2091                  */
2092                 if (s->tlsext_ocsp_resp)
2093                         {
2094                         OPENSSL_free(s->tlsext_ocsp_resp);
2095                         s->tlsext_ocsp_resp = NULL;
2096                         }
2097                 s->tlsext_ocsp_resplen = -1;
2098                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2099                 if (r == 0)
2100                         {
2101                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2102                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2103                         }
2104                 if (r < 0)
2105                         {
2106                         al = SSL_AD_INTERNAL_ERROR;
2107                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2108                         }
2109                 }
2110
2111         switch (ret)
2112                 {
2113                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2114                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2115                         return -1;
2116
2117                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2118                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2119                         return 1; 
2120                                         
2121                 case SSL_TLSEXT_ERR_NOACK:
2122                         s->servername_done=0;
2123                         default:
2124                 return 1;
2125                 }
2126         }
2127
2128 /* Since the server cache lookup is done early on in the processing of the
2129  * ClientHello, and other operations depend on the result, we need to handle
2130  * any TLS session ticket extension at the same time.
2131  *
2132  *   session_id: points at the session ID in the ClientHello. This code will
2133  *       read past the end of this in order to parse out the session ticket
2134  *       extension, if any.
2135  *   len: the length of the session ID.
2136  *   limit: a pointer to the first byte after the ClientHello.
2137  *   ret: (output) on return, if a ticket was decrypted, then this is set to
2138  *       point to the resulting session.
2139  *
2140  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2141  * ciphersuite, in which case we have no use for session tickets and one will
2142  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2143  *
2144  * Returns:
2145  *   -1: fatal error, either from parsing or decrypting the ticket.
2146  *    0: no ticket was found (or was ignored, based on settings).
2147  *    1: a zero length extension was found, indicating that the client supports
2148  *       session tickets but doesn't currently have one to offer.
2149  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
2150  *       couldn't be decrypted because of a non-fatal error.
2151  *    3: a ticket was successfully decrypted and *ret was set.
2152  *
2153  * Side effects:
2154  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
2155  *   a new session ticket to the client because the client indicated support
2156  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
2157  *   a session ticket or we couldn't use the one it gave us, or if
2158  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
2159  *   Otherwise, s->tlsext_ticket_expected is set to 0.
2160  */
2161 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
2162                         const unsigned char *limit, SSL_SESSION **ret)
2163         {
2164         /* Point after session ID in client hello */
2165         const unsigned char *p = session_id + len;
2166         unsigned short i;
2167
2168         *ret = NULL;
2169         s->tlsext_ticket_expected = 0;
2170
2171         /* If tickets disabled behave as if no ticket present
2172          * to permit stateful resumption.
2173          */
2174         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
2175                 return 0;
2176         if ((s->version <= SSL3_VERSION) || !limit)
2177                 return 0;
2178         if (p >= limit)
2179                 return -1;
2180         /* Skip past DTLS cookie */
2181         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
2182                 {
2183                 i = *(p++);
2184                 p+= i;
2185                 if (p >= limit)
2186                         return -1;
2187                 }
2188         /* Skip past cipher list */
2189         n2s(p, i);
2190         p+= i;
2191         if (p >= limit)
2192                 return -1;
2193         /* Skip past compression algorithm list */
2194         i = *(p++);
2195         p += i;
2196         if (p > limit)
2197                 return -1;
2198         /* Now at start of extensions */
2199         if ((p + 2) >= limit)
2200                 return 0;
2201         n2s(p, i);
2202         while ((p + 4) <= limit)
2203                 {
2204                 unsigned short type, size;
2205                 n2s(p, type);
2206                 n2s(p, size);
2207                 if (p + size > limit)
2208                         return 0;
2209                 if (type == TLSEXT_TYPE_session_ticket)
2210                         {
2211                         int r;
2212                         if (size == 0)
2213                                 {
2214                                 /* The client will accept a ticket but doesn't
2215                                  * currently have one. */
2216                                 s->tlsext_ticket_expected = 1;
2217                                 return 1;
2218                                 }
2219                         if (s->tls_session_secret_cb)
2220                                 {
2221                                 /* Indicate that the ticket couldn't be
2222                                  * decrypted rather than generating the session
2223                                  * from ticket now, trigger abbreviated
2224                                  * handshake based on external mechanism to
2225                                  * calculate the master secret later. */
2226                                 return 2;
2227                                 }
2228                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
2229                         switch (r)
2230                                 {
2231                                 case 2: /* ticket couldn't be decrypted */
2232                                         s->tlsext_ticket_expected = 1;
2233                                         return 2;
2234                                 case 3: /* ticket was decrypted */
2235                                         return r;
2236                                 case 4: /* ticket decrypted but need to renew */
2237                                         s->tlsext_ticket_expected = 1;
2238                                         return 3;
2239                                 default: /* fatal error */
2240                                         return -1;
2241                                 }
2242                         }
2243                 p += size;
2244                 }
2245         return 0;
2246         }
2247
2248 /* tls_decrypt_ticket attempts to decrypt a session ticket.
2249  *
2250  *   etick: points to the body of the session ticket extension.
2251  *   eticklen: the length of the session tickets extenion.
2252  *   sess_id: points at the session ID.
2253  *   sesslen: the length of the session ID.
2254  *   psess: (output) on return, if a ticket was decrypted, then this is set to
2255  *       point to the resulting session.
2256  *
2257  * Returns:
2258  *   -1: fatal error, either from parsing or decrypting the ticket.
2259  *    2: the ticket couldn't be decrypted.
2260  *    3: a ticket was successfully decrypted and *psess was set.
2261  *    4: same as 3, but the ticket needs to be renewed.
2262  */
2263 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
2264                                 const unsigned char *sess_id, int sesslen,
2265                                 SSL_SESSION **psess)
2266         {
2267         SSL_SESSION *sess;
2268         unsigned char *sdec;
2269         const unsigned char *p;
2270         int slen, mlen, renew_ticket = 0;
2271         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
2272         HMAC_CTX hctx;
2273         EVP_CIPHER_CTX ctx;
2274         SSL_CTX *tctx = s->initial_ctx;
2275         /* Need at least keyname + iv + some encrypted data */
2276         if (eticklen < 48)
2277                 return 2;
2278         /* Initialize session ticket encryption and HMAC contexts */
2279         HMAC_CTX_init(&hctx);
2280         EVP_CIPHER_CTX_init(&ctx);
2281         if (tctx->tlsext_ticket_key_cb)
2282                 {
2283                 unsigned char *nctick = (unsigned char *)etick;
2284                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
2285                                                         &ctx, &hctx, 0);
2286                 if (rv < 0)
2287                         return -1;
2288                 if (rv == 0)
2289                         return 2;
2290                 if (rv == 2)
2291                         renew_ticket = 1;
2292                 }
2293         else
2294                 {
2295                 /* Check key name matches */
2296                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
2297                         return 2;
2298                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2299                                         tlsext_tick_md(), NULL);
2300                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2301                                 tctx->tlsext_tick_aes_key, etick + 16);
2302                 }
2303         /* Attempt to process session ticket, first conduct sanity and
2304          * integrity checks on ticket.
2305          */
2306         mlen = HMAC_size(&hctx);
2307         if (mlen < 0)
2308                 {
2309                 EVP_CIPHER_CTX_cleanup(&ctx);
2310                 return -1;
2311                 }
2312         eticklen -= mlen;
2313         /* Check HMAC of encrypted ticket */
2314         HMAC_Update(&hctx, etick, eticklen);
2315         HMAC_Final(&hctx, tick_hmac, NULL);
2316         HMAC_CTX_cleanup(&hctx);
2317         if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
2318                 return 2;
2319         /* Attempt to decrypt session data */
2320         /* Move p after IV to start of encrypted ticket, update length */
2321         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2322         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
2323         sdec = OPENSSL_malloc(eticklen);
2324         if (!sdec)
2325                 {
2326                 EVP_CIPHER_CTX_cleanup(&ctx);
2327                 return -1;
2328                 }
2329         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
2330         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
2331                 return 2;
2332         slen += mlen;
2333         EVP_CIPHER_CTX_cleanup(&ctx);
2334         p = sdec;
2335
2336         sess = d2i_SSL_SESSION(NULL, &p, slen);
2337         OPENSSL_free(sdec);
2338         if (sess)
2339                 {
2340                 /* The session ID, if non-empty, is used by some clients to
2341                  * detect that the ticket has been accepted. So we copy it to
2342                  * the session structure. If it is empty set length to zero
2343                  * as required by standard.
2344                  */
2345                 if (sesslen)
2346                         memcpy(sess->session_id, sess_id, sesslen);
2347                 sess->session_id_length = sesslen;
2348                 *psess = sess;
2349                 if (renew_ticket)
2350                         return 4;
2351                 else
2352                         return 3;
2353                 }
2354         ERR_clear_error();
2355         /* For session parse failure, indicate that we need to send a new
2356          * ticket. */
2357         return 2;
2358         }
2359
2360 /* Tables to translate from NIDs to TLS v1.2 ids */
2361
2362 typedef struct 
2363         {
2364         int nid;
2365         int id;
2366         } tls12_lookup;
2367
2368 static tls12_lookup tls12_md[] = {
2369 #ifndef OPENSSL_NO_MD5
2370         {NID_md5, TLSEXT_hash_md5},
2371 #endif
2372 #ifndef OPENSSL_NO_SHA
2373         {NID_sha1, TLSEXT_hash_sha1},
2374 #endif
2375 #ifndef OPENSSL_NO_SHA256
2376         {NID_sha224, TLSEXT_hash_sha224},
2377         {NID_sha256, TLSEXT_hash_sha256},
2378 #endif
2379 #ifndef OPENSSL_NO_SHA512
2380         {NID_sha384, TLSEXT_hash_sha384},
2381         {NID_sha512, TLSEXT_hash_sha512}
2382 #endif
2383 };
2384
2385 static tls12_lookup tls12_sig[] = {
2386 #ifndef OPENSSL_NO_RSA
2387         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
2388 #endif
2389 #ifndef OPENSSL_NO_DSA
2390         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
2391 #endif
2392 #ifndef OPENSSL_NO_ECDSA
2393         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
2394 #endif
2395 };
2396
2397 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
2398         {
2399         size_t i;
2400         for (i = 0; i < tlen; i++)
2401                 {
2402                 if (table[i].nid == nid)
2403                         return table[i].id;
2404                 }
2405         return -1;
2406         }
2407 #if 0
2408 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
2409         {
2410         size_t i;
2411         for (i = 0; i < tlen; i++)
2412                 {
2413                 if (table[i].id == id)
2414                         return table[i].nid;
2415                 }
2416         return -1;
2417         }
2418 #endif
2419
2420 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
2421         {
2422         int sig_id, md_id;
2423         if (!md)
2424                 return 0;
2425         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
2426                                 sizeof(tls12_md)/sizeof(tls12_lookup));
2427         if (md_id == -1)
2428                 return 0;
2429         sig_id = tls12_get_sigid(pk);
2430         if (sig_id == -1)
2431                 return 0;
2432         p[0] = (unsigned char)md_id;
2433         p[1] = (unsigned char)sig_id;
2434         return 1;
2435         }
2436
2437 int tls12_get_sigid(const EVP_PKEY *pk)
2438         {
2439         return tls12_find_id(pk->type, tls12_sig,
2440                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
2441         }
2442
2443 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
2444         {
2445         switch(hash_alg)
2446                 {
2447 #ifndef OPENSSL_NO_SHA
2448                 case TLSEXT_hash_sha1:
2449                 return EVP_sha1();
2450 #endif
2451 #ifndef OPENSSL_NO_SHA256
2452                 case TLSEXT_hash_sha224:
2453                 return EVP_sha224();
2454
2455                 case TLSEXT_hash_sha256:
2456                 return EVP_sha256();
2457 #endif
2458 #ifndef OPENSSL_NO_SHA512
2459                 case TLSEXT_hash_sha384:
2460                 return EVP_sha384();
2461
2462                 case TLSEXT_hash_sha512:
2463                 return EVP_sha512();
2464 #endif
2465                 default:
2466                 return NULL;
2467
2468                 }
2469         }
2470
2471 /* Set preferred digest for each key type */
2472
2473 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
2474         {
2475         int i, idx;
2476         const EVP_MD *md;
2477         CERT *c = s->cert;
2478         /* Extension ignored for TLS versions below 1.2 */
2479         if (TLS1_get_version(s) < TLS1_2_VERSION)
2480                 return 1;
2481         /* Should never happen */
2482         if (!c)
2483                 return 0;
2484
2485         c->pkeys[SSL_PKEY_DSA_SIGN].digest = NULL;
2486         c->pkeys[SSL_PKEY_RSA_SIGN].digest = NULL;
2487         c->pkeys[SSL_PKEY_RSA_ENC].digest = NULL;
2488         c->pkeys[SSL_PKEY_ECC].digest = NULL;
2489
2490         for (i = 0; i < dsize; i += 2)
2491                 {
2492                 unsigned char hash_alg = data[i], sig_alg = data[i+1];
2493
2494                 switch(sig_alg)
2495                         {
2496 #ifndef OPENSSL_NO_RSA
2497                         case TLSEXT_signature_rsa:
2498                         idx = SSL_PKEY_RSA_SIGN;
2499                         break;
2500 #endif
2501 #ifndef OPENSSL_NO_DSA
2502                         case TLSEXT_signature_dsa:
2503                         idx = SSL_PKEY_DSA_SIGN;
2504                         break;
2505 #endif
2506 #ifndef OPENSSL_NO_ECDSA
2507                         case TLSEXT_signature_ecdsa:
2508                         idx = SSL_PKEY_ECC;
2509                         break;
2510 #endif
2511                         default:
2512                         continue;
2513                         }
2514
2515                 if (c->pkeys[idx].digest == NULL)
2516                         {
2517                         md = tls12_get_hash(hash_alg);
2518                         if (md)
2519                                 {
2520                                 c->pkeys[idx].digest = md;
2521                                 if (idx == SSL_PKEY_RSA_SIGN)
2522                                         c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
2523                                 }
2524                         }
2525
2526                 }
2527
2528
2529         /* Set any remaining keys to default values. NOTE: if alg is not
2530          * supported it stays as NULL.
2531          */
2532 #ifndef OPENSSL_NO_DSA
2533         if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
2534                 c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
2535 #endif
2536 #ifndef OPENSSL_NO_RSA
2537         if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
2538                 {
2539                 c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
2540                 c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
2541                 }
2542 #endif
2543 #ifndef OPENSSL_NO_ECDSA
2544         if (!c->pkeys[SSL_PKEY_ECC].digest)
2545                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
2546 #endif
2547         return 1;
2548         }
2549
2550 #endif
2551
2552 #ifndef OPENSSL_NO_HEARTBEATS
2553 int
2554 tls1_process_heartbeat(SSL *s)
2555         {
2556         unsigned char *p = &s->s3->rrec.data[0], *pl;
2557         unsigned short hbtype;
2558         unsigned int payload;
2559         unsigned int padding = 16; /* Use minimum padding */
2560
2561         /* Read type and payload length first */
2562         hbtype = *p++;
2563         n2s(p, payload);
2564         pl = p;
2565
2566         if (s->msg_callback)
2567                 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
2568                         &s->s3->rrec.data[0], s->s3->rrec.length,
2569                         s, s->msg_callback_arg);
2570
2571         if (hbtype == TLS1_HB_REQUEST)
2572                 {
2573                 unsigned char *buffer, *bp;
2574                 int r;
2575
2576                 /* Allocate memory for the response, size is 1 bytes
2577                  * message type, plus 2 bytes payload length, plus
2578                  * payload, plus padding
2579                  */
2580                 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
2581                 bp = buffer;
2582                 
2583                 /* Enter response type, length and copy payload */
2584                 *bp++ = TLS1_HB_RESPONSE;
2585                 s2n(payload, bp);
2586                 memcpy(bp, pl, payload);
2587                 bp += payload;
2588                 /* Random padding */
2589                 RAND_pseudo_bytes(bp, padding);
2590
2591                 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
2592
2593                 if (r >= 0 && s->msg_callback)
2594                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
2595                                 buffer, 3 + payload + padding,
2596                                 s, s->msg_callback_arg);
2597
2598                 OPENSSL_free(buffer);
2599
2600                 if (r < 0)
2601                         return r;
2602                 }
2603         else if (hbtype == TLS1_HB_RESPONSE)
2604                 {
2605                 unsigned int seq;
2606                 
2607                 /* We only send sequence numbers (2 bytes unsigned int),
2608                  * and 16 random bytes, so we just try to read the
2609                  * sequence number */
2610                 n2s(pl, seq);
2611                 
2612                 if (payload == 18 && seq == s->tlsext_hb_seq)
2613                         {
2614                         s->tlsext_hb_seq++;
2615                         s->tlsext_hb_pending = 0;
2616                         }
2617                 }
2618
2619         return 0;
2620         }
2621
2622 int
2623 tls1_heartbeat(SSL *s)
2624         {
2625         unsigned char *buf, *p;
2626         int ret;
2627         unsigned int payload = 18; /* Sequence number + random bytes */
2628         unsigned int padding = 16; /* Use minimum padding */
2629
2630         /* Only send if peer supports and accepts HB requests... */
2631         if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
2632             s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
2633                 {
2634                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
2635                 return -1;
2636                 }
2637
2638         /* ...and there is none in flight yet... */
2639         if (s->tlsext_hb_pending)
2640                 {
2641                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
2642                 return -1;
2643                 }
2644                 
2645         /* ...and no handshake in progress. */
2646         if (SSL_in_init(s) || s->in_handshake)
2647                 {
2648                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
2649                 return -1;
2650                 }
2651                 
2652         /* Check if padding is too long, payload and padding
2653          * must not exceed 2^14 - 3 = 16381 bytes in total.
2654          */
2655         OPENSSL_assert(payload + padding <= 16381);
2656
2657         /* Create HeartBeat message, we just use a sequence number
2658          * as payload to distuingish different messages and add
2659          * some random stuff.
2660          *  - Message Type, 1 byte
2661          *  - Payload Length, 2 bytes (unsigned int)
2662          *  - Payload, the sequence number (2 bytes uint)
2663          *  - Payload, random bytes (16 bytes uint)
2664          *  - Padding
2665          */
2666         buf = OPENSSL_malloc(1 + 2 + payload + padding);
2667         p = buf;
2668         /* Message Type */
2669         *p++ = TLS1_HB_REQUEST;
2670         /* Payload length (18 bytes here) */
2671         s2n(payload, p);
2672         /* Sequence number */
2673         s2n(s->tlsext_hb_seq, p);
2674         /* 16 random bytes */
2675         RAND_pseudo_bytes(p, 16);
2676         p += 16;
2677         /* Random padding */
2678         RAND_pseudo_bytes(p, padding);
2679
2680         ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
2681         if (ret >= 0)
2682                 {
2683                 if (s->msg_callback)
2684                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
2685                                 buf, 3 + payload + padding,
2686                                 s, s->msg_callback_arg);
2687
2688                 s->tlsext_hb_pending = 1;
2689                 }
2690                 
2691         OPENSSL_free(buf);
2692
2693         return ret;
2694         }
2695 #endif