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