Add three Suite B modes to TLS code, supporting RFC6460.
[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 static int ssl_check_clienthello_tlsext_early(SSL *s);
127 int ssl_check_serverhello_tlsext(SSL *s);
128 #endif
129
130 SSL3_ENC_METHOD TLSv1_enc_data={
131         tls1_enc,
132         tls1_mac,
133         tls1_setup_key_block,
134         tls1_generate_master_secret,
135         tls1_change_cipher_state,
136         tls1_final_finish_mac,
137         TLS1_FINISH_MAC_LENGTH,
138         tls1_cert_verify_mac,
139         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
140         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
141         tls1_alert_code,
142         tls1_export_keying_material,
143         };
144
145 long tls1_default_timeout(void)
146         {
147         /* 2 hours, the 24 hours mentioned in the TLSv1 spec
148          * is way too long for http, the cache would over fill */
149         return(60*60*2);
150         }
151
152 int tls1_new(SSL *s)
153         {
154         if (!ssl3_new(s)) return(0);
155         s->method->ssl_clear(s);
156         return(1);
157         }
158
159 void tls1_free(SSL *s)
160         {
161 #ifndef OPENSSL_NO_TLSEXT
162         if (s->tlsext_session_ticket)
163                 {
164                 OPENSSL_free(s->tlsext_session_ticket);
165                 }
166 #endif /* OPENSSL_NO_TLSEXT */
167         ssl3_free(s);
168         }
169
170 void tls1_clear(SSL *s)
171         {
172         ssl3_clear(s);
173         s->version = s->method->version;
174         }
175
176 #ifndef OPENSSL_NO_EC
177
178 static int nid_list[] =
179         {
180                 NID_sect163k1, /* sect163k1 (1) */
181                 NID_sect163r1, /* sect163r1 (2) */
182                 NID_sect163r2, /* sect163r2 (3) */
183                 NID_sect193r1, /* sect193r1 (4) */ 
184                 NID_sect193r2, /* sect193r2 (5) */ 
185                 NID_sect233k1, /* sect233k1 (6) */
186                 NID_sect233r1, /* sect233r1 (7) */ 
187                 NID_sect239k1, /* sect239k1 (8) */ 
188                 NID_sect283k1, /* sect283k1 (9) */
189                 NID_sect283r1, /* sect283r1 (10) */ 
190                 NID_sect409k1, /* sect409k1 (11) */ 
191                 NID_sect409r1, /* sect409r1 (12) */
192                 NID_sect571k1, /* sect571k1 (13) */ 
193                 NID_sect571r1, /* sect571r1 (14) */ 
194                 NID_secp160k1, /* secp160k1 (15) */
195                 NID_secp160r1, /* secp160r1 (16) */ 
196                 NID_secp160r2, /* secp160r2 (17) */ 
197                 NID_secp192k1, /* secp192k1 (18) */
198                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
199                 NID_secp224k1, /* secp224k1 (20) */ 
200                 NID_secp224r1, /* secp224r1 (21) */
201                 NID_secp256k1, /* secp256k1 (22) */ 
202                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
203                 NID_secp384r1, /* secp384r1 (24) */
204                 NID_secp521r1  /* secp521r1 (25) */     
205         };
206
207
208 static const unsigned char ecformats_default[] = 
209         {
210         TLSEXT_ECPOINTFORMAT_uncompressed,
211         TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
212         TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
213         };
214
215 static const unsigned char eccurves_default[] =
216         {
217                 0,14, /* sect571r1 (14) */ 
218                 0,13, /* sect571k1 (13) */ 
219                 0,25, /* secp521r1 (25) */      
220                 0,11, /* sect409k1 (11) */ 
221                 0,12, /* sect409r1 (12) */
222                 0,24, /* secp384r1 (24) */
223                 0,9,  /* sect283k1 (9) */
224                 0,10, /* sect283r1 (10) */ 
225                 0,22, /* secp256k1 (22) */ 
226                 0,23, /* secp256r1 (23) */ 
227                 0,8,  /* sect239k1 (8) */ 
228                 0,6,  /* sect233k1 (6) */
229                 0,7,  /* sect233r1 (7) */ 
230                 0,20, /* secp224k1 (20) */ 
231                 0,21, /* secp224r1 (21) */
232                 0,4,  /* sect193r1 (4) */ 
233                 0,5,  /* sect193r2 (5) */ 
234                 0,18, /* secp192k1 (18) */
235                 0,19, /* secp192r1 (19) */ 
236                 0,1,  /* sect163k1 (1) */
237                 0,2,  /* sect163r1 (2) */
238                 0,3,  /* sect163r2 (3) */
239                 0,15, /* secp160k1 (15) */
240                 0,16, /* secp160r1 (16) */ 
241                 0,17, /* secp160r2 (17) */ 
242         };
243
244 static const unsigned char suiteb_curves[] =
245         {
246                 0, TLSEXT_curve_P_256,
247                 0, TLSEXT_curve_P_384
248         };
249
250 int tls1_ec_curve_id2nid(int curve_id)
251         {
252         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
253         if ((curve_id < 1) || ((unsigned int)curve_id >
254                                 sizeof(nid_list)/sizeof(nid_list[0])))
255                 return 0;
256         return nid_list[curve_id-1];
257         }
258
259 int tls1_ec_nid2curve_id(int nid)
260         {
261         /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
262         switch (nid)
263                 {
264         case NID_sect163k1: /* sect163k1 (1) */
265                 return 1;
266         case NID_sect163r1: /* sect163r1 (2) */
267                 return 2;
268         case NID_sect163r2: /* sect163r2 (3) */
269                 return 3;
270         case NID_sect193r1: /* sect193r1 (4) */ 
271                 return 4;
272         case NID_sect193r2: /* sect193r2 (5) */ 
273                 return 5;
274         case NID_sect233k1: /* sect233k1 (6) */
275                 return 6;
276         case NID_sect233r1: /* sect233r1 (7) */ 
277                 return 7;
278         case NID_sect239k1: /* sect239k1 (8) */ 
279                 return 8;
280         case NID_sect283k1: /* sect283k1 (9) */
281                 return 9;
282         case NID_sect283r1: /* sect283r1 (10) */ 
283                 return 10;
284         case NID_sect409k1: /* sect409k1 (11) */ 
285                 return 11;
286         case NID_sect409r1: /* sect409r1 (12) */
287                 return 12;
288         case NID_sect571k1: /* sect571k1 (13) */ 
289                 return 13;
290         case NID_sect571r1: /* sect571r1 (14) */ 
291                 return 14;
292         case NID_secp160k1: /* secp160k1 (15) */
293                 return 15;
294         case NID_secp160r1: /* secp160r1 (16) */ 
295                 return 16;
296         case NID_secp160r2: /* secp160r2 (17) */ 
297                 return 17;
298         case NID_secp192k1: /* secp192k1 (18) */
299                 return 18;
300         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
301                 return 19;
302         case NID_secp224k1: /* secp224k1 (20) */ 
303                 return 20;
304         case NID_secp224r1: /* secp224r1 (21) */
305                 return 21;
306         case NID_secp256k1: /* secp256k1 (22) */ 
307                 return 22;
308         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
309                 return 23;
310         case NID_secp384r1: /* secp384r1 (24) */
311                 return 24;
312         case NID_secp521r1:  /* secp521r1 (25) */       
313                 return 25;
314         default:
315                 return 0;
316                 }
317         }
318 /* Get curves list, if "sess" is set return client curves otherwise
319  * preferred list
320  */
321 static void tls1_get_curvelist(SSL *s, int sess,
322                                         const unsigned char **pcurves,
323                                         size_t *pcurveslen)
324         {
325         if (sess)
326                 {
327                 *pcurves = s->session->tlsext_ellipticcurvelist;
328                 *pcurveslen = s->session->tlsext_ellipticcurvelist_length;
329                 return;
330                 }
331         /* For Suite B mode only include P-256, P-384 */
332         switch (tls1_suiteb(s))
333                 {
334         case SSL_CERT_FLAG_SUITEB_128_LOS:
335                 *pcurves = suiteb_curves;
336                 *pcurveslen = sizeof(suiteb_curves);
337                 break;
338
339         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
340                 *pcurves = suiteb_curves;
341                 *pcurveslen = 2;
342                 break;
343
344         case SSL_CERT_FLAG_SUITEB_192_LOS:
345                 *pcurves = suiteb_curves + 2;
346                 *pcurveslen = 2;
347                 break;
348         default:
349                 *pcurves = s->tlsext_ellipticcurvelist;
350                 *pcurveslen = s->tlsext_ellipticcurvelist_length;
351                 }
352         if (!*pcurves)
353                 {
354                 *pcurves = eccurves_default;
355                 *pcurveslen = sizeof(eccurves_default);
356                 }
357         }
358 /* Check a curve is one of our preferences */
359 int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
360         {
361         const unsigned char *curves;
362         size_t curveslen, i;
363         unsigned int suiteb_flags = tls1_suiteb(s);
364         if (len != 3 || p[0] != NAMED_CURVE_TYPE)
365                 return 0;
366         /* Check curve matches Suite B preferences */
367         if (suiteb_flags)
368                 {
369                 unsigned long cid = s->s3->tmp.new_cipher->id;
370                 if (p[1])
371                         return 0;
372                 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
373                         {
374                         if (p[2] != TLSEXT_curve_P_256)
375                                 return 0;
376                         }
377                 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
378                         {
379                         if (p[2] != TLSEXT_curve_P_384)
380                                 return 0;
381                         }
382                 else    /* Should never happen */
383                         return 0;
384                 }
385         tls1_get_curvelist(s, 0, &curves, &curveslen);
386         for (i = 0; i < curveslen; i += 2, curves += 2)
387                 {
388                 if (p[1] == curves[0] && p[2] == curves[1])
389                         return 1;
390                 }
391         return 0;
392         }
393
394 /* Return nth shared curve. If nmatch == -1 return number of
395  * matches. For nmatch == -2 return the NID of the curve to use for
396  * an EC tmp key.
397  */
398
399 int tls1_shared_curve(SSL *s, int nmatch)
400         {
401         const unsigned char *pref, *supp;
402         size_t preflen, supplen, i, j;
403         int k;
404         /* Can't do anything on client side */
405         if (s->server == 0)
406                 return -1;
407         if (nmatch == -2)
408                 {
409                 if (tls1_suiteb(s))
410                         {
411                         /* For Suite B ciphersuite determines curve: we 
412                          * already know these are acceptable due to previous
413                          * checks.
414                          */
415                         unsigned long cid = s->s3->tmp.new_cipher->id;
416                         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
417                                 return NID_X9_62_prime256v1; /* P-256 */
418                         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
419                                 return NID_secp384r1; /* P-384 */
420                         /* Should never happen */
421                         return NID_undef;
422                         }
423                 /* If not Suite B just return first preference shared curve */
424                 nmatch = 0;
425                 }
426         tls1_get_curvelist(s, !!(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
427                                 &supp, &supplen);
428         tls1_get_curvelist(s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
429                                 &pref, &preflen);
430         preflen /= 2;
431         supplen /= 2;
432         k = 0;
433         for (i = 0; i < preflen; i++, pref+=2)
434                 {
435                 const unsigned char *tsupp = supp;
436                 for (j = 0; j < supplen; j++, tsupp+=2)
437                         {
438                         if (pref[0] == tsupp[0] && pref[1] == tsupp[1])
439                                 {
440                                 if (nmatch == k)
441                                         {
442                                         int id = (pref[0] << 8) | pref[1];
443                                         return tls1_ec_curve_id2nid(id);
444                                         }
445                                 k++;
446                                 }
447                         }
448                 }
449         if (nmatch == -1)
450                 return k;
451         return 0;
452         }
453
454 int tls1_set_curves(unsigned char **pext, size_t *pextlen,
455                         int *curves, size_t ncurves)
456         {
457         unsigned char *clist, *p;
458         size_t i;
459         /* Bitmap of curves included to detect duplicates: only works
460          * while curve ids < 32 
461          */
462         unsigned long dup_list = 0;
463         clist = OPENSSL_malloc(ncurves * 2);
464         if (!clist)
465                 return 0;
466         for (i = 0, p = clist; i < ncurves; i++)
467                 {
468                 unsigned long idmask;
469                 int id;
470                 id = tls1_ec_nid2curve_id(curves[i]);
471                 idmask = 1L << id;
472                 if (!id || (dup_list & idmask))
473                         {
474                         OPENSSL_free(clist);
475                         return 0;
476                         }
477                 dup_list |= idmask;
478                 s2n(id, p);
479                 }
480         if (*pext)
481                 OPENSSL_free(*pext);
482         *pext = clist;
483         *pextlen = ncurves * 2;
484         return 1;
485         }
486
487 #define MAX_CURVELIST   25
488
489 typedef struct
490         {
491         size_t nidcnt;
492         int nid_arr[MAX_CURVELIST];
493         } nid_cb_st;
494
495 static int nid_cb(const char *elem, int len, void *arg)
496         {
497         nid_cb_st *narg = arg;
498         size_t i;
499         int nid;
500         char etmp[20];
501         if (narg->nidcnt == MAX_CURVELIST)
502                 return 0;
503         if (len > (int)(sizeof(etmp) - 1))
504                 return 0;
505         memcpy(etmp, elem, len);
506         etmp[len] = 0;
507         nid = EC_curve_nist2nid(etmp);
508         if (nid == NID_undef)
509                 nid = OBJ_sn2nid(etmp);
510         if (nid == NID_undef)
511                 nid = OBJ_ln2nid(etmp);
512         if (nid == NID_undef)
513                 return 0;
514         for (i = 0; i < narg->nidcnt; i++)
515                 if (narg->nid_arr[i] == nid)
516                         return 0;
517         narg->nid_arr[narg->nidcnt++] = nid;
518         return 1;
519         }
520 /* Set curves based on a colon separate list */
521 int tls1_set_curves_list(unsigned char **pext, size_t *pextlen, 
522                                 const char *str)
523         {
524         nid_cb_st ncb;
525         ncb.nidcnt = 0;
526         if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
527                 return 0;
528         return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
529         }
530 /* For an EC key set TLS id and required compression based on parameters */
531 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
532                                 EC_KEY *ec)
533         {
534         int is_prime, id;
535         const EC_GROUP *grp;
536         const EC_POINT *pt;
537         const EC_METHOD *meth;
538         if (!ec)
539                 return 0;
540         /* Determine if it is a prime field */
541         grp = EC_KEY_get0_group(ec);
542         pt = EC_KEY_get0_public_key(ec);
543         if (!grp || !pt)
544                 return 0;
545         meth = EC_GROUP_method_of(grp);
546         if (!meth)
547                 return 0;
548         if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
549                 is_prime = 1;
550         else
551                 is_prime = 0;
552         /* Determine curve ID */
553         id = EC_GROUP_get_curve_name(grp);
554         id = tls1_ec_nid2curve_id(id);
555         /* If we have an ID set it, otherwise set arbitrary explicit curve */
556         if (id)
557                 {
558                 curve_id[0] = 0;
559                 curve_id[1] = (unsigned char)id;
560                 }
561         else
562                 {
563                 curve_id[0] = 0xff;
564                 if (is_prime)
565                         curve_id[1] = 0x01;
566                 else
567                         curve_id[1] = 0x02;
568                 }
569         if (comp_id)
570                 {
571                 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
572                         {
573                         if (is_prime)
574                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
575                         else
576                                 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
577                         }
578                 else
579                         *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
580                 }
581         return 1;
582         }
583 /* Check an EC key is compatible with extensions */
584 static int tls1_check_ec_key(SSL *s,
585                         unsigned char *curve_id, unsigned char *comp_id)
586         {
587         const unsigned char *p;
588         size_t plen, i;
589         int j;
590         /* If point formats extension present check it, otherwise everything
591          * is supported (see RFC4492).
592          */
593         if (comp_id && s->session->tlsext_ecpointformatlist)
594                 {
595                 p = s->session->tlsext_ecpointformatlist;
596                 plen = s->session->tlsext_ecpointformatlist_length;
597                 for (i = 0; i < plen; i++, p++)
598                         {
599                         if (*comp_id == *p)
600                                 break;
601                         }
602                 if (i == plen)
603                         return 0;
604                 }
605         if (!curve_id)
606                 return 1;
607         /* Check curve is consistent with client and server preferences */
608         for (j = 0; j <= 1; j++)
609                 {
610                 tls1_get_curvelist(s, j, &p, &plen);
611                 for (i = 0; i < plen; i+=2, p+=2)
612                         {
613                         if (p[0] == curve_id[0] && p[1] == curve_id[1])
614                                 break;
615                         }
616                 if (i == plen)
617                         return 0;
618                 /* For clients can only check sent curve list */
619                 if (!s->server)
620                         return 1;
621                 }
622         return 1;
623         }
624
625 /* Check cert parameters compatible with extensions: currently just checks
626  * EC certificates have compatible curves and compression.
627  */
628 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
629         {
630         unsigned char comp_id, curve_id[2];
631         EVP_PKEY *pkey;
632         int rv;
633         pkey = X509_get_pubkey(x);
634         if (!pkey)
635                 return 0;
636         /* If not EC nothing to do */
637         if (pkey->type != EVP_PKEY_EC)
638                 {
639                 EVP_PKEY_free(pkey);
640                 return 1;
641                 }
642         rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
643         EVP_PKEY_free(pkey);
644         if (!rv)
645                 return 0;
646         /* Can't check curve_id for client certs as we don't have a
647          * supported curves extension.
648          */
649         rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
650         if (!rv)
651                 return 0;
652         /* Special case for suite B. We *MUST* sign using SHA256+P-256 or
653          * SHA384+P-384, adjust digest if necessary.
654          */
655         if (set_ee_md && tls1_suiteb(s))
656                 {
657                 int check_md;
658                 size_t i;
659                 CERT *c = s->cert;
660                 if (curve_id[0])
661                         return 0;
662                 /* Check to see we have necessary signing algorithm */
663                 if (curve_id[1] == TLSEXT_curve_P_256)
664                         check_md = NID_ecdsa_with_SHA256;
665                 else if (curve_id[1] == TLSEXT_curve_P_384)
666                         check_md = NID_ecdsa_with_SHA384;
667                 else
668                         return 0; /* Should never happen */
669                 for (i = 0; i < c->shared_sigalgslen; i++)
670                         if (check_md == c->shared_sigalgs[i].signandhash_nid)
671                                 break;
672                 if (i == c->shared_sigalgslen)
673                         return 0;
674                 if (set_ee_md == 2)
675                         {
676                         if (check_md == NID_ecdsa_with_SHA256)
677                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
678                         else
679                                 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
680                         }
681                 }
682         return rv;
683         }
684 /* Check EC temporary key is compatible with client extensions */
685 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
686         {
687         unsigned char curve_id[2];
688         EC_KEY *ec = s->cert->ecdh_tmp;
689         /* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384,
690          * no other curves permitted.
691          */
692         if (tls1_suiteb(s))
693                 {
694                 /* Curve to check determined by ciphersuite */
695                 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
696                         curve_id[1] = TLSEXT_curve_P_256;
697                 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
698                         curve_id[1] = TLSEXT_curve_P_384;
699                 else
700                         return 0;
701                 curve_id[0] = 0;
702                 /* Check this curve is acceptable */
703                 if (!tls1_check_ec_key(s, curve_id, NULL))
704                         return 0;
705                 /* If auto or setting curve from callback assume OK */
706                 if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
707                         return 1;
708                 /* Otherwise check curve is acceptable */
709                 else 
710                         {
711                         unsigned char curve_tmp[2];
712                         if (!ec)
713                                 return 0;
714                         if (!tls1_set_ec_id(curve_tmp, NULL, ec))
715                                 return 0;
716                         if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
717                                 return 1;
718                         return 0;
719                         }
720                         
721                 }
722         if (s->cert->ecdh_tmp_auto)
723                 {
724                 /* Need a shared curve */
725                 if (tls1_shared_curve(s, 0))
726                         return 1;
727                 else return 0;
728                 }
729         if (!ec)
730                 {
731                 if (s->cert->ecdh_tmp_cb)
732                         return 1;
733                 else
734                         return 0;
735                 }
736         if (!tls1_set_ec_id(curve_id, NULL, ec))
737                 return 0;
738 /* Set this to allow use of invalid curves for testing */
739 #if 0
740         return 1;
741 #else
742         return tls1_check_ec_key(s, curve_id, NULL);
743 #endif
744         }
745
746 #endif /* OPENSSL_NO_EC */
747
748 #ifndef OPENSSL_NO_TLSEXT
749
750 /* List of supported signature algorithms and hashes. Should make this
751  * customisable at some point, for now include everything we support.
752  */
753
754 #ifdef OPENSSL_NO_RSA
755 #define tlsext_sigalg_rsa(md) /* */
756 #else
757 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
758 #endif
759
760 #ifdef OPENSSL_NO_DSA
761 #define tlsext_sigalg_dsa(md) /* */
762 #else
763 #define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
764 #endif
765
766 #ifdef OPENSSL_NO_ECDSA
767 #define tlsext_sigalg_ecdsa(md) /* */
768 #else
769 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
770 #endif
771
772 #define tlsext_sigalg(md) \
773                 tlsext_sigalg_rsa(md) \
774                 tlsext_sigalg_dsa(md) \
775                 tlsext_sigalg_ecdsa(md)
776
777 static unsigned char tls12_sigalgs[] = {
778 #ifndef OPENSSL_NO_SHA512
779         tlsext_sigalg(TLSEXT_hash_sha512)
780         tlsext_sigalg(TLSEXT_hash_sha384)
781 #endif
782 #ifndef OPENSSL_NO_SHA256
783         tlsext_sigalg(TLSEXT_hash_sha256)
784         tlsext_sigalg(TLSEXT_hash_sha224)
785 #endif
786 #ifndef OPENSSL_NO_SHA
787         tlsext_sigalg(TLSEXT_hash_sha1)
788 #endif
789 #ifndef OPENSSL_NO_MD5
790         tlsext_sigalg_rsa(TLSEXT_hash_md5)
791 #endif
792 };
793
794 static unsigned char suiteb_sigalgs[] = {
795         tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
796         tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
797 };
798
799 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
800         {
801         /* If Suite B mode use Suite B sigalgs only, ignore any other
802          * preferences.
803          */
804         switch (tls1_suiteb(s))
805                 {
806         case SSL_CERT_FLAG_SUITEB_128_LOS:
807                 *psigs = suiteb_sigalgs;
808                 return sizeof(suiteb_sigalgs);
809
810         case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
811                 *psigs = suiteb_sigalgs;
812                 return 2;
813
814         case SSL_CERT_FLAG_SUITEB_192_LOS:
815                 *psigs = suiteb_sigalgs + 2;
816                 return 2;
817                 }
818
819         /* If server use client authentication sigalgs if not NULL */
820         if (s->server && s->cert->client_sigalgs)
821                 {
822                 *psigs = s->cert->client_sigalgs;
823                 return s->cert->client_sigalgslen;
824                 }
825         else if (s->cert->conf_sigalgs)
826                 {
827                 *psigs = s->cert->conf_sigalgs;
828                 return s->cert->conf_sigalgslen;
829                 }
830         else
831                 {
832                 *psigs = tls12_sigalgs;
833 #ifdef OPENSSL_FIPS
834                 /* If FIPS mode don't include MD5 which is last */
835                 if (FIPS_mode())
836                         return sizeof(tls12_sigalgs) - 2;
837                 else
838 #endif
839                         return sizeof(tls12_sigalgs);
840                 }
841         }
842 /* Check signature algorithm is consistent with sent supported signature
843  * algorithms and if so return relevant digest.
844  */
845 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
846                                 const unsigned char *sig, EVP_PKEY *pkey)
847         {
848         const unsigned char *sent_sigs;
849         size_t sent_sigslen, i;
850         int sigalg = tls12_get_sigid(pkey);
851         /* Should never happen */
852         if (sigalg == -1)
853                 return -1;
854         /* Check key type is consistent with signature */
855         if (sigalg != (int)sig[1])
856                 {
857                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
858                 return 0;
859                 }
860         if (pkey->type == EVP_PKEY_EC)
861                 {
862                 unsigned char curve_id[2], comp_id;
863                 /* Check compression and curve matches extensions */
864                 if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
865                         return 0;
866                 if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id))
867                         return 0;
868                 /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
869                 if (tls1_suiteb(s))
870                         {
871                         if (curve_id[0])
872                                 return 0;
873                         if (curve_id[1] == TLSEXT_curve_P_256)
874                                 {
875                                 if (sig[0] != TLSEXT_hash_sha256)
876                                         {
877                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
878                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
879                                         return 0;
880                                         }
881                                 }
882                         else if (curve_id[1] == TLSEXT_curve_P_384)
883                                 {
884                                 if (sig[0] != TLSEXT_hash_sha384)
885                                         {
886                                         SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
887                                                 SSL_R_ILLEGAL_SUITEB_DIGEST);
888                                         return 0;
889                                         }
890                                 }
891                         else
892                                 return 0;
893                         }
894                 }
895         else if (tls1_suiteb(s))
896                 return 0;
897
898         /* Check signature matches a type we sent */
899         sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
900         for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
901                 {
902                 if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
903                         break;
904                 }
905         /* Allow fallback to SHA1 if not strict mode */
906         if (i == sent_sigslen && (sig[0] != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
907                 {
908                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
909                 return 0;
910                 }
911         *pmd = tls12_get_hash(sig[0]);
912         if (*pmd == NULL)
913                 {
914                 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_UNKNOWN_DIGEST);
915                 return 0;
916                 }
917         return 1;
918         }
919 /* Get a mask of disabled algorithms: an algorithm is disabled
920  * if it isn't supported or doesn't appear in supported signature
921  * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
922  * session and not global settings.
923  * 
924  */
925 void ssl_set_client_disabled(SSL *s)
926         {
927         CERT *c = s->cert;
928         const unsigned char *sigalgs;
929         size_t i, sigalgslen;
930         int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
931         c->mask_a = 0;
932         c->mask_k = 0;
933         /* If less than TLS 1.2 don't allow TLS 1.2 only ciphers */
934         if (TLS1_get_version(s) < TLS1_2_VERSION)
935                 c->mask_ssl = SSL_TLSV1_2;
936         else
937                 c->mask_ssl = 0;
938         /* Now go through all signature algorithms seeing if we support
939          * any for RSA, DSA, ECDSA. Do this for all versions not just
940          * TLS 1.2.
941          */
942         sigalgslen = tls12_get_psigalgs(s, &sigalgs);
943         for (i = 0; i < sigalgslen; i += 2, sigalgs += 2)
944                 {
945                 switch(sigalgs[1])
946                         {
947 #ifndef OPENSSL_NO_RSA
948                 case TLSEXT_signature_rsa:
949                         have_rsa = 1;
950                         break;
951 #endif
952 #ifndef OPENSSL_NO_DSA
953                 case TLSEXT_signature_dsa:
954                         have_dsa = 1;
955                         break;
956 #endif
957 #ifndef OPENSSL_NO_ECDSA
958                 case TLSEXT_signature_ecdsa:
959                         have_ecdsa = 1;
960                         break;
961 #endif
962                         }
963                 }
964         /* Disable auth and static DH if we don't include any appropriate
965          * signature algorithms.
966          */
967         if (!have_rsa)
968                 {
969                 c->mask_a |= SSL_aRSA;
970                 c->mask_k |= SSL_kDHr|SSL_kECDHr;
971                 }
972         if (!have_dsa)
973                 {
974                 c->mask_a |= SSL_aDSS;
975                 c->mask_k |= SSL_kDHd;
976                 }
977         if (!have_ecdsa)
978                 {
979                 c->mask_a |= SSL_aECDSA;
980                 c->mask_k |= SSL_kECDHe;
981                 }
982 #ifndef OPENSSL_NO_KRB5
983         if (!kssl_tgt_is_available(s->kssl_ctx))
984                 {
985                 c->mask_a |= SSL_aKRB5;
986                 c->mask_k |= SSL_kKRB5;
987                 }
988 #endif
989 #ifndef OPENSSL_NO_PSK
990         /* with PSK there must be client callback set */
991         if (!s->psk_client_callback)
992                 {
993                 c->mask_a |= SSL_aPSK;
994                 c->mask_k |= SSL_kPSK;
995                 }
996 #endif /* OPENSSL_NO_PSK */
997         c->valid = 1;
998         }
999
1000 /* byte_compare is a compare function for qsort(3) that compares bytes. */
1001 static int byte_compare(const void *in_a, const void *in_b)
1002         {
1003         unsigned char a = *((const unsigned char*) in_a);
1004         unsigned char b = *((const unsigned char*) in_b);
1005
1006         if (a > b)
1007                 return 1;
1008         else if (a < b)
1009                 return -1;
1010         return 0;
1011 }
1012
1013 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1014         {
1015         int extdatalen=0;
1016         unsigned char *ret = p;
1017 #ifndef OPENSSL_NO_EC
1018         /* See if we support any ECC ciphersuites */
1019         int using_ecc = 0;
1020         if (s->version != DTLS1_VERSION && s->version >= TLS1_VERSION)
1021                 {
1022                 int i;
1023                 unsigned long alg_k, alg_a;
1024                 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1025
1026                 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1027                         {
1028                         SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1029
1030                         alg_k = c->algorithm_mkey;
1031                         alg_a = c->algorithm_auth;
1032                         if ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)
1033                                 || (alg_a & SSL_aECDSA)))
1034                                 {
1035                                 using_ecc = 1;
1036                                 break;
1037                                 }
1038                         }
1039                 }
1040 #endif
1041
1042         /* don't add extensions for SSLv3 unless doing secure renegotiation */
1043         if (s->client_version == SSL3_VERSION
1044                                         && !s->s3->send_connection_binding)
1045                 return p;
1046
1047         ret+=2;
1048
1049         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1050
1051         if (s->tlsext_hostname != NULL)
1052                 { 
1053                 /* Add TLS extension servername to the Client Hello message */
1054                 unsigned long size_str;
1055                 long lenmax; 
1056
1057                 /* check for enough space.
1058                    4 for the servername type and entension length
1059                    2 for servernamelist length
1060                    1 for the hostname type
1061                    2 for hostname length
1062                    + hostname length 
1063                 */
1064                    
1065                 if ((lenmax = limit - ret - 9) < 0 
1066                     || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) 
1067                         return NULL;
1068                         
1069                 /* extension type and length */
1070                 s2n(TLSEXT_TYPE_server_name,ret); 
1071                 s2n(size_str+5,ret);
1072                 
1073                 /* length of servername list */
1074                 s2n(size_str+3,ret);
1075         
1076                 /* hostname type, length and hostname */
1077                 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
1078                 s2n(size_str,ret);
1079                 memcpy(ret, s->tlsext_hostname, size_str);
1080                 ret+=size_str;
1081                 }
1082
1083         /* Add RI if renegotiating */
1084         if (s->renegotiate)
1085           {
1086           int el;
1087           
1088           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
1089               {
1090               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1091               return NULL;
1092               }
1093
1094           if((limit - p - 4 - el) < 0) return NULL;
1095           
1096           s2n(TLSEXT_TYPE_renegotiate,ret);
1097           s2n(el,ret);
1098
1099           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
1100               {
1101               SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1102               return NULL;
1103               }
1104
1105           ret += el;
1106         }
1107
1108 #ifndef OPENSSL_NO_SRP
1109         /* Add SRP username if there is one */
1110         if (s->srp_ctx.login != NULL)
1111                 { /* Add TLS extension SRP username to the Client Hello message */
1112
1113                 int login_len = strlen(s->srp_ctx.login);       
1114                 if (login_len > 255 || login_len == 0)
1115                         {
1116                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1117                         return NULL;
1118                         } 
1119
1120                 /* check for enough space.
1121                    4 for the srp type type and entension length
1122                    1 for the srp user identity
1123                    + srp user identity length 
1124                 */
1125                 if ((limit - ret - 5 - login_len) < 0) return NULL; 
1126
1127                 /* fill in the extension */
1128                 s2n(TLSEXT_TYPE_srp,ret);
1129                 s2n(login_len+1,ret);
1130                 (*ret++) = (unsigned char) login_len;
1131                 memcpy(ret, s->srp_ctx.login, login_len);
1132                 ret+=login_len;
1133                 }
1134 #endif
1135
1136 #ifndef OPENSSL_NO_EC
1137         if (using_ecc)
1138                 {
1139                 /* Add TLS extension ECPointFormats to the ClientHello message */
1140                 long lenmax; 
1141                 const unsigned char *plist;
1142                 size_t plistlen;
1143                 /* If we have a custom point format list use it otherwise
1144                  * use default */
1145                 plist = s->tlsext_ecpointformatlist;
1146                 if (plist)
1147                         plistlen = s->tlsext_ecpointformatlist_length;
1148                 else
1149                         {
1150                         plist = ecformats_default;
1151                         plistlen = sizeof(ecformats_default);
1152                         }
1153
1154                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1155                 if (plistlen > (size_t)lenmax) return NULL;
1156                 if (plistlen > 255)
1157                         {
1158                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1159                         return NULL;
1160                         }
1161                 
1162                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1163                 s2n(plistlen + 1,ret);
1164                 *(ret++) = (unsigned char)plistlen ;
1165                 memcpy(ret, plist, plistlen);
1166                 ret+=plistlen;
1167
1168                 /* Add TLS extension EllipticCurves to the ClientHello message */
1169                 plist = s->tlsext_ellipticcurvelist;
1170                 tls1_get_curvelist(s, 0, &plist, &plistlen);
1171
1172                 if ((lenmax = limit - ret - 6) < 0) return NULL; 
1173                 if (plistlen > (size_t)lenmax) return NULL;
1174                 if (plistlen > 65532)
1175                         {
1176                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1177                         return NULL;
1178                         }
1179                 
1180                 s2n(TLSEXT_TYPE_elliptic_curves,ret);
1181                 s2n(plistlen + 2, ret);
1182
1183                 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
1184                  * elliptic_curve_list, but the examples use two bytes.
1185                  * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
1186                  * resolves this to two bytes.
1187                  */
1188                 s2n(plistlen, ret);
1189                 memcpy(ret, plist, plistlen);
1190                 ret+=plistlen;
1191                 }
1192 #endif /* OPENSSL_NO_EC */
1193
1194         if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
1195                 {
1196                 int ticklen;
1197                 if (!s->new_session && s->session && s->session->tlsext_tick)
1198                         ticklen = s->session->tlsext_ticklen;
1199                 else if (s->session && s->tlsext_session_ticket &&
1200                          s->tlsext_session_ticket->data)
1201                         {
1202                         ticklen = s->tlsext_session_ticket->length;
1203                         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1204                         if (!s->session->tlsext_tick)
1205                                 return NULL;
1206                         memcpy(s->session->tlsext_tick,
1207                                s->tlsext_session_ticket->data,
1208                                ticklen);
1209                         s->session->tlsext_ticklen = ticklen;
1210                         }
1211                 else
1212                         ticklen = 0;
1213                 if (ticklen == 0 && s->tlsext_session_ticket &&
1214                     s->tlsext_session_ticket->data == NULL)
1215                         goto skip_ext;
1216                 /* Check for enough room 2 for extension type, 2 for len
1217                  * rest for ticket
1218                  */
1219                 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1220                 s2n(TLSEXT_TYPE_session_ticket,ret); 
1221                 s2n(ticklen,ret);
1222                 if (ticklen)
1223                         {
1224                         memcpy(ret, s->session->tlsext_tick, ticklen);
1225                         ret += ticklen;
1226                         }
1227                 }
1228                 skip_ext:
1229
1230         if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
1231                 {
1232                 size_t salglen;
1233                 const unsigned char *salg;
1234                 salglen = tls12_get_psigalgs(s, &salg);
1235                 if ((size_t)(limit - ret) < salglen + 6)
1236                         return NULL; 
1237                 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1238                 s2n(salglen + 2, ret);
1239                 s2n(salglen, ret);
1240                 memcpy(ret, salg, salglen);
1241                 ret += salglen;
1242                 }
1243
1244 #ifdef TLSEXT_TYPE_opaque_prf_input
1245         if (s->s3->client_opaque_prf_input != NULL &&
1246             s->version != DTLS1_VERSION)
1247                 {
1248                 size_t col = s->s3->client_opaque_prf_input_len;
1249                 
1250                 if ((long)(limit - ret - 6 - col < 0))
1251                         return NULL;
1252                 if (col > 0xFFFD) /* can't happen */
1253                         return NULL;
1254
1255                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1256                 s2n(col + 2, ret);
1257                 s2n(col, ret);
1258                 memcpy(ret, s->s3->client_opaque_prf_input, col);
1259                 ret += col;
1260                 }
1261 #endif
1262
1263         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
1264             s->version != DTLS1_VERSION)
1265                 {
1266                 int i;
1267                 long extlen, idlen, itmp;
1268                 OCSP_RESPID *id;
1269
1270                 idlen = 0;
1271                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1272                         {
1273                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1274                         itmp = i2d_OCSP_RESPID(id, NULL);
1275                         if (itmp <= 0)
1276                                 return NULL;
1277                         idlen += itmp + 2;
1278                         }
1279
1280                 if (s->tlsext_ocsp_exts)
1281                         {
1282                         extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1283                         if (extlen < 0)
1284                                 return NULL;
1285                         }
1286                 else
1287                         extlen = 0;
1288                         
1289                 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1290                 s2n(TLSEXT_TYPE_status_request, ret);
1291                 if (extlen + idlen > 0xFFF0)
1292                         return NULL;
1293                 s2n(extlen + idlen + 5, ret);
1294                 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1295                 s2n(idlen, ret);
1296                 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1297                         {
1298                         /* save position of id len */
1299                         unsigned char *q = ret;
1300                         id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1301                         /* skip over id len */
1302                         ret += 2;
1303                         itmp = i2d_OCSP_RESPID(id, &ret);
1304                         /* write id len */
1305                         s2n(itmp, q);
1306                         }
1307                 s2n(extlen, ret);
1308                 if (extlen > 0)
1309                         i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1310                 }
1311
1312 #ifndef OPENSSL_NO_HEARTBEATS
1313         /* Add Heartbeat extension */
1314         s2n(TLSEXT_TYPE_heartbeat,ret);
1315         s2n(1,ret);
1316         /* Set mode:
1317          * 1: peer may send requests
1318          * 2: peer not allowed to send requests
1319          */
1320         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1321                 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1322         else
1323                 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1324 #endif
1325
1326 #ifndef OPENSSL_NO_NEXTPROTONEG
1327         if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1328                 {
1329                 /* The client advertises an emtpy extension to indicate its
1330                  * support for Next Protocol Negotiation */
1331                 if (limit - ret - 4 < 0)
1332                         return NULL;
1333                 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1334                 s2n(0,ret);
1335                 }
1336 #endif
1337
1338         if(SSL_get_srtp_profiles(s))
1339                 {
1340                 int el;
1341
1342                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1343                 
1344                 if((limit - p - 4 - el) < 0) return NULL;
1345
1346                 s2n(TLSEXT_TYPE_use_srtp,ret);
1347                 s2n(el,ret);
1348
1349                 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1350                         {
1351                         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1352                         return NULL;
1353                         }
1354                 ret += el;
1355                 }
1356
1357         /* Add TLS extension Server_Authz_DataFormats to the ClientHello */
1358         /* 2 bytes for extension type */
1359         /* 2 bytes for extension length */
1360         /* 1 byte for the list length */
1361         /* 1 byte for the list (we only support audit proofs) */
1362         if (s->ctx->tlsext_authz_server_audit_proof_cb != NULL)
1363                 {
1364                 size_t lenmax;
1365                 const unsigned short ext_len = 2;
1366                 const unsigned char list_len = 1;
1367
1368                 if ((lenmax = limit - ret - 6) < 0) return NULL;
1369
1370                 s2n(TLSEXT_TYPE_server_authz, ret);
1371                 /* Extension length: 2 bytes */
1372                 s2n(ext_len, ret);
1373                 *(ret++) = list_len;
1374                 *(ret++) = TLSEXT_AUTHZDATAFORMAT_audit_proof;
1375                 }
1376
1377         if ((extdatalen = ret-p-2) == 0)
1378                 return p;
1379
1380         s2n(extdatalen,p);
1381         return ret;
1382         }
1383
1384 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit)
1385         {
1386         int extdatalen=0;
1387         unsigned char *ret = p;
1388 #ifndef OPENSSL_NO_NEXTPROTONEG
1389         int next_proto_neg_seen;
1390 #endif
1391
1392         /* don't add extensions for SSLv3, unless doing secure renegotiation */
1393         if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1394                 return p;
1395         
1396         ret+=2;
1397         if (ret>=limit) return NULL; /* this really never occurs, but ... */
1398
1399         if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1400                 { 
1401                 if ((long)(limit - ret - 4) < 0) return NULL; 
1402
1403                 s2n(TLSEXT_TYPE_server_name,ret);
1404                 s2n(0,ret);
1405                 }
1406
1407         if(s->s3->send_connection_binding)
1408         {
1409           int el;
1410           
1411           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1412               {
1413               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1414               return NULL;
1415               }
1416
1417           if((limit - p - 4 - el) < 0) return NULL;
1418           
1419           s2n(TLSEXT_TYPE_renegotiate,ret);
1420           s2n(el,ret);
1421
1422           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1423               {
1424               SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1425               return NULL;
1426               }
1427
1428           ret += el;
1429         }
1430
1431 #ifndef OPENSSL_NO_EC
1432         if (s->tlsext_ecpointformatlist != NULL &&
1433             s->version != DTLS1_VERSION)
1434                 {
1435                 /* Add TLS extension ECPointFormats to the ServerHello message */
1436                 long lenmax; 
1437
1438                 if ((lenmax = limit - ret - 5) < 0) return NULL; 
1439                 if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
1440                 if (s->tlsext_ecpointformatlist_length > 255)
1441                         {
1442                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1443                         return NULL;
1444                         }
1445                 
1446                 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1447                 s2n(s->tlsext_ecpointformatlist_length + 1,ret);
1448                 *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
1449                 memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
1450                 ret+=s->tlsext_ecpointformatlist_length;
1451
1452                 }
1453         /* Currently the server should not respond with a SupportedCurves extension */
1454 #endif /* OPENSSL_NO_EC */
1455
1456         if (s->tlsext_ticket_expected
1457                 && !(SSL_get_options(s) & SSL_OP_NO_TICKET)) 
1458                 { 
1459                 if ((long)(limit - ret - 4) < 0) return NULL; 
1460                 s2n(TLSEXT_TYPE_session_ticket,ret);
1461                 s2n(0,ret);
1462                 }
1463
1464         if (s->tlsext_status_expected)
1465                 { 
1466                 if ((long)(limit - ret - 4) < 0) return NULL; 
1467                 s2n(TLSEXT_TYPE_status_request,ret);
1468                 s2n(0,ret);
1469                 }
1470
1471 #ifdef TLSEXT_TYPE_opaque_prf_input
1472         if (s->s3->server_opaque_prf_input != NULL &&
1473             s->version != DTLS1_VERSION)
1474                 {
1475                 size_t sol = s->s3->server_opaque_prf_input_len;
1476                 
1477                 if ((long)(limit - ret - 6 - sol) < 0)
1478                         return NULL;
1479                 if (sol > 0xFFFD) /* can't happen */
1480                         return NULL;
1481
1482                 s2n(TLSEXT_TYPE_opaque_prf_input, ret); 
1483                 s2n(sol + 2, ret);
1484                 s2n(sol, ret);
1485                 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1486                 ret += sol;
1487                 }
1488 #endif
1489
1490         if(s->srtp_profile)
1491                 {
1492                 int el;
1493
1494                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1495                 
1496                 if((limit - p - 4 - el) < 0) return NULL;
1497
1498                 s2n(TLSEXT_TYPE_use_srtp,ret);
1499                 s2n(el,ret);
1500
1501                 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1502                         {
1503                         SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1504                         return NULL;
1505                         }
1506                 ret+=el;
1507                 }
1508
1509         if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81) 
1510                 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1511                 { const unsigned char cryptopro_ext[36] = {
1512                         0xfd, 0xe8, /*65000*/
1513                         0x00, 0x20, /*32 bytes length*/
1514                         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 
1515                         0x03,   0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 
1516                         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 
1517                         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1518                         if (limit-ret<36) return NULL;
1519                         memcpy(ret,cryptopro_ext,36);
1520                         ret+=36;
1521
1522                 }
1523
1524 #ifndef OPENSSL_NO_HEARTBEATS
1525         /* Add Heartbeat extension if we've received one */
1526         if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1527                 {
1528                 s2n(TLSEXT_TYPE_heartbeat,ret);
1529                 s2n(1,ret);
1530                 /* Set mode:
1531                  * 1: peer may send requests
1532                  * 2: peer not allowed to send requests
1533                  */
1534                 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1535                         *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1536                 else
1537                         *(ret++) = SSL_TLSEXT_HB_ENABLED;
1538
1539                 }
1540 #endif
1541
1542 #ifndef OPENSSL_NO_NEXTPROTONEG
1543         next_proto_neg_seen = s->s3->next_proto_neg_seen;
1544         s->s3->next_proto_neg_seen = 0;
1545         if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1546                 {
1547                 const unsigned char *npa;
1548                 unsigned int npalen;
1549                 int r;
1550
1551                 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1552                 if (r == SSL_TLSEXT_ERR_OK)
1553                         {
1554                         if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1555                         s2n(TLSEXT_TYPE_next_proto_neg,ret);
1556                         s2n(npalen,ret);
1557                         memcpy(ret, npa, npalen);
1558                         ret += npalen;
1559                         s->s3->next_proto_neg_seen = 1;
1560                         }
1561                 }
1562 #endif
1563
1564         /* If the client supports authz then see whether we have any to offer
1565          * to it. */
1566         if (s->s3->tlsext_authz_client_types_len)
1567                 {
1568                 size_t authz_length;
1569                 /* By now we already know the new cipher, so we can look ahead
1570                  * to see whether the cert we are going to send
1571                  * has any authz data attached to it. */
1572                 const unsigned char* authz = ssl_get_authz_data(s, &authz_length);
1573                 const unsigned char* const orig_authz = authz;
1574                 size_t i;
1575                 unsigned authz_count = 0;
1576
1577                 /* The authz data contains a number of the following structures:
1578                  *      uint8_t authz_type
1579                  *      uint16_t length
1580                  *      uint8_t data[length]
1581                  *
1582                  * First we walk over it to find the number of authz elements. */
1583                 for (i = 0; i < authz_length; i++)
1584                         {
1585                         unsigned short length;
1586                         unsigned char type;
1587
1588                         type = *(authz++);
1589                         if (memchr(s->s3->tlsext_authz_client_types,
1590                                    type,
1591                                    s->s3->tlsext_authz_client_types_len) != NULL)
1592                                 authz_count++;
1593
1594                         n2s(authz, length);
1595                         /* n2s increments authz by 2 */
1596                         i += 2;
1597                         authz += length;
1598                         i += length;
1599                         }
1600
1601                 if (authz_count)
1602                         {
1603                         /* Add TLS extension server_authz to the ServerHello message
1604                          * 2 bytes for extension type
1605                          * 2 bytes for extension length
1606                          * 1 byte for the list length
1607                          * n bytes for the list */
1608                         const unsigned short ext_len = 1 + authz_count;
1609
1610                         if ((long)(limit - ret - 4 - ext_len) < 0) return NULL;
1611                         s2n(TLSEXT_TYPE_server_authz, ret);
1612                         s2n(ext_len, ret);
1613                         *(ret++) = authz_count;
1614                         s->s3->tlsext_authz_promised_to_client = 1;
1615                         }
1616
1617                 authz = orig_authz;
1618                 for (i = 0; i < authz_length; i++)
1619                         {
1620                         unsigned short length;
1621                         unsigned char type;
1622
1623                         authz_count++;
1624                         type = *(authz++);
1625                         if (memchr(s->s3->tlsext_authz_client_types,
1626                                    type,
1627                                    s->s3->tlsext_authz_client_types_len) != NULL)
1628                                 *(ret++) = type;
1629                         n2s(authz, length);
1630                         /* n2s increments authz by 2 */
1631                         i += 2;
1632                         authz += length;
1633                         i += length;
1634                         }
1635                 }
1636
1637         if ((extdatalen = ret-p-2)== 0) 
1638                 return p;
1639
1640         s2n(extdatalen,p);
1641         return ret;
1642         }
1643
1644 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) 
1645         {       
1646         unsigned short type;
1647         unsigned short size;
1648         unsigned short len;
1649         unsigned char *data = *p;
1650         int renegotiate_seen = 0;
1651         size_t i;
1652
1653         s->servername_done = 0;
1654         s->tlsext_status_type = -1;
1655 #ifndef OPENSSL_NO_NEXTPROTONEG
1656         s->s3->next_proto_neg_seen = 0;
1657 #endif
1658
1659 #ifndef OPENSSL_NO_HEARTBEATS
1660         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1661                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1662 #endif
1663         /* Clear any signature algorithms extension received */
1664         if (s->cert->peer_sigalgs)
1665                 {
1666                 OPENSSL_free(s->cert->peer_sigalgs);
1667                 s->cert->peer_sigalgs = NULL;
1668                 }
1669         /* Clear any shared sigtnature algorithms */
1670         if (s->cert->shared_sigalgs)
1671                 {
1672                 OPENSSL_free(s->cert->shared_sigalgs);
1673                 s->cert->shared_sigalgs = NULL;
1674                 }
1675         /* Clear certificate digests and validity flags */
1676         for (i = 0; i < SSL_PKEY_NUM; i++)
1677                 {
1678                 s->cert->pkeys[i].digest = NULL;
1679                 s->cert->pkeys[i].valid_flags = 0;
1680                 }
1681
1682         if (data >= (d+n-2))
1683                 goto ri_check;
1684         n2s(data,len);
1685
1686         if (data > (d+n-len)) 
1687                 goto ri_check;
1688
1689         while (data <= (d+n-4))
1690                 {
1691                 n2s(data,type);
1692                 n2s(data,size);
1693
1694                 if (data+size > (d+n))
1695                         goto ri_check;
1696 #if 0
1697                 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1698 #endif
1699                 if (s->tlsext_debug_cb)
1700                         s->tlsext_debug_cb(s, 0, type, data, size,
1701                                                 s->tlsext_debug_arg);
1702 /* The servername extension is treated as follows:
1703
1704    - Only the hostname type is supported with a maximum length of 255.
1705    - The servername is rejected if too long or if it contains zeros,
1706      in which case an fatal alert is generated.
1707    - The servername field is maintained together with the session cache.
1708    - When a session is resumed, the servername call back invoked in order
1709      to allow the application to position itself to the right context. 
1710    - The servername is acknowledged if it is new for a session or when 
1711      it is identical to a previously used for the same session. 
1712      Applications can control the behaviour.  They can at any time
1713      set a 'desirable' servername for a new SSL object. This can be the
1714      case for example with HTTPS when a Host: header field is received and
1715      a renegotiation is requested. In this case, a possible servername
1716      presented in the new client hello is only acknowledged if it matches
1717      the value of the Host: field. 
1718    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1719      if they provide for changing an explicit servername context for the session,
1720      i.e. when the session has been established with a servername extension. 
1721    - On session reconnect, the servername extension may be absent. 
1722
1723 */      
1724
1725                 if (type == TLSEXT_TYPE_server_name)
1726                         {
1727                         unsigned char *sdata;
1728                         int servname_type;
1729                         int dsize; 
1730                 
1731                         if (size < 2) 
1732                                 {
1733                                 *al = SSL_AD_DECODE_ERROR;
1734                                 return 0;
1735                                 }
1736                         n2s(data,dsize);  
1737                         size -= 2;
1738                         if (dsize > size  ) 
1739                                 {
1740                                 *al = SSL_AD_DECODE_ERROR;
1741                                 return 0;
1742                                 } 
1743
1744                         sdata = data;
1745                         while (dsize > 3) 
1746                                 {
1747                                 servname_type = *(sdata++); 
1748                                 n2s(sdata,len);
1749                                 dsize -= 3;
1750
1751                                 if (len > dsize) 
1752                                         {
1753                                         *al = SSL_AD_DECODE_ERROR;
1754                                         return 0;
1755                                         }
1756                                 if (s->servername_done == 0)
1757                                 switch (servname_type)
1758                                         {
1759                                 case TLSEXT_NAMETYPE_host_name:
1760                                         if (!s->hit)
1761                                                 {
1762                                                 if(s->session->tlsext_hostname)
1763                                                         {
1764                                                         *al = SSL_AD_DECODE_ERROR;
1765                                                         return 0;
1766                                                         }
1767                                                 if (len > TLSEXT_MAXLEN_host_name)
1768                                                         {
1769                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1770                                                         return 0;
1771                                                         }
1772                                                 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
1773                                                         {
1774                                                         *al = TLS1_AD_INTERNAL_ERROR;
1775                                                         return 0;
1776                                                         }
1777                                                 memcpy(s->session->tlsext_hostname, sdata, len);
1778                                                 s->session->tlsext_hostname[len]='\0';
1779                                                 if (strlen(s->session->tlsext_hostname) != len) {
1780                                                         OPENSSL_free(s->session->tlsext_hostname);
1781                                                         s->session->tlsext_hostname = NULL;
1782                                                         *al = TLS1_AD_UNRECOGNIZED_NAME;
1783                                                         return 0;
1784                                                 }
1785                                                 s->servername_done = 1; 
1786
1787                                                 }
1788                                         else 
1789                                                 s->servername_done = s->session->tlsext_hostname
1790                                                         && strlen(s->session->tlsext_hostname) == len 
1791                                                         && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
1792                                         
1793                                         break;
1794
1795                                 default:
1796                                         break;
1797                                         }
1798                                  
1799                                 dsize -= len;
1800                                 }
1801                         if (dsize != 0) 
1802                                 {
1803                                 *al = SSL_AD_DECODE_ERROR;
1804                                 return 0;
1805                                 }
1806
1807                         }
1808 #ifndef OPENSSL_NO_SRP
1809                 else if (type == TLSEXT_TYPE_srp)
1810                         {
1811                         if (size <= 0 || ((len = data[0])) != (size -1))
1812                                 {
1813                                 *al = SSL_AD_DECODE_ERROR;
1814                                 return 0;
1815                                 }
1816                         if (s->srp_ctx.login != NULL)
1817                                 {
1818                                 *al = SSL_AD_DECODE_ERROR;
1819                                 return 0;
1820                                 }
1821                         if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
1822                                 return -1;
1823                         memcpy(s->srp_ctx.login, &data[1], len);
1824                         s->srp_ctx.login[len]='\0';
1825   
1826                         if (strlen(s->srp_ctx.login) != len) 
1827                                 {
1828                                 *al = SSL_AD_DECODE_ERROR;
1829                                 return 0;
1830                                 }
1831                         }
1832 #endif
1833
1834 #ifndef OPENSSL_NO_EC
1835                 else if (type == TLSEXT_TYPE_ec_point_formats &&
1836                      s->version != DTLS1_VERSION)
1837                         {
1838                         unsigned char *sdata = data;
1839                         int ecpointformatlist_length = *(sdata++);
1840
1841                         if (ecpointformatlist_length != size - 1)
1842                                 {
1843                                 *al = TLS1_AD_DECODE_ERROR;
1844                                 return 0;
1845                                 }
1846                         if (!s->hit)
1847                                 {
1848                                 if(s->session->tlsext_ecpointformatlist)
1849                                         {
1850                                         OPENSSL_free(s->session->tlsext_ecpointformatlist);
1851                                         s->session->tlsext_ecpointformatlist = NULL;
1852                                         }
1853                                 s->session->tlsext_ecpointformatlist_length = 0;
1854                                 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
1855                                         {
1856                                         *al = TLS1_AD_INTERNAL_ERROR;
1857                                         return 0;
1858                                         }
1859                                 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
1860                                 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
1861                                 }
1862 #if 0
1863                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
1864                         sdata = s->session->tlsext_ecpointformatlist;
1865                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
1866                                 fprintf(stderr,"%i ",*(sdata++));
1867                         fprintf(stderr,"\n");
1868 #endif
1869                         }
1870                 else if (type == TLSEXT_TYPE_elliptic_curves &&
1871                      s->version != DTLS1_VERSION)
1872                         {
1873                         unsigned char *sdata = data;
1874                         int ellipticcurvelist_length = (*(sdata++) << 8);
1875                         ellipticcurvelist_length += (*(sdata++));
1876
1877                         if (ellipticcurvelist_length != size - 2 ||
1878                                 ellipticcurvelist_length < 1)
1879                                 {
1880                                 *al = TLS1_AD_DECODE_ERROR;
1881                                 return 0;
1882                                 }
1883                         if (!s->hit)
1884                                 {
1885                                 if(s->session->tlsext_ellipticcurvelist)
1886                                         {
1887                                         *al = TLS1_AD_DECODE_ERROR;
1888                                         return 0;
1889                                         }
1890                                 s->session->tlsext_ellipticcurvelist_length = 0;
1891                                 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
1892                                         {
1893                                         *al = TLS1_AD_INTERNAL_ERROR;
1894                                         return 0;
1895                                         }
1896                                 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
1897                                 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
1898                                 }
1899 #if 0
1900                         fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
1901                         sdata = s->session->tlsext_ellipticcurvelist;
1902                         for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
1903                                 fprintf(stderr,"%i ",*(sdata++));
1904                         fprintf(stderr,"\n");
1905 #endif
1906                         }
1907 #endif /* OPENSSL_NO_EC */
1908 #ifdef TLSEXT_TYPE_opaque_prf_input
1909                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
1910                      s->version != DTLS1_VERSION)
1911                         {
1912                         unsigned char *sdata = data;
1913
1914                         if (size < 2)
1915                                 {
1916                                 *al = SSL_AD_DECODE_ERROR;
1917                                 return 0;
1918                                 }
1919                         n2s(sdata, s->s3->client_opaque_prf_input_len);
1920                         if (s->s3->client_opaque_prf_input_len != size - 2)
1921                                 {
1922                                 *al = SSL_AD_DECODE_ERROR;
1923                                 return 0;
1924                                 }
1925
1926                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
1927                                 OPENSSL_free(s->s3->client_opaque_prf_input);
1928                         if (s->s3->client_opaque_prf_input_len == 0)
1929                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
1930                         else
1931                                 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
1932                         if (s->s3->client_opaque_prf_input == NULL)
1933                                 {
1934                                 *al = TLS1_AD_INTERNAL_ERROR;
1935                                 return 0;
1936                                 }
1937                         }
1938 #endif
1939                 else if (type == TLSEXT_TYPE_session_ticket)
1940                         {
1941                         if (s->tls_session_ticket_ext_cb &&
1942                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
1943                                 {
1944                                 *al = TLS1_AD_INTERNAL_ERROR;
1945                                 return 0;
1946                                 }
1947                         }
1948                 else if (type == TLSEXT_TYPE_renegotiate)
1949                         {
1950                         if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
1951                                 return 0;
1952                         renegotiate_seen = 1;
1953                         }
1954                 else if (type == TLSEXT_TYPE_signature_algorithms)
1955                         {
1956                         int dsize;
1957                         if (s->cert->peer_sigalgs || size < 2) 
1958                                 {
1959                                 *al = SSL_AD_DECODE_ERROR;
1960                                 return 0;
1961                                 }
1962                         n2s(data,dsize);
1963                         size -= 2;
1964                         if (dsize != size || dsize & 1 || !dsize) 
1965                                 {
1966                                 *al = SSL_AD_DECODE_ERROR;
1967                                 return 0;
1968                                 }
1969                         if (!tls1_process_sigalgs(s, data, dsize))
1970                                 {
1971                                 *al = SSL_AD_DECODE_ERROR;
1972                                 return 0;
1973                                 }
1974                         /* If sigalgs received and no shared algorithms fatal
1975                          * error.
1976                          */
1977                         if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
1978                                 {
1979                                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
1980                                         SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
1981                                 *al = SSL_AD_ILLEGAL_PARAMETER;
1982                                 return 0;
1983                                 }
1984                         }
1985                 else if (type == TLSEXT_TYPE_status_request &&
1986                          s->version != DTLS1_VERSION && s->ctx->tlsext_status_cb)
1987                         {
1988                 
1989                         if (size < 5) 
1990                                 {
1991                                 *al = SSL_AD_DECODE_ERROR;
1992                                 return 0;
1993                                 }
1994
1995                         s->tlsext_status_type = *data++;
1996                         size--;
1997                         if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1998                                 {
1999                                 const unsigned char *sdata;
2000                                 int dsize;
2001                                 /* Read in responder_id_list */
2002                                 n2s(data,dsize);
2003                                 size -= 2;
2004                                 if (dsize > size  ) 
2005                                         {
2006                                         *al = SSL_AD_DECODE_ERROR;
2007                                         return 0;
2008                                         }
2009                                 while (dsize > 0)
2010                                         {
2011                                         OCSP_RESPID *id;
2012                                         int idsize;
2013                                         if (dsize < 4)
2014                                                 {
2015                                                 *al = SSL_AD_DECODE_ERROR;
2016                                                 return 0;
2017                                                 }
2018                                         n2s(data, idsize);
2019                                         dsize -= 2 + idsize;
2020                                         size -= 2 + idsize;
2021                                         if (dsize < 0)
2022                                                 {
2023                                                 *al = SSL_AD_DECODE_ERROR;
2024                                                 return 0;
2025                                                 }
2026                                         sdata = data;
2027                                         data += idsize;
2028                                         id = d2i_OCSP_RESPID(NULL,
2029                                                                 &sdata, idsize);
2030                                         if (!id)
2031                                                 {
2032                                                 *al = SSL_AD_DECODE_ERROR;
2033                                                 return 0;
2034                                                 }
2035                                         if (data != sdata)
2036                                                 {
2037                                                 OCSP_RESPID_free(id);
2038                                                 *al = SSL_AD_DECODE_ERROR;
2039                                                 return 0;
2040                                                 }
2041                                         if (!s->tlsext_ocsp_ids
2042                                                 && !(s->tlsext_ocsp_ids =
2043                                                 sk_OCSP_RESPID_new_null()))
2044                                                 {
2045                                                 OCSP_RESPID_free(id);
2046                                                 *al = SSL_AD_INTERNAL_ERROR;
2047                                                 return 0;
2048                                                 }
2049                                         if (!sk_OCSP_RESPID_push(
2050                                                         s->tlsext_ocsp_ids, id))
2051                                                 {
2052                                                 OCSP_RESPID_free(id);
2053                                                 *al = SSL_AD_INTERNAL_ERROR;
2054                                                 return 0;
2055                                                 }
2056                                         }
2057
2058                                 /* Read in request_extensions */
2059                                 if (size < 2)
2060                                         {
2061                                         *al = SSL_AD_DECODE_ERROR;
2062                                         return 0;
2063                                         }
2064                                 n2s(data,dsize);
2065                                 size -= 2;
2066                                 if (dsize != size)
2067                                         {
2068                                         *al = SSL_AD_DECODE_ERROR;
2069                                         return 0;
2070                                         }
2071                                 sdata = data;
2072                                 if (dsize > 0)
2073                                         {
2074                                         if (s->tlsext_ocsp_exts)
2075                                                 {
2076                                                 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2077                                                                            X509_EXTENSION_free);
2078                                                 }
2079
2080                                         s->tlsext_ocsp_exts =
2081                                                 d2i_X509_EXTENSIONS(NULL,
2082                                                         &sdata, dsize);
2083                                         if (!s->tlsext_ocsp_exts
2084                                                 || (data + dsize != sdata))
2085                                                 {
2086                                                 *al = SSL_AD_DECODE_ERROR;
2087                                                 return 0;
2088                                                 }
2089                                         }
2090                                 }
2091                                 /* We don't know what to do with any other type
2092                                 * so ignore it.
2093                                 */
2094                                 else
2095                                         s->tlsext_status_type = -1;
2096                         }
2097 #ifndef OPENSSL_NO_HEARTBEATS
2098                 else if (type == TLSEXT_TYPE_heartbeat)
2099                         {
2100                         switch(data[0])
2101                                 {
2102                                 case 0x01:      /* Client allows us to send HB requests */
2103                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2104                                                         break;
2105                                 case 0x02:      /* Client doesn't accept HB requests */
2106                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2107                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2108                                                         break;
2109                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2110                                                         return 0;
2111                                 }
2112                         }
2113 #endif
2114 #ifndef OPENSSL_NO_NEXTPROTONEG
2115                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2116                          s->s3->tmp.finish_md_len == 0)
2117                         {
2118                         /* We shouldn't accept this extension on a
2119                          * renegotiation.
2120                          *
2121                          * s->new_session will be set on renegotiation, but we
2122                          * probably shouldn't rely that it couldn't be set on
2123                          * the initial renegotation too in certain cases (when
2124                          * there's some other reason to disallow resuming an
2125                          * earlier session -- the current code won't be doing
2126                          * anything like that, but this might change).
2127
2128                          * A valid sign that there's been a previous handshake
2129                          * in this connection is if s->s3->tmp.finish_md_len >
2130                          * 0.  (We are talking about a check that will happen
2131                          * in the Hello protocol round, well before a new
2132                          * Finished message could have been computed.) */
2133                         s->s3->next_proto_neg_seen = 1;
2134                         }
2135 #endif
2136
2137                 /* session ticket processed earlier */
2138                 else if (type == TLSEXT_TYPE_use_srtp)
2139                         {
2140                         if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2141                                                               al))
2142                                 return 0;
2143                         }
2144
2145                 else if (type == TLSEXT_TYPE_server_authz)
2146                         {
2147                         unsigned char *sdata = data;
2148                         unsigned char server_authz_dataformatlist_length;
2149
2150                         if (size == 0)
2151                                 {
2152                                 *al = TLS1_AD_DECODE_ERROR;
2153                                 return 0;
2154                                 }
2155
2156                         server_authz_dataformatlist_length = *(sdata++);
2157
2158                         if (server_authz_dataformatlist_length != size - 1)
2159                                 {
2160                                 *al = TLS1_AD_DECODE_ERROR;
2161                                 return 0;
2162                                 }
2163
2164                         /* Successful session resumption uses the same authz
2165                          * information as the original session so we ignore this
2166                          * in the case of a session resumption. */
2167                         if (!s->hit)
2168                                 {
2169                                 if (s->s3->tlsext_authz_client_types != NULL)
2170                                         OPENSSL_free(s->s3->tlsext_authz_client_types);
2171                                 s->s3->tlsext_authz_client_types =
2172                                         OPENSSL_malloc(server_authz_dataformatlist_length);
2173                                 if (!s->s3->tlsext_authz_client_types)
2174                                         {
2175                                         *al = TLS1_AD_INTERNAL_ERROR;
2176                                         return 0;
2177                                         }
2178
2179                                 s->s3->tlsext_authz_client_types_len =
2180                                         server_authz_dataformatlist_length;
2181                                 memcpy(s->s3->tlsext_authz_client_types,
2182                                        sdata,
2183                                        server_authz_dataformatlist_length);
2184
2185                                 /* Sort the types in order to check for duplicates. */
2186                                 qsort(s->s3->tlsext_authz_client_types,
2187                                       server_authz_dataformatlist_length,
2188                                       1 /* element size */,
2189                                       byte_compare);
2190
2191                                 for (i = 0; i < server_authz_dataformatlist_length; i++)
2192                                         {
2193                                         if (i > 0 &&
2194                                             s->s3->tlsext_authz_client_types[i] ==
2195                                               s->s3->tlsext_authz_client_types[i-1])
2196                                                 {
2197                                                 *al = TLS1_AD_DECODE_ERROR;
2198                                                 return 0;
2199                                                 }
2200                                         }
2201                                 }
2202                         }
2203
2204                 data+=size;
2205                 }
2206
2207         *p = data;
2208
2209         ri_check:
2210
2211         /* Need RI if renegotiating */
2212
2213         if (!renegotiate_seen && s->renegotiate &&
2214                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2215                 {
2216                 *al = SSL_AD_HANDSHAKE_FAILURE;
2217                 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2218                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2219                 return 0;
2220                 }
2221         /* If no signature algorithms extension set default values */
2222         if (!s->cert->peer_sigalgs)
2223                 ssl_cert_set_default_md(s->cert);
2224
2225         return 1;
2226         }
2227
2228 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2229         {
2230         int al = -1;
2231         if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) 
2232                 {
2233                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2234                 return 0;
2235                 }
2236
2237         if (ssl_check_clienthello_tlsext_early(s) <= 0) 
2238                 {
2239                 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2240                 return 0;
2241                 }
2242         return 1;
2243 }
2244
2245 #ifndef OPENSSL_NO_NEXTPROTONEG
2246 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2247  * elements of zero length are allowed and the set of elements must exactly fill
2248  * the length of the block. */
2249 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2250         {
2251         unsigned int off = 0;
2252
2253         while (off < len)
2254                 {
2255                 if (d[off] == 0)
2256                         return 0;
2257                 off += d[off];
2258                 off++;
2259                 }
2260
2261         return off == len;
2262         }
2263 #endif
2264
2265 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2266         {
2267         unsigned short length;
2268         unsigned short type;
2269         unsigned short size;
2270         unsigned char *data = *p;
2271         int tlsext_servername = 0;
2272         int renegotiate_seen = 0;
2273
2274 #ifndef OPENSSL_NO_NEXTPROTONEG
2275         s->s3->next_proto_neg_seen = 0;
2276 #endif
2277
2278 #ifndef OPENSSL_NO_HEARTBEATS
2279         s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2280                                SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2281 #endif
2282
2283         if (data >= (d+n-2))
2284                 goto ri_check;
2285
2286         n2s(data,length);
2287         if (data+length != d+n)
2288                 {
2289                 *al = SSL_AD_DECODE_ERROR;
2290                 return 0;
2291                 }
2292
2293         while(data <= (d+n-4))
2294                 {
2295                 n2s(data,type);
2296                 n2s(data,size);
2297
2298                 if (data+size > (d+n))
2299                         goto ri_check;
2300
2301                 if (s->tlsext_debug_cb)
2302                         s->tlsext_debug_cb(s, 1, type, data, size,
2303                                                 s->tlsext_debug_arg);
2304
2305                 if (type == TLSEXT_TYPE_server_name)
2306                         {
2307                         if (s->tlsext_hostname == NULL || size > 0)
2308                                 {
2309                                 *al = TLS1_AD_UNRECOGNIZED_NAME;
2310                                 return 0;
2311                                 }
2312                         tlsext_servername = 1;   
2313                         }
2314
2315 #ifndef OPENSSL_NO_EC
2316                 else if (type == TLSEXT_TYPE_ec_point_formats &&
2317                      s->version != DTLS1_VERSION)
2318                         {
2319                         unsigned char *sdata = data;
2320                         int ecpointformatlist_length = *(sdata++);
2321
2322                         if (ecpointformatlist_length != size - 1 || 
2323                                 ecpointformatlist_length < 1)
2324                                 {
2325                                 *al = TLS1_AD_DECODE_ERROR;
2326                                 return 0;
2327                                 }
2328                         s->session->tlsext_ecpointformatlist_length = 0;
2329                         if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2330                         if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2331                                 {
2332                                 *al = TLS1_AD_INTERNAL_ERROR;
2333                                 return 0;
2334                                 }
2335                         s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2336                         memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2337 #if 0
2338                         fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2339                         sdata = s->session->tlsext_ecpointformatlist;
2340                         for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2341                                 fprintf(stderr,"%i ",*(sdata++));
2342                         fprintf(stderr,"\n");
2343 #endif
2344                         }
2345 #endif /* OPENSSL_NO_EC */
2346
2347                 else if (type == TLSEXT_TYPE_session_ticket)
2348                         {
2349                         if (s->tls_session_ticket_ext_cb &&
2350                             !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2351                                 {
2352                                 *al = TLS1_AD_INTERNAL_ERROR;
2353                                 return 0;
2354                                 }
2355                         if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2356                                 || (size > 0))
2357                                 {
2358                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2359                                 return 0;
2360                                 }
2361                         s->tlsext_ticket_expected = 1;
2362                         }
2363 #ifdef TLSEXT_TYPE_opaque_prf_input
2364                 else if (type == TLSEXT_TYPE_opaque_prf_input &&
2365                      s->version != DTLS1_VERSION)
2366                         {
2367                         unsigned char *sdata = data;
2368
2369                         if (size < 2)
2370                                 {
2371                                 *al = SSL_AD_DECODE_ERROR;
2372                                 return 0;
2373                                 }
2374                         n2s(sdata, s->s3->server_opaque_prf_input_len);
2375                         if (s->s3->server_opaque_prf_input_len != size - 2)
2376                                 {
2377                                 *al = SSL_AD_DECODE_ERROR;
2378                                 return 0;
2379                                 }
2380                         
2381                         if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2382                                 OPENSSL_free(s->s3->server_opaque_prf_input);
2383                         if (s->s3->server_opaque_prf_input_len == 0)
2384                                 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2385                         else
2386                                 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2387
2388                         if (s->s3->server_opaque_prf_input == NULL)
2389                                 {
2390                                 *al = TLS1_AD_INTERNAL_ERROR;
2391                                 return 0;
2392                                 }
2393                         }
2394 #endif
2395                 else if (type == TLSEXT_TYPE_status_request &&
2396                          s->version != DTLS1_VERSION)
2397                         {
2398                         /* MUST be empty and only sent if we've requested
2399                          * a status request message.
2400                          */ 
2401                         if ((s->tlsext_status_type == -1) || (size > 0))
2402                                 {
2403                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2404                                 return 0;
2405                                 }
2406                         /* Set flag to expect CertificateStatus message */
2407                         s->tlsext_status_expected = 1;
2408                         }
2409 #ifndef OPENSSL_NO_NEXTPROTONEG
2410                 else if (type == TLSEXT_TYPE_next_proto_neg &&
2411                          s->s3->tmp.finish_md_len == 0)
2412                         {
2413                         unsigned char *selected;
2414                         unsigned char selected_len;
2415
2416                         /* We must have requested it. */
2417                         if ((s->ctx->next_proto_select_cb == NULL))
2418                                 {
2419                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2420                                 return 0;
2421                                 }
2422                         /* The data must be valid */
2423                         if (!ssl_next_proto_validate(data, size))
2424                                 {
2425                                 *al = TLS1_AD_DECODE_ERROR;
2426                                 return 0;
2427                                 }
2428                         if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2429                                 {
2430                                 *al = TLS1_AD_INTERNAL_ERROR;
2431                                 return 0;
2432                                 }
2433                         s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2434                         if (!s->next_proto_negotiated)
2435                                 {
2436                                 *al = TLS1_AD_INTERNAL_ERROR;
2437                                 return 0;
2438                                 }
2439                         memcpy(s->next_proto_negotiated, selected, selected_len);
2440                         s->next_proto_negotiated_len = selected_len;
2441                         s->s3->next_proto_neg_seen = 1;
2442                         }
2443 #endif
2444                 else if (type == TLSEXT_TYPE_renegotiate)
2445                         {
2446                         if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2447                                 return 0;
2448                         renegotiate_seen = 1;
2449                         }
2450 #ifndef OPENSSL_NO_HEARTBEATS
2451                 else if (type == TLSEXT_TYPE_heartbeat)
2452                         {
2453                         switch(data[0])
2454                                 {
2455                                 case 0x01:      /* Server allows us to send HB requests */
2456                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2457                                                         break;
2458                                 case 0x02:      /* Server doesn't accept HB requests */
2459                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2460                                                         s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2461                                                         break;
2462                                 default:        *al = SSL_AD_ILLEGAL_PARAMETER;
2463                                                         return 0;
2464                                 }
2465                         }
2466 #endif
2467                 else if (type == TLSEXT_TYPE_use_srtp)
2468                         {
2469                         if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2470                                                               al))
2471                                 return 0;
2472                         }
2473
2474                 else if (type == TLSEXT_TYPE_server_authz)
2475                         {
2476                         /* We only support audit proofs. It's an error to send
2477                          * an authz hello extension if the client
2478                          * didn't request a proof. */
2479                         unsigned char *sdata = data;
2480                         unsigned char server_authz_dataformatlist_length;
2481
2482                         if (!s->ctx->tlsext_authz_server_audit_proof_cb)
2483                                 {
2484                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2485                                 return 0;
2486                                 }
2487
2488                         if (!size)
2489                                 {
2490                                 *al = TLS1_AD_DECODE_ERROR;
2491                                 return 0;
2492                                 }
2493
2494                         server_authz_dataformatlist_length = *(sdata++);
2495                         if (server_authz_dataformatlist_length != size - 1)
2496                                 {
2497                                 *al = TLS1_AD_DECODE_ERROR;
2498                                 return 0;
2499                                 }
2500
2501                         /* We only support audit proofs, so a legal ServerHello
2502                          * authz list contains exactly one entry. */
2503                         if (server_authz_dataformatlist_length != 1 ||
2504                                 sdata[0] != TLSEXT_AUTHZDATAFORMAT_audit_proof)
2505                                 {
2506                                 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2507                                 return 0;
2508                                 }
2509
2510                         s->s3->tlsext_authz_server_promised = 1;
2511                         }
2512  
2513                 data += size;
2514                 }
2515
2516         if (data != d+n)
2517                 {
2518                 *al = SSL_AD_DECODE_ERROR;
2519                 return 0;
2520                 }
2521
2522         if (!s->hit && tlsext_servername == 1)
2523                 {
2524                 if (s->tlsext_hostname)
2525                         {
2526                         if (s->session->tlsext_hostname == NULL)
2527                                 {
2528                                 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);   
2529                                 if (!s->session->tlsext_hostname)
2530                                         {
2531                                         *al = SSL_AD_UNRECOGNIZED_NAME;
2532                                         return 0;
2533                                         }
2534                                 }
2535                         else 
2536                                 {
2537                                 *al = SSL_AD_DECODE_ERROR;
2538                                 return 0;
2539                                 }
2540                         }
2541                 }
2542
2543         *p = data;
2544
2545         ri_check:
2546
2547         /* Determine if we need to see RI. Strictly speaking if we want to
2548          * avoid an attack we should *always* see RI even on initial server
2549          * hello because the client doesn't see any renegotiation during an
2550          * attack. However this would mean we could not connect to any server
2551          * which doesn't support RI so for the immediate future tolerate RI
2552          * absence on initial connect only.
2553          */
2554         if (!renegotiate_seen
2555                 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2556                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2557                 {
2558                 *al = SSL_AD_HANDSHAKE_FAILURE;
2559                 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2560                                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2561                 return 0;
2562                 }
2563
2564         return 1;
2565         }
2566
2567
2568 int ssl_prepare_clienthello_tlsext(SSL *s)
2569         {
2570
2571 #ifdef TLSEXT_TYPE_opaque_prf_input
2572         {
2573                 int r = 1;
2574         
2575                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2576                         {
2577                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2578                         if (!r)
2579                                 return -1;
2580                         }
2581
2582                 if (s->tlsext_opaque_prf_input != NULL)
2583                         {
2584                         if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2585                                 OPENSSL_free(s->s3->client_opaque_prf_input);
2586
2587                         if (s->tlsext_opaque_prf_input_len == 0)
2588                                 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2589                         else
2590                                 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2591                         if (s->s3->client_opaque_prf_input == NULL)
2592                                 {
2593                                 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2594                                 return -1;
2595                                 }
2596                         s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2597                         }
2598
2599                 if (r == 2)
2600                         /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2601                         s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2602         }
2603 #endif
2604
2605         return 1;
2606         }
2607
2608 int ssl_prepare_serverhello_tlsext(SSL *s)
2609         {
2610 #ifndef OPENSSL_NO_EC
2611         /* If we are server and using an ECC cipher suite, send the point formats we support 
2612          * if the client sent us an ECPointsFormat extension.  Note that the server is not
2613          * supposed to send an EllipticCurves extension.
2614          */
2615
2616         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2617         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2618         int using_ecc = (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
2619         using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
2620         
2621         if (using_ecc)
2622                 {
2623                 if (s->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->tlsext_ecpointformatlist);
2624                 if ((s->tlsext_ecpointformatlist = OPENSSL_malloc(3)) == NULL)
2625                         {
2626                         SSLerr(SSL_F_SSL_PREPARE_SERVERHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2627                         return -1;
2628                         }
2629                 s->tlsext_ecpointformatlist_length = 3;
2630                 s->tlsext_ecpointformatlist[0] = TLSEXT_ECPOINTFORMAT_uncompressed;
2631                 s->tlsext_ecpointformatlist[1] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
2632                 s->tlsext_ecpointformatlist[2] = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
2633                 }
2634 #endif /* OPENSSL_NO_EC */
2635
2636         return 1;
2637         }
2638
2639 static int ssl_check_clienthello_tlsext_early(SSL *s)
2640         {
2641         int ret=SSL_TLSEXT_ERR_NOACK;
2642         int al = SSL_AD_UNRECOGNIZED_NAME;
2643
2644 #ifndef OPENSSL_NO_EC
2645         /* The handling of the ECPointFormats extension is done elsewhere, namely in 
2646          * ssl3_choose_cipher in s3_lib.c.
2647          */
2648         /* The handling of the EllipticCurves extension is done elsewhere, namely in 
2649          * ssl3_choose_cipher in s3_lib.c.
2650          */
2651 #endif
2652
2653         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2654                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2655         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2656                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2657
2658 #ifdef TLSEXT_TYPE_opaque_prf_input
2659         {
2660                 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2661                  * but we might be sending an alert in response to the client hello,
2662                  * so this has to happen here in
2663                  * ssl_check_clienthello_tlsext_early(). */
2664
2665                 int r = 1;
2666         
2667                 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2668                         {
2669                         r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2670                         if (!r)
2671                                 {
2672                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2673                                 al = SSL_AD_INTERNAL_ERROR;
2674                                 goto err;
2675                                 }
2676                         }
2677
2678                 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2679                         OPENSSL_free(s->s3->server_opaque_prf_input);
2680                 s->s3->server_opaque_prf_input = NULL;
2681
2682                 if (s->tlsext_opaque_prf_input != NULL)
2683                         {
2684                         if (s->s3->client_opaque_prf_input != NULL &&
2685                                 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2686                                 {
2687                                 /* can only use this extension if we have a server opaque PRF input
2688                                  * of the same length as the client opaque PRF input! */
2689
2690                                 if (s->tlsext_opaque_prf_input_len == 0)
2691                                         s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2692                                 else
2693                                         s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2694                                 if (s->s3->server_opaque_prf_input == NULL)
2695                                         {
2696                                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2697                                         al = SSL_AD_INTERNAL_ERROR;
2698                                         goto err;
2699                                         }
2700                                 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2701                                 }
2702                         }
2703
2704                 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2705                         {
2706                         /* The callback wants to enforce use of the extension,
2707                          * but we can't do that with the client opaque PRF input;
2708                          * abort the handshake.
2709                          */
2710                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2711                         al = SSL_AD_HANDSHAKE_FAILURE;
2712                         }
2713         }
2714
2715  err:
2716 #endif
2717         switch (ret)
2718                 {
2719                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2720                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2721                         return -1;
2722
2723                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2724                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2725                         return 1; 
2726                                         
2727                 case SSL_TLSEXT_ERR_NOACK:
2728                         s->servername_done=0;
2729                         default:
2730                 return 1;
2731                 }
2732         }
2733
2734 int ssl_check_clienthello_tlsext_late(SSL *s)
2735         {
2736         int ret = SSL_TLSEXT_ERR_OK;
2737         int al;
2738
2739         /* If status request then ask callback what to do.
2740          * Note: this must be called after servername callbacks in case
2741          * the certificate has changed, and must be called after the cipher
2742          * has been chosen because this may influence which certificate is sent
2743          */
2744         if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
2745                 {
2746                 int r;
2747                 CERT_PKEY *certpkey;
2748                 certpkey = ssl_get_server_send_pkey(s);
2749                 /* If no certificate can't return certificate status */
2750                 if (certpkey == NULL)
2751                         {
2752                         s->tlsext_status_expected = 0;
2753                         return 1;
2754                         }
2755                 /* Set current certificate to one we will use so
2756                  * SSL_get_certificate et al can pick it up.
2757                  */
2758                 s->cert->key = certpkey;
2759                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2760                 switch (r)
2761                         {
2762                         /* We don't want to send a status request response */
2763                         case SSL_TLSEXT_ERR_NOACK:
2764                                 s->tlsext_status_expected = 0;
2765                                 break;
2766                         /* status request response should be sent */
2767                         case SSL_TLSEXT_ERR_OK:
2768                                 if (s->tlsext_ocsp_resp)
2769                                         s->tlsext_status_expected = 1;
2770                                 else
2771                                         s->tlsext_status_expected = 0;
2772                                 break;
2773                         /* something bad happened */
2774                         case SSL_TLSEXT_ERR_ALERT_FATAL:
2775                                 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2776                                 al = SSL_AD_INTERNAL_ERROR;
2777                                 goto err;
2778                         }
2779                 }
2780         else
2781                 s->tlsext_status_expected = 0;
2782
2783  err:
2784         switch (ret)
2785                 {
2786                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2787                         ssl3_send_alert(s, SSL3_AL_FATAL,al);
2788                         return -1;
2789
2790                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2791                         ssl3_send_alert(s, SSL3_AL_WARNING,al);
2792                         return 1; 
2793
2794                 default:
2795                         return 1;
2796                 }
2797         }
2798
2799 int ssl_check_serverhello_tlsext(SSL *s)
2800         {
2801         int ret=SSL_TLSEXT_ERR_NOACK;
2802         int al = SSL_AD_UNRECOGNIZED_NAME;
2803
2804 #ifndef OPENSSL_NO_EC
2805         /* If we are client and using an elliptic curve cryptography cipher
2806          * suite, then if server returns an EC point formats lists extension
2807          * it must contain uncompressed.
2808          */
2809         unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2810         unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2811         if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && 
2812             (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && 
2813             ((alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
2814                 {
2815                 /* we are using an ECC cipher */
2816                 size_t i;
2817                 unsigned char *list;
2818                 int found_uncompressed = 0;
2819                 list = s->session->tlsext_ecpointformatlist;
2820                 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2821                         {
2822                         if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
2823                                 {
2824                                 found_uncompressed = 1;
2825                                 break;
2826                                 }
2827                         }
2828                 if (!found_uncompressed)
2829                         {
2830                         SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2831                         return -1;
2832                         }
2833                 }
2834         ret = SSL_TLSEXT_ERR_OK;
2835 #endif /* OPENSSL_NO_EC */
2836
2837         if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) 
2838                 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2839         else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)             
2840                 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2841
2842 #ifdef TLSEXT_TYPE_opaque_prf_input
2843         if (s->s3->server_opaque_prf_input_len > 0)
2844                 {
2845                 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
2846                  * So first verify that we really have a value from the server too. */
2847
2848                 if (s->s3->server_opaque_prf_input == NULL)
2849                         {
2850                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2851                         al = SSL_AD_HANDSHAKE_FAILURE;
2852                         }
2853                 
2854                 /* Anytime the server *has* sent an opaque PRF input, we need to check
2855                  * that we have a client opaque PRF input of the same size. */
2856                 if (s->s3->client_opaque_prf_input == NULL ||
2857                     s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
2858                         {
2859                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2860                         al = SSL_AD_ILLEGAL_PARAMETER;
2861                         }
2862                 }
2863 #endif
2864
2865         /* If we've requested certificate status and we wont get one
2866          * tell the callback
2867          */
2868         if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
2869                         && s->ctx && s->ctx->tlsext_status_cb)
2870                 {
2871                 int r;
2872                 /* Set resp to NULL, resplen to -1 so callback knows
2873                  * there is no response.
2874                  */
2875                 if (s->tlsext_ocsp_resp)
2876                         {
2877                         OPENSSL_free(s->tlsext_ocsp_resp);
2878                         s->tlsext_ocsp_resp = NULL;
2879                         }
2880                 s->tlsext_ocsp_resplen = -1;
2881                 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2882                 if (r == 0)
2883                         {
2884                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2885                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2886                         }
2887                 if (r < 0)
2888                         {
2889                         al = SSL_AD_INTERNAL_ERROR;
2890                         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2891                         }
2892                 }
2893
2894         switch (ret)
2895                 {
2896                 case SSL_TLSEXT_ERR_ALERT_FATAL:
2897                         ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2898                         return -1;
2899
2900                 case SSL_TLSEXT_ERR_ALERT_WARNING:
2901                         ssl3_send_alert(s,SSL3_AL_WARNING,al);
2902                         return 1; 
2903                                         
2904                 case SSL_TLSEXT_ERR_NOACK:
2905                         s->servername_done=0;
2906                         default:
2907                 return 1;
2908                 }
2909         }
2910
2911 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n) 
2912         {
2913         int al = -1;
2914         if (s->version < SSL3_VERSION)
2915                 return 1;
2916         if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) 
2917                 {
2918                 ssl3_send_alert(s,SSL3_AL_FATAL,al); 
2919                 return 0;
2920                 }
2921
2922         if (ssl_check_serverhello_tlsext(s) <= 0) 
2923                 {
2924                 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
2925                 return 0;
2926                 }
2927         return 1;
2928 }
2929
2930 /* Since the server cache lookup is done early on in the processing of the
2931  * ClientHello, and other operations depend on the result, we need to handle
2932  * any TLS session ticket extension at the same time.
2933  *
2934  *   session_id: points at the session ID in the ClientHello. This code will
2935  *       read past the end of this in order to parse out the session ticket
2936  *       extension, if any.
2937  *   len: the length of the session ID.
2938  *   limit: a pointer to the first byte after the ClientHello.
2939  *   ret: (output) on return, if a ticket was decrypted, then this is set to
2940  *       point to the resulting session.
2941  *
2942  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2943  * ciphersuite, in which case we have no use for session tickets and one will
2944  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2945  *
2946  * Returns:
2947  *   -1: fatal error, either from parsing or decrypting the ticket.
2948  *    0: no ticket was found (or was ignored, based on settings).
2949  *    1: a zero length extension was found, indicating that the client supports
2950  *       session tickets but doesn't currently have one to offer.
2951  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
2952  *       couldn't be decrypted because of a non-fatal error.
2953  *    3: a ticket was successfully decrypted and *ret was set.
2954  *
2955  * Side effects:
2956  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
2957  *   a new session ticket to the client because the client indicated support
2958  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
2959  *   a session ticket or we couldn't use the one it gave us, or if
2960  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
2961  *   Otherwise, s->tlsext_ticket_expected is set to 0.
2962  */
2963 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
2964                         const unsigned char *limit, SSL_SESSION **ret)
2965         {
2966         /* Point after session ID in client hello */
2967         const unsigned char *p = session_id + len;
2968         unsigned short i;
2969
2970         *ret = NULL;
2971         s->tlsext_ticket_expected = 0;
2972
2973         /* If tickets disabled behave as if no ticket present
2974          * to permit stateful resumption.
2975          */
2976         if (SSL_get_options(s) & SSL_OP_NO_TICKET)
2977                 return 0;
2978         if ((s->version <= SSL3_VERSION) || !limit)
2979                 return 0;
2980         if (p >= limit)
2981                 return -1;
2982         /* Skip past DTLS cookie */
2983         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
2984                 {
2985                 i = *(p++);
2986                 p+= i;
2987                 if (p >= limit)
2988                         return -1;
2989                 }
2990         /* Skip past cipher list */
2991         n2s(p, i);
2992         p+= i;
2993         if (p >= limit)
2994                 return -1;
2995         /* Skip past compression algorithm list */
2996         i = *(p++);
2997         p += i;
2998         if (p > limit)
2999                 return -1;
3000         /* Now at start of extensions */
3001         if ((p + 2) >= limit)
3002                 return 0;
3003         n2s(p, i);
3004         while ((p + 4) <= limit)
3005                 {
3006                 unsigned short type, size;
3007                 n2s(p, type);
3008                 n2s(p, size);
3009                 if (p + size > limit)
3010                         return 0;
3011                 if (type == TLSEXT_TYPE_session_ticket)
3012                         {
3013                         int r;
3014                         if (size == 0)
3015                                 {
3016                                 /* The client will accept a ticket but doesn't
3017                                  * currently have one. */
3018                                 s->tlsext_ticket_expected = 1;
3019                                 return 1;
3020                                 }
3021                         if (s->tls_session_secret_cb)
3022                                 {
3023                                 /* Indicate that the ticket couldn't be
3024                                  * decrypted rather than generating the session
3025                                  * from ticket now, trigger abbreviated
3026                                  * handshake based on external mechanism to
3027                                  * calculate the master secret later. */
3028                                 return 2;
3029                                 }
3030                         r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3031                         switch (r)
3032                                 {
3033                                 case 2: /* ticket couldn't be decrypted */
3034                                         s->tlsext_ticket_expected = 1;
3035                                         return 2;
3036                                 case 3: /* ticket was decrypted */
3037                                         return r;
3038                                 case 4: /* ticket decrypted but need to renew */
3039                                         s->tlsext_ticket_expected = 1;
3040                                         return 3;
3041                                 default: /* fatal error */
3042                                         return -1;
3043                                 }
3044                         }
3045                 p += size;
3046                 }
3047         return 0;
3048         }
3049
3050 /* tls_decrypt_ticket attempts to decrypt a session ticket.
3051  *
3052  *   etick: points to the body of the session ticket extension.
3053  *   eticklen: the length of the session tickets extenion.
3054  *   sess_id: points at the session ID.
3055  *   sesslen: the length of the session ID.
3056  *   psess: (output) on return, if a ticket was decrypted, then this is set to
3057  *       point to the resulting session.
3058  *
3059  * Returns:
3060  *   -1: fatal error, either from parsing or decrypting the ticket.
3061  *    2: the ticket couldn't be decrypted.
3062  *    3: a ticket was successfully decrypted and *psess was set.
3063  *    4: same as 3, but the ticket needs to be renewed.
3064  */
3065 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3066                                 const unsigned char *sess_id, int sesslen,
3067                                 SSL_SESSION **psess)
3068         {
3069         SSL_SESSION *sess;
3070         unsigned char *sdec;
3071         const unsigned char *p;
3072         int slen, mlen, renew_ticket = 0;
3073         unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3074         HMAC_CTX hctx;
3075         EVP_CIPHER_CTX ctx;
3076         SSL_CTX *tctx = s->initial_ctx;
3077         /* Need at least keyname + iv + some encrypted data */
3078         if (eticklen < 48)
3079                 return 2;
3080         /* Initialize session ticket encryption and HMAC contexts */
3081         HMAC_CTX_init(&hctx);
3082         EVP_CIPHER_CTX_init(&ctx);
3083         if (tctx->tlsext_ticket_key_cb)
3084                 {
3085                 unsigned char *nctick = (unsigned char *)etick;
3086                 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3087                                                         &ctx, &hctx, 0);
3088                 if (rv < 0)
3089                         return -1;
3090                 if (rv == 0)
3091                         return 2;
3092                 if (rv == 2)
3093                         renew_ticket = 1;
3094                 }
3095         else
3096                 {
3097                 /* Check key name matches */
3098                 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3099                         return 2;
3100                 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3101                                         tlsext_tick_md(), NULL);
3102                 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3103                                 tctx->tlsext_tick_aes_key, etick + 16);
3104                 }
3105         /* Attempt to process session ticket, first conduct sanity and
3106          * integrity checks on ticket.
3107          */
3108         mlen = HMAC_size(&hctx);
3109         if (mlen < 0)
3110                 {
3111                 EVP_CIPHER_CTX_cleanup(&ctx);
3112                 return -1;
3113                 }
3114         eticklen -= mlen;
3115         /* Check HMAC of encrypted ticket */
3116         HMAC_Update(&hctx, etick, eticklen);
3117         HMAC_Final(&hctx, tick_hmac, NULL);
3118         HMAC_CTX_cleanup(&hctx);
3119         if (memcmp(tick_hmac, etick + eticklen, mlen))
3120                 return 2;
3121         /* Attempt to decrypt session data */
3122         /* Move p after IV to start of encrypted ticket, update length */
3123         p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3124         eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3125         sdec = OPENSSL_malloc(eticklen);
3126         if (!sdec)
3127                 {
3128                 EVP_CIPHER_CTX_cleanup(&ctx);
3129                 return -1;
3130                 }
3131         EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
3132         if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
3133                 return 2;
3134         slen += mlen;
3135         EVP_CIPHER_CTX_cleanup(&ctx);
3136         p = sdec;
3137
3138         sess = d2i_SSL_SESSION(NULL, &p, slen);
3139         OPENSSL_free(sdec);
3140         if (sess)
3141                 {
3142                 /* The session ID, if non-empty, is used by some clients to
3143                  * detect that the ticket has been accepted. So we copy it to
3144                  * the session structure. If it is empty set length to zero
3145                  * as required by standard.
3146                  */
3147                 if (sesslen)
3148                         memcpy(sess->session_id, sess_id, sesslen);
3149                 sess->session_id_length = sesslen;
3150                 *psess = sess;
3151                 if (renew_ticket)
3152                         return 4;
3153                 else
3154                         return 3;
3155                 }
3156         ERR_clear_error();
3157         /* For session parse failure, indicate that we need to send a new
3158          * ticket. */
3159         return 2;
3160         }
3161
3162 /* Tables to translate from NIDs to TLS v1.2 ids */
3163
3164 typedef struct 
3165         {
3166         int nid;
3167         int id;
3168         } tls12_lookup;
3169
3170 static tls12_lookup tls12_md[] = {
3171         {NID_md5, TLSEXT_hash_md5},
3172         {NID_sha1, TLSEXT_hash_sha1},
3173         {NID_sha224, TLSEXT_hash_sha224},
3174         {NID_sha256, TLSEXT_hash_sha256},
3175         {NID_sha384, TLSEXT_hash_sha384},
3176         {NID_sha512, TLSEXT_hash_sha512}
3177 };
3178
3179 static tls12_lookup tls12_sig[] = {
3180         {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3181         {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3182         {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3183 };
3184
3185 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3186         {
3187         size_t i;
3188         for (i = 0; i < tlen; i++)
3189                 {
3190                 if (table[i].nid == nid)
3191                         return table[i].id;
3192                 }
3193         return -1;
3194         }
3195
3196 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3197         {
3198         size_t i;
3199         for (i = 0; i < tlen; i++)
3200                 {
3201                 if ((table[i].id) == id)
3202                         return table[i].nid;
3203                 }
3204         return NID_undef;
3205         }
3206
3207 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
3208         {
3209         int sig_id, md_id;
3210         if (!md)
3211                 return 0;
3212         md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3213                                 sizeof(tls12_md)/sizeof(tls12_lookup));
3214         if (md_id == -1)
3215                 return 0;
3216         sig_id = tls12_get_sigid(pk);
3217         if (sig_id == -1)
3218                 return 0;
3219         p[0] = (unsigned char)md_id;
3220         p[1] = (unsigned char)sig_id;
3221         return 1;
3222         }
3223
3224 int tls12_get_sigid(const EVP_PKEY *pk)
3225         {
3226         return tls12_find_id(pk->type, tls12_sig,
3227                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
3228         }
3229
3230 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3231         {
3232         switch(hash_alg)
3233                 {
3234 #ifndef OPENSSL_NO_MD5
3235                 case TLSEXT_hash_md5:
3236 #ifdef OPENSSL_FIPS
3237                 if (FIPS_mode())
3238                         return NULL;
3239 #endif
3240                 return EVP_md5();
3241 #endif
3242 #ifndef OPENSSL_NO_SHA
3243                 case TLSEXT_hash_sha1:
3244                 return EVP_sha1();
3245 #endif
3246 #ifndef OPENSSL_NO_SHA256
3247                 case TLSEXT_hash_sha224:
3248                 return EVP_sha224();
3249
3250                 case TLSEXT_hash_sha256:
3251                 return EVP_sha256();
3252 #endif
3253 #ifndef OPENSSL_NO_SHA512
3254                 case TLSEXT_hash_sha384:
3255                 return EVP_sha384();
3256
3257                 case TLSEXT_hash_sha512:
3258                 return EVP_sha512();
3259 #endif
3260                 default:
3261                 return NULL;
3262
3263                 }
3264         }
3265
3266 static int tls12_get_pkey_idx(unsigned char sig_alg)
3267         {
3268         switch(sig_alg)
3269                 {
3270 #ifndef OPENSSL_NO_RSA
3271         case TLSEXT_signature_rsa:
3272                 return SSL_PKEY_RSA_SIGN;
3273 #endif
3274 #ifndef OPENSSL_NO_DSA
3275         case TLSEXT_signature_dsa:
3276                 return SSL_PKEY_DSA_SIGN;
3277 #endif
3278 #ifndef OPENSSL_NO_ECDSA
3279         case TLSEXT_signature_ecdsa:
3280                 return SSL_PKEY_ECC;
3281 #endif
3282                 }
3283         return -1;
3284         }
3285
3286 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3287 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3288                         int *psignhash_nid, const unsigned char *data)
3289         {
3290         int sign_nid = 0, hash_nid = 0;
3291         if (!phash_nid && !psign_nid && !psignhash_nid)
3292                 return;
3293         if (phash_nid || psignhash_nid)
3294                 {
3295                 hash_nid = tls12_find_nid(data[0], tls12_md,
3296                                         sizeof(tls12_md)/sizeof(tls12_lookup));
3297                 if (phash_nid)
3298                         *phash_nid = hash_nid;
3299                 }
3300         if (psign_nid || psignhash_nid)
3301                 {
3302                 sign_nid = tls12_find_nid(data[1], tls12_sig,
3303                                         sizeof(tls12_sig)/sizeof(tls12_lookup));
3304                 if (psign_nid)
3305                         *psign_nid = sign_nid;
3306                 }
3307         if (psignhash_nid)
3308                 {
3309                 if (sign_nid && hash_nid)
3310                         OBJ_find_sigid_by_algs(psignhash_nid,
3311                                                         hash_nid, sign_nid);
3312                 else
3313                         *psignhash_nid = NID_undef;
3314                 }
3315         }
3316 /* Given preference and allowed sigalgs set shared sigalgs */
3317 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3318                                 const unsigned char *pref, size_t preflen,
3319                                 const unsigned char *allow, size_t allowlen)
3320         {
3321         const unsigned char *ptmp, *atmp;
3322         size_t i, j, nmatch = 0;
3323         for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
3324                 {
3325                 /* Skip disabled hashes or signature algorithms */
3326                 if (tls12_get_hash(ptmp[0]) == NULL)
3327                         continue;
3328                 if (tls12_get_pkey_idx(ptmp[1]) == -1)
3329                         continue;
3330                 for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
3331                         {
3332                         if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
3333                                 {
3334                                 nmatch++;
3335                                 if (shsig)
3336                                         {
3337                                         shsig->rhash = ptmp[0];
3338                                         shsig->rsign = ptmp[1];
3339                                         tls1_lookup_sigalg(&shsig->hash_nid,
3340                                                 &shsig->sign_nid,
3341                                                 &shsig->signandhash_nid,
3342                                                 ptmp);
3343                                         shsig++;
3344                                         }
3345                                 break;
3346                                 }
3347                         }
3348                 }
3349         return nmatch;
3350         }
3351
3352 /* Set shared signature algorithms for SSL structures */
3353 static int tls1_set_shared_sigalgs(SSL *s)
3354         {
3355         const unsigned char *pref, *allow, *conf;
3356         size_t preflen, allowlen, conflen;
3357         size_t nmatch;
3358         TLS_SIGALGS *salgs = NULL;
3359         CERT *c = s->cert;
3360         unsigned int is_suiteb = tls1_suiteb(s);
3361         /* If client use client signature algorithms if not NULL */
3362         if (!s->server && c->client_sigalgs && !is_suiteb)
3363                 {
3364                 conf = c->client_sigalgs;
3365                 conflen = c->client_sigalgslen;
3366                 }
3367         else if (c->conf_sigalgs && !is_suiteb)
3368                 {
3369                 conf = c->conf_sigalgs;
3370                 conflen = c->conf_sigalgslen;
3371                 }
3372         else
3373                 conflen = tls12_get_psigalgs(s, &conf);
3374         if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb)
3375                 {
3376                 pref = conf;
3377                 preflen = conflen;
3378                 allow = c->peer_sigalgs;
3379                 allowlen = c->peer_sigalgslen;
3380                 }
3381         else
3382                 {
3383                 allow = conf;
3384                 allowlen = conflen;
3385                 pref = c->peer_sigalgs;
3386                 preflen = c->peer_sigalgslen;
3387                 }
3388         nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3389         if (!nmatch)
3390                 return 1;
3391         salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3392         if (!salgs)
3393                 return 0;
3394         nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3395         c->shared_sigalgs = salgs;
3396         c->shared_sigalgslen = nmatch;
3397         return 1;
3398         }
3399                 
3400
3401 /* Set preferred digest for each key type */
3402
3403 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
3404         {
3405         int idx;
3406         size_t i;
3407         const EVP_MD *md;
3408         CERT *c = s->cert;
3409         TLS_SIGALGS *sigptr;
3410         /* Extension ignored for TLS versions below 1.2 */
3411         if (TLS1_get_version(s) < TLS1_2_VERSION)
3412                 return 1;
3413         /* Should never happen */
3414         if (!c)
3415                 return 0;
3416
3417         c->peer_sigalgs = OPENSSL_malloc(dsize);
3418         if (!c->peer_sigalgs)
3419                 return 0;
3420         c->peer_sigalgslen = dsize;
3421         memcpy(c->peer_sigalgs, data, dsize);
3422
3423         tls1_set_shared_sigalgs(s);
3424
3425         for (i = 0, sigptr = c->shared_sigalgs;
3426                         i < c->shared_sigalgslen; i++, sigptr++)
3427                 {
3428                 idx = tls12_get_pkey_idx(sigptr->rsign);
3429                 if (idx > 0 && c->pkeys[idx].digest == NULL)
3430                         {
3431                         md = tls12_get_hash(sigptr->rhash);
3432                         c->pkeys[idx].digest = md;
3433                         c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3434                         if (idx == SSL_PKEY_RSA_SIGN)
3435                                 {
3436                                 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3437                                 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3438                                 }
3439                         }
3440
3441                 }
3442         /* In strict mode leave unset digests as NULL to indicate we can't
3443          * use the certificate for signing.
3444          */
3445         if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
3446                 {
3447                 /* Set any remaining keys to default values. NOTE: if alg is
3448                  * not supported it stays as NULL.
3449                  */
3450 #ifndef OPENSSL_NO_DSA
3451                 if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3452                         c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3453 #endif
3454 #ifndef OPENSSL_NO_RSA
3455                 if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
3456                         {
3457                         c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3458                         c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3459                         }
3460 #endif
3461 #ifndef OPENSSL_NO_ECDSA
3462                 if (!c->pkeys[SSL_PKEY_ECC].digest)
3463                         c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3464 #endif
3465                 }
3466         return 1;
3467         }
3468
3469
3470 int SSL_get_sigalgs(SSL *s, int idx,
3471                         int *psign, int *phash, int *psignhash,
3472                         unsigned char *rsig, unsigned char *rhash)
3473         {
3474         const unsigned char *psig = s->cert->peer_sigalgs;
3475         if (psig == NULL)
3476                 return 0;
3477         if (idx >= 0)
3478                 {
3479                 idx <<= 1;
3480                 if (idx >= (int)s->cert->peer_sigalgslen)
3481                         return 0;
3482                 psig += idx;
3483                 if (rhash)
3484                         *rhash = psig[0];
3485                 if (rsig)
3486                         *rsig = psig[1];
3487                 tls1_lookup_sigalg(phash, psign, psignhash, psig);
3488                 }
3489         return s->cert->peer_sigalgslen / 2;
3490         }
3491
3492 int SSL_get_shared_sigalgs(SSL *s, int idx,
3493                         int *psign, int *phash, int *psignhash,
3494                         unsigned char *rsig, unsigned char *rhash)
3495         {
3496         TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3497         if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3498                 return 0;
3499         shsigalgs += idx;
3500         if (phash)
3501                 *phash = shsigalgs->hash_nid;
3502         if (psign)
3503                 *psign = shsigalgs->sign_nid;
3504         if (psignhash)
3505                 *psignhash = shsigalgs->signandhash_nid;
3506         if (rsig)
3507                 *rsig = shsigalgs->rsign;
3508         if (rhash)
3509                 *rhash = shsigalgs->rhash;
3510         return s->cert->shared_sigalgslen;
3511         }
3512         
3513
3514 #ifndef OPENSSL_NO_HEARTBEATS
3515 int
3516 tls1_process_heartbeat(SSL *s)
3517         {
3518         unsigned char *p = &s->s3->rrec.data[0], *pl;
3519         unsigned short hbtype;
3520         unsigned int payload;
3521         unsigned int padding = 16; /* Use minimum padding */
3522
3523         /* Read type and payload length first */
3524         hbtype = *p++;
3525         n2s(p, payload);
3526         pl = p;
3527
3528         if (s->msg_callback)
3529                 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
3530                         &s->s3->rrec.data[0], s->s3->rrec.length,
3531                         s, s->msg_callback_arg);
3532
3533         if (hbtype == TLS1_HB_REQUEST)
3534                 {
3535                 unsigned char *buffer, *bp;
3536                 int r;
3537
3538                 /* Allocate memory for the response, size is 1 bytes
3539                  * message type, plus 2 bytes payload length, plus
3540                  * payload, plus padding
3541                  */
3542                 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
3543                 bp = buffer;
3544                 
3545                 /* Enter response type, length and copy payload */
3546                 *bp++ = TLS1_HB_RESPONSE;
3547                 s2n(payload, bp);
3548                 memcpy(bp, pl, payload);
3549                 bp += payload;
3550                 /* Random padding */
3551                 RAND_pseudo_bytes(bp, padding);
3552
3553                 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
3554
3555                 if (r >= 0 && s->msg_callback)
3556                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3557                                 buffer, 3 + payload + padding,
3558                                 s, s->msg_callback_arg);
3559
3560                 OPENSSL_free(buffer);
3561
3562                 if (r < 0)
3563                         return r;
3564                 }
3565         else if (hbtype == TLS1_HB_RESPONSE)
3566                 {
3567                 unsigned int seq;
3568                 
3569                 /* We only send sequence numbers (2 bytes unsigned int),
3570                  * and 16 random bytes, so we just try to read the
3571                  * sequence number */
3572                 n2s(pl, seq);
3573                 
3574                 if (payload == 18 && seq == s->tlsext_hb_seq)
3575                         {
3576                         s->tlsext_hb_seq++;
3577                         s->tlsext_hb_pending = 0;
3578                         }
3579                 }
3580
3581         return 0;
3582         }
3583
3584 int
3585 tls1_heartbeat(SSL *s)
3586         {
3587         unsigned char *buf, *p;
3588         int ret;
3589         unsigned int payload = 18; /* Sequence number + random bytes */
3590         unsigned int padding = 16; /* Use minimum padding */
3591
3592         /* Only send if peer supports and accepts HB requests... */
3593         if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
3594             s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
3595                 {
3596                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
3597                 return -1;
3598                 }
3599
3600         /* ...and there is none in flight yet... */
3601         if (s->tlsext_hb_pending)
3602                 {
3603                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
3604                 return -1;
3605                 }
3606                 
3607         /* ...and no handshake in progress. */
3608         if (SSL_in_init(s) || s->in_handshake)
3609                 {
3610                 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
3611                 return -1;
3612                 }
3613                 
3614         /* Check if padding is too long, payload and padding
3615          * must not exceed 2^14 - 3 = 16381 bytes in total.
3616          */
3617         OPENSSL_assert(payload + padding <= 16381);
3618
3619         /* Create HeartBeat message, we just use a sequence number
3620          * as payload to distuingish different messages and add
3621          * some random stuff.
3622          *  - Message Type, 1 byte
3623          *  - Payload Length, 2 bytes (unsigned int)
3624          *  - Payload, the sequence number (2 bytes uint)
3625          *  - Payload, random bytes (16 bytes uint)
3626          *  - Padding
3627          */
3628         buf = OPENSSL_malloc(1 + 2 + payload + padding);
3629         p = buf;
3630         /* Message Type */
3631         *p++ = TLS1_HB_REQUEST;
3632         /* Payload length (18 bytes here) */
3633         s2n(payload, p);
3634         /* Sequence number */
3635         s2n(s->tlsext_hb_seq, p);
3636         /* 16 random bytes */
3637         RAND_pseudo_bytes(p, 16);
3638         p += 16;
3639         /* Random padding */
3640         RAND_pseudo_bytes(p, padding);
3641
3642         ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
3643         if (ret >= 0)
3644                 {
3645                 if (s->msg_callback)
3646                         s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3647                                 buf, 3 + payload + padding,
3648                                 s, s->msg_callback_arg);
3649
3650                 s->tlsext_hb_pending = 1;
3651                 }
3652                 
3653         OPENSSL_free(buf);
3654
3655         return ret;
3656         }
3657 #endif
3658
3659 #define MAX_SIGALGLEN   (TLSEXT_hash_num * TLSEXT_signature_num * 2)
3660
3661 typedef struct
3662         {
3663         size_t sigalgcnt;
3664         int sigalgs[MAX_SIGALGLEN];
3665         } sig_cb_st;
3666
3667 static int sig_cb(const char *elem, int len, void *arg)
3668         {
3669         sig_cb_st *sarg = arg;
3670         size_t i;
3671         char etmp[20], *p;
3672         int sig_alg, hash_alg;
3673         if (sarg->sigalgcnt == MAX_SIGALGLEN)
3674                 return 0;
3675         if (len > (int)(sizeof(etmp) - 1))
3676                 return 0;
3677         memcpy(etmp, elem, len);
3678         etmp[len] = 0;
3679         p = strchr(etmp, '+');
3680         if (!p)
3681                 return 0;
3682         *p = 0;
3683         p++;
3684         if (!*p)
3685                 return 0;
3686
3687         if (!strcmp(etmp, "RSA"))
3688                 sig_alg = EVP_PKEY_RSA;
3689         else if (!strcmp(etmp, "DSA"))
3690                 sig_alg = EVP_PKEY_DSA;
3691         else if (!strcmp(etmp, "ECDSA"))
3692                 sig_alg = EVP_PKEY_EC;
3693         else return 0;
3694
3695         hash_alg = OBJ_sn2nid(p);
3696         if (hash_alg == NID_undef)
3697                 hash_alg = OBJ_ln2nid(p);
3698         if (hash_alg == NID_undef)
3699                 return 0;
3700
3701         for (i = 0; i < sarg->sigalgcnt; i+=2)
3702                 {
3703                 if (sarg->sigalgs[i] == sig_alg
3704                         && sarg->sigalgs[i + 1] == hash_alg)
3705                         return 0;
3706                 }
3707         sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
3708         sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
3709         return 1;
3710         }
3711
3712 /* Set suppored signature algorithms based on a colon separated list
3713  * of the form sig+hash e.g. RSA+SHA512:DSA+SHA512 */
3714 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
3715         {
3716         sig_cb_st sig;
3717         sig.sigalgcnt = 0;
3718         if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
3719                 return 0;
3720         return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
3721         }
3722
3723 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
3724         {
3725         unsigned char *sigalgs, *sptr;
3726         int rhash, rsign;
3727         size_t i;
3728         if (salglen & 1)
3729                 return 0;
3730         sigalgs = OPENSSL_malloc(salglen);
3731         if (sigalgs == NULL)
3732                 return 0;
3733         for (i = 0, sptr = sigalgs; i < salglen; i+=2)
3734                 {
3735                 rhash = tls12_find_id(*psig_nids++, tls12_md,
3736                                         sizeof(tls12_md)/sizeof(tls12_lookup));
3737                 rsign = tls12_find_id(*psig_nids++, tls12_sig,
3738                                 sizeof(tls12_sig)/sizeof(tls12_lookup));
3739
3740                 if (rhash == -1 || rsign == -1)
3741                         goto err;
3742                 *sptr++ = rhash;
3743                 *sptr++ = rsign;
3744                 }
3745
3746         if (client)
3747                 {
3748                 if (c->client_sigalgs)
3749                         OPENSSL_free(c->client_sigalgs);
3750                 c->client_sigalgs = sigalgs;
3751                 c->client_sigalgslen = salglen;
3752                 }
3753         else
3754                 {
3755                 if (c->conf_sigalgs)
3756                         OPENSSL_free(c->conf_sigalgs);
3757                 c->conf_sigalgs = sigalgs;
3758                 c->conf_sigalgslen = salglen;
3759                 }
3760
3761         return 1;
3762
3763         err:
3764         OPENSSL_free(sigalgs);
3765         return 0;
3766         }
3767
3768 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
3769         {
3770         int sig_nid;
3771         size_t i;
3772         if (default_nid == -1)
3773                 return 1;
3774         sig_nid = X509_get_signature_nid(x);
3775         if (default_nid)
3776                 return sig_nid == default_nid ? 1 : 0;
3777         for (i = 0; i < c->shared_sigalgslen; i++)
3778                 if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
3779                         return 1;
3780         return 0;
3781         }
3782 /* Check to see if a certificate issuer name matches list of CA names */
3783 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
3784         {
3785         X509_NAME *nm;
3786         int i;
3787         nm = X509_get_issuer_name(x);
3788         for (i = 0; i < sk_X509_NAME_num(names); i++)
3789                 {
3790                 if(!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
3791                         return 1;
3792                 }
3793         return 0;
3794         }
3795
3796 /* Check certificate chain is consistent with TLS extensions and is
3797  * usable by server. This servers two purposes: it allows users to 
3798  * check chains before passing them to the server and it allows the
3799  * server to check chains before attempting to use them.
3800  */
3801
3802 /* Flags which need to be set for a certificate when stict mode not set */
3803
3804 #define CERT_PKEY_VALID_FLAGS \
3805         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
3806 /* Strict mode flags */
3807 #define CERT_PKEY_STRICT_FLAGS \
3808          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
3809          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
3810
3811 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
3812                                                                         int idx)
3813         {
3814         int i;
3815         int rv = 0;
3816         int check_flags = 0, strict_mode;
3817         CERT_PKEY *cpk = NULL;
3818         CERT *c = s->cert;
3819         unsigned int suiteb_flags = tls1_suiteb(s);
3820         /* idx == -1 means checking server chains */
3821         if (idx != -1)
3822                 {
3823                 /* idx == -2 means checking client certificate chains */
3824                 if (idx == -2)
3825                         {
3826                         cpk = c->key;
3827                         idx = cpk - c->pkeys;
3828                         }
3829                 else
3830                         cpk = c->pkeys + idx;
3831                 x = cpk->x509;
3832                 pk = cpk->privatekey;
3833                 chain = cpk->chain;
3834                 strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
3835                 /* If no cert or key, forget it */
3836                 if (!x || !pk)
3837                         goto end;
3838                 }
3839         else
3840                 {
3841                 if (!x || !pk)
3842                         goto end;
3843                 idx = ssl_cert_type(x, pk);
3844                 if (idx == -1)
3845                         goto end;
3846                 cpk = c->pkeys + idx;
3847                 if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
3848                         check_flags = CERT_PKEY_STRICT_FLAGS;
3849                 else
3850                         check_flags = CERT_PKEY_VALID_FLAGS;
3851                 strict_mode = 1;
3852                 }
3853
3854         if (suiteb_flags)
3855                 {
3856                 int ok;
3857                 if (check_flags)
3858                         check_flags |= CERT_PKEY_SUITEB;
3859                 ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
3860                 if (ok != X509_V_OK)
3861                         {
3862                         if (check_flags)
3863                                 rv |= CERT_PKEY_SUITEB;
3864                         else
3865                                 goto end;
3866                         }
3867                 }
3868
3869         /* Check all signature algorithms are consistent with
3870          * signature algorithms extension if TLS 1.2 or later
3871          * and strict mode.
3872          */
3873         if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode)
3874                 {
3875                 int default_nid;
3876                 unsigned char rsign = 0;
3877                 if (c->peer_sigalgs)
3878                         default_nid = 0;
3879                 /* If no sigalgs extension use defaults from RFC5246 */
3880                 else
3881                         {
3882                         switch(idx)
3883                                 {       
3884                         case SSL_PKEY_RSA_ENC:
3885                         case SSL_PKEY_RSA_SIGN:
3886                         case SSL_PKEY_DH_RSA:
3887                                 rsign = TLSEXT_signature_rsa;
3888                                 default_nid = NID_sha1WithRSAEncryption;
3889                                 break;
3890
3891                         case SSL_PKEY_DSA_SIGN:
3892                         case SSL_PKEY_DH_DSA:
3893                                 rsign = TLSEXT_signature_dsa;
3894                                 default_nid = NID_dsaWithSHA1;
3895                                 break;
3896
3897                         case SSL_PKEY_ECC:
3898                                 rsign = TLSEXT_signature_ecdsa;
3899                                 default_nid = NID_ecdsa_with_SHA1;
3900                                 break;
3901
3902                         default:
3903                                 default_nid = -1;
3904                                 break;
3905                                 }
3906                         }
3907                 /* If peer sent no signature algorithms extension and we
3908                  * have set preferred signature algorithms check we support
3909                  * sha1.
3910                  */
3911                 if (default_nid > 0 && c->conf_sigalgs)
3912                         {
3913                         size_t j;
3914                         const unsigned char *p = c->conf_sigalgs;
3915                         for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2)
3916                                 {
3917                                 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
3918                                         break;
3919                                 }
3920                         if (j == c->conf_sigalgslen)
3921                                 {
3922                                 if (check_flags)
3923                                         goto skip_sigs;
3924                                 else
3925                                         goto end;
3926                                 }
3927                         }
3928                 /* Check signature algorithm of each cert in chain */
3929                 if (!tls1_check_sig_alg(c, x, default_nid))
3930                         {
3931                         if (!check_flags) goto end;
3932                         }
3933                 else
3934                         rv |= CERT_PKEY_EE_SIGNATURE;
3935                 rv |= CERT_PKEY_CA_SIGNATURE;
3936                 for (i = 0; i < sk_X509_num(chain); i++)
3937                         {
3938                         if (!tls1_check_sig_alg(c, sk_X509_value(chain, i),
3939                                                         default_nid))
3940                                 {
3941                                 if (check_flags)
3942                                         {
3943                                         rv &= ~CERT_PKEY_CA_SIGNATURE;
3944                                         break;
3945                                         }
3946                                 else
3947                                         goto end;
3948                                 }
3949                         }
3950                 }
3951         /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
3952         else if(check_flags)
3953                 rv |= CERT_PKEY_EE_SIGNATURE|CERT_PKEY_CA_SIGNATURE;
3954         skip_sigs:
3955         /* Check cert parameters are consistent */
3956         if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
3957                 rv |= CERT_PKEY_EE_PARAM;
3958         else if (!check_flags)
3959                 goto end;
3960         if (!s->server)
3961                 rv |= CERT_PKEY_CA_PARAM;
3962         /* In strict mode check rest of chain too */
3963         else if (strict_mode)
3964                 {
3965                 rv |= CERT_PKEY_CA_PARAM;
3966                 for (i = 0; i < sk_X509_num(chain); i++)
3967                         {
3968                         X509 *ca = sk_X509_value(chain, i);
3969                         if (!tls1_check_cert_param(s, ca, 0))
3970                                 {
3971                                 if (check_flags)
3972                                         {
3973                                         rv &= ~CERT_PKEY_CA_PARAM;
3974                                         break;
3975                                         }
3976                                 else
3977                                         goto end;
3978                                 }
3979                         }
3980                 }
3981         if (!s->server && strict_mode)
3982                 {
3983                 STACK_OF(X509_NAME) *ca_dn;
3984                 int check_type = 0;
3985                 switch (pk->type)
3986                         {
3987                 case EVP_PKEY_RSA:
3988                         check_type = TLS_CT_RSA_SIGN;
3989                         break;
3990                 case EVP_PKEY_DSA:
3991                         check_type = TLS_CT_DSS_SIGN;
3992                         break;
3993                 case EVP_PKEY_EC:
3994                         check_type = TLS_CT_ECDSA_SIGN;
3995                         break;
3996                 case EVP_PKEY_DH:
3997                 case EVP_PKEY_DHX:
3998                                 {
3999                                 int cert_type = X509_certificate_type(x, pk);
4000                                 if (cert_type & EVP_PKS_RSA)
4001                                         check_type = TLS_CT_RSA_FIXED_DH;
4002                                 if (cert_type & EVP_PKS_DSA)
4003                                         check_type = TLS_CT_DSS_FIXED_DH;
4004                                 }
4005                         }
4006                 if (check_type)
4007                         {
4008                         const unsigned char *ctypes;
4009                         int ctypelen;
4010                         if (c->ctypes)
4011                                 {
4012                                 ctypes = c->ctypes;
4013                                 ctypelen = (int)c->ctype_num;
4014                                 }
4015                         else
4016                                 {
4017                                 ctypes = (unsigned char *)s->s3->tmp.ctype;
4018                                 ctypelen = s->s3->tmp.ctype_num;
4019                                 }
4020                         for (i = 0; i < ctypelen; i++)
4021                                 {
4022                                 if (ctypes[i] == check_type)
4023                                         {
4024                                         rv |= CERT_PKEY_CERT_TYPE;
4025                                         break;
4026                                         }
4027                                 }
4028                         if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4029                                 goto end;
4030                         }
4031                 else
4032                         rv |= CERT_PKEY_CERT_TYPE;
4033
4034
4035                 ca_dn = s->s3->tmp.ca_names;
4036
4037                 if (!sk_X509_NAME_num(ca_dn))
4038                         rv |= CERT_PKEY_ISSUER_NAME;
4039
4040                 if (!(rv & CERT_PKEY_ISSUER_NAME))
4041                         {
4042                         if (ssl_check_ca_name(ca_dn, x))
4043                                 rv |= CERT_PKEY_ISSUER_NAME;
4044                         }
4045                 if (!(rv & CERT_PKEY_ISSUER_NAME))
4046                         {
4047                         for (i = 0; i < sk_X509_num(chain); i++)
4048                                 {
4049                                 X509 *xtmp = sk_X509_value(chain, i);
4050                                 if (ssl_check_ca_name(ca_dn, xtmp))
4051                                         {
4052                                         rv |= CERT_PKEY_ISSUER_NAME;
4053                                         break;
4054                                         }
4055                                 }
4056                         }
4057                 if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4058                         goto end;
4059                 }
4060         else
4061                 rv |= CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE;
4062
4063         if (!check_flags || (rv & check_flags) == check_flags)
4064                 rv |= CERT_PKEY_VALID;
4065
4066         end:
4067
4068         if (TLS1_get_version(s) >= TLS1_2_VERSION)
4069                 {
4070                 if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4071                         rv |= CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_SIGN;
4072                 else if (cpk->digest)
4073                         rv |= CERT_PKEY_SIGN;
4074                 }
4075         else
4076                 rv |= CERT_PKEY_SIGN|CERT_PKEY_EXPLICIT_SIGN;
4077
4078         /* When checking a CERT_PKEY structure all flags are irrelevant
4079          * if the chain is invalid.
4080          */
4081         if (!check_flags)
4082                 {
4083                 if (rv & CERT_PKEY_VALID)
4084                         cpk->valid_flags = rv;
4085                 else
4086                         {
4087                         /* Preserve explicit sign flag, clear rest */
4088                         cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4089                         return 0;
4090                         }
4091                 }
4092         return rv;
4093         }
4094
4095 /* Set validity of certificates in an SSL structure */
4096 void tls1_set_cert_validity(SSL *s)
4097         {
4098         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4099         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4100         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4101         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4102         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4103         tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4104         }
4105 /* User level utiity function to check a chain is suitable */
4106 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4107         {
4108         return tls1_check_chain(s, x, pk, chain, -1);
4109         }
4110
4111 #endif