Certificate.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Certificate.h"
  7. #include <AK/Debug.h>
  8. #include <LibCrypto/ASN1/ASN1.h>
  9. #include <LibCrypto/ASN1/DER.h>
  10. #include <LibCrypto/ASN1/PEM.h>
  11. namespace TLS {
  12. constexpr static Array<int, 4>
  13. common_name_oid { 2, 5, 4, 3 },
  14. country_name_oid { 2, 5, 4, 6 },
  15. locality_name_oid { 2, 5, 4, 7 },
  16. organization_name_oid { 2, 5, 4, 10 },
  17. organizational_unit_name_oid { 2, 5, 4, 11 };
  18. constexpr static Array<int, 7>
  19. rsa_encryption_oid { 1, 2, 840, 113549, 1, 1, 1 },
  20. rsa_md5_encryption_oid { 1, 2, 840, 113549, 1, 1, 4 },
  21. rsa_sha1_encryption_oid { 1, 2, 840, 113549, 1, 1, 5 },
  22. rsa_sha256_encryption_oid { 1, 2, 840, 113549, 1, 1, 11 },
  23. rsa_sha512_encryption_oid { 1, 2, 840, 113549, 1, 1, 13 };
  24. constexpr static Array<int, 4>
  25. subject_alternative_name_oid { 2, 5, 29, 17 };
  26. Optional<Certificate> Certificate::parse_asn1(ReadonlyBytes buffer, bool)
  27. {
  28. #define ENTER_SCOPE_WITHOUT_TYPECHECK(scope) \
  29. do { \
  30. if (auto result = decoder.enter(); result.has_value()) { \
  31. dbgln_if(TLS_DEBUG, "Failed to enter object (" scope "): {}", result.value()); \
  32. return {}; \
  33. } \
  34. } while (0)
  35. #define ENTER_SCOPE_OR_FAIL(kind_name, scope) \
  36. do { \
  37. if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::kind_name) { \
  38. if constexpr (TLS_DEBUG) { \
  39. if (tag.is_error()) \
  40. dbgln(scope " data was invalid: {}", tag.error()); \
  41. else \
  42. dbgln(scope " data was not of kind " #kind_name); \
  43. } \
  44. return {}; \
  45. } \
  46. ENTER_SCOPE_WITHOUT_TYPECHECK(scope); \
  47. } while (0)
  48. #define EXIT_SCOPE(scope) \
  49. do { \
  50. if (auto error = decoder.leave(); error.has_value()) { \
  51. dbgln_if(TLS_DEBUG, "Error while exiting scope " scope ": {}", error.value()); \
  52. return {}; \
  53. } \
  54. } while (0)
  55. #define ENSURE_OBJECT_KIND(_kind_name, scope) \
  56. do { \
  57. if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::_kind_name) { \
  58. if constexpr (TLS_DEBUG) { \
  59. if (tag.is_error()) \
  60. dbgln(scope " data was invalid: {}", tag.error()); \
  61. else \
  62. dbgln(scope " data was not of kind " #_kind_name ", it was {}", Crypto::ASN1::kind_name(tag.value().kind)); \
  63. } \
  64. return {}; \
  65. } \
  66. } while (0)
  67. #define READ_OBJECT_OR_FAIL(kind_name, type_name, value_name, scope) \
  68. auto value_name##_result = decoder.read<type_name>(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::kind_name); \
  69. if (value_name##_result.is_error()) { \
  70. dbgln_if(TLS_DEBUG, scope " read of kind " #kind_name " failed: {}", value_name##_result.error()); \
  71. return {}; \
  72. } \
  73. auto value_name = value_name##_result.release_value();
  74. #define DROP_OBJECT_OR_FAIL(scope) \
  75. do { \
  76. if (auto error = decoder.drop(); error.has_value()) { \
  77. dbgln_if(TLS_DEBUG, scope " read failed: {}", error.value()); \
  78. } \
  79. } while (0)
  80. Certificate certificate;
  81. Crypto::ASN1::Decoder decoder { buffer };
  82. // Certificate ::= Sequence {
  83. // certificate TBSCertificate,
  84. // signature_algorithm AlgorithmIdentifier,
  85. // signature_value BitString
  86. // }
  87. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate");
  88. // TBSCertificate ::= Sequence {
  89. // version (0) EXPLICIT Version DEFAULT v1,
  90. // serial_number CertificateSerialNumber,
  91. // signature AlgorithmIdentifier,
  92. // issuer Name,
  93. // validity Validity,
  94. // subject Name,
  95. // subject_public_key_info SubjectPublicKeyInfo,
  96. // issuer_unique_id (1) IMPLICIT UniqueIdentifer OPTIONAL (if present, version > v1),
  97. // subject_unique_id (2) IMPLICIT UniqueIdentiier OPTIONAL (if present, version > v1),
  98. // extensions (3) EXPLICIT Extensions OPTIONAL (if present, version > v2)
  99. // }
  100. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate");
  101. // version
  102. {
  103. // Version :: Integer { v1(0), v2(1), v3(2) } (Optional)
  104. if (auto tag = decoder.peek(); !tag.is_error() && tag.value().type == Crypto::ASN1::Type::Constructed) {
  105. ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::version");
  106. READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::version");
  107. if (!(value < 3)) {
  108. dbgln_if(TLS_DEBUG, "Certificate::version Invalid value for version: {}", value.to_base(10));
  109. return {};
  110. }
  111. certificate.version = value.words()[0];
  112. EXIT_SCOPE("Certificate::version");
  113. } else {
  114. certificate.version = 0;
  115. }
  116. }
  117. // serial_number
  118. {
  119. // CertificateSerialNumber :: Integer
  120. READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::serial_number");
  121. certificate.serial_number = move(value);
  122. }
  123. auto parse_algorithm_identifier = [&](CertificateKeyAlgorithm& field) -> Optional<bool> {
  124. // AlgorithmIdentifier ::= Sequence {
  125. // algorithm ObjectIdentifier,
  126. // parameters ANY OPTIONAL
  127. // }
  128. ENTER_SCOPE_OR_FAIL(Sequence, "AlgorithmIdentifier");
  129. READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, identifier, "AlgorithmIdentifier::algorithm");
  130. if (identifier == rsa_encryption_oid)
  131. field = CertificateKeyAlgorithm ::RSA_RSA;
  132. else if (identifier == rsa_md5_encryption_oid)
  133. field = CertificateKeyAlgorithm ::RSA_MD5;
  134. else if (identifier == rsa_sha1_encryption_oid)
  135. field = CertificateKeyAlgorithm ::RSA_SHA1;
  136. else if (identifier == rsa_sha256_encryption_oid)
  137. field = CertificateKeyAlgorithm ::RSA_SHA256;
  138. else if (identifier == rsa_sha512_encryption_oid)
  139. field = CertificateKeyAlgorithm ::RSA_SHA512;
  140. else
  141. return {};
  142. EXIT_SCOPE("AlgorithmIdentifier");
  143. return true;
  144. };
  145. // signature
  146. {
  147. if (!parse_algorithm_identifier(certificate.algorithm).has_value())
  148. return {};
  149. }
  150. auto parse_name = [&](auto& name_struct) -> Optional<bool> {
  151. // Name ::= Choice {
  152. // rdn_sequence RDNSequence
  153. // } // NOTE: since this is the only alternative, there's no index
  154. // RDNSequence ::= Sequence OF RelativeDistinguishedName
  155. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject");
  156. // RelativeDistinguishedName ::= Set OF AttributeTypeAndValue
  157. // AttributeTypeAndValue ::= Sequence {
  158. // type AttributeType,
  159. // value AttributeValue
  160. // }
  161. // AttributeType ::= ObjectIdentifier
  162. // AttributeValue ::= Any
  163. while (!decoder.eof()) {
  164. // Parse only the the required fields, and ignore the rest.
  165. ENTER_SCOPE_OR_FAIL(Set, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName");
  166. while (!decoder.eof()) {
  167. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue");
  168. ENSURE_OBJECT_KIND(ObjectIdentifier, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type");
  169. if (auto type_identifier_or_error = decoder.read<Vector<int>>(); !type_identifier_or_error.is_error()) {
  170. // Figure out what type of identifier this is
  171. auto& identifier = type_identifier_or_error.value();
  172. if (identifier == common_name_oid) {
  173. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  174. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  175. name_struct.subject = name;
  176. } else if (identifier == country_name_oid) {
  177. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  178. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  179. name_struct.country = name;
  180. } else if (identifier == locality_name_oid) {
  181. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  182. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  183. name_struct.location = name;
  184. } else if (identifier == organization_name_oid) {
  185. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  186. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  187. name_struct.entity = name;
  188. } else if (identifier == organizational_unit_name_oid) {
  189. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  190. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  191. name_struct.unit = name;
  192. }
  193. } else {
  194. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type data was invalid: {}", type_identifier_or_error.error());
  195. return {};
  196. }
  197. EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue");
  198. }
  199. EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName");
  200. }
  201. EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject");
  202. return true;
  203. };
  204. // issuer
  205. {
  206. if (!parse_name(certificate.issuer).has_value())
  207. return {};
  208. }
  209. // validity
  210. {
  211. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Validity");
  212. auto parse_time = [&](Core::DateTime& datetime) -> Optional<bool> {
  213. // Time ::= Choice {
  214. // utc_time UTCTime,
  215. // general_time GeneralizedTime
  216. // }
  217. auto tag = decoder.peek();
  218. if (tag.is_error()) {
  219. dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time failed to read tag: {}", tag.error());
  220. return {};
  221. };
  222. if (tag.value().kind == Crypto::ASN1::Kind::UTCTime) {
  223. READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$");
  224. auto result = Crypto::ASN1::parse_utc_time(time);
  225. if (!result.has_value()) {
  226. dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid UTC Time: {}", time);
  227. return {};
  228. }
  229. datetime = result.release_value();
  230. return true;
  231. }
  232. if (tag.value().kind == Crypto::ASN1::Kind::GeneralizedTime) {
  233. READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$");
  234. auto result = Crypto::ASN1::parse_generalized_time(time);
  235. if (!result.has_value()) {
  236. dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid Generalized Time: {}", time);
  237. return {};
  238. }
  239. datetime = result.release_value();
  240. return true;
  241. }
  242. dbgln_if(1, "Unrecognised Time format {}", Crypto::ASN1::kind_name(tag.value().kind));
  243. return {};
  244. };
  245. if (!parse_time(certificate.not_before).has_value())
  246. return {};
  247. if (!parse_time(certificate.not_after).has_value())
  248. return {};
  249. EXIT_SCOPE("Certificate::TBSCertificate::Validity");
  250. }
  251. // subject
  252. {
  253. if (!parse_name(certificate.subject).has_value())
  254. return {};
  255. }
  256. // subject_public_key_info
  257. {
  258. // SubjectPublicKeyInfo ::= Sequence {
  259. // algorithm AlgorithmIdentifier,
  260. // subject_public_key BitString
  261. // }
  262. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::subject_public_key_info");
  263. if (!parse_algorithm_identifier(certificate.key_algorithm).has_value())
  264. return {};
  265. READ_OBJECT_OR_FAIL(BitString, const BitmapView, value, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info");
  266. // Note: Once we support other kinds of keys, make sure to check the kind here!
  267. auto key = Crypto::PK::RSA::parse_rsa_key({ value.data(), value.size_in_bytes() });
  268. if (!key.public_key.length()) {
  269. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info: Invalid key");
  270. return {};
  271. }
  272. certificate.public_key = move(key.public_key);
  273. EXIT_SCOPE("Certificate::TBSCertificate::subject_public_key_info");
  274. }
  275. auto parse_unique_identifier = [&]() -> Optional<bool> {
  276. if (certificate.version == 0)
  277. return true;
  278. auto tag = decoder.peek();
  279. if (tag.is_error()) {
  280. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error());
  281. return {};
  282. }
  283. // The spec says to just ignore these.
  284. if (static_cast<u8>(tag.value().kind) == 1 || static_cast<u8>(tag.value().kind) == 2)
  285. DROP_OBJECT_OR_FAIL("UniqueIdentifier");
  286. return true;
  287. };
  288. // issuer_unique_identifier
  289. {
  290. if (!parse_unique_identifier().has_value())
  291. return {};
  292. }
  293. // subject_unique_identifier
  294. {
  295. if (!parse_unique_identifier().has_value())
  296. return {};
  297. }
  298. // extensions
  299. {
  300. if (certificate.version == 2) {
  301. auto tag = decoder.peek();
  302. if (tag.is_error()) {
  303. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error());
  304. return {};
  305. }
  306. if (static_cast<u8>(tag.value().kind) == 3) {
  307. // Extensions ::= Sequence OF Extension
  308. // Extension ::= Sequence {
  309. // extension_id ObjectIdentifier,
  310. // critical Boolean DEFAULT false,
  311. // extension_value OctetString (DER-encoded)
  312. // }
  313. ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::TBSCertificate::Extensions(IMPLICIT)");
  314. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions");
  315. while (!decoder.eof()) {
  316. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension");
  317. READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, extension_id, "Certificate::TBSCertificate::Extensions::$::Extension::extension_id");
  318. bool is_critical = false;
  319. if (auto tag = decoder.peek(); !tag.is_error() && tag.value().kind == Crypto::ASN1::Kind::Boolean) {
  320. // Read the 'critical' property
  321. READ_OBJECT_OR_FAIL(Boolean, bool, critical, "Certificate::TBSCertificate::Extensions::$::Extension::critical");
  322. is_critical = critical;
  323. }
  324. READ_OBJECT_OR_FAIL(OctetString, StringView, extension_value, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value");
  325. // Figure out what this extension is.
  326. if (extension_id == subject_alternative_name_oid) {
  327. Crypto::ASN1::Decoder decoder { extension_value.bytes() };
  328. // SubjectAlternativeName ::= GeneralNames
  329. // GeneralNames ::= Sequence OF GeneralName
  330. // GeneralName ::= CHOICE {
  331. // other_name (0) OtherName,
  332. // rfc_822_name (1) IA5String,
  333. // dns_name (2) IA5String,
  334. // x400Address (3) ORAddress,
  335. // directory_name (4) Name,
  336. // edi_party_name (5) EDIPartyName,
  337. // uri (6) IA5String,
  338. // ip_address (7) OctetString,
  339. // registered_id (8) ObjectIdentifier,
  340. // }
  341. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName");
  342. while (!decoder.eof()) {
  343. auto tag = decoder.peek();
  344. if (tag.is_error()) {
  345. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$ could not read tag: {}", tag.error());
  346. return {};
  347. }
  348. auto tag_value = static_cast<u8>(tag.value().kind);
  349. switch (tag_value) {
  350. case 0:
  351. // OtherName
  352. // We don't know how to use this.
  353. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::OtherName");
  354. break;
  355. case 1:
  356. // RFC 822 name
  357. // We don't know how to use this.
  358. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RFC822Name");
  359. break;
  360. case 2: {
  361. // DNS Name
  362. READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DNSName");
  363. certificate.SAN.append(name);
  364. break;
  365. }
  366. case 3:
  367. // x400Address
  368. // We don't know how to use this.
  369. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::X400Adress");
  370. break;
  371. case 4:
  372. // Directory name
  373. // We don't know how to use this.
  374. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DirectoryName");
  375. break;
  376. case 5:
  377. // edi party name
  378. // We don't know how to use this.
  379. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::EDIPartyName");
  380. break;
  381. case 6: {
  382. // URI
  383. READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::URI");
  384. certificate.SAN.append(name);
  385. break;
  386. }
  387. case 7:
  388. // IP Address
  389. // We can't handle these.
  390. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::IPAddress");
  391. break;
  392. case 8:
  393. // Registered ID
  394. // We can't handle these.
  395. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RegisteredID");
  396. break;
  397. default:
  398. dbgln_if(TLS_DEBUG, "Unknown tag in SAN choice {}", tag_value);
  399. if (is_critical)
  400. return {};
  401. else
  402. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::???");
  403. }
  404. }
  405. }
  406. EXIT_SCOPE("Certificate::TBSCertificate::Extensions::$::Extension");
  407. }
  408. EXIT_SCOPE("Certificate::TBSCertificate::Extensions");
  409. EXIT_SCOPE("Certificate::TBSCertificate::Extensions(IMPLICIT)");
  410. }
  411. }
  412. }
  413. // Just ignore the rest of the data for now.
  414. EXIT_SCOPE("Certificate::TBSCertificate");
  415. EXIT_SCOPE("Certificate");
  416. dbgln_if(TLS_DEBUG, "Certificate issued for {} by {}", certificate.subject.subject, certificate.issuer.subject);
  417. return certificate;
  418. #undef DROP_OBJECT_OR_FAIL
  419. #undef ENSURE_OBJECT_KIND
  420. #undef ENTER_SCOPE_OR_FAIL
  421. #undef ENTER_SCOPE_WITHOUT_TYPECHECK
  422. #undef EXIT_SCOPE
  423. #undef READ_OBJECT_OR_FAIL
  424. }
  425. }