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