• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <limits>
21 #include <string>
22 #include <utility>
23 #include <vector>
24 
25 #include <gtest/gtest.h>
26 
27 #include <openssl/aead.h>
28 #include <openssl/base64.h>
29 #include <openssl/bio.h>
30 #include <openssl/cipher.h>
31 #include <openssl/crypto.h>
32 #include <openssl/err.h>
33 #include <openssl/hmac.h>
34 #include <openssl/pem.h>
35 #include <openssl/sha.h>
36 #include <openssl/ssl.h>
37 #include <openssl/rand.h>
38 #include <openssl/x509.h>
39 
40 #include "internal.h"
41 #include "../crypto/internal.h"
42 #include "../crypto/test/test_util.h"
43 
44 #if defined(OPENSSL_WINDOWS)
45 // Windows defines struct timeval in winsock2.h.
46 OPENSSL_MSVC_PRAGMA(warning(push, 3))
47 #include <winsock2.h>
48 OPENSSL_MSVC_PRAGMA(warning(pop))
49 #else
50 #include <sys/time.h>
51 #endif
52 
53 #if defined(OPENSSL_THREADS)
54 #include <thread>
55 #endif
56 
57 
58 BSSL_NAMESPACE_BEGIN
59 
60 namespace {
61 
62 #define TRACED_CALL(code)                     \
63   do {                                        \
64     SCOPED_TRACE("<- called from here");      \
65     code;                                     \
66     if (::testing::Test::HasFatalFailure()) { \
67       return;                                 \
68     }                                         \
69   } while (false)
70 
71 struct VersionParam {
72   uint16_t version;
73   enum { is_tls, is_dtls } ssl_method;
74   const char name[8];
75 };
76 
77 static const size_t kTicketKeyLen = 48;
78 
79 static const VersionParam kAllVersions[] = {
80     {TLS1_VERSION, VersionParam::is_tls, "TLS1"},
81     {TLS1_1_VERSION, VersionParam::is_tls, "TLS1_1"},
82     {TLS1_2_VERSION, VersionParam::is_tls, "TLS1_2"},
83     {TLS1_3_VERSION, VersionParam::is_tls, "TLS1_3"},
84     {DTLS1_VERSION, VersionParam::is_dtls, "DTLS1"},
85     {DTLS1_2_VERSION, VersionParam::is_dtls, "DTLS1_2"},
86 };
87 
88 struct ExpectedCipher {
89   unsigned long id;
90   int in_group_flag;
91 };
92 
93 struct CipherTest {
94   // The rule string to apply.
95   const char *rule;
96   // The list of expected ciphers, in order.
97   std::vector<ExpectedCipher> expected;
98   // True if this cipher list should fail in strict mode.
99   bool strict_fail;
100 };
101 
102 struct CurveTest {
103   // The rule string to apply.
104   const char *rule;
105   // The list of expected curves, in order.
106   std::vector<uint16_t> expected;
107 };
108 
109 template <typename T>
110 class UnownedSSLExData {
111  public:
UnownedSSLExData()112   UnownedSSLExData() {
113     index_ = SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
114   }
115 
Get(const SSL * ssl)116   T *Get(const SSL *ssl) {
117     return index_ < 0 ? nullptr
118                       : static_cast<T *>(SSL_get_ex_data(ssl, index_));
119   }
120 
Set(SSL * ssl,T * t)121   bool Set(SSL *ssl, T *t) {
122     return index_ >= 0 && SSL_set_ex_data(ssl, index_, t);
123   }
124 
125  private:
126   int index_;
127 };
128 
129 static const CipherTest kCipherTests[] = {
130     // Selecting individual ciphers should work.
131     {
132         "ECDHE-ECDSA-CHACHA20-POLY1305:"
133         "ECDHE-RSA-CHACHA20-POLY1305:"
134         "ECDHE-ECDSA-AES128-GCM-SHA256:"
135         "ECDHE-RSA-AES128-GCM-SHA256",
136         {
137             {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
138             {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
139             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
140             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
141         },
142         false,
143     },
144     // + reorders selected ciphers to the end, keeping their relative order.
145     {
146         "ECDHE-ECDSA-CHACHA20-POLY1305:"
147         "ECDHE-RSA-CHACHA20-POLY1305:"
148         "ECDHE-ECDSA-AES128-GCM-SHA256:"
149         "ECDHE-RSA-AES128-GCM-SHA256:"
150         "+aRSA",
151         {
152             {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
153             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
154             {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
155             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
156         },
157         false,
158     },
159     // ! banishes ciphers from future selections.
160     {
161         "!aRSA:"
162         "ECDHE-ECDSA-CHACHA20-POLY1305:"
163         "ECDHE-RSA-CHACHA20-POLY1305:"
164         "ECDHE-ECDSA-AES128-GCM-SHA256:"
165         "ECDHE-RSA-AES128-GCM-SHA256",
166         {
167             {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
168             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
169         },
170         false,
171     },
172     // Multiple masks can be ANDed in a single rule.
173     {
174         "kRSA+AESGCM+AES128",
175         {
176             {TLS1_CK_RSA_WITH_AES_128_GCM_SHA256, 0},
177         },
178         false,
179     },
180     // - removes selected ciphers, but preserves their order for future
181     // selections. Select AES_128_GCM, but order the key exchanges RSA,
182     // ECDHE_RSA.
183     {
184         "ALL:-kECDHE:"
185         "-kRSA:-ALL:"
186         "AESGCM+AES128+aRSA",
187         {
188             {TLS1_CK_RSA_WITH_AES_128_GCM_SHA256, 0},
189             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
190         },
191         false,
192     },
193     // Unknown selectors are no-ops, except in strict mode.
194     {
195         "ECDHE-ECDSA-CHACHA20-POLY1305:"
196         "ECDHE-RSA-CHACHA20-POLY1305:"
197         "ECDHE-ECDSA-AES128-GCM-SHA256:"
198         "ECDHE-RSA-AES128-GCM-SHA256:"
199         "BOGUS1",
200         {
201             {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
202             {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
203             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
204             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
205         },
206         true,
207     },
208     // Unknown selectors are no-ops, except in strict mode.
209     {
210         "ECDHE-ECDSA-CHACHA20-POLY1305:"
211         "ECDHE-RSA-CHACHA20-POLY1305:"
212         "ECDHE-ECDSA-AES128-GCM-SHA256:"
213         "ECDHE-RSA-AES128-GCM-SHA256:"
214         "-BOGUS2:+BOGUS3:!BOGUS4",
215         {
216             {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 0},
217             {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
218             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
219             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
220         },
221         true,
222     },
223     // Square brackets specify equi-preference groups.
224     {
225         "[ECDHE-ECDSA-CHACHA20-POLY1305|ECDHE-ECDSA-AES128-GCM-SHA256]:"
226         "[ECDHE-RSA-CHACHA20-POLY1305]:"
227         "ECDHE-RSA-AES128-GCM-SHA256",
228         {
229             {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 1},
230             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
231             {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
232             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
233         },
234         false,
235     },
236     // Standard names may be used instead of OpenSSL names.
237     {
238         "[TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256|"
239         "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256]:"
240         "[TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256]:"
241         "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
242         {
243             {TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, 1},
244             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
245             {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
246             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
247         },
248         false,
249     },
250     // @STRENGTH performs a stable strength-sort of the selected ciphers and
251     // only the selected ciphers.
252     {
253         // To simplify things, banish all but {ECDHE_RSA,RSA} x
254         // {CHACHA20,AES_256_CBC,AES_128_CBC} x SHA1.
255         "!AESGCM:!3DES:"
256         // Order some ciphers backwards by strength.
257         "ALL:-CHACHA20:-AES256:-AES128:-ALL:"
258         // Select ECDHE ones and sort them by strength. Ties should resolve
259         // based on the order above.
260         "kECDHE:@STRENGTH:-ALL:"
261         // Now bring back everything uses RSA. ECDHE_RSA should be first, sorted
262         // by strength. Then RSA, backwards by strength.
263         "aRSA",
264         {
265             {TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA, 0},
266             {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
267             {TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA, 0},
268             {TLS1_CK_RSA_WITH_AES_128_SHA, 0},
269             {TLS1_CK_RSA_WITH_AES_256_SHA, 0},
270         },
271         false,
272     },
273     // Additional masks after @STRENGTH get silently discarded.
274     //
275     // TODO(davidben): Make this an error. If not silently discarded, they get
276     // interpreted as + opcodes which are very different.
277     {
278         "ECDHE-RSA-AES128-GCM-SHA256:"
279         "ECDHE-RSA-AES256-GCM-SHA384:"
280         "@STRENGTH+AES256",
281         {
282             {TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0},
283             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
284         },
285         false,
286     },
287     {
288         "ECDHE-RSA-AES128-GCM-SHA256:"
289         "ECDHE-RSA-AES256-GCM-SHA384:"
290         "@STRENGTH+AES256:"
291         "ECDHE-RSA-CHACHA20-POLY1305",
292         {
293             {TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0},
294             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
295             {TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, 0},
296         },
297         false,
298     },
299     // Exact ciphers may not be used in multi-part rules; they are treated
300     // as unknown aliases.
301     {
302         "ECDHE-ECDSA-AES128-GCM-SHA256:"
303         "ECDHE-RSA-AES128-GCM-SHA256:"
304         "!ECDHE-RSA-AES128-GCM-SHA256+RSA:"
305         "!ECDSA+ECDHE-ECDSA-AES128-GCM-SHA256",
306         {
307             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
308             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
309         },
310         true,
311     },
312     // SSLv3 matches everything that existed before TLS 1.2.
313     {
314         "AES128-SHA:ECDHE-RSA-AES128-GCM-SHA256:!SSLv3",
315         {
316             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
317         },
318         false,
319     },
320     // TLSv1.2 matches everything added in TLS 1.2.
321     {
322         "AES128-SHA:ECDHE-RSA-AES128-GCM-SHA256:!TLSv1.2",
323         {
324             {TLS1_CK_RSA_WITH_AES_128_SHA, 0},
325         },
326         false,
327     },
328     // The two directives have no intersection.  But each component is valid, so
329     // even in strict mode it is accepted.
330     {
331         "AES128-SHA:ECDHE-RSA-AES128-GCM-SHA256:!TLSv1.2+SSLv3",
332         {
333             {TLS1_CK_RSA_WITH_AES_128_SHA, 0},
334             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
335         },
336         false,
337     },
338     // Spaces, semi-colons and commas are separators.
339     {
340         "AES128-SHA: ECDHE-RSA-AES128-GCM-SHA256 AES256-SHA ,ECDHE-ECDSA-AES128-GCM-SHA256 ; AES128-GCM-SHA256",
341         {
342             {TLS1_CK_RSA_WITH_AES_128_SHA, 0},
343             {TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0},
344             {TLS1_CK_RSA_WITH_AES_256_SHA, 0},
345             {TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0},
346             {TLS1_CK_RSA_WITH_AES_128_GCM_SHA256, 0},
347         },
348         // …but not in strict mode.
349         true,
350     },
351 };
352 
353 static const char *kBadRules[] = {
354   // Invalid brackets.
355   "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256",
356   "RSA]",
357   "[[RSA]]",
358   // Operators inside brackets.
359   "[+RSA]",
360   // Unknown directive.
361   "@BOGUS",
362   // Empty cipher lists error at SSL_CTX_set_cipher_list.
363   "",
364   "BOGUS",
365   // COMPLEMENTOFDEFAULT is empty.
366   "COMPLEMENTOFDEFAULT",
367   // Invalid command.
368   "?BAR",
369   // Special operators are not allowed if groups are used.
370   "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256]:+FOO",
371   "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256]:!FOO",
372   "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256]:-FOO",
373   "[ECDHE-RSA-CHACHA20-POLY1305|ECDHE-RSA-AES128-GCM-SHA256]:@STRENGTH",
374   // Opcode supplied, but missing selector.
375   "+",
376   // Spaces are forbidden in equal-preference groups.
377   "[AES128-SHA | AES128-SHA256]",
378 };
379 
380 static const char *kMustNotIncludeNull[] = {
381   "ALL",
382   "DEFAULT",
383   "HIGH",
384   "FIPS",
385   "SHA",
386   "SHA1",
387   "RSA",
388   "SSLv3",
389   "TLSv1",
390   "TLSv1.2",
391 };
392 
393 static const CurveTest kCurveTests[] = {
394   {
395     "P-256",
396     { SSL_CURVE_SECP256R1 },
397   },
398   {
399     "P-256:CECPQ2",
400     { SSL_CURVE_SECP256R1, SSL_CURVE_CECPQ2 },
401   },
402 
403   {
404     "P-256:P-384:P-521:X25519",
405     {
406       SSL_CURVE_SECP256R1,
407       SSL_CURVE_SECP384R1,
408       SSL_CURVE_SECP521R1,
409       SSL_CURVE_X25519,
410     },
411   },
412   {
413     "prime256v1:secp384r1:secp521r1:x25519",
414     {
415       SSL_CURVE_SECP256R1,
416       SSL_CURVE_SECP384R1,
417       SSL_CURVE_SECP521R1,
418       SSL_CURVE_X25519,
419     },
420   },
421 };
422 
423 static const char *kBadCurvesLists[] = {
424   "",
425   ":",
426   "::",
427   "P-256::X25519",
428   "RSA:P-256",
429   "P-256:RSA",
430   "X25519:P-256:",
431   ":X25519:P-256",
432 };
433 
CipherListToString(SSL_CTX * ctx)434 static std::string CipherListToString(SSL_CTX *ctx) {
435   bool in_group = false;
436   std::string ret;
437   const STACK_OF(SSL_CIPHER) *ciphers = SSL_CTX_get_ciphers(ctx);
438   for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
439     const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
440     if (!in_group && SSL_CTX_cipher_in_group(ctx, i)) {
441       ret += "\t[\n";
442       in_group = true;
443     }
444     ret += "\t";
445     if (in_group) {
446       ret += "  ";
447     }
448     ret += SSL_CIPHER_get_name(cipher);
449     ret += "\n";
450     if (in_group && !SSL_CTX_cipher_in_group(ctx, i)) {
451       ret += "\t]\n";
452       in_group = false;
453     }
454   }
455   return ret;
456 }
457 
CipherListsEqual(SSL_CTX * ctx,const std::vector<ExpectedCipher> & expected)458 static bool CipherListsEqual(SSL_CTX *ctx,
459                              const std::vector<ExpectedCipher> &expected) {
460   const STACK_OF(SSL_CIPHER) *ciphers = SSL_CTX_get_ciphers(ctx);
461   if (sk_SSL_CIPHER_num(ciphers) != expected.size()) {
462     return false;
463   }
464 
465   for (size_t i = 0; i < expected.size(); i++) {
466     const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
467     if (expected[i].id != SSL_CIPHER_get_id(cipher) ||
468         expected[i].in_group_flag != !!SSL_CTX_cipher_in_group(ctx, i)) {
469       return false;
470     }
471   }
472 
473   return true;
474 }
475 
TEST(GrowableArrayTest,Resize)476 TEST(GrowableArrayTest, Resize) {
477   GrowableArray<size_t> array;
478   ASSERT_TRUE(array.empty());
479   EXPECT_EQ(array.size(), 0u);
480 
481   ASSERT_TRUE(array.Push(42));
482   ASSERT_TRUE(!array.empty());
483   EXPECT_EQ(array.size(), 1u);
484 
485   // Force a resize operation to occur
486   for (size_t i = 0; i < 16; i++) {
487     ASSERT_TRUE(array.Push(i + 1));
488   }
489 
490   EXPECT_EQ(array.size(), 17u);
491 
492   // Verify that expected values are still contained in array
493   for (size_t i = 0; i < array.size(); i++) {
494     EXPECT_EQ(array[i], i == 0 ? 42 : i);
495   }
496 }
497 
TEST(GrowableArrayTest,MoveConstructor)498 TEST(GrowableArrayTest, MoveConstructor) {
499   GrowableArray<size_t> array;
500   for (size_t i = 0; i < 100; i++) {
501     ASSERT_TRUE(array.Push(i));
502   }
503 
504   GrowableArray<size_t> array_moved(std::move(array));
505   for (size_t i = 0; i < 100; i++) {
506     EXPECT_EQ(array_moved[i], i);
507   }
508 }
509 
TEST(GrowableArrayTest,GrowableArrayContainingGrowableArrays)510 TEST(GrowableArrayTest, GrowableArrayContainingGrowableArrays) {
511   // Representative example of a struct that contains a GrowableArray.
512   struct TagAndArray {
513     size_t tag;
514     GrowableArray<size_t> array;
515   };
516 
517   GrowableArray<TagAndArray> array;
518   for (size_t i = 0; i < 100; i++) {
519     TagAndArray elem;
520     elem.tag = i;
521     for (size_t j = 0; j < i; j++) {
522       ASSERT_TRUE(elem.array.Push(j));
523     }
524     ASSERT_TRUE(array.Push(std::move(elem)));
525   }
526   EXPECT_EQ(array.size(), static_cast<size_t>(100));
527 
528   GrowableArray<TagAndArray> array_moved(std::move(array));
529   EXPECT_EQ(array_moved.size(), static_cast<size_t>(100));
530   size_t count = 0;
531   for (const TagAndArray &elem : array_moved) {
532     // Test the square bracket operator returns the same value as iteration.
533     EXPECT_EQ(&elem, &array_moved[count]);
534 
535     EXPECT_EQ(elem.tag, count);
536     EXPECT_EQ(elem.array.size(), count);
537     for (size_t j = 0; j < count; j++) {
538       EXPECT_EQ(elem.array[j], j);
539     }
540     count++;
541   }
542 }
543 
TEST(SSLTest,CipherRules)544 TEST(SSLTest, CipherRules) {
545   for (const CipherTest &t : kCipherTests) {
546     SCOPED_TRACE(t.rule);
547     bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
548     ASSERT_TRUE(ctx);
549 
550     // Test lax mode.
551     ASSERT_TRUE(SSL_CTX_set_cipher_list(ctx.get(), t.rule));
552     EXPECT_TRUE(CipherListsEqual(ctx.get(), t.expected))
553         << "Cipher rule evaluated to:\n"
554         << CipherListToString(ctx.get());
555 
556     // Test strict mode.
557     if (t.strict_fail) {
558       EXPECT_FALSE(SSL_CTX_set_strict_cipher_list(ctx.get(), t.rule));
559     } else {
560       ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(ctx.get(), t.rule));
561       EXPECT_TRUE(CipherListsEqual(ctx.get(), t.expected))
562           << "Cipher rule evaluated to:\n"
563           << CipherListToString(ctx.get());
564     }
565   }
566 
567   for (const char *rule : kBadRules) {
568     SCOPED_TRACE(rule);
569     bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
570     ASSERT_TRUE(ctx);
571 
572     EXPECT_FALSE(SSL_CTX_set_cipher_list(ctx.get(), rule));
573     ERR_clear_error();
574   }
575 
576   for (const char *rule : kMustNotIncludeNull) {
577     SCOPED_TRACE(rule);
578     bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
579     ASSERT_TRUE(ctx);
580 
581     ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(ctx.get(), rule));
582     for (const SSL_CIPHER *cipher : SSL_CTX_get_ciphers(ctx.get())) {
583       EXPECT_NE(NID_undef, SSL_CIPHER_get_cipher_nid(cipher));
584     }
585   }
586 }
587 
TEST(SSLTest,CurveRules)588 TEST(SSLTest, CurveRules) {
589   for (const CurveTest &t : kCurveTests) {
590     SCOPED_TRACE(t.rule);
591     bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
592     ASSERT_TRUE(ctx);
593 
594     ASSERT_TRUE(SSL_CTX_set1_curves_list(ctx.get(), t.rule));
595     ASSERT_EQ(t.expected.size(), ctx->supported_group_list.size());
596     for (size_t i = 0; i < t.expected.size(); i++) {
597       EXPECT_EQ(t.expected[i], ctx->supported_group_list[i]);
598     }
599   }
600 
601   for (const char *rule : kBadCurvesLists) {
602     SCOPED_TRACE(rule);
603     bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
604     ASSERT_TRUE(ctx);
605 
606     EXPECT_FALSE(SSL_CTX_set1_curves_list(ctx.get(), rule));
607     ERR_clear_error();
608   }
609 }
610 
611 // kOpenSSLSession is a serialized SSL_SESSION.
612 static const char kOpenSSLSession[] =
613     "MIIFqgIBAQICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
614     "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
615     "IWoJoQYCBFRDO46iBAICASyjggR6MIIEdjCCA16gAwIBAgIIK9dUvsPWSlUwDQYJ"
616     "KoZIhvcNAQEFBQAwSTELMAkGA1UEBhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMx"
617     "JTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5ldCBBdXRob3JpdHkgRzIwHhcNMTQxMDA4"
618     "MTIwNzU3WhcNMTUwMTA2MDAwMDAwWjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwK"
619     "Q2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzETMBEGA1UECgwKR29v"
620     "Z2xlIEluYzEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEB"
621     "AQUAA4IBDwAwggEKAoIBAQCcKeLrplAC+Lofy8t/wDwtB6eu72CVp0cJ4V3lknN6"
622     "huH9ct6FFk70oRIh/VBNBBz900jYy+7111Jm1b8iqOTQ9aT5C7SEhNcQFJvqzH3e"
623     "MPkb6ZSWGm1yGF7MCQTGQXF20Sk/O16FSjAynU/b3oJmOctcycWYkY0ytS/k3LBu"
624     "Id45PJaoMqjB0WypqvNeJHC3q5JjCB4RP7Nfx5jjHSrCMhw8lUMW4EaDxjaR9KDh"
625     "PLgjsk+LDIySRSRDaCQGhEOWLJZVLzLo4N6/UlctCHEllpBUSvEOyFga52qroGjg"
626     "rf3WOQ925MFwzd6AK+Ich0gDRg8sQfdLH5OuP1cfLfU1AgMBAAGjggFBMIIBPTAd"
627     "BgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdv"
628     "b2dsZS5jb20waAYIKwYBBQUHAQEEXDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtp"
629     "Lmdvb2dsZS5jb20vR0lBRzIuY3J0MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50"
630     "czEuZ29vZ2xlLmNvbS9vY3NwMB0GA1UdDgQWBBQ7a+CcxsZByOpc+xpYFcIbnUMZ"
631     "hTAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEv"
632     "MBcGA1UdIAQQMA4wDAYKKwYBBAHWeQIFATAwBgNVHR8EKTAnMCWgI6Ahhh9odHRw"
633     "Oi8vcGtpLmdvb2dsZS5jb20vR0lBRzIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCa"
634     "OXCBdoqUy5bxyq+Wrh1zsyyCFim1PH5VU2+yvDSWrgDY8ibRGJmfff3r4Lud5kal"
635     "dKs9k8YlKD3ITG7P0YT/Rk8hLgfEuLcq5cc0xqmE42xJ+Eo2uzq9rYorc5emMCxf"
636     "5L0TJOXZqHQpOEcuptZQ4OjdYMfSxk5UzueUhA3ogZKRcRkdB3WeWRp+nYRhx4St"
637     "o2rt2A0MKmY9165GHUqMK9YaaXHDXqBu7Sefr1uSoAP9gyIJKeihMivsGqJ1TD6Z"
638     "cc6LMe+dN2P8cZEQHtD1y296ul4Mivqk3jatUVL8/hCwgch9A8O4PGZq9WqBfEWm"
639     "IyHh1dPtbg1lOXdYCWtjpAIEAKUDAgEUqQUCAwGJwKqBpwSBpBwUQvoeOk0Kg36S"
640     "YTcLEkXqKwOBfF9vE4KX0NxeLwjcDTpsuh3qXEaZ992r1N38VDcyS6P7I6HBYN9B"
641     "sNHM362zZnY27GpTw+Kwd751CLoXFPoaMOe57dbBpXoro6Pd3BTbf/Tzr88K06yE"
642     "OTDKPNj3+inbMaVigtK4PLyPq+Topyzvx9USFgRvyuoxn0Hgb+R0A3j6SLRuyOdA"
643     "i4gv7Y5oliyntgMBAQA=";
644 
645 // kCustomSession is a custom serialized SSL_SESSION generated by
646 // filling in missing fields from |kOpenSSLSession|. This includes
647 // providing |peer_sha256|, so |peer| is not serialized.
648 static const char kCustomSession[] =
649     "MIIBZAIBAQICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
650     "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
651     "IWoJoQYCBFRDO46iBAICASykAwQBAqUDAgEUqAcEBXdvcmxkqQUCAwGJwKqBpwSB"
652     "pBwUQvoeOk0Kg36SYTcLEkXqKwOBfF9vE4KX0NxeLwjcDTpsuh3qXEaZ992r1N38"
653     "VDcyS6P7I6HBYN9BsNHM362zZnY27GpTw+Kwd751CLoXFPoaMOe57dbBpXoro6Pd"
654     "3BTbf/Tzr88K06yEOTDKPNj3+inbMaVigtK4PLyPq+Topyzvx9USFgRvyuoxn0Hg"
655     "b+R0A3j6SLRuyOdAi4gv7Y5oliynrSIEIAYGBgYGBgYGBgYGBgYGBgYGBgYGBgYG"
656     "BgYGBgYGBgYGrgMEAQevAwQBBLADBAEF";
657 
658 // kBoringSSLSession is a serialized SSL_SESSION generated from bssl client.
659 static const char kBoringSSLSession[] =
660     "MIIRwQIBAQICAwMEAsAvBCDdoGxGK26mR+8lM0uq6+k9xYuxPnwAjpcF9n0Yli9R"
661     "kQQwbyshfWhdi5XQ1++7n2L1qqrcVlmHBPpr6yknT/u4pUrpQB5FZ7vqvNn8MdHf"
662     "9rWgoQYCBFXgs7uiBAICHCCjggR6MIIEdjCCA16gAwIBAgIIf+yfD7Y6UicwDQYJ"
663     "KoZIhvcNAQELBQAwSTELMAkGA1UEBhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMx"
664     "JTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5ldCBBdXRob3JpdHkgRzIwHhcNMTUwODEy"
665     "MTQ1MzE1WhcNMTUxMTEwMDAwMDAwWjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwK"
666     "Q2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzETMBEGA1UECgwKR29v"
667     "Z2xlIEluYzEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEB"
668     "AQUAA4IBDwAwggEKAoIBAQC0MeG5YGQ0t+IeJeoneP/PrhEaieibeKYkbKVLNZpo"
669     "PLuBinvhkXZo3DC133NpCBpy6ZktBwamqyixAyuk/NU6OjgXqwwxfQ7di1AInLIU"
670     "792c7hFyNXSUCG7At8Ifi3YwBX9Ba6u/1d6rWTGZJrdCq3QU11RkKYyTq2KT5mce"
671     "Tv9iGKqSkSTlp8puy/9SZ/3DbU3U+BuqCFqeSlz7zjwFmk35acdCilpJlVDDN5C/"
672     "RCh8/UKc8PaL+cxlt531qoTENvYrflBno14YEZlCBZsPiFeUSILpKEj3Ccwhy0eL"
673     "EucWQ72YZU8mUzXBoXGn0zA0crFl5ci/2sTBBGZsylNBAgMBAAGjggFBMIIBPTAd"
674     "BgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdv"
675     "b2dsZS5jb20waAYIKwYBBQUHAQEEXDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtp"
676     "Lmdvb2dsZS5jb20vR0lBRzIuY3J0MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50"
677     "czEuZ29vZ2xlLmNvbS9vY3NwMB0GA1UdDgQWBBS/bzHxcE73Q4j3slC4BLbMtLjG"
678     "GjAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEv"
679     "MBcGA1UdIAQQMA4wDAYKKwYBBAHWeQIFATAwBgNVHR8EKTAnMCWgI6Ahhh9odHRw"
680     "Oi8vcGtpLmdvb2dsZS5jb20vR0lBRzIuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQAb"
681     "qdWPZEHk0X7iKPCTHL6S3w6q1eR67goxZGFSM1lk1hjwyu7XcLJuvALVV9uY3ovE"
682     "kQZSHwT+pyOPWQhsSjO+1GyjvCvK/CAwiUmBX+bQRGaqHsRcio7xSbdVcajQ3bXd"
683     "X+s0WdbOpn6MStKAiBVloPlSxEI8pxY6x/BBCnTIk/+DMB17uZlOjG3vbAnkDkP+"
684     "n0OTucD9sHV7EVj9XUxi51nOfNBCN/s7lpUjDS/NJ4k3iwOtbCPswiot8vLO779a"
685     "f07vR03r349Iz/KTzk95rlFtX0IU+KYNxFNsanIXZ+C9FYGRXkwhHcvFb4qMUB1y"
686     "TTlM80jBMOwyjZXmjRAhpAIEAKUDAgEUqQUCAwGJwKqBpwSBpOgebbmn9NRUtMWH"
687     "+eJpqA5JLMFSMCChOsvKey3toBaCNGU7HfAEiiXNuuAdCBoK262BjQc2YYfqFzqH"
688     "zuppopXCvhohx7j/tnCNZIMgLYt/O9SXK2RYI5z8FhCCHvB4CbD5G0LGl5EFP27s"
689     "Jb6S3aTTYPkQe8yZSlxevg6NDwmTogLO9F7UUkaYmVcMQhzssEE2ZRYNwSOU6KjE"
690     "0Yj+8fAiBtbQriIEIN2L8ZlpaVrdN5KFNdvcmOxJu81P8q53X55xQyGTnGWwsgMC"
691     "ARezggvvMIIEdjCCA16gAwIBAgIIf+yfD7Y6UicwDQYJKoZIhvcNAQELBQAwSTEL"
692     "MAkGA1UEBhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2ds"
693     "ZSBJbnRlcm5ldCBBdXRob3JpdHkgRzIwHhcNMTUwODEyMTQ1MzE1WhcNMTUxMTEw"
694     "MDAwMDAwWjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQG"
695     "A1UEBwwNTW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEXMBUGA1UE"
696     "AwwOd3d3Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB"
697     "AQC0MeG5YGQ0t+IeJeoneP/PrhEaieibeKYkbKVLNZpoPLuBinvhkXZo3DC133Np"
698     "CBpy6ZktBwamqyixAyuk/NU6OjgXqwwxfQ7di1AInLIU792c7hFyNXSUCG7At8If"
699     "i3YwBX9Ba6u/1d6rWTGZJrdCq3QU11RkKYyTq2KT5mceTv9iGKqSkSTlp8puy/9S"
700     "Z/3DbU3U+BuqCFqeSlz7zjwFmk35acdCilpJlVDDN5C/RCh8/UKc8PaL+cxlt531"
701     "qoTENvYrflBno14YEZlCBZsPiFeUSILpKEj3Ccwhy0eLEucWQ72YZU8mUzXBoXGn"
702     "0zA0crFl5ci/2sTBBGZsylNBAgMBAAGjggFBMIIBPTAdBgNVHSUEFjAUBggrBgEF"
703     "BQcDAQYIKwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdvb2dsZS5jb20waAYIKwYB"
704     "BQUHAQEEXDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtpLmdvb2dsZS5jb20vR0lB"
705     "RzIuY3J0MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50czEuZ29vZ2xlLmNvbS9v"
706     "Y3NwMB0GA1UdDgQWBBS/bzHxcE73Q4j3slC4BLbMtLjGGjAMBgNVHRMBAf8EAjAA"
707     "MB8GA1UdIwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEvMBcGA1UdIAQQMA4wDAYK"
708     "KwYBBAHWeQIFATAwBgNVHR8EKTAnMCWgI6Ahhh9odHRwOi8vcGtpLmdvb2dsZS5j"
709     "b20vR0lBRzIuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQAbqdWPZEHk0X7iKPCTHL6S"
710     "3w6q1eR67goxZGFSM1lk1hjwyu7XcLJuvALVV9uY3ovEkQZSHwT+pyOPWQhsSjO+"
711     "1GyjvCvK/CAwiUmBX+bQRGaqHsRcio7xSbdVcajQ3bXdX+s0WdbOpn6MStKAiBVl"
712     "oPlSxEI8pxY6x/BBCnTIk/+DMB17uZlOjG3vbAnkDkP+n0OTucD9sHV7EVj9XUxi"
713     "51nOfNBCN/s7lpUjDS/NJ4k3iwOtbCPswiot8vLO779af07vR03r349Iz/KTzk95"
714     "rlFtX0IU+KYNxFNsanIXZ+C9FYGRXkwhHcvFb4qMUB1yTTlM80jBMOwyjZXmjRAh"
715     "MIID8DCCAtigAwIBAgIDAjqDMA0GCSqGSIb3DQEBCwUAMEIxCzAJBgNVBAYTAlVT"
716     "MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i"
717     "YWwgQ0EwHhcNMTMwNDA1MTUxNTU2WhcNMTYxMjMxMjM1OTU5WjBJMQswCQYDVQQG"
718     "EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy"
719     "bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB"
720     "AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP"
721     "VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv"
722     "h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE"
723     "ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ"
724     "EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC"
725     "DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB5zCB5DAfBgNVHSMEGDAWgBTAephojYn7"
726     "qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wDgYD"
727     "VR0PAQH/BAQDAgEGMC4GCCsGAQUFBwEBBCIwIDAeBggrBgEFBQcwAYYSaHR0cDov"
728     "L2cuc3ltY2QuY29tMBIGA1UdEwEB/wQIMAYBAf8CAQAwNQYDVR0fBC4wLDAqoCig"
729     "JoYkaHR0cDovL2cuc3ltY2IuY29tL2NybHMvZ3RnbG9iYWwuY3JsMBcGA1UdIAQQ"
730     "MA4wDAYKKwYBBAHWeQIFATANBgkqhkiG9w0BAQsFAAOCAQEAqvqpIM1qZ4PtXtR+"
731     "3h3Ef+AlBgDFJPupyC1tft6dgmUsgWM0Zj7pUsIItMsv91+ZOmqcUHqFBYx90SpI"
732     "hNMJbHzCzTWf84LuUt5oX+QAihcglvcpjZpNy6jehsgNb1aHA30DP9z6eX0hGfnI"
733     "Oi9RdozHQZJxjyXON/hKTAAj78Q1EK7gI4BzfE00LshukNYQHpmEcxpw8u1VDu4X"
734     "Bupn7jLrLN1nBz/2i8Jw3lsA5rsb0zYaImxssDVCbJAJPZPpZAkiDoUGn8JzIdPm"
735     "X4DkjYUiOnMDsWCOrmji9D6X52ASCWg23jrW4kOVWzeBkoEfu43XrVJkFleW2V40"
736     "fsg12DCCA30wggLmoAMCAQICAxK75jANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQG"
737     "EwJVUzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUg"
738     "Q2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTAyMDUyMTA0MDAwMFoXDTE4MDgyMTA0"
739     "MDAwMFowQjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xGzAZ"
740     "BgNVBAMTEkdlb1RydXN0IEdsb2JhbCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP"
741     "ADCCAQoCggEBANrMGGMw/fQXIxpWflvfPGw45HG3eJHUvKHYTPioQ7YD6U0hBwiI"
742     "2lgvZjkpvQV4i5046AW3an5xpObEYKaw74DkiSgPniXW7YPzraaRx5jJQhg1FJ2t"
743     "mEaSLk/K8YdDwRaVVy1Q74ktgHpXrfLuX2vSAI25FPgUFTXZwEaje3LIkb/JVSvN"
744     "0Jc+nCZkzN/Ogxlxyk7m1NV7qRnNVd7I7NJeOFPlXE+MLf5QIzb8ZubLjqQ5GQC3"
745     "lQI5kQsO/jgu0R0FmvZNPm8PBx2vLB6PYDni+jZTEznUXiYr2z2oFL0y6xgDKFIE"
746     "ceWrMz3hOLsHNoRinHnqFjD0X8Ar6HFr5PkCAwEAAaOB8DCB7TAfBgNVHSMEGDAW"
747     "gBRI5mj5K9KylddH2CMgEE8zmJCf1DAdBgNVHQ4EFgQUwHqYaI2J+6sFZAwRfap9"
748     "ZbjKzE4wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMw"
749     "MTAvoC2gK4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9zZWN1cmVjYS5j"
750     "cmwwTgYDVR0gBEcwRTBDBgRVHSAAMDswOQYIKwYBBQUHAgEWLWh0dHBzOi8vd3d3"
751     "Lmdlb3RydXN0LmNvbS9yZXNvdXJjZXMvcmVwb3NpdG9yeTANBgkqhkiG9w0BAQUF"
752     "AAOBgQB24RJuTksWEoYwBrKBCM/wCMfHcX5m7sLt1Dsf//DwyE7WQziwuTB9GNBV"
753     "g6JqyzYRnOhIZqNtf7gT1Ef+i1pcc/yu2RsyGTirlzQUqpbS66McFAhJtrvlke+D"
754     "NusdVm/K2rxzY5Dkf3s+Iss9B+1fOHSc4wNQTqGvmO5h8oQ/Eg==";
755 
756 // kBadSessionExtraField is a custom serialized SSL_SESSION generated by replacing
757 // the final (optional) element of |kCustomSession| with tag number 99.
758 static const char kBadSessionExtraField[] =
759     "MIIBdgIBAQICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
760     "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
761     "IWoJoQYCBFRDO46iBAICASykAwQBAqUDAgEUphAEDnd3dy5nb29nbGUuY29tqAcE"
762     "BXdvcmxkqQUCAwGJwKqBpwSBpBwUQvoeOk0Kg36SYTcLEkXqKwOBfF9vE4KX0Nxe"
763     "LwjcDTpsuh3qXEaZ992r1N38VDcyS6P7I6HBYN9BsNHM362zZnY27GpTw+Kwd751"
764     "CLoXFPoaMOe57dbBpXoro6Pd3BTbf/Tzr88K06yEOTDKPNj3+inbMaVigtK4PLyP"
765     "q+Topyzvx9USFgRvyuoxn0Hgb+R0A3j6SLRuyOdAi4gv7Y5oliynrSIEIAYGBgYG"
766     "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGrgMEAQevAwQBBOMDBAEF";
767 
768 // kBadSessionVersion is a custom serialized SSL_SESSION generated by replacing
769 // the version of |kCustomSession| with 2.
770 static const char kBadSessionVersion[] =
771     "MIIBdgIBAgICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
772     "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
773     "IWoJoQYCBFRDO46iBAICASykAwQBAqUDAgEUphAEDnd3dy5nb29nbGUuY29tqAcE"
774     "BXdvcmxkqQUCAwGJwKqBpwSBpBwUQvoeOk0Kg36SYTcLEkXqKwOBfF9vE4KX0Nxe"
775     "LwjcDTpsuh3qXEaZ992r1N38VDcyS6P7I6HBYN9BsNHM362zZnY27GpTw+Kwd751"
776     "CLoXFPoaMOe57dbBpXoro6Pd3BTbf/Tzr88K06yEOTDKPNj3+inbMaVigtK4PLyP"
777     "q+Topyzvx9USFgRvyuoxn0Hgb+R0A3j6SLRuyOdAi4gv7Y5oliynrSIEIAYGBgYG"
778     "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGrgMEAQevAwQBBLADBAEF";
779 
780 // kBadSessionTrailingData is a custom serialized SSL_SESSION with trailing data
781 // appended.
782 static const char kBadSessionTrailingData[] =
783     "MIIBdgIBAQICAwMEAsAvBCAG5Q1ndq4Yfmbeo1zwLkNRKmCXGdNgWvGT3cskV0yQ"
784     "kAQwJlrlzkAWBOWiLj/jJ76D7l+UXoizP2KI2C7I2FccqMmIfFmmkUy32nIJ0mZH"
785     "IWoJoQYCBFRDO46iBAICASykAwQBAqUDAgEUphAEDnd3dy5nb29nbGUuY29tqAcE"
786     "BXdvcmxkqQUCAwGJwKqBpwSBpBwUQvoeOk0Kg36SYTcLEkXqKwOBfF9vE4KX0Nxe"
787     "LwjcDTpsuh3qXEaZ992r1N38VDcyS6P7I6HBYN9BsNHM362zZnY27GpTw+Kwd751"
788     "CLoXFPoaMOe57dbBpXoro6Pd3BTbf/Tzr88K06yEOTDKPNj3+inbMaVigtK4PLyP"
789     "q+Topyzvx9USFgRvyuoxn0Hgb+R0A3j6SLRuyOdAi4gv7Y5oliynrSIEIAYGBgYG"
790     "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGrgMEAQevAwQBBLADBAEFAAAA";
791 
DecodeBase64(std::vector<uint8_t> * out,const char * in)792 static bool DecodeBase64(std::vector<uint8_t> *out, const char *in) {
793   size_t len;
794   if (!EVP_DecodedLength(&len, strlen(in))) {
795     fprintf(stderr, "EVP_DecodedLength failed\n");
796     return false;
797   }
798 
799   out->resize(len);
800   if (!EVP_DecodeBase64(out->data(), &len, len, (const uint8_t *)in,
801                         strlen(in))) {
802     fprintf(stderr, "EVP_DecodeBase64 failed\n");
803     return false;
804   }
805   out->resize(len);
806   return true;
807 }
808 
TEST(SSLTest,SessionEncoding)809 TEST(SSLTest, SessionEncoding) {
810   for (const char *input_b64 : {
811            kOpenSSLSession,
812            kCustomSession,
813            kBoringSSLSession,
814        }) {
815     SCOPED_TRACE(std::string(input_b64));
816     // Decode the input.
817     std::vector<uint8_t> input;
818     ASSERT_TRUE(DecodeBase64(&input, input_b64));
819 
820     // Verify the SSL_SESSION decodes.
821     bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
822     ASSERT_TRUE(ssl_ctx);
823     bssl::UniquePtr<SSL_SESSION> session(
824         SSL_SESSION_from_bytes(input.data(), input.size(), ssl_ctx.get()));
825     ASSERT_TRUE(session) << "SSL_SESSION_from_bytes failed";
826 
827     // Verify the SSL_SESSION encoding round-trips.
828     size_t encoded_len;
829     bssl::UniquePtr<uint8_t> encoded;
830     uint8_t *encoded_raw;
831     ASSERT_TRUE(SSL_SESSION_to_bytes(session.get(), &encoded_raw, &encoded_len))
832         << "SSL_SESSION_to_bytes failed";
833     encoded.reset(encoded_raw);
834     EXPECT_EQ(Bytes(encoded.get(), encoded_len), Bytes(input))
835         << "SSL_SESSION_to_bytes did not round-trip";
836 
837     // Verify the SSL_SESSION also decodes with the legacy API.
838     const uint8_t *cptr = input.data();
839     session.reset(d2i_SSL_SESSION(NULL, &cptr, input.size()));
840     ASSERT_TRUE(session) << "d2i_SSL_SESSION failed";
841     EXPECT_EQ(cptr, input.data() + input.size());
842 
843     // Verify the SSL_SESSION encoding round-trips via the legacy API.
844     int len = i2d_SSL_SESSION(session.get(), NULL);
845     ASSERT_GT(len, 0) << "i2d_SSL_SESSION failed";
846     ASSERT_EQ(static_cast<size_t>(len), input.size())
847         << "i2d_SSL_SESSION(NULL) returned invalid length";
848 
849     encoded.reset((uint8_t *)OPENSSL_malloc(input.size()));
850     ASSERT_TRUE(encoded);
851 
852     uint8_t *ptr = encoded.get();
853     len = i2d_SSL_SESSION(session.get(), &ptr);
854     ASSERT_GT(len, 0) << "i2d_SSL_SESSION failed";
855     ASSERT_EQ(static_cast<size_t>(len), input.size())
856         << "i2d_SSL_SESSION(NULL) returned invalid length";
857     ASSERT_EQ(ptr, encoded.get() + input.size())
858         << "i2d_SSL_SESSION did not advance ptr correctly";
859     EXPECT_EQ(Bytes(encoded.get(), encoded_len), Bytes(input))
860         << "SSL_SESSION_to_bytes did not round-trip";
861   }
862 
863   for (const char *input_b64 : {
864            kBadSessionExtraField,
865            kBadSessionVersion,
866            kBadSessionTrailingData,
867        }) {
868     SCOPED_TRACE(std::string(input_b64));
869     std::vector<uint8_t> input;
870     ASSERT_TRUE(DecodeBase64(&input, input_b64));
871 
872     // Verify that the SSL_SESSION fails to decode.
873     bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
874     ASSERT_TRUE(ssl_ctx);
875     bssl::UniquePtr<SSL_SESSION> session(
876         SSL_SESSION_from_bytes(input.data(), input.size(), ssl_ctx.get()));
877     EXPECT_FALSE(session) << "SSL_SESSION_from_bytes unexpectedly succeeded";
878     ERR_clear_error();
879   }
880 }
881 
ExpectDefaultVersion(uint16_t min_version,uint16_t max_version,const SSL_METHOD * (* method)(void))882 static void ExpectDefaultVersion(uint16_t min_version, uint16_t max_version,
883                                  const SSL_METHOD *(*method)(void)) {
884   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(method()));
885   ASSERT_TRUE(ctx);
886   EXPECT_EQ(min_version, SSL_CTX_get_min_proto_version(ctx.get()));
887   EXPECT_EQ(max_version, SSL_CTX_get_max_proto_version(ctx.get()));
888 }
889 
TEST(SSLTest,DefaultVersion)890 TEST(SSLTest, DefaultVersion) {
891   ExpectDefaultVersion(TLS1_VERSION, TLS1_3_VERSION, &TLS_method);
892   ExpectDefaultVersion(TLS1_VERSION, TLS1_VERSION, &TLSv1_method);
893   ExpectDefaultVersion(TLS1_1_VERSION, TLS1_1_VERSION, &TLSv1_1_method);
894   ExpectDefaultVersion(TLS1_2_VERSION, TLS1_2_VERSION, &TLSv1_2_method);
895   ExpectDefaultVersion(DTLS1_VERSION, DTLS1_2_VERSION, &DTLS_method);
896   ExpectDefaultVersion(DTLS1_VERSION, DTLS1_VERSION, &DTLSv1_method);
897   ExpectDefaultVersion(DTLS1_2_VERSION, DTLS1_2_VERSION, &DTLSv1_2_method);
898 }
899 
TEST(SSLTest,CipherProperties)900 TEST(SSLTest, CipherProperties) {
901   static const struct {
902     int id;
903     const char *standard_name;
904     int cipher_nid;
905     int digest_nid;
906     int kx_nid;
907     int auth_nid;
908     int prf_nid;
909   } kTests[] = {
910       {
911           SSL3_CK_RSA_DES_192_CBC3_SHA,
912           "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
913           NID_des_ede3_cbc,
914           NID_sha1,
915           NID_kx_rsa,
916           NID_auth_rsa,
917           NID_md5_sha1,
918       },
919       {
920           TLS1_CK_RSA_WITH_AES_128_SHA,
921           "TLS_RSA_WITH_AES_128_CBC_SHA",
922           NID_aes_128_cbc,
923           NID_sha1,
924           NID_kx_rsa,
925           NID_auth_rsa,
926           NID_md5_sha1,
927       },
928       {
929           TLS1_CK_PSK_WITH_AES_256_CBC_SHA,
930           "TLS_PSK_WITH_AES_256_CBC_SHA",
931           NID_aes_256_cbc,
932           NID_sha1,
933           NID_kx_psk,
934           NID_auth_psk,
935           NID_md5_sha1,
936       },
937       {
938           TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA,
939           "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
940           NID_aes_128_cbc,
941           NID_sha1,
942           NID_kx_ecdhe,
943           NID_auth_rsa,
944           NID_md5_sha1,
945       },
946       {
947           TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA,
948           "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
949           NID_aes_256_cbc,
950           NID_sha1,
951           NID_kx_ecdhe,
952           NID_auth_rsa,
953           NID_md5_sha1,
954       },
955       {
956           TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
957           "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
958           NID_aes_128_gcm,
959           NID_undef,
960           NID_kx_ecdhe,
961           NID_auth_rsa,
962           NID_sha256,
963       },
964       {
965           TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
966           "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
967           NID_aes_128_gcm,
968           NID_undef,
969           NID_kx_ecdhe,
970           NID_auth_ecdsa,
971           NID_sha256,
972       },
973       {
974           TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
975           "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
976           NID_aes_256_gcm,
977           NID_undef,
978           NID_kx_ecdhe,
979           NID_auth_ecdsa,
980           NID_sha384,
981       },
982       {
983           TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA,
984           "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
985           NID_aes_128_cbc,
986           NID_sha1,
987           NID_kx_ecdhe,
988           NID_auth_psk,
989           NID_md5_sha1,
990       },
991       {
992           TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
993           "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
994           NID_chacha20_poly1305,
995           NID_undef,
996           NID_kx_ecdhe,
997           NID_auth_rsa,
998           NID_sha256,
999       },
1000       {
1001           TLS1_CK_AES_256_GCM_SHA384,
1002           "TLS_AES_256_GCM_SHA384",
1003           NID_aes_256_gcm,
1004           NID_undef,
1005           NID_kx_any,
1006           NID_auth_any,
1007           NID_sha384,
1008       },
1009       {
1010           TLS1_CK_AES_128_GCM_SHA256,
1011           "TLS_AES_128_GCM_SHA256",
1012           NID_aes_128_gcm,
1013           NID_undef,
1014           NID_kx_any,
1015           NID_auth_any,
1016           NID_sha256,
1017       },
1018       {
1019           TLS1_CK_CHACHA20_POLY1305_SHA256,
1020           "TLS_CHACHA20_POLY1305_SHA256",
1021           NID_chacha20_poly1305,
1022           NID_undef,
1023           NID_kx_any,
1024           NID_auth_any,
1025           NID_sha256,
1026       },
1027   };
1028 
1029   for (const auto &t : kTests) {
1030     SCOPED_TRACE(t.standard_name);
1031 
1032     const SSL_CIPHER *cipher = SSL_get_cipher_by_value(t.id & 0xffff);
1033     ASSERT_TRUE(cipher);
1034     EXPECT_STREQ(t.standard_name, SSL_CIPHER_standard_name(cipher));
1035 
1036     bssl::UniquePtr<char> rfc_name(SSL_CIPHER_get_rfc_name(cipher));
1037     ASSERT_TRUE(rfc_name);
1038     EXPECT_STREQ(t.standard_name, rfc_name.get());
1039 
1040     EXPECT_EQ(t.cipher_nid, SSL_CIPHER_get_cipher_nid(cipher));
1041     EXPECT_EQ(t.digest_nid, SSL_CIPHER_get_digest_nid(cipher));
1042     EXPECT_EQ(t.kx_nid, SSL_CIPHER_get_kx_nid(cipher));
1043     EXPECT_EQ(t.auth_nid, SSL_CIPHER_get_auth_nid(cipher));
1044     EXPECT_EQ(t.prf_nid, SSL_CIPHER_get_prf_nid(cipher));
1045   }
1046 }
1047 
1048 // CreateSessionWithTicket returns a sample |SSL_SESSION| with the specified
1049 // version and ticket length or nullptr on failure.
CreateSessionWithTicket(uint16_t version,size_t ticket_len)1050 static bssl::UniquePtr<SSL_SESSION> CreateSessionWithTicket(uint16_t version,
1051                                                             size_t ticket_len) {
1052   std::vector<uint8_t> der;
1053   if (!DecodeBase64(&der, kOpenSSLSession)) {
1054     return nullptr;
1055   }
1056 
1057   bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
1058   if (!ssl_ctx) {
1059     return nullptr;
1060   }
1061   // Use a garbage ticket.
1062   std::vector<uint8_t> ticket(ticket_len, 'a');
1063   bssl::UniquePtr<SSL_SESSION> session(
1064       SSL_SESSION_from_bytes(der.data(), der.size(), ssl_ctx.get()));
1065   if (!session ||
1066       !SSL_SESSION_set_protocol_version(session.get(), version) ||
1067       !SSL_SESSION_set_ticket(session.get(), ticket.data(), ticket.size())) {
1068     return nullptr;
1069   }
1070   // Fix up the timeout.
1071 #if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
1072   SSL_SESSION_set_time(session.get(), 1234);
1073 #else
1074   SSL_SESSION_set_time(session.get(), time(nullptr));
1075 #endif
1076   return session;
1077 }
1078 
GetClientHello(SSL * ssl,std::vector<uint8_t> * out)1079 static bool GetClientHello(SSL *ssl, std::vector<uint8_t> *out) {
1080   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
1081   if (!bio) {
1082     return false;
1083   }
1084   // Do not configure a reading BIO, but record what's written to a memory BIO.
1085   BIO_up_ref(bio.get());
1086   SSL_set_bio(ssl, nullptr /* rbio */, bio.get());
1087   int ret = SSL_connect(ssl);
1088   if (ret > 0) {
1089     // SSL_connect should fail without a BIO to write to.
1090     return false;
1091   }
1092   ERR_clear_error();
1093 
1094   const uint8_t *client_hello;
1095   size_t client_hello_len;
1096   if (!BIO_mem_contents(bio.get(), &client_hello, &client_hello_len)) {
1097     return false;
1098   }
1099   *out = std::vector<uint8_t>(client_hello, client_hello + client_hello_len);
1100   return true;
1101 }
1102 
1103 // GetClientHelloLen creates a client SSL connection with the specified version
1104 // and ticket length. It returns the length of the ClientHello, not including
1105 // the record header, on success and zero on error.
GetClientHelloLen(uint16_t max_version,uint16_t session_version,size_t ticket_len)1106 static size_t GetClientHelloLen(uint16_t max_version, uint16_t session_version,
1107                                 size_t ticket_len) {
1108   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1109   bssl::UniquePtr<SSL_SESSION> session =
1110       CreateSessionWithTicket(session_version, ticket_len);
1111   if (!ctx || !session) {
1112     return 0;
1113   }
1114 
1115   // Set a one-element cipher list so the baseline ClientHello is unpadded.
1116   bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1117   if (!ssl || !SSL_set_session(ssl.get(), session.get()) ||
1118       !SSL_set_strict_cipher_list(ssl.get(), "ECDHE-RSA-AES128-GCM-SHA256") ||
1119       !SSL_set_max_proto_version(ssl.get(), max_version)) {
1120     return 0;
1121   }
1122 
1123   std::vector<uint8_t> client_hello;
1124   if (!GetClientHello(ssl.get(), &client_hello) ||
1125       client_hello.size() <= SSL3_RT_HEADER_LENGTH) {
1126     return 0;
1127   }
1128 
1129   return client_hello.size() - SSL3_RT_HEADER_LENGTH;
1130 }
1131 
TEST(SSLTest,Padding)1132 TEST(SSLTest, Padding) {
1133   struct PaddingVersions {
1134     uint16_t max_version, session_version;
1135   };
1136   static const PaddingVersions kPaddingVersions[] = {
1137       // Test the padding extension at TLS 1.2.
1138       {TLS1_2_VERSION, TLS1_2_VERSION},
1139       // Test the padding extension at TLS 1.3 with a TLS 1.2 session, so there
1140       // will be no PSK binder after the padding extension.
1141       {TLS1_3_VERSION, TLS1_2_VERSION},
1142       // Test the padding extension at TLS 1.3 with a TLS 1.3 session, so there
1143       // will be a PSK binder after the padding extension.
1144       {TLS1_3_VERSION, TLS1_3_VERSION},
1145 
1146   };
1147 
1148   struct PaddingTest {
1149     size_t input_len, padded_len;
1150   };
1151   static const PaddingTest kPaddingTests[] = {
1152       // ClientHellos of length below 0x100 do not require padding.
1153       {0xfe, 0xfe},
1154       {0xff, 0xff},
1155       // ClientHellos of length 0x100 through 0x1fb are padded up to 0x200.
1156       {0x100, 0x200},
1157       {0x123, 0x200},
1158       {0x1fb, 0x200},
1159       // ClientHellos of length 0x1fc through 0x1ff get padded beyond 0x200. The
1160       // padding extension takes a minimum of four bytes plus one required
1161       // content
1162       // byte. (To work around yet more server bugs, we avoid empty final
1163       // extensions.)
1164       {0x1fc, 0x201},
1165       {0x1fd, 0x202},
1166       {0x1fe, 0x203},
1167       {0x1ff, 0x204},
1168       // Finally, larger ClientHellos need no padding.
1169       {0x200, 0x200},
1170       {0x201, 0x201},
1171   };
1172 
1173   for (const PaddingVersions &versions : kPaddingVersions) {
1174     SCOPED_TRACE(versions.max_version);
1175     SCOPED_TRACE(versions.session_version);
1176 
1177     // Sample a baseline length.
1178     size_t base_len =
1179         GetClientHelloLen(versions.max_version, versions.session_version, 1);
1180     ASSERT_NE(base_len, 0u) << "Baseline length could not be sampled";
1181 
1182     for (const PaddingTest &test : kPaddingTests) {
1183       SCOPED_TRACE(test.input_len);
1184       ASSERT_LE(base_len, test.input_len) << "Baseline ClientHello too long";
1185 
1186       size_t padded_len =
1187           GetClientHelloLen(versions.max_version, versions.session_version,
1188                             1 + test.input_len - base_len);
1189       EXPECT_EQ(padded_len, test.padded_len)
1190           << "ClientHello was not padded to expected length";
1191     }
1192   }
1193 }
1194 
GetTestCertificate()1195 static bssl::UniquePtr<X509> GetTestCertificate() {
1196   static const char kCertPEM[] =
1197       "-----BEGIN CERTIFICATE-----\n"
1198       "MIICWDCCAcGgAwIBAgIJAPuwTC6rEJsMMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV\n"
1199       "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n"
1200       "aWRnaXRzIFB0eSBMdGQwHhcNMTQwNDIzMjA1MDQwWhcNMTcwNDIyMjA1MDQwWjBF\n"
1201       "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n"
1202       "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n"
1203       "gQDYK8imMuRi/03z0K1Zi0WnvfFHvwlYeyK9Na6XJYaUoIDAtB92kWdGMdAQhLci\n"
1204       "HnAjkXLI6W15OoV3gA/ElRZ1xUpxTMhjP6PyY5wqT5r6y8FxbiiFKKAnHmUcrgfV\n"
1205       "W28tQ+0rkLGMryRtrukXOgXBv7gcrmU7G1jC2a7WqmeI8QIDAQABo1AwTjAdBgNV\n"
1206       "HQ4EFgQUi3XVrMsIvg4fZbf6Vr5sp3Xaha8wHwYDVR0jBBgwFoAUi3XVrMsIvg4f\n"
1207       "Zbf6Vr5sp3Xaha8wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQA76Hht\n"
1208       "ldY9avcTGSwbwoiuIqv0jTL1fHFnzy3RHMLDh+Lpvolc5DSrSJHCP5WuK0eeJXhr\n"
1209       "T5oQpHL9z/cCDLAKCKRa4uV0fhEdOWBqyR9p8y5jJtye72t6CuFUV5iqcpF4BH4f\n"
1210       "j2VNHwsSrJwkD4QUGlUtH7vwnQmyCFxZMmWAJg==\n"
1211       "-----END CERTIFICATE-----\n";
1212   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kCertPEM, strlen(kCertPEM)));
1213   return bssl::UniquePtr<X509>(
1214       PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
1215 }
1216 
GetTestKey()1217 static bssl::UniquePtr<EVP_PKEY> GetTestKey() {
1218   static const char kKeyPEM[] =
1219       "-----BEGIN RSA PRIVATE KEY-----\n"
1220       "MIICXgIBAAKBgQDYK8imMuRi/03z0K1Zi0WnvfFHvwlYeyK9Na6XJYaUoIDAtB92\n"
1221       "kWdGMdAQhLciHnAjkXLI6W15OoV3gA/ElRZ1xUpxTMhjP6PyY5wqT5r6y8FxbiiF\n"
1222       "KKAnHmUcrgfVW28tQ+0rkLGMryRtrukXOgXBv7gcrmU7G1jC2a7WqmeI8QIDAQAB\n"
1223       "AoGBAIBy09Fd4DOq/Ijp8HeKuCMKTHqTW1xGHshLQ6jwVV2vWZIn9aIgmDsvkjCe\n"
1224       "i6ssZvnbjVcwzSoByhjN8ZCf/i15HECWDFFh6gt0P5z0MnChwzZmvatV/FXCT0j+\n"
1225       "WmGNB/gkehKjGXLLcjTb6dRYVJSCZhVuOLLcbWIV10gggJQBAkEA8S8sGe4ezyyZ\n"
1226       "m4e9r95g6s43kPqtj5rewTsUxt+2n4eVodD+ZUlCULWVNAFLkYRTBCASlSrm9Xhj\n"
1227       "QpmWAHJUkQJBAOVzQdFUaewLtdOJoPCtpYoY1zd22eae8TQEmpGOR11L6kbxLQsk\n"
1228       "aMly/DOnOaa82tqAGTdqDEZgSNmCeKKknmECQAvpnY8GUOVAubGR6c+W90iBuQLj\n"
1229       "LtFp/9ihd2w/PoDwrHZaoUYVcT4VSfJQog/k7kjE4MYXYWL8eEKg3WTWQNECQQDk\n"
1230       "104Wi91Umd1PzF0ijd2jXOERJU1wEKe6XLkYYNHWQAe5l4J4MWj9OdxFXAxIuuR/\n"
1231       "tfDwbqkta4xcux67//khAkEAvvRXLHTaa6VFzTaiiO8SaFsHV3lQyXOtMrBpB5jd\n"
1232       "moZWgjHvB2W9Ckn7sDqsPB+U2tyX0joDdQEyuiMECDY8oQ==\n"
1233       "-----END RSA PRIVATE KEY-----\n";
1234   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kKeyPEM, strlen(kKeyPEM)));
1235   return bssl::UniquePtr<EVP_PKEY>(
1236       PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
1237 }
1238 
GetECDSATestCertificate()1239 static bssl::UniquePtr<X509> GetECDSATestCertificate() {
1240   static const char kCertPEM[] =
1241       "-----BEGIN CERTIFICATE-----\n"
1242       "MIIBzzCCAXagAwIBAgIJANlMBNpJfb/rMAkGByqGSM49BAEwRTELMAkGA1UEBhMC\n"
1243       "QVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdp\n"
1244       "dHMgUHR5IEx0ZDAeFw0xNDA0MjMyMzIxNTdaFw0xNDA1MjMyMzIxNTdaMEUxCzAJ\n"
1245       "BgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5l\n"
1246       "dCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATmK2ni\n"
1247       "v2Wfl74vHg2UikzVl2u3qR4NRvvdqakendy6WgHn1peoChj5w8SjHlbifINI2xYa\n"
1248       "HPUdfvGULUvPciLBo1AwTjAdBgNVHQ4EFgQUq4TSrKuV8IJOFngHVVdf5CaNgtEw\n"
1249       "HwYDVR0jBBgwFoAUq4TSrKuV8IJOFngHVVdf5CaNgtEwDAYDVR0TBAUwAwEB/zAJ\n"
1250       "BgcqhkjOPQQBA0gAMEUCIQDyoDVeUTo2w4J5m+4nUIWOcAZ0lVfSKXQA9L4Vh13E\n"
1251       "BwIgfB55FGohg/B6dGh5XxSZmmi08cueFV7mHzJSYV51yRQ=\n"
1252       "-----END CERTIFICATE-----\n";
1253   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kCertPEM, strlen(kCertPEM)));
1254   return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
1255 }
1256 
GetECDSATestKey()1257 static bssl::UniquePtr<EVP_PKEY> GetECDSATestKey() {
1258   static const char kKeyPEM[] =
1259       "-----BEGIN PRIVATE KEY-----\n"
1260       "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgBw8IcnrUoEqc3VnJ\n"
1261       "TYlodwi1b8ldMHcO6NHJzgqLtGqhRANCAATmK2niv2Wfl74vHg2UikzVl2u3qR4N\n"
1262       "Rvvdqakendy6WgHn1peoChj5w8SjHlbifINI2xYaHPUdfvGULUvPciLB\n"
1263       "-----END PRIVATE KEY-----\n";
1264   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kKeyPEM, strlen(kKeyPEM)));
1265   return bssl::UniquePtr<EVP_PKEY>(
1266       PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
1267 }
1268 
BufferFromPEM(const char * pem)1269 static bssl::UniquePtr<CRYPTO_BUFFER> BufferFromPEM(const char *pem) {
1270   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(pem, strlen(pem)));
1271   char *name, *header;
1272   uint8_t *data;
1273   long data_len;
1274   if (!PEM_read_bio(bio.get(), &name, &header, &data,
1275                     &data_len)) {
1276     return nullptr;
1277   }
1278   OPENSSL_free(name);
1279   OPENSSL_free(header);
1280 
1281   auto ret = bssl::UniquePtr<CRYPTO_BUFFER>(
1282       CRYPTO_BUFFER_new(data, data_len, nullptr));
1283   OPENSSL_free(data);
1284   return ret;
1285 }
1286 
GetChainTestCertificateBuffer()1287 static bssl::UniquePtr<CRYPTO_BUFFER> GetChainTestCertificateBuffer() {
1288   static const char kCertPEM[] =
1289       "-----BEGIN CERTIFICATE-----\n"
1290       "MIIC0jCCAbqgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwDzENMAsGA1UEAwwEQiBD\n"
1291       "QTAeFw0xNjAyMjgyMDI3MDNaFw0yNjAyMjUyMDI3MDNaMBgxFjAUBgNVBAMMDUNs\n"
1292       "aWVudCBDZXJ0IEEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDRvaz8\n"
1293       "CC/cshpCafJo4jLkHEoBqDLhdgFelJoAiQUyIqyWl2O7YHPnpJH+TgR7oelzNzt/\n"
1294       "kLRcH89M/TszB6zqyLTC4aqmvzKL0peD/jL2LWBucR0WXIvjA3zoRuF/x86+rYH3\n"
1295       "tHb+xs2PSs8EGL/Ev+ss+qTzTGEn26fuGNHkNw6tOwPpc+o8+wUtzf/kAthamo+c\n"
1296       "IDs2rQ+lP7+aLZTLeU/q4gcLutlzcK5imex5xy2jPkweq48kijK0kIzl1cPlA5d1\n"
1297       "z7C8jU50Pj9X9sQDJTN32j7UYRisJeeYQF8GaaN8SbrDI6zHgKzrRLyxDt/KQa9V\n"
1298       "iLeXANgZi+Xx9KgfAgMBAAGjLzAtMAwGA1UdEwEB/wQCMAAwHQYDVR0lBBYwFAYI\n"
1299       "KwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IBAQBFEVbmYl+2RtNw\n"
1300       "rDftRDF1v2QUbcN2ouSnQDHxeDQdSgasLzT3ui8iYu0Rw2WWcZ0DV5e0ztGPhWq7\n"
1301       "AO0B120aFRMOY+4+bzu9Q2FFkQqc7/fKTvTDzIJI5wrMnFvUfzzvxh3OHWMYSs/w\n"
1302       "giq33hTKeHEq6Jyk3btCny0Ycecyc3yGXH10sizUfiHlhviCkDuESk8mFDwDDzqW\n"
1303       "ZF0IipzFbEDHoIxLlm3GQxpiLoEV4k8KYJp3R5KBLFyxM6UGPz8h72mIPCJp2RuK\n"
1304       "MYgF91UDvVzvnYm6TfseM2+ewKirC00GOrZ7rEcFvtxnKSqYf4ckqfNdSU1Y+RRC\n"
1305       "1ngWZ7Ih\n"
1306       "-----END CERTIFICATE-----\n";
1307   return BufferFromPEM(kCertPEM);
1308 }
1309 
X509FromBuffer(bssl::UniquePtr<CRYPTO_BUFFER> buffer)1310 static bssl::UniquePtr<X509> X509FromBuffer(
1311     bssl::UniquePtr<CRYPTO_BUFFER> buffer) {
1312   if (!buffer) {
1313     return nullptr;
1314   }
1315   const uint8_t *derp = CRYPTO_BUFFER_data(buffer.get());
1316   return bssl::UniquePtr<X509>(
1317       d2i_X509(NULL, &derp, CRYPTO_BUFFER_len(buffer.get())));
1318 }
1319 
GetChainTestCertificate()1320 static bssl::UniquePtr<X509> GetChainTestCertificate() {
1321   return X509FromBuffer(GetChainTestCertificateBuffer());
1322 }
1323 
GetChainTestIntermediateBuffer()1324 static bssl::UniquePtr<CRYPTO_BUFFER> GetChainTestIntermediateBuffer() {
1325   static const char kCertPEM[] =
1326       "-----BEGIN CERTIFICATE-----\n"
1327       "MIICwjCCAaqgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwFDESMBAGA1UEAwwJQyBS\n"
1328       "b290IENBMB4XDTE2MDIyODIwMjcwM1oXDTI2MDIyNTIwMjcwM1owDzENMAsGA1UE\n"
1329       "AwwEQiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALsSCYmDip2D\n"
1330       "GkjFxw7ykz26JSjELkl6ArlYjFJ3aT/SCh8qbS4gln7RH8CPBd78oFdfhIKQrwtZ\n"
1331       "3/q21ykD9BAS3qHe2YdcJfm8/kWAy5DvXk6NXU4qX334KofBAEpgdA/igEFq1P1l\n"
1332       "HAuIfZCpMRfT+i5WohVsGi8f/NgpRvVaMONLNfgw57mz1lbtFeBEISmX0kbsuJxF\n"
1333       "Qj/Bwhi5/0HAEXG8e7zN4cEx0yPRvmOATRdVb/8dW2pwOHRJq9R5M0NUkIsTSnL7\n"
1334       "6N/z8hRAHMsV3IudC5Yd7GXW1AGu9a+iKU+Q4xcZCoj0DC99tL4VKujrV1kAeqsM\n"
1335       "cz5/dKzi6+cCAwEAAaMjMCEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n"
1336       "AQYwDQYJKoZIhvcNAQELBQADggEBAIIeZiEeNhWWQ8Y4D+AGDwqUUeG8NjCbKrXQ\n"
1337       "BlHg5wZ8xftFaiP1Dp/UAezmx2LNazdmuwrYB8lm3FVTyaPDTKEGIPS4wJKHgqH1\n"
1338       "QPDhqNm85ey7TEtI9oYjsNim/Rb+iGkIAMXaxt58SzxbjvP0kMr1JfJIZbic9vye\n"
1339       "NwIspMFIpP3FB8ywyu0T0hWtCQgL4J47nigCHpOu58deP88fS/Nyz/fyGVWOZ76b\n"
1340       "WhWwgM3P3X95fQ3d7oFPR/bVh0YV+Cf861INwplokXgXQ3/TCQ+HNXeAMWn3JLWv\n"
1341       "XFwk8owk9dq/kQGdndGgy3KTEW4ctPX5GNhf3LJ9Q7dLji4ReQ4=\n"
1342       "-----END CERTIFICATE-----\n";
1343   return BufferFromPEM(kCertPEM);
1344 }
1345 
GetChainTestIntermediate()1346 static bssl::UniquePtr<X509> GetChainTestIntermediate() {
1347   return X509FromBuffer(GetChainTestIntermediateBuffer());
1348 }
1349 
GetChainTestKey()1350 static bssl::UniquePtr<EVP_PKEY> GetChainTestKey() {
1351   static const char kKeyPEM[] =
1352       "-----BEGIN PRIVATE KEY-----\n"
1353       "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDRvaz8CC/cshpC\n"
1354       "afJo4jLkHEoBqDLhdgFelJoAiQUyIqyWl2O7YHPnpJH+TgR7oelzNzt/kLRcH89M\n"
1355       "/TszB6zqyLTC4aqmvzKL0peD/jL2LWBucR0WXIvjA3zoRuF/x86+rYH3tHb+xs2P\n"
1356       "Ss8EGL/Ev+ss+qTzTGEn26fuGNHkNw6tOwPpc+o8+wUtzf/kAthamo+cIDs2rQ+l\n"
1357       "P7+aLZTLeU/q4gcLutlzcK5imex5xy2jPkweq48kijK0kIzl1cPlA5d1z7C8jU50\n"
1358       "Pj9X9sQDJTN32j7UYRisJeeYQF8GaaN8SbrDI6zHgKzrRLyxDt/KQa9ViLeXANgZ\n"
1359       "i+Xx9KgfAgMBAAECggEBAK0VjSJzkyPaamcyTVSWjo7GdaBGcK60lk657RjR+lK0\n"
1360       "YJ7pkej4oM2hdsVZFsP8Cs4E33nXLa/0pDsRov/qrp0WQm2skwqGMC1I/bZ0WRPk\n"
1361       "wHaDrBBfESWnJDX/AGpVtlyOjPmgmK6J2usMPihQUDkKdAYrVWJePrMIxt1q6BMe\n"
1362       "iczs3qriMmtY3bUc4UyUwJ5fhDLjshHvfuIpYQyI6EXZM6dZksn9LylXJnigY6QJ\n"
1363       "HxOYO0BDwOsZ8yQ8J8afLk88i0GizEkgE1z3REtQUwgWfxr1WV/ud+T6/ZhSAgH9\n"
1364       "042mQvSFZnIUSEsmCvjhWuAunfxHKCTcAoYISWfzWpkCgYEA7gpf3HHU5Tn+CgUn\n"
1365       "1X5uGpG3DmcMgfeGgs2r2f/IIg/5Ac1dfYILiybL1tN9zbyLCJfcbFpWBc9hJL6f\n"
1366       "CPc5hUiwWFJqBJewxQkC1Ae/HakHbip+IZ+Jr0842O4BAArvixk4Lb7/N2Ct9sTE\n"
1367       "NJO6RtK9lbEZ5uK61DglHy8CS2UCgYEA4ZC1o36kPAMQBggajgnucb2yuUEelk0f\n"
1368       "AEr+GI32MGE+93xMr7rAhBoqLg4AITyIfEnOSQ5HwagnIHonBbv1LV/Gf9ursx8Z\n"
1369       "YOGbvT8zzzC+SU1bkDzdjAYnFQVGIjMtKOBJ3K07++ypwX1fr4QsQ8uKL8WSOWwt\n"
1370       "Z3Bym6XiZzMCgYADnhy+2OwHX85AkLt+PyGlPbmuelpyTzS4IDAQbBa6jcuW/2wA\n"
1371       "UE2km75VUXmD+u2R/9zVuLm99NzhFhSMqlUxdV1YukfqMfP5yp1EY6m/5aW7QuIP\n"
1372       "2MDa7TVL9rIFMiVZ09RKvbBbQxjhuzPQKL6X/PPspnhiTefQ+dl2k9xREQKBgHDS\n"
1373       "fMfGNEeAEKezrfSVqxphE9/tXms3L+ZpnCaT+yu/uEr5dTIAawKoQ6i9f/sf1/Sy\n"
1374       "xedsqR+IB+oKrzIDDWMgoJybN4pkZ8E5lzhVQIjFjKgFdWLzzqyW9z1gYfABQPlN\n"
1375       "FiS20WX0vgP1vcKAjdNrHzc9zyHBpgQzDmAj3NZZAoGBAI8vKCKdH7w3aL5CNkZQ\n"
1376       "2buIeWNA2HZazVwAGG5F2TU/LmXfRKnG6dX5bkU+AkBZh56jNZy//hfFSewJB4Kk\n"
1377       "buB7ERSdaNbO21zXt9FEA3+z0RfMd/Zv2vlIWOSB5nzl/7UKti3sribK6s9ZVLfi\n"
1378       "SxpiPQ8d/hmSGwn4ksrWUsJD\n"
1379       "-----END PRIVATE KEY-----\n";
1380   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kKeyPEM, strlen(kKeyPEM)));
1381   return bssl::UniquePtr<EVP_PKEY>(
1382       PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
1383 }
1384 
1385 // Test that |SSL_get_client_CA_list| echoes back the configured parameter even
1386 // before configuring as a server.
TEST(SSLTest,ClientCAList)1387 TEST(SSLTest, ClientCAList) {
1388   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1389   ASSERT_TRUE(ctx);
1390   bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1391   ASSERT_TRUE(ssl);
1392 
1393   bssl::UniquePtr<X509_NAME> name(X509_NAME_new());
1394   ASSERT_TRUE(name);
1395 
1396   bssl::UniquePtr<X509_NAME> name_dup(X509_NAME_dup(name.get()));
1397   ASSERT_TRUE(name_dup);
1398 
1399   bssl::UniquePtr<STACK_OF(X509_NAME)> stack(sk_X509_NAME_new_null());
1400   ASSERT_TRUE(stack);
1401   ASSERT_TRUE(PushToStack(stack.get(), std::move(name_dup)));
1402 
1403   // |SSL_set_client_CA_list| takes ownership.
1404   SSL_set_client_CA_list(ssl.get(), stack.release());
1405 
1406   STACK_OF(X509_NAME) *result = SSL_get_client_CA_list(ssl.get());
1407   ASSERT_TRUE(result);
1408   ASSERT_EQ(1u, sk_X509_NAME_num(result));
1409   EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(result, 0), name.get()));
1410 }
1411 
TEST(SSLTest,AddClientCA)1412 TEST(SSLTest, AddClientCA) {
1413   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1414   ASSERT_TRUE(ctx);
1415   bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1416   ASSERT_TRUE(ssl);
1417 
1418   bssl::UniquePtr<X509> cert1 = GetTestCertificate();
1419   bssl::UniquePtr<X509> cert2 = GetChainTestCertificate();
1420   ASSERT_TRUE(cert1 && cert2);
1421   X509_NAME *name1 = X509_get_subject_name(cert1.get());
1422   X509_NAME *name2 = X509_get_subject_name(cert2.get());
1423 
1424   EXPECT_EQ(0u, sk_X509_NAME_num(SSL_get_client_CA_list(ssl.get())));
1425 
1426   ASSERT_TRUE(SSL_add_client_CA(ssl.get(), cert1.get()));
1427   ASSERT_TRUE(SSL_add_client_CA(ssl.get(), cert2.get()));
1428 
1429   STACK_OF(X509_NAME) *list = SSL_get_client_CA_list(ssl.get());
1430   ASSERT_EQ(2u, sk_X509_NAME_num(list));
1431   EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 0), name1));
1432   EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 1), name2));
1433 
1434   ASSERT_TRUE(SSL_add_client_CA(ssl.get(), cert1.get()));
1435 
1436   list = SSL_get_client_CA_list(ssl.get());
1437   ASSERT_EQ(3u, sk_X509_NAME_num(list));
1438   EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 0), name1));
1439   EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 1), name2));
1440   EXPECT_EQ(0, X509_NAME_cmp(sk_X509_NAME_value(list, 2), name1));
1441 }
1442 
AppendSession(SSL_SESSION * session,void * arg)1443 static void AppendSession(SSL_SESSION *session, void *arg) {
1444   std::vector<SSL_SESSION*> *out =
1445       reinterpret_cast<std::vector<SSL_SESSION*>*>(arg);
1446   out->push_back(session);
1447 }
1448 
1449 // CacheEquals returns true if |ctx|'s session cache consists of |expected|, in
1450 // order.
CacheEquals(SSL_CTX * ctx,const std::vector<SSL_SESSION * > & expected)1451 static bool CacheEquals(SSL_CTX *ctx,
1452                         const std::vector<SSL_SESSION*> &expected) {
1453   // Check the linked list.
1454   SSL_SESSION *ptr = ctx->session_cache_head;
1455   for (SSL_SESSION *session : expected) {
1456     if (ptr != session) {
1457       return false;
1458     }
1459     // TODO(davidben): This is an absurd way to denote the end of the list.
1460     if (ptr->next ==
1461         reinterpret_cast<SSL_SESSION *>(&ctx->session_cache_tail)) {
1462       ptr = nullptr;
1463     } else {
1464       ptr = ptr->next;
1465     }
1466   }
1467   if (ptr != nullptr) {
1468     return false;
1469   }
1470 
1471   // Check the hash table.
1472   std::vector<SSL_SESSION*> actual, expected_copy;
1473   lh_SSL_SESSION_doall_arg(ctx->sessions, AppendSession, &actual);
1474   expected_copy = expected;
1475 
1476   std::sort(actual.begin(), actual.end());
1477   std::sort(expected_copy.begin(), expected_copy.end());
1478 
1479   return actual == expected_copy;
1480 }
1481 
CreateTestSession(uint32_t number)1482 static bssl::UniquePtr<SSL_SESSION> CreateTestSession(uint32_t number) {
1483   bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
1484   if (!ssl_ctx) {
1485     return nullptr;
1486   }
1487   bssl::UniquePtr<SSL_SESSION> ret(SSL_SESSION_new(ssl_ctx.get()));
1488   if (!ret) {
1489     return nullptr;
1490   }
1491 
1492   uint8_t id[SSL3_SSL_SESSION_ID_LENGTH] = {0};
1493   OPENSSL_memcpy(id, &number, sizeof(number));
1494   if (!SSL_SESSION_set1_id(ret.get(), id, sizeof(id))) {
1495     return nullptr;
1496   }
1497   return ret;
1498 }
1499 
1500 // Test that the internal session cache behaves as expected.
TEST(SSLTest,InternalSessionCache)1501 TEST(SSLTest, InternalSessionCache) {
1502   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1503   ASSERT_TRUE(ctx);
1504 
1505   // Prepare 10 test sessions.
1506   std::vector<bssl::UniquePtr<SSL_SESSION>> sessions;
1507   for (int i = 0; i < 10; i++) {
1508     bssl::UniquePtr<SSL_SESSION> session = CreateTestSession(i);
1509     ASSERT_TRUE(session);
1510     sessions.push_back(std::move(session));
1511   }
1512 
1513   SSL_CTX_sess_set_cache_size(ctx.get(), 5);
1514 
1515   // Insert all the test sessions.
1516   for (const auto &session : sessions) {
1517     ASSERT_TRUE(SSL_CTX_add_session(ctx.get(), session.get()));
1518   }
1519 
1520   // Only the last five should be in the list.
1521   ASSERT_TRUE(CacheEquals(
1522       ctx.get(), {sessions[9].get(), sessions[8].get(), sessions[7].get(),
1523                   sessions[6].get(), sessions[5].get()}));
1524 
1525   // Inserting an element already in the cache should fail and leave the cache
1526   // unchanged.
1527   ASSERT_FALSE(SSL_CTX_add_session(ctx.get(), sessions[7].get()));
1528   ASSERT_TRUE(CacheEquals(
1529       ctx.get(), {sessions[9].get(), sessions[8].get(), sessions[7].get(),
1530                   sessions[6].get(), sessions[5].get()}));
1531 
1532   // Although collisions should be impossible (256-bit session IDs), the cache
1533   // must handle them gracefully.
1534   bssl::UniquePtr<SSL_SESSION> collision(CreateTestSession(7));
1535   ASSERT_TRUE(collision);
1536   ASSERT_TRUE(SSL_CTX_add_session(ctx.get(), collision.get()));
1537   ASSERT_TRUE(CacheEquals(
1538       ctx.get(), {collision.get(), sessions[9].get(), sessions[8].get(),
1539                   sessions[6].get(), sessions[5].get()}));
1540 
1541   // Removing sessions behaves correctly.
1542   ASSERT_TRUE(SSL_CTX_remove_session(ctx.get(), sessions[6].get()));
1543   ASSERT_TRUE(CacheEquals(ctx.get(), {collision.get(), sessions[9].get(),
1544                                       sessions[8].get(), sessions[5].get()}));
1545 
1546   // Removing sessions requires an exact match.
1547   ASSERT_FALSE(SSL_CTX_remove_session(ctx.get(), sessions[0].get()));
1548   ASSERT_FALSE(SSL_CTX_remove_session(ctx.get(), sessions[7].get()));
1549 
1550   // The cache remains unchanged.
1551   ASSERT_TRUE(CacheEquals(ctx.get(), {collision.get(), sessions[9].get(),
1552                                       sessions[8].get(), sessions[5].get()}));
1553 }
1554 
EpochFromSequence(uint64_t seq)1555 static uint16_t EpochFromSequence(uint64_t seq) {
1556   return static_cast<uint16_t>(seq >> 48);
1557 }
1558 
1559 static const uint8_t kTestName[] = {
1560     0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
1561     0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08,
1562     0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65,
1563     0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49,
1564     0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67,
1565     0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64,
1566 };
1567 
CompleteHandshakes(SSL * client,SSL * server)1568 static bool CompleteHandshakes(SSL *client, SSL *server) {
1569   // Drive both their handshakes to completion.
1570   for (;;) {
1571     int client_ret = SSL_do_handshake(client);
1572     int client_err = SSL_get_error(client, client_ret);
1573     if (client_err != SSL_ERROR_NONE &&
1574         client_err != SSL_ERROR_WANT_READ &&
1575         client_err != SSL_ERROR_WANT_WRITE &&
1576         client_err != SSL_ERROR_PENDING_TICKET) {
1577       fprintf(stderr, "Client error: %s\n", SSL_error_description(client_err));
1578       return false;
1579     }
1580 
1581     int server_ret = SSL_do_handshake(server);
1582     int server_err = SSL_get_error(server, server_ret);
1583     if (server_err != SSL_ERROR_NONE &&
1584         server_err != SSL_ERROR_WANT_READ &&
1585         server_err != SSL_ERROR_WANT_WRITE &&
1586         server_err != SSL_ERROR_PENDING_TICKET) {
1587       fprintf(stderr, "Server error: %s\n", SSL_error_description(server_err));
1588       return false;
1589     }
1590 
1591     if (client_ret == 1 && server_ret == 1) {
1592       break;
1593     }
1594   }
1595 
1596   return true;
1597 }
1598 
FlushNewSessionTickets(SSL * client,SSL * server)1599 static bool FlushNewSessionTickets(SSL *client, SSL *server) {
1600   // NewSessionTickets are deferred on the server to |SSL_write|, and clients do
1601   // not pick them up until |SSL_read|.
1602   for (;;) {
1603     int server_ret = SSL_write(server, nullptr, 0);
1604     int server_err = SSL_get_error(server, server_ret);
1605     // The server may either succeed (|server_ret| is zero) or block on write
1606     // (|server_ret| is -1 and |server_err| is |SSL_ERROR_WANT_WRITE|).
1607     if (server_ret > 0 ||
1608         (server_ret < 0 && server_err != SSL_ERROR_WANT_WRITE)) {
1609       fprintf(stderr, "Unexpected server result: %d %d\n", server_ret,
1610               server_err);
1611       return false;
1612     }
1613 
1614     int client_ret = SSL_read(client, nullptr, 0);
1615     int client_err = SSL_get_error(client, client_ret);
1616     // The client must always block on read.
1617     if (client_ret != -1 || client_err != SSL_ERROR_WANT_READ) {
1618       fprintf(stderr, "Unexpected client result: %d %d\n", client_ret,
1619               client_err);
1620       return false;
1621     }
1622 
1623     // The server flushed everything it had to write.
1624     if (server_ret == 0) {
1625       return true;
1626     }
1627   }
1628 }
1629 
1630 struct ClientConfig {
1631   SSL_SESSION *session = nullptr;
1632   std::string servername;
1633   bool early_data = false;
1634 };
1635 
ConnectClientAndServer(bssl::UniquePtr<SSL> * out_client,bssl::UniquePtr<SSL> * out_server,SSL_CTX * client_ctx,SSL_CTX * server_ctx,const ClientConfig & config=ClientConfig (),bool do_handshake=true,bool shed_handshake_config=true)1636 static bool ConnectClientAndServer(bssl::UniquePtr<SSL> *out_client,
1637                                    bssl::UniquePtr<SSL> *out_server,
1638                                    SSL_CTX *client_ctx, SSL_CTX *server_ctx,
1639                                    const ClientConfig &config = ClientConfig(),
1640                                    bool do_handshake = true,
1641                                    bool shed_handshake_config = true) {
1642   bssl::UniquePtr<SSL> client(SSL_new(client_ctx)), server(SSL_new(server_ctx));
1643   if (!client || !server) {
1644     return false;
1645   }
1646   if (config.early_data) {
1647     SSL_set_early_data_enabled(client.get(), 1);
1648   }
1649   SSL_set_connect_state(client.get());
1650   SSL_set_accept_state(server.get());
1651 
1652   if (config.session) {
1653     SSL_set_session(client.get(), config.session);
1654   }
1655   if (!config.servername.empty() &&
1656       !SSL_set_tlsext_host_name(client.get(), config.servername.c_str())) {
1657     return false;
1658   }
1659 
1660   BIO *bio1, *bio2;
1661   if (!BIO_new_bio_pair(&bio1, 0, &bio2, 0)) {
1662     return false;
1663   }
1664   // SSL_set_bio takes ownership.
1665   SSL_set_bio(client.get(), bio1, bio1);
1666   SSL_set_bio(server.get(), bio2, bio2);
1667 
1668   SSL_set_shed_handshake_config(client.get(), shed_handshake_config);
1669   SSL_set_shed_handshake_config(server.get(), shed_handshake_config);
1670 
1671   if (do_handshake && !CompleteHandshakes(client.get(), server.get())) {
1672     return false;
1673   }
1674 
1675   *out_client = std::move(client);
1676   *out_server = std::move(server);
1677   return true;
1678 }
1679 
1680 // SSLVersionTest executes its test cases under all available protocol versions.
1681 // Test cases call |Connect| to create a connection using context objects with
1682 // the protocol version fixed to the current version under test.
1683 class SSLVersionTest : public ::testing::TestWithParam<VersionParam> {
1684  protected:
SSLVersionTest()1685   SSLVersionTest() : cert_(GetTestCertificate()), key_(GetTestKey()) {}
1686 
SetUp()1687   void SetUp() { ResetContexts(); }
1688 
CreateContext() const1689   bssl::UniquePtr<SSL_CTX> CreateContext() const {
1690     const SSL_METHOD *method = is_dtls() ? DTLS_method() : TLS_method();
1691     bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(method));
1692     if (!ctx || !SSL_CTX_set_min_proto_version(ctx.get(), version()) ||
1693         !SSL_CTX_set_max_proto_version(ctx.get(), version())) {
1694       return nullptr;
1695     }
1696     return ctx;
1697   }
1698 
ResetContexts()1699   void ResetContexts() {
1700     ASSERT_TRUE(cert_);
1701     ASSERT_TRUE(key_);
1702     client_ctx_ = CreateContext();
1703     ASSERT_TRUE(client_ctx_);
1704     server_ctx_ = CreateContext();
1705     ASSERT_TRUE(server_ctx_);
1706     // Set up a server cert. Client certs can be set up explicitly.
1707     ASSERT_TRUE(UseCertAndKey(server_ctx_.get()));
1708   }
1709 
UseCertAndKey(SSL_CTX * ctx) const1710   bool UseCertAndKey(SSL_CTX *ctx) const {
1711     return SSL_CTX_use_certificate(ctx, cert_.get()) &&
1712            SSL_CTX_use_PrivateKey(ctx, key_.get());
1713   }
1714 
Connect(const ClientConfig & config=ClientConfig ())1715   bool Connect(const ClientConfig &config = ClientConfig()) {
1716     return ConnectClientAndServer(&client_, &server_, client_ctx_.get(),
1717                                   server_ctx_.get(), config, true,
1718                                   shed_handshake_config_);
1719   }
1720 
version() const1721   uint16_t version() const { return GetParam().version; }
1722 
is_dtls() const1723   bool is_dtls() const {
1724     return GetParam().ssl_method == VersionParam::is_dtls;
1725   }
1726 
1727   bool shed_handshake_config_ = true;
1728   bssl::UniquePtr<SSL> client_, server_;
1729   bssl::UniquePtr<SSL_CTX> server_ctx_, client_ctx_;
1730   bssl::UniquePtr<X509> cert_;
1731   bssl::UniquePtr<EVP_PKEY> key_;
1732 };
1733 
1734 INSTANTIATE_TEST_SUITE_P(WithVersion, SSLVersionTest,
1735                          testing::ValuesIn(kAllVersions),
__anon671ed3370402(const testing::TestParamInfo<VersionParam> &i) 1736                          [](const testing::TestParamInfo<VersionParam> &i) {
1737                            return i.param.name;
1738                          });
1739 
TEST_P(SSLVersionTest,SequenceNumber)1740 TEST_P(SSLVersionTest, SequenceNumber) {
1741   ASSERT_TRUE(Connect());
1742 
1743   // Drain any post-handshake messages to ensure there are no unread records
1744   // on either end.
1745   ASSERT_TRUE(FlushNewSessionTickets(client_.get(), server_.get()));
1746 
1747   uint64_t client_read_seq = SSL_get_read_sequence(client_.get());
1748   uint64_t client_write_seq = SSL_get_write_sequence(client_.get());
1749   uint64_t server_read_seq = SSL_get_read_sequence(server_.get());
1750   uint64_t server_write_seq = SSL_get_write_sequence(server_.get());
1751 
1752   if (is_dtls()) {
1753     // Both client and server must be at epoch 1.
1754     EXPECT_EQ(EpochFromSequence(client_read_seq), 1);
1755     EXPECT_EQ(EpochFromSequence(client_write_seq), 1);
1756     EXPECT_EQ(EpochFromSequence(server_read_seq), 1);
1757     EXPECT_EQ(EpochFromSequence(server_write_seq), 1);
1758 
1759     // The next record to be written should exceed the largest received.
1760     EXPECT_GT(client_write_seq, server_read_seq);
1761     EXPECT_GT(server_write_seq, client_read_seq);
1762   } else {
1763     // The next record to be written should equal the next to be received.
1764     EXPECT_EQ(client_write_seq, server_read_seq);
1765     EXPECT_EQ(server_write_seq, client_read_seq);
1766   }
1767 
1768   // Send a record from client to server.
1769   uint8_t byte = 0;
1770   EXPECT_EQ(SSL_write(client_.get(), &byte, 1), 1);
1771   EXPECT_EQ(SSL_read(server_.get(), &byte, 1), 1);
1772 
1773   // The client write and server read sequence numbers should have
1774   // incremented.
1775   EXPECT_EQ(client_write_seq + 1, SSL_get_write_sequence(client_.get()));
1776   EXPECT_EQ(server_read_seq + 1, SSL_get_read_sequence(server_.get()));
1777 }
1778 
TEST_P(SSLVersionTest,OneSidedShutdown)1779 TEST_P(SSLVersionTest, OneSidedShutdown) {
1780   // SSL_shutdown is a no-op in DTLS.
1781   if (is_dtls()) {
1782     return;
1783   }
1784   ASSERT_TRUE(Connect());
1785 
1786   // Shut down half the connection. SSL_shutdown will return 0 to signal only
1787   // one side has shut down.
1788   ASSERT_EQ(SSL_shutdown(client_.get()), 0);
1789 
1790   // Reading from the server should consume the EOF.
1791   uint8_t byte;
1792   ASSERT_EQ(SSL_read(server_.get(), &byte, 1), 0);
1793   ASSERT_EQ(SSL_get_error(server_.get(), 0), SSL_ERROR_ZERO_RETURN);
1794 
1795   // However, the server may continue to write data and then shut down the
1796   // connection.
1797   byte = 42;
1798   ASSERT_EQ(SSL_write(server_.get(), &byte, 1), 1);
1799   ASSERT_EQ(SSL_read(client_.get(), &byte, 1), 1);
1800   ASSERT_EQ(byte, 42);
1801 
1802   // The server may then shutdown the connection.
1803   EXPECT_EQ(SSL_shutdown(server_.get()), 1);
1804   EXPECT_EQ(SSL_shutdown(client_.get()), 1);
1805 }
1806 
TEST(SSLTest,SessionDuplication)1807 TEST(SSLTest, SessionDuplication) {
1808   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
1809   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
1810   ASSERT_TRUE(client_ctx);
1811   ASSERT_TRUE(server_ctx);
1812 
1813   bssl::UniquePtr<X509> cert = GetTestCertificate();
1814   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
1815   ASSERT_TRUE(cert);
1816   ASSERT_TRUE(key);
1817   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
1818   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
1819 
1820   bssl::UniquePtr<SSL> client, server;
1821   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
1822                                      server_ctx.get()));
1823 
1824   SSL_SESSION *session0 = SSL_get_session(client.get());
1825   bssl::UniquePtr<SSL_SESSION> session1 =
1826       bssl::SSL_SESSION_dup(session0, SSL_SESSION_DUP_ALL);
1827   ASSERT_TRUE(session1);
1828 
1829   session1->not_resumable = false;
1830 
1831   uint8_t *s0_bytes, *s1_bytes;
1832   size_t s0_len, s1_len;
1833 
1834   ASSERT_TRUE(SSL_SESSION_to_bytes(session0, &s0_bytes, &s0_len));
1835   bssl::UniquePtr<uint8_t> free_s0(s0_bytes);
1836 
1837   ASSERT_TRUE(SSL_SESSION_to_bytes(session1.get(), &s1_bytes, &s1_len));
1838   bssl::UniquePtr<uint8_t> free_s1(s1_bytes);
1839 
1840   EXPECT_EQ(Bytes(s0_bytes, s0_len), Bytes(s1_bytes, s1_len));
1841 }
1842 
ExpectFDs(const SSL * ssl,int rfd,int wfd)1843 static void ExpectFDs(const SSL *ssl, int rfd, int wfd) {
1844   EXPECT_EQ(rfd, SSL_get_fd(ssl));
1845   EXPECT_EQ(rfd, SSL_get_rfd(ssl));
1846   EXPECT_EQ(wfd, SSL_get_wfd(ssl));
1847 
1848   // The wrapper BIOs are always equal when fds are equal, even if set
1849   // individually.
1850   if (rfd == wfd) {
1851     EXPECT_EQ(SSL_get_rbio(ssl), SSL_get_wbio(ssl));
1852   }
1853 }
1854 
TEST(SSLTest,SetFD)1855 TEST(SSLTest, SetFD) {
1856   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1857   ASSERT_TRUE(ctx);
1858 
1859   // Test setting different read and write FDs.
1860   bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1861   ASSERT_TRUE(ssl);
1862   EXPECT_TRUE(SSL_set_rfd(ssl.get(), 1));
1863   EXPECT_TRUE(SSL_set_wfd(ssl.get(), 2));
1864   ExpectFDs(ssl.get(), 1, 2);
1865 
1866   // Test setting the same FD.
1867   ssl.reset(SSL_new(ctx.get()));
1868   ASSERT_TRUE(ssl);
1869   EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1870   ExpectFDs(ssl.get(), 1, 1);
1871 
1872   // Test setting the same FD one side at a time.
1873   ssl.reset(SSL_new(ctx.get()));
1874   ASSERT_TRUE(ssl);
1875   EXPECT_TRUE(SSL_set_rfd(ssl.get(), 1));
1876   EXPECT_TRUE(SSL_set_wfd(ssl.get(), 1));
1877   ExpectFDs(ssl.get(), 1, 1);
1878 
1879   // Test setting the same FD in the other order.
1880   ssl.reset(SSL_new(ctx.get()));
1881   ASSERT_TRUE(ssl);
1882   EXPECT_TRUE(SSL_set_wfd(ssl.get(), 1));
1883   EXPECT_TRUE(SSL_set_rfd(ssl.get(), 1));
1884   ExpectFDs(ssl.get(), 1, 1);
1885 
1886   // Test changing the read FD partway through.
1887   ssl.reset(SSL_new(ctx.get()));
1888   ASSERT_TRUE(ssl);
1889   EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1890   EXPECT_TRUE(SSL_set_rfd(ssl.get(), 2));
1891   ExpectFDs(ssl.get(), 2, 1);
1892 
1893   // Test changing the write FD partway through.
1894   ssl.reset(SSL_new(ctx.get()));
1895   ASSERT_TRUE(ssl);
1896   EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1897   EXPECT_TRUE(SSL_set_wfd(ssl.get(), 2));
1898   ExpectFDs(ssl.get(), 1, 2);
1899 
1900   // Test a no-op change to the read FD partway through.
1901   ssl.reset(SSL_new(ctx.get()));
1902   ASSERT_TRUE(ssl);
1903   EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1904   EXPECT_TRUE(SSL_set_rfd(ssl.get(), 1));
1905   ExpectFDs(ssl.get(), 1, 1);
1906 
1907   // Test a no-op change to the write FD partway through.
1908   ssl.reset(SSL_new(ctx.get()));
1909   ASSERT_TRUE(ssl);
1910   EXPECT_TRUE(SSL_set_fd(ssl.get(), 1));
1911   EXPECT_TRUE(SSL_set_wfd(ssl.get(), 1));
1912   ExpectFDs(ssl.get(), 1, 1);
1913 
1914   // ASan builds will implicitly test that the internal |BIO| reference-counting
1915   // is correct.
1916 }
1917 
TEST(SSLTest,SetBIO)1918 TEST(SSLTest, SetBIO) {
1919   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
1920   ASSERT_TRUE(ctx);
1921 
1922   bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
1923   bssl::UniquePtr<BIO> bio1(BIO_new(BIO_s_mem())), bio2(BIO_new(BIO_s_mem())),
1924       bio3(BIO_new(BIO_s_mem()));
1925   ASSERT_TRUE(ssl);
1926   ASSERT_TRUE(bio1);
1927   ASSERT_TRUE(bio2);
1928   ASSERT_TRUE(bio3);
1929 
1930   // SSL_set_bio takes one reference when the parameters are the same.
1931   BIO_up_ref(bio1.get());
1932   SSL_set_bio(ssl.get(), bio1.get(), bio1.get());
1933 
1934   // Repeating the call does nothing.
1935   SSL_set_bio(ssl.get(), bio1.get(), bio1.get());
1936 
1937   // It takes one reference each when the parameters are different.
1938   BIO_up_ref(bio2.get());
1939   BIO_up_ref(bio3.get());
1940   SSL_set_bio(ssl.get(), bio2.get(), bio3.get());
1941 
1942   // Repeating the call does nothing.
1943   SSL_set_bio(ssl.get(), bio2.get(), bio3.get());
1944 
1945   // It takes one reference when changing only wbio.
1946   BIO_up_ref(bio1.get());
1947   SSL_set_bio(ssl.get(), bio2.get(), bio1.get());
1948 
1949   // It takes one reference when changing only rbio and the two are different.
1950   BIO_up_ref(bio3.get());
1951   SSL_set_bio(ssl.get(), bio3.get(), bio1.get());
1952 
1953   // If setting wbio to rbio, it takes no additional references.
1954   SSL_set_bio(ssl.get(), bio3.get(), bio3.get());
1955 
1956   // From there, wbio may be switched to something else.
1957   BIO_up_ref(bio1.get());
1958   SSL_set_bio(ssl.get(), bio3.get(), bio1.get());
1959 
1960   // If setting rbio to wbio, it takes no additional references.
1961   SSL_set_bio(ssl.get(), bio1.get(), bio1.get());
1962 
1963   // From there, rbio may be switched to something else, but, for historical
1964   // reasons, it takes a reference to both parameters.
1965   BIO_up_ref(bio1.get());
1966   BIO_up_ref(bio2.get());
1967   SSL_set_bio(ssl.get(), bio2.get(), bio1.get());
1968 
1969   // ASAN builds will implicitly test that the internal |BIO| reference-counting
1970   // is correct.
1971 }
1972 
VerifySucceed(X509_STORE_CTX * store_ctx,void * arg)1973 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) { return 1; }
1974 
TEST_P(SSLVersionTest,GetPeerCertificate)1975 TEST_P(SSLVersionTest, GetPeerCertificate) {
1976   ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
1977 
1978   // Configure both client and server to accept any certificate.
1979   SSL_CTX_set_verify(client_ctx_.get(),
1980                      SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1981                      nullptr);
1982   SSL_CTX_set_cert_verify_callback(client_ctx_.get(), VerifySucceed, NULL);
1983   SSL_CTX_set_verify(server_ctx_.get(),
1984                      SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1985                      nullptr);
1986   SSL_CTX_set_cert_verify_callback(server_ctx_.get(), VerifySucceed, NULL);
1987 
1988   ASSERT_TRUE(Connect());
1989 
1990   // Client and server should both see the leaf certificate.
1991   bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(server_.get()));
1992   ASSERT_TRUE(peer);
1993   ASSERT_EQ(X509_cmp(cert_.get(), peer.get()), 0);
1994 
1995   peer.reset(SSL_get_peer_certificate(client_.get()));
1996   ASSERT_TRUE(peer);
1997   ASSERT_EQ(X509_cmp(cert_.get(), peer.get()), 0);
1998 
1999   // However, for historical reasons, the X509 chain includes the leaf on the
2000   // client, but does not on the server.
2001   EXPECT_EQ(sk_X509_num(SSL_get_peer_cert_chain(client_.get())), 1u);
2002   EXPECT_EQ(sk_CRYPTO_BUFFER_num(SSL_get0_peer_certificates(client_.get())),
2003             1u);
2004 
2005   EXPECT_EQ(sk_X509_num(SSL_get_peer_cert_chain(server_.get())), 0u);
2006   EXPECT_EQ(sk_CRYPTO_BUFFER_num(SSL_get0_peer_certificates(server_.get())),
2007             1u);
2008 }
2009 
TEST_P(SSLVersionTest,NoPeerCertificate)2010 TEST_P(SSLVersionTest, NoPeerCertificate) {
2011   SSL_CTX_set_verify(server_ctx_.get(), SSL_VERIFY_PEER, nullptr);
2012   SSL_CTX_set_cert_verify_callback(server_ctx_.get(), VerifySucceed, NULL);
2013   SSL_CTX_set_cert_verify_callback(client_ctx_.get(), VerifySucceed, NULL);
2014 
2015   ASSERT_TRUE(Connect());
2016 
2017   // Server should not see a peer certificate.
2018   bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(server_.get()));
2019   ASSERT_FALSE(peer);
2020   ASSERT_FALSE(SSL_get0_peer_certificates(server_.get()));
2021 }
2022 
TEST_P(SSLVersionTest,RetainOnlySHA256OfCerts)2023 TEST_P(SSLVersionTest, RetainOnlySHA256OfCerts) {
2024   uint8_t *cert_der = NULL;
2025   int cert_der_len = i2d_X509(cert_.get(), &cert_der);
2026   ASSERT_GE(cert_der_len, 0);
2027   bssl::UniquePtr<uint8_t> free_cert_der(cert_der);
2028 
2029   uint8_t cert_sha256[SHA256_DIGEST_LENGTH];
2030   SHA256(cert_der, cert_der_len, cert_sha256);
2031 
2032   ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
2033 
2034   // Configure both client and server to accept any certificate, but the
2035   // server must retain only the SHA-256 of the peer.
2036   SSL_CTX_set_verify(client_ctx_.get(),
2037                      SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2038                      nullptr);
2039   SSL_CTX_set_verify(server_ctx_.get(),
2040                      SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2041                      nullptr);
2042   SSL_CTX_set_cert_verify_callback(client_ctx_.get(), VerifySucceed, NULL);
2043   SSL_CTX_set_cert_verify_callback(server_ctx_.get(), VerifySucceed, NULL);
2044   SSL_CTX_set_retain_only_sha256_of_client_certs(server_ctx_.get(), 1);
2045 
2046   ASSERT_TRUE(Connect());
2047 
2048   // The peer certificate has been dropped.
2049   bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(server_.get()));
2050   EXPECT_FALSE(peer);
2051 
2052   SSL_SESSION *session = SSL_get_session(server_.get());
2053   EXPECT_TRUE(SSL_SESSION_has_peer_sha256(session));
2054 
2055   const uint8_t *peer_sha256;
2056   size_t peer_sha256_len;
2057   SSL_SESSION_get0_peer_sha256(session, &peer_sha256, &peer_sha256_len);
2058   EXPECT_EQ(Bytes(cert_sha256), Bytes(peer_sha256, peer_sha256_len));
2059 }
2060 
2061 // Tests that our ClientHellos do not change unexpectedly. These are purely
2062 // change detection tests. If they fail as part of an intentional ClientHello
2063 // change, update the test vector.
TEST(SSLTest,ClientHello)2064 TEST(SSLTest, ClientHello) {
2065   struct {
2066     uint16_t max_version;
2067     std::vector<uint8_t> expected;
2068   } kTests[] = {
2069     {TLS1_VERSION,
2070      {0x16, 0x03, 0x01, 0x00, 0x5a, 0x01, 0x00, 0x00, 0x56, 0x03, 0x01, 0x00,
2071       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2072       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2073       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0xc0, 0x09,
2074       0xc0, 0x13, 0xc0, 0x0a, 0xc0, 0x14, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a,
2075       0x01, 0x00, 0x00, 0x1f, 0x00, 0x17, 0x00, 0x00, 0xff, 0x01, 0x00, 0x01,
2076       0x00, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1d, 0x00, 0x17, 0x00,
2077       0x18, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x23, 0x00, 0x00}},
2078     {TLS1_1_VERSION,
2079      {0x16, 0x03, 0x01, 0x00, 0x5a, 0x01, 0x00, 0x00, 0x56, 0x03, 0x02, 0x00,
2080       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2081       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2082       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0xc0, 0x09,
2083       0xc0, 0x13, 0xc0, 0x0a, 0xc0, 0x14, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a,
2084       0x01, 0x00, 0x00, 0x1f, 0x00, 0x17, 0x00, 0x00, 0xff, 0x01, 0x00, 0x01,
2085       0x00, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1d, 0x00, 0x17, 0x00,
2086       0x18, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x23, 0x00, 0x00}},
2087     {TLS1_2_VERSION,
2088      {0x16, 0x03, 0x01, 0x00, 0x82, 0x01, 0x00, 0x00, 0x7e, 0x03, 0x03, 0x00,
2089       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2090       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2091       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0xcc, 0xa9,
2092       0xcc, 0xa8, 0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30, 0xc0, 0x09,
2093       0xc0, 0x13, 0xc0, 0x0a, 0xc0, 0x14, 0x00, 0x9c, 0x00, 0x9d, 0x00, 0x2f,
2094       0x00, 0x35, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x37, 0x00, 0x17, 0x00, 0x00,
2095       0xff, 0x01, 0x00, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00,
2096       0x1d, 0x00, 0x17, 0x00, 0x18, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00,
2097       0x23, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x14, 0x00, 0x12, 0x04, 0x03, 0x08,
2098       0x04, 0x04, 0x01, 0x05, 0x03, 0x08, 0x05, 0x05, 0x01, 0x08, 0x06, 0x06,
2099       0x01, 0x02, 0x01}},
2100     // TODO(davidben): Add a change detector for TLS 1.3 once the spec and our
2101     // implementation has settled enough that it won't change.
2102   };
2103 
2104   for (const auto &t : kTests) {
2105     SCOPED_TRACE(t.max_version);
2106 
2107     bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
2108     ASSERT_TRUE(ctx);
2109     // Our default cipher list varies by CPU capabilities, so manually place the
2110     // ChaCha20 ciphers in front.
2111     const char *cipher_list = "CHACHA20:ALL";
2112     ASSERT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), t.max_version));
2113     ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(ctx.get(), cipher_list));
2114 
2115     bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
2116     ASSERT_TRUE(ssl);
2117     std::vector<uint8_t> client_hello;
2118     ASSERT_TRUE(GetClientHello(ssl.get(), &client_hello));
2119 
2120     // Zero the client_random.
2121     constexpr size_t kRandomOffset = 1 + 2 + 2 +  // record header
2122                                      1 + 3 +      // handshake message header
2123                                      2;           // client_version
2124     ASSERT_GE(client_hello.size(), kRandomOffset + SSL3_RANDOM_SIZE);
2125     OPENSSL_memset(client_hello.data() + kRandomOffset, 0, SSL3_RANDOM_SIZE);
2126 
2127     if (client_hello != t.expected) {
2128       ADD_FAILURE() << "ClientHellos did not match.";
2129       // Print the value manually so it is easier to update the test vector.
2130       for (size_t i = 0; i < client_hello.size(); i += 12) {
2131         printf("     %c", i == 0 ? '{' : ' ');
2132         for (size_t j = i; j < client_hello.size() && j < i + 12; j++) {
2133           if (j > i) {
2134             printf(" ");
2135           }
2136           printf("0x%02x", client_hello[j]);
2137           if (j < client_hello.size() - 1) {
2138             printf(",");
2139           }
2140         }
2141         if (i + 12 >= client_hello.size()) {
2142           printf("}},");
2143         }
2144         printf("\n");
2145       }
2146     }
2147   }
2148 }
2149 
2150 static bssl::UniquePtr<SSL_SESSION> g_last_session;
2151 
SaveLastSession(SSL * ssl,SSL_SESSION * session)2152 static int SaveLastSession(SSL *ssl, SSL_SESSION *session) {
2153   // Save the most recent session.
2154   g_last_session.reset(session);
2155   return 1;
2156 }
2157 
CreateClientSession(SSL_CTX * client_ctx,SSL_CTX * server_ctx,const ClientConfig & config=ClientConfig ())2158 static bssl::UniquePtr<SSL_SESSION> CreateClientSession(
2159     SSL_CTX *client_ctx, SSL_CTX *server_ctx,
2160     const ClientConfig &config = ClientConfig()) {
2161   g_last_session = nullptr;
2162   SSL_CTX_sess_set_new_cb(client_ctx, SaveLastSession);
2163 
2164   // Connect client and server to get a session.
2165   bssl::UniquePtr<SSL> client, server;
2166   if (!ConnectClientAndServer(&client, &server, client_ctx, server_ctx,
2167                               config) ||
2168       !FlushNewSessionTickets(client.get(), server.get())) {
2169     fprintf(stderr, "Failed to connect client and server.\n");
2170     return nullptr;
2171   }
2172 
2173   SSL_CTX_sess_set_new_cb(client_ctx, nullptr);
2174 
2175   if (!g_last_session) {
2176     fprintf(stderr, "Client did not receive a session.\n");
2177     return nullptr;
2178   }
2179   return std::move(g_last_session);
2180 }
2181 
ExpectSessionReused(SSL_CTX * client_ctx,SSL_CTX * server_ctx,SSL_SESSION * session,bool want_reused)2182 static void ExpectSessionReused(SSL_CTX *client_ctx, SSL_CTX *server_ctx,
2183                                 SSL_SESSION *session, bool want_reused) {
2184   bssl::UniquePtr<SSL> client, server;
2185   ClientConfig config;
2186   config.session = session;
2187   EXPECT_TRUE(
2188       ConnectClientAndServer(&client, &server, client_ctx, server_ctx, config));
2189 
2190   EXPECT_EQ(SSL_session_reused(client.get()), SSL_session_reused(server.get()));
2191 
2192   bool was_reused = !!SSL_session_reused(client.get());
2193   EXPECT_EQ(was_reused, want_reused);
2194 }
2195 
ExpectSessionRenewed(SSL_CTX * client_ctx,SSL_CTX * server_ctx,SSL_SESSION * session)2196 static bssl::UniquePtr<SSL_SESSION> ExpectSessionRenewed(SSL_CTX *client_ctx,
2197                                                          SSL_CTX *server_ctx,
2198                                                          SSL_SESSION *session) {
2199   g_last_session = nullptr;
2200   SSL_CTX_sess_set_new_cb(client_ctx, SaveLastSession);
2201 
2202   bssl::UniquePtr<SSL> client, server;
2203   ClientConfig config;
2204   config.session = session;
2205   if (!ConnectClientAndServer(&client, &server, client_ctx, server_ctx,
2206                               config) ||
2207       !FlushNewSessionTickets(client.get(), server.get())) {
2208     fprintf(stderr, "Failed to connect client and server.\n");
2209     return nullptr;
2210   }
2211 
2212   if (SSL_session_reused(client.get()) != SSL_session_reused(server.get())) {
2213     fprintf(stderr, "Client and server were inconsistent.\n");
2214     return nullptr;
2215   }
2216 
2217   if (!SSL_session_reused(client.get())) {
2218     fprintf(stderr, "Session was not reused.\n");
2219     return nullptr;
2220   }
2221 
2222   SSL_CTX_sess_set_new_cb(client_ctx, nullptr);
2223 
2224   if (!g_last_session) {
2225     fprintf(stderr, "Client did not receive a renewed session.\n");
2226     return nullptr;
2227   }
2228   return std::move(g_last_session);
2229 }
2230 
ExpectTicketKeyChanged(SSL_CTX * ctx,uint8_t * inout_key,bool changed)2231 static void ExpectTicketKeyChanged(SSL_CTX *ctx, uint8_t *inout_key,
2232                                    bool changed) {
2233   uint8_t new_key[kTicketKeyLen];
2234   // May return 0, 1 or 48.
2235   ASSERT_EQ(SSL_CTX_get_tlsext_ticket_keys(ctx, new_key, kTicketKeyLen), 1);
2236   if (changed) {
2237     ASSERT_NE(Bytes(inout_key, kTicketKeyLen), Bytes(new_key));
2238   } else {
2239     ASSERT_EQ(Bytes(inout_key, kTicketKeyLen), Bytes(new_key));
2240   }
2241   OPENSSL_memcpy(inout_key, new_key, kTicketKeyLen);
2242 }
2243 
SwitchSessionIDContextSNI(SSL * ssl,int * out_alert,void * arg)2244 static int SwitchSessionIDContextSNI(SSL *ssl, int *out_alert, void *arg) {
2245   static const uint8_t kContext[] = {3};
2246 
2247   if (!SSL_set_session_id_context(ssl, kContext, sizeof(kContext))) {
2248     return SSL_TLSEXT_ERR_ALERT_FATAL;
2249   }
2250 
2251   return SSL_TLSEXT_ERR_OK;
2252 }
2253 
TEST_P(SSLVersionTest,SessionIDContext)2254 TEST_P(SSLVersionTest, SessionIDContext) {
2255   static const uint8_t kContext1[] = {1};
2256   static const uint8_t kContext2[] = {2};
2257 
2258   ASSERT_TRUE(SSL_CTX_set_session_id_context(server_ctx_.get(), kContext1,
2259                                              sizeof(kContext1)));
2260 
2261   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
2262   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
2263 
2264   bssl::UniquePtr<SSL_SESSION> session =
2265       CreateClientSession(client_ctx_.get(), server_ctx_.get());
2266   ASSERT_TRUE(session);
2267 
2268   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2269                                   session.get(),
2270                                   true /* expect session reused */));
2271 
2272   // Change the session ID context.
2273   ASSERT_TRUE(SSL_CTX_set_session_id_context(server_ctx_.get(), kContext2,
2274                                              sizeof(kContext2)));
2275 
2276   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2277                                   session.get(),
2278                                   false /* expect session not reused */));
2279 
2280   // Change the session ID context back and install an SNI callback to switch
2281   // it.
2282   ASSERT_TRUE(SSL_CTX_set_session_id_context(server_ctx_.get(), kContext1,
2283                                              sizeof(kContext1)));
2284 
2285   SSL_CTX_set_tlsext_servername_callback(server_ctx_.get(),
2286                                          SwitchSessionIDContextSNI);
2287 
2288   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2289                                   session.get(),
2290                                   false /* expect session not reused */));
2291 
2292   // Switch the session ID context with the early callback instead.
2293   SSL_CTX_set_tlsext_servername_callback(server_ctx_.get(), nullptr);
2294   SSL_CTX_set_select_certificate_cb(
2295       server_ctx_.get(),
2296       [](const SSL_CLIENT_HELLO *client_hello) -> ssl_select_cert_result_t {
2297         static const uint8_t kContext[] = {3};
2298 
2299         if (!SSL_set_session_id_context(client_hello->ssl, kContext,
2300                                         sizeof(kContext))) {
2301           return ssl_select_cert_error;
2302         }
2303 
2304         return ssl_select_cert_success;
2305       });
2306 
2307   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2308                                   session.get(),
2309                                   false /* expect session not reused */));
2310 }
2311 
2312 static timeval g_current_time;
2313 
CurrentTimeCallback(const SSL * ssl,timeval * out_clock)2314 static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
2315   *out_clock = g_current_time;
2316 }
2317 
FrozenTimeCallback(const SSL * ssl,timeval * out_clock)2318 static void FrozenTimeCallback(const SSL *ssl, timeval *out_clock) {
2319   out_clock->tv_sec = 1000;
2320   out_clock->tv_usec = 0;
2321 }
2322 
RenewTicketCallback(SSL * ssl,uint8_t * key_name,uint8_t * iv,EVP_CIPHER_CTX * ctx,HMAC_CTX * hmac_ctx,int encrypt)2323 static int RenewTicketCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
2324                                EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
2325                                int encrypt) {
2326   static const uint8_t kZeros[16] = {0};
2327 
2328   if (encrypt) {
2329     OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros));
2330     RAND_bytes(iv, 16);
2331   } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) {
2332     return 0;
2333   }
2334 
2335   if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
2336       !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
2337     return -1;
2338   }
2339 
2340   // Returning two from the callback in decrypt mode renews the
2341   // session in TLS 1.2 and below.
2342   return encrypt ? 1 : 2;
2343 }
2344 
GetServerTicketTime(long * out,const SSL_SESSION * session)2345 static bool GetServerTicketTime(long *out, const SSL_SESSION *session) {
2346   const uint8_t *ticket;
2347   size_t ticket_len;
2348   SSL_SESSION_get0_ticket(session, &ticket, &ticket_len);
2349   if (ticket_len < 16 + 16 + SHA256_DIGEST_LENGTH) {
2350     return false;
2351   }
2352 
2353   const uint8_t *ciphertext = ticket + 16 + 16;
2354   size_t len = ticket_len - 16 - 16 - SHA256_DIGEST_LENGTH;
2355   std::unique_ptr<uint8_t[]> plaintext(new uint8_t[len]);
2356 
2357 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
2358   // Fuzzer-mode tickets are unencrypted.
2359   OPENSSL_memcpy(plaintext.get(), ciphertext, len);
2360 #else
2361   static const uint8_t kZeros[16] = {0};
2362   const uint8_t *iv = ticket + 16;
2363   bssl::ScopedEVP_CIPHER_CTX ctx;
2364   int len1, len2;
2365   if (!EVP_DecryptInit_ex(ctx.get(), EVP_aes_128_cbc(), nullptr, kZeros, iv) ||
2366       !EVP_DecryptUpdate(ctx.get(), plaintext.get(), &len1, ciphertext, len) ||
2367       !EVP_DecryptFinal_ex(ctx.get(), plaintext.get() + len1, &len2)) {
2368     return false;
2369   }
2370 
2371   len = static_cast<size_t>(len1 + len2);
2372 #endif
2373 
2374   bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(TLS_method()));
2375   if (!ssl_ctx) {
2376     return false;
2377   }
2378   bssl::UniquePtr<SSL_SESSION> server_session(
2379       SSL_SESSION_from_bytes(plaintext.get(), len, ssl_ctx.get()));
2380   if (!server_session) {
2381     return false;
2382   }
2383 
2384   *out = SSL_SESSION_get_time(server_session.get());
2385   return true;
2386 }
2387 
TEST_P(SSLVersionTest,SessionTimeout)2388 TEST_P(SSLVersionTest, SessionTimeout) {
2389   for (bool server_test : {false, true}) {
2390     SCOPED_TRACE(server_test);
2391 
2392     ResetContexts();
2393     SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
2394     SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
2395 
2396     static const time_t kStartTime = 1000;
2397     g_current_time.tv_sec = kStartTime;
2398 
2399     // We are willing to use a longer lifetime for TLS 1.3 sessions as
2400     // resumptions still perform ECDHE.
2401     const time_t timeout = version() == TLS1_3_VERSION
2402                                ? SSL_DEFAULT_SESSION_PSK_DHE_TIMEOUT
2403                                : SSL_DEFAULT_SESSION_TIMEOUT;
2404 
2405     // Both client and server must enforce session timeouts. We configure the
2406     // other side with a frozen clock so it never expires tickets.
2407     if (server_test) {
2408       SSL_CTX_set_current_time_cb(client_ctx_.get(), FrozenTimeCallback);
2409       SSL_CTX_set_current_time_cb(server_ctx_.get(), CurrentTimeCallback);
2410     } else {
2411       SSL_CTX_set_current_time_cb(client_ctx_.get(), CurrentTimeCallback);
2412       SSL_CTX_set_current_time_cb(server_ctx_.get(), FrozenTimeCallback);
2413     }
2414 
2415     // Configure a ticket callback which renews tickets.
2416     SSL_CTX_set_tlsext_ticket_key_cb(server_ctx_.get(), RenewTicketCallback);
2417 
2418     bssl::UniquePtr<SSL_SESSION> session =
2419         CreateClientSession(client_ctx_.get(), server_ctx_.get());
2420     ASSERT_TRUE(session);
2421 
2422     // Advance the clock just behind the timeout.
2423     g_current_time.tv_sec += timeout - 1;
2424 
2425     TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2426                                     session.get(),
2427                                     true /* expect session reused */));
2428 
2429     // Advance the clock one more second.
2430     g_current_time.tv_sec++;
2431 
2432     TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2433                                     session.get(),
2434                                     false /* expect session not reused */));
2435 
2436     // Rewind the clock to before the session was minted.
2437     g_current_time.tv_sec = kStartTime - 1;
2438 
2439     TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2440                                     session.get(),
2441                                     false /* expect session not reused */));
2442 
2443     // Renew the session 10 seconds before expiration.
2444     time_t new_start_time = kStartTime + timeout - 10;
2445     g_current_time.tv_sec = new_start_time;
2446     bssl::UniquePtr<SSL_SESSION> new_session = ExpectSessionRenewed(
2447         client_ctx_.get(), server_ctx_.get(), session.get());
2448     ASSERT_TRUE(new_session);
2449 
2450     // This new session is not the same object as before.
2451     EXPECT_NE(session.get(), new_session.get());
2452 
2453     // Check the sessions have timestamps measured from issuance.
2454     long session_time = 0;
2455     if (server_test) {
2456       ASSERT_TRUE(GetServerTicketTime(&session_time, new_session.get()));
2457     } else {
2458       session_time = SSL_SESSION_get_time(new_session.get());
2459     }
2460 
2461     ASSERT_EQ(session_time, g_current_time.tv_sec);
2462 
2463     if (version() == TLS1_3_VERSION) {
2464       // Renewal incorporates fresh key material in TLS 1.3, so we extend the
2465       // lifetime TLS 1.3.
2466       g_current_time.tv_sec = new_start_time + timeout - 1;
2467       TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2468                                       new_session.get(),
2469                                       true /* expect session reused */));
2470 
2471       // The new session expires after the new timeout.
2472       g_current_time.tv_sec = new_start_time + timeout + 1;
2473       TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2474                                       new_session.get(),
2475                                       false /* expect session ot reused */));
2476 
2477       // Renew the session until it begins just past the auth timeout.
2478       time_t auth_end_time = kStartTime + SSL_DEFAULT_SESSION_AUTH_TIMEOUT;
2479       while (new_start_time < auth_end_time - 1000) {
2480         // Get as close as possible to target start time.
2481         new_start_time =
2482             std::min(auth_end_time - 1000, new_start_time + timeout - 1);
2483         g_current_time.tv_sec = new_start_time;
2484         new_session = ExpectSessionRenewed(client_ctx_.get(), server_ctx_.get(),
2485                                            new_session.get());
2486         ASSERT_TRUE(new_session);
2487       }
2488 
2489       // Now the session's lifetime is bound by the auth timeout.
2490       g_current_time.tv_sec = auth_end_time - 1;
2491       TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2492                                       new_session.get(),
2493                                       true /* expect session reused */));
2494 
2495       g_current_time.tv_sec = auth_end_time + 1;
2496       TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2497                                       new_session.get(),
2498                                       false /* expect session ot reused */));
2499     } else {
2500       // The new session is usable just before the old expiration.
2501       g_current_time.tv_sec = kStartTime + timeout - 1;
2502       TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2503                                       new_session.get(),
2504                                       true /* expect session reused */));
2505 
2506       // Renewal does not extend the lifetime, so it is not usable beyond the
2507       // old expiration.
2508       g_current_time.tv_sec = kStartTime + timeout + 1;
2509       TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2510                                       new_session.get(),
2511                                       false /* expect session not reused */));
2512     }
2513   }
2514 }
2515 
TEST_P(SSLVersionTest,DefaultTicketKeyInitialization)2516 TEST_P(SSLVersionTest, DefaultTicketKeyInitialization) {
2517   static const uint8_t kZeroKey[kTicketKeyLen] = {};
2518   uint8_t ticket_key[kTicketKeyLen];
2519   ASSERT_EQ(1, SSL_CTX_get_tlsext_ticket_keys(server_ctx_.get(), ticket_key,
2520                                               kTicketKeyLen));
2521   ASSERT_NE(0, OPENSSL_memcmp(ticket_key, kZeroKey, kTicketKeyLen));
2522 }
2523 
TEST_P(SSLVersionTest,DefaultTicketKeyRotation)2524 TEST_P(SSLVersionTest, DefaultTicketKeyRotation) {
2525   static const time_t kStartTime = 1001;
2526   g_current_time.tv_sec = kStartTime;
2527 
2528   // We use session reuse as a proxy for ticket decryption success, hence
2529   // disable session timeouts.
2530   SSL_CTX_set_timeout(server_ctx_.get(), std::numeric_limits<uint32_t>::max());
2531   SSL_CTX_set_session_psk_dhe_timeout(server_ctx_.get(),
2532                                       std::numeric_limits<uint32_t>::max());
2533 
2534   SSL_CTX_set_current_time_cb(client_ctx_.get(), FrozenTimeCallback);
2535   SSL_CTX_set_current_time_cb(server_ctx_.get(), CurrentTimeCallback);
2536 
2537   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
2538   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_OFF);
2539 
2540   // Initialize ticket_key with the current key and check that it was
2541   // initialized to something, not all zeros.
2542   uint8_t ticket_key[kTicketKeyLen] = {0};
2543   TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2544                                      true /* changed */));
2545 
2546   // Verify ticket resumption actually works.
2547   bssl::UniquePtr<SSL> client, server;
2548   bssl::UniquePtr<SSL_SESSION> session =
2549       CreateClientSession(client_ctx_.get(), server_ctx_.get());
2550   ASSERT_TRUE(session);
2551   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2552                                   session.get(), true /* reused */));
2553 
2554   // Advance time to just before key rotation.
2555   g_current_time.tv_sec += SSL_DEFAULT_TICKET_KEY_ROTATION_INTERVAL - 1;
2556   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2557                                   session.get(), true /* reused */));
2558   TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2559                                      false /* NOT changed */));
2560 
2561   // Force key rotation.
2562   g_current_time.tv_sec += 1;
2563   bssl::UniquePtr<SSL_SESSION> new_session =
2564       CreateClientSession(client_ctx_.get(), server_ctx_.get());
2565   TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2566                                      true /* changed */));
2567 
2568   // Resumption with both old and new ticket should work.
2569   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2570                                   session.get(), true /* reused */));
2571   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2572                                   new_session.get(), true /* reused */));
2573   TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2574                                      false /* NOT changed */));
2575 
2576   // Force key rotation again. Resumption with the old ticket now fails.
2577   g_current_time.tv_sec += SSL_DEFAULT_TICKET_KEY_ROTATION_INTERVAL;
2578   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2579                                   session.get(), false /* NOT reused */));
2580   TRACED_CALL(ExpectTicketKeyChanged(server_ctx_.get(), ticket_key,
2581                                      true /* changed */));
2582 
2583   // But resumption with the newer session still works.
2584   TRACED_CALL(ExpectSessionReused(client_ctx_.get(), server_ctx_.get(),
2585                                   new_session.get(), true /* reused */));
2586 }
2587 
SwitchContext(SSL * ssl,int * out_alert,void * arg)2588 static int SwitchContext(SSL *ssl, int *out_alert, void *arg) {
2589   SSL_CTX *ctx = reinterpret_cast<SSL_CTX *>(arg);
2590   SSL_set_SSL_CTX(ssl, ctx);
2591   return SSL_TLSEXT_ERR_OK;
2592 }
2593 
TEST_P(SSLVersionTest,SNICallback)2594 TEST_P(SSLVersionTest, SNICallback) {
2595   bssl::UniquePtr<X509> cert2 = GetECDSATestCertificate();
2596   ASSERT_TRUE(cert2);
2597   bssl::UniquePtr<EVP_PKEY> key2 = GetECDSATestKey();
2598   ASSERT_TRUE(key2);
2599 
2600   // Test that switching the |SSL_CTX| at the SNI callback behaves correctly.
2601   static const uint16_t kECDSAWithSHA256 = SSL_SIGN_ECDSA_SECP256R1_SHA256;
2602 
2603   static const uint8_t kSCTList[] = {0, 6, 0, 4, 5, 6, 7, 8};
2604   static const uint8_t kOCSPResponse[] = {1, 2, 3, 4};
2605 
2606   bssl::UniquePtr<SSL_CTX> server_ctx2 = CreateContext();
2607   ASSERT_TRUE(server_ctx2);
2608   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx2.get(), cert2.get()));
2609   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx2.get(), key2.get()));
2610   ASSERT_TRUE(SSL_CTX_set_signed_cert_timestamp_list(
2611       server_ctx2.get(), kSCTList, sizeof(kSCTList)));
2612   ASSERT_TRUE(SSL_CTX_set_ocsp_response(server_ctx2.get(), kOCSPResponse,
2613                                         sizeof(kOCSPResponse)));
2614   // Historically signing preferences would be lost in some cases with the
2615   // SNI callback, which triggers the TLS 1.2 SHA-1 default. To ensure
2616   // this doesn't happen when |version| is TLS 1.2, configure the private
2617   // key to only sign SHA-256.
2618   ASSERT_TRUE(SSL_CTX_set_signing_algorithm_prefs(server_ctx2.get(),
2619                                                   &kECDSAWithSHA256, 1));
2620 
2621   SSL_CTX_set_tlsext_servername_callback(server_ctx_.get(), SwitchContext);
2622   SSL_CTX_set_tlsext_servername_arg(server_ctx_.get(), server_ctx2.get());
2623 
2624   SSL_CTX_enable_signed_cert_timestamps(client_ctx_.get());
2625   SSL_CTX_enable_ocsp_stapling(client_ctx_.get());
2626 
2627   ASSERT_TRUE(Connect());
2628 
2629   // The client should have received |cert2|.
2630   bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(client_.get()));
2631   ASSERT_TRUE(peer);
2632   EXPECT_EQ(X509_cmp(peer.get(), cert2.get()), 0);
2633 
2634   // The client should have received |server_ctx2|'s SCT list.
2635   const uint8_t *data;
2636   size_t len;
2637   SSL_get0_signed_cert_timestamp_list(client_.get(), &data, &len);
2638   EXPECT_EQ(Bytes(kSCTList), Bytes(data, len));
2639 
2640   // The client should have received |server_ctx2|'s OCSP response.
2641   SSL_get0_ocsp_response(client_.get(), &data, &len);
2642   EXPECT_EQ(Bytes(kOCSPResponse), Bytes(data, len));
2643 }
2644 
2645 // Test that the early callback can swap the maximum version.
TEST(SSLTest,EarlyCallbackVersionSwitch)2646 TEST(SSLTest, EarlyCallbackVersionSwitch) {
2647   bssl::UniquePtr<X509> cert = GetTestCertificate();
2648   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
2649   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
2650   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
2651   ASSERT_TRUE(cert);
2652   ASSERT_TRUE(key);
2653   ASSERT_TRUE(server_ctx);
2654   ASSERT_TRUE(client_ctx);
2655   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
2656   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
2657   ASSERT_TRUE(SSL_CTX_set_max_proto_version(client_ctx.get(), TLS1_3_VERSION));
2658   ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), TLS1_3_VERSION));
2659 
2660   SSL_CTX_set_select_certificate_cb(
2661       server_ctx.get(),
2662       [](const SSL_CLIENT_HELLO *client_hello) -> ssl_select_cert_result_t {
2663         if (!SSL_set_max_proto_version(client_hello->ssl, TLS1_2_VERSION)) {
2664           return ssl_select_cert_error;
2665         }
2666 
2667         return ssl_select_cert_success;
2668       });
2669 
2670   bssl::UniquePtr<SSL> client, server;
2671   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
2672                                      server_ctx.get()));
2673   EXPECT_EQ(TLS1_2_VERSION, SSL_version(client.get()));
2674 }
2675 
TEST(SSLTest,SetVersion)2676 TEST(SSLTest, SetVersion) {
2677   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
2678   ASSERT_TRUE(ctx);
2679 
2680   // Set valid TLS versions.
2681   EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_VERSION));
2682   EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_1_VERSION));
2683   EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_VERSION));
2684   EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_1_VERSION));
2685 
2686   // Invalid TLS versions are rejected.
2687   EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), DTLS1_VERSION));
2688   EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0x0200));
2689   EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0x1234));
2690   EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), DTLS1_VERSION));
2691   EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0x0200));
2692   EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0x1234));
2693 
2694   // Zero is the default version.
2695   EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), 0));
2696   EXPECT_EQ(TLS1_3_VERSION, SSL_CTX_get_max_proto_version(ctx.get()));
2697   EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), 0));
2698   EXPECT_EQ(TLS1_VERSION, SSL_CTX_get_min_proto_version(ctx.get()));
2699 
2700   // TLS 1.3 is available, but not by default.
2701   EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_3_VERSION));
2702   EXPECT_EQ(TLS1_3_VERSION, SSL_CTX_get_max_proto_version(ctx.get()));
2703 
2704   // SSL 3.0 is not available.
2705   EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), SSL3_VERSION));
2706 
2707   ctx.reset(SSL_CTX_new(DTLS_method()));
2708   ASSERT_TRUE(ctx);
2709 
2710   EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), DTLS1_VERSION));
2711   EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), DTLS1_2_VERSION));
2712   EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), DTLS1_VERSION));
2713   EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), DTLS1_2_VERSION));
2714 
2715   EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_VERSION));
2716   EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0xfefe /* DTLS 1.1 */));
2717   EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0xfffe /* DTLS 0.1 */));
2718   EXPECT_FALSE(SSL_CTX_set_max_proto_version(ctx.get(), 0x1234));
2719   EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_VERSION));
2720   EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0xfefe /* DTLS 1.1 */));
2721   EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0xfffe /* DTLS 0.1 */));
2722   EXPECT_FALSE(SSL_CTX_set_min_proto_version(ctx.get(), 0x1234));
2723 
2724   EXPECT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), 0));
2725   EXPECT_EQ(DTLS1_2_VERSION, SSL_CTX_get_max_proto_version(ctx.get()));
2726   EXPECT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), 0));
2727   EXPECT_EQ(DTLS1_VERSION, SSL_CTX_get_min_proto_version(ctx.get()));
2728 }
2729 
GetVersionName(uint16_t version)2730 static const char *GetVersionName(uint16_t version) {
2731   switch (version) {
2732     case TLS1_VERSION:
2733       return "TLSv1";
2734     case TLS1_1_VERSION:
2735       return "TLSv1.1";
2736     case TLS1_2_VERSION:
2737       return "TLSv1.2";
2738     case TLS1_3_VERSION:
2739       return "TLSv1.3";
2740     case DTLS1_VERSION:
2741       return "DTLSv1";
2742     case DTLS1_2_VERSION:
2743       return "DTLSv1.2";
2744     default:
2745       return "???";
2746   }
2747 }
2748 
TEST_P(SSLVersionTest,Version)2749 TEST_P(SSLVersionTest, Version) {
2750   ASSERT_TRUE(Connect());
2751 
2752   EXPECT_EQ(SSL_version(client_.get()), version());
2753   EXPECT_EQ(SSL_version(server_.get()), version());
2754 
2755   // Test the version name is reported as expected.
2756   const char *version_name = GetVersionName(version());
2757   EXPECT_EQ(strcmp(version_name, SSL_get_version(client_.get())), 0);
2758   EXPECT_EQ(strcmp(version_name, SSL_get_version(server_.get())), 0);
2759 
2760   // Test SSL_SESSION reports the same name.
2761   const char *client_name =
2762       SSL_SESSION_get_version(SSL_get_session(client_.get()));
2763   const char *server_name =
2764       SSL_SESSION_get_version(SSL_get_session(server_.get()));
2765   EXPECT_EQ(strcmp(version_name, client_name), 0);
2766   EXPECT_EQ(strcmp(version_name, server_name), 0);
2767 }
2768 
2769 // Tests that that |SSL_get_pending_cipher| is available during the ALPN
2770 // selection callback.
TEST_P(SSLVersionTest,ALPNCipherAvailable)2771 TEST_P(SSLVersionTest, ALPNCipherAvailable) {
2772   ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
2773 
2774   static const uint8_t kALPNProtos[] = {0x03, 'f', 'o', 'o'};
2775   ASSERT_EQ(SSL_CTX_set_alpn_protos(client_ctx_.get(), kALPNProtos,
2776                                     sizeof(kALPNProtos)),
2777             0);
2778 
2779   // The ALPN callback does not fail the handshake on error, so have the
2780   // callback write a boolean.
2781   std::pair<uint16_t, bool> callback_state(version(), false);
2782   SSL_CTX_set_alpn_select_cb(
2783       server_ctx_.get(),
2784       [](SSL *ssl, const uint8_t **out, uint8_t *out_len, const uint8_t *in,
2785          unsigned in_len, void *arg) -> int {
2786         auto state = reinterpret_cast<std::pair<uint16_t, bool> *>(arg);
2787         if (SSL_get_pending_cipher(ssl) != nullptr &&
2788             SSL_version(ssl) == state->first) {
2789           state->second = true;
2790         }
2791         return SSL_TLSEXT_ERR_NOACK;
2792       },
2793       &callback_state);
2794 
2795   ASSERT_TRUE(Connect());
2796 
2797   ASSERT_TRUE(callback_state.second);
2798 }
2799 
TEST_P(SSLVersionTest,SSLClearSessionResumption)2800 TEST_P(SSLVersionTest, SSLClearSessionResumption) {
2801   // Skip this for TLS 1.3. TLS 1.3's ticket mechanism is incompatible with this
2802   // API pattern.
2803   if (version() == TLS1_3_VERSION) {
2804     return;
2805   }
2806 
2807   shed_handshake_config_ = false;
2808   ASSERT_TRUE(Connect());
2809 
2810   EXPECT_FALSE(SSL_session_reused(client_.get()));
2811   EXPECT_FALSE(SSL_session_reused(server_.get()));
2812 
2813   // Reset everything.
2814   ASSERT_TRUE(SSL_clear(client_.get()));
2815   ASSERT_TRUE(SSL_clear(server_.get()));
2816 
2817   // Attempt to connect a second time.
2818   ASSERT_TRUE(CompleteHandshakes(client_.get(), server_.get()));
2819 
2820   // |SSL_clear| should implicitly offer the previous session to the server.
2821   EXPECT_TRUE(SSL_session_reused(client_.get()));
2822   EXPECT_TRUE(SSL_session_reused(server_.get()));
2823 }
2824 
TEST_P(SSLVersionTest,SSLClearFailsWithShedding)2825 TEST_P(SSLVersionTest, SSLClearFailsWithShedding) {
2826   shed_handshake_config_ = false;
2827   ASSERT_TRUE(Connect());
2828   ASSERT_TRUE(CompleteHandshakes(client_.get(), server_.get()));
2829 
2830   // Reset everything.
2831   ASSERT_TRUE(SSL_clear(client_.get()));
2832   ASSERT_TRUE(SSL_clear(server_.get()));
2833 
2834   // Now enable shedding, and connect a second time.
2835   shed_handshake_config_ = true;
2836   ASSERT_TRUE(Connect());
2837   ASSERT_TRUE(CompleteHandshakes(client_.get(), server_.get()));
2838 
2839   // |SSL_clear| should now fail.
2840   ASSERT_FALSE(SSL_clear(client_.get()));
2841   ASSERT_FALSE(SSL_clear(server_.get()));
2842 }
2843 
ChainsEqual(STACK_OF (X509)* chain,const std::vector<X509 * > & expected)2844 static bool ChainsEqual(STACK_OF(X509) * chain,
2845                         const std::vector<X509 *> &expected) {
2846   if (sk_X509_num(chain) != expected.size()) {
2847     return false;
2848   }
2849 
2850   for (size_t i = 0; i < expected.size(); i++) {
2851     if (X509_cmp(sk_X509_value(chain, i), expected[i]) != 0) {
2852       return false;
2853     }
2854   }
2855 
2856   return true;
2857 }
2858 
TEST_P(SSLVersionTest,AutoChain)2859 TEST_P(SSLVersionTest, AutoChain) {
2860   cert_ = GetChainTestCertificate();
2861   ASSERT_TRUE(cert_);
2862   key_ = GetChainTestKey();
2863   ASSERT_TRUE(key_);
2864   bssl::UniquePtr<X509> intermediate = GetChainTestIntermediate();
2865   ASSERT_TRUE(intermediate);
2866 
2867   ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
2868   ASSERT_TRUE(UseCertAndKey(server_ctx_.get()));
2869 
2870   // Configure both client and server to accept any certificate. Add
2871   // |intermediate| to the cert store.
2872   ASSERT_TRUE(X509_STORE_add_cert(SSL_CTX_get_cert_store(client_ctx_.get()),
2873                                   intermediate.get()));
2874   ASSERT_TRUE(X509_STORE_add_cert(SSL_CTX_get_cert_store(server_ctx_.get()),
2875                                   intermediate.get()));
2876   SSL_CTX_set_verify(client_ctx_.get(),
2877                      SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2878                      nullptr);
2879   SSL_CTX_set_verify(server_ctx_.get(),
2880                      SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2881                      nullptr);
2882   SSL_CTX_set_cert_verify_callback(client_ctx_.get(), VerifySucceed, NULL);
2883   SSL_CTX_set_cert_verify_callback(server_ctx_.get(), VerifySucceed, NULL);
2884 
2885   // By default, the client and server should each only send the leaf.
2886   ASSERT_TRUE(Connect());
2887 
2888   EXPECT_TRUE(
2889       ChainsEqual(SSL_get_peer_full_cert_chain(client_.get()), {cert_.get()}));
2890   EXPECT_TRUE(
2891       ChainsEqual(SSL_get_peer_full_cert_chain(server_.get()), {cert_.get()}));
2892 
2893   // If auto-chaining is enabled, then the intermediate is sent.
2894   SSL_CTX_clear_mode(client_ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
2895   SSL_CTX_clear_mode(server_ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
2896   ASSERT_TRUE(Connect());
2897 
2898   EXPECT_TRUE(ChainsEqual(SSL_get_peer_full_cert_chain(client_.get()),
2899                           {cert_.get(), intermediate.get()}));
2900   EXPECT_TRUE(ChainsEqual(SSL_get_peer_full_cert_chain(server_.get()),
2901                           {cert_.get(), intermediate.get()}));
2902 
2903   // Auto-chaining does not override explicitly-configured intermediates.
2904   ASSERT_TRUE(SSL_CTX_add1_chain_cert(client_ctx_.get(), cert_.get()));
2905   ASSERT_TRUE(SSL_CTX_add1_chain_cert(server_ctx_.get(), cert_.get()));
2906   ASSERT_TRUE(Connect());
2907 
2908   EXPECT_TRUE(ChainsEqual(SSL_get_peer_full_cert_chain(client_.get()),
2909                           {cert_.get(), cert_.get()}));
2910 
2911   EXPECT_TRUE(ChainsEqual(SSL_get_peer_full_cert_chain(server_.get()),
2912                           {cert_.get(), cert_.get()}));
2913 }
2914 
ExpectBadWriteRetry()2915 static bool ExpectBadWriteRetry() {
2916   int err = ERR_get_error();
2917   if (ERR_GET_LIB(err) != ERR_LIB_SSL ||
2918       ERR_GET_REASON(err) != SSL_R_BAD_WRITE_RETRY) {
2919     char buf[ERR_ERROR_STRING_BUF_LEN];
2920     ERR_error_string_n(err, buf, sizeof(buf));
2921     fprintf(stderr, "Wanted SSL_R_BAD_WRITE_RETRY, got: %s.\n", buf);
2922     return false;
2923   }
2924 
2925   if (ERR_peek_error() != 0) {
2926     fprintf(stderr, "Unexpected error following SSL_R_BAD_WRITE_RETRY.\n");
2927     return false;
2928   }
2929 
2930   return true;
2931 }
2932 
TEST_P(SSLVersionTest,SSLWriteRetry)2933 TEST_P(SSLVersionTest, SSLWriteRetry) {
2934   if (is_dtls()) {
2935     return;
2936   }
2937 
2938   for (bool enable_partial_write : {false, true}) {
2939     SCOPED_TRACE(enable_partial_write);
2940 
2941     // Connect a client and server.
2942     ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
2943 
2944     ASSERT_TRUE(Connect());
2945 
2946     if (enable_partial_write) {
2947       SSL_set_mode(client_.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
2948     }
2949 
2950     // Write without reading until the buffer is full and we have an unfinished
2951     // write. Keep a count so we may reread it again later. "hello!" will be
2952     // written in two chunks, "hello" and "!".
2953     char data[] = "hello!";
2954     static const int kChunkLen = 5;  // The length of "hello".
2955     unsigned count = 0;
2956     for (;;) {
2957       int ret = SSL_write(client_.get(), data, kChunkLen);
2958       if (ret <= 0) {
2959         ASSERT_EQ(SSL_get_error(client_.get(), ret), SSL_ERROR_WANT_WRITE);
2960         break;
2961       }
2962 
2963       ASSERT_EQ(ret, 5);
2964 
2965       count++;
2966     }
2967 
2968     // Retrying with the same parameters is legal.
2969     ASSERT_EQ(
2970         SSL_get_error(client_.get(), SSL_write(client_.get(), data, kChunkLen)),
2971         SSL_ERROR_WANT_WRITE);
2972 
2973     // Retrying with the same buffer but shorter length is not legal.
2974     ASSERT_EQ(SSL_get_error(client_.get(),
2975                             SSL_write(client_.get(), data, kChunkLen - 1)),
2976               SSL_ERROR_SSL);
2977     ASSERT_TRUE(ExpectBadWriteRetry());
2978 
2979     // Retrying with a different buffer pointer is not legal.
2980     char data2[] = "hello";
2981     ASSERT_EQ(SSL_get_error(client_.get(),
2982                             SSL_write(client_.get(), data2, kChunkLen)),
2983               SSL_ERROR_SSL);
2984     ASSERT_TRUE(ExpectBadWriteRetry());
2985 
2986     // With |SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER|, the buffer may move.
2987     SSL_set_mode(client_.get(), SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
2988     ASSERT_EQ(SSL_get_error(client_.get(),
2989                             SSL_write(client_.get(), data2, kChunkLen)),
2990               SSL_ERROR_WANT_WRITE);
2991 
2992     // |SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER| does not disable length checks.
2993     ASSERT_EQ(SSL_get_error(client_.get(),
2994                             SSL_write(client_.get(), data2, kChunkLen - 1)),
2995               SSL_ERROR_SSL);
2996     ASSERT_TRUE(ExpectBadWriteRetry());
2997 
2998     // Retrying with a larger buffer is legal.
2999     ASSERT_EQ(SSL_get_error(client_.get(),
3000                             SSL_write(client_.get(), data, kChunkLen + 1)),
3001               SSL_ERROR_WANT_WRITE);
3002 
3003     // Drain the buffer.
3004     char buf[20];
3005     for (unsigned i = 0; i < count; i++) {
3006       ASSERT_EQ(SSL_read(server_.get(), buf, sizeof(buf)), kChunkLen);
3007       ASSERT_EQ(OPENSSL_memcmp(buf, "hello", kChunkLen), 0);
3008     }
3009 
3010     // Now that there is space, a retry with a larger buffer should flush the
3011     // pending record, skip over that many bytes of input (on assumption they
3012     // are the same), and write the remainder. If SSL_MODE_ENABLE_PARTIAL_WRITE
3013     // is set, this will complete in two steps.
3014     char data3[] = "_____!";
3015     if (enable_partial_write) {
3016       ASSERT_EQ(SSL_write(client_.get(), data3, kChunkLen + 1), kChunkLen);
3017       ASSERT_EQ(SSL_write(client_.get(), data3 + kChunkLen, 1), 1);
3018     } else {
3019       ASSERT_EQ(SSL_write(client_.get(), data3, kChunkLen + 1), kChunkLen + 1);
3020     }
3021 
3022     // Check the last write was correct. The data will be spread over two
3023     // records, so SSL_read returns twice.
3024     ASSERT_EQ(SSL_read(server_.get(), buf, sizeof(buf)), kChunkLen);
3025     ASSERT_EQ(OPENSSL_memcmp(buf, "hello", kChunkLen), 0);
3026     ASSERT_EQ(SSL_read(server_.get(), buf, sizeof(buf)), 1);
3027     ASSERT_EQ(buf[0], '!');
3028   }
3029 }
3030 
TEST_P(SSLVersionTest,RecordCallback)3031 TEST_P(SSLVersionTest, RecordCallback) {
3032   for (bool test_server : {true, false}) {
3033     SCOPED_TRACE(test_server);
3034     ResetContexts();
3035 
3036     bool read_seen = false;
3037     bool write_seen = false;
3038     auto cb = [&](int is_write, int cb_version, int cb_type, const void *buf,
3039                   size_t len, SSL *ssl) {
3040       if (cb_type != SSL3_RT_HEADER) {
3041         return;
3042       }
3043 
3044       // The callback does not report a version for records.
3045       EXPECT_EQ(0, cb_version);
3046 
3047       if (is_write) {
3048         write_seen = true;
3049       } else {
3050         read_seen = true;
3051       }
3052 
3053       // Sanity-check that the record header is plausible.
3054       CBS cbs;
3055       CBS_init(&cbs, reinterpret_cast<const uint8_t *>(buf), len);
3056       uint8_t type;
3057       uint16_t record_version, length;
3058       ASSERT_TRUE(CBS_get_u8(&cbs, &type));
3059       ASSERT_TRUE(CBS_get_u16(&cbs, &record_version));
3060       EXPECT_EQ(record_version & 0xff00, version() & 0xff00);
3061       if (is_dtls()) {
3062         uint16_t epoch;
3063         ASSERT_TRUE(CBS_get_u16(&cbs, &epoch));
3064         EXPECT_TRUE(epoch == 0 || epoch == 1) << "Invalid epoch: " << epoch;
3065         ASSERT_TRUE(CBS_skip(&cbs, 6));
3066       }
3067       ASSERT_TRUE(CBS_get_u16(&cbs, &length));
3068       EXPECT_EQ(0u, CBS_len(&cbs));
3069     };
3070     using CallbackType = decltype(cb);
3071     SSL_CTX *ctx = test_server ? server_ctx_.get() : client_ctx_.get();
3072     SSL_CTX_set_msg_callback(
3073         ctx, [](int is_write, int cb_version, int cb_type, const void *buf,
3074                 size_t len, SSL *ssl, void *arg) {
3075           CallbackType *cb_ptr = reinterpret_cast<CallbackType *>(arg);
3076           (*cb_ptr)(is_write, cb_version, cb_type, buf, len, ssl);
3077         });
3078     SSL_CTX_set_msg_callback_arg(ctx, &cb);
3079 
3080     ASSERT_TRUE(Connect());
3081 
3082     EXPECT_TRUE(read_seen);
3083     EXPECT_TRUE(write_seen);
3084   }
3085 }
3086 
TEST_P(SSLVersionTest,GetServerName)3087 TEST_P(SSLVersionTest, GetServerName) {
3088   ClientConfig config;
3089   config.servername = "host1";
3090 
3091   SSL_CTX_set_tlsext_servername_callback(
3092       server_ctx_.get(), [](SSL *ssl, int *out_alert, void *arg) -> int {
3093         // During the handshake, |SSL_get_servername| must match |config|.
3094         ClientConfig *config_p = reinterpret_cast<ClientConfig *>(arg);
3095         EXPECT_STREQ(config_p->servername.c_str(),
3096                      SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name));
3097         return SSL_TLSEXT_ERR_OK;
3098       });
3099   SSL_CTX_set_tlsext_servername_arg(server_ctx_.get(), &config);
3100 
3101   ASSERT_TRUE(Connect(config));
3102   // After the handshake, it must also be available.
3103   EXPECT_STREQ(config.servername.c_str(),
3104                SSL_get_servername(server_.get(), TLSEXT_NAMETYPE_host_name));
3105 
3106   // Establish a session under host1.
3107   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
3108   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
3109   bssl::UniquePtr<SSL_SESSION> session =
3110       CreateClientSession(client_ctx_.get(), server_ctx_.get(), config);
3111 
3112   // If the client resumes a session with a different name, |SSL_get_servername|
3113   // must return the new name.
3114   ASSERT_TRUE(session);
3115   config.session = session.get();
3116   config.servername = "host2";
3117   ASSERT_TRUE(Connect(config));
3118   EXPECT_STREQ(config.servername.c_str(),
3119                SSL_get_servername(server_.get(), TLSEXT_NAMETYPE_host_name));
3120 }
3121 
3122 // Test that session cache mode bits are honored in the client session callback.
TEST_P(SSLVersionTest,ClientSessionCacheMode)3123 TEST_P(SSLVersionTest, ClientSessionCacheMode) {
3124   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_OFF);
3125   EXPECT_FALSE(CreateClientSession(client_ctx_.get(), server_ctx_.get()));
3126 
3127   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_CLIENT);
3128   EXPECT_TRUE(CreateClientSession(client_ctx_.get(), server_ctx_.get()));
3129 
3130   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_SERVER);
3131   EXPECT_FALSE(CreateClientSession(client_ctx_.get(), server_ctx_.get()));
3132 }
3133 
3134 // Test that all versions survive tiny write buffers. In particular, TLS 1.3
3135 // NewSessionTickets are written post-handshake. Servers that block
3136 // |SSL_do_handshake| on writing them will deadlock if clients are not draining
3137 // the buffer. Test that we do not do this.
TEST_P(SSLVersionTest,SmallBuffer)3138 TEST_P(SSLVersionTest, SmallBuffer) {
3139   // DTLS is a datagram protocol and requires packet-sized buffers.
3140   if (is_dtls()) {
3141     return;
3142   }
3143 
3144   // Test both flushing NewSessionTickets with a zero-sized write and
3145   // non-zero-sized write.
3146   for (bool use_zero_write : {false, true}) {
3147     SCOPED_TRACE(use_zero_write);
3148 
3149     g_last_session = nullptr;
3150     SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
3151     SSL_CTX_sess_set_new_cb(client_ctx_.get(), SaveLastSession);
3152 
3153     bssl::UniquePtr<SSL> client(SSL_new(client_ctx_.get())),
3154         server(SSL_new(server_ctx_.get()));
3155     ASSERT_TRUE(client);
3156     ASSERT_TRUE(server);
3157     SSL_set_connect_state(client.get());
3158     SSL_set_accept_state(server.get());
3159 
3160     // Use a tiny buffer.
3161     BIO *bio1, *bio2;
3162     ASSERT_TRUE(BIO_new_bio_pair(&bio1, 1, &bio2, 1));
3163 
3164     // SSL_set_bio takes ownership.
3165     SSL_set_bio(client.get(), bio1, bio1);
3166     SSL_set_bio(server.get(), bio2, bio2);
3167 
3168     ASSERT_TRUE(CompleteHandshakes(client.get(), server.get()));
3169     if (version() >= TLS1_3_VERSION) {
3170       // The post-handshake ticket should not have been processed yet.
3171       EXPECT_FALSE(g_last_session);
3172     }
3173 
3174     if (use_zero_write) {
3175       ASSERT_TRUE(FlushNewSessionTickets(client.get(), server.get()));
3176       EXPECT_TRUE(g_last_session);
3177     }
3178 
3179     // Send some data from server to client. If |use_zero_write| is false, this
3180     // will also flush the NewSessionTickets.
3181     static const char kMessage[] = "hello world";
3182     char buf[sizeof(kMessage)];
3183     for (;;) {
3184       int server_ret = SSL_write(server.get(), kMessage, sizeof(kMessage));
3185       int server_err = SSL_get_error(server.get(), server_ret);
3186       int client_ret = SSL_read(client.get(), buf, sizeof(buf));
3187       int client_err = SSL_get_error(client.get(), client_ret);
3188 
3189       // The server will write a single record, so every iteration should see
3190       // |SSL_ERROR_WANT_WRITE| and |SSL_ERROR_WANT_READ|, until the final
3191       // iteration, where both will complete.
3192       if (server_ret > 0) {
3193         EXPECT_EQ(server_ret, static_cast<int>(sizeof(kMessage)));
3194         EXPECT_EQ(client_ret, static_cast<int>(sizeof(kMessage)));
3195         EXPECT_EQ(Bytes(buf), Bytes(kMessage));
3196         break;
3197       }
3198 
3199       ASSERT_EQ(server_ret, -1);
3200       ASSERT_EQ(server_err, SSL_ERROR_WANT_WRITE);
3201       ASSERT_EQ(client_ret, -1);
3202       ASSERT_EQ(client_err, SSL_ERROR_WANT_READ);
3203     }
3204 
3205     // The NewSessionTickets should have been flushed and processed.
3206     EXPECT_TRUE(g_last_session);
3207   }
3208 }
3209 
TEST(SSLTest,AddChainCertHack)3210 TEST(SSLTest, AddChainCertHack) {
3211   // Ensure that we don't accidently break the hack that we have in place to
3212   // keep curl and serf happy when they use an |X509| even after transfering
3213   // ownership.
3214 
3215   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3216   ASSERT_TRUE(ctx);
3217   X509 *cert = GetTestCertificate().release();
3218   ASSERT_TRUE(cert);
3219   SSL_CTX_add0_chain_cert(ctx.get(), cert);
3220 
3221   // This should not trigger a use-after-free.
3222   X509_cmp(cert, cert);
3223 }
3224 
TEST(SSLTest,GetCertificate)3225 TEST(SSLTest, GetCertificate) {
3226   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3227   ASSERT_TRUE(ctx);
3228   bssl::UniquePtr<X509> cert = GetTestCertificate();
3229   ASSERT_TRUE(cert);
3230   ASSERT_TRUE(SSL_CTX_use_certificate(ctx.get(), cert.get()));
3231   bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
3232   ASSERT_TRUE(ssl);
3233 
3234   X509 *cert2 = SSL_CTX_get0_certificate(ctx.get());
3235   ASSERT_TRUE(cert2);
3236   X509 *cert3 = SSL_get_certificate(ssl.get());
3237   ASSERT_TRUE(cert3);
3238 
3239   // The old and new certificates must be identical.
3240   EXPECT_EQ(0, X509_cmp(cert.get(), cert2));
3241   EXPECT_EQ(0, X509_cmp(cert.get(), cert3));
3242 
3243   uint8_t *der = nullptr;
3244   long der_len = i2d_X509(cert.get(), &der);
3245   ASSERT_LT(0, der_len);
3246   bssl::UniquePtr<uint8_t> free_der(der);
3247 
3248   uint8_t *der2 = nullptr;
3249   long der2_len = i2d_X509(cert2, &der2);
3250   ASSERT_LT(0, der2_len);
3251   bssl::UniquePtr<uint8_t> free_der2(der2);
3252 
3253   uint8_t *der3 = nullptr;
3254   long der3_len = i2d_X509(cert3, &der3);
3255   ASSERT_LT(0, der3_len);
3256   bssl::UniquePtr<uint8_t> free_der3(der3);
3257 
3258   // They must also encode identically.
3259   EXPECT_EQ(Bytes(der, der_len), Bytes(der2, der2_len));
3260   EXPECT_EQ(Bytes(der, der_len), Bytes(der3, der3_len));
3261 }
3262 
TEST(SSLTest,SetChainAndKeyMismatch)3263 TEST(SSLTest, SetChainAndKeyMismatch) {
3264   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_with_buffers_method()));
3265   ASSERT_TRUE(ctx);
3266 
3267   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3268   ASSERT_TRUE(key);
3269   bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3270   ASSERT_TRUE(leaf);
3271   std::vector<CRYPTO_BUFFER*> chain = {
3272       leaf.get(),
3273   };
3274 
3275   // Should fail because |GetTestKey| doesn't match the chain-test certificate.
3276   ASSERT_FALSE(SSL_CTX_set_chain_and_key(ctx.get(), &chain[0], chain.size(),
3277                                          key.get(), nullptr));
3278   ERR_clear_error();
3279 }
3280 
TEST(SSLTest,SetChainAndKey)3281 TEST(SSLTest, SetChainAndKey) {
3282   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3283   ASSERT_TRUE(client_ctx);
3284   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3285   ASSERT_TRUE(server_ctx);
3286 
3287   ASSERT_EQ(nullptr, SSL_CTX_get0_chain(server_ctx.get()));
3288 
3289   bssl::UniquePtr<EVP_PKEY> key = GetChainTestKey();
3290   ASSERT_TRUE(key);
3291   bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3292   ASSERT_TRUE(leaf);
3293   bssl::UniquePtr<CRYPTO_BUFFER> intermediate =
3294       GetChainTestIntermediateBuffer();
3295   ASSERT_TRUE(intermediate);
3296   std::vector<CRYPTO_BUFFER*> chain = {
3297       leaf.get(), intermediate.get(),
3298   };
3299   ASSERT_TRUE(SSL_CTX_set_chain_and_key(server_ctx.get(), &chain[0],
3300                                         chain.size(), key.get(), nullptr));
3301 
3302   ASSERT_EQ(chain.size(),
3303             sk_CRYPTO_BUFFER_num(SSL_CTX_get0_chain(server_ctx.get())));
3304 
3305   SSL_CTX_set_custom_verify(
3306       client_ctx.get(), SSL_VERIFY_PEER,
3307       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3308         return ssl_verify_ok;
3309       });
3310 
3311   bssl::UniquePtr<SSL> client, server;
3312   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3313                                      server_ctx.get()));
3314 }
3315 
TEST(SSLTest,BuffersFailWithoutCustomVerify)3316 TEST(SSLTest, BuffersFailWithoutCustomVerify) {
3317   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3318   ASSERT_TRUE(client_ctx);
3319   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3320   ASSERT_TRUE(server_ctx);
3321 
3322   bssl::UniquePtr<EVP_PKEY> key = GetChainTestKey();
3323   ASSERT_TRUE(key);
3324   bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3325   ASSERT_TRUE(leaf);
3326   std::vector<CRYPTO_BUFFER*> chain = { leaf.get() };
3327   ASSERT_TRUE(SSL_CTX_set_chain_and_key(server_ctx.get(), &chain[0],
3328                                         chain.size(), key.get(), nullptr));
3329 
3330   // Without SSL_CTX_set_custom_verify(), i.e. with everything in the default
3331   // configuration, certificate verification should fail.
3332   bssl::UniquePtr<SSL> client, server;
3333   ASSERT_FALSE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3334                                       server_ctx.get()));
3335 
3336   // Whereas with a verifier, the connection should succeed.
3337   SSL_CTX_set_custom_verify(
3338       client_ctx.get(), SSL_VERIFY_PEER,
3339       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3340         return ssl_verify_ok;
3341       });
3342   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3343                                      server_ctx.get()));
3344 }
3345 
TEST(SSLTest,CustomVerify)3346 TEST(SSLTest, CustomVerify) {
3347   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3348   ASSERT_TRUE(client_ctx);
3349   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3350   ASSERT_TRUE(server_ctx);
3351 
3352   bssl::UniquePtr<EVP_PKEY> key = GetChainTestKey();
3353   ASSERT_TRUE(key);
3354   bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3355   ASSERT_TRUE(leaf);
3356   std::vector<CRYPTO_BUFFER*> chain = { leaf.get() };
3357   ASSERT_TRUE(SSL_CTX_set_chain_and_key(server_ctx.get(), &chain[0],
3358                                         chain.size(), key.get(), nullptr));
3359 
3360   SSL_CTX_set_custom_verify(
3361       client_ctx.get(), SSL_VERIFY_PEER,
3362       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3363         return ssl_verify_ok;
3364       });
3365 
3366   bssl::UniquePtr<SSL> client, server;
3367   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3368                                      server_ctx.get()));
3369 
3370   // With SSL_VERIFY_PEER, ssl_verify_invalid should result in a dropped
3371   // connection.
3372   SSL_CTX_set_custom_verify(
3373       client_ctx.get(), SSL_VERIFY_PEER,
3374       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3375         return ssl_verify_invalid;
3376       });
3377 
3378   ASSERT_FALSE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3379                                       server_ctx.get()));
3380 
3381   // But with SSL_VERIFY_NONE, ssl_verify_invalid should not cause a dropped
3382   // connection.
3383   SSL_CTX_set_custom_verify(
3384       client_ctx.get(), SSL_VERIFY_NONE,
3385       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3386         return ssl_verify_invalid;
3387       });
3388 
3389   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3390                                      server_ctx.get()));
3391 }
3392 
TEST(SSLTest,ClientCABuffers)3393 TEST(SSLTest, ClientCABuffers) {
3394   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3395   ASSERT_TRUE(client_ctx);
3396   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_with_buffers_method()));
3397   ASSERT_TRUE(server_ctx);
3398 
3399   bssl::UniquePtr<EVP_PKEY> key = GetChainTestKey();
3400   ASSERT_TRUE(key);
3401   bssl::UniquePtr<CRYPTO_BUFFER> leaf = GetChainTestCertificateBuffer();
3402   ASSERT_TRUE(leaf);
3403   bssl::UniquePtr<CRYPTO_BUFFER> intermediate =
3404       GetChainTestIntermediateBuffer();
3405   ASSERT_TRUE(intermediate);
3406   std::vector<CRYPTO_BUFFER *> chain = {
3407       leaf.get(),
3408       intermediate.get(),
3409   };
3410   ASSERT_TRUE(SSL_CTX_set_chain_and_key(server_ctx.get(), &chain[0],
3411                                         chain.size(), key.get(), nullptr));
3412 
3413   bssl::UniquePtr<CRYPTO_BUFFER> ca_name(
3414       CRYPTO_BUFFER_new(kTestName, sizeof(kTestName), nullptr));
3415   ASSERT_TRUE(ca_name);
3416   bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names(
3417       sk_CRYPTO_BUFFER_new_null());
3418   ASSERT_TRUE(ca_names);
3419   ASSERT_TRUE(PushToStack(ca_names.get(), std::move(ca_name)));
3420   SSL_CTX_set0_client_CAs(server_ctx.get(), ca_names.release());
3421 
3422   // Configure client and server to accept all certificates.
3423   SSL_CTX_set_custom_verify(
3424       client_ctx.get(), SSL_VERIFY_PEER,
3425       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3426         return ssl_verify_ok;
3427       });
3428   SSL_CTX_set_custom_verify(
3429       server_ctx.get(), SSL_VERIFY_PEER,
3430       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
3431         return ssl_verify_ok;
3432       });
3433 
3434   bool cert_cb_called = false;
3435   SSL_CTX_set_cert_cb(
3436       client_ctx.get(),
3437       [](SSL *ssl, void *arg) -> int {
3438         const STACK_OF(CRYPTO_BUFFER) *peer_names =
3439             SSL_get0_server_requested_CAs(ssl);
3440         EXPECT_EQ(1u, sk_CRYPTO_BUFFER_num(peer_names));
3441         CRYPTO_BUFFER *peer_name = sk_CRYPTO_BUFFER_value(peer_names, 0);
3442         EXPECT_EQ(Bytes(kTestName), Bytes(CRYPTO_BUFFER_data(peer_name),
3443                                           CRYPTO_BUFFER_len(peer_name)));
3444         *reinterpret_cast<bool *>(arg) = true;
3445         return 1;
3446       },
3447       &cert_cb_called);
3448 
3449   bssl::UniquePtr<SSL> client, server;
3450   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3451                                      server_ctx.get()));
3452   EXPECT_TRUE(cert_cb_called);
3453 }
3454 
3455 // Configuring the empty cipher list, though an error, should still modify the
3456 // configuration.
TEST(SSLTest,EmptyCipherList)3457 TEST(SSLTest, EmptyCipherList) {
3458   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3459   ASSERT_TRUE(ctx);
3460 
3461   // Initially, the cipher list is not empty.
3462   EXPECT_NE(0u, sk_SSL_CIPHER_num(SSL_CTX_get_ciphers(ctx.get())));
3463 
3464   // Configuring the empty cipher list fails.
3465   EXPECT_FALSE(SSL_CTX_set_cipher_list(ctx.get(), ""));
3466   ERR_clear_error();
3467 
3468   // But the cipher list is still updated to empty.
3469   EXPECT_EQ(0u, sk_SSL_CIPHER_num(SSL_CTX_get_ciphers(ctx.get())));
3470 }
3471 
3472 // ssl_test_ticket_aead_failure_mode enumerates the possible ways in which the
3473 // test |SSL_TICKET_AEAD_METHOD| can fail.
3474 enum ssl_test_ticket_aead_failure_mode {
3475   ssl_test_ticket_aead_ok = 0,
3476   ssl_test_ticket_aead_seal_fail,
3477   ssl_test_ticket_aead_open_soft_fail,
3478   ssl_test_ticket_aead_open_hard_fail,
3479 };
3480 
3481 struct ssl_test_ticket_aead_state {
3482   unsigned retry_count;
3483   ssl_test_ticket_aead_failure_mode failure_mode;
3484 };
3485 
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)3486 static int ssl_test_ticket_aead_ex_index_dup(CRYPTO_EX_DATA *to,
3487                                              const CRYPTO_EX_DATA *from,
3488                                              void **from_d, int index,
3489                                              long argl, void *argp) {
3490   abort();
3491 }
3492 
ssl_test_ticket_aead_ex_index_free(void * parent,void * ptr,CRYPTO_EX_DATA * ad,int index,long argl,void * argp)3493 static void ssl_test_ticket_aead_ex_index_free(void *parent, void *ptr,
3494                                                CRYPTO_EX_DATA *ad, int index,
3495                                                long argl, void *argp) {
3496   auto state = reinterpret_cast<ssl_test_ticket_aead_state*>(ptr);
3497   if (state == nullptr) {
3498     return;
3499   }
3500 
3501   OPENSSL_free(state);
3502 }
3503 
3504 static CRYPTO_once_t g_ssl_test_ticket_aead_ex_index_once = CRYPTO_ONCE_INIT;
3505 static int g_ssl_test_ticket_aead_ex_index;
3506 
ssl_test_ticket_aead_get_ex_index()3507 static int ssl_test_ticket_aead_get_ex_index() {
3508   CRYPTO_once(&g_ssl_test_ticket_aead_ex_index_once, [] {
3509     g_ssl_test_ticket_aead_ex_index = SSL_get_ex_new_index(
3510         0, nullptr, nullptr, ssl_test_ticket_aead_ex_index_dup,
3511         ssl_test_ticket_aead_ex_index_free);
3512   });
3513   return g_ssl_test_ticket_aead_ex_index;
3514 }
3515 
ssl_test_ticket_aead_max_overhead(SSL * ssl)3516 static size_t ssl_test_ticket_aead_max_overhead(SSL *ssl) {
3517   return 1;
3518 }
3519 
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)3520 static int ssl_test_ticket_aead_seal(SSL *ssl, uint8_t *out, size_t *out_len,
3521                                      size_t max_out_len, const uint8_t *in,
3522                                      size_t in_len) {
3523   auto state = reinterpret_cast<ssl_test_ticket_aead_state *>(
3524       SSL_get_ex_data(ssl, ssl_test_ticket_aead_get_ex_index()));
3525 
3526   if (state->failure_mode == ssl_test_ticket_aead_seal_fail ||
3527       max_out_len < in_len + 1) {
3528     return 0;
3529   }
3530 
3531   OPENSSL_memmove(out, in, in_len);
3532   out[in_len] = 0xff;
3533   *out_len = in_len + 1;
3534 
3535   return 1;
3536 }
3537 
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)3538 static ssl_ticket_aead_result_t ssl_test_ticket_aead_open(
3539     SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out_len,
3540     const uint8_t *in, size_t in_len) {
3541   auto state = reinterpret_cast<ssl_test_ticket_aead_state *>(
3542       SSL_get_ex_data(ssl, ssl_test_ticket_aead_get_ex_index()));
3543 
3544   if (state->retry_count > 0) {
3545     state->retry_count--;
3546     return ssl_ticket_aead_retry;
3547   }
3548 
3549   switch (state->failure_mode) {
3550     case ssl_test_ticket_aead_ok:
3551       break;
3552     case ssl_test_ticket_aead_seal_fail:
3553       // If |seal| failed then there shouldn't be any ticket to try and
3554       // decrypt.
3555       abort();
3556       break;
3557     case ssl_test_ticket_aead_open_soft_fail:
3558       return ssl_ticket_aead_ignore_ticket;
3559     case ssl_test_ticket_aead_open_hard_fail:
3560       return ssl_ticket_aead_error;
3561   }
3562 
3563   if (in_len == 0 || in[in_len - 1] != 0xff) {
3564     return ssl_ticket_aead_ignore_ticket;
3565   }
3566 
3567   if (max_out_len < in_len - 1) {
3568     return ssl_ticket_aead_error;
3569   }
3570 
3571   OPENSSL_memmove(out, in, in_len - 1);
3572   *out_len = in_len - 1;
3573   return ssl_ticket_aead_success;
3574 }
3575 
3576 static const SSL_TICKET_AEAD_METHOD kSSLTestTicketMethod = {
3577   ssl_test_ticket_aead_max_overhead,
3578   ssl_test_ticket_aead_seal,
3579   ssl_test_ticket_aead_open,
3580 };
3581 
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)3582 static void ConnectClientAndServerWithTicketMethod(
3583     bssl::UniquePtr<SSL> *out_client, bssl::UniquePtr<SSL> *out_server,
3584     SSL_CTX *client_ctx, SSL_CTX *server_ctx, unsigned retry_count,
3585     ssl_test_ticket_aead_failure_mode failure_mode, SSL_SESSION *session) {
3586   bssl::UniquePtr<SSL> client(SSL_new(client_ctx)), server(SSL_new(server_ctx));
3587   ASSERT_TRUE(client);
3588   ASSERT_TRUE(server);
3589   SSL_set_connect_state(client.get());
3590   SSL_set_accept_state(server.get());
3591 
3592   auto state = reinterpret_cast<ssl_test_ticket_aead_state *>(
3593       OPENSSL_malloc(sizeof(ssl_test_ticket_aead_state)));
3594   ASSERT_TRUE(state);
3595   OPENSSL_memset(state, 0, sizeof(ssl_test_ticket_aead_state));
3596   state->retry_count = retry_count;
3597   state->failure_mode = failure_mode;
3598 
3599   ASSERT_TRUE(SSL_set_ex_data(server.get(), ssl_test_ticket_aead_get_ex_index(),
3600                               state));
3601 
3602   SSL_set_session(client.get(), session);
3603 
3604   BIO *bio1, *bio2;
3605   ASSERT_TRUE(BIO_new_bio_pair(&bio1, 0, &bio2, 0));
3606 
3607   // SSL_set_bio takes ownership.
3608   SSL_set_bio(client.get(), bio1, bio1);
3609   SSL_set_bio(server.get(), bio2, bio2);
3610 
3611   if (CompleteHandshakes(client.get(), server.get())) {
3612     *out_client = std::move(client);
3613     *out_server = std::move(server);
3614   } else {
3615     out_client->reset();
3616     out_server->reset();
3617   }
3618 }
3619 
3620 using TicketAEADMethodParam =
3621     testing::tuple<uint16_t, unsigned, ssl_test_ticket_aead_failure_mode>;
3622 
3623 class TicketAEADMethodTest
3624     : public ::testing::TestWithParam<TicketAEADMethodParam> {};
3625 
TEST_P(TicketAEADMethodTest,Resume)3626 TEST_P(TicketAEADMethodTest, Resume) {
3627   bssl::UniquePtr<X509> cert = GetTestCertificate();
3628   ASSERT_TRUE(cert);
3629   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3630   ASSERT_TRUE(key);
3631 
3632   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
3633   ASSERT_TRUE(server_ctx);
3634   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
3635   ASSERT_TRUE(client_ctx);
3636 
3637   const uint16_t version = testing::get<0>(GetParam());
3638   const unsigned retry_count = testing::get<1>(GetParam());
3639   const ssl_test_ticket_aead_failure_mode failure_mode =
3640       testing::get<2>(GetParam());
3641 
3642   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3643   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3644   ASSERT_TRUE(SSL_CTX_set_min_proto_version(client_ctx.get(), version));
3645   ASSERT_TRUE(SSL_CTX_set_max_proto_version(client_ctx.get(), version));
3646   ASSERT_TRUE(SSL_CTX_set_min_proto_version(server_ctx.get(), version));
3647   ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), version));
3648 
3649   SSL_CTX_set_session_cache_mode(client_ctx.get(), SSL_SESS_CACHE_BOTH);
3650   SSL_CTX_set_session_cache_mode(server_ctx.get(), SSL_SESS_CACHE_BOTH);
3651   SSL_CTX_set_current_time_cb(client_ctx.get(), FrozenTimeCallback);
3652   SSL_CTX_set_current_time_cb(server_ctx.get(), FrozenTimeCallback);
3653   SSL_CTX_sess_set_new_cb(client_ctx.get(), SaveLastSession);
3654 
3655   SSL_CTX_set_ticket_aead_method(server_ctx.get(), &kSSLTestTicketMethod);
3656 
3657   bssl::UniquePtr<SSL> client, server;
3658   ConnectClientAndServerWithTicketMethod(&client, &server, client_ctx.get(),
3659                                          server_ctx.get(), retry_count,
3660                                          failure_mode, nullptr);
3661   switch (failure_mode) {
3662     case ssl_test_ticket_aead_ok:
3663     case ssl_test_ticket_aead_open_hard_fail:
3664     case ssl_test_ticket_aead_open_soft_fail:
3665       ASSERT_TRUE(client);
3666       break;
3667     case ssl_test_ticket_aead_seal_fail:
3668       EXPECT_FALSE(client);
3669       return;
3670   }
3671   EXPECT_FALSE(SSL_session_reused(client.get()));
3672   EXPECT_FALSE(SSL_session_reused(server.get()));
3673 
3674   ASSERT_TRUE(FlushNewSessionTickets(client.get(), server.get()));
3675   bssl::UniquePtr<SSL_SESSION> session = std::move(g_last_session);
3676   ConnectClientAndServerWithTicketMethod(&client, &server, client_ctx.get(),
3677                                          server_ctx.get(), retry_count,
3678                                          failure_mode, session.get());
3679   switch (failure_mode) {
3680     case ssl_test_ticket_aead_ok:
3681       ASSERT_TRUE(client);
3682       EXPECT_TRUE(SSL_session_reused(client.get()));
3683       EXPECT_TRUE(SSL_session_reused(server.get()));
3684       break;
3685     case ssl_test_ticket_aead_seal_fail:
3686       abort();
3687       break;
3688     case ssl_test_ticket_aead_open_hard_fail:
3689       EXPECT_FALSE(client);
3690       break;
3691     case ssl_test_ticket_aead_open_soft_fail:
3692       ASSERT_TRUE(client);
3693       EXPECT_FALSE(SSL_session_reused(client.get()));
3694       EXPECT_FALSE(SSL_session_reused(server.get()));
3695   }
3696 }
3697 
TicketAEADMethodParamToString(const testing::TestParamInfo<TicketAEADMethodParam> & params)3698 std::string TicketAEADMethodParamToString(
3699     const testing::TestParamInfo<TicketAEADMethodParam> &params) {
3700   std::string ret = GetVersionName(std::get<0>(params.param));
3701   // GTest only allows alphanumeric characters and '_' in the parameter
3702   // string. Additionally filter out the 'v' to get "TLS13" over "TLSv13".
3703   for (auto it = ret.begin(); it != ret.end();) {
3704     if (*it == '.' || *it == 'v') {
3705       it = ret.erase(it);
3706     } else {
3707       ++it;
3708     }
3709   }
3710   char retry_count[256];
3711   snprintf(retry_count, sizeof(retry_count), "%d", std::get<1>(params.param));
3712   ret += "_";
3713   ret += retry_count;
3714   ret += "Retries_";
3715   switch (std::get<2>(params.param)) {
3716     case ssl_test_ticket_aead_ok:
3717       ret += "OK";
3718       break;
3719     case ssl_test_ticket_aead_seal_fail:
3720       ret += "SealFail";
3721       break;
3722     case ssl_test_ticket_aead_open_soft_fail:
3723       ret += "OpenSoftFail";
3724       break;
3725     case ssl_test_ticket_aead_open_hard_fail:
3726       ret += "OpenHardFail";
3727       break;
3728   }
3729   return ret;
3730 }
3731 
3732 INSTANTIATE_TEST_SUITE_P(
3733     TicketAEADMethodTests, TicketAEADMethodTest,
3734     testing::Combine(testing::Values(TLS1_2_VERSION, TLS1_3_VERSION),
3735                      testing::Values(0, 1, 2),
3736                      testing::Values(ssl_test_ticket_aead_ok,
3737                                      ssl_test_ticket_aead_seal_fail,
3738                                      ssl_test_ticket_aead_open_soft_fail,
3739                                      ssl_test_ticket_aead_open_hard_fail)),
3740     TicketAEADMethodParamToString);
3741 
TEST(SSLTest,SelectNextProto)3742 TEST(SSLTest, SelectNextProto) {
3743   uint8_t *result;
3744   uint8_t result_len;
3745 
3746   // If there is an overlap, it should be returned.
3747   EXPECT_EQ(OPENSSL_NPN_NEGOTIATED,
3748             SSL_select_next_proto(&result, &result_len,
3749                                   (const uint8_t *)"\1a\2bb\3ccc", 9,
3750                                   (const uint8_t *)"\1x\1y\1a\1z", 8));
3751   EXPECT_EQ(Bytes("a"), Bytes(result, result_len));
3752 
3753   EXPECT_EQ(OPENSSL_NPN_NEGOTIATED,
3754             SSL_select_next_proto(&result, &result_len,
3755                                   (const uint8_t *)"\1a\2bb\3ccc", 9,
3756                                   (const uint8_t *)"\1x\1y\2bb\1z", 9));
3757   EXPECT_EQ(Bytes("bb"), Bytes(result, result_len));
3758 
3759   EXPECT_EQ(OPENSSL_NPN_NEGOTIATED,
3760             SSL_select_next_proto(&result, &result_len,
3761                                   (const uint8_t *)"\1a\2bb\3ccc", 9,
3762                                   (const uint8_t *)"\1x\1y\3ccc\1z", 10));
3763   EXPECT_EQ(Bytes("ccc"), Bytes(result, result_len));
3764 
3765   // Peer preference order takes precedence over local.
3766   EXPECT_EQ(OPENSSL_NPN_NEGOTIATED,
3767             SSL_select_next_proto(&result, &result_len,
3768                                   (const uint8_t *)"\1a\2bb\3ccc", 9,
3769                                   (const uint8_t *)"\3ccc\2bb\1a", 9));
3770   EXPECT_EQ(Bytes("a"), Bytes(result, result_len));
3771 
3772   // If there is no overlap, return the first local protocol.
3773   EXPECT_EQ(OPENSSL_NPN_NO_OVERLAP,
3774             SSL_select_next_proto(&result, &result_len,
3775                                   (const uint8_t *)"\1a\2bb\3ccc", 9,
3776                                   (const uint8_t *)"\1x\2yy\3zzz", 9));
3777   EXPECT_EQ(Bytes("x"), Bytes(result, result_len));
3778 
3779   EXPECT_EQ(OPENSSL_NPN_NO_OVERLAP,
3780             SSL_select_next_proto(&result, &result_len, nullptr, 0,
3781                                   (const uint8_t *)"\1x\2yy\3zzz", 9));
3782   EXPECT_EQ(Bytes("x"), Bytes(result, result_len));
3783 }
3784 
TEST(SSLTest,SealRecord)3785 TEST(SSLTest, SealRecord) {
3786   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLSv1_2_method())),
3787       server_ctx(SSL_CTX_new(TLSv1_2_method()));
3788   ASSERT_TRUE(client_ctx);
3789   ASSERT_TRUE(server_ctx);
3790 
3791   bssl::UniquePtr<X509> cert = GetTestCertificate();
3792   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3793   ASSERT_TRUE(cert);
3794   ASSERT_TRUE(key);
3795   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3796   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3797 
3798   bssl::UniquePtr<SSL> client, server;
3799   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3800                                      server_ctx.get()));
3801 
3802   const std::vector<uint8_t> record = {1, 2, 3, 4, 5};
3803   std::vector<uint8_t> prefix(
3804       bssl::SealRecordPrefixLen(client.get(), record.size())),
3805       body(record.size()),
3806       suffix(bssl::SealRecordSuffixLen(client.get(), record.size()));
3807   ASSERT_TRUE(bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3808                                bssl::MakeSpan(body), bssl::MakeSpan(suffix),
3809                                record));
3810 
3811   std::vector<uint8_t> sealed;
3812   sealed.insert(sealed.end(), prefix.begin(), prefix.end());
3813   sealed.insert(sealed.end(), body.begin(), body.end());
3814   sealed.insert(sealed.end(), suffix.begin(), suffix.end());
3815   std::vector<uint8_t> sealed_copy = sealed;
3816 
3817   bssl::Span<uint8_t> plaintext;
3818   size_t record_len;
3819   uint8_t alert = 255;
3820   EXPECT_EQ(bssl::OpenRecord(server.get(), &plaintext, &record_len, &alert,
3821                              bssl::MakeSpan(sealed)),
3822             bssl::OpenRecordResult::kOK);
3823   EXPECT_EQ(record_len, sealed.size());
3824   EXPECT_EQ(plaintext, record);
3825   EXPECT_EQ(255, alert);
3826 }
3827 
TEST(SSLTest,SealRecordInPlace)3828 TEST(SSLTest, SealRecordInPlace) {
3829   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLSv1_2_method())),
3830       server_ctx(SSL_CTX_new(TLSv1_2_method()));
3831   ASSERT_TRUE(client_ctx);
3832   ASSERT_TRUE(server_ctx);
3833 
3834   bssl::UniquePtr<X509> cert = GetTestCertificate();
3835   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3836   ASSERT_TRUE(cert);
3837   ASSERT_TRUE(key);
3838   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3839   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3840 
3841   bssl::UniquePtr<SSL> client, server;
3842   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3843                                      server_ctx.get()));
3844 
3845   const std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5};
3846   std::vector<uint8_t> record = plaintext;
3847   std::vector<uint8_t> prefix(
3848       bssl::SealRecordPrefixLen(client.get(), record.size())),
3849       suffix(bssl::SealRecordSuffixLen(client.get(), record.size()));
3850   ASSERT_TRUE(bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3851                                bssl::MakeSpan(record), bssl::MakeSpan(suffix),
3852                                record));
3853   record.insert(record.begin(), prefix.begin(), prefix.end());
3854   record.insert(record.end(), suffix.begin(), suffix.end());
3855 
3856   bssl::Span<uint8_t> result;
3857   size_t record_len;
3858   uint8_t alert;
3859   EXPECT_EQ(bssl::OpenRecord(server.get(), &result, &record_len, &alert,
3860                              bssl::MakeSpan(record)),
3861             bssl::OpenRecordResult::kOK);
3862   EXPECT_EQ(record_len, record.size());
3863   EXPECT_EQ(plaintext, result);
3864 }
3865 
TEST(SSLTest,SealRecordTrailingData)3866 TEST(SSLTest, SealRecordTrailingData) {
3867   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLSv1_2_method())),
3868       server_ctx(SSL_CTX_new(TLSv1_2_method()));
3869   ASSERT_TRUE(client_ctx);
3870   ASSERT_TRUE(server_ctx);
3871 
3872   bssl::UniquePtr<X509> cert = GetTestCertificate();
3873   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3874   ASSERT_TRUE(cert);
3875   ASSERT_TRUE(key);
3876   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3877   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3878 
3879   bssl::UniquePtr<SSL> client, server;
3880   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3881                                      server_ctx.get()));
3882 
3883   const std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5};
3884   std::vector<uint8_t> record = plaintext;
3885   std::vector<uint8_t> prefix(
3886       bssl::SealRecordPrefixLen(client.get(), record.size())),
3887       suffix(bssl::SealRecordSuffixLen(client.get(), record.size()));
3888   ASSERT_TRUE(bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3889                                bssl::MakeSpan(record), bssl::MakeSpan(suffix),
3890                                record));
3891   record.insert(record.begin(), prefix.begin(), prefix.end());
3892   record.insert(record.end(), suffix.begin(), suffix.end());
3893   record.insert(record.end(), {5, 4, 3, 2, 1});
3894 
3895   bssl::Span<uint8_t> result;
3896   size_t record_len;
3897   uint8_t alert;
3898   EXPECT_EQ(bssl::OpenRecord(server.get(), &result, &record_len, &alert,
3899                              bssl::MakeSpan(record)),
3900             bssl::OpenRecordResult::kOK);
3901   EXPECT_EQ(record_len, record.size() - 5);
3902   EXPECT_EQ(plaintext, result);
3903 }
3904 
TEST(SSLTest,SealRecordInvalidSpanSize)3905 TEST(SSLTest, SealRecordInvalidSpanSize) {
3906   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLSv1_2_method())),
3907       server_ctx(SSL_CTX_new(TLSv1_2_method()));
3908   ASSERT_TRUE(client_ctx);
3909   ASSERT_TRUE(server_ctx);
3910 
3911   bssl::UniquePtr<X509> cert = GetTestCertificate();
3912   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
3913   ASSERT_TRUE(cert);
3914   ASSERT_TRUE(key);
3915   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
3916   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
3917 
3918   bssl::UniquePtr<SSL> client, server;
3919   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
3920                                      server_ctx.get()));
3921 
3922   std::vector<uint8_t> record = {1, 2, 3, 4, 5};
3923   std::vector<uint8_t> prefix(
3924       bssl::SealRecordPrefixLen(client.get(), record.size())),
3925       body(record.size()),
3926       suffix(bssl::SealRecordSuffixLen(client.get(), record.size()));
3927 
3928   auto expect_err = []() {
3929     int err = ERR_get_error();
3930     EXPECT_EQ(ERR_GET_LIB(err), ERR_LIB_SSL);
3931     EXPECT_EQ(ERR_GET_REASON(err), SSL_R_BUFFER_TOO_SMALL);
3932     ERR_clear_error();
3933   };
3934   EXPECT_FALSE(bssl::SealRecord(
3935       client.get(), bssl::MakeSpan(prefix.data(), prefix.size() - 1),
3936       bssl::MakeSpan(record), bssl::MakeSpan(suffix), record));
3937   expect_err();
3938   EXPECT_FALSE(bssl::SealRecord(
3939       client.get(), bssl::MakeSpan(prefix.data(), prefix.size() + 1),
3940       bssl::MakeSpan(record), bssl::MakeSpan(suffix), record));
3941   expect_err();
3942 
3943   EXPECT_FALSE(
3944       bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3945                        bssl::MakeSpan(record.data(), record.size() - 1),
3946                        bssl::MakeSpan(suffix), record));
3947   expect_err();
3948   EXPECT_FALSE(
3949       bssl::SealRecord(client.get(), bssl::MakeSpan(prefix),
3950                        bssl::MakeSpan(record.data(), record.size() + 1),
3951                        bssl::MakeSpan(suffix), record));
3952   expect_err();
3953 
3954   EXPECT_FALSE(bssl::SealRecord(
3955       client.get(), bssl::MakeSpan(prefix), bssl::MakeSpan(record),
3956       bssl::MakeSpan(suffix.data(), suffix.size() - 1), record));
3957   expect_err();
3958   EXPECT_FALSE(bssl::SealRecord(
3959       client.get(), bssl::MakeSpan(prefix), bssl::MakeSpan(record),
3960       bssl::MakeSpan(suffix.data(), suffix.size() + 1), record));
3961   expect_err();
3962 }
3963 
3964 // The client should gracefully handle no suitable ciphers being enabled.
TEST(SSLTest,NoCiphersAvailable)3965 TEST(SSLTest, NoCiphersAvailable) {
3966   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
3967   ASSERT_TRUE(ctx);
3968 
3969   // Configure |client_ctx| with a cipher list that does not intersect with its
3970   // version configuration.
3971   ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(
3972       ctx.get(), "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"));
3973   ASSERT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_1_VERSION));
3974 
3975   bssl::UniquePtr<SSL> ssl(SSL_new(ctx.get()));
3976   ASSERT_TRUE(ssl);
3977   SSL_set_connect_state(ssl.get());
3978 
3979   UniquePtr<BIO> rbio(BIO_new(BIO_s_mem())), wbio(BIO_new(BIO_s_mem()));
3980   ASSERT_TRUE(rbio);
3981   ASSERT_TRUE(wbio);
3982   SSL_set0_rbio(ssl.get(), rbio.release());
3983   SSL_set0_wbio(ssl.get(), wbio.release());
3984 
3985   int ret = SSL_do_handshake(ssl.get());
3986   EXPECT_EQ(-1, ret);
3987   EXPECT_EQ(SSL_ERROR_SSL, SSL_get_error(ssl.get(), ret));
3988   uint32_t err = ERR_get_error();
3989   EXPECT_EQ(ERR_LIB_SSL, ERR_GET_LIB(err));
3990   EXPECT_EQ(SSL_R_NO_CIPHERS_AVAILABLE, ERR_GET_REASON(err));
3991 }
3992 
TEST_P(SSLVersionTest,SessionVersion)3993 TEST_P(SSLVersionTest, SessionVersion) {
3994   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
3995   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
3996 
3997   bssl::UniquePtr<SSL_SESSION> session =
3998       CreateClientSession(client_ctx_.get(), server_ctx_.get());
3999   ASSERT_TRUE(session);
4000   EXPECT_EQ(version(), SSL_SESSION_get_protocol_version(session.get()));
4001 
4002   // Sessions in TLS 1.3 and later should be single-use.
4003   EXPECT_EQ(version() == TLS1_3_VERSION,
4004             !!SSL_SESSION_should_be_single_use(session.get()));
4005 
4006   // Making fake sessions for testing works.
4007   session.reset(SSL_SESSION_new(client_ctx_.get()));
4008   ASSERT_TRUE(session);
4009   ASSERT_TRUE(SSL_SESSION_set_protocol_version(session.get(), version()));
4010   EXPECT_EQ(version(), SSL_SESSION_get_protocol_version(session.get()));
4011 }
4012 
TEST_P(SSLVersionTest,SSLPending)4013 TEST_P(SSLVersionTest, SSLPending) {
4014   UniquePtr<SSL> ssl(SSL_new(client_ctx_.get()));
4015   ASSERT_TRUE(ssl);
4016   EXPECT_EQ(0, SSL_pending(ssl.get()));
4017 
4018   ASSERT_TRUE(Connect());
4019   EXPECT_EQ(0, SSL_pending(client_.get()));
4020 
4021   ASSERT_EQ(5, SSL_write(server_.get(), "hello", 5));
4022   ASSERT_EQ(5, SSL_write(server_.get(), "world", 5));
4023   EXPECT_EQ(0, SSL_pending(client_.get()));
4024 
4025   char buf[10];
4026   ASSERT_EQ(1, SSL_peek(client_.get(), buf, 1));
4027   EXPECT_EQ(5, SSL_pending(client_.get()));
4028 
4029   ASSERT_EQ(1, SSL_read(client_.get(), buf, 1));
4030   EXPECT_EQ(4, SSL_pending(client_.get()));
4031 
4032   ASSERT_EQ(4, SSL_read(client_.get(), buf, 10));
4033   EXPECT_EQ(0, SSL_pending(client_.get()));
4034 
4035   ASSERT_EQ(2, SSL_read(client_.get(), buf, 2));
4036   EXPECT_EQ(3, SSL_pending(client_.get()));
4037 }
4038 
4039 // Test that post-handshake tickets consumed by |SSL_shutdown| are ignored.
TEST(SSLTest,ShutdownIgnoresTickets)4040 TEST(SSLTest, ShutdownIgnoresTickets) {
4041   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
4042   ASSERT_TRUE(ctx);
4043   ASSERT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_3_VERSION));
4044   ASSERT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_3_VERSION));
4045 
4046   bssl::UniquePtr<X509> cert = GetTestCertificate();
4047   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
4048   ASSERT_TRUE(cert);
4049   ASSERT_TRUE(key);
4050   ASSERT_TRUE(SSL_CTX_use_certificate(ctx.get(), cert.get()));
4051   ASSERT_TRUE(SSL_CTX_use_PrivateKey(ctx.get(), key.get()));
4052 
4053   SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_BOTH);
4054 
4055   bssl::UniquePtr<SSL> client, server;
4056   ASSERT_TRUE(ConnectClientAndServer(&client, &server, ctx.get(), ctx.get()));
4057 
4058   SSL_CTX_sess_set_new_cb(ctx.get(), [](SSL *ssl, SSL_SESSION *session) -> int {
4059     ADD_FAILURE() << "New session callback called during SSL_shutdown";
4060     return 0;
4061   });
4062 
4063   // Send close_notify.
4064   EXPECT_EQ(0, SSL_shutdown(server.get()));
4065   EXPECT_EQ(0, SSL_shutdown(client.get()));
4066 
4067   // Receive close_notify.
4068   EXPECT_EQ(1, SSL_shutdown(server.get()));
4069   EXPECT_EQ(1, SSL_shutdown(client.get()));
4070 }
4071 
TEST(SSLTest,SignatureAlgorithmProperties)4072 TEST(SSLTest, SignatureAlgorithmProperties) {
4073   EXPECT_EQ(EVP_PKEY_NONE, SSL_get_signature_algorithm_key_type(0x1234));
4074   EXPECT_EQ(nullptr, SSL_get_signature_algorithm_digest(0x1234));
4075   EXPECT_FALSE(SSL_is_signature_algorithm_rsa_pss(0x1234));
4076 
4077   EXPECT_EQ(EVP_PKEY_RSA,
4078             SSL_get_signature_algorithm_key_type(SSL_SIGN_RSA_PKCS1_MD5_SHA1));
4079   EXPECT_EQ(EVP_md5_sha1(),
4080             SSL_get_signature_algorithm_digest(SSL_SIGN_RSA_PKCS1_MD5_SHA1));
4081   EXPECT_FALSE(SSL_is_signature_algorithm_rsa_pss(SSL_SIGN_RSA_PKCS1_MD5_SHA1));
4082 
4083   EXPECT_EQ(EVP_PKEY_EC, SSL_get_signature_algorithm_key_type(
4084                              SSL_SIGN_ECDSA_SECP256R1_SHA256));
4085   EXPECT_EQ(EVP_sha256(), SSL_get_signature_algorithm_digest(
4086                               SSL_SIGN_ECDSA_SECP256R1_SHA256));
4087   EXPECT_FALSE(
4088       SSL_is_signature_algorithm_rsa_pss(SSL_SIGN_ECDSA_SECP256R1_SHA256));
4089 
4090   EXPECT_EQ(EVP_PKEY_RSA,
4091             SSL_get_signature_algorithm_key_type(SSL_SIGN_RSA_PSS_RSAE_SHA384));
4092   EXPECT_EQ(EVP_sha384(),
4093             SSL_get_signature_algorithm_digest(SSL_SIGN_RSA_PSS_RSAE_SHA384));
4094   EXPECT_TRUE(SSL_is_signature_algorithm_rsa_pss(SSL_SIGN_RSA_PSS_RSAE_SHA384));
4095 }
4096 
XORCompressFunc(SSL * ssl,CBB * out,const uint8_t * in,size_t in_len)4097 static int XORCompressFunc(SSL *ssl, CBB *out, const uint8_t *in,
4098                            size_t in_len) {
4099   for (size_t i = 0; i < in_len; i++) {
4100     if (!CBB_add_u8(out, in[i] ^ 0x55)) {
4101       return 0;
4102     }
4103   }
4104 
4105   SSL_set_app_data(ssl, XORCompressFunc);
4106 
4107   return 1;
4108 }
4109 
XORDecompressFunc(SSL * ssl,CRYPTO_BUFFER ** out,size_t uncompressed_len,const uint8_t * in,size_t in_len)4110 static int XORDecompressFunc(SSL *ssl, CRYPTO_BUFFER **out,
4111                              size_t uncompressed_len, const uint8_t *in,
4112                              size_t in_len) {
4113   if (in_len != uncompressed_len) {
4114     return 0;
4115   }
4116 
4117   uint8_t *data;
4118   *out = CRYPTO_BUFFER_alloc(&data, uncompressed_len);
4119   if (*out == nullptr) {
4120     return 0;
4121   }
4122 
4123   for (size_t i = 0; i < in_len; i++) {
4124     data[i] = in[i] ^ 0x55;
4125   }
4126 
4127   SSL_set_app_data(ssl, XORDecompressFunc);
4128 
4129   return 1;
4130 }
4131 
TEST(SSLTest,CertCompression)4132 TEST(SSLTest, CertCompression) {
4133   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
4134   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
4135   ASSERT_TRUE(client_ctx);
4136   ASSERT_TRUE(server_ctx);
4137 
4138   bssl::UniquePtr<X509> cert = GetTestCertificate();
4139   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
4140   ASSERT_TRUE(cert);
4141   ASSERT_TRUE(key);
4142   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
4143   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
4144 
4145   ASSERT_TRUE(SSL_CTX_set_max_proto_version(client_ctx.get(), TLS1_3_VERSION));
4146   ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), TLS1_3_VERSION));
4147   ASSERT_TRUE(SSL_CTX_add_cert_compression_alg(
4148       client_ctx.get(), 0x1234, XORCompressFunc, XORDecompressFunc));
4149   ASSERT_TRUE(SSL_CTX_add_cert_compression_alg(
4150       server_ctx.get(), 0x1234, XORCompressFunc, XORDecompressFunc));
4151 
4152   bssl::UniquePtr<SSL> client, server;
4153   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
4154                                      server_ctx.get()));
4155 
4156   EXPECT_TRUE(SSL_get_app_data(client.get()) == XORDecompressFunc);
4157   EXPECT_TRUE(SSL_get_app_data(server.get()) == XORCompressFunc);
4158 }
4159 
MoveBIOs(SSL * dest,SSL * src)4160 void MoveBIOs(SSL *dest, SSL *src) {
4161   BIO *rbio = SSL_get_rbio(src);
4162   BIO_up_ref(rbio);
4163   SSL_set0_rbio(dest, rbio);
4164 
4165   BIO *wbio = SSL_get_wbio(src);
4166   BIO_up_ref(wbio);
4167   SSL_set0_wbio(dest, wbio);
4168 
4169   SSL_set0_rbio(src, nullptr);
4170   SSL_set0_wbio(src, nullptr);
4171 }
4172 
TEST(SSLTest,Handoff)4173 TEST(SSLTest, Handoff) {
4174   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
4175   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
4176   bssl::UniquePtr<SSL_CTX> handshaker_ctx(SSL_CTX_new(TLS_method()));
4177   ASSERT_TRUE(client_ctx);
4178   ASSERT_TRUE(server_ctx);
4179   ASSERT_TRUE(handshaker_ctx);
4180 
4181   SSL_CTX_set_session_cache_mode(client_ctx.get(), SSL_SESS_CACHE_CLIENT);
4182   SSL_CTX_sess_set_new_cb(client_ctx.get(), SaveLastSession);
4183   SSL_CTX_set_handoff_mode(server_ctx.get(), 1);
4184   uint8_t keys[48];
4185   SSL_CTX_get_tlsext_ticket_keys(server_ctx.get(), &keys, sizeof(keys));
4186   SSL_CTX_set_tlsext_ticket_keys(handshaker_ctx.get(), &keys, sizeof(keys));
4187 
4188   bssl::UniquePtr<X509> cert = GetTestCertificate();
4189   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
4190   ASSERT_TRUE(cert);
4191   ASSERT_TRUE(key);
4192   ASSERT_TRUE(SSL_CTX_use_certificate(handshaker_ctx.get(), cert.get()));
4193   ASSERT_TRUE(SSL_CTX_use_PrivateKey(handshaker_ctx.get(), key.get()));
4194 
4195   for (bool early_data : {false, true}) {
4196     SCOPED_TRACE(early_data);
4197     for (bool is_resume : {false, true}) {
4198       SCOPED_TRACE(is_resume);
4199       bssl::UniquePtr<SSL> client, server;
4200       auto config = ClientConfig();
4201       config.early_data = early_data;
4202       if (is_resume) {
4203         ASSERT_TRUE(g_last_session);
4204         config.session = g_last_session.get();
4205       }
4206       if (is_resume && config.early_data) {
4207         EXPECT_GT(g_last_session->ticket_max_early_data, 0u);
4208       }
4209       ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
4210                                          server_ctx.get(), config,
4211                                          false /* don't handshake */));
4212 
4213       int client_ret = SSL_do_handshake(client.get());
4214       int client_err = SSL_get_error(client.get(), client_ret);
4215 
4216       uint8_t byte_written;
4217       if (config.early_data && is_resume) {
4218         ASSERT_EQ(client_err, 0);
4219         EXPECT_TRUE(SSL_in_early_data(client.get()));
4220         // Attempt to write early data.
4221         byte_written = 43;
4222         EXPECT_EQ(SSL_write(client.get(), &byte_written, 1), 1);
4223       } else {
4224         ASSERT_EQ(client_err, SSL_ERROR_WANT_READ);
4225       }
4226 
4227       int server_ret = SSL_do_handshake(server.get());
4228       int server_err = SSL_get_error(server.get(), server_ret);
4229       ASSERT_EQ(server_err, SSL_ERROR_HANDOFF);
4230 
4231       ScopedCBB cbb;
4232       Array<uint8_t> handoff;
4233       SSL_CLIENT_HELLO hello;
4234       ASSERT_TRUE(CBB_init(cbb.get(), 256));
4235       ASSERT_TRUE(SSL_serialize_handoff(server.get(), cbb.get(), &hello));
4236       ASSERT_TRUE(CBBFinishArray(cbb.get(), &handoff));
4237 
4238       bssl::UniquePtr<SSL> handshaker(SSL_new(handshaker_ctx.get()));
4239       // Note split handshakes determines 0-RTT support, for both the current
4240       // handshake and newly-issued tickets, entirely by |handshaker|. There is
4241       // no need to call |SSL_set_early_data_enabled| on |server|.
4242       SSL_set_early_data_enabled(handshaker.get(), 1);
4243       ASSERT_TRUE(SSL_apply_handoff(handshaker.get(), handoff));
4244 
4245       MoveBIOs(handshaker.get(), server.get());
4246 
4247       int handshake_ret = SSL_do_handshake(handshaker.get());
4248       int handshake_err = SSL_get_error(handshaker.get(), handshake_ret);
4249       ASSERT_EQ(handshake_err, SSL_ERROR_HANDBACK);
4250 
4251       // Double-check that additional calls to |SSL_do_handshake| continue
4252       // to get |SSL_ERROR_HANDBACK|.
4253       handshake_ret = SSL_do_handshake(handshaker.get());
4254       handshake_err = SSL_get_error(handshaker.get(), handshake_ret);
4255       ASSERT_EQ(handshake_err, SSL_ERROR_HANDBACK);
4256 
4257       ScopedCBB cbb_handback;
4258       Array<uint8_t> handback;
4259       ASSERT_TRUE(CBB_init(cbb_handback.get(), 1024));
4260       ASSERT_TRUE(SSL_serialize_handback(handshaker.get(), cbb_handback.get()));
4261       ASSERT_TRUE(CBBFinishArray(cbb_handback.get(), &handback));
4262 
4263       bssl::UniquePtr<SSL> server2(SSL_new(server_ctx.get()));
4264       ASSERT_TRUE(SSL_apply_handback(server2.get(), handback));
4265 
4266       MoveBIOs(server2.get(), handshaker.get());
4267       ASSERT_TRUE(CompleteHandshakes(client.get(), server2.get()));
4268       EXPECT_EQ(is_resume, SSL_session_reused(client.get()));
4269 
4270       if (config.early_data && is_resume) {
4271         // In this case, one byte of early data has already been written above.
4272         EXPECT_TRUE(SSL_early_data_accepted(client.get()));
4273       } else {
4274         byte_written = 42;
4275         EXPECT_EQ(SSL_write(client.get(), &byte_written, 1), 1);
4276       }
4277       uint8_t byte;
4278       EXPECT_EQ(SSL_read(server2.get(), &byte, 1), 1);
4279       EXPECT_EQ(byte_written, byte);
4280 
4281       byte = 44;
4282       EXPECT_EQ(SSL_write(server2.get(), &byte, 1), 1);
4283       EXPECT_EQ(SSL_read(client.get(), &byte, 1), 1);
4284       EXPECT_EQ(44, byte);
4285     }
4286   }
4287 }
4288 
TEST(SSLTest,HandoffDeclined)4289 TEST(SSLTest, HandoffDeclined) {
4290   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
4291   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
4292   ASSERT_TRUE(client_ctx);
4293   ASSERT_TRUE(server_ctx);
4294 
4295   SSL_CTX_set_handoff_mode(server_ctx.get(), 1);
4296   ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), TLS1_2_VERSION));
4297 
4298   bssl::UniquePtr<X509> cert = GetTestCertificate();
4299   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
4300   ASSERT_TRUE(cert);
4301   ASSERT_TRUE(key);
4302   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
4303   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
4304 
4305   bssl::UniquePtr<SSL> client, server;
4306   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
4307                                      server_ctx.get(), ClientConfig(),
4308                                      false /* don't handshake */));
4309 
4310   int client_ret = SSL_do_handshake(client.get());
4311   int client_err = SSL_get_error(client.get(), client_ret);
4312   ASSERT_EQ(client_err, SSL_ERROR_WANT_READ);
4313 
4314   int server_ret = SSL_do_handshake(server.get());
4315   int server_err = SSL_get_error(server.get(), server_ret);
4316   ASSERT_EQ(server_err, SSL_ERROR_HANDOFF);
4317 
4318   ScopedCBB cbb;
4319   SSL_CLIENT_HELLO hello;
4320   ASSERT_TRUE(CBB_init(cbb.get(), 256));
4321   ASSERT_TRUE(SSL_serialize_handoff(server.get(), cbb.get(), &hello));
4322 
4323   ASSERT_TRUE(SSL_decline_handoff(server.get()));
4324 
4325   ASSERT_TRUE(CompleteHandshakes(client.get(), server.get()));
4326 
4327   uint8_t byte = 42;
4328   EXPECT_EQ(SSL_write(client.get(), &byte, 1), 1);
4329   EXPECT_EQ(SSL_read(server.get(), &byte, 1), 1);
4330   EXPECT_EQ(42, byte);
4331 
4332   byte = 43;
4333   EXPECT_EQ(SSL_write(server.get(), &byte, 1), 1);
4334   EXPECT_EQ(SSL_read(client.get(), &byte, 1), 1);
4335   EXPECT_EQ(43, byte);
4336 }
4337 
SigAlgsToString(Span<const uint16_t> sigalgs)4338 static std::string SigAlgsToString(Span<const uint16_t> sigalgs) {
4339   std::string ret = "{";
4340 
4341   for (uint16_t v : sigalgs) {
4342     if (ret.size() > 1) {
4343       ret += ", ";
4344     }
4345 
4346     char buf[8];
4347     snprintf(buf, sizeof(buf) - 1, "0x%02x", v);
4348     buf[sizeof(buf)-1] = 0;
4349     ret += std::string(buf);
4350   }
4351 
4352   ret += "}";
4353   return ret;
4354 }
4355 
ExpectSigAlgsEqual(Span<const uint16_t> expected,Span<const uint16_t> actual)4356 void ExpectSigAlgsEqual(Span<const uint16_t> expected,
4357                         Span<const uint16_t> actual) {
4358   bool matches = false;
4359   if (expected.size() == actual.size()) {
4360     matches = true;
4361 
4362     for (size_t i = 0; i < expected.size(); i++) {
4363       if (expected[i] != actual[i]) {
4364         matches = false;
4365         break;
4366       }
4367     }
4368   }
4369 
4370   if (!matches) {
4371     ADD_FAILURE() << "expected: " << SigAlgsToString(expected)
4372                   << " got: " << SigAlgsToString(actual);
4373   }
4374 }
4375 
TEST(SSLTest,SigAlgs)4376 TEST(SSLTest, SigAlgs) {
4377   static const struct {
4378     std::vector<int> input;
4379     bool ok;
4380     std::vector<uint16_t> expected;
4381   } kTests[] = {
4382       {{}, true, {}},
4383       {{1}, false, {}},
4384       {{1, 2, 3}, false, {}},
4385       {{NID_sha256, EVP_PKEY_ED25519}, false, {}},
4386       {{NID_sha256, EVP_PKEY_RSA, NID_sha256, EVP_PKEY_RSA}, false, {}},
4387 
4388       {{NID_sha256, EVP_PKEY_RSA}, true, {SSL_SIGN_RSA_PKCS1_SHA256}},
4389       {{NID_sha512, EVP_PKEY_RSA}, true, {SSL_SIGN_RSA_PKCS1_SHA512}},
4390       {{NID_sha256, EVP_PKEY_RSA_PSS}, true, {SSL_SIGN_RSA_PSS_RSAE_SHA256}},
4391       {{NID_undef, EVP_PKEY_ED25519}, true, {SSL_SIGN_ED25519}},
4392       {{NID_undef, EVP_PKEY_ED25519, NID_sha384, EVP_PKEY_EC},
4393        true,
4394        {SSL_SIGN_ED25519, SSL_SIGN_ECDSA_SECP384R1_SHA384}},
4395   };
4396 
4397   UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
4398 
4399   unsigned n = 1;
4400   for (const auto &test : kTests) {
4401     SCOPED_TRACE(n++);
4402 
4403     const bool ok =
4404         SSL_CTX_set1_sigalgs(ctx.get(), test.input.data(), test.input.size());
4405     EXPECT_EQ(ok, test.ok);
4406 
4407     if (!ok) {
4408       ERR_clear_error();
4409     }
4410 
4411     if (!test.ok) {
4412       continue;
4413     }
4414 
4415     ExpectSigAlgsEqual(test.expected, ctx->cert->sigalgs);
4416   }
4417 }
4418 
TEST(SSLTest,SigAlgsList)4419 TEST(SSLTest, SigAlgsList) {
4420   static const struct {
4421     const char *input;
4422     bool ok;
4423     std::vector<uint16_t> expected;
4424   } kTests[] = {
4425       {"", false, {}},
4426       {":", false, {}},
4427       {"+", false, {}},
4428       {"RSA", false, {}},
4429       {"RSA+", false, {}},
4430       {"RSA+SHA256:", false, {}},
4431       {":RSA+SHA256:", false, {}},
4432       {":RSA+SHA256+:", false, {}},
4433       {"!", false, {}},
4434       {"\x01", false, {}},
4435       {"RSA+SHA256:RSA+SHA384:RSA+SHA256", false, {}},
4436       {"RSA-PSS+SHA256:rsa_pss_rsae_sha256", false, {}},
4437 
4438       {"RSA+SHA256", true, {SSL_SIGN_RSA_PKCS1_SHA256}},
4439       {"RSA+SHA256:ed25519",
4440        true,
4441        {SSL_SIGN_RSA_PKCS1_SHA256, SSL_SIGN_ED25519}},
4442       {"ECDSA+SHA256:RSA+SHA512",
4443        true,
4444        {SSL_SIGN_ECDSA_SECP256R1_SHA256, SSL_SIGN_RSA_PKCS1_SHA512}},
4445       {"ecdsa_secp256r1_sha256:rsa_pss_rsae_sha256",
4446        true,
4447        {SSL_SIGN_ECDSA_SECP256R1_SHA256, SSL_SIGN_RSA_PSS_RSAE_SHA256}},
4448       {"RSA-PSS+SHA256", true, {SSL_SIGN_RSA_PSS_RSAE_SHA256}},
4449       {"PSS+SHA256", true, {SSL_SIGN_RSA_PSS_RSAE_SHA256}},
4450   };
4451 
4452   UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
4453 
4454   unsigned n = 1;
4455   for (const auto &test : kTests) {
4456     SCOPED_TRACE(n++);
4457 
4458     const bool ok = SSL_CTX_set1_sigalgs_list(ctx.get(), test.input);
4459     EXPECT_EQ(ok, test.ok);
4460 
4461     if (!ok) {
4462       if (test.ok) {
4463         ERR_print_errors_fp(stderr);
4464       }
4465       ERR_clear_error();
4466     }
4467 
4468     if (!test.ok) {
4469       continue;
4470     }
4471 
4472     ExpectSigAlgsEqual(test.expected, ctx->cert->sigalgs);
4473   }
4474 }
4475 
TEST(SSLTest,ApplyHandoffRemovesUnsupportedCiphers)4476 TEST(SSLTest, ApplyHandoffRemovesUnsupportedCiphers) {
4477   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
4478   bssl::UniquePtr<SSL> server(SSL_new(server_ctx.get()));
4479 
4480   // handoff is a handoff message that has been artificially modified to pretend
4481   // that only cipher 0x0A is supported.  When it is applied to |server|, all
4482   // ciphers but that one should be removed.
4483   //
4484   // To make a new one of these, try sticking this in the |Handoff| test above:
4485   //
4486   // hexdump(stderr, "", handoff.data(), handoff.size());
4487   // sed -e 's/\(..\)/0x\1, /g'
4488   //
4489   // and modify serialize_features() to emit only cipher 0x0A.
4490 
4491   uint8_t handoff[] = {
4492       0x30, 0x81, 0x9a, 0x02, 0x01, 0x00, 0x04, 0x00, 0x04, 0x81, 0x82, 0x01,
4493       0x00, 0x00, 0x7e, 0x03, 0x03, 0x30, 0x8e, 0x8f, 0x79, 0xd2, 0x87, 0x39,
4494       0xc2, 0x23, 0x23, 0x13, 0xca, 0x3c, 0x80, 0x44, 0xfd, 0x80, 0x83, 0x62,
4495       0x3c, 0xcc, 0xf8, 0x76, 0xd3, 0x62, 0xbb, 0x54, 0xe3, 0xc4, 0x39, 0x24,
4496       0xa5, 0x00, 0x00, 0x1e, 0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30,
4497       0xcc, 0xa9, 0xcc, 0xa8, 0xc0, 0x09, 0xc0, 0x13, 0xc0, 0x0a, 0xc0, 0x14,
4498       0x00, 0x9c, 0x00, 0x9d, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00,
4499       0x00, 0x37, 0x00, 0x17, 0x00, 0x00, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00,
4500       0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18, 0x00,
4501       0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00,
4502       0x14, 0x00, 0x12, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01, 0x05, 0x03, 0x08,
4503       0x05, 0x05, 0x01, 0x08, 0x06, 0x06, 0x01, 0x02, 0x01, 0x04, 0x02, 0x00,
4504       0x0a, 0x04, 0x0a, 0x00, 0x15, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, 0x00,
4505       0x1d,
4506   };
4507 
4508   EXPECT_EQ(20u, sk_SSL_CIPHER_num(SSL_get_ciphers(server.get())));
4509   ASSERT_TRUE(
4510       SSL_apply_handoff(server.get(), {handoff, OPENSSL_ARRAY_SIZE(handoff)}));
4511   EXPECT_EQ(1u, sk_SSL_CIPHER_num(SSL_get_ciphers(server.get())));
4512 }
4513 
TEST(SSLTest,ApplyHandoffRemovesUnsupportedCurves)4514 TEST(SSLTest, ApplyHandoffRemovesUnsupportedCurves) {
4515   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
4516   bssl::UniquePtr<SSL> server(SSL_new(server_ctx.get()));
4517 
4518   // handoff is a handoff message that has been artificially modified to pretend
4519   // that only one curve is supported.  When it is applied to |server|, all
4520   // curves but that one should be removed.
4521   //
4522   // See |ApplyHandoffRemovesUnsupportedCiphers| for how to make a new one of
4523   // these.
4524   uint8_t handoff[] = {
4525       0x30, 0x81, 0xc0, 0x02, 0x01, 0x00, 0x04, 0x00, 0x04, 0x81, 0x82, 0x01,
4526       0x00, 0x00, 0x7e, 0x03, 0x03, 0x98, 0x30, 0xce, 0xd9, 0xb0, 0xdf, 0x5f,
4527       0x82, 0x05, 0x4a, 0x43, 0x67, 0x7e, 0xdb, 0x6a, 0x4f, 0x21, 0x18, 0x4e,
4528       0x0d, 0x94, 0x63, 0x18, 0x8b, 0x54, 0x89, 0xdb, 0x8b, 0x1d, 0x84, 0xbc,
4529       0x09, 0x00, 0x00, 0x1e, 0xc0, 0x2b, 0xc0, 0x2f, 0xc0, 0x2c, 0xc0, 0x30,
4530       0xcc, 0xa9, 0xcc, 0xa8, 0xc0, 0x09, 0xc0, 0x13, 0xc0, 0x0a, 0xc0, 0x14,
4531       0x00, 0x9c, 0x00, 0x9d, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00,
4532       0x00, 0x37, 0x00, 0x17, 0x00, 0x00, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00,
4533       0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18, 0x00,
4534       0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0d, 0x00,
4535       0x14, 0x00, 0x12, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01, 0x05, 0x03, 0x08,
4536       0x05, 0x05, 0x01, 0x08, 0x06, 0x06, 0x01, 0x02, 0x01, 0x04, 0x30, 0x00,
4537       0x02, 0x00, 0x0a, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x8c, 0x00, 0x8d, 0x00,
4538       0x9c, 0x00, 0x9d, 0x13, 0x01, 0x13, 0x02, 0x13, 0x03, 0xc0, 0x09, 0xc0,
4539       0x0a, 0xc0, 0x13, 0xc0, 0x14, 0xc0, 0x2b, 0xc0, 0x2c, 0xc0, 0x2f, 0xc0,
4540       0x30, 0xc0, 0x35, 0xc0, 0x36, 0xcc, 0xa8, 0xcc, 0xa9, 0xcc, 0xac, 0x04,
4541       0x02, 0x00, 0x17,
4542   };
4543 
4544   // The zero length means that the default list of groups is used.
4545   EXPECT_EQ(0u, server->config->supported_group_list.size());
4546   ASSERT_TRUE(
4547       SSL_apply_handoff(server.get(), {handoff, OPENSSL_ARRAY_SIZE(handoff)}));
4548   EXPECT_EQ(1u, server->config->supported_group_list.size());
4549 }
4550 
TEST(SSLTest,ZeroSizedWiteFlushesHandshakeMessages)4551 TEST(SSLTest, ZeroSizedWiteFlushesHandshakeMessages) {
4552   // If there are pending handshake mesages, an |SSL_write| of zero bytes should
4553   // flush them.
4554   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
4555   EXPECT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), TLS1_3_VERSION));
4556   EXPECT_TRUE(SSL_CTX_set_min_proto_version(server_ctx.get(), TLS1_3_VERSION));
4557   bssl::UniquePtr<X509> cert = GetTestCertificate();
4558   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
4559   ASSERT_TRUE(cert);
4560   ASSERT_TRUE(key);
4561   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
4562   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
4563 
4564   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
4565   EXPECT_TRUE(SSL_CTX_set_max_proto_version(client_ctx.get(), TLS1_3_VERSION));
4566   EXPECT_TRUE(SSL_CTX_set_min_proto_version(client_ctx.get(), TLS1_3_VERSION));
4567 
4568   bssl::UniquePtr<SSL> client, server;
4569   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
4570                                      server_ctx.get()));
4571 
4572   BIO *client_wbio = SSL_get_wbio(client.get());
4573   EXPECT_EQ(0u, BIO_wpending(client_wbio));
4574   EXPECT_TRUE(SSL_key_update(client.get(), SSL_KEY_UPDATE_NOT_REQUESTED));
4575   EXPECT_EQ(0u, BIO_wpending(client_wbio));
4576   EXPECT_EQ(0, SSL_write(client.get(), nullptr, 0));
4577   EXPECT_NE(0u, BIO_wpending(client_wbio));
4578 }
4579 
TEST_P(SSLVersionTest,VerifyBeforeCertRequest)4580 TEST_P(SSLVersionTest, VerifyBeforeCertRequest) {
4581   // Configure the server to request client certificates.
4582   SSL_CTX_set_custom_verify(
4583       server_ctx_.get(), SSL_VERIFY_PEER,
4584       [](SSL *ssl, uint8_t *out_alert) { return ssl_verify_ok; });
4585 
4586   // Configure the client to reject the server certificate.
4587   SSL_CTX_set_custom_verify(
4588       client_ctx_.get(), SSL_VERIFY_PEER,
4589       [](SSL *ssl, uint8_t *out_alert) { return ssl_verify_invalid; });
4590 
4591   // cert_cb should not be called. Verification should fail first.
4592   SSL_CTX_set_cert_cb(client_ctx_.get(),
4593                       [](SSL *ssl, void *arg) {
4594                         ADD_FAILURE() << "cert_cb unexpectedly called";
4595                         return 0;
4596                       },
4597                       nullptr);
4598 
4599   bssl::UniquePtr<SSL> client, server;
4600   EXPECT_FALSE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
4601                                       server_ctx_.get()));
4602 }
4603 
4604 // Test that ticket-based sessions on the client get fake session IDs.
TEST_P(SSLVersionTest,FakeIDsForTickets)4605 TEST_P(SSLVersionTest, FakeIDsForTickets) {
4606   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
4607   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
4608 
4609   bssl::UniquePtr<SSL_SESSION> session =
4610       CreateClientSession(client_ctx_.get(), server_ctx_.get());
4611   ASSERT_TRUE(session);
4612 
4613   EXPECT_TRUE(SSL_SESSION_has_ticket(session.get()));
4614   unsigned session_id_length;
4615   SSL_SESSION_get_id(session.get(), &session_id_length);
4616   EXPECT_NE(session_id_length, 0u);
4617 }
4618 
4619 // These tests test multi-threaded behavior. They are intended to run with
4620 // ThreadSanitizer.
4621 #if defined(OPENSSL_THREADS)
TEST_P(SSLVersionTest,SessionCacheThreads)4622 TEST_P(SSLVersionTest, SessionCacheThreads) {
4623   SSL_CTX_set_options(server_ctx_.get(), SSL_OP_NO_TICKET);
4624   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
4625   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
4626 
4627   if (version() == TLS1_3_VERSION) {
4628     // Our TLS 1.3 implementation does not support stateful resumption.
4629     ASSERT_FALSE(CreateClientSession(client_ctx_.get(), server_ctx_.get()));
4630     return;
4631   }
4632 
4633   // Establish two client sessions to test with.
4634   bssl::UniquePtr<SSL_SESSION> session1 =
4635       CreateClientSession(client_ctx_.get(), server_ctx_.get());
4636   ASSERT_TRUE(session1);
4637   bssl::UniquePtr<SSL_SESSION> session2 =
4638       CreateClientSession(client_ctx_.get(), server_ctx_.get());
4639   ASSERT_TRUE(session2);
4640 
4641   auto connect_with_session = [&](SSL_SESSION *session) {
4642     ClientConfig config;
4643     config.session = session;
4644     UniquePtr<SSL> client, server;
4645     EXPECT_TRUE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
4646                                        server_ctx_.get(), config));
4647   };
4648 
4649   // Resume sessions in parallel with establishing new ones.
4650   {
4651     std::vector<std::thread> threads;
4652     threads.emplace_back([&] { connect_with_session(nullptr); });
4653     threads.emplace_back([&] { connect_with_session(nullptr); });
4654     threads.emplace_back([&] { connect_with_session(session1.get()); });
4655     threads.emplace_back([&] { connect_with_session(session1.get()); });
4656     threads.emplace_back([&] { connect_with_session(session2.get()); });
4657     threads.emplace_back([&] { connect_with_session(session2.get()); });
4658     for (auto &thread : threads) {
4659       thread.join();
4660     }
4661   }
4662 
4663   // Hit the maximum session cache size across multiple threads
4664   size_t limit = SSL_CTX_sess_number(server_ctx_.get()) + 2;
4665   SSL_CTX_sess_set_cache_size(server_ctx_.get(), limit);
4666   {
4667     std::vector<std::thread> threads;
4668     for (int i = 0; i < 4; i++) {
4669       threads.emplace_back([&]() {
4670         connect_with_session(nullptr);
4671         EXPECT_LE(SSL_CTX_sess_number(server_ctx_.get()), limit);
4672       });
4673     }
4674     for (auto &thread : threads) {
4675       thread.join();
4676     }
4677     EXPECT_EQ(SSL_CTX_sess_number(server_ctx_.get()), limit);
4678   }
4679 }
4680 
TEST_P(SSLVersionTest,SessionTicketThreads)4681 TEST_P(SSLVersionTest, SessionTicketThreads) {
4682   for (bool renew_ticket : {false, true}) {
4683     SCOPED_TRACE(renew_ticket);
4684     ResetContexts();
4685     SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
4686     SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
4687     if (renew_ticket) {
4688       SSL_CTX_set_tlsext_ticket_key_cb(server_ctx_.get(), RenewTicketCallback);
4689     }
4690 
4691     // Establish two client sessions to test with.
4692     bssl::UniquePtr<SSL_SESSION> session1 =
4693         CreateClientSession(client_ctx_.get(), server_ctx_.get());
4694     ASSERT_TRUE(session1);
4695     bssl::UniquePtr<SSL_SESSION> session2 =
4696         CreateClientSession(client_ctx_.get(), server_ctx_.get());
4697     ASSERT_TRUE(session2);
4698 
4699     auto connect_with_session = [&](SSL_SESSION *session) {
4700       ClientConfig config;
4701       config.session = session;
4702       UniquePtr<SSL> client, server;
4703       EXPECT_TRUE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
4704                                          server_ctx_.get(), config));
4705     };
4706 
4707     // Resume sessions in parallel with establishing new ones.
4708     {
4709       std::vector<std::thread> threads;
4710       threads.emplace_back([&] { connect_with_session(nullptr); });
4711       threads.emplace_back([&] { connect_with_session(nullptr); });
4712       threads.emplace_back([&] { connect_with_session(session1.get()); });
4713       threads.emplace_back([&] { connect_with_session(session1.get()); });
4714       threads.emplace_back([&] { connect_with_session(session2.get()); });
4715       threads.emplace_back([&] { connect_with_session(session2.get()); });
4716       for (auto &thread : threads) {
4717         thread.join();
4718       }
4719     }
4720   }
4721 }
4722 
4723 // SSL_CTX_get0_certificate needs to lock internally. Test this works.
TEST(SSLTest,GetCertificateThreads)4724 TEST(SSLTest, GetCertificateThreads) {
4725   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
4726   ASSERT_TRUE(ctx);
4727   bssl::UniquePtr<X509> cert = GetTestCertificate();
4728   ASSERT_TRUE(cert);
4729   ASSERT_TRUE(SSL_CTX_use_certificate(ctx.get(), cert.get()));
4730 
4731   // Existing code expects |SSL_CTX_get0_certificate| to be callable from two
4732   // threads concurrently. It originally was an immutable operation. Now we
4733   // implement it with a thread-safe cache, so it is worth testing.
4734   X509 *cert2_thread;
4735   std::thread thread(
4736       [&] { cert2_thread = SSL_CTX_get0_certificate(ctx.get()); });
4737   X509 *cert2 = SSL_CTX_get0_certificate(ctx.get());
4738   thread.join();
4739 
4740   EXPECT_EQ(cert2, cert2_thread);
4741   EXPECT_EQ(0, X509_cmp(cert.get(), cert2));
4742 }
4743 
4744 // Functions which access properties on the negotiated session are thread-safe
4745 // where needed. Prior to TLS 1.3, clients resuming sessions and servers
4746 // performing stateful resumption will share an underlying SSL_SESSION object,
4747 // potentially across threads.
TEST_P(SSLVersionTest,SessionPropertiesThreads)4748 TEST_P(SSLVersionTest, SessionPropertiesThreads) {
4749   if (version() == TLS1_3_VERSION) {
4750     // Our TLS 1.3 implementation does not support stateful resumption.
4751     ASSERT_FALSE(CreateClientSession(client_ctx_.get(), server_ctx_.get()));
4752     return;
4753   }
4754 
4755   SSL_CTX_set_options(server_ctx_.get(), SSL_OP_NO_TICKET);
4756   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
4757   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
4758 
4759   ASSERT_TRUE(UseCertAndKey(client_ctx_.get()));
4760   ASSERT_TRUE(UseCertAndKey(server_ctx_.get()));
4761 
4762   // Configure mutual authentication, so we have more session state.
4763   SSL_CTX_set_custom_verify(
4764       client_ctx_.get(), SSL_VERIFY_PEER,
4765       [](SSL *ssl, uint8_t *out_alert) { return ssl_verify_ok; });
4766   SSL_CTX_set_custom_verify(
4767       server_ctx_.get(), SSL_VERIFY_PEER,
4768       [](SSL *ssl, uint8_t *out_alert) { return ssl_verify_ok; });
4769 
4770   // Establish a client session to test with.
4771   bssl::UniquePtr<SSL_SESSION> session =
4772       CreateClientSession(client_ctx_.get(), server_ctx_.get());
4773   ASSERT_TRUE(session);
4774 
4775   // Resume with it twice.
4776   UniquePtr<SSL> ssls[4];
4777   ClientConfig config;
4778   config.session = session.get();
4779   ASSERT_TRUE(ConnectClientAndServer(&ssls[0], &ssls[1], client_ctx_.get(),
4780                                      server_ctx_.get(), config));
4781   ASSERT_TRUE(ConnectClientAndServer(&ssls[2], &ssls[3], client_ctx_.get(),
4782                                      server_ctx_.get(), config));
4783 
4784   // Read properties in parallel.
4785   auto read_properties = [](const SSL *ssl) {
4786     EXPECT_TRUE(SSL_get_peer_cert_chain(ssl));
4787     bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl));
4788     EXPECT_TRUE(peer);
4789     EXPECT_TRUE(SSL_get_current_cipher(ssl));
4790     EXPECT_TRUE(SSL_get_curve_id(ssl));
4791   };
4792 
4793   std::vector<std::thread> threads;
4794   for (const auto &ssl_ptr : ssls) {
4795     const SSL *ssl = ssl_ptr.get();
4796     threads.emplace_back([=] { read_properties(ssl); });
4797   }
4798   for (auto &thread : threads) {
4799     thread.join();
4800   }
4801 }
4802 #endif  // OPENSSL_THREADS
4803 
4804 constexpr size_t kNumQUICLevels = 4;
4805 static_assert(ssl_encryption_initial < kNumQUICLevels,
4806               "kNumQUICLevels is wrong");
4807 static_assert(ssl_encryption_early_data < kNumQUICLevels,
4808               "kNumQUICLevels is wrong");
4809 static_assert(ssl_encryption_handshake < kNumQUICLevels,
4810               "kNumQUICLevels is wrong");
4811 static_assert(ssl_encryption_application < kNumQUICLevels,
4812               "kNumQUICLevels is wrong");
4813 
LevelToString(ssl_encryption_level_t level)4814 const char *LevelToString(ssl_encryption_level_t level) {
4815   switch (level) {
4816     case ssl_encryption_initial:
4817       return "initial";
4818     case ssl_encryption_early_data:
4819       return "early data";
4820     case ssl_encryption_handshake:
4821       return "handshake";
4822     case ssl_encryption_application:
4823       return "application";
4824   }
4825   return "<unknown>";
4826 }
4827 
4828 class MockQUICTransport {
4829  public:
4830   enum class Role { kClient, kServer };
4831 
MockQUICTransport(Role role)4832   explicit MockQUICTransport(Role role) : role_(role) {
4833     // The caller is expected to configure initial secrets.
4834     levels_[ssl_encryption_initial].write_secret = {1};
4835     levels_[ssl_encryption_initial].read_secret = {1};
4836   }
4837 
set_peer(MockQUICTransport * peer)4838   void set_peer(MockQUICTransport *peer) { peer_ = peer; }
4839 
has_alert() const4840   bool has_alert() const { return has_alert_; }
alert_level() const4841   ssl_encryption_level_t alert_level() const { return alert_level_; }
alert() const4842   uint8_t alert() const { return alert_; }
4843 
PeerSecretsMatch(ssl_encryption_level_t level) const4844   bool PeerSecretsMatch(ssl_encryption_level_t level) const {
4845     return levels_[level].write_secret == peer_->levels_[level].read_secret &&
4846            levels_[level].read_secret == peer_->levels_[level].write_secret &&
4847            levels_[level].cipher == peer_->levels_[level].cipher;
4848   }
4849 
HasReadSecret(ssl_encryption_level_t level) const4850   bool HasReadSecret(ssl_encryption_level_t level) const {
4851     return !levels_[level].read_secret.empty();
4852   }
4853 
HasWriteSecret(ssl_encryption_level_t level) const4854   bool HasWriteSecret(ssl_encryption_level_t level) const {
4855     return !levels_[level].write_secret.empty();
4856   }
4857 
AllowOutOfOrderWrites()4858   void AllowOutOfOrderWrites() { allow_out_of_order_writes_ = true; }
4859 
SetReadSecret(ssl_encryption_level_t level,const SSL_CIPHER * cipher,Span<const uint8_t> secret)4860   bool SetReadSecret(ssl_encryption_level_t level, const SSL_CIPHER *cipher,
4861                      Span<const uint8_t> secret) {
4862     if (HasReadSecret(level)) {
4863       ADD_FAILURE() << LevelToString(level) << " read secret configured twice";
4864       return false;
4865     }
4866 
4867     if (role_ == Role::kClient && level == ssl_encryption_early_data) {
4868       ADD_FAILURE() << "Unexpected early data read secret";
4869       return false;
4870     }
4871 
4872     ssl_encryption_level_t ack_level =
4873         level == ssl_encryption_early_data ? ssl_encryption_application : level;
4874     if (!HasWriteSecret(ack_level)) {
4875       ADD_FAILURE() << LevelToString(level)
4876                     << " read secret configured before ACK write secret";
4877       return false;
4878     }
4879 
4880     if (cipher == nullptr) {
4881       ADD_FAILURE() << "Unexpected null cipher";
4882       return false;
4883     }
4884 
4885     if (level != ssl_encryption_early_data &&
4886         SSL_CIPHER_get_id(cipher) != levels_[level].cipher) {
4887       ADD_FAILURE() << "Cipher suite inconsistent";
4888       return false;
4889     }
4890 
4891     levels_[level].read_secret.assign(secret.begin(), secret.end());
4892     levels_[level].cipher = SSL_CIPHER_get_id(cipher);
4893     return true;
4894   }
4895 
SetWriteSecret(ssl_encryption_level_t level,const SSL_CIPHER * cipher,Span<const uint8_t> secret)4896   bool SetWriteSecret(ssl_encryption_level_t level, const SSL_CIPHER *cipher,
4897                       Span<const uint8_t> secret) {
4898     if (HasWriteSecret(level)) {
4899       ADD_FAILURE() << LevelToString(level) << " write secret configured twice";
4900       return false;
4901     }
4902 
4903     if (role_ == Role::kServer && level == ssl_encryption_early_data) {
4904       ADD_FAILURE() << "Unexpected early data write secret";
4905       return false;
4906     }
4907 
4908     if (cipher == nullptr) {
4909       ADD_FAILURE() << "Unexpected null cipher";
4910       return false;
4911     }
4912 
4913     levels_[level].write_secret.assign(secret.begin(), secret.end());
4914     levels_[level].cipher = SSL_CIPHER_get_id(cipher);
4915     return true;
4916   }
4917 
WriteHandshakeData(ssl_encryption_level_t level,Span<const uint8_t> data)4918   bool WriteHandshakeData(ssl_encryption_level_t level,
4919                           Span<const uint8_t> data) {
4920     if (levels_[level].write_secret.empty()) {
4921       ADD_FAILURE() << LevelToString(level)
4922                     << " write secret not yet configured";
4923       return false;
4924     }
4925 
4926     // Although the levels are conceptually separate, BoringSSL finishes writing
4927     // data from a previous level before installing keys for the next level.
4928     if (!allow_out_of_order_writes_) {
4929       switch (level) {
4930         case ssl_encryption_early_data:
4931           ADD_FAILURE() << "unexpected handshake data at early data level";
4932           return false;
4933         case ssl_encryption_initial:
4934           if (!levels_[ssl_encryption_handshake].write_secret.empty()) {
4935             ADD_FAILURE()
4936                 << LevelToString(level)
4937                 << " handshake data written after handshake keys installed";
4938             return false;
4939           }
4940           OPENSSL_FALLTHROUGH;
4941         case ssl_encryption_handshake:
4942           if (!levels_[ssl_encryption_application].write_secret.empty()) {
4943             ADD_FAILURE()
4944                 << LevelToString(level)
4945                 << " handshake data written after application keys installed";
4946             return false;
4947           }
4948           OPENSSL_FALLTHROUGH;
4949         case ssl_encryption_application:
4950           break;
4951       }
4952     }
4953 
4954     levels_[level].write_data.insert(levels_[level].write_data.end(),
4955                                      data.begin(), data.end());
4956     return true;
4957   }
4958 
SendAlert(ssl_encryption_level_t level,uint8_t alert_value)4959   bool SendAlert(ssl_encryption_level_t level, uint8_t alert_value) {
4960     if (has_alert_) {
4961       ADD_FAILURE() << "duplicate alert sent";
4962       return false;
4963     }
4964 
4965     if (levels_[level].write_secret.empty()) {
4966       ADD_FAILURE() << LevelToString(level)
4967                     << " write secret not yet configured";
4968       return false;
4969     }
4970 
4971     has_alert_ = true;
4972     alert_level_ = level;
4973     alert_ = alert_value;
4974     return true;
4975   }
4976 
ReadHandshakeData(std::vector<uint8_t> * out,ssl_encryption_level_t level,size_t num=std::numeric_limits<size_t>::max ())4977   bool ReadHandshakeData(std::vector<uint8_t> *out,
4978                          ssl_encryption_level_t level,
4979                          size_t num = std::numeric_limits<size_t>::max()) {
4980     if (levels_[level].read_secret.empty()) {
4981       ADD_FAILURE() << "data read before keys configured in level " << level;
4982       return false;
4983     }
4984     // The peer may not have configured any keys yet.
4985     if (peer_->levels_[level].write_secret.empty()) {
4986       out->clear();
4987       return true;
4988     }
4989     // Check the peer computed the same key.
4990     if (peer_->levels_[level].write_secret != levels_[level].read_secret) {
4991       ADD_FAILURE() << "peer write key does not match read key in level "
4992                     << level;
4993       return false;
4994     }
4995     if (peer_->levels_[level].cipher != levels_[level].cipher) {
4996       ADD_FAILURE() << "peer cipher does not match in level " << level;
4997       return false;
4998     }
4999     std::vector<uint8_t> *peer_data = &peer_->levels_[level].write_data;
5000     num = std::min(num, peer_data->size());
5001     out->assign(peer_data->begin(), peer_data->begin() + num);
5002     peer_data->erase(peer_data->begin(), peer_data->begin() + num);
5003     return true;
5004   }
5005 
5006  private:
5007   Role role_;
5008   MockQUICTransport *peer_ = nullptr;
5009 
5010   bool allow_out_of_order_writes_ = false;
5011   bool has_alert_ = false;
5012   ssl_encryption_level_t alert_level_ = ssl_encryption_initial;
5013   uint8_t alert_ = 0;
5014 
5015   struct Level {
5016     std::vector<uint8_t> write_data;
5017     std::vector<uint8_t> write_secret;
5018     std::vector<uint8_t> read_secret;
5019     uint32_t cipher = 0;
5020   };
5021   Level levels_[kNumQUICLevels];
5022 };
5023 
5024 class MockQUICTransportPair {
5025  public:
MockQUICTransportPair()5026   MockQUICTransportPair()
5027       : client_(MockQUICTransport::Role::kClient),
5028         server_(MockQUICTransport::Role::kServer) {
5029     client_.set_peer(&server_);
5030     server_.set_peer(&client_);
5031   }
5032 
~MockQUICTransportPair()5033   ~MockQUICTransportPair() {
5034     client_.set_peer(nullptr);
5035     server_.set_peer(nullptr);
5036   }
5037 
client()5038   MockQUICTransport *client() { return &client_; }
server()5039   MockQUICTransport *server() { return &server_; }
5040 
SecretsMatch(ssl_encryption_level_t level) const5041   bool SecretsMatch(ssl_encryption_level_t level) const {
5042     // We only need to check |HasReadSecret| and |HasWriteSecret| on |client_|.
5043     // |PeerSecretsMatch| checks that |server_| is analogously configured.
5044     return client_.PeerSecretsMatch(level) &&
5045            client_.HasWriteSecret(level) &&
5046            (level == ssl_encryption_early_data || client_.HasReadSecret(level));
5047   }
5048 
5049  private:
5050   MockQUICTransport client_;
5051   MockQUICTransport server_;
5052 };
5053 
5054 class QUICMethodTest : public testing::Test {
5055  protected:
SetUp()5056   void SetUp() override {
5057     client_ctx_.reset(SSL_CTX_new(TLS_method()));
5058     server_ctx_.reset(SSL_CTX_new(TLS_method()));
5059     ASSERT_TRUE(client_ctx_);
5060     ASSERT_TRUE(server_ctx_);
5061 
5062     bssl::UniquePtr<X509> cert = GetTestCertificate();
5063     bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
5064     ASSERT_TRUE(cert);
5065     ASSERT_TRUE(key);
5066     ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx_.get(), cert.get()));
5067     ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx_.get(), key.get()));
5068 
5069     SSL_CTX_set_min_proto_version(server_ctx_.get(), TLS1_3_VERSION);
5070     SSL_CTX_set_max_proto_version(server_ctx_.get(), TLS1_3_VERSION);
5071     SSL_CTX_set_min_proto_version(client_ctx_.get(), TLS1_3_VERSION);
5072     SSL_CTX_set_max_proto_version(client_ctx_.get(), TLS1_3_VERSION);
5073 
5074     static const uint8_t kALPNProtos[] = {0x03, 'f', 'o', 'o'};
5075     ASSERT_EQ(SSL_CTX_set_alpn_protos(client_ctx_.get(), kALPNProtos,
5076                                       sizeof(kALPNProtos)),
5077               0);
5078     SSL_CTX_set_alpn_select_cb(
5079         server_ctx_.get(),
5080         [](SSL *ssl, const uint8_t **out, uint8_t *out_len, const uint8_t *in,
5081            unsigned in_len, void *arg) -> int {
5082           return SSL_select_next_proto(
5083                      const_cast<uint8_t **>(out), out_len, in, in_len,
5084                      kALPNProtos, sizeof(kALPNProtos)) == OPENSSL_NPN_NEGOTIATED
5085                      ? SSL_TLSEXT_ERR_OK
5086                      : SSL_TLSEXT_ERR_NOACK;
5087         },
5088         nullptr);
5089   }
5090 
TransportFromSSL(const SSL * ssl)5091   static MockQUICTransport *TransportFromSSL(const SSL *ssl) {
5092     return ex_data_.Get(ssl);
5093   }
5094 
ProvideHandshakeData(SSL * ssl,size_t num=std::numeric_limits<size_t>::max ())5095   static bool ProvideHandshakeData(
5096       SSL *ssl, size_t num = std::numeric_limits<size_t>::max()) {
5097     MockQUICTransport *transport = TransportFromSSL(ssl);
5098     ssl_encryption_level_t level = SSL_quic_read_level(ssl);
5099     std::vector<uint8_t> data;
5100     return transport->ReadHandshakeData(&data, level, num) &&
5101            SSL_provide_quic_data(ssl, level, data.data(), data.size());
5102   }
5103 
AllowOutOfOrderWrites()5104   void AllowOutOfOrderWrites() {
5105     allow_out_of_order_writes_ = true;
5106   }
5107 
CreateClientAndServer()5108   bool CreateClientAndServer() {
5109     client_.reset(SSL_new(client_ctx_.get()));
5110     server_.reset(SSL_new(server_ctx_.get()));
5111     if (!client_ || !server_) {
5112       return false;
5113     }
5114 
5115     SSL_set_connect_state(client_.get());
5116     SSL_set_accept_state(server_.get());
5117 
5118     transport_.reset(new MockQUICTransportPair);
5119     ex_data_.Set(client_.get(), transport_->client());
5120     ex_data_.Set(server_.get(), transport_->server());
5121     if (allow_out_of_order_writes_) {
5122       transport_->client()->AllowOutOfOrderWrites();
5123       transport_->server()->AllowOutOfOrderWrites();
5124     }
5125     static const uint8_t client_transport_params[] = {0};
5126     if (!SSL_set_quic_transport_params(client_.get(), client_transport_params,
5127                                        sizeof(client_transport_params)) ||
5128         !SSL_set_quic_transport_params(server_.get(),
5129                                        server_transport_params_.data(),
5130                                        server_transport_params_.size()) ||
5131         !SSL_set_quic_early_data_context(
5132             server_.get(), server_quic_early_data_context_.data(),
5133             server_quic_early_data_context_.size())) {
5134       return false;
5135     }
5136     return true;
5137   }
5138 
5139   enum class ExpectedError {
5140     kNoError,
5141     kClientError,
5142     kServerError,
5143   };
5144 
5145   // CompleteHandshakesForQUIC runs |SSL_do_handshake| on |client_| and
5146   // |server_| until each completes once. It returns true on success and false
5147   // on failure.
CompleteHandshakesForQUIC()5148   bool CompleteHandshakesForQUIC() {
5149     return RunQUICHandshakesAndExpectError(ExpectedError::kNoError);
5150   }
5151 
5152   // Runs |SSL_do_handshake| on |client_| and |server_| until each completes
5153   // once. If |expect_client_error| is true, it will return true only if the
5154   // client handshake failed. Otherwise, it returns true if both handshakes
5155   // succeed and false otherwise.
RunQUICHandshakesAndExpectError(ExpectedError expected_error)5156   bool RunQUICHandshakesAndExpectError(ExpectedError expected_error) {
5157     bool client_done = false, server_done = false;
5158     while (!client_done || !server_done) {
5159       if (!client_done) {
5160         if (!ProvideHandshakeData(client_.get())) {
5161           ADD_FAILURE() << "ProvideHandshakeData(client_) failed";
5162           return false;
5163         }
5164         int client_ret = SSL_do_handshake(client_.get());
5165         int client_err = SSL_get_error(client_.get(), client_ret);
5166         if (client_ret == 1) {
5167           client_done = true;
5168         } else if (client_ret != -1 || client_err != SSL_ERROR_WANT_READ) {
5169           if (expected_error == ExpectedError::kClientError) {
5170             return true;
5171           }
5172           ADD_FAILURE() << "Unexpected client output: " << client_ret << " "
5173                         << client_err;
5174           return false;
5175         }
5176       }
5177 
5178       if (!server_done) {
5179         if (!ProvideHandshakeData(server_.get())) {
5180           ADD_FAILURE() << "ProvideHandshakeData(server_) failed";
5181           return false;
5182         }
5183         int server_ret = SSL_do_handshake(server_.get());
5184         int server_err = SSL_get_error(server_.get(), server_ret);
5185         if (server_ret == 1) {
5186           server_done = true;
5187         } else if (server_ret != -1 || server_err != SSL_ERROR_WANT_READ) {
5188           if (expected_error == ExpectedError::kServerError) {
5189             return true;
5190           }
5191           ADD_FAILURE() << "Unexpected server output: " << server_ret << " "
5192                         << server_err;
5193           return false;
5194         }
5195       }
5196     }
5197     return expected_error == ExpectedError::kNoError;
5198   }
5199 
CreateClientSessionForQUIC()5200   bssl::UniquePtr<SSL_SESSION> CreateClientSessionForQUIC() {
5201     g_last_session = nullptr;
5202     SSL_CTX_sess_set_new_cb(client_ctx_.get(), SaveLastSession);
5203     if (!CreateClientAndServer() ||
5204         !CompleteHandshakesForQUIC()) {
5205       return nullptr;
5206     }
5207 
5208     // The server sent NewSessionTicket messages in the handshake.
5209     if (!ProvideHandshakeData(client_.get()) ||
5210         !SSL_process_quic_post_handshake(client_.get())) {
5211       return nullptr;
5212     }
5213 
5214     return std::move(g_last_session);
5215   }
5216 
ExpectHandshakeSuccess()5217   void ExpectHandshakeSuccess() {
5218     EXPECT_TRUE(transport_->SecretsMatch(ssl_encryption_application));
5219     EXPECT_EQ(ssl_encryption_application, SSL_quic_read_level(client_.get()));
5220     EXPECT_EQ(ssl_encryption_application, SSL_quic_write_level(client_.get()));
5221     EXPECT_EQ(ssl_encryption_application, SSL_quic_read_level(server_.get()));
5222     EXPECT_EQ(ssl_encryption_application, SSL_quic_write_level(server_.get()));
5223     EXPECT_FALSE(transport_->client()->has_alert());
5224     EXPECT_FALSE(transport_->server()->has_alert());
5225 
5226     // SSL_do_handshake is now idempotent.
5227     EXPECT_EQ(SSL_do_handshake(client_.get()), 1);
5228     EXPECT_EQ(SSL_do_handshake(server_.get()), 1);
5229   }
5230 
5231   // Returns a default SSL_QUIC_METHOD. Individual methods may be overwritten by
5232   // the test.
DefaultQUICMethod()5233   SSL_QUIC_METHOD DefaultQUICMethod() {
5234     return SSL_QUIC_METHOD{
5235         SetReadSecretCallback, SetWriteSecretCallback, AddHandshakeDataCallback,
5236         FlushFlightCallback,   SendAlertCallback,
5237     };
5238   }
5239 
SetReadSecretCallback(SSL * ssl,ssl_encryption_level_t level,const SSL_CIPHER * cipher,const uint8_t * secret,size_t secret_len)5240   static int SetReadSecretCallback(SSL *ssl, ssl_encryption_level_t level,
5241                                    const SSL_CIPHER *cipher,
5242                                    const uint8_t *secret, size_t secret_len) {
5243     return TransportFromSSL(ssl)->SetReadSecret(
5244         level, cipher, MakeConstSpan(secret, secret_len));
5245   }
5246 
SetWriteSecretCallback(SSL * ssl,ssl_encryption_level_t level,const SSL_CIPHER * cipher,const uint8_t * secret,size_t secret_len)5247   static int SetWriteSecretCallback(SSL *ssl, ssl_encryption_level_t level,
5248                                     const SSL_CIPHER *cipher,
5249                                     const uint8_t *secret, size_t secret_len) {
5250     return TransportFromSSL(ssl)->SetWriteSecret(
5251         level, cipher, MakeConstSpan(secret, secret_len));
5252   }
5253 
AddHandshakeDataCallback(SSL * ssl,enum ssl_encryption_level_t level,const uint8_t * data,size_t len)5254   static int AddHandshakeDataCallback(SSL *ssl,
5255                                       enum ssl_encryption_level_t level,
5256                                       const uint8_t *data, size_t len) {
5257     EXPECT_EQ(level, SSL_quic_write_level(ssl));
5258     return TransportFromSSL(ssl)->WriteHandshakeData(level,
5259                                                      MakeConstSpan(data, len));
5260   }
5261 
FlushFlightCallback(SSL * ssl)5262   static int FlushFlightCallback(SSL *ssl) { return 1; }
5263 
SendAlertCallback(SSL * ssl,ssl_encryption_level_t level,uint8_t alert)5264   static int SendAlertCallback(SSL *ssl, ssl_encryption_level_t level,
5265                                uint8_t alert) {
5266     EXPECT_EQ(level, SSL_quic_write_level(ssl));
5267     return TransportFromSSL(ssl)->SendAlert(level, alert);
5268   }
5269 
5270   bssl::UniquePtr<SSL_CTX> client_ctx_;
5271   bssl::UniquePtr<SSL_CTX> server_ctx_;
5272 
5273   static UnownedSSLExData<MockQUICTransport> ex_data_;
5274   std::unique_ptr<MockQUICTransportPair> transport_;
5275 
5276   bssl::UniquePtr<SSL> client_;
5277   bssl::UniquePtr<SSL> server_;
5278 
5279   std::vector<uint8_t> server_transport_params_ = {1};
5280   std::vector<uint8_t> server_quic_early_data_context_ = {2};
5281 
5282   bool allow_out_of_order_writes_ = false;
5283 };
5284 
5285 UnownedSSLExData<MockQUICTransport> QUICMethodTest::ex_data_;
5286 
5287 // Test a full handshake and resumption work.
TEST_F(QUICMethodTest,Basic)5288 TEST_F(QUICMethodTest, Basic) {
5289   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5290 
5291   g_last_session = nullptr;
5292 
5293   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
5294   SSL_CTX_sess_set_new_cb(client_ctx_.get(), SaveLastSession);
5295   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5296   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5297 
5298   ASSERT_TRUE(CreateClientAndServer());
5299   ASSERT_TRUE(CompleteHandshakesForQUIC());
5300 
5301   ExpectHandshakeSuccess();
5302   EXPECT_FALSE(SSL_session_reused(client_.get()));
5303   EXPECT_FALSE(SSL_session_reused(server_.get()));
5304 
5305   // The server sent NewSessionTicket messages in the handshake.
5306   EXPECT_FALSE(g_last_session);
5307   ASSERT_TRUE(ProvideHandshakeData(client_.get()));
5308   EXPECT_EQ(SSL_process_quic_post_handshake(client_.get()), 1);
5309   EXPECT_TRUE(g_last_session);
5310 
5311   // Create a second connection to verify resumption works.
5312   ASSERT_TRUE(CreateClientAndServer());
5313   bssl::UniquePtr<SSL_SESSION> session = std::move(g_last_session);
5314   SSL_set_session(client_.get(), session.get());
5315 
5316   ASSERT_TRUE(CompleteHandshakesForQUIC());
5317 
5318   ExpectHandshakeSuccess();
5319   EXPECT_TRUE(SSL_session_reused(client_.get()));
5320   EXPECT_TRUE(SSL_session_reused(server_.get()));
5321 }
5322 
5323 // Test that HelloRetryRequest in QUIC works.
TEST_F(QUICMethodTest,HelloRetryRequest)5324 TEST_F(QUICMethodTest, HelloRetryRequest) {
5325   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5326 
5327   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5328   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5329 
5330   // BoringSSL predicts the most preferred curve, so using different preferences
5331   // will trigger HelloRetryRequest.
5332   static const int kClientPrefs[] = {NID_X25519, NID_X9_62_prime256v1};
5333   ASSERT_TRUE(SSL_CTX_set1_curves(client_ctx_.get(), kClientPrefs,
5334                                   OPENSSL_ARRAY_SIZE(kClientPrefs)));
5335   static const int kServerPrefs[] = {NID_X9_62_prime256v1, NID_X25519};
5336   ASSERT_TRUE(SSL_CTX_set1_curves(server_ctx_.get(), kServerPrefs,
5337                                   OPENSSL_ARRAY_SIZE(kServerPrefs)));
5338 
5339   ASSERT_TRUE(CreateClientAndServer());
5340   ASSERT_TRUE(CompleteHandshakesForQUIC());
5341   ExpectHandshakeSuccess();
5342 }
5343 
5344 // Test that the client does not send a legacy_session_id in the ClientHello.
TEST_F(QUICMethodTest,NoLegacySessionId)5345 TEST_F(QUICMethodTest, NoLegacySessionId) {
5346   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5347 
5348   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5349   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5350   // Check that the session ID length is 0 in an early callback.
5351   SSL_CTX_set_select_certificate_cb(
5352       server_ctx_.get(),
5353       [](const SSL_CLIENT_HELLO *client_hello) -> ssl_select_cert_result_t {
5354         EXPECT_EQ(client_hello->session_id_len, 0u);
5355         return ssl_select_cert_success;
5356       });
5357 
5358   ASSERT_TRUE(CreateClientAndServer());
5359   ASSERT_TRUE(CompleteHandshakesForQUIC());
5360 
5361   ExpectHandshakeSuccess();
5362 }
5363 
5364 // Test that, even in a 1-RTT handshake, the server installs keys at the right
5365 // time. Half-RTT keys are available early, but 1-RTT read keys are deferred.
TEST_F(QUICMethodTest,HalfRTTKeys)5366 TEST_F(QUICMethodTest, HalfRTTKeys) {
5367   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5368 
5369   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5370   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5371   ASSERT_TRUE(CreateClientAndServer());
5372 
5373   // The client sends ClientHello.
5374   ASSERT_EQ(SSL_do_handshake(client_.get()), -1);
5375   ASSERT_EQ(SSL_ERROR_WANT_READ, SSL_get_error(client_.get(), -1));
5376 
5377   // The server reads ClientHello and sends ServerHello..Finished.
5378   ASSERT_TRUE(ProvideHandshakeData(server_.get()));
5379   ASSERT_EQ(SSL_do_handshake(server_.get()), -1);
5380   ASSERT_EQ(SSL_ERROR_WANT_READ, SSL_get_error(server_.get(), -1));
5381 
5382   // At this point, the server has half-RTT write keys, but it cannot access
5383   // 1-RTT read keys until client Finished.
5384   EXPECT_TRUE(transport_->server()->HasWriteSecret(ssl_encryption_application));
5385   EXPECT_FALSE(transport_->server()->HasReadSecret(ssl_encryption_application));
5386 
5387   // Finish up the client and server handshakes.
5388   ASSERT_TRUE(CompleteHandshakesForQUIC());
5389 
5390   // Both sides can now exchange 1-RTT data.
5391   ExpectHandshakeSuccess();
5392 }
5393 
TEST_F(QUICMethodTest,ZeroRTTAccept)5394 TEST_F(QUICMethodTest, ZeroRTTAccept) {
5395   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5396 
5397   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
5398   SSL_CTX_set_early_data_enabled(client_ctx_.get(), 1);
5399   SSL_CTX_set_early_data_enabled(server_ctx_.get(), 1);
5400   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5401   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5402 
5403   bssl::UniquePtr<SSL_SESSION> session = CreateClientSessionForQUIC();
5404   ASSERT_TRUE(session);
5405 
5406   ASSERT_TRUE(CreateClientAndServer());
5407   SSL_set_session(client_.get(), session.get());
5408 
5409   // The client handshake should return immediately into the early data state.
5410   ASSERT_EQ(SSL_do_handshake(client_.get()), 1);
5411   EXPECT_TRUE(SSL_in_early_data(client_.get()));
5412   // The transport should have keys for sending 0-RTT data.
5413   EXPECT_TRUE(transport_->client()->HasWriteSecret(ssl_encryption_early_data));
5414 
5415   // The server will consume the ClientHello and also enter the early data
5416   // state.
5417   ASSERT_TRUE(ProvideHandshakeData(server_.get()));
5418   ASSERT_EQ(SSL_do_handshake(server_.get()), 1);
5419   EXPECT_TRUE(SSL_in_early_data(server_.get()));
5420   EXPECT_TRUE(transport_->SecretsMatch(ssl_encryption_early_data));
5421   // At this point, the server has half-RTT write keys, but it cannot access
5422   // 1-RTT read keys until client Finished.
5423   EXPECT_TRUE(transport_->server()->HasWriteSecret(ssl_encryption_application));
5424   EXPECT_FALSE(transport_->server()->HasReadSecret(ssl_encryption_application));
5425 
5426   // Finish up the client and server handshakes.
5427   ASSERT_TRUE(CompleteHandshakesForQUIC());
5428 
5429   // Both sides can now exchange 1-RTT data.
5430   ExpectHandshakeSuccess();
5431   EXPECT_TRUE(SSL_session_reused(client_.get()));
5432   EXPECT_TRUE(SSL_session_reused(server_.get()));
5433   EXPECT_FALSE(SSL_in_early_data(client_.get()));
5434   EXPECT_FALSE(SSL_in_early_data(server_.get()));
5435   EXPECT_TRUE(SSL_early_data_accepted(client_.get()));
5436   EXPECT_TRUE(SSL_early_data_accepted(server_.get()));
5437 
5438   // Finish handling post-handshake messages after the first 0-RTT resumption.
5439   EXPECT_TRUE(ProvideHandshakeData(client_.get()));
5440   EXPECT_TRUE(SSL_process_quic_post_handshake(client_.get()));
5441 
5442   // Perform a second 0-RTT resumption attempt, and confirm that 0-RTT is
5443   // accepted again.
5444   ASSERT_TRUE(CreateClientAndServer());
5445   SSL_set_session(client_.get(), g_last_session.get());
5446 
5447   // The client handshake should return immediately into the early data state.
5448   ASSERT_EQ(SSL_do_handshake(client_.get()), 1);
5449   EXPECT_TRUE(SSL_in_early_data(client_.get()));
5450   // The transport should have keys for sending 0-RTT data.
5451   EXPECT_TRUE(transport_->client()->HasWriteSecret(ssl_encryption_early_data));
5452 
5453   // The server will consume the ClientHello and also enter the early data
5454   // state.
5455   ASSERT_TRUE(ProvideHandshakeData(server_.get()));
5456   ASSERT_EQ(SSL_do_handshake(server_.get()), 1);
5457   EXPECT_TRUE(SSL_in_early_data(server_.get()));
5458   EXPECT_TRUE(transport_->SecretsMatch(ssl_encryption_early_data));
5459   // At this point, the server has half-RTT write keys, but it cannot access
5460   // 1-RTT read keys until client Finished.
5461   EXPECT_TRUE(transport_->server()->HasWriteSecret(ssl_encryption_application));
5462   EXPECT_FALSE(transport_->server()->HasReadSecret(ssl_encryption_application));
5463 
5464   // Finish up the client and server handshakes.
5465   ASSERT_TRUE(CompleteHandshakesForQUIC());
5466 
5467   // Both sides can now exchange 1-RTT data.
5468   ExpectHandshakeSuccess();
5469   EXPECT_TRUE(SSL_session_reused(client_.get()));
5470   EXPECT_TRUE(SSL_session_reused(server_.get()));
5471   EXPECT_FALSE(SSL_in_early_data(client_.get()));
5472   EXPECT_FALSE(SSL_in_early_data(server_.get()));
5473   EXPECT_TRUE(SSL_early_data_accepted(client_.get()));
5474   EXPECT_TRUE(SSL_early_data_accepted(server_.get()));
5475   EXPECT_EQ(SSL_get_early_data_reason(client_.get()), ssl_early_data_accepted);
5476   EXPECT_EQ(SSL_get_early_data_reason(server_.get()), ssl_early_data_accepted);
5477 }
5478 
TEST_F(QUICMethodTest,ZeroRTTRejectMismatchedParameters)5479 TEST_F(QUICMethodTest, ZeroRTTRejectMismatchedParameters) {
5480   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5481 
5482   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
5483   SSL_CTX_set_early_data_enabled(client_ctx_.get(), 1);
5484   SSL_CTX_set_early_data_enabled(server_ctx_.get(), 1);
5485   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5486   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5487 
5488 
5489   bssl::UniquePtr<SSL_SESSION> session = CreateClientSessionForQUIC();
5490   ASSERT_TRUE(session);
5491 
5492   ASSERT_TRUE(CreateClientAndServer());
5493   static const uint8_t new_context[] = {4};
5494   ASSERT_TRUE(SSL_set_quic_early_data_context(server_.get(), new_context,
5495                                               sizeof(new_context)));
5496   SSL_set_session(client_.get(), session.get());
5497 
5498   // The client handshake should return immediately into the early data
5499   // state.
5500   ASSERT_EQ(SSL_do_handshake(client_.get()), 1);
5501   EXPECT_TRUE(SSL_in_early_data(client_.get()));
5502   // The transport should have keys for sending 0-RTT data.
5503   EXPECT_TRUE(transport_->client()->HasWriteSecret(ssl_encryption_early_data));
5504 
5505   // The server will consume the ClientHello, but it will not accept 0-RTT.
5506   ASSERT_TRUE(ProvideHandshakeData(server_.get()));
5507   ASSERT_EQ(SSL_do_handshake(server_.get()), -1);
5508   EXPECT_EQ(SSL_ERROR_WANT_READ, SSL_get_error(server_.get(), -1));
5509   EXPECT_FALSE(SSL_in_early_data(server_.get()));
5510   EXPECT_FALSE(transport_->server()->HasReadSecret(ssl_encryption_early_data));
5511 
5512   // The client consumes the server response and signals 0-RTT rejection.
5513   for (;;) {
5514     ASSERT_TRUE(ProvideHandshakeData(client_.get()));
5515     ASSERT_EQ(-1, SSL_do_handshake(client_.get()));
5516     int err = SSL_get_error(client_.get(), -1);
5517     if (err == SSL_ERROR_EARLY_DATA_REJECTED) {
5518       break;
5519     }
5520     ASSERT_EQ(SSL_ERROR_WANT_READ, err);
5521   }
5522 
5523   // As in TLS over TCP, 0-RTT rejection is sticky.
5524   ASSERT_EQ(-1, SSL_do_handshake(client_.get()));
5525   ASSERT_EQ(SSL_ERROR_EARLY_DATA_REJECTED, SSL_get_error(client_.get(), -1));
5526 
5527   // Finish up the client and server handshakes.
5528   SSL_reset_early_data_reject(client_.get());
5529   ASSERT_TRUE(CompleteHandshakesForQUIC());
5530 
5531   // Both sides can now exchange 1-RTT data.
5532   ExpectHandshakeSuccess();
5533   EXPECT_TRUE(SSL_session_reused(client_.get()));
5534   EXPECT_TRUE(SSL_session_reused(server_.get()));
5535   EXPECT_FALSE(SSL_in_early_data(client_.get()));
5536   EXPECT_FALSE(SSL_in_early_data(server_.get()));
5537   EXPECT_FALSE(SSL_early_data_accepted(client_.get()));
5538   EXPECT_FALSE(SSL_early_data_accepted(server_.get()));
5539 }
5540 
TEST_F(QUICMethodTest,NoZeroRTTTicketWithoutEarlyDataContext)5541 TEST_F(QUICMethodTest, NoZeroRTTTicketWithoutEarlyDataContext) {
5542   server_quic_early_data_context_ = {};
5543   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5544 
5545   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
5546   SSL_CTX_set_early_data_enabled(client_ctx_.get(), 1);
5547   SSL_CTX_set_early_data_enabled(server_ctx_.get(), 1);
5548   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5549   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5550 
5551   bssl::UniquePtr<SSL_SESSION> session = CreateClientSessionForQUIC();
5552   ASSERT_TRUE(session);
5553   EXPECT_FALSE(SSL_SESSION_early_data_capable(session.get()));
5554 }
5555 
TEST_F(QUICMethodTest,ZeroRTTReject)5556 TEST_F(QUICMethodTest, ZeroRTTReject) {
5557   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5558 
5559   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
5560   SSL_CTX_set_early_data_enabled(client_ctx_.get(), 1);
5561   SSL_CTX_set_early_data_enabled(server_ctx_.get(), 1);
5562   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5563   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5564 
5565   bssl::UniquePtr<SSL_SESSION> session = CreateClientSessionForQUIC();
5566   ASSERT_TRUE(session);
5567 
5568   for (bool reject_hrr : {false, true}) {
5569     SCOPED_TRACE(reject_hrr);
5570 
5571     ASSERT_TRUE(CreateClientAndServer());
5572     if (reject_hrr) {
5573       // Configure the server to prefer P-256, which will reject 0-RTT via
5574       // HelloRetryRequest.
5575       int p256 = NID_X9_62_prime256v1;
5576       ASSERT_TRUE(SSL_set1_curves(server_.get(), &p256, 1));
5577     } else {
5578       // Disable 0-RTT on the server, so it will reject it.
5579       SSL_set_early_data_enabled(server_.get(), 0);
5580     }
5581     SSL_set_session(client_.get(), session.get());
5582 
5583     // The client handshake should return immediately into the early data state.
5584     ASSERT_EQ(SSL_do_handshake(client_.get()), 1);
5585     EXPECT_TRUE(SSL_in_early_data(client_.get()));
5586     // The transport should have keys for sending 0-RTT data.
5587     EXPECT_TRUE(
5588         transport_->client()->HasWriteSecret(ssl_encryption_early_data));
5589 
5590     // The server will consume the ClientHello, but it will not accept 0-RTT.
5591     ASSERT_TRUE(ProvideHandshakeData(server_.get()));
5592     ASSERT_EQ(SSL_do_handshake(server_.get()), -1);
5593     EXPECT_EQ(SSL_ERROR_WANT_READ, SSL_get_error(server_.get(), -1));
5594     EXPECT_FALSE(SSL_in_early_data(server_.get()));
5595     EXPECT_FALSE(
5596         transport_->server()->HasReadSecret(ssl_encryption_early_data));
5597 
5598     // The client consumes the server response and signals 0-RTT rejection.
5599     for (;;) {
5600       ASSERT_TRUE(ProvideHandshakeData(client_.get()));
5601       ASSERT_EQ(-1, SSL_do_handshake(client_.get()));
5602       int err = SSL_get_error(client_.get(), -1);
5603       if (err == SSL_ERROR_EARLY_DATA_REJECTED) {
5604         break;
5605       }
5606       ASSERT_EQ(SSL_ERROR_WANT_READ, err);
5607     }
5608 
5609     // As in TLS over TCP, 0-RTT rejection is sticky.
5610     ASSERT_EQ(-1, SSL_do_handshake(client_.get()));
5611     ASSERT_EQ(SSL_ERROR_EARLY_DATA_REJECTED, SSL_get_error(client_.get(), -1));
5612 
5613     // Finish up the client and server handshakes.
5614     SSL_reset_early_data_reject(client_.get());
5615     ASSERT_TRUE(CompleteHandshakesForQUIC());
5616 
5617     // Both sides can now exchange 1-RTT data.
5618     ExpectHandshakeSuccess();
5619     EXPECT_TRUE(SSL_session_reused(client_.get()));
5620     EXPECT_TRUE(SSL_session_reused(server_.get()));
5621     EXPECT_FALSE(SSL_in_early_data(client_.get()));
5622     EXPECT_FALSE(SSL_in_early_data(server_.get()));
5623     EXPECT_FALSE(SSL_early_data_accepted(client_.get()));
5624     EXPECT_FALSE(SSL_early_data_accepted(server_.get()));
5625   }
5626 }
5627 
TEST_F(QUICMethodTest,NoZeroRTTKeysBeforeReverify)5628 TEST_F(QUICMethodTest, NoZeroRTTKeysBeforeReverify) {
5629   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5630 
5631   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
5632   SSL_CTX_set_early_data_enabled(client_ctx_.get(), 1);
5633   SSL_CTX_set_reverify_on_resume(client_ctx_.get(), 1);
5634   SSL_CTX_set_early_data_enabled(server_ctx_.get(), 1);
5635   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5636   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5637 
5638   bssl::UniquePtr<SSL_SESSION> session = CreateClientSessionForQUIC();
5639   ASSERT_TRUE(session);
5640 
5641   ASSERT_TRUE(CreateClientAndServer());
5642   SSL_set_session(client_.get(), session.get());
5643 
5644   // Configure the certificate (re)verification to never complete. The client
5645   // handshake should pause.
5646   SSL_set_custom_verify(
5647       client_.get(), SSL_VERIFY_PEER,
5648       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
5649         return ssl_verify_retry;
5650       });
5651   ASSERT_EQ(SSL_do_handshake(client_.get()), -1);
5652   ASSERT_EQ(SSL_get_error(client_.get(), -1),
5653             SSL_ERROR_WANT_CERTIFICATE_VERIFY);
5654 
5655   // The early data keys have not yet been released.
5656   EXPECT_FALSE(transport_->client()->HasWriteSecret(ssl_encryption_early_data));
5657 
5658   // After the verification completes, the handshake progresses to the 0-RTT
5659   // point and releases keys.
5660   SSL_set_custom_verify(
5661       client_.get(), SSL_VERIFY_PEER,
5662       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
5663         return ssl_verify_ok;
5664       });
5665   ASSERT_EQ(SSL_do_handshake(client_.get()), 1);
5666   EXPECT_TRUE(SSL_in_early_data(client_.get()));
5667   EXPECT_TRUE(transport_->client()->HasWriteSecret(ssl_encryption_early_data));
5668 }
5669 
5670 // Test only releasing data to QUIC one byte at a time on request, to maximize
5671 // state machine pauses. Additionally, test that existing asynchronous callbacks
5672 // still work.
TEST_F(QUICMethodTest,Async)5673 TEST_F(QUICMethodTest, Async) {
5674   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5675 
5676   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5677   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5678   ASSERT_TRUE(CreateClientAndServer());
5679 
5680   // Install an asynchronous certificate callback.
5681   bool cert_cb_ok = false;
5682   SSL_set_cert_cb(server_.get(),
5683                   [](SSL *, void *arg) -> int {
5684                     return *static_cast<bool *>(arg) ? 1 : -1;
5685                   },
5686                   &cert_cb_ok);
5687 
5688   for (;;) {
5689     int client_ret = SSL_do_handshake(client_.get());
5690     if (client_ret != 1) {
5691       ASSERT_EQ(client_ret, -1);
5692       ASSERT_EQ(SSL_get_error(client_.get(), client_ret), SSL_ERROR_WANT_READ);
5693       ASSERT_TRUE(ProvideHandshakeData(client_.get(), 1));
5694     }
5695 
5696     int server_ret = SSL_do_handshake(server_.get());
5697     if (server_ret != 1) {
5698       ASSERT_EQ(server_ret, -1);
5699       int ssl_err = SSL_get_error(server_.get(), server_ret);
5700       switch (ssl_err) {
5701         case SSL_ERROR_WANT_READ:
5702           ASSERT_TRUE(ProvideHandshakeData(server_.get(), 1));
5703           break;
5704         case SSL_ERROR_WANT_X509_LOOKUP:
5705           ASSERT_FALSE(cert_cb_ok);
5706           cert_cb_ok = true;
5707           break;
5708         default:
5709           FAIL() << "Unexpected SSL_get_error result: " << ssl_err;
5710       }
5711     }
5712 
5713     if (client_ret == 1 && server_ret == 1) {
5714       break;
5715     }
5716   }
5717 
5718   ExpectHandshakeSuccess();
5719 }
5720 
5721 // Test buffering write data until explicit flushes.
TEST_F(QUICMethodTest,Buffered)5722 TEST_F(QUICMethodTest, Buffered) {
5723   AllowOutOfOrderWrites();
5724 
5725   struct BufferedFlight {
5726     std::vector<uint8_t> data[kNumQUICLevels];
5727   };
5728   static UnownedSSLExData<BufferedFlight> buffered_flights;
5729 
5730   auto add_handshake_data = [](SSL *ssl, enum ssl_encryption_level_t level,
5731                                const uint8_t *data, size_t len) -> int {
5732     BufferedFlight *flight = buffered_flights.Get(ssl);
5733     flight->data[level].insert(flight->data[level].end(), data, data + len);
5734     return 1;
5735   };
5736 
5737   auto flush_flight = [](SSL *ssl) -> int {
5738     BufferedFlight *flight = buffered_flights.Get(ssl);
5739     for (size_t level = 0; level < kNumQUICLevels; level++) {
5740       if (!flight->data[level].empty()) {
5741         if (!TransportFromSSL(ssl)->WriteHandshakeData(
5742                 static_cast<ssl_encryption_level_t>(level),
5743                 flight->data[level])) {
5744           return 0;
5745         }
5746         flight->data[level].clear();
5747       }
5748     }
5749     return 1;
5750   };
5751 
5752   SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5753   quic_method.add_handshake_data = add_handshake_data;
5754   quic_method.flush_flight = flush_flight;
5755 
5756   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5757   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5758   ASSERT_TRUE(CreateClientAndServer());
5759 
5760   BufferedFlight client_flight, server_flight;
5761   buffered_flights.Set(client_.get(), &client_flight);
5762   buffered_flights.Set(server_.get(), &server_flight);
5763 
5764   ASSERT_TRUE(CompleteHandshakesForQUIC());
5765 
5766   ExpectHandshakeSuccess();
5767 }
5768 
5769 // Test that excess data at one level is rejected. That is, if a single
5770 // |SSL_provide_quic_data| call included both ServerHello and
5771 // EncryptedExtensions in a single chunk, BoringSSL notices and rejects this on
5772 // key change.
TEST_F(QUICMethodTest,ExcessProvidedData)5773 TEST_F(QUICMethodTest, ExcessProvidedData) {
5774   AllowOutOfOrderWrites();
5775 
5776   auto add_handshake_data = [](SSL *ssl, enum ssl_encryption_level_t level,
5777                                const uint8_t *data, size_t len) -> int {
5778     // Switch everything to the initial level.
5779     return TransportFromSSL(ssl)->WriteHandshakeData(ssl_encryption_initial,
5780                                                      MakeConstSpan(data, len));
5781   };
5782 
5783   SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5784   quic_method.add_handshake_data = add_handshake_data;
5785 
5786   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5787   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5788   ASSERT_TRUE(CreateClientAndServer());
5789 
5790   // Send the ClientHello and ServerHello through Finished.
5791   ASSERT_EQ(SSL_do_handshake(client_.get()), -1);
5792   ASSERT_EQ(SSL_get_error(client_.get(), -1), SSL_ERROR_WANT_READ);
5793   ASSERT_TRUE(ProvideHandshakeData(server_.get()));
5794   ASSERT_EQ(SSL_do_handshake(server_.get()), -1);
5795   ASSERT_EQ(SSL_get_error(server_.get(), -1), SSL_ERROR_WANT_READ);
5796 
5797   // The client is still waiting for the ServerHello at initial
5798   // encryption.
5799   ASSERT_EQ(ssl_encryption_initial, SSL_quic_read_level(client_.get()));
5800 
5801   // |add_handshake_data| incorrectly wrote everything at the initial level, so
5802   // this queues up ServerHello through Finished in one chunk.
5803   ASSERT_TRUE(ProvideHandshakeData(client_.get()));
5804 
5805   // The client reads ServerHello successfully, but then rejects the buffered
5806   // EncryptedExtensions on key change.
5807   ASSERT_EQ(SSL_do_handshake(client_.get()), -1);
5808   ASSERT_EQ(SSL_get_error(client_.get(), -1), SSL_ERROR_SSL);
5809   uint32_t err = ERR_get_error();
5810   EXPECT_EQ(ERR_GET_LIB(err), ERR_LIB_SSL);
5811   EXPECT_EQ(ERR_GET_REASON(err), SSL_R_EXCESS_HANDSHAKE_DATA);
5812 
5813   // The client sends an alert in response to this. The alert is sent at
5814   // handshake level because we install write secrets before read secrets and
5815   // the error is discovered when installing the read secret. (How to send
5816   // alerts on protocol syntax errors near key changes is ambiguous in general.)
5817   ASSERT_TRUE(transport_->client()->has_alert());
5818   EXPECT_EQ(transport_->client()->alert_level(), ssl_encryption_handshake);
5819   EXPECT_EQ(transport_->client()->alert(), SSL_AD_UNEXPECTED_MESSAGE);
5820 
5821   // Sanity-check handshake secrets. The error is discovered while setting the
5822   // read secret, so only the write secret has been installed.
5823   EXPECT_TRUE(transport_->client()->HasWriteSecret(ssl_encryption_handshake));
5824   EXPECT_FALSE(transport_->client()->HasReadSecret(ssl_encryption_handshake));
5825 }
5826 
5827 // Test that |SSL_provide_quic_data| will reject data at the wrong level.
TEST_F(QUICMethodTest,ProvideWrongLevel)5828 TEST_F(QUICMethodTest, ProvideWrongLevel) {
5829   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5830 
5831   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5832   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5833   ASSERT_TRUE(CreateClientAndServer());
5834 
5835   // Send the ClientHello and ServerHello through Finished.
5836   ASSERT_EQ(SSL_do_handshake(client_.get()), -1);
5837   ASSERT_EQ(SSL_get_error(client_.get(), -1), SSL_ERROR_WANT_READ);
5838   ASSERT_TRUE(ProvideHandshakeData(server_.get()));
5839   ASSERT_EQ(SSL_do_handshake(server_.get()), -1);
5840   ASSERT_EQ(SSL_get_error(server_.get(), -1), SSL_ERROR_WANT_READ);
5841 
5842   // The client is still waiting for the ServerHello at initial
5843   // encryption.
5844   ASSERT_EQ(ssl_encryption_initial, SSL_quic_read_level(client_.get()));
5845 
5846   // Data cannot be provided at the next level.
5847   std::vector<uint8_t> data;
5848   ASSERT_TRUE(
5849       transport_->client()->ReadHandshakeData(&data, ssl_encryption_initial));
5850   ASSERT_FALSE(SSL_provide_quic_data(client_.get(), ssl_encryption_handshake,
5851                                      data.data(), data.size()));
5852   ERR_clear_error();
5853 
5854   // Progress to EncryptedExtensions.
5855   ASSERT_TRUE(SSL_provide_quic_data(client_.get(), ssl_encryption_initial,
5856                                     data.data(), data.size()));
5857   ASSERT_EQ(SSL_do_handshake(client_.get()), -1);
5858   ASSERT_EQ(SSL_get_error(client_.get(), -1), SSL_ERROR_WANT_READ);
5859   ASSERT_EQ(ssl_encryption_handshake, SSL_quic_read_level(client_.get()));
5860 
5861   // Data cannot be provided at the previous level.
5862   ASSERT_TRUE(
5863       transport_->client()->ReadHandshakeData(&data, ssl_encryption_handshake));
5864   ASSERT_FALSE(SSL_provide_quic_data(client_.get(), ssl_encryption_initial,
5865                                      data.data(), data.size()));
5866 }
5867 
TEST_F(QUICMethodTest,TooMuchData)5868 TEST_F(QUICMethodTest, TooMuchData) {
5869   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5870 
5871   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5872   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5873   ASSERT_TRUE(CreateClientAndServer());
5874 
5875   size_t limit =
5876       SSL_quic_max_handshake_flight_len(client_.get(), ssl_encryption_initial);
5877   uint8_t b = 0;
5878   for (size_t i = 0; i < limit; i++) {
5879     ASSERT_TRUE(
5880         SSL_provide_quic_data(client_.get(), ssl_encryption_initial, &b, 1));
5881   }
5882 
5883   EXPECT_FALSE(
5884       SSL_provide_quic_data(client_.get(), ssl_encryption_initial, &b, 1));
5885 }
5886 
5887 // Provide invalid post-handshake data.
TEST_F(QUICMethodTest,BadPostHandshake)5888 TEST_F(QUICMethodTest, BadPostHandshake) {
5889   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5890 
5891   g_last_session = nullptr;
5892 
5893   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
5894   SSL_CTX_sess_set_new_cb(client_ctx_.get(), SaveLastSession);
5895   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5896   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5897   ASSERT_TRUE(CreateClientAndServer());
5898   ASSERT_TRUE(CompleteHandshakesForQUIC());
5899 
5900   EXPECT_EQ(SSL_do_handshake(client_.get()), 1);
5901   EXPECT_EQ(SSL_do_handshake(server_.get()), 1);
5902   EXPECT_TRUE(transport_->SecretsMatch(ssl_encryption_application));
5903   EXPECT_FALSE(transport_->client()->has_alert());
5904   EXPECT_FALSE(transport_->server()->has_alert());
5905 
5906   // Junk sent as part of post-handshake data should cause an error.
5907   uint8_t kJunk[] = {0x17, 0x0, 0x0, 0x4, 0xB, 0xE, 0xE, 0xF};
5908   ASSERT_TRUE(SSL_provide_quic_data(client_.get(), ssl_encryption_application,
5909                                     kJunk, sizeof(kJunk)));
5910   EXPECT_EQ(SSL_process_quic_post_handshake(client_.get()), 0);
5911 }
5912 
ExpectReceivedTransportParamsEqual(const SSL * ssl,Span<const uint8_t> expected)5913 static void ExpectReceivedTransportParamsEqual(const SSL *ssl,
5914                                                Span<const uint8_t> expected) {
5915   const uint8_t *received;
5916   size_t received_len;
5917   SSL_get_peer_quic_transport_params(ssl, &received, &received_len);
5918   ASSERT_EQ(received_len, expected.size());
5919   EXPECT_EQ(Bytes(received, received_len), Bytes(expected));
5920 }
5921 
TEST_F(QUICMethodTest,SetTransportParameters)5922 TEST_F(QUICMethodTest, SetTransportParameters) {
5923   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5924   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5925   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5926 
5927   ASSERT_TRUE(CreateClientAndServer());
5928   uint8_t kClientParams[] = {1, 2, 3, 4};
5929   uint8_t kServerParams[] = {5, 6, 7};
5930   ASSERT_TRUE(SSL_set_quic_transport_params(client_.get(), kClientParams,
5931                                             sizeof(kClientParams)));
5932   ASSERT_TRUE(SSL_set_quic_transport_params(server_.get(), kServerParams,
5933                                             sizeof(kServerParams)));
5934 
5935   ASSERT_TRUE(CompleteHandshakesForQUIC());
5936   ExpectReceivedTransportParamsEqual(client_.get(), kServerParams);
5937   ExpectReceivedTransportParamsEqual(server_.get(), kClientParams);
5938 }
5939 
TEST_F(QUICMethodTest,SetTransportParamsInCallback)5940 TEST_F(QUICMethodTest, SetTransportParamsInCallback) {
5941   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5942   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5943   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5944 
5945   ASSERT_TRUE(CreateClientAndServer());
5946   uint8_t kClientParams[] = {1, 2, 3, 4};
5947   static uint8_t kServerParams[] = {5, 6, 7};
5948   ASSERT_TRUE(SSL_set_quic_transport_params(client_.get(), kClientParams,
5949                                             sizeof(kClientParams)));
5950   SSL_CTX_set_tlsext_servername_callback(
5951       server_ctx_.get(), [](SSL *ssl, int *out_alert, void *arg) -> int {
5952         EXPECT_TRUE(SSL_set_quic_transport_params(ssl, kServerParams,
5953                                                   sizeof(kServerParams)));
5954         return SSL_TLSEXT_ERR_OK;
5955       });
5956 
5957   ASSERT_TRUE(CompleteHandshakesForQUIC());
5958   ExpectReceivedTransportParamsEqual(client_.get(), kServerParams);
5959   ExpectReceivedTransportParamsEqual(server_.get(), kClientParams);
5960 }
5961 
TEST_F(QUICMethodTest,ForbidCrossProtocolResumptionClient)5962 TEST_F(QUICMethodTest, ForbidCrossProtocolResumptionClient) {
5963   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
5964 
5965   g_last_session = nullptr;
5966 
5967   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
5968   SSL_CTX_sess_set_new_cb(client_ctx_.get(), SaveLastSession);
5969   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
5970   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
5971 
5972   ASSERT_TRUE(CreateClientAndServer());
5973   ASSERT_TRUE(CompleteHandshakesForQUIC());
5974 
5975   ExpectHandshakeSuccess();
5976   EXPECT_FALSE(SSL_session_reused(client_.get()));
5977   EXPECT_FALSE(SSL_session_reused(server_.get()));
5978 
5979   // The server sent NewSessionTicket messages in the handshake.
5980   EXPECT_FALSE(g_last_session);
5981   ASSERT_TRUE(ProvideHandshakeData(client_.get()));
5982   EXPECT_EQ(SSL_process_quic_post_handshake(client_.get()), 1);
5983   EXPECT_TRUE(g_last_session);
5984 
5985   // Pretend that g_last_session came from a TLS-over-TCP connection.
5986   g_last_session.get()->is_quic = false;
5987 
5988   // Create a second connection and verify that resumption does not occur with
5989   // a session from a non-QUIC connection. This tests that the client does not
5990   // offer over QUIC a session believed to be received over TCP. The server
5991   // believes this is a QUIC session, so if the client offered the session, the
5992   // server would have resumed it.
5993   ASSERT_TRUE(CreateClientAndServer());
5994   bssl::UniquePtr<SSL_SESSION> session = std::move(g_last_session);
5995   SSL_set_session(client_.get(), session.get());
5996 
5997   ASSERT_TRUE(CompleteHandshakesForQUIC());
5998   ExpectHandshakeSuccess();
5999   EXPECT_FALSE(SSL_session_reused(client_.get()));
6000   EXPECT_FALSE(SSL_session_reused(server_.get()));
6001 }
6002 
TEST_F(QUICMethodTest,ForbidCrossProtocolResumptionServer)6003 TEST_F(QUICMethodTest, ForbidCrossProtocolResumptionServer) {
6004   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
6005 
6006   g_last_session = nullptr;
6007 
6008   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
6009   SSL_CTX_sess_set_new_cb(client_ctx_.get(), SaveLastSession);
6010   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
6011   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
6012 
6013   ASSERT_TRUE(CreateClientAndServer());
6014   ASSERT_TRUE(CompleteHandshakesForQUIC());
6015 
6016   ExpectHandshakeSuccess();
6017   EXPECT_FALSE(SSL_session_reused(client_.get()));
6018   EXPECT_FALSE(SSL_session_reused(server_.get()));
6019 
6020   // The server sent NewSessionTicket messages in the handshake.
6021   EXPECT_FALSE(g_last_session);
6022   ASSERT_TRUE(ProvideHandshakeData(client_.get()));
6023   EXPECT_EQ(SSL_process_quic_post_handshake(client_.get()), 1);
6024   EXPECT_TRUE(g_last_session);
6025 
6026   // Attempt a resumption with g_last_session using TLS_method.
6027   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
6028   ASSERT_TRUE(client_ctx);
6029 
6030   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), nullptr));
6031 
6032   bssl::UniquePtr<SSL> client(SSL_new(client_ctx.get())),
6033       server(SSL_new(server_ctx_.get()));
6034   ASSERT_TRUE(client);
6035   ASSERT_TRUE(server);
6036   SSL_set_connect_state(client.get());
6037   SSL_set_accept_state(server.get());
6038 
6039   // The TLS-over-TCP client will refuse to resume with a quic session, so
6040   // mark is_quic = false to bypass the client check to test the server check.
6041   g_last_session.get()->is_quic = false;
6042   SSL_set_session(client.get(), g_last_session.get());
6043 
6044   BIO *bio1, *bio2;
6045   ASSERT_TRUE(BIO_new_bio_pair(&bio1, 0, &bio2, 0));
6046 
6047   // SSL_set_bio takes ownership.
6048   SSL_set_bio(client.get(), bio1, bio1);
6049   SSL_set_bio(server.get(), bio2, bio2);
6050   ASSERT_TRUE(CompleteHandshakes(client.get(), server.get()));
6051 
6052   EXPECT_FALSE(SSL_session_reused(client.get()));
6053   EXPECT_FALSE(SSL_session_reused(server.get()));
6054 }
6055 
TEST_F(QUICMethodTest,ClientRejectsMissingTransportParams)6056 TEST_F(QUICMethodTest, ClientRejectsMissingTransportParams) {
6057   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
6058   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
6059   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
6060 
6061   ASSERT_TRUE(CreateClientAndServer());
6062   ASSERT_TRUE(SSL_set_quic_transport_params(server_.get(), nullptr, 0));
6063   ASSERT_TRUE(RunQUICHandshakesAndExpectError(ExpectedError::kServerError));
6064 }
6065 
TEST_F(QUICMethodTest,ServerRejectsMissingTransportParams)6066 TEST_F(QUICMethodTest, ServerRejectsMissingTransportParams) {
6067   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
6068   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
6069   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
6070 
6071   ASSERT_TRUE(CreateClientAndServer());
6072   ASSERT_TRUE(SSL_set_quic_transport_params(client_.get(), nullptr, 0));
6073   ASSERT_TRUE(RunQUICHandshakesAndExpectError(ExpectedError::kClientError));
6074 }
6075 
TEST_F(QUICMethodTest,QuicLegacyCodepointEnabled)6076 TEST_F(QUICMethodTest, QuicLegacyCodepointEnabled) {
6077   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
6078   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
6079   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
6080 
6081   ASSERT_TRUE(CreateClientAndServer());
6082   uint8_t kClientParams[] = {1, 2, 3, 4};
6083   uint8_t kServerParams[] = {5, 6, 7};
6084   SSL_set_quic_use_legacy_codepoint(client_.get(), 1);
6085   SSL_set_quic_use_legacy_codepoint(server_.get(), 1);
6086   ASSERT_TRUE(SSL_set_quic_transport_params(client_.get(), kClientParams,
6087                                             sizeof(kClientParams)));
6088   ASSERT_TRUE(SSL_set_quic_transport_params(server_.get(), kServerParams,
6089                                             sizeof(kServerParams)));
6090 
6091   ASSERT_TRUE(CompleteHandshakesForQUIC());
6092   ExpectReceivedTransportParamsEqual(client_.get(), kServerParams);
6093   ExpectReceivedTransportParamsEqual(server_.get(), kClientParams);
6094 }
6095 
TEST_F(QUICMethodTest,QuicLegacyCodepointDisabled)6096 TEST_F(QUICMethodTest, QuicLegacyCodepointDisabled) {
6097   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
6098   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
6099   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
6100 
6101   ASSERT_TRUE(CreateClientAndServer());
6102   uint8_t kClientParams[] = {1, 2, 3, 4};
6103   uint8_t kServerParams[] = {5, 6, 7};
6104   SSL_set_quic_use_legacy_codepoint(client_.get(), 0);
6105   SSL_set_quic_use_legacy_codepoint(server_.get(), 0);
6106   ASSERT_TRUE(SSL_set_quic_transport_params(client_.get(), kClientParams,
6107                                             sizeof(kClientParams)));
6108   ASSERT_TRUE(SSL_set_quic_transport_params(server_.get(), kServerParams,
6109                                             sizeof(kServerParams)));
6110 
6111   ASSERT_TRUE(CompleteHandshakesForQUIC());
6112   ExpectReceivedTransportParamsEqual(client_.get(), kServerParams);
6113   ExpectReceivedTransportParamsEqual(server_.get(), kClientParams);
6114 }
6115 
TEST_F(QUICMethodTest,QuicLegacyCodepointClientOnly)6116 TEST_F(QUICMethodTest, QuicLegacyCodepointClientOnly) {
6117   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
6118   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
6119   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
6120 
6121   ASSERT_TRUE(CreateClientAndServer());
6122   uint8_t kClientParams[] = {1, 2, 3, 4};
6123   uint8_t kServerParams[] = {5, 6, 7};
6124   SSL_set_quic_use_legacy_codepoint(client_.get(), 1);
6125   SSL_set_quic_use_legacy_codepoint(server_.get(), 0);
6126   ASSERT_TRUE(SSL_set_quic_transport_params(client_.get(), kClientParams,
6127                                             sizeof(kClientParams)));
6128   ASSERT_TRUE(SSL_set_quic_transport_params(server_.get(), kServerParams,
6129                                             sizeof(kServerParams)));
6130 
6131   ASSERT_TRUE(RunQUICHandshakesAndExpectError(ExpectedError::kServerError));
6132 }
6133 
TEST_F(QUICMethodTest,QuicLegacyCodepointServerOnly)6134 TEST_F(QUICMethodTest, QuicLegacyCodepointServerOnly) {
6135   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
6136   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
6137   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
6138 
6139   ASSERT_TRUE(CreateClientAndServer());
6140   uint8_t kClientParams[] = {1, 2, 3, 4};
6141   uint8_t kServerParams[] = {5, 6, 7};
6142   SSL_set_quic_use_legacy_codepoint(client_.get(), 0);
6143   SSL_set_quic_use_legacy_codepoint(server_.get(), 1);
6144   ASSERT_TRUE(SSL_set_quic_transport_params(client_.get(), kClientParams,
6145                                             sizeof(kClientParams)));
6146   ASSERT_TRUE(SSL_set_quic_transport_params(server_.get(), kServerParams,
6147                                             sizeof(kServerParams)));
6148 
6149   ASSERT_TRUE(RunQUICHandshakesAndExpectError(ExpectedError::kServerError));
6150 }
6151 
6152 // Test that the default QUIC code point is consistent with
6153 // |TLSEXT_TYPE_quic_transport_parameters|. This test ensures we remember to
6154 // update the two values together.
TEST_F(QUICMethodTest,QuicCodePointDefault)6155 TEST_F(QUICMethodTest, QuicCodePointDefault) {
6156   const SSL_QUIC_METHOD quic_method = DefaultQUICMethod();
6157   ASSERT_TRUE(SSL_CTX_set_quic_method(client_ctx_.get(), &quic_method));
6158   ASSERT_TRUE(SSL_CTX_set_quic_method(server_ctx_.get(), &quic_method));
6159   SSL_CTX_set_select_certificate_cb(
6160       server_ctx_.get(),
6161       [](const SSL_CLIENT_HELLO *client_hello) -> ssl_select_cert_result_t {
6162         const uint8_t *data;
6163         size_t len;
6164         if (!SSL_early_callback_ctx_extension_get(
6165                 client_hello, TLSEXT_TYPE_quic_transport_parameters, &data,
6166                 &len)) {
6167           ADD_FAILURE() << "Could not find quic_transport_parameters extension";
6168           return ssl_select_cert_error;
6169         }
6170         return ssl_select_cert_success;
6171       });
6172 
6173   ASSERT_TRUE(CreateClientAndServer());
6174   ASSERT_TRUE(CompleteHandshakesForQUIC());
6175 }
6176 
6177 extern "C" {
6178 int BORINGSSL_enum_c_type_test(void);
6179 }
6180 
TEST(SSLTest,EnumTypes)6181 TEST(SSLTest, EnumTypes) {
6182   EXPECT_EQ(sizeof(int), sizeof(ssl_private_key_result_t));
6183   EXPECT_EQ(1, BORINGSSL_enum_c_type_test());
6184 }
6185 
TEST_P(SSLVersionTest,DoubleSSLError)6186 TEST_P(SSLVersionTest, DoubleSSLError) {
6187   // Connect the inner SSL connections.
6188   ASSERT_TRUE(Connect());
6189 
6190   // Make a pair of |BIO|s which wrap |client_| and |server_|.
6191   UniquePtr<BIO_METHOD> bio_method(BIO_meth_new(0, nullptr));
6192   ASSERT_TRUE(bio_method);
6193   ASSERT_TRUE(BIO_meth_set_read(
6194       bio_method.get(), [](BIO *bio, char *out, int len) -> int {
6195         SSL *ssl = static_cast<SSL *>(BIO_get_data(bio));
6196         int ret = SSL_read(ssl, out, len);
6197         int ssl_ret = SSL_get_error(ssl, ret);
6198         if (ssl_ret == SSL_ERROR_WANT_READ) {
6199           BIO_set_retry_read(bio);
6200         }
6201         return ret;
6202       }));
6203   ASSERT_TRUE(BIO_meth_set_write(
6204       bio_method.get(), [](BIO *bio, const char *in, int len) -> int {
6205         SSL *ssl = static_cast<SSL *>(BIO_get_data(bio));
6206         int ret = SSL_write(ssl, in, len);
6207         int ssl_ret = SSL_get_error(ssl, ret);
6208         if (ssl_ret == SSL_ERROR_WANT_WRITE) {
6209           BIO_set_retry_write(bio);
6210         }
6211         return ret;
6212       }));
6213   ASSERT_TRUE(BIO_meth_set_ctrl(
6214       bio_method.get(), [](BIO *bio, int cmd, long larg, void *parg) -> long {
6215         // |SSL| objects require |BIO_flush| support.
6216         if (cmd == BIO_CTRL_FLUSH) {
6217           return 1;
6218         }
6219         return 0;
6220       }));
6221 
6222   UniquePtr<BIO> client_bio(BIO_new(bio_method.get()));
6223   ASSERT_TRUE(client_bio);
6224   BIO_set_data(client_bio.get(), client_.get());
6225   BIO_set_init(client_bio.get(), 1);
6226 
6227   UniquePtr<BIO> server_bio(BIO_new(bio_method.get()));
6228   ASSERT_TRUE(server_bio);
6229   BIO_set_data(server_bio.get(), server_.get());
6230   BIO_set_init(server_bio.get(), 1);
6231 
6232   // Wrap the inner connections in another layer of SSL.
6233   UniquePtr<SSL> client_outer(SSL_new(client_ctx_.get()));
6234   ASSERT_TRUE(client_outer);
6235   SSL_set_connect_state(client_outer.get());
6236   SSL_set_bio(client_outer.get(), client_bio.get(), client_bio.get());
6237   client_bio.release();  // |SSL_set_bio| takes ownership.
6238 
6239   UniquePtr<SSL> server_outer(SSL_new(server_ctx_.get()));
6240   ASSERT_TRUE(server_outer);
6241   SSL_set_accept_state(server_outer.get());
6242   SSL_set_bio(server_outer.get(), server_bio.get(), server_bio.get());
6243   server_bio.release();  // |SSL_set_bio| takes ownership.
6244 
6245   // Configure |client_outer| to reject the server certificate.
6246   SSL_set_custom_verify(
6247       client_outer.get(), SSL_VERIFY_PEER,
6248       [](SSL *ssl, uint8_t *out_alert) -> ssl_verify_result_t {
6249         return ssl_verify_invalid;
6250       });
6251 
6252   for (;;) {
6253     int client_ret = SSL_do_handshake(client_outer.get());
6254     int client_err = SSL_get_error(client_outer.get(), client_ret);
6255     if (client_err != SSL_ERROR_WANT_READ &&
6256         client_err != SSL_ERROR_WANT_WRITE) {
6257       // The client handshake should terminate on a certificate verification
6258       // error.
6259       EXPECT_EQ(SSL_ERROR_SSL, client_err);
6260       uint32_t err = ERR_peek_error();
6261       EXPECT_EQ(ERR_LIB_SSL, ERR_GET_LIB(err));
6262       EXPECT_EQ(SSL_R_CERTIFICATE_VERIFY_FAILED, ERR_GET_REASON(err));
6263       break;
6264     }
6265 
6266     // Run the server handshake and continue.
6267     int server_ret = SSL_do_handshake(server_outer.get());
6268     int server_err = SSL_get_error(server_outer.get(), server_ret);
6269     ASSERT_TRUE(server_err == SSL_ERROR_NONE ||
6270                 server_err == SSL_ERROR_WANT_READ ||
6271                 server_err == SSL_ERROR_WANT_WRITE);
6272   }
6273 }
6274 
TEST_P(SSLVersionTest,SameKeyResume)6275 TEST_P(SSLVersionTest, SameKeyResume) {
6276   uint8_t key[48];
6277   RAND_bytes(key, sizeof(key));
6278 
6279   bssl::UniquePtr<SSL_CTX> server_ctx2 = CreateContext();
6280   ASSERT_TRUE(server_ctx2);
6281   ASSERT_TRUE(UseCertAndKey(server_ctx2.get()));
6282   ASSERT_TRUE(
6283       SSL_CTX_set_tlsext_ticket_keys(server_ctx_.get(), key, sizeof(key)));
6284   ASSERT_TRUE(
6285       SSL_CTX_set_tlsext_ticket_keys(server_ctx2.get(), key, sizeof(key)));
6286 
6287   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
6288   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
6289   SSL_CTX_set_session_cache_mode(server_ctx2.get(), SSL_SESS_CACHE_BOTH);
6290 
6291   // Establish a session for |server_ctx_|.
6292   bssl::UniquePtr<SSL_SESSION> session =
6293       CreateClientSession(client_ctx_.get(), server_ctx_.get());
6294   ASSERT_TRUE(session);
6295   ClientConfig config;
6296   config.session = session.get();
6297 
6298   // Resuming with |server_ctx_| again works.
6299   bssl::UniquePtr<SSL> client, server;
6300   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
6301                                      server_ctx_.get(), config));
6302   EXPECT_TRUE(SSL_session_reused(client.get()));
6303   EXPECT_TRUE(SSL_session_reused(server.get()));
6304 
6305   // Resuming with |server_ctx2| also works.
6306   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
6307                                      server_ctx2.get(), config));
6308   EXPECT_TRUE(SSL_session_reused(client.get()));
6309   EXPECT_TRUE(SSL_session_reused(server.get()));
6310 }
6311 
TEST_P(SSLVersionTest,DifferentKeyNoResume)6312 TEST_P(SSLVersionTest, DifferentKeyNoResume) {
6313   uint8_t key1[48], key2[48];
6314   RAND_bytes(key1, sizeof(key1));
6315   RAND_bytes(key2, sizeof(key2));
6316 
6317   bssl::UniquePtr<SSL_CTX> server_ctx2 = CreateContext();
6318   ASSERT_TRUE(server_ctx2);
6319   ASSERT_TRUE(UseCertAndKey(server_ctx2.get()));
6320   ASSERT_TRUE(
6321       SSL_CTX_set_tlsext_ticket_keys(server_ctx_.get(), key1, sizeof(key1)));
6322   ASSERT_TRUE(
6323       SSL_CTX_set_tlsext_ticket_keys(server_ctx2.get(), key2, sizeof(key2)));
6324 
6325   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
6326   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
6327   SSL_CTX_set_session_cache_mode(server_ctx2.get(), SSL_SESS_CACHE_BOTH);
6328 
6329   // Establish a session for |server_ctx_|.
6330   bssl::UniquePtr<SSL_SESSION> session =
6331       CreateClientSession(client_ctx_.get(), server_ctx_.get());
6332   ASSERT_TRUE(session);
6333   ClientConfig config;
6334   config.session = session.get();
6335 
6336   // Resuming with |server_ctx_| again works.
6337   bssl::UniquePtr<SSL> client, server;
6338   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
6339                                      server_ctx_.get(), config));
6340   EXPECT_TRUE(SSL_session_reused(client.get()));
6341   EXPECT_TRUE(SSL_session_reused(server.get()));
6342 
6343   // Resuming with |server_ctx2| does not work.
6344   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
6345                                      server_ctx2.get(), config));
6346   EXPECT_FALSE(SSL_session_reused(client.get()));
6347   EXPECT_FALSE(SSL_session_reused(server.get()));
6348 }
6349 
TEST_P(SSLVersionTest,UnrelatedServerNoResume)6350 TEST_P(SSLVersionTest, UnrelatedServerNoResume) {
6351   bssl::UniquePtr<SSL_CTX> server_ctx2 = CreateContext();
6352   ASSERT_TRUE(server_ctx2);
6353   ASSERT_TRUE(UseCertAndKey(server_ctx2.get()));
6354 
6355   SSL_CTX_set_session_cache_mode(client_ctx_.get(), SSL_SESS_CACHE_BOTH);
6356   SSL_CTX_set_session_cache_mode(server_ctx_.get(), SSL_SESS_CACHE_BOTH);
6357   SSL_CTX_set_session_cache_mode(server_ctx2.get(), SSL_SESS_CACHE_BOTH);
6358 
6359   // Establish a session for |server_ctx_|.
6360   bssl::UniquePtr<SSL_SESSION> session =
6361       CreateClientSession(client_ctx_.get(), server_ctx_.get());
6362   ASSERT_TRUE(session);
6363   ClientConfig config;
6364   config.session = session.get();
6365 
6366   // Resuming with |server_ctx_| again works.
6367   bssl::UniquePtr<SSL> client, server;
6368   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
6369                                      server_ctx_.get(), config));
6370   EXPECT_TRUE(SSL_session_reused(client.get()));
6371   EXPECT_TRUE(SSL_session_reused(server.get()));
6372 
6373   // Resuming with |server_ctx2| does not work.
6374   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx_.get(),
6375                                      server_ctx2.get(), config));
6376   EXPECT_FALSE(SSL_session_reused(client.get()));
6377   EXPECT_FALSE(SSL_session_reused(server.get()));
6378 }
6379 
TEST(SSLTest,WriteWhileExplicitRenegotiate)6380 TEST(SSLTest, WriteWhileExplicitRenegotiate) {
6381   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
6382   ASSERT_TRUE(ctx);
6383 
6384   bssl::UniquePtr<X509> cert = GetTestCertificate();
6385   bssl::UniquePtr<EVP_PKEY> pkey = GetTestKey();
6386   ASSERT_TRUE(cert);
6387   ASSERT_TRUE(pkey);
6388   ASSERT_TRUE(SSL_CTX_use_certificate(ctx.get(), cert.get()));
6389   ASSERT_TRUE(SSL_CTX_use_PrivateKey(ctx.get(), pkey.get()));
6390   ASSERT_TRUE(SSL_CTX_set_min_proto_version(ctx.get(), TLS1_2_VERSION));
6391   ASSERT_TRUE(SSL_CTX_set_max_proto_version(ctx.get(), TLS1_2_VERSION));
6392   ASSERT_TRUE(SSL_CTX_set_strict_cipher_list(
6393       ctx.get(), "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"));
6394 
6395   bssl::UniquePtr<SSL> client, server;
6396   ASSERT_TRUE(ConnectClientAndServer(&client, &server, ctx.get(), ctx.get(),
6397                                      ClientConfig(), true /* do_handshake */,
6398                                      false /* don't shed handshake config */));
6399   SSL_set_renegotiate_mode(client.get(), ssl_renegotiate_explicit);
6400 
6401   static const uint8_t kInput[] = {'h', 'e', 'l', 'l', 'o'};
6402 
6403   // Write "hello" until the buffer is full, so |client| has a pending write.
6404   size_t num_writes = 0;
6405   for (;;) {
6406     int ret = SSL_write(client.get(), kInput, sizeof(kInput));
6407     if (ret != int(sizeof(kInput))) {
6408       ASSERT_EQ(-1, ret);
6409       ASSERT_EQ(SSL_ERROR_WANT_WRITE, SSL_get_error(client.get(), ret));
6410       break;
6411     }
6412     num_writes++;
6413   }
6414 
6415   // Encrypt a HelloRequest.
6416   uint8_t in[] = {SSL3_MT_HELLO_REQUEST, 0, 0, 0};
6417 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
6418   // Fuzzer-mode records are unencrypted.
6419   uint8_t record[5 + sizeof(in)];
6420   record[0] = SSL3_RT_HANDSHAKE;
6421   record[1] = 3;
6422   record[2] = 3;  // TLS 1.2
6423   record[3] = 0;
6424   record[4] = sizeof(record) - 5;
6425   memcpy(record + 5, in, sizeof(in));
6426 #else
6427   // Extract key material from |server|.
6428   static const size_t kKeyLen = 32;
6429   static const size_t kNonceLen = 12;
6430   ASSERT_EQ(2u * (kKeyLen + kNonceLen), SSL_get_key_block_len(server.get()));
6431   uint8_t key_block[2u * (kKeyLen + kNonceLen)];
6432   ASSERT_TRUE(
6433       SSL_generate_key_block(server.get(), key_block, sizeof(key_block)));
6434   Span<uint8_t> key = MakeSpan(key_block + kKeyLen, kKeyLen);
6435   Span<uint8_t> nonce =
6436       MakeSpan(key_block + kKeyLen + kKeyLen + kNonceLen, kNonceLen);
6437 
6438   uint8_t ad[13];
6439   uint64_t seq = SSL_get_write_sequence(server.get());
6440   for (size_t i = 0; i < 8; i++) {
6441     // The nonce is XORed with the sequence number.
6442     nonce[11 - i] ^= uint8_t(seq);
6443     ad[7 - i] = uint8_t(seq);
6444     seq >>= 8;
6445   }
6446 
6447   ad[8] = SSL3_RT_HANDSHAKE;
6448   ad[9] = 3;
6449   ad[10] = 3;  // TLS 1.2
6450   ad[11] = 0;
6451   ad[12] = sizeof(in);
6452 
6453   uint8_t record[5 + sizeof(in) + 16];
6454   record[0] = SSL3_RT_HANDSHAKE;
6455   record[1] = 3;
6456   record[2] = 3;  // TLS 1.2
6457   record[3] = 0;
6458   record[4] = sizeof(record) - 5;
6459 
6460   ScopedEVP_AEAD_CTX aead;
6461   ASSERT_TRUE(EVP_AEAD_CTX_init(aead.get(), EVP_aead_chacha20_poly1305(),
6462                                 key.data(), key.size(),
6463                                 EVP_AEAD_DEFAULT_TAG_LENGTH, nullptr));
6464   size_t len;
6465   ASSERT_TRUE(EVP_AEAD_CTX_seal(aead.get(), record + 5, &len,
6466                                 sizeof(record) - 5, nonce.data(), nonce.size(),
6467                                 in, sizeof(in), ad, sizeof(ad)));
6468   ASSERT_EQ(sizeof(record) - 5, len);
6469 #endif  // BORINGSSL_UNSAFE_FUZZER_MODE
6470 
6471   ASSERT_EQ(int(sizeof(record)),
6472             BIO_write(SSL_get_wbio(server.get()), record, sizeof(record)));
6473 
6474   // |SSL_read| should pick up the HelloRequest.
6475   uint8_t byte;
6476   ASSERT_EQ(-1, SSL_read(client.get(), &byte, 1));
6477   ASSERT_EQ(SSL_ERROR_WANT_RENEGOTIATE, SSL_get_error(client.get(), -1));
6478 
6479   // Drain the data from the |client|.
6480   uint8_t buf[sizeof(kInput)];
6481   for (size_t i = 0; i < num_writes; i++) {
6482     ASSERT_EQ(int(sizeof(buf)), SSL_read(server.get(), buf, sizeof(buf)));
6483     EXPECT_EQ(Bytes(buf), Bytes(kInput));
6484   }
6485 
6486   // |client| should be able to finish the pending write and continue to write,
6487   // despite the paused HelloRequest.
6488   ASSERT_EQ(int(sizeof(kInput)),
6489             SSL_write(client.get(), kInput, sizeof(kInput)));
6490   ASSERT_EQ(int(sizeof(buf)), SSL_read(server.get(), buf, sizeof(buf)));
6491   EXPECT_EQ(Bytes(buf), Bytes(kInput));
6492 
6493   ASSERT_EQ(int(sizeof(kInput)),
6494             SSL_write(client.get(), kInput, sizeof(kInput)));
6495   ASSERT_EQ(int(sizeof(buf)), SSL_read(server.get(), buf, sizeof(buf)));
6496   EXPECT_EQ(Bytes(buf), Bytes(kInput));
6497 
6498   // |SSL_read| is stuck until we acknowledge the HelloRequest.
6499   ASSERT_EQ(-1, SSL_read(client.get(), &byte, 1));
6500   ASSERT_EQ(SSL_ERROR_WANT_RENEGOTIATE, SSL_get_error(client.get(), -1));
6501 
6502   ASSERT_TRUE(SSL_renegotiate(client.get()));
6503   ASSERT_EQ(-1, SSL_read(client.get(), &byte, 1));
6504   ASSERT_EQ(SSL_ERROR_WANT_READ, SSL_get_error(client.get(), -1));
6505 
6506   // We never renegotiate as a server.
6507   ASSERT_EQ(-1, SSL_read(server.get(), buf, sizeof(buf)));
6508   ASSERT_EQ(SSL_ERROR_SSL, SSL_get_error(server.get(), -1));
6509   uint32_t err = ERR_get_error();
6510   EXPECT_EQ(ERR_LIB_SSL, ERR_GET_LIB(err));
6511   EXPECT_EQ(SSL_R_NO_RENEGOTIATION, ERR_GET_REASON(err));
6512 }
6513 
6514 
TEST(SSLTest,CopyWithoutEarlyData)6515 TEST(SSLTest, CopyWithoutEarlyData) {
6516   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
6517   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
6518   ASSERT_TRUE(client_ctx);
6519   ASSERT_TRUE(server_ctx);
6520 
6521   bssl::UniquePtr<X509> cert = GetTestCertificate();
6522   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
6523   ASSERT_TRUE(cert);
6524   ASSERT_TRUE(key);
6525   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
6526   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
6527 
6528   SSL_CTX_set_session_cache_mode(client_ctx.get(), SSL_SESS_CACHE_BOTH);
6529   SSL_CTX_set_session_cache_mode(server_ctx.get(), SSL_SESS_CACHE_BOTH);
6530   SSL_CTX_set_early_data_enabled(client_ctx.get(), 1);
6531   SSL_CTX_set_early_data_enabled(server_ctx.get(), 1);
6532 
6533   bssl::UniquePtr<SSL_SESSION> session =
6534       CreateClientSession(client_ctx.get(), server_ctx.get());
6535   ASSERT_TRUE(session);
6536 
6537   // The client should attempt early data with |session|.
6538   auto config = ClientConfig();
6539   config.early_data = true;
6540   config.session = session.get();
6541   bssl::UniquePtr<SSL> client, server;
6542   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
6543                                      server_ctx.get(), config,
6544                                      /*do_handshake=*/false));
6545   ASSERT_EQ(1, SSL_do_handshake(client.get()));
6546   EXPECT_TRUE(SSL_in_early_data(client.get()));
6547 
6548   // |SSL_SESSION_copy_without_early_data| should disable early data but
6549   // still resume the session.
6550   bssl::UniquePtr<SSL_SESSION> session2(
6551       SSL_SESSION_copy_without_early_data(session.get()));
6552   ASSERT_TRUE(session2);
6553   EXPECT_NE(session.get(), session2.get());
6554   config.session = session2.get();
6555   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
6556                                      server_ctx.get(), config));
6557   EXPECT_TRUE(SSL_session_reused(client.get()));
6558   EXPECT_EQ(ssl_early_data_unsupported_for_session,
6559             SSL_get_early_data_reason(client.get()));
6560 
6561   // |SSL_SESSION_copy_without_early_data| should be a reference count increase
6562   // when passed an early-data-incapable session.
6563   bssl::UniquePtr<SSL_SESSION> session3(
6564       SSL_SESSION_copy_without_early_data(session2.get()));
6565   EXPECT_EQ(session2.get(), session3.get());
6566 }
6567 
TEST(SSLTest,ProcessTLS13NewSessionTicket)6568 TEST(SSLTest, ProcessTLS13NewSessionTicket) {
6569   // Configure client and server to negotiate TLS 1.3 only.
6570   bssl::UniquePtr<X509> cert = GetTestCertificate();
6571   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
6572   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
6573   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
6574   ASSERT_TRUE(client_ctx);
6575   ASSERT_TRUE(server_ctx);
6576   ASSERT_TRUE(SSL_CTX_set_min_proto_version(client_ctx.get(), TLS1_3_VERSION));
6577   ASSERT_TRUE(SSL_CTX_set_min_proto_version(server_ctx.get(), TLS1_3_VERSION));
6578   ASSERT_TRUE(SSL_CTX_set_max_proto_version(client_ctx.get(), TLS1_3_VERSION));
6579   ASSERT_TRUE(SSL_CTX_set_max_proto_version(server_ctx.get(), TLS1_3_VERSION));
6580   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
6581   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
6582 
6583   bssl::UniquePtr<SSL> client, server;
6584   ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
6585                                      server_ctx.get()));
6586   EXPECT_EQ(TLS1_3_VERSION, SSL_version(client.get()));
6587 
6588   // Process a TLS 1.3 NewSessionTicket.
6589   static const uint8_t kTicket[] = {
6590       0x04, 0x00, 0x00, 0xb2, 0x00, 0x02, 0xa3, 0x00, 0x04, 0x03, 0x02, 0x01,
6591       0x01, 0x00, 0x00, 0xa0, 0x01, 0x06, 0x09, 0x11, 0x16, 0x19, 0x21, 0x26,
6592       0x29, 0x31, 0x36, 0x39, 0x41, 0x46, 0x49, 0x51, 0x03, 0x06, 0x09, 0x13,
6593       0x16, 0x19, 0x23, 0x26, 0x29, 0x33, 0x36, 0x39, 0x43, 0x46, 0x49, 0x53,
6594       0xf7, 0x00, 0x29, 0xec, 0xf2, 0xc4, 0xa4, 0x41, 0xfc, 0x30, 0x17, 0x2e,
6595       0x9f, 0x7c, 0xa8, 0xaf, 0x75, 0x70, 0xf0, 0x1f, 0xc7, 0x98, 0xf7, 0xcf,
6596       0x5a, 0x5a, 0x6b, 0x5b, 0xfe, 0xf1, 0xe7, 0x3a, 0xe8, 0xf7, 0x6c, 0xd2,
6597       0xa8, 0xa6, 0x92, 0x5b, 0x96, 0x8d, 0xde, 0xdb, 0xd3, 0x20, 0x6a, 0xcb,
6598       0x69, 0x06, 0xf4, 0x91, 0x85, 0x2e, 0xe6, 0x5e, 0x0c, 0x59, 0xf2, 0x9e,
6599       0x9b, 0x79, 0x91, 0x24, 0x7e, 0x4a, 0x32, 0x3d, 0xbe, 0x4b, 0x80, 0x70,
6600       0xaf, 0xd0, 0x1d, 0xe2, 0xca, 0x05, 0x35, 0x09, 0x09, 0x05, 0x0f, 0xbb,
6601       0xc4, 0xae, 0xd7, 0xc4, 0xed, 0xd7, 0xae, 0x35, 0xc8, 0x73, 0x63, 0x78,
6602       0x64, 0xc9, 0x7a, 0x1f, 0xed, 0x7a, 0x9a, 0x47, 0x44, 0xfd, 0x50, 0xf7,
6603       0xb7, 0xe0, 0x64, 0xa9, 0x02, 0xc1, 0x5c, 0x23, 0x18, 0x3f, 0xc4, 0xcf,
6604       0x72, 0x02, 0x59, 0x2d, 0xe1, 0xaa, 0x61, 0x72, 0x00, 0x04, 0x5a, 0x5a,
6605       0x00, 0x00,
6606   };
6607   bssl::UniquePtr<SSL_SESSION> session(SSL_process_tls13_new_session_ticket(
6608       client.get(), kTicket, sizeof(kTicket)));
6609   ASSERT_TRUE(session);
6610   ASSERT_TRUE(SSL_SESSION_has_ticket(session.get()));
6611 
6612   uint8_t *session_buf = nullptr;
6613   size_t session_length = 0;
6614   ASSERT_TRUE(
6615       SSL_SESSION_to_bytes(session.get(), &session_buf, &session_length));
6616   bssl::UniquePtr<uint8_t> session_buf_free(session_buf);
6617   ASSERT_TRUE(session_buf);
6618   ASSERT_GT(session_length, 0u);
6619 
6620   // Servers cannot call |SSL_process_tls13_new_session_ticket|.
6621   ASSERT_FALSE(SSL_process_tls13_new_session_ticket(server.get(), kTicket,
6622                                                     sizeof(kTicket)));
6623 
6624   // Clients cannot call |SSL_process_tls13_new_session_ticket| before the
6625   // handshake completes.
6626   bssl::UniquePtr<SSL> client2(SSL_new(client_ctx.get()));
6627   ASSERT_TRUE(client2);
6628   SSL_set_connect_state(client2.get());
6629   ASSERT_FALSE(SSL_process_tls13_new_session_ticket(client2.get(), kTicket,
6630                                                     sizeof(kTicket)));
6631 }
6632 
TEST(SSLTest,BIO)6633 TEST(SSLTest, BIO) {
6634   bssl::UniquePtr<SSL_CTX> client_ctx(SSL_CTX_new(TLS_method()));
6635   bssl::UniquePtr<SSL_CTX> server_ctx(SSL_CTX_new(TLS_method()));
6636   ASSERT_TRUE(client_ctx);
6637   ASSERT_TRUE(server_ctx);
6638 
6639   bssl::UniquePtr<X509> cert = GetTestCertificate();
6640   bssl::UniquePtr<EVP_PKEY> key = GetTestKey();
6641   ASSERT_TRUE(cert);
6642   ASSERT_TRUE(key);
6643   ASSERT_TRUE(SSL_CTX_use_certificate(server_ctx.get(), cert.get()));
6644   ASSERT_TRUE(SSL_CTX_use_PrivateKey(server_ctx.get(), key.get()));
6645 
6646   for (bool take_ownership : {true, false}) {
6647     // For simplicity, get the handshake out of the way first.
6648     bssl::UniquePtr<SSL> client, server;
6649     ASSERT_TRUE(ConnectClientAndServer(&client, &server, client_ctx.get(),
6650                                        server_ctx.get()));
6651 
6652     // Wrap |client| in an SSL BIO.
6653     bssl::UniquePtr<BIO> client_bio(BIO_new(BIO_f_ssl()));
6654     ASSERT_TRUE(client_bio);
6655     ASSERT_EQ(1, BIO_set_ssl(client_bio.get(), client.get(), take_ownership));
6656     if (take_ownership) {
6657       client.release();
6658     }
6659 
6660     // Flushing the BIO should not crash.
6661     EXPECT_EQ(1, BIO_flush(client_bio.get()));
6662 
6663     // Exchange some data.
6664     EXPECT_EQ(5, BIO_write(client_bio.get(), "hello", 5));
6665     uint8_t buf[5];
6666     ASSERT_EQ(5, SSL_read(server.get(), buf, sizeof(buf)));
6667     EXPECT_EQ(Bytes("hello"), Bytes(buf));
6668 
6669     EXPECT_EQ(5, SSL_write(server.get(), "world", 5));
6670     ASSERT_EQ(5, BIO_read(client_bio.get(), buf, sizeof(buf)));
6671     EXPECT_EQ(Bytes("world"), Bytes(buf));
6672 
6673     // |BIO_should_read| should work.
6674     EXPECT_EQ(-1, BIO_read(client_bio.get(), buf, sizeof(buf)));
6675     EXPECT_TRUE(BIO_should_read(client_bio.get()));
6676 
6677     // Writing data should eventually exceed the buffer size and fail, reporting
6678     // |BIO_should_write|.
6679     int ret;
6680     for (int i = 0; i < 1024; i++) {
6681       std::vector<uint8_t> buffer(1024);
6682       ret = BIO_write(client_bio.get(), buffer.data(), buffer.size());
6683       if (ret <= 0) {
6684         break;
6685       }
6686     }
6687     EXPECT_EQ(-1, ret);
6688     EXPECT_TRUE(BIO_should_write(client_bio.get()));
6689   }
6690 }
6691 
6692 }  // namespace
6693 BSSL_NAMESPACE_END
6694