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