1 /* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include <stdio.h>
16 #include <string.h>
17 #include <time.h>
18
19 #include <algorithm>
20 #include <string>
21 #include <utility>
22 #include <vector>
23
24 #include <gtest/gtest.h>
25
26 #include <openssl/base64.h>
27 #include <openssl/bio.h>
28 #include <openssl/cipher.h>
29 #include <openssl/crypto.h>
30 #include <openssl/err.h>
31 #include <openssl/hmac.h>
32 #include <openssl/pem.h>
33 #include <openssl/sha.h>
34 #include <openssl/ssl.h>
35 #include <openssl/rand.h>
36 #include <openssl/x509.h>
37
38 #include "internal.h"
39 #include "../crypto/internal.h"
40 #include "../crypto/test/test_util.h"
41
42 #if defined(OPENSSL_WINDOWS)
43 // Windows defines struct timeval in winsock2.h.
44 OPENSSL_MSVC_PRAGMA(warning(push, 3))
45 #include <winsock2.h>
46 OPENSSL_MSVC_PRAGMA(warning(pop))
47 #else
48 #include <sys/time.h>
49 #endif
50
51
52 namespace bssl {
53
54 namespace {
55
56 #define TRACED_CALL(code) \
57 do { \
58 SCOPED_TRACE("<- called from here"); \
59 code; \
60 if (::testing::Test::HasFatalFailure()) { \
61 return; \
62 } \
63 } while (false)
64
65 struct VersionParam {
66 uint16_t version;
67 enum { is_tls, is_dtls } ssl_method;
68 const char name[8];
69 };
70
71 static const size_t kTicketKeyLen = 48;
72
73 static const VersionParam kAllVersions[] = {
74 {SSL3_VERSION, VersionParam::is_tls, "SSL3"},
75 {TLS1_VERSION, VersionParam::is_tls, "TLS1"},
76 {TLS1_1_VERSION, VersionParam::is_tls, "TLS1_1"},
77 {TLS1_2_VERSION, VersionParam::is_tls, "TLS1_2"},
78 {TLS1_3_VERSION, VersionParam::is_tls, "TLS1_3"},
79 {DTLS1_VERSION, VersionParam::is_dtls, "DTLS1"},
80 {DTLS1_2_VERSION, VersionParam::is_dtls, "DTLS1_2"},
81 };
82
83 struct ExpectedCipher {
84 unsigned long id;
85 int in_group_flag;
86 };
87
88 struct CipherTest {
89 // The rule string to apply.
90 const char *rule;
91 // The list of expected ciphers, in order.
92 std::vector<ExpectedCipher> expected;
93 // True if this cipher list should fail in strict mode.
94 bool strict_fail;
95 };
96
97 struct CurveTest {
98 // The rule string to apply.
99 const char *rule;
100 // The list of expected curves, in order.
101 std::vector<uint16_t> expected;
102 };
103
104 static const CipherTest kCipherTests[] = {
105 // Selecting individual ciphers should work.
106 {
107 "ECDHE-ECDSA-CHACHA20-POLY1305:"
108 "ECDHE-RSA-CHACHA20-POLY1305:"
109 "ECDHE-ECDSA-AES128-GCM-SHA256:"
110 "ECDHE-RSA-AES128-GCM-SHA256",
111 {
112 {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
113 {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
114 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
115 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
116 },
117 false,
118 },
119 // + reorders selected ciphers to the end, keeping their relative order.
120 {
121 "ECDHE-ECDSA-CHACHA20-POLY1305:"
122 "ECDHE-RSA-CHACHA20-POLY1305:"
123 "ECDHE-ECDSA-AES128-GCM-SHA256:"
124 "ECDHE-RSA-AES128-GCM-SHA256:"
125 "+aRSA",
126 {
127 {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
128 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
129 {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
130 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
131 },
132 false,
133 },
134 // ! banishes ciphers from future selections.
135 {
136 "!aRSA:"
137 "ECDHE-ECDSA-CHACHA20-POLY1305:"
138 "ECDHE-RSA-CHACHA20-POLY1305:"
139 "ECDHE-ECDSA-AES128-GCM-SHA256:"
140 "ECDHE-RSA-AES128-GCM-SHA256",
141 {
142 {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
143 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
144 },
145 false,
146 },
147 // Multiple masks can be ANDed in a single rule.
148 {
149 "kRSA+AESGCM+AES128",
150 {
151 {TLS1_CK_RSA_WITH_AES_128_GCM_SHA256, 0},
152 },
153 false,
154 },
155 // - removes selected ciphers, but preserves their order for future
156 // selections. Select AES_128_GCM, but order the key exchanges RSA,
157 // ECDHE_RSA.
158 {
159 "ALL:-kECDHE:"
160 "-kRSA:-ALL:"
161 "AESGCM+AES128+aRSA",
162 {
163 {TLS1_CK_RSA_WITH_AES_128_GCM_SHA256, 0},
164 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
165 },
166 false,
167 },
168 // Unknown selectors are no-ops, except in strict mode.
169 {
170 "ECDHE-ECDSA-CHACHA20-POLY1305:"
171 "ECDHE-RSA-CHACHA20-POLY1305:"
172 "ECDHE-ECDSA-AES128-GCM-SHA256:"
173 "ECDHE-RSA-AES128-GCM-SHA256:"
174 "BOGUS1",
175 {
176 {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
177 {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
178 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
179 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
180 },
181 true,
182 },
183 // Unknown selectors are no-ops, except in strict mode.
184 {
185 "ECDHE-ECDSA-CHACHA20-POLY1305:"
186 "ECDHE-RSA-CHACHA20-POLY1305:"
187 "ECDHE-ECDSA-AES128-GCM-SHA256:"
188 "ECDHE-RSA-AES128-GCM-SHA256:"
189 "-BOGUS2:+BOGUS3:!BOGUS4",
190 {
191 {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
192 {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
193 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
194 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
195 },
196 true,
197 },
198 // Square brackets specify equi-preference groups.
199 {
200 "[ECDHE-ECDSA-CHACHA20-POLY1305|ECDHE-ECDSA-AES128-GCM-SHA256]:"
201 "[ECDHE-RSA-CHACHA20-POLY1305]:"
202 "ECDHE-RSA-AES128-GCM-SHA256",
203 {
204 {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 1},
205 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
206 {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
207 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
208 },
209 false,
210 },
211 // Standard names may be used instead of OpenSSL names.
212 {
213 "[TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256|"
214 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256]:"
215 "[TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256]:"
216 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
217 {
218 {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 1},
219 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
220 {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
221 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
222 },
223 false,
224 },
225 // @STRENGTH performs a stable strength-sort of the selected ciphers and
226 // only the selected ciphers.
227 {
228 // To simplify things, banish all but {ECDHE_RSA,RSA} x
229 // {CHACHA20,AES_256_CBC,AES_128_CBC} x SHA1.
230 "!AESGCM:!3DES:!SHA256:!SHA384:"
231 // Order some ciphers backwards by strength.
232 "ALL:-CHACHA20:-AES256:-AES128:-ALL:"
233 // Select ECDHE ones and sort them by strength. Ties should resolve
234 // based on the order above.
235 "kECDHE:@STRENGTH:-ALL:"
236 // Now bring back everything uses RSA. ECDHE_RSA should be first, sorted
237 // by strength. Then RSA, backwards by strength.
238 "aRSA",
239 {
240 {TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA, 0},
241 {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
242 {TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA, 0},
243 {TLS1_CK_RSA_WITH_AES_128_SHA, 0},
244 {TLS1_CK_RSA_WITH_AES_256_SHA, 0},
245 },
246 false,
247 },
248 // Additional masks after @STRENGTH get silently discarded.
249 //
250 // TODO(davidben): Make this an error. If not silently discarded, they get
251 // interpreted as + opcodes which are very different.
252 {
253 "ECDHE-RSA-AES128-GCM-SHA256:"
254 "ECDHE-RSA-AES256-GCM-SHA384:"
255 "@STRENGTH+AES256",
256 {
257 {TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0},
258 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
259 },
260 false,
261 },
262 {
263 "ECDHE-RSA-AES128-GCM-SHA256:"
264 "ECDHE-RSA-AES256-GCM-SHA384:"
265 "@STRENGTH+AES256:"
266 "ECDHE-RSA-CHACHA20-POLY1305",
267 {
268 {TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0},
269 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
270 {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
271 },
272 false,
273 },
274 // Exact ciphers may not be used in multi-part rules; they are treated
275 // as unknown aliases.
276 {
277 "ECDHE-ECDSA-AES128-GCM-SHA256:"
278 "ECDHE-RSA-AES128-GCM-SHA256:"
279 "!ECDHE-RSA-AES128-GCM-SHA256+RSA:"
280 "!ECDSA+ECDHE-ECDSA-AES128-GCM-SHA256",
281 {
282 {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
283 {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
284 },
285 true,
286 },
287 // SSLv3 matches everything that existed before TLS 1.2.
288 {
289 "AES128-SHA:AES128-SHA256:!SSLv3",
290 {
291 {TLS1_CK_RSA_WITH_AES_128_SHA256, 0},
292 },
293 false,
294 },
295 // TLSv1.2 matches everything added in TLS 1.2.
296 {
297 "AES128-SHA:AES128-SHA256:!TLSv1.2",
298 {
299 {TLS1_CK_RSA_WITH_AES_128_SHA, 0},
300 },
301 false,
302 },
303 // The two directives have no intersection. But each component is valid, so
304 // even in strict mode it is accepted.
305 {
306 "AES128-SHA:AES128-SHA256:!TLSv1.2+SSLv3",
307 {
308 {TLS1_CK_RSA_WITH_AES_128_SHA, 0},
309 {TLS1_CK_RSA_WITH_AES_128_SHA256, 0},
310 },
311 false,
312 },
313 // Spaces, semi-colons and commas are separators.
314 {
315 "AES128-SHA: AES128-SHA256 AES256-SHA ,AES256-SHA256 ; AES128-GCM-SHA256",
316 {
317 {TLS1_CK_RSA_WITH_AES_128_SHA, 0},
318 {TLS1_CK_RSA_WITH_AES_128_SHA256, 0},
319 {TLS1_CK_RSA_WITH_AES_256_SHA, 0},
320 {TLS1_CK_RSA_WITH_AES_256_SHA256, 0},
321 {TLS1_CK_RSA_WITH_AES_128_GCM_SHA256, 0},
322 },
323 // …but not in strict mode.
324 true,
325 },
326 };
327
328 static const char *kBadRules[] = {
329 // Invalid brackets.
330 "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256",
331 "RSA]",
332 "[[RSA]]",
333 // Operators inside brackets.
334 "[+RSA]",
335 // Unknown directive.
336 "@BOGUS",
337 // Empty cipher lists error at SSL_CTX_set_cipher_list.
338 "",
339 "BOGUS",
340 // COMPLEMENTOFDEFAULT is empty.
341 "COMPLEMENTOFDEFAULT",
342 // Invalid command.
343 "?BAR",
344 // Special operators are not allowed if groups are used.
345 "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256]:+FOO",
346 "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256]:!FOO",
347 "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256]:-FOO",
348 "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256]:@STRENGTH",
349 // Opcode supplied, but missing selector.
350 "+",
351 // Spaces are forbidden in equal-preference groups.
352 "[AES128-SHA | AES128-SHA256]",
353 };
354
355 static const char *kMustNotIncludeNull[] = {
356 "ALL",
357 "DEFAULT",
358 "HIGH",
359 "FIPS",
360 "SHA",
361 "SHA1",
362 "RSA",
363 "SSLv3",
364 "TLSv1",
365 "TLSv1.2",
366 };
367
368 static const CurveTest kCurveTests[] = {
369 {
370 "P-256",
371 { SSL_CURVE_SECP256R1 },
372 },
373 {
374 "P-256:P-384:P-521:X25519",
375 {
376 SSL_CURVE_SECP256R1,
377 SSL_CURVE_SECP384R1,
378 SSL_CURVE_SECP521R1,
379 SSL_CURVE_X25519,
380 },
381 },
382 {
383 "prime256v1:secp384r1:secp521r1:x25519",
384 {
385 SSL_CURVE_SECP256R1,
386 SSL_CURVE_SECP384R1,
387 SSL_CURVE_SECP521R1,
388 SSL_CURVE_X25519,
389 },
390 },
391 };
392
393 static const char *kBadCurvesLists[] = {
394 "",
395 ":",
396 "::",
397 "P-256::X25519",
398 "RSA:P-256",
399 "P-256:RSA",
400 "X25519:P-256:",
401 ":X25519:P-256",
402 };
403
CipherListToString(SSL_CTX * ctx)404 static std::string CipherListToString(SSL_CTX *ctx) {
405 bool in_group = false;
406 std::string ret;
407 const STACK_OF(SSL_CIPHER) *ciphers = SSL_CTX_get_ciphers(ctx);
408 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
409 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
410 if (!in_group && SSL_CTX_cipher_in_group(ctx, i)) {
411 ret += "\t[\n";
412 in_group = true;
413 }
414 ret += "\t";
415 if (in_group) {
416 ret += " ";
417 }
418 ret += SSL_CIPHER_get_name(cipher);
419 ret += "\n";
420 if (in_group && !SSL_CTX_cipher_in_group(ctx, i)) {
421 ret += "\t]\n";
422 in_group = false;
423 }
424 }
425 return ret;
426 }
427
CipherListsEqual(SSL_CTX * ctx,const std::vector<ExpectedCipher> & expected)428 static bool CipherListsEqual(SSL_CTX *ctx,
429 const std::vector<ExpectedCipher> &expected) {
430 const STACK_OF(SSL_CIPHER) *ciphers = SSL_CTX_get_ciphers(ctx);
431 if (sk_SSL_CIPHER_num(ciphers) != expected.size()) {
432 return false;
433 }
434
435 for (size_t i = 0; i < expected.size(); i++) {
436 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
437 if (expected[i].id != SSL_CIPHER_get_id(cipher) ||
438 expected[i].in_group_flag != !!SSL_CTX_cipher_in_group(ctx, i)) {
439 return false;
440 }
441 }
442
443 return true;
444 }
445
TEST(SSLTest,CipherRules)446 TEST(SSLTest, CipherRules) {
447 for (const CipherTest &t : kCipherTests) {
448 SCOPED_TRACE(t.rule);
449 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
450 ASSERT_TRUE(ctx);
451
452 // Test lax mode.
453 ASSERT_TRUE(SSL_CTX_set_cipher_list(ctx.get(), t.rule));
454 EXPECT_TRUE(CipherListsEqual(ctx.get(), t.expected))
455 << "Cipher rule evaluated to:\n"
456 << CipherListToString(ctx.get());
457
458 // Test strict mode.
459 if (t.strict_fail) {
460 EXPECT_FALSE(SSL_CTX_set_strict_cipher_list(ctx.get(), t.rule));
461 } else {
462 ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(ctx.get(), t.rule));
463 EXPECT_TRUE(CipherListsEqual(ctx.get(), t.expected))
464 << "Cipher rule evaluated to:\n"
465 << CipherListToString(ctx.get());
466 }
467 }
468
469 for (const char *rule : kBadRules) {
470 SCOPED_TRACE(rule);
471 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
472 ASSERT_TRUE(ctx);
473
474 EXPECT_FALSE(SSL_CTX_set_cipher_list(ctx.get(), rule));
475 ERR_clear_error();
476 }
477
478 for (const char *rule : kMustNotIncludeNull) {
479 SCOPED_TRACE(rule);
480 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
481 ASSERT_TRUE(ctx);
482
483 ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(ctx.get(), rule));
484 for (const SSL_CIPHER *cipher : SSL_CTX_get_ciphers(ctx.get())) {
485 EXPECT_NE(NID_undef, SSL_CIPHER_get_cipher_nid(cipher));
486 }
487 }
488 }
489
TEST(SSLTest,CurveRules)490 TEST(SSLTest, CurveRules) {
491 for (const CurveTest &t : kCurveTests) {
492 SCOPED_TRACE(t.rule);
493 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
494 ASSERT_TRUE(ctx);
495
496 ASSERT_TRUE(SSL_CTX_set1_curves_list(ctx.get(), t.rule));
497 ASSERT_EQ(t.expected.size(), ctx->supported_group_list_len);
498 for (size_t i = 0; i < t.expected.size(); i++) {
499 EXPECT_EQ(t.expected[i], ctx->supported_group_list[i]);
500 }
501 }
502
503 for (const char *rule : kBadCurvesLists) {
504 SCOPED_TRACE(rule);
505 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
506 ASSERT_TRUE(ctx);
507
508 EXPECT_FALSE(SSL_CTX_set1_curves_list(ctx.get(), rule));
509 ERR_clear_error();
510 }
511 }
512
513 // kOpenSSLSession is a serialized SSL_SESSION.
514 static const char kOpenSSLSession[] =
515 "MIIFqgIBAQICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
516 "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
517 "IWoJoQYCBFRDO46iBAICASyjggR6MIIEdjCCA16gAwIBAgIIK9dUvsPWSlUwDQYJ"
518 "KoZIhvcNAQEFBQAwSTELMAkGA1UEBhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMx"
519 "JTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5ldCBBdXRob3JpdHkgRzIwHhcNMTQxMDA4"
520 "MTIwNzU3WhcNMTUwMTA2MDAwMDAwWjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwK"
521 "Q2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzETMBEGA1UECgwKR29v"
522 "Z2xlIEluYzEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEB"
523 "AQUAA4IBDwAwggEKAoIBAQCcKeLrplAC+Lofy8t/wDwtB6eu72CVp0cJ4V3lknN6"
524 "huH9ct6FFk70oRIh/VBNBBz900jYy+7111Jm1b8iqOTQ9aT5C7SEhNcQFJvqzH3e"
525 "MPkb6ZSWGm1yGF7MCQTGQXF20Sk/O16FSjAynU/b3oJmOctcycWYkY0ytS/k3LBu"
526 "Id45PJaoMqjB0WypqvNeJHC3q5JjCB4RP7Nfx5jjHSrCMhw8lUMW4EaDxjaR9KDh"
527 "PLgjsk+LDIySRSRDaCQGhEOWLJZVLzLo4N6/UlctCHEllpBUSvEOyFga52qroGjg"
528 "rf3WOQ925MFwzd6AK+Ich0gDRg8sQfdLH5OuP1cfLfU1AgMBAAGjggFBMIIBPTAd"
529 "BgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdv"
530 "b2dsZS5jb20waAYIKwYBBQUHAQEEXDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtp"
531 "Lmdvb2dsZS5jb20vR0lBRzIuY3J0MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50"
532 "czEuZ29vZ2xlLmNvbS9vY3NwMB0GA1UdDgQWBBQ7a+CcxsZByOpc+xpYFcIbnUMZ"
533 "hTAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEv"
534 "MBcGA1UdIAQQMA4wDAYKKwYBBAHWeQIFATAwBgNVHR8EKTAnMCWgI6Ahhh9odHRw"
535 "Oi8vcGtpLmdvb2dsZS5jb20vR0lBRzIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCa"
536 "OXCBdoqUy5bxyq+Wrh1zsyyCFim1PH5VU2+yvDSWrgDY8ibRGJmfff3r4Lud5kal"
537 "dKs9k8YlKD3ITG7P0YT/Rk8hLgfEuLcq5cc0xqmE42xJ+Eo2uzq9rYorc5emMCxf"
538 "5L0TJOXZqHQpOEcuptZQ4OjdYMfSxk5UzueUhA3ogZKRcRkdB3WeWRp+nYRhx4St"
539 "o2rt2A0MKmY9165GHUqMK9YaaXHDXqBu7Sefr1uSoAP9gyIJKeihMivsGqJ1TD6Z"
540 "cc6LMe+dN2P8cZEQHtD1y296ul4Mivqk3jatUVL8/hCwgch9A8O4PGZq9WqBfEWm"
541 "IyHh1dPtbg1lOXdYCWtjpAIEAKUDAgEUqQUCAwGJwKqBpwSBpBwUQvoeOk0Kg36S"
542 "YTcLEkXqKwOBfF9vE4KX0NxeLwjcDTpsuh3qXEaZ992r1N38VDcyS6P7I6HBYN9B"
543 "sNHM362zZnY27GpTw+Kwd751CLoXFPoaMOe57dbBpXoro6Pd3BTbf/Tzr88K06yE"
544 "OTDKPNj3+inbMaVigtK4PLyPq+Topyzvx9USFgRvyuoxn0Hgb+R0A3j6SLRuyOdA"
545 "i4gv7Y5oliyntgMBAQA=";
546
547 // kCustomSession is a custom serialized SSL_SESSION generated by
548 // filling in missing fields from |kOpenSSLSession|. This includes
549 // providing |peer_sha256|, so |peer| is not serialized.
550 static const char kCustomSession[] =
551 "MIIBZAIBAQICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
552 "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
553 "IWoJoQYCBFRDO46iBAICASykAwQBAqUDAgEUqAcEBXdvcmxkqQUCAwGJwKqBpwSB"
554 "pBwUQvoeOk0Kg36SYTcLEkXqKwOBfF9vE4KX0NxeLwjcDTpsuh3qXEaZ992r1N38"
555 "VDcyS6P7I6HBYN9BsNHM362zZnY27GpTw+Kwd751CLoXFPoaMOe57dbBpXoro6Pd"
556 "3BTbf/Tzr88K06yEOTDKPNj3+inbMaVigtK4PLyPq+Topyzvx9USFgRvyuoxn0Hg"
557 "b+R0A3j6SLRuyOdAi4gv7Y5oliynrSIEIAYGBgYGBgYGBgYGBgYGBgYGBgYGBgYG"
558 "BgYGBgYGBgYGrgMEAQevAwQBBLADBAEF";
559
560 // kBoringSSLSession is a serialized SSL_SESSION generated from bssl client.
561 static const char kBoringSSLSession[] =
562 "MIIRwQIBAQICAwMEAsAvBCDdoGxGK26mR+8lM0uq6+k9xYuxPnwAjpcF9n0Yli9R"
563 "kQQwbyshfWhdi5XQ1++7n2L1qqrcVlmHBPpr6yknT/u4pUrpQB5FZ7vqvNn8MdHf"
564 "9rWgoQYCBFXgs7uiBAICHCCjggR6MIIEdjCCA16gAwIBAgIIf+yfD7Y6UicwDQYJ"
565 "KoZIhvcNAQELBQAwSTELMAkGA1UEBhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMx"
566 "JTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5ldCBBdXRob3JpdHkgRzIwHhcNMTUwODEy"
567 "MTQ1MzE1WhcNMTUxMTEwMDAwMDAwWjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwK"
568 "Q2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzETMBEGA1UECgwKR29v"
569 "Z2xlIEluYzEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEB"
570 "AQUAA4IBDwAwggEKAoIBAQC0MeG5YGQ0t+IeJeoneP/PrhEaieibeKYkbKVLNZpo"
571 "PLuBinvhkXZo3DC133NpCBpy6ZktBwamqyixAyuk/NU6OjgXqwwxfQ7di1AInLIU"
572 "792c7hFyNXSUCG7At8Ifi3YwBX9Ba6u/1d6rWTGZJrdCq3QU11RkKYyTq2KT5mce"
573 "Tv9iGKqSkSTlp8puy/9SZ/3DbU3U+BuqCFqeSlz7zjwFmk35acdCilpJlVDDN5C/"
574 "RCh8/UKc8PaL+cxlt531qoTENvYrflBno14YEZlCBZsPiFeUSILpKEj3Ccwhy0eL"
575 "EucWQ72YZU8mUzXBoXGn0zA0crFl5ci/2sTBBGZsylNBAgMBAAGjggFBMIIBPTAd"
576 "BgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdv"
577 "b2dsZS5jb20waAYIKwYBBQUHAQEEXDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtp"
578 "Lmdvb2dsZS5jb20vR0lBRzIuY3J0MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50"
579 "czEuZ29vZ2xlLmNvbS9vY3NwMB0GA1UdDgQWBBS/bzHxcE73Q4j3slC4BLbMtLjG"
580 "GjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEv"
581 "MBcGA1UdIAQQMA4wDAYKKwYBBAHWeQIFATAwBgNVHR8EKTAnMCWgI6Ahhh9odHRw"
582 "Oi8vcGtpLmdvb2dsZS5jb20vR0lBRzIuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQAb"
583 "qdWPZEHk0X7iKPCTHL6S3w6q1eR67goxZGFSM1lk1hjwyu7XcLJuvALVV9uY3ovE"
584 "kQZSHwT+pyOPWQhsSjO+1GyjvCvK/CAwiUmBX+bQRGaqHsRcio7xSbdVcajQ3bXd"
585 "X+s0WdbOpn6MStKAiBVloPlSxEI8pxY6x/BBCnTIk/+DMB17uZlOjG3vbAnkDkP+"
586 "n0OTucD9sHV7EVj9XUxi51nOfNBCN/s7lpUjDS/NJ4k3iwOtbCPswiot8vLO779a"
587 "f07vR03r349Iz/KTzk95rlFtX0IU+KYNxFNsanIXZ+C9FYGRXkwhHcvFb4qMUB1y"
588 "TTlM80jBMOwyjZXmjRAhpAIEAKUDAgEUqQUCAwGJwKqBpwSBpOgebbmn9NRUtMWH"
589 "+eJpqA5JLMFSMCChOsvKey3toBaCNGU7HfAEiiXNuuAdCBoK262BjQc2YYfqFzqH"
590 "zuppopXCvhohx7j/tnCNZIMgLYt/O9SXK2RYI5z8FhCCHvB4CbD5G0LGl5EFP27s"
591 "Jb6S3aTTYPkQe8yZSlxevg6NDwmTogLO9F7UUkaYmVcMQhzssEE2ZRYNwSOU6KjE"
592 "0Yj+8fAiBtbQriIEIN2L8ZlpaVrdN5KFNdvcmOxJu81P8q53X55xQyGTnGWwsgMC"
593 "ARezggvvMIIEdjCCA16gAwIBAgIIf+yfD7Y6UicwDQYJKoZIhvcNAQELBQAwSTEL"
594 "MAkGA1UEBhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2ds"
595 "ZSBJbnRlcm5ldCBBdXRob3JpdHkgRzIwHhcNMTUwODEyMTQ1MzE1WhcNMTUxMTEw"
596 "MDAwMDAwWjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQG"
597 "A1UEBwwNTW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEXMBUGA1UE"
598 "AwwOd3d3Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB"
599 "AQC0MeG5YGQ0t+IeJeoneP/PrhEaieibeKYkbKVLNZpoPLuBinvhkXZo3DC133Np"
600 "CBpy6ZktBwamqyixAyuk/NU6OjgXqwwxfQ7di1AInLIU792c7hFyNXSUCG7At8If"
601 "i3YwBX9Ba6u/1d6rWTGZJrdCq3QU11RkKYyTq2KT5mceTv9iGKqSkSTlp8puy/9S"
602 "Z/3DbU3U+BuqCFqeSlz7zjwFmk35acdCilpJlVDDN5C/RCh8/UKc8PaL+cxlt531"
603 "qoTENvYrflBno14YEZlCBZsPiFeUSILpKEj3Ccwhy0eLEucWQ72YZU8mUzXBoXGn"
604 "0zA0crFl5ci/2sTBBGZsylNBAgMBAAGjggFBMIIBPTAdBgNVHSUEFjAUBggrBgEF"
605 "BQcDAQYIKwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdvb2dsZS5jb20waAYIKwYB"
606 "BQUHAQEEXDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtpLmdvb2dsZS5jb20vR0lB"
607 "RzIuY3J0MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50czEuZ29vZ2xlLmNvbS9v"
608 "Y3NwMB0GA1UdDgQWBBS/bzHxcE73Q4j3slC4BLbMtLjGGjAMBgNVHRMBAf8EAjAA"
609 "MB8GA1UdIwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEvMBcGA1UdIAQQMA4wDAYK"
610 "KwYBBAHWeQIFATAwBgNVHR8EKTAnMCWgI6Ahhh9odHRwOi8vcGtpLmdvb2dsZS5j"
611 "b20vR0lBRzIuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQAbqdWPZEHk0X7iKPCTHL6S"
612 "3w6q1eR67goxZGFSM1lk1hjwyu7XcLJuvALVV9uY3ovEkQZSHwT+pyOPWQhsSjO+"
613 "1GyjvCvK/CAwiUmBX+bQRGaqHsRcio7xSbdVcajQ3bXdX+s0WdbOpn6MStKAiBVl"
614 "oPlSxEI8pxY6x/BBCnTIk/+DMB17uZlOjG3vbAnkDkP+n0OTucD9sHV7EVj9XUxi"
615 "51nOfNBCN/s7lpUjDS/NJ4k3iwOtbCPswiot8vLO779af07vR03r349Iz/KTzk95"
616 "rlFtX0IU+KYNxFNsanIXZ+C9FYGRXkwhHcvFb4qMUB1yTTlM80jBMOwyjZXmjRAh"
617 "MIID8DCCAtigAwIBAgIDAjqDMA0GCSqGSIb3DQEBCwUAMEIxCzAJBgNVBAYTAlVT"
618 "MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i"
619 "YWwgQ0EwHhcNMTMwNDA1MTUxNTU2WhcNMTYxMjMxMjM1OTU5WjBJMQswCQYDVQQG"
620 "EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy"
621 "bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB"
622 "AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP"
623 "VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv"
624 "h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE"
625 "ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ"
626 "EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC"
627 "DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB5zCB5DAfBgNVHSMEGDAWgBTAephojYn7"
628 "qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wDgYD"
629 "VR0PAQH/BAQDAgEGMC4GCCsGAQUFBwEBBCIwIDAeBggrBgEFBQcwAYYSaHR0cDov"
630 "L2cuc3ltY2QuY29tMBIGA1UdEwEB/wQIMAYBAf8CAQAwNQYDVR0fBC4wLDAqoCig"
631 "JoYkaHR0cDovL2cuc3ltY2IuY29tL2NybHMvZ3RnbG9iYWwuY3JsMBcGA1UdIAQQ"
632 "MA4wDAYKKwYBBAHWeQIFATANBgkqhkiG9w0BAQsFAAOCAQEAqvqpIM1qZ4PtXtR+"
633 "3h3Ef+AlBgDFJPupyC1tft6dgmUsgWM0Zj7pUsIItMsv91+ZOmqcUHqFBYx90SpI"
634 "hNMJbHzCzTWf84LuUt5oX+QAihcglvcpjZpNy6jehsgNb1aHA30DP9z6eX0hGfnI"
635 "Oi9RdozHQZJxjyXON/hKTAAj78Q1EK7gI4BzfE00LshukNYQHpmEcxpw8u1VDu4X"
636 "Bupn7jLrLN1nBz/2i8Jw3lsA5rsb0zYaImxssDVCbJAJPZPpZAkiDoUGn8JzIdPm"
637 "X4DkjYUiOnMDsWCOrmji9D6X52ASCWg23jrW4kOVWzeBkoEfu43XrVJkFleW2V40"
638 "fsg12DCCA30wggLmoAMCAQICAxK75jANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQG"
639 "EwJVUzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUg"
640 "Q2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTAyMDUyMTA0MDAwMFoXDTE4MDgyMTA0"
641 "MDAwMFowQjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xGzAZ"
642 "BgNVBAMTEkdlb1RydXN0IEdsb2JhbCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP"
643 "ADCCAQoCggEBANrMGGMw/fQXIxpWflvfPGw45HG3eJHUvKHYTPioQ7YD6U0hBwiI"
644 "2lgvZjkpvQV4i5046AW3an5xpObEYKaw74DkiSgPniXW7YPzraaRx5jJQhg1FJ2t"
645 "mEaSLk/K8YdDwRaVVy1Q74ktgHpXrfLuX2vSAI25FPgUFTXZwEaje3LIkb/JVSvN"
646 "0Jc+nCZkzN/Ogxlxyk7m1NV7qRnNVd7I7NJeOFPlXE+MLf5QIzb8ZubLjqQ5GQC3"
647 "lQI5kQsO/jgu0R0FmvZNPm8PBx2vLB6PYDni+jZTEznUXiYr2z2oFL0y6xgDKFIE"
648 "ceWrMz3hOLsHNoRinHnqFjD0X8Ar6HFr5PkCAwEAAaOB8DCB7TAfBgNVHSMEGDAW"
649 "gBRI5mj5K9KylddH2CMgEE8zmJCf1DAdBgNVHQ4EFgQUwHqYaI2J+6sFZAwRfap9"
650 "ZbjKzE4wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMw"
651 "MTAvoC2gK4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9zZWN1cmVjYS5j"
652 "cmwwTgYDVR0gBEcwRTBDBgRVHSAAMDswOQYIKwYBBQUHAgEWLWh0dHBzOi8vd3d3"
653 "Lmdlb3RydXN0LmNvbS9yZXNvdXJjZXMvcmVwb3NpdG9yeTANBgkqhkiG9w0BAQUF"
654 "AAOBgQB24RJuTksWEoYwBrKBCM/wCMfHcX5m7sLt1Dsf//DwyE7WQziwuTB9GNBV"
655 "g6JqyzYRnOhIZqNtf7gT1Ef+i1pcc/yu2RsyGTirlzQUqpbS66McFAhJtrvlke+D"
656 "NusdVm/K2rxzY5Dkf3s+Iss9B+1fOHSc4wNQTqGvmO5h8oQ/Eg==";
657
658 // kBadSessionExtraField is a custom serialized SSL_SESSION generated by replacing
659 // the final (optional) element of |kCustomSession| with tag number 30.
660 static const char kBadSessionExtraField[] =
661 "MIIBdgIBAQICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
662 "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
663 "IWoJoQYCBFRDO46iBAICASykAwQBAqUDAgEUphAEDnd3dy5nb29nbGUuY29tqAcE"
664 "BXdvcmxkqQUCAwGJwKqBpwSBpBwUQvoeOk0Kg36SYTcLEkXqKwOBfF9vE4KX0Nxe"
665 "LwjcDTpsuh3qXEaZ992r1N38VDcyS6P7I6HBYN9BsNHM362zZnY27GpTw+Kwd751"
666 "CLoXFPoaMOe57dbBpXoro6Pd3BTbf/Tzr88K06yEOTDKPNj3+inbMaVigtK4PLyP"
667 "q+Topyzvx9USFgRvyuoxn0Hgb+R0A3j6SLRuyOdAi4gv7Y5oliynrSIEIAYGBgYG"
668 "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGrgMEAQevAwQBBL4DBAEF";
669
670 // kBadSessionVersion is a custom serialized SSL_SESSION generated by replacing
671 // the version of |kCustomSession| with 2.
672 static const char kBadSessionVersion[] =
673 "MIIBdgIBAgICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
674 "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
675 "IWoJoQYCBFRDO46iBAICASykAwQBAqUDAgEUphAEDnd3dy5nb29nbGUuY29tqAcE"
676 "BXdvcmxkqQUCAwGJwKqBpwSBpBwUQvoeOk0Kg36SYTcLEkXqKwOBfF9vE4KX0Nxe"
677 "LwjcDTpsuh3qXEaZ992r1N38VDcyS6P7I6HBYN9BsNHM362zZnY27GpTw+Kwd751"
678 "CLoXFPoaMOe57dbBpXoro6Pd3BTbf/Tzr88K06yEOTDKPNj3+inbMaVigtK4PLyP"
679 "q+Topyzvx9USFgRvyuoxn0Hgb+R0A3j6SLRuyOdAi4gv7Y5oliynrSIEIAYGBgYG"
680 "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGrgMEAQevAwQBBLADBAEF";
681
682 // kBadSessionTrailingData is a custom serialized SSL_SESSION with trailing data
683 // appended.
684 static const char kBadSessionTrailingData[] =
685 "MIIBdgIBAQICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
686 "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
687 "IWoJoQYCBFRDO46iBAICASykAwQBAqUDAgEUphAEDnd3dy5nb29nbGUuY29tqAcE"
688 "BXdvcmxkqQUCAwGJwKqBpwSBpBwUQvoeOk0Kg36SYTcLEkXqKwOBfF9vE4KX0Nxe"
689 "LwjcDTpsuh3qXEaZ992r1N38VDcyS6P7I6HBYN9BsNHM362zZnY27GpTw+Kwd751"
690 "CLoXFPoaMOe57dbBpXoro6Pd3BTbf/Tzr88K06yEOTDKPNj3+inbMaVigtK4PLyP"
691 "q+Topyzvx9USFgRvyuoxn0Hgb+R0A3j6SLRuyOdAi4gv7Y5oliynrSIEIAYGBgYG"
692 "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGrgMEAQevAwQBBLADBAEFAAAA";
693
DecodeBase64(std::vector<uint8_t> * out,const char * in)694 static bool DecodeBase64(std::vector<uint8_t> *out, const char *in) {
695 size_t len;
696 if (!EVP_DecodedLength(&len, strlen(in))) {
697 fprintf(stderr, "EVP_DecodedLength failed\n");
698 return false;
699 }
700
701 out->resize(len);
702 if (!EVP_DecodeBase64(out->data(), &len, len, (const uint8_t *)in,
703 strlen(in))) {
704 fprintf(stderr, "EVP_DecodeBase64 failed\n");
705 return false;
706 }
707 out->resize(len);
708 return true;
709 }
710
TestSSL_SESSIONEncoding(const char * input_b64)711 static bool TestSSL_SESSIONEncoding(const char *input_b64) {
712 const uint8_t *cptr;
713 uint8_t *ptr;
714
715 // Decode the input.
716 std::vector<uint8_t> input;
717 if (!DecodeBase64(&input, input_b64)) {
718 return false;
719 }
720
721 // Verify the SSL_SESSION decodes.
722 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
723 if (!ssl_ctx) {
724 return false;
725 }
726 bssl::UniquePtr<SSL_SESSION> session(
727 SSL_SESSION_from_bytes(input.data(), input.size(), ssl_ctx.get()));
728 if (!session) {
729 fprintf(stderr, "SSL_SESSION_from_bytes failed\n");
730 return false;
731 }
732
733 // Verify the SSL_SESSION encoding round-trips.
734 size_t encoded_len;
735 bssl::UniquePtr<uint8_t> encoded;
736 uint8_t *encoded_raw;
737 if (!SSL_SESSION_to_bytes(session.get(), &encoded_raw, &encoded_len)) {
738 fprintf(stderr, "SSL_SESSION_to_bytes failed\n");
739 return false;
740 }
741 encoded.reset(encoded_raw);
742 if (encoded_len != input.size() ||
743 OPENSSL_memcmp(input.data(), encoded.get(), input.size()) != 0) {
744 fprintf(stderr, "SSL_SESSION_to_bytes did not round-trip\n");
745 hexdump(stderr, "Before: ", input.data(), input.size());
746 hexdump(stderr, "After: ", encoded_raw, encoded_len);
747 return false;
748 }
749
750 // Verify the SSL_SESSION also decodes with the legacy API.
751 cptr = input.data();
752 session.reset(d2i_SSL_SESSION(NULL, &cptr, input.size()));
753 if (!session || cptr != input.data() + input.size()) {
754 fprintf(stderr, "d2i_SSL_SESSION failed\n");
755 return false;
756 }
757
758 // Verify the SSL_SESSION encoding round-trips via the legacy API.
759 int len = i2d_SSL_SESSION(session.get(), NULL);
760 if (len < 0 || (size_t)len != input.size()) {
761 fprintf(stderr, "i2d_SSL_SESSION(NULL) returned invalid length\n");
762 return false;
763 }
764
765 encoded.reset((uint8_t *)OPENSSL_malloc(input.size()));
766 if (!encoded) {
767 fprintf(stderr, "malloc failed\n");
768 return false;
769 }
770
771 ptr = encoded.get();
772 len = i2d_SSL_SESSION(session.get(), &ptr);
773 if (len < 0 || (size_t)len != input.size()) {
774 fprintf(stderr, "i2d_SSL_SESSION returned invalid length\n");
775 return false;
776 }
777 if (ptr != encoded.get() + input.size()) {
778 fprintf(stderr, "i2d_SSL_SESSION did not advance ptr correctly\n");
779 return false;
780 }
781 if (OPENSSL_memcmp(input.data(), encoded.get(), input.size()) != 0) {
782 fprintf(stderr, "i2d_SSL_SESSION did not round-trip\n");
783 return false;
784 }
785
786 return true;
787 }
788
TestBadSSL_SESSIONEncoding(const char * input_b64)789 static bool TestBadSSL_SESSIONEncoding(const char *input_b64) {
790 std::vector<uint8_t> input;
791 if (!DecodeBase64(&input, input_b64)) {
792 return false;
793 }
794
795 // Verify that the SSL_SESSION fails to decode.
796 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
797 if (!ssl_ctx) {
798 return false;
799 }
800 bssl::UniquePtr<SSL_SESSION> session(
801 SSL_SESSION_from_bytes(input.data(), input.size(), ssl_ctx.get()));
802 if (session) {
803 fprintf(stderr, "SSL_SESSION_from_bytes unexpectedly succeeded\n");
804 return false;
805 }
806 ERR_clear_error();
807 return true;
808 }
809
ExpectDefaultVersion(uint16_t min_version,uint16_t max_version,const SSL_METHOD * (* method)(void))810 static void ExpectDefaultVersion(uint16_t min_version, uint16_t max_version,
811 const SSL_METHOD *(*method)(void)) {
812 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(method()));
813 ASSERT_TRUE(ctx);
814 EXPECT_EQ(min_version, ctx->conf_min_version);
815 EXPECT_EQ(max_version, ctx->conf_max_version);
816 }
817
TEST(SSLTest,DefaultVersion)818 TEST(SSLTest, DefaultVersion) {
819 // TODO(svaldez): Update this when TLS 1.3 is enabled by default.
820 ExpectDefaultVersion(TLS1_VERSION, TLS1_2_VERSION, &TLS_method);
821 ExpectDefaultVersion(TLS1_VERSION, TLS1_VERSION, &TLSv1_method);
822 ExpectDefaultVersion(TLS1_1_VERSION, TLS1_1_VERSION, &TLSv1_1_method);
823 ExpectDefaultVersion(TLS1_2_VERSION, TLS1_2_VERSION, &TLSv1_2_method);
824 ExpectDefaultVersion(TLS1_1_VERSION, TLS1_2_VERSION, &DTLS_method);
825 ExpectDefaultVersion(TLS1_1_VERSION, TLS1_1_VERSION, &DTLSv1_method);
826 ExpectDefaultVersion(TLS1_2_VERSION, TLS1_2_VERSION, &DTLSv1_2_method);
827 }
828
TEST(SSLTest,CipherProperties)829 TEST(SSLTest, CipherProperties) {
830 static const struct {
831 int id;
832 const char *standard_name;
833 int cipher_nid;
834 int digest_nid;
835 int kx_nid;
836 int auth_nid;
837 int prf_nid;
838 } kTests[] = {
839 {
840 SSL3_CK_RSA_DES_192_CBC3_SHA,
841 "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
842 NID_des_ede3_cbc,
843 NID_sha1,
844 NID_kx_rsa,
845 NID_auth_rsa,
846 NID_md5_sha1,
847 },
848 {
849 TLS1_CK_RSA_WITH_AES_128_SHA,
850 "TLS_RSA_WITH_AES_128_CBC_SHA",
851 NID_aes_128_cbc,
852 NID_sha1,
853 NID_kx_rsa,
854 NID_auth_rsa,
855 NID_md5_sha1,
856 },
857 {
858 TLS1_CK_PSK_WITH_AES_256_CBC_SHA,
859 "TLS_PSK_WITH_AES_256_CBC_SHA",
860 NID_aes_256_cbc,
861 NID_sha1,
862 NID_kx_psk,
863 NID_auth_psk,
864 NID_md5_sha1,
865 },
866 {
867 TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
868 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
869 NID_aes_128_cbc,
870 NID_sha256,
871 NID_kx_ecdhe,
872 NID_auth_rsa,
873 NID_sha256,
874 },
875 {
876 TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
877 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
878 NID_aes_256_cbc,
879 NID_sha384,
880 NID_kx_ecdhe,
881 NID_auth_rsa,
882 NID_sha384,
883 },
884 {
885 TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
886 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
887 NID_aes_128_gcm,
888 NID_undef,
889 NID_kx_ecdhe,
890 NID_auth_rsa,
891 NID_sha256,
892 },
893 {
894 TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
895 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
896 NID_aes_128_gcm,
897 NID_undef,
898 NID_kx_ecdhe,
899 NID_auth_ecdsa,
900 NID_sha256,
901 },
902 {
903 TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
904 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
905 NID_aes_256_gcm,
906 NID_undef,
907 NID_kx_ecdhe,
908 NID_auth_ecdsa,
909 NID_sha384,
910 },
911 {
912 TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA,
913 "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
914 NID_aes_128_cbc,
915 NID_sha1,
916 NID_kx_ecdhe,
917 NID_auth_psk,
918 NID_md5_sha1,
919 },
920 {
921 TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
922 "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
923 NID_chacha20_poly1305,
924 NID_undef,
925 NID_kx_ecdhe,
926 NID_auth_rsa,
927 NID_sha256,
928 },
929 {
930 TLS1_CK_AES_256_GCM_SHA384,
931 "TLS_AES_256_GCM_SHA384",
932 NID_aes_256_gcm,
933 NID_undef,
934 NID_kx_any,
935 NID_auth_any,
936 NID_sha384,
937 },
938 {
939 TLS1_CK_AES_128_GCM_SHA256,
940 "TLS_AES_128_GCM_SHA256",
941 NID_aes_128_gcm,
942 NID_undef,
943 NID_kx_any,
944 NID_auth_any,
945 NID_sha256,
946 },
947 {
948 TLS1_CK_CHACHA20_POLY1305_SHA256,
949 "TLS_CHACHA20_POLY1305_SHA256",
950 NID_chacha20_poly1305,
951 NID_undef,
952 NID_kx_any,
953 NID_auth_any,
954 NID_sha256,
955 },
956 };
957
958 for (const auto &t : kTests) {
959 SCOPED_TRACE(t.standard_name);
960
961 const SSL_CIPHER *cipher = SSL_get_cipher_by_value(t.id & 0xffff);
962 ASSERT_TRUE(cipher);
963 EXPECT_STREQ(t.standard_name, SSL_CIPHER_standard_name(cipher));
964
965 bssl::UniquePtr<char> rfc_name(SSL_CIPHER_get_rfc_name(cipher));
966 ASSERT_TRUE(rfc_name);
967 EXPECT_STREQ(t.standard_name, rfc_name.get());
968
969 EXPECT_EQ(t.cipher_nid, SSL_CIPHER_get_cipher_nid(cipher));
970 EXPECT_EQ(t.digest_nid, SSL_CIPHER_get_digest_nid(cipher));
971 EXPECT_EQ(t.kx_nid, SSL_CIPHER_get_kx_nid(cipher));
972 EXPECT_EQ(t.auth_nid, SSL_CIPHER_get_auth_nid(cipher));
973 EXPECT_EQ(t.prf_nid, SSL_CIPHER_get_prf_nid(cipher));
974 }
975 }
976
977 // CreateSessionWithTicket returns a sample |SSL_SESSION| with the specified
978 // version and ticket length or nullptr on failure.
CreateSessionWithTicket(uint16_t version,size_t ticket_len)979 static bssl::UniquePtr<SSL_SESSION> CreateSessionWithTicket(uint16_t version,
980 size_t ticket_len) {
981 std::vector<uint8_t> der;
982 if (!DecodeBase64(&der, kOpenSSLSession)) {
983 return nullptr;
984 }
985
986 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
987 if (!ssl_ctx) {
988 return nullptr;
989 }
990 bssl::UniquePtr<SSL_SESSION> session(
991 SSL_SESSION_from_bytes(der.data(), der.size(), ssl_ctx.get()));
992 if (!session) {
993 return nullptr;
994 }
995
996 session->ssl_version = version;
997
998 // Swap out the ticket for a garbage one.
999 OPENSSL_free(session->tlsext_tick);
1000 session->tlsext_tick = reinterpret_cast<uint8_t*>(OPENSSL_malloc(ticket_len));
1001 if (session->tlsext_tick == nullptr) {
1002 return nullptr;
1003 }
1004 OPENSSL_memset(session->tlsext_tick, 'a', ticket_len);
1005 session->tlsext_ticklen = ticket_len;
1006
1007 // Fix up the timeout.
1008 #if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
1009 session->time = 1234;
1010 #else
1011 session->time = time(NULL);
1012 #endif
1013 return session;
1014 }
1015
GetClientHello(SSL * ssl,std::vector<uint8_t> * out)1016 static bool GetClientHello(SSL *ssl, std::vector<uint8_t> *out) {
1017 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
1018 if (!bio) {
1019 return false;
1020 }
1021 // Do not configure a reading BIO, but record what's written to a memory BIO.
1022 BIO_up_ref(bio.get());
1023 SSL_set_bio(ssl, nullptr /* rbio */, bio.get());
1024 int ret = SSL_connect(ssl);
1025 if (ret > 0) {
1026 // SSL_connect should fail without a BIO to write to.
1027 return false;
1028 }
1029 ERR_clear_error();
1030
1031 const uint8_t *client_hello;
1032 size_t client_hello_len;
1033 if (!BIO_mem_contents(bio.get(), &client_hello, &client_hello_len)) {
1034 return false;
1035 }
1036 *out = std::vector<uint8_t>(client_hello, client_hello + client_hello_len);
1037 return true;
1038 }
1039
1040 // GetClientHelloLen creates a client SSL connection with the specified version
1041 // and ticket length. It returns the length of the ClientHello, not including
1042 // the record header, on success and zero on error.
GetClientHelloLen(uint16_t max_version,uint16_t session_version,size_t ticket_len)1043 static size_t GetClientHelloLen(uint16_t max_version, uint16_t session_version,
1044 size_t ticket_len) {
1045 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1046 bssl::UniquePtr<SSL_SESSION> session =
1047 CreateSessionWithTicket(session_version, ticket_len);
1048 if (!ctx || !session) {
1049 return 0;
1050 }
1051
1052 // Set a one-element cipher list so the baseline ClientHello is unpadded.
1053 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1054 if (!ssl || !SSL_set_session(ssl.get(), session.get()) ||
1055 !SSL_set_strict_cipher_list(ssl.get(), "ECDHE-RSA-AES128-GCM-SHA256") ||
1056 !SSL_set_max_proto_version(ssl.get(), max_version)) {
1057 return 0;
1058 }
1059
1060 std::vector<uint8_t> client_hello;
1061 if (!GetClientHello(ssl.get(), &client_hello) ||
1062 client_hello.size() <= SSL3_RT_HEADER_LENGTH) {
1063 return 0;
1064 }
1065
1066 return client_hello.size() - SSL3_RT_HEADER_LENGTH;
1067 }
1068
1069 struct PaddingTest {
1070 size_t input_len, padded_len;
1071 };
1072
1073 static const PaddingTest kPaddingTests[] = {
1074 // ClientHellos of length below 0x100 do not require padding.
1075 {0xfe, 0xfe},
1076 {0xff, 0xff},
1077 // ClientHellos of length 0x100 through 0x1fb are padded up to 0x200.
1078 {0x100, 0x200},
1079 {0x123, 0x200},
1080 {0x1fb, 0x200},
1081 // ClientHellos of length 0x1fc through 0x1ff get padded beyond 0x200. The
1082 // padding extension takes a minimum of four bytes plus one required content
1083 // byte. (To work around yet more server bugs, we avoid empty final
1084 // extensions.)
1085 {0x1fc, 0x201},
1086 {0x1fd, 0x202},
1087 {0x1fe, 0x203},
1088 {0x1ff, 0x204},
1089 // Finally, larger ClientHellos need no padding.
1090 {0x200, 0x200},
1091 {0x201, 0x201},
1092 };
1093
TestPaddingExtension(uint16_t max_version,uint16_t session_version)1094 static bool TestPaddingExtension(uint16_t max_version,
1095 uint16_t session_version) {
1096 // Sample a baseline length.
1097 size_t base_len = GetClientHelloLen(max_version, session_version, 1);
1098 if (base_len == 0) {
1099 return false;
1100 }
1101
1102 for (const PaddingTest &test : kPaddingTests) {
1103 if (base_len > test.input_len) {
1104 fprintf(stderr,
1105 "Baseline ClientHello too long (max_version = %04x, "
1106 "session_version = %04x).\n",
1107 max_version, session_version);
1108 return false;
1109 }
1110
1111 size_t padded_len = GetClientHelloLen(max_version, session_version,
1112 1 + test.input_len - base_len);
1113 if (padded_len != test.padded_len) {
1114 fprintf(stderr,
1115 "%u-byte ClientHello padded to %u bytes, not %u (max_version = "
1116 "%04x, session_version = %04x).\n",
1117 static_cast<unsigned>(test.input_len),
1118 static_cast<unsigned>(padded_len),
1119 static_cast<unsigned>(test.padded_len), max_version,
1120 session_version);
1121 return false;
1122 }
1123 }
1124
1125 return true;
1126 }
1127
GetTestCertificate()1128 static bssl::UniquePtr<X509> GetTestCertificate() {
1129 static const char kCertPEM[] =
1130 "-----BEGIN CERTIFICATE-----\n"
1131 "MIICWDCCAcGgAwIBAgIJAPuwTC6rEJsMMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV\n"
1132 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n"
1133 "aWRnaXRzIFB0eSBMdGQwHhcNMTQwNDIzMjA1MDQwWhcNMTcwNDIyMjA1MDQwWjBF\n"
1134 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n"
1135 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n"
1136 "gQDYK8imMuRi/03z0K1Zi0WnvfFHvwlYeyK9Na6XJYaUoIDAtB92kWdGMdAQhLci\n"
1137 "HnAjkXLI6W15OoV3gA/ElRZ1xUpxTMhjP6PyY5wqT5r6y8FxbiiFKKAnHmUcrgfV\n"
1138 "W28tQ+0rkLGMryRtrukXOgXBv7gcrmU7G1jC2a7WqmeI8QIDAQABo1AwTjAdBgNV\n"
1139 "HQ4EFgQUi3XVrMsIvg4fZbf6Vr5sp3Xaha8wHwYDVR0jBBgwFoAUi3XVrMsIvg4f\n"
1140 "Zbf6Vr5sp3Xaha8wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQA76Hht\n"
1141 "ldY9avcTGSwbwoiuIqv0jTL1fHFnzy3RHMLDh+Lpvolc5DSrSJHCP5WuK0eeJXhr\n"
1142 "T5oQpHL9z/cCDLAKCKRa4uV0fhEdOWBqyR9p8y5jJtye72t6CuFUV5iqcpF4BH4f\n"
1143 "j2VNHwsSrJwkD4QUGlUtH7vwnQmyCFxZMmWAJg==\n"
1144 "-----END CERTIFICATE-----\n";
1145 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kCertPEM, strlen(kCertPEM)));
1146 return bssl::UniquePtr<X509>(
1147 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
1148 }
1149
GetTestKey()1150 static bssl::UniquePtr<EVP_PKEY> GetTestKey() {
1151 static const char kKeyPEM[] =
1152 "-----BEGIN RSA PRIVATE KEY-----\n"
1153 "MIICXgIBAAKBgQDYK8imMuRi/03z0K1Zi0WnvfFHvwlYeyK9Na6XJYaUoIDAtB92\n"
1154 "kWdGMdAQhLciHnAjkXLI6W15OoV3gA/ElRZ1xUpxTMhjP6PyY5wqT5r6y8FxbiiF\n"
1155 "KKAnHmUcrgfVW28tQ+0rkLGMryRtrukXOgXBv7gcrmU7G1jC2a7WqmeI8QIDAQAB\n"
1156 "AoGBAIBy09Fd4DOq/Ijp8HeKuCMKTHqTW1xGHshLQ6jwVV2vWZIn9aIgmDsvkjCe\n"
1157 "i6ssZvnbjVcwzSoByhjN8ZCf/i15HECWDFFh6gt0P5z0MnChwzZmvatV/FXCT0j+\n"
1158 "WmGNB/gkehKjGXLLcjTb6dRYVJSCZhVuOLLcbWIV10gggJQBAkEA8S8sGe4ezyyZ\n"
1159 "m4e9r95g6s43kPqtj5rewTsUxt+2n4eVodD+ZUlCULWVNAFLkYRTBCASlSrm9Xhj\n"
1160 "QpmWAHJUkQJBAOVzQdFUaewLtdOJoPCtpYoY1zd22eae8TQEmpGOR11L6kbxLQsk\n"
1161 "aMly/DOnOaa82tqAGTdqDEZgSNmCeKKknmECQAvpnY8GUOVAubGR6c+W90iBuQLj\n"
1162 "LtFp/9ihd2w/PoDwrHZaoUYVcT4VSfJQog/k7kjE4MYXYWL8eEKg3WTWQNECQQDk\n"
1163 "104Wi91Umd1PzF0ijd2jXOERJU1wEKe6XLkYYNHWQAe5l4J4MWj9OdxFXAxIuuR/\n"
1164 "tfDwbqkta4xcux67//khAkEAvvRXLHTaa6VFzTaiiO8SaFsHV3lQyXOtMrBpB5jd\n"
1165 "moZWgjHvB2W9Ckn7sDqsPB+U2tyX0joDdQEyuiMECDY8oQ==\n"
1166 "-----END RSA PRIVATE KEY-----\n";
1167 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kKeyPEM, strlen(kKeyPEM)));
1168 return bssl::UniquePtr<EVP_PKEY>(
1169 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
1170 }
1171
GetECDSATestCertificate()1172 static bssl::UniquePtr<X509> GetECDSATestCertificate() {
1173 static const char kCertPEM[] =
1174 "-----BEGIN CERTIFICATE-----\n"
1175 "MIIBzzCCAXagAwIBAgIJANlMBNpJfb/rMAkGByqGSM49BAEwRTELMAkGA1UEBhMC\n"
1176 "QVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdp\n"
1177 "dHMgUHR5IEx0ZDAeFw0xNDA0MjMyMzIxNTdaFw0xNDA1MjMyMzIxNTdaMEUxCzAJ\n"
1178 "BgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5l\n"
1179 "dCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATmK2ni\n"
1180 "v2Wfl74vHg2UikzVl2u3qR4NRvvdqakendy6WgHn1peoChj5w8SjHlbifINI2xYa\n"
1181 "HPUdfvGULUvPciLBo1AwTjAdBgNVHQ4EFgQUq4TSrKuV8IJOFngHVVdf5CaNgtEw\n"
1182 "HwYDVR0jBBgwFoAUq4TSrKuV8IJOFngHVVdf5CaNgtEwDAYDVR0TBAUwAwEB/zAJ\n"
1183 "BgcqhkjOPQQBA0gAMEUCIQDyoDVeUTo2w4J5m+4nUIWOcAZ0lVfSKXQA9L4Vh13E\n"
1184 "BwIgfB55FGohg/B6dGh5XxSZmmi08cueFV7mHzJSYV51yRQ=\n"
1185 "-----END CERTIFICATE-----\n";
1186 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kCertPEM, strlen(kCertPEM)));
1187 return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
1188 }
1189
GetECDSATestKey()1190 static bssl::UniquePtr<EVP_PKEY> GetECDSATestKey() {
1191 static const char kKeyPEM[] =
1192 "-----BEGIN PRIVATE KEY-----\n"
1193 "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgBw8IcnrUoEqc3VnJ\n"
1194 "TYlodwi1b8ldMHcO6NHJzgqLtGqhRANCAATmK2niv2Wfl74vHg2UikzVl2u3qR4N\n"
1195 "Rvvdqakendy6WgHn1peoChj5w8SjHlbifINI2xYaHPUdfvGULUvPciLB\n"
1196 "-----END PRIVATE KEY-----\n";
1197 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kKeyPEM, strlen(kKeyPEM)));
1198 return bssl::UniquePtr<EVP_PKEY>(
1199 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
1200 }
1201
BufferFromPEM(const char * pem)1202 static bssl::UniquePtr<CRYPTO_BUFFER> BufferFromPEM(const char *pem) {
1203 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(pem, strlen(pem)));
1204 char *name, *header;
1205 uint8_t *data;
1206 long data_len;
1207 if (!PEM_read_bio(bio.get(), &name, &header, &data,
1208 &data_len)) {
1209 return nullptr;
1210 }
1211 OPENSSL_free(name);
1212 OPENSSL_free(header);
1213
1214 auto ret = bssl::UniquePtr<CRYPTO_BUFFER>(
1215 CRYPTO_BUFFER_new(data, data_len, nullptr));
1216 OPENSSL_free(data);
1217 return ret;
1218 }
1219
GetChainTestCertificateBuffer()1220 static bssl::UniquePtr<CRYPTO_BUFFER> GetChainTestCertificateBuffer() {
1221 static const char kCertPEM[] =
1222 "-----BEGIN CERTIFICATE-----\n"
1223 "MIIC0jCCAbqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwDzENMAsGA1UEAwwEQiBD\n"
1224 "QTAeFw0xNjAyMjgyMDI3MDNaFw0yNjAyMjUyMDI3MDNaMBgxFjAUBgNVBAMMDUNs\n"
1225 "aWVudCBDZXJ0IEEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDRvaz8\n"
1226 "CC/cshpCafJo4jLkHEoBqDLhdgFelJoAiQUyIqyWl2O7YHPnpJH+TgR7oelzNzt/\n"
1227 "kLRcH89M/TszB6zqyLTC4aqmvzKL0peD/jL2LWBucR0WXIvjA3zoRuF/x86+rYH3\n"
1228 "tHb+xs2PSs8EGL/Ev+ss+qTzTGEn26fuGNHkNw6tOwPpc+o8+wUtzf/kAthamo+c\n"
1229 "IDs2rQ+lP7+aLZTLeU/q4gcLutlzcK5imex5xy2jPkweq48kijK0kIzl1cPlA5d1\n"
1230 "z7C8jU50Pj9X9sQDJTN32j7UYRisJeeYQF8GaaN8SbrDI6zHgKzrRLyxDt/KQa9V\n"
1231 "iLeXANgZi+Xx9KgfAgMBAAGjLzAtMAwGA1UdEwEB/wQCMAAwHQYDVR0lBBYwFAYI\n"
1232 "KwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IBAQBFEVbmYl+2RtNw\n"
1233 "rDftRDF1v2QUbcN2ouSnQDHxeDQdSgasLzT3ui8iYu0Rw2WWcZ0DV5e0ztGPhWq7\n"
1234 "AO0B120aFRMOY+4+bzu9Q2FFkQqc7/fKTvTDzIJI5wrMnFvUfzzvxh3OHWMYSs/w\n"
1235 "giq33hTKeHEq6Jyk3btCny0Ycecyc3yGXH10sizUfiHlhviCkDuESk8mFDwDDzqW\n"
1236 "ZF0IipzFbEDHoIxLlm3GQxpiLoEV4k8KYJp3R5KBLFyxM6UGPz8h72mIPCJp2RuK\n"
1237 "MYgF91UDvVzvnYm6TfseM2+ewKirC00GOrZ7rEcFvtxnKSqYf4ckqfNdSU1Y+RRC\n"
1238 "1ngWZ7Ih\n"
1239 "-----END CERTIFICATE-----\n";
1240 return BufferFromPEM(kCertPEM);
1241 }
1242
X509FromBuffer(bssl::UniquePtr<CRYPTO_BUFFER> buffer)1243 static bssl::UniquePtr<X509> X509FromBuffer(
1244 bssl::UniquePtr<CRYPTO_BUFFER> buffer) {
1245 if (!buffer) {
1246 return nullptr;
1247 }
1248 const uint8_t *derp = CRYPTO_BUFFER_data(buffer.get());
1249 return bssl::UniquePtr<X509>(
1250 d2i_X509(NULL, &derp, CRYPTO_BUFFER_len(buffer.get())));
1251 }
1252
GetChainTestCertificate()1253 static bssl::UniquePtr<X509> GetChainTestCertificate() {
1254 return X509FromBuffer(GetChainTestCertificateBuffer());
1255 }
1256
GetChainTestIntermediateBuffer()1257 static bssl::UniquePtr<CRYPTO_BUFFER> GetChainTestIntermediateBuffer() {
1258 static const char kCertPEM[] =
1259 "-----BEGIN CERTIFICATE-----\n"
1260 "MIICwjCCAaqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwFDESMBAGA1UEAwwJQyBS\n"
1261 "b290IENBMB4XDTE2MDIyODIwMjcwM1oXDTI2MDIyNTIwMjcwM1owDzENMAsGA1UE\n"
1262 "AwwEQiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALsSCYmDip2D\n"
1263 "GkjFxw7ykz26JSjELkl6ArlYjFJ3aT/SCh8qbS4gln7RH8CPBd78oFdfhIKQrwtZ\n"
1264 "3/q21ykD9BAS3qHe2YdcJfm8/kWAy5DvXk6NXU4qX334KofBAEpgdA/igEFq1P1l\n"
1265 "HAuIfZCpMRfT+i5WohVsGi8f/NgpRvVaMONLNfgw57mz1lbtFeBEISmX0kbsuJxF\n"
1266 "Qj/Bwhi5/0HAEXG8e7zN4cEx0yPRvmOATRdVb/8dW2pwOHRJq9R5M0NUkIsTSnL7\n"
1267 "6N/z8hRAHMsV3IudC5Yd7GXW1AGu9a+iKU+Q4xcZCoj0DC99tL4VKujrV1kAeqsM\n"
1268 "cz5/dKzi6+cCAwEAAaMjMCEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n"
1269 "AQYwDQYJKoZIhvcNAQELBQADggEBAIIeZiEeNhWWQ8Y4D+AGDwqUUeG8NjCbKrXQ\n"
1270 "BlHg5wZ8xftFaiP1Dp/UAezmx2LNazdmuwrYB8lm3FVTyaPDTKEGIPS4wJKHgqH1\n"
1271 "QPDhqNm85ey7TEtI9oYjsNim/Rb+iGkIAMXaxt58SzxbjvP0kMr1JfJIZbic9vye\n"
1272 "NwIspMFIpP3FB8ywyu0T0hWtCQgL4J47nigCHpOu58deP88fS/Nyz/fyGVWOZ76b\n"
1273 "WhWwgM3P3X95fQ3d7oFPR/bVh0YV+Cf861INwplokXgXQ3/TCQ+HNXeAMWn3JLWv\n"
1274 "XFwk8owk9dq/kQGdndGgy3KTEW4ctPX5GNhf3LJ9Q7dLji4ReQ4=\n"
1275 "-----END CERTIFICATE-----\n";
1276 return BufferFromPEM(kCertPEM);
1277 }
1278
GetChainTestIntermediate()1279 static bssl::UniquePtr<X509> GetChainTestIntermediate() {
1280 return X509FromBuffer(GetChainTestIntermediateBuffer());
1281 }
1282
GetChainTestKey()1283 static bssl::UniquePtr<EVP_PKEY> GetChainTestKey() {
1284 static const char kKeyPEM[] =
1285 "-----BEGIN PRIVATE KEY-----\n"
1286 "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDRvaz8CC/cshpC\n"
1287 "afJo4jLkHEoBqDLhdgFelJoAiQUyIqyWl2O7YHPnpJH+TgR7oelzNzt/kLRcH89M\n"
1288 "/TszB6zqyLTC4aqmvzKL0peD/jL2LWBucR0WXIvjA3zoRuF/x86+rYH3tHb+xs2P\n"
1289 "Ss8EGL/Ev+ss+qTzTGEn26fuGNHkNw6tOwPpc+o8+wUtzf/kAthamo+cIDs2rQ+l\n"
1290 "P7+aLZTLeU/q4gcLutlzcK5imex5xy2jPkweq48kijK0kIzl1cPlA5d1z7C8jU50\n"
1291 "Pj9X9sQDJTN32j7UYRisJeeYQF8GaaN8SbrDI6zHgKzrRLyxDt/KQa9ViLeXANgZ\n"
1292 "i+Xx9KgfAgMBAAECggEBAK0VjSJzkyPaamcyTVSWjo7GdaBGcK60lk657RjR+lK0\n"
1293 "YJ7pkej4oM2hdsVZFsP8Cs4E33nXLa/0pDsRov/qrp0WQm2skwqGMC1I/bZ0WRPk\n"
1294 "wHaDrBBfESWnJDX/AGpVtlyOjPmgmK6J2usMPihQUDkKdAYrVWJePrMIxt1q6BMe\n"
1295 "iczs3qriMmtY3bUc4UyUwJ5fhDLjshHvfuIpYQyI6EXZM6dZksn9LylXJnigY6QJ\n"
1296 "HxOYO0BDwOsZ8yQ8J8afLk88i0GizEkgE1z3REtQUwgWfxr1WV/ud+T6/ZhSAgH9\n"
1297 "042mQvSFZnIUSEsmCvjhWuAunfxHKCTcAoYISWfzWpkCgYEA7gpf3HHU5Tn+CgUn\n"
1298 "1X5uGpG3DmcMgfeGgs2r2f/IIg/5Ac1dfYILiybL1tN9zbyLCJfcbFpWBc9hJL6f\n"
1299 "CPc5hUiwWFJqBJewxQkC1Ae/HakHbip+IZ+Jr0842O4BAArvixk4Lb7/N2Ct9sTE\n"
1300 "NJO6RtK9lbEZ5uK61DglHy8CS2UCgYEA4ZC1o36kPAMQBggajgnucb2yuUEelk0f\n"
1301 "AEr+GI32MGE+93xMr7rAhBoqLg4AITyIfEnOSQ5HwagnIHonBbv1LV/Gf9ursx8Z\n"
1302 "YOGbvT8zzzC+SU1bkDzdjAYnFQVGIjMtKOBJ3K07++ypwX1fr4QsQ8uKL8WSOWwt\n"
1303 "Z3Bym6XiZzMCgYADnhy+2OwHX85AkLt+PyGlPbmuelpyTzS4IDAQbBa6jcuW/2wA\n"
1304 "UE2km75VUXmD+u2R/9zVuLm99NzhFhSMqlUxdV1YukfqMfP5yp1EY6m/5aW7QuIP\n"
1305 "2MDa7TVL9rIFMiVZ09RKvbBbQxjhuzPQKL6X/PPspnhiTefQ+dl2k9xREQKBgHDS\n"
1306 "fMfGNEeAEKezrfSVqxphE9/tXms3L+ZpnCaT+yu/uEr5dTIAawKoQ6i9f/sf1/Sy\n"
1307 "xedsqR+IB+oKrzIDDWMgoJybN4pkZ8E5lzhVQIjFjKgFdWLzzqyW9z1gYfABQPlN\n"
1308 "FiS20WX0vgP1vcKAjdNrHzc9zyHBpgQzDmAj3NZZAoGBAI8vKCKdH7w3aL5CNkZQ\n"
1309 "2buIeWNA2HZazVwAGG5F2TU/LmXfRKnG6dX5bkU+AkBZh56jNZy//hfFSewJB4Kk\n"
1310 "buB7ERSdaNbO21zXt9FEA3+z0RfMd/Zv2vlIWOSB5nzl/7UKti3sribK6s9ZVLfi\n"
1311 "SxpiPQ8d/hmSGwn4ksrWUsJD\n"
1312 "-----END PRIVATE KEY-----\n";
1313 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kKeyPEM, strlen(kKeyPEM)));
1314 return bssl::UniquePtr<EVP_PKEY>(
1315 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
1316 }
1317
1318 // Test that |SSL_get_client_CA_list| echoes back the configured parameter even
1319 // before configuring as a server.
TEST(SSLTest,ClientCAList)1320 TEST(SSLTest, ClientCAList) {
1321 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1322 ASSERT_TRUE(ctx);
1323 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1324 ASSERT_TRUE(ssl);
1325
1326 bssl::UniquePtr<X509_NAME> name(X509_NAME_new());
1327 ASSERT_TRUE(name);
1328
1329 bssl::UniquePtr<X509_NAME> name_dup(X509_NAME_dup(name.get()));
1330 ASSERT_TRUE(name_dup);
1331
1332 bssl::UniquePtr<STACK_OF(X509_NAME)> stack(sk_X509_NAME_new_null());
1333 ASSERT_TRUE(stack);
1334
1335 ASSERT_TRUE(sk_X509_NAME_push(stack.get(), name_dup.get()));
1336 name_dup.release();
1337
1338 // |SSL_set_client_CA_list| takes ownership.
1339 SSL_set_client_CA_list(ssl.get(), stack.release());
1340
1341 STACK_OF(X509_NAME) *result = SSL_get_client_CA_list(ssl.get());
1342 ASSERT_TRUE(result);
1343 ASSERT_EQ(1u, sk_X509_NAME_num(result));
1344 EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(result, 0), name.get()));
1345 }
1346
TEST(SSLTest,AddClientCA)1347 TEST(SSLTest, AddClientCA) {
1348 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1349 ASSERT_TRUE(ctx);
1350 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1351 ASSERT_TRUE(ssl);
1352
1353 bssl::UniquePtr<X509> cert1 = GetTestCertificate();
1354 bssl::UniquePtr<X509> cert2 = GetChainTestCertificate();
1355 ASSERT_TRUE(cert1 && cert2);
1356 X509_NAME *name1 = X509_get_subject_name(cert1.get());
1357 X509_NAME *name2 = X509_get_subject_name(cert2.get());
1358
1359 EXPECT_EQ(0u, sk_X509_NAME_num(SSL_get_client_CA_list(ssl.get())));
1360
1361 ASSERT_TRUE(SSL_add_client_CA(ssl.get(), cert1.get()));
1362 ASSERT_TRUE(SSL_add_client_CA(ssl.get(), cert2.get()));
1363
1364 STACK_OF(X509_NAME) *list = SSL_get_client_CA_list(ssl.get());
1365 ASSERT_EQ(2u, sk_X509_NAME_num(list));
1366 EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 0), name1));
1367 EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 1), name2));
1368
1369 ASSERT_TRUE(SSL_add_client_CA(ssl.get(), cert1.get()));
1370
1371 list = SSL_get_client_CA_list(ssl.get());
1372 ASSERT_EQ(3u, sk_X509_NAME_num(list));
1373 EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 0), name1));
1374 EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 1), name2));
1375 EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 2), name1));
1376 }
1377
AppendSession(SSL_SESSION * session,void * arg)1378 static void AppendSession(SSL_SESSION *session, void *arg) {
1379 std::vector<SSL_SESSION*> *out =
1380 reinterpret_cast<std::vector<SSL_SESSION*>*>(arg);
1381 out->push_back(session);
1382 }
1383
1384 // CacheEquals returns true if |ctx|'s session cache consists of |expected|, in
1385 // order.
CacheEquals(SSL_CTX * ctx,const std::vector<SSL_SESSION * > & expected)1386 static bool CacheEquals(SSL_CTX *ctx,
1387 const std::vector<SSL_SESSION*> &expected) {
1388 // Check the linked list.
1389 SSL_SESSION *ptr = ctx->session_cache_head;
1390 for (SSL_SESSION *session : expected) {
1391 if (ptr != session) {
1392 return false;
1393 }
1394 // TODO(davidben): This is an absurd way to denote the end of the list.
1395 if (ptr->next ==
1396 reinterpret_cast<SSL_SESSION *>(&ctx->session_cache_tail)) {
1397 ptr = nullptr;
1398 } else {
1399 ptr = ptr->next;
1400 }
1401 }
1402 if (ptr != nullptr) {
1403 return false;
1404 }
1405
1406 // Check the hash table.
1407 std::vector<SSL_SESSION*> actual, expected_copy;
1408 lh_SSL_SESSION_doall_arg(ctx->sessions, AppendSession, &actual);
1409 expected_copy = expected;
1410
1411 std::sort(actual.begin(), actual.end());
1412 std::sort(expected_copy.begin(), expected_copy.end());
1413
1414 return actual == expected_copy;
1415 }
1416
CreateTestSession(uint32_t number)1417 static bssl::UniquePtr<SSL_SESSION> CreateTestSession(uint32_t number) {
1418 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
1419 if (!ssl_ctx) {
1420 return nullptr;
1421 }
1422 bssl::UniquePtr<SSL_SESSION> ret(SSL_SESSION_new(ssl_ctx.get()));
1423 if (!ret) {
1424 return nullptr;
1425 }
1426
1427 ret->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
1428 OPENSSL_memset(ret->session_id, 0, ret->session_id_length);
1429 OPENSSL_memcpy(ret->session_id, &number, sizeof(number));
1430 return ret;
1431 }
1432
1433 // Test that the internal session cache behaves as expected.
TEST(SSLTest,InternalSessionCache)1434 TEST(SSLTest, InternalSessionCache) {
1435 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1436 ASSERT_TRUE(ctx);
1437
1438 // Prepare 10 test sessions.
1439 std::vector<bssl::UniquePtr<SSL_SESSION>> sessions;
1440 for (int i = 0; i < 10; i++) {
1441 bssl::UniquePtr<SSL_SESSION> session = CreateTestSession(i);
1442 ASSERT_TRUE(session);
1443 sessions.push_back(std::move(session));
1444 }
1445
1446 SSL_CTX_sess_set_cache_size(ctx.get(), 5);
1447
1448 // Insert all the test sessions.
1449 for (const auto &session : sessions) {
1450 ASSERT_TRUE(SSL_CTX_add_session(ctx.get(), session.get()));
1451 }
1452
1453 // Only the last five should be in the list.
1454 ASSERT_TRUE(CacheEquals(
1455 ctx.get(), {sessions[9].get(), sessions[8].get(), sessions[7].get(),
1456 sessions[6].get(), sessions[5].get()}));
1457
1458 // Inserting an element already in the cache should fail and leave the cache
1459 // unchanged.
1460 ASSERT_FALSE(SSL_CTX_add_session(ctx.get(), sessions[7].get()));
1461 ASSERT_TRUE(CacheEquals(
1462 ctx.get(), {sessions[9].get(), sessions[8].get(), sessions[7].get(),
1463 sessions[6].get(), sessions[5].get()}));
1464
1465 // Although collisions should be impossible (256-bit session IDs), the cache
1466 // must handle them gracefully.
1467 bssl::UniquePtr<SSL_SESSION> collision(CreateTestSession(7));
1468 ASSERT_TRUE(collision);
1469 ASSERT_TRUE(SSL_CTX_add_session(ctx.get(), collision.get()));
1470 ASSERT_TRUE(CacheEquals(
1471 ctx.get(), {collision.get(), sessions[9].get(), sessions[8].get(),
1472 sessions[6].get(), sessions[5].get()}));
1473
1474 // Removing sessions behaves correctly.
1475 ASSERT_TRUE(SSL_CTX_remove_session(ctx.get(), sessions[6].get()));
1476 ASSERT_TRUE(CacheEquals(ctx.get(), {collision.get(), sessions[9].get(),
1477 sessions[8].get(), sessions[5].get()}));
1478
1479 // Removing sessions requires an exact match.
1480 ASSERT_FALSE(SSL_CTX_remove_session(ctx.get(), sessions[0].get()));
1481 ASSERT_FALSE(SSL_CTX_remove_session(ctx.get(), sessions[7].get()));
1482
1483 // The cache remains unchanged.
1484 ASSERT_TRUE(CacheEquals(ctx.get(), {collision.get(), sessions[9].get(),
1485 sessions[8].get(), sessions[5].get()}));
1486 }
1487
EpochFromSequence(uint64_t seq)1488 static uint16_t EpochFromSequence(uint64_t seq) {
1489 return static_cast<uint16_t>(seq >> 48);
1490 }
1491
1492 static const uint8_t kTestName[] = {
1493 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
1494 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08,
1495 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65,
1496 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49,
1497 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67,
1498 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64,
1499 };
1500
CompleteHandshakes(SSL * client,SSL * server)1501 static bool CompleteHandshakes(SSL *client, SSL *server) {
1502 // Drive both their handshakes to completion.
1503 for (;;) {
1504 int client_ret = SSL_do_handshake(client);
1505 int client_err = SSL_get_error(client, client_ret);
1506 if (client_err != SSL_ERROR_NONE &&
1507 client_err != SSL_ERROR_WANT_READ &&
1508 client_err != SSL_ERROR_WANT_WRITE &&
1509 client_err != SSL_ERROR_PENDING_TICKET) {
1510 fprintf(stderr, "Client error: %d\n", client_err);
1511 return false;
1512 }
1513
1514 int server_ret = SSL_do_handshake(server);
1515 int server_err = SSL_get_error(server, server_ret);
1516 if (server_err != SSL_ERROR_NONE &&
1517 server_err != SSL_ERROR_WANT_READ &&
1518 server_err != SSL_ERROR_WANT_WRITE &&
1519 server_err != SSL_ERROR_PENDING_TICKET) {
1520 fprintf(stderr, "Server error: %d\n", server_err);
1521 return false;
1522 }
1523
1524 if (client_ret == 1 && server_ret == 1) {
1525 break;
1526 }
1527 }
1528
1529 return true;
1530 }
1531
1532 struct ClientConfig {
1533 SSL_SESSION *session = nullptr;
1534 std::string servername;
1535 };
1536
ConnectClientAndServer(bssl::UniquePtr<SSL> * out_client,bssl::UniquePtr<SSL> * out_server,SSL_CTX * client_ctx,SSL_CTX * server_ctx,const ClientConfig & config=ClientConfig (),bool do_handshake=true)1537 static bool ConnectClientAndServer(bssl::UniquePtr<SSL> *out_client,
1538 bssl::UniquePtr<SSL> *out_server,
1539 SSL_CTX *client_ctx, SSL_CTX *server_ctx,
1540 const ClientConfig &config = ClientConfig(),
1541 bool do_handshake = true) {
1542 bssl::UniquePtr<SSL> client(SSL_new(client_ctx)), server(SSL_new(server_ctx));
1543 if (!client || !server) {
1544 return false;
1545 }
1546 SSL_set_connect_state(client.get());
1547 SSL_set_accept_state(server.get());
1548
1549 if (config.session) {
1550 SSL_set_session(client.get(), config.session);
1551 }
1552 if (!config.servername.empty() &&
1553 !SSL_set_tlsext_host_name(client.get(), config.servername.c_str())) {
1554 return false;
1555 }
1556
1557 BIO *bio1, *bio2;
1558 if (!BIO_new_bio_pair(&bio1, 0, &bio2, 0)) {
1559 return false;
1560 }
1561 // SSL_set_bio takes ownership.
1562 SSL_set_bio(client.get(), bio1, bio1);
1563 SSL_set_bio(server.get(), bio2, bio2);
1564
1565 if (do_handshake && !CompleteHandshakes(client.get(), server.get())) {
1566 return false;
1567 }
1568
1569 *out_client = std::move(client);
1570 *out_server = std::move(server);
1571 return true;
1572 }
1573
1574 // SSLVersionTest executes its test cases under all available protocol versions.
1575 // Test cases call |Connect| to create a connection using context objects with
1576 // the protocol version fixed to the current version under test.
1577 class SSLVersionTest : public ::testing::TestWithParam<VersionParam> {
1578 protected:
SSLVersionTest()1579 SSLVersionTest() : cert_(GetTestCertificate()), key_(GetTestKey()) {}
1580
SetUp()1581 void SetUp() { ResetContexts(); }
1582
CreateContext() const1583 bssl::UniquePtr<SSL_CTX> CreateContext() const {
1584 const SSL_METHOD *method = is_dtls() ? DTLS_method() : TLS_method();
1585 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(method));
1586 if (!ctx || !SSL_CTX_set_min_proto_version(ctx.get(), version()) ||
1587 !SSL_CTX_set_max_proto_version(ctx.get(), version())) {
1588 return nullptr;
1589 }
1590 return ctx;
1591 }
1592
ResetContexts()1593 void ResetContexts() {
1594 ASSERT_TRUE(cert_);
1595 ASSERT_TRUE(key_);
1596 client_ctx_ = CreateContext();
1597 ASSERT_TRUE(client_ctx_);
1598 server_ctx_ = CreateContext();
1599 ASSERT_TRUE(server_ctx_);
1600 // Set up a server cert. Client certs can be set up explicitly.
1601 ASSERT_TRUE(UseCertAndKey(server_ctx_.get()));
1602 }
1603
UseCertAndKey(SSL_CTX * ctx) const1604 bool UseCertAndKey(SSL_CTX *ctx) const {
1605 return SSL_CTX_use_certificate(ctx, cert_.get()) &&
1606 SSL_CTX_use_PrivateKey(ctx, key_.get());
1607 }
1608
Connect(const ClientConfig & config=ClientConfig ())1609 bool Connect(const ClientConfig &config = ClientConfig()) {
1610 return ConnectClientAndServer(&client_, &server_, client_ctx_.get(),
1611 server_ctx_.get(), config);
1612 }
1613
version() const1614 uint16_t version() const { return GetParam().version; }
1615
is_dtls() const1616 bool is_dtls() const {
1617 return GetParam().ssl_method == VersionParam::is_dtls;
1618 }
1619
1620 bssl::UniquePtr<SSL> client_, server_;
1621 bssl::UniquePtr<SSL_CTX> server_ctx_, client_ctx_;
1622 bssl::UniquePtr<X509> cert_;
1623 bssl::UniquePtr<EVP_PKEY> key_;
1624 };
1625
1626 INSTANTIATE_TEST_CASE_P(WithVersion, SSLVersionTest,
1627 testing::ValuesIn(kAllVersions),
__anonb772228d0402(const testing::TestParamInfo<VersionParam> &i) 1628 [](const testing::TestParamInfo<VersionParam> &i) {
1629 return i.param.name;
1630 });
1631
TEST_P(SSLVersionTest,SequenceNumber)1632 TEST_P(SSLVersionTest, SequenceNumber) {
1633 ASSERT_TRUE(Connect());
1634
1635 // Drain any post-handshake messages to ensure there are no unread records
1636 // on either end.
1637 uint8_t byte = 0;
1638 ASSERT_LE(SSL_read(client_.get(), &byte, 1), 0);
1639 ASSERT_LE(SSL_read(server_.get(), &byte, 1), 0);
1640
1641 uint64_t client_read_seq = SSL_get_read_sequence(client_.get());
1642 uint64_t client_write_seq = SSL_get_write_sequence(client_.get());
1643 uint64_t server_read_seq = SSL_get_read_sequence(server_.get());
1644 uint64_t server_write_seq = SSL_get_write_sequence(server_.get());
1645
1646 if (is_dtls()) {
1647 // Both client and server must be at epoch 1.
1648 EXPECT_EQ(EpochFromSequence(client_read_seq), 1);
1649 EXPECT_EQ(EpochFromSequence(client_write_seq), 1);
1650 EXPECT_EQ(EpochFromSequence(server_read_seq), 1);
1651 EXPECT_EQ(EpochFromSequence(server_write_seq), 1);
1652
1653 // The next record to be written should exceed the largest received.
1654 EXPECT_GT(client_write_seq, server_read_seq);
1655 EXPECT_GT(server_write_seq, client_read_seq);
1656 } else {
1657 // The next record to be written should equal the next to be received.
1658 EXPECT_EQ(client_write_seq, server_read_seq);
1659 EXPECT_EQ(server_write_seq, client_read_seq);
1660 }
1661
1662 // Send a record from client to server.
1663 EXPECT_EQ(SSL_write(client_.get(), &byte, 1), 1);
1664 EXPECT_EQ(SSL_read(server_.get(), &byte, 1), 1);
1665
1666 // The client write and server read sequence numbers should have
1667 // incremented.
1668 EXPECT_EQ(client_write_seq + 1, SSL_get_write_sequence(client_.get()));
1669 EXPECT_EQ(server_read_seq + 1, SSL_get_read_sequence(server_.get()));
1670 }
1671
TEST_P(SSLVersionTest,OneSidedShutdown)1672 TEST_P(SSLVersionTest, OneSidedShutdown) {
1673 // SSL_shutdown is a no-op in DTLS.
1674 if (is_dtls()) {
1675 return;
1676 }
1677 ASSERT_TRUE(Connect());
1678
1679 // Shut down half the connection. SSL_shutdown will return 0 to signal only
1680 // one side has shut down.
1681 ASSERT_EQ(SSL_shutdown(client_.get()), 0);
1682
1683 // Reading from the server should consume the EOF.
1684 uint8_t byte;
1685 ASSERT_EQ(SSL_read(server_.get(), &byte, 1), 0);
1686 ASSERT_EQ(SSL_get_error(server_.get(), 0), SSL_ERROR_ZERO_RETURN);
1687
1688 // However, the server may continue to write data and then shut down the
1689 // connection.
1690 byte = 42;
1691 ASSERT_EQ(SSL_write(server_.get(), &byte, 1), 1);
1692 ASSERT_EQ(SSL_read(client_.get(), &byte, 1), 1);
1693 ASSERT_EQ(byte, 42);
1694
1695 // The server may then shutdown the connection.
1696 EXPECT_EQ(SSL_shutdown(server_.get()), 1);
1697 EXPECT_EQ(SSL_shutdown(client_.get()), 1);
1698 }
1699
TEST(SSLTest,SessionDuplication)1700 TEST(SSLTest, SessionDuplication) {
1701 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
1702 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
1703 ASSERT_TRUE(client_ctx);
1704 ASSERT_TRUE(server_ctx);
1705
1706 bssl::UniquePtr<X509> cert = GetTestCertificate();
1707 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
1708 ASSERT_TRUE(cert);
1709 ASSERT_TRUE(key);
1710 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
1711 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
1712
1713 bssl::UniquePtr<SSL> client, server;
1714 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
1715 server_ctx.get()));
1716
1717 SSL_SESSION *session0 = SSL_get_session(client.get());
1718 bssl::UniquePtr<SSL_SESSION> session1 =
1719 bssl::SSL_SESSION_dup(session0, SSL_SESSION_DUP_ALL);
1720 ASSERT_TRUE(session1);
1721
1722 session1->not_resumable = 0;
1723
1724 uint8_t *s0_bytes, *s1_bytes;
1725 size_t s0_len, s1_len;
1726
1727 ASSERT_TRUE(SSL_SESSION_to_bytes(session0, &s0_bytes, &s0_len));
1728 bssl::UniquePtr<uint8_t> free_s0(s0_bytes);
1729
1730 ASSERT_TRUE(SSL_SESSION_to_bytes(session1.get(), &s1_bytes, &s1_len));
1731 bssl::UniquePtr<uint8_t> free_s1(s1_bytes);
1732
1733 EXPECT_EQ(Bytes(s0_bytes, s0_len), Bytes(s1_bytes, s1_len));
1734 }
1735
ExpectFDs(const SSL * ssl,int rfd,int wfd)1736 static void ExpectFDs(const SSL *ssl, int rfd, int wfd) {
1737 EXPECT_EQ(rfd, SSL_get_fd(ssl));
1738 EXPECT_EQ(rfd, SSL_get_rfd(ssl));
1739 EXPECT_EQ(wfd, SSL_get_wfd(ssl));
1740
1741 // The wrapper BIOs are always equal when fds are equal, even if set
1742 // individually.
1743 if (rfd == wfd) {
1744 EXPECT_EQ(SSL_get_rbio(ssl), SSL_get_wbio(ssl));
1745 }
1746 }
1747
TEST(SSLTest,SetFD)1748 TEST(SSLTest, SetFD) {
1749 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1750 ASSERT_TRUE(ctx);
1751
1752 // Test setting different read and write FDs.
1753 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1754 ASSERT_TRUE(ssl);
1755 EXPECT_TRUE(SSL_set_rfd(ssl.get(), 1));
1756 EXPECT_TRUE(SSL_set_wfd(ssl.get(), 2));
1757 ExpectFDs(ssl.get(), 1, 2);
1758
1759 // Test setting the same FD.
1760 ssl.reset(SSL_new(ctx.get()));
1761 ASSERT_TRUE(ssl);
1762 EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1763 ExpectFDs(ssl.get(), 1, 1);
1764
1765 // Test setting the same FD one side at a time.
1766 ssl.reset(SSL_new(ctx.get()));
1767 ASSERT_TRUE(ssl);
1768 EXPECT_TRUE(SSL_set_rfd(ssl.get(), 1));
1769 EXPECT_TRUE(SSL_set_wfd(ssl.get(), 1));
1770 ExpectFDs(ssl.get(), 1, 1);
1771
1772 // Test setting the same FD in the other order.
1773 ssl.reset(SSL_new(ctx.get()));
1774 ASSERT_TRUE(ssl);
1775 EXPECT_TRUE(SSL_set_wfd(ssl.get(), 1));
1776 EXPECT_TRUE(SSL_set_rfd(ssl.get(), 1));
1777 ExpectFDs(ssl.get(), 1, 1);
1778
1779 // Test changing the read FD partway through.
1780 ssl.reset(SSL_new(ctx.get()));
1781 ASSERT_TRUE(ssl);
1782 EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1783 EXPECT_TRUE(SSL_set_rfd(ssl.get(), 2));
1784 ExpectFDs(ssl.get(), 2, 1);
1785
1786 // Test changing the write FD partway through.
1787 ssl.reset(SSL_new(ctx.get()));
1788 ASSERT_TRUE(ssl);
1789 EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1790 EXPECT_TRUE(SSL_set_wfd(ssl.get(), 2));
1791 ExpectFDs(ssl.get(), 1, 2);
1792
1793 // Test a no-op change to the read FD partway through.
1794 ssl.reset(SSL_new(ctx.get()));
1795 ASSERT_TRUE(ssl);
1796 EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1797 EXPECT_TRUE(SSL_set_rfd(ssl.get(), 1));
1798 ExpectFDs(ssl.get(), 1, 1);
1799
1800 // Test a no-op change to the write FD partway through.
1801 ssl.reset(SSL_new(ctx.get()));
1802 ASSERT_TRUE(ssl);
1803 EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1804 EXPECT_TRUE(SSL_set_wfd(ssl.get(), 1));
1805 ExpectFDs(ssl.get(), 1, 1);
1806
1807 // ASan builds will implicitly test that the internal |BIO| reference-counting
1808 // is correct.
1809 }
1810
TEST(SSLTest,SetBIO)1811 TEST(SSLTest, SetBIO) {
1812 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1813 ASSERT_TRUE(ctx);
1814
1815 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1816 bssl::UniquePtr<BIO> bio1(BIO_new(BIO_s_mem())), bio2(BIO_new(BIO_s_mem())),
1817 bio3(BIO_new(BIO_s_mem()));
1818 ASSERT_TRUE(ssl);
1819 ASSERT_TRUE(bio1);
1820 ASSERT_TRUE(bio2);
1821 ASSERT_TRUE(bio3);
1822
1823 // SSL_set_bio takes one reference when the parameters are the same.
1824 BIO_up_ref(bio1.get());
1825 SSL_set_bio(ssl.get(), bio1.get(), bio1.get());
1826
1827 // Repeating the call does nothing.
1828 SSL_set_bio(ssl.get(), bio1.get(), bio1.get());
1829
1830 // It takes one reference each when the parameters are different.
1831 BIO_up_ref(bio2.get());
1832 BIO_up_ref(bio3.get());
1833 SSL_set_bio(ssl.get(), bio2.get(), bio3.get());
1834
1835 // Repeating the call does nothing.
1836 SSL_set_bio(ssl.get(), bio2.get(), bio3.get());
1837
1838 // It takes one reference when changing only wbio.
1839 BIO_up_ref(bio1.get());
1840 SSL_set_bio(ssl.get(), bio2.get(), bio1.get());
1841
1842 // It takes one reference when changing only rbio and the two are different.
1843 BIO_up_ref(bio3.get());
1844 SSL_set_bio(ssl.get(), bio3.get(), bio1.get());
1845
1846 // If setting wbio to rbio, it takes no additional references.
1847 SSL_set_bio(ssl.get(), bio3.get(), bio3.get());
1848
1849 // From there, wbio may be switched to something else.
1850 BIO_up_ref(bio1.get());
1851 SSL_set_bio(ssl.get(), bio3.get(), bio1.get());
1852
1853 // If setting rbio to wbio, it takes no additional references.
1854 SSL_set_bio(ssl.get(), bio1.get(), bio1.get());
1855
1856 // From there, rbio may be switched to something else, but, for historical
1857 // reasons, it takes a reference to both parameters.
1858 BIO_up_ref(bio1.get());
1859 BIO_up_ref(bio2.get());
1860 SSL_set_bio(ssl.get(), bio2.get(), bio1.get());
1861
1862 // ASAN builds will implicitly test that the internal |BIO| reference-counting
1863 // is correct.
1864 }
1865
VerifySucceed(X509_STORE_CTX * store_ctx,void * arg)1866 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) { return 1; }
1867
TEST_P(SSLVersionTest,GetPeerCertificate)1868 TEST_P(SSLVersionTest, GetPeerCertificate) {
1869 ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
1870
1871 // Configure both client and server to accept any certificate.
1872 SSL_CTX_set_verify(client_ctx_.get(),
1873 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1874 nullptr);
1875 SSL_CTX_set_cert_verify_callback(client_ctx_.get(), VerifySucceed, NULL);
1876 SSL_CTX_set_verify(server_ctx_.get(),
1877 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1878 nullptr);
1879 SSL_CTX_set_cert_verify_callback(server_ctx_.get(), VerifySucceed, NULL);
1880
1881 ASSERT_TRUE(Connect());
1882
1883 // Client and server should both see the leaf certificate.
1884 bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(server_.get()));
1885 ASSERT_TRUE(peer);
1886 ASSERT_EQ(X509_cmp(cert_.get(), peer.get()), 0);
1887
1888 peer.reset(SSL_get_peer_certificate(client_.get()));
1889 ASSERT_TRUE(peer);
1890 ASSERT_EQ(X509_cmp(cert_.get(), peer.get()), 0);
1891
1892 // However, for historical reasons, the X509 chain includes the leaf on the
1893 // client, but does not on the server.
1894 EXPECT_EQ(sk_X509_num(SSL_get_peer_cert_chain(client_.get())), 1u);
1895 EXPECT_EQ(sk_CRYPTO_BUFFER_num(SSL_get0_peer_certificates(client_.get())),
1896 1u);
1897
1898 EXPECT_EQ(sk_X509_num(SSL_get_peer_cert_chain(server_.get())), 0u);
1899 EXPECT_EQ(sk_CRYPTO_BUFFER_num(SSL_get0_peer_certificates(server_.get())),
1900 1u);
1901 }
1902
TEST_P(SSLVersionTest,NoPeerCertificate)1903 TEST_P(SSLVersionTest, NoPeerCertificate) {
1904 SSL_CTX_set_verify(server_ctx_.get(), SSL_VERIFY_PEER, nullptr);
1905 SSL_CTX_set_cert_verify_callback(server_ctx_.get(), VerifySucceed, NULL);
1906 SSL_CTX_set_cert_verify_callback(client_ctx_.get(), VerifySucceed, NULL);
1907
1908 ASSERT_TRUE(Connect());
1909
1910 // Server should not see a peer certificate.
1911 bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(server_.get()));
1912 ASSERT_FALSE(peer);
1913 ASSERT_FALSE(SSL_get0_peer_certificates(server_.get()));
1914 }
1915
TEST_P(SSLVersionTest,RetainOnlySHA256OfCerts)1916 TEST_P(SSLVersionTest, RetainOnlySHA256OfCerts) {
1917 uint8_t *cert_der = NULL;
1918 int cert_der_len = i2d_X509(cert_.get(), &cert_der);
1919 ASSERT_GE(cert_der_len, 0);
1920 bssl::UniquePtr<uint8_t> free_cert_der(cert_der);
1921
1922 uint8_t cert_sha256[SHA256_DIGEST_LENGTH];
1923 SHA256(cert_der, cert_der_len, cert_sha256);
1924
1925 ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
1926
1927 // Configure both client and server to accept any certificate, but the
1928 // server must retain only the SHA-256 of the peer.
1929 SSL_CTX_set_verify(client_ctx_.get(),
1930 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1931 nullptr);
1932 SSL_CTX_set_verify(server_ctx_.get(),
1933 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1934 nullptr);
1935 SSL_CTX_set_cert_verify_callback(client_ctx_.get(), VerifySucceed, NULL);
1936 SSL_CTX_set_cert_verify_callback(server_ctx_.get(), VerifySucceed, NULL);
1937 SSL_CTX_set_retain_only_sha256_of_client_certs(server_ctx_.get(), 1);
1938
1939 ASSERT_TRUE(Connect());
1940
1941 // The peer certificate has been dropped.
1942 bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(server_.get()));
1943 EXPECT_FALSE(peer);
1944
1945 SSL_SESSION *session = SSL_get_session(server_.get());
1946 EXPECT_TRUE(session->peer_sha256_valid);
1947
1948 EXPECT_EQ(Bytes(cert_sha256), Bytes(session->peer_sha256));
1949 }
1950
1951 // Tests that our ClientHellos do not change unexpectedly. These are purely
1952 // change detection tests. If they fail as part of an intentional ClientHello
1953 // change, update the test vector.
TEST(SSLTest,ClientHello)1954 TEST(SSLTest, ClientHello) {
1955 struct {
1956 uint16_t max_version;
1957 std::vector<uint8_t> expected;
1958 } kTests[] = {
1959 {SSL3_VERSION,
1960 {0x16, 0x03, 0x00, 0x00, 0x3b, 0x01, 0x00, 0x00, 0x37, 0x03, 0x00,
1961 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1962 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1963 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1964 0x00, 0x10, 0xc0, 0x09, 0xc0, 0x13, 0xc0, 0x0a, 0xc0, 0x14, 0x00,
1965 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x00, 0xff, 0x01, 0x00}},
1966 {TLS1_VERSION,
1967 {0x16, 0x03, 0x01, 0x00, 0x5a, 0x01, 0x00, 0x00, 0x56, 0x03, 0x01, 0x00,
1968 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1969 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1970 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0xc0, 0x09,
1971 0xc0, 0x13, 0xc0, 0x0a, 0xc0, 0x14, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a,
1972 0x01, 0x00, 0x00, 0x1f, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00, 0x17, 0x00,
1973 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00,
1974 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18}},
1975 {TLS1_1_VERSION,
1976 {0x16, 0x03, 0x01, 0x00, 0x5a, 0x01, 0x00, 0x00, 0x56, 0x03, 0x02, 0x00,
1977 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1978 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1979 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0xc0, 0x09,
1980 0xc0, 0x13, 0xc0, 0x0a, 0xc0, 0x14, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a,
1981 0x01, 0x00, 0x00, 0x1f, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00, 0x17, 0x00,
1982 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00,
1983 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18}},
1984 {TLS1_2_VERSION,
1985 {0x16, 0x03, 0x01, 0x00, 0x8e, 0x01, 0x00, 0x00, 0x8a, 0x03, 0x03, 0x00,
1986 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1987 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1988 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0xcc, 0xa9,
1989 0xcc, 0xa8, 0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30, 0xc0, 0x09,
1990 0xc0, 0x23, 0xc0, 0x13, 0xc0, 0x27, 0xc0, 0x0a, 0xc0, 0x24, 0xc0, 0x14,
1991 0xc0, 0x28, 0x00, 0x9c, 0x00, 0x9d, 0x00, 0x2f, 0x00, 0x3c, 0x00, 0x35,
1992 0x00, 0x3d, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x37, 0xff, 0x01, 0x00, 0x01,
1993 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00,
1994 0x14, 0x00, 0x12, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01, 0x05, 0x03, 0x08,
1995 0x05, 0x05, 0x01, 0x08, 0x06, 0x06, 0x01, 0x02, 0x01, 0x00, 0x0b, 0x00,
1996 0x02, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1d, 0x00,
1997 0x17, 0x00, 0x18}},
1998 // TODO(davidben): Add a change detector for TLS 1.3 once the spec and our
1999 // implementation has settled enough that it won't change.
2000 };
2001
2002 for (const auto &t : kTests) {
2003 SCOPED_TRACE(t.max_version);
2004
2005 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
2006 ASSERT_TRUE(ctx);
2007 // Our default cipher list varies by CPU capabilities, so manually place the
2008 // ChaCha20 ciphers in front.
2009 const char *cipher_list = "CHACHA20:ALL";
2010 // SSLv3 is off by default.
2011 ASSERT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), SSL3_VERSION));
2012 ASSERT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), t.max_version));
2013 ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(ctx.get(), cipher_list));
2014
2015 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
2016 ASSERT_TRUE(ssl);
2017 std::vector<uint8_t> client_hello;
2018 ASSERT_TRUE(GetClientHello(ssl.get(), &client_hello));
2019
2020 // Zero the client_random.
2021 constexpr size_t kRandomOffset = 1 + 2 + 2 + // record header
2022 1 + 3 + // handshake message header
2023 2; // client_version
2024 ASSERT_GE(client_hello.size(), kRandomOffset + SSL3_RANDOM_SIZE);
2025 OPENSSL_memset(client_hello.data() + kRandomOffset, 0, SSL3_RANDOM_SIZE);
2026
2027 if (client_hello != t.expected) {
2028 ADD_FAILURE() << "ClientHellos did not match.";
2029 // Print the value manually so it is easier to update the test vector.
2030 for (size_t i = 0; i < client_hello.size(); i += 12) {
2031 printf(" %c", i == 0 ? '{' : ' ');
2032 for (size_t j = i; j < client_hello.size() && j < i + 12; j++) {
2033 if (j > i) {
2034 printf(" ");
2035 }
2036 printf("0x%02x", client_hello[j]);
2037 if (j < client_hello.size() - 1) {
2038 printf(",");
2039 }
2040 }
2041 if (i + 12 >= client_hello.size()) {
2042 printf("}}");
2043 }
2044 printf("\n");
2045 }
2046 }
2047 }
2048 }
2049
2050 static bssl::UniquePtr<SSL_SESSION> g_last_session;
2051
SaveLastSession(SSL * ssl,SSL_SESSION * session)2052 static int SaveLastSession(SSL *ssl, SSL_SESSION *session) {
2053 // Save the most recent session.
2054 g_last_session.reset(session);
2055 return 1;
2056 }
2057
CreateClientSession(SSL_CTX * client_ctx,SSL_CTX * server_ctx,const ClientConfig & config=ClientConfig ())2058 static bssl::UniquePtr<SSL_SESSION> CreateClientSession(
2059 SSL_CTX *client_ctx, SSL_CTX *server_ctx,
2060 const ClientConfig &config = ClientConfig()) {
2061 g_last_session = nullptr;
2062 SSL_CTX_sess_set_new_cb(client_ctx, SaveLastSession);
2063
2064 // Connect client and server to get a session.
2065 bssl::UniquePtr<SSL> client, server;
2066 if (!ConnectClientAndServer(&client, &server, client_ctx, server_ctx,
2067 config)) {
2068 fprintf(stderr, "Failed to connect client and server.\n");
2069 return nullptr;
2070 }
2071
2072 // Run the read loop to account for post-handshake tickets in TLS 1.3.
2073 SSL_read(client.get(), nullptr, 0);
2074
2075 SSL_CTX_sess_set_new_cb(client_ctx, nullptr);
2076
2077 if (!g_last_session) {
2078 fprintf(stderr, "Client did not receive a session.\n");
2079 return nullptr;
2080 }
2081 return std::move(g_last_session);
2082 }
2083
ExpectSessionReused(SSL_CTX * client_ctx,SSL_CTX * server_ctx,SSL_SESSION * session,bool want_reused)2084 static void ExpectSessionReused(SSL_CTX *client_ctx, SSL_CTX *server_ctx,
2085 SSL_SESSION *session, bool want_reused) {
2086 bssl::UniquePtr<SSL> client, server;
2087 ClientConfig config;
2088 config.session = session;
2089 EXPECT_TRUE(
2090 ConnectClientAndServer(&client, &server, client_ctx, server_ctx, config));
2091
2092 EXPECT_EQ(SSL_session_reused(client.get()), SSL_session_reused(server.get()));
2093
2094 bool was_reused = !!SSL_session_reused(client.get());
2095 EXPECT_EQ(was_reused, want_reused);
2096 }
2097
ExpectSessionRenewed(SSL_CTX * client_ctx,SSL_CTX * server_ctx,SSL_SESSION * session)2098 static bssl::UniquePtr<SSL_SESSION> ExpectSessionRenewed(SSL_CTX *client_ctx,
2099 SSL_CTX *server_ctx,
2100 SSL_SESSION *session) {
2101 g_last_session = nullptr;
2102 SSL_CTX_sess_set_new_cb(client_ctx, SaveLastSession);
2103
2104 bssl::UniquePtr<SSL> client, server;
2105 ClientConfig config;
2106 config.session = session;
2107 if (!ConnectClientAndServer(&client, &server, client_ctx, server_ctx,
2108 config)) {
2109 fprintf(stderr, "Failed to connect client and server.\n");
2110 return nullptr;
2111 }
2112
2113 if (SSL_session_reused(client.get()) != SSL_session_reused(server.get())) {
2114 fprintf(stderr, "Client and server were inconsistent.\n");
2115 return nullptr;
2116 }
2117
2118 if (!SSL_session_reused(client.get())) {
2119 fprintf(stderr, "Session was not reused.\n");
2120 return nullptr;
2121 }
2122
2123 // Run the read loop to account for post-handshake tickets in TLS 1.3.
2124 SSL_read(client.get(), nullptr, 0);
2125
2126 SSL_CTX_sess_set_new_cb(client_ctx, nullptr);
2127
2128 if (!g_last_session) {
2129 fprintf(stderr, "Client did not receive a renewed session.\n");
2130 return nullptr;
2131 }
2132 return std::move(g_last_session);
2133 }
2134
ExpectTicketKeyChanged(SSL_CTX * ctx,uint8_t * inout_key,bool changed)2135 static void ExpectTicketKeyChanged(SSL_CTX *ctx, uint8_t *inout_key,
2136 bool changed) {
2137 uint8_t new_key[kTicketKeyLen];
2138 // May return 0, 1 or 48.
2139 ASSERT_EQ(SSL_CTX_get_tlsext_ticket_keys(ctx, new_key, kTicketKeyLen), 1);
2140 if (changed) {
2141 ASSERT_NE(Bytes(inout_key, kTicketKeyLen), Bytes(new_key));
2142 } else {
2143 ASSERT_EQ(Bytes(inout_key, kTicketKeyLen), Bytes(new_key));
2144 }
2145 OPENSSL_memcpy(inout_key, new_key, kTicketKeyLen);
2146 }
2147
SwitchSessionIDContextSNI(SSL * ssl,int * out_alert,void * arg)2148 static int SwitchSessionIDContextSNI(SSL *ssl, int *out_alert, void *arg) {
2149 static const uint8_t kContext[] = {3};
2150
2151 if (!SSL_set_session_id_context(ssl, kContext, sizeof(kContext))) {
2152 return SSL_TLSEXT_ERR_ALERT_FATAL;
2153 }
2154
2155 return SSL_TLSEXT_ERR_OK;
2156 }
2157
TEST_P(SSLVersionTest,SessionIDContext)2158 TEST_P(SSLVersionTest, SessionIDContext) {
2159 static const uint8_t kContext1[] = {1};
2160 static const uint8_t kContext2[] = {2};
2161
2162 ASSERT_TRUE(SSL_CTX_set_session_id_context(server_ctx_.get(), kContext1,
2163 sizeof(kContext1)));
2164
2165 SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
2166 SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
2167
2168 bssl::UniquePtr<SSL_SESSION> session =
2169 CreateClientSession(client_ctx_.get(), server_ctx_.get());
2170 ASSERT_TRUE(session);
2171
2172 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2173 session.get(),
2174 true /* expect session reused */));
2175
2176 // Change the session ID context.
2177 ASSERT_TRUE(SSL_CTX_set_session_id_context(server_ctx_.get(), kContext2,
2178 sizeof(kContext2)));
2179
2180 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2181 session.get(),
2182 false /* expect session not reused */));
2183
2184 // Change the session ID context back and install an SNI callback to switch
2185 // it.
2186 ASSERT_TRUE(SSL_CTX_set_session_id_context(server_ctx_.get(), kContext1,
2187 sizeof(kContext1)));
2188
2189 SSL_CTX_set_tlsext_servername_callback(server_ctx_.get(),
2190 SwitchSessionIDContextSNI);
2191
2192 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2193 session.get(),
2194 false /* expect session not reused */));
2195
2196 // Switch the session ID context with the early callback instead.
2197 SSL_CTX_set_tlsext_servername_callback(server_ctx_.get(), nullptr);
2198 SSL_CTX_set_select_certificate_cb(
2199 server_ctx_.get(),
2200 [](const SSL_CLIENT_HELLO *client_hello) -> ssl_select_cert_result_t {
2201 static const uint8_t kContext[] = {3};
2202
2203 if (!SSL_set_session_id_context(client_hello->ssl, kContext,
2204 sizeof(kContext))) {
2205 return ssl_select_cert_error;
2206 }
2207
2208 return ssl_select_cert_success;
2209 });
2210
2211 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2212 session.get(),
2213 false /* expect session not reused */));
2214 }
2215
2216 static timeval g_current_time;
2217
CurrentTimeCallback(const SSL * ssl,timeval * out_clock)2218 static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
2219 *out_clock = g_current_time;
2220 }
2221
FrozenTimeCallback(const SSL * ssl,timeval * out_clock)2222 static void FrozenTimeCallback(const SSL *ssl, timeval *out_clock) {
2223 out_clock->tv_sec = 1000;
2224 out_clock->tv_usec = 0;
2225 }
2226
RenewTicketCallback(SSL * ssl,uint8_t * key_name,uint8_t * iv,EVP_CIPHER_CTX * ctx,HMAC_CTX * hmac_ctx,int encrypt)2227 static int RenewTicketCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
2228 EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
2229 int encrypt) {
2230 static const uint8_t kZeros[16] = {0};
2231
2232 if (encrypt) {
2233 OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
2234 RAND_bytes(iv, 16);
2235 } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
2236 return 0;
2237 }
2238
2239 if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
2240 !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
2241 return -1;
2242 }
2243
2244 // Returning two from the callback in decrypt mode renews the
2245 // session in TLS 1.2 and below.
2246 return encrypt ? 1 : 2;
2247 }
2248
GetServerTicketTime(long * out,const SSL_SESSION * session)2249 static bool GetServerTicketTime(long *out, const SSL_SESSION *session) {
2250 if (session->tlsext_ticklen < 16 + 16 + SHA256_DIGEST_LENGTH) {
2251 return false;
2252 }
2253
2254 const uint8_t *ciphertext = session->tlsext_tick + 16 + 16;
2255 size_t len = session->tlsext_ticklen - 16 - 16 - SHA256_DIGEST_LENGTH;
2256 std::unique_ptr<uint8_t[]> plaintext(new uint8_t[len]);
2257
2258 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
2259 // Fuzzer-mode tickets are unencrypted.
2260 OPENSSL_memcpy(plaintext.get(), ciphertext, len);
2261 #else
2262 static const uint8_t kZeros[16] = {0};
2263 const uint8_t *iv = session->tlsext_tick + 16;
2264 bssl::ScopedEVP_CIPHER_CTX ctx;
2265 int len1, len2;
2266 if (!EVP_DecryptInit_ex(ctx.get(), EVP_aes_128_cbc(), nullptr, kZeros, iv) ||
2267 !EVP_DecryptUpdate(ctx.get(), plaintext.get(), &len1, ciphertext, len) ||
2268 !EVP_DecryptFinal_ex(ctx.get(), plaintext.get() + len1, &len2)) {
2269 return false;
2270 }
2271
2272 len = static_cast<size_t>(len1 + len2);
2273 #endif
2274
2275 bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
2276 if (!ssl_ctx) {
2277 return false;
2278 }
2279 bssl::UniquePtr<SSL_SESSION> server_session(
2280 SSL_SESSION_from_bytes(plaintext.get(), len, ssl_ctx.get()));
2281 if (!server_session) {
2282 return false;
2283 }
2284
2285 *out = server_session->time;
2286 return true;
2287 }
2288
TEST_P(SSLVersionTest,SessionTimeout)2289 TEST_P(SSLVersionTest, SessionTimeout) {
2290 for (bool server_test : {false, true}) {
2291 SCOPED_TRACE(server_test);
2292
2293 ResetContexts();
2294 SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
2295 SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
2296
2297 static const time_t kStartTime = 1000;
2298 g_current_time.tv_sec = kStartTime;
2299
2300 // We are willing to use a longer lifetime for TLS 1.3 sessions as
2301 // resumptions still perform ECDHE.
2302 const time_t timeout = version() == TLS1_3_VERSION
2303 ? SSL_DEFAULT_SESSION_PSK_DHE_TIMEOUT
2304 : SSL_DEFAULT_SESSION_TIMEOUT;
2305
2306 // Both client and server must enforce session timeouts. We configure the
2307 // other side with a frozen clock so it never expires tickets.
2308 if (server_test) {
2309 SSL_CTX_set_current_time_cb(client_ctx_.get(), FrozenTimeCallback);
2310 SSL_CTX_set_current_time_cb(server_ctx_.get(), CurrentTimeCallback);
2311 } else {
2312 SSL_CTX_set_current_time_cb(client_ctx_.get(), CurrentTimeCallback);
2313 SSL_CTX_set_current_time_cb(server_ctx_.get(), FrozenTimeCallback);
2314 }
2315
2316 // Configure a ticket callback which renews tickets.
2317 SSL_CTX_set_tlsext_ticket_key_cb(server_ctx_.get(), RenewTicketCallback);
2318
2319 bssl::UniquePtr<SSL_SESSION> session =
2320 CreateClientSession(client_ctx_.get(), server_ctx_.get());
2321 ASSERT_TRUE(session);
2322
2323 // Advance the clock just behind the timeout.
2324 g_current_time.tv_sec += timeout - 1;
2325
2326 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2327 session.get(),
2328 true /* expect session reused */));
2329
2330 // Advance the clock one more second.
2331 g_current_time.tv_sec++;
2332
2333 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2334 session.get(),
2335 false /* expect session not reused */));
2336
2337 // Rewind the clock to before the session was minted.
2338 g_current_time.tv_sec = kStartTime - 1;
2339
2340 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2341 session.get(),
2342 false /* expect session not reused */));
2343
2344 // SSL 3.0 cannot renew sessions.
2345 if (version() == SSL3_VERSION) {
2346 continue;
2347 }
2348
2349 // Renew the session 10 seconds before expiration.
2350 time_t new_start_time = kStartTime + timeout - 10;
2351 g_current_time.tv_sec = new_start_time;
2352 bssl::UniquePtr<SSL_SESSION> new_session = ExpectSessionRenewed(
2353 client_ctx_.get(), server_ctx_.get(), session.get());
2354 ASSERT_TRUE(new_session);
2355
2356 // This new session is not the same object as before.
2357 EXPECT_NE(session.get(), new_session.get());
2358
2359 // Check the sessions have timestamps measured from issuance.
2360 long session_time = 0;
2361 if (server_test) {
2362 ASSERT_TRUE(GetServerTicketTime(&session_time, new_session.get()));
2363 } else {
2364 session_time = new_session->time;
2365 }
2366
2367 ASSERT_EQ(session_time, g_current_time.tv_sec);
2368
2369 if (version() == TLS1_3_VERSION) {
2370 // Renewal incorporates fresh key material in TLS 1.3, so we extend the
2371 // lifetime TLS 1.3.
2372 g_current_time.tv_sec = new_start_time + timeout - 1;
2373 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2374 new_session.get(),
2375 true /* expect session reused */));
2376
2377 // The new session expires after the new timeout.
2378 g_current_time.tv_sec = new_start_time + timeout + 1;
2379 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2380 new_session.get(),
2381 false /* expect session ot reused */));
2382
2383 // Renew the session until it begins just past the auth timeout.
2384 time_t auth_end_time = kStartTime + SSL_DEFAULT_SESSION_AUTH_TIMEOUT;
2385 while (new_start_time < auth_end_time - 1000) {
2386 // Get as close as possible to target start time.
2387 new_start_time =
2388 std::min(auth_end_time - 1000, new_start_time + timeout - 1);
2389 g_current_time.tv_sec = new_start_time;
2390 new_session = ExpectSessionRenewed(client_ctx_.get(), server_ctx_.get(),
2391 new_session.get());
2392 ASSERT_TRUE(new_session);
2393 }
2394
2395 // Now the session's lifetime is bound by the auth timeout.
2396 g_current_time.tv_sec = auth_end_time - 1;
2397 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2398 new_session.get(),
2399 true /* expect session reused */));
2400
2401 g_current_time.tv_sec = auth_end_time + 1;
2402 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2403 new_session.get(),
2404 false /* expect session ot reused */));
2405 } else {
2406 // The new session is usable just before the old expiration.
2407 g_current_time.tv_sec = kStartTime + timeout - 1;
2408 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2409 new_session.get(),
2410 true /* expect session reused */));
2411
2412 // Renewal does not extend the lifetime, so it is not usable beyond the
2413 // old expiration.
2414 g_current_time.tv_sec = kStartTime + timeout + 1;
2415 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2416 new_session.get(),
2417 false /* expect session not reused */));
2418 }
2419 }
2420 }
2421
TEST_P(SSLVersionTest,DefaultTicketKeyInitialization)2422 TEST_P(SSLVersionTest, DefaultTicketKeyInitialization) {
2423 static const uint8_t kZeroKey[kTicketKeyLen] = {};
2424 uint8_t ticket_key[kTicketKeyLen];
2425 ASSERT_EQ(1, SSL_CTX_get_tlsext_ticket_keys(server_ctx_.get(), ticket_key,
2426 kTicketKeyLen));
2427 ASSERT_NE(0, OPENSSL_memcmp(ticket_key, kZeroKey, kTicketKeyLen));
2428 }
2429
TEST_P(SSLVersionTest,DefaultTicketKeyRotation)2430 TEST_P(SSLVersionTest, DefaultTicketKeyRotation) {
2431 if (GetParam().version == SSL3_VERSION) {
2432 return;
2433 }
2434
2435 static const time_t kStartTime = 1001;
2436 g_current_time.tv_sec = kStartTime;
2437 uint8_t ticket_key[kTicketKeyLen];
2438
2439 // We use session reuse as a proxy for ticket decryption success, hence
2440 // disable session timeouts.
2441 SSL_CTX_set_timeout(server_ctx_.get(), std::numeric_limits<uint32_t>::max());
2442 SSL_CTX_set_session_psk_dhe_timeout(server_ctx_.get(),
2443 std::numeric_limits<uint32_t>::max());
2444
2445 SSL_CTX_set_current_time_cb(client_ctx_.get(), FrozenTimeCallback);
2446 SSL_CTX_set_current_time_cb(server_ctx_.get(), CurrentTimeCallback);
2447
2448 SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
2449 SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_OFF);
2450
2451 // Initialize ticket_key with the current key.
2452 TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2453 true /* changed */));
2454
2455 // Verify ticket resumption actually works.
2456 bssl::UniquePtr<SSL> client, server;
2457 bssl::UniquePtr<SSL_SESSION> session =
2458 CreateClientSession(client_ctx_.get(), server_ctx_.get());
2459 ASSERT_TRUE(session);
2460 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2461 session.get(), true /* reused */));
2462
2463 // Advance time to just before key rotation.
2464 g_current_time.tv_sec += SSL_DEFAULT_TICKET_KEY_ROTATION_INTERVAL - 1;
2465 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2466 session.get(), true /* reused */));
2467 TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2468 false /* NOT changed */));
2469
2470 // Force key rotation.
2471 g_current_time.tv_sec += 1;
2472 bssl::UniquePtr<SSL_SESSION> new_session =
2473 CreateClientSession(client_ctx_.get(), server_ctx_.get());
2474 TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2475 true /* changed */));
2476
2477 // Resumption with both old and new ticket should work.
2478 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2479 session.get(), true /* reused */));
2480 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2481 new_session.get(), true /* reused */));
2482 TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2483 false /* NOT changed */));
2484
2485 // Force key rotation again. Resumption with the old ticket now fails.
2486 g_current_time.tv_sec += SSL_DEFAULT_TICKET_KEY_ROTATION_INTERVAL;
2487 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2488 session.get(), false /* NOT reused */));
2489 TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2490 true /* changed */));
2491
2492 // But resumption with the newer session still works.
2493 TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2494 new_session.get(), true /* reused */));
2495 }
2496
SwitchContext(SSL * ssl,int * out_alert,void * arg)2497 static int SwitchContext(SSL *ssl, int *out_alert, void *arg) {
2498 SSL_CTX *ctx = reinterpret_cast<SSL_CTX *>(arg);
2499 SSL_set_SSL_CTX(ssl, ctx);
2500 return SSL_TLSEXT_ERR_OK;
2501 }
2502
TEST_P(SSLVersionTest,SNICallback)2503 TEST_P(SSLVersionTest, SNICallback) {
2504 // SSL 3.0 lacks extensions.
2505 if (version() == SSL3_VERSION) {
2506 return;
2507 }
2508
2509 bssl::UniquePtr<X509> cert2 = GetECDSATestCertificate();
2510 ASSERT_TRUE(cert2);
2511 bssl::UniquePtr<EVP_PKEY> key2 = GetECDSATestKey();
2512 ASSERT_TRUE(key2);
2513
2514 // Test that switching the |SSL_CTX| at the SNI callback behaves correctly.
2515 static const uint16_t kECDSAWithSHA256 = SSL_SIGN_ECDSA_SECP256R1_SHA256;
2516
2517 static const uint8_t kSCTList[] = {0, 6, 0, 4, 5, 6, 7, 8};
2518 static const uint8_t kOCSPResponse[] = {1, 2, 3, 4};
2519
2520 bssl::UniquePtr<SSL_CTX> server_ctx2 = CreateContext();
2521 ASSERT_TRUE(server_ctx2);
2522 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx2.get(), cert2.get()));
2523 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx2.get(), key2.get()));
2524 ASSERT_TRUE(SSL_CTX_set_signed_cert_timestamp_list(
2525 server_ctx2.get(), kSCTList, sizeof(kSCTList)));
2526 ASSERT_TRUE(SSL_CTX_set_ocsp_response(server_ctx2.get(), kOCSPResponse,
2527 sizeof(kOCSPResponse)));
2528 // Historically signing preferences would be lost in some cases with the
2529 // SNI callback, which triggers the TLS 1.2 SHA-1 default. To ensure
2530 // this doesn't happen when |version| is TLS 1.2, configure the private
2531 // key to only sign SHA-256.
2532 ASSERT_TRUE(SSL_CTX_set_signing_algorithm_prefs(server_ctx2.get(),
2533 &kECDSAWithSHA256, 1));
2534
2535 SSL_CTX_set_tlsext_servername_callback(server_ctx_.get(), SwitchContext);
2536 SSL_CTX_set_tlsext_servername_arg(server_ctx_.get(), server_ctx2.get());
2537
2538 SSL_CTX_enable_signed_cert_timestamps(client_ctx_.get());
2539 SSL_CTX_enable_ocsp_stapling(client_ctx_.get());
2540
2541 ASSERT_TRUE(Connect());
2542
2543 // The client should have received |cert2|.
2544 bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(client_.get()));
2545 ASSERT_TRUE(peer);
2546 EXPECT_EQ(X509_cmp(peer.get(), cert2.get()), 0);
2547
2548 // The client should have received |server_ctx2|'s SCT list.
2549 const uint8_t *data;
2550 size_t len;
2551 SSL_get0_signed_cert_timestamp_list(client_.get(), &data, &len);
2552 EXPECT_EQ(Bytes(kSCTList), Bytes(data, len));
2553
2554 // The client should have received |server_ctx2|'s OCSP response.
2555 SSL_get0_ocsp_response(client_.get(), &data, &len);
2556 EXPECT_EQ(Bytes(kOCSPResponse), Bytes(data, len));
2557 }
2558
2559 // Test that the early callback can swap the maximum version.
TEST(SSLTest,EarlyCallbackVersionSwitch)2560 TEST(SSLTest, EarlyCallbackVersionSwitch) {
2561 bssl::UniquePtr<X509> cert = GetTestCertificate();
2562 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
2563 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
2564 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
2565 ASSERT_TRUE(cert);
2566 ASSERT_TRUE(key);
2567 ASSERT_TRUE(server_ctx);
2568 ASSERT_TRUE(client_ctx);
2569 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
2570 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
2571 ASSERT_TRUE(SSL_CTX_set_max_proto_version(client_ctx.get(), TLS1_3_VERSION));
2572 ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), TLS1_3_VERSION));
2573
2574 SSL_CTX_set_select_certificate_cb(
2575 server_ctx.get(),
2576 [](const SSL_CLIENT_HELLO *client_hello) -> ssl_select_cert_result_t {
2577 if (!SSL_set_max_proto_version(client_hello->ssl, TLS1_2_VERSION)) {
2578 return ssl_select_cert_error;
2579 }
2580
2581 return ssl_select_cert_success;
2582 });
2583
2584 bssl::UniquePtr<SSL> client, server;
2585 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
2586 server_ctx.get()));
2587 EXPECT_EQ(TLS1_2_VERSION, SSL_version(client.get()));
2588 }
2589
TEST(SSLTest,SetVersion)2590 TEST(SSLTest, SetVersion) {
2591 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
2592 ASSERT_TRUE(ctx);
2593
2594 // Set valid TLS versions.
2595 EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_VERSION));
2596 EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_1_VERSION));
2597 EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_VERSION));
2598 EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_1_VERSION));
2599
2600 // Invalid TLS versions are rejected.
2601 EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), DTLS1_VERSION));
2602 EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0x0200));
2603 EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0x1234));
2604 EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), DTLS1_VERSION));
2605 EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0x0200));
2606 EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0x1234));
2607
2608 // Zero is the default version.
2609 EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), 0));
2610 EXPECT_EQ(TLS1_2_VERSION, ctx->conf_max_version);
2611 EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), 0));
2612 EXPECT_EQ(TLS1_VERSION, ctx->conf_min_version);
2613
2614 // SSL 3.0 and TLS 1.3 are available, but not by default.
2615 EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), SSL3_VERSION));
2616 EXPECT_EQ(SSL3_VERSION, ctx->conf_min_version);
2617 EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_3_VERSION));
2618 EXPECT_EQ(TLS1_3_VERSION, ctx->conf_max_version);
2619
2620 // TLS1_3_DRAFT_VERSION is not an API-level version.
2621 EXPECT_FALSE(
2622 SSL_CTX_set_max_proto_version(ctx.get(), TLS1_3_DRAFT23_VERSION));
2623 ERR_clear_error();
2624
2625 ctx.reset(SSL_CTX_new(DTLS_method()));
2626 ASSERT_TRUE(ctx);
2627
2628 EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), DTLS1_VERSION));
2629 EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), DTLS1_2_VERSION));
2630 EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), DTLS1_VERSION));
2631 EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), DTLS1_2_VERSION));
2632
2633 EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_VERSION));
2634 EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0xfefe /* DTLS 1.1 */));
2635 EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0xfffe /* DTLS 0.1 */));
2636 EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0x1234));
2637 EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_VERSION));
2638 EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0xfefe /* DTLS 1.1 */));
2639 EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0xfffe /* DTLS 0.1 */));
2640 EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0x1234));
2641
2642 EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), 0));
2643 EXPECT_EQ(TLS1_2_VERSION, ctx->conf_max_version);
2644 EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), 0));
2645 EXPECT_EQ(TLS1_1_VERSION, ctx->conf_min_version);
2646 }
2647
GetVersionName(uint16_t version)2648 static const char *GetVersionName(uint16_t version) {
2649 switch (version) {
2650 case SSL3_VERSION:
2651 return "SSLv3";
2652 case TLS1_VERSION:
2653 return "TLSv1";
2654 case TLS1_1_VERSION:
2655 return "TLSv1.1";
2656 case TLS1_2_VERSION:
2657 return "TLSv1.2";
2658 case TLS1_3_VERSION:
2659 return "TLSv1.3";
2660 case DTLS1_VERSION:
2661 return "DTLSv1";
2662 case DTLS1_2_VERSION:
2663 return "DTLSv1.2";
2664 default:
2665 return "???";
2666 }
2667 }
2668
TEST_P(SSLVersionTest,Version)2669 TEST_P(SSLVersionTest, Version) {
2670 ASSERT_TRUE(Connect());
2671
2672 EXPECT_EQ(SSL_version(client_.get()), version());
2673 EXPECT_EQ(SSL_version(server_.get()), version());
2674
2675 // Test the version name is reported as expected.
2676 const char *version_name = GetVersionName(version());
2677 EXPECT_EQ(strcmp(version_name, SSL_get_version(client_.get())), 0);
2678 EXPECT_EQ(strcmp(version_name, SSL_get_version(server_.get())), 0);
2679
2680 // Test SSL_SESSION reports the same name.
2681 const char *client_name =
2682 SSL_SESSION_get_version(SSL_get_session(client_.get()));
2683 const char *server_name =
2684 SSL_SESSION_get_version(SSL_get_session(server_.get()));
2685 EXPECT_EQ(strcmp(version_name, client_name), 0);
2686 EXPECT_EQ(strcmp(version_name, server_name), 0);
2687 }
2688
2689 // Tests that that |SSL_get_pending_cipher| is available during the ALPN
2690 // selection callback.
TEST_P(SSLVersionTest,ALPNCipherAvailable)2691 TEST_P(SSLVersionTest, ALPNCipherAvailable) {
2692 // SSL 3.0 lacks extensions.
2693 if (version() == SSL3_VERSION) {
2694 return;
2695 }
2696
2697 ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
2698
2699 static const uint8_t kALPNProtos[] = {0x03, 'f', 'o', 'o'};
2700 ASSERT_EQ(SSL_CTX_set_alpn_protos(client_ctx_.get(), kALPNProtos,
2701 sizeof(kALPNProtos)),
2702 0);
2703
2704 // The ALPN callback does not fail the handshake on error, so have the
2705 // callback write a boolean.
2706 std::pair<uint16_t, bool> callback_state(version(), false);
2707 SSL_CTX_set_alpn_select_cb(
2708 server_ctx_.get(),
2709 [](SSL *ssl, const uint8_t **out, uint8_t *out_len, const uint8_t *in,
2710 unsigned in_len, void *arg) -> int {
2711 auto state = reinterpret_cast<std::pair<uint16_t, bool> *>(arg);
2712 if (SSL_get_pending_cipher(ssl) != nullptr &&
2713 SSL_version(ssl) == state->first) {
2714 state->second = true;
2715 }
2716 return SSL_TLSEXT_ERR_NOACK;
2717 },
2718 &callback_state);
2719
2720 ASSERT_TRUE(Connect());
2721
2722 ASSERT_TRUE(callback_state.second);
2723 }
2724
TEST_P(SSLVersionTest,SSLClearSessionResumption)2725 TEST_P(SSLVersionTest, SSLClearSessionResumption) {
2726 // Skip this for TLS 1.3. TLS 1.3's ticket mechanism is incompatible with this
2727 // API pattern.
2728 if (version() == TLS1_3_VERSION) {
2729 return;
2730 }
2731
2732 ASSERT_TRUE(Connect());
2733
2734 EXPECT_FALSE(SSL_session_reused(client_.get()));
2735 EXPECT_FALSE(SSL_session_reused(server_.get()));
2736
2737 // Reset everything.
2738 ASSERT_TRUE(SSL_clear(client_.get()));
2739 ASSERT_TRUE(SSL_clear(server_.get()));
2740
2741 // Attempt to connect a second time.
2742 ASSERT_TRUE(CompleteHandshakes(client_.get(), server_.get()));
2743
2744 // |SSL_clear| should implicitly offer the previous session to the server.
2745 EXPECT_TRUE(SSL_session_reused(client_.get()));
2746 EXPECT_TRUE(SSL_session_reused(server_.get()));
2747 }
2748
ChainsEqual(STACK_OF (X509)* chain,const std::vector<X509 * > & expected)2749 static bool ChainsEqual(STACK_OF(X509) * chain,
2750 const std::vector<X509 *> &expected) {
2751 if (sk_X509_num(chain) != expected.size()) {
2752 return false;
2753 }
2754
2755 for (size_t i = 0; i < expected.size(); i++) {
2756 if (X509_cmp(sk_X509_value(chain, i), expected[i]) != 0) {
2757 return false;
2758 }
2759 }
2760
2761 return true;
2762 }
2763
TEST_P(SSLVersionTest,AutoChain)2764 TEST_P(SSLVersionTest, AutoChain) {
2765 cert_ = GetChainTestCertificate();
2766 ASSERT_TRUE(cert_);
2767 key_ = GetChainTestKey();
2768 ASSERT_TRUE(key_);
2769 bssl::UniquePtr<X509> intermediate = GetChainTestIntermediate();
2770 ASSERT_TRUE(intermediate);
2771
2772 ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
2773 ASSERT_TRUE(UseCertAndKey(server_ctx_.get()));
2774
2775 // Configure both client and server to accept any certificate. Add
2776 // |intermediate| to the cert store.
2777 ASSERT_TRUE(X509_STORE_add_cert(SSL_CTX_get_cert_store(client_ctx_.get()),
2778 intermediate.get()));
2779 ASSERT_TRUE(X509_STORE_add_cert(SSL_CTX_get_cert_store(server_ctx_.get()),
2780 intermediate.get()));
2781 SSL_CTX_set_verify(client_ctx_.get(),
2782 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2783 nullptr);
2784 SSL_CTX_set_verify(server_ctx_.get(),
2785 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2786 nullptr);
2787 SSL_CTX_set_cert_verify_callback(client_ctx_.get(), VerifySucceed, NULL);
2788 SSL_CTX_set_cert_verify_callback(server_ctx_.get(), VerifySucceed, NULL);
2789
2790 // By default, the client and server should each only send the leaf.
2791 ASSERT_TRUE(Connect());
2792
2793 EXPECT_TRUE(
2794 ChainsEqual(SSL_get_peer_full_cert_chain(client_.get()), {cert_.get()}));
2795 EXPECT_TRUE(
2796 ChainsEqual(SSL_get_peer_full_cert_chain(server_.get()), {cert_.get()}));
2797
2798 // If auto-chaining is enabled, then the intermediate is sent.
2799 SSL_CTX_clear_mode(client_ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
2800 SSL_CTX_clear_mode(server_ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
2801 ASSERT_TRUE(Connect());
2802
2803 EXPECT_TRUE(ChainsEqual(SSL_get_peer_full_cert_chain(client_.get()),
2804 {cert_.get(), intermediate.get()}));
2805 EXPECT_TRUE(ChainsEqual(SSL_get_peer_full_cert_chain(server_.get()),
2806 {cert_.get(), intermediate.get()}));
2807
2808 // Auto-chaining does not override explicitly-configured intermediates.
2809 ASSERT_TRUE(SSL_CTX_add1_chain_cert(client_ctx_.get(), cert_.get()));
2810 ASSERT_TRUE(SSL_CTX_add1_chain_cert(server_ctx_.get(), cert_.get()));
2811 ASSERT_TRUE(Connect());
2812
2813 EXPECT_TRUE(ChainsEqual(SSL_get_peer_full_cert_chain(client_.get()),
2814 {cert_.get(), cert_.get()}));
2815
2816 EXPECT_TRUE(ChainsEqual(SSL_get_peer_full_cert_chain(server_.get()),
2817 {cert_.get(), cert_.get()}));
2818 }
2819
ExpectBadWriteRetry()2820 static bool ExpectBadWriteRetry() {
2821 int err = ERR_get_error();
2822 if (ERR_GET_LIB(err) != ERR_LIB_SSL ||
2823 ERR_GET_REASON(err) != SSL_R_BAD_WRITE_RETRY) {
2824 char buf[ERR_ERROR_STRING_BUF_LEN];
2825 ERR_error_string_n(err, buf, sizeof(buf));
2826 fprintf(stderr, "Wanted SSL_R_BAD_WRITE_RETRY, got: %s.\n", buf);
2827 return false;
2828 }
2829
2830 if (ERR_peek_error() != 0) {
2831 fprintf(stderr, "Unexpected error following SSL_R_BAD_WRITE_RETRY.\n");
2832 return false;
2833 }
2834
2835 return true;
2836 }
2837
TEST_P(SSLVersionTest,SSLWriteRetry)2838 TEST_P(SSLVersionTest, SSLWriteRetry) {
2839 if (is_dtls()) {
2840 return;
2841 }
2842
2843 for (bool enable_partial_write : {false, true}) {
2844 SCOPED_TRACE(enable_partial_write);
2845
2846 // Connect a client and server.
2847 ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
2848
2849 ASSERT_TRUE(Connect());
2850
2851 if (enable_partial_write) {
2852 SSL_set_mode(client_.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
2853 }
2854
2855 // Write without reading until the buffer is full and we have an unfinished
2856 // write. Keep a count so we may reread it again later. "hello!" will be
2857 // written in two chunks, "hello" and "!".
2858 char data[] = "hello!";
2859 static const int kChunkLen = 5; // The length of "hello".
2860 unsigned count = 0;
2861 for (;;) {
2862 int ret = SSL_write(client_.get(), data, kChunkLen);
2863 if (ret <= 0) {
2864 ASSERT_EQ(SSL_get_error(client_.get(), ret), SSL_ERROR_WANT_WRITE);
2865 break;
2866 }
2867
2868 ASSERT_EQ(ret, 5);
2869
2870 count++;
2871 }
2872
2873 // Retrying with the same parameters is legal.
2874 ASSERT_EQ(
2875 SSL_get_error(client_.get(), SSL_write(client_.get(), data, kChunkLen)),
2876 SSL_ERROR_WANT_WRITE);
2877
2878 // Retrying with the same buffer but shorter length is not legal.
2879 ASSERT_EQ(SSL_get_error(client_.get(),
2880 SSL_write(client_.get(), data, kChunkLen - 1)),
2881 SSL_ERROR_SSL);
2882 ASSERT_TRUE(ExpectBadWriteRetry());
2883
2884 // Retrying with a different buffer pointer is not legal.
2885 char data2[] = "hello";
2886 ASSERT_EQ(SSL_get_error(client_.get(),
2887 SSL_write(client_.get(), data2, kChunkLen)),
2888 SSL_ERROR_SSL);
2889 ASSERT_TRUE(ExpectBadWriteRetry());
2890
2891 // With |SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER|, the buffer may move.
2892 SSL_set_mode(client_.get(), SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
2893 ASSERT_EQ(SSL_get_error(client_.get(),
2894 SSL_write(client_.get(), data2, kChunkLen)),
2895 SSL_ERROR_WANT_WRITE);
2896
2897 // |SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER| does not disable length checks.
2898 ASSERT_EQ(SSL_get_error(client_.get(),
2899 SSL_write(client_.get(), data2, kChunkLen - 1)),
2900 SSL_ERROR_SSL);
2901 ASSERT_TRUE(ExpectBadWriteRetry());
2902
2903 // Retrying with a larger buffer is legal.
2904 ASSERT_EQ(SSL_get_error(client_.get(),
2905 SSL_write(client_.get(), data, kChunkLen + 1)),
2906 SSL_ERROR_WANT_WRITE);
2907
2908 // Drain the buffer.
2909 char buf[20];
2910 for (unsigned i = 0; i < count; i++) {
2911 ASSERT_EQ(SSL_read(server_.get(), buf, sizeof(buf)), kChunkLen);
2912 ASSERT_EQ(OPENSSL_memcmp(buf, "hello", kChunkLen), 0);
2913 }
2914
2915 // Now that there is space, a retry with a larger buffer should flush the
2916 // pending record, skip over that many bytes of input (on assumption they
2917 // are the same), and write the remainder. If SSL_MODE_ENABLE_PARTIAL_WRITE
2918 // is set, this will complete in two steps.
2919 char data3[] = "_____!";
2920 if (enable_partial_write) {
2921 ASSERT_EQ(SSL_write(client_.get(), data3, kChunkLen + 1), kChunkLen);
2922 ASSERT_EQ(SSL_write(client_.get(), data3 + kChunkLen, 1), 1);
2923 } else {
2924 ASSERT_EQ(SSL_write(client_.get(), data3, kChunkLen + 1), kChunkLen + 1);
2925 }
2926
2927 // Check the last write was correct. The data will be spread over two
2928 // records, so SSL_read returns twice.
2929 ASSERT_EQ(SSL_read(server_.get(), buf, sizeof(buf)), kChunkLen);
2930 ASSERT_EQ(OPENSSL_memcmp(buf, "hello", kChunkLen), 0);
2931 ASSERT_EQ(SSL_read(server_.get(), buf, sizeof(buf)), 1);
2932 ASSERT_EQ(buf[0], '!');
2933 }
2934 }
2935
TEST_P(SSLVersionTest,RecordCallback)2936 TEST_P(SSLVersionTest, RecordCallback) {
2937 for (bool test_server : {true, false}) {
2938 SCOPED_TRACE(test_server);
2939 ResetContexts();
2940
2941 bool read_seen = false;
2942 bool write_seen = false;
2943 auto cb = [&](int is_write, int cb_version, int cb_type, const void *buf,
2944 size_t len, SSL *ssl) {
2945 if (cb_type != SSL3_RT_HEADER) {
2946 return;
2947 }
2948
2949 // The callback does not report a version for records.
2950 EXPECT_EQ(0, cb_version);
2951
2952 if (is_write) {
2953 write_seen = true;
2954 } else {
2955 read_seen = true;
2956 }
2957
2958 // Sanity-check that the record header is plausible.
2959 CBS cbs;
2960 CBS_init(&cbs, reinterpret_cast<const uint8_t *>(buf), len);
2961 uint8_t type;
2962 uint16_t record_version, length;
2963 ASSERT_TRUE(CBS_get_u8(&cbs, &type));
2964 ASSERT_TRUE(CBS_get_u16(&cbs, &record_version));
2965 EXPECT_EQ(record_version & 0xff00, version() & 0xff00);
2966 if (is_dtls()) {
2967 uint16_t epoch;
2968 ASSERT_TRUE(CBS_get_u16(&cbs, &epoch));
2969 EXPECT_TRUE(epoch == 0 || epoch == 1) << "Invalid epoch: " << epoch;
2970 ASSERT_TRUE(CBS_skip(&cbs, 6));
2971 }
2972 ASSERT_TRUE(CBS_get_u16(&cbs, &length));
2973 EXPECT_EQ(0u, CBS_len(&cbs));
2974 };
2975 using CallbackType = decltype(cb);
2976 SSL_CTX *ctx = test_server ? server_ctx_.get() : client_ctx_.get();
2977 SSL_CTX_set_msg_callback(
2978 ctx, [](int is_write, int cb_version, int cb_type, const void *buf,
2979 size_t len, SSL *ssl, void *arg) {
2980 CallbackType *cb_ptr = reinterpret_cast<CallbackType *>(arg);
2981 (*cb_ptr)(is_write, cb_version, cb_type, buf, len, ssl);
2982 });
2983 SSL_CTX_set_msg_callback_arg(ctx, &cb);
2984
2985 ASSERT_TRUE(Connect());
2986
2987 EXPECT_TRUE(read_seen);
2988 EXPECT_TRUE(write_seen);
2989 }
2990 }
2991
TEST_P(SSLVersionTest,GetServerName)2992 TEST_P(SSLVersionTest, GetServerName) {
2993 // No extensions in SSL 3.0.
2994 if (version() == SSL3_VERSION) {
2995 return;
2996 }
2997
2998 ClientConfig config;
2999 config.servername = "host1";
3000
3001 SSL_CTX_set_tlsext_servername_callback(
3002 server_ctx_.get(), [](SSL *ssl, int *out_alert, void *arg) -> int {
3003 // During the handshake, |SSL_get_servername| must match |config|.
3004 ClientConfig *config_p = reinterpret_cast<ClientConfig *>(arg);
3005 EXPECT_STREQ(config_p->servername.c_str(),
3006 SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name));
3007 return SSL_TLSEXT_ERR_OK;
3008 });
3009 SSL_CTX_set_tlsext_servername_arg(server_ctx_.get(), &config);
3010
3011 ASSERT_TRUE(Connect(config));
3012 // After the handshake, it must also be available.
3013 EXPECT_STREQ(config.servername.c_str(),
3014 SSL_get_servername(server_.get(), TLSEXT_NAMETYPE_host_name));
3015
3016 // Establish a session under host1.
3017 SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
3018 SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
3019 bssl::UniquePtr<SSL_SESSION> session =
3020 CreateClientSession(client_ctx_.get(), server_ctx_.get(), config);
3021
3022 // If the client resumes a session with a different name, |SSL_get_servername|
3023 // must return the new name.
3024 ASSERT_TRUE(session);
3025 config.session = session.get();
3026 config.servername = "host2";
3027 ASSERT_TRUE(Connect(config));
3028 EXPECT_STREQ(config.servername.c_str(),
3029 SSL_get_servername(server_.get(), TLSEXT_NAMETYPE_host_name));
3030 }
3031
3032 // Test that session cache mode bits are honored in the client session callback.
TEST_P(SSLVersionTest,ClientSessionCacheMode)3033 TEST_P(SSLVersionTest, ClientSessionCacheMode) {
3034 SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_OFF);
3035 EXPECT_FALSE(CreateClientSession(client_ctx_.get(), server_ctx_.get()));
3036
3037 SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_CLIENT);
3038 EXPECT_TRUE(CreateClientSession(client_ctx_.get(), server_ctx_.get()));
3039
3040 SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_SERVER);
3041 EXPECT_FALSE(CreateClientSession(client_ctx_.get(), server_ctx_.get()));
3042 }
3043
TEST(SSLTest,AddChainCertHack)3044 TEST(SSLTest, AddChainCertHack) {
3045 // Ensure that we don't accidently break the hack that we have in place to
3046 // keep curl and serf happy when they use an |X509| even after transfering
3047 // ownership.
3048
3049 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3050 ASSERT_TRUE(ctx);
3051 X509 *cert = GetTestCertificate().release();
3052 ASSERT_TRUE(cert);
3053 SSL_CTX_add0_chain_cert(ctx.get(), cert);
3054
3055 // This should not trigger a use-after-free.
3056 X509_cmp(cert, cert);
3057 }
3058
TEST(SSLTest,GetCertificate)3059 TEST(SSLTest, GetCertificate) {
3060 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3061 ASSERT_TRUE(ctx);
3062 bssl::UniquePtr<X509> cert = GetTestCertificate();
3063 ASSERT_TRUE(cert);
3064 ASSERT_TRUE(SSL_CTX_use_certificate(ctx.get(), cert.get()));
3065 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
3066 ASSERT_TRUE(ssl);
3067
3068 X509 *cert2 = SSL_CTX_get0_certificate(ctx.get());
3069 ASSERT_TRUE(cert2);
3070 X509 *cert3 = SSL_get_certificate(ssl.get());
3071 ASSERT_TRUE(cert3);
3072
3073 // The old and new certificates must be identical.
3074 EXPECT_EQ(0, X509_cmp(cert.get(), cert2));
3075 EXPECT_EQ(0, X509_cmp(cert.get(), cert3));
3076
3077 uint8_t *der = nullptr;
3078 long der_len = i2d_X509(cert.get(), &der);
3079 ASSERT_LT(0, der_len);
3080 bssl::UniquePtr<uint8_t> free_der(der);
3081
3082 uint8_t *der2 = nullptr;
3083 long der2_len = i2d_X509(cert2, &der2);
3084 ASSERT_LT(0, der2_len);
3085 bssl::UniquePtr<uint8_t> free_der2(der2);
3086
3087 uint8_t *der3 = nullptr;
3088 long der3_len = i2d_X509(cert3, &der3);
3089 ASSERT_LT(0, der3_len);
3090 bssl::UniquePtr<uint8_t> free_der3(der3);
3091
3092 // They must also encode identically.
3093 EXPECT_EQ(Bytes(der, der_len), Bytes(der2, der2_len));
3094 EXPECT_EQ(Bytes(der, der_len), Bytes(der3, der3_len));
3095 }
3096
TEST(SSLTest,SetChainAndKeyMismatch)3097 TEST(SSLTest, SetChainAndKeyMismatch) {
3098 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_with_buffers_method()));
3099 ASSERT_TRUE(ctx);
3100
3101 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3102 ASSERT_TRUE(key);
3103 bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3104 ASSERT_TRUE(leaf);
3105 std::vector<CRYPTO_BUFFER*> chain = {
3106 leaf.get(),
3107 };
3108
3109 // Should fail because |GetTestKey| doesn't match the chain-test certificate.
3110 ASSERT_FALSE(SSL_CTX_set_chain_and_key(ctx.get(), &chain[0], chain.size(),
3111 key.get(), nullptr));
3112 ERR_clear_error();
3113 }
3114
TEST(SSLTest,SetChainAndKey)3115 TEST(SSLTest, SetChainAndKey) {
3116 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3117 ASSERT_TRUE(client_ctx);
3118 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3119 ASSERT_TRUE(server_ctx);
3120
3121 bssl::UniquePtr<EVP_PKEY> key = GetChainTestKey();
3122 ASSERT_TRUE(key);
3123 bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3124 ASSERT_TRUE(leaf);
3125 bssl::UniquePtr<CRYPTO_BUFFER> intermediate =
3126 GetChainTestIntermediateBuffer();
3127 ASSERT_TRUE(intermediate);
3128 std::vector<CRYPTO_BUFFER*> chain = {
3129 leaf.get(), intermediate.get(),
3130 };
3131 ASSERT_TRUE(SSL_CTX_set_chain_and_key(server_ctx.get(), &chain[0],
3132 chain.size(), key.get(), nullptr));
3133
3134 SSL_CTX_set_custom_verify(
3135 client_ctx.get(), SSL_VERIFY_PEER,
3136 [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3137 return ssl_verify_ok;
3138 });
3139
3140 bssl::UniquePtr<SSL> client, server;
3141 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3142 server_ctx.get()));
3143 }
3144
TEST(SSLTest,BuffersFailWithoutCustomVerify)3145 TEST(SSLTest, BuffersFailWithoutCustomVerify) {
3146 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3147 ASSERT_TRUE(client_ctx);
3148 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3149 ASSERT_TRUE(server_ctx);
3150
3151 bssl::UniquePtr<EVP_PKEY> key = GetChainTestKey();
3152 ASSERT_TRUE(key);
3153 bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3154 ASSERT_TRUE(leaf);
3155 std::vector<CRYPTO_BUFFER*> chain = { leaf.get() };
3156 ASSERT_TRUE(SSL_CTX_set_chain_and_key(server_ctx.get(), &chain[0],
3157 chain.size(), key.get(), nullptr));
3158
3159 // Without SSL_CTX_set_custom_verify(), i.e. with everything in the default
3160 // configuration, certificate verification should fail.
3161 bssl::UniquePtr<SSL> client, server;
3162 ASSERT_FALSE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3163 server_ctx.get()));
3164
3165 // Whereas with a verifier, the connection should succeed.
3166 SSL_CTX_set_custom_verify(
3167 client_ctx.get(), SSL_VERIFY_PEER,
3168 [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3169 return ssl_verify_ok;
3170 });
3171 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3172 server_ctx.get()));
3173 }
3174
TEST(SSLTest,CustomVerify)3175 TEST(SSLTest, CustomVerify) {
3176 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3177 ASSERT_TRUE(client_ctx);
3178 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3179 ASSERT_TRUE(server_ctx);
3180
3181 bssl::UniquePtr<EVP_PKEY> key = GetChainTestKey();
3182 ASSERT_TRUE(key);
3183 bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3184 ASSERT_TRUE(leaf);
3185 std::vector<CRYPTO_BUFFER*> chain = { leaf.get() };
3186 ASSERT_TRUE(SSL_CTX_set_chain_and_key(server_ctx.get(), &chain[0],
3187 chain.size(), key.get(), nullptr));
3188
3189 SSL_CTX_set_custom_verify(
3190 client_ctx.get(), SSL_VERIFY_PEER,
3191 [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3192 return ssl_verify_ok;
3193 });
3194
3195 bssl::UniquePtr<SSL> client, server;
3196 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3197 server_ctx.get()));
3198
3199 // With SSL_VERIFY_PEER, ssl_verify_invalid should result in a dropped
3200 // connection.
3201 SSL_CTX_set_custom_verify(
3202 client_ctx.get(), SSL_VERIFY_PEER,
3203 [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3204 return ssl_verify_invalid;
3205 });
3206
3207 ASSERT_FALSE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3208 server_ctx.get()));
3209
3210 // But with SSL_VERIFY_NONE, ssl_verify_invalid should not cause a dropped
3211 // connection.
3212 SSL_CTX_set_custom_verify(
3213 client_ctx.get(), SSL_VERIFY_NONE,
3214 [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3215 return ssl_verify_invalid;
3216 });
3217
3218 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3219 server_ctx.get()));
3220 }
3221
TEST(SSLTest,ClientCABuffers)3222 TEST(SSLTest, ClientCABuffers) {
3223 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3224 ASSERT_TRUE(client_ctx);
3225 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3226 ASSERT_TRUE(server_ctx);
3227
3228 bssl::UniquePtr<EVP_PKEY> key = GetChainTestKey();
3229 ASSERT_TRUE(key);
3230 bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3231 ASSERT_TRUE(leaf);
3232 bssl::UniquePtr<CRYPTO_BUFFER> intermediate =
3233 GetChainTestIntermediateBuffer();
3234 ASSERT_TRUE(intermediate);
3235 std::vector<CRYPTO_BUFFER *> chain = {
3236 leaf.get(),
3237 intermediate.get(),
3238 };
3239 ASSERT_TRUE(SSL_CTX_set_chain_and_key(server_ctx.get(), &chain[0],
3240 chain.size(), key.get(), nullptr));
3241
3242 bssl::UniquePtr<CRYPTO_BUFFER> ca_name(
3243 CRYPTO_BUFFER_new(kTestName, sizeof(kTestName), nullptr));
3244 ASSERT_TRUE(ca_name);
3245 bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names(
3246 sk_CRYPTO_BUFFER_new_null());
3247 ASSERT_TRUE(ca_names);
3248 ASSERT_TRUE(sk_CRYPTO_BUFFER_push(ca_names.get(), ca_name.get()));
3249 ca_name.release();
3250 SSL_CTX_set0_client_CAs(server_ctx.get(), ca_names.release());
3251
3252 // Configure client and server to accept all certificates.
3253 SSL_CTX_set_custom_verify(
3254 client_ctx.get(), SSL_VERIFY_PEER,
3255 [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3256 return ssl_verify_ok;
3257 });
3258 SSL_CTX_set_custom_verify(
3259 server_ctx.get(), SSL_VERIFY_PEER,
3260 [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3261 return ssl_verify_ok;
3262 });
3263
3264 bool cert_cb_called = false;
3265 SSL_CTX_set_cert_cb(
3266 client_ctx.get(),
3267 [](SSL *ssl, void *arg) -> int {
3268 STACK_OF(CRYPTO_BUFFER) *peer_names =
3269 SSL_get0_server_requested_CAs(ssl);
3270 EXPECT_EQ(1u, sk_CRYPTO_BUFFER_num(peer_names));
3271 CRYPTO_BUFFER *peer_name = sk_CRYPTO_BUFFER_value(peer_names, 0);
3272 EXPECT_EQ(Bytes(kTestName), Bytes(CRYPTO_BUFFER_data(peer_name),
3273 CRYPTO_BUFFER_len(peer_name)));
3274 *reinterpret_cast<bool *>(arg) = true;
3275 return 1;
3276 },
3277 &cert_cb_called);
3278
3279 bssl::UniquePtr<SSL> client, server;
3280 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3281 server_ctx.get()));
3282 EXPECT_TRUE(cert_cb_called);
3283 }
3284
3285 // Configuring the empty cipher list, though an error, should still modify the
3286 // configuration.
TEST(SSLTest,EmptyCipherList)3287 TEST(SSLTest, EmptyCipherList) {
3288 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3289 ASSERT_TRUE(ctx);
3290
3291 // Initially, the cipher list is not empty.
3292 EXPECT_NE(0u, sk_SSL_CIPHER_num(SSL_CTX_get_ciphers(ctx.get())));
3293
3294 // Configuring the empty cipher list fails.
3295 EXPECT_FALSE(SSL_CTX_set_cipher_list(ctx.get(), ""));
3296 ERR_clear_error();
3297
3298 // But the cipher list is still updated to empty.
3299 EXPECT_EQ(0u, sk_SSL_CIPHER_num(SSL_CTX_get_ciphers(ctx.get())));
3300 }
3301
3302 // ssl_test_ticket_aead_failure_mode enumerates the possible ways in which the
3303 // test |SSL_TICKET_AEAD_METHOD| can fail.
3304 enum ssl_test_ticket_aead_failure_mode {
3305 ssl_test_ticket_aead_ok = 0,
3306 ssl_test_ticket_aead_seal_fail,
3307 ssl_test_ticket_aead_open_soft_fail,
3308 ssl_test_ticket_aead_open_hard_fail,
3309 };
3310
3311 struct ssl_test_ticket_aead_state {
3312 unsigned retry_count;
3313 ssl_test_ticket_aead_failure_mode failure_mode;
3314 };
3315
ssl_test_ticket_aead_ex_index_dup(CRYPTO_EX_DATA * to,const CRYPTO_EX_DATA * from,void ** from_d,int index,long argl,void * argp)3316 static int ssl_test_ticket_aead_ex_index_dup(CRYPTO_EX_DATA *to,
3317 const CRYPTO_EX_DATA *from,
3318 void **from_d, int index,
3319 long argl, void *argp) {
3320 abort();
3321 }
3322
ssl_test_ticket_aead_ex_index_free(void * parent,void * ptr,CRYPTO_EX_DATA * ad,int index,long argl,void * argp)3323 static void ssl_test_ticket_aead_ex_index_free(void *parent, void *ptr,
3324 CRYPTO_EX_DATA *ad, int index,
3325 long argl, void *argp) {
3326 auto state = reinterpret_cast<ssl_test_ticket_aead_state*>(ptr);
3327 if (state == nullptr) {
3328 return;
3329 }
3330
3331 OPENSSL_free(state);
3332 }
3333
3334 static CRYPTO_once_t g_ssl_test_ticket_aead_ex_index_once = CRYPTO_ONCE_INIT;
3335 static int g_ssl_test_ticket_aead_ex_index;
3336
ssl_test_ticket_aead_get_ex_index()3337 static int ssl_test_ticket_aead_get_ex_index() {
3338 CRYPTO_once(&g_ssl_test_ticket_aead_ex_index_once, [] {
3339 g_ssl_test_ticket_aead_ex_index = SSL_get_ex_new_index(
3340 0, nullptr, nullptr, ssl_test_ticket_aead_ex_index_dup,
3341 ssl_test_ticket_aead_ex_index_free);
3342 });
3343 return g_ssl_test_ticket_aead_ex_index;
3344 }
3345
ssl_test_ticket_aead_max_overhead(SSL * ssl)3346 static size_t ssl_test_ticket_aead_max_overhead(SSL *ssl) {
3347 return 1;
3348 }
3349
ssl_test_ticket_aead_seal(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out_len,const uint8_t * in,size_t in_len)3350 static int ssl_test_ticket_aead_seal(SSL *ssl, uint8_t *out, size_t *out_len,
3351 size_t max_out_len, const uint8_t *in,
3352 size_t in_len) {
3353 auto state = reinterpret_cast<ssl_test_ticket_aead_state *>(
3354 SSL_get_ex_data(ssl, ssl_test_ticket_aead_get_ex_index()));
3355
3356 if (state->failure_mode == ssl_test_ticket_aead_seal_fail ||
3357 max_out_len < in_len + 1) {
3358 return 0;
3359 }
3360
3361 OPENSSL_memmove(out, in, in_len);
3362 out[in_len] = 0xff;
3363 *out_len = in_len + 1;
3364
3365 return 1;
3366 }
3367
ssl_test_ticket_aead_open(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out_len,const uint8_t * in,size_t in_len)3368 static ssl_ticket_aead_result_t ssl_test_ticket_aead_open(
3369 SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out_len,
3370 const uint8_t *in, size_t in_len) {
3371 auto state = reinterpret_cast<ssl_test_ticket_aead_state *>(
3372 SSL_get_ex_data(ssl, ssl_test_ticket_aead_get_ex_index()));
3373
3374 if (state->retry_count > 0) {
3375 state->retry_count--;
3376 return ssl_ticket_aead_retry;
3377 }
3378
3379 switch (state->failure_mode) {
3380 case ssl_test_ticket_aead_ok:
3381 break;
3382 case ssl_test_ticket_aead_seal_fail:
3383 // If |seal| failed then there shouldn't be any ticket to try and
3384 // decrypt.
3385 abort();
3386 break;
3387 case ssl_test_ticket_aead_open_soft_fail:
3388 return ssl_ticket_aead_ignore_ticket;
3389 case ssl_test_ticket_aead_open_hard_fail:
3390 return ssl_ticket_aead_error;
3391 }
3392
3393 if (in_len == 0 || in[in_len - 1] != 0xff) {
3394 return ssl_ticket_aead_ignore_ticket;
3395 }
3396
3397 if (max_out_len < in_len - 1) {
3398 return ssl_ticket_aead_error;
3399 }
3400
3401 OPENSSL_memmove(out, in, in_len - 1);
3402 *out_len = in_len - 1;
3403 return ssl_ticket_aead_success;
3404 }
3405
3406 static const SSL_TICKET_AEAD_METHOD kSSLTestTicketMethod = {
3407 ssl_test_ticket_aead_max_overhead,
3408 ssl_test_ticket_aead_seal,
3409 ssl_test_ticket_aead_open,
3410 };
3411
ConnectClientAndServerWithTicketMethod(bssl::UniquePtr<SSL> * out_client,bssl::UniquePtr<SSL> * out_server,SSL_CTX * client_ctx,SSL_CTX * server_ctx,unsigned retry_count,ssl_test_ticket_aead_failure_mode failure_mode,SSL_SESSION * session)3412 static void ConnectClientAndServerWithTicketMethod(
3413 bssl::UniquePtr<SSL> *out_client, bssl::UniquePtr<SSL> *out_server,
3414 SSL_CTX *client_ctx, SSL_CTX *server_ctx, unsigned retry_count,
3415 ssl_test_ticket_aead_failure_mode failure_mode, SSL_SESSION *session) {
3416 bssl::UniquePtr<SSL> client(SSL_new(client_ctx)), server(SSL_new(server_ctx));
3417 ASSERT_TRUE(client);
3418 ASSERT_TRUE(server);
3419 SSL_set_connect_state(client.get());
3420 SSL_set_accept_state(server.get());
3421
3422 auto state = reinterpret_cast<ssl_test_ticket_aead_state *>(
3423 OPENSSL_malloc(sizeof(ssl_test_ticket_aead_state)));
3424 ASSERT_TRUE(state);
3425 OPENSSL_memset(state, 0, sizeof(ssl_test_ticket_aead_state));
3426 state->retry_count = retry_count;
3427 state->failure_mode = failure_mode;
3428
3429 ASSERT_TRUE(SSL_set_ex_data(server.get(), ssl_test_ticket_aead_get_ex_index(),
3430 state));
3431
3432 SSL_set_session(client.get(), session);
3433
3434 BIO *bio1, *bio2;
3435 ASSERT_TRUE(BIO_new_bio_pair(&bio1, 0, &bio2, 0));
3436
3437 // SSL_set_bio takes ownership.
3438 SSL_set_bio(client.get(), bio1, bio1);
3439 SSL_set_bio(server.get(), bio2, bio2);
3440
3441 if (CompleteHandshakes(client.get(), server.get())) {
3442 *out_client = std::move(client);
3443 *out_server = std::move(server);
3444 } else {
3445 out_client->reset();
3446 out_server->reset();
3447 }
3448 }
3449
3450 class TicketAEADMethodTest
3451 : public ::testing::TestWithParam<testing::tuple<
3452 uint16_t, unsigned, ssl_test_ticket_aead_failure_mode>> {};
3453
TEST_P(TicketAEADMethodTest,Resume)3454 TEST_P(TicketAEADMethodTest, Resume) {
3455 bssl::UniquePtr<X509> cert = GetTestCertificate();
3456 ASSERT_TRUE(cert);
3457 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3458 ASSERT_TRUE(key);
3459
3460 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
3461 ASSERT_TRUE(server_ctx);
3462 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
3463 ASSERT_TRUE(client_ctx);
3464
3465 const uint16_t version = testing::get<0>(GetParam());
3466 const unsigned retry_count = testing::get<1>(GetParam());
3467 const ssl_test_ticket_aead_failure_mode failure_mode =
3468 testing::get<2>(GetParam());
3469
3470 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3471 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3472 ASSERT_TRUE(SSL_CTX_set_min_proto_version(client_ctx.get(), version));
3473 ASSERT_TRUE(SSL_CTX_set_max_proto_version(client_ctx.get(), version));
3474 ASSERT_TRUE(SSL_CTX_set_min_proto_version(server_ctx.get(), version));
3475 ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), version));
3476
3477 SSL_CTX_set_session_cache_mode(client_ctx.get(), SSL_SESS_CACHE_BOTH);
3478 SSL_CTX_set_session_cache_mode(server_ctx.get(), SSL_SESS_CACHE_BOTH);
3479 SSL_CTX_set_current_time_cb(client_ctx.get(), FrozenTimeCallback);
3480 SSL_CTX_set_current_time_cb(server_ctx.get(), FrozenTimeCallback);
3481 SSL_CTX_sess_set_new_cb(client_ctx.get(), SaveLastSession);
3482
3483 SSL_CTX_set_ticket_aead_method(server_ctx.get(), &kSSLTestTicketMethod);
3484
3485 bssl::UniquePtr<SSL> client, server;
3486 ConnectClientAndServerWithTicketMethod(&client, &server, client_ctx.get(),
3487 server_ctx.get(), retry_count,
3488 failure_mode, nullptr);
3489 switch (failure_mode) {
3490 case ssl_test_ticket_aead_ok:
3491 case ssl_test_ticket_aead_open_hard_fail:
3492 case ssl_test_ticket_aead_open_soft_fail:
3493 ASSERT_TRUE(client);
3494 break;
3495 case ssl_test_ticket_aead_seal_fail:
3496 EXPECT_FALSE(client);
3497 return;
3498 }
3499 EXPECT_FALSE(SSL_session_reused(client.get()));
3500 EXPECT_FALSE(SSL_session_reused(server.get()));
3501
3502 // Run the read loop to account for post-handshake tickets in TLS 1.3.
3503 SSL_read(client.get(), nullptr, 0);
3504
3505 bssl::UniquePtr<SSL_SESSION> session = std::move(g_last_session);
3506 ConnectClientAndServerWithTicketMethod(&client, &server, client_ctx.get(),
3507 server_ctx.get(), retry_count,
3508 failure_mode, session.get());
3509 switch (failure_mode) {
3510 case ssl_test_ticket_aead_ok:
3511 ASSERT_TRUE(client);
3512 EXPECT_TRUE(SSL_session_reused(client.get()));
3513 EXPECT_TRUE(SSL_session_reused(server.get()));
3514 break;
3515 case ssl_test_ticket_aead_seal_fail:
3516 abort();
3517 break;
3518 case ssl_test_ticket_aead_open_hard_fail:
3519 EXPECT_FALSE(client);
3520 break;
3521 case ssl_test_ticket_aead_open_soft_fail:
3522 ASSERT_TRUE(client);
3523 EXPECT_FALSE(SSL_session_reused(client.get()));
3524 EXPECT_FALSE(SSL_session_reused(server.get()));
3525 }
3526 }
3527
3528 INSTANTIATE_TEST_CASE_P(
3529 TicketAEADMethodTests, TicketAEADMethodTest,
3530 testing::Combine(
3531 testing::Values(TLS1_2_VERSION, TLS1_3_VERSION),
3532 testing::Values(0, 1, 2),
3533 testing::Values(ssl_test_ticket_aead_ok,
3534 ssl_test_ticket_aead_seal_fail,
3535 ssl_test_ticket_aead_open_soft_fail,
3536 ssl_test_ticket_aead_open_hard_fail)));
3537
TEST(SSLTest,SSL3Method)3538 TEST(SSLTest, SSL3Method) {
3539 bssl::UniquePtr<X509> cert = GetTestCertificate();
3540 ASSERT_TRUE(cert);
3541
3542 // For compatibility, SSLv3_method should work up to SSL_CTX_new and SSL_new.
3543 bssl::UniquePtr<SSL_CTX> ssl3_ctx(SSL_CTX_new(SSLv3_method()));
3544 ASSERT_TRUE(ssl3_ctx);
3545 ASSERT_TRUE(SSL_CTX_use_certificate(ssl3_ctx.get(), cert.get()));
3546 bssl::UniquePtr<SSL> ssl(SSL_new(ssl3_ctx.get()));
3547 EXPECT_TRUE(ssl);
3548
3549 // Create a normal TLS context to test against.
3550 bssl::UniquePtr<SSL_CTX> tls_ctx(SSL_CTX_new(TLS_method()));
3551 ASSERT_TRUE(tls_ctx);
3552 ASSERT_TRUE(SSL_CTX_use_certificate(tls_ctx.get(), cert.get()));
3553
3554 // However, handshaking an SSLv3_method server should fail to resolve the
3555 // version range. Explicit calls to SSL_CTX_set_min_proto_version are the only
3556 // way to enable SSL 3.0.
3557 bssl::UniquePtr<SSL> client, server;
3558 EXPECT_FALSE(ConnectClientAndServer(&client, &server, tls_ctx.get(),
3559 ssl3_ctx.get()));
3560 uint32_t err = ERR_get_error();
3561 EXPECT_EQ(ERR_LIB_SSL, ERR_GET_LIB(err));
3562 EXPECT_EQ(SSL_R_NO_SUPPORTED_VERSIONS_ENABLED, ERR_GET_REASON(err));
3563
3564 // Likewise for SSLv3_method clients.
3565 EXPECT_FALSE(ConnectClientAndServer(&client, &server, ssl3_ctx.get(),
3566 tls_ctx.get()));
3567 err = ERR_get_error();
3568 EXPECT_EQ(ERR_LIB_SSL, ERR_GET_LIB(err));
3569 EXPECT_EQ(SSL_R_NO_SUPPORTED_VERSIONS_ENABLED, ERR_GET_REASON(err));
3570 }
3571
TEST(SSLTest,SelectNextProto)3572 TEST(SSLTest, SelectNextProto) {
3573 uint8_t *result;
3574 uint8_t result_len;
3575
3576 // If there is an overlap, it should be returned.
3577 EXPECT_EQ(OPENSSL_NPN_NEGOTIATED,
3578 SSL_select_next_proto(&result, &result_len,
3579 (const uint8_t *)"\1a\2bb\3ccc", 9,
3580 (const uint8_t *)"\1x\1y\1a\1z", 8));
3581 EXPECT_EQ(Bytes("a"), Bytes(result, result_len));
3582
3583 EXPECT_EQ(OPENSSL_NPN_NEGOTIATED,
3584 SSL_select_next_proto(&result, &result_len,
3585 (const uint8_t *)"\1a\2bb\3ccc", 9,
3586 (const uint8_t *)"\1x\1y\2bb\1z", 9));
3587 EXPECT_EQ(Bytes("bb"), Bytes(result, result_len));
3588
3589 EXPECT_EQ(OPENSSL_NPN_NEGOTIATED,
3590 SSL_select_next_proto(&result, &result_len,
3591 (const uint8_t *)"\1a\2bb\3ccc", 9,
3592 (const uint8_t *)"\1x\1y\3ccc\1z", 10));
3593 EXPECT_EQ(Bytes("ccc"), Bytes(result, result_len));
3594
3595 // Peer preference order takes precedence over local.
3596 EXPECT_EQ(OPENSSL_NPN_NEGOTIATED,
3597 SSL_select_next_proto(&result, &result_len,
3598 (const uint8_t *)"\1a\2bb\3ccc", 9,
3599 (const uint8_t *)"\3ccc\2bb\1a", 9));
3600 EXPECT_EQ(Bytes("a"), Bytes(result, result_len));
3601
3602 // If there is no overlap, return the first local protocol.
3603 EXPECT_EQ(OPENSSL_NPN_NO_OVERLAP,
3604 SSL_select_next_proto(&result, &result_len,
3605 (const uint8_t *)"\1a\2bb\3ccc", 9,
3606 (const uint8_t *)"\1x\2yy\3zzz", 9));
3607 EXPECT_EQ(Bytes("x"), Bytes(result, result_len));
3608
3609 EXPECT_EQ(OPENSSL_NPN_NO_OVERLAP,
3610 SSL_select_next_proto(&result, &result_len, nullptr, 0,
3611 (const uint8_t *)"\1x\2yy\3zzz", 9));
3612 EXPECT_EQ(Bytes("x"), Bytes(result, result_len));
3613 }
3614
TEST(SSLTest,SealRecord)3615 TEST(SSLTest, SealRecord) {
3616 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method())),
3617 server_ctx(SSL_CTX_new(TLS_method()));
3618 ASSERT_TRUE(client_ctx);
3619 ASSERT_TRUE(server_ctx);
3620
3621 bssl::UniquePtr<X509> cert = GetTestCertificate();
3622 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3623 ASSERT_TRUE(cert);
3624 ASSERT_TRUE(key);
3625 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3626 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3627
3628 bssl::UniquePtr<SSL> client, server;
3629 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3630 server_ctx.get()));
3631
3632 const std::vector<uint8_t> record = {1, 2, 3, 4, 5};
3633 std::vector<uint8_t> prefix(
3634 bssl::SealRecordPrefixLen(client.get(), record.size())),
3635 body(record.size()),
3636 suffix(bssl::SealRecordSuffixLen(client.get(), record.size()));
3637 ASSERT_TRUE(bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3638 bssl::MakeSpan(body), bssl::MakeSpan(suffix),
3639 record));
3640
3641 std::vector<uint8_t> sealed;
3642 sealed.insert(sealed.end(), prefix.begin(), prefix.end());
3643 sealed.insert(sealed.end(), body.begin(), body.end());
3644 sealed.insert(sealed.end(), suffix.begin(), suffix.end());
3645 std::vector<uint8_t> sealed_copy = sealed;
3646
3647 bssl::Span<uint8_t> plaintext;
3648 size_t record_len;
3649 uint8_t alert = 255;
3650 EXPECT_EQ(bssl::OpenRecord(server.get(), &plaintext, &record_len, &alert,
3651 bssl::MakeSpan(sealed)),
3652 bssl::OpenRecordResult::kOK);
3653 EXPECT_EQ(record_len, sealed.size());
3654 EXPECT_EQ(plaintext, record);
3655 EXPECT_EQ(255, alert);
3656 }
3657
TEST(SSLTest,SealRecordInPlace)3658 TEST(SSLTest, SealRecordInPlace) {
3659 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method())),
3660 server_ctx(SSL_CTX_new(TLS_method()));
3661 ASSERT_TRUE(client_ctx);
3662 ASSERT_TRUE(server_ctx);
3663
3664 bssl::UniquePtr<X509> cert = GetTestCertificate();
3665 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3666 ASSERT_TRUE(cert);
3667 ASSERT_TRUE(key);
3668 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3669 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3670
3671 bssl::UniquePtr<SSL> client, server;
3672 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3673 server_ctx.get()));
3674
3675 const std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5};
3676 std::vector<uint8_t> record = plaintext;
3677 std::vector<uint8_t> prefix(
3678 bssl::SealRecordPrefixLen(client.get(), record.size())),
3679 suffix(bssl::SealRecordSuffixLen(client.get(), record.size()));
3680 ASSERT_TRUE(bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3681 bssl::MakeSpan(record), bssl::MakeSpan(suffix),
3682 record));
3683 record.insert(record.begin(), prefix.begin(), prefix.end());
3684 record.insert(record.end(), suffix.begin(), suffix.end());
3685
3686 bssl::Span<uint8_t> result;
3687 size_t record_len;
3688 uint8_t alert;
3689 EXPECT_EQ(bssl::OpenRecord(server.get(), &result, &record_len, &alert,
3690 bssl::MakeSpan(record)),
3691 bssl::OpenRecordResult::kOK);
3692 EXPECT_EQ(record_len, record.size());
3693 EXPECT_EQ(plaintext, result);
3694 }
3695
TEST(SSLTest,SealRecordTrailingData)3696 TEST(SSLTest, SealRecordTrailingData) {
3697 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method())),
3698 server_ctx(SSL_CTX_new(TLS_method()));
3699 ASSERT_TRUE(client_ctx);
3700 ASSERT_TRUE(server_ctx);
3701
3702 bssl::UniquePtr<X509> cert = GetTestCertificate();
3703 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3704 ASSERT_TRUE(cert);
3705 ASSERT_TRUE(key);
3706 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3707 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3708
3709 bssl::UniquePtr<SSL> client, server;
3710 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3711 server_ctx.get()));
3712
3713 const std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5};
3714 std::vector<uint8_t> record = plaintext;
3715 std::vector<uint8_t> prefix(
3716 bssl::SealRecordPrefixLen(client.get(), record.size())),
3717 suffix(bssl::SealRecordSuffixLen(client.get(), record.size()));
3718 ASSERT_TRUE(bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3719 bssl::MakeSpan(record), bssl::MakeSpan(suffix),
3720 record));
3721 record.insert(record.begin(), prefix.begin(), prefix.end());
3722 record.insert(record.end(), suffix.begin(), suffix.end());
3723 record.insert(record.end(), {5, 4, 3, 2, 1});
3724
3725 bssl::Span<uint8_t> result;
3726 size_t record_len;
3727 uint8_t alert;
3728 EXPECT_EQ(bssl::OpenRecord(server.get(), &result, &record_len, &alert,
3729 bssl::MakeSpan(record)),
3730 bssl::OpenRecordResult::kOK);
3731 EXPECT_EQ(record_len, record.size() - 5);
3732 EXPECT_EQ(plaintext, result);
3733 }
3734
TEST(SSLTest,SealRecordInvalidSpanSize)3735 TEST(SSLTest, SealRecordInvalidSpanSize) {
3736 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method())),
3737 server_ctx(SSL_CTX_new(TLS_method()));
3738 ASSERT_TRUE(client_ctx);
3739 ASSERT_TRUE(server_ctx);
3740
3741 bssl::UniquePtr<X509> cert = GetTestCertificate();
3742 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3743 ASSERT_TRUE(cert);
3744 ASSERT_TRUE(key);
3745 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3746 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3747
3748 bssl::UniquePtr<SSL> client, server;
3749 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3750 server_ctx.get()));
3751
3752 std::vector<uint8_t> record = {1, 2, 3, 4, 5};
3753 std::vector<uint8_t> prefix(
3754 bssl::SealRecordPrefixLen(client.get(), record.size())),
3755 body(record.size()),
3756 suffix(bssl::SealRecordSuffixLen(client.get(), record.size()));
3757
3758 auto expect_err = []() {
3759 int err = ERR_get_error();
3760 EXPECT_EQ(ERR_GET_LIB(err), ERR_LIB_SSL);
3761 EXPECT_EQ(ERR_GET_REASON(err), SSL_R_BUFFER_TOO_SMALL);
3762 ERR_clear_error();
3763 };
3764 EXPECT_FALSE(bssl::SealRecord(
3765 client.get(), bssl::MakeSpan(prefix.data(), prefix.size() - 1),
3766 bssl::MakeSpan(record), bssl::MakeSpan(suffix), record));
3767 expect_err();
3768 EXPECT_FALSE(bssl::SealRecord(
3769 client.get(), bssl::MakeSpan(prefix.data(), prefix.size() + 1),
3770 bssl::MakeSpan(record), bssl::MakeSpan(suffix), record));
3771 expect_err();
3772
3773 EXPECT_FALSE(
3774 bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3775 bssl::MakeSpan(record.data(), record.size() - 1),
3776 bssl::MakeSpan(suffix), record));
3777 expect_err();
3778 EXPECT_FALSE(
3779 bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3780 bssl::MakeSpan(record.data(), record.size() + 1),
3781 bssl::MakeSpan(suffix), record));
3782 expect_err();
3783
3784 EXPECT_FALSE(bssl::SealRecord(
3785 client.get(), bssl::MakeSpan(prefix), bssl::MakeSpan(record),
3786 bssl::MakeSpan(suffix.data(), suffix.size() - 1), record));
3787 expect_err();
3788 EXPECT_FALSE(bssl::SealRecord(
3789 client.get(), bssl::MakeSpan(prefix), bssl::MakeSpan(record),
3790 bssl::MakeSpan(suffix.data(), suffix.size() + 1), record));
3791 expect_err();
3792 }
3793
3794 // The client should gracefully handle no suitable ciphers being enabled.
TEST(SSLTest,NoCiphersAvailable)3795 TEST(SSLTest, NoCiphersAvailable) {
3796 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3797 ASSERT_TRUE(ctx);
3798
3799 // Configure |client_ctx| with a cipher list that does not intersect with its
3800 // version configuration.
3801 ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(
3802 ctx.get(), "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"));
3803 ASSERT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_1_VERSION));
3804
3805 bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
3806 ASSERT_TRUE(ssl);
3807 SSL_set_connect_state(ssl.get());
3808
3809 UniquePtr<BIO> rbio(BIO_new(BIO_s_mem())), wbio(BIO_new(BIO_s_mem()));
3810 ASSERT_TRUE(rbio);
3811 ASSERT_TRUE(wbio);
3812 SSL_set0_rbio(ssl.get(), rbio.release());
3813 SSL_set0_wbio(ssl.get(), wbio.release());
3814
3815 int ret = SSL_do_handshake(ssl.get());
3816 EXPECT_EQ(-1, ret);
3817 EXPECT_EQ(SSL_ERROR_SSL, SSL_get_error(ssl.get(), ret));
3818 uint32_t err = ERR_get_error();
3819 EXPECT_EQ(ERR_LIB_SSL, ERR_GET_LIB(err));
3820 EXPECT_EQ(SSL_R_NO_CIPHERS_AVAILABLE, ERR_GET_REASON(err));
3821 }
3822
TEST_P(SSLVersionTest,SessionVersion)3823 TEST_P(SSLVersionTest, SessionVersion) {
3824 SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
3825 SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
3826
3827 bssl::UniquePtr<SSL_SESSION> session =
3828 CreateClientSession(client_ctx_.get(), server_ctx_.get());
3829 ASSERT_TRUE(session);
3830 EXPECT_EQ(version(), SSL_SESSION_get_protocol_version(session.get()));
3831
3832 // Sessions in TLS 1.3 and later should be single-use.
3833 EXPECT_EQ(version() == TLS1_3_VERSION,
3834 !!SSL_SESSION_should_be_single_use(session.get()));
3835
3836 // Making fake sessions for testing works.
3837 session.reset(SSL_SESSION_new(client_ctx_.get()));
3838 ASSERT_TRUE(session);
3839 ASSERT_TRUE(SSL_SESSION_set_protocol_version(session.get(), version()));
3840 EXPECT_EQ(version(), SSL_SESSION_get_protocol_version(session.get()));
3841 }
3842
TEST_P(SSLVersionTest,SSLPending)3843 TEST_P(SSLVersionTest, SSLPending) {
3844 UniquePtr<SSL> ssl(SSL_new(client_ctx_.get()));
3845 ASSERT_TRUE(ssl);
3846 EXPECT_EQ(0, SSL_pending(ssl.get()));
3847
3848 ASSERT_TRUE(Connect());
3849 EXPECT_EQ(0, SSL_pending(client_.get()));
3850
3851 ASSERT_EQ(5, SSL_write(server_.get(), "hello", 5));
3852 ASSERT_EQ(5, SSL_write(server_.get(), "world", 5));
3853 EXPECT_EQ(0, SSL_pending(client_.get()));
3854
3855 char buf[10];
3856 ASSERT_EQ(1, SSL_peek(client_.get(), buf, 1));
3857 EXPECT_EQ(5, SSL_pending(client_.get()));
3858
3859 ASSERT_EQ(1, SSL_read(client_.get(), buf, 1));
3860 EXPECT_EQ(4, SSL_pending(client_.get()));
3861
3862 ASSERT_EQ(4, SSL_read(client_.get(), buf, 10));
3863 EXPECT_EQ(0, SSL_pending(client_.get()));
3864
3865 ASSERT_EQ(2, SSL_read(client_.get(), buf, 2));
3866 EXPECT_EQ(3, SSL_pending(client_.get()));
3867 }
3868
3869 // Test that post-handshake tickets consumed by |SSL_shutdown| are ignored.
TEST(SSLTest,ShutdownIgnoresTickets)3870 TEST(SSLTest, ShutdownIgnoresTickets) {
3871 bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3872 ASSERT_TRUE(ctx);
3873 ASSERT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_3_VERSION));
3874 ASSERT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_3_VERSION));
3875
3876 bssl::UniquePtr<X509> cert = GetTestCertificate();
3877 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3878 ASSERT_TRUE(cert);
3879 ASSERT_TRUE(key);
3880 ASSERT_TRUE(SSL_CTX_use_certificate(ctx.get(), cert.get()));
3881 ASSERT_TRUE(SSL_CTX_use_PrivateKey(ctx.get(), key.get()));
3882
3883 SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_BOTH);
3884
3885 bssl::UniquePtr<SSL> client, server;
3886 ASSERT_TRUE(ConnectClientAndServer(&client, &server, ctx.get(), ctx.get()));
3887
3888 SSL_CTX_sess_set_new_cb(ctx.get(), [](SSL *ssl, SSL_SESSION *session) -> int {
3889 ADD_FAILURE() << "New session callback called during SSL_shutdown";
3890 return 0;
3891 });
3892
3893 // Send close_notify.
3894 EXPECT_EQ(0, SSL_shutdown(server.get()));
3895 EXPECT_EQ(0, SSL_shutdown(client.get()));
3896
3897 // Receive close_notify.
3898 EXPECT_EQ(1, SSL_shutdown(server.get()));
3899 EXPECT_EQ(1, SSL_shutdown(client.get()));
3900 }
3901
TEST(SSLTest,SignatureAlgorithmProperties)3902 TEST(SSLTest, SignatureAlgorithmProperties) {
3903 EXPECT_EQ(EVP_PKEY_NONE, SSL_get_signature_algorithm_key_type(0x1234));
3904 EXPECT_EQ(nullptr, SSL_get_signature_algorithm_digest(0x1234));
3905 EXPECT_FALSE(SSL_is_signature_algorithm_rsa_pss(0x1234));
3906
3907 EXPECT_EQ(EVP_PKEY_RSA,
3908 SSL_get_signature_algorithm_key_type(SSL_SIGN_RSA_PKCS1_MD5_SHA1));
3909 EXPECT_EQ(EVP_md5_sha1(),
3910 SSL_get_signature_algorithm_digest(SSL_SIGN_RSA_PKCS1_MD5_SHA1));
3911 EXPECT_FALSE(SSL_is_signature_algorithm_rsa_pss(SSL_SIGN_RSA_PKCS1_MD5_SHA1));
3912
3913 EXPECT_EQ(EVP_PKEY_EC, SSL_get_signature_algorithm_key_type(
3914 SSL_SIGN_ECDSA_SECP256R1_SHA256));
3915 EXPECT_EQ(EVP_sha256(), SSL_get_signature_algorithm_digest(
3916 SSL_SIGN_ECDSA_SECP256R1_SHA256));
3917 EXPECT_FALSE(
3918 SSL_is_signature_algorithm_rsa_pss(SSL_SIGN_ECDSA_SECP256R1_SHA256));
3919
3920 EXPECT_EQ(EVP_PKEY_RSA,
3921 SSL_get_signature_algorithm_key_type(SSL_SIGN_RSA_PSS_SHA384));
3922 EXPECT_EQ(EVP_sha384(),
3923 SSL_get_signature_algorithm_digest(SSL_SIGN_RSA_PSS_SHA384));
3924 EXPECT_TRUE(SSL_is_signature_algorithm_rsa_pss(SSL_SIGN_RSA_PSS_SHA384));
3925 }
3926
MoveBIOs(SSL * dest,SSL * src)3927 void MoveBIOs(SSL *dest, SSL *src) {
3928 BIO *rbio = SSL_get_rbio(src);
3929 BIO_up_ref(rbio);
3930 SSL_set0_rbio(dest, rbio);
3931
3932 BIO *wbio = SSL_get_wbio(src);
3933 BIO_up_ref(wbio);
3934 SSL_set0_wbio(dest, wbio);
3935
3936 SSL_set0_rbio(src, nullptr);
3937 SSL_set0_wbio(src, nullptr);
3938 }
3939
TEST(SSLTest,Handoff)3940 TEST(SSLTest, Handoff) {
3941 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
3942 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
3943 bssl::UniquePtr<SSL_CTX> handshaker_ctx(SSL_CTX_new(TLS_method()));
3944 ASSERT_TRUE(client_ctx);
3945 ASSERT_TRUE(server_ctx);
3946 ASSERT_TRUE(handshaker_ctx);
3947
3948 SSL_CTX_set_handoff_mode(server_ctx.get(), 1);
3949 ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), TLS1_2_VERSION));
3950 ASSERT_TRUE(
3951 SSL_CTX_set_max_proto_version(handshaker_ctx.get(), TLS1_2_VERSION));
3952
3953 bssl::UniquePtr<X509> cert = GetTestCertificate();
3954 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3955 ASSERT_TRUE(cert);
3956 ASSERT_TRUE(key);
3957 ASSERT_TRUE(SSL_CTX_use_certificate(handshaker_ctx.get(), cert.get()));
3958 ASSERT_TRUE(SSL_CTX_use_PrivateKey(handshaker_ctx.get(), key.get()));
3959
3960 bssl::UniquePtr<SSL> client, server;
3961 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3962 server_ctx.get(), ClientConfig(),
3963 false /* don't handshake */));
3964
3965 int client_ret = SSL_do_handshake(client.get());
3966 int client_err = SSL_get_error(client.get(), client_ret);
3967 ASSERT_EQ(client_err, SSL_ERROR_WANT_READ);
3968
3969 int server_ret = SSL_do_handshake(server.get());
3970 int server_err = SSL_get_error(server.get(), server_ret);
3971 ASSERT_EQ(server_err, SSL_ERROR_HANDOFF);
3972
3973 ScopedCBB cbb;
3974 Array<uint8_t> handoff;
3975 ASSERT_TRUE(CBB_init(cbb.get(), 256));
3976 ASSERT_TRUE(SSL_serialize_handoff(server.get(), cbb.get()));
3977 ASSERT_TRUE(CBBFinishArray(cbb.get(), &handoff));
3978
3979 bssl::UniquePtr<SSL> handshaker(SSL_new(handshaker_ctx.get()));
3980 ASSERT_TRUE(SSL_apply_handoff(handshaker.get(), handoff));
3981
3982 MoveBIOs(handshaker.get(), server.get());
3983
3984 int handshake_ret = SSL_do_handshake(handshaker.get());
3985 int handshake_err = SSL_get_error(handshaker.get(), handshake_ret);
3986 ASSERT_EQ(handshake_err, SSL_ERROR_WANT_READ);
3987
3988 ASSERT_TRUE(CompleteHandshakes(client.get(), handshaker.get()));
3989
3990 ScopedCBB cbb_handback;
3991 Array<uint8_t> handback;
3992 ASSERT_TRUE(CBB_init(cbb_handback.get(), 1024));
3993 ASSERT_TRUE(SSL_serialize_handback(handshaker.get(), cbb_handback.get()));
3994 ASSERT_TRUE(CBBFinishArray(cbb_handback.get(), &handback));
3995
3996 bssl::UniquePtr<SSL> server2(SSL_new(server_ctx.get()));
3997 ASSERT_TRUE(SSL_apply_handback(server2.get(), handback));
3998
3999 MoveBIOs(server2.get(), handshaker.get());
4000
4001 uint8_t byte = 42;
4002 EXPECT_EQ(SSL_write(client.get(), &byte, 1), 1);
4003 EXPECT_EQ(SSL_read(server2.get(), &byte, 1), 1);
4004 EXPECT_EQ(42, byte);
4005
4006 byte = 43;
4007 EXPECT_EQ(SSL_write(server2.get(), &byte, 1), 1);
4008 EXPECT_EQ(SSL_read(client.get(), &byte, 1), 1);
4009 EXPECT_EQ(43, byte);
4010 }
4011
TEST(SSLTest,HandoffDeclined)4012 TEST(SSLTest, HandoffDeclined) {
4013 bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
4014 bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
4015 ASSERT_TRUE(client_ctx);
4016 ASSERT_TRUE(server_ctx);
4017
4018 SSL_CTX_set_handoff_mode(server_ctx.get(), 1);
4019 ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), TLS1_2_VERSION));
4020
4021 bssl::UniquePtr<X509> cert = GetTestCertificate();
4022 bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
4023 ASSERT_TRUE(cert);
4024 ASSERT_TRUE(key);
4025 ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
4026 ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
4027
4028 bssl::UniquePtr<SSL> client, server;
4029 ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
4030 server_ctx.get(), ClientConfig(),
4031 false /* don't handshake */));
4032
4033 int client_ret = SSL_do_handshake(client.get());
4034 int client_err = SSL_get_error(client.get(), client_ret);
4035 ASSERT_EQ(client_err, SSL_ERROR_WANT_READ);
4036
4037 int server_ret = SSL_do_handshake(server.get());
4038 int server_err = SSL_get_error(server.get(), server_ret);
4039 ASSERT_EQ(server_err, SSL_ERROR_HANDOFF);
4040
4041 ScopedCBB cbb;
4042 ASSERT_TRUE(CBB_init(cbb.get(), 256));
4043 ASSERT_TRUE(SSL_serialize_handoff(server.get(), cbb.get()));
4044
4045 ASSERT_TRUE(SSL_decline_handoff(server.get()));
4046
4047 ASSERT_TRUE(CompleteHandshakes(client.get(), server.get()));
4048
4049 uint8_t byte = 42;
4050 EXPECT_EQ(SSL_write(client.get(), &byte, 1), 1);
4051 EXPECT_EQ(SSL_read(server.get(), &byte, 1), 1);
4052 EXPECT_EQ(42, byte);
4053
4054 byte = 43;
4055 EXPECT_EQ(SSL_write(server.get(), &byte, 1), 1);
4056 EXPECT_EQ(SSL_read(client.get(), &byte, 1), 1);
4057 EXPECT_EQ(43, byte);
4058 }
4059
4060 // TODO(davidben): Convert this file to GTest properly.
TEST(SSLTest,AllTests)4061 TEST(SSLTest, AllTests) {
4062 if (!TestSSL_SESSIONEncoding(kOpenSSLSession) ||
4063 !TestSSL_SESSIONEncoding(kCustomSession) ||
4064 !TestSSL_SESSIONEncoding(kBoringSSLSession) ||
4065 !TestBadSSL_SESSIONEncoding(kBadSessionExtraField) ||
4066 !TestBadSSL_SESSIONEncoding(kBadSessionVersion) ||
4067 !TestBadSSL_SESSIONEncoding(kBadSessionTrailingData) ||
4068 // Test the padding extension at TLS 1.2.
4069 !TestPaddingExtension(TLS1_2_VERSION, TLS1_2_VERSION) ||
4070 // Test the padding extension at TLS 1.3 with a TLS 1.2 session, so there
4071 // will be no PSK binder after the padding extension.
4072 !TestPaddingExtension(TLS1_3_VERSION, TLS1_2_VERSION) ||
4073 // Test the padding extension at TLS 1.3 with a TLS 1.3 session, so there
4074 // will be a PSK binder after the padding extension.
4075 !TestPaddingExtension(TLS1_3_VERSION, TLS1_3_DRAFT23_VERSION)) {
4076 ADD_FAILURE() << "Tests failed";
4077 }
4078 }
4079
4080 } // namespace
4081 } // namespace bssl
4082