• 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 <openssl/asn1.h>
16 #include <openssl/bytestring.h>
17 #include <openssl/mem.h>
18 
19 #include <assert.h>
20 #include <ctype.h>
21 #include <inttypes.h>
22 #include <string.h>
23 
24 #include "../asn1/internal.h"
25 #include "../internal.h"
26 #include "internal.h"
27 
28 
CBS_init(CBS * cbs,const uint8_t * data,size_t len)29 void CBS_init(CBS *cbs, const uint8_t *data, size_t len) {
30   cbs->data = data;
31   cbs->len = len;
32 }
33 
cbs_get(CBS * cbs,const uint8_t ** p,size_t n)34 static int cbs_get(CBS *cbs, const uint8_t **p, size_t n) {
35   if (cbs->len < n) {
36     return 0;
37   }
38 
39   *p = cbs->data;
40   cbs->data += n;
41   cbs->len -= n;
42   return 1;
43 }
44 
CBS_skip(CBS * cbs,size_t len)45 int CBS_skip(CBS *cbs, size_t len) {
46   const uint8_t *dummy;
47   return cbs_get(cbs, &dummy, len);
48 }
49 
CBS_data(const CBS * cbs)50 const uint8_t *CBS_data(const CBS *cbs) {
51   return cbs->data;
52 }
53 
CBS_len(const CBS * cbs)54 size_t CBS_len(const CBS *cbs) {
55   return cbs->len;
56 }
57 
CBS_stow(const CBS * cbs,uint8_t ** out_ptr,size_t * out_len)58 int CBS_stow(const CBS *cbs, uint8_t **out_ptr, size_t *out_len) {
59   OPENSSL_free(*out_ptr);
60   *out_ptr = NULL;
61   *out_len = 0;
62 
63   if (cbs->len == 0) {
64     return 1;
65   }
66   *out_ptr = OPENSSL_memdup(cbs->data, cbs->len);
67   if (*out_ptr == NULL) {
68     return 0;
69   }
70   *out_len = cbs->len;
71   return 1;
72 }
73 
CBS_strdup(const CBS * cbs,char ** out_ptr)74 int CBS_strdup(const CBS *cbs, char **out_ptr) {
75   if (*out_ptr != NULL) {
76     OPENSSL_free(*out_ptr);
77   }
78   *out_ptr = OPENSSL_strndup((const char*)cbs->data, cbs->len);
79   return (*out_ptr != NULL);
80 }
81 
CBS_contains_zero_byte(const CBS * cbs)82 int CBS_contains_zero_byte(const CBS *cbs) {
83   return OPENSSL_memchr(cbs->data, 0, cbs->len) != NULL;
84 }
85 
CBS_mem_equal(const CBS * cbs,const uint8_t * data,size_t len)86 int CBS_mem_equal(const CBS *cbs, const uint8_t *data, size_t len) {
87   if (len != cbs->len) {
88     return 0;
89   }
90   return CRYPTO_memcmp(cbs->data, data, len) == 0;
91 }
92 
cbs_get_u(CBS * cbs,uint64_t * out,size_t len)93 static int cbs_get_u(CBS *cbs, uint64_t *out, size_t len) {
94   uint64_t result = 0;
95   const uint8_t *data;
96 
97   if (!cbs_get(cbs, &data, len)) {
98     return 0;
99   }
100   for (size_t i = 0; i < len; i++) {
101     result <<= 8;
102     result |= data[i];
103   }
104   *out = result;
105   return 1;
106 }
107 
CBS_get_u8(CBS * cbs,uint8_t * out)108 int CBS_get_u8(CBS *cbs, uint8_t *out) {
109   const uint8_t *v;
110   if (!cbs_get(cbs, &v, 1)) {
111     return 0;
112   }
113   *out = *v;
114   return 1;
115 }
116 
CBS_get_u16(CBS * cbs,uint16_t * out)117 int CBS_get_u16(CBS *cbs, uint16_t *out) {
118   uint64_t v;
119   if (!cbs_get_u(cbs, &v, 2)) {
120     return 0;
121   }
122   *out = v;
123   return 1;
124 }
125 
CBS_get_u16le(CBS * cbs,uint16_t * out)126 int CBS_get_u16le(CBS *cbs, uint16_t *out) {
127   if (!CBS_get_u16(cbs, out)) {
128     return 0;
129   }
130   *out = CRYPTO_bswap2(*out);
131   return 1;
132 }
133 
CBS_get_u24(CBS * cbs,uint32_t * out)134 int CBS_get_u24(CBS *cbs, uint32_t *out) {
135   uint64_t v;
136   if (!cbs_get_u(cbs, &v, 3)) {
137     return 0;
138   }
139   *out = (uint32_t)v;
140   return 1;
141 }
142 
CBS_get_u32(CBS * cbs,uint32_t * out)143 int CBS_get_u32(CBS *cbs, uint32_t *out) {
144   uint64_t v;
145   if (!cbs_get_u(cbs, &v, 4)) {
146     return 0;
147   }
148   *out = (uint32_t)v;
149   return 1;
150 }
151 
CBS_get_u32le(CBS * cbs,uint32_t * out)152 int CBS_get_u32le(CBS *cbs, uint32_t *out) {
153   if (!CBS_get_u32(cbs, out)) {
154     return 0;
155   }
156   *out = CRYPTO_bswap4(*out);
157   return 1;
158 }
159 
CBS_get_u64(CBS * cbs,uint64_t * out)160 int CBS_get_u64(CBS *cbs, uint64_t *out) {
161   return cbs_get_u(cbs, out, 8);
162 }
163 
CBS_get_u64le(CBS * cbs,uint64_t * out)164 int CBS_get_u64le(CBS *cbs, uint64_t *out) {
165   if (!cbs_get_u(cbs, out, 8)) {
166     return 0;
167   }
168   *out = CRYPTO_bswap8(*out);
169   return 1;
170 }
171 
CBS_get_last_u8(CBS * cbs,uint8_t * out)172 int CBS_get_last_u8(CBS *cbs, uint8_t *out) {
173   if (cbs->len == 0) {
174     return 0;
175   }
176   *out = cbs->data[cbs->len - 1];
177   cbs->len--;
178   return 1;
179 }
180 
CBS_get_bytes(CBS * cbs,CBS * out,size_t len)181 int CBS_get_bytes(CBS *cbs, CBS *out, size_t len) {
182   const uint8_t *v;
183   if (!cbs_get(cbs, &v, len)) {
184     return 0;
185   }
186   CBS_init(out, v, len);
187   return 1;
188 }
189 
CBS_copy_bytes(CBS * cbs,uint8_t * out,size_t len)190 int CBS_copy_bytes(CBS *cbs, uint8_t *out, size_t len) {
191   const uint8_t *v;
192   if (!cbs_get(cbs, &v, len)) {
193     return 0;
194   }
195   OPENSSL_memcpy(out, v, len);
196   return 1;
197 }
198 
cbs_get_length_prefixed(CBS * cbs,CBS * out,size_t len_len)199 static int cbs_get_length_prefixed(CBS *cbs, CBS *out, size_t len_len) {
200   uint64_t len;
201   if (!cbs_get_u(cbs, &len, len_len)) {
202     return 0;
203   }
204   // If |len_len| <= 3 then we know that |len| will fit into a |size_t|, even on
205   // 32-bit systems.
206   assert(len_len <= 3);
207   return CBS_get_bytes(cbs, out, len);
208 }
209 
CBS_get_u8_length_prefixed(CBS * cbs,CBS * out)210 int CBS_get_u8_length_prefixed(CBS *cbs, CBS *out) {
211   return cbs_get_length_prefixed(cbs, out, 1);
212 }
213 
CBS_get_u16_length_prefixed(CBS * cbs,CBS * out)214 int CBS_get_u16_length_prefixed(CBS *cbs, CBS *out) {
215   return cbs_get_length_prefixed(cbs, out, 2);
216 }
217 
CBS_get_u24_length_prefixed(CBS * cbs,CBS * out)218 int CBS_get_u24_length_prefixed(CBS *cbs, CBS *out) {
219   return cbs_get_length_prefixed(cbs, out, 3);
220 }
221 
CBS_get_until_first(CBS * cbs,CBS * out,uint8_t c)222 int CBS_get_until_first(CBS *cbs, CBS *out, uint8_t c) {
223   const uint8_t *split = OPENSSL_memchr(CBS_data(cbs), c, CBS_len(cbs));
224   if (split == NULL) {
225     return 0;
226   }
227   return CBS_get_bytes(cbs, out, split - CBS_data(cbs));
228 }
229 
CBS_get_u64_decimal(CBS * cbs,uint64_t * out)230 int CBS_get_u64_decimal(CBS *cbs, uint64_t *out) {
231   uint64_t v = 0;
232   int seen_digit = 0;
233   while (CBS_len(cbs) != 0) {
234     uint8_t c = CBS_data(cbs)[0];
235     if (!OPENSSL_isdigit(c)) {
236       break;
237     }
238     CBS_skip(cbs, 1);
239     if (// Forbid stray leading zeros.
240         (v == 0 && seen_digit) ||
241         // Check for overflow.
242         v > UINT64_MAX / 10 ||  //
243         v * 10 > UINT64_MAX - (c - '0')) {
244       return 0;
245     }
246     v = v * 10 + (c - '0');
247     seen_digit = 1;
248   }
249 
250   *out = v;
251   return seen_digit;
252 }
253 
254 // parse_base128_integer reads a big-endian base-128 integer from |cbs| and sets
255 // |*out| to the result. This is the encoding used in DER for both high tag
256 // number form and OID components.
parse_base128_integer(CBS * cbs,uint64_t * out)257 static int parse_base128_integer(CBS *cbs, uint64_t *out) {
258   uint64_t v = 0;
259   uint8_t b;
260   do {
261     if (!CBS_get_u8(cbs, &b)) {
262       return 0;
263     }
264     if ((v >> (64 - 7)) != 0) {
265       // The value is too large.
266       return 0;
267     }
268     if (v == 0 && b == 0x80) {
269       // The value must be minimally encoded.
270       return 0;
271     }
272     v = (v << 7) | (b & 0x7f);
273 
274     // Values end at an octet with the high bit cleared.
275   } while (b & 0x80);
276 
277   *out = v;
278   return 1;
279 }
280 
parse_asn1_tag(CBS * cbs,CBS_ASN1_TAG * out)281 static int parse_asn1_tag(CBS *cbs, CBS_ASN1_TAG *out) {
282   uint8_t tag_byte;
283   if (!CBS_get_u8(cbs, &tag_byte)) {
284     return 0;
285   }
286 
287   // ITU-T X.690 section 8.1.2.3 specifies the format for identifiers with a tag
288   // number no greater than 30.
289   //
290   // If the number portion is 31 (0x1f, the largest value that fits in the
291   // allotted bits), then the tag is more than one byte long and the
292   // continuation bytes contain the tag number.
293   CBS_ASN1_TAG tag = ((CBS_ASN1_TAG)tag_byte & 0xe0) << CBS_ASN1_TAG_SHIFT;
294   CBS_ASN1_TAG tag_number = tag_byte & 0x1f;
295   if (tag_number == 0x1f) {
296     uint64_t v;
297     if (!parse_base128_integer(cbs, &v) ||
298         // Check the tag number is within our supported bounds.
299         v > CBS_ASN1_TAG_NUMBER_MASK ||
300         // Small tag numbers should have used low tag number form, even in BER.
301         v < 0x1f) {
302       return 0;
303     }
304     tag_number = (CBS_ASN1_TAG)v;
305   }
306 
307   tag |= tag_number;
308 
309   // Tag [UNIVERSAL 0] is reserved for use by the encoding. Reject it here to
310   // avoid some ambiguity around ANY values and BER indefinite-length EOCs. See
311   // https://crbug.com/boringssl/455.
312   if ((tag & ~CBS_ASN1_CONSTRUCTED) == 0) {
313     return 0;
314   }
315 
316   *out = tag;
317   return 1;
318 }
319 
cbs_get_any_asn1_element(CBS * cbs,CBS * out,CBS_ASN1_TAG * out_tag,size_t * out_header_len,int * out_ber_found,int * out_indefinite,int ber_ok)320 static int cbs_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
321                                     size_t *out_header_len, int *out_ber_found,
322                                     int *out_indefinite, int ber_ok) {
323   CBS header = *cbs;
324   CBS throwaway;
325 
326   if (out == NULL) {
327     out = &throwaway;
328   }
329   if (ber_ok) {
330     *out_ber_found = 0;
331     *out_indefinite = 0;
332   } else {
333     assert(out_ber_found == NULL);
334     assert(out_indefinite == NULL);
335   }
336 
337   CBS_ASN1_TAG tag;
338   if (!parse_asn1_tag(&header, &tag)) {
339     return 0;
340   }
341   if (out_tag != NULL) {
342     *out_tag = tag;
343   }
344 
345   uint8_t length_byte;
346   if (!CBS_get_u8(&header, &length_byte)) {
347     return 0;
348   }
349 
350   size_t header_len = CBS_len(cbs) - CBS_len(&header);
351 
352   size_t len;
353   // The format for the length encoding is specified in ITU-T X.690 section
354   // 8.1.3.
355   if ((length_byte & 0x80) == 0) {
356     // Short form length.
357     len = ((size_t) length_byte) + header_len;
358     if (out_header_len != NULL) {
359       *out_header_len = header_len;
360     }
361   } else {
362     // The high bit indicate that this is the long form, while the next 7 bits
363     // encode the number of subsequent octets used to encode the length (ITU-T
364     // X.690 clause 8.1.3.5.b).
365     const size_t num_bytes = length_byte & 0x7f;
366     uint64_t len64;
367 
368     if (ber_ok && (tag & CBS_ASN1_CONSTRUCTED) != 0 && num_bytes == 0) {
369       // indefinite length
370       if (out_header_len != NULL) {
371         *out_header_len = header_len;
372       }
373       *out_ber_found = 1;
374       *out_indefinite = 1;
375       return CBS_get_bytes(cbs, out, header_len);
376     }
377 
378     // ITU-T X.690 clause 8.1.3.5.c specifies that the value 0xff shall not be
379     // used as the first byte of the length. If this parser encounters that
380     // value, num_bytes will be parsed as 127, which will fail this check.
381     if (num_bytes == 0 || num_bytes > 4) {
382       return 0;
383     }
384     if (!cbs_get_u(&header, &len64, num_bytes)) {
385       return 0;
386     }
387     // ITU-T X.690 section 10.1 (DER length forms) requires encoding the
388     // length with the minimum number of octets. BER could, technically, have
389     // 125 superfluous zero bytes. We do not attempt to handle that and still
390     // require that the length fit in a |uint32_t| for BER.
391     if (len64 < 128) {
392       // Length should have used short-form encoding.
393       if (ber_ok) {
394         *out_ber_found = 1;
395       } else {
396         return 0;
397       }
398     }
399     if ((len64 >> ((num_bytes - 1) * 8)) == 0) {
400       // Length should have been at least one byte shorter.
401       if (ber_ok) {
402         *out_ber_found = 1;
403       } else {
404         return 0;
405       }
406     }
407     len = len64;
408     if (len + header_len + num_bytes < len) {
409       // Overflow.
410       return 0;
411     }
412     len += header_len + num_bytes;
413     if (out_header_len != NULL) {
414       *out_header_len = header_len + num_bytes;
415     }
416   }
417 
418   return CBS_get_bytes(cbs, out, len);
419 }
420 
CBS_get_any_asn1(CBS * cbs,CBS * out,CBS_ASN1_TAG * out_tag)421 int CBS_get_any_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag) {
422   size_t header_len;
423   if (!CBS_get_any_asn1_element(cbs, out, out_tag, &header_len)) {
424     return 0;
425   }
426 
427   if (!CBS_skip(out, header_len)) {
428     assert(0);
429     return 0;
430   }
431 
432   return 1;
433 }
434 
CBS_get_any_asn1_element(CBS * cbs,CBS * out,CBS_ASN1_TAG * out_tag,size_t * out_header_len)435 int CBS_get_any_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
436                                     size_t *out_header_len) {
437   return cbs_get_any_asn1_element(cbs, out, out_tag, out_header_len, NULL, NULL,
438                                   /*ber_ok=*/0);
439 }
440 
CBS_get_any_ber_asn1_element(CBS * cbs,CBS * out,CBS_ASN1_TAG * out_tag,size_t * out_header_len,int * out_ber_found,int * out_indefinite)441 int CBS_get_any_ber_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG *out_tag,
442                                  size_t *out_header_len, int *out_ber_found,
443                                  int *out_indefinite) {
444   int ber_found_temp;
445   return cbs_get_any_asn1_element(
446       cbs, out, out_tag, out_header_len,
447       out_ber_found ? out_ber_found : &ber_found_temp, out_indefinite,
448       /*ber_ok=*/1);
449 }
450 
cbs_get_asn1(CBS * cbs,CBS * out,CBS_ASN1_TAG tag_value,int skip_header)451 static int cbs_get_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value,
452                         int skip_header) {
453   size_t header_len;
454   CBS_ASN1_TAG tag;
455   CBS throwaway;
456 
457   if (out == NULL) {
458     out = &throwaway;
459   }
460 
461   if (!CBS_get_any_asn1_element(cbs, out, &tag, &header_len) ||
462       tag != tag_value) {
463     return 0;
464   }
465 
466   if (skip_header && !CBS_skip(out, header_len)) {
467     assert(0);
468     return 0;
469   }
470 
471   return 1;
472 }
473 
CBS_get_asn1(CBS * cbs,CBS * out,CBS_ASN1_TAG tag_value)474 int CBS_get_asn1(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value) {
475   return cbs_get_asn1(cbs, out, tag_value, 1 /* skip header */);
476 }
477 
CBS_get_asn1_element(CBS * cbs,CBS * out,CBS_ASN1_TAG tag_value)478 int CBS_get_asn1_element(CBS *cbs, CBS *out, CBS_ASN1_TAG tag_value) {
479   return cbs_get_asn1(cbs, out, tag_value, 0 /* include header */);
480 }
481 
CBS_peek_asn1_tag(const CBS * cbs,CBS_ASN1_TAG tag_value)482 int CBS_peek_asn1_tag(const CBS *cbs, CBS_ASN1_TAG tag_value) {
483   CBS copy = *cbs;
484   CBS_ASN1_TAG actual_tag;
485   return parse_asn1_tag(&copy, &actual_tag) && tag_value == actual_tag;
486 }
487 
CBS_get_asn1_uint64(CBS * cbs,uint64_t * out)488 int CBS_get_asn1_uint64(CBS *cbs, uint64_t *out) {
489   CBS bytes;
490   if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER) ||
491       !CBS_is_unsigned_asn1_integer(&bytes)) {
492     return 0;
493   }
494 
495   *out = 0;
496   const uint8_t *data = CBS_data(&bytes);
497   size_t len = CBS_len(&bytes);
498   for (size_t i = 0; i < len; i++) {
499     if ((*out >> 56) != 0) {
500       // Too large to represent as a uint64_t.
501       return 0;
502     }
503     *out <<= 8;
504     *out |= data[i];
505   }
506 
507   return 1;
508 }
509 
CBS_get_asn1_int64(CBS * cbs,int64_t * out)510 int CBS_get_asn1_int64(CBS *cbs, int64_t *out) {
511   int is_negative;
512   CBS bytes;
513   if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_INTEGER) ||
514       !CBS_is_valid_asn1_integer(&bytes, &is_negative)) {
515     return 0;
516   }
517   const uint8_t *data = CBS_data(&bytes);
518   const size_t len = CBS_len(&bytes);
519   if (len > sizeof(int64_t)) {
520     return 0;
521   }
522   uint8_t sign_extend[sizeof(int64_t)];
523   memset(sign_extend, is_negative ? 0xff : 0, sizeof(sign_extend));
524   for (size_t i = 0; i < len; i++) {
525     sign_extend[i] = data[len - i - 1];
526   }
527   memcpy(out, sign_extend, sizeof(sign_extend));
528   return 1;
529 }
530 
CBS_get_asn1_bool(CBS * cbs,int * out)531 int CBS_get_asn1_bool(CBS *cbs, int *out) {
532   CBS bytes;
533   if (!CBS_get_asn1(cbs, &bytes, CBS_ASN1_BOOLEAN) ||
534       CBS_len(&bytes) != 1) {
535     return 0;
536   }
537 
538   const uint8_t value = *CBS_data(&bytes);
539   if (value != 0 && value != 0xff) {
540     return 0;
541   }
542 
543   *out = !!value;
544   return 1;
545 }
546 
CBS_get_optional_asn1(CBS * cbs,CBS * out,int * out_present,CBS_ASN1_TAG tag)547 int CBS_get_optional_asn1(CBS *cbs, CBS *out, int *out_present, CBS_ASN1_TAG tag) {
548   int present = 0;
549 
550   if (CBS_peek_asn1_tag(cbs, tag)) {
551     if (!CBS_get_asn1(cbs, out, tag)) {
552       return 0;
553     }
554     present = 1;
555   }
556 
557   if (out_present != NULL) {
558     *out_present = present;
559   }
560 
561   return 1;
562 }
563 
CBS_get_optional_asn1_octet_string(CBS * cbs,CBS * out,int * out_present,CBS_ASN1_TAG tag)564 int CBS_get_optional_asn1_octet_string(CBS *cbs, CBS *out, int *out_present,
565                                        CBS_ASN1_TAG tag) {
566   CBS child;
567   int present;
568   if (!CBS_get_optional_asn1(cbs, &child, &present, tag)) {
569     return 0;
570   }
571   if (present) {
572     assert(out);
573     if (!CBS_get_asn1(&child, out, CBS_ASN1_OCTETSTRING) ||
574         CBS_len(&child) != 0) {
575       return 0;
576     }
577   } else {
578     CBS_init(out, NULL, 0);
579   }
580   if (out_present) {
581     *out_present = present;
582   }
583   return 1;
584 }
585 
CBS_get_optional_asn1_uint64(CBS * cbs,uint64_t * out,CBS_ASN1_TAG tag,uint64_t default_value)586 int CBS_get_optional_asn1_uint64(CBS *cbs, uint64_t *out, CBS_ASN1_TAG tag,
587                                  uint64_t default_value) {
588   CBS child;
589   int present;
590   if (!CBS_get_optional_asn1(cbs, &child, &present, tag)) {
591     return 0;
592   }
593   if (present) {
594     if (!CBS_get_asn1_uint64(&child, out) ||
595         CBS_len(&child) != 0) {
596       return 0;
597     }
598   } else {
599     *out = default_value;
600   }
601   return 1;
602 }
603 
CBS_get_optional_asn1_bool(CBS * cbs,int * out,CBS_ASN1_TAG tag,int default_value)604 int CBS_get_optional_asn1_bool(CBS *cbs, int *out, CBS_ASN1_TAG tag,
605                                int default_value) {
606   CBS child, child2;
607   int present;
608   if (!CBS_get_optional_asn1(cbs, &child, &present, tag)) {
609     return 0;
610   }
611   if (present) {
612     uint8_t boolean;
613 
614     if (!CBS_get_asn1(&child, &child2, CBS_ASN1_BOOLEAN) ||
615         CBS_len(&child2) != 1 ||
616         CBS_len(&child) != 0) {
617       return 0;
618     }
619 
620     boolean = CBS_data(&child2)[0];
621     if (boolean == 0) {
622       *out = 0;
623     } else if (boolean == 0xff) {
624       *out = 1;
625     } else {
626       return 0;
627     }
628   } else {
629     *out = default_value;
630   }
631   return 1;
632 }
633 
CBS_is_valid_asn1_bitstring(const CBS * cbs)634 int CBS_is_valid_asn1_bitstring(const CBS *cbs) {
635   CBS in = *cbs;
636   uint8_t num_unused_bits;
637   if (!CBS_get_u8(&in, &num_unused_bits) ||
638       num_unused_bits > 7) {
639     return 0;
640   }
641 
642   if (num_unused_bits == 0) {
643     return 1;
644   }
645 
646   // All num_unused_bits bits must exist and be zeros.
647   uint8_t last;
648   if (!CBS_get_last_u8(&in, &last) ||
649       (last & ((1 << num_unused_bits) - 1)) != 0) {
650     return 0;
651   }
652 
653   return 1;
654 }
655 
CBS_asn1_bitstring_has_bit(const CBS * cbs,unsigned bit)656 int CBS_asn1_bitstring_has_bit(const CBS *cbs, unsigned bit) {
657   if (!CBS_is_valid_asn1_bitstring(cbs)) {
658     return 0;
659   }
660 
661   const unsigned byte_num = (bit >> 3) + 1;
662   const unsigned bit_num = 7 - (bit & 7);
663 
664   // Unused bits are zero, and this function does not distinguish between
665   // missing and unset bits. Thus it is sufficient to do a byte-level length
666   // check.
667   return byte_num < CBS_len(cbs) &&
668          (CBS_data(cbs)[byte_num] & (1 << bit_num)) != 0;
669 }
670 
CBS_is_valid_asn1_integer(const CBS * cbs,int * out_is_negative)671 int CBS_is_valid_asn1_integer(const CBS *cbs, int *out_is_negative) {
672   CBS copy = *cbs;
673   uint8_t first_byte, second_byte;
674   if (!CBS_get_u8(&copy, &first_byte)) {
675     return 0;  // INTEGERs may not be empty.
676   }
677   if (out_is_negative != NULL) {
678     *out_is_negative = (first_byte & 0x80) != 0;
679   }
680   if (!CBS_get_u8(&copy, &second_byte)) {
681     return 1;  // One byte INTEGERs are always minimal.
682   }
683   if ((first_byte == 0x00 && (second_byte & 0x80) == 0) ||
684       (first_byte == 0xff && (second_byte & 0x80) != 0)) {
685     return 0;  // The value is minimal iff the first 9 bits are not all equal.
686   }
687   return 1;
688 }
689 
CBS_is_unsigned_asn1_integer(const CBS * cbs)690 int CBS_is_unsigned_asn1_integer(const CBS *cbs) {
691   int is_negative;
692   return CBS_is_valid_asn1_integer(cbs, &is_negative) && !is_negative;
693 }
694 
add_decimal(CBB * out,uint64_t v)695 static int add_decimal(CBB *out, uint64_t v) {
696   char buf[DECIMAL_SIZE(uint64_t) + 1];
697   BIO_snprintf(buf, sizeof(buf), "%" PRIu64, v);
698   return CBB_add_bytes(out, (const uint8_t *)buf, strlen(buf));
699 }
700 
CBS_is_valid_asn1_oid(const CBS * cbs)701 int CBS_is_valid_asn1_oid(const CBS *cbs) {
702   if (CBS_len(cbs) == 0) {
703     return 0;  // OID encodings cannot be empty.
704   }
705 
706   CBS copy = *cbs;
707   uint8_t v, prev = 0;
708   while (CBS_get_u8(&copy, &v)) {
709     // OID encodings are a sequence of minimally-encoded base-128 integers (see
710     // |parse_base128_integer|). If |prev|'s MSB was clear, it was the last byte
711     // of an integer (or |v| is the first byte). |v| is then the first byte of
712     // the next integer. If first byte of an integer is 0x80, it is not
713     // minimally-encoded.
714     if ((prev & 0x80) == 0 && v == 0x80) {
715       return 0;
716     }
717     prev = v;
718   }
719 
720   // The last byte should must end an integer encoding.
721   return (prev & 0x80) == 0;
722 }
723 
CBS_asn1_oid_to_text(const CBS * cbs)724 char *CBS_asn1_oid_to_text(const CBS *cbs) {
725   CBB cbb;
726   if (!CBB_init(&cbb, 32)) {
727     goto err;
728   }
729 
730   CBS copy = *cbs;
731   // The first component is 40 * value1 + value2, where value1 is 0, 1, or 2.
732   uint64_t v;
733   if (!parse_base128_integer(&copy, &v)) {
734     goto err;
735   }
736 
737   if (v >= 80) {
738     if (!CBB_add_bytes(&cbb, (const uint8_t *)"2.", 2) ||
739         !add_decimal(&cbb, v - 80)) {
740       goto err;
741     }
742   } else if (!add_decimal(&cbb, v / 40) ||
743              !CBB_add_u8(&cbb, '.') ||
744              !add_decimal(&cbb, v % 40)) {
745     goto err;
746   }
747 
748   while (CBS_len(&copy) != 0) {
749     if (!parse_base128_integer(&copy, &v) ||
750         !CBB_add_u8(&cbb, '.') ||
751         !add_decimal(&cbb, v)) {
752       goto err;
753     }
754   }
755 
756   uint8_t *txt;
757   size_t txt_len;
758   if (!CBB_add_u8(&cbb, '\0') ||
759       !CBB_finish(&cbb, &txt, &txt_len)) {
760     goto err;
761   }
762 
763   return (char *)txt;
764 
765 err:
766   CBB_cleanup(&cbb);
767   return NULL;
768 }
769 
cbs_get_two_digits(CBS * cbs,int * out)770 static int cbs_get_two_digits(CBS *cbs, int *out) {
771   uint8_t first_digit, second_digit;
772   if (!CBS_get_u8(cbs, &first_digit)) {
773     return 0;
774   }
775   if (!OPENSSL_isdigit(first_digit)) {
776     return 0;
777   }
778   if (!CBS_get_u8(cbs, &second_digit)) {
779     return 0;
780   }
781   if (!OPENSSL_isdigit(second_digit)) {
782     return 0;
783   }
784   *out = (first_digit - '0') * 10 + (second_digit - '0');
785   return 1;
786 }
787 
is_valid_day(int year,int month,int day)788 static int is_valid_day(int year, int month, int day) {
789   if (day < 1) {
790     return 0;
791   }
792   switch (month) {
793     case 1:
794     case 3:
795     case 5:
796     case 7:
797     case 8:
798     case 10:
799     case 12:
800       return day <= 31;
801     case 4:
802     case 6:
803     case 9:
804     case 11:
805       return day <= 30;
806     case 2:
807       if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
808         return day <= 29;
809       } else {
810         return day <= 28;
811       }
812     default:
813       return 0;
814   }
815 }
816 
CBS_parse_rfc5280_time_internal(const CBS * cbs,int is_gentime,int allow_timezone_offset,struct tm * out_tm)817 static int CBS_parse_rfc5280_time_internal(const CBS *cbs, int is_gentime,
818                                            int allow_timezone_offset,
819                                            struct tm *out_tm) {
820   int year, month, day, hour, min, sec, tmp;
821   CBS copy = *cbs;
822   uint8_t tz;
823 
824   if (is_gentime) {
825     if (!cbs_get_two_digits(&copy, &tmp)) {
826       return 0;
827     }
828     year = tmp * 100;
829     if (!cbs_get_two_digits(&copy, &tmp)) {
830       return 0;
831     }
832       year += tmp;
833   } else {
834     year = 1900;
835     if (!cbs_get_two_digits(&copy, &tmp)) {
836       return 0;
837     }
838     year += tmp;
839     if (year < 1950) {
840       year += 100;
841     }
842     if (year >= 2050) {
843       return 0;  // A Generalized time must be used.
844     }
845   }
846   if (!cbs_get_two_digits(&copy, &month) || month < 1 ||
847       month > 12 ||  // Reject invalid months.
848       !cbs_get_two_digits(&copy, &day) ||
849       !is_valid_day(year, month, day) ||  // Reject invalid days.
850       !cbs_get_two_digits(&copy, &hour) ||
851       hour > 23 ||  // Reject invalid hours.
852       !cbs_get_two_digits(&copy, &min) ||
853       min > 59 ||  // Reject invalid minutes.
854       !cbs_get_two_digits(&copy, &sec) || sec > 59 || !CBS_get_u8(&copy, &tz)) {
855     return 0;
856   }
857 
858   int offset_sign = 0;
859   switch (tz) {
860     case 'Z':
861       break;  // We correctly have 'Z' on the end as per spec.
862     case '+':
863       offset_sign = 1;
864       break;  // Should not be allowed per RFC 5280.
865     case '-':
866       offset_sign = -1;
867       break;  // Should not be allowed per RFC 5280.
868     default:
869       return 0;  // Reject anything else after the time.
870   }
871 
872   // If allow_timezone_offset is non-zero, allow for a four digit timezone
873   // offset to be specified even though this is not allowed by RFC 5280. We are
874   // permissive of this for UTCTimes due to the unfortunate existence of
875   // artisinally rolled long lived certificates that were baked into places that
876   // are now difficult to change. These certificates were generated with the
877   // 'openssl' command that permissively allowed the creation of certificates
878   // with notBefore and notAfter times specified as strings for direct
879   // certificate inclusion on the command line. For context see cl/237068815.
880   //
881   // TODO(bbe): This has been expunged from public web-pki as the ecosystem has
882   // managed to encourage CA compliance with standards. We should find a way to
883   // get rid of this or make it off by default.
884   int offset_seconds = 0;
885   if (offset_sign != 0) {
886     if (!allow_timezone_offset) {
887       return 0;
888     }
889     int offset_hours, offset_minutes;
890     if (!cbs_get_two_digits(&copy, &offset_hours) ||
891         offset_hours > 23 ||  // Reject invalid hours.
892         !cbs_get_two_digits(&copy, &offset_minutes) ||
893         offset_minutes > 59) {  // Reject invalid minutes.
894       return 0;
895     }
896     offset_seconds = offset_sign * (offset_hours * 3600 + offset_minutes * 60);
897   }
898 
899   if (CBS_len(&copy) != 0) {
900     return 0;  // Reject invalid lengths.
901   }
902 
903   if (out_tm != NULL) {
904     // Fill in the tm fields corresponding to what we validated.
905     out_tm->tm_year = year - 1900;
906     out_tm->tm_mon = month - 1;
907     out_tm->tm_mday = day;
908     out_tm->tm_hour = hour;
909     out_tm->tm_min = min;
910     out_tm->tm_sec = sec;
911     if (offset_seconds && !OPENSSL_gmtime_adj(out_tm, 0, offset_seconds)) {
912       return 0;
913     }
914   }
915   return 1;
916 }
917 
CBS_parse_generalized_time(const CBS * cbs,struct tm * out_tm,int allow_timezone_offset)918 int CBS_parse_generalized_time(const CBS *cbs, struct tm *out_tm,
919                                int allow_timezone_offset) {
920   return CBS_parse_rfc5280_time_internal(cbs, 1, allow_timezone_offset, out_tm);
921 }
922 
CBS_parse_utc_time(const CBS * cbs,struct tm * out_tm,int allow_timezone_offset)923 int CBS_parse_utc_time(const CBS *cbs, struct tm *out_tm,
924                        int allow_timezone_offset) {
925   return CBS_parse_rfc5280_time_internal(cbs, 0, allow_timezone_offset, out_tm);
926 }
927