• 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 
26 #include "internal.h"
27 #include "../internal.h"
28 #include "../test/test_util.h"
29 
30 
TEST(CBSTest,Skip)31 TEST(CBSTest, Skip) {
32   static const uint8_t kData[] = {1, 2, 3};
33   CBS data;
34 
35   CBS_init(&data, kData, sizeof(kData));
36   EXPECT_EQ(3u, CBS_len(&data));
37   EXPECT_TRUE(CBS_skip(&data, 1));
38   EXPECT_EQ(2u, CBS_len(&data));
39   EXPECT_TRUE(CBS_skip(&data, 2));
40   EXPECT_EQ(0u, CBS_len(&data));
41   EXPECT_FALSE(CBS_skip(&data, 1));
42 }
43 
TEST(CBSTest,GetUint)44 TEST(CBSTest, GetUint) {
45   static const uint8_t kData[] = {1,  2,  3,  4,  5,  6,  7,  8,  9,  10,
46                                   11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
47   uint8_t u8;
48   uint16_t u16;
49   uint32_t u32;
50   uint64_t u64;
51   CBS data;
52 
53   CBS_init(&data, kData, sizeof(kData));
54   ASSERT_TRUE(CBS_get_u8(&data, &u8));
55   EXPECT_EQ(1u, u8);
56   ASSERT_TRUE(CBS_get_u16(&data, &u16));
57   EXPECT_EQ(0x203u, u16);
58   ASSERT_TRUE(CBS_get_u24(&data, &u32));
59   EXPECT_EQ(0x40506u, u32);
60   ASSERT_TRUE(CBS_get_u32(&data, &u32));
61   EXPECT_EQ(0x708090au, u32);
62   ASSERT_TRUE(CBS_get_u64(&data, &u64));
63   EXPECT_EQ(0xb0c0d0e0f101112u, u64);
64   ASSERT_TRUE(CBS_get_last_u8(&data, &u8));
65   EXPECT_EQ(0x14u, u8);
66   ASSERT_TRUE(CBS_get_last_u8(&data, &u8));
67   EXPECT_EQ(0x13u, u8);
68   EXPECT_FALSE(CBS_get_u8(&data, &u8));
69   EXPECT_FALSE(CBS_get_last_u8(&data, &u8));
70 }
71 
TEST(CBSTest,GetPrefixed)72 TEST(CBSTest, GetPrefixed) {
73   static const uint8_t kData[] = {1, 2, 0, 2, 3, 4, 0, 0, 3, 3, 2, 1};
74   uint8_t u8;
75   uint16_t u16;
76   uint32_t u32;
77   CBS data, prefixed;
78 
79   CBS_init(&data, kData, sizeof(kData));
80   ASSERT_TRUE(CBS_get_u8_length_prefixed(&data, &prefixed));
81   EXPECT_EQ(1u, CBS_len(&prefixed));
82   ASSERT_TRUE(CBS_get_u8(&prefixed, &u8));
83   EXPECT_EQ(2u, u8);
84   ASSERT_TRUE(CBS_get_u16_length_prefixed(&data, &prefixed));
85   EXPECT_EQ(2u, CBS_len(&prefixed));
86   ASSERT_TRUE(CBS_get_u16(&prefixed, &u16));
87   EXPECT_EQ(0x304u, u16);
88   ASSERT_TRUE(CBS_get_u24_length_prefixed(&data, &prefixed));
89   EXPECT_EQ(3u, CBS_len(&prefixed));
90   ASSERT_TRUE(CBS_get_u24(&prefixed, &u32));
91   EXPECT_EQ(0x30201u, u32);
92 }
93 
TEST(CBSTest,GetPrefixedBad)94 TEST(CBSTest, GetPrefixedBad) {
95   static const uint8_t kData1[] = {2, 1};
96   static const uint8_t kData2[] = {0, 2, 1};
97   static const uint8_t kData3[] = {0, 0, 2, 1};
98   CBS data, prefixed;
99 
100   CBS_init(&data, kData1, sizeof(kData1));
101   EXPECT_FALSE(CBS_get_u8_length_prefixed(&data, &prefixed));
102 
103   CBS_init(&data, kData2, sizeof(kData2));
104   EXPECT_FALSE(CBS_get_u16_length_prefixed(&data, &prefixed));
105 
106   CBS_init(&data, kData3, sizeof(kData3));
107   EXPECT_FALSE(CBS_get_u24_length_prefixed(&data, &prefixed));
108 }
109 
TEST(CBSTest,GetASN1)110 TEST(CBSTest, GetASN1) {
111   static const uint8_t kData1[] = {0x30, 2, 1, 2};
112   static const uint8_t kData2[] = {0x30, 3, 1, 2};
113   static const uint8_t kData3[] = {0x30, 0x80};
114   static const uint8_t kData4[] = {0x30, 0x81, 1, 1};
115   static const uint8_t kData5[4 + 0x80] = {0x30, 0x82, 0, 0x80};
116   static const uint8_t kData6[] = {0xa1, 3, 0x4, 1, 1};
117   static const uint8_t kData7[] = {0xa1, 3, 0x4, 2, 1};
118   static const uint8_t kData8[] = {0xa1, 3, 0x2, 1, 1};
119   static const uint8_t kData9[] = {0xa1, 3, 0x2, 1, 0xff};
120 
121   CBS data, contents;
122   int present;
123   uint64_t value;
124 
125   CBS_init(&data, kData1, sizeof(kData1));
126   EXPECT_FALSE(CBS_peek_asn1_tag(&data, CBS_ASN1_BOOLEAN));
127   EXPECT_TRUE(CBS_peek_asn1_tag(&data, CBS_ASN1_SEQUENCE));
128 
129   ASSERT_TRUE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
130   EXPECT_EQ(Bytes("\x01\x02"), Bytes(CBS_data(&contents), CBS_len(&contents)));
131 
132   CBS_init(&data, kData2, sizeof(kData2));
133   // data is truncated
134   EXPECT_FALSE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
135 
136   CBS_init(&data, kData3, sizeof(kData3));
137   // zero byte length of length
138   EXPECT_FALSE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
139 
140   CBS_init(&data, kData4, sizeof(kData4));
141   // long form mistakenly used.
142   EXPECT_FALSE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
143 
144   CBS_init(&data, kData5, sizeof(kData5));
145   // length takes too many bytes.
146   EXPECT_FALSE(CBS_get_asn1(&data, &contents, CBS_ASN1_SEQUENCE));
147 
148   CBS_init(&data, kData1, sizeof(kData1));
149   // wrong tag.
150   EXPECT_FALSE(CBS_get_asn1(&data, &contents, 0x31));
151 
152   CBS_init(&data, NULL, 0);
153   // peek at empty data.
154   EXPECT_FALSE(CBS_peek_asn1_tag(&data, CBS_ASN1_SEQUENCE));
155 
156   CBS_init(&data, NULL, 0);
157   // optional elements at empty data.
158   ASSERT_TRUE(CBS_get_optional_asn1(
159       &data, &contents, &present,
160       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
161   EXPECT_FALSE(present);
162   ASSERT_TRUE(CBS_get_optional_asn1_octet_string(
163       &data, &contents, &present,
164       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
165   EXPECT_FALSE(present);
166   EXPECT_EQ(0u, CBS_len(&contents));
167   ASSERT_TRUE(CBS_get_optional_asn1_octet_string(
168       &data, &contents, NULL,
169       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
170   EXPECT_EQ(0u, CBS_len(&contents));
171   ASSERT_TRUE(CBS_get_optional_asn1_uint64(
172       &data, &value, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0, 42));
173   EXPECT_EQ(42u, value);
174 
175   CBS_init(&data, kData6, sizeof(kData6));
176   // optional element.
177   ASSERT_TRUE(CBS_get_optional_asn1(
178       &data, &contents, &present,
179       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
180   EXPECT_FALSE(present);
181   ASSERT_TRUE(CBS_get_optional_asn1(
182       &data, &contents, &present,
183       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1));
184   EXPECT_TRUE(present);
185   EXPECT_EQ(Bytes("\x04\x01\x01"),
186             Bytes(CBS_data(&contents), CBS_len(&contents)));
187 
188   CBS_init(&data, kData6, sizeof(kData6));
189   // optional octet string.
190   ASSERT_TRUE(CBS_get_optional_asn1_octet_string(
191       &data, &contents, &present,
192       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0));
193   EXPECT_FALSE(present);
194   EXPECT_EQ(0u, CBS_len(&contents));
195   ASSERT_TRUE(CBS_get_optional_asn1_octet_string(
196       &data, &contents, &present,
197       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1));
198   EXPECT_TRUE(present);
199   EXPECT_EQ(Bytes("\x01"), Bytes(CBS_data(&contents), CBS_len(&contents)));
200 
201   CBS_init(&data, kData7, sizeof(kData7));
202   // invalid optional octet string.
203   EXPECT_FALSE(CBS_get_optional_asn1_octet_string(
204       &data, &contents, &present,
205       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1));
206 
207   CBS_init(&data, kData8, sizeof(kData8));
208   // optional integer.
209   ASSERT_TRUE(CBS_get_optional_asn1_uint64(
210       &data, &value, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0, 42));
211   EXPECT_EQ(42u, value);
212   ASSERT_TRUE(CBS_get_optional_asn1_uint64(
213       &data, &value, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1, 42));
214   EXPECT_EQ(1u, value);
215 
216   CBS_init(&data, kData9, sizeof(kData9));
217   // invalid optional integer.
218   EXPECT_FALSE(CBS_get_optional_asn1_uint64(
219       &data, &value, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 1, 42));
220 
221   unsigned tag;
222   CBS_init(&data, kData1, sizeof(kData1));
223   ASSERT_TRUE(CBS_get_any_asn1(&data, &contents, &tag));
224   EXPECT_EQ(CBS_ASN1_SEQUENCE, tag);
225   EXPECT_EQ(Bytes("\x01\x02"), Bytes(CBS_data(&contents), CBS_len(&contents)));
226 
227   size_t header_len;
228   CBS_init(&data, kData1, sizeof(kData1));
229   ASSERT_TRUE(CBS_get_any_asn1_element(&data, &contents, &tag, &header_len));
230   EXPECT_EQ(CBS_ASN1_SEQUENCE, tag);
231   EXPECT_EQ(2u, header_len);
232   EXPECT_EQ(Bytes("\x30\x02\x01\x02"),
233             Bytes(CBS_data(&contents), CBS_len(&contents)));
234 }
235 
TEST(CBSTest,ParseASN1Tag)236 TEST(CBSTest, ParseASN1Tag) {
237   const struct {
238     bool ok;
239     unsigned tag;
240     std::vector<uint8_t> in;
241   } kTests[] = {
242       {true, CBS_ASN1_SEQUENCE, {0x30, 0}},
243       {true, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 4, {0xa4, 0}},
244       {true, CBS_ASN1_APPLICATION | 30, {0x5e, 0}},
245       {true, CBS_ASN1_APPLICATION | 31, {0x5f, 0x1f, 0}},
246       {true, CBS_ASN1_APPLICATION | 32, {0x5f, 0x20, 0}},
247       {true,
248        CBS_ASN1_PRIVATE | CBS_ASN1_CONSTRUCTED | 0x1fffffff,
249        {0xff, 0x81, 0xff, 0xff, 0xff, 0x7f, 0}},
250       // Tag number fits in unsigned but not |CBS_ASN1_TAG_NUMBER_MASK|.
251       {false, 0, {0xff, 0x82, 0xff, 0xff, 0xff, 0x7f, 0}},
252       // Tag number does not fit in unsigned.
253       {false, 0, {0xff, 0x90, 0x80, 0x80, 0x80, 0, 0}},
254       // Tag number is not minimally-encoded
255       {false, 0, {0x5f, 0x80, 0x1f, 0}},
256       // Tag number should have used short form.
257       {false, 0, {0x5f, 0x80, 0x1e, 0}},
258   };
259   for (const auto &t : kTests) {
260     SCOPED_TRACE(Bytes(t.in));
261     unsigned tag;
262     CBS cbs, child;
263     CBS_init(&cbs, t.in.data(), t.in.size());
264     ASSERT_EQ(t.ok, !!CBS_get_any_asn1(&cbs, &child, &tag));
265     if (t.ok) {
266       EXPECT_EQ(t.tag, tag);
267       EXPECT_EQ(0u, CBS_len(&child));
268       EXPECT_EQ(0u, CBS_len(&cbs));
269 
270       CBS_init(&cbs, t.in.data(), t.in.size());
271       EXPECT_TRUE(CBS_peek_asn1_tag(&cbs, t.tag));
272       EXPECT_FALSE(CBS_peek_asn1_tag(&cbs, t.tag + 1));
273 
274       EXPECT_TRUE(CBS_get_asn1(&cbs, &child, t.tag));
275       EXPECT_EQ(0u, CBS_len(&child));
276       EXPECT_EQ(0u, CBS_len(&cbs));
277 
278       CBS_init(&cbs, t.in.data(), t.in.size());
279       EXPECT_FALSE(CBS_get_asn1(&cbs, &child, t.tag + 1));
280     }
281   }
282 }
283 
TEST(CBSTest,GetOptionalASN1Bool)284 TEST(CBSTest, GetOptionalASN1Bool) {
285   static const uint8_t kTrue[] = {0x0a, 3, CBS_ASN1_BOOLEAN, 1, 0xff};
286   static const uint8_t kFalse[] = {0x0a, 3, CBS_ASN1_BOOLEAN, 1, 0x00};
287   static const uint8_t kInvalid[] = {0x0a, 3, CBS_ASN1_BOOLEAN, 1, 0x01};
288 
289   CBS data;
290   CBS_init(&data, NULL, 0);
291   int val = 2;
292   ASSERT_TRUE(CBS_get_optional_asn1_bool(&data, &val, 0x0a, 0));
293   EXPECT_EQ(0, val);
294 
295   CBS_init(&data, kTrue, sizeof(kTrue));
296   val = 2;
297   ASSERT_TRUE(CBS_get_optional_asn1_bool(&data, &val, 0x0a, 0));
298   EXPECT_EQ(1, val);
299 
300   CBS_init(&data, kFalse, sizeof(kFalse));
301   val = 2;
302   ASSERT_TRUE(CBS_get_optional_asn1_bool(&data, &val, 0x0a, 1));
303   EXPECT_EQ(0, val);
304 
305   CBS_init(&data, kInvalid, sizeof(kInvalid));
306   EXPECT_FALSE(CBS_get_optional_asn1_bool(&data, &val, 0x0a, 1));
307 }
308 
309 // Test that CBB_init may be used on an uninitialized input.
TEST(CBBTest,InitUninitialized)310 TEST(CBBTest, InitUninitialized) {
311   CBB cbb;
312   ASSERT_TRUE(CBB_init(&cbb, 100));
313   CBB_cleanup(&cbb);
314 }
315 
TEST(CBBTest,Basic)316 TEST(CBBTest, Basic) {
317   static const uint8_t kExpected[] = {1,   2,    3,    4,    5,    6,   7,
318                                       8,   9,    0xa,  0xb,  0xc,  0xd, 0xe,
319                                       0xf, 0x10, 0x11, 0x12, 0x13, 0x14};
320   uint8_t *buf;
321   size_t buf_len;
322 
323   bssl::ScopedCBB cbb;
324   ASSERT_TRUE(CBB_init(cbb.get(), 100));
325   cbb.Reset();
326 
327   ASSERT_TRUE(CBB_init(cbb.get(), 0));
328   ASSERT_TRUE(CBB_add_u8(cbb.get(), 1));
329   ASSERT_TRUE(CBB_add_u16(cbb.get(), 0x203));
330   ASSERT_TRUE(CBB_add_u24(cbb.get(), 0x40506));
331   ASSERT_TRUE(CBB_add_u32(cbb.get(), 0x708090a));
332   ASSERT_TRUE(CBB_add_u64(cbb.get(), 0xb0c0d0e0f101112));
333   ASSERT_TRUE(CBB_add_bytes(cbb.get(), (const uint8_t *)"\x13\x14", 2));
334   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
335 
336   bssl::UniquePtr<uint8_t> scoper(buf);
337   EXPECT_EQ(Bytes(kExpected), Bytes(buf, buf_len));
338 }
339 
TEST(CBBTest,Fixed)340 TEST(CBBTest, Fixed) {
341   bssl::ScopedCBB cbb;
342   uint8_t buf[1];
343   uint8_t *out_buf;
344   size_t out_size;
345 
346   ASSERT_TRUE(CBB_init_fixed(cbb.get(), NULL, 0));
347   ASSERT_TRUE(CBB_finish(cbb.get(), &out_buf, &out_size));
348   EXPECT_EQ(NULL, out_buf);
349   EXPECT_EQ(0u, out_size);
350 
351   cbb.Reset();
352   ASSERT_TRUE(CBB_init_fixed(cbb.get(), buf, 1));
353   ASSERT_TRUE(CBB_add_u8(cbb.get(), 1));
354   ASSERT_TRUE(CBB_finish(cbb.get(), &out_buf, &out_size));
355   EXPECT_EQ(buf, out_buf);
356   EXPECT_EQ(1u, out_size);
357   EXPECT_EQ(1u, buf[0]);
358 
359   cbb.Reset();
360   ASSERT_TRUE(CBB_init_fixed(cbb.get(), buf, 1));
361   ASSERT_TRUE(CBB_add_u8(cbb.get(), 1));
362   EXPECT_FALSE(CBB_add_u8(cbb.get(), 2));
363 }
364 
365 // Test that calling CBB_finish on a child does nothing.
TEST(CBBTest,FinishChild)366 TEST(CBBTest, FinishChild) {
367   CBB child;
368   uint8_t *out_buf;
369   size_t out_size;
370 
371   bssl::ScopedCBB cbb;
372   ASSERT_TRUE(CBB_init(cbb.get(), 16));
373   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &child));
374 
375   EXPECT_FALSE(CBB_finish(&child, &out_buf, &out_size));
376 
377   ASSERT_TRUE(CBB_finish(cbb.get(), &out_buf, &out_size));
378   bssl::UniquePtr<uint8_t> scoper(out_buf);
379   ASSERT_EQ(1u, out_size);
380   EXPECT_EQ(0u, out_buf[0]);
381 }
382 
TEST(CBBTest,Prefixed)383 TEST(CBBTest, Prefixed) {
384   static const uint8_t kExpected[] = {0, 1, 1, 0, 2, 2, 3, 0, 0, 3,
385                                       4, 5, 6, 5, 4, 1, 0, 1, 2};
386   uint8_t *buf;
387   size_t buf_len;
388   bssl::ScopedCBB cbb;
389   CBB contents, inner_contents, inner_inner_contents;
390   ASSERT_TRUE(CBB_init(cbb.get(), 0));
391   EXPECT_EQ(0u, CBB_len(cbb.get()));
392   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
393   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
394   ASSERT_TRUE(CBB_add_u8(&contents, 1));
395   EXPECT_EQ(1u, CBB_len(&contents));
396   ASSERT_TRUE(CBB_flush(cbb.get()));
397   EXPECT_EQ(3u, CBB_len(cbb.get()));
398   ASSERT_TRUE(CBB_add_u16_length_prefixed(cbb.get(), &contents));
399   ASSERT_TRUE(CBB_add_u16(&contents, 0x203));
400   ASSERT_TRUE(CBB_add_u24_length_prefixed(cbb.get(), &contents));
401   ASSERT_TRUE(CBB_add_u24(&contents, 0x40506));
402   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
403   ASSERT_TRUE(CBB_add_u8_length_prefixed(&contents, &inner_contents));
404   ASSERT_TRUE(CBB_add_u8(&inner_contents, 1));
405   ASSERT_TRUE(
406       CBB_add_u16_length_prefixed(&inner_contents, &inner_inner_contents));
407   ASSERT_TRUE(CBB_add_u8(&inner_inner_contents, 2));
408   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
409 
410   bssl::UniquePtr<uint8_t> scoper(buf);
411   EXPECT_EQ(Bytes(kExpected), Bytes(buf, buf_len));
412 }
413 
TEST(CBBTest,DiscardChild)414 TEST(CBBTest, DiscardChild) {
415   bssl::ScopedCBB cbb;
416   CBB contents, inner_contents, inner_inner_contents;
417 
418   ASSERT_TRUE(CBB_init(cbb.get(), 0));
419   ASSERT_TRUE(CBB_add_u8(cbb.get(), 0xaa));
420 
421   // Discarding |cbb|'s children preserves the byte written.
422   CBB_discard_child(cbb.get());
423 
424   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
425   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
426   ASSERT_TRUE(CBB_add_u8(&contents, 0xbb));
427   ASSERT_TRUE(CBB_add_u16_length_prefixed(cbb.get(), &contents));
428   ASSERT_TRUE(CBB_add_u16(&contents, 0xcccc));
429   ASSERT_TRUE(CBB_add_u24_length_prefixed(cbb.get(), &contents));
430   ASSERT_TRUE(CBB_add_u24(&contents, 0xdddddd));
431   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &contents));
432   ASSERT_TRUE(CBB_add_u8(&contents, 0xff));
433   ASSERT_TRUE(CBB_add_u8_length_prefixed(&contents, &inner_contents));
434   ASSERT_TRUE(CBB_add_u8(&inner_contents, 0x42));
435   ASSERT_TRUE(
436       CBB_add_u16_length_prefixed(&inner_contents, &inner_inner_contents));
437   ASSERT_TRUE(CBB_add_u8(&inner_inner_contents, 0x99));
438 
439   // Discard everything from |inner_contents| down.
440   CBB_discard_child(&contents);
441 
442   uint8_t *buf;
443   size_t buf_len;
444   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
445   bssl::UniquePtr<uint8_t> scoper(buf);
446 
447   static const uint8_t kExpected[] = {
448         0xaa,
449         0,
450         1, 0xbb,
451         0, 2, 0xcc, 0xcc,
452         0, 0, 3, 0xdd, 0xdd, 0xdd,
453         1, 0xff,
454   };
455   EXPECT_EQ(Bytes(kExpected), Bytes(buf, buf_len));
456 }
457 
TEST(CBBTest,Misuse)458 TEST(CBBTest, Misuse) {
459   bssl::ScopedCBB cbb;
460   CBB child, contents;
461   uint8_t *buf;
462   size_t buf_len;
463 
464   ASSERT_TRUE(CBB_init(cbb.get(), 0));
465   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &child));
466   ASSERT_TRUE(CBB_add_u8(&child, 1));
467   ASSERT_TRUE(CBB_add_u8(cbb.get(), 2));
468 
469   // Since we wrote to |cbb|, |child| is now invalid and attempts to write to
470   // it should fail.
471   EXPECT_FALSE(CBB_add_u8(&child, 1));
472   EXPECT_FALSE(CBB_add_u16(&child, 1));
473   EXPECT_FALSE(CBB_add_u24(&child, 1));
474   EXPECT_FALSE(CBB_add_u8_length_prefixed(&child, &contents));
475   EXPECT_FALSE(CBB_add_u16_length_prefixed(&child, &contents));
476   EXPECT_FALSE(CBB_add_asn1(&child, &contents, 1));
477   EXPECT_FALSE(CBB_add_bytes(&child, (const uint8_t*) "a", 1));
478 
479   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
480   bssl::UniquePtr<uint8_t> scoper(buf);
481 
482   EXPECT_EQ(Bytes("\x01\x01\x02"), Bytes(buf, buf_len));
483 }
484 
TEST(CBBTest,ASN1)485 TEST(CBBTest, ASN1) {
486   static const uint8_t kExpected[] = {
487       // SEQUENCE { 1 2 3 }
488       0x30, 3, 1, 2, 3,
489       // [4 CONSTRUCTED] { 4 5 6 }
490       0xa4, 3, 4, 5, 6,
491       // [APPLICATION 30 PRIMITIVE] { 7 8 9 }
492       0x5e, 3, 7, 8, 9,
493       // [APPLICATION 31 PRIMITIVE] { 10 11 12 }
494       0x5f, 0x1f, 3, 10, 11, 12,
495       // [PRIVATE 2^29-1 CONSTRUCTED] { 13 14 15 }
496       0xff, 0x81, 0xff, 0xff, 0xff, 0x7f, 3, 13, 14, 15,
497   };
498   uint8_t *buf;
499   size_t buf_len;
500   bssl::ScopedCBB cbb;
501   CBB contents, inner_contents;
502 
503   ASSERT_TRUE(CBB_init(cbb.get(), 0));
504   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &contents, CBS_ASN1_SEQUENCE));
505   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x01\x02\x03", 3));
506   ASSERT_TRUE(
507       CBB_add_asn1(cbb.get(), &contents,
508                    CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 4));
509   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x04\x05\x06", 3));
510   ASSERT_TRUE(
511       CBB_add_asn1(cbb.get(), &contents,
512                    CBS_ASN1_APPLICATION | 30));
513   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x07\x08\x09", 3));
514   ASSERT_TRUE(
515       CBB_add_asn1(cbb.get(), &contents,
516                    CBS_ASN1_APPLICATION | 31));
517   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x0a\x0b\x0c", 3));
518   ASSERT_TRUE(
519       CBB_add_asn1(cbb.get(), &contents,
520                    CBS_ASN1_PRIVATE | CBS_ASN1_CONSTRUCTED | 0x1fffffff));
521   ASSERT_TRUE(CBB_add_bytes(&contents, (const uint8_t *)"\x0d\x0e\x0f", 3));
522   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
523   bssl::UniquePtr<uint8_t> scoper(buf);
524 
525   EXPECT_EQ(Bytes(kExpected), Bytes(buf, buf_len));
526 
527   std::vector<uint8_t> test_data(100000, 0x42);
528   ASSERT_TRUE(CBB_init(cbb.get(), 0));
529   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &contents, CBS_ASN1_SEQUENCE));
530   ASSERT_TRUE(CBB_add_bytes(&contents, test_data.data(), 130));
531   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
532   scoper.reset(buf);
533 
534   ASSERT_EQ(3u + 130u, buf_len);
535   EXPECT_EQ(Bytes("\x30\x81\x82"), Bytes(buf, 3));
536   EXPECT_EQ(Bytes(test_data.data(), 130), Bytes(buf + 3, 130));
537 
538   ASSERT_TRUE(CBB_init(cbb.get(), 0));
539   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &contents, CBS_ASN1_SEQUENCE));
540   ASSERT_TRUE(CBB_add_bytes(&contents, test_data.data(), 1000));
541   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
542   scoper.reset(buf);
543 
544   ASSERT_EQ(4u + 1000u, buf_len);
545   EXPECT_EQ(Bytes("\x30\x82\x03\xe8"), Bytes(buf, 4));
546   EXPECT_EQ(Bytes(test_data.data(), 1000), Bytes(buf + 4, 1000));
547 
548   ASSERT_TRUE(CBB_init(cbb.get(), 0));
549   ASSERT_TRUE(CBB_add_asn1(cbb.get(), &contents, CBS_ASN1_SEQUENCE));
550   ASSERT_TRUE(CBB_add_asn1(&contents, &inner_contents, CBS_ASN1_SEQUENCE));
551   ASSERT_TRUE(CBB_add_bytes(&inner_contents, test_data.data(), 100000));
552   ASSERT_TRUE(CBB_finish(cbb.get(), &buf, &buf_len));
553   scoper.reset(buf);
554 
555   ASSERT_EQ(5u + 5u + 100000u, buf_len);
556   EXPECT_EQ(Bytes("\x30\x83\x01\x86\xa5\x30\x83\x01\x86\xa0"), Bytes(buf, 10));
557   EXPECT_EQ(Bytes(test_data.data(), test_data.size()), Bytes(buf + 10, 100000));
558 }
559 
ExpectBerConvert(const char * name,const uint8_t * der_expected,size_t der_len,const uint8_t * ber,size_t ber_len)560 static void ExpectBerConvert(const char *name, const uint8_t *der_expected,
561                              size_t der_len, const uint8_t *ber,
562                              size_t ber_len) {
563   SCOPED_TRACE(name);
564   CBS in, out;
565   uint8_t *storage;
566 
567   CBS_init(&in, ber, ber_len);
568   ASSERT_TRUE(CBS_asn1_ber_to_der(&in, &out, &storage));
569   bssl::UniquePtr<uint8_t> scoper(storage);
570 
571   EXPECT_EQ(Bytes(der_expected, der_len), Bytes(CBS_data(&out), CBS_len(&out)));
572   if (storage != nullptr) {
573     EXPECT_NE(Bytes(der_expected, der_len), Bytes(ber, ber_len));
574   } else {
575     EXPECT_EQ(Bytes(der_expected, der_len), Bytes(ber, ber_len));
576   }
577 }
578 
TEST(CBSTest,BerConvert)579 TEST(CBSTest, BerConvert) {
580   static const uint8_t kSimpleBER[] = {0x01, 0x01, 0x00};
581 
582   // kIndefBER contains a SEQUENCE with an indefinite length.
583   static const uint8_t kIndefBER[] = {0x30, 0x80, 0x01, 0x01, 0x02, 0x00, 0x00};
584   static const uint8_t kIndefDER[] = {0x30, 0x03, 0x01, 0x01, 0x02};
585 
586   // kIndefBER2 contains a constructed [APPLICATION 31] with an indefinite
587   // length.
588   static const uint8_t kIndefBER2[] = {0x7f, 0x1f, 0x80, 0x01,
589                                        0x01, 0x02, 0x00, 0x00};
590   static const uint8_t kIndefDER2[] = {0x7f, 0x1f, 0x03, 0x01, 0x01, 0x02};
591 
592   // kOctetStringBER contains an indefinite length OCTET STRING with two parts.
593   // These parts need to be concatenated in DER form.
594   static const uint8_t kOctetStringBER[] = {0x24, 0x80, 0x04, 0x02, 0,    1,
595                                             0x04, 0x02, 2,    3,    0x00, 0x00};
596   static const uint8_t kOctetStringDER[] = {0x04, 0x04, 0, 1, 2, 3};
597 
598   // kNSSBER is part of a PKCS#12 message generated by NSS that uses indefinite
599   // length elements extensively.
600   static const uint8_t kNSSBER[] = {
601       0x30, 0x80, 0x02, 0x01, 0x03, 0x30, 0x80, 0x06, 0x09, 0x2a, 0x86, 0x48,
602       0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x80, 0x24, 0x80, 0x04, 0x04,
603       0x01, 0x02, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x39,
604       0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05,
605       0x00, 0x04, 0x14, 0x84, 0x98, 0xfc, 0x66, 0x33, 0xee, 0xba, 0xe7, 0x90,
606       0xc1, 0xb6, 0xe8, 0x8f, 0xfe, 0x1d, 0xc5, 0xa5, 0x97, 0x93, 0x3e, 0x04,
607       0x10, 0x38, 0x62, 0xc6, 0x44, 0x12, 0xd5, 0x30, 0x00, 0xf8, 0xf2, 0x1b,
608       0xf0, 0x6e, 0x10, 0x9b, 0xb8, 0x02, 0x02, 0x07, 0xd0, 0x00, 0x00,
609   };
610 
611   static const uint8_t kNSSDER[] = {
612       0x30, 0x53, 0x02, 0x01, 0x03, 0x30, 0x13, 0x06, 0x09, 0x2a, 0x86,
613       0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x06, 0x04, 0x04,
614       0x01, 0x02, 0x03, 0x04, 0x30, 0x39, 0x30, 0x21, 0x30, 0x09, 0x06,
615       0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14, 0x84,
616       0x98, 0xfc, 0x66, 0x33, 0xee, 0xba, 0xe7, 0x90, 0xc1, 0xb6, 0xe8,
617       0x8f, 0xfe, 0x1d, 0xc5, 0xa5, 0x97, 0x93, 0x3e, 0x04, 0x10, 0x38,
618       0x62, 0xc6, 0x44, 0x12, 0xd5, 0x30, 0x00, 0xf8, 0xf2, 0x1b, 0xf0,
619       0x6e, 0x10, 0x9b, 0xb8, 0x02, 0x02, 0x07, 0xd0,
620   };
621 
622   // kConstructedStringBER contains a deeply-nested constructed OCTET STRING.
623   // The BER conversion collapses this to one level deep, but not completely.
624   static const uint8_t kConstructedStringBER[] = {
625       0xa0, 0x10, 0x24, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01,
626       0x01, 0x24, 0x06, 0x04, 0x01, 0x02, 0x04, 0x01, 0x03,
627   };
628   static const uint8_t kConstructedStringDER[] = {
629       0xa0, 0x08, 0x04, 0x02, 0x00, 0x01, 0x04, 0x02, 0x02, 0x03,
630   };
631 
632   ExpectBerConvert("kSimpleBER", kSimpleBER, sizeof(kSimpleBER), kSimpleBER,
633                    sizeof(kSimpleBER));
634   ExpectBerConvert("kIndefBER", kIndefDER, sizeof(kIndefDER), kIndefBER,
635                    sizeof(kIndefBER));
636   ExpectBerConvert("kIndefBER2", kIndefDER2, sizeof(kIndefDER2), kIndefBER2,
637                    sizeof(kIndefBER2));
638   ExpectBerConvert("kOctetStringBER", kOctetStringDER, sizeof(kOctetStringDER),
639                    kOctetStringBER, sizeof(kOctetStringBER));
640   ExpectBerConvert("kNSSBER", kNSSDER, sizeof(kNSSDER), kNSSBER,
641                    sizeof(kNSSBER));
642   ExpectBerConvert("kConstructedStringBER", kConstructedStringDER,
643                    sizeof(kConstructedStringDER), kConstructedStringBER,
644                    sizeof(kConstructedStringBER));
645 }
646 
647 struct ImplicitStringTest {
648   const char *in;
649   size_t in_len;
650   bool ok;
651   const char *out;
652   size_t out_len;
653 };
654 
655 static const ImplicitStringTest kImplicitStringTests[] = {
656     // A properly-encoded string.
657     {"\x80\x03\x61\x61\x61", 5, true, "aaa", 3},
658     // An implicit-tagged string.
659     {"\xa0\x09\x04\x01\x61\x04\x01\x61\x04\x01\x61", 11, true, "aaa", 3},
660     // |CBS_get_asn1_implicit_string| only accepts one level deep of nesting.
661     {"\xa0\x0b\x24\x06\x04\x01\x61\x04\x01\x61\x04\x01\x61", 13, false, nullptr,
662      0},
663     // The outer tag must match.
664     {"\x81\x03\x61\x61\x61", 5, false, nullptr, 0},
665     {"\xa1\x09\x04\x01\x61\x04\x01\x61\x04\x01\x61", 11, false, nullptr, 0},
666     // The inner tag must match.
667     {"\xa1\x09\x0c\x01\x61\x0c\x01\x61\x0c\x01\x61", 11, false, nullptr, 0},
668 };
669 
TEST(CBSTest,ImplicitString)670 TEST(CBSTest, ImplicitString) {
671   for (const auto &test : kImplicitStringTests) {
672     SCOPED_TRACE(Bytes(test.in, test.in_len));
673     uint8_t *storage = nullptr;
674     CBS in, out;
675     CBS_init(&in, reinterpret_cast<const uint8_t *>(test.in), test.in_len);
676     int ok = CBS_get_asn1_implicit_string(&in, &out, &storage,
677                                           CBS_ASN1_CONTEXT_SPECIFIC | 0,
678                                           CBS_ASN1_OCTETSTRING);
679     bssl::UniquePtr<uint8_t> scoper(storage);
680     EXPECT_EQ(test.ok, static_cast<bool>(ok));
681 
682     if (ok) {
683       EXPECT_EQ(Bytes(test.out, test.out_len),
684                 Bytes(CBS_data(&out), CBS_len(&out)));
685     }
686   }
687 }
688 
689 struct ASN1Uint64Test {
690   uint64_t value;
691   const char *encoding;
692   size_t encoding_len;
693 };
694 
695 static const ASN1Uint64Test kASN1Uint64Tests[] = {
696     {0, "\x02\x01\x00", 3},
697     {1, "\x02\x01\x01", 3},
698     {127, "\x02\x01\x7f", 3},
699     {128, "\x02\x02\x00\x80", 4},
700     {0xdeadbeef, "\x02\x05\x00\xde\xad\xbe\xef", 7},
701     {UINT64_C(0x0102030405060708),
702      "\x02\x08\x01\x02\x03\x04\x05\x06\x07\x08", 10},
703     {UINT64_C(0xffffffffffffffff),
704       "\x02\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff", 11},
705 };
706 
707 struct ASN1InvalidUint64Test {
708   const char *encoding;
709   size_t encoding_len;
710 };
711 
712 static const ASN1InvalidUint64Test kASN1InvalidUint64Tests[] = {
713     // Bad tag.
714     {"\x03\x01\x00", 3},
715     // Empty contents.
716     {"\x02\x00", 2},
717     // Negative number.
718     {"\x02\x01\x80", 3},
719     // Overflow.
720     {"\x02\x09\x01\x00\x00\x00\x00\x00\x00\x00\x00", 11},
721     // Leading zeros.
722     {"\x02\x02\x00\x01", 4},
723 };
724 
TEST(CBSTest,ASN1Uint64)725 TEST(CBSTest, ASN1Uint64) {
726   for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kASN1Uint64Tests); i++) {
727     SCOPED_TRACE(i);
728     const ASN1Uint64Test *test = &kASN1Uint64Tests[i];
729     CBS cbs;
730     uint64_t value;
731     uint8_t *out;
732     size_t len;
733 
734     CBS_init(&cbs, (const uint8_t *)test->encoding, test->encoding_len);
735     ASSERT_TRUE(CBS_get_asn1_uint64(&cbs, &value));
736     EXPECT_EQ(0u, CBS_len(&cbs));
737     EXPECT_EQ(test->value, value);
738 
739     bssl::ScopedCBB cbb;
740     ASSERT_TRUE(CBB_init(cbb.get(), 0));
741     ASSERT_TRUE(CBB_add_asn1_uint64(cbb.get(), test->value));
742     ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
743     bssl::UniquePtr<uint8_t> scoper(out);
744     EXPECT_EQ(Bytes(test->encoding, test->encoding_len), Bytes(out, len));
745   }
746 
747   for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kASN1InvalidUint64Tests); i++) {
748     const ASN1InvalidUint64Test *test = &kASN1InvalidUint64Tests[i];
749     CBS cbs;
750     uint64_t value;
751 
752     CBS_init(&cbs, (const uint8_t *)test->encoding, test->encoding_len);
753     EXPECT_FALSE(CBS_get_asn1_uint64(&cbs, &value));
754   }
755 }
756 
TEST(CBBTest,Zero)757 TEST(CBBTest, Zero) {
758   CBB cbb;
759   CBB_zero(&cbb);
760   // Calling |CBB_cleanup| on a zero-state |CBB| must not crash.
761   CBB_cleanup(&cbb);
762 }
763 
TEST(CBBTest,Reserve)764 TEST(CBBTest, Reserve) {
765   uint8_t buf[10];
766   uint8_t *ptr;
767   size_t len;
768   bssl::ScopedCBB cbb;
769   ASSERT_TRUE(CBB_init_fixed(cbb.get(), buf, sizeof(buf)));
770   // Too large.
771   EXPECT_FALSE(CBB_reserve(cbb.get(), &ptr, 11));
772 
773   cbb.Reset();
774   ASSERT_TRUE(CBB_init_fixed(cbb.get(), buf, sizeof(buf)));
775   // Successfully reserve the entire space.
776   ASSERT_TRUE(CBB_reserve(cbb.get(), &ptr, 10));
777   EXPECT_EQ(buf, ptr);
778   // Advancing under the maximum bytes is legal.
779   ASSERT_TRUE(CBB_did_write(cbb.get(), 5));
780   ASSERT_TRUE(CBB_finish(cbb.get(), NULL, &len));
781   EXPECT_EQ(5u, len);
782 }
783 
784 // Test that CBB errors are sticky; once on operation on CBB fails, all
785 // subsequent ones do.
TEST(CBBTest,StickyError)786 TEST(CBBTest, StickyError) {
787   // Write an input that exceeds the limit for its length prefix.
788   bssl::ScopedCBB cbb;
789   CBB child;
790   static const uint8_t kZeros[256] = {0};
791   ASSERT_TRUE(CBB_init(cbb.get(), 0));
792   ASSERT_TRUE(CBB_add_u8_length_prefixed(cbb.get(), &child));
793   ASSERT_TRUE(CBB_add_bytes(&child, kZeros, sizeof(kZeros)));
794   ASSERT_FALSE(CBB_flush(cbb.get()));
795 
796   // All future operations should fail.
797   uint8_t *ptr;
798   size_t len;
799   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
800   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
801 
802   // Write an input that cannot fit in a fixed CBB.
803   cbb.Reset();
804   uint8_t buf;
805   ASSERT_TRUE(CBB_init_fixed(cbb.get(), &buf, 1));
806   ASSERT_FALSE(CBB_add_bytes(cbb.get(), kZeros, sizeof(kZeros)));
807 
808   // All future operations should fail.
809   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
810   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
811 
812   // Write a u32 that cannot fit in a u24.
813   cbb.Reset();
814   ASSERT_TRUE(CBB_init(cbb.get(), 0));
815   ASSERT_FALSE(CBB_add_u24(cbb.get(), 1u << 24));
816 
817   // All future operations should fail.
818   EXPECT_FALSE(CBB_add_u8(cbb.get(), 0));
819   EXPECT_FALSE(CBB_finish(cbb.get(), &ptr, &len));
820 }
821 
TEST(CBSTest,BitString)822 TEST(CBSTest, BitString) {
823   static const std::vector<uint8_t> kValidBitStrings[] = {
824       {0x00},                                      // 0 bits
825       {0x07, 0x80},                                // 1 bit
826       {0x04, 0xf0},                                // 4 bits
827       {0x00, 0xff},                                // 8 bits
828       {0x06, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0},  // 42 bits
829   };
830   for (const auto& test : kValidBitStrings) {
831     SCOPED_TRACE(Bytes(test.data(), test.size()));
832     CBS cbs;
833     CBS_init(&cbs, test.data(), test.size());
834     EXPECT_TRUE(CBS_is_valid_asn1_bitstring(&cbs));
835   }
836 
837   static const std::vector<uint8_t> kInvalidBitStrings[] = {
838       // BIT STRINGs always have a leading byte.
839       std::vector<uint8_t>{},
840       // It's not possible to take an unused bit off the empty string.
841       {0x01},
842       // There can be at most 7 unused bits.
843       {0x08, 0xff},
844       {0xff, 0xff},
845       // All unused bits must be cleared.
846       {0x06, 0xff, 0xc1},
847   };
848   for (const auto& test : kInvalidBitStrings) {
849     SCOPED_TRACE(Bytes(test.data(), test.size()));
850     CBS cbs;
851     CBS_init(&cbs, test.data(), test.size());
852     EXPECT_FALSE(CBS_is_valid_asn1_bitstring(&cbs));
853 
854     // CBS_asn1_bitstring_has_bit returns false on invalid inputs.
855     EXPECT_FALSE(CBS_asn1_bitstring_has_bit(&cbs, 0));
856   }
857 
858   static const struct {
859     std::vector<uint8_t> in;
860     unsigned bit;
861     bool bit_set;
862   } kBitTests[] = {
863       // Basic tests.
864       {{0x00}, 0, false},
865       {{0x07, 0x80}, 0, true},
866       {{0x06, 0x0f, 0x40}, 0, false},
867       {{0x06, 0x0f, 0x40}, 1, false},
868       {{0x06, 0x0f, 0x40}, 2, false},
869       {{0x06, 0x0f, 0x40}, 3, false},
870       {{0x06, 0x0f, 0x40}, 4, true},
871       {{0x06, 0x0f, 0x40}, 5, true},
872       {{0x06, 0x0f, 0x40}, 6, true},
873       {{0x06, 0x0f, 0x40}, 7, true},
874       {{0x06, 0x0f, 0x40}, 8, false},
875       {{0x06, 0x0f, 0x40}, 9, true},
876       // Out-of-bounds bits return 0.
877       {{0x06, 0x0f, 0x40}, 10, false},
878       {{0x06, 0x0f, 0x40}, 15, false},
879       {{0x06, 0x0f, 0x40}, 16, false},
880       {{0x06, 0x0f, 0x40}, 1000, false},
881   };
882   for (const auto& test : kBitTests) {
883     SCOPED_TRACE(Bytes(test.in.data(), test.in.size()));
884     SCOPED_TRACE(test.bit);
885     CBS cbs;
886     CBS_init(&cbs, test.in.data(), test.in.size());
887     EXPECT_EQ(static_cast<int>(test.bit_set),
888               CBS_asn1_bitstring_has_bit(&cbs, test.bit));
889   }
890 }
891 
TEST(CBBTest,AddOIDFromText)892 TEST(CBBTest, AddOIDFromText) {
893   const struct {
894     const char *text;
895     std::vector<uint8_t> der;
896   } kValidOIDs[] = {
897       // Some valid values.
898       {"0.0", {0x00}},
899       {"0.2.3.4", {0x2, 0x3, 0x4}},
900       {"1.2.3.4", {0x2a, 0x3, 0x4}},
901       {"2.2.3.4", {0x52, 0x3, 0x4}},
902       {"1.2.840.113554.4.1.72585",
903        {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09}},
904       // Test edge cases around the first component.
905       {"0.39", {0x27}},
906       {"1.0", {0x28}},
907       {"1.39", {0x4f}},
908       {"2.0", {0x50}},
909       {"2.1", {0x51}},
910       {"2.40", {0x78}},
911       // Edge cases near an overflow.
912       {"1.2.18446744073709551615",
913        {0x2a, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}},
914       {"2.18446744073709551535",
915        {0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}},
916   };
917 
918   const char *kInvalidTexts[] = {
919       // Invalid second component.
920       "0.40",
921       "1.40",
922       // Invalid first component.
923       "3.1",
924       // The empty string is not an OID.
925       "",
926       // No empty components.
927       ".1.2.3.4.5",
928       "1..2.3.4.5",
929       "1.2.3.4.5.",
930       // There must be at least two components.
931       "1",
932       // No extra leading zeros.
933       "00.1.2.3.4",
934       "01.1.2.3.4",
935       // Overflow for both components or 40*A + B.
936       "1.2.18446744073709551616",
937       "2.18446744073709551536",
938   };
939 
940   const std::vector<uint8_t> kInvalidDER[] = {
941       // The empty string is not an OID.
942       {},
943       // Non-minimal representation.
944       {0x80, 0x01},
945       // Overflow. This is the DER representation of
946       // 1.2.840.113554.4.1.72585.18446744073709551616. (The final value is
947       // 2^64.)
948       {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09,
949        0x82, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00},
950   };
951 
952   for (const auto &t : kValidOIDs) {
953     SCOPED_TRACE(t.text);
954 
955     bssl::ScopedCBB cbb;
956     ASSERT_TRUE(CBB_init(cbb.get(), 0));
957     ASSERT_TRUE(CBB_add_asn1_oid_from_text(cbb.get(), t.text, strlen(t.text)));
958     uint8_t *out;
959     size_t len;
960     ASSERT_TRUE(CBB_finish(cbb.get(), &out, &len));
961     bssl::UniquePtr<uint8_t> free_out(out);
962     EXPECT_EQ(Bytes(t.der), Bytes(out, len));
963 
964     CBS cbs;
965     CBS_init(&cbs, t.der.data(), t.der.size());
966     bssl::UniquePtr<char> text(CBS_asn1_oid_to_text(&cbs));
967     ASSERT_TRUE(text.get());
968     EXPECT_STREQ(t.text, text.get());
969   }
970 
971   for (const char *t : kInvalidTexts) {
972     SCOPED_TRACE(t);
973     bssl::ScopedCBB cbb;
974     ASSERT_TRUE(CBB_init(cbb.get(), 0));
975     EXPECT_FALSE(CBB_add_asn1_oid_from_text(cbb.get(), t, strlen(t)));
976   }
977 
978   for (const auto &t : kInvalidDER) {
979     SCOPED_TRACE(Bytes(t));
980     CBS cbs;
981     CBS_init(&cbs, t.data(), t.size());
982     bssl::UniquePtr<char> text(CBS_asn1_oid_to_text(&cbs));
983     EXPECT_FALSE(text);
984   }
985 }
986 
TEST(CBBTest,FlushASN1SetOf)987 TEST(CBBTest, FlushASN1SetOf) {
988   const struct {
989     std::vector<uint8_t> in, out;
990   } kValidInputs[] = {
991     // No elements.
992     {{}, {}},
993     // One element.
994     {{0x30, 0x00}, {0x30, 0x00}},
995     // Two identical elements.
996     {{0x30, 0x00, 0x30, 0x00}, {0x30, 0x00, 0x30, 0x00}},
997     // clang-format off
998     {{0x30, 0x02, 0x00, 0x00,
999       0x30, 0x00,
1000       0x01, 0x00,
1001       0x30, 0x02, 0x00, 0x00,
1002       0x30, 0x03, 0x00, 0x00, 0x00,
1003       0x30, 0x00,
1004       0x30, 0x03, 0x00, 0x00, 0x01,
1005       0x30, 0x01, 0x00,
1006       0x01, 0x01, 0x00},
1007      {0x01, 0x00,
1008       0x01, 0x01, 0x00,
1009       0x30, 0x00,
1010       0x30, 0x00,
1011       0x30, 0x01, 0x00,
1012       0x30, 0x02, 0x00, 0x00,
1013       0x30, 0x02, 0x00, 0x00,
1014       0x30, 0x03, 0x00, 0x00, 0x00,
1015       0x30, 0x03, 0x00, 0x00, 0x01}},
1016     // clang-format on
1017   };
1018 
1019   for (const auto &t : kValidInputs) {
1020     SCOPED_TRACE(Bytes(t.in));
1021 
1022     bssl::ScopedCBB cbb;
1023     CBB child;
1024     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1025     ASSERT_TRUE(CBB_add_asn1(cbb.get(), &child, CBS_ASN1_SET));
1026     ASSERT_TRUE(CBB_add_bytes(&child, t.in.data(), t.in.size()));
1027     ASSERT_TRUE(CBB_flush_asn1_set_of(&child));
1028     EXPECT_EQ(Bytes(t.out), Bytes(CBB_data(&child), CBB_len(&child)));
1029 
1030     // Running it again should be idempotent.
1031     ASSERT_TRUE(CBB_flush_asn1_set_of(&child));
1032     EXPECT_EQ(Bytes(t.out), Bytes(CBB_data(&child), CBB_len(&child)));
1033 
1034     // The ASN.1 header remain intact.
1035     ASSERT_TRUE(CBB_flush(cbb.get()));
1036     EXPECT_EQ(0x31, CBB_data(cbb.get())[0]);
1037   }
1038 
1039   const std::vector<uint8_t> kInvalidInputs[] = {
1040     {0x30},
1041     {0x30, 0x01},
1042     {0x30, 0x00, 0x30, 0x00, 0x30, 0x01},
1043   };
1044 
1045   for (const auto &t : kInvalidInputs) {
1046     SCOPED_TRACE(Bytes(t));
1047 
1048     bssl::ScopedCBB cbb;
1049     CBB child;
1050     ASSERT_TRUE(CBB_init(cbb.get(), 0));
1051     ASSERT_TRUE(CBB_add_asn1(cbb.get(), &child, CBS_ASN1_SET));
1052     ASSERT_TRUE(CBB_add_bytes(&child, t.data(), t.size()));
1053     EXPECT_FALSE(CBB_flush_asn1_set_of(&child));
1054   }
1055 }
1056 
1057 template <class T>
LiteralToBytes(const T * str)1058 static std::vector<uint8_t> LiteralToBytes(const T *str) {
1059   std::vector<uint8_t> ret;
1060   for (; *str != 0; str++) {
1061     for (size_t i = 0; i < sizeof(T); i++) {
1062       ret.push_back(static_cast<uint8_t>(*str >> (8 * (sizeof(T) - 1 - i))));
1063     }
1064   }
1065   return ret;
1066 }
1067 
LiteralToCodePoints(const char32_t * str)1068 static std::vector<uint32_t> LiteralToCodePoints(const char32_t *str) {
1069   std::vector<uint32_t> ret;
1070   for (; *str != 0; str++) {
1071     ret.push_back(static_cast<uint32_t>(*str));
1072   }
1073   return ret;
1074 }
1075 
TEST(CBBTest,Unicode)1076 TEST(CBBTest, Unicode) {
1077   struct {
1078     int (*decode)(CBS *, uint32_t *);
1079     int (*encode)(CBB *, uint32_t);
1080     std::vector<uint8_t> in;
1081     std::vector<uint32_t> out;
1082     bool ok;
1083   } kTests[] = {
1084       {cbs_get_utf8, cbb_add_utf8,
1085        // This test string captures all four cases in UTF-8.
1086        LiteralToBytes(u8"Hello, 世界! ¡Hola, ��!"),
1087        LiteralToCodePoints(U"Hello, 世界! ¡Hola, ��!"), true},
1088 
1089       // Some invalid inputs adapted from
1090       // http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
1091       // 2.1  First possible sequence of a certain length. (5- and 6-bit
1092       // sequences no longer exist.)
1093       {cbs_get_utf8, cbb_add_utf8, {0xf8, 0x88, 0x80, 0x80, 0x80}, {}, false},
1094       {cbs_get_utf8,
1095        cbb_add_utf8,
1096        {0xfc, 0x84, 0x80, 0x80, 0x80, 0x80},
1097        {},
1098        false},
1099       // 3.1  Unexpected continuation bytes.
1100       {cbs_get_utf8, cbb_add_utf8, {0x80}, {}, false},
1101       {cbs_get_utf8, cbb_add_utf8, {0xbf}, {}, false},
1102       // 3.2  Lonely start characters.
1103       {cbs_get_utf8, cbb_add_utf8, {0xc0, ' '}, {}, false},
1104       {cbs_get_utf8, cbb_add_utf8, {0xe0, ' '}, {}, false},
1105       {cbs_get_utf8, cbb_add_utf8, {0xf0, ' '}, {}, false},
1106       // 3.3  Sequences with last continuation byte missing
1107       {cbs_get_utf8, cbb_add_utf8, {0xc0}, {}, false},
1108       {cbs_get_utf8, cbb_add_utf8, {0xe0, 0x80}, {}, false},
1109       {cbs_get_utf8, cbb_add_utf8, {0xf0, 0x80, 0x80}, {}, false},
1110       // Variation of the above with unexpected spaces.
1111       {cbs_get_utf8, cbb_add_utf8, {0xe0, 0x80, ' '}, {}, false},
1112       {cbs_get_utf8, cbb_add_utf8, {0xf0, 0x80, 0x80, ' '}, {}, false},
1113       // 4.1  Examples of an overlong ASCII character
1114       {cbs_get_utf8, cbb_add_utf8, {0xc0, 0xaf}, {}, false},
1115       {cbs_get_utf8, cbb_add_utf8, {0xe0, 0x80, 0xaf}, {}, false},
1116       {cbs_get_utf8, cbb_add_utf8, {0xf0, 0x80, 0x80, 0xaf}, {}, false},
1117       // 4.2  Maximum overlong sequences
1118       {cbs_get_utf8, cbb_add_utf8, {0xc1, 0xbf}, {}, false},
1119       {cbs_get_utf8, cbb_add_utf8, {0xe0, 0x9f, 0xbf}, {}, false},
1120       {cbs_get_utf8, cbb_add_utf8, {0xf0, 0x8f, 0xbf, 0xbf}, {}, false},
1121       // 4.3  Overlong representation of the NUL character
1122       {cbs_get_utf8, cbb_add_utf8, {0xc0, 0x80}, {}, false},
1123       {cbs_get_utf8, cbb_add_utf8, {0xe0, 0x80, 0x80}, {}, false},
1124       {cbs_get_utf8, cbb_add_utf8, {0xf0, 0x80, 0x80, 0x80}, {}, false},
1125       // 5.1  Single UTF-16 surrogates
1126       {cbs_get_utf8, cbb_add_utf8, {0xed, 0xa0, 0x80}, {}, false},
1127       {cbs_get_utf8, cbb_add_utf8, {0xed, 0xad, 0xbf}, {}, false},
1128       {cbs_get_utf8, cbb_add_utf8, {0xed, 0xae, 0x80}, {}, false},
1129       {cbs_get_utf8, cbb_add_utf8, {0xed, 0xb0, 0x80}, {}, false},
1130       {cbs_get_utf8, cbb_add_utf8, {0xed, 0xbe, 0x80}, {}, false},
1131       {cbs_get_utf8, cbb_add_utf8, {0xed, 0xbf, 0xbf}, {}, false},
1132       // 5.2  Paired UTF-16 surrogates
1133       {cbs_get_utf8,
1134        cbb_add_utf8,
1135        {0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80},
1136        {},
1137        false},
1138       {cbs_get_utf8,
1139        cbb_add_utf8,
1140        {0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf},
1141        {},
1142        false},
1143       {cbs_get_utf8,
1144        cbb_add_utf8,
1145        {0xed, 0xad, 0xbf, 0xed, 0xb0, 0x80},
1146        {},
1147        false},
1148       {cbs_get_utf8,
1149        cbb_add_utf8,
1150        {0xed, 0xad, 0xbf, 0xed, 0xbf, 0xbf},
1151        {},
1152        false},
1153       {cbs_get_utf8,
1154        cbb_add_utf8,
1155        {0xed, 0xae, 0x80, 0xed, 0xb0, 0x80},
1156        {},
1157        false},
1158       {cbs_get_utf8,
1159        cbb_add_utf8,
1160        {0xed, 0xae, 0x80, 0xed, 0xbf, 0xbf},
1161        {},
1162        false},
1163       {cbs_get_utf8,
1164        cbb_add_utf8,
1165        {0xed, 0xaf, 0xbf, 0xed, 0xb0, 0x80},
1166        {},
1167        false},
1168       {cbs_get_utf8,
1169        cbb_add_utf8,
1170        {0xed, 0xaf, 0xbf, 0xed, 0xbf, 0xbf},
1171        {},
1172        false},
1173       // 5.3  Noncharacter code positions
1174       {cbs_get_utf8, cbb_add_utf8, {0xef, 0xbf, 0xbe}, {}, false},
1175       {cbs_get_utf8, cbb_add_utf8, {0xef, 0xbf, 0xbf}, {}, false},
1176       {cbs_get_utf8, cbb_add_utf8, {0xef, 0xb7, 0x90}, {}, false},
1177       {cbs_get_utf8, cbb_add_utf8, {0xef, 0xb7, 0xaf}, {}, false},
1178       {cbs_get_utf8, cbb_add_utf8, {0xf0, 0x9f, 0xbf, 0xbe}, {}, false},
1179       {cbs_get_utf8, cbb_add_utf8, {0xf0, 0x9f, 0xbf, 0xbf}, {}, false},
1180 
1181       {cbs_get_latin1, cbb_add_latin1, LiteralToBytes("\xa1Hola!"),
1182        LiteralToCodePoints(U"¡Hola!"), true},
1183 
1184       // UCS-2 matches UTF-16 on the BMP.
1185       {cbs_get_ucs2_be, cbb_add_ucs2_be, LiteralToBytes(u"Hello, 世界!"),
1186        LiteralToCodePoints(U"Hello, 世界!"), true},
1187       // It does not support characters beyond the BMP.
1188       {cbs_get_ucs2_be, cbb_add_ucs2_be,
1189        LiteralToBytes(u"Hello, 世界! ¡Hola, ��!"),
1190        LiteralToCodePoints(U"Hello, 世界! ¡Hola, "), false},
1191       // Unpaired surrogates and non-characters are also rejected.
1192       {cbs_get_ucs2_be, cbb_add_ucs2_be, {0xd8, 0x00}, {}, false},
1193       {cbs_get_ucs2_be, cbb_add_ucs2_be, {0xff, 0xfe}, {}, false},
1194 
1195       {cbs_get_utf32_be, cbb_add_utf32_be,
1196        LiteralToBytes(U"Hello, 世界! ¡Hola, ��!"),
1197        LiteralToCodePoints(U"Hello, 世界! ¡Hola, ��!"), true},
1198       // Unpaired surrogates and non-characters are rejected.
1199       {cbs_get_utf32_be, cbb_add_utf32_be, {0x00, 0x00, 0xd8, 0x00}, {}, false},
1200       {cbs_get_utf32_be, cbb_add_utf32_be, {0x00, 0x00, 0xff, 0xfe}, {}, false},
1201 
1202       // Test that the NUL character can be encoded.
1203       {cbs_get_latin1, cbb_add_latin1, {0}, {0}, true},
1204       {cbs_get_utf8, cbb_add_utf8, {0}, {0}, true},
1205       {cbs_get_ucs2_be, cbb_add_ucs2_be, {0, 0}, {0}, true},
1206       {cbs_get_utf32_be, cbb_add_utf32_be, {0, 0, 0, 0}, {0}, true},
1207   };
1208   for (const auto &t : kTests) {
1209     SCOPED_TRACE(Bytes(t.in));
1210 
1211     // Test decoding.
1212     CBS cbs;
1213     CBS_init(&cbs, t.in.data(), t.in.size());
1214     std::vector<uint32_t> out;
1215     bool ok = true;
1216     while (CBS_len(&cbs) != 0) {
1217       uint32_t u;
1218       if (!t.decode(&cbs, &u)) {
1219         ok = false;
1220         break;
1221       }
1222       out.push_back(u);
1223     }
1224     EXPECT_EQ(t.ok, ok);
1225     EXPECT_EQ(t.out, out);
1226 
1227     // Test encoding.
1228     if (t.ok) {
1229       bssl::ScopedCBB cbb;
1230       ASSERT_TRUE(CBB_init(cbb.get(), 0));
1231       for (uint32_t u : t.out) {
1232         ASSERT_TRUE(t.encode(cbb.get(), u));
1233       }
1234       EXPECT_EQ(Bytes(t.in), Bytes(CBB_data(cbb.get()), CBB_len(cbb.get())));
1235     }
1236   }
1237 
1238   static const uint32_t kBadCodePoints[] = {
1239     // Surrogate pairs.
1240     0xd800,
1241     0xdfff,
1242     // Non-characters.
1243     0xfffe,
1244     0xffff,
1245     0xfdd0,
1246     0x1fffe,
1247     0x1ffff,
1248     // Too big.
1249     0x110000,
1250   };
1251   bssl::ScopedCBB cbb;
1252   ASSERT_TRUE(CBB_init(cbb.get(), 0));
1253   for (uint32_t v : kBadCodePoints) {
1254     SCOPED_TRACE(v);
1255     EXPECT_FALSE(cbb_add_utf8(cbb.get(), v));
1256     EXPECT_FALSE(cbb_add_latin1(cbb.get(), v));
1257     EXPECT_FALSE(cbb_add_ucs2_be(cbb.get(), v));
1258     EXPECT_FALSE(cbb_add_utf32_be(cbb.get(), v));
1259   }
1260 
1261   // Additional values that are out of range.
1262   EXPECT_FALSE(cbb_add_latin1(cbb.get(), 0x100));
1263   EXPECT_FALSE(cbb_add_ucs2_be(cbb.get(), 0x10000));
1264 
1265   EXPECT_EQ(1u, cbb_get_utf8_len(0));
1266   EXPECT_EQ(1u, cbb_get_utf8_len(0x7f));
1267   EXPECT_EQ(2u, cbb_get_utf8_len(0x80));
1268   EXPECT_EQ(2u, cbb_get_utf8_len(0x7ff));
1269   EXPECT_EQ(3u, cbb_get_utf8_len(0x800));
1270   EXPECT_EQ(3u, cbb_get_utf8_len(0xffff));
1271   EXPECT_EQ(4u, cbb_get_utf8_len(0x10000));
1272   EXPECT_EQ(4u, cbb_get_utf8_len(0x10ffff));
1273 }
1274