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