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