• 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   // kConstructedBitString contains a BER constructed BIT STRING. These are not
683   // supported and thus are left unchanged.
684   static const uint8_t kConstructedBitStringBER[] = {
685       0x23, 0x0a, 0x03, 0x03, 0x00, 0x12, 0x34, 0x03, 0x03, 0x00, 0x56, 0x78};
686 
687   ExpectBerConvert("kSimpleBER", kSimpleBER, kSimpleBER);
688   ExpectBerConvert("kNonMinimalLengthBER", kNonMinimalLengthDER,
689                    kNonMinimalLengthBER);
690   ExpectBerConvert("kIndefBER", kIndefDER, kIndefBER);
691   ExpectBerConvert("kIndefBER2", kIndefDER2, kIndefBER2);
692   ExpectBerConvert("kOctetStringBER", kOctetStringDER, kOctetStringBER);
693   ExpectBerConvert("kNSSBER", kNSSDER, kNSSBER);
694   ExpectBerConvert("kConstructedStringBER", kConstructedStringDER,
695                    kConstructedStringBER);
696   ExpectBerConvert("kConstructedBitStringBER", kConstructedBitStringBER,
697                    kConstructedBitStringBER);
698 }
699 
700 struct BERTest {
701   const char *in_hex;
702   bool ok;
703   bool ber_found;
704   bool indefinite;
705   CBS_ASN1_TAG tag;
706 };
707 
708 static const BERTest kBERTests[] = {
709     // Trivial cases, also valid DER.
710     {"0100", true, false, false, 1},
711     {"020101", true, false, false, 2},
712 
713     // Non-minimally encoded lengths.
714     {"02810101", true, true, false, 2},
715     {"0282000101", true, true, false, 2},
716     {"028300000101", true, true, false, 2},
717     {"02840000000101", true, true, false, 2},
718     // Technically valid BER, but not handled.
719     {"02850000000101", false, false, false, 0},
720 
721     // Indefinite length, but not constructed.
722     {"0280", false, false, false, 0},
723     // Indefinite length.
724     {"2280", true, true, true, CBS_ASN1_CONSTRUCTED | 2},
725     // Indefinite length with multi-byte tag.
726     {"bf1f80", true, true, true,
727      CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 31},
728     // Invalid extended tag zero (X.690 8.1.2.4.2.c)
729     {"3f0000", false, false, false, 0},
730     // Should be a low-number tag form, even in BER.
731     {"1f0100", false, false, false, 0},
732     {"1f4000", true, false, false, 0x40},
733     // Non-minimal tags are invalid, even in BER.
734     {"1f804000", false, false, false, 0},
735 
736     // EOCs and other forms of tag [UNIVERSAL 0] are rejected as elements.
737     {"0000", false, false, false, 0},
738     {"000100", false, false, false, 0},
739     {"00800000", false, false, false, 0},
740     {"2000", false, false, false, 0},
741 };
742 
TEST(CBSTest,BERElementTest)743 TEST(CBSTest, BERElementTest) {
744   for (const auto &test : kBERTests) {
745     SCOPED_TRACE(test.in_hex);
746 
747     std::vector<uint8_t> in_bytes;
748     ASSERT_TRUE(DecodeHex(&in_bytes, test.in_hex));
749     CBS in(in_bytes);
750     CBS out;
751     CBS_ASN1_TAG tag;
752     size_t header_len;
753     int ber_found;
754     int indefinite;
755     int ok = CBS_get_any_ber_asn1_element(&in, &out, &tag, &header_len,
756                                           &ber_found, &indefinite);
757     ASSERT_TRUE((ok == 1) == test.ok);
758     if (!test.ok) {
759       continue;
760     }
761 
762     EXPECT_EQ(test.ber_found ? 1 : 0, ber_found);
763     EXPECT_EQ(test.indefinite ? 1 : 0, indefinite);
764     EXPECT_LE(header_len, in_bytes.size());
765     EXPECT_EQ(CBS_len(&out), in_bytes.size());
766     EXPECT_EQ(CBS_len(&in), 0u);
767     EXPECT_EQ(Bytes(out), Bytes(in_bytes));
768     EXPECT_EQ(tag, test.tag);
769   }
770 }
771 
772 struct ImplicitStringTest {
773   const char *in;
774   size_t in_len;
775   bool ok;
776   const char *out;
777   size_t out_len;
778 };
779 
780 static const ImplicitStringTest kImplicitStringTests[] = {
781     // A properly-encoded string.
782     {"\x80\x03\x61\x61\x61", 5, true, "aaa", 3},
783     // An implicit-tagged string.
784     {"\xa0\x09\x04\x01\x61\x04\x01\x61\x04\x01\x61", 11, true, "aaa", 3},
785     // |CBS_get_asn1_implicit_string| only accepts one level deep of nesting.
786     {"\xa0\x0b\x24\x06\x04\x01\x61\x04\x01\x61\x04\x01\x61", 13, false, nullptr,
787      0},
788     // The outer tag must match.
789     {"\x81\x03\x61\x61\x61", 5, false, nullptr, 0},
790     {"\xa1\x09\x04\x01\x61\x04\x01\x61\x04\x01\x61", 11, false, nullptr, 0},
791     // The inner tag must match.
792     {"\xa1\x09\x0c\x01\x61\x0c\x01\x61\x0c\x01\x61", 11, false, nullptr, 0},
793 };
794 
TEST(CBSTest,ImplicitString)795 TEST(CBSTest, ImplicitString) {
796   for (const auto &test : kImplicitStringTests) {
797     SCOPED_TRACE(Bytes(test.in, test.in_len));
798     uint8_t *storage = nullptr;
799     CBS in, out;
800     CBS_init(&in, reinterpret_cast<const uint8_t *>(test.in), test.in_len);
801     int ok = CBS_get_asn1_implicit_string(&in, &out, &storage,
802                                           CBS_ASN1_CONTEXT_SPECIFIC | 0,
803                                           CBS_ASN1_OCTETSTRING);
804     bssl::UniquePtr<uint8_t> scoper(storage);
805     EXPECT_EQ(test.ok, static_cast<bool>(ok));
806 
807     if (ok) {
808       EXPECT_EQ(Bytes(test.out, test.out_len),
809                 Bytes(CBS_data(&out), CBS_len(&out)));
810     }
811   }
812 }
813 
814 struct ASN1Uint64Test {
815   uint64_t value;
816   const char *encoding;
817   size_t encoding_len;
818 };
819 
820 static const ASN1Uint64Test kASN1Uint64Tests[] = {
821     {0, "\x02\x01\x00", 3},
822     {1, "\x02\x01\x01", 3},
823     {127, "\x02\x01\x7f", 3},
824     {128, "\x02\x02\x00\x80", 4},
825     {0xdeadbeef, "\x02\x05\x00\xde\xad\xbe\xef", 7},
826     {UINT64_C(0x0102030405060708),
827      "\x02\x08\x01\x02\x03\x04\x05\x06\x07\x08", 10},
828     {UINT64_C(0xffffffffffffffff),
829       "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff", 11},
830 };
831 
832 struct ASN1InvalidUint64Test {
833   const char *encoding;
834   size_t encoding_len;
835   bool overflow;
836 };
837 
838 static const ASN1InvalidUint64Test kASN1InvalidUint64Tests[] = {
839     // Bad tag.
840     {"\x03\x01\x00", 3, false},
841     // Empty contents.
842     {"\x02\x00", 2, false},
843     // Negative number.
844     {"\x02\x01\x80", 3, false},
845     // Overflow.
846     {"\x02\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00", 11, true},
847     // Leading zeros.
848     {"\x02\x02\x00\x01", 4, false},
849 };
850 
TEST(CBSTest,ASN1Uint64)851 TEST(CBSTest, ASN1Uint64) {
852   for (const ASN1Uint64Test &test : kASN1Uint64Tests) {
853     SCOPED_TRACE(Bytes(test.encoding, test.encoding_len));
854     SCOPED_TRACE(test.value);
855     CBS cbs;
856     uint64_t value;
857     uint8_t *out;
858     size_t len;
859 
860     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
861     ASSERT_TRUE(CBS_get_asn1_uint64(&cbs, &value));
862     EXPECT_EQ(0u, CBS_len(&cbs));
863     EXPECT_EQ(test.value, value);
864 
865     CBS child;
866     int is_negative;
867     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
868     ASSERT_TRUE(CBS_get_asn1(&cbs, &child, CBS_ASN1_INTEGER));
869     EXPECT_TRUE(CBS_is_valid_asn1_integer(&child, &is_negative));
870     EXPECT_EQ(0, is_negative);
871     EXPECT_TRUE(CBS_is_unsigned_asn1_integer(&child));
872 
873     {
874       bssl::ScopedCBB cbb;
875       ASSERT_TRUE(CBB_init(cbb.get(), 0));
876       ASSERT_TRUE(CBB_add_asn1_uint64(cbb.get(), test.value));
877       ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
878       bssl::UniquePtr<uint8_t> scoper(out);
879       EXPECT_EQ(Bytes(test.encoding, test.encoding_len), Bytes(out, len));
880     }
881 
882     {
883       // Overwrite the tag.
884       bssl::ScopedCBB cbb;
885       ASSERT_TRUE(CBB_init(cbb.get(), 0));
886       ASSERT_TRUE(CBB_add_asn1_uint64_with_tag(cbb.get(), test.value,
887                                                CBS_ASN1_CONTEXT_SPECIFIC | 1));
888       ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
889       bssl::UniquePtr<uint8_t> scoper(out);
890       std::vector<uint8_t> expected(test.encoding,
891                                     test.encoding + test.encoding_len);
892       expected[0] = 0x81;
893       EXPECT_EQ(Bytes(expected), Bytes(out, len));
894     }
895   }
896 
897   for (const ASN1InvalidUint64Test &test : kASN1InvalidUint64Tests) {
898     SCOPED_TRACE(Bytes(test.encoding, test.encoding_len));
899     CBS cbs;
900     uint64_t value;
901 
902     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
903     EXPECT_FALSE(CBS_get_asn1_uint64(&cbs, &value));
904 
905     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
906     CBS child;
907     if (CBS_get_asn1(&cbs, &child, CBS_ASN1_INTEGER)) {
908       EXPECT_EQ(test.overflow, !!CBS_is_unsigned_asn1_integer(&child));
909     }
910   }
911 }
912 
913 struct ASN1Int64Test {
914   int64_t value;
915   const char *encoding;
916   size_t encoding_len;
917 };
918 
919 static const ASN1Int64Test kASN1Int64Tests[] = {
920     {0, "\x02\x01\x00", 3},
921     {1, "\x02\x01\x01", 3},
922     {-1, "\x02\x01\xff", 3},
923     {127, "\x02\x01\x7f", 3},
924     {-127, "\x02\x01\x81", 3},
925     {128, "\x02\x02\x00\x80", 4},
926     {-128, "\x02\x01\x80", 3},
927     {129, "\x02\x02\x00\x81", 4},
928     {-129, "\x02\x02\xff\x7f", 4},
929     {0xdeadbeef, "\x02\x05\x00\xde\xad\xbe\xef", 7},
930     {INT64_C(0x0102030405060708), "\x02\x08\x01\x02\x03\x04\x05\x06\x07\x08",
931      10},
932     {INT64_MIN, "\x02\x08\x80\x00\x00\x00\x00\x00\x00\x00", 10},
933     {INT64_MAX, "\x02\x08\x7f\xff\xff\xff\xff\xff\xff\xff", 10},
934 };
935 
936 struct ASN1InvalidInt64Test {
937   const char *encoding;
938   size_t encoding_len;
939   bool overflow;
940 };
941 
942 static const ASN1InvalidInt64Test kASN1InvalidInt64Tests[] = {
943     // Bad tag.
944     {"\x03\x01\x00", 3, false},
945     // Empty contents.
946     {"\x02\x00", 2, false},
947     // Overflow.
948     {"\x02\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00", 11, true},
949     // Underflow.
950     {"\x02\x09\x08\xff\xff\xff\xff\xff\xff\xff\xff", 11, true},
951     // Leading zeros.
952     {"\x02\x02\x00\x01", 4, false},
953     // Leading 0xff.
954     {"\x02\x02\xff\xff", 4, false},
955 };
956 
TEST(CBSTest,ASN1Int64)957 TEST(CBSTest, ASN1Int64) {
958   for (const ASN1Int64Test &test : kASN1Int64Tests) {
959     SCOPED_TRACE(Bytes(test.encoding, test.encoding_len));
960     SCOPED_TRACE(test.value);
961     CBS cbs;
962     int64_t value;
963     uint8_t *out;
964     size_t len;
965 
966     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
967     ASSERT_TRUE(CBS_get_asn1_int64(&cbs, &value));
968     EXPECT_EQ(0u, CBS_len(&cbs));
969     EXPECT_EQ(test.value, value);
970 
971     CBS child;
972     int is_negative;
973     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
974     ASSERT_TRUE(CBS_get_asn1(&cbs, &child, CBS_ASN1_INTEGER));
975     EXPECT_TRUE(CBS_is_valid_asn1_integer(&child, &is_negative));
976     EXPECT_EQ(test.value < 0, !!is_negative);
977     EXPECT_EQ(test.value >= 0, !!CBS_is_unsigned_asn1_integer(&child));
978 
979     {
980       bssl::ScopedCBB cbb;
981       ASSERT_TRUE(CBB_init(cbb.get(), 0));
982       ASSERT_TRUE(CBB_add_asn1_int64(cbb.get(), test.value));
983       ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
984       bssl::UniquePtr<uint8_t> scoper(out);
985       EXPECT_EQ(Bytes(test.encoding, test.encoding_len), Bytes(out, len));
986     }
987 
988     {
989       // Overwrite the tag.
990       bssl::ScopedCBB cbb;
991       ASSERT_TRUE(CBB_init(cbb.get(), 0));
992       ASSERT_TRUE(CBB_add_asn1_int64_with_tag(cbb.get(), test.value,
993                                               CBS_ASN1_CONTEXT_SPECIFIC | 1));
994       ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
995       bssl::UniquePtr<uint8_t> scoper(out);
996       std::vector<uint8_t> expected(test.encoding,
997                                     test.encoding + test.encoding_len);
998       expected[0] = 0x81;
999       EXPECT_EQ(Bytes(expected), Bytes(out, len));
1000     }
1001   }
1002 
1003   for (const ASN1InvalidInt64Test &test : kASN1InvalidInt64Tests) {
1004     SCOPED_TRACE(Bytes(test.encoding, test.encoding_len));
1005     CBS cbs;
1006     int64_t value;
1007 
1008     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
1009     EXPECT_FALSE(CBS_get_asn1_int64(&cbs, &value));
1010 
1011     CBS_init(&cbs, (const uint8_t *)test.encoding, test.encoding_len);
1012     CBS child;
1013     if (CBS_get_asn1(&cbs, &child, CBS_ASN1_INTEGER)) {
1014       EXPECT_EQ(test.overflow, !!CBS_is_valid_asn1_integer(&child, NULL));
1015     }
1016   }
1017 }
1018 
TEST(CBBTest,Zero)1019 TEST(CBBTest, Zero) {
1020   CBB cbb;
1021   CBB_zero(&cbb);
1022   // Calling |CBB_cleanup| on a zero-state |CBB| must not crash.
1023   CBB_cleanup(&cbb);
1024 }
1025 
TEST(CBBTest,Reserve)1026 TEST(CBBTest, Reserve) {
1027   uint8_t buf[10];
1028   uint8_t *ptr;
1029   size_t len;
1030   bssl::ScopedCBB cbb;
1031   ASSERT_TRUE(CBB_init_fixed(cbb.get(), buf, sizeof(buf)));
1032   // Too large.
1033   EXPECT_FALSE(CBB_reserve(cbb.get(), &ptr, 11));
1034 
1035   cbb.Reset();
1036   ASSERT_TRUE(CBB_init_fixed(cbb.get(), buf, sizeof(buf)));
1037   // Successfully reserve the entire space.
1038   ASSERT_TRUE(CBB_reserve(cbb.get(), &ptr, 10));
1039   EXPECT_EQ(buf, ptr);
1040   // Advancing under the maximum bytes is legal.
1041   ASSERT_TRUE(CBB_did_write(cbb.get(), 5));
1042   ASSERT_TRUE(CBB_finish(cbb.get(), NULL, &len));
1043   EXPECT_EQ(5u, len);
1044 }
1045 
1046 // Test that CBB errors are sticky; once on operation on CBB fails, all
1047 // subsequent ones do.
TEST(CBBTest,StickyError)1048 TEST(CBBTest, StickyError) {
1049   // Write an input that exceeds the limit for its length prefix.
1050   bssl::ScopedCBB cbb;
1051   CBB child;
1052   static const uint8_t kZeros[256] = {0};
1053   ASSERT_TRUE(CBB_init(cbb.get(), 0));
1054   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &child));
1055   ASSERT_TRUE(CBB_add_bytes(&child, kZeros, sizeof(kZeros)));
1056   ASSERT_FALSE(CBB_flush(cbb.get()));
1057 
1058   // All future operations should fail.
1059   uint8_t *ptr;
1060   size_t len;
1061   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
1062   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
1063 
1064   // Write an input that cannot fit in a fixed CBB.
1065   cbb.Reset();
1066   uint8_t buf;
1067   ASSERT_TRUE(CBB_init_fixed(cbb.get(), &buf, 1));
1068   ASSERT_FALSE(CBB_add_bytes(cbb.get(), kZeros, sizeof(kZeros)));
1069 
1070   // All future operations should fail.
1071   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
1072   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
1073 
1074   // Write a u32 that cannot fit in a u24.
1075   cbb.Reset();
1076   ASSERT_TRUE(CBB_init(cbb.get(), 0));
1077   ASSERT_FALSE(CBB_add_u24(cbb.get(), 1u << 24));
1078 
1079   // All future operations should fail.
1080   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
1081   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
1082 }
1083 
TEST(CBSTest,BitString)1084 TEST(CBSTest, BitString) {
1085   static const std::vector<uint8_t> kValidBitStrings[] = {
1086       {0x00},                                      // 0 bits
1087       {0x07, 0x80},                                // 1 bit
1088       {0x04, 0xf0},                                // 4 bits
1089       {0x00, 0xff},                                // 8 bits
1090       {0x06, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0},  // 42 bits
1091   };
1092   for (const auto& test : kValidBitStrings) {
1093     SCOPED_TRACE(Bytes(test.data(), test.size()));
1094     CBS cbs;
1095     CBS_init(&cbs, test.data(), test.size());
1096     EXPECT_TRUE(CBS_is_valid_asn1_bitstring(&cbs));
1097   }
1098 
1099   static const std::vector<uint8_t> kInvalidBitStrings[] = {
1100       // BIT STRINGs always have a leading byte.
1101       std::vector<uint8_t>{},
1102       // It's not possible to take an unused bit off the empty string.
1103       {0x01},
1104       // There can be at most 7 unused bits.
1105       {0x08, 0xff},
1106       {0xff, 0xff},
1107       // All unused bits must be cleared.
1108       {0x06, 0xff, 0xc1},
1109   };
1110   for (const auto& test : kInvalidBitStrings) {
1111     SCOPED_TRACE(Bytes(test.data(), test.size()));
1112     CBS cbs;
1113     CBS_init(&cbs, test.data(), test.size());
1114     EXPECT_FALSE(CBS_is_valid_asn1_bitstring(&cbs));
1115 
1116     // CBS_asn1_bitstring_has_bit returns false on invalid inputs.
1117     EXPECT_FALSE(CBS_asn1_bitstring_has_bit(&cbs, 0));
1118   }
1119 
1120   static const struct {
1121     std::vector<uint8_t> in;
1122     unsigned bit;
1123     bool bit_set;
1124   } kBitTests[] = {
1125       // Basic tests.
1126       {{0x00}, 0, false},
1127       {{0x07, 0x80}, 0, true},
1128       {{0x06, 0x0f, 0x40}, 0, false},
1129       {{0x06, 0x0f, 0x40}, 1, false},
1130       {{0x06, 0x0f, 0x40}, 2, false},
1131       {{0x06, 0x0f, 0x40}, 3, false},
1132       {{0x06, 0x0f, 0x40}, 4, true},
1133       {{0x06, 0x0f, 0x40}, 5, true},
1134       {{0x06, 0x0f, 0x40}, 6, true},
1135       {{0x06, 0x0f, 0x40}, 7, true},
1136       {{0x06, 0x0f, 0x40}, 8, false},
1137       {{0x06, 0x0f, 0x40}, 9, true},
1138       // Out-of-bounds bits return 0.
1139       {{0x06, 0x0f, 0x40}, 10, false},
1140       {{0x06, 0x0f, 0x40}, 15, false},
1141       {{0x06, 0x0f, 0x40}, 16, false},
1142       {{0x06, 0x0f, 0x40}, 1000, false},
1143   };
1144   for (const auto& test : kBitTests) {
1145     SCOPED_TRACE(Bytes(test.in.data(), test.in.size()));
1146     SCOPED_TRACE(test.bit);
1147     CBS cbs;
1148     CBS_init(&cbs, test.in.data(), test.in.size());
1149     EXPECT_EQ(static_cast<int>(test.bit_set),
1150               CBS_asn1_bitstring_has_bit(&cbs, test.bit));
1151   }
1152 }
1153 
TEST(CBBTest,AddOIDFromText)1154 TEST(CBBTest, AddOIDFromText) {
1155   const struct {
1156     const char *text;
1157     std::vector<uint8_t> der;
1158   } kValidOIDs[] = {
1159       // Some valid values.
1160       {"0.0", {0x00}},
1161       {"0.2.3.4", {0x2, 0x3, 0x4}},
1162       {"1.2.3.4", {0x2a, 0x3, 0x4}},
1163       {"2.2.3.4", {0x52, 0x3, 0x4}},
1164       {"1.2.840.113554.4.1.72585",
1165        {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09}},
1166       // Test edge cases around the first component.
1167       {"0.39", {0x27}},
1168       {"1.0", {0x28}},
1169       {"1.39", {0x4f}},
1170       {"2.0", {0x50}},
1171       {"2.1", {0x51}},
1172       {"2.40", {0x78}},
1173       // Edge cases near an overflow.
1174       {"1.2.18446744073709551615",
1175        {0x2a, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}},
1176       {"2.18446744073709551535",
1177        {0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}},
1178   };
1179 
1180   const char *kInvalidTexts[] = {
1181       // Invalid second component.
1182       "0.40",
1183       "1.40",
1184       // Invalid first component.
1185       "3.1",
1186       // The empty string is not an OID.
1187       "",
1188       // No empty components.
1189       ".1.2.3.4.5",
1190       "1..2.3.4.5",
1191       "1.2.3.4.5.",
1192       // There must be at least two components.
1193       "1",
1194       // No extra leading zeros.
1195       "00.1.2.3.4",
1196       "01.1.2.3.4",
1197       // Overflow for both components or 40*A + B.
1198       "1.2.18446744073709551616",
1199       "2.18446744073709551536",
1200   };
1201 
1202   const struct {
1203     std::vector<uint8_t> der;
1204     // If true, |der| is valid but has a component that exceeds 2^64-1.
1205     bool overflow;
1206   } kInvalidDER[] = {
1207       // The empty string is not an OID.
1208       {{}, false},
1209       // Non-minimal representation.
1210       {{0x80, 0x01}, false},
1211       // Unterminated integer.
1212       {{0x01, 0x02, 0x83}, false},
1213       // Overflow. This is the DER representation of
1214       // 1.2.840.113554.4.1.72585.18446744073709551616. (The final value is
1215       // 2^64.)
1216       {{0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09,
1217         0x82, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00},
1218        true},
1219   };
1220 
1221   for (const auto &t : kValidOIDs) {
1222     SCOPED_TRACE(t.text);
1223 
1224     bssl::ScopedCBB cbb;
1225     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1226     ASSERT_TRUE(CBB_add_asn1_oid_from_text(cbb.get(), t.text, strlen(t.text)));
1227     uint8_t *out;
1228     size_t len;
1229     ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
1230     bssl::UniquePtr<uint8_t> free_out(out);
1231     EXPECT_EQ(Bytes(t.der), Bytes(out, len));
1232 
1233     CBS cbs;
1234     CBS_init(&cbs, t.der.data(), t.der.size());
1235     bssl::UniquePtr<char> text(CBS_asn1_oid_to_text(&cbs));
1236     ASSERT_TRUE(text.get());
1237     EXPECT_STREQ(t.text, text.get());
1238 
1239     EXPECT_TRUE(CBS_is_valid_asn1_oid(&cbs));
1240   }
1241 
1242   for (const char *t : kInvalidTexts) {
1243     SCOPED_TRACE(t);
1244     bssl::ScopedCBB cbb;
1245     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1246     EXPECT_FALSE(CBB_add_asn1_oid_from_text(cbb.get(), t, strlen(t)));
1247   }
1248 
1249   for (const auto &t : kInvalidDER) {
1250     SCOPED_TRACE(Bytes(t.der));
1251     CBS cbs;
1252     CBS_init(&cbs, t.der.data(), t.der.size());
1253     bssl::UniquePtr<char> text(CBS_asn1_oid_to_text(&cbs));
1254     EXPECT_FALSE(text);
1255     EXPECT_EQ(t.overflow ? 1 : 0, CBS_is_valid_asn1_oid(&cbs));
1256   }
1257 }
1258 
TEST(CBBTest,FlushASN1SetOf)1259 TEST(CBBTest, FlushASN1SetOf) {
1260   const struct {
1261     std::vector<uint8_t> in, out;
1262   } kValidInputs[] = {
1263     // No elements.
1264     {{}, {}},
1265     // One element.
1266     {{0x30, 0x00}, {0x30, 0x00}},
1267     // Two identical elements.
1268     {{0x30, 0x00, 0x30, 0x00}, {0x30, 0x00, 0x30, 0x00}},
1269     // clang-format off
1270     {{0x30, 0x02, 0x00, 0x00,
1271       0x30, 0x00,
1272       0x01, 0x00,
1273       0x30, 0x02, 0x00, 0x00,
1274       0x30, 0x03, 0x00, 0x00, 0x00,
1275       0x30, 0x00,
1276       0x30, 0x03, 0x00, 0x00, 0x01,
1277       0x30, 0x01, 0x00,
1278       0x01, 0x01, 0x00},
1279      {0x01, 0x00,
1280       0x01, 0x01, 0x00,
1281       0x30, 0x00,
1282       0x30, 0x00,
1283       0x30, 0x01, 0x00,
1284       0x30, 0x02, 0x00, 0x00,
1285       0x30, 0x02, 0x00, 0x00,
1286       0x30, 0x03, 0x00, 0x00, 0x00,
1287       0x30, 0x03, 0x00, 0x00, 0x01}},
1288     // clang-format on
1289   };
1290 
1291   for (const auto &t : kValidInputs) {
1292     SCOPED_TRACE(Bytes(t.in));
1293 
1294     bssl::ScopedCBB cbb;
1295     CBB child;
1296     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1297     ASSERT_TRUE(CBB_add_asn1(cbb.get(), &child, CBS_ASN1_SET));
1298     ASSERT_TRUE(CBB_add_bytes(&child, t.in.data(), t.in.size()));
1299     ASSERT_TRUE(CBB_flush_asn1_set_of(&child));
1300     EXPECT_EQ(Bytes(t.out), Bytes(CBB_data(&child), CBB_len(&child)));
1301 
1302     // Running it again should be idempotent.
1303     ASSERT_TRUE(CBB_flush_asn1_set_of(&child));
1304     EXPECT_EQ(Bytes(t.out), Bytes(CBB_data(&child), CBB_len(&child)));
1305 
1306     // The ASN.1 header remain intact.
1307     ASSERT_TRUE(CBB_flush(cbb.get()));
1308     EXPECT_EQ(0x31, CBB_data(cbb.get())[0]);
1309   }
1310 
1311   const std::vector<uint8_t> kInvalidInputs[] = {
1312     {0x30},
1313     {0x30, 0x01},
1314     {0x30, 0x00, 0x30, 0x00, 0x30, 0x01},
1315   };
1316 
1317   for (const auto &t : kInvalidInputs) {
1318     SCOPED_TRACE(Bytes(t));
1319 
1320     bssl::ScopedCBB cbb;
1321     CBB child;
1322     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1323     ASSERT_TRUE(CBB_add_asn1(cbb.get(), &child, CBS_ASN1_SET));
1324     ASSERT_TRUE(CBB_add_bytes(&child, t.data(), t.size()));
1325     EXPECT_FALSE(CBB_flush_asn1_set_of(&child));
1326   }
1327 }
1328 
1329 template <class T>
LiteralToBytes(const T * str)1330 static std::vector<uint8_t> LiteralToBytes(const T *str) {
1331   std::vector<uint8_t> ret;
1332   for (; *str != 0; str++) {
1333     for (size_t i = 0; i < sizeof(T); i++) {
1334       ret.push_back(static_cast<uint8_t>(*str >> (8 * (sizeof(T) - 1 - i))));
1335     }
1336   }
1337   return ret;
1338 }
1339 
LiteralToCodePoints(const char32_t * str)1340 static std::vector<uint32_t> LiteralToCodePoints(const char32_t *str) {
1341   std::vector<uint32_t> ret;
1342   for (; *str != 0; str++) {
1343     ret.push_back(static_cast<uint32_t>(*str));
1344   }
1345   return ret;
1346 }
1347 
TEST(CBBTest,Unicode)1348 TEST(CBBTest, Unicode) {
1349   struct {
1350     int (*decode)(CBS *, uint32_t *);
1351     int (*encode)(CBB *, uint32_t);
1352     std::vector<uint8_t> in;
1353     std::vector<uint32_t> out;
1354     bool ok;
1355   } kTests[] = {
1356       {CBS_get_utf8, CBB_add_utf8,
1357        // This test string captures all four cases in UTF-8.
1358        LiteralToBytes(u8"Hello, 世界! ¡Hola, ��!"),
1359        LiteralToCodePoints(U"Hello, 世界! ¡Hola, ��!"), true},
1360 
1361       // Some invalid inputs adapted from
1362       // http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
1363       // 2.1  First possible sequence of a certain length. (5- and 6-bit
1364       // sequences no longer exist.)
1365       {CBS_get_utf8, CBB_add_utf8, {0xf8, 0x88, 0x80, 0x80, 0x80}, {}, false},
1366       {CBS_get_utf8,
1367        CBB_add_utf8,
1368        {0xfc, 0x84, 0x80, 0x80, 0x80, 0x80},
1369        {},
1370        false},
1371       // 3.1  Unexpected continuation bytes.
1372       {CBS_get_utf8, CBB_add_utf8, {0x80}, {}, false},
1373       {CBS_get_utf8, CBB_add_utf8, {0xbf}, {}, false},
1374       // 3.2  Lonely start characters.
1375       {CBS_get_utf8, CBB_add_utf8, {0xc0, ' '}, {}, false},
1376       {CBS_get_utf8, CBB_add_utf8, {0xe0, ' '}, {}, false},
1377       {CBS_get_utf8, CBB_add_utf8, {0xf0, ' '}, {}, false},
1378       // 3.3  Sequences with last continuation byte missing
1379       {CBS_get_utf8, CBB_add_utf8, {0xc0}, {}, false},
1380       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x80}, {}, false},
1381       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x80, 0x80}, {}, false},
1382       // Variation of the above with unexpected spaces.
1383       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x80, ' '}, {}, false},
1384       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x80, 0x80, ' '}, {}, false},
1385       // 4.1  Examples of an overlong ASCII character
1386       {CBS_get_utf8, CBB_add_utf8, {0xc0, 0xaf}, {}, false},
1387       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x80, 0xaf}, {}, false},
1388       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x80, 0x80, 0xaf}, {}, false},
1389       // 4.2  Maximum overlong sequences
1390       {CBS_get_utf8, CBB_add_utf8, {0xc1, 0xbf}, {}, false},
1391       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x9f, 0xbf}, {}, false},
1392       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x8f, 0xbf, 0xbf}, {}, false},
1393       // 4.3  Overlong representation of the NUL character
1394       {CBS_get_utf8, CBB_add_utf8, {0xc0, 0x80}, {}, false},
1395       {CBS_get_utf8, CBB_add_utf8, {0xe0, 0x80, 0x80}, {}, false},
1396       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x80, 0x80, 0x80}, {}, false},
1397       // 5.1  Single UTF-16 surrogates
1398       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xa0, 0x80}, {}, false},
1399       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xad, 0xbf}, {}, false},
1400       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xae, 0x80}, {}, false},
1401       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xb0, 0x80}, {}, false},
1402       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xbe, 0x80}, {}, false},
1403       {CBS_get_utf8, CBB_add_utf8, {0xed, 0xbf, 0xbf}, {}, false},
1404       // 5.2  Paired UTF-16 surrogates
1405       {CBS_get_utf8,
1406        CBB_add_utf8,
1407        {0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80},
1408        {},
1409        false},
1410       {CBS_get_utf8,
1411        CBB_add_utf8,
1412        {0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf},
1413        {},
1414        false},
1415       {CBS_get_utf8,
1416        CBB_add_utf8,
1417        {0xed, 0xad, 0xbf, 0xed, 0xb0, 0x80},
1418        {},
1419        false},
1420       {CBS_get_utf8,
1421        CBB_add_utf8,
1422        {0xed, 0xad, 0xbf, 0xed, 0xbf, 0xbf},
1423        {},
1424        false},
1425       {CBS_get_utf8,
1426        CBB_add_utf8,
1427        {0xed, 0xae, 0x80, 0xed, 0xb0, 0x80},
1428        {},
1429        false},
1430       {CBS_get_utf8,
1431        CBB_add_utf8,
1432        {0xed, 0xae, 0x80, 0xed, 0xbf, 0xbf},
1433        {},
1434        false},
1435       {CBS_get_utf8,
1436        CBB_add_utf8,
1437        {0xed, 0xaf, 0xbf, 0xed, 0xb0, 0x80},
1438        {},
1439        false},
1440       {CBS_get_utf8,
1441        CBB_add_utf8,
1442        {0xed, 0xaf, 0xbf, 0xed, 0xbf, 0xbf},
1443        {},
1444        false},
1445       // 5.3  Noncharacter code positions
1446       {CBS_get_utf8, CBB_add_utf8, {0xef, 0xbf, 0xbe}, {}, false},
1447       {CBS_get_utf8, CBB_add_utf8, {0xef, 0xbf, 0xbf}, {}, false},
1448       {CBS_get_utf8, CBB_add_utf8, {0xef, 0xb7, 0x90}, {}, false},
1449       {CBS_get_utf8, CBB_add_utf8, {0xef, 0xb7, 0xaf}, {}, false},
1450       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x9f, 0xbf, 0xbe}, {}, false},
1451       {CBS_get_utf8, CBB_add_utf8, {0xf0, 0x9f, 0xbf, 0xbf}, {}, false},
1452 
1453       {CBS_get_latin1, CBB_add_latin1, LiteralToBytes("\xa1Hola!"),
1454        LiteralToCodePoints(U"¡Hola!"), true},
1455 
1456       // UCS-2 matches UTF-16 on the BMP.
1457       {CBS_get_ucs2_be, CBB_add_ucs2_be, LiteralToBytes(u"Hello, 世界!"),
1458        LiteralToCodePoints(U"Hello, 世界!"), true},
1459       // It does not support characters beyond the BMP.
1460       {CBS_get_ucs2_be, CBB_add_ucs2_be,
1461        LiteralToBytes(u"Hello, 世界! ¡Hola, ��!"),
1462        LiteralToCodePoints(U"Hello, 世界! ¡Hola, "), false},
1463       // Unpaired surrogates and non-characters are also rejected.
1464       {CBS_get_ucs2_be, CBB_add_ucs2_be, {0xd8, 0x00}, {}, false},
1465       {CBS_get_ucs2_be, CBB_add_ucs2_be, {0xff, 0xfe}, {}, false},
1466 
1467       {CBS_get_utf32_be, CBB_add_utf32_be,
1468        LiteralToBytes(U"Hello, 世界! ¡Hola, ��!"),
1469        LiteralToCodePoints(U"Hello, 世界! ¡Hola, ��!"), true},
1470       // Unpaired surrogates and non-characters are rejected.
1471       {CBS_get_utf32_be, CBB_add_utf32_be, {0x00, 0x00, 0xd8, 0x00}, {}, false},
1472       {CBS_get_utf32_be, CBB_add_utf32_be, {0x00, 0x00, 0xff, 0xfe}, {}, false},
1473 
1474       // Test that the NUL character can be encoded.
1475       {CBS_get_latin1, CBB_add_latin1, {0}, {0}, true},
1476       {CBS_get_utf8, CBB_add_utf8, {0}, {0}, true},
1477       {CBS_get_ucs2_be, CBB_add_ucs2_be, {0, 0}, {0}, true},
1478       {CBS_get_utf32_be, CBB_add_utf32_be, {0, 0, 0, 0}, {0}, true},
1479   };
1480   for (const auto &t : kTests) {
1481     SCOPED_TRACE(Bytes(t.in));
1482 
1483     // Test decoding.
1484     CBS cbs;
1485     CBS_init(&cbs, t.in.data(), t.in.size());
1486     std::vector<uint32_t> out;
1487     bool ok = true;
1488     while (CBS_len(&cbs) != 0) {
1489       uint32_t u;
1490       if (!t.decode(&cbs, &u)) {
1491         ok = false;
1492         break;
1493       }
1494       out.push_back(u);
1495     }
1496     EXPECT_EQ(t.ok, ok);
1497     EXPECT_EQ(t.out, out);
1498 
1499     // Test encoding.
1500     if (t.ok) {
1501       bssl::ScopedCBB cbb;
1502       ASSERT_TRUE(CBB_init(cbb.get(), 0));
1503       for (uint32_t u : t.out) {
1504         ASSERT_TRUE(t.encode(cbb.get(), u));
1505       }
1506       EXPECT_EQ(Bytes(t.in), Bytes(CBB_data(cbb.get()), CBB_len(cbb.get())));
1507     }
1508   }
1509 
1510   static const uint32_t kBadCodePoints[] = {
1511     // Surrogate pairs.
1512     0xd800,
1513     0xdfff,
1514     // Non-characters.
1515     0xfffe,
1516     0xffff,
1517     0xfdd0,
1518     0x1fffe,
1519     0x1ffff,
1520     // Too big.
1521     0x110000,
1522   };
1523   bssl::ScopedCBB cbb;
1524   ASSERT_TRUE(CBB_init(cbb.get(), 0));
1525   for (uint32_t v : kBadCodePoints) {
1526     SCOPED_TRACE(v);
1527     EXPECT_FALSE(CBB_add_utf8(cbb.get(), v));
1528     EXPECT_FALSE(CBB_add_latin1(cbb.get(), v));
1529     EXPECT_FALSE(CBB_add_ucs2_be(cbb.get(), v));
1530     EXPECT_FALSE(CBB_add_utf32_be(cbb.get(), v));
1531   }
1532 
1533   // Additional values that are out of range.
1534   EXPECT_FALSE(CBB_add_latin1(cbb.get(), 0x100));
1535   EXPECT_FALSE(CBB_add_ucs2_be(cbb.get(), 0x10000));
1536 
1537   EXPECT_EQ(1u, CBB_get_utf8_len(0));
1538   EXPECT_EQ(1u, CBB_get_utf8_len(0x7f));
1539   EXPECT_EQ(2u, CBB_get_utf8_len(0x80));
1540   EXPECT_EQ(2u, CBB_get_utf8_len(0x7ff));
1541   EXPECT_EQ(3u, CBB_get_utf8_len(0x800));
1542   EXPECT_EQ(3u, CBB_get_utf8_len(0xffff));
1543   EXPECT_EQ(4u, CBB_get_utf8_len(0x10000));
1544   EXPECT_EQ(4u, CBB_get_utf8_len(0x10ffff));
1545 }
1546 
TEST(CBSTest,BogusTime)1547 TEST(CBSTest, BogusTime) {
1548   static const struct {
1549     const char *timestring;
1550   } kBogusTimeTests[] = {
1551       {""},
1552       {"invalidtimesZ"},
1553       {"Z"},
1554       {"0000"},
1555       {"9999Z"},
1556       {"00000000000000000000000000000Z"},
1557       {"19491231235959"},
1558       {"500101000000.001Z"},
1559       {"500101000000+6"},
1560       {"-1970010100000Z"},
1561       {"7a0101000000Z"},
1562       {"20500101000000-6"},
1563       {"20500101000000.001"},
1564       {"20500229000000Z"},
1565       {"220229000000Z"},
1566       {"20500132000000Z"},
1567       {"220132000000Z"},
1568       {"20500332000000Z"},
1569       {"220332000000Z"},
1570       {"20500532000000Z"},
1571       {"220532000000Z"},
1572       {"20500732000000Z"},
1573       {"220732000000Z"},
1574       {"20500832000000Z"},
1575       {"220832000000Z"},
1576       {"20501032000000Z"},
1577       {"221032000000Z"},
1578       {"20501232000000Z"},
1579       {"221232000000Z"},
1580       {"20500431000000Z"},
1581       {"220431000000Z"},
1582       {"20500631000000Z"},
1583       {"220631000000Z"},
1584       {"20500931000000Z"},
1585       {"220931000000Z"},
1586       {"20501131000000Z"},
1587       {"221131000000Z"},
1588       {"20501100000000Z"},
1589       {"221100000000Z"},
1590       {"19500101000000+0600"},
1591   };
1592   for (const auto &t : kBogusTimeTests) {
1593     SCOPED_TRACE(t.timestring);
1594     CBS cbs;
1595     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1596     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1597                                             /*allow_timezone_offset=*/0));
1598     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1599   }
1600   static const struct {
1601     const char *timestring;
1602   } kUTCTZTests[] = {
1603       {"480711220333-0700"},
1604       {"140704000000-0700"},
1605       {"480222202332-0500"},
1606       {"480726113216-0000"},
1607       {"480726113216-2359"},
1608   };
1609   for (const auto &t : kUTCTZTests) {
1610     SCOPED_TRACE(t.timestring);
1611     CBS cbs;
1612     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1613     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1614                                             /*allow_timezone_offset=*/0));
1615     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1616                                             /*allow_timezone_offset=*/1));
1617     EXPECT_TRUE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1618     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/0));
1619   }
1620   static const struct {
1621     const char *timestring;
1622   } kBogusUTCTZTests[] = {
1623       {"480711220333-0160"},
1624       {"140704000000-9999"},
1625       {"480222202332-2400"},
1626   };
1627   for (const auto &t : kBogusUTCTZTests) {
1628     SCOPED_TRACE(t.timestring);
1629     CBS cbs;
1630     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1631     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1632                                             /*allow_timezone_offset=*/0));
1633     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1634   }
1635   static const struct {
1636     const char *timestring;
1637   } kGenTZTests[] = {
1638       {"20480711220333-0000"},
1639       {"20140704000000-0100"},
1640       {"20460311174630-0300"},
1641       {"20140704000000-2359"},
1642   };
1643   for (const auto &t : kGenTZTests) {
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_TRUE(CBS_parse_generalized_time(&cbs, NULL,
1650                                            /*allow_timezone_offset=*/1));
1651     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1652     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/0));
1653   }
1654   static const struct {
1655     const char *timestring;
1656   } kBogusGenTZTests[] = {
1657       {"20480222202332-2400"},
1658       {"20140704000000-9999"},
1659       {"20480726113216-0160"},
1660   };
1661   for (const auto &t : kBogusGenTZTests) {
1662     SCOPED_TRACE(t.timestring);
1663     CBS cbs;
1664     CBS_init(&cbs, (const uint8_t *)t.timestring, strlen(t.timestring));
1665     EXPECT_FALSE(CBS_parse_generalized_time(&cbs, NULL,
1666                                             /*allow_timezone_offset=*/0));
1667     EXPECT_FALSE(CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1));
1668   }
1669 }
1670 
TEST(CBSTest,GetU64Decimal)1671 TEST(CBSTest, GetU64Decimal) {
1672   const struct {
1673     uint64_t val;
1674     const char *text;
1675   } kTests[] = {
1676       {0, "0"},
1677       {1, "1"},
1678       {123456, "123456"},
1679       // 2^64 - 1
1680       {UINT64_C(18446744073709551615), "18446744073709551615"},
1681   };
1682   for (const auto &t : kTests) {
1683     SCOPED_TRACE(t.text);
1684     CBS cbs;
1685     CBS_init(&cbs, reinterpret_cast<const uint8_t*>(t.text), strlen(t.text));
1686     uint64_t v;
1687     ASSERT_TRUE(CBS_get_u64_decimal(&cbs, &v));
1688     EXPECT_EQ(v, t.val);
1689     EXPECT_EQ(CBS_data(&cbs),
1690               reinterpret_cast<const uint8_t *>(t.text) + strlen(t.text));
1691     EXPECT_EQ(CBS_len(&cbs), 0u);
1692 
1693     std::string str(t.text);
1694     str += "Z";
1695     CBS_init(&cbs, reinterpret_cast<const uint8_t *>(str.data()), str.size());
1696     ASSERT_TRUE(CBS_get_u64_decimal(&cbs, &v));
1697     EXPECT_EQ(v, t.val);
1698     EXPECT_EQ(CBS_data(&cbs),
1699               reinterpret_cast<const uint8_t *>(str.data()) + strlen(t.text));
1700     EXPECT_EQ(CBS_len(&cbs), 1u);
1701   }
1702 
1703   static const char *kInvalidTests[] = {
1704       "",
1705       "nope",
1706       "-1",
1707       // 2^64
1708       "18446744073709551616",
1709       // Overflows at multiplying by 10.
1710       "18446744073709551620",
1711   };
1712   for (const char *invalid : kInvalidTests) {
1713     SCOPED_TRACE(invalid);
1714     CBS cbs;
1715     CBS_init(&cbs, reinterpret_cast<const uint8_t *>(invalid), strlen(invalid));
1716     uint64_t v;
1717     EXPECT_FALSE(CBS_get_u64_decimal(&cbs, &v));
1718   }
1719 }
1720