TLSv12.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Endian.h>
  8. #include <LibCore/ConfigFile.h>
  9. #include <LibCore/DateTime.h>
  10. #include <LibCore/File.h>
  11. #include <LibCore/FileStream.h>
  12. #include <LibCore/Timer.h>
  13. #include <LibCrypto/ASN1/ASN1.h>
  14. #include <LibCrypto/ASN1/DER.h>
  15. #include <LibCrypto/ASN1/PEM.h>
  16. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  17. #include <LibTLS/TLSv12.h>
  18. #include <errno.h>
  19. #ifndef SOCK_NONBLOCK
  20. # include <sys/ioctl.h>
  21. #endif
  22. namespace TLS {
  23. constexpr static Array<int, 4>
  24. common_name_oid { 2, 5, 4, 3 },
  25. country_name_oid { 2, 5, 4, 6 },
  26. locality_name_oid { 2, 5, 4, 7 },
  27. organization_name_oid { 2, 5, 4, 10 },
  28. organizational_unit_name_oid { 2, 5, 4, 11 };
  29. constexpr static Array<int, 7>
  30. rsa_encryption_oid { 1, 2, 840, 113549, 1, 1, 1 },
  31. rsa_md5_encryption_oid { 1, 2, 840, 113549, 1, 1, 4 },
  32. rsa_sha1_encryption_oid { 1, 2, 840, 113549, 1, 1, 5 },
  33. rsa_sha256_encryption_oid { 1, 2, 840, 113549, 1, 1, 11 },
  34. rsa_sha512_encryption_oid { 1, 2, 840, 113549, 1, 1, 13 };
  35. constexpr static Array<int, 4>
  36. subject_alternative_name_oid { 2, 5, 29, 17 };
  37. Optional<Certificate> TLSv12::parse_asn1(ReadonlyBytes buffer, bool) const
  38. {
  39. #define ENTER_SCOPE_WITHOUT_TYPECHECK(scope) \
  40. do { \
  41. if (auto result = decoder.enter(); result.has_value()) { \
  42. dbgln_if(TLS_DEBUG, "Failed to enter object (" scope "): {}", result.value()); \
  43. return {}; \
  44. } \
  45. } while (0)
  46. #define ENTER_SCOPE_OR_FAIL(kind_name, scope) \
  47. do { \
  48. if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::kind_name) { \
  49. if constexpr (TLS_DEBUG) { \
  50. if (tag.is_error()) \
  51. dbgln(scope " data was invalid: {}", tag.error()); \
  52. else \
  53. dbgln(scope " data was not of kind " #kind_name); \
  54. } \
  55. return {}; \
  56. } \
  57. ENTER_SCOPE_WITHOUT_TYPECHECK(scope); \
  58. } while (0)
  59. #define EXIT_SCOPE(scope) \
  60. do { \
  61. if (auto error = decoder.leave(); error.has_value()) { \
  62. dbgln_if(TLS_DEBUG, "Error while exiting scope " scope ": {}", error.value()); \
  63. return {}; \
  64. } \
  65. } while (0)
  66. #define ENSURE_OBJECT_KIND(_kind_name, scope) \
  67. do { \
  68. if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::_kind_name) { \
  69. if constexpr (TLS_DEBUG) { \
  70. if (tag.is_error()) \
  71. dbgln(scope " data was invalid: {}", tag.error()); \
  72. else \
  73. dbgln(scope " data was not of kind " #_kind_name ", it was {}", Crypto::ASN1::kind_name(tag.value().kind)); \
  74. } \
  75. return {}; \
  76. } \
  77. } while (0)
  78. #define READ_OBJECT_OR_FAIL(kind_name, type_name, value_name, scope) \
  79. auto value_name##_result = decoder.read<type_name>(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::kind_name); \
  80. if (value_name##_result.is_error()) { \
  81. dbgln_if(TLS_DEBUG, scope " read of kind " #kind_name " failed: {}", value_name##_result.error()); \
  82. return {}; \
  83. } \
  84. auto value_name = value_name##_result.release_value();
  85. #define DROP_OBJECT_OR_FAIL(scope) \
  86. do { \
  87. if (auto error = decoder.drop(); error.has_value()) { \
  88. dbgln_if(TLS_DEBUG, scope " read failed: {}", error.value()); \
  89. } \
  90. } while (0)
  91. Certificate certificate;
  92. Crypto::ASN1::Decoder decoder { buffer };
  93. // Certificate ::= Sequence {
  94. // certificate TBSCertificate,
  95. // signature_algorithm AlgorithmIdentifier,
  96. // signature_value BitString
  97. // }
  98. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate");
  99. // TBSCertificate ::= Sequence {
  100. // version (0) EXPLICIT Version DEFAULT v1,
  101. // serial_number CertificateSerialNumber,
  102. // signature AlgorithmIdentifier,
  103. // issuer Name,
  104. // validity Validity,
  105. // subject Name,
  106. // subject_public_key_info SubjectPublicKeyInfo,
  107. // issuer_unique_id (1) IMPLICIT UniqueIdentifer OPTIONAL (if present, version > v1),
  108. // subject_unique_id (2) IMPLICIT UniqueIdentiier OPTIONAL (if present, version > v1),
  109. // extensions (3) EXPLICIT Extensions OPTIONAL (if present, version > v2)
  110. // }
  111. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate");
  112. // version
  113. {
  114. // Version :: Integer { v1(0), v2(1), v3(2) } (Optional)
  115. if (auto tag = decoder.peek(); !tag.is_error() && tag.value().type == Crypto::ASN1::Type::Constructed) {
  116. ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::version");
  117. READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::version");
  118. if (!(value < 3)) {
  119. dbgln_if(TLS_DEBUG, "Certificate::version Invalid value for version: {}", value.to_base10());
  120. return {};
  121. }
  122. certificate.version = value.words()[0];
  123. EXIT_SCOPE("Certificate::version");
  124. } else {
  125. certificate.version = 0;
  126. }
  127. }
  128. // serial_number
  129. {
  130. // CertificateSerialNumber :: Integer
  131. READ_OBJECT_OR_FAIL(Integer, Crypto::UnsignedBigInteger, value, "Certificate::serial_number");
  132. certificate.serial_number = move(value);
  133. }
  134. auto parse_algorithm_identifier = [&](CertificateKeyAlgorithm& field) -> Optional<bool> {
  135. // AlgorithmIdentifier ::= Sequence {
  136. // algorithm ObjectIdentifier,
  137. // parameters ANY OPTIONAL
  138. // }
  139. ENTER_SCOPE_OR_FAIL(Sequence, "AlgorithmIdentifier");
  140. READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, identifier, "AlgorithmIdentifier::algorithm");
  141. if (identifier == rsa_encryption_oid)
  142. field = CertificateKeyAlgorithm ::RSA_RSA;
  143. else if (identifier == rsa_md5_encryption_oid)
  144. field = CertificateKeyAlgorithm ::RSA_MD5;
  145. else if (identifier == rsa_sha1_encryption_oid)
  146. field = CertificateKeyAlgorithm ::RSA_SHA1;
  147. else if (identifier == rsa_sha256_encryption_oid)
  148. field = CertificateKeyAlgorithm ::RSA_SHA256;
  149. else if (identifier == rsa_sha512_encryption_oid)
  150. field = CertificateKeyAlgorithm ::RSA_SHA512;
  151. else
  152. return {};
  153. EXIT_SCOPE("AlgorithmIdentifier");
  154. return true;
  155. };
  156. // signature
  157. {
  158. if (!parse_algorithm_identifier(certificate.algorithm).has_value())
  159. return {};
  160. }
  161. auto parse_name = [&](auto& name_struct) -> Optional<bool> {
  162. // Name ::= Choice {
  163. // rdn_sequence RDNSequence
  164. // } // NOTE: since this is the only alternative, there's no index
  165. // RDNSequence ::= Sequence OF RelativeDistinguishedName
  166. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject");
  167. // RelativeDistinguishedName ::= Set OF AttributeTypeAndValue
  168. // AttributeTypeAndValue ::= Sequence {
  169. // type AttributeType,
  170. // value AttributeValue
  171. // }
  172. // AttributeType ::= ObjectIdentifier
  173. // AttributeValue ::= Any
  174. while (!decoder.eof()) {
  175. // Parse only the the required fields, and ignore the rest.
  176. ENTER_SCOPE_OR_FAIL(Set, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName");
  177. while (!decoder.eof()) {
  178. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue");
  179. ENSURE_OBJECT_KIND(ObjectIdentifier, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type");
  180. if (auto type_identifier_or_error = decoder.read<Vector<int>>(); !type_identifier_or_error.is_error()) {
  181. // Figure out what type of identifier this is
  182. auto& identifier = type_identifier_or_error.value();
  183. if (identifier == common_name_oid) {
  184. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  185. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  186. name_struct.subject = name;
  187. } else if (identifier == country_name_oid) {
  188. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  189. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  190. name_struct.country = name;
  191. } else if (identifier == locality_name_oid) {
  192. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  193. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  194. name_struct.location = name;
  195. } else if (identifier == organization_name_oid) {
  196. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  197. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  198. name_struct.entity = name;
  199. } else if (identifier == organizational_unit_name_oid) {
  200. READ_OBJECT_OR_FAIL(PrintableString, StringView, name,
  201. "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::Value");
  202. name_struct.unit = name;
  203. }
  204. } else {
  205. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue::type data was invalid: {}", type_identifier_or_error.error());
  206. return {};
  207. }
  208. EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName::$::AttributeTypeAndValue");
  209. }
  210. EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject::$::RelativeDistinguishedName");
  211. }
  212. EXIT_SCOPE("Certificate::TBSCertificate::issuer/subject");
  213. return true;
  214. };
  215. // issuer
  216. {
  217. if (!parse_name(certificate.issuer).has_value())
  218. return {};
  219. }
  220. // validity
  221. {
  222. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Validity");
  223. auto parse_time = [&](Core::DateTime& datetime) -> Optional<bool> {
  224. // Time ::= Choice {
  225. // utc_time UTCTime,
  226. // general_time GeneralizedTime
  227. // }
  228. auto tag = decoder.peek();
  229. if (tag.is_error()) {
  230. dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time failed to read tag: {}", tag.error());
  231. return {};
  232. };
  233. if (tag.value().kind == Crypto::ASN1::Kind::UTCTime) {
  234. READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$");
  235. auto result = Crypto::ASN1::parse_utc_time(time);
  236. if (!result.has_value()) {
  237. dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid UTC Time: {}", time);
  238. return {};
  239. }
  240. datetime = result.release_value();
  241. return true;
  242. }
  243. if (tag.value().kind == Crypto::ASN1::Kind::GeneralizedTime) {
  244. READ_OBJECT_OR_FAIL(UTCTime, StringView, time, "Certificate::TBSCertificate::Validity::$");
  245. auto result = Crypto::ASN1::parse_generalized_time(time);
  246. if (!result.has_value()) {
  247. dbgln_if(1, "Certificate::TBSCertificate::Validity::$::Time Invalid Generalized Time: {}", time);
  248. return {};
  249. }
  250. datetime = result.release_value();
  251. return true;
  252. }
  253. dbgln_if(1, "Unrecognised Time format {}", Crypto::ASN1::kind_name(tag.value().kind));
  254. return {};
  255. };
  256. if (!parse_time(certificate.not_before).has_value())
  257. return {};
  258. if (!parse_time(certificate.not_after).has_value())
  259. return {};
  260. EXIT_SCOPE("Certificate::TBSCertificate::Validity");
  261. }
  262. // subject
  263. {
  264. if (!parse_name(certificate.subject).has_value())
  265. return {};
  266. }
  267. // subject_public_key_info
  268. {
  269. // SubjectPublicKeyInfo ::= Sequence {
  270. // algorithm AlgorithmIdentifier,
  271. // subject_public_key BitString
  272. // }
  273. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::subject_public_key_info");
  274. if (!parse_algorithm_identifier(certificate.key_algorithm).has_value())
  275. return {};
  276. READ_OBJECT_OR_FAIL(BitString, const BitmapView, value, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info");
  277. // Note: Once we support other kinds of keys, make sure to check the kind here!
  278. auto key = Crypto::PK::RSA::parse_rsa_key({ value.data(), value.size_in_bytes() });
  279. if (!key.public_key.length()) {
  280. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::subject_public_key_info::subject_public_key_info: Invalid key");
  281. return {};
  282. }
  283. certificate.public_key = move(key.public_key);
  284. EXIT_SCOPE("Certificate::TBSCertificate::subject_public_key_info");
  285. }
  286. auto parse_unique_identifier = [&]() -> Optional<bool> {
  287. if (certificate.version == 0)
  288. return true;
  289. auto tag = decoder.peek();
  290. if (tag.is_error()) {
  291. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error());
  292. return {};
  293. }
  294. // The spec says to just ignore these.
  295. if (static_cast<u8>(tag.value().kind) == 1 || static_cast<u8>(tag.value().kind) == 2)
  296. DROP_OBJECT_OR_FAIL("UniqueIdentifier");
  297. return true;
  298. };
  299. // issuer_unique_identifier
  300. {
  301. if (!parse_unique_identifier().has_value())
  302. return {};
  303. }
  304. // subject_unique_identifier
  305. {
  306. if (!parse_unique_identifier().has_value())
  307. return {};
  308. }
  309. // extensions
  310. {
  311. if (certificate.version == 2) {
  312. auto tag = decoder.peek();
  313. if (tag.is_error()) {
  314. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::*::UniqueIdentifier could not read tag: {}", tag.error());
  315. return {};
  316. }
  317. if (static_cast<u8>(tag.value().kind) == 3) {
  318. // Extensions ::= Sequence OF Extension
  319. // Extension ::= Sequence {
  320. // extension_id ObjectIdentifier,
  321. // critical Boolean DEFAULT false,
  322. // extension_value OctetString (DER-encoded)
  323. // }
  324. ENTER_SCOPE_WITHOUT_TYPECHECK("Certificate::TBSCertificate::Extensions(IMPLICIT)");
  325. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions");
  326. while (!decoder.eof()) {
  327. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension");
  328. READ_OBJECT_OR_FAIL(ObjectIdentifier, Vector<int>, extension_id, "Certificate::TBSCertificate::Extensions::$::Extension::extension_id");
  329. bool is_critical = false;
  330. if (auto tag = decoder.peek(); !tag.is_error() && tag.value().kind == Crypto::ASN1::Kind::Boolean) {
  331. // Read the 'critical' property
  332. READ_OBJECT_OR_FAIL(Boolean, bool, critical, "Certificate::TBSCertificate::Extensions::$::Extension::critical");
  333. is_critical = critical;
  334. }
  335. READ_OBJECT_OR_FAIL(OctetString, StringView, extension_value, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value");
  336. // Figure out what this extension is.
  337. if (extension_id == subject_alternative_name_oid) {
  338. Crypto::ASN1::Decoder decoder { extension_value.bytes() };
  339. // SubjectAlternativeName ::= GeneralNames
  340. // GeneralNames ::= Sequence OF GeneralName
  341. // GeneralName ::= CHOICE {
  342. // other_name (0) OtherName,
  343. // rfc_822_name (1) IA5String,
  344. // dns_name (2) IA5String,
  345. // x400Address (3) ORAddress,
  346. // directory_name (4) Name,
  347. // edi_party_name (5) EDIPartyName,
  348. // uri (6) IA5String,
  349. // ip_address (7) OctetString,
  350. // registered_id (8) ObjectIdentifier,
  351. // }
  352. ENTER_SCOPE_OR_FAIL(Sequence, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName");
  353. while (!decoder.eof()) {
  354. auto tag = decoder.peek();
  355. if (tag.is_error()) {
  356. dbgln_if(TLS_DEBUG, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$ could not read tag: {}", tag.error());
  357. return {};
  358. }
  359. auto tag_value = static_cast<u8>(tag.value().kind);
  360. switch (tag_value) {
  361. case 0:
  362. // OtherName
  363. // We don't know how to use this.
  364. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::OtherName");
  365. break;
  366. case 1:
  367. // RFC 822 name
  368. // We don't know how to use this.
  369. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RFC822Name");
  370. break;
  371. case 2: {
  372. // DNS Name
  373. READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DNSName");
  374. certificate.SAN.append(name);
  375. break;
  376. }
  377. case 3:
  378. // x400Address
  379. // We don't know how to use this.
  380. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::X400Adress");
  381. break;
  382. case 4:
  383. // Directory name
  384. // We don't know how to use this.
  385. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::DirectoryName");
  386. break;
  387. case 5:
  388. // edi party name
  389. // We don't know how to use this.
  390. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::EDIPartyName");
  391. break;
  392. case 6: {
  393. // URI
  394. READ_OBJECT_OR_FAIL(IA5String, StringView, name, "Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::URI");
  395. certificate.SAN.append(name);
  396. break;
  397. }
  398. case 7:
  399. // IP Address
  400. // We can't handle these.
  401. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::IPAddress");
  402. break;
  403. case 8:
  404. // Registered ID
  405. // We can't handle these.
  406. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::RegisteredID");
  407. break;
  408. default:
  409. dbgln_if(TLS_DEBUG, "Unknown tag in SAN choice {}", tag_value);
  410. if (is_critical)
  411. return {};
  412. else
  413. DROP_OBJECT_OR_FAIL("Certificate::TBSCertificate::Extensions::$::Extension::extension_value::SubjectAlternativeName::$::???");
  414. }
  415. }
  416. }
  417. EXIT_SCOPE("Certificate::TBSCertificate::Extensions::$::Extension");
  418. }
  419. EXIT_SCOPE("Certificate::TBSCertificate::Extensions");
  420. EXIT_SCOPE("Certificate::TBSCertificate::Extensions(IMPLICIT)");
  421. }
  422. }
  423. }
  424. // Just ignore the rest of the data for now.
  425. EXIT_SCOPE("Certificate::TBSCertificate");
  426. EXIT_SCOPE("Certificate");
  427. dbgln_if(TLS_DEBUG, "Certificate issued for {} by {}", certificate.subject.subject, certificate.issuer.subject);
  428. return certificate;
  429. #undef DROP_OBJECT_OR_FAIL
  430. #undef ENSURE_OBJECT_KIND
  431. #undef ENTER_SCOPE_OR_FAIL
  432. #undef ENTER_SCOPE_WITHOUT_TYPECHECK
  433. #undef EXIT_SCOPE
  434. #undef READ_OBJECT_OR_FAIL
  435. }
  436. ssize_t TLSv12::handle_certificate(ReadonlyBytes buffer)
  437. {
  438. ssize_t res = 0;
  439. if (buffer.size() < 3) {
  440. #if TLS_DEBUG
  441. dbgln("not enough certificate header data");
  442. #endif
  443. return (i8)Error::NeedMoreData;
  444. }
  445. u32 certificate_total_length = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
  446. dbgln_if(TLS_DEBUG, "total length: {}", certificate_total_length);
  447. if (certificate_total_length <= 4)
  448. return 3 * certificate_total_length;
  449. res += 3;
  450. if (certificate_total_length > buffer.size() - res) {
  451. #if TLS_DEBUG
  452. dbgln("not enough data for claimed total cert length");
  453. #endif
  454. return (i8)Error::NeedMoreData;
  455. }
  456. size_t size = certificate_total_length;
  457. size_t index = 0;
  458. bool valid_certificate = false;
  459. while (size > 0) {
  460. ++index;
  461. if (buffer.size() - res < 3) {
  462. #if TLS_DEBUG
  463. dbgln("not enough data for certificate length");
  464. #endif
  465. return (i8)Error::NeedMoreData;
  466. }
  467. size_t certificate_size = buffer[res] * 0x10000 + buffer[res + 1] * 0x100 + buffer[res + 2];
  468. res += 3;
  469. if (buffer.size() - res < certificate_size) {
  470. #if TLS_DEBUG
  471. dbgln("not enough data for certificate body");
  472. #endif
  473. return (i8)Error::NeedMoreData;
  474. }
  475. auto res_cert = res;
  476. auto remaining = certificate_size;
  477. size_t certificates_in_chain = 0;
  478. do {
  479. if (remaining <= 3) {
  480. dbgln("Ran out of data");
  481. break;
  482. }
  483. ++certificates_in_chain;
  484. if (buffer.size() < (size_t)res_cert + 3) {
  485. dbgln("not enough data to read cert size ({} < {})", buffer.size(), res_cert + 3);
  486. break;
  487. }
  488. size_t certificate_size_specific = buffer[res_cert] * 0x10000 + buffer[res_cert + 1] * 0x100 + buffer[res_cert + 2];
  489. res_cert += 3;
  490. remaining -= 3;
  491. if (certificate_size_specific > remaining) {
  492. dbgln("invalid certificate size (expected {} but got {})", remaining, certificate_size_specific);
  493. break;
  494. }
  495. remaining -= certificate_size_specific;
  496. auto certificate = parse_asn1(buffer.slice(res_cert, certificate_size_specific), false);
  497. if (certificate.has_value()) {
  498. if (certificate.value().is_valid()) {
  499. m_context.certificates.append(certificate.value());
  500. valid_certificate = true;
  501. }
  502. }
  503. res_cert += certificate_size_specific;
  504. } while (remaining > 0);
  505. if (remaining) {
  506. dbgln("extraneous {} bytes left over after parsing certificates", remaining);
  507. }
  508. size -= certificate_size + 3;
  509. res += certificate_size;
  510. }
  511. if (!valid_certificate)
  512. return (i8)Error::UnsupportedCertificate;
  513. if ((size_t)res != buffer.size())
  514. dbgln("some data left unread: {} bytes out of {}", res, buffer.size());
  515. return res;
  516. }
  517. void TLSv12::consume(ReadonlyBytes record)
  518. {
  519. if (m_context.critical_error) {
  520. dbgln("There has been a critical error ({}), refusing to continue", (i8)m_context.critical_error);
  521. return;
  522. }
  523. if (record.size() == 0) {
  524. return;
  525. }
  526. dbgln_if(TLS_DEBUG, "Consuming {} bytes", record.size());
  527. m_context.message_buffer.append(record.data(), record.size());
  528. size_t index { 0 };
  529. size_t buffer_length = m_context.message_buffer.size();
  530. size_t size_offset { 3 }; // read the common record header
  531. size_t header_size { 5 };
  532. dbgln_if(TLS_DEBUG, "message buffer length {}", buffer_length);
  533. while (buffer_length >= 5) {
  534. auto length = AK::convert_between_host_and_network_endian(*(u16*)m_context.message_buffer.offset_pointer(index + size_offset)) + header_size;
  535. if (length > buffer_length) {
  536. dbgln_if(TLS_DEBUG, "Need more data: {} > {}", length, buffer_length);
  537. break;
  538. }
  539. auto consumed = handle_message(m_context.message_buffer.bytes().slice(index, length));
  540. if constexpr (TLS_DEBUG) {
  541. if (consumed > 0)
  542. dbgln("consumed {} bytes", consumed);
  543. else
  544. dbgln("error: {}", consumed);
  545. }
  546. if (consumed != (i8)Error::NeedMoreData) {
  547. if (consumed < 0) {
  548. dbgln("Consumed an error: {}", consumed);
  549. if (!m_context.critical_error)
  550. m_context.critical_error = (i8)consumed;
  551. m_context.error_code = (Error)consumed;
  552. break;
  553. }
  554. } else {
  555. continue;
  556. }
  557. index += length;
  558. buffer_length -= length;
  559. if (m_context.critical_error) {
  560. dbgln("Broken connection");
  561. m_context.error_code = Error::BrokenConnection;
  562. break;
  563. }
  564. }
  565. if (m_context.error_code != Error::NoError && m_context.error_code != Error::NeedMoreData) {
  566. dbgln("consume error: {}", (i8)m_context.error_code);
  567. m_context.message_buffer.clear();
  568. return;
  569. }
  570. if (index) {
  571. m_context.message_buffer = m_context.message_buffer.slice(index, m_context.message_buffer.size() - index);
  572. }
  573. }
  574. void TLSv12::ensure_hmac(size_t digest_size, bool local)
  575. {
  576. if (local && m_hmac_local)
  577. return;
  578. if (!local && m_hmac_remote)
  579. return;
  580. auto hash_kind = Crypto::Hash::HashKind::None;
  581. switch (digest_size) {
  582. case Crypto::Hash::SHA1::DigestSize:
  583. hash_kind = Crypto::Hash::HashKind::SHA1;
  584. break;
  585. case Crypto::Hash::SHA256::DigestSize:
  586. hash_kind = Crypto::Hash::HashKind::SHA256;
  587. break;
  588. case Crypto::Hash::SHA512::DigestSize:
  589. hash_kind = Crypto::Hash::HashKind::SHA512;
  590. break;
  591. default:
  592. dbgln("Failed to find a suitable hash for size {}", digest_size);
  593. break;
  594. }
  595. auto hmac = make<Crypto::Authentication::HMAC<Crypto::Hash::Manager>>(ReadonlyBytes { local ? m_context.crypto.local_mac : m_context.crypto.remote_mac, digest_size }, hash_kind);
  596. if (local)
  597. m_hmac_local = move(hmac);
  598. else
  599. m_hmac_remote = move(hmac);
  600. }
  601. bool Certificate::is_valid() const
  602. {
  603. auto now = Core::DateTime::now();
  604. if (now < not_before) {
  605. dbgln("certificate expired (not yet valid, signed for {})", not_before.to_string());
  606. return false;
  607. }
  608. if (not_after < now) {
  609. dbgln("certificate expired (expiry date {})", not_after.to_string());
  610. return false;
  611. }
  612. return true;
  613. }
  614. void TLSv12::try_disambiguate_error() const
  615. {
  616. dbgln("Possible failure cause(s): ");
  617. switch ((AlertDescription)m_context.critical_error) {
  618. case AlertDescription::HandshakeFailure:
  619. if (!m_context.cipher_spec_set) {
  620. dbgln("- No cipher suite in common with {}", m_context.extensions.SNI);
  621. } else {
  622. dbgln("- Unknown internal issue");
  623. }
  624. break;
  625. case AlertDescription::InsufficientSecurity:
  626. dbgln("- No cipher suite in common with {} (the server is oh so secure)", m_context.extensions.SNI);
  627. break;
  628. case AlertDescription::ProtocolVersion:
  629. dbgln("- The server refused to negotiate with TLS 1.2 :(");
  630. break;
  631. case AlertDescription::UnexpectedMessage:
  632. dbgln("- We sent an invalid message for the state we're in.");
  633. break;
  634. case AlertDescription::BadRecordMAC:
  635. dbgln("- Bad MAC record from our side.");
  636. dbgln("- Ciphertext wasn't an even multiple of the block length.");
  637. dbgln("- Bad block cipher padding.");
  638. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  639. break;
  640. case AlertDescription::RecordOverflow:
  641. dbgln("- Sent a ciphertext record which has a length bigger than 18432 bytes.");
  642. dbgln("- Sent record decrypted to a compressed record that has a length bigger than 18432 bytes.");
  643. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  644. break;
  645. case AlertDescription::DecompressionFailure:
  646. dbgln("- We sent invalid input for decompression (e.g. data that would expand to excessive length)");
  647. break;
  648. case AlertDescription::IllegalParameter:
  649. dbgln("- We sent a parameter in the handshake that is out of range or inconsistent with the other parameters.");
  650. break;
  651. case AlertDescription::DecodeError:
  652. dbgln("- The message we sent cannot be decoded because a field was out of range or the length was incorrect.");
  653. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  654. break;
  655. case AlertDescription::DecryptError:
  656. dbgln("- A handshake crypto operation failed. This includes signature verification and validating Finished.");
  657. break;
  658. case AlertDescription::AccessDenied:
  659. dbgln("- The certificate is valid, but once access control was applied, the sender decided to stop negotiation.");
  660. break;
  661. case AlertDescription::InternalError:
  662. dbgln("- No one knows, but it isn't a protocol failure.");
  663. break;
  664. case AlertDescription::DecryptionFailed:
  665. case AlertDescription::NoCertificate:
  666. case AlertDescription::ExportRestriction:
  667. dbgln("- No one knows, the server sent a non-compliant alert.");
  668. break;
  669. default:
  670. dbgln("- No one knows.");
  671. break;
  672. }
  673. }
  674. void TLSv12::set_root_certificates(Vector<Certificate> certificates)
  675. {
  676. if (!m_context.root_ceritificates.is_empty())
  677. dbgln("TLS warn: resetting root certificates!");
  678. for (auto& cert : certificates) {
  679. if (!cert.is_valid())
  680. dbgln("Certificate for {} by {} is invalid, things may or may not work!", cert.subject.subject, cert.issuer.subject);
  681. // FIXME: Figure out what we should do when our root certs are invalid.
  682. }
  683. m_context.root_ceritificates = move(certificates);
  684. }
  685. bool Context::verify_chain() const
  686. {
  687. if (!options.validate_certificates)
  688. return true;
  689. const Vector<Certificate>* local_chain = nullptr;
  690. if (is_server) {
  691. dbgln("Unsupported: Server mode");
  692. TODO();
  693. } else {
  694. local_chain = &certificates;
  695. }
  696. // FIXME: Actually verify the signature, instead of just checking the name.
  697. HashMap<String, String> chain;
  698. HashTable<String> roots;
  699. // First, walk the root certs.
  700. for (auto& cert : root_ceritificates) {
  701. roots.set(cert.subject.subject);
  702. chain.set(cert.subject.subject, cert.issuer.subject);
  703. }
  704. // Then, walk the local certs.
  705. for (auto& cert : *local_chain) {
  706. auto& issuer_unique_name = cert.issuer.unit.is_empty() ? cert.issuer.subject : cert.issuer.unit;
  707. chain.set(cert.subject.subject, issuer_unique_name);
  708. }
  709. // Then verify the chain.
  710. for (auto& it : chain) {
  711. if (it.key == it.value) { // Allow self-signed certificates.
  712. if (!roots.contains(it.key))
  713. dbgln("Self-signed warning: Certificate for {} is self-signed", it.key);
  714. continue;
  715. }
  716. auto ref = chain.get(it.value);
  717. if (!ref.has_value()) {
  718. dbgln("Certificate for {} is not signed by anyone we trust ({})", it.key, it.value);
  719. return false;
  720. }
  721. if (ref.value() == it.key) // Allow (but warn about) mutually recursively signed cert A <-> B.
  722. dbgln("Co-dependency warning: Certificate for {} is issued by {}, which itself is issued by {}", ref.value(), it.key, ref.value());
  723. }
  724. return true;
  725. }
  726. static bool wildcard_matches(const StringView& host, const StringView& subject)
  727. {
  728. if (host.matches(subject))
  729. return true;
  730. if (subject.starts_with("*."))
  731. return wildcard_matches(host, subject.substring_view(2));
  732. return false;
  733. }
  734. Optional<size_t> TLSv12::verify_chain_and_get_matching_certificate(const StringView& host) const
  735. {
  736. if (m_context.certificates.is_empty() || !m_context.verify_chain())
  737. return {};
  738. if (host.is_empty())
  739. return 0;
  740. for (size_t i = 0; i < m_context.certificates.size(); ++i) {
  741. auto& cert = m_context.certificates[i];
  742. if (wildcard_matches(host, cert.subject.subject))
  743. return i;
  744. for (auto& san : cert.SAN) {
  745. if (wildcard_matches(host, san))
  746. return i;
  747. }
  748. }
  749. return {};
  750. }
  751. TLSv12::TLSv12(Core::Object* parent, Options options)
  752. : Core::Socket(Core::Socket::Type::TCP, parent)
  753. {
  754. m_context.options = move(options);
  755. m_context.is_server = false;
  756. m_context.tls_buffer = ByteBuffer::create_uninitialized(0);
  757. #ifdef SOCK_NONBLOCK
  758. int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  759. #else
  760. int fd = socket(AF_INET, SOCK_STREAM, 0);
  761. int option = 1;
  762. ioctl(fd, FIONBIO, &option);
  763. #endif
  764. if (fd < 0) {
  765. set_error(errno);
  766. } else {
  767. set_fd(fd);
  768. set_mode(IODevice::ReadWrite);
  769. set_error(0);
  770. }
  771. }
  772. bool TLSv12::add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes rsa_key) // FIXME: This should not be bound to RSA
  773. {
  774. if (certificate_pem_buffer.is_empty() || rsa_key.is_empty()) {
  775. return true;
  776. }
  777. auto decoded_certificate = Crypto::decode_pem(certificate_pem_buffer);
  778. if (decoded_certificate.is_empty()) {
  779. dbgln("Certificate not PEM");
  780. return false;
  781. }
  782. auto maybe_certificate = parse_asn1(decoded_certificate);
  783. if (!maybe_certificate.has_value()) {
  784. dbgln("Invalid certificate");
  785. return false;
  786. }
  787. Crypto::PK::RSA rsa(rsa_key);
  788. auto certificate = maybe_certificate.value();
  789. certificate.private_key = rsa.private_key();
  790. return add_client_key(certificate);
  791. }
  792. AK::Singleton<DefaultRootCACertificates> DefaultRootCACertificates::s_the;
  793. DefaultRootCACertificates::DefaultRootCACertificates()
  794. {
  795. // FIXME: This might not be the best format, find a better way to represent CA certificates.
  796. auto config = Core::ConfigFile::get_for_system("ca_certs");
  797. auto now = Core::DateTime::now();
  798. auto last_year = Core::DateTime::create(now.year() - 1);
  799. auto next_year = Core::DateTime::create(now.year() + 1);
  800. for (auto& entity : config->groups()) {
  801. Certificate cert;
  802. cert.subject.subject = entity;
  803. cert.issuer.subject = config->read_entry(entity, "issuer_subject", entity);
  804. cert.subject.country = config->read_entry(entity, "country");
  805. cert.not_before = Crypto::ASN1::parse_generalized_time(config->read_entry(entity, "not_before", "")).value_or(last_year);
  806. cert.not_after = Crypto::ASN1::parse_generalized_time(config->read_entry(entity, "not_after", "")).value_or(next_year);
  807. m_ca_certificates.append(move(cert));
  808. }
  809. }
  810. }