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