DER.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/IntegralMath.h>
  7. #include <AK/Stream.h>
  8. #include <AK/Try.h>
  9. #include <AK/Utf8View.h>
  10. #include <LibCrypto/ASN1/DER.h>
  11. namespace Crypto::ASN1 {
  12. ErrorOr<Tag> Decoder::read_tag()
  13. {
  14. auto byte = TRY(read_byte());
  15. u8 class_ = byte & 0xc0;
  16. u8 type = byte & 0x20;
  17. u8 kind = byte & 0x1f;
  18. if (kind == 0x1f) {
  19. kind = 0;
  20. while (byte & 0x80) {
  21. byte = TRY(read_byte());
  22. kind = (kind << 7) | (byte & 0x7f);
  23. }
  24. }
  25. return Tag { (Kind)kind, (Class)class_, (Type)type };
  26. }
  27. ErrorOr<size_t> Decoder::read_length()
  28. {
  29. auto byte = TRY(read_byte());
  30. size_t length = byte;
  31. if (byte & 0x80) {
  32. auto count = byte & 0x7f;
  33. if (count == 0x7f)
  34. return Error::from_string_literal("ASN1::Decoder: Length has an invalid count value");
  35. auto data = TRY(read_bytes(count));
  36. length = 0;
  37. if (data.size() > sizeof(size_t))
  38. return Error::from_string_literal("ASN1::Decoder: Length is larger than the target type");
  39. for (auto&& byte : data)
  40. length = (length << 8) | (size_t)byte;
  41. }
  42. return length;
  43. }
  44. ErrorOr<u8> Decoder::read_byte()
  45. {
  46. if (m_stack.is_empty())
  47. return Error::from_string_literal("ASN1::Decoder: Reading byte from an empty stack");
  48. auto& entry = m_stack.last();
  49. if (entry.is_empty())
  50. return Error::from_string_literal("ASN1::Decoder: Reading byte from an empty entry");
  51. auto byte = entry[0];
  52. entry = entry.slice(1);
  53. return byte;
  54. }
  55. ErrorOr<ReadonlyBytes> Decoder::peek_entry_bytes()
  56. {
  57. if (m_stack.is_empty())
  58. return Error::from_string_literal("ASN1::Decoder: Reading bytes from an empty stack");
  59. auto entry = m_stack.last();
  60. return entry;
  61. }
  62. ErrorOr<ReadonlyBytes> Decoder::read_bytes(size_t length)
  63. {
  64. if (m_stack.is_empty())
  65. return Error::from_string_literal("ASN1::Decoder: Reading bytes from an empty stack");
  66. auto& entry = m_stack.last();
  67. if (entry.size() < length)
  68. return Error::from_string_literal("ASN1::Decoder: Reading bytes from an empty entry");
  69. auto bytes = entry.slice(0, length);
  70. entry = entry.slice(length);
  71. return bytes;
  72. }
  73. ErrorOr<bool> Decoder::decode_boolean(ReadonlyBytes data)
  74. {
  75. if (data.size() != 1)
  76. return Error::from_string_literal("ASN1::Decoder: Decoding boolean from a non boolean-sized span");
  77. return data[0] != 0;
  78. }
  79. ErrorOr<UnsignedBigInteger> Decoder::decode_arbitrary_sized_integer(ReadonlyBytes data)
  80. {
  81. if (data.size() < 1)
  82. return Error::from_string_literal("ASN1::Decoder: Decoding arbitrary sized integer from an empty span");
  83. if (data.size() > 1
  84. && ((data[0] == 0xff && data[1] & 0x80)
  85. || (data[0] == 0x00 && !(data[1] & 0x80)))) {
  86. return Error::from_string_literal("ASN1::Decoder: Arbitrary sized integer has an invalid format");
  87. }
  88. bool is_negative = data[0] & 0x80;
  89. if (is_negative)
  90. return Error::from_string_literal("ASN1::Decoder: Decoding a negative unsigned arbitrary sized integer");
  91. return UnsignedBigInteger::import_data(data.data(), data.size());
  92. }
  93. ErrorOr<StringView> Decoder::decode_octet_string(ReadonlyBytes bytes)
  94. {
  95. return StringView { bytes.data(), bytes.size() };
  96. }
  97. ErrorOr<nullptr_t> Decoder::decode_null(ReadonlyBytes data)
  98. {
  99. if (data.size() != 0)
  100. return Error::from_string_literal("ASN1::Decoder: Decoding null from a non-empty span");
  101. return nullptr;
  102. }
  103. ErrorOr<Vector<int>> Decoder::decode_object_identifier(ReadonlyBytes data)
  104. {
  105. Vector<int> result;
  106. result.append(0); // Reserved space.
  107. u32 value = 0;
  108. for (auto&& byte : data) {
  109. if (value == 0 && byte == 0x80)
  110. return Error::from_string_literal("ASN1::Decoder: Invalid first byte in object identifier");
  111. value = (value << 7) | (byte & 0x7f);
  112. if (!(byte & 0x80)) {
  113. result.append(value);
  114. value = 0;
  115. }
  116. }
  117. if (result.size() == 1 || result[1] >= 1600)
  118. return Error::from_string_literal("ASN1::Decoder: Invalid encoding in object identifier");
  119. result[0] = result[1] / 40;
  120. result[1] = result[1] % 40;
  121. return result;
  122. }
  123. ErrorOr<StringView> Decoder::decode_printable_string(ReadonlyBytes data)
  124. {
  125. Utf8View view { data };
  126. if (!view.validate())
  127. return Error::from_string_literal("ASN1::Decoder: Invalid UTF-8 in printable string");
  128. return StringView { data };
  129. }
  130. ErrorOr<BitStringView> Decoder::decode_bit_string(ReadonlyBytes data)
  131. {
  132. if (data.size() < 1)
  133. return Error::from_string_literal("ASN1::Decoder: Decoding bit string from empty span");
  134. auto unused_bits = data[0];
  135. auto total_size_in_bits = (data.size() - 1) * 8;
  136. if (unused_bits > total_size_in_bits)
  137. return Error::from_string_literal("ASN1::Decoder: Number of unused bits is larger than the total size");
  138. return BitStringView { data.slice(1), unused_bits };
  139. }
  140. ErrorOr<Tag> Decoder::peek()
  141. {
  142. if (m_stack.is_empty())
  143. return Error::from_string_literal("ASN1::Decoder: Peeking using an empty stack");
  144. if (eof())
  145. return Error::from_string_literal("ASN1::Decoder: Peeking using a decoder that is at EOF");
  146. if (m_current_tag.has_value())
  147. return m_current_tag.value();
  148. m_current_tag = TRY(read_tag());
  149. return m_current_tag.value();
  150. }
  151. bool Decoder::eof() const
  152. {
  153. return m_stack.is_empty() || m_stack.last().is_empty();
  154. }
  155. ErrorOr<void> Decoder::enter()
  156. {
  157. if (m_stack.is_empty())
  158. return Error::from_string_literal("ASN1::Decoder: Entering using an empty stack");
  159. auto tag = TRY(peek());
  160. if (tag.type != Type::Constructed)
  161. return Error::from_string_literal("ASN1::Decoder: Entering a non-constructed type");
  162. auto length = TRY(read_length());
  163. auto data = TRY(read_bytes(length));
  164. m_current_tag.clear();
  165. m_stack.append(data);
  166. return {};
  167. }
  168. ErrorOr<void> Decoder::leave()
  169. {
  170. if (m_stack.is_empty())
  171. return Error::from_string_literal("ASN1::Decoder: Leaving using an empty stack");
  172. if (m_stack.size() == 1)
  173. return Error::from_string_literal("ASN1::Decoder: Leaving the main context");
  174. m_stack.take_last();
  175. m_current_tag.clear();
  176. return {};
  177. }
  178. ErrorOr<void> Encoder::write_tag(Class class_, Type type, Kind kind)
  179. {
  180. auto class_byte = to_underlying(class_);
  181. auto type_byte = to_underlying(type);
  182. auto kind_byte = to_underlying(kind);
  183. auto byte = class_byte | type_byte | kind_byte;
  184. if (kind_byte > 0x1f) {
  185. auto high = kind_byte >> 7;
  186. byte = class_byte | type_byte | 0x1f;
  187. TRY(write_byte(byte));
  188. byte = (kind_byte & 0x7f) | high;
  189. }
  190. return write_byte(byte);
  191. }
  192. ErrorOr<void> Encoder::write_byte(u8 byte)
  193. {
  194. return write_bytes({ &byte, 1 });
  195. }
  196. ErrorOr<void> Encoder::write_length(size_t value)
  197. {
  198. if (value < 0x80)
  199. return write_byte(value);
  200. size_t size = ceil_div(AK::ceil_log2(value), 3ul);
  201. TRY(write_byte(0x80 | size));
  202. for (size_t i = 0; i < size; i++) {
  203. auto shift = (size - i - 1) * 8;
  204. auto byte = (value >> shift) & 0xff;
  205. TRY(write_byte(byte));
  206. }
  207. return {};
  208. }
  209. ErrorOr<void> Encoder::write_bytes(ReadonlyBytes bytes)
  210. {
  211. auto output = TRY(m_buffer_stack.last().get_bytes_for_writing(bytes.size()));
  212. bytes.copy_to(output);
  213. return {};
  214. }
  215. ErrorOr<void> Encoder::write_boolean(bool value, Optional<Class> class_override, Optional<Kind> kind_override)
  216. {
  217. auto class_ = class_override.value_or(Class::Universal);
  218. auto type = Type::Primitive;
  219. auto kind = kind_override.value_or(Kind::Boolean);
  220. TRY(write_tag(class_, type, kind));
  221. TRY(write_length(1));
  222. return write_byte(value ? 0xff : 0x00);
  223. }
  224. ErrorOr<void> Encoder::write_arbitrary_sized_integer(UnsignedBigInteger const& value, Optional<Class> class_override, Optional<Kind> kind_override)
  225. {
  226. auto class_ = class_override.value_or(Class::Universal);
  227. auto type = Type::Primitive;
  228. auto kind = kind_override.value_or(Kind::Integer);
  229. TRY(write_tag(class_, type, kind));
  230. auto max_byte_size = max(1ull, value.length() * UnsignedBigInteger::BITS_IN_WORD / 8); // At minimum, we need one byte to encode 0.
  231. ByteBuffer buffer;
  232. auto output = TRY(buffer.get_bytes_for_writing(max_byte_size));
  233. auto size = value.export_data(output);
  234. // DER does not allow empty integers, encode a zero if the exported size is zero.
  235. if (size == 0) {
  236. output[0] = 0;
  237. size = 1;
  238. }
  239. // Chop off the leading zeros
  240. if constexpr (AK::HostIsLittleEndian) {
  241. while (size > 1 && output[0] == 0) {
  242. size--;
  243. output = output.slice(1);
  244. }
  245. } else {
  246. while (size > 1 && output[size - 1] == 0)
  247. size--;
  248. }
  249. // If the MSB is set, we need to add a leading zero to indicate a positive number.
  250. if ((output[0] & 0x80) != 0) {
  251. TRY(write_length(size + 1));
  252. TRY(write_byte(0));
  253. } else {
  254. TRY(write_length(size));
  255. }
  256. return write_bytes(output.slice(0, size));
  257. }
  258. ErrorOr<void> Encoder::write_printable_string(StringView string, Optional<Class> class_override, Optional<Kind> kind_override)
  259. {
  260. Utf8View view { string };
  261. if (!view.validate())
  262. return Error::from_string_literal("ASN1::Encoder: Invalid UTF-8 in printable string");
  263. auto class_ = class_override.value_or(Class::Universal);
  264. auto type = Type::Primitive;
  265. auto kind = kind_override.value_or(Kind::PrintableString);
  266. TRY(write_tag(class_, type, kind));
  267. TRY(write_length(string.length()));
  268. return write_bytes(string.bytes());
  269. }
  270. ErrorOr<void> Encoder::write_octet_string(ReadonlyBytes bytes, Optional<Class> class_override, Optional<Kind> kind_override)
  271. {
  272. auto class_ = class_override.value_or(Class::Universal);
  273. auto type = Type::Primitive;
  274. auto kind = kind_override.value_or(Kind::OctetString);
  275. TRY(write_tag(class_, type, kind));
  276. TRY(write_length(bytes.size()));
  277. return write_bytes(bytes);
  278. }
  279. ErrorOr<void> Encoder::write_null(Optional<Class> class_override, Optional<Kind> kind_override)
  280. {
  281. auto class_ = class_override.value_or(Class::Universal);
  282. auto type = Type::Primitive;
  283. auto kind = kind_override.value_or(Kind::Null);
  284. TRY(write_tag(class_, type, kind));
  285. TRY(write_length(0));
  286. return {};
  287. }
  288. ErrorOr<void> Encoder::write_object_identifier(Span<int const> segments, Optional<Class> class_override, Optional<Kind> kind_override)
  289. {
  290. auto class_ = class_override.value_or(Class::Universal);
  291. auto type = Type::Primitive;
  292. auto kind = kind_override.value_or(Kind::ObjectIdentifier);
  293. if (segments.size() < 2)
  294. return Error::from_string_literal("ASN1::Encoder: Object identifier must have at least two segments");
  295. TRY(write_tag(class_, type, kind));
  296. size_t length = 1;
  297. for (size_t i = 2; i < segments.size(); i++) {
  298. auto segment = segments[i];
  299. if (segment < 0)
  300. return Error::from_string_literal("ASN1::Encoder: Object identifier segments must be non-negative");
  301. if (segment < 0x80)
  302. length += 1;
  303. else if (segment < 0x4000)
  304. length += 2;
  305. else if (segment < 0x200000)
  306. length += 3;
  307. else
  308. length += 4;
  309. }
  310. TRY(write_length(length));
  311. auto first_byte = (segments[0] * 40) + segments[1];
  312. TRY(write_byte(first_byte));
  313. for (size_t i = 2; i < segments.size(); i++) {
  314. auto segment = segments[i];
  315. if (segment < 0x80) {
  316. TRY(write_byte(segment));
  317. } else if (segment < 0x4000) {
  318. TRY(write_byte((segment >> 7) | 0x80));
  319. TRY(write_byte(segment & 0x7f));
  320. } else if (segment < 0x200000) {
  321. TRY(write_byte((segment >> 14) | 0x80));
  322. TRY(write_byte(((segment >> 7) & 0x7f) | 0x80));
  323. TRY(write_byte(segment & 0x7f));
  324. } else {
  325. TRY(write_byte((segment >> 21) | 0x80));
  326. TRY(write_byte(((segment >> 14) & 0x7f) | 0x80));
  327. TRY(write_byte(((segment >> 7) & 0x7f) | 0x80));
  328. TRY(write_byte(segment & 0x7f));
  329. }
  330. }
  331. return {};
  332. }
  333. ErrorOr<void> Encoder::write_bit_string(BitStringView view, Optional<Class> class_override, Optional<Kind> kind_override)
  334. {
  335. auto class_ = class_override.value_or(Class::Universal);
  336. auto type = Type::Primitive;
  337. auto kind = kind_override.value_or(Kind::BitString);
  338. auto unused_bits = view.unused_bits();
  339. auto total_size_in_bits = view.byte_length() * 8 - unused_bits;
  340. TRY(write_tag(class_, type, kind));
  341. TRY(write_length(ceil_div(total_size_in_bits, 8ul) + 1));
  342. TRY(write_byte(unused_bits));
  343. return write_bytes(view.underlying_bytes());
  344. }
  345. ErrorOr<void> pretty_print(Decoder& decoder, Stream& stream, int indent)
  346. {
  347. while (!decoder.eof()) {
  348. auto tag = TRY(decoder.peek());
  349. StringBuilder builder;
  350. for (int i = 0; i < indent; ++i)
  351. builder.append(' ');
  352. builder.appendff("<{}> ", class_name(tag.class_));
  353. if (tag.type == Type::Constructed) {
  354. builder.appendff("[{}] {} ({})", type_name(tag.type), to_underlying(tag.kind), kind_name(tag.kind));
  355. TRY(decoder.enter());
  356. builder.append('\n');
  357. TRY(stream.write_until_depleted(builder.string_view().bytes()));
  358. TRY(pretty_print(decoder, stream, indent + 2));
  359. TRY(decoder.leave());
  360. continue;
  361. } else {
  362. if (tag.class_ != Class::Universal)
  363. builder.appendff("[{}] {} {}", type_name(tag.type), to_underlying(tag.kind), kind_name(tag.kind));
  364. else
  365. builder.appendff("[{}] {}", type_name(tag.type), kind_name(tag.kind));
  366. switch (tag.kind) {
  367. case Kind::Eol: {
  368. TRY(decoder.read<ReadonlyBytes>());
  369. break;
  370. }
  371. case Kind::Boolean: {
  372. auto value = TRY(decoder.read<bool>());
  373. builder.appendff(" {}", value);
  374. break;
  375. }
  376. case Kind::Integer: {
  377. auto value = TRY(decoder.read<ReadonlyBytes>());
  378. builder.append(" 0x"sv);
  379. for (auto ch : value)
  380. builder.appendff("{:0>2x}", ch);
  381. break;
  382. }
  383. case Kind::BitString: {
  384. auto value = TRY(decoder.read<BitmapView>());
  385. builder.append(" 0b"sv);
  386. for (size_t i = 0; i < value.size(); ++i)
  387. builder.append(value.get(i) ? '1' : '0');
  388. break;
  389. }
  390. case Kind::OctetString: {
  391. auto value = TRY(decoder.read<StringView>());
  392. builder.append(" 0x"sv);
  393. for (auto ch : value)
  394. builder.appendff("{:0>2x}", ch);
  395. break;
  396. }
  397. case Kind::Null: {
  398. TRY(decoder.read<decltype(nullptr)>());
  399. break;
  400. }
  401. case Kind::ObjectIdentifier: {
  402. auto value = TRY(decoder.read<Vector<int>>());
  403. for (auto& id : value)
  404. builder.appendff(" {}", id);
  405. break;
  406. }
  407. case Kind::UTCTime:
  408. case Kind::GeneralizedTime:
  409. case Kind::IA5String:
  410. case Kind::VisibleString:
  411. case Kind::BMPString:
  412. case Kind::PrintableString: {
  413. auto value = TRY(decoder.read<StringView>());
  414. builder.append(' ');
  415. builder.append(value);
  416. break;
  417. }
  418. case Kind::Utf8String: {
  419. auto value = TRY(decoder.read<Utf8View>());
  420. builder.append(' ');
  421. for (auto cp : value)
  422. builder.append_code_point(cp);
  423. break;
  424. }
  425. case Kind::Sequence:
  426. case Kind::Set:
  427. return Error::from_string_literal("ASN1::Decoder: Unexpected Primitive");
  428. default: {
  429. dbgln("PrettyPrint error: Unhandled kind {}", to_underlying(tag.kind));
  430. }
  431. }
  432. }
  433. builder.append('\n');
  434. TRY(stream.write_until_depleted(builder.string_view().bytes()));
  435. }
  436. return {};
  437. }
  438. }