TLSv12.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Debug.h>
  27. #include <AK/Endian.h>
  28. #include <LibCore/ConfigFile.h>
  29. #include <LibCore/DateTime.h>
  30. #include <LibCore/Timer.h>
  31. #include <LibCrypto/ASN1/DER.h>
  32. #include <LibCrypto/ASN1/PEM.h>
  33. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  34. #include <LibTLS/TLSv12.h>
  35. #include <errno.h>
  36. #ifndef SOCK_NONBLOCK
  37. # include <sys/ioctl.h>
  38. #endif
  39. namespace {
  40. struct OIDChain {
  41. OIDChain* root { nullptr };
  42. u8* oid { nullptr };
  43. };
  44. }
  45. namespace TLS {
  46. // "for now" q&d implementation of ASN1
  47. namespace {
  48. static bool _asn1_is_field_present(const u32* fields, const u32* prefix)
  49. {
  50. size_t i = 0;
  51. while (prefix[i]) {
  52. if (fields[i] != prefix[i])
  53. return false;
  54. ++i;
  55. }
  56. return true;
  57. }
  58. static bool _asn1_is_oid(const u8* oid, const u8* compare, size_t length = 3)
  59. {
  60. size_t i = 0;
  61. while (oid[i] && i < length) {
  62. if (oid[i] != compare[i])
  63. return false;
  64. ++i;
  65. }
  66. return true;
  67. }
  68. static bool _asn1_is_oid_in_chain(OIDChain* reference_chain, const u8* lookup, size_t lookup_length = 3)
  69. {
  70. auto is_oid = [](const u8* oid, size_t oid_length, const u8* compare, size_t compare_length) {
  71. if (oid_length < compare_length)
  72. compare_length = oid_length;
  73. for (size_t i = 0; i < compare_length; i++) {
  74. if (oid[i] != compare[i])
  75. return false;
  76. }
  77. return true;
  78. };
  79. for (; reference_chain; reference_chain = reference_chain->root) {
  80. if (reference_chain->oid)
  81. if (is_oid(reference_chain->oid, 16, lookup, lookup_length))
  82. return true;
  83. }
  84. return false;
  85. }
  86. static bool _set_algorithm(CertificateKeyAlgorithm& algorithm, const u8* value, size_t length)
  87. {
  88. if (length == 7) {
  89. // Elliptic Curve pubkey
  90. dbgln("Cert.algorithm: EC, unsupported");
  91. return false;
  92. }
  93. if (length == 8) {
  94. // named EC key
  95. dbgln("Cert.algorithm: Named EC ({}), unsupported", *value);
  96. return false;
  97. }
  98. if (length == 5) {
  99. // named EC SECP key
  100. dbgln("Cert.algorithm: Named EC secp ({}), unsupported", *value);
  101. return false;
  102. }
  103. if (length != 9) {
  104. dbgln("Invalid certificate algorithm");
  105. return false;
  106. }
  107. if (_asn1_is_oid(value, Constants::RSA_SIGN_RSA_OID, 9)) {
  108. algorithm = CertificateKeyAlgorithm::RSA_RSA;
  109. return true;
  110. }
  111. if (_asn1_is_oid(value, Constants::RSA_SIGN_SHA256_OID, 9)) {
  112. algorithm = CertificateKeyAlgorithm::RSA_SHA256;
  113. return true;
  114. }
  115. if (_asn1_is_oid(value, Constants::RSA_SIGN_SHA512_OID, 9)) {
  116. algorithm = CertificateKeyAlgorithm::RSA_SHA512;
  117. return true;
  118. }
  119. if (_asn1_is_oid(value, Constants::RSA_SIGN_SHA1_OID, 9)) {
  120. algorithm = CertificateKeyAlgorithm::RSA_SHA1;
  121. return true;
  122. }
  123. if (_asn1_is_oid(value, Constants::RSA_SIGN_MD5_OID, 9)) {
  124. algorithm = CertificateKeyAlgorithm::RSA_MD5;
  125. return true;
  126. }
  127. dbgln("Unsupported RSA Signature mode {}", value[8]);
  128. return false;
  129. }
  130. static size_t _get_asn1_length(const u8* buffer, size_t length, size_t& octets)
  131. {
  132. octets = 0;
  133. if (length < 1)
  134. return 0;
  135. u8 size = buffer[0];
  136. if (size & 0x80) {
  137. octets = size & 0x7f;
  138. if (octets > length - 1) {
  139. return 0;
  140. }
  141. auto reference_octets = octets;
  142. if (octets > 4)
  143. reference_octets = 4;
  144. size_t long_size = 0, coeff = 1;
  145. for (auto i = reference_octets; i > 0; --i) {
  146. long_size += buffer[i] * coeff;
  147. coeff *= 0x100;
  148. }
  149. ++octets;
  150. return long_size;
  151. }
  152. ++octets;
  153. return size;
  154. }
  155. static ssize_t _parse_asn1(const Context& context, Certificate& cert, const u8* buffer, size_t size, int level, u32* fields, u8* has_key, int client_cert, u8* root_oid, OIDChain* chain)
  156. {
  157. OIDChain local_chain;
  158. local_chain.root = chain;
  159. size_t position = 0;
  160. // parse DER...again
  161. size_t index = 0;
  162. u8 oid[16] { 0 };
  163. local_chain.oid = oid;
  164. if (has_key)
  165. *has_key = 0;
  166. u8 local_has_key = 0;
  167. const u8* cert_data = nullptr;
  168. size_t cert_length = 0;
  169. while (position < size) {
  170. size_t start_position = position;
  171. if (size - position < 2) {
  172. dbgln("not enough data for certificate size");
  173. return (i8)Error::NeedMoreData;
  174. }
  175. u8 first = buffer[position++];
  176. u8 type = first & 0x1f;
  177. u8 constructed = first & 0x20;
  178. size_t octets = 0;
  179. u32 temp;
  180. index++;
  181. if (level <= 0xff)
  182. fields[level - 1] = index;
  183. size_t length = _get_asn1_length((const u8*)&buffer[position], size - position, octets);
  184. if (octets > 4 || octets > size - position) {
  185. #if TLS_DEBUG
  186. dbgln("could not read the certificate");
  187. #endif
  188. return position;
  189. }
  190. position += octets;
  191. if (size - position < length) {
  192. #if TLS_DEBUG
  193. dbgln("not enough data for sequence");
  194. #endif
  195. return (i8)Error::NeedMoreData;
  196. }
  197. if (length && constructed) {
  198. switch (type) {
  199. case 0x03:
  200. break;
  201. case 0x10:
  202. if (level == 2 && index == 1) {
  203. cert_length = length + position - start_position;
  204. cert_data = buffer + start_position;
  205. }
  206. // public key data
  207. if (!cert.version && _asn1_is_field_present(fields, Constants::priv_der_id)) {
  208. temp = length + position - start_position;
  209. if (cert.der.size() < temp) {
  210. cert.der.grow(temp);
  211. } else {
  212. cert.der.trim(temp);
  213. }
  214. cert.der.overwrite(0, buffer + start_position, temp);
  215. }
  216. break;
  217. default:
  218. break;
  219. }
  220. local_has_key = false;
  221. _parse_asn1(context, cert, buffer + position, length, level + 1, fields, &local_has_key, client_cert, root_oid, &local_chain);
  222. if ((local_has_key && (!context.is_server || client_cert)) || (client_cert || _asn1_is_field_present(fields, Constants::pk_id))) {
  223. temp = length + position - start_position;
  224. if (cert.der.size() < temp) {
  225. cert.der.grow(temp);
  226. } else {
  227. cert.der.trim(temp);
  228. }
  229. cert.der.overwrite(0, buffer + start_position, temp);
  230. }
  231. } else {
  232. switch (type) {
  233. case 0x00:
  234. return position;
  235. break;
  236. case 0x01:
  237. temp = buffer[position];
  238. break;
  239. case 0x02:
  240. if (_asn1_is_field_present(fields, Constants::pk_id)) {
  241. if (has_key)
  242. *has_key = true;
  243. if (index == 1)
  244. cert.public_key.set(
  245. Crypto::UnsignedBigInteger::import_data(buffer + position, length),
  246. cert.public_key.public_exponent());
  247. else if (index == 2)
  248. cert.public_key.set(
  249. cert.public_key.modulus(),
  250. Crypto::UnsignedBigInteger::import_data(buffer + position, length));
  251. } else if (_asn1_is_field_present(fields, Constants::serial_id)) {
  252. cert.serial_number = Crypto::UnsignedBigInteger::import_data(buffer + position, length);
  253. }
  254. if (_asn1_is_field_present(fields, Constants::version_id)) {
  255. if (length == 1)
  256. cert.version = buffer[position];
  257. }
  258. if (chain && length > 2) {
  259. if (_asn1_is_oid_in_chain(chain, Constants::san_oid)) {
  260. StringView alt_name { &buffer[position], length };
  261. cert.SAN.append(alt_name);
  262. }
  263. }
  264. // print_buffer(ReadonlyBytes { buffer + position, length });
  265. break;
  266. case 0x03:
  267. if (_asn1_is_field_present(fields, Constants::pk_id)) {
  268. if (has_key)
  269. *has_key = true;
  270. }
  271. if (_asn1_is_field_present(fields, Constants::sign_id)) {
  272. auto* value = buffer + position;
  273. auto len = length;
  274. if (!value[0] && len % 2) {
  275. ++value;
  276. --len;
  277. }
  278. cert.sign_key = ByteBuffer::copy(value, len);
  279. } else {
  280. if (buffer[position] == 0 && length > 256) {
  281. _parse_asn1(context, cert, buffer + position + 1, length - 1, level + 1, fields, &local_has_key, client_cert, root_oid, &local_chain);
  282. } else {
  283. _parse_asn1(context, cert, buffer + position, length, level + 1, fields, &local_has_key, client_cert, root_oid, &local_chain);
  284. }
  285. }
  286. break;
  287. case 0x04:
  288. _parse_asn1(context, cert, buffer + position, length, level + 1, fields, &local_has_key, client_cert, root_oid, &local_chain);
  289. break;
  290. case 0x05:
  291. break;
  292. case 0x06:
  293. if (_asn1_is_field_present(fields, Constants::pk_id)) {
  294. _set_algorithm(cert.key_algorithm, buffer + position, length);
  295. }
  296. if (_asn1_is_field_present(fields, Constants::algorithm_id)) {
  297. _set_algorithm(cert.algorithm, buffer + position, length);
  298. }
  299. if (length < 16)
  300. memcpy(oid, buffer + position, length);
  301. else
  302. memcpy(oid, buffer + position, 16);
  303. if (root_oid)
  304. memcpy(root_oid, oid, 16);
  305. break;
  306. case 0x09:
  307. break;
  308. case 0x17:
  309. case 0x018:
  310. // time
  311. // ignore
  312. break;
  313. case 0x013:
  314. case 0x0c:
  315. case 0x14:
  316. case 0x15:
  317. case 0x16:
  318. case 0x19:
  319. case 0x1a:
  320. case 0x1b:
  321. case 0x1c:
  322. case 0x1d:
  323. case 0x1e:
  324. // printable string and such
  325. if (_asn1_is_field_present(fields, Constants::issurer_id)) {
  326. if (_asn1_is_oid(oid, Constants::country_oid)) {
  327. cert.issuer_country = String { (const char*)buffer + position, length };
  328. } else if (_asn1_is_oid(oid, Constants::state_oid)) {
  329. cert.issuer_state = String { (const char*)buffer + position, length };
  330. } else if (_asn1_is_oid(oid, Constants::location_oid)) {
  331. cert.issuer_location = String { (const char*)buffer + position, length };
  332. } else if (_asn1_is_oid(oid, Constants::entity_oid)) {
  333. cert.issuer_entity = String { (const char*)buffer + position, length };
  334. } else if (_asn1_is_oid(oid, Constants::subject_oid)) {
  335. cert.issuer_subject = String { (const char*)buffer + position, length };
  336. } else if (_asn1_is_oid(oid, Constants::unit_oid)) {
  337. cert.issuer_unit = String { (const char*)buffer + position, length };
  338. }
  339. } else if (_asn1_is_field_present(fields, Constants::owner_id)) {
  340. if (_asn1_is_oid(oid, Constants::country_oid)) {
  341. cert.country = String { (const char*)buffer + position, length };
  342. } else if (_asn1_is_oid(oid, Constants::state_oid)) {
  343. cert.state = String { (const char*)buffer + position, length };
  344. } else if (_asn1_is_oid(oid, Constants::location_oid)) {
  345. cert.location = String { (const char*)buffer + position, length };
  346. } else if (_asn1_is_oid(oid, Constants::entity_oid)) {
  347. cert.entity = String { (const char*)buffer + position, length };
  348. } else if (_asn1_is_oid(oid, Constants::subject_oid)) {
  349. cert.subject = String { (const char*)buffer + position, length };
  350. } else if (_asn1_is_oid(oid, Constants::unit_oid)) {
  351. cert.unit = String { (const char*)buffer + position, length };
  352. }
  353. }
  354. break;
  355. default:
  356. break;
  357. }
  358. }
  359. position += length;
  360. }
  361. if (level == 2 && cert.sign_key.size() && cert_length && cert_data) {
  362. cert.fingerprint.clear();
  363. Crypto::Hash::Manager hash;
  364. switch (cert.key_algorithm) {
  365. case CertificateKeyAlgorithm::RSA_MD5:
  366. hash.initialize(Crypto::Hash::HashKind::MD5);
  367. break;
  368. case CertificateKeyAlgorithm::RSA_SHA1:
  369. hash.initialize(Crypto::Hash::HashKind::SHA1);
  370. break;
  371. case CertificateKeyAlgorithm::RSA_SHA256:
  372. hash.initialize(Crypto::Hash::HashKind::SHA256);
  373. break;
  374. case CertificateKeyAlgorithm::RSA_SHA512:
  375. hash.initialize(Crypto::Hash::HashKind::SHA512);
  376. break;
  377. default:
  378. dbgln_if(TLS_DEBUG, "Unsupported hash mode {}", (u32)cert.key_algorithm);
  379. // fallback to md5, it will fail later
  380. hash.initialize(Crypto::Hash::HashKind::MD5);
  381. break;
  382. }
  383. hash.update(cert_data, cert_length);
  384. auto fingerprint = hash.digest();
  385. cert.fingerprint.grow(fingerprint.data_length());
  386. cert.fingerprint.overwrite(0, fingerprint.immutable_data(), fingerprint.data_length());
  387. #if TLS_DEBUG
  388. dbgln("Certificate fingerprint:");
  389. print_buffer(cert.fingerprint);
  390. #endif
  391. }
  392. return position;
  393. }
  394. }
  395. Optional<Certificate> TLSv12::parse_asn1(ReadonlyBytes buffer, bool) const
  396. {
  397. // FIXME: Our ASN.1 parser is not quite up to the task of
  398. // parsing this X.509 certificate, so for the
  399. // time being, we will "parse" the certificate
  400. // manually right here.
  401. Certificate cert;
  402. u32 fields[0xff];
  403. _parse_asn1(m_context, cert, buffer.data(), buffer.size(), 1, fields, nullptr, 0, nullptr, nullptr);
  404. dbgln_if(TLS_DEBUG, "Certificate issued for {} by {}", cert.subject, cert.issuer_subject);
  405. return cert;
  406. }
  407. ssize_t TLSv12::handle_certificate(ReadonlyBytes buffer)
  408. {
  409. ssize_t res = 0;
  410. if (buffer.size() < 3) {
  411. #if TLS_DEBUG
  412. dbgln("not enough certificate header data");
  413. #endif
  414. return (i8)Error::NeedMoreData;
  415. }
  416. u32 certificate_total_length = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
  417. dbgln_if(TLS_DEBUG, "total length: {}", certificate_total_length);
  418. if (certificate_total_length <= 4)
  419. return 3 * certificate_total_length;
  420. res += 3;
  421. if (certificate_total_length > buffer.size() - res) {
  422. #if TLS_DEBUG
  423. dbgln("not enough data for claimed total cert length");
  424. #endif
  425. return (i8)Error::NeedMoreData;
  426. }
  427. size_t size = certificate_total_length;
  428. size_t index = 0;
  429. bool valid_certificate = false;
  430. while (size > 0) {
  431. ++index;
  432. if (buffer.size() - res < 3) {
  433. #if TLS_DEBUG
  434. dbgln("not enough data for certificate length");
  435. #endif
  436. return (i8)Error::NeedMoreData;
  437. }
  438. size_t certificate_size = buffer[res] * 0x10000 + buffer[res + 1] * 0x100 + buffer[res + 2];
  439. res += 3;
  440. if (buffer.size() - res < certificate_size) {
  441. #if TLS_DEBUG
  442. dbgln("not enough data for certificate body");
  443. #endif
  444. return (i8)Error::NeedMoreData;
  445. }
  446. auto res_cert = res;
  447. auto remaining = certificate_size;
  448. size_t certificates_in_chain = 0;
  449. do {
  450. if (remaining <= 3) {
  451. dbgln("Ran out of data");
  452. break;
  453. }
  454. ++certificates_in_chain;
  455. if (buffer.size() < (size_t)res_cert + 3) {
  456. dbgln("not enough data to read cert size ({} < {})", buffer.size(), res_cert + 3);
  457. break;
  458. }
  459. size_t certificate_size_specific = buffer[res_cert] * 0x10000 + buffer[res_cert + 1] * 0x100 + buffer[res_cert + 2];
  460. res_cert += 3;
  461. remaining -= 3;
  462. if (certificate_size_specific > remaining) {
  463. dbgln("invalid certificate size (expected {} but got {})", remaining, certificate_size_specific);
  464. break;
  465. }
  466. remaining -= certificate_size_specific;
  467. auto certificate = parse_asn1(buffer.slice(res_cert, certificate_size_specific), false);
  468. if (certificate.has_value()) {
  469. if (certificate.value().is_valid()) {
  470. m_context.certificates.append(certificate.value());
  471. valid_certificate = true;
  472. }
  473. }
  474. res_cert += certificate_size_specific;
  475. } while (remaining > 0);
  476. if (remaining) {
  477. dbgln("extraneous {} bytes left over after parsing certificates", remaining);
  478. }
  479. size -= certificate_size + 3;
  480. res += certificate_size;
  481. }
  482. if (!valid_certificate)
  483. return (i8)Error::UnsupportedCertificate;
  484. if ((size_t)res != buffer.size())
  485. dbgln("some data left unread: {} bytes out of {}", res, buffer.size());
  486. return res;
  487. }
  488. void TLSv12::consume(ReadonlyBytes record)
  489. {
  490. if (m_context.critical_error) {
  491. dbgln("There has been a critical error ({}), refusing to continue", (i8)m_context.critical_error);
  492. return;
  493. }
  494. if (record.size() == 0) {
  495. return;
  496. }
  497. dbgln_if(TLS_DEBUG, "Consuming {} bytes", record.size());
  498. m_context.message_buffer.append(record.data(), record.size());
  499. size_t index { 0 };
  500. size_t buffer_length = m_context.message_buffer.size();
  501. size_t size_offset { 3 }; // read the common record header
  502. size_t header_size { 5 };
  503. dbgln_if(TLS_DEBUG, "message buffer length {}", buffer_length);
  504. while (buffer_length >= 5) {
  505. auto length = AK::convert_between_host_and_network_endian(*(u16*)m_context.message_buffer.offset_pointer(index + size_offset)) + header_size;
  506. if (length > buffer_length) {
  507. dbgln_if(TLS_DEBUG, "Need more data: {} > {}", length, buffer_length);
  508. break;
  509. }
  510. auto consumed = handle_message(m_context.message_buffer.bytes().slice(index, length));
  511. if constexpr (TLS_DEBUG) {
  512. if (consumed > 0)
  513. dbgln("consumed {} bytes", consumed);
  514. else
  515. dbgln("error: {}", consumed);
  516. }
  517. if (consumed != (i8)Error::NeedMoreData) {
  518. if (consumed < 0) {
  519. dbgln("Consumed an error: {}", consumed);
  520. if (!m_context.critical_error)
  521. m_context.critical_error = (i8)consumed;
  522. m_context.error_code = (Error)consumed;
  523. break;
  524. }
  525. } else {
  526. continue;
  527. }
  528. index += length;
  529. buffer_length -= length;
  530. if (m_context.critical_error) {
  531. dbgln("Broken connection");
  532. m_context.error_code = Error::BrokenConnection;
  533. break;
  534. }
  535. }
  536. if (m_context.error_code != Error::NoError && m_context.error_code != Error::NeedMoreData) {
  537. dbgln("consume error: {}", (i8)m_context.error_code);
  538. m_context.message_buffer.clear();
  539. return;
  540. }
  541. if (index) {
  542. m_context.message_buffer = m_context.message_buffer.slice(index, m_context.message_buffer.size() - index);
  543. }
  544. }
  545. void TLSv12::ensure_hmac(size_t digest_size, bool local)
  546. {
  547. if (local && m_hmac_local)
  548. return;
  549. if (!local && m_hmac_remote)
  550. return;
  551. auto hash_kind = Crypto::Hash::HashKind::None;
  552. switch (digest_size) {
  553. case Crypto::Hash::SHA1::DigestSize:
  554. hash_kind = Crypto::Hash::HashKind::SHA1;
  555. break;
  556. case Crypto::Hash::SHA256::DigestSize:
  557. hash_kind = Crypto::Hash::HashKind::SHA256;
  558. break;
  559. case Crypto::Hash::SHA512::DigestSize:
  560. hash_kind = Crypto::Hash::HashKind::SHA512;
  561. break;
  562. default:
  563. dbgln("Failed to find a suitable hash for size {}", digest_size);
  564. break;
  565. }
  566. 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);
  567. if (local)
  568. m_hmac_local = move(hmac);
  569. else
  570. m_hmac_remote = move(hmac);
  571. }
  572. bool Certificate::is_valid() const
  573. {
  574. auto now = Core::DateTime::now();
  575. if (!not_before.is_empty()) {
  576. if (now.is_before(not_before)) {
  577. dbgln("certificate expired (not yet valid, signed for {})", not_before);
  578. return false;
  579. }
  580. }
  581. if (!not_after.is_empty()) {
  582. if (!now.is_before(not_after)) {
  583. dbgln("certificate expired (expiry date {})", not_after);
  584. return false;
  585. }
  586. }
  587. return true;
  588. }
  589. void TLSv12::try_disambiguate_error() const
  590. {
  591. dbgln("Possible failure cause(s): ");
  592. switch ((AlertDescription)m_context.critical_error) {
  593. case AlertDescription::HandshakeFailure:
  594. if (!m_context.cipher_spec_set) {
  595. dbgln("- No cipher suite in common with {}", m_context.extensions.SNI);
  596. } else {
  597. dbgln("- Unknown internal issue");
  598. }
  599. break;
  600. case AlertDescription::InsufficientSecurity:
  601. dbgln("- No cipher suite in common with {} (the server is oh so secure)", m_context.extensions.SNI);
  602. break;
  603. case AlertDescription::ProtocolVersion:
  604. dbgln("- The server refused to negotiate with TLS 1.2 :(");
  605. break;
  606. case AlertDescription::UnexpectedMessage:
  607. dbgln("- We sent an invalid message for the state we're in.");
  608. break;
  609. case AlertDescription::BadRecordMAC:
  610. dbgln("- Bad MAC record from our side.");
  611. dbgln("- Ciphertext wasn't an even multiple of the block length.");
  612. dbgln("- Bad block cipher padding.");
  613. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  614. break;
  615. case AlertDescription::RecordOverflow:
  616. dbgln("- Sent a ciphertext record which has a length bigger than 18432 bytes.");
  617. dbgln("- Sent record decrypted to a compressed record that has a length bigger than 18432 bytes.");
  618. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  619. break;
  620. case AlertDescription::DecompressionFailure:
  621. dbgln("- We sent invalid input for decompression (e.g. data that would expand to excessive length)");
  622. break;
  623. case AlertDescription::IllegalParameter:
  624. dbgln("- We sent a parameter in the handshake that is out of range or inconsistent with the other parameters.");
  625. break;
  626. case AlertDescription::DecodeError:
  627. dbgln("- The message we sent cannot be decoded because a field was out of range or the length was incorrect.");
  628. dbgln("- If both sides are compliant, the only cause is messages being corrupted in the network.");
  629. break;
  630. case AlertDescription::DecryptError:
  631. dbgln("- A handshake crypto operation failed. This includes signature verification and validating Finished.");
  632. break;
  633. case AlertDescription::AccessDenied:
  634. dbgln("- The certificate is valid, but once access control was applied, the sender decided to stop negotiation.");
  635. break;
  636. case AlertDescription::InternalError:
  637. dbgln("- No one knows, but it isn't a protocol failure.");
  638. break;
  639. case AlertDescription::DecryptionFailed:
  640. case AlertDescription::NoCertificate:
  641. case AlertDescription::ExportRestriction:
  642. dbgln("- No one knows, the server sent a non-compliant alert.");
  643. break;
  644. default:
  645. dbgln("- No one knows.");
  646. break;
  647. }
  648. }
  649. void TLSv12::set_root_certificates(Vector<Certificate> certificates)
  650. {
  651. if (!m_context.root_ceritificates.is_empty())
  652. dbgln("TLS warn: resetting root certificates!");
  653. for (auto& cert : certificates) {
  654. if (!cert.is_valid())
  655. dbgln("Certificate for {} by {} is invalid, things may or may not work!", cert.subject, cert.issuer_subject);
  656. // FIXME: Figure out what we should do when our root certs are invalid.
  657. }
  658. m_context.root_ceritificates = move(certificates);
  659. }
  660. bool Context::verify_chain() const
  661. {
  662. const Vector<Certificate>* local_chain = nullptr;
  663. if (is_server) {
  664. dbgln("Unsupported: Server mode");
  665. TODO();
  666. } else {
  667. local_chain = &certificates;
  668. }
  669. // FIXME: Actually verify the signature, instead of just checking the name.
  670. HashMap<String, String> chain;
  671. HashTable<String> roots;
  672. // First, walk the root certs.
  673. for (auto& cert : root_ceritificates) {
  674. roots.set(cert.subject);
  675. chain.set(cert.subject, cert.issuer_subject);
  676. }
  677. // Then, walk the local certs.
  678. for (auto& cert : *local_chain) {
  679. auto& issuer_unique_name = cert.issuer_unit.is_empty() ? cert.issuer_subject : cert.issuer_unit;
  680. chain.set(cert.subject, issuer_unique_name);
  681. }
  682. // Then verify the chain.
  683. for (auto& it : chain) {
  684. if (it.key == it.value) { // Allow self-signed certificates.
  685. if (!roots.contains(it.key))
  686. dbgln("Self-signed warning: Certificate for {} is self-signed", it.key);
  687. continue;
  688. }
  689. auto ref = chain.get(it.value);
  690. if (!ref.has_value()) {
  691. dbgln("Certificate for {} is not signed by anyone we trust ({})", it.key, it.value);
  692. return false;
  693. }
  694. if (ref.value() == it.key) // Allow (but warn about) mutually recursively signed cert A <-> B.
  695. dbgln("Co-dependency warning: Certificate for {} is issued by {}, which itself is issued by {}", ref.value(), it.key, ref.value());
  696. }
  697. return true;
  698. }
  699. static bool wildcard_matches(const StringView& host, const StringView& subject)
  700. {
  701. if (host.matches(subject))
  702. return true;
  703. if (subject.starts_with("*."))
  704. return wildcard_matches(host, subject.substring_view(2));
  705. return false;
  706. }
  707. Optional<size_t> TLSv12::verify_chain_and_get_matching_certificate(const StringView& host) const
  708. {
  709. if (m_context.certificates.is_empty() || !m_context.verify_chain())
  710. return {};
  711. if (host.is_empty())
  712. return 0;
  713. for (size_t i = 0; i < m_context.certificates.size(); ++i) {
  714. auto& cert = m_context.certificates[i];
  715. if (wildcard_matches(host, cert.subject))
  716. return i;
  717. for (auto& san : cert.SAN) {
  718. if (wildcard_matches(host, san))
  719. return i;
  720. }
  721. }
  722. return {};
  723. }
  724. TLSv12::TLSv12(Core::Object* parent, Version version)
  725. : Core::Socket(Core::Socket::Type::TCP, parent)
  726. {
  727. m_context.version = version;
  728. m_context.is_server = false;
  729. m_context.tls_buffer = ByteBuffer::create_uninitialized(0);
  730. #ifdef SOCK_NONBLOCK
  731. int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  732. #else
  733. int fd = socket(AF_INET, SOCK_STREAM, 0);
  734. int option = 1;
  735. ioctl(fd, FIONBIO, &option);
  736. #endif
  737. if (fd < 0) {
  738. set_error(errno);
  739. } else {
  740. set_fd(fd);
  741. set_mode(IODevice::ReadWrite);
  742. set_error(0);
  743. }
  744. }
  745. bool TLSv12::add_client_key(ReadonlyBytes certificate_pem_buffer, ReadonlyBytes rsa_key) // FIXME: This should not be bound to RSA
  746. {
  747. if (certificate_pem_buffer.is_empty() || rsa_key.is_empty()) {
  748. return true;
  749. }
  750. auto decoded_certificate = Crypto::decode_pem(certificate_pem_buffer);
  751. if (decoded_certificate.is_empty()) {
  752. dbgln("Certificate not PEM");
  753. return false;
  754. }
  755. auto maybe_certificate = parse_asn1(decoded_certificate);
  756. if (!maybe_certificate.has_value()) {
  757. dbgln("Invalid certificate");
  758. return false;
  759. }
  760. Crypto::PK::RSA rsa(rsa_key);
  761. auto certificate = maybe_certificate.value();
  762. certificate.private_key = rsa.private_key();
  763. return add_client_key(certificate);
  764. }
  765. AK::Singleton<DefaultRootCACertificates> DefaultRootCACertificates::s_the;
  766. DefaultRootCACertificates::DefaultRootCACertificates()
  767. {
  768. // FIXME: This might not be the best format, find a better way to represent CA certificates.
  769. auto config = Core::ConfigFile::get_for_system("ca_certs");
  770. for (auto& entity : config->groups()) {
  771. Certificate cert;
  772. cert.subject = entity;
  773. cert.issuer_subject = config->read_entry(entity, "issuer_subject", entity);
  774. cert.country = config->read_entry(entity, "country");
  775. m_ca_certificates.append(move(cert));
  776. }
  777. }
  778. }