1 // Copyright 2015 The Chromium Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "parse_values.h"
16 
17 #include <stdlib.h>
18 
19 #include <tuple>
20 
21 #include <openssl/base.h>
22 #include <openssl/bytestring.h>
23 #include <openssl/mem.h>
24 
25 BSSL_NAMESPACE_BEGIN
26 namespace der {
27 
28 namespace {
29 
ParseBoolInternal(Input in,bool * out,bool relaxed)30 bool ParseBoolInternal(Input in, bool *out, bool relaxed) {
31   // According to ITU-T X.690 section 8.2, a bool is encoded as a single octet
32   // where the octet of all zeroes is FALSE and a non-zero value for the octet
33   // is TRUE.
34   if (in.size() != 1) {
35     return false;
36   }
37   ByteReader data(in);
38   uint8_t byte;
39   if (!data.ReadByte(&byte)) {
40     return false;
41   }
42   if (byte == 0) {
43     *out = false;
44     return true;
45   }
46   // ITU-T X.690 section 11.1 specifies that for DER, the TRUE value must be
47   // encoded as an octet of all ones.
48   if (byte == 0xff || relaxed) {
49     *out = true;
50     return true;
51   }
52   return false;
53 }
54 
55 // Reads a positive decimal number with |digits| digits and stores it in
56 // |*out|. This function does not check that the type of |*out| is large
57 // enough to hold 10^digits - 1; the caller must choose an appropriate type
58 // based on the number of digits they wish to parse.
59 template <typename UINT>
DecimalStringToUint(ByteReader & in,size_t digits,UINT * out)60 bool DecimalStringToUint(ByteReader &in, size_t digits, UINT *out) {
61   UINT value = 0;
62   for (size_t i = 0; i < digits; ++i) {
63     uint8_t digit;
64     if (!in.ReadByte(&digit)) {
65       return false;
66     }
67     if (digit < '0' || digit > '9') {
68       return false;
69     }
70     value = (value * 10) + (digit - '0');
71   }
72   *out = value;
73   return true;
74 }
75 
76 // Checks that the values in a GeneralizedTime struct are valid. This involves
77 // checking that the year is 4 digits, the month is between 1 and 12, the day
78 // is a day that exists in that month (following current leap year rules),
79 // hours are between 0 and 23, minutes between 0 and 59, and seconds between
80 // 0 and 60 (to allow for leap seconds; no validation is done that a leap
81 // second is on a day that could be a leap second).
ValidateGeneralizedTime(const GeneralizedTime & time)82 bool ValidateGeneralizedTime(const GeneralizedTime &time) {
83   if (time.month < 1 || time.month > 12) {
84     return false;
85   }
86   if (time.day < 1) {
87     return false;
88   }
89   if (time.hours > 23) {
90     return false;
91   }
92   if (time.minutes > 59) {
93     return false;
94   }
95   // Leap seconds are allowed.
96   if (time.seconds > 60) {
97     return false;
98   }
99 
100   // validate upper bound for day of month
101   switch (time.month) {
102     case 4:
103     case 6:
104     case 9:
105     case 11:
106       if (time.day > 30) {
107         return false;
108       }
109       break;
110     case 1:
111     case 3:
112     case 5:
113     case 7:
114     case 8:
115     case 10:
116     case 12:
117       if (time.day > 31) {
118         return false;
119       }
120       break;
121     case 2:
122       if (time.year % 4 == 0 &&
123           (time.year % 100 != 0 || time.year % 400 == 0)) {
124         if (time.day > 29) {
125           return false;
126         }
127       } else {
128         if (time.day > 28) {
129           return false;
130         }
131       }
132       break;
133     default:
134       abort();
135   }
136   return true;
137 }
138 
139 // Returns the number of bytes of numeric precision in a DER encoded INTEGER
140 // value. |in| must be a valid DER encoding of an INTEGER for this to work.
141 //
142 // Normally the precision of the number is exactly in.size(). However when
143 // encoding positive numbers using DER it is possible to have a leading zero
144 // (to prevent number from being interpreted as negative).
145 //
146 // For instance a 160-bit positive number might take 21 bytes to encode. This
147 // function will return 20 in such a case.
GetUnsignedIntegerLength(Input in)148 size_t GetUnsignedIntegerLength(Input in) {
149   der::ByteReader reader(in);
150   uint8_t first_byte;
151   if (!reader.ReadByte(&first_byte)) {
152     return 0;  // Not valid DER  as |in| was empty.
153   }
154 
155   if (first_byte == 0 && in.size() > 1) {
156     return in.size() - 1;
157   }
158   return in.size();
159 }
160 
161 }  // namespace
162 
ParseBool(Input in,bool * out)163 bool ParseBool(Input in, bool *out) {
164   return ParseBoolInternal(in, out, false /* relaxed */);
165 }
166 
167 // BER interprets any non-zero value as true, while DER requires a bool to
168 // have either all bits zero (false) or all bits one (true). To support
169 // malformed certs, we recognized the BER encoding instead of failing to
170 // parse.
ParseBoolRelaxed(Input in,bool * out)171 bool ParseBoolRelaxed(Input in, bool *out) {
172   return ParseBoolInternal(in, out, true /* relaxed */);
173 }
174 
175 // ITU-T X.690 section 8.3.2 specifies that an integer value must be encoded
176 // in the smallest number of octets. If the encoding consists of more than
177 // one octet, then the bits of the first octet and the most significant bit
178 // of the second octet must not be all zeroes or all ones.
IsValidInteger(Input in,bool * negative)179 bool IsValidInteger(Input in, bool *negative) {
180   CBS cbs;
181   CBS_init(&cbs, in.data(), in.size());
182   int negative_int;
183   if (!CBS_is_valid_asn1_integer(&cbs, &negative_int)) {
184     return false;
185   }
186 
187   *negative = !!negative_int;
188   return true;
189 }
190 
ParseUint64(Input in,uint64_t * out)191 bool ParseUint64(Input in, uint64_t *out) {
192   // Reject non-minimally encoded numbers and negative numbers.
193   bool negative;
194   if (!IsValidInteger(in, &negative) || negative) {
195     return false;
196   }
197 
198   // Reject (non-negative) integers whose value would overflow the output type.
199   if (GetUnsignedIntegerLength(in) > sizeof(*out)) {
200     return false;
201   }
202 
203   ByteReader reader(in);
204   uint8_t data;
205   uint64_t value = 0;
206 
207   while (reader.ReadByte(&data)) {
208     value <<= 8;
209     value |= data;
210   }
211   *out = value;
212   return true;
213 }
214 
ParseUint8(Input in,uint8_t * out)215 bool ParseUint8(Input in, uint8_t *out) {
216   // TODO(eroman): Implement this more directly.
217   uint64_t value;
218   if (!ParseUint64(in, &value)) {
219     return false;
220   }
221 
222   if (value > 0xFF) {
223     return false;
224   }
225 
226   *out = static_cast<uint8_t>(value);
227   return true;
228 }
229 
BitString(Input bytes,uint8_t unused_bits)230 BitString::BitString(Input bytes, uint8_t unused_bits)
231     : bytes_(bytes), unused_bits_(unused_bits) {
232   BSSL_CHECK(unused_bits < 8);
233   BSSL_CHECK(unused_bits == 0 || !bytes.empty());
234   // The unused bits must be zero.
235   BSSL_CHECK(bytes.empty() || (bytes.back() & ((1u << unused_bits) - 1)) == 0);
236 }
237 
AssertsBit(size_t bit_index) const238 bool BitString::AssertsBit(size_t bit_index) const {
239   // Index of the byte that contains the bit.
240   size_t byte_index = bit_index / 8;
241 
242   // If the bit is outside of the bitstring, by definition it is not
243   // asserted.
244   if (byte_index >= bytes_.size()) {
245     return false;
246   }
247 
248   // Within a byte, bits are ordered from most significant to least significant.
249   // Convert |bit_index| to an index within the |byte_index| byte, measured from
250   // its least significant bit.
251   uint8_t bit_index_in_byte = 7 - (bit_index - byte_index * 8);
252 
253   // BIT STRING parsing already guarantees that unused bits in a byte are zero
254   // (otherwise it wouldn't be valid DER). Therefore it isn't necessary to check
255   // |unused_bits_|
256   uint8_t byte = bytes_[byte_index];
257   return 0 != (byte & (1 << bit_index_in_byte));
258 }
259 
ParseBitString(Input in)260 std::optional<BitString> ParseBitString(Input in) {
261   ByteReader reader(in);
262 
263   // From ITU-T X.690, section 8.6.2.2 (applies to BER, CER, DER):
264   //
265   // The initial octet shall encode, as an unsigned binary integer with
266   // bit 1 as the least significant bit, the number of unused bits in the final
267   // subsequent octet. The number shall be in the range zero to seven.
268   uint8_t unused_bits;
269   if (!reader.ReadByte(&unused_bits)) {
270     return std::nullopt;
271   }
272   if (unused_bits > 7) {
273     return std::nullopt;
274   }
275 
276   Input bytes;
277   if (!reader.ReadBytes(reader.BytesLeft(), &bytes)) {
278     return std::nullopt;  // Not reachable.
279   }
280 
281   // Ensure that unused bits in the last byte are set to 0.
282   if (unused_bits > 0) {
283     // From ITU-T X.690, section 8.6.2.3 (applies to BER, CER, DER):
284     //
285     // If the bitstring is empty, there shall be no subsequent octets,
286     // and the initial octet shall be zero.
287     if (bytes.empty()) {
288       return std::nullopt;
289     }
290     uint8_t last_byte = bytes.back();
291 
292     // From ITU-T X.690, section 11.2.1 (applies to CER and DER, but not BER):
293     //
294     // Each unused bit in the final octet of the encoding of a bit string value
295     // shall be set to zero.
296     uint8_t mask = 0xFF >> (8 - unused_bits);
297     if ((mask & last_byte) != 0) {
298       return std::nullopt;
299     }
300   }
301 
302   return BitString(bytes, unused_bits);
303 }
304 
InUTCTimeRange() const305 bool GeneralizedTime::InUTCTimeRange() const {
306   return 1950 <= year && year < 2050;
307 }
308 
operator <(const GeneralizedTime & lhs,const GeneralizedTime & rhs)309 bool operator<(const GeneralizedTime &lhs, const GeneralizedTime &rhs) {
310   return std::tie(lhs.year, lhs.month, lhs.day, lhs.hours, lhs.minutes,
311                   lhs.seconds) < std::tie(rhs.year, rhs.month, rhs.day,
312                                           rhs.hours, rhs.minutes, rhs.seconds);
313 }
314 
operator >(const GeneralizedTime & lhs,const GeneralizedTime & rhs)315 bool operator>(const GeneralizedTime &lhs, const GeneralizedTime &rhs) {
316   return rhs < lhs;
317 }
318 
operator <=(const GeneralizedTime & lhs,const GeneralizedTime & rhs)319 bool operator<=(const GeneralizedTime &lhs, const GeneralizedTime &rhs) {
320   return !(lhs > rhs);
321 }
322 
operator >=(const GeneralizedTime & lhs,const GeneralizedTime & rhs)323 bool operator>=(const GeneralizedTime &lhs, const GeneralizedTime &rhs) {
324   return !(lhs < rhs);
325 }
326 
ParseUTCTime(Input in,GeneralizedTime * value)327 bool ParseUTCTime(Input in, GeneralizedTime *value) {
328   ByteReader reader(in);
329   GeneralizedTime time;
330   if (!DecimalStringToUint(reader, 2, &time.year) ||
331       !DecimalStringToUint(reader, 2, &time.month) ||
332       !DecimalStringToUint(reader, 2, &time.day) ||
333       !DecimalStringToUint(reader, 2, &time.hours) ||
334       !DecimalStringToUint(reader, 2, &time.minutes) ||
335       !DecimalStringToUint(reader, 2, &time.seconds)) {
336     return false;
337   }
338   uint8_t zulu;
339   if (!reader.ReadByte(&zulu) || zulu != 'Z' || reader.HasMore()) {
340     return false;
341   }
342   if (time.year < 50) {
343     time.year += 2000;
344   } else {
345     time.year += 1900;
346   }
347   if (!ValidateGeneralizedTime(time)) {
348     return false;
349   }
350   *value = time;
351   return true;
352 }
353 
ParseGeneralizedTime(Input in,GeneralizedTime * value)354 bool ParseGeneralizedTime(Input in, GeneralizedTime *value) {
355   ByteReader reader(in);
356   GeneralizedTime time;
357   if (!DecimalStringToUint(reader, 4, &time.year) ||
358       !DecimalStringToUint(reader, 2, &time.month) ||
359       !DecimalStringToUint(reader, 2, &time.day) ||
360       !DecimalStringToUint(reader, 2, &time.hours) ||
361       !DecimalStringToUint(reader, 2, &time.minutes) ||
362       !DecimalStringToUint(reader, 2, &time.seconds)) {
363     return false;
364   }
365   uint8_t zulu;
366   if (!reader.ReadByte(&zulu) || zulu != 'Z' || reader.HasMore()) {
367     return false;
368   }
369   if (!ValidateGeneralizedTime(time)) {
370     return false;
371   }
372   *value = time;
373   return true;
374 }
375 
ParseIA5String(Input in,std::string * out)376 bool ParseIA5String(Input in, std::string *out) {
377   for (uint8_t c : in) {
378     if (c > 127) {
379       return false;
380     }
381   }
382   *out = BytesAsStringView(in);
383   return true;
384 }
385 
ParseVisibleString(Input in,std::string * out)386 bool ParseVisibleString(Input in, std::string *out) {
387   // ITU-T X.680:
388   // VisibleString : "Defining registration number 6" + SPACE
389   // 6 includes all the characters from '!' .. '~' (33 .. 126), space is 32.
390   // Also ITU-T X.691 says it much more clearly:
391   // "for VisibleString [the range] is 32 to 126 ... For VisibleString .. all
392   // the values in the range are present."
393   for (uint8_t c : in) {
394     if (c < 32 || c > 126) {
395       return false;
396     }
397   }
398   *out = BytesAsStringView(in);
399   return true;
400 }
401 
ParsePrintableString(Input in,std::string * out)402 bool ParsePrintableString(Input in, std::string *out) {
403   for (uint8_t c : in) {
404     if (!(OPENSSL_isalpha(c) || c == ' ' || (c >= '\'' && c <= ':') ||
405           c == '=' || c == '?')) {
406       return false;
407     }
408   }
409   *out = BytesAsStringView(in);
410   return true;
411 }
412 
ParseTeletexStringAsLatin1(Input in,std::string * out)413 bool ParseTeletexStringAsLatin1(Input in, std::string *out) {
414   out->clear();
415   // Convert from Latin-1 to UTF-8.
416   size_t utf8_length = in.size();
417   for (size_t i = 0; i < in.size(); i++) {
418     if (in[i] > 0x7f) {
419       utf8_length++;
420     }
421   }
422   out->reserve(utf8_length);
423   for (size_t i = 0; i < in.size(); i++) {
424     uint8_t u = in[i];
425     if (u <= 0x7f) {
426       out->push_back(u);
427     } else {
428       out->push_back(0xc0 | (u >> 6));
429       out->push_back(0x80 | (u & 0x3f));
430     }
431   }
432   BSSL_CHECK(utf8_length == out->size());
433   return true;
434 }
435 
ParseUniversalString(Input in,std::string * out)436 bool ParseUniversalString(Input in, std::string *out) {
437   if (in.size() % 4 != 0) {
438     return false;
439   }
440 
441   CBS cbs;
442   CBS_init(&cbs, in.data(), in.size());
443   bssl::ScopedCBB cbb;
444   if (!CBB_init(cbb.get(), in.size())) {
445     return false;
446   }
447 
448   while (CBS_len(&cbs) != 0) {
449     uint32_t c;
450     if (!CBS_get_utf32_be(&cbs, &c) ||  //
451         !CBB_add_utf8(cbb.get(), c)) {
452       return false;
453     }
454   }
455 
456   out->assign(CBB_data(cbb.get()), CBB_data(cbb.get()) + CBB_len(cbb.get()));
457   return true;
458 }
459 
ParseBmpString(Input in,std::string * out)460 bool ParseBmpString(Input in, std::string *out) {
461   if (in.size() % 2 != 0) {
462     return false;
463   }
464 
465   CBS cbs;
466   CBS_init(&cbs, in.data(), in.size());
467   bssl::ScopedCBB cbb;
468   if (!CBB_init(cbb.get(), in.size())) {
469     return false;
470   }
471 
472   while (CBS_len(&cbs) != 0) {
473     uint32_t c;
474     if (!CBS_get_ucs2_be(&cbs, &c) ||  //
475         !CBB_add_utf8(cbb.get(), c)) {
476       return false;
477     }
478   }
479 
480   out->assign(CBB_data(cbb.get()), CBB_data(cbb.get()) + CBB_len(cbb.get()));
481   return true;
482 }
483 
484 }  // namespace der
485 BSSL_NAMESPACE_END
486