• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2016, 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 <limits.h>
16 #include <stdio.h>
17 
18 #include <map>
19 #include <string>
20 #include <vector>
21 
22 #include <gtest/gtest.h>
23 
24 #include <openssl/asn1.h>
25 #include <openssl/asn1t.h>
26 #include <openssl/bio.h>
27 #include <openssl/bytestring.h>
28 #include <openssl/err.h>
29 #include <openssl/mem.h>
30 #include <openssl/obj.h>
31 #include <openssl/pem.h>
32 #include <openssl/span.h>
33 #include <openssl/time.h>
34 #include <openssl/x509.h>
35 #include <openssl/x509v3.h>
36 
37 #include "../test/test_util.h"
38 #include "internal.h"
39 
40 #if defined(OPENSSL_THREADS)
41 #include <thread>
42 #endif
43 
44 
45 // |obj| and |i2d_func| require different template parameters because C++ may
46 // deduce, say, |ASN1_STRING*| via |obj| and |const ASN1_STRING*| via
47 // |i2d_func|. Template argument deduction then fails. The language is not able
48 // to resolve this by observing that |const ASN1_STRING*| works for both.
49 template <typename T, typename U>
TestSerialize(T obj,int (* i2d_func)(U a,uint8_t ** pp),bssl::Span<const uint8_t> expected)50 void TestSerialize(T obj, int (*i2d_func)(U a, uint8_t **pp),
51                    bssl::Span<const uint8_t> expected) {
52   static_assert(std::is_convertible<T, U>::value,
53                 "incompatible parameter to i2d_func");
54   // Test the allocating version first. It is easiest to debug.
55   uint8_t *ptr = nullptr;
56   int len = i2d_func(obj, &ptr);
57   ASSERT_GT(len, 0);
58   EXPECT_EQ(Bytes(expected), Bytes(ptr, len));
59   OPENSSL_free(ptr);
60 
61   len = i2d_func(obj, nullptr);
62   ASSERT_GT(len, 0);
63   EXPECT_EQ(len, static_cast<int>(expected.size()));
64 
65   std::vector<uint8_t> buf(len);
66   ptr = buf.data();
67   len = i2d_func(obj, &ptr);
68   ASSERT_EQ(len, static_cast<int>(expected.size()));
69   EXPECT_EQ(ptr, buf.data() + buf.size());
70   EXPECT_EQ(Bytes(expected), Bytes(buf));
71 }
72 
73 // Historically, unknown universal tags were represented in |ASN1_TYPE| as
74 // |ASN1_STRING|s with the type matching the tag number. This can collide with
75 // |V_ASN_NEG|, which was one of the causes of CVE-2016-2108. We now represent
76 // unsupported values with |V_ASN1_OTHER|, but retain the |V_ASN1_MAX_UNIVERSAL|
77 // limit.
TEST(ASN1Test,UnknownTags)78 TEST(ASN1Test, UnknownTags) {
79   // kTag258 is an ASN.1 structure with a universal tag with number 258.
80   static const uint8_t kTag258[] = {0x1f, 0x82, 0x02, 0x01, 0x00};
81   static_assert(
82       V_ASN1_NEG_INTEGER == 258,
83       "V_ASN1_NEG_INTEGER changed. Update kTag258 to collide with it.");
84   const uint8_t *p = kTag258;
85   bssl::UniquePtr<ASN1_TYPE> obj(d2i_ASN1_TYPE(NULL, &p, sizeof(kTag258)));
86   EXPECT_FALSE(obj) << "Parsed value with illegal tag" << obj->type;
87   ERR_clear_error();
88 
89   // kTagOverflow is an ASN.1 structure with a universal tag with number 2^35-1,
90   // which will not fit in an int.
91   static const uint8_t kTagOverflow[] = {0x1f, 0xff, 0xff, 0xff,
92                                          0xff, 0x7f, 0x01, 0x00};
93   p = kTagOverflow;
94   obj.reset(d2i_ASN1_TYPE(NULL, &p, sizeof(kTagOverflow)));
95   EXPECT_FALSE(obj) << "Parsed value with tag overflow" << obj->type;
96   ERR_clear_error();
97 
98   // kTag128 is an ASN.1 structure with a universal tag with number 128. It
99   // should be parsed as |V_ASN1_OTHER|.
100   static const uint8_t kTag128[] = {0x1f, 0x81, 0x00, 0x01, 0x00};
101   p = kTag128;
102   obj.reset(d2i_ASN1_TYPE(NULL, &p, sizeof(kTag128)));
103   ASSERT_TRUE(obj);
104   EXPECT_EQ(V_ASN1_OTHER, obj->type);
105   EXPECT_EQ(Bytes(kTag128), Bytes(obj->value.asn1_string->data,
106                                   obj->value.asn1_string->length));
107   TestSerialize(obj.get(), i2d_ASN1_TYPE, kTag128);
108 
109   // The historical in-memory representation of |kTag128| was for both
110   // |obj->type| and |obj->value.asn1_string->type| to be 128. This is no
111   // longer used but is still accepted by the encoder.
112   //
113   // TODO(crbug.com/boringssl/412): The encoder should reject it. However, it is
114   // still needed to support some edge cases in |ASN1_PRINTABLE|. When that is
115   // fixed, test that we reject it.
116   obj.reset(ASN1_TYPE_new());
117   ASSERT_TRUE(obj);
118   obj->type = 128;
119   obj->value.asn1_string = ASN1_STRING_type_new(128);
120   ASSERT_TRUE(obj->value.asn1_string);
121   const uint8_t zero = 0;
122   ASSERT_TRUE(ASN1_STRING_set(obj->value.asn1_string, &zero, sizeof(zero)));
123   TestSerialize(obj.get(), i2d_ASN1_TYPE, kTag128);
124 
125   // If a tag is known, but has the wrong constructed bit, it should be
126   // rejected, not placed in |V_ASN1_OTHER|.
127   static const uint8_t kConstructedOctetString[] = {0x24, 0x00};
128   p = kConstructedOctetString;
129   obj.reset(d2i_ASN1_TYPE(nullptr, &p, sizeof(kConstructedOctetString)));
130   EXPECT_FALSE(obj);
131 
132   static const uint8_t kPrimitiveSequence[] = {0x10, 0x00};
133   p = kPrimitiveSequence;
134   obj.reset(d2i_ASN1_TYPE(nullptr, &p, sizeof(kPrimitiveSequence)));
135   EXPECT_FALSE(obj);
136 }
137 
BIGNUMPow2(unsigned bit)138 static bssl::UniquePtr<BIGNUM> BIGNUMPow2(unsigned bit) {
139   bssl::UniquePtr<BIGNUM> bn(BN_new());
140   if (!bn ||
141       !BN_set_bit(bn.get(), bit)) {
142     return nullptr;
143   }
144   return bn;
145 }
146 
TEST(ASN1Test,Integer)147 TEST(ASN1Test, Integer) {
148   bssl::UniquePtr<BIGNUM> int64_min = BIGNUMPow2(63);
149   ASSERT_TRUE(int64_min);
150   BN_set_negative(int64_min.get(), 1);
151 
152   bssl::UniquePtr<BIGNUM> int64_max = BIGNUMPow2(63);
153   ASSERT_TRUE(int64_max);
154   ASSERT_TRUE(BN_sub_word(int64_max.get(), 1));
155 
156   bssl::UniquePtr<BIGNUM> int32_min = BIGNUMPow2(31);
157   ASSERT_TRUE(int32_min);
158   BN_set_negative(int32_min.get(), 1);
159 
160   bssl::UniquePtr<BIGNUM> int32_max = BIGNUMPow2(31);
161   ASSERT_TRUE(int32_max);
162   ASSERT_TRUE(BN_sub_word(int32_max.get(), 1));
163 
164   struct {
165     // der is the DER encoding of the INTEGER, including the tag and length.
166     std::vector<uint8_t> der;
167     // type and data are the corresponding fields of the |ASN1_STRING|
168     // representation.
169     int type;
170     std::vector<uint8_t> data;
171     // bn_asc is the |BIGNUM| representation, as parsed by the |BN_asc2bn|
172     // function.
173     const char *bn_asc;
174   } kTests[] = {
175       // -2^64 - 1
176       {{0x02, 0x09, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
177        V_ASN1_NEG_INTEGER,
178        {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
179        "-0x10000000000000001"},
180       // -2^64
181       {{0x02, 0x09, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
182        V_ASN1_NEG_INTEGER,
183        {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
184        "-0x10000000000000000"},
185       // -2^64 + 1
186       {{0x02, 0x09, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
187        V_ASN1_NEG_INTEGER,
188        {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
189        "-0xffffffffffffffff"},
190       // -2^63 - 1
191       {{0x02, 0x09, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
192        V_ASN1_NEG_INTEGER,
193        {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
194        "-0x8000000000000001"},
195       // -2^63 (INT64_MIN)
196       {{0x02, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
197        V_ASN1_NEG_INTEGER,
198        {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
199        "-0x8000000000000000"},
200       // -2^63 + 1
201       {{0x02, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
202        V_ASN1_NEG_INTEGER,
203        {0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
204        "-0x7fffffffffffffff"},
205       // -2^32 - 1
206       {{0x02, 0x05, 0xfe, 0xff, 0xff, 0xff, 0xff},
207        V_ASN1_NEG_INTEGER,
208        {0x01, 0x00, 0x00, 0x00, 0x01},
209        "-0x100000001"},
210       // -2^32
211       {{0x02, 0x05, 0xff, 0x00, 0x00, 0x00, 0x00},
212        V_ASN1_NEG_INTEGER,
213        {0x01, 0x00, 0x00, 0x00, 0x00},
214        "-0x100000000"},
215       // -2^32 + 1
216       {{0x02, 0x05, 0xff, 0x00, 0x00, 0x00, 0x01},
217        V_ASN1_NEG_INTEGER,
218        {0xff, 0xff, 0xff, 0xff},
219        "-0xffffffff"},
220       // -2^31 - 1
221       {{0x02, 0x05, 0xff, 0x7f, 0xff, 0xff, 0xff},
222        V_ASN1_NEG_INTEGER,
223        {0x80, 0x00, 0x00, 0x01},
224        "-0x80000001"},
225       // -2^31 (INT32_MIN)
226       {{0x02, 0x04, 0x80, 0x00, 0x00, 0x00},
227        V_ASN1_NEG_INTEGER,
228        {0x80, 0x00, 0x00, 0x00},
229        "-0x80000000"},
230       // -2^31 + 1
231       {{0x02, 0x04, 0x80, 0x00, 0x00, 0x01},
232        V_ASN1_NEG_INTEGER,
233        {0x7f, 0xff, 0xff, 0xff},
234        "-0x7fffffff"},
235       // -257
236       {{0x02, 0x02, 0xfe, 0xff}, V_ASN1_NEG_INTEGER, {0x01, 0x01}, "-257"},
237       // -256
238       {{0x02, 0x02, 0xff, 0x00}, V_ASN1_NEG_INTEGER, {0x01, 0x00}, "-256"},
239       // -255
240       {{0x02, 0x02, 0xff, 0x01}, V_ASN1_NEG_INTEGER, {0xff}, "-255"},
241       // -129
242       {{0x02, 0x02, 0xff, 0x7f}, V_ASN1_NEG_INTEGER, {0x81}, "-129"},
243       // -128
244       {{0x02, 0x01, 0x80}, V_ASN1_NEG_INTEGER, {0x80}, "-128"},
245       // -127
246       {{0x02, 0x01, 0x81}, V_ASN1_NEG_INTEGER, {0x7f}, "-127"},
247       // -1
248       {{0x02, 0x01, 0xff}, V_ASN1_NEG_INTEGER, {0x01}, "-1"},
249       // 0
250       {{0x02, 0x01, 0x00}, V_ASN1_INTEGER, {}, "0"},
251       // 1
252       {{0x02, 0x01, 0x01}, V_ASN1_INTEGER, {0x01}, "1"},
253       // 127
254       {{0x02, 0x01, 0x7f}, V_ASN1_INTEGER, {0x7f}, "127"},
255       // 128
256       {{0x02, 0x02, 0x00, 0x80}, V_ASN1_INTEGER, {0x80}, "128"},
257       // 129
258       {{0x02, 0x02, 0x00, 0x81}, V_ASN1_INTEGER, {0x81}, "129"},
259       // 255
260       {{0x02, 0x02, 0x00, 0xff}, V_ASN1_INTEGER, {0xff}, "255"},
261       // 256
262       {{0x02, 0x02, 0x01, 0x00}, V_ASN1_INTEGER, {0x01, 0x00}, "256"},
263       // 257
264       {{0x02, 0x02, 0x01, 0x01}, V_ASN1_INTEGER, {0x01, 0x01}, "257"},
265       // 2^31 - 2
266       {{0x02, 0x04, 0x7f, 0xff, 0xff, 0xfe},
267        V_ASN1_INTEGER,
268        {0x7f, 0xff, 0xff, 0xfe},
269        "0x7ffffffe"},
270       // 2^31 - 1 (INT32_MAX)
271       {{0x02, 0x04, 0x7f, 0xff, 0xff, 0xff},
272        V_ASN1_INTEGER,
273        {0x7f, 0xff, 0xff, 0xff},
274        "0x7fffffff"},
275       // 2^31
276       {{0x02, 0x05, 0x00, 0x80, 0x00, 0x00, 0x00},
277        V_ASN1_INTEGER,
278        {0x80, 0x00, 0x00, 0x00},
279        "0x80000000"},
280       // 2^32 - 2
281       {{0x02, 0x05, 0x00, 0xff, 0xff, 0xff, 0xfe},
282        V_ASN1_INTEGER,
283        {0xff, 0xff, 0xff, 0xfe},
284        "0xfffffffe"},
285       // 2^32 - 1 (UINT32_MAX)
286       {{0x02, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff},
287        V_ASN1_INTEGER,
288        {0xff, 0xff, 0xff, 0xff},
289        "0xffffffff"},
290       // 2^32
291       {{0x02, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00},
292        V_ASN1_INTEGER,
293        {0x01, 0x00, 0x00, 0x00, 0x00},
294        "0x100000000"},
295       // 2^63 - 2
296       {{0x02, 0x08, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe},
297        V_ASN1_INTEGER,
298        {0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe},
299        "0x7ffffffffffffffe"},
300       // 2^63 - 1 (INT64_MAX)
301       {{0x02, 0x08, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
302        V_ASN1_INTEGER,
303        {0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
304        "0x7fffffffffffffff"},
305       // 2^63
306       {{0x02, 0x09, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
307        V_ASN1_INTEGER,
308        {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
309        "0x8000000000000000"},
310       // 2^64 - 2
311       {{0x02, 0x09, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe},
312        V_ASN1_INTEGER,
313        {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe},
314        "0xfffffffffffffffe"},
315       // 2^64 - 1 (UINT64_MAX)
316       {{0x02, 0x09, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
317        V_ASN1_INTEGER,
318        {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
319        "0xffffffffffffffff"},
320       // 2^64
321       {{0x02, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
322        V_ASN1_INTEGER,
323        {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
324        "0x10000000000000000"},
325       // 2^64 + 1
326       {{0x02, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
327        V_ASN1_INTEGER,
328        {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
329        "0x10000000000000001"},
330   };
331 
332   for (const auto &t : kTests) {
333     SCOPED_TRACE(t.bn_asc);
334     // Collect a map of different ways to construct the integer. The key is the
335     // method used and is only retained to aid debugging.
336     std::map<std::string, bssl::UniquePtr<ASN1_INTEGER>> objs;
337 
338     // Construct |ASN1_INTEGER| by setting the type and data manually.
339     bssl::UniquePtr<ASN1_INTEGER> by_data(ASN1_STRING_type_new(t.type));
340     ASSERT_TRUE(by_data);
341     ASSERT_TRUE(ASN1_STRING_set(by_data.get(), t.data.data(), t.data.size()));
342     objs["data"] = std::move(by_data);
343 
344     // Construct |ASN1_INTEGER| from a |BIGNUM|.
345     BIGNUM *bn_raw = nullptr;
346     ASSERT_TRUE(BN_asc2bn(&bn_raw, t.bn_asc));
347     bssl::UniquePtr<BIGNUM> bn(bn_raw);
348     bssl::UniquePtr<ASN1_INTEGER> by_bn(BN_to_ASN1_INTEGER(bn.get(), nullptr));
349     ASSERT_TRUE(by_bn);
350     objs["bn"] = std::move(by_bn);
351 
352     // Construct |ASN1_INTEGER| from decoding.
353     const uint8_t *ptr = t.der.data();
354     bssl::UniquePtr<ASN1_INTEGER> by_der(
355         d2i_ASN1_INTEGER(nullptr, &ptr, t.der.size()));
356     ASSERT_TRUE(by_der);
357     EXPECT_EQ(ptr, t.der.data() + t.der.size());
358     objs["der"] = std::move(by_der);
359 
360     // Construct |ASN1_INTEGER| from various C types, if it fits.
361     bool fits_in_long = false, fits_in_i64 = false, fits_in_u64 = false;
362     uint64_t u64 = 0;
363     int64_t i64 = 0;
364     long l = 0;
365     uint64_t abs_u64;
366     if (BN_get_u64(bn.get(), &abs_u64)) {
367       fits_in_u64 = !BN_is_negative(bn.get());
368       if (fits_in_u64) {
369         u64 = abs_u64;
370         bssl::UniquePtr<ASN1_INTEGER> by_u64(ASN1_INTEGER_new());
371         ASSERT_TRUE(by_u64);
372         ASSERT_TRUE(ASN1_INTEGER_set_uint64(by_u64.get(), u64));
373         objs["u64"] = std::move(by_u64);
374       }
375 
376       fits_in_i64 = BN_cmp(int64_min.get(), bn.get()) <= 0 &&
377                     BN_cmp(bn.get(), int64_max.get()) <= 0;
378       if (fits_in_i64) {
379         if (BN_is_negative(bn.get())) {
380           i64 = static_cast<int64_t>(0u - abs_u64);
381         } else {
382           i64 = static_cast<int64_t>(abs_u64);
383         }
384         bssl::UniquePtr<ASN1_INTEGER> by_i64(ASN1_INTEGER_new());
385         ASSERT_TRUE(by_i64);
386         ASSERT_TRUE(ASN1_INTEGER_set_int64(by_i64.get(), i64));
387         objs["i64"] = std::move(by_i64);
388       }
389 
390       if (sizeof(long) == 8) {
391         fits_in_long = fits_in_i64;
392       } else {
393         ASSERT_EQ(4u, sizeof(long));
394         fits_in_long = BN_cmp(int32_min.get(), bn.get()) <= 0 &&
395                        BN_cmp(bn.get(), int32_max.get()) <= 0;
396       }
397       if (fits_in_long) {
398         l = static_cast<long>(i64);
399         bssl::UniquePtr<ASN1_INTEGER> by_long(ASN1_INTEGER_new());
400         ASSERT_TRUE(by_long);
401         ASSERT_TRUE(ASN1_INTEGER_set(by_long.get(), l));
402         objs["long"] = std::move(by_long);
403       }
404     }
405 
406     // Default construction should return the zero |ASN1_INTEGER|.
407     if (BN_is_zero(bn.get())) {
408       bssl::UniquePtr<ASN1_INTEGER> by_default(ASN1_INTEGER_new());
409       ASSERT_TRUE(by_default);
410       objs["default"] = std::move(by_default);
411     }
412 
413     // Test that every |ASN1_INTEGER| constructed behaves as expected.
414     for (const auto &pair : objs) {
415       // The fields should be as expected.
416       SCOPED_TRACE(pair.first);
417       const ASN1_INTEGER *obj = pair.second.get();
418       EXPECT_EQ(t.type, ASN1_STRING_type(obj));
419       EXPECT_EQ(Bytes(t.data), Bytes(ASN1_STRING_get0_data(obj),
420                                      ASN1_STRING_length(obj)));
421 
422       // The object should encode correctly.
423       TestSerialize(obj, i2d_ASN1_INTEGER, t.der);
424 
425       bssl::UniquePtr<BIGNUM> bn2(ASN1_INTEGER_to_BN(obj, nullptr));
426       ASSERT_TRUE(bn2);
427       EXPECT_EQ(0, BN_cmp(bn.get(), bn2.get()));
428 
429       if (fits_in_u64) {
430         uint64_t v;
431         ASSERT_TRUE(ASN1_INTEGER_get_uint64(&v, obj));
432         EXPECT_EQ(v, u64);
433       } else {
434         uint64_t v;
435         EXPECT_FALSE(ASN1_INTEGER_get_uint64(&v, obj));
436       }
437 
438       if (fits_in_i64) {
439         int64_t v;
440         ASSERT_TRUE(ASN1_INTEGER_get_int64(&v, obj));
441         EXPECT_EQ(v, i64);
442       } else {
443         int64_t v;
444         EXPECT_FALSE(ASN1_INTEGER_get_int64(&v, obj));
445       }
446 
447       if (fits_in_long) {
448         EXPECT_EQ(l, ASN1_INTEGER_get(obj));
449       } else {
450         EXPECT_EQ(-1, ASN1_INTEGER_get(obj));
451       }
452 
453       // All variations of integers should compare as equal to each other, as
454       // strings or integers. (Functions like |ASN1_TYPE_cmp| rely on
455       // string-based comparison.)
456       for (const auto &pair2 : objs) {
457         SCOPED_TRACE(pair2.first);
458         EXPECT_EQ(0, ASN1_INTEGER_cmp(obj, pair2.second.get()));
459         EXPECT_EQ(0, ASN1_STRING_cmp(obj, pair2.second.get()));
460       }
461     }
462 
463     // Although our parsers will never output non-minimal |ASN1_INTEGER|s, it is
464     // possible to construct them manually. They should encode correctly.
465     std::vector<uint8_t> data = t.data;
466     const int kMaxExtraBytes = 5;
467     for (int i = 0; i < kMaxExtraBytes; i++) {
468       data.insert(data.begin(), 0x00);
469       SCOPED_TRACE(Bytes(data));
470 
471       bssl::UniquePtr<ASN1_INTEGER> non_minimal(ASN1_STRING_type_new(t.type));
472       ASSERT_TRUE(non_minimal);
473       ASSERT_TRUE(ASN1_STRING_set(non_minimal.get(), data.data(), data.size()));
474 
475       TestSerialize(non_minimal.get(), i2d_ASN1_INTEGER, t.der);
476     }
477   }
478 
479   for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kTests); i++) {
480     SCOPED_TRACE(Bytes(kTests[i].der));
481     const uint8_t *ptr = kTests[i].der.data();
482     bssl::UniquePtr<ASN1_INTEGER> a(
483         d2i_ASN1_INTEGER(nullptr, &ptr, kTests[i].der.size()));
484     ASSERT_TRUE(a);
485     for (size_t j = 0; j < OPENSSL_ARRAY_SIZE(kTests); j++) {
486       SCOPED_TRACE(Bytes(kTests[j].der));
487       ptr = kTests[j].der.data();
488       bssl::UniquePtr<ASN1_INTEGER> b(
489           d2i_ASN1_INTEGER(nullptr, &ptr, kTests[j].der.size()));
490       ASSERT_TRUE(b);
491 
492       // |ASN1_INTEGER_cmp| should compare numerically. |ASN1_STRING_cmp| does
493       // not but should preserve equality.
494       if (i < j) {
495         EXPECT_LT(ASN1_INTEGER_cmp(a.get(), b.get()), 0);
496         EXPECT_NE(ASN1_STRING_cmp(a.get(), b.get()), 0);
497       } else if (i > j) {
498         EXPECT_GT(ASN1_INTEGER_cmp(a.get(), b.get()), 0);
499         EXPECT_NE(ASN1_STRING_cmp(a.get(), b.get()), 0);
500       } else {
501         EXPECT_EQ(ASN1_INTEGER_cmp(a.get(), b.get()), 0);
502         EXPECT_EQ(ASN1_STRING_cmp(a.get(), b.get()), 0);
503       }
504     }
505   }
506 
507   std::vector<uint8_t> kInvalidTests[] = {
508       // The empty string is not an integer.
509       {0x02, 0x00},
510       // Integers must be minimally-encoded.
511       {0x02, 0x02, 0x00, 0x00},
512       {0x02, 0x02, 0x00, 0x7f},
513       {0x02, 0x02, 0xff, 0xff},
514       {0x02, 0x02, 0xff, 0x80},
515   };
516   for (const auto &invalid : kInvalidTests) {
517     SCOPED_TRACE(Bytes(invalid));
518 
519     const uint8_t *ptr = invalid.data();
520     bssl::UniquePtr<ASN1_INTEGER> integer(
521         d2i_ASN1_INTEGER(nullptr, &ptr, invalid.size()));
522     EXPECT_FALSE(integer);
523   }
524 
525   // Callers expect |ASN1_INTEGER_get| and |ASN1_ENUMERATED_get| to return zero
526   // given NULL.
527   EXPECT_EQ(0, ASN1_INTEGER_get(nullptr));
528   EXPECT_EQ(0, ASN1_ENUMERATED_get(nullptr));
529 }
530 
531 // Although invalid, a negative zero should encode correctly.
TEST(ASN1Test,NegativeZero)532 TEST(ASN1Test, NegativeZero) {
533   bssl::UniquePtr<ASN1_INTEGER> neg_zero(
534       ASN1_STRING_type_new(V_ASN1_NEG_INTEGER));
535   ASSERT_TRUE(neg_zero);
536   EXPECT_EQ(0, ASN1_INTEGER_get(neg_zero.get()));
537 
538   static const uint8_t kDER[] = {0x02, 0x01, 0x00};
539   TestSerialize(neg_zero.get(), i2d_ASN1_INTEGER, kDER);
540 }
541 
TEST(ASN1Test,SerializeObject)542 TEST(ASN1Test, SerializeObject) {
543   static const uint8_t kDER[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
544                                  0xf7, 0x0d, 0x01, 0x01, 0x01};
545   const ASN1_OBJECT *obj = OBJ_nid2obj(NID_rsaEncryption);
546   TestSerialize(obj, i2d_ASN1_OBJECT, kDER);
547 }
548 
TEST(ASN1Test,Boolean)549 TEST(ASN1Test, Boolean) {
550   static const uint8_t kTrue[] = {0x01, 0x01, 0xff};
551   TestSerialize(0xff, i2d_ASN1_BOOLEAN, kTrue);
552   // Other constants are also correctly encoded as TRUE.
553   TestSerialize(1, i2d_ASN1_BOOLEAN, kTrue);
554   TestSerialize(0x100, i2d_ASN1_BOOLEAN, kTrue);
555 
556   const uint8_t *ptr = kTrue;
557   EXPECT_EQ(0xff, d2i_ASN1_BOOLEAN(nullptr, &ptr, sizeof(kTrue)));
558   EXPECT_EQ(ptr, kTrue + sizeof(kTrue));
559 
560   static const uint8_t kFalse[] = {0x01, 0x01, 0x00};
561   TestSerialize(0x00, i2d_ASN1_BOOLEAN, kFalse);
562 
563   ptr = kFalse;
564   EXPECT_EQ(0, d2i_ASN1_BOOLEAN(nullptr, &ptr, sizeof(kFalse)));
565   EXPECT_EQ(ptr, kFalse + sizeof(kFalse));
566 
567   const std::vector<uint8_t> kInvalidBooleans[] = {
568       // No tag header.
569       {},
570       // No length.
571       {0x01},
572       // Truncated contents.
573       {0x01, 0x01},
574       // Contents too short or too long.
575       {0x01, 0x00},
576       {0x01, 0x02, 0x00, 0x00},
577       // Wrong tag number.
578       {0x02, 0x01, 0x00},
579       // Wrong tag class.
580       {0x81, 0x01, 0x00},
581       // Element is constructed.
582       {0x21, 0x01, 0x00},
583       // Not a DER encoding of TRUE.
584       {0x01, 0x01, 0x01},
585       // Non-minimal tag length.
586       {0x01, 0x81, 0x01, 0xff},
587   };
588   for (const auto &invalid : kInvalidBooleans) {
589     SCOPED_TRACE(Bytes(invalid));
590     ptr = invalid.data();
591     EXPECT_EQ(-1, d2i_ASN1_BOOLEAN(nullptr, &ptr, invalid.size()));
592     ERR_clear_error();
593   }
594 }
595 
596 // The templates go through a different codepath, so test them separately.
TEST(ASN1Test,SerializeEmbeddedBoolean)597 TEST(ASN1Test, SerializeEmbeddedBoolean) {
598   bssl::UniquePtr<BASIC_CONSTRAINTS> val(BASIC_CONSTRAINTS_new());
599   ASSERT_TRUE(val);
600 
601   // BasicConstraints defaults to FALSE, so the encoding should be empty.
602   static const uint8_t kLeaf[] = {0x30, 0x00};
603   val->ca = 0;
604   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kLeaf);
605 
606   // TRUE should always be encoded as 0xff, independent of what value the caller
607   // placed in the |ASN1_BOOLEAN|.
608   static const uint8_t kCA[] = {0x30, 0x03, 0x01, 0x01, 0xff};
609   val->ca = 0xff;
610   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA);
611   val->ca = 1;
612   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA);
613   val->ca = 0x100;
614   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA);
615 }
616 
TEST(ASN1Test,ASN1Type)617 TEST(ASN1Test, ASN1Type) {
618   const struct {
619     int type;
620     std::vector<uint8_t> der;
621   } kTests[] = {
622       // BOOLEAN { TRUE }
623       {V_ASN1_BOOLEAN, {0x01, 0x01, 0xff}},
624       // BOOLEAN { FALSE }
625       {V_ASN1_BOOLEAN, {0x01, 0x01, 0x00}},
626       // OCTET_STRING { "a" }
627       {V_ASN1_OCTET_STRING, {0x04, 0x01, 0x61}},
628       // OCTET_STRING { }
629       {V_ASN1_OCTET_STRING, {0x04, 0x00}},
630       // BIT_STRING { `01` `00` }
631       {V_ASN1_BIT_STRING, {0x03, 0x02, 0x01, 0x00}},
632       // INTEGER { -1 }
633       {V_ASN1_INTEGER, {0x02, 0x01, 0xff}},
634       // OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2 }
635       {V_ASN1_OBJECT,
636        {0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7,
637         0x09, 0x02}},
638       // NULL {}
639       {V_ASN1_NULL, {0x05, 0x00}},
640       // SEQUENCE {}
641       {V_ASN1_SEQUENCE, {0x30, 0x00}},
642       // SET {}
643       {V_ASN1_SET, {0x31, 0x00}},
644       // [0] { UTF8String { "a" } }
645       {V_ASN1_OTHER, {0xa0, 0x03, 0x0c, 0x01, 0x61}},
646   };
647   for (const auto &t : kTests) {
648     SCOPED_TRACE(Bytes(t.der));
649 
650     // The input should successfully parse.
651     const uint8_t *ptr = t.der.data();
652     bssl::UniquePtr<ASN1_TYPE> val(d2i_ASN1_TYPE(nullptr, &ptr, t.der.size()));
653     ASSERT_TRUE(val);
654 
655     EXPECT_EQ(ASN1_TYPE_get(val.get()), t.type);
656     EXPECT_EQ(val->type, t.type);
657     TestSerialize(val.get(), i2d_ASN1_TYPE, t.der);
658   }
659 }
660 
661 // Test that reading |value.ptr| from a FALSE |ASN1_TYPE| behaves correctly. The
662 // type historically supported this, so maintain the invariant in case external
663 // code relies on it.
TEST(ASN1Test,UnusedBooleanBits)664 TEST(ASN1Test, UnusedBooleanBits) {
665   // OCTET_STRING { "a" }
666   static const uint8_t kDER[] = {0x04, 0x01, 0x61};
667   const uint8_t *ptr = kDER;
668   bssl::UniquePtr<ASN1_TYPE> val(d2i_ASN1_TYPE(nullptr, &ptr, sizeof(kDER)));
669   ASSERT_TRUE(val);
670   EXPECT_EQ(V_ASN1_OCTET_STRING, val->type);
671   EXPECT_TRUE(val->value.ptr);
672 
673   // Set |val| to a BOOLEAN containing FALSE.
674   ASN1_TYPE_set(val.get(), V_ASN1_BOOLEAN, NULL);
675   EXPECT_EQ(V_ASN1_BOOLEAN, val->type);
676   EXPECT_FALSE(val->value.ptr);
677 }
678 
TEST(ASN1Test,ParseASN1Object)679 TEST(ASN1Test, ParseASN1Object) {
680   // 1.2.840.113554.4.1.72585.2, an arbitrary unknown OID.
681   static const uint8_t kOID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12,
682                                  0x04, 0x01, 0x84, 0xb7, 0x09, 0x02};
683   ASN1_OBJECT *obj = ASN1_OBJECT_create(NID_undef, kOID, sizeof(kOID),
684                                         "short name", "long name");
685   ASSERT_TRUE(obj);
686 
687   // OBJECT_IDENTIFIER { 1.3.101.112 }
688   static const uint8_t kDER[] = {0x06, 0x03, 0x2b, 0x65, 0x70};
689   const uint8_t *ptr = kDER;
690   // Parse an |ASN1_OBJECT| with object reuse.
691   EXPECT_TRUE(d2i_ASN1_OBJECT(&obj, &ptr, sizeof(kDER)));
692   EXPECT_EQ(NID_ED25519, OBJ_obj2nid(obj));
693   ASN1_OBJECT_free(obj);
694 
695   // Repeat the test, this time overriding a static |ASN1_OBJECT|. It should
696   // detect this and construct a new one.
697   obj = OBJ_nid2obj(NID_rsaEncryption);
698   ptr = kDER;
699   EXPECT_TRUE(d2i_ASN1_OBJECT(&obj, &ptr, sizeof(kDER)));
700   EXPECT_EQ(NID_ED25519, OBJ_obj2nid(obj));
701   ASN1_OBJECT_free(obj);
702 
703   const std::vector<uint8_t> kInvalidObjects[] = {
704       // No tag header.
705       {},
706       // No length.
707       {0x06},
708       // Truncated contents.
709       {0x06, 0x01},
710       // An OID may not be empty.
711       {0x06, 0x00},
712       // The last byte may not be a continuation byte (high bit set).
713       {0x06, 0x03, 0x2b, 0x65, 0xf0},
714       // Each component must be minimally-encoded.
715       {0x06, 0x03, 0x2b, 0x65, 0x80, 0x70},
716       {0x06, 0x03, 0x80, 0x2b, 0x65, 0x70},
717       // Wrong tag number.
718       {0x01, 0x03, 0x2b, 0x65, 0x70},
719       // Wrong tag class.
720       {0x86, 0x03, 0x2b, 0x65, 0x70},
721       // Element is constructed.
722       {0x26, 0x03, 0x2b, 0x65, 0x70},
723       // Non-minimal tag length.
724       {0x06, 0x81, 0x03, 0x2b, 0x65, 0x70},
725   };
726   for (const auto &invalid : kInvalidObjects) {
727     SCOPED_TRACE(Bytes(invalid));
728     ptr = invalid.data();
729     obj = d2i_ASN1_OBJECT(nullptr, &ptr, invalid.size());
730     EXPECT_FALSE(obj);
731     ASN1_OBJECT_free(obj);
732     ERR_clear_error();
733   }
734 }
735 
TEST(ASN1Test,BitString)736 TEST(ASN1Test, BitString) {
737   const size_t kNotWholeBytes = static_cast<size_t>(-1);
738   const struct {
739     std::vector<uint8_t> in;
740     size_t num_bytes;
741   } kValidInputs[] = {
742       // Empty bit string
743       {{0x03, 0x01, 0x00}, 0},
744       // 0b1
745       {{0x03, 0x02, 0x07, 0x80}, kNotWholeBytes},
746       // 0b1010
747       {{0x03, 0x02, 0x04, 0xa0}, kNotWholeBytes},
748       // 0b1010101
749       {{0x03, 0x02, 0x01, 0xaa}, kNotWholeBytes},
750       // 0b10101010
751       {{0x03, 0x02, 0x00, 0xaa}, 1},
752       // Bits 0 and 63 are set
753       {{0x03, 0x09, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, 8},
754       // 64 zero bits
755       {{0x03, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 8},
756   };
757   for (const auto &test : kValidInputs) {
758     SCOPED_TRACE(Bytes(test.in));
759     // The input should parse and round-trip correctly.
760     const uint8_t *ptr = test.in.data();
761     bssl::UniquePtr<ASN1_BIT_STRING> val(
762         d2i_ASN1_BIT_STRING(nullptr, &ptr, test.in.size()));
763     ASSERT_TRUE(val);
764     TestSerialize(val.get(), i2d_ASN1_BIT_STRING, test.in);
765 
766     // Check the byte count.
767     size_t num_bytes;
768     if (test.num_bytes == kNotWholeBytes) {
769       EXPECT_FALSE(ASN1_BIT_STRING_num_bytes(val.get(), &num_bytes));
770     } else {
771       ASSERT_TRUE(ASN1_BIT_STRING_num_bytes(val.get(), &num_bytes));
772       EXPECT_EQ(num_bytes, test.num_bytes);
773     }
774   }
775 
776   const std::vector<uint8_t> kInvalidInputs[] = {
777       // Wrong tag
778       {0x04, 0x01, 0x00},
779       // Missing leading byte
780       {0x03, 0x00},
781       // Leading byte too high
782       {0x03, 0x02, 0x08, 0x00},
783       {0x03, 0x02, 0xff, 0x00},
784       // Empty bit strings must have a zero leading byte.
785       {0x03, 0x01, 0x01},
786       // Unused bits must all be zero.
787       {0x03, 0x02, 0x06, 0xc1 /* 0b11000001 */},
788   };
789   for (const auto &test : kInvalidInputs) {
790     SCOPED_TRACE(Bytes(test));
791     const uint8_t *ptr = test.data();
792     bssl::UniquePtr<ASN1_BIT_STRING> val(
793         d2i_ASN1_BIT_STRING(nullptr, &ptr, test.size()));
794     EXPECT_FALSE(val);
795   }
796 }
797 
TEST(ASN1Test,SetBit)798 TEST(ASN1Test, SetBit) {
799   bssl::UniquePtr<ASN1_BIT_STRING> val(ASN1_BIT_STRING_new());
800   ASSERT_TRUE(val);
801   static const uint8_t kBitStringEmpty[] = {0x03, 0x01, 0x00};
802   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringEmpty);
803   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 0));
804   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 100));
805 
806   // Set a few bits via |ASN1_BIT_STRING_set_bit|.
807   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 0, 1));
808   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 1, 1));
809   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 2, 0));
810   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 3, 1));
811   static const uint8_t kBitString1101[] = {0x03, 0x02, 0x04, 0xd0};
812   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1101);
813   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
814   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 1));
815   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2));
816   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 3));
817   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4));
818 
819   // Bits that were set may be cleared.
820   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 1, 0));
821   static const uint8_t kBitString1001[] = {0x03, 0x02, 0x04, 0x90};
822   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1001);
823   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
824   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 1));
825   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2));
826   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 3));
827   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4));
828 
829   // Clearing trailing bits truncates the string.
830   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 3, 0));
831   static const uint8_t kBitString1[] = {0x03, 0x02, 0x07, 0x80};
832   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1);
833   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
834   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 1));
835   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2));
836   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 3));
837   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4));
838 
839   // Bits may be set beyond the end of the string.
840   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 1));
841   static const uint8_t kBitStringLong[] = {0x03, 0x09, 0x00, 0x80, 0x00, 0x00,
842                                            0x00, 0x00, 0x00, 0x00, 0x01};
843   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringLong);
844   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
845   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62));
846   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 63));
847   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64));
848 
849   // The string can be truncated back down again.
850   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 0));
851   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1);
852   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
853   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62));
854   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63));
855   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64));
856 
857   // |ASN1_BIT_STRING_set_bit| also truncates when starting from a parsed
858   // string.
859   const uint8_t *ptr = kBitStringLong;
860   val.reset(d2i_ASN1_BIT_STRING(nullptr, &ptr, sizeof(kBitStringLong)));
861   ASSERT_TRUE(val);
862   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringLong);
863   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 0));
864   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1);
865   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
866   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62));
867   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63));
868   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64));
869 
870   // A parsed bit string preserves trailing zero bits.
871   static const uint8_t kBitString10010[] = {0x03, 0x02, 0x03, 0x90};
872   ptr = kBitString10010;
873   val.reset(d2i_ASN1_BIT_STRING(nullptr, &ptr, sizeof(kBitString10010)));
874   ASSERT_TRUE(val);
875   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString10010);
876   // But |ASN1_BIT_STRING_set_bit| will truncate it even if otherwise a no-op.
877   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 0, 1));
878   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1001);
879   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
880   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62));
881   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63));
882   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64));
883 
884   // By default, a BIT STRING implicitly truncates trailing zeros.
885   val.reset(ASN1_BIT_STRING_new());
886   ASSERT_TRUE(val);
887   static const uint8_t kZeros[64] = {0};
888   ASSERT_TRUE(ASN1_STRING_set(val.get(), kZeros, sizeof(kZeros)));
889   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringEmpty);
890 }
891 
TEST(ASN1Test,StringToUTF8)892 TEST(ASN1Test, StringToUTF8) {
893   static const struct {
894     std::vector<uint8_t> in;
895     int type;
896     const char *expected;
897   } kTests[] = {
898       // Non-minimal, two-byte UTF-8.
899       {{0xc0, 0x81}, V_ASN1_UTF8STRING, nullptr},
900       // Non-minimal, three-byte UTF-8.
901       {{0xe0, 0x80, 0x81}, V_ASN1_UTF8STRING, nullptr},
902       // Non-minimal, four-byte UTF-8.
903       {{0xf0, 0x80, 0x80, 0x81}, V_ASN1_UTF8STRING, nullptr},
904       // Truncated, four-byte UTF-8.
905       {{0xf0, 0x80, 0x80}, V_ASN1_UTF8STRING, nullptr},
906       // Low-surrogate value.
907       {{0xed, 0xa0, 0x80}, V_ASN1_UTF8STRING, nullptr},
908       // High-surrogate value.
909       {{0xed, 0xb0, 0x81}, V_ASN1_UTF8STRING, nullptr},
910       // Initial BOMs should be rejected from UCS-2 and UCS-4.
911       {{0xfe, 0xff, 0, 88}, V_ASN1_BMPSTRING, nullptr},
912       {{0, 0, 0xfe, 0xff, 0, 0, 0, 88}, V_ASN1_UNIVERSALSTRING, nullptr},
913       // Otherwise, BOMs should pass through.
914       {{0, 88, 0xfe, 0xff}, V_ASN1_BMPSTRING, "X\xef\xbb\xbf"},
915       {{0, 0, 0, 88, 0, 0, 0xfe, 0xff}, V_ASN1_UNIVERSALSTRING,
916        "X\xef\xbb\xbf"},
917       // The maximum code-point should pass though.
918       {{0, 16, 0xff, 0xfd}, V_ASN1_UNIVERSALSTRING, "\xf4\x8f\xbf\xbd"},
919       // Values outside the Unicode space should not.
920       {{0, 17, 0, 0}, V_ASN1_UNIVERSALSTRING, nullptr},
921       // Non-characters should be rejected.
922       {{0, 1, 0xff, 0xff}, V_ASN1_UNIVERSALSTRING, nullptr},
923       {{0, 1, 0xff, 0xfe}, V_ASN1_UNIVERSALSTRING, nullptr},
924       {{0, 0, 0xfd, 0xd5}, V_ASN1_UNIVERSALSTRING, nullptr},
925       // BMPString is UCS-2, not UTF-16, so surrogate pairs are invalid.
926       {{0xd8, 0, 0xdc, 1}, V_ASN1_BMPSTRING, nullptr},
927       // INTEGERs are stored as strings, but cannot be converted to UTF-8.
928       {{0x01}, V_ASN1_INTEGER, nullptr},
929   };
930 
931   for (const auto &test : kTests) {
932     SCOPED_TRACE(Bytes(test.in));
933     SCOPED_TRACE(test.type);
934     bssl::UniquePtr<ASN1_STRING> s(ASN1_STRING_type_new(test.type));
935     ASSERT_TRUE(s);
936     ASSERT_TRUE(ASN1_STRING_set(s.get(), test.in.data(), test.in.size()));
937 
938     uint8_t *utf8;
939     const int utf8_len = ASN1_STRING_to_UTF8(&utf8, s.get());
940     EXPECT_EQ(utf8_len < 0, test.expected == nullptr);
941     if (utf8_len >= 0) {
942       if (test.expected != nullptr) {
943         EXPECT_EQ(Bytes(test.expected), Bytes(utf8, utf8_len));
944       }
945       OPENSSL_free(utf8);
946     } else {
947       ERR_clear_error();
948     }
949   }
950 }
951 
ASN1StringToStdString(const ASN1_STRING * str)952 static std::string ASN1StringToStdString(const ASN1_STRING *str) {
953   return std::string(ASN1_STRING_get0_data(str),
954                      ASN1_STRING_get0_data(str) + ASN1_STRING_length(str));
955 }
956 
ASN1Time_check_posix(const ASN1_TIME * s,int64_t t)957 static bool ASN1Time_check_posix(const ASN1_TIME *s, int64_t t) {
958   struct tm stm, ttm;
959   int day, sec;
960 
961   switch (ASN1_STRING_type(s)) {
962     case V_ASN1_GENERALIZEDTIME:
963       if (!asn1_generalizedtime_to_tm(&stm, s)) {
964         return false;
965       }
966       break;
967     case V_ASN1_UTCTIME:
968       if (!asn1_utctime_to_tm(&stm, s, /*allow_timezone_offset=*/1)) {
969         return false;
970       }
971       break;
972     default:
973       return false;
974   }
975   if (!OPENSSL_posix_to_tm(t, &ttm) ||
976       !OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm)) {
977     return false;
978   }
979   return day == 0 && sec ==0;
980 }
981 
PrintStringToBIO(const ASN1_STRING * str,int (* print_func)(BIO *,const ASN1_STRING *))982 static std::string PrintStringToBIO(const ASN1_STRING *str,
983                                     int (*print_func)(BIO *,
984                                                       const ASN1_STRING *)) {
985   const uint8_t *data;
986   size_t len;
987   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
988   if (!bio ||  //
989       !print_func(bio.get(), str) ||
990       !BIO_mem_contents(bio.get(), &data, &len)) {
991     ADD_FAILURE() << "Could not print to BIO";
992     return "";
993   }
994   return std::string(data, data + len);
995 }
996 
TEST(ASN1Test,SetTime)997 TEST(ASN1Test, SetTime) {
998   static const struct {
999     int64_t time;
1000     const char *generalized;
1001     const char *utc;
1002     const char *printed;
1003   } kTests[] = {
1004       {-631152001, "19491231235959Z", nullptr, "Dec 31 23:59:59 1949 GMT"},
1005       {-631152000, "19500101000000Z", "500101000000Z",
1006        "Jan  1 00:00:00 1950 GMT"},
1007       {0, "19700101000000Z", "700101000000Z", "Jan  1 00:00:00 1970 GMT"},
1008       {981173106, "20010203040506Z", "010203040506Z",
1009        "Feb  3 04:05:06 2001 GMT"},
1010       {951804000, "20000229060000Z", "000229060000Z",
1011        "Feb 29 06:00:00 2000 GMT"},
1012       // NASA says this is the correct time for posterity.
1013       {-16751025, "19690621025615Z", "690621025615Z",
1014        "Jun 21 02:56:15 1969 GMT"},
1015       // -1 is sometimes used as an error value. Ensure we correctly handle it.
1016       {-1, "19691231235959Z", "691231235959Z", "Dec 31 23:59:59 1969 GMT"},
1017       {2524607999, "20491231235959Z", "491231235959Z",
1018        "Dec 31 23:59:59 2049 GMT"},
1019       {2524608000, "20500101000000Z", nullptr, "Jan  1 00:00:00 2050 GMT"},
1020       // Test boundary conditions.
1021       {-62167219200, "00000101000000Z", nullptr, "Jan  1 00:00:00 0 GMT"},
1022       {-62167219201, nullptr, nullptr, nullptr},
1023       {253402300799, "99991231235959Z", nullptr, "Dec 31 23:59:59 9999 GMT"},
1024       {253402300800, nullptr, nullptr, nullptr},
1025   };
1026   for (const auto &t : kTests) {
1027     int64_t tt;
1028     SCOPED_TRACE(t.time);
1029 
1030     bssl::UniquePtr<ASN1_UTCTIME> utc(ASN1_UTCTIME_set(nullptr, t.time));
1031     if (t.utc) {
1032       ASSERT_TRUE(utc);
1033       EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(utc.get()));
1034       EXPECT_EQ(t.utc, ASN1StringToStdString(utc.get()));
1035       EXPECT_TRUE(ASN1Time_check_posix(utc.get(), t.time));
1036       EXPECT_EQ(ASN1_TIME_to_posix(utc.get(), &tt), 1);
1037       EXPECT_EQ(tt, t.time);
1038       EXPECT_EQ(PrintStringToBIO(utc.get(), &ASN1_UTCTIME_print), t.printed);
1039       EXPECT_EQ(PrintStringToBIO(utc.get(), &ASN1_TIME_print), t.printed);
1040     } else {
1041       EXPECT_FALSE(utc);
1042     }
1043 
1044     bssl::UniquePtr<ASN1_GENERALIZEDTIME> generalized(
1045         ASN1_GENERALIZEDTIME_set(nullptr, t.time));
1046     if (t.generalized) {
1047       ASSERT_TRUE(generalized);
1048       EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(generalized.get()));
1049       EXPECT_EQ(t.generalized, ASN1StringToStdString(generalized.get()));
1050       EXPECT_TRUE(ASN1Time_check_posix(generalized.get(), t.time));
1051       EXPECT_EQ(ASN1_TIME_to_posix(generalized.get(), &tt), 1);
1052       EXPECT_EQ(tt, t.time);
1053       EXPECT_EQ(
1054           PrintStringToBIO(generalized.get(), &ASN1_GENERALIZEDTIME_print),
1055           t.printed);
1056       EXPECT_EQ(PrintStringToBIO(generalized.get(), &ASN1_TIME_print),
1057                 t.printed);
1058     } else {
1059       EXPECT_FALSE(generalized);
1060     }
1061 
1062     bssl::UniquePtr<ASN1_TIME> choice(ASN1_TIME_set_posix(nullptr, t.time));
1063     if (t.generalized) {
1064       ASSERT_TRUE(choice);
1065       if (t.utc) {
1066         EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(choice.get()));
1067         EXPECT_EQ(t.utc, ASN1StringToStdString(choice.get()));
1068       } else {
1069         EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(choice.get()));
1070         EXPECT_EQ(t.generalized, ASN1StringToStdString(choice.get()));
1071       }
1072       EXPECT_TRUE(ASN1Time_check_posix(choice.get(), t.time));
1073       EXPECT_EQ(ASN1_TIME_to_posix(choice.get(), &tt), 1);
1074       EXPECT_EQ(tt, t.time);
1075     } else {
1076       EXPECT_FALSE(choice);
1077     }
1078   }
1079 }
1080 
TEST(ASN1Test,TimeSetString)1081 TEST(ASN1Test, TimeSetString) {
1082   bssl::UniquePtr<ASN1_STRING> s(ASN1_STRING_new());
1083   ASSERT_TRUE(s);
1084 
1085   ASSERT_TRUE(ASN1_UTCTIME_set_string(s.get(), "700101000000Z"));
1086   EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(s.get()));
1087   EXPECT_EQ("700101000000Z", ASN1StringToStdString(s.get()));
1088 
1089   ASSERT_TRUE(ASN1_GENERALIZEDTIME_set_string(s.get(), "19700101000000Z"));
1090   EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(s.get()));
1091   EXPECT_EQ("19700101000000Z", ASN1StringToStdString(s.get()));
1092 
1093   // |ASN1_TIME_set_string| accepts either format. It relies on there being no
1094   // overlap between the two.
1095   ASSERT_TRUE(ASN1_TIME_set_string(s.get(), "700101000000Z"));
1096   EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(s.get()));
1097   EXPECT_EQ("700101000000Z", ASN1StringToStdString(s.get()));
1098 
1099   ASSERT_TRUE(ASN1_TIME_set_string(s.get(), "19700101000000Z"));
1100   EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(s.get()));
1101   EXPECT_EQ("19700101000000Z", ASN1StringToStdString(s.get()));
1102 
1103   // |ASN1_TIME_set_string_X509| behaves similarly except it additionally
1104   // converts GeneralizedTime to UTCTime if it fits.
1105   ASSERT_TRUE(ASN1_TIME_set_string_X509(s.get(), "700101000000Z"));
1106   EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(s.get()));
1107   EXPECT_EQ("700101000000Z", ASN1StringToStdString(s.get()));
1108 
1109   ASSERT_TRUE(ASN1_TIME_set_string_X509(s.get(), "19700101000000Z"));
1110   EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(s.get()));
1111   EXPECT_EQ("700101000000Z", ASN1StringToStdString(s.get()));
1112 
1113   ASSERT_TRUE(ASN1_TIME_set_string_X509(s.get(), "19500101000000Z"));
1114   EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(s.get()));
1115   EXPECT_EQ("500101000000Z", ASN1StringToStdString(s.get()));
1116 
1117   ASSERT_TRUE(ASN1_TIME_set_string_X509(s.get(), "19491231235959Z"));
1118   EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(s.get()));
1119   EXPECT_EQ("19491231235959Z", ASN1StringToStdString(s.get()));
1120 
1121   ASSERT_TRUE(ASN1_TIME_set_string_X509(s.get(), "20491231235959Z"));
1122   EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(s.get()));
1123   EXPECT_EQ("491231235959Z", ASN1StringToStdString(s.get()));
1124 
1125   ASSERT_TRUE(ASN1_TIME_set_string_X509(s.get(), "20500101000000Z"));
1126   EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(s.get()));
1127   EXPECT_EQ("20500101000000Z", ASN1StringToStdString(s.get()));
1128 
1129   // Invalid inputs are rejected.
1130   EXPECT_FALSE(ASN1_UTCTIME_set_string(s.get(), "nope"));
1131   EXPECT_FALSE(ASN1_UTCTIME_set_string(s.get(), "19700101000000Z"));
1132   EXPECT_FALSE(ASN1_GENERALIZEDTIME_set_string(s.get(), "nope"));
1133   EXPECT_FALSE(ASN1_GENERALIZEDTIME_set_string(s.get(), "700101000000Z"));
1134   EXPECT_FALSE(ASN1_TIME_set_string(s.get(), "nope"));
1135 
1136   // If passed a null object, the functions validate the input without writing
1137   // to anything.
1138   EXPECT_TRUE(ASN1_UTCTIME_set_string(nullptr, "700101000000Z"));
1139   EXPECT_TRUE(ASN1_TIME_set_string(nullptr, "700101000000Z"));
1140   EXPECT_TRUE(ASN1_TIME_set_string_X509(nullptr, "700101000000Z"));
1141   EXPECT_TRUE(ASN1_GENERALIZEDTIME_set_string(nullptr, "19700101000000Z"));
1142   EXPECT_TRUE(ASN1_TIME_set_string(nullptr, "19700101000000Z"));
1143   EXPECT_TRUE(ASN1_TIME_set_string_X509(nullptr, "19700101000000Z"));
1144   // Test an input |ASN1_TIME_set_string_X509| won't convert to UTCTime.
1145   EXPECT_TRUE(ASN1_GENERALIZEDTIME_set_string(nullptr, "20500101000000Z"));
1146   EXPECT_TRUE(ASN1_TIME_set_string(nullptr, "20500101000000Z"));
1147   EXPECT_TRUE(ASN1_TIME_set_string_X509(nullptr, "20500101000000Z"));
1148   EXPECT_FALSE(ASN1_UTCTIME_set_string(nullptr, "nope"));
1149   EXPECT_FALSE(ASN1_GENERALIZEDTIME_set_string(nullptr, "nope"));
1150   EXPECT_FALSE(ASN1_TIME_set_string(nullptr, "nope"));
1151   EXPECT_FALSE(ASN1_TIME_set_string_X509(nullptr, "nope"));
1152 
1153   // Timezone offsets are not allowed by DER.
1154   EXPECT_FALSE(ASN1_UTCTIME_set_string(nullptr, "700101000000-0400"));
1155   EXPECT_FALSE(ASN1_TIME_set_string(nullptr, "700101000000-0400"));
1156   EXPECT_FALSE(ASN1_TIME_set_string_X509(nullptr, "700101000000-0400"));
1157   EXPECT_FALSE(ASN1_GENERALIZEDTIME_set_string(nullptr, "19700101000000-0400"));
1158   EXPECT_FALSE(ASN1_TIME_set_string(nullptr, "19700101000000-0400"));
1159   EXPECT_FALSE(ASN1_TIME_set_string_X509(nullptr, "19700101000000-0400"));
1160 }
1161 
TEST(ASN1Test,AdjTime)1162 TEST(ASN1Test, AdjTime) {
1163   struct tm tm1, tm2;
1164   int days, secs;
1165 
1166   OPENSSL_posix_to_tm(0, &tm1);
1167   OPENSSL_posix_to_tm(0, &tm2);
1168   // Test values that are too large and should be rejected.
1169   EXPECT_FALSE(OPENSSL_gmtime_adj(&tm1, INT_MIN, INT_MIN));
1170   EXPECT_FALSE(OPENSSL_gmtime_adj(&tm1, INT_MAX, INT_MAX));
1171   // Basic functionality.
1172   EXPECT_TRUE(OPENSSL_gmtime_adj(&tm2, 1, 1));
1173   EXPECT_TRUE(OPENSSL_gmtime_diff(&days, &secs, &tm1, &tm2));
1174   EXPECT_EQ(days, 1);
1175   EXPECT_EQ(secs, 1);
1176   EXPECT_TRUE(OPENSSL_gmtime_diff(&days, &secs, &tm2, &tm1));
1177   EXPECT_EQ(days, -1);
1178   EXPECT_EQ(secs, -1);
1179   // Test a value of days that is very large, but valid.
1180   EXPECT_TRUE(OPENSSL_gmtime_adj(&tm2, 2932800, 0));
1181   EXPECT_TRUE(OPENSSL_gmtime_diff(&days, &secs, &tm1, &tm2));
1182   EXPECT_EQ(days, 2932801);
1183   EXPECT_EQ(secs, 1);
1184   EXPECT_TRUE(OPENSSL_gmtime_diff(&days, &secs, &tm2, &tm1));
1185   EXPECT_EQ(days, -2932801);
1186   EXPECT_EQ(secs, -1);
1187 }
StringToVector(const std::string & str)1188 static std::vector<uint8_t> StringToVector(const std::string &str) {
1189   return std::vector<uint8_t>(str.begin(), str.end());
1190 }
1191 
TEST(ASN1Test,StringPrintEx)1192 TEST(ASN1Test, StringPrintEx) {
1193   const struct {
1194     int type;
1195     std::vector<uint8_t> data;
1196     int str_flags;
1197     unsigned long flags;
1198     std::string expected;
1199   } kTests[] = {
1200       // A string like "hello" is never escaped or quoted.
1201       // |ASN1_STRFLGS_ESC_QUOTE| only introduces quotes when needed. Note
1202       // OpenSSL interprets T61String as Latin-1.
1203       {V_ASN1_T61STRING, StringToVector("hello"), 0, 0, "hello"},
1204       {V_ASN1_T61STRING, StringToVector("hello"), 0,
1205        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB,
1206        "hello"},
1207       {V_ASN1_T61STRING, StringToVector("hello"), 0,
1208        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB |
1209            ASN1_STRFLGS_ESC_QUOTE,
1210        "hello"},
1211 
1212       // By default, 8-bit characters are printed without escaping.
1213       {V_ASN1_T61STRING,
1214        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
1215        0,
1216        0,
1217        std::string(1, '\0') + "\n\x80\xff,+\"\\<>;"},
1218 
1219       // Flags control different escapes. Note that any escape flag will cause
1220       // blackslashes to be escaped.
1221       {V_ASN1_T61STRING,
1222        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
1223        0,
1224        ASN1_STRFLGS_ESC_2253,
1225        std::string(1, '\0') + "\n\x80\xff\\,\\+\\\"\\\\\\<\\>\\;"},
1226       {V_ASN1_T61STRING,
1227        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
1228        0,
1229        ASN1_STRFLGS_ESC_CTRL,
1230        "\\00\\0A\x80\xff,+\"\\\\<>;"},
1231       {V_ASN1_T61STRING,
1232        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
1233        0,
1234        ASN1_STRFLGS_ESC_MSB,
1235        std::string(1, '\0') + "\n\\80\\FF,+\"\\\\<>;"},
1236       {V_ASN1_T61STRING,
1237        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
1238        0,
1239        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB,
1240        "\\00\\0A\\80\\FF\\,\\+\\\"\\\\\\<\\>\\;"},
1241 
1242       // When quoted, fewer characters need to be escaped in RFC 2253.
1243       {V_ASN1_T61STRING,
1244        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
1245        0,
1246        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB |
1247            ASN1_STRFLGS_ESC_QUOTE,
1248        "\"\\00\\0A\\80\\FF,+\\\"\\\\<>;\""},
1249 
1250       // If no characters benefit from quotes, no quotes are added.
1251       {V_ASN1_T61STRING,
1252        {0, '\n', 0x80, 0xff, '"', '\\'},
1253        0,
1254        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB |
1255            ASN1_STRFLGS_ESC_QUOTE,
1256        "\\00\\0A\\80\\FF\\\"\\\\"},
1257 
1258       // RFC 2253 only escapes spaces at the start and end of a string.
1259       {V_ASN1_T61STRING, StringToVector("   "), 0, ASN1_STRFLGS_ESC_2253,
1260        "\\  \\ "},
1261       {V_ASN1_T61STRING, StringToVector("   "), 0,
1262        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_UTF8_CONVERT, "\\  \\ "},
1263       {V_ASN1_T61STRING, StringToVector("   "), 0,
1264        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE, "\"   \""},
1265 
1266       // RFC 2253 only escapes # at the start of a string.
1267       {V_ASN1_T61STRING, StringToVector("###"), 0, ASN1_STRFLGS_ESC_2253,
1268        "\\###"},
1269       {V_ASN1_T61STRING, StringToVector("###"), 0,
1270        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE, "\"###\""},
1271 
1272       // By default, strings are decoded and Unicode code points are
1273       // individually escaped.
1274       {V_ASN1_UTF8STRING, StringToVector("a\xc2\x80\xc4\x80\xf0\x90\x80\x80"),
1275        0, ASN1_STRFLGS_ESC_MSB, "a\\80\\U0100\\W00010000"},
1276       {V_ASN1_BMPSTRING,
1277        {0x00, 'a', 0x00, 0x80, 0x01, 0x00},
1278        0,
1279        ASN1_STRFLGS_ESC_MSB,
1280        "a\\80\\U0100"},
1281       {V_ASN1_UNIVERSALSTRING,
1282        {0x00, 0x00, 0x00, 'a',   //
1283         0x00, 0x00, 0x00, 0x80,  //
1284         0x00, 0x00, 0x01, 0x00,  //
1285         0x00, 0x01, 0x00, 0x00},
1286        0,
1287        ASN1_STRFLGS_ESC_MSB,
1288        "a\\80\\U0100\\W00010000"},
1289 
1290       // |ASN1_STRFLGS_UTF8_CONVERT| normalizes everything to UTF-8 and then
1291       // escapes individual bytes.
1292       {V_ASN1_IA5STRING, StringToVector("a\x80"), 0,
1293        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, "a\\C2\\80"},
1294       {V_ASN1_T61STRING, StringToVector("a\x80"), 0,
1295        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, "a\\C2\\80"},
1296       {V_ASN1_UTF8STRING, StringToVector("a\xc2\x80\xc4\x80\xf0\x90\x80\x80"),
1297        0, ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT,
1298        "a\\C2\\80\\C4\\80\\F0\\90\\80\\80"},
1299       {V_ASN1_BMPSTRING,
1300        {0x00, 'a', 0x00, 0x80, 0x01, 0x00},
1301        0,
1302        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT,
1303        "a\\C2\\80\\C4\\80"},
1304       {V_ASN1_UNIVERSALSTRING,
1305        {0x00, 0x00, 0x00, 'a',   //
1306         0x00, 0x00, 0x00, 0x80,  //
1307         0x00, 0x00, 0x01, 0x00,  //
1308         0x00, 0x01, 0x00, 0x00},
1309        0,
1310        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT,
1311        "a\\C2\\80\\C4\\80\\F0\\90\\80\\80"},
1312 
1313       // The same as above, but without escaping the UTF-8 encoding.
1314       {V_ASN1_IA5STRING, StringToVector("a\x80"), 0, ASN1_STRFLGS_UTF8_CONVERT,
1315        "a\xc2\x80"},
1316       {V_ASN1_T61STRING, StringToVector("a\x80"), 0, ASN1_STRFLGS_UTF8_CONVERT,
1317        "a\xc2\x80"},
1318       {V_ASN1_UTF8STRING, StringToVector("a\xc2\x80\xc4\x80\xf0\x90\x80\x80"),
1319        0, ASN1_STRFLGS_UTF8_CONVERT, "a\xc2\x80\xc4\x80\xf0\x90\x80\x80"},
1320       {V_ASN1_BMPSTRING,
1321        {0x00, 'a', 0x00, 0x80, 0x01, 0x00},
1322        0,
1323        ASN1_STRFLGS_UTF8_CONVERT,
1324        "a\xc2\x80\xc4\x80"},
1325       {V_ASN1_UNIVERSALSTRING,
1326        {0x00, 0x00, 0x00, 'a',   //
1327         0x00, 0x00, 0x00, 0x80,  //
1328         0x00, 0x00, 0x01, 0x00,  //
1329         0x00, 0x01, 0x00, 0x00},
1330        0,
1331        ASN1_STRFLGS_UTF8_CONVERT,
1332        "a\xc2\x80\xc4\x80\xf0\x90\x80\x80"},
1333 
1334       // Types that cannot be decoded are, by default, treated as a byte string.
1335       {V_ASN1_OCTET_STRING, {0xff}, 0, 0, "\xff"},
1336       {-1, {0xff}, 0, 0, "\xff"},
1337       {100, {0xff}, 0, 0, "\xff"},
1338 
1339       // |ASN1_STRFLGS_UTF8_CONVERT| still converts these bytes to UTF-8.
1340       //
1341       // TODO(davidben): This seems like a bug. Although it's unclear because
1342       // the non-RFC-2253 options aren't especially sound. Can we just remove
1343       // them?
1344       {V_ASN1_OCTET_STRING, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, "\xc3\xbf"},
1345       {-1, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, "\xc3\xbf"},
1346       {100, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, "\xc3\xbf"},
1347 
1348       // |ASN1_STRFLGS_IGNORE_TYPE| causes the string type to be ignored, so it
1349       // is always treated as a byte string, even if it is not a valid encoding.
1350       {V_ASN1_UTF8STRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, "\xff"},
1351       {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, "\xff"},
1352       {V_ASN1_UNIVERSALSTRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, "\xff"},
1353 
1354       // |ASN1_STRFLGS_SHOW_TYPE| prepends the type name.
1355       {V_ASN1_UTF8STRING, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, "UTF8STRING:a"},
1356       {-1, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, "(unknown):a"},
1357       {100, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, "(unknown):a"},
1358 
1359       // |ASN1_STRFLGS_DUMP_ALL| and |ASN1_STRFLGS_DUMP_UNKNOWN| cause
1360       // non-string types to be printed in hex, though without the DER wrapper
1361       // by default.
1362       {V_ASN1_UTF8STRING, StringToVector("\xe2\x98\x83"), 0,
1363        ASN1_STRFLGS_DUMP_UNKNOWN, "\\U2603"},
1364       {V_ASN1_UTF8STRING, StringToVector("\xe2\x98\x83"), 0,
1365        ASN1_STRFLGS_DUMP_ALL, "#E29883"},
1366       {V_ASN1_OCTET_STRING, StringToVector("\xe2\x98\x83"), 0,
1367        ASN1_STRFLGS_DUMP_UNKNOWN, "#E29883"},
1368       {V_ASN1_OCTET_STRING, StringToVector("\xe2\x98\x83"), 0,
1369        ASN1_STRFLGS_DUMP_ALL, "#E29883"},
1370 
1371       // |ASN1_STRFLGS_DUMP_DER| includes the entire element.
1372       {V_ASN1_UTF8STRING, StringToVector("\xe2\x98\x83"), 0,
1373        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, "#0C03E29883"},
1374       {V_ASN1_OCTET_STRING, StringToVector("\xe2\x98\x83"), 0,
1375        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, "#0403E29883"},
1376       {V_ASN1_BIT_STRING,
1377        {0x80},
1378        ASN1_STRING_FLAG_BITS_LEFT | 4,
1379        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
1380        "#03020480"},
1381       // INTEGER { 1 }
1382       {V_ASN1_INTEGER,
1383        {0x01},
1384        0,
1385        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
1386        "#020101"},
1387       // INTEGER { -1 }
1388       {V_ASN1_NEG_INTEGER,
1389        {0x01},
1390        0,
1391        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
1392        "#0201FF"},
1393       // ENUMERATED { 1 }
1394       {V_ASN1_ENUMERATED,
1395        {0x01},
1396        0,
1397        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
1398        "#0A0101"},
1399       // ENUMERATED { -1 }
1400       {V_ASN1_NEG_ENUMERATED,
1401        {0x01},
1402        0,
1403        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
1404        "#0A01FF"},
1405   };
1406   for (const auto &t : kTests) {
1407     SCOPED_TRACE(t.type);
1408     SCOPED_TRACE(Bytes(t.data));
1409     SCOPED_TRACE(t.str_flags);
1410     SCOPED_TRACE(t.flags);
1411 
1412     bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_type_new(t.type));
1413     ASSERT_TRUE(str);
1414     ASSERT_TRUE(ASN1_STRING_set(str.get(), t.data.data(), t.data.size()));
1415     str->flags = t.str_flags;
1416 
1417     // If the |BIO| is null, it should measure the size.
1418     int len = ASN1_STRING_print_ex(nullptr, str.get(), t.flags);
1419     EXPECT_EQ(len, static_cast<int>(t.expected.size()));
1420 
1421     // Measuring the size should also work for the |FILE| version
1422     len = ASN1_STRING_print_ex_fp(nullptr, str.get(), t.flags);
1423     EXPECT_EQ(len, static_cast<int>(t.expected.size()));
1424 
1425     // Actually print the string.
1426     bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
1427     ASSERT_TRUE(bio);
1428     len = ASN1_STRING_print_ex(bio.get(), str.get(), t.flags);
1429     EXPECT_EQ(len, static_cast<int>(t.expected.size()));
1430 
1431     const uint8_t *bio_contents;
1432     size_t bio_len;
1433     ASSERT_TRUE(BIO_mem_contents(bio.get(), &bio_contents, &bio_len));
1434     EXPECT_EQ(t.expected, std::string(bio_contents, bio_contents + bio_len));
1435   }
1436 
1437   const struct {
1438     int type;
1439     std::vector<uint8_t> data;
1440     int str_flags;
1441     unsigned long flags;
1442   } kUnprintableTests[] = {
1443       // It is an error if the string cannot be decoded.
1444       {V_ASN1_UTF8STRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB},
1445       {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB},
1446       {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB},
1447       {V_ASN1_UNIVERSALSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB},
1448       // Invalid codepoints are errors.
1449       {V_ASN1_UTF8STRING, {0xed, 0xa0, 0x80}, 0, ASN1_STRFLGS_ESC_MSB},
1450       {V_ASN1_BMPSTRING, {0xd8, 0x00}, 0, ASN1_STRFLGS_ESC_MSB},
1451       {V_ASN1_UNIVERSALSTRING,
1452        {0x00, 0x00, 0xd8, 0x00},
1453        0,
1454        ASN1_STRFLGS_ESC_MSB},
1455       // Even when re-encoding UTF-8 back into UTF-8, we should check validity.
1456       {V_ASN1_UTF8STRING,
1457        {0xff},
1458        0,
1459        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT},
1460   };
1461   for (const auto &t : kUnprintableTests) {
1462     SCOPED_TRACE(t.type);
1463     SCOPED_TRACE(Bytes(t.data));
1464     SCOPED_TRACE(t.str_flags);
1465     SCOPED_TRACE(t.flags);
1466 
1467     bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_type_new(t.type));
1468     ASSERT_TRUE(str);
1469     ASSERT_TRUE(ASN1_STRING_set(str.get(), t.data.data(), t.data.size()));
1470     str->flags = t.str_flags;
1471 
1472     // If the |BIO| is null, it should measure the size.
1473     int len = ASN1_STRING_print_ex(nullptr, str.get(), t.flags);
1474     EXPECT_EQ(len, -1);
1475     ERR_clear_error();
1476 
1477     // Measuring the size should also work for the |FILE| version
1478     len = ASN1_STRING_print_ex_fp(nullptr, str.get(), t.flags);
1479     EXPECT_EQ(len, -1);
1480     ERR_clear_error();
1481 
1482     // Actually print the string.
1483     bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
1484     ASSERT_TRUE(bio);
1485     len = ASN1_STRING_print_ex(bio.get(), str.get(), t.flags);
1486     EXPECT_EQ(len, -1);
1487     ERR_clear_error();
1488   }
1489 }
1490 
TEST(ASN1Test,MBString)1491 TEST(ASN1Test, MBString) {
1492   const unsigned long kAll = B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING |
1493                              B_ASN1_T61STRING | B_ASN1_BMPSTRING |
1494                              B_ASN1_UNIVERSALSTRING | B_ASN1_UTF8STRING;
1495 
1496   const struct {
1497     int format;
1498     std::vector<uint8_t> in;
1499     unsigned long mask;
1500     int expected_type;
1501     std::vector<uint8_t> expected_data;
1502     int num_codepoints;
1503   } kTests[] = {
1504       // Given a choice of formats, we pick the smallest that fits.
1505       {MBSTRING_UTF8, {}, kAll, V_ASN1_PRINTABLESTRING, {}, 0},
1506       {MBSTRING_UTF8, {'a'}, kAll, V_ASN1_PRINTABLESTRING, {'a'}, 1},
1507       {MBSTRING_UTF8,
1508        {'a', 'A', '0', '\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'},
1509        kAll,
1510        V_ASN1_PRINTABLESTRING,
1511        {'a', 'A', '0', '\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'},
1512        14},
1513       {MBSTRING_UTF8, {'*'}, kAll, V_ASN1_IA5STRING, {'*'}, 1},
1514       {MBSTRING_UTF8, {'\n'}, kAll, V_ASN1_IA5STRING, {'\n'}, 1},
1515       {MBSTRING_UTF8,
1516        {0xc2, 0x80 /* U+0080 */},
1517        kAll,
1518        V_ASN1_T61STRING,
1519        {0x80},
1520        1},
1521       {MBSTRING_UTF8,
1522        {0xc4, 0x80 /* U+0100 */},
1523        kAll,
1524        V_ASN1_BMPSTRING,
1525        {0x01, 0x00},
1526        1},
1527       {MBSTRING_UTF8,
1528        {0xf0, 0x90, 0x80, 0x80 /* U+10000 */},
1529        kAll,
1530        V_ASN1_UNIVERSALSTRING,
1531        {0x00, 0x01, 0x00, 0x00},
1532        1},
1533       {MBSTRING_UTF8,
1534        {0xf0, 0x90, 0x80, 0x80 /* U+10000 */},
1535        kAll & ~B_ASN1_UNIVERSALSTRING,
1536        V_ASN1_UTF8STRING,
1537        {0xf0, 0x90, 0x80, 0x80},
1538        1},
1539 
1540       // NUL is not printable. It should also not terminate iteration.
1541       {MBSTRING_UTF8, {0}, kAll, V_ASN1_IA5STRING, {0}, 1},
1542       {MBSTRING_UTF8, {0, 'a'}, kAll, V_ASN1_IA5STRING, {0, 'a'}, 2},
1543 
1544       // When a particular format is specified, we use it.
1545       {MBSTRING_UTF8,
1546        {'a'},
1547        B_ASN1_PRINTABLESTRING,
1548        V_ASN1_PRINTABLESTRING,
1549        {'a'},
1550        1},
1551       {MBSTRING_UTF8, {'a'}, B_ASN1_IA5STRING, V_ASN1_IA5STRING, {'a'}, 1},
1552       {MBSTRING_UTF8, {'a'}, B_ASN1_T61STRING, V_ASN1_T61STRING, {'a'}, 1},
1553       {MBSTRING_UTF8, {'a'}, B_ASN1_UTF8STRING, V_ASN1_UTF8STRING, {'a'}, 1},
1554       {MBSTRING_UTF8,
1555        {'a'},
1556        B_ASN1_BMPSTRING,
1557        V_ASN1_BMPSTRING,
1558        {0x00, 'a'},
1559        1},
1560       {MBSTRING_UTF8,
1561        {'a'},
1562        B_ASN1_UNIVERSALSTRING,
1563        V_ASN1_UNIVERSALSTRING,
1564        {0x00, 0x00, 0x00, 'a'},
1565        1},
1566 
1567       // A long string with characters of many widths, to test sizes are
1568       // measured in code points.
1569       {MBSTRING_UTF8,
1570        {
1571            'a',                     //
1572            0xc2, 0x80,              // U+0080
1573            0xc4, 0x80,              // U+0100
1574            0xf0, 0x90, 0x80, 0x80,  // U+10000
1575        },
1576        B_ASN1_UNIVERSALSTRING,
1577        V_ASN1_UNIVERSALSTRING,
1578        {
1579            0x00, 0x00, 0x00, 'a',   //
1580            0x00, 0x00, 0x00, 0x80,  //
1581            0x00, 0x00, 0x01, 0x00,  //
1582            0x00, 0x01, 0x00, 0x00,  //
1583        },
1584        4},
1585   };
1586   for (const auto &t : kTests) {
1587     SCOPED_TRACE(t.format);
1588     SCOPED_TRACE(Bytes(t.in));
1589     SCOPED_TRACE(t.mask);
1590 
1591     // Passing in nullptr should do a dry run.
1592     EXPECT_EQ(t.expected_type,
1593               ASN1_mbstring_copy(nullptr, t.in.data(), t.in.size(), t.format,
1594                                  t.mask));
1595 
1596     // Test allocating a new object.
1597     ASN1_STRING *str = nullptr;
1598     EXPECT_EQ(
1599         t.expected_type,
1600         ASN1_mbstring_copy(&str, t.in.data(), t.in.size(), t.format, t.mask));
1601     ASSERT_TRUE(str);
1602     EXPECT_EQ(t.expected_type, ASN1_STRING_type(str));
1603     EXPECT_EQ(Bytes(t.expected_data),
1604               Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str)));
1605 
1606     // Test writing into an existing object.
1607     ASN1_STRING_free(str);
1608     str = ASN1_STRING_new();
1609     ASSERT_TRUE(str);
1610     ASN1_STRING *old_str = str;
1611     EXPECT_EQ(
1612         t.expected_type,
1613         ASN1_mbstring_copy(&str, t.in.data(), t.in.size(), t.format, t.mask));
1614     ASSERT_EQ(old_str, str);
1615     EXPECT_EQ(t.expected_type, ASN1_STRING_type(str));
1616     EXPECT_EQ(Bytes(t.expected_data),
1617               Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str)));
1618     ASN1_STRING_free(str);
1619     str = nullptr;
1620 
1621     // minsize and maxsize should be enforced, even in a dry run.
1622     EXPECT_EQ(t.expected_type,
1623               ASN1_mbstring_ncopy(nullptr, t.in.data(), t.in.size(), t.format,
1624                                   t.mask, /*minsize=*/t.num_codepoints,
1625                                   /*maxsize=*/t.num_codepoints));
1626 
1627     EXPECT_EQ(t.expected_type,
1628               ASN1_mbstring_ncopy(&str, t.in.data(), t.in.size(), t.format,
1629                                   t.mask, /*minsize=*/t.num_codepoints,
1630                                   /*maxsize=*/t.num_codepoints));
1631     ASSERT_TRUE(str);
1632     EXPECT_EQ(t.expected_type, ASN1_STRING_type(str));
1633     EXPECT_EQ(Bytes(t.expected_data),
1634               Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str)));
1635     ASN1_STRING_free(str);
1636     str = nullptr;
1637 
1638     EXPECT_EQ(-1, ASN1_mbstring_ncopy(
1639                       nullptr, t.in.data(), t.in.size(), t.format, t.mask,
1640                       /*minsize=*/t.num_codepoints + 1, /*maxsize=*/0));
1641     ERR_clear_error();
1642     EXPECT_EQ(-1, ASN1_mbstring_ncopy(
1643                       &str, t.in.data(), t.in.size(), t.format, t.mask,
1644                       /*minsize=*/t.num_codepoints + 1, /*maxsize=*/0));
1645     EXPECT_FALSE(str);
1646     ERR_clear_error();
1647     if (t.num_codepoints > 1) {
1648       EXPECT_EQ(-1, ASN1_mbstring_ncopy(
1649                         nullptr, t.in.data(), t.in.size(), t.format, t.mask,
1650                         /*minsize=*/0, /*maxsize=*/t.num_codepoints - 1));
1651       ERR_clear_error();
1652       EXPECT_EQ(-1, ASN1_mbstring_ncopy(
1653                         &str, t.in.data(), t.in.size(), t.format, t.mask,
1654                         /*minsize=*/0, /*maxsize=*/t.num_codepoints - 1));
1655       EXPECT_FALSE(str);
1656       ERR_clear_error();
1657     }
1658   }
1659 
1660   const struct {
1661     int format;
1662     std::vector<uint8_t> in;
1663     unsigned long mask;
1664   } kInvalidTests[] = {
1665       // Invalid encodings are rejected.
1666       {MBSTRING_UTF8, {0xff}, B_ASN1_UTF8STRING},
1667       {MBSTRING_BMP, {0xff}, B_ASN1_UTF8STRING},
1668       {MBSTRING_UNIV, {0xff}, B_ASN1_UTF8STRING},
1669 
1670       // Lone surrogates are not code points.
1671       {MBSTRING_UTF8, {0xed, 0xa0, 0x80}, B_ASN1_UTF8STRING},
1672       {MBSTRING_BMP, {0xd8, 0x00}, B_ASN1_UTF8STRING},
1673       {MBSTRING_UNIV, {0x00, 0x00, 0xd8, 0x00}, B_ASN1_UTF8STRING},
1674 
1675       // The input does not fit in the allowed output types.
1676       {MBSTRING_UTF8, {'\n'}, B_ASN1_PRINTABLESTRING},
1677       {MBSTRING_UTF8,
1678        {0xc2, 0x80 /* U+0080 */},
1679        B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING},
1680       {MBSTRING_UTF8,
1681        {0xc4, 0x80 /* U+0100 */},
1682        B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING | B_ASN1_T61STRING},
1683       {MBSTRING_UTF8,
1684        {0xf0, 0x90, 0x80, 0x80 /* U+10000 */},
1685        B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING | B_ASN1_T61STRING |
1686            B_ASN1_BMPSTRING},
1687 
1688       // Unrecognized bits are ignored.
1689       {MBSTRING_UTF8, {'\n'}, B_ASN1_PRINTABLESTRING | B_ASN1_SEQUENCE},
1690   };
1691   for (const auto &t : kInvalidTests) {
1692     SCOPED_TRACE(t.format);
1693     SCOPED_TRACE(Bytes(t.in));
1694     SCOPED_TRACE(t.mask);
1695 
1696     EXPECT_EQ(-1, ASN1_mbstring_copy(nullptr, t.in.data(), t.in.size(),
1697                                      t.format, t.mask));
1698     ERR_clear_error();
1699 
1700     ASN1_STRING *str = nullptr;
1701     EXPECT_EQ(-1, ASN1_mbstring_copy(&str, t.in.data(), t.in.size(),
1702                                      t.format, t.mask));
1703     ERR_clear_error();
1704     EXPECT_EQ(nullptr, str);
1705   }
1706 }
1707 
TEST(ASN1Test,StringByNID)1708 TEST(ASN1Test, StringByNID) {
1709   // |ASN1_mbstring_*| tests above test most of the interactions with |inform|,
1710   // so all tests below use UTF-8.
1711   const struct {
1712     int nid;
1713     std::string in;
1714     int expected_type;
1715     std::string expected;
1716   } kTests[] = {
1717       // Although DirectoryString and PKCS9String allow many types of strings,
1718       // we prefer UTF8String.
1719       {NID_commonName, "abc", V_ASN1_UTF8STRING, "abc"},
1720       {NID_commonName, "\xe2\x98\x83", V_ASN1_UTF8STRING, "\xe2\x98\x83"},
1721       {NID_localityName, "abc", V_ASN1_UTF8STRING, "abc"},
1722       {NID_stateOrProvinceName, "abc", V_ASN1_UTF8STRING, "abc"},
1723       {NID_organizationName, "abc", V_ASN1_UTF8STRING, "abc"},
1724       {NID_organizationalUnitName, "abc", V_ASN1_UTF8STRING, "abc"},
1725       {NID_pkcs9_unstructuredName, "abc", V_ASN1_UTF8STRING, "abc"},
1726       {NID_pkcs9_challengePassword, "abc", V_ASN1_UTF8STRING, "abc"},
1727       {NID_pkcs9_unstructuredAddress, "abc", V_ASN1_UTF8STRING, "abc"},
1728       {NID_givenName, "abc", V_ASN1_UTF8STRING, "abc"},
1729       {NID_givenName, "abc", V_ASN1_UTF8STRING, "abc"},
1730       {NID_givenName, "abc", V_ASN1_UTF8STRING, "abc"},
1731       {NID_surname, "abc", V_ASN1_UTF8STRING, "abc"},
1732       {NID_initials, "abc", V_ASN1_UTF8STRING, "abc"},
1733       {NID_name, "abc", V_ASN1_UTF8STRING, "abc"},
1734 
1735       // Some attribute types use a particular string type.
1736       {NID_countryName, "US", V_ASN1_PRINTABLESTRING, "US"},
1737       {NID_pkcs9_emailAddress, "example@example.com", V_ASN1_IA5STRING,
1738        "example@example.com"},
1739       {NID_serialNumber, "1234", V_ASN1_PRINTABLESTRING, "1234"},
1740       {NID_friendlyName, "abc", V_ASN1_BMPSTRING,
1741        std::string({'\0', 'a', '\0', 'b', '\0', 'c'})},
1742       {NID_dnQualifier, "US", V_ASN1_PRINTABLESTRING, "US"},
1743       {NID_domainComponent, "com", V_ASN1_IA5STRING, "com"},
1744       {NID_ms_csp_name, "abc", V_ASN1_BMPSTRING,
1745        std::string({'\0', 'a', '\0', 'b', '\0', 'c'})},
1746 
1747       // Unknown NIDs default to UTF8String.
1748       {NID_rsaEncryption, "abc", V_ASN1_UTF8STRING, "abc"},
1749   };
1750   for (const auto &t : kTests) {
1751     SCOPED_TRACE(t.nid);
1752     SCOPED_TRACE(t.in);
1753 
1754     // Test allocating a new object.
1755     bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_set_by_NID(
1756         nullptr, reinterpret_cast<const uint8_t *>(t.in.data()), t.in.size(),
1757         MBSTRING_UTF8, t.nid));
1758     ASSERT_TRUE(str);
1759     EXPECT_EQ(t.expected_type, ASN1_STRING_type(str.get()));
1760     EXPECT_EQ(Bytes(t.expected), Bytes(ASN1_STRING_get0_data(str.get()),
1761                                        ASN1_STRING_length(str.get())));
1762 
1763     // Test writing into an existing object.
1764     str.reset(ASN1_STRING_new());
1765     ASSERT_TRUE(str);
1766     ASN1_STRING *old_str = str.get();
1767     ASSERT_TRUE(ASN1_STRING_set_by_NID(
1768         &old_str, reinterpret_cast<const uint8_t *>(t.in.data()), t.in.size(),
1769         MBSTRING_UTF8, t.nid));
1770     ASSERT_EQ(old_str, str.get());
1771     EXPECT_EQ(t.expected_type, ASN1_STRING_type(str.get()));
1772     EXPECT_EQ(Bytes(t.expected), Bytes(ASN1_STRING_get0_data(str.get()),
1773                                        ASN1_STRING_length(str.get())));
1774   }
1775 
1776   const struct {
1777     int nid;
1778     std::string in;
1779   } kInvalidTests[] = {
1780       // DirectoryString forbids empty inputs.
1781       {NID_commonName, ""},
1782       {NID_localityName, ""},
1783       {NID_stateOrProvinceName, ""},
1784       {NID_organizationName, ""},
1785       {NID_organizationalUnitName, ""},
1786       {NID_pkcs9_unstructuredName, ""},
1787       {NID_pkcs9_challengePassword, ""},
1788       {NID_pkcs9_unstructuredAddress, ""},
1789       {NID_givenName, ""},
1790       {NID_givenName, ""},
1791       {NID_givenName, ""},
1792       {NID_surname, ""},
1793       {NID_initials, ""},
1794       {NID_name, ""},
1795 
1796       // Test upper bounds from RFC 5280.
1797       {NID_name, std::string(32769, 'a')},
1798       {NID_commonName, std::string(65, 'a')},
1799       {NID_localityName, std::string(129, 'a')},
1800       {NID_stateOrProvinceName, std::string(129, 'a')},
1801       {NID_organizationName, std::string(65, 'a')},
1802       {NID_organizationalUnitName, std::string(65, 'a')},
1803       {NID_pkcs9_emailAddress, std::string(256, 'a')},
1804       {NID_serialNumber, std::string(65, 'a')},
1805 
1806       // X520countryName must be exactly two characters.
1807       {NID_countryName, "A"},
1808       {NID_countryName, "AAA"},
1809 
1810       // Some string types cannot represent all codepoints.
1811       {NID_countryName, "\xe2\x98\x83"},
1812       {NID_pkcs9_emailAddress, "\xe2\x98\x83"},
1813       {NID_serialNumber, "\xe2\x98\x83"},
1814       {NID_dnQualifier, "\xe2\x98\x83"},
1815       {NID_domainComponent, "\xe2\x98\x83"},
1816   };
1817   for (const auto &t : kInvalidTests) {
1818     SCOPED_TRACE(t.nid);
1819     SCOPED_TRACE(t.in);
1820     bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_set_by_NID(
1821         nullptr, reinterpret_cast<const uint8_t *>(t.in.data()), t.in.size(),
1822         MBSTRING_UTF8, t.nid));
1823     EXPECT_FALSE(str);
1824     ERR_clear_error();
1825   }
1826 }
1827 
TEST(ASN1Test,StringByCustomNID)1828 TEST(ASN1Test, StringByCustomNID) {
1829   // This test affects library-global state. We rely on nothing else in the test
1830   // suite using these OIDs.
1831   int nid1 = OBJ_create("1.2.840.113554.4.1.72585.1000", "custom OID 1000",
1832                         "custom OID 1000");
1833   ASSERT_NE(NID_undef, nid1);
1834   int nid2 = OBJ_create("1.2.840.113554.4.1.72585.1001", "custom OID 1001",
1835                         "custom OID 1001");
1836   ASSERT_NE(NID_undef, nid2);
1837 
1838   // Values registered in the string table should be picked up.
1839   ASSERT_TRUE(ASN1_STRING_TABLE_add(nid1, 5, 10, V_ASN1_PRINTABLESTRING,
1840                                     STABLE_NO_MASK));
1841   bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_set_by_NID(
1842       nullptr, reinterpret_cast<const uint8_t *>("12345"), 5, MBSTRING_UTF8,
1843       nid1));
1844   ASSERT_TRUE(str);
1845   EXPECT_EQ(V_ASN1_PRINTABLESTRING, ASN1_STRING_type(str.get()));
1846   EXPECT_EQ(Bytes("12345"), Bytes(ASN1_STRING_get0_data(str.get()),
1847                                   ASN1_STRING_length(str.get())));
1848 
1849   // Minimum and maximum lengths are enforced.
1850   str.reset(ASN1_STRING_set_by_NID(
1851       nullptr, reinterpret_cast<const uint8_t *>("1234"), 4, MBSTRING_UTF8,
1852       nid1));
1853   EXPECT_FALSE(str);
1854   ERR_clear_error();
1855   str.reset(ASN1_STRING_set_by_NID(
1856       nullptr, reinterpret_cast<const uint8_t *>("12345678901"), 11,
1857       MBSTRING_UTF8, nid1));
1858   EXPECT_FALSE(str);
1859   ERR_clear_error();
1860 
1861   // Without |STABLE_NO_MASK|, we always pick UTF8String. -1 means there is no
1862   // length limit.
1863   ASSERT_TRUE(ASN1_STRING_TABLE_add(nid2, -1, -1, DIRSTRING_TYPE, 0));
1864   str.reset(ASN1_STRING_set_by_NID(nullptr,
1865                                    reinterpret_cast<const uint8_t *>("12345"),
1866                                    5, MBSTRING_UTF8, nid2));
1867   ASSERT_TRUE(str);
1868   EXPECT_EQ(V_ASN1_UTF8STRING, ASN1_STRING_type(str.get()));
1869   EXPECT_EQ(Bytes("12345"), Bytes(ASN1_STRING_get0_data(str.get()),
1870                                   ASN1_STRING_length(str.get())));
1871 
1872   // Overriding existing entries, built-in or custom, is an error.
1873   EXPECT_FALSE(
1874       ASN1_STRING_TABLE_add(NID_countryName, -1, -1, DIRSTRING_TYPE, 0));
1875   EXPECT_FALSE(ASN1_STRING_TABLE_add(nid1, -1, -1, DIRSTRING_TYPE, 0));
1876 }
1877 
1878 #if defined(OPENSSL_THREADS)
TEST(ASN1Test,StringByCustomNIDThreads)1879 TEST(ASN1Test, StringByCustomNIDThreads) {
1880   // This test affects library-global state. We rely on nothing else in the test
1881   // suite using these OIDs.
1882   int nid1 = OBJ_create("1.2.840.113554.4.1.72585.1002", "custom OID 1002",
1883                         "custom OID 1002");
1884   ASSERT_NE(NID_undef, nid1);
1885   int nid2 = OBJ_create("1.2.840.113554.4.1.72585.1003", "custom OID 1003",
1886                         "custom OID 1003");
1887   ASSERT_NE(NID_undef, nid2);
1888 
1889   std::vector<std::thread> threads;
1890   threads.emplace_back([&] {
1891     ASSERT_TRUE(ASN1_STRING_TABLE_add(nid1, 5, 10, V_ASN1_PRINTABLESTRING,
1892                                       STABLE_NO_MASK));
1893     bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_set_by_NID(
1894         nullptr, reinterpret_cast<const uint8_t *>("12345"), 5, MBSTRING_UTF8,
1895         nid1));
1896     ASSERT_TRUE(str);
1897     EXPECT_EQ(V_ASN1_PRINTABLESTRING, ASN1_STRING_type(str.get()));
1898     EXPECT_EQ(Bytes("12345"), Bytes(ASN1_STRING_get0_data(str.get()),
1899                                     ASN1_STRING_length(str.get())));
1900   });
1901   threads.emplace_back([&] {
1902     ASSERT_TRUE(ASN1_STRING_TABLE_add(nid2, 5, 10, V_ASN1_PRINTABLESTRING,
1903                                       STABLE_NO_MASK));
1904     bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_set_by_NID(
1905         nullptr, reinterpret_cast<const uint8_t *>("12345"), 5, MBSTRING_UTF8,
1906         nid2));
1907     ASSERT_TRUE(str);
1908     EXPECT_EQ(V_ASN1_PRINTABLESTRING, ASN1_STRING_type(str.get()));
1909     EXPECT_EQ(Bytes("12345"), Bytes(ASN1_STRING_get0_data(str.get()),
1910                                     ASN1_STRING_length(str.get())));
1911   });
1912   for (auto &thread : threads) {
1913     thread.join();
1914   }
1915 }
1916 #endif  // OPENSSL_THREADS
1917 
1918 // Test that multi-string types correctly encode negative ENUMERATED.
1919 // Multi-string types cannot contain INTEGER, so we only test ENUMERATED.
TEST(ASN1Test,NegativeEnumeratedMultistring)1920 TEST(ASN1Test, NegativeEnumeratedMultistring) {
1921   static const uint8_t kMinusOne[] = {0x0a, 0x01, 0xff};  // ENUMERATED { -1 }
1922   // |ASN1_PRINTABLE| is a multi-string type that allows ENUMERATED.
1923   const uint8_t *p = kMinusOne;
1924   bssl::UniquePtr<ASN1_STRING> str(
1925       d2i_ASN1_PRINTABLE(nullptr, &p, sizeof(kMinusOne)));
1926   ASSERT_TRUE(str);
1927   TestSerialize(str.get(), i2d_ASN1_PRINTABLE, kMinusOne);
1928 }
1929 
1930 // Encoding a CHOICE type with an invalid selector should fail.
TEST(ASN1Test,InvalidChoice)1931 TEST(ASN1Test, InvalidChoice) {
1932   bssl::UniquePtr<GENERAL_NAME> name(GENERAL_NAME_new());
1933   ASSERT_TRUE(name);
1934   // CHOICE types are initialized with an invalid selector.
1935   EXPECT_EQ(-1, name->type);
1936   // |name| should fail to encode.
1937   EXPECT_EQ(-1, i2d_GENERAL_NAME(name.get(), nullptr));
1938 
1939   // The error should be propagated through types containing |name|.
1940   bssl::UniquePtr<GENERAL_NAMES> names(GENERAL_NAMES_new());
1941   ASSERT_TRUE(names);
1942   EXPECT_TRUE(bssl::PushToStack(names.get(), std::move(name)));
1943   EXPECT_EQ(-1, i2d_GENERAL_NAMES(names.get(), nullptr));
1944 }
1945 
1946 // Encoding NID-only |ASN1_OBJECT|s should fail.
TEST(ASN1Test,InvalidObject)1947 TEST(ASN1Test, InvalidObject) {
1948   EXPECT_EQ(-1, i2d_ASN1_OBJECT(OBJ_nid2obj(NID_kx_ecdhe), nullptr));
1949 
1950   bssl::UniquePtr<X509_ALGOR> alg(X509_ALGOR_new());
1951   ASSERT_TRUE(alg);
1952   ASSERT_TRUE(X509_ALGOR_set0(alg.get(), OBJ_nid2obj(NID_kx_ecdhe),
1953                               V_ASN1_UNDEF, nullptr));
1954   EXPECT_EQ(-1, i2d_X509_ALGOR(alg.get(), nullptr));
1955 }
1956 
1957 // Encoding invalid |ASN1_TYPE|s should fail. |ASN1_TYPE|s are
1958 // default-initialized to an invalid type.
TEST(ASN1Test,InvalidASN1Type)1959 TEST(ASN1Test, InvalidASN1Type) {
1960   bssl::UniquePtr<ASN1_TYPE> obj(ASN1_TYPE_new());
1961   ASSERT_TRUE(obj);
1962   EXPECT_EQ(-1, obj->type);
1963   EXPECT_EQ(-1, i2d_ASN1_TYPE(obj.get(), nullptr));
1964 }
1965 
1966 // Encoding invalid MSTRING types should fail. An MSTRING is a CHOICE of
1967 // string-like types. They are initialized to an invalid type.
TEST(ASN1Test,InvalidMSTRING)1968 TEST(ASN1Test, InvalidMSTRING) {
1969   bssl::UniquePtr<ASN1_STRING> obj(ASN1_TIME_new());
1970   ASSERT_TRUE(obj);
1971   EXPECT_EQ(-1, obj->type);
1972   EXPECT_EQ(-1, i2d_ASN1_TIME(obj.get(), nullptr));
1973 
1974   obj.reset(DIRECTORYSTRING_new());
1975   ASSERT_TRUE(obj);
1976   EXPECT_EQ(-1, obj->type);
1977   EXPECT_EQ(-1, i2d_DIRECTORYSTRING(obj.get(), nullptr));
1978 }
1979 
TEST(ASN1Test,StringTableSorted)1980 TEST(ASN1Test, StringTableSorted) {
1981   const ASN1_STRING_TABLE *table;
1982   size_t table_len;
1983   asn1_get_string_table_for_testing(&table, &table_len);
1984   for (size_t i = 1; i < table_len; i++) {
1985     EXPECT_LT(table[i-1].nid, table[i].nid);
1986   }
1987 }
1988 
TEST(ASN1Test,Null)1989 TEST(ASN1Test, Null) {
1990   // An |ASN1_NULL| is an opaque, non-null pointer. It is an arbitrary signaling
1991   // value and does not need to be freed. (If the pointer is null, this is an
1992   // omitted OPTIONAL NULL.)
1993   EXPECT_NE(nullptr, ASN1_NULL_new());
1994 
1995   // It is safe to free either the non-null pointer or the null one.
1996   ASN1_NULL_free(ASN1_NULL_new());
1997   ASN1_NULL_free(nullptr);
1998 
1999   // A NULL may be decoded.
2000   static const uint8_t kNull[] = {0x05, 0x00};
2001   const uint8_t *ptr = kNull;
2002   EXPECT_NE(nullptr, d2i_ASN1_NULL(nullptr, &ptr, sizeof(kNull)));
2003   EXPECT_EQ(ptr, kNull + sizeof(kNull));
2004 
2005   // It may also be re-encoded.
2006   uint8_t *enc = nullptr;
2007   int enc_len = i2d_ASN1_NULL(ASN1_NULL_new(), &enc);
2008   ASSERT_GE(enc_len, 0);
2009   EXPECT_EQ(Bytes(kNull), Bytes(enc, enc_len));
2010   OPENSSL_free(enc);
2011   enc = nullptr;
2012 
2013   // Although the standalone representation of NULL is a non-null pointer, the
2014   // |ASN1_TYPE| representation is a null pointer.
2015   ptr = kNull;
2016   bssl::UniquePtr<ASN1_TYPE> null_type(
2017       d2i_ASN1_TYPE(nullptr, &ptr, sizeof(kNull)));
2018   ASSERT_TRUE(null_type);
2019   EXPECT_EQ(ptr, kNull + sizeof(kNull));
2020   EXPECT_EQ(V_ASN1_NULL, ASN1_TYPE_get(null_type.get()));
2021   EXPECT_EQ(nullptr, null_type->value.ptr);
2022 }
2023 
TEST(ASN1Test,Pack)2024 TEST(ASN1Test, Pack) {
2025   bssl::UniquePtr<BASIC_CONSTRAINTS> val(BASIC_CONSTRAINTS_new());
2026   ASSERT_TRUE(val);
2027   val->ca = 0;
2028 
2029   // Test all three calling conventions.
2030   static const uint8_t kExpected[] = {0x30, 0x00};
2031   bssl::UniquePtr<ASN1_STRING> str(
2032       ASN1_item_pack(val.get(), ASN1_ITEM_rptr(BASIC_CONSTRAINTS), nullptr));
2033   ASSERT_TRUE(str);
2034   EXPECT_EQ(
2035       Bytes(ASN1_STRING_get0_data(str.get()), ASN1_STRING_length(str.get())),
2036       Bytes(kExpected));
2037 
2038   ASN1_STRING *raw = nullptr;
2039   str.reset(ASN1_item_pack(val.get(), ASN1_ITEM_rptr(BASIC_CONSTRAINTS), &raw));
2040   ASSERT_TRUE(str);
2041   EXPECT_EQ(raw, str.get());
2042   EXPECT_EQ(
2043       Bytes(ASN1_STRING_get0_data(str.get()), ASN1_STRING_length(str.get())),
2044       Bytes(kExpected));
2045 
2046   str.reset(ASN1_STRING_new());
2047   ASSERT_TRUE(str);
2048   raw = str.get();
2049   EXPECT_TRUE(
2050       ASN1_item_pack(val.get(), ASN1_ITEM_rptr(BASIC_CONSTRAINTS), &raw));
2051   EXPECT_EQ(raw, str.get());
2052   EXPECT_EQ(
2053       Bytes(ASN1_STRING_get0_data(str.get()), ASN1_STRING_length(str.get())),
2054       Bytes(kExpected));
2055 }
2056 
TEST(ASN1Test,Unpack)2057 TEST(ASN1Test, Unpack) {
2058   bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_new());
2059   ASSERT_TRUE(str);
2060 
2061   static const uint8_t kValid[] = {0x30, 0x00};
2062   ASSERT_TRUE(
2063       ASN1_STRING_set(str.get(), kValid, sizeof(kValid)));
2064   bssl::UniquePtr<BASIC_CONSTRAINTS> val(static_cast<BASIC_CONSTRAINTS *>(
2065       ASN1_item_unpack(str.get(), ASN1_ITEM_rptr(BASIC_CONSTRAINTS))));
2066   ASSERT_TRUE(val);
2067   EXPECT_EQ(val->ca, 0);
2068   EXPECT_EQ(val->pathlen, nullptr);
2069 
2070   static const uint8_t kInvalid[] = {0x31, 0x00};
2071   ASSERT_TRUE(ASN1_STRING_set(str.get(), kInvalid, sizeof(kInvalid)));
2072   val.reset(static_cast<BASIC_CONSTRAINTS *>(
2073       ASN1_item_unpack(str.get(), ASN1_ITEM_rptr(BASIC_CONSTRAINTS))));
2074   EXPECT_FALSE(val);
2075 
2076   static const uint8_t kTraiilingData[] = {0x30, 0x00, 0x00};
2077   ASSERT_TRUE(
2078       ASN1_STRING_set(str.get(), kTraiilingData, sizeof(kTraiilingData)));
2079   val.reset(static_cast<BASIC_CONSTRAINTS *>(
2080       ASN1_item_unpack(str.get(), ASN1_ITEM_rptr(BASIC_CONSTRAINTS))));
2081   EXPECT_FALSE(val);
2082 }
2083 
TEST(ASN1Test,StringCmp)2084 TEST(ASN1Test, StringCmp) {
2085   struct Input {
2086     int type;
2087     std::vector<uint8_t> data;
2088     int flags;
2089     bool equals_previous;
2090   };
2091   // kInputs is a list of |ASN1_STRING| parameters, in sorted order. The input
2092   // should be sorted by bit length, then data, then type.
2093   const Input kInputs[] = {
2094       {V_ASN1_BIT_STRING, {}, ASN1_STRING_FLAG_BITS_LEFT | 0, false},
2095       {V_ASN1_BIT_STRING, {}, 0, true},
2096       // When |ASN1_STRING_FLAG_BITS_LEFT| is unset, BIT STRINGs implicitly
2097       // drop trailing zeros.
2098       {V_ASN1_BIT_STRING, {0x00, 0x00, 0x00, 0x00}, 0, true},
2099 
2100       {V_ASN1_OCTET_STRING, {}, 0, false},
2101       {V_ASN1_UTF8STRING, {}, 0, false},
2102 
2103       // BIT STRINGs with padding bits (i.e. not part of the actual value) are
2104       // shorter and thus sort earlier:
2105       // 1-bit inputs.
2106       {V_ASN1_BIT_STRING, {0x00}, ASN1_STRING_FLAG_BITS_LEFT | 7, false},
2107       {V_ASN1_BIT_STRING, {0x80}, ASN1_STRING_FLAG_BITS_LEFT | 7, false},
2108       // 2-bit inputs.
2109       {V_ASN1_BIT_STRING, {0x00}, ASN1_STRING_FLAG_BITS_LEFT | 6, false},
2110       {V_ASN1_BIT_STRING, {0xc0}, ASN1_STRING_FLAG_BITS_LEFT | 6, false},
2111       // 3-bit inputs.
2112       {V_ASN1_BIT_STRING, {0x00}, ASN1_STRING_FLAG_BITS_LEFT | 5, false},
2113       {V_ASN1_BIT_STRING, {0xe0}, ASN1_STRING_FLAG_BITS_LEFT | 5, false},
2114       // 4-bit inputs.
2115       {V_ASN1_BIT_STRING, {0xf0}, ASN1_STRING_FLAG_BITS_LEFT | 4, false},
2116       {V_ASN1_BIT_STRING, {0xf0}, 0, true},        // 4 trailing zeros dropped.
2117       {V_ASN1_BIT_STRING, {0xf0, 0x00}, 0, true},  // 12 trailing zeros dropped.
2118       // 5-bit inputs.
2119       {V_ASN1_BIT_STRING, {0x00}, ASN1_STRING_FLAG_BITS_LEFT | 3, false},
2120       {V_ASN1_BIT_STRING, {0xf0}, ASN1_STRING_FLAG_BITS_LEFT | 3, false},
2121       {V_ASN1_BIT_STRING, {0xf8}, ASN1_STRING_FLAG_BITS_LEFT | 3, false},
2122       // 6-bit inputs.
2123       {V_ASN1_BIT_STRING, {0x00}, ASN1_STRING_FLAG_BITS_LEFT | 2, false},
2124       {V_ASN1_BIT_STRING, {0xf0}, ASN1_STRING_FLAG_BITS_LEFT | 2, false},
2125       {V_ASN1_BIT_STRING, {0xfc}, ASN1_STRING_FLAG_BITS_LEFT | 2, false},
2126       // 7-bit inputs.
2127       {V_ASN1_BIT_STRING, {0x00}, ASN1_STRING_FLAG_BITS_LEFT | 1, false},
2128       {V_ASN1_BIT_STRING, {0xf0}, ASN1_STRING_FLAG_BITS_LEFT | 1, false},
2129       {V_ASN1_BIT_STRING, {0xfe}, ASN1_STRING_FLAG_BITS_LEFT | 1, false},
2130 
2131       // 8-bit inputs.
2132       {V_ASN1_BIT_STRING, {0x00}, ASN1_STRING_FLAG_BITS_LEFT | 0, false},
2133       {V_ASN1_OCTET_STRING, {0x00}, 0, false},
2134       {V_ASN1_UTF8STRING, {0x00}, 0, false},
2135 
2136       {V_ASN1_BIT_STRING, {0x80}, ASN1_STRING_FLAG_BITS_LEFT | 0, false},
2137       {V_ASN1_OCTET_STRING, {0x80}, 0, false},
2138       {V_ASN1_UTF8STRING, {0x80}, 0, false},
2139 
2140       {V_ASN1_BIT_STRING, {0xff}, ASN1_STRING_FLAG_BITS_LEFT | 0, false},
2141       {V_ASN1_BIT_STRING, {0xff}, 0, true},  // No trailing zeros to drop.
2142       {V_ASN1_OCTET_STRING, {0xff}, 0, false},
2143       {V_ASN1_UTF8STRING, {0xff}, 0, false},
2144 
2145       // Bytes are compared lexicographically.
2146       {V_ASN1_BIT_STRING, {0x00, 0x00}, ASN1_STRING_FLAG_BITS_LEFT | 0, false},
2147       {V_ASN1_OCTET_STRING, {0x00, 0x00}, 0, false},
2148       {V_ASN1_UTF8STRING, {0x00, 0x00}, 0, false},
2149 
2150       {V_ASN1_BIT_STRING, {0x00, 0xff}, ASN1_STRING_FLAG_BITS_LEFT | 0, false},
2151       {V_ASN1_OCTET_STRING, {0x00, 0xff}, 0, false},
2152       {V_ASN1_UTF8STRING, {0x00, 0xff}, 0, false},
2153 
2154       {V_ASN1_BIT_STRING, {0xff, 0x00}, ASN1_STRING_FLAG_BITS_LEFT | 0, false},
2155       {V_ASN1_OCTET_STRING, {0xff, 0x00}, 0, false},
2156       {V_ASN1_UTF8STRING, {0xff, 0x00}, 0, false},
2157   };
2158   std::vector<bssl::UniquePtr<ASN1_STRING>> strs;
2159   strs.reserve(OPENSSL_ARRAY_SIZE(kInputs));
2160   for (const auto &input : kInputs) {
2161     strs.emplace_back(ASN1_STRING_type_new(input.type));
2162     ASSERT_TRUE(strs.back());
2163     ASSERT_TRUE(ASN1_STRING_set(strs.back().get(), input.data.data(),
2164                                 input.data.size()));
2165     strs.back()->flags = input.flags;
2166   }
2167 
2168   for (size_t i = 0; i < strs.size(); i++) {
2169     SCOPED_TRACE(i);
2170     bool expect_equal = true;
2171     for (size_t j = i; j < strs.size(); j++) {
2172       SCOPED_TRACE(j);
2173       if (j > i && !kInputs[j].equals_previous) {
2174         expect_equal = false;
2175       }
2176 
2177       const int cmp_i_j = ASN1_STRING_cmp(strs[i].get(), strs[j].get());
2178       const int cmp_j_i = ASN1_STRING_cmp(strs[j].get(), strs[i].get());
2179       if (expect_equal) {
2180         EXPECT_EQ(cmp_i_j, 0);
2181         EXPECT_EQ(cmp_j_i, 0);
2182       } else if (i < j) {
2183         EXPECT_LT(cmp_i_j, 0);
2184         EXPECT_GT(cmp_j_i, 0);
2185       } else {
2186         EXPECT_GT(cmp_i_j, 0);
2187         EXPECT_LT(cmp_j_i, 0);
2188       }
2189     }
2190   }
2191 }
2192 
TEST(ASN1Test,PrintASN1Object)2193 TEST(ASN1Test, PrintASN1Object) {
2194   const struct {
2195     std::vector<uint8_t> in;
2196     const char *expected;
2197   } kDataTests[] = {
2198       // Known OIDs print as the name.
2199       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01}, "rsaEncryption"},
2200 
2201       // Unknown OIDs print in decimal.
2202       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x00},
2203        "1.2.840.113554.4.1.72585.0"},
2204 
2205       // Inputs which cannot be parsed as OIDs print as "<INVALID>".
2206       {{0xff}, "<INVALID>"},
2207 
2208       // The function has an internal 80-byte buffer. Test inputs at that
2209       // boundary. First, 78 characters.
2210       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7,
2211         0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2212         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2213         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
2214        "1.2.840.113554.4.1.72585.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0."
2215        "0.0.0.1"},
2216       // 79 characters.
2217       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7,
2218         0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2219         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2220         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a},
2221        "1.2.840.113554.4.1.72585.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0."
2222        "0.0.0.10"},
2223       // 80 characters.
2224       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7,
2225         0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2226         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2227         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64},
2228        "1.2.840.113554.4.1.72585.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0."
2229        "0.0.0.100"},
2230       // 81 characters.
2231       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7,
2232         0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2233         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2234         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87, 0x68},
2235        "1.2.840.113554.4.1.72585.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0."
2236        "0.0.0.1000"},
2237       // 82 characters.
2238       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7,
2239         0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2240         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2241         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xce, 0x10},
2242        "1.2.840.113554.4.1.72585.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0."
2243        "0.0.0.10000"},
2244   };
2245   for (const auto &t : kDataTests) {
2246     SCOPED_TRACE(Bytes(t.in));
2247     bssl::UniquePtr<ASN1_OBJECT> obj(ASN1_OBJECT_create(
2248         NID_undef, t.in.data(), t.in.size(), /*sn=*/nullptr, /*ln=*/nullptr));
2249     ASSERT_TRUE(obj);
2250     bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
2251     ASSERT_TRUE(bio);
2252 
2253     int len = i2a_ASN1_OBJECT(bio.get(), obj.get());
2254     EXPECT_EQ(len, static_cast<int>(strlen(t.expected)));
2255 
2256     const uint8_t *bio_data;
2257     size_t bio_len;
2258     BIO_mem_contents(bio.get(), &bio_data, &bio_len);
2259     EXPECT_EQ(t.expected,
2260               std::string(reinterpret_cast<const char *>(bio_data), bio_len));
2261   }
2262 
2263   // Test writing NULL.
2264   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
2265   ASSERT_TRUE(bio);
2266   int len = i2a_ASN1_OBJECT(bio.get(), nullptr);
2267   EXPECT_EQ(len, 4);
2268   const uint8_t *bio_data;
2269   size_t bio_len;
2270   BIO_mem_contents(bio.get(), &bio_data, &bio_len);
2271   EXPECT_EQ("NULL",
2272             std::string(reinterpret_cast<const char *>(bio_data), bio_len));
2273 }
2274 
TEST(ASN1Test,GetObject)2275 TEST(ASN1Test, GetObject) {
2276   // The header is valid, but there are not enough bytes for the length.
2277   static const uint8_t kTruncated[] = {0x30, 0x01};
2278   const uint8_t *ptr = kTruncated;
2279   long length;
2280   int tag;
2281   int tag_class;
2282   EXPECT_EQ(0x80, ASN1_get_object(&ptr, &length, &tag, &tag_class,
2283                                   sizeof(kTruncated)));
2284 
2285   // Indefinite-length encoding is not allowed in DER.
2286   static const uint8_t kIndefinite[] = {0x30, 0x80, 0x00, 0x00};
2287   ptr = kIndefinite;
2288   EXPECT_EQ(0x80, ASN1_get_object(&ptr, &length, &tag, &tag_class,
2289                                   sizeof(kIndefinite)));
2290 
2291   // DER requires lengths be minimally-encoded. This should be {0x30, 0x00}.
2292   static const uint8_t kNonMinimal[] = {0x30, 0x81, 0x00};
2293   ptr = kNonMinimal;
2294   EXPECT_EQ(0x80, ASN1_get_object(&ptr, &length, &tag, &tag_class,
2295                                   sizeof(kNonMinimal)));
2296 
2297   // This should be {0x04, 0x81, 0x80, ...}.
2298   std::vector<uint8_t> non_minimal = {0x04, 0x82, 0x00, 0x80};
2299   non_minimal.resize(non_minimal.size() + 0x80);
2300   ptr = non_minimal.data();
2301   EXPECT_EQ(0x80, ASN1_get_object(&ptr, &length, &tag, &tag_class,
2302                                   non_minimal.size()));
2303 }
2304 
2305 template <typename T>
ExpectNoParse(T * (* d2i)(T **,const uint8_t **,long),const std::vector<uint8_t> & in)2306 void ExpectNoParse(T *(*d2i)(T **, const uint8_t **, long),
2307                    const std::vector<uint8_t> &in) {
2308   SCOPED_TRACE(Bytes(in));
2309   const uint8_t *ptr = in.data();
2310   bssl::UniquePtr<T> obj(d2i(nullptr, &ptr, in.size()));
2311   EXPECT_FALSE(obj);
2312 }
2313 
2314 // The zero tag, constructed or primitive, is reserved and should rejected by
2315 // the parser.
TEST(ASN1Test,ZeroTag)2316 TEST(ASN1Test, ZeroTag) {
2317   ExpectNoParse(d2i_ASN1_TYPE, {0x00, 0x00});
2318   ExpectNoParse(d2i_ASN1_TYPE, {0x00, 0x10, 0x00});
2319   ExpectNoParse(d2i_ASN1_TYPE, {0x20, 0x00});
2320   ExpectNoParse(d2i_ASN1_TYPE, {0x20, 0x00});
2321   ExpectNoParse(d2i_ASN1_SEQUENCE_ANY, {0x30, 0x02, 0x00, 0x00});
2322   ExpectNoParse(d2i_ASN1_SET_ANY, {0x31, 0x02, 0x00, 0x00});
2323   // SEQUENCE {
2324   //   OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.1 }
2325   //   [UNIVERSAL 0 PRIMITIVE] {}
2326   // }
2327   ExpectNoParse(d2i_X509_ALGOR,
2328                 {0x30, 0x10, 0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12,
2329                  0x04, 0x01, 0x84, 0xb7, 0x09, 0x01, 0x00, 0x00});
2330   // SEQUENCE {
2331   //   OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.1 }
2332   //   [UNIVERSAL 0 CONSTRUCTED] {}
2333   // }
2334   ExpectNoParse(d2i_X509_ALGOR,
2335                 {0x30, 0x10, 0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12,
2336                  0x04, 0x01, 0x84, 0xb7, 0x09, 0x01, 0x20, 0x00});
2337   // SEQUENCE {
2338   //   OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.1 }
2339   //   [UNIVERSAL 0 PRIMITIVE] { "a" }
2340   // }
2341   ExpectNoParse(d2i_X509_ALGOR,
2342                 {0x30, 0x11, 0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12,
2343                  0x04, 0x01, 0x84, 0xb7, 0x09, 0x01, 0x00, 0x01, 0x61});
2344 }
2345 
TEST(ASN1Test,StringEncoding)2346 TEST(ASN1Test, StringEncoding) {
2347   const struct {
2348     ASN1_STRING *(*d2i)(ASN1_STRING **out, const uint8_t **inp, long len);
2349     std::vector<uint8_t> in;
2350     bool valid;
2351   } kTests[] = {
2352       // All OCTET STRINGs are valid.
2353       {d2i_ASN1_OCTET_STRING, {0x04, 0x00}, true},
2354       {d2i_ASN1_OCTET_STRING, {0x04, 0x01, 0x00}, true},
2355 
2356       // UTF8String must be valid UTF-8.
2357       {d2i_ASN1_UTF8STRING, {0x0c, 0x00}, true},
2358       {d2i_ASN1_UTF8STRING, {0x0c, 0x01, 'a'}, true},
2359       {d2i_ASN1_UTF8STRING, {0x0c, 0x03, 0xe2, 0x98, 0x83}, true},
2360       // Non-minimal, two-byte UTF-8.
2361       {d2i_ASN1_UTF8STRING, {0x0c, 0x02, 0xc0, 0x81}, false},
2362       // Truncated, four-byte UTF-8.
2363       {d2i_ASN1_UTF8STRING, {0x0c, 0x03, 0xf0, 0x80, 0x80}, false},
2364       // Low-surrogate value.
2365       {d2i_ASN1_UTF8STRING, {0x0c, 0x03, 0xed, 0xa0, 0x80}, false},
2366       // High-surrogate value.
2367       {d2i_ASN1_UTF8STRING, {0x0c, 0x03, 0xed, 0xb0, 0x81}, false},
2368 
2369       // BMPString must be valid UCS-2.
2370       {d2i_ASN1_BMPSTRING, {0x1e, 0x00}, true},
2371       {d2i_ASN1_BMPSTRING, {0x1e, 0x02, 0x00, 'a'}, true},
2372       // Truncated code unit.
2373       {d2i_ASN1_BMPSTRING, {0x1e, 0x01, 'a'}, false},
2374       // Lone surrogate.
2375       {d2i_ASN1_BMPSTRING, {0x1e, 0x02, 0xd8, 0}, false},
2376       // BMPString is UCS-2, not UTF-16, so surrogate pairs are also invalid.
2377       {d2i_ASN1_BMPSTRING, {0x1e, 0x04, 0xd8, 0, 0xdc, 1}, false},
2378 
2379       // UniversalString must be valid UTF-32.
2380       {d2i_ASN1_UNIVERSALSTRING, {0x1c, 0x00}, true},
2381       {d2i_ASN1_UNIVERSALSTRING, {0x1c, 0x04, 0x00, 0x00, 0x00, 'a'}, true},
2382       // Maximum code point.
2383       {d2i_ASN1_UNIVERSALSTRING, {0x1c, 0x04, 0x00, 0x10, 0xff, 0xfd}, true},
2384       // Reserved.
2385       {d2i_ASN1_UNIVERSALSTRING, {0x1c, 0x04, 0x00, 0x10, 0xff, 0xfe}, false},
2386       {d2i_ASN1_UNIVERSALSTRING, {0x1c, 0x04, 0x00, 0x10, 0xff, 0xff}, false},
2387       // Too high.
2388       {d2i_ASN1_UNIVERSALSTRING, {0x1c, 0x04, 0x00, 0x11, 0x00, 0x00}, false},
2389       // Surrogates are not characters.
2390       {d2i_ASN1_UNIVERSALSTRING, {0x1c, 0x04, 0x00, 0x00, 0xd8, 0}, false},
2391       // Truncated codepoint.
2392       {d2i_ASN1_UNIVERSALSTRING, {0x1c, 0x03, 0x00, 0x00, 0x00}, false},
2393 
2394       // We interpret T61String as Latin-1, so all inputs are valid.
2395       {d2i_ASN1_T61STRING, {0x14, 0x00}, true},
2396       {d2i_ASN1_T61STRING, {0x14, 0x01, 0x00}, true},
2397   };
2398   for (const auto& t : kTests) {
2399     SCOPED_TRACE(Bytes(t.in));
2400     const uint8_t *inp;
2401 
2402     if (t.d2i != nullptr) {
2403       inp = t.in.data();
2404       bssl::UniquePtr<ASN1_STRING> str(t.d2i(nullptr, &inp, t.in.size()));
2405       EXPECT_EQ(t.valid, str != nullptr);
2406     }
2407 
2408     // Also test with the ANY parser.
2409     inp = t.in.data();
2410     bssl::UniquePtr<ASN1_TYPE> any(d2i_ASN1_TYPE(nullptr, &inp, t.in.size()));
2411     EXPECT_EQ(t.valid, any != nullptr);
2412   }
2413 }
2414 
2415 // Exhaustively test POSIX time conversions for every day across the millenium.
TEST(ASN1Test,POSIXTime)2416 TEST(ASN1Test, POSIXTime) {
2417   const int kDaysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
2418 
2419   // Test the epoch explicitly, to confirm our baseline is correct.
2420   struct tm civil_time;
2421   ASSERT_TRUE(OPENSSL_posix_to_tm(0, &civil_time));
2422   ASSERT_EQ(civil_time.tm_year + 1900, 1970);
2423   ASSERT_EQ(civil_time.tm_mon + 1, 1);
2424   ASSERT_EQ(civil_time.tm_mday, 1);
2425   ASSERT_EQ(civil_time.tm_hour, 0);
2426   ASSERT_EQ(civil_time.tm_min, 0);
2427   ASSERT_EQ(civil_time.tm_sec, 0);
2428 
2429   int64_t posix_time = -11676096000;  // Sat, 01 Jan 1600 00:00:00 +0000
2430   for (int year = 1600; year < 3000; year++) {
2431     SCOPED_TRACE(year);
2432     bool is_leap_year = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
2433     for (int month = 1; month <= 12; month++) {
2434       SCOPED_TRACE(month);
2435       int days = kDaysInMonth[month - 1];
2436       if (month == 2 && is_leap_year) {
2437         days++;
2438       }
2439       for (int day = 1; day <= days; day++) {
2440         SCOPED_TRACE(day);
2441         SCOPED_TRACE(posix_time);
2442 
2443         ASSERT_TRUE(OPENSSL_posix_to_tm(posix_time, &civil_time));
2444         ASSERT_EQ(civil_time.tm_year + 1900, year);
2445         ASSERT_EQ(civil_time.tm_mon + 1, month);
2446         ASSERT_EQ(civil_time.tm_mday, day);
2447         ASSERT_EQ(civil_time.tm_hour, 0);
2448         ASSERT_EQ(civil_time.tm_min, 0);
2449         ASSERT_EQ(civil_time.tm_sec, 0);
2450 
2451         int64_t posix_time_computed;
2452         ASSERT_TRUE(OPENSSL_tm_to_posix(&civil_time, &posix_time_computed));
2453         ASSERT_EQ(posix_time_computed, posix_time);
2454 
2455         // Advance to the next day.
2456         posix_time += 24 * 60 * 60;
2457       }
2458     }
2459   }
2460 }
2461 
TEST(ASN1Test,LargeString)2462 TEST(ASN1Test, LargeString) {
2463   bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_type_new(V_ASN1_OCTET_STRING));
2464   ASSERT_TRUE(str);
2465   // Very large strings should be rejected by |ASN1_STRING_set|. Strictly
2466   // speaking, this is an invalid call because the buffer does not have that
2467   // much size available. |ASN1_STRING_set| should cleanly fail before it
2468   // crashes, and actually allocating 512 MiB in a test is likely to break.
2469   char b = 0;
2470   EXPECT_FALSE(ASN1_STRING_set(str.get(), &b, INT_MAX / 4));
2471 
2472 #if defined(OPENSSL_64_BIT)
2473   // |ASN1_STRING_set| should tolerate lengths that exceed |int| without
2474   // overflow.
2475   EXPECT_FALSE(ASN1_STRING_set(str.get(), &b, 1 + (ossl_ssize_t{1} << 48)));
2476 #endif
2477 }
2478 
2479 // The ASN.1 macros do not work on Windows shared library builds, where usage of
2480 // |OPENSSL_EXPORT| is a bit stricter.
2481 #if !defined(OPENSSL_WINDOWS) || !defined(BORINGSSL_SHARED_LIBRARY)
2482 
2483 typedef struct asn1_linked_list_st {
2484   struct asn1_linked_list_st *next;
2485 } ASN1_LINKED_LIST;
2486 
2487 DECLARE_ASN1_ITEM(ASN1_LINKED_LIST)
DECLARE_ASN1_FUNCTIONS(ASN1_LINKED_LIST)2488 DECLARE_ASN1_FUNCTIONS(ASN1_LINKED_LIST)
2489 
2490 ASN1_SEQUENCE(ASN1_LINKED_LIST) = {
2491     ASN1_OPT(ASN1_LINKED_LIST, next, ASN1_LINKED_LIST),
2492 } ASN1_SEQUENCE_END(ASN1_LINKED_LIST)
2493 
2494 IMPLEMENT_ASN1_FUNCTIONS(ASN1_LINKED_LIST)
2495 
2496 static bool MakeLinkedList(bssl::UniquePtr<uint8_t> *out, size_t *out_len,
2497                            size_t count) {
2498   bssl::ScopedCBB cbb;
2499   std::vector<CBB> cbbs(count);
2500   if (!CBB_init(cbb.get(), 2 * count) ||
2501       !CBB_add_asn1(cbb.get(), &cbbs[0], CBS_ASN1_SEQUENCE)) {
2502     return false;
2503   }
2504   for (size_t i = 1; i < count; i++) {
2505     if (!CBB_add_asn1(&cbbs[i - 1], &cbbs[i], CBS_ASN1_SEQUENCE)) {
2506       return false;
2507     }
2508   }
2509   uint8_t *ptr;
2510   if (!CBB_finish(cbb.get(), &ptr, out_len)) {
2511     return false;
2512   }
2513   out->reset(ptr);
2514   return true;
2515 }
2516 
TEST(ASN1Test,Recursive)2517 TEST(ASN1Test, Recursive) {
2518   bssl::UniquePtr<uint8_t> data;
2519   size_t len;
2520 
2521   // Sanity-check that MakeLinkedList can be parsed.
2522   ASSERT_TRUE(MakeLinkedList(&data, &len, 5));
2523   const uint8_t *ptr = data.get();
2524   ASN1_LINKED_LIST *list = d2i_ASN1_LINKED_LIST(nullptr, &ptr, len);
2525   EXPECT_TRUE(list);
2526   ASN1_LINKED_LIST_free(list);
2527 
2528   // Excessively deep structures are rejected.
2529   ASSERT_TRUE(MakeLinkedList(&data, &len, 100));
2530   ptr = data.get();
2531   list = d2i_ASN1_LINKED_LIST(nullptr, &ptr, len);
2532   EXPECT_FALSE(list);
2533   // Note checking the error queue here does not work. The error "stack trace"
2534   // is too deep, so the |ASN1_R_NESTED_TOO_DEEP| entry drops off the queue.
2535   ASN1_LINKED_LIST_free(list);
2536 }
2537 
2538 struct IMPLICIT_CHOICE {
2539   ASN1_STRING *string;
2540 };
2541 
2542 DECLARE_ASN1_FUNCTIONS(IMPLICIT_CHOICE)
2543 
ASN1_SEQUENCE(IMPLICIT_CHOICE)2544 ASN1_SEQUENCE(IMPLICIT_CHOICE) = {
2545     ASN1_IMP(IMPLICIT_CHOICE, string, DIRECTORYSTRING, 0),
2546 } ASN1_SEQUENCE_END(IMPLICIT_CHOICE)
2547 
2548 IMPLEMENT_ASN1_FUNCTIONS(IMPLICIT_CHOICE)
2549 
2550 // Test that the ASN.1 templates reject types with implicitly-tagged CHOICE
2551 // types.
2552 TEST(ASN1Test, ImplicitChoice) {
2553   // Serializing a type with an implicitly tagged CHOICE should fail.
2554   std::unique_ptr<IMPLICIT_CHOICE, decltype(&IMPLICIT_CHOICE_free)> obj(
2555       IMPLICIT_CHOICE_new(), IMPLICIT_CHOICE_free);
2556   EXPECT_EQ(-1, i2d_IMPLICIT_CHOICE(obj.get(), nullptr));
2557 
2558   // An implicitly-tagged CHOICE is an error. Depending on the implementation,
2559   // it may be misinterpreted as without the tag, or as clobbering the CHOICE
2560   // tag. Test both inputs and ensure they fail.
2561 
2562   // SEQUENCE { UTF8String {} }
2563   static const uint8_t kInput1[] = {0x30, 0x02, 0x0c, 0x00};
2564   const uint8_t *ptr = kInput1;
2565   EXPECT_EQ(nullptr, d2i_IMPLICIT_CHOICE(nullptr, &ptr, sizeof(kInput1)));
2566 
2567   // SEQUENCE { [0 PRIMITIVE] {} }
2568   static const uint8_t kInput2[] = {0x30, 0x02, 0x80, 0x00};
2569   ptr = kInput2;
2570   EXPECT_EQ(nullptr, d2i_IMPLICIT_CHOICE(nullptr, &ptr, sizeof(kInput2)));
2571 }
2572 
2573 struct REQUIRED_FIELD {
2574   ASN1_INTEGER *value;
2575   ASN1_INTEGER *value_imp;
2576   ASN1_INTEGER *value_exp;
2577   STACK_OF(ASN1_INTEGER) *seq;
2578   STACK_OF(ASN1_INTEGER) *seq_imp;
2579   STACK_OF(ASN1_INTEGER) *seq_exp;
2580   ASN1_NULL *null;
2581   ASN1_NULL *null_imp;
2582   ASN1_NULL *null_exp;
2583 };
2584 
2585 DECLARE_ASN1_FUNCTIONS(REQUIRED_FIELD)
ASN1_SEQUENCE(REQUIRED_FIELD)2586 ASN1_SEQUENCE(REQUIRED_FIELD) = {
2587     ASN1_SIMPLE(REQUIRED_FIELD, value, ASN1_INTEGER),
2588     ASN1_IMP(REQUIRED_FIELD, value_imp, ASN1_INTEGER, 0),
2589     ASN1_EXP(REQUIRED_FIELD, value_exp, ASN1_INTEGER, 1),
2590     ASN1_SEQUENCE_OF(REQUIRED_FIELD, seq, ASN1_INTEGER),
2591     ASN1_IMP_SEQUENCE_OF(REQUIRED_FIELD, seq_imp, ASN1_INTEGER, 2),
2592     ASN1_EXP_SEQUENCE_OF(REQUIRED_FIELD, seq_exp, ASN1_INTEGER, 3),
2593     ASN1_SIMPLE(REQUIRED_FIELD, null, ASN1_NULL),
2594     ASN1_IMP(REQUIRED_FIELD, null_imp, ASN1_NULL, 4),
2595     ASN1_EXP(REQUIRED_FIELD, null_exp, ASN1_NULL, 5),
2596 } ASN1_SEQUENCE_END(REQUIRED_FIELD)
2597 IMPLEMENT_ASN1_FUNCTIONS(REQUIRED_FIELD)
2598 
2599 // Test that structures with missing required fields cannot be serialized. Test
2600 // the full combination of tagging and SEQUENCE OF.
2601 TEST(ASN1Test, MissingRequiredField) {
2602   EXPECT_EQ(-1, i2d_REQUIRED_FIELD(nullptr, nullptr));
2603 
2604   std::unique_ptr<REQUIRED_FIELD, decltype(&REQUIRED_FIELD_free)> obj(
2605       nullptr, REQUIRED_FIELD_free);
2606   for (auto field : {&REQUIRED_FIELD::value, &REQUIRED_FIELD::value_imp,
2607                      &REQUIRED_FIELD::value_exp}) {
2608     obj.reset(REQUIRED_FIELD_new());
2609     ASSERT_TRUE(obj);
2610     ASN1_INTEGER_free((*obj).*field);
2611     (*obj).*field = nullptr;
2612     EXPECT_EQ(-1, i2d_REQUIRED_FIELD(obj.get(), nullptr));
2613   }
2614 
2615   for (auto field : {&REQUIRED_FIELD::seq, &REQUIRED_FIELD::seq_imp,
2616                      &REQUIRED_FIELD::seq_exp}) {
2617     obj.reset(REQUIRED_FIELD_new());
2618     ASSERT_TRUE(obj);
2619     sk_ASN1_INTEGER_pop_free((*obj).*field, ASN1_INTEGER_free);
2620     (*obj).*field = nullptr;
2621     EXPECT_EQ(-1, i2d_REQUIRED_FIELD(obj.get(), nullptr));
2622   }
2623 
2624   for (auto field : {&REQUIRED_FIELD::null, &REQUIRED_FIELD::null_imp,
2625                      &REQUIRED_FIELD::null_exp}) {
2626     obj.reset(REQUIRED_FIELD_new());
2627     ASSERT_TRUE(obj);
2628     (*obj).*field = nullptr;
2629     EXPECT_EQ(-1, i2d_REQUIRED_FIELD(obj.get(), nullptr));
2630   }
2631 }
2632 
2633 struct BOOLEANS {
2634   ASN1_BOOLEAN required;
2635   ASN1_BOOLEAN optional;
2636   ASN1_BOOLEAN default_true;
2637   ASN1_BOOLEAN default_false;
2638 };
2639 
2640 DECLARE_ASN1_FUNCTIONS(BOOLEANS)
ASN1_SEQUENCE(BOOLEANS)2641 ASN1_SEQUENCE(BOOLEANS) = {
2642     ASN1_SIMPLE(BOOLEANS, required, ASN1_BOOLEAN),
2643     ASN1_IMP_OPT(BOOLEANS, optional, ASN1_BOOLEAN, 1),
2644     // Although not actually optional, |ASN1_TBOOLEAN| and |ASN1_FBOOLEAN| need
2645     // to be marked optional in the template.
2646     ASN1_IMP_OPT(BOOLEANS, default_true, ASN1_TBOOLEAN, 2),
2647     ASN1_IMP_OPT(BOOLEANS, default_false, ASN1_FBOOLEAN, 3),
2648 } ASN1_SEQUENCE_END(BOOLEANS)
2649 IMPLEMENT_ASN1_FUNCTIONS(BOOLEANS)
2650 
2651 TEST(ASN1Test, OptionalAndDefaultBooleans) {
2652   std::unique_ptr<BOOLEANS, decltype(&BOOLEANS_free)> obj(nullptr,
2653                                                           BOOLEANS_free);
2654 
2655   // A default-constructed object should use, respectively, omitted, omitted,
2656   // TRUE, FALSE.
2657   //
2658   // TODO(davidben): Is the first one a bug? It seems more consistent for a
2659   // required BOOLEAN default to FALSE. |FOO_new| typically default-initializes
2660   // fields valid states. (Though there are exceptions. CHOICE, ANY, and OBJECT
2661   // IDENTIFIER are default-initialized to something invalid.)
2662   obj.reset(BOOLEANS_new());
2663   ASSERT_TRUE(obj);
2664   EXPECT_EQ(obj->required, ASN1_BOOLEAN_NONE);
2665   EXPECT_EQ(obj->optional, ASN1_BOOLEAN_NONE);
2666   EXPECT_EQ(obj->default_true, ASN1_BOOLEAN_TRUE);
2667   EXPECT_EQ(obj->default_false, ASN1_BOOLEAN_FALSE);
2668 
2669   // Trying to serialize this should fail, because |obj->required| is omitted.
2670   EXPECT_EQ(-1, i2d_BOOLEANS(obj.get(), nullptr));
2671 
2672   // Otherwise, this object is serializable. Most fields are omitted, due to
2673   // them being optional or defaulted.
2674   static const uint8_t kFieldsOmitted[] = {0x30, 0x03, 0x01, 0x01, 0x00};
2675   obj->required = 0;
2676   TestSerialize(obj.get(), i2d_BOOLEANS, kFieldsOmitted);
2677 
2678   const uint8_t *der = kFieldsOmitted;
2679   obj.reset(d2i_BOOLEANS(nullptr, &der, sizeof(kFieldsOmitted)));
2680   ASSERT_TRUE(obj);
2681   EXPECT_EQ(obj->required, ASN1_BOOLEAN_FALSE);
2682   EXPECT_EQ(obj->optional, ASN1_BOOLEAN_NONE);
2683   EXPECT_EQ(obj->default_true, ASN1_BOOLEAN_TRUE);
2684   EXPECT_EQ(obj->default_false, ASN1_BOOLEAN_FALSE);
2685 
2686   // Include the optinonal fields instead.
2687   static const uint8_t kFieldsIncluded[] = {0x30, 0x0c, 0x01, 0x01, 0xff,
2688                                             0x81, 0x01, 0x00, 0x82, 0x01,
2689                                             0x00, 0x83, 0x01, 0xff};
2690   obj->required = ASN1_BOOLEAN_TRUE;
2691   obj->optional = ASN1_BOOLEAN_FALSE;
2692   obj->default_true = ASN1_BOOLEAN_FALSE;
2693   obj->default_false = ASN1_BOOLEAN_TRUE;
2694   TestSerialize(obj.get(), i2d_BOOLEANS, kFieldsIncluded);
2695 
2696   der = kFieldsIncluded;
2697   obj.reset(d2i_BOOLEANS(nullptr, &der, sizeof(kFieldsIncluded)));
2698   ASSERT_TRUE(obj);
2699   EXPECT_EQ(obj->required, ASN1_BOOLEAN_TRUE);
2700   EXPECT_EQ(obj->optional, ASN1_BOOLEAN_FALSE);
2701   EXPECT_EQ(obj->default_true, ASN1_BOOLEAN_FALSE);
2702   EXPECT_EQ(obj->default_false, ASN1_BOOLEAN_TRUE);
2703 
2704   // TODO(https://crbug.com/boringssl/354): Reject explicit DEFAULTs.
2705 }
2706 
2707 // EXPLICIT_BOOLEAN is a [1] EXPLICIT BOOLEAN.
2708 ASN1_ITEM_TEMPLATE(EXPLICIT_BOOLEAN) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_EXPLICIT,
2709                                                              1,
2710                                                              EXPLICIT_BOOLEAN,
2711                                                              ASN1_BOOLEAN)
2712 ASN1_ITEM_TEMPLATE_END(EXPLICIT_BOOLEAN)
2713 
2714 // EXPLICIT_OCTET_STRING is a [2] EXPLICIT OCTET STRING.
2715 ASN1_ITEM_TEMPLATE(EXPLICIT_OCTET_STRING) = ASN1_EX_TEMPLATE_TYPE(
2716     ASN1_TFLG_EXPLICIT, 2, EXPLICIT_OCTET_STRING, ASN1_OCTET_STRING)
2717 ASN1_ITEM_TEMPLATE_END(EXPLICIT_OCTET_STRING)
2718 
2719 // DOUBLY_TAGGED is
2720 //   SEQUENCE {
2721 //     b   [3] EXPLICIT [1] EXPLICIT BOOLEAN OPTIONAL,
2722 //     oct [4] EXPLICIT [2] EXPLICIT OCTET STRING OPTIONAL }
2723 // with explicit tagging.
2724 struct DOUBLY_TAGGED {
2725   ASN1_BOOLEAN b;
2726   ASN1_OCTET_STRING *oct;
2727 };
2728 
2729 DECLARE_ASN1_FUNCTIONS(DOUBLY_TAGGED)
ASN1_SEQUENCE(DOUBLY_TAGGED)2730 ASN1_SEQUENCE(DOUBLY_TAGGED) = {
2731     ASN1_EXP_OPT(DOUBLY_TAGGED, b, EXPLICIT_BOOLEAN, 3),
2732     ASN1_EXP_OPT(DOUBLY_TAGGED, oct, EXPLICIT_OCTET_STRING, 4),
2733 } ASN1_SEQUENCE_END(DOUBLY_TAGGED)
2734 IMPLEMENT_ASN1_FUNCTIONS(DOUBLY_TAGGED)
2735 
2736 // Test that optional fields with two layers of explicit tagging are correctly
2737 // handled.
2738 TEST(ASN1Test, DoublyTagged) {
2739   std::unique_ptr<DOUBLY_TAGGED, decltype(&DOUBLY_TAGGED_free)> obj(
2740       nullptr, DOUBLY_TAGGED_free);
2741 
2742   // Both fields missing.
2743   static const uint8_t kOmitted[] = {0x30, 0x00};
2744   const uint8_t *inp = kOmitted;
2745   obj.reset(d2i_DOUBLY_TAGGED(nullptr, &inp, sizeof(kOmitted)));
2746   ASSERT_TRUE(obj);
2747   EXPECT_EQ(obj->b, -1);
2748   EXPECT_FALSE(obj->oct);
2749   TestSerialize(obj.get(), i2d_DOUBLY_TAGGED, kOmitted);
2750 
2751   // Both fields present, true and the empty string.
2752   static const uint8_t kTrueEmpty[] = {0x30, 0x0d, 0xa3, 0x05, 0xa1,
2753                                        0x03, 0x01, 0x01, 0xff, 0xa4,
2754                                        0x04, 0xa2, 0x02, 0x04, 0x00};
2755   inp = kTrueEmpty;
2756   obj.reset(d2i_DOUBLY_TAGGED(nullptr, &inp, sizeof(kTrueEmpty)));
2757   ASSERT_TRUE(obj);
2758   EXPECT_EQ(obj->b, 0xff);
2759   ASSERT_TRUE(obj->oct);
2760   EXPECT_EQ(ASN1_STRING_length(obj->oct), 0);
2761   TestSerialize(obj.get(), i2d_DOUBLY_TAGGED, kTrueEmpty);
2762 }
2763 
2764 #define CHOICE_TYPE_OCT 0
2765 #define CHOICE_TYPE_BOOL 1
2766 
2767 struct CHOICE_TYPE {
2768   int type;
2769   union {
2770     ASN1_OCTET_STRING *oct;
2771     ASN1_BOOLEAN b;
2772   } value;
2773 };
2774 
2775 DECLARE_ASN1_FUNCTIONS(CHOICE_TYPE)
2776 ASN1_CHOICE(CHOICE_TYPE) = {
2777     ASN1_SIMPLE(CHOICE_TYPE, value.oct, ASN1_OCTET_STRING),
2778     ASN1_SIMPLE(CHOICE_TYPE, value.b, ASN1_BOOLEAN),
2779 } ASN1_CHOICE_END(CHOICE_TYPE)
2780 IMPLEMENT_ASN1_FUNCTIONS(CHOICE_TYPE)
2781 
2782 struct OPTIONAL_CHOICE {
2783   CHOICE_TYPE *choice;
2784 };
2785 
2786 DECLARE_ASN1_FUNCTIONS(OPTIONAL_CHOICE)
ASN1_SEQUENCE(OPTIONAL_CHOICE)2787 ASN1_SEQUENCE(OPTIONAL_CHOICE) = {
2788     ASN1_OPT(OPTIONAL_CHOICE, choice, CHOICE_TYPE),
2789 } ASN1_SEQUENCE_END(OPTIONAL_CHOICE)
2790 IMPLEMENT_ASN1_FUNCTIONS(OPTIONAL_CHOICE)
2791 
2792 TEST(ASN1Test, OptionalChoice) {
2793   std::unique_ptr<OPTIONAL_CHOICE, decltype(&OPTIONAL_CHOICE_free)> obj(
2794       nullptr, OPTIONAL_CHOICE_free);
2795 
2796   // Value omitted.
2797   static const uint8_t kOmitted[] = {0x30, 0x00};
2798   const uint8_t *inp = kOmitted;
2799   obj.reset(d2i_OPTIONAL_CHOICE(nullptr, &inp, sizeof(kOmitted)));
2800   ASSERT_TRUE(obj);
2801   EXPECT_FALSE(obj->choice);
2802   TestSerialize(obj.get(), i2d_OPTIONAL_CHOICE, kOmitted);
2803 
2804   // Value is present as an OCTET STRING.
2805   static const uint8_t kOct[] = {0x30, 0x02, 0x04, 0x00};
2806   inp = kOct;
2807   obj.reset(d2i_OPTIONAL_CHOICE(nullptr, &inp, sizeof(kOct)));
2808   ASSERT_TRUE(obj);
2809   ASSERT_TRUE(obj->choice);
2810   ASSERT_EQ(obj->choice->type, CHOICE_TYPE_OCT);
2811   ASSERT_TRUE(obj->choice->value.oct);
2812   EXPECT_EQ(ASN1_STRING_length(obj->choice->value.oct), 0);
2813   TestSerialize(obj.get(), i2d_OPTIONAL_CHOICE, kOct);
2814 
2815   // Value is present as TRUE.
2816   static const uint8_t kTrue[] = {0x30, 0x03, 0x01, 0x01, 0xff};
2817   inp = kTrue;
2818   obj.reset(d2i_OPTIONAL_CHOICE(nullptr, &inp, sizeof(kTrue)));
2819   ASSERT_TRUE(obj);
2820   ASSERT_TRUE(obj->choice);
2821   ASSERT_EQ(obj->choice->type, CHOICE_TYPE_BOOL);
2822   EXPECT_EQ(obj->choice->value.b, ASN1_BOOLEAN_TRUE);
2823   TestSerialize(obj.get(), i2d_OPTIONAL_CHOICE, kTrue);
2824 }
2825 
2826 struct EMBED_X509 {
2827   X509 *x509;
2828   X509 *x509_opt;
2829   STACK_OF(X509) *x509_seq;
2830 };
2831 
2832 DECLARE_ASN1_FUNCTIONS(EMBED_X509)
ASN1_SEQUENCE(EMBED_X509)2833 ASN1_SEQUENCE(EMBED_X509) = {
2834     ASN1_SIMPLE(EMBED_X509, x509, X509),
2835     ASN1_EXP_OPT(EMBED_X509, x509_opt, X509, 0),
2836     ASN1_IMP_SEQUENCE_OF_OPT(EMBED_X509, x509_seq, X509, 1),
2837 } ASN1_SEQUENCE_END(EMBED_X509)
2838 IMPLEMENT_ASN1_FUNCTIONS(EMBED_X509)
2839 
2840 // Test that X.509 types defined in this library can be embedded into other
2841 // types, as we rewrite them away from the templating system.
2842 TEST(ASN1Test, EmbedX509) {
2843   // Set up a test certificate.
2844   static const char kTestCert[] = R"(
2845 -----BEGIN CERTIFICATE-----
2846 MIIBzzCCAXagAwIBAgIJANlMBNpJfb/rMAkGByqGSM49BAEwRTELMAkGA1UEBhMC
2847 QVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdp
2848 dHMgUHR5IEx0ZDAeFw0xNDA0MjMyMzIxNTdaFw0xNDA1MjMyMzIxNTdaMEUxCzAJ
2849 BgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5l
2850 dCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATmK2ni
2851 v2Wfl74vHg2UikzVl2u3qR4NRvvdqakendy6WgHn1peoChj5w8SjHlbifINI2xYa
2852 HPUdfvGULUvPciLBo1AwTjAdBgNVHQ4EFgQUq4TSrKuV8IJOFngHVVdf5CaNgtEw
2853 HwYDVR0jBBgwFoAUq4TSrKuV8IJOFngHVVdf5CaNgtEwDAYDVR0TBAUwAwEB/zAJ
2854 BgcqhkjOPQQBA0gAMEUCIQDyoDVeUTo2w4J5m+4nUIWOcAZ0lVfSKXQA9L4Vh13E
2855 BwIgfB55FGohg/B6dGh5XxSZmmi08cueFV7mHzJSYV51yRQ=
2856 -----END CERTIFICATE-----
2857 )";
2858   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(kTestCert, sizeof(kTestCert)));
2859   ASSERT_TRUE(bio);
2860   bssl::UniquePtr<X509> cert(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
2861   ASSERT_TRUE(cert);
2862   uint8_t *cert_der = nullptr;
2863   int cert_len = i2d_X509(cert.get(), &cert_der);
2864   ASSERT_GT(cert_len, 0);
2865   bssl::UniquePtr<uint8_t> free_cert_der(cert_der);
2866 
2867   std::unique_ptr<EMBED_X509, decltype(&EMBED_X509_free)> obj(nullptr,
2868                                                               EMBED_X509_free);
2869 
2870   // Test only the first field present.
2871   bssl::ScopedCBB cbb;
2872   ASSERT_TRUE(CBB_init(cbb.get(), 64));
2873   CBB seq;
2874   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &seq, CBS_ASN1_SEQUENCE));
2875   ASSERT_TRUE(CBB_add_bytes(&seq, cert_der, cert_len));
2876   ASSERT_TRUE(CBB_flush(cbb.get()));
2877   const uint8_t *ptr = CBB_data(cbb.get());
2878   obj.reset(d2i_EMBED_X509(nullptr, &ptr, CBB_len(cbb.get())));
2879   ASSERT_TRUE(obj);
2880   ASSERT_TRUE(obj->x509);
2881   EXPECT_EQ(X509_cmp(obj->x509, cert.get()), 0);
2882   EXPECT_FALSE(obj->x509_opt);
2883   EXPECT_FALSE(obj->x509_seq);
2884   TestSerialize(obj.get(), i2d_EMBED_X509,
2885                 {CBB_data(cbb.get()), CBB_len(cbb.get())});
2886 
2887   // Test all fields present.
2888   cbb.Reset();
2889   ASSERT_TRUE(CBB_init(cbb.get(), 64));
2890   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &seq, CBS_ASN1_SEQUENCE));
2891   ASSERT_TRUE(CBB_add_bytes(&seq, cert_der, cert_len));
2892   CBB child;
2893   ASSERT_TRUE(CBB_add_asn1(
2894       &seq, &child, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
2895   ASSERT_TRUE(CBB_add_bytes(&child, cert_der, cert_len));
2896   ASSERT_TRUE(CBB_add_asn1(
2897       &seq, &child, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1));
2898   ASSERT_TRUE(CBB_add_bytes(&child, cert_der, cert_len));
2899   ASSERT_TRUE(CBB_add_bytes(&child, cert_der, cert_len));
2900   ASSERT_TRUE(CBB_flush(cbb.get()));
2901   ptr = CBB_data(cbb.get());
2902   obj.reset(d2i_EMBED_X509(nullptr, &ptr, CBB_len(cbb.get())));
2903   ASSERT_TRUE(obj);
2904   ASSERT_TRUE(obj->x509);
2905   EXPECT_EQ(X509_cmp(obj->x509, cert.get()), 0);
2906   ASSERT_TRUE(obj->x509_opt);
2907   EXPECT_EQ(X509_cmp(obj->x509_opt, cert.get()), 0);
2908   ASSERT_EQ(sk_X509_num(obj->x509_seq), 2u);
2909   EXPECT_EQ(X509_cmp(sk_X509_value(obj->x509_seq, 0), cert.get()), 0);
2910   EXPECT_EQ(X509_cmp(sk_X509_value(obj->x509_seq, 1), cert.get()), 0);
2911   TestSerialize(obj.get(), i2d_EMBED_X509,
2912                 {CBB_data(cbb.get()), CBB_len(cbb.get())});
2913 }
2914 
2915 #endif  // !WINDOWS || !SHARED_LIBRARY
2916