parse_values.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/der/parse_values.h"
  5. #include <tuple>
  6. #include "base/check_op.h"
  7. #include "base/notreached.h"
  8. #include "base/strings/string_util.h"
  9. #include "base/strings/utf_string_conversion_utils.h"
  10. #include "base/strings/utf_string_conversions.h"
  11. #include "base/sys_byteorder.h"
  12. #include "base/third_party/icu/icu_utf.h"
  13. #include "third_party/boringssl/src/include/openssl/bytestring.h"
  14. namespace net::der {
  15. namespace {
  16. bool ParseBoolInternal(const Input& in, bool* out, bool relaxed) {
  17. // According to ITU-T X.690 section 8.2, a bool is encoded as a single octet
  18. // where the octet of all zeroes is FALSE and a non-zero value for the octet
  19. // is TRUE.
  20. if (in.Length() != 1)
  21. return false;
  22. ByteReader data(in);
  23. uint8_t byte;
  24. if (!data.ReadByte(&byte))
  25. return false;
  26. if (byte == 0) {
  27. *out = false;
  28. return true;
  29. }
  30. // ITU-T X.690 section 11.1 specifies that for DER, the TRUE value must be
  31. // encoded as an octet of all ones.
  32. if (byte == 0xff || relaxed) {
  33. *out = true;
  34. return true;
  35. }
  36. return false;
  37. }
  38. // Reads a positive decimal number with |digits| digits and stores it in
  39. // |*out|. This function does not check that the type of |*out| is large
  40. // enough to hold 10^digits - 1; the caller must choose an appropriate type
  41. // based on the number of digits they wish to parse.
  42. template <typename UINT>
  43. bool DecimalStringToUint(ByteReader& in, size_t digits, UINT* out) {
  44. UINT value = 0;
  45. for (size_t i = 0; i < digits; ++i) {
  46. uint8_t digit;
  47. if (!in.ReadByte(&digit)) {
  48. return false;
  49. }
  50. if (digit < '0' || digit > '9') {
  51. return false;
  52. }
  53. value = (value * 10) + (digit - '0');
  54. }
  55. *out = value;
  56. return true;
  57. }
  58. // Checks that the values in a GeneralizedTime struct are valid. This involves
  59. // checking that the year is 4 digits, the month is between 1 and 12, the day
  60. // is a day that exists in that month (following current leap year rules),
  61. // hours are between 0 and 23, minutes between 0 and 59, and seconds between
  62. // 0 and 60 (to allow for leap seconds; no validation is done that a leap
  63. // second is on a day that could be a leap second).
  64. bool ValidateGeneralizedTime(const GeneralizedTime& time) {
  65. if (time.month < 1 || time.month > 12)
  66. return false;
  67. if (time.day < 1)
  68. return false;
  69. if (time.hours < 0 || time.hours > 23)
  70. return false;
  71. if (time.minutes < 0 || time.minutes > 59)
  72. return false;
  73. // Leap seconds are allowed.
  74. if (time.seconds < 0 || time.seconds > 60)
  75. return false;
  76. // validate upper bound for day of month
  77. switch (time.month) {
  78. case 4:
  79. case 6:
  80. case 9:
  81. case 11:
  82. if (time.day > 30)
  83. return false;
  84. break;
  85. case 1:
  86. case 3:
  87. case 5:
  88. case 7:
  89. case 8:
  90. case 10:
  91. case 12:
  92. if (time.day > 31)
  93. return false;
  94. break;
  95. case 2:
  96. if (time.year % 4 == 0 &&
  97. (time.year % 100 != 0 || time.year % 400 == 0)) {
  98. if (time.day > 29)
  99. return false;
  100. } else {
  101. if (time.day > 28)
  102. return false;
  103. }
  104. break;
  105. default:
  106. NOTREACHED();
  107. return false;
  108. }
  109. return true;
  110. }
  111. // Returns the number of bytes of numeric precision in a DER encoded INTEGER
  112. // value. |in| must be a valid DER encoding of an INTEGER for this to work.
  113. //
  114. // Normally the precision of the number is exactly in.Length(). However when
  115. // encoding positive numbers using DER it is possible to have a leading zero
  116. // (to prevent number from being interpreted as negative).
  117. //
  118. // For instance a 160-bit positive number might take 21 bytes to encode. This
  119. // function will return 20 in such a case.
  120. size_t GetUnsignedIntegerLength(const Input& in) {
  121. der::ByteReader reader(in);
  122. uint8_t first_byte;
  123. if (!reader.ReadByte(&first_byte))
  124. return 0; // Not valid DER as |in| was empty.
  125. if (first_byte == 0 && in.Length() > 1)
  126. return in.Length() - 1;
  127. return in.Length();
  128. }
  129. } // namespace
  130. bool ParseBool(const Input& in, bool* out) {
  131. return ParseBoolInternal(in, out, false /* relaxed */);
  132. }
  133. // BER interprets any non-zero value as true, while DER requires a bool to
  134. // have either all bits zero (false) or all bits one (true). To support
  135. // malformed certs, we recognized the BER encoding instead of failing to
  136. // parse.
  137. bool ParseBoolRelaxed(const Input& in, bool* out) {
  138. return ParseBoolInternal(in, out, true /* relaxed */);
  139. }
  140. // ITU-T X.690 section 8.3.2 specifies that an integer value must be encoded
  141. // in the smallest number of octets. If the encoding consists of more than
  142. // one octet, then the bits of the first octet and the most significant bit
  143. // of the second octet must not be all zeroes or all ones.
  144. bool IsValidInteger(const Input& in, bool* negative) {
  145. CBS cbs;
  146. CBS_init(&cbs, in.UnsafeData(), in.Length());
  147. int negative_int;
  148. if (!CBS_is_valid_asn1_integer(&cbs, &negative_int)) {
  149. return false;
  150. }
  151. *negative = !!negative_int;
  152. return true;
  153. }
  154. bool ParseUint64(const Input& in, uint64_t* out) {
  155. // Reject non-minimally encoded numbers and negative numbers.
  156. bool negative;
  157. if (!IsValidInteger(in, &negative) || negative)
  158. return false;
  159. // Reject (non-negative) integers whose value would overflow the output type.
  160. if (GetUnsignedIntegerLength(in) > sizeof(*out))
  161. return false;
  162. ByteReader reader(in);
  163. uint8_t data;
  164. uint64_t value = 0;
  165. while (reader.ReadByte(&data)) {
  166. value <<= 8;
  167. value |= data;
  168. }
  169. *out = value;
  170. return true;
  171. }
  172. bool ParseUint8(const Input& in, uint8_t* out) {
  173. // TODO(eroman): Implement this more directly.
  174. uint64_t value;
  175. if (!ParseUint64(in, &value))
  176. return false;
  177. if (value > 0xFF)
  178. return false;
  179. *out = static_cast<uint8_t>(value);
  180. return true;
  181. }
  182. BitString::BitString(const Input& bytes, uint8_t unused_bits)
  183. : bytes_(bytes), unused_bits_(unused_bits) {
  184. DCHECK_LT(unused_bits, 8);
  185. DCHECK(unused_bits == 0 || bytes.Length() != 0);
  186. // The unused bits must be zero.
  187. DCHECK(bytes.Length() == 0 ||
  188. (bytes.UnsafeData()[bytes.Length() - 1] & ((1u << unused_bits) - 1)) ==
  189. 0);
  190. }
  191. bool BitString::AssertsBit(size_t bit_index) const {
  192. // Index of the byte that contains the bit.
  193. size_t byte_index = bit_index / 8;
  194. // If the bit is outside of the bitstring, by definition it is not
  195. // asserted.
  196. if (byte_index >= bytes_.Length())
  197. return false;
  198. // Within a byte, bits are ordered from most significant to least significant.
  199. // Convert |bit_index| to an index within the |byte_index| byte, measured from
  200. // its least significant bit.
  201. uint8_t bit_index_in_byte = 7 - (bit_index - byte_index * 8);
  202. // BIT STRING parsing already guarantees that unused bits in a byte are zero
  203. // (otherwise it wouldn't be valid DER). Therefore it isn't necessary to check
  204. // |unused_bits_|
  205. uint8_t byte = bytes_.UnsafeData()[byte_index];
  206. return 0 != (byte & (1 << bit_index_in_byte));
  207. }
  208. absl::optional<BitString> ParseBitString(const Input& in) {
  209. ByteReader reader(in);
  210. // From ITU-T X.690, section 8.6.2.2 (applies to BER, CER, DER):
  211. //
  212. // The initial octet shall encode, as an unsigned binary integer with
  213. // bit 1 as the least significant bit, the number of unused bits in the final
  214. // subsequent octet. The number shall be in the range zero to seven.
  215. uint8_t unused_bits;
  216. if (!reader.ReadByte(&unused_bits))
  217. return absl::nullopt;
  218. if (unused_bits > 7)
  219. return absl::nullopt;
  220. Input bytes;
  221. if (!reader.ReadBytes(reader.BytesLeft(), &bytes))
  222. return absl::nullopt; // Not reachable.
  223. // Ensure that unused bits in the last byte are set to 0.
  224. if (unused_bits > 0) {
  225. // From ITU-T X.690, section 8.6.2.3 (applies to BER, CER, DER):
  226. //
  227. // If the bitstring is empty, there shall be no subsequent octets,
  228. // and the initial octet shall be zero.
  229. if (bytes.Length() == 0)
  230. return absl::nullopt;
  231. uint8_t last_byte = bytes.UnsafeData()[bytes.Length() - 1];
  232. // From ITU-T X.690, section 11.2.1 (applies to CER and DER, but not BER):
  233. //
  234. // Each unused bit in the final octet of the encoding of a bit string value
  235. // shall be set to zero.
  236. uint8_t mask = 0xFF >> (8 - unused_bits);
  237. if ((mask & last_byte) != 0)
  238. return absl::nullopt;
  239. }
  240. return BitString(bytes, unused_bits);
  241. }
  242. bool GeneralizedTime::InUTCTimeRange() const {
  243. return 1950 <= year && year < 2050;
  244. }
  245. bool operator<(const GeneralizedTime& lhs, const GeneralizedTime& rhs) {
  246. return std::tie(lhs.year, lhs.month, lhs.day, lhs.hours, lhs.minutes,
  247. lhs.seconds) < std::tie(rhs.year, rhs.month, rhs.day,
  248. rhs.hours, rhs.minutes, rhs.seconds);
  249. }
  250. bool operator>(const GeneralizedTime& lhs, const GeneralizedTime& rhs) {
  251. return rhs < lhs;
  252. }
  253. bool operator<=(const GeneralizedTime& lhs, const GeneralizedTime& rhs) {
  254. return !(lhs > rhs);
  255. }
  256. bool operator>=(const GeneralizedTime& lhs, const GeneralizedTime& rhs) {
  257. return !(lhs < rhs);
  258. }
  259. bool ParseUTCTime(const Input& in, GeneralizedTime* value) {
  260. ByteReader reader(in);
  261. GeneralizedTime time;
  262. if (!DecimalStringToUint(reader, 2, &time.year) ||
  263. !DecimalStringToUint(reader, 2, &time.month) ||
  264. !DecimalStringToUint(reader, 2, &time.day) ||
  265. !DecimalStringToUint(reader, 2, &time.hours) ||
  266. !DecimalStringToUint(reader, 2, &time.minutes) ||
  267. !DecimalStringToUint(reader, 2, &time.seconds)) {
  268. return false;
  269. }
  270. uint8_t zulu;
  271. if (!reader.ReadByte(&zulu) || zulu != 'Z' || reader.HasMore())
  272. return false;
  273. if (time.year < 50) {
  274. time.year += 2000;
  275. } else {
  276. time.year += 1900;
  277. }
  278. if (!ValidateGeneralizedTime(time))
  279. return false;
  280. *value = time;
  281. return true;
  282. }
  283. bool ParseGeneralizedTime(const Input& in, GeneralizedTime* value) {
  284. ByteReader reader(in);
  285. GeneralizedTime time;
  286. if (!DecimalStringToUint(reader, 4, &time.year) ||
  287. !DecimalStringToUint(reader, 2, &time.month) ||
  288. !DecimalStringToUint(reader, 2, &time.day) ||
  289. !DecimalStringToUint(reader, 2, &time.hours) ||
  290. !DecimalStringToUint(reader, 2, &time.minutes) ||
  291. !DecimalStringToUint(reader, 2, &time.seconds)) {
  292. return false;
  293. }
  294. uint8_t zulu;
  295. if (!reader.ReadByte(&zulu) || zulu != 'Z' || reader.HasMore())
  296. return false;
  297. if (!ValidateGeneralizedTime(time))
  298. return false;
  299. *value = time;
  300. return true;
  301. }
  302. bool ParseIA5String(Input in, std::string* out) {
  303. for (char c : in.AsStringPiece()) {
  304. if (static_cast<uint8_t>(c) > 127)
  305. return false;
  306. }
  307. *out = in.AsString();
  308. return true;
  309. }
  310. bool ParseVisibleString(Input in, std::string* out) {
  311. // ITU-T X.680:
  312. // VisibleString : "Defining registration number 6" + SPACE
  313. // 6 includes all the characters from '!' .. '~' (33 .. 126), space is 32.
  314. // Also ITU-T X.691 says it much more clearly:
  315. // "for VisibleString [the range] is 32 to 126 ... For VisibleString .. all
  316. // the values in the range are present."
  317. for (char c : in.AsStringPiece()) {
  318. if (static_cast<uint8_t>(c) < 32 || static_cast<uint8_t>(c) > 126)
  319. return false;
  320. }
  321. *out = in.AsString();
  322. return true;
  323. }
  324. bool ParsePrintableString(Input in, std::string* out) {
  325. for (char c : in.AsStringPiece()) {
  326. if (!(base::IsAsciiAlpha(c) || c == ' ' || (c >= '\'' && c <= ':') ||
  327. c == '=' || c == '?')) {
  328. return false;
  329. }
  330. }
  331. *out = in.AsString();
  332. return true;
  333. }
  334. bool ParseTeletexStringAsLatin1(Input in, std::string* out) {
  335. out->clear();
  336. // Convert from Latin-1 to UTF-8.
  337. size_t utf8_length = in.Length();
  338. for (size_t i = 0; i < in.Length(); i++) {
  339. if (in.UnsafeData()[i] > 0x7f)
  340. utf8_length++;
  341. }
  342. out->reserve(utf8_length);
  343. for (size_t i = 0; i < in.Length(); i++) {
  344. uint8_t u = in.UnsafeData()[i];
  345. if (u <= 0x7f) {
  346. out->push_back(u);
  347. } else {
  348. out->push_back(0xc0 | (u >> 6));
  349. out->push_back(0x80 | (u & 0x3f));
  350. }
  351. }
  352. DCHECK_EQ(utf8_length, out->size());
  353. return true;
  354. }
  355. bool ParseUniversalString(Input in, std::string* out) {
  356. if (in.Length() % 4 != 0)
  357. return false;
  358. out->clear();
  359. std::vector<uint32_t> in_32bit(in.Length() / 4);
  360. if (in.Length())
  361. memcpy(in_32bit.data(), in.UnsafeData(), in.Length());
  362. for (const uint32_t c : in_32bit) {
  363. // UniversalString is UCS-4 in big-endian order.
  364. auto codepoint = static_cast<base_icu::UChar32>(base::NetToHost32(c));
  365. if (!CBU_IS_UNICODE_CHAR(codepoint))
  366. return false;
  367. base::WriteUnicodeCharacter(codepoint, out);
  368. }
  369. return true;
  370. }
  371. bool ParseBmpString(Input in, std::string* out) {
  372. if (in.Length() % 2 != 0)
  373. return false;
  374. out->clear();
  375. std::vector<uint16_t> in_16bit(in.Length() / 2);
  376. if (in.Length())
  377. memcpy(in_16bit.data(), in.UnsafeData(), in.Length());
  378. for (const uint16_t c : in_16bit) {
  379. // BMPString is UCS-2 in big-endian order.
  380. base_icu::UChar32 codepoint = base::NetToHost16(c);
  381. // BMPString only supports codepoints in the Basic Multilingual Plane;
  382. // surrogates are not allowed. CBU_IS_UNICODE_CHAR excludes the surrogate
  383. // code points, among other invalid values.
  384. if (!CBU_IS_UNICODE_CHAR(codepoint))
  385. return false;
  386. base::WriteUnicodeCharacter(codepoint, out);
  387. }
  388. return true;
  389. }
  390. } // namespace net::der