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