• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2016, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <limits.h>
16 #include <stdio.h>
17 
18 #include <string>
19 #include <vector>
20 
21 #include <gtest/gtest.h>
22 
23 #include <openssl/asn1.h>
24 #include <openssl/asn1t.h>
25 #include <openssl/bytestring.h>
26 #include <openssl/err.h>
27 #include <openssl/mem.h>
28 #include <openssl/obj.h>
29 #include <openssl/span.h>
30 #include <openssl/x509v3.h>
31 
32 #include "../test/test_util.h"
33 
34 
35 // kTag128 is an ASN.1 structure with a universal tag with number 128.
36 static const uint8_t kTag128[] = {
37     0x1f, 0x81, 0x00, 0x01, 0x00,
38 };
39 
40 // kTag258 is an ASN.1 structure with a universal tag with number 258.
41 static const uint8_t kTag258[] = {
42     0x1f, 0x82, 0x02, 0x01, 0x00,
43 };
44 
45 static_assert(V_ASN1_NEG_INTEGER == 258,
46               "V_ASN1_NEG_INTEGER changed. Update kTag258 to collide with it.");
47 
48 // kTagOverflow is an ASN.1 structure with a universal tag with number 2^35-1,
49 // which will not fit in an int.
50 static const uint8_t kTagOverflow[] = {
51     0x1f, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01, 0x00,
52 };
53 
TEST(ASN1Test,LargeTags)54 TEST(ASN1Test, LargeTags) {
55   const uint8_t *p = kTag258;
56   bssl::UniquePtr<ASN1_TYPE> obj(d2i_ASN1_TYPE(NULL, &p, sizeof(kTag258)));
57   EXPECT_FALSE(obj) << "Parsed value with illegal tag" << obj->type;
58   ERR_clear_error();
59 
60   p = kTagOverflow;
61   obj.reset(d2i_ASN1_TYPE(NULL, &p, sizeof(kTagOverflow)));
62   EXPECT_FALSE(obj) << "Parsed value with tag overflow" << obj->type;
63   ERR_clear_error();
64 
65   p = kTag128;
66   obj.reset(d2i_ASN1_TYPE(NULL, &p, sizeof(kTag128)));
67   ASSERT_TRUE(obj);
68   EXPECT_EQ(128, obj->type);
69   const uint8_t kZero = 0;
70   EXPECT_EQ(Bytes(&kZero, 1), Bytes(obj->value.asn1_string->data,
71                                     obj->value.asn1_string->length));
72 }
73 
TEST(ASN1Test,IntegerSetting)74 TEST(ASN1Test, IntegerSetting) {
75   bssl::UniquePtr<ASN1_INTEGER> by_bn(ASN1_INTEGER_new());
76   bssl::UniquePtr<ASN1_INTEGER> by_long(ASN1_INTEGER_new());
77   bssl::UniquePtr<ASN1_INTEGER> by_uint64(ASN1_INTEGER_new());
78   bssl::UniquePtr<BIGNUM> bn(BN_new());
79 
80   const std::vector<int64_t> kValues = {
81       LONG_MIN, -2, -1, 0, 1, 2, 0xff, 0x100, 0xffff, 0x10000, LONG_MAX,
82   };
83   for (const auto &i : kValues) {
84     SCOPED_TRACE(i);
85 
86     ASSERT_EQ(1, ASN1_INTEGER_set(by_long.get(), i));
87     const uint64_t abs = i < 0 ? (0 - (uint64_t) i) : i;
88     ASSERT_TRUE(BN_set_u64(bn.get(), abs));
89     BN_set_negative(bn.get(), i < 0);
90     ASSERT_TRUE(BN_to_ASN1_INTEGER(bn.get(), by_bn.get()));
91 
92     EXPECT_EQ(0, ASN1_INTEGER_cmp(by_bn.get(), by_long.get()));
93 
94     if (i >= 0) {
95       ASSERT_EQ(1, ASN1_INTEGER_set_uint64(by_uint64.get(), i));
96       EXPECT_EQ(0, ASN1_INTEGER_cmp(by_bn.get(), by_uint64.get()));
97     }
98   }
99 }
100 
101 template <typename T>
TestSerialize(T obj,int (* i2d_func)(T a,uint8_t ** pp),bssl::Span<const uint8_t> expected)102 void TestSerialize(T obj, int (*i2d_func)(T a, uint8_t **pp),
103                    bssl::Span<const uint8_t> expected) {
104   // Test the allocating version first. It is easiest to debug.
105   uint8_t *ptr = nullptr;
106   int len = i2d_func(obj, &ptr);
107   ASSERT_GT(len, 0);
108   EXPECT_EQ(Bytes(expected), Bytes(ptr, len));
109   OPENSSL_free(ptr);
110 
111   len = i2d_func(obj, nullptr);
112   ASSERT_GT(len, 0);
113   EXPECT_EQ(len, static_cast<int>(expected.size()));
114 
115   std::vector<uint8_t> buf(len);
116   ptr = buf.data();
117   len = i2d_func(obj, &ptr);
118   ASSERT_EQ(len, static_cast<int>(expected.size()));
119   EXPECT_EQ(ptr, buf.data() + buf.size());
120   EXPECT_EQ(Bytes(expected), Bytes(buf));
121 }
122 
TEST(ASN1Test,SerializeObject)123 TEST(ASN1Test, SerializeObject) {
124   static const uint8_t kDER[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
125                                  0xf7, 0x0d, 0x01, 0x01, 0x01};
126   const ASN1_OBJECT *obj = OBJ_nid2obj(NID_rsaEncryption);
127   TestSerialize(obj, i2d_ASN1_OBJECT, kDER);
128 }
129 
TEST(ASN1Test,SerializeBoolean)130 TEST(ASN1Test, SerializeBoolean) {
131   static const uint8_t kTrue[] = {0x01, 0x01, 0xff};
132   TestSerialize(0xff, i2d_ASN1_BOOLEAN, kTrue);
133   // Other constants are also correctly encoded as TRUE.
134   TestSerialize(1, i2d_ASN1_BOOLEAN, kTrue);
135   TestSerialize(0x100, i2d_ASN1_BOOLEAN, kTrue);
136 
137   static const uint8_t kFalse[] = {0x01, 0x01, 0x00};
138   TestSerialize(0x00, i2d_ASN1_BOOLEAN, kFalse);
139 }
140 
141 // The templates go through a different codepath, so test them separately.
TEST(ASN1Test,SerializeEmbeddedBoolean)142 TEST(ASN1Test, SerializeEmbeddedBoolean) {
143   bssl::UniquePtr<BASIC_CONSTRAINTS> val(BASIC_CONSTRAINTS_new());
144   ASSERT_TRUE(val);
145 
146   // BasicConstraints defaults to FALSE, so the encoding should be empty.
147   static const uint8_t kLeaf[] = {0x30, 0x00};
148   val->ca = 0;
149   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kLeaf);
150 
151   // TRUE should always be encoded as 0xff, independent of what value the caller
152   // placed in the |ASN1_BOOLEAN|.
153   static const uint8_t kCA[] = {0x30, 0x03, 0x01, 0x01, 0xff};
154   val->ca = 0xff;
155   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA);
156   val->ca = 1;
157   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA);
158   val->ca = 0x100;
159   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA);
160 }
161 
TEST(ASN1Test,ASN1Type)162 TEST(ASN1Test, ASN1Type) {
163   const struct {
164     int type;
165     std::vector<uint8_t> der;
166   } kTests[] = {
167       // BOOLEAN { TRUE }
168       {V_ASN1_BOOLEAN, {0x01, 0x01, 0xff}},
169       // BOOLEAN { FALSE }
170       {V_ASN1_BOOLEAN, {0x01, 0x01, 0x00}},
171       // OCTET_STRING { "a" }
172       {V_ASN1_OCTET_STRING, {0x04, 0x01, 0x61}},
173       // BIT_STRING { `01` `00` }
174       {V_ASN1_BIT_STRING, {0x03, 0x02, 0x01, 0x00}},
175       // INTEGER { -1 }
176       {V_ASN1_INTEGER, {0x02, 0x01, 0xff}},
177       // OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2 }
178       {V_ASN1_OBJECT,
179        {0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7,
180         0x09, 0x02}},
181       // NULL {}
182       {V_ASN1_NULL, {0x05, 0x00}},
183       // SEQUENCE {}
184       {V_ASN1_SEQUENCE, {0x30, 0x00}},
185       // SET {}
186       {V_ASN1_SET, {0x31, 0x00}},
187       // [0] { UTF8String { "a" } }
188       {V_ASN1_OTHER, {0xa0, 0x03, 0x0c, 0x01, 0x61}},
189   };
190   for (const auto &t : kTests) {
191     SCOPED_TRACE(Bytes(t.der));
192 
193     // The input should successfully parse.
194     const uint8_t *ptr = t.der.data();
195     bssl::UniquePtr<ASN1_TYPE> val(d2i_ASN1_TYPE(nullptr, &ptr, t.der.size()));
196     ASSERT_TRUE(val);
197 
198     EXPECT_EQ(ASN1_TYPE_get(val.get()), t.type);
199     EXPECT_EQ(val->type, t.type);
200     TestSerialize(val.get(), i2d_ASN1_TYPE, t.der);
201   }
202 }
203 
204 // Test that reading |value.ptr| from a FALSE |ASN1_TYPE| behaves correctly. The
205 // type historically supported this, so maintain the invariant in case external
206 // code relies on it.
TEST(ASN1Test,UnusedBooleanBits)207 TEST(ASN1Test, UnusedBooleanBits) {
208   // OCTET_STRING { "a" }
209   static const uint8_t kDER[] = {0x04, 0x01, 0x61};
210   const uint8_t *ptr = kDER;
211   bssl::UniquePtr<ASN1_TYPE> val(d2i_ASN1_TYPE(nullptr, &ptr, sizeof(kDER)));
212   ASSERT_TRUE(val);
213   EXPECT_EQ(V_ASN1_OCTET_STRING, val->type);
214   EXPECT_TRUE(val->value.ptr);
215 
216   // Set |val| to a BOOLEAN containing FALSE.
217   ASN1_TYPE_set(val.get(), V_ASN1_BOOLEAN, NULL);
218   EXPECT_EQ(V_ASN1_BOOLEAN, val->type);
219   EXPECT_FALSE(val->value.ptr);
220 }
221 
TEST(ASN1Test,ASN1ObjectReuse)222 TEST(ASN1Test, ASN1ObjectReuse) {
223   // 1.2.840.113554.4.1.72585.2, an arbitrary unknown OID.
224   static const uint8_t kOID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12,
225                                  0x04, 0x01, 0x84, 0xb7, 0x09, 0x02};
226   ASN1_OBJECT *obj = ASN1_OBJECT_create(NID_undef, kOID, sizeof(kOID),
227                                         "short name", "long name");
228   ASSERT_TRUE(obj);
229 
230   // OBJECT_IDENTIFIER { 1.3.101.112 }
231   static const uint8_t kDER[] = {0x06, 0x03, 0x2b, 0x65, 0x70};
232   const uint8_t *ptr = kDER;
233   EXPECT_TRUE(d2i_ASN1_OBJECT(&obj, &ptr, sizeof(kDER)));
234   EXPECT_EQ(NID_ED25519, OBJ_obj2nid(obj));
235   ASN1_OBJECT_free(obj);
236 
237   // Repeat the test, this time overriding a static |ASN1_OBJECT|.
238   obj = OBJ_nid2obj(NID_rsaEncryption);
239   ptr = kDER;
240   EXPECT_TRUE(d2i_ASN1_OBJECT(&obj, &ptr, sizeof(kDER)));
241   EXPECT_EQ(NID_ED25519, OBJ_obj2nid(obj));
242   ASN1_OBJECT_free(obj);
243 }
244 
TEST(ASN1Test,BitString)245 TEST(ASN1Test, BitString) {
246   const size_t kNotWholeBytes = static_cast<size_t>(-1);
247   const struct {
248     std::vector<uint8_t> in;
249     size_t num_bytes;
250   } kValidInputs[] = {
251       // Empty bit string
252       {{0x03, 0x01, 0x00}, 0},
253       // 0b1
254       {{0x03, 0x02, 0x07, 0x80}, kNotWholeBytes},
255       // 0b1010
256       {{0x03, 0x02, 0x04, 0xa0}, kNotWholeBytes},
257       // 0b1010101
258       {{0x03, 0x02, 0x01, 0xaa}, kNotWholeBytes},
259       // 0b10101010
260       {{0x03, 0x02, 0x00, 0xaa}, 1},
261       // Bits 0 and 63 are set
262       {{0x03, 0x09, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, 8},
263       // 64 zero bits
264       {{0x03, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 8},
265   };
266   for (const auto &test : kValidInputs) {
267     SCOPED_TRACE(Bytes(test.in));
268     // The input should parse and round-trip correctly.
269     const uint8_t *ptr = test.in.data();
270     bssl::UniquePtr<ASN1_BIT_STRING> val(
271         d2i_ASN1_BIT_STRING(nullptr, &ptr, test.in.size()));
272     ASSERT_TRUE(val);
273     TestSerialize(val.get(), i2d_ASN1_BIT_STRING, test.in);
274 
275     // Check the byte count.
276     size_t num_bytes;
277     if (test.num_bytes == kNotWholeBytes) {
278       EXPECT_FALSE(ASN1_BIT_STRING_num_bytes(val.get(), &num_bytes));
279     } else {
280       ASSERT_TRUE(ASN1_BIT_STRING_num_bytes(val.get(), &num_bytes));
281       EXPECT_EQ(num_bytes, test.num_bytes);
282     }
283   }
284 
285   const std::vector<uint8_t> kInvalidInputs[] = {
286       // Wrong tag
287       {0x04, 0x01, 0x00},
288       // Missing leading byte
289       {0x03, 0x00},
290       // Leading byte too high
291       {0x03, 0x02, 0x08, 0x00},
292       {0x03, 0x02, 0xff, 0x00},
293       // TODO(https://crbug.com/boringssl/354): Reject these inputs.
294       // Empty bit strings must have a zero leading byte.
295       // {0x03, 0x01, 0x01},
296       // Unused bits must all be zero.
297       // {0x03, 0x02, 0x06, 0xc1 /* 0b11000001 */},
298   };
299   for (const auto &test : kInvalidInputs) {
300     SCOPED_TRACE(Bytes(test));
301     const uint8_t *ptr = test.data();
302     bssl::UniquePtr<ASN1_BIT_STRING> val(
303         d2i_ASN1_BIT_STRING(nullptr, &ptr, test.size()));
304     EXPECT_FALSE(val);
305   }
306 }
307 
TEST(ASN1Test,SetBit)308 TEST(ASN1Test, SetBit) {
309   bssl::UniquePtr<ASN1_BIT_STRING> val(ASN1_BIT_STRING_new());
310   ASSERT_TRUE(val);
311   static const uint8_t kBitStringEmpty[] = {0x03, 0x01, 0x00};
312   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringEmpty);
313   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 0));
314   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 100));
315 
316   // Set a few bits via |ASN1_BIT_STRING_set_bit|.
317   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 0, 1));
318   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 1, 1));
319   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 2, 0));
320   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 3, 1));
321   static const uint8_t kBitString1101[] = {0x03, 0x02, 0x04, 0xd0};
322   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1101);
323   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
324   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 1));
325   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2));
326   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 3));
327   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4));
328 
329   // Bits that were set may be cleared.
330   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 1, 0));
331   static const uint8_t kBitString1001[] = {0x03, 0x02, 0x04, 0x90};
332   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1001);
333   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
334   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 1));
335   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2));
336   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 3));
337   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4));
338 
339   // Clearing trailing bits truncates the string.
340   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 3, 0));
341   static const uint8_t kBitString1[] = {0x03, 0x02, 0x07, 0x80};
342   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1);
343   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
344   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 1));
345   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2));
346   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 3));
347   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4));
348 
349   // Bits may be set beyond the end of the string.
350   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 1));
351   static const uint8_t kBitStringLong[] = {0x03, 0x09, 0x00, 0x80, 0x00, 0x00,
352                                            0x00, 0x00, 0x00, 0x00, 0x01};
353   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringLong);
354   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
355   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62));
356   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 63));
357   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64));
358 
359   // The string can be truncated back down again.
360   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 0));
361   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1);
362   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
363   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62));
364   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63));
365   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64));
366 
367   // |ASN1_BIT_STRING_set_bit| also truncates when starting from a parsed
368   // string.
369   const uint8_t *ptr = kBitStringLong;
370   val.reset(d2i_ASN1_BIT_STRING(nullptr, &ptr, sizeof(kBitStringLong)));
371   ASSERT_TRUE(val);
372   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringLong);
373   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 0));
374   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1);
375   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
376   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62));
377   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63));
378   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64));
379 
380   // A parsed bit string preserves trailing zero bits.
381   static const uint8_t kBitString10010[] = {0x03, 0x02, 0x03, 0x90};
382   ptr = kBitString10010;
383   val.reset(d2i_ASN1_BIT_STRING(nullptr, &ptr, sizeof(kBitString10010)));
384   ASSERT_TRUE(val);
385   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString10010);
386   // But |ASN1_BIT_STRING_set_bit| will truncate it even if otherwise a no-op.
387   ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 0, 1));
388   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1001);
389   EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0));
390   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62));
391   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63));
392   EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64));
393 
394   // By default, a BIT STRING implicitly truncates trailing zeros.
395   val.reset(ASN1_BIT_STRING_new());
396   ASSERT_TRUE(val);
397   static const uint8_t kZeros[64] = {0};
398   ASSERT_TRUE(ASN1_STRING_set(val.get(), kZeros, sizeof(kZeros)));
399   TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringEmpty);
400 }
401 
TEST(ASN1Test,StringToUTF8)402 TEST(ASN1Test, StringToUTF8) {
403   static const struct {
404     std::vector<uint8_t> in;
405     int type;
406     const char *expected;
407   } kTests[] = {
408       // Non-minimal, two-byte UTF-8.
409       {{0xc0, 0x81}, V_ASN1_UTF8STRING, nullptr},
410       // Non-minimal, three-byte UTF-8.
411       {{0xe0, 0x80, 0x81}, V_ASN1_UTF8STRING, nullptr},
412       // Non-minimal, four-byte UTF-8.
413       {{0xf0, 0x80, 0x80, 0x81}, V_ASN1_UTF8STRING, nullptr},
414       // Truncated, four-byte UTF-8.
415       {{0xf0, 0x80, 0x80}, V_ASN1_UTF8STRING, nullptr},
416       // Low-surrogate value.
417       {{0xed, 0xa0, 0x80}, V_ASN1_UTF8STRING, nullptr},
418       // High-surrogate value.
419       {{0xed, 0xb0, 0x81}, V_ASN1_UTF8STRING, nullptr},
420       // Initial BOMs should be rejected from UCS-2 and UCS-4.
421       {{0xfe, 0xff, 0, 88}, V_ASN1_BMPSTRING, nullptr},
422       {{0, 0, 0xfe, 0xff, 0, 0, 0, 88}, V_ASN1_UNIVERSALSTRING, nullptr},
423       // Otherwise, BOMs should pass through.
424       {{0, 88, 0xfe, 0xff}, V_ASN1_BMPSTRING, "X\xef\xbb\xbf"},
425       {{0, 0, 0, 88, 0, 0, 0xfe, 0xff}, V_ASN1_UNIVERSALSTRING,
426        "X\xef\xbb\xbf"},
427       // The maximum code-point should pass though.
428       {{0, 16, 0xff, 0xfd}, V_ASN1_UNIVERSALSTRING, "\xf4\x8f\xbf\xbd"},
429       // Values outside the Unicode space should not.
430       {{0, 17, 0, 0}, V_ASN1_UNIVERSALSTRING, nullptr},
431       // Non-characters should be rejected.
432       {{0, 1, 0xff, 0xff}, V_ASN1_UNIVERSALSTRING, nullptr},
433       {{0, 1, 0xff, 0xfe}, V_ASN1_UNIVERSALSTRING, nullptr},
434       {{0, 0, 0xfd, 0xd5}, V_ASN1_UNIVERSALSTRING, nullptr},
435       // BMPString is UCS-2, not UTF-16, so surrogate pairs are invalid.
436       {{0xd8, 0, 0xdc, 1}, V_ASN1_BMPSTRING, nullptr},
437   };
438 
439   for (const auto &test : kTests) {
440     SCOPED_TRACE(Bytes(test.in));
441     SCOPED_TRACE(test.type);
442     bssl::UniquePtr<ASN1_STRING> s(ASN1_STRING_type_new(test.type));
443     ASSERT_TRUE(s);
444     ASSERT_TRUE(ASN1_STRING_set(s.get(), test.in.data(), test.in.size()));
445 
446     uint8_t *utf8;
447     const int utf8_len = ASN1_STRING_to_UTF8(&utf8, s.get());
448     EXPECT_EQ(utf8_len < 0, test.expected == nullptr);
449     if (utf8_len >= 0) {
450       if (test.expected != nullptr) {
451         EXPECT_EQ(Bytes(test.expected), Bytes(utf8, utf8_len));
452       }
453       OPENSSL_free(utf8);
454     } else {
455       ERR_clear_error();
456     }
457   }
458 }
459 
ASN1StringToStdString(const ASN1_STRING * str)460 static std::string ASN1StringToStdString(const ASN1_STRING *str) {
461   return std::string(ASN1_STRING_get0_data(str),
462                      ASN1_STRING_get0_data(str) + ASN1_STRING_length(str));
463 }
464 
TEST(ASN1Test,SetTime)465 TEST(ASN1Test, SetTime) {
466   static const struct {
467     time_t time;
468     const char *generalized;
469     const char *utc;
470   } kTests[] = {
471     {-631152001, "19491231235959Z", nullptr},
472     {-631152000, "19500101000000Z", "500101000000Z"},
473     {0, "19700101000000Z", "700101000000Z"},
474     {981173106, "20010203040506Z", "010203040506Z"},
475 #if defined(OPENSSL_64_BIT)
476     // TODO(https://crbug.com/boringssl/416): These cases overflow 32-bit
477     // |time_t| and do not consistently work on 32-bit platforms. For now,
478     // disable the tests on 32-bit. Re-enable them once the bug is fixed.
479     {2524607999, "20491231235959Z", "491231235959Z"},
480     {2524608000, "20500101000000Z", nullptr},
481     // Test boundary conditions.
482     {-62167219200, "00000101000000Z", nullptr},
483     {-62167219201, nullptr, nullptr},
484     {253402300799, "99991231235959Z", nullptr},
485     {253402300800, nullptr, nullptr},
486 #endif
487   };
488   for (const auto &t : kTests) {
489     SCOPED_TRACE(t.time);
490 #if defined(OPENSSL_WINDOWS)
491     // Windows |time_t| functions can only handle 1970 through 3000. See
492     // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/gmtime-s-gmtime32-s-gmtime64-s?view=msvc-160
493     if (t.time < 0 || int64_t{t.time} > 32535215999) {
494       continue;
495     }
496 #endif
497 
498     bssl::UniquePtr<ASN1_UTCTIME> utc(ASN1_UTCTIME_set(nullptr, t.time));
499     if (t.utc) {
500       ASSERT_TRUE(utc);
501       EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(utc.get()));
502       EXPECT_EQ(t.utc, ASN1StringToStdString(utc.get()));
503     } else {
504       EXPECT_FALSE(utc);
505     }
506 
507     bssl::UniquePtr<ASN1_GENERALIZEDTIME> generalized(
508         ASN1_GENERALIZEDTIME_set(nullptr, t.time));
509     if (t.generalized) {
510       ASSERT_TRUE(generalized);
511       EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(generalized.get()));
512       EXPECT_EQ(t.generalized, ASN1StringToStdString(generalized.get()));
513     } else {
514       EXPECT_FALSE(generalized);
515     }
516 
517     bssl::UniquePtr<ASN1_TIME> choice(ASN1_TIME_set(nullptr, t.time));
518     if (t.generalized) {
519       ASSERT_TRUE(choice);
520       if (t.utc) {
521         EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(choice.get()));
522         EXPECT_EQ(t.utc, ASN1StringToStdString(choice.get()));
523       } else {
524         EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(choice.get()));
525         EXPECT_EQ(t.generalized, ASN1StringToStdString(choice.get()));
526       }
527     } else {
528       EXPECT_FALSE(choice);
529     }
530   }
531 }
532 
StringToVector(const std::string & str)533 static std::vector<uint8_t> StringToVector(const std::string &str) {
534   return std::vector<uint8_t>(str.begin(), str.end());
535 }
536 
TEST(ASN1Test,StringPrintEx)537 TEST(ASN1Test, StringPrintEx) {
538   const struct {
539     int type;
540     std::vector<uint8_t> data;
541     int str_flags;
542     unsigned long flags;
543     std::string expected;
544   } kTests[] = {
545       // A string like "hello" is never escaped or quoted.
546       // |ASN1_STRFLGS_ESC_QUOTE| only introduces quotes when needed. Note
547       // OpenSSL interprets T61String as Latin-1.
548       {V_ASN1_T61STRING, StringToVector("hello"), 0, 0, "hello"},
549       {V_ASN1_T61STRING, StringToVector("hello"), 0,
550        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB,
551        "hello"},
552       {V_ASN1_T61STRING, StringToVector("hello"), 0,
553        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB |
554            ASN1_STRFLGS_ESC_QUOTE,
555        "hello"},
556 
557       // By default, 8-bit characters are printed without escaping.
558       {V_ASN1_T61STRING,
559        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
560        0,
561        0,
562        std::string(1, '\0') + "\n\x80\xff,+\"\\<>;"},
563 
564       // Flags control different escapes. Note that any escape flag will cause
565       // blackslashes to be escaped.
566       {V_ASN1_T61STRING,
567        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
568        0,
569        ASN1_STRFLGS_ESC_2253,
570        std::string(1, '\0') + "\n\x80\xff\\,\\+\\\"\\\\\\<\\>\\;"},
571       {V_ASN1_T61STRING,
572        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
573        0,
574        ASN1_STRFLGS_ESC_CTRL,
575        "\\00\\0A\x80\xff,+\"\\\\<>;"},
576       {V_ASN1_T61STRING,
577        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
578        0,
579        ASN1_STRFLGS_ESC_MSB,
580        std::string(1, '\0') + "\n\\80\\FF,+\"\\\\<>;"},
581       {V_ASN1_T61STRING,
582        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
583        0,
584        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB,
585        "\\00\\0A\\80\\FF\\,\\+\\\"\\\\\\<\\>\\;"},
586 
587       // When quoted, fewer characters need to be escaped in RFC 2253.
588       {V_ASN1_T61STRING,
589        {0, '\n', 0x80, 0xff, ',', '+', '"', '\\', '<', '>', ';'},
590        0,
591        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB |
592            ASN1_STRFLGS_ESC_QUOTE,
593        "\"\\00\\0A\\80\\FF,+\\\"\\\\<>;\""},
594 
595       // If no characters benefit from quotes, no quotes are added.
596       {V_ASN1_T61STRING,
597        {0, '\n', 0x80, 0xff, '"', '\\'},
598        0,
599        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB |
600            ASN1_STRFLGS_ESC_QUOTE,
601        "\\00\\0A\\80\\FF\\\"\\\\"},
602 
603       // RFC 2253 only escapes spaces at the start and end of a string.
604       {V_ASN1_T61STRING, StringToVector("   "), 0, ASN1_STRFLGS_ESC_2253,
605        "\\  \\ "},
606       {V_ASN1_T61STRING, StringToVector("   "), 0,
607        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE, "\"   \""},
608 
609       // RFC 2253 only escapes # at the start of a string.
610       {V_ASN1_T61STRING, StringToVector("###"), 0, ASN1_STRFLGS_ESC_2253,
611        "\\###"},
612       {V_ASN1_T61STRING, StringToVector("###"), 0,
613        ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE, "\"###\""},
614 
615       // By default, strings are decoded and Unicode code points are
616       // individually escaped.
617       {V_ASN1_UTF8STRING, StringToVector("a\xc2\x80\xc4\x80\xf0\x90\x80\x80"),
618        0, ASN1_STRFLGS_ESC_MSB, "a\\80\\U0100\\W00010000"},
619       {V_ASN1_BMPSTRING,
620        {0x00, 'a', 0x00, 0x80, 0x01, 0x00},
621        0,
622        ASN1_STRFLGS_ESC_MSB,
623        "a\\80\\U0100"},
624       {V_ASN1_UNIVERSALSTRING,
625        {0x00, 0x00, 0x00, 'a',   //
626         0x00, 0x00, 0x00, 0x80,  //
627         0x00, 0x00, 0x01, 0x00,  //
628         0x00, 0x01, 0x00, 0x00},
629        0,
630        ASN1_STRFLGS_ESC_MSB,
631        "a\\80\\U0100\\W00010000"},
632 
633       // |ASN1_STRFLGS_UTF8_CONVERT| normalizes everything to UTF-8 and then
634       // escapes individual bytes.
635       {V_ASN1_IA5STRING, StringToVector("a\x80"), 0,
636        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, "a\\C2\\80"},
637       {V_ASN1_T61STRING, StringToVector("a\x80"), 0,
638        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, "a\\C2\\80"},
639       {V_ASN1_UTF8STRING, StringToVector("a\xc2\x80\xc4\x80\xf0\x90\x80\x80"),
640        0, ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT,
641        "a\\C2\\80\\C4\\80\\F0\\90\\80\\80"},
642       {V_ASN1_BMPSTRING,
643        {0x00, 'a', 0x00, 0x80, 0x01, 0x00},
644        0,
645        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT,
646        "a\\C2\\80\\C4\\80"},
647       {V_ASN1_UNIVERSALSTRING,
648        {0x00, 0x00, 0x00, 'a',   //
649         0x00, 0x00, 0x00, 0x80,  //
650         0x00, 0x00, 0x01, 0x00,  //
651         0x00, 0x01, 0x00, 0x00},
652        0,
653        ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT,
654        "a\\C2\\80\\C4\\80\\F0\\90\\80\\80"},
655 
656       // The same as above, but without escaping the UTF-8 encoding.
657       {V_ASN1_IA5STRING, StringToVector("a\x80"), 0, ASN1_STRFLGS_UTF8_CONVERT,
658        "a\xc2\x80"},
659       {V_ASN1_T61STRING, StringToVector("a\x80"), 0, ASN1_STRFLGS_UTF8_CONVERT,
660        "a\xc2\x80"},
661       {V_ASN1_UTF8STRING, StringToVector("a\xc2\x80\xc4\x80\xf0\x90\x80\x80"),
662        0, ASN1_STRFLGS_UTF8_CONVERT, "a\xc2\x80\xc4\x80\xf0\x90\x80\x80"},
663       {V_ASN1_BMPSTRING,
664        {0x00, 'a', 0x00, 0x80, 0x01, 0x00},
665        0,
666        ASN1_STRFLGS_UTF8_CONVERT,
667        "a\xc2\x80\xc4\x80"},
668       {V_ASN1_UNIVERSALSTRING,
669        {0x00, 0x00, 0x00, 'a',   //
670         0x00, 0x00, 0x00, 0x80,  //
671         0x00, 0x00, 0x01, 0x00,  //
672         0x00, 0x01, 0x00, 0x00},
673        0,
674        ASN1_STRFLGS_UTF8_CONVERT,
675        "a\xc2\x80\xc4\x80\xf0\x90\x80\x80"},
676 
677       // Types that cannot be decoded are, by default, treated as a byte string.
678       {V_ASN1_OCTET_STRING, {0xff}, 0, 0, "\xff"},
679       {-1, {0xff}, 0, 0, "\xff"},
680       {100, {0xff}, 0, 0, "\xff"},
681 
682       // |ASN1_STRFLGS_UTF8_CONVERT| still converts these bytes to UTF-8.
683       //
684       // TODO(davidben): This seems like a bug. Although it's unclear because
685       // the non-RFC-2253 options aren't especially sound. Can we just remove
686       // them?
687       {V_ASN1_OCTET_STRING, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, "\xc3\xbf"},
688       {-1, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, "\xc3\xbf"},
689       {100, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, "\xc3\xbf"},
690 
691       // |ASN1_STRFLGS_IGNORE_TYPE| causes the string type to be ignored, so it
692       // is always treated as a byte string, even if it is not a valid encoding.
693       {V_ASN1_UTF8STRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, "\xff"},
694       {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, "\xff"},
695       {V_ASN1_UNIVERSALSTRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, "\xff"},
696 
697       // |ASN1_STRFLGS_SHOW_TYPE| prepends the type name.
698       {V_ASN1_UTF8STRING, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, "UTF8STRING:a"},
699       {-1, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, "(unknown):a"},
700       {100, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, "(unknown):a"},
701 
702       // |ASN1_STRFLGS_DUMP_ALL| and |ASN1_STRFLGS_DUMP_UNKNOWN| cause
703       // non-string types to be printed in hex, though without the DER wrapper
704       // by default.
705       {V_ASN1_UTF8STRING, StringToVector("\xe2\x98\x83"), 0,
706        ASN1_STRFLGS_DUMP_UNKNOWN, "\\U2603"},
707       {V_ASN1_UTF8STRING, StringToVector("\xe2\x98\x83"), 0,
708        ASN1_STRFLGS_DUMP_ALL, "#E29883"},
709       {V_ASN1_OCTET_STRING, StringToVector("\xe2\x98\x83"), 0,
710        ASN1_STRFLGS_DUMP_UNKNOWN, "#E29883"},
711       {V_ASN1_OCTET_STRING, StringToVector("\xe2\x98\x83"), 0,
712        ASN1_STRFLGS_DUMP_ALL, "#E29883"},
713 
714       // |ASN1_STRFLGS_DUMP_DER| includes the entire element.
715       {V_ASN1_UTF8STRING, StringToVector("\xe2\x98\x83"), 0,
716        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, "#0C03E29883"},
717       {V_ASN1_OCTET_STRING, StringToVector("\xe2\x98\x83"), 0,
718        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, "#0403E29883"},
719       {V_ASN1_BIT_STRING,
720        {0x80},
721        ASN1_STRING_FLAG_BITS_LEFT | 4,
722        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
723        "#03020480"},
724       // INTEGER { 1 }
725       {V_ASN1_INTEGER,
726        {0x01},
727        0,
728        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
729        "#020101"},
730       // INTEGER { -1 }
731       {V_ASN1_NEG_INTEGER,
732        {0x01},
733        0,
734        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
735        "#0201FF"},
736       // ENUMERATED { 1 }
737       {V_ASN1_ENUMERATED,
738        {0x01},
739        0,
740        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
741        "#0A0101"},
742       // ENUMERATED { -1 }
743       {V_ASN1_NEG_ENUMERATED,
744        {0x01},
745        0,
746        ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER,
747        "#0A01FF"},
748   };
749   for (const auto &t : kTests) {
750     SCOPED_TRACE(t.type);
751     SCOPED_TRACE(Bytes(t.data));
752     SCOPED_TRACE(t.str_flags);
753     SCOPED_TRACE(t.flags);
754 
755     bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_type_new(t.type));
756     ASSERT_TRUE(ASN1_STRING_set(str.get(), t.data.data(), t.data.size()));
757     str->flags = t.str_flags;
758 
759     // If the |BIO| is null, it should measure the size.
760     int len = ASN1_STRING_print_ex(nullptr, str.get(), t.flags);
761     EXPECT_EQ(len, static_cast<int>(t.expected.size()));
762 
763     // Measuring the size should also work for the |FILE| version
764     len = ASN1_STRING_print_ex_fp(nullptr, str.get(), t.flags);
765     EXPECT_EQ(len, static_cast<int>(t.expected.size()));
766 
767     // Actually print the string.
768     bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
769     ASSERT_TRUE(bio);
770     len = ASN1_STRING_print_ex(bio.get(), str.get(), t.flags);
771     EXPECT_EQ(len, static_cast<int>(t.expected.size()));
772 
773     const uint8_t *bio_contents;
774     size_t bio_len;
775     ASSERT_TRUE(BIO_mem_contents(bio.get(), &bio_contents, &bio_len));
776     EXPECT_EQ(t.expected, std::string(bio_contents, bio_contents + bio_len));
777   }
778 
779   const struct {
780     int type;
781     std::vector<uint8_t> data;
782     int str_flags;
783     unsigned long flags;
784   } kUnprintableTests[] = {
785       // When decoding strings, invalid codepoints are errors.
786       {V_ASN1_UTF8STRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB},
787       {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB},
788       {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB},
789       {V_ASN1_UNIVERSALSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB},
790   };
791   for (const auto &t : kUnprintableTests) {
792     SCOPED_TRACE(t.type);
793     SCOPED_TRACE(Bytes(t.data));
794     SCOPED_TRACE(t.str_flags);
795     SCOPED_TRACE(t.flags);
796 
797     bssl::UniquePtr<ASN1_STRING> str(ASN1_STRING_type_new(t.type));
798     ASSERT_TRUE(ASN1_STRING_set(str.get(), t.data.data(), t.data.size()));
799     str->flags = t.str_flags;
800 
801     // If the |BIO| is null, it should measure the size.
802     int len = ASN1_STRING_print_ex(nullptr, str.get(), t.flags);
803     EXPECT_EQ(len, -1);
804     ERR_clear_error();
805 
806     // Measuring the size should also work for the |FILE| version
807     len = ASN1_STRING_print_ex_fp(nullptr, str.get(), t.flags);
808     EXPECT_EQ(len, -1);
809     ERR_clear_error();
810 
811     // Actually print the string.
812     bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
813     ASSERT_TRUE(bio);
814     len = ASN1_STRING_print_ex(bio.get(), str.get(), t.flags);
815     EXPECT_EQ(len, -1);
816     ERR_clear_error();
817   }
818 }
819 
TEST(ASN1Test,MBString)820 TEST(ASN1Test, MBString) {
821   const unsigned long kAll = B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING |
822                              B_ASN1_T61STRING | B_ASN1_BMPSTRING |
823                              B_ASN1_UNIVERSALSTRING | B_ASN1_UTF8STRING;
824 
825   const struct {
826     int format;
827     std::vector<uint8_t> in;
828     unsigned long mask;
829     int expected_type;
830     std::vector<uint8_t> expected_data;
831     int num_codepoints;
832   } kTests[] = {
833       // Given a choice of formats, we pick the smallest that fits.
834       {MBSTRING_UTF8, {}, kAll, V_ASN1_PRINTABLESTRING, {}, 0},
835       {MBSTRING_UTF8, {'a'}, kAll, V_ASN1_PRINTABLESTRING, {'a'}, 1},
836       {MBSTRING_UTF8,
837        {'a', 'A', '0', '\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'},
838        kAll,
839        V_ASN1_PRINTABLESTRING,
840        {'a', 'A', '0', '\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'},
841        14},
842       {MBSTRING_UTF8, {'*'}, kAll, V_ASN1_IA5STRING, {'*'}, 1},
843       {MBSTRING_UTF8, {'\n'}, kAll, V_ASN1_IA5STRING, {'\n'}, 1},
844       {MBSTRING_UTF8,
845        {0xc2, 0x80 /* U+0080 */},
846        kAll,
847        V_ASN1_T61STRING,
848        {0x80},
849        1},
850       {MBSTRING_UTF8,
851        {0xc4, 0x80 /* U+0100 */},
852        kAll,
853        V_ASN1_BMPSTRING,
854        {0x01, 0x00},
855        1},
856       {MBSTRING_UTF8,
857        {0xf0, 0x90, 0x80, 0x80 /* U+10000 */},
858        kAll,
859        V_ASN1_UNIVERSALSTRING,
860        {0x00, 0x01, 0x00, 0x00},
861        1},
862       {MBSTRING_UTF8,
863        {0xf0, 0x90, 0x80, 0x80 /* U+10000 */},
864        kAll & ~B_ASN1_UNIVERSALSTRING,
865        V_ASN1_UTF8STRING,
866        {0xf0, 0x90, 0x80, 0x80},
867        1},
868 
869       // NUL is not printable. It should also not terminate iteration.
870       {MBSTRING_UTF8, {0}, kAll, V_ASN1_IA5STRING, {0}, 1},
871       {MBSTRING_UTF8, {0, 'a'}, kAll, V_ASN1_IA5STRING, {0, 'a'}, 2},
872 
873       // When a particular format is specified, we use it.
874       {MBSTRING_UTF8,
875        {'a'},
876        B_ASN1_PRINTABLESTRING,
877        V_ASN1_PRINTABLESTRING,
878        {'a'},
879        1},
880       {MBSTRING_UTF8, {'a'}, B_ASN1_IA5STRING, V_ASN1_IA5STRING, {'a'}, 1},
881       {MBSTRING_UTF8, {'a'}, B_ASN1_T61STRING, V_ASN1_T61STRING, {'a'}, 1},
882       {MBSTRING_UTF8, {'a'}, B_ASN1_UTF8STRING, V_ASN1_UTF8STRING, {'a'}, 1},
883       {MBSTRING_UTF8,
884        {'a'},
885        B_ASN1_BMPSTRING,
886        V_ASN1_BMPSTRING,
887        {0x00, 'a'},
888        1},
889       {MBSTRING_UTF8,
890        {'a'},
891        B_ASN1_UNIVERSALSTRING,
892        V_ASN1_UNIVERSALSTRING,
893        {0x00, 0x00, 0x00, 'a'},
894        1},
895 
896       // A long string with characters of many widths, to test sizes are
897       // measured in code points.
898       {MBSTRING_UTF8,
899        {
900            'a',                     //
901            0xc2, 0x80,              // U+0080
902            0xc4, 0x80,              // U+0100
903            0xf0, 0x90, 0x80, 0x80,  // U+10000
904        },
905        B_ASN1_UNIVERSALSTRING,
906        V_ASN1_UNIVERSALSTRING,
907        {
908            0x00, 0x00, 0x00, 'a',   //
909            0x00, 0x00, 0x00, 0x80,  //
910            0x00, 0x00, 0x01, 0x00,  //
911            0x00, 0x01, 0x00, 0x00,  //
912        },
913        4},
914   };
915   for (const auto &t : kTests) {
916     SCOPED_TRACE(t.format);
917     SCOPED_TRACE(Bytes(t.in));
918     SCOPED_TRACE(t.mask);
919 
920     // Passing in nullptr should do a dry run.
921     EXPECT_EQ(t.expected_type,
922               ASN1_mbstring_copy(nullptr, t.in.data(), t.in.size(), t.format,
923                                  t.mask));
924 
925     // Test allocating a new object.
926     ASN1_STRING *str = nullptr;
927     EXPECT_EQ(
928         t.expected_type,
929         ASN1_mbstring_copy(&str, t.in.data(), t.in.size(), t.format, t.mask));
930     ASSERT_TRUE(str);
931     EXPECT_EQ(t.expected_type, ASN1_STRING_type(str));
932     EXPECT_EQ(Bytes(t.expected_data),
933               Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str)));
934 
935     // Test writing into an existing object.
936     ASN1_STRING_free(str);
937     str = ASN1_STRING_new();
938     ASSERT_TRUE(str);
939     ASN1_STRING *old_str = str;
940     EXPECT_EQ(
941         t.expected_type,
942         ASN1_mbstring_copy(&str, t.in.data(), t.in.size(), t.format, t.mask));
943     ASSERT_EQ(old_str, str);
944     EXPECT_EQ(t.expected_type, ASN1_STRING_type(str));
945     EXPECT_EQ(Bytes(t.expected_data),
946               Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str)));
947     ASN1_STRING_free(str);
948     str = nullptr;
949 
950     // minsize and maxsize should be enforced, even in a dry run.
951     EXPECT_EQ(t.expected_type,
952               ASN1_mbstring_ncopy(nullptr, t.in.data(), t.in.size(), t.format,
953                                   t.mask, /*minsize=*/t.num_codepoints,
954                                   /*maxsize=*/t.num_codepoints));
955 
956     EXPECT_EQ(t.expected_type,
957               ASN1_mbstring_ncopy(&str, t.in.data(), t.in.size(), t.format,
958                                   t.mask, /*minsize=*/t.num_codepoints,
959                                   /*maxsize=*/t.num_codepoints));
960     ASSERT_TRUE(str);
961     EXPECT_EQ(t.expected_type, ASN1_STRING_type(str));
962     EXPECT_EQ(Bytes(t.expected_data),
963               Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str)));
964     ASN1_STRING_free(str);
965     str = nullptr;
966 
967     EXPECT_EQ(-1, ASN1_mbstring_ncopy(
968                       nullptr, t.in.data(), t.in.size(), t.format, t.mask,
969                       /*minsize=*/t.num_codepoints + 1, /*maxsize=*/0));
970     ERR_clear_error();
971     EXPECT_EQ(-1, ASN1_mbstring_ncopy(
972                       &str, t.in.data(), t.in.size(), t.format, t.mask,
973                       /*minsize=*/t.num_codepoints + 1, /*maxsize=*/0));
974     EXPECT_FALSE(str);
975     ERR_clear_error();
976     if (t.num_codepoints > 1) {
977       EXPECT_EQ(-1, ASN1_mbstring_ncopy(
978                         nullptr, t.in.data(), t.in.size(), t.format, t.mask,
979                         /*minsize=*/0, /*maxsize=*/t.num_codepoints - 1));
980       ERR_clear_error();
981       EXPECT_EQ(-1, ASN1_mbstring_ncopy(
982                         &str, t.in.data(), t.in.size(), t.format, t.mask,
983                         /*minsize=*/0, /*maxsize=*/t.num_codepoints - 1));
984       EXPECT_FALSE(str);
985       ERR_clear_error();
986     }
987   }
988 
989   const struct {
990     int format;
991     std::vector<uint8_t> in;
992     unsigned long mask;
993   } kInvalidTests[] = {
994       // Invalid encodings are rejected.
995       {MBSTRING_UTF8, {0xff}, B_ASN1_UTF8STRING},
996       {MBSTRING_BMP, {0xff}, B_ASN1_UTF8STRING},
997       {MBSTRING_UNIV, {0xff}, B_ASN1_UTF8STRING},
998 
999       // Lone surrogates are not code points.
1000       {MBSTRING_UTF8, {0xed, 0xa0, 0x80}, B_ASN1_UTF8STRING},
1001       {MBSTRING_BMP, {0xd8, 0x00}, B_ASN1_UTF8STRING},
1002       {MBSTRING_UNIV, {0x00, 0x00, 0xd8, 0x00}, B_ASN1_UTF8STRING},
1003 
1004       // The input does not fit in the allowed output types.
1005       {MBSTRING_UTF8, {'\n'}, B_ASN1_PRINTABLESTRING},
1006       {MBSTRING_UTF8,
1007        {0xc2, 0x80 /* U+0080 */},
1008        B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING},
1009       {MBSTRING_UTF8,
1010        {0xc4, 0x80 /* U+0100 */},
1011        B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING | B_ASN1_T61STRING},
1012       {MBSTRING_UTF8,
1013        {0xf0, 0x90, 0x80, 0x80 /* U+10000 */},
1014        B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING | B_ASN1_T61STRING |
1015            B_ASN1_BMPSTRING},
1016 
1017       // Unrecognized bits are ignored.
1018       {MBSTRING_UTF8, {'\n'}, B_ASN1_PRINTABLESTRING | B_ASN1_SEQUENCE},
1019   };
1020   for (const auto &t : kInvalidTests) {
1021     SCOPED_TRACE(t.format);
1022     SCOPED_TRACE(Bytes(t.in));
1023     SCOPED_TRACE(t.mask);
1024 
1025     EXPECT_EQ(-1, ASN1_mbstring_copy(nullptr, t.in.data(), t.in.size(),
1026                                      t.format, t.mask));
1027     ERR_clear_error();
1028 
1029     ASN1_STRING *str = nullptr;
1030     EXPECT_EQ(-1, ASN1_mbstring_copy(&str, t.in.data(), t.in.size(),
1031                                      t.format, t.mask));
1032     ERR_clear_error();
1033     EXPECT_EQ(nullptr, str);
1034   }
1035 }
1036 
1037 // Test that multi-string types correctly encode negative ENUMERATED.
1038 // Multi-string types cannot contain INTEGER, so we only test ENUMERATED.
TEST(ASN1Test,NegativeEnumeratedMultistring)1039 TEST(ASN1Test, NegativeEnumeratedMultistring) {
1040   static const uint8_t kMinusOne[] = {0x0a, 0x01, 0xff};  // ENUMERATED { -1 }
1041   // |ASN1_PRINTABLE| is a multi-string type that allows ENUMERATED.
1042   const uint8_t *p = kMinusOne;
1043   bssl::UniquePtr<ASN1_STRING> str(
1044       d2i_ASN1_PRINTABLE(nullptr, &p, sizeof(kMinusOne)));
1045   ASSERT_TRUE(str);
1046   TestSerialize(str.get(), i2d_ASN1_PRINTABLE, kMinusOne);
1047 }
1048 
TEST(ASN1Test,PrintableType)1049 TEST(ASN1Test, PrintableType) {
1050   const struct {
1051     std::vector<uint8_t> in;
1052     int result;
1053   } kTests[] = {
1054       {{}, V_ASN1_PRINTABLESTRING},
1055       {{'a', 'A', '0', '\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'},
1056        V_ASN1_PRINTABLESTRING},
1057       {{'*'}, V_ASN1_IA5STRING},
1058       {{'\0'}, V_ASN1_IA5STRING},
1059       {{'\0', 'a'}, V_ASN1_IA5STRING},
1060       {{0, 1, 2, 3, 125, 126, 127}, V_ASN1_IA5STRING},
1061       {{0, 1, 2, 3, 125, 126, 127, 128}, V_ASN1_T61STRING},
1062       {{128, 0, 1, 2, 3, 125, 126, 127}, V_ASN1_T61STRING},
1063   };
1064   for (const auto &t : kTests) {
1065     SCOPED_TRACE(Bytes(t.in));
1066     EXPECT_EQ(t.result, ASN1_PRINTABLE_type(t.in.data(), t.in.size()));
1067   }
1068 }
1069 
1070 // The ASN.1 macros do not work on Windows shared library builds, where usage of
1071 // |OPENSSL_EXPORT| is a bit stricter.
1072 #if !defined(OPENSSL_WINDOWS) || !defined(BORINGSSL_SHARED_LIBRARY)
1073 
1074 typedef struct asn1_linked_list_st {
1075   struct asn1_linked_list_st *next;
1076 } ASN1_LINKED_LIST;
1077 
1078 DECLARE_ASN1_ITEM(ASN1_LINKED_LIST)
DECLARE_ASN1_FUNCTIONS(ASN1_LINKED_LIST)1079 DECLARE_ASN1_FUNCTIONS(ASN1_LINKED_LIST)
1080 
1081 ASN1_SEQUENCE(ASN1_LINKED_LIST) = {
1082   ASN1_OPT(ASN1_LINKED_LIST, next, ASN1_LINKED_LIST),
1083 } ASN1_SEQUENCE_END(ASN1_LINKED_LIST)
1084 
1085 IMPLEMENT_ASN1_FUNCTIONS(ASN1_LINKED_LIST)
1086 
1087 static bool MakeLinkedList(bssl::UniquePtr<uint8_t> *out, size_t *out_len,
1088                            size_t count) {
1089   bssl::ScopedCBB cbb;
1090   std::vector<CBB> cbbs(count);
1091   if (!CBB_init(cbb.get(), 2 * count) ||
1092       !CBB_add_asn1(cbb.get(), &cbbs[0], CBS_ASN1_SEQUENCE)) {
1093     return false;
1094   }
1095   for (size_t i = 1; i < count; i++) {
1096     if (!CBB_add_asn1(&cbbs[i - 1], &cbbs[i], CBS_ASN1_SEQUENCE)) {
1097       return false;
1098     }
1099   }
1100   uint8_t *ptr;
1101   if (!CBB_finish(cbb.get(), &ptr, out_len)) {
1102     return false;
1103   }
1104   out->reset(ptr);
1105   return true;
1106 }
1107 
TEST(ASN1Test,Recursive)1108 TEST(ASN1Test, Recursive) {
1109   bssl::UniquePtr<uint8_t> data;
1110   size_t len;
1111 
1112   // Sanity-check that MakeLinkedList can be parsed.
1113   ASSERT_TRUE(MakeLinkedList(&data, &len, 5));
1114   const uint8_t *ptr = data.get();
1115   ASN1_LINKED_LIST *list = d2i_ASN1_LINKED_LIST(nullptr, &ptr, len);
1116   EXPECT_TRUE(list);
1117   ASN1_LINKED_LIST_free(list);
1118 
1119   // Excessively deep structures are rejected.
1120   ASSERT_TRUE(MakeLinkedList(&data, &len, 100));
1121   ptr = data.get();
1122   list = d2i_ASN1_LINKED_LIST(nullptr, &ptr, len);
1123   EXPECT_FALSE(list);
1124   // Note checking the error queue here does not work. The error "stack trace"
1125   // is too deep, so the |ASN1_R_NESTED_TOO_DEEP| entry drops off the queue.
1126   ASN1_LINKED_LIST_free(list);
1127 }
1128 
1129 struct IMPLICIT_CHOICE {
1130   ASN1_STRING *string;
1131 };
1132 
1133 // clang-format off
1134 DECLARE_ASN1_FUNCTIONS(IMPLICIT_CHOICE)
1135 
ASN1_SEQUENCE(IMPLICIT_CHOICE)1136 ASN1_SEQUENCE(IMPLICIT_CHOICE) = {
1137   ASN1_IMP(IMPLICIT_CHOICE, string, DIRECTORYSTRING, 0)
1138 } ASN1_SEQUENCE_END(IMPLICIT_CHOICE)
1139 
1140 IMPLEMENT_ASN1_FUNCTIONS(IMPLICIT_CHOICE)
1141 // clang-format on
1142 
1143 // Test that the ASN.1 templates reject types with implicitly-tagged CHOICE
1144 // types.
1145 TEST(ASN1Test, ImplicitChoice) {
1146   // Serializing a type with an implicitly tagged CHOICE should fail.
1147   std::unique_ptr<IMPLICIT_CHOICE, decltype(&IMPLICIT_CHOICE_free)> obj(
1148       IMPLICIT_CHOICE_new(), IMPLICIT_CHOICE_free);
1149   EXPECT_EQ(-1, i2d_IMPLICIT_CHOICE(obj.get(), nullptr));
1150 
1151   // An implicitly-tagged CHOICE is an error. Depending on the implementation,
1152   // it may be misinterpreted as without the tag, or as clobbering the CHOICE
1153   // tag. Test both inputs and ensure they fail.
1154 
1155   // SEQUENCE { UTF8String {} }
1156   static const uint8_t kInput1[] = {0x30, 0x02, 0x0c, 0x00};
1157   const uint8_t *ptr = kInput1;
1158   EXPECT_EQ(nullptr, d2i_IMPLICIT_CHOICE(nullptr, &ptr, sizeof(kInput1)));
1159 
1160   // SEQUENCE { [0 PRIMITIVE] {} }
1161   static const uint8_t kInput2[] = {0x30, 0x02, 0x80, 0x00};
1162   ptr = kInput2;
1163   EXPECT_EQ(nullptr, d2i_IMPLICIT_CHOICE(nullptr, &ptr, sizeof(kInput2)));
1164 }
1165 
1166 #endif  // !WINDOWS || !SHARED_LIBRARY
1167