• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2014, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 
19 #include <vector>
20 
21 #include <gtest/gtest.h>
22 
23 #include <openssl/bytestring.h>
24 #include <openssl/crypto.h>
25 #include <openssl/span.h>
26 
27 #include "../internal.h"
28 #include "../test/test_util.h"
29 #include "internal.h"
30 
31 
TEST(CBSTest,Skip)32 TEST(CBSTest, Skip) {
33   static const uint8_t kData[] = {1, 2, 3};
34   CBS data;
35 
36   CBS_init(&data, kData, sizeof(kData));
37   EXPECT_EQ(3u, CBS_len(&data));
38   EXPECT_TRUE(CBS_skip(&data, 1));
39   EXPECT_EQ(2u, CBS_len(&data));
40   EXPECT_TRUE(CBS_skip(&data, 2));
41   EXPECT_EQ(0u, CBS_len(&data));
42   EXPECT_FALSE(CBS_skip(&data, 1));
43 }
44 
TEST(CBSTest,GetUint)45 TEST(CBSTest, GetUint) {
46   static const uint8_t kData[] = {1,  2,  3,  4,  5,  6,  7,  8,  9,  10,
47                                   11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
48   uint8_t u8;
49   uint16_t u16;
50   uint32_t u32;
51   uint64_t u64;
52   CBS data;
53 
54   CBS_init(&data, kData, sizeof(kData));
55   ASSERT_TRUE(CBS_get_u8(&data, &u8));
56   EXPECT_EQ(1u, u8);
57   ASSERT_TRUE(CBS_get_u16(&data, &u16));
58   EXPECT_EQ(0x203u, u16);
59   ASSERT_TRUE(CBS_get_u24(&data, &u32));
60   EXPECT_EQ(0x40506u, u32);
61   ASSERT_TRUE(CBS_get_u32(&data, &u32));
62   EXPECT_EQ(0x708090au, u32);
63   ASSERT_TRUE(CBS_get_u64(&data, &u64));
64   EXPECT_EQ(0xb0c0d0e0f101112u, u64);
65   ASSERT_TRUE(CBS_get_last_u8(&data, &u8));
66   EXPECT_EQ(0x14u, u8);
67   ASSERT_TRUE(CBS_get_last_u8(&data, &u8));
68   EXPECT_EQ(0x13u, u8);
69   EXPECT_FALSE(CBS_get_u8(&data, &u8));
70   EXPECT_FALSE(CBS_get_last_u8(&data, &u8));
71 
72   CBS_init(&data, kData, sizeof(kData));
73   ASSERT_TRUE(CBS_get_u16le(&data, &u16));
74   EXPECT_EQ(0x0201u, u16);
75   ASSERT_TRUE(CBS_get_u32le(&data, &u32));
76   EXPECT_EQ(0x06050403u, u32);
77   ASSERT_TRUE(CBS_get_u64le(&data, &u64));
78   EXPECT_EQ(0x0e0d0c0b0a090807u, u64);
79 }
80 
TEST(CBSTest,GetPrefixed)81 TEST(CBSTest, GetPrefixed) {
82   static const uint8_t kData[] = {1, 2, 0, 2, 3, 4, 0, 0, 3, 3, 2, 1};
83   uint8_t u8;
84   uint16_t u16;
85   uint32_t u32;
86   CBS data, prefixed;
87 
88   CBS_init(&data, kData, sizeof(kData));
89   ASSERT_TRUE(CBS_get_u8_length_prefixed(&data, &prefixed));
90   EXPECT_EQ(1u, CBS_len(&prefixed));
91   ASSERT_TRUE(CBS_get_u8(&prefixed, &u8));
92   EXPECT_EQ(2u, u8);
93   ASSERT_TRUE(CBS_get_u16_length_prefixed(&data, &prefixed));
94   EXPECT_EQ(2u, CBS_len(&prefixed));
95   ASSERT_TRUE(CBS_get_u16(&prefixed, &u16));
96   EXPECT_EQ(0x304u, u16);
97   ASSERT_TRUE(CBS_get_u24_length_prefixed(&data, &prefixed));
98   EXPECT_EQ(3u, CBS_len(&prefixed));
99   ASSERT_TRUE(CBS_get_u24(&prefixed, &u32));
100   EXPECT_EQ(0x30201u, u32);
101 }
102 
TEST(CBSTest,GetPrefixedBad)103 TEST(CBSTest, GetPrefixedBad) {
104   static const uint8_t kData1[] = {2, 1};
105   static const uint8_t kData2[] = {0, 2, 1};
106   static const uint8_t kData3[] = {0, 0, 2, 1};
107   CBS data, prefixed;
108 
109   CBS_init(&data, kData1, sizeof(kData1));
110   EXPECT_FALSE(CBS_get_u8_length_prefixed(&data, &prefixed));
111 
112   CBS_init(&data, kData2, sizeof(kData2));
113   EXPECT_FALSE(CBS_get_u16_length_prefixed(&data, &prefixed));
114 
115   CBS_init(&data, kData3, sizeof(kData3));
116   EXPECT_FALSE(CBS_get_u24_length_prefixed(&data, &prefixed));
117 }
118 
TEST(CBSTest,GetUntilFirst)119 TEST(CBSTest, GetUntilFirst) {
120   static const uint8_t kData[] = {0, 1, 2, 3, 0, 1, 2, 3};
121   CBS data;
122   CBS_init(&data, kData, sizeof(kData));
123 
124   CBS prefix;
125   EXPECT_FALSE(CBS_get_until_first(&data, &prefix, 4));
126   EXPECT_EQ(CBS_data(&data), kData);
127   EXPECT_EQ(CBS_len(&data), sizeof(kData));
128 
129   ASSERT_TRUE(CBS_get_until_first(&data, &prefix, 0));
130   EXPECT_EQ(CBS_len(&prefix), 0u);
131   EXPECT_EQ(CBS_data(&data), kData);
132   EXPECT_EQ(CBS_len(&data), sizeof(kData));
133 
134   ASSERT_TRUE(CBS_get_until_first(&data, &prefix, 2));
135   EXPECT_EQ(CBS_data(&prefix), kData);
136   EXPECT_EQ(CBS_len(&prefix), 2u);
137   EXPECT_EQ(CBS_data(&data), kData + 2);
138   EXPECT_EQ(CBS_len(&data), sizeof(kData) - 2);
139 }
140 
TEST(CBSTest,GetASN1)141 TEST(CBSTest, GetASN1) {
142   static const uint8_t kData1[] = {0x30, 2, 1, 2};
143   static const uint8_t kData2[] = {0x30, 3, 1, 2};
144   static const uint8_t kData3[] = {0x30, 0x80};
145   static const uint8_t kData4[] = {0x30, 0x81, 1, 1};
146   static const uint8_t kData5[4 + 0x80] = {0x30, 0x82, 0, 0x80};
147   static const uint8_t kData6[] = {0xa1, 3, 0x4, 1, 1};
148   static const uint8_t kData7[] = {0xa1, 3, 0x4, 2, 1};
149   static const uint8_t kData8[] = {0xa1, 3, 0x2, 1, 1};
150   static const uint8_t kData9[] = {0xa1, 3, 0x2, 1, 0xff};
151 
152   CBS data, contents;
153   int present;
154   uint64_t value;
155 
156   CBS_init(&data, kData1, sizeof(kData1));
157   EXPECT_FALSE(CBS_peek_asn1_tag(&data, CBS_ASN1_BOOLEAN));
158   EXPECT_TRUE(CBS_peek_asn1_tag(&data, CBS_ASN1_SEQUENCE));
159 
160   ASSERT_TRUE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
161   EXPECT_EQ(Bytes("\x01\x02"), Bytes(CBS_data(&contents), CBS_len(&contents)));
162 
163   CBS_init(&data, kData2, sizeof(kData2));
164   // data is truncated
165   EXPECT_FALSE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
166 
167   CBS_init(&data, kData3, sizeof(kData3));
168   // zero byte length of length
169   EXPECT_FALSE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
170 
171   CBS_init(&data, kData4, sizeof(kData4));
172   // long form mistakenly used.
173   EXPECT_FALSE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
174 
175   CBS_init(&data, kData5, sizeof(kData5));
176   // length takes too many bytes.
177   EXPECT_FALSE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
178 
179   CBS_init(&data, kData1, sizeof(kData1));
180   // wrong tag.
181   EXPECT_FALSE(CBS_get_asn1(&data, &contents, 0x31));
182 
183   CBS_init(&data, NULL, 0);
184   // peek at empty data.
185   EXPECT_FALSE(CBS_peek_asn1_tag(&data, CBS_ASN1_SEQUENCE));
186 
187   CBS_init(&data, NULL, 0);
188   // optional elements at empty data.
189   ASSERT_TRUE(CBS_get_optional_asn1(
190       &data, &contents, &present,
191       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
192   EXPECT_FALSE(present);
193   ASSERT_TRUE(CBS_get_optional_asn1_octet_string(
194       &data, &contents, &present,
195       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
196   EXPECT_FALSE(present);
197   EXPECT_EQ(0u, CBS_len(&contents));
198   ASSERT_TRUE(CBS_get_optional_asn1_octet_string(
199       &data, &contents, NULL,
200       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
201   EXPECT_EQ(0u, CBS_len(&contents));
202   ASSERT_TRUE(CBS_get_optional_asn1_uint64(
203       &data, &value, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0, 42));
204   EXPECT_EQ(42u, value);
205 
206   CBS_init(&data, kData6, sizeof(kData6));
207   // optional element.
208   ASSERT_TRUE(CBS_get_optional_asn1(
209       &data, &contents, &present,
210       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
211   EXPECT_FALSE(present);
212   ASSERT_TRUE(CBS_get_optional_asn1(
213       &data, &contents, &present,
214       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1));
215   EXPECT_TRUE(present);
216   EXPECT_EQ(Bytes("\x04\x01\x01"),
217             Bytes(CBS_data(&contents), CBS_len(&contents)));
218 
219   CBS_init(&data, kData6, sizeof(kData6));
220   // optional octet string.
221   ASSERT_TRUE(CBS_get_optional_asn1_octet_string(
222       &data, &contents, &present,
223       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
224   EXPECT_FALSE(present);
225   EXPECT_EQ(0u, CBS_len(&contents));
226   ASSERT_TRUE(CBS_get_optional_asn1_octet_string(
227       &data, &contents, &present,
228       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1));
229   EXPECT_TRUE(present);
230   EXPECT_EQ(Bytes("\x01"), Bytes(CBS_data(&contents), CBS_len(&contents)));
231 
232   CBS_init(&data, kData7, sizeof(kData7));
233   // invalid optional octet string.
234   EXPECT_FALSE(CBS_get_optional_asn1_octet_string(
235       &data, &contents, &present,
236       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1));
237 
238   CBS_init(&data, kData8, sizeof(kData8));
239   // optional integer.
240   ASSERT_TRUE(CBS_get_optional_asn1_uint64(
241       &data, &value, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0, 42));
242   EXPECT_EQ(42u, value);
243   ASSERT_TRUE(CBS_get_optional_asn1_uint64(
244       &data, &value, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1, 42));
245   EXPECT_EQ(1u, value);
246 
247   CBS_init(&data, kData9, sizeof(kData9));
248   // invalid optional integer.
249   EXPECT_FALSE(CBS_get_optional_asn1_uint64(
250       &data, &value, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1, 42));
251 
252   CBS_ASN1_TAG tag;
253   CBS_init(&data, kData1, sizeof(kData1));
254   ASSERT_TRUE(CBS_get_any_asn1(&data, &contents, &tag));
255   EXPECT_EQ(CBS_ASN1_SEQUENCE, tag);
256   EXPECT_EQ(Bytes("\x01\x02"), Bytes(CBS_data(&contents), CBS_len(&contents)));
257 
258   size_t header_len;
259   CBS_init(&data, kData1, sizeof(kData1));
260   ASSERT_TRUE(CBS_get_any_asn1_element(&data, &contents, &tag, &header_len));
261   EXPECT_EQ(CBS_ASN1_SEQUENCE, tag);
262   EXPECT_EQ(2u, header_len);
263   EXPECT_EQ(Bytes("\x30\x02\x01\x02"),
264             Bytes(CBS_data(&contents), CBS_len(&contents)));
265 }
266 
TEST(CBSTest,ParseASN1Tag)267 TEST(CBSTest, ParseASN1Tag) {
268   const struct {
269     bool ok;
270     CBS_ASN1_TAG tag;
271     std::vector<uint8_t> in;
272   } kTests[] = {
273       {true, CBS_ASN1_SEQUENCE, {0x30, 0}},
274       {true, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 4, {0xa4, 0}},
275       {true, CBS_ASN1_APPLICATION | 30, {0x5e, 0}},
276       {true, CBS_ASN1_APPLICATION | 31, {0x5f, 0x1f, 0}},
277       {true, CBS_ASN1_APPLICATION | 32, {0x5f, 0x20, 0}},
278       {true,
279        CBS_ASN1_PRIVATE | CBS_ASN1_CONSTRUCTED | 0x1fffffff,
280        {0xff, 0x81, 0xff, 0xff, 0xff, 0x7f, 0}},
281       // Tag number fits in |uint32_t| but not |CBS_ASN1_TAG_NUMBER_MASK|.
282       {false, 0, {0xff, 0x82, 0xff, 0xff, 0xff, 0x7f, 0}},
283       // Tag number does not fit in |uint32_t|.
284       {false, 0, {0xff, 0x90, 0x80, 0x80, 0x80, 0, 0}},
285       // Tag number is not minimally-encoded
286       {false, 0, {0x5f, 0x80, 0x1f, 0}},
287       // Tag number should have used short form.
288       {false, 0, {0x5f, 0x80, 0x1e, 0}},
289   };
290   for (const auto &t : kTests) {
291     SCOPED_TRACE(Bytes(t.in));
292     CBS_ASN1_TAG tag;
293     CBS cbs, child;
294     CBS_init(&cbs, t.in.data(), t.in.size());
295     ASSERT_EQ(t.ok, !!CBS_get_any_asn1(&cbs, &child, &tag));
296     if (t.ok) {
297       EXPECT_EQ(t.tag, tag);
298       EXPECT_EQ(0u, CBS_len(&child));
299       EXPECT_EQ(0u, CBS_len(&cbs));
300 
301       CBS_init(&cbs, t.in.data(), t.in.size());
302       EXPECT_TRUE(CBS_peek_asn1_tag(&cbs, t.tag));
303       EXPECT_FALSE(CBS_peek_asn1_tag(&cbs, t.tag + 1));
304 
305       EXPECT_TRUE(CBS_get_asn1(&cbs, &child, t.tag));
306       EXPECT_EQ(0u, CBS_len(&child));
307       EXPECT_EQ(0u, CBS_len(&cbs));
308 
309       CBS_init(&cbs, t.in.data(), t.in.size());
310       EXPECT_FALSE(CBS_get_asn1(&cbs, &child, t.tag + 1));
311     }
312   }
313 }
314 
TEST(CBSTest,GetOptionalASN1Bool)315 TEST(CBSTest, GetOptionalASN1Bool) {
316   static const uint8_t kTrue[] = {0x0a, 3, CBS_ASN1_BOOLEAN, 1, 0xff};
317   static const uint8_t kFalse[] = {0x0a, 3, CBS_ASN1_BOOLEAN, 1, 0x00};
318   static const uint8_t kInvalid[] = {0x0a, 3, CBS_ASN1_BOOLEAN, 1, 0x01};
319 
320   CBS data;
321   CBS_init(&data, NULL, 0);
322   int val = 2;
323   ASSERT_TRUE(CBS_get_optional_asn1_bool(&data, &val, 0x0a, 0));
324   EXPECT_EQ(0, val);
325 
326   CBS_init(&data, kTrue, sizeof(kTrue));
327   val = 2;
328   ASSERT_TRUE(CBS_get_optional_asn1_bool(&data, &val, 0x0a, 0));
329   EXPECT_EQ(1, val);
330 
331   CBS_init(&data, kFalse, sizeof(kFalse));
332   val = 2;
333   ASSERT_TRUE(CBS_get_optional_asn1_bool(&data, &val, 0x0a, 1));
334   EXPECT_EQ(0, val);
335 
336   CBS_init(&data, kInvalid, sizeof(kInvalid));
337   EXPECT_FALSE(CBS_get_optional_asn1_bool(&data, &val, 0x0a, 1));
338 }
339 
340 // Test that CBB_init may be used on an uninitialized input.
TEST(CBBTest,InitUninitialized)341 TEST(CBBTest, InitUninitialized) {
342   CBB cbb;
343   ASSERT_TRUE(CBB_init(&cbb, 100));
344   CBB_cleanup(&cbb);
345 }
346 
TEST(CBBTest,Basic)347 TEST(CBBTest, Basic) {
348   static const uint8_t kExpected[] = {
349       0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
350       0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
351       0x03, 0x02, 0x0a, 0x09, 0x08, 0x07, 0x12, 0x11, 0x10, 0x0f,
352       0x0e, 0x0d, 0x0c, 0x0b, 0x00, 0x00, 0x00, 0x00};
353   uint8_t *buf;
354   size_t buf_len;
355 
356   bssl::ScopedCBB cbb;
357   ASSERT_TRUE(CBB_init(cbb.get(), 100));
358   cbb.Reset();
359 
360   ASSERT_TRUE(CBB_init(cbb.get(), 0));
361   ASSERT_TRUE(CBB_add_zeros(cbb.get(), 0));
362   ASSERT_TRUE(CBB_add_u8(cbb.get(), 1));
363   ASSERT_TRUE(CBB_add_u16(cbb.get(), 0x203));
364   ASSERT_TRUE(CBB_add_u24(cbb.get(), 0x40506));
365   ASSERT_TRUE(CBB_add_u32(cbb.get(), 0x708090a));
366   ASSERT_TRUE(CBB_add_u64(cbb.get(), 0xb0c0d0e0f101112));
367   ASSERT_TRUE(CBB_add_bytes(cbb.get(), (const uint8_t *)"\x13\x14", 2));
368   ASSERT_TRUE(CBB_add_u16le(cbb.get(), 0x203));
369   ASSERT_TRUE(CBB_add_u32le(cbb.get(), 0x708090a));
370   ASSERT_TRUE(CBB_add_u64le(cbb.get(), 0xb0c0d0e0f101112));
371   ASSERT_TRUE(CBB_add_zeros(cbb.get(), 4));
372   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
373 
374   bssl::UniquePtr<uint8_t> scoper(buf);
375   EXPECT_EQ(Bytes(kExpected), Bytes(buf, buf_len));
376 }
377 
TEST(CBBTest,Fixed)378 TEST(CBBTest, Fixed) {
379   CBB cbb;
380   uint8_t buf[1];
381   uint8_t *out_buf;
382   size_t out_size;
383 
384   ASSERT_TRUE(CBB_init_fixed(&cbb, NULL, 0));
385   ASSERT_TRUE(CBB_finish(&cbb, &out_buf, &out_size));
386   EXPECT_EQ(NULL, out_buf);
387   EXPECT_EQ(0u, out_size);
388 
389   ASSERT_TRUE(CBB_init_fixed(&cbb, buf, 1));
390   ASSERT_TRUE(CBB_add_u8(&cbb, 1));
391   ASSERT_TRUE(CBB_finish(&cbb, &out_buf, &out_size));
392   EXPECT_EQ(buf, out_buf);
393   EXPECT_EQ(1u, out_size);
394   EXPECT_EQ(1u, buf[0]);
395 
396   ASSERT_TRUE(CBB_init_fixed(&cbb, buf, 1));
397   ASSERT_TRUE(CBB_add_u8(&cbb, 1));
398   EXPECT_FALSE(CBB_add_u8(&cbb, 2));
399   // We do not need |CBB_cleanup| or |bssl::ScopedCBB| here because a fixed
400   // |CBB| has no allocations. Leak-checking tools will confirm there was
401   // nothing to clean up.
402 
403   // However, it should be harmless to call |CBB_cleanup|.
404   CBB cbb2;
405   ASSERT_TRUE(CBB_init_fixed(&cbb2, buf, 1));
406   ASSERT_TRUE(CBB_add_u8(&cbb2, 1));
407   EXPECT_FALSE(CBB_add_u8(&cbb2, 2));
408   CBB_cleanup(&cbb2);
409 }
410 
411 // Test that calling CBB_finish on a child does nothing.
TEST(CBBTest,FinishChild)412 TEST(CBBTest, FinishChild) {
413   CBB child;
414   uint8_t *out_buf;
415   size_t out_size;
416 
417   bssl::ScopedCBB cbb;
418   ASSERT_TRUE(CBB_init(cbb.get(), 16));
419   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &child));
420 
421   EXPECT_FALSE(CBB_finish(&child, &out_buf, &out_size));
422 
423   ASSERT_TRUE(CBB_finish(cbb.get(), &out_buf, &out_size));
424   bssl::UniquePtr<uint8_t> scoper(out_buf);
425   ASSERT_EQ(1u, out_size);
426   EXPECT_EQ(0u, out_buf[0]);
427 }
428 
TEST(CBBTest,Prefixed)429 TEST(CBBTest, Prefixed) {
430   static const uint8_t kExpected[] = {0, 1, 1, 0, 2, 2, 3, 0, 0, 3,
431                                       4, 5, 6, 5, 4, 1, 0, 1, 2};
432   uint8_t *buf;
433   size_t buf_len;
434   bssl::ScopedCBB cbb;
435   CBB contents, inner_contents, inner_inner_contents;
436   ASSERT_TRUE(CBB_init(cbb.get(), 0));
437   EXPECT_EQ(0u, CBB_len(cbb.get()));
438   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
439   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
440   ASSERT_TRUE(CBB_add_u8(&contents, 1));
441   EXPECT_EQ(1u, CBB_len(&contents));
442   ASSERT_TRUE(CBB_flush(cbb.get()));
443   EXPECT_EQ(3u, CBB_len(cbb.get()));
444   ASSERT_TRUE(CBB_add_u16_length_prefixed(cbb.get(), &contents));
445   ASSERT_TRUE(CBB_add_u16(&contents, 0x203));
446   ASSERT_TRUE(CBB_add_u24_length_prefixed(cbb.get(), &contents));
447   ASSERT_TRUE(CBB_add_u24(&contents, 0x40506));
448   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
449   ASSERT_TRUE(CBB_add_u8_length_prefixed(&contents, &inner_contents));
450   ASSERT_TRUE(CBB_add_u8(&inner_contents, 1));
451   ASSERT_TRUE(
452       CBB_add_u16_length_prefixed(&inner_contents, &inner_inner_contents));
453   ASSERT_TRUE(CBB_add_u8(&inner_inner_contents, 2));
454   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
455 
456   bssl::UniquePtr<uint8_t> scoper(buf);
457   EXPECT_EQ(Bytes(kExpected), Bytes(buf, buf_len));
458 }
459 
TEST(CBBTest,DiscardChild)460 TEST(CBBTest, DiscardChild) {
461   bssl::ScopedCBB cbb;
462   CBB contents, inner_contents, inner_inner_contents;
463 
464   ASSERT_TRUE(CBB_init(cbb.get(), 0));
465   ASSERT_TRUE(CBB_add_u8(cbb.get(), 0xaa));
466 
467   // Discarding |cbb|'s children preserves the byte written.
468   CBB_discard_child(cbb.get());
469 
470   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
471   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
472   ASSERT_TRUE(CBB_add_u8(&contents, 0xbb));
473   ASSERT_TRUE(CBB_add_u16_length_prefixed(cbb.get(), &contents));
474   ASSERT_TRUE(CBB_add_u16(&contents, 0xcccc));
475   ASSERT_TRUE(CBB_add_u24_length_prefixed(cbb.get(), &contents));
476   ASSERT_TRUE(CBB_add_u24(&contents, 0xdddddd));
477   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
478   ASSERT_TRUE(CBB_add_u8(&contents, 0xff));
479   ASSERT_TRUE(CBB_add_u8_length_prefixed(&contents, &inner_contents));
480   ASSERT_TRUE(CBB_add_u8(&inner_contents, 0x42));
481   ASSERT_TRUE(
482       CBB_add_u16_length_prefixed(&inner_contents, &inner_inner_contents));
483   ASSERT_TRUE(CBB_add_u8(&inner_inner_contents, 0x99));
484 
485   // Discard everything from |inner_contents| down.
486   CBB_discard_child(&contents);
487 
488   uint8_t *buf;
489   size_t buf_len;
490   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
491   bssl::UniquePtr<uint8_t> scoper(buf);
492 
493   static const uint8_t kExpected[] = {
494         0xaa,
495         0,
496         1, 0xbb,
497         0, 2, 0xcc, 0xcc,
498         0, 0, 3, 0xdd, 0xdd, 0xdd,
499         1, 0xff,
500   };
501   EXPECT_EQ(Bytes(kExpected), Bytes(buf, buf_len));
502 }
503 
TEST(CBBTest,Misuse)504 TEST(CBBTest, Misuse) {
505   bssl::ScopedCBB cbb;
506   CBB child, contents;
507   uint8_t *buf;
508   size_t buf_len;
509 
510   ASSERT_TRUE(CBB_init(cbb.get(), 0));
511   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &child));
512   ASSERT_TRUE(CBB_add_u8(&child, 1));
513   ASSERT_TRUE(CBB_add_u8(cbb.get(), 2));
514 
515   // Since we wrote to |cbb|, |child| is now invalid and attempts to write to
516   // it should fail.
517   EXPECT_FALSE(CBB_add_u8(&child, 1));
518   EXPECT_FALSE(CBB_add_u16(&child, 1));
519   EXPECT_FALSE(CBB_add_u24(&child, 1));
520   EXPECT_FALSE(CBB_add_u8_length_prefixed(&child, &contents));
521   EXPECT_FALSE(CBB_add_u16_length_prefixed(&child, &contents));
522   EXPECT_FALSE(CBB_add_asn1(&child, &contents, 1));
523   EXPECT_FALSE(CBB_add_bytes(&child, (const uint8_t*) "a", 1));
524 
525   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
526   bssl::UniquePtr<uint8_t> scoper(buf);
527 
528   EXPECT_EQ(Bytes("\x01\x01\x02"), Bytes(buf, buf_len));
529 }
530 
TEST(CBBTest,ASN1)531 TEST(CBBTest, ASN1) {
532   static const uint8_t kExpected[] = {
533       // SEQUENCE { 1 2 3 }
534       0x30, 3, 1, 2, 3,
535       // [4 CONSTRUCTED] { 4 5 6 }
536       0xa4, 3, 4, 5, 6,
537       // [APPLICATION 30 PRIMITIVE] { 7 8 9 }
538       0x5e, 3, 7, 8, 9,
539       // [APPLICATION 31 PRIMITIVE] { 10 11 12 }
540       0x5f, 0x1f, 3, 10, 11, 12,
541       // [PRIVATE 2^29-1 CONSTRUCTED] { 13 14 15 }
542       0xff, 0x81, 0xff, 0xff, 0xff, 0x7f, 3, 13, 14, 15,
543   };
544   uint8_t *buf;
545   size_t buf_len;
546   bssl::ScopedCBB cbb;
547   CBB contents, inner_contents;
548 
549   ASSERT_TRUE(CBB_init(cbb.get(), 0));
550   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &contents, CBS_ASN1_SEQUENCE));
551   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x01\x02\x03", 3));
552   ASSERT_TRUE(
553       CBB_add_asn1(cbb.get(), &contents,
554                    CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 4));
555   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x04\x05\x06", 3));
556   ASSERT_TRUE(
557       CBB_add_asn1(cbb.get(), &contents,
558                    CBS_ASN1_APPLICATION | 30));
559   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x07\x08\x09", 3));
560   ASSERT_TRUE(
561       CBB_add_asn1(cbb.get(), &contents,
562                    CBS_ASN1_APPLICATION | 31));
563   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x0a\x0b\x0c", 3));
564   ASSERT_TRUE(
565       CBB_add_asn1(cbb.get(), &contents,
566                    CBS_ASN1_PRIVATE | CBS_ASN1_CONSTRUCTED | 0x1fffffff));
567   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x0d\x0e\x0f", 3));
568   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
569   bssl::UniquePtr<uint8_t> scoper(buf);
570 
571   EXPECT_EQ(Bytes(kExpected), Bytes(buf, buf_len));
572 
573   std::vector<uint8_t> test_data(100000, 0x42);
574   ASSERT_TRUE(CBB_init(cbb.get(), 0));
575   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &contents, CBS_ASN1_SEQUENCE));
576   ASSERT_TRUE(CBB_add_bytes(&contents, test_data.data(), 130));
577   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
578   scoper.reset(buf);
579 
580   ASSERT_EQ(3u + 130u, buf_len);
581   EXPECT_EQ(Bytes("\x30\x81\x82"), Bytes(buf, 3));
582   EXPECT_EQ(Bytes(test_data.data(), 130), Bytes(buf + 3, 130));
583 
584   ASSERT_TRUE(CBB_init(cbb.get(), 0));
585   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &contents, CBS_ASN1_SEQUENCE));
586   ASSERT_TRUE(CBB_add_bytes(&contents, test_data.data(), 1000));
587   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
588   scoper.reset(buf);
589 
590   ASSERT_EQ(4u + 1000u, buf_len);
591   EXPECT_EQ(Bytes("\x30\x82\x03\xe8"), Bytes(buf, 4));
592   EXPECT_EQ(Bytes(test_data.data(), 1000), Bytes(buf + 4, 1000));
593 
594   ASSERT_TRUE(CBB_init(cbb.get(), 0));
595   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &contents, CBS_ASN1_SEQUENCE));
596   ASSERT_TRUE(CBB_add_asn1(&contents, &inner_contents, CBS_ASN1_SEQUENCE));
597   ASSERT_TRUE(CBB_add_bytes(&inner_contents, test_data.data(), 100000));
598   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
599   scoper.reset(buf);
600 
601   ASSERT_EQ(5u + 5u + 100000u, buf_len);
602   EXPECT_EQ(Bytes("\x30\x83\x01\x86\xa5\x30\x83\x01\x86\xa0"), Bytes(buf, 10));
603   EXPECT_EQ(Bytes(test_data.data(), test_data.size()), Bytes(buf + 10, 100000));
604 }
605 
ExpectBerConvert(const char * name,bssl::Span<const uint8_t> der_expected,bssl::Span<const uint8_t> ber)606 static void ExpectBerConvert(const char *name,
607                              bssl::Span<const uint8_t> der_expected,
608                              bssl::Span<const uint8_t> ber) {
609   SCOPED_TRACE(name);
610   CBS in, out;
611   uint8_t *storage;
612 
613   CBS_init(&in, ber.data(), ber.size());
614   ASSERT_TRUE(CBS_asn1_ber_to_der(&in, &out, &storage));
615   bssl::UniquePtr<uint8_t> scoper(storage);
616 
617   EXPECT_EQ(Bytes(der_expected), Bytes(CBS_data(&out), CBS_len(&out)));
618   if (storage != nullptr) {
619     EXPECT_NE(Bytes(der_expected), Bytes(ber));
620   } else {
621     EXPECT_EQ(Bytes(der_expected), Bytes(ber));
622   }
623 }
624 
TEST(CBSTest,BerConvert)625 TEST(CBSTest, BerConvert) {
626   static const uint8_t kSimpleBER[] = {0x01, 0x01, 0x00};
627 
628   // kNonMinimalLengthBER has a non-minimally encoded length.
629   static const uint8_t kNonMinimalLengthBER[] = {0x02, 0x82, 0x00, 0x01, 0x01};
630   static const uint8_t kNonMinimalLengthDER[] = {0x02, 0x01, 0x01};
631 
632   // kIndefBER contains a SEQUENCE with an indefinite length.
633   static const uint8_t kIndefBER[] = {0x30, 0x80, 0x01, 0x01, 0x02, 0x00, 0x00};
634   static const uint8_t kIndefDER[] = {0x30, 0x03, 0x01, 0x01, 0x02};
635 
636   // kIndefBER2 contains a constructed [APPLICATION 31] with an indefinite
637   // length.
638   static const uint8_t kIndefBER2[] = {0x7f, 0x1f, 0x80, 0x01,
639                                        0x01, 0x02, 0x00, 0x00};
640   static const uint8_t kIndefDER2[] = {0x7f, 0x1f, 0x03, 0x01, 0x01, 0x02};
641 
642   // kOctetStringBER contains an indefinite length OCTET STRING with two parts.
643   // These parts need to be concatenated in DER form.
644   static const uint8_t kOctetStringBER[] = {0x24, 0x80, 0x04, 0x02, 0,    1,
645                                             0x04, 0x02, 2,    3,    0x00, 0x00};
646   static const uint8_t kOctetStringDER[] = {0x04, 0x04, 0, 1, 2, 3};
647 
648   // kNSSBER is part of a PKCS#12 message generated by NSS that uses indefinite
649   // length elements extensively.
650   static const uint8_t kNSSBER[] = {
651       0x30, 0x80, 0x02, 0x01, 0x03, 0x30, 0x80, 0x06, 0x09, 0x2a, 0x86, 0x48,
652       0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x80, 0x24, 0x80, 0x04, 0x04,
653       0x01, 0x02, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x39,
654       0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05,
655       0x00, 0x04, 0x14, 0x84, 0x98, 0xfc, 0x66, 0x33, 0xee, 0xba, 0xe7, 0x90,
656       0xc1, 0xb6, 0xe8, 0x8f, 0xfe, 0x1d, 0xc5, 0xa5, 0x97, 0x93, 0x3e, 0x04,
657       0x10, 0x38, 0x62, 0xc6, 0x44, 0x12, 0xd5, 0x30, 0x00, 0xf8, 0xf2, 0x1b,
658       0xf0, 0x6e, 0x10, 0x9b, 0xb8, 0x02, 0x02, 0x07, 0xd0, 0x00, 0x00,
659   };
660 
661   static const uint8_t kNSSDER[] = {
662       0x30, 0x53, 0x02, 0x01, 0x03, 0x30, 0x13, 0x06, 0x09, 0x2a, 0x86,
663       0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x06, 0x04, 0x04,
664       0x01, 0x02, 0x03, 0x04, 0x30, 0x39, 0x30, 0x21, 0x30, 0x09, 0x06,
665       0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14, 0x84,
666       0x98, 0xfc, 0x66, 0x33, 0xee, 0xba, 0xe7, 0x90, 0xc1, 0xb6, 0xe8,
667       0x8f, 0xfe, 0x1d, 0xc5, 0xa5, 0x97, 0x93, 0x3e, 0x04, 0x10, 0x38,
668       0x62, 0xc6, 0x44, 0x12, 0xd5, 0x30, 0x00, 0xf8, 0xf2, 0x1b, 0xf0,
669       0x6e, 0x10, 0x9b, 0xb8, 0x02, 0x02, 0x07, 0xd0,
670   };
671 
672   // kConstructedStringBER contains a deeply-nested constructed OCTET STRING.
673   // The BER conversion collapses this to one level deep, but not completely.
674   static const uint8_t kConstructedStringBER[] = {
675       0xa0, 0x10, 0x24, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01,
676       0x01, 0x24, 0x06, 0x04, 0x01, 0x02, 0x04, 0x01, 0x03,
677   };
678   static const uint8_t kConstructedStringDER[] = {
679       0xa0, 0x08, 0x04, 0x02, 0x00, 0x01, 0x04, 0x02, 0x02, 0x03,
680   };
681 
682   // kWrappedIndefBER contains indefinite-length SEQUENCE, wrapped
683   // and followed by valid DER. This tests that we correctly identify BER nested
684   // inside DER.
685   //
686   //  SEQUENCE {
687   //    SEQUENCE {
688   //      SEQUENCE indefinite {}
689   //    }
690   //    SEQUENCE {}
691   //  }
692   static const uint8_t kWrappedIndefBER[] = {0x30, 0x08, 0x30, 0x04, 0x30,
693                                              0x80, 0x00, 0x00, 0x30, 0x00};
694   static const uint8_t kWrappedIndefDER[] = {0x30, 0x06, 0x30, 0x02,
695                                              0x30, 0x00, 0x30, 0x00};
696 
697   // kWrappedConstructedStringBER contains a constructed OCTET STRING, wrapped
698   // and followed by valid DER. This tests that we correctly identify BER nested
699   // inside DER.
700   //
701   //  SEQUENCE {
702   //    SEQUENCE {
703   //      [OCTET_STRING CONSTRUCTED] {
704   //        OCTET_STRING {}
705   //      }
706   //    }
707   //    SEQUENCE {}
708   //  }
709   static const uint8_t kWrappedConstructedStringBER[] = {
710       0x30, 0x08, 0x30, 0x04, 0x24, 0x02, 0x04, 0x00, 0x30, 0x00};
711   static const uint8_t kWrappedConstructedStringDER[] = {
712       0x30, 0x06, 0x30, 0x02, 0x04, 0x00, 0x30, 0x00};
713 
714   // kConstructedBitString contains a BER constructed BIT STRING. These are not
715   // supported and thus are left unchanged.
716   static const uint8_t kConstructedBitStringBER[] = {
717       0x23, 0x0a, 0x03, 0x03, 0x00, 0x12, 0x34, 0x03, 0x03, 0x00, 0x56, 0x78};
718 
719   ExpectBerConvert("kSimpleBER", kSimpleBER, kSimpleBER);
720   ExpectBerConvert("kNonMinimalLengthBER", kNonMinimalLengthDER,
721                    kNonMinimalLengthBER);
722   ExpectBerConvert("kIndefBER", kIndefDER, kIndefBER);
723   ExpectBerConvert("kIndefBER2", kIndefDER2, kIndefBER2);
724   ExpectBerConvert("kOctetStringBER", kOctetStringDER, kOctetStringBER);
725   ExpectBerConvert("kNSSBER", kNSSDER, kNSSBER);
726   ExpectBerConvert("kConstructedStringBER", kConstructedStringDER,
727                    kConstructedStringBER);
728   ExpectBerConvert("kConstructedBitStringBER", kConstructedBitStringBER,
729                    kConstructedBitStringBER);
730   ExpectBerConvert("kWrappedIndefBER", kWrappedIndefDER, kWrappedIndefBER);
731   ExpectBerConvert("kWrappedConstructedStringBER", kWrappedConstructedStringDER,
732                    kWrappedConstructedStringBER);
733 
734   // indef_overflow is 200 levels deep of an indefinite-length-encoded SEQUENCE.
735   // This will exceed our recursion limits and fail to be converted.
736   std::vector<uint8_t> indef_overflow;
737   for (int i = 0; i < 200; i++) {
738     indef_overflow.push_back(0x30);
739     indef_overflow.push_back(0x80);
740   }
741   for (int i = 0; i < 200; i++) {
742     indef_overflow.push_back(0x00);
743     indef_overflow.push_back(0x00);
744   }
745   CBS in, out;
746   CBS_init(&in, indef_overflow.data(), indef_overflow.size());
747   uint8_t *storage;
748   ASSERT_FALSE(CBS_asn1_ber_to_der(&in, &out, &storage));
749 }
750 
751 struct BERTest {
752   const char *in_hex;
753   bool ok;
754   bool ber_found;
755   bool indefinite;
756   CBS_ASN1_TAG tag;
757 };
758 
759 static const BERTest kBERTests[] = {
760     // Trivial cases, also valid DER.
761     {"0100", true, false, false, 1},
762     {"020101", true, false, false, 2},
763 
764     // Non-minimally encoded lengths.
765     {"02810101", true, true, false, 2},
766     {"0282000101", true, true, false, 2},
767     {"028300000101", true, true, false, 2},
768     {"02840000000101", true, true, false, 2},
769     // Technically valid BER, but not handled.
770     {"02850000000101", false, false, false, 0},
771 
772     // Indefinite length, but not constructed.
773     {"0280", false, false, false, 0},
774     // Indefinite length.
775     {"2280", true, true, true, CBS_ASN1_CONSTRUCTED | 2},
776     // Indefinite length with multi-byte tag.
777     {"bf1f80", true, true, true,
778      CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 31},
779     // Invalid extended tag zero (X.690 8.1.2.4.2.c)
780     {"3f0000", false, false, false, 0},
781     // Should be a low-number tag form, even in BER.
782     {"1f0100", false, false, false, 0},
783     {"1f4000", true, false, false, 0x40},
784     // Non-minimal tags are invalid, even in BER.
785     {"1f804000", false, false, false, 0},
786 
787     // EOCs and other forms of tag [UNIVERSAL 0] are rejected as elements.
788     {"0000", false, false, false, 0},
789     {"000100", false, false, false, 0},
790     {"00800000", false, false, false, 0},
791     {"2000", false, false, false, 0},
792 };
793 
TEST(CBSTest,BERElementTest)794 TEST(CBSTest, BERElementTest) {
795   for (const auto &test : kBERTests) {
796     SCOPED_TRACE(test.in_hex);
797 
798     std::vector<uint8_t> in_bytes;
799     ASSERT_TRUE(DecodeHex(&in_bytes, test.in_hex));
800     CBS in(in_bytes);
801     CBS out;
802     CBS_ASN1_TAG tag;
803     size_t header_len;
804     int ber_found;
805     int indefinite;
806     int ok = CBS_get_any_ber_asn1_element(&in, &out, &tag, &header_len,
807                                           &ber_found, &indefinite);
808     ASSERT_TRUE((ok == 1) == test.ok);
809     if (!test.ok) {
810       continue;
811     }
812 
813     EXPECT_EQ(test.ber_found ? 1 : 0, ber_found);
814     EXPECT_EQ(test.indefinite ? 1 : 0, indefinite);
815     EXPECT_LE(header_len, in_bytes.size());
816     EXPECT_EQ(CBS_len(&out), in_bytes.size());
817     EXPECT_EQ(CBS_len(&in), 0u);
818     EXPECT_EQ(Bytes(out), Bytes(in_bytes));
819     EXPECT_EQ(tag, test.tag);
820   }
821 }
822 
823 struct ImplicitStringTest {
824   const char *in;
825   size_t in_len;
826   bool ok;
827   const char *out;
828   size_t out_len;
829 };
830 
831 static const ImplicitStringTest kImplicitStringTests[] = {
832     // A properly-encoded string.
833     {"\x80\x03\x61\x61\x61", 5, true, "aaa", 3},
834     // An implicit-tagged string.
835     {"\xa0\x09\x04\x01\x61\x04\x01\x61\x04\x01\x61", 11, true, "aaa", 3},
836     // |CBS_get_asn1_implicit_string| only accepts one level deep of nesting.
837     {"\xa0\x0b\x24\x06\x04\x01\x61\x04\x01\x61\x04\x01\x61", 13, false, nullptr,
838      0},
839     // The outer tag must match.
840     {"\x81\x03\x61\x61\x61", 5, false, nullptr, 0},
841     {"\xa1\x09\x04\x01\x61\x04\x01\x61\x04\x01\x61", 11, false, nullptr, 0},
842     // The inner tag must match.
843     {"\xa1\x09\x0c\x01\x61\x0c\x01\x61\x0c\x01\x61", 11, false, nullptr, 0},
844 };
845 
TEST(CBSTest,ImplicitString)846 TEST(CBSTest, ImplicitString) {
847   for (const auto &test : kImplicitStringTests) {
848     SCOPED_TRACE(Bytes(test.in, test.in_len));
849     uint8_t *storage = nullptr;
850     CBS in, out;
851     CBS_init(&in, reinterpret_cast<const uint8_t *>(test.in), test.in_len);
852     int ok = CBS_get_asn1_implicit_string(&in, &out, &storage,
853                                           CBS_ASN1_CONTEXT_SPECIFIC | 0,
854                                           CBS_ASN1_OCTETSTRING);
855     bssl::UniquePtr<uint8_t> scoper(storage);
856     EXPECT_EQ(test.ok, static_cast<bool>(ok));
857 
858     if (ok) {
859       EXPECT_EQ(Bytes(test.out, test.out_len),
860                 Bytes(CBS_data(&out), CBS_len(&out)));
861     }
862   }
863 }
864 
865 struct ASN1Uint64Test {
866   uint64_t value;
867   const char *encoding;
868   size_t encoding_len;
869 };
870 
871 static const ASN1Uint64Test kASN1Uint64Tests[] = {
872     {0, "\x02\x01\x00", 3},
873     {1, "\x02\x01\x01", 3},
874     {127, "\x02\x01\x7f", 3},
875     {128, "\x02\x02\x00\x80", 4},
876     {0xdeadbeef, "\x02\x05\x00\xde\xad\xbe\xef", 7},
877     {UINT64_C(0x0102030405060708),
878      "\x02\x08\x01\x02\x03\x04\x05\x06\x07\x08", 10},
879     {UINT64_C(0xffffffffffffffff),
880       "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff", 11},
881 };
882 
883 struct ASN1InvalidUint64Test {
884   const char *encoding;
885   size_t encoding_len;
886   bool overflow;
887 };
888 
889 static const ASN1InvalidUint64Test kASN1InvalidUint64Tests[] = {
890     // Bad tag.
891     {"\x03\x01\x00", 3, false},
892     // Empty contents.
893     {"\x02\x00", 2, false},
894     // Negative number.
895     {"\x02\x01\x80", 3, false},
896     // Overflow.
897     {"\x02\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00", 11, true},
898     // Leading zeros.
899     {"\x02\x02\x00\x01", 4, false},
900 };
901 
TEST(CBSTest,ASN1Uint64)902 TEST(CBSTest, ASN1Uint64) {
903   for (const ASN1Uint64Test &test : kASN1Uint64Tests) {
904     SCOPED_TRACE(Bytes(test.encoding, test.encoding_len));
905     SCOPED_TRACE(test.value);
906     CBS cbs;
907     uint64_t value;
908     uint8_t *out;
909     size_t len;
910 
911     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
912     ASSERT_TRUE(CBS_get_asn1_uint64(&cbs, &value));
913     EXPECT_EQ(0u, CBS_len(&cbs));
914     EXPECT_EQ(test.value, value);
915 
916     CBS child;
917     int is_negative;
918     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
919     ASSERT_TRUE(CBS_get_asn1(&cbs, &child, CBS_ASN1_INTEGER));
920     EXPECT_TRUE(CBS_is_valid_asn1_integer(&child, &is_negative));
921     EXPECT_EQ(0, is_negative);
922     EXPECT_TRUE(CBS_is_unsigned_asn1_integer(&child));
923 
924     {
925       bssl::ScopedCBB cbb;
926       ASSERT_TRUE(CBB_init(cbb.get(), 0));
927       ASSERT_TRUE(CBB_add_asn1_uint64(cbb.get(), test.value));
928       ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
929       bssl::UniquePtr<uint8_t> scoper(out);
930       EXPECT_EQ(Bytes(test.encoding, test.encoding_len), Bytes(out, len));
931     }
932 
933     {
934       // Overwrite the tag.
935       bssl::ScopedCBB cbb;
936       ASSERT_TRUE(CBB_init(cbb.get(), 0));
937       ASSERT_TRUE(CBB_add_asn1_uint64_with_tag(cbb.get(), test.value,
938                                                CBS_ASN1_CONTEXT_SPECIFIC | 1));
939       ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
940       bssl::UniquePtr<uint8_t> scoper(out);
941       std::vector<uint8_t> expected(test.encoding,
942                                     test.encoding + test.encoding_len);
943       expected[0] = 0x81;
944       EXPECT_EQ(Bytes(expected), Bytes(out, len));
945     }
946   }
947 
948   for (const ASN1InvalidUint64Test &test : kASN1InvalidUint64Tests) {
949     SCOPED_TRACE(Bytes(test.encoding, test.encoding_len));
950     CBS cbs;
951     uint64_t value;
952 
953     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
954     EXPECT_FALSE(CBS_get_asn1_uint64(&cbs, &value));
955 
956     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
957     CBS child;
958     if (CBS_get_asn1(&cbs, &child, CBS_ASN1_INTEGER)) {
959       EXPECT_EQ(test.overflow, !!CBS_is_unsigned_asn1_integer(&child));
960     }
961   }
962 }
963 
964 struct ASN1Int64Test {
965   int64_t value;
966   const char *encoding;
967   size_t encoding_len;
968 };
969 
970 static const ASN1Int64Test kASN1Int64Tests[] = {
971     {0, "\x02\x01\x00", 3},
972     {1, "\x02\x01\x01", 3},
973     {-1, "\x02\x01\xff", 3},
974     {127, "\x02\x01\x7f", 3},
975     {-127, "\x02\x01\x81", 3},
976     {128, "\x02\x02\x00\x80", 4},
977     {-128, "\x02\x01\x80", 3},
978     {129, "\x02\x02\x00\x81", 4},
979     {-129, "\x02\x02\xff\x7f", 4},
980     {0xdeadbeef, "\x02\x05\x00\xde\xad\xbe\xef", 7},
981     {INT64_C(0x0102030405060708), "\x02\x08\x01\x02\x03\x04\x05\x06\x07\x08",
982      10},
983     {INT64_MIN, "\x02\x08\x80\x00\x00\x00\x00\x00\x00\x00", 10},
984     {INT64_MAX, "\x02\x08\x7f\xff\xff\xff\xff\xff\xff\xff", 10},
985 };
986 
987 struct ASN1InvalidInt64Test {
988   const char *encoding;
989   size_t encoding_len;
990   bool overflow;
991 };
992 
993 static const ASN1InvalidInt64Test kASN1InvalidInt64Tests[] = {
994     // Bad tag.
995     {"\x03\x01\x00", 3, false},
996     // Empty contents.
997     {"\x02\x00", 2, false},
998     // Overflow.
999     {"\x02\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00", 11, true},
1000     // Underflow.
1001     {"\x02\x09\x08\xff\xff\xff\xff\xff\xff\xff\xff", 11, true},
1002     // Leading zeros.
1003     {"\x02\x02\x00\x01", 4, false},
1004     // Leading 0xff.
1005     {"\x02\x02\xff\xff", 4, false},
1006 };
1007 
TEST(CBSTest,ASN1Int64)1008 TEST(CBSTest, ASN1Int64) {
1009   for (const ASN1Int64Test &test : kASN1Int64Tests) {
1010     SCOPED_TRACE(Bytes(test.encoding, test.encoding_len));
1011     SCOPED_TRACE(test.value);
1012     CBS cbs;
1013     int64_t value;
1014     uint8_t *out;
1015     size_t len;
1016 
1017     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
1018     ASSERT_TRUE(CBS_get_asn1_int64(&cbs, &value));
1019     EXPECT_EQ(0u, CBS_len(&cbs));
1020     EXPECT_EQ(test.value, value);
1021 
1022     CBS child;
1023     int is_negative;
1024     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
1025     ASSERT_TRUE(CBS_get_asn1(&cbs, &child, CBS_ASN1_INTEGER));
1026     EXPECT_TRUE(CBS_is_valid_asn1_integer(&child, &is_negative));
1027     EXPECT_EQ(test.value < 0, !!is_negative);
1028     EXPECT_EQ(test.value >= 0, !!CBS_is_unsigned_asn1_integer(&child));
1029 
1030     {
1031       bssl::ScopedCBB cbb;
1032       ASSERT_TRUE(CBB_init(cbb.get(), 0));
1033       ASSERT_TRUE(CBB_add_asn1_int64(cbb.get(), test.value));
1034       ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
1035       bssl::UniquePtr<uint8_t> scoper(out);
1036       EXPECT_EQ(Bytes(test.encoding, test.encoding_len), Bytes(out, len));
1037     }
1038 
1039     {
1040       // Overwrite the tag.
1041       bssl::ScopedCBB cbb;
1042       ASSERT_TRUE(CBB_init(cbb.get(), 0));
1043       ASSERT_TRUE(CBB_add_asn1_int64_with_tag(cbb.get(), test.value,
1044                                               CBS_ASN1_CONTEXT_SPECIFIC | 1));
1045       ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
1046       bssl::UniquePtr<uint8_t> scoper(out);
1047       std::vector<uint8_t> expected(test.encoding,
1048                                     test.encoding + test.encoding_len);
1049       expected[0] = 0x81;
1050       EXPECT_EQ(Bytes(expected), Bytes(out, len));
1051     }
1052   }
1053 
1054   for (const ASN1InvalidInt64Test &test : kASN1InvalidInt64Tests) {
1055     SCOPED_TRACE(Bytes(test.encoding, test.encoding_len));
1056     CBS cbs;
1057     int64_t value;
1058 
1059     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
1060     EXPECT_FALSE(CBS_get_asn1_int64(&cbs, &value));
1061 
1062     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
1063     CBS child;
1064     if (CBS_get_asn1(&cbs, &child, CBS_ASN1_INTEGER)) {
1065       EXPECT_EQ(test.overflow, !!CBS_is_valid_asn1_integer(&child, NULL));
1066     }
1067   }
1068 }
1069 
TEST(CBBTest,Zero)1070 TEST(CBBTest, Zero) {
1071   CBB cbb;
1072   CBB_zero(&cbb);
1073   // Calling |CBB_cleanup| on a zero-state |CBB| must not crash.
1074   CBB_cleanup(&cbb);
1075 }
1076 
TEST(CBBTest,Reserve)1077 TEST(CBBTest, Reserve) {
1078   uint8_t buf[10];
1079   uint8_t *ptr;
1080   size_t len;
1081   bssl::ScopedCBB cbb;
1082   ASSERT_TRUE(CBB_init_fixed(cbb.get(), buf, sizeof(buf)));
1083   // Too large.
1084   EXPECT_FALSE(CBB_reserve(cbb.get(), &ptr, 11));
1085 
1086   cbb.Reset();
1087   ASSERT_TRUE(CBB_init_fixed(cbb.get(), buf, sizeof(buf)));
1088   // Successfully reserve the entire space.
1089   ASSERT_TRUE(CBB_reserve(cbb.get(), &ptr, 10));
1090   EXPECT_EQ(buf, ptr);
1091   // Advancing under the maximum bytes is legal.
1092   ASSERT_TRUE(CBB_did_write(cbb.get(), 5));
1093   ASSERT_TRUE(CBB_finish(cbb.get(), NULL, &len));
1094   EXPECT_EQ(5u, len);
1095 }
1096 
1097 // Test that CBB errors are sticky; once on operation on CBB fails, all
1098 // subsequent ones do.
TEST(CBBTest,StickyError)1099 TEST(CBBTest, StickyError) {
1100   // Write an input that exceeds the limit for its length prefix.
1101   bssl::ScopedCBB cbb;
1102   CBB child;
1103   static const uint8_t kZeros[256] = {0};
1104   ASSERT_TRUE(CBB_init(cbb.get(), 0));
1105   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &child));
1106   ASSERT_TRUE(CBB_add_bytes(&child, kZeros, sizeof(kZeros)));
1107   ASSERT_FALSE(CBB_flush(cbb.get()));
1108 
1109   // All future operations should fail.
1110   uint8_t *ptr;
1111   size_t len;
1112   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
1113   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
1114 
1115   // Write an input that cannot fit in a fixed CBB.
1116   cbb.Reset();
1117   uint8_t buf;
1118   ASSERT_TRUE(CBB_init_fixed(cbb.get(), &buf, 1));
1119   ASSERT_FALSE(CBB_add_bytes(cbb.get(), kZeros, sizeof(kZeros)));
1120 
1121   // All future operations should fail.
1122   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
1123   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
1124 
1125   // Write a u32 that cannot fit in a u24.
1126   cbb.Reset();
1127   ASSERT_TRUE(CBB_init(cbb.get(), 0));
1128   ASSERT_FALSE(CBB_add_u24(cbb.get(), 1u << 24));
1129 
1130   // All future operations should fail.
1131   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
1132   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
1133 }
1134 
TEST(CBSTest,BitString)1135 TEST(CBSTest, BitString) {
1136   static const std::vector<uint8_t> kValidBitStrings[] = {
1137       {0x00},                                      // 0 bits
1138       {0x07, 0x80},                                // 1 bit
1139       {0x04, 0xf0},                                // 4 bits
1140       {0x00, 0xff},                                // 8 bits
1141       {0x06, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0},  // 42 bits
1142   };
1143   for (const auto& test : kValidBitStrings) {
1144     SCOPED_TRACE(Bytes(test.data(), test.size()));
1145     CBS cbs;
1146     CBS_init(&cbs, test.data(), test.size());
1147     EXPECT_TRUE(CBS_is_valid_asn1_bitstring(&cbs));
1148   }
1149 
1150   static const std::vector<uint8_t> kInvalidBitStrings[] = {
1151       // BIT STRINGs always have a leading byte.
1152       std::vector<uint8_t>{},
1153       // It's not possible to take an unused bit off the empty string.
1154       {0x01},
1155       // There can be at most 7 unused bits.
1156       {0x08, 0xff},
1157       {0xff, 0xff},
1158       // All unused bits must be cleared.
1159       {0x06, 0xff, 0xc1},
1160   };
1161   for (const auto& test : kInvalidBitStrings) {
1162     SCOPED_TRACE(Bytes(test.data(), test.size()));
1163     CBS cbs;
1164     CBS_init(&cbs, test.data(), test.size());
1165     EXPECT_FALSE(CBS_is_valid_asn1_bitstring(&cbs));
1166 
1167     // CBS_asn1_bitstring_has_bit returns false on invalid inputs.
1168     EXPECT_FALSE(CBS_asn1_bitstring_has_bit(&cbs, 0));
1169   }
1170 
1171   static const struct {
1172     std::vector<uint8_t> in;
1173     unsigned bit;
1174     bool bit_set;
1175   } kBitTests[] = {
1176       // Basic tests.
1177       {{0x00}, 0, false},
1178       {{0x07, 0x80}, 0, true},
1179       {{0x06, 0x0f, 0x40}, 0, false},
1180       {{0x06, 0x0f, 0x40}, 1, false},
1181       {{0x06, 0x0f, 0x40}, 2, false},
1182       {{0x06, 0x0f, 0x40}, 3, false},
1183       {{0x06, 0x0f, 0x40}, 4, true},
1184       {{0x06, 0x0f, 0x40}, 5, true},
1185       {{0x06, 0x0f, 0x40}, 6, true},
1186       {{0x06, 0x0f, 0x40}, 7, true},
1187       {{0x06, 0x0f, 0x40}, 8, false},
1188       {{0x06, 0x0f, 0x40}, 9, true},
1189       // Out-of-bounds bits return 0.
1190       {{0x06, 0x0f, 0x40}, 10, false},
1191       {{0x06, 0x0f, 0x40}, 15, false},
1192       {{0x06, 0x0f, 0x40}, 16, false},
1193       {{0x06, 0x0f, 0x40}, 1000, false},
1194   };
1195   for (const auto& test : kBitTests) {
1196     SCOPED_TRACE(Bytes(test.in.data(), test.in.size()));
1197     SCOPED_TRACE(test.bit);
1198     CBS cbs;
1199     CBS_init(&cbs, test.in.data(), test.in.size());
1200     EXPECT_EQ(static_cast<int>(test.bit_set),
1201               CBS_asn1_bitstring_has_bit(&cbs, test.bit));
1202   }
1203 }
1204 
TEST(CBBTest,AddOIDFromText)1205 TEST(CBBTest, AddOIDFromText) {
1206   const struct {
1207     const char *text;
1208     std::vector<uint8_t> der;
1209   } kValidOIDs[] = {
1210       // Some valid values.
1211       {"0.0", {0x00}},
1212       {"0.2.3.4", {0x2, 0x3, 0x4}},
1213       {"1.2.3.4", {0x2a, 0x3, 0x4}},
1214       {"2.2.3.4", {0x52, 0x3, 0x4}},
1215       {"1.2.840.113554.4.1.72585",
1216        {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09}},
1217       // Test edge cases around the first component.
1218       {"0.39", {0x27}},
1219       {"1.0", {0x28}},
1220       {"1.39", {0x4f}},
1221       {"2.0", {0x50}},
1222       {"2.1", {0x51}},
1223       {"2.40", {0x78}},
1224       // Edge cases near an overflow.
1225       {"1.2.18446744073709551615",
1226        {0x2a, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}},
1227       {"2.18446744073709551535",
1228        {0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}},
1229   };
1230 
1231   const char *kInvalidTexts[] = {
1232       // Invalid second component.
1233       "0.40",
1234       "1.40",
1235       // Invalid first component.
1236       "3.1",
1237       // The empty string is not an OID.
1238       "",
1239       // No empty components.
1240       ".1.2.3.4.5",
1241       "1..2.3.4.5",
1242       "1.2.3.4.5.",
1243       // There must be at least two components.
1244       "1",
1245       // No extra leading zeros.
1246       "00.1.2.3.4",
1247       "01.1.2.3.4",
1248       // Overflow for both components or 40*A + B.
1249       "1.2.18446744073709551616",
1250       "2.18446744073709551536",
1251   };
1252 
1253   const struct {
1254     std::vector<uint8_t> der;
1255     // If true, |der| is valid but has a component that exceeds 2^64-1.
1256     bool overflow;
1257   } kInvalidDER[] = {
1258       // The empty string is not an OID.
1259       {{}, false},
1260       // Non-minimal representation.
1261       {{0x80, 0x01}, false},
1262       // Unterminated integer.
1263       {{0x01, 0x02, 0x83}, false},
1264       // Overflow. This is the DER representation of
1265       // 1.2.840.113554.4.1.72585.18446744073709551616. (The final value is
1266       // 2^64.)
1267       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09,
1268         0x82, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00},
1269        true},
1270   };
1271 
1272   for (const auto &t : kValidOIDs) {
1273     SCOPED_TRACE(t.text);
1274 
1275     bssl::ScopedCBB cbb;
1276     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1277     ASSERT_TRUE(CBB_add_asn1_oid_from_text(cbb.get(), t.text, strlen(t.text)));
1278     uint8_t *out;
1279     size_t len;
1280     ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
1281     bssl::UniquePtr<uint8_t> free_out(out);
1282     EXPECT_EQ(Bytes(t.der), Bytes(out, len));
1283 
1284     CBS cbs;
1285     CBS_init(&cbs, t.der.data(), t.der.size());
1286     bssl::UniquePtr<char> text(CBS_asn1_oid_to_text(&cbs));
1287     ASSERT_TRUE(text.get());
1288     EXPECT_STREQ(t.text, text.get());
1289 
1290     EXPECT_TRUE(CBS_is_valid_asn1_oid(&cbs));
1291   }
1292 
1293   for (const char *t : kInvalidTexts) {
1294     SCOPED_TRACE(t);
1295     bssl::ScopedCBB cbb;
1296     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1297     EXPECT_FALSE(CBB_add_asn1_oid_from_text(cbb.get(), t, strlen(t)));
1298   }
1299 
1300   for (const auto &t : kInvalidDER) {
1301     SCOPED_TRACE(Bytes(t.der));
1302     CBS cbs;
1303     CBS_init(&cbs, t.der.data(), t.der.size());
1304     bssl::UniquePtr<char> text(CBS_asn1_oid_to_text(&cbs));
1305     EXPECT_FALSE(text);
1306     EXPECT_EQ(t.overflow ? 1 : 0, CBS_is_valid_asn1_oid(&cbs));
1307   }
1308 }
1309 
TEST(CBBTest,FlushASN1SetOf)1310 TEST(CBBTest, FlushASN1SetOf) {
1311   const struct {
1312     std::vector<uint8_t> in, out;
1313   } kValidInputs[] = {
1314     // No elements.
1315     {{}, {}},
1316     // One element.
1317     {{0x30, 0x00}, {0x30, 0x00}},
1318     // Two identical elements.
1319     {{0x30, 0x00, 0x30, 0x00}, {0x30, 0x00, 0x30, 0x00}},
1320     // clang-format off
1321     {{0x30, 0x02, 0x00, 0x00,
1322       0x30, 0x00,
1323       0x01, 0x00,
1324       0x30, 0x02, 0x00, 0x00,
1325       0x30, 0x03, 0x00, 0x00, 0x00,
1326       0x30, 0x00,
1327       0x30, 0x03, 0x00, 0x00, 0x01,
1328       0x30, 0x01, 0x00,
1329       0x01, 0x01, 0x00},
1330      {0x01, 0x00,
1331       0x01, 0x01, 0x00,
1332       0x30, 0x00,
1333       0x30, 0x00,
1334       0x30, 0x01, 0x00,
1335       0x30, 0x02, 0x00, 0x00,
1336       0x30, 0x02, 0x00, 0x00,
1337       0x30, 0x03, 0x00, 0x00, 0x00,
1338       0x30, 0x03, 0x00, 0x00, 0x01}},
1339     // clang-format on
1340   };
1341 
1342   for (const auto &t : kValidInputs) {
1343     SCOPED_TRACE(Bytes(t.in));
1344 
1345     bssl::ScopedCBB cbb;
1346     CBB child;
1347     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1348     ASSERT_TRUE(CBB_add_asn1(cbb.get(), &child, CBS_ASN1_SET));
1349     ASSERT_TRUE(CBB_add_bytes(&child, t.in.data(), t.in.size()));
1350     ASSERT_TRUE(CBB_flush_asn1_set_of(&child));
1351     EXPECT_EQ(Bytes(t.out), Bytes(CBB_data(&child), CBB_len(&child)));
1352 
1353     // Running it again should be idempotent.
1354     ASSERT_TRUE(CBB_flush_asn1_set_of(&child));
1355     EXPECT_EQ(Bytes(t.out), Bytes(CBB_data(&child), CBB_len(&child)));
1356 
1357     // The ASN.1 header remain intact.
1358     ASSERT_TRUE(CBB_flush(cbb.get()));
1359     EXPECT_EQ(0x31, CBB_data(cbb.get())[0]);
1360   }
1361 
1362   const std::vector<uint8_t> kInvalidInputs[] = {
1363     {0x30},
1364     {0x30, 0x01},
1365     {0x30, 0x00, 0x30, 0x00, 0x30, 0x01},
1366   };
1367 
1368   for (const auto &t : kInvalidInputs) {
1369     SCOPED_TRACE(Bytes(t));
1370 
1371     bssl::ScopedCBB cbb;
1372     CBB child;
1373     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1374     ASSERT_TRUE(CBB_add_asn1(cbb.get(), &child, CBS_ASN1_SET));
1375     ASSERT_TRUE(CBB_add_bytes(&child, t.data(), t.size()));
1376     EXPECT_FALSE(CBB_flush_asn1_set_of(&child));
1377   }
1378 }
1379 
1380 template <class T>
LiteralToBytes(const T * str)1381 static std::vector<uint8_t> LiteralToBytes(const T *str) {
1382   std::vector<uint8_t> ret;
1383   for (; *str != 0; str++) {
1384     for (size_t i = 0; i < sizeof(T); i++) {
1385       ret.push_back(static_cast<uint8_t>(*str >> (8 * (sizeof(T) - 1 - i))));
1386     }
1387   }
1388   return ret;
1389 }
1390 
LiteralToCodePoints(const char32_t * str)1391 static std::vector<uint32_t> LiteralToCodePoints(const char32_t *str) {
1392   std::vector<uint32_t> ret;
1393   for (; *str != 0; str++) {
1394     ret.push_back(static_cast<uint32_t>(*str));
1395   }
1396   return ret;
1397 }
1398 
TEST(CBBTest,Unicode)1399 TEST(CBBTest, Unicode) {
1400   struct {
1401     int (*decode)(CBS *, uint32_t *);
1402     int (*encode)(CBB *, uint32_t);
1403     std::vector<uint8_t> in;
1404     std::vector<uint32_t> out;
1405     bool ok;
1406   } kTests[] = {
1407       {CBS_get_utf8, CBB_add_utf8,
1408        // This test string captures all four cases in UTF-8.
1409        LiteralToBytes(u8"Hello, 世界! ¡Hola, ��!"),
1410        LiteralToCodePoints(U"Hello, 世界! ¡Hola, ��!"), true},
1411 
1412       // Some invalid inputs adapted from
1413       // http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
1414       // 2.1  First possible sequence of a certain length. (5- and 6-bit
1415       // sequences no longer exist.)
1416       {CBS_get_utf8, CBB_add_utf8, {0xf8, 0x88, 0x80, 0x80, 0x80}, {}, false},
1417       {CBS_get_utf8,
1418        CBB_add_utf8,
1419        {0xfc, 0x84, 0x80, 0x80, 0x80, 0x80},
1420        {},
1421        false},
1422       // 3.1  Unexpected continuation bytes.
1423       {CBS_get_utf8, CBB_add_utf8, {0x80}, {}, false},
1424       {CBS_get_utf8, CBB_add_utf8, {0xbf}, {}, false},
1425       // 3.2  Lonely start characters.
1426       {CBS_get_utf8, CBB_add_utf8, {0xc0, ' '}, {}, false},
1427       {CBS_get_utf8, CBB_add_utf8, {0xe0, ' '}, {}, false},
1428       {CBS_get_utf8, CBB_add_utf8, {0xf0, ' '}, {}, false},
1429       // 3.3  Sequences with last continuation byte missing
1430       {CBS_get_utf8, CBB_add_utf8, {0xc0}, {}, false},
1431       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x80}, {}, false},
1432       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x80, 0x80}, {}, false},
1433       // Variation of the above with unexpected spaces.
1434       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x80, ' '}, {}, false},
1435       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x80, 0x80, ' '}, {}, false},
1436       // 4.1  Examples of an overlong ASCII character
1437       {CBS_get_utf8, CBB_add_utf8, {0xc0, 0xaf}, {}, false},
1438       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x80, 0xaf}, {}, false},
1439       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x80, 0x80, 0xaf}, {}, false},
1440       // 4.2  Maximum overlong sequences
1441       {CBS_get_utf8, CBB_add_utf8, {0xc1, 0xbf}, {}, false},
1442       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x9f, 0xbf}, {}, false},
1443       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x8f, 0xbf, 0xbf}, {}, false},
1444       // 4.3  Overlong representation of the NUL character
1445       {CBS_get_utf8, CBB_add_utf8, {0xc0, 0x80}, {}, false},
1446       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x80, 0x80}, {}, false},
1447       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x80, 0x80, 0x80}, {}, false},
1448       // 5.1  Single UTF-16 surrogates
1449       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xa0, 0x80}, {}, false},
1450       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xad, 0xbf}, {}, false},
1451       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xae, 0x80}, {}, false},
1452       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xb0, 0x80}, {}, false},
1453       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xbe, 0x80}, {}, false},
1454       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xbf, 0xbf}, {}, false},
1455       // 5.2  Paired UTF-16 surrogates
1456       {CBS_get_utf8,
1457        CBB_add_utf8,
1458        {0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80},
1459        {},
1460        false},
1461       {CBS_get_utf8,
1462        CBB_add_utf8,
1463        {0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf},
1464        {},
1465        false},
1466       {CBS_get_utf8,
1467        CBB_add_utf8,
1468        {0xed, 0xad, 0xbf, 0xed, 0xb0, 0x80},
1469        {},
1470        false},
1471       {CBS_get_utf8,
1472        CBB_add_utf8,
1473        {0xed, 0xad, 0xbf, 0xed, 0xbf, 0xbf},
1474        {},
1475        false},
1476       {CBS_get_utf8,
1477        CBB_add_utf8,
1478        {0xed, 0xae, 0x80, 0xed, 0xb0, 0x80},
1479        {},
1480        false},
1481       {CBS_get_utf8,
1482        CBB_add_utf8,
1483        {0xed, 0xae, 0x80, 0xed, 0xbf, 0xbf},
1484        {},
1485        false},
1486       {CBS_get_utf8,
1487        CBB_add_utf8,
1488        {0xed, 0xaf, 0xbf, 0xed, 0xb0, 0x80},
1489        {},
1490        false},
1491       {CBS_get_utf8,
1492        CBB_add_utf8,
1493        {0xed, 0xaf, 0xbf, 0xed, 0xbf, 0xbf},
1494        {},
1495        false},
1496       // 5.3  Noncharacter code positions
1497       {CBS_get_utf8, CBB_add_utf8, {0xef, 0xbf, 0xbe}, {}, false},
1498       {CBS_get_utf8, CBB_add_utf8, {0xef, 0xbf, 0xbf}, {}, false},
1499       {CBS_get_utf8, CBB_add_utf8, {0xef, 0xb7, 0x90}, {}, false},
1500       {CBS_get_utf8, CBB_add_utf8, {0xef, 0xb7, 0xaf}, {}, false},
1501       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x9f, 0xbf, 0xbe}, {}, false},
1502       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x9f, 0xbf, 0xbf}, {}, false},
1503 
1504       {CBS_get_latin1, CBB_add_latin1, LiteralToBytes("\xa1Hola!"),
1505        LiteralToCodePoints(U"¡Hola!"), true},
1506 
1507       // UCS-2 matches UTF-16 on the BMP.
1508       {CBS_get_ucs2_be, CBB_add_ucs2_be, LiteralToBytes(u"Hello, 世界!"),
1509        LiteralToCodePoints(U"Hello, 世界!"), true},
1510       // It does not support characters beyond the BMP.
1511       {CBS_get_ucs2_be, CBB_add_ucs2_be,
1512        LiteralToBytes(u"Hello, 世界! ¡Hola, ��!"),
1513        LiteralToCodePoints(U"Hello, 世界! ¡Hola, "), false},
1514       // Unpaired surrogates and non-characters are also rejected.
1515       {CBS_get_ucs2_be, CBB_add_ucs2_be, {0xd8, 0x00}, {}, false},
1516       {CBS_get_ucs2_be, CBB_add_ucs2_be, {0xff, 0xfe}, {}, false},
1517 
1518       {CBS_get_utf32_be, CBB_add_utf32_be,
1519        LiteralToBytes(U"Hello, 世界! ¡Hola, ��!"),
1520        LiteralToCodePoints(U"Hello, 世界! ¡Hola, ��!"), true},
1521       // Unpaired surrogates and non-characters are rejected.
1522       {CBS_get_utf32_be, CBB_add_utf32_be, {0x00, 0x00, 0xd8, 0x00}, {}, false},
1523       {CBS_get_utf32_be, CBB_add_utf32_be, {0x00, 0x00, 0xff, 0xfe}, {}, false},
1524 
1525       // Test that the NUL character can be encoded.
1526       {CBS_get_latin1, CBB_add_latin1, {0}, {0}, true},
1527       {CBS_get_utf8, CBB_add_utf8, {0}, {0}, true},
1528       {CBS_get_ucs2_be, CBB_add_ucs2_be, {0, 0}, {0}, true},
1529       {CBS_get_utf32_be, CBB_add_utf32_be, {0, 0, 0, 0}, {0}, true},
1530   };
1531   for (const auto &t : kTests) {
1532     SCOPED_TRACE(Bytes(t.in));
1533 
1534     // Test decoding.
1535     CBS cbs;
1536     CBS_init(&cbs, t.in.data(), t.in.size());
1537     std::vector<uint32_t> out;
1538     bool ok = true;
1539     while (CBS_len(&cbs) != 0) {
1540       uint32_t u;
1541       if (!t.decode(&cbs, &u)) {
1542         ok = false;
1543         break;
1544       }
1545       out.push_back(u);
1546     }
1547     EXPECT_EQ(t.ok, ok);
1548     EXPECT_EQ(t.out, out);
1549 
1550     // Test encoding.
1551     if (t.ok) {
1552       bssl::ScopedCBB cbb;
1553       ASSERT_TRUE(CBB_init(cbb.get(), 0));
1554       for (uint32_t u : t.out) {
1555         ASSERT_TRUE(t.encode(cbb.get(), u));
1556       }
1557       EXPECT_EQ(Bytes(t.in), Bytes(CBB_data(cbb.get()), CBB_len(cbb.get())));
1558     }
1559   }
1560 
1561   static const uint32_t kBadCodePoints[] = {
1562     // Surrogate pairs.
1563     0xd800,
1564     0xdfff,
1565     // Non-characters.
1566     0xfffe,
1567     0xffff,
1568     0xfdd0,
1569     0x1fffe,
1570     0x1ffff,
1571     // Too big.
1572     0x110000,
1573   };
1574   bssl::ScopedCBB cbb;
1575   ASSERT_TRUE(CBB_init(cbb.get(), 0));
1576   for (uint32_t v : kBadCodePoints) {
1577     SCOPED_TRACE(v);
1578     EXPECT_FALSE(CBB_add_utf8(cbb.get(), v));
1579     EXPECT_FALSE(CBB_add_latin1(cbb.get(), v));
1580     EXPECT_FALSE(CBB_add_ucs2_be(cbb.get(), v));
1581     EXPECT_FALSE(CBB_add_utf32_be(cbb.get(), v));
1582   }
1583 
1584   // Additional values that are out of range.
1585   EXPECT_FALSE(CBB_add_latin1(cbb.get(), 0x100));
1586   EXPECT_FALSE(CBB_add_ucs2_be(cbb.get(), 0x10000));
1587 
1588   EXPECT_EQ(1u, CBB_get_utf8_len(0));
1589   EXPECT_EQ(1u, CBB_get_utf8_len(0x7f));
1590   EXPECT_EQ(2u, CBB_get_utf8_len(0x80));
1591   EXPECT_EQ(2u, CBB_get_utf8_len(0x7ff));
1592   EXPECT_EQ(3u, CBB_get_utf8_len(0x800));
1593   EXPECT_EQ(3u, CBB_get_utf8_len(0xffff));
1594   EXPECT_EQ(4u, CBB_get_utf8_len(0x10000));
1595   EXPECT_EQ(4u, CBB_get_utf8_len(0x10ffff));
1596 }
1597 
TEST(CBSTest,BogusTime)1598 TEST(CBSTest, BogusTime) {
1599   static const struct {
1600     const char *timestring;
1601   } kBogusTimeTests[] = {
1602       {""},
1603       {"invalidtimesZ"},
1604       {"Z"},
1605       {"0000"},
1606       {"9999Z"},
1607       {"00000000000000000000000000000Z"},
1608       {"19491231235959"},
1609       {"500101000000.001Z"},
1610       {"500101000000+6"},
1611       {"-1970010100000Z"},
1612       {"7a0101000000Z"},
1613       {"20500101000000-6"},
1614       {"20500101000000.001"},
1615       {"20500229000000Z"},
1616       {"220229000000Z"},
1617       {"20500132000000Z"},
1618       {"220132000000Z"},
1619       {"20500332000000Z"},
1620       {"220332000000Z"},
1621       {"20500532000000Z"},
1622       {"220532000000Z"},
1623       {"20500732000000Z"},
1624       {"220732000000Z"},
1625       {"20500832000000Z"},
1626       {"220832000000Z"},
1627       {"20501032000000Z"},
1628       {"221032000000Z"},
1629       {"20501232000000Z"},
1630       {"221232000000Z"},
1631       {"20500431000000Z"},
1632       {"220431000000Z"},
1633       {"20500631000000Z"},
1634       {"220631000000Z"},
1635       {"20500931000000Z"},
1636       {"220931000000Z"},
1637       {"20501131000000Z"},
1638       {"221131000000Z"},
1639       {"20501100000000Z"},
1640       {"221100000000Z"},
1641       {"19500101000000+0600"},
1642   };
1643   for (const auto &t : kBogusTimeTests) {
1644     SCOPED_TRACE(t.timestring);
1645     CBS cbs;
1646     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1647     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1648                                             /*allow_timezone_offset=*/0));
1649     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1650   }
1651   static const struct {
1652     const char *timestring;
1653   } kUTCTZTests[] = {
1654       {"480711220333-0700"},
1655       {"140704000000-0700"},
1656       {"480222202332-0500"},
1657       {"480726113216-0000"},
1658       {"480726113216-2359"},
1659   };
1660   for (const auto &t : kUTCTZTests) {
1661     SCOPED_TRACE(t.timestring);
1662     CBS cbs;
1663     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1664     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1665                                             /*allow_timezone_offset=*/0));
1666     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1667                                             /*allow_timezone_offset=*/1));
1668     EXPECT_TRUE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1669     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/0));
1670   }
1671   static const struct {
1672     const char *timestring;
1673   } kBogusUTCTZTests[] = {
1674       {"480711220333-0160"},
1675       {"140704000000-9999"},
1676       {"480222202332-2400"},
1677   };
1678   for (const auto &t : kBogusUTCTZTests) {
1679     SCOPED_TRACE(t.timestring);
1680     CBS cbs;
1681     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1682     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1683                                             /*allow_timezone_offset=*/0));
1684     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1685   }
1686   static const struct {
1687     const char *timestring;
1688   } kGenTZTests[] = {
1689       {"20480711220333-0000"},
1690       {"20140704000000-0100"},
1691       {"20460311174630-0300"},
1692       {"20140704000000-2359"},
1693   };
1694   for (const auto &t : kGenTZTests) {
1695     SCOPED_TRACE(t.timestring);
1696     CBS cbs;
1697     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1698     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1699                                             /*allow_timezone_offset=*/0));
1700     EXPECT_TRUE(CBS_parse_generalized_time(&cbs, NULL,
1701                                            /*allow_timezone_offset=*/1));
1702     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1703     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/0));
1704   }
1705   static const struct {
1706     const char *timestring;
1707   } kBogusGenTZTests[] = {
1708       {"20480222202332-2400"},
1709       {"20140704000000-9999"},
1710       {"20480726113216-0160"},
1711   };
1712   for (const auto &t : kBogusGenTZTests) {
1713     SCOPED_TRACE(t.timestring);
1714     CBS cbs;
1715     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1716     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1717                                             /*allow_timezone_offset=*/0));
1718     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1719   }
1720 }
1721 
TEST(CBSTest,GetU64Decimal)1722 TEST(CBSTest, GetU64Decimal) {
1723   const struct {
1724     uint64_t val;
1725     const char *text;
1726   } kTests[] = {
1727       {0, "0"},
1728       {1, "1"},
1729       {123456, "123456"},
1730       // 2^64 - 1
1731       {UINT64_C(18446744073709551615), "18446744073709551615"},
1732   };
1733   for (const auto &t : kTests) {
1734     SCOPED_TRACE(t.text);
1735     CBS cbs;
1736     CBS_init(&cbs, reinterpret_cast<const uint8_t*>(t.text), strlen(t.text));
1737     uint64_t v;
1738     ASSERT_TRUE(CBS_get_u64_decimal(&cbs, &v));
1739     EXPECT_EQ(v, t.val);
1740     EXPECT_EQ(CBS_data(&cbs),
1741               reinterpret_cast<const uint8_t *>(t.text) + strlen(t.text));
1742     EXPECT_EQ(CBS_len(&cbs), 0u);
1743 
1744     std::string str(t.text);
1745     str += "Z";
1746     CBS_init(&cbs, reinterpret_cast<const uint8_t *>(str.data()), str.size());
1747     ASSERT_TRUE(CBS_get_u64_decimal(&cbs, &v));
1748     EXPECT_EQ(v, t.val);
1749     EXPECT_EQ(CBS_data(&cbs),
1750               reinterpret_cast<const uint8_t *>(str.data()) + strlen(t.text));
1751     EXPECT_EQ(CBS_len(&cbs), 1u);
1752   }
1753 
1754   static const char *kInvalidTests[] = {
1755       "",
1756       "nope",
1757       "-1",
1758       // 2^64
1759       "18446744073709551616",
1760       // Overflows at multiplying by 10.
1761       "18446744073709551620",
1762   };
1763   for (const char *invalid : kInvalidTests) {
1764     SCOPED_TRACE(invalid);
1765     CBS cbs;
1766     CBS_init(&cbs, reinterpret_cast<const uint8_t *>(invalid), strlen(invalid));
1767     uint64_t v;
1768     EXPECT_FALSE(CBS_get_u64_decimal(&cbs, &v));
1769   }
1770 }
1771