TLSv12.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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/Endian.h>
  27. #include <LibCore/DateTime.h>
  28. #include <LibCore/Timer.h>
  29. #include <LibCrypto/ASN1/DER.h>
  30. #include <LibCrypto/ASN1/PEM.h>
  31. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  32. #include <LibTLS/TLSv12.h>
  33. #ifndef SOCK_NONBLOCK
  34. # include <sys/ioctl.h>
  35. #endif
  36. //#define TLS_DEBUG
  37. namespace {
  38. struct OIDChain {
  39. void* root { nullptr };
  40. u8* oid { nullptr };
  41. };
  42. }
  43. namespace TLS {
  44. // "for now" q&d implementation of ASN1
  45. namespace {
  46. static bool _asn1_is_field_present(const u32* fields, const u32* prefix)
  47. {
  48. size_t i = 0;
  49. while (prefix[i]) {
  50. if (fields[i] != prefix[i])
  51. return false;
  52. ++i;
  53. }
  54. return true;
  55. }
  56. static bool _asn1_is_oid(const u8* oid, const u8* compare, size_t length = 3)
  57. {
  58. size_t i = 0;
  59. while (oid[i] && i < length) {
  60. if (oid[i] != compare[i])
  61. return false;
  62. ++i;
  63. }
  64. return true;
  65. }
  66. static bool _set_algorithm(CertificateKeyAlgorithm& algorithm, const u8* value, size_t length)
  67. {
  68. if (length == 7) {
  69. // Elliptic Curve pubkey
  70. dbg() << "Cert.algorithm: EC, unsupported";
  71. return false;
  72. }
  73. if (length == 8) {
  74. // named EC key
  75. dbg() << "Cert.algorithm: Named EC (" << *value << "), unsupported";
  76. return false;
  77. }
  78. if (length == 5) {
  79. // named EC SECP key
  80. dbg() << "Cert.algorithm: Named EC secp (" << *value << "), unsupported";
  81. return false;
  82. }
  83. if (length != 9) {
  84. dbg() << "Invalid certificate algorithm";
  85. return false;
  86. }
  87. if (_asn1_is_oid(value, Constants::RSA_SIGN_RSA_OID, 9)) {
  88. algorithm = CertificateKeyAlgorithm::RSA_RSA;
  89. return true;
  90. }
  91. if (_asn1_is_oid(value, Constants::RSA_SIGN_SHA256_OID, 9)) {
  92. algorithm = CertificateKeyAlgorithm::RSA_SHA256;
  93. return true;
  94. }
  95. if (_asn1_is_oid(value, Constants::RSA_SIGN_SHA512_OID, 9)) {
  96. algorithm = CertificateKeyAlgorithm::RSA_SHA512;
  97. return true;
  98. }
  99. if (_asn1_is_oid(value, Constants::RSA_SIGN_SHA1_OID, 9)) {
  100. algorithm = CertificateKeyAlgorithm::RSA_SHA1;
  101. return true;
  102. }
  103. if (_asn1_is_oid(value, Constants::RSA_SIGN_MD5_OID, 9)) {
  104. algorithm = CertificateKeyAlgorithm::RSA_MD5;
  105. return true;
  106. }
  107. dbg() << "Unsupported RSA Signature mode " << value[8];
  108. return false;
  109. }
  110. static size_t _get_asn1_length(const u8* buffer, size_t length, size_t& octets)
  111. {
  112. octets = 0;
  113. if (length < 1)
  114. return 0;
  115. u8 size = buffer[0];
  116. if (size & 0x80) {
  117. octets = size & 0x7f;
  118. if (octets > length - 1) {
  119. return 0;
  120. }
  121. auto reference_octets = octets;
  122. if (octets > 4)
  123. reference_octets = 4;
  124. size_t long_size = 0, coeff = 1;
  125. for (auto i = reference_octets; i > 0; --i) {
  126. long_size += buffer[i] * coeff;
  127. coeff *= 0x100;
  128. }
  129. ++octets;
  130. return long_size;
  131. }
  132. ++octets;
  133. return size;
  134. }
  135. 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)
  136. {
  137. OIDChain local_chain;
  138. local_chain.root = chain;
  139. size_t position = 0;
  140. // parse DER...again
  141. size_t index = 0;
  142. u8 oid[16] { 0 };
  143. local_chain.oid = oid;
  144. if (has_key)
  145. *has_key = 0;
  146. u8 local_has_key = 0;
  147. const u8* cert_data = nullptr;
  148. size_t cert_length = 0;
  149. while (position < size) {
  150. size_t start_position = position;
  151. if (size - position < 2) {
  152. dbg() << "not enough data for certificate size";
  153. return (i8)Error::NeedMoreData;
  154. }
  155. u8 first = buffer[position++];
  156. u8 type = first & 0x1f;
  157. u8 constructed = first & 0x20;
  158. size_t octets = 0;
  159. u32 temp;
  160. index++;
  161. if (level <= 0xff)
  162. fields[level - 1] = index;
  163. size_t length = _get_asn1_length((const u8*)&buffer[position], size - position, octets);
  164. if (octets > 4 || octets > size - position) {
  165. #ifdef TLS_DEBUG
  166. dbg() << "could not read the certificate";
  167. #endif
  168. return position;
  169. }
  170. position += octets;
  171. if (size - position < length) {
  172. #ifdef TLS_DEBUG
  173. dbg() << "not enough data for sequence";
  174. #endif
  175. return (i8)Error::NeedMoreData;
  176. }
  177. if (length && constructed) {
  178. switch (type) {
  179. case 0x03:
  180. break;
  181. case 0x10:
  182. if (level == 2 && index == 1) {
  183. cert_length = length + position - start_position;
  184. cert_data = buffer + start_position;
  185. }
  186. // public key data
  187. if (!cert.version && _asn1_is_field_present(fields, Constants::priv_der_id)) {
  188. temp = length + position - start_position;
  189. if (cert.der.size() < temp) {
  190. cert.der.grow(temp);
  191. } else {
  192. cert.der.trim(temp);
  193. }
  194. cert.der.overwrite(0, buffer + start_position, temp);
  195. }
  196. break;
  197. default:
  198. break;
  199. }
  200. local_has_key = false;
  201. _parse_asn1(context, cert, buffer + position, length, level + 1, fields, &local_has_key, client_cert, root_oid, &local_chain);
  202. if ((local_has_key && (!context.is_server || client_cert)) || (client_cert || _asn1_is_field_present(fields, Constants::pk_id))) {
  203. temp = length + position - start_position;
  204. if (cert.der.size() < temp) {
  205. cert.der.grow(temp);
  206. } else {
  207. cert.der.trim(temp);
  208. }
  209. cert.der.overwrite(0, buffer + start_position, temp);
  210. }
  211. } else {
  212. switch (type) {
  213. case 0x00:
  214. return position;
  215. break;
  216. case 0x01:
  217. temp = buffer[position];
  218. break;
  219. case 0x02:
  220. if (_asn1_is_field_present(fields, Constants::pk_id)) {
  221. if (has_key)
  222. *has_key = true;
  223. if (index == 1)
  224. cert.public_key.set(
  225. Crypto::UnsignedBigInteger::import_data(buffer + position, length),
  226. cert.public_key.public_exponent());
  227. else if (index == 2)
  228. cert.public_key.set(
  229. cert.public_key.modulus(),
  230. Crypto::UnsignedBigInteger::import_data(buffer + position, length));
  231. } else if (_asn1_is_field_present(fields, Constants::serial_id)) {
  232. cert.serial_number = Crypto::UnsignedBigInteger::import_data(buffer + position, length);
  233. }
  234. if (_asn1_is_field_present(fields, Constants::version_id)) {
  235. if (length == 1)
  236. cert.version = buffer[position];
  237. }
  238. // print_buffer(ByteBuffer::wrap(const_cast<u8*>(buffer) + position, length));
  239. break;
  240. case 0x03:
  241. if (_asn1_is_field_present(fields, Constants::pk_id)) {
  242. if (has_key)
  243. *has_key = true;
  244. }
  245. if (_asn1_is_field_present(fields, Constants::sign_id)) {
  246. auto* value = buffer + position;
  247. auto len = length;
  248. if (!value[0] && len % 2) {
  249. ++value;
  250. --len;
  251. }
  252. cert.sign_key = ByteBuffer::copy(value, len);
  253. } else {
  254. if (buffer[position] == 0 && length > 256) {
  255. _parse_asn1(context, cert, buffer + position + 1, length - 1, level + 1, fields, &local_has_key, client_cert, root_oid, &local_chain);
  256. } else {
  257. _parse_asn1(context, cert, buffer + position, length, level + 1, fields, &local_has_key, client_cert, root_oid, &local_chain);
  258. }
  259. }
  260. break;
  261. case 0x04:
  262. _parse_asn1(context, cert, buffer + position, length, level + 1, fields, &local_has_key, client_cert, root_oid, &local_chain);
  263. break;
  264. case 0x05:
  265. break;
  266. case 0x06:
  267. if (_asn1_is_field_present(fields, Constants::pk_id)) {
  268. _set_algorithm(cert.key_algorithm, buffer + position, length);
  269. }
  270. if (_asn1_is_field_present(fields, Constants::algorithm_id)) {
  271. _set_algorithm(cert.algorithm, buffer + position, length);
  272. }
  273. if (length < 16)
  274. memcpy(oid, buffer + position, length);
  275. else
  276. memcpy(oid, buffer + position, 16);
  277. if (root_oid)
  278. memcpy(root_oid, oid, 16);
  279. break;
  280. case 0x09:
  281. break;
  282. case 0x17:
  283. case 0x018:
  284. // time
  285. // ignore
  286. break;
  287. case 0x013:
  288. case 0x0c:
  289. case 0x14:
  290. case 0x15:
  291. case 0x16:
  292. case 0x19:
  293. case 0x1a:
  294. case 0x1b:
  295. case 0x1c:
  296. case 0x1d:
  297. case 0x1e:
  298. // printable string and such
  299. if (_asn1_is_field_present(fields, Constants::issurer_id)) {
  300. if (_asn1_is_oid(oid, Constants::country_oid)) {
  301. cert.issuer_country = String { (const char*)buffer + position, length };
  302. } else if (_asn1_is_oid(oid, Constants::state_oid)) {
  303. cert.issuer_state = String { (const char*)buffer + position, length };
  304. } else if (_asn1_is_oid(oid, Constants::location_oid)) {
  305. cert.issuer_location = String { (const char*)buffer + position, length };
  306. } else if (_asn1_is_oid(oid, Constants::entity_oid)) {
  307. cert.issuer_entity = String { (const char*)buffer + position, length };
  308. } else if (_asn1_is_oid(oid, Constants::subject_oid)) {
  309. cert.issuer_subject = String { (const char*)buffer + position, length };
  310. }
  311. } else if (_asn1_is_field_present(fields, Constants::owner_id)) {
  312. if (_asn1_is_oid(oid, Constants::country_oid)) {
  313. cert.country = String { (const char*)buffer + position, length };
  314. } else if (_asn1_is_oid(oid, Constants::state_oid)) {
  315. cert.state = String { (const char*)buffer + position, length };
  316. } else if (_asn1_is_oid(oid, Constants::location_oid)) {
  317. cert.location = String { (const char*)buffer + position, length };
  318. } else if (_asn1_is_oid(oid, Constants::entity_oid)) {
  319. cert.entity = String { (const char*)buffer + position, length };
  320. } else if (_asn1_is_oid(oid, Constants::subject_oid)) {
  321. cert.subject = String { (const char*)buffer + position, length };
  322. }
  323. }
  324. break;
  325. default:
  326. // dbg() << "unused field " << type;
  327. break;
  328. }
  329. }
  330. position += length;
  331. }
  332. if (level == 2 && cert.sign_key.size() && cert_length && cert_data) {
  333. cert.fingerprint.clear();
  334. Crypto::Hash::Manager hash;
  335. switch (cert.key_algorithm) {
  336. case CertificateKeyAlgorithm::RSA_MD5:
  337. hash.initialize(Crypto::Hash::HashKind::MD5);
  338. break;
  339. case CertificateKeyAlgorithm::RSA_SHA1:
  340. hash.initialize(Crypto::Hash::HashKind::SHA1);
  341. break;
  342. case CertificateKeyAlgorithm::RSA_SHA256:
  343. hash.initialize(Crypto::Hash::HashKind::SHA256);
  344. break;
  345. case CertificateKeyAlgorithm::RSA_SHA512:
  346. hash.initialize(Crypto::Hash::HashKind::SHA512);
  347. break;
  348. default:
  349. #ifdef TLS_DEBUG
  350. dbg() << "Unsupported hash mode " << (u32)cert.key_algorithm;
  351. #endif
  352. // fallback to md5, it will fail later
  353. hash.initialize(Crypto::Hash::HashKind::MD5);
  354. break;
  355. }
  356. hash.update(cert_data, cert_length);
  357. auto fingerprint = hash.digest();
  358. cert.fingerprint.grow(fingerprint.data_length());
  359. cert.fingerprint.overwrite(0, fingerprint.immutable_data(), fingerprint.data_length());
  360. #ifdef TLS_DEBUG
  361. dbg() << "Certificate fingerprint:";
  362. print_buffer(cert.fingerprint);
  363. #endif
  364. }
  365. return position;
  366. }
  367. }
  368. Optional<Certificate> TLSv12::parse_asn1(const ByteBuffer& buffer, bool) const
  369. {
  370. // FIXME: Our ASN.1 parser is not quite up to the task of
  371. // parsing this X.509 certificate, so for the
  372. // time being, we will "parse" the certificate
  373. // manually right here.
  374. Certificate cert;
  375. u32 fields[0xff];
  376. _parse_asn1(m_context, cert, buffer.data(), buffer.size(), 1, fields, nullptr, 0, nullptr, nullptr);
  377. #ifdef TLS_DEBUG
  378. dbg() << "Certificate issued for " << cert.subject << " by " << cert.issuer_subject;
  379. #endif
  380. return cert;
  381. }
  382. ssize_t TLSv12::handle_certificate(const ByteBuffer& buffer)
  383. {
  384. ssize_t res = 0;
  385. if (buffer.size() < 3) {
  386. #ifdef TLS_DEBUG
  387. dbg() << "not enough certificate header data";
  388. #endif
  389. return (i8)Error::NeedMoreData;
  390. }
  391. u32 certificate_total_length = buffer[0] * 0x10000 + buffer[1] * 0x100 + buffer[2];
  392. #ifdef TLS_DEBUG
  393. dbg() << "total length: " << certificate_total_length;
  394. #endif
  395. if (certificate_total_length <= 4)
  396. return 3 * certificate_total_length;
  397. res += 3;
  398. if (certificate_total_length > buffer.size() - res) {
  399. #ifdef TLS_DEBUG
  400. dbg() << "not enough data for claimed total cert length";
  401. #endif
  402. return (i8)Error::NeedMoreData;
  403. }
  404. size_t size = certificate_total_length;
  405. size_t index = 0;
  406. bool valid_certificate = false;
  407. while (size > 0) {
  408. ++index;
  409. if (buffer.size() - res < 3) {
  410. #ifdef TLS_DEBUG
  411. dbg() << "not enough data for certificate length";
  412. #endif
  413. return (i8)Error::NeedMoreData;
  414. }
  415. size_t certificate_size = buffer[res] * 0x10000 + buffer[res + 1] * 0x100 + buffer[res + 2];
  416. res += 3;
  417. if (buffer.size() - res < certificate_size) {
  418. #ifdef TLS_DEBUG
  419. dbg() << "not enough data for certificate body";
  420. #endif
  421. return (i8)Error::NeedMoreData;
  422. }
  423. auto res_cert = res;
  424. auto remaining = certificate_size;
  425. size_t certificates_in_chain = 0;
  426. do {
  427. if (remaining <= 3) {
  428. dbg() << "Ran out of data";
  429. break;
  430. }
  431. ++certificates_in_chain;
  432. if (buffer.size() < (size_t)res_cert + 3) {
  433. dbg() << "not enough data to read cert size (" << buffer.size() << " < " << res_cert + 3 << ")";
  434. break;
  435. }
  436. size_t certificate_size_specific = buffer[res_cert] * 0x10000 + buffer[res_cert + 1] * 0x100 + buffer[res_cert + 2];
  437. res_cert += 3;
  438. remaining -= 3;
  439. if (certificate_size_specific > remaining) {
  440. dbg() << "invalid certificate size (expected " << remaining << " but got " << certificate_size_specific << ")";
  441. break;
  442. }
  443. remaining -= certificate_size_specific;
  444. auto certificate = parse_asn1(buffer.slice_view(res_cert, certificate_size_specific), false);
  445. if (certificate.has_value()) {
  446. m_context.certificates.append(certificate.value());
  447. valid_certificate = true;
  448. }
  449. res_cert += certificate_size_specific;
  450. } while (remaining > 0);
  451. if (remaining) {
  452. dbg() << "extraneous " << remaining << " bytes left over after parsing certificates";
  453. }
  454. size -= certificate_size + 3;
  455. res += certificate_size;
  456. }
  457. if (!valid_certificate)
  458. return (i8)Error::UnsupportedCertificate;
  459. if ((size_t)res != buffer.size())
  460. dbg() << "some data left unread: " << (size_t)res << " bytes out of " << buffer.size();
  461. return res;
  462. }
  463. void TLSv12::consume(const ByteBuffer& record)
  464. {
  465. if (m_context.critical_error) {
  466. dbg() << "There has been a critical error (" << (i8)m_context.critical_error << "), refusing to continue";
  467. return;
  468. }
  469. if (record.size() == 0) {
  470. return;
  471. }
  472. #ifdef TLS_DEBUG
  473. dbg() << "Consuming " << record.size() << " bytes";
  474. #endif
  475. m_context.message_buffer.append(record.data(), record.size());
  476. size_t index { 0 };
  477. size_t buffer_length = m_context.message_buffer.size();
  478. size_t size_offset { 3 }; // read the common record header
  479. size_t header_size { 5 };
  480. #ifdef TLS_DEBUG
  481. dbg() << "message buffer length " << buffer_length;
  482. #endif
  483. while (buffer_length >= 5) {
  484. auto length = AK::convert_between_host_and_network_endian(*(u16*)m_context.message_buffer.offset_pointer(index + size_offset)) + header_size;
  485. if (length > buffer_length) {
  486. #ifdef TLS_DEBUG
  487. dbg() << "Need more data: " << length << " | " << buffer_length;
  488. #endif
  489. break;
  490. }
  491. auto consumed = handle_message(m_context.message_buffer.slice_view(index, length));
  492. #ifdef TLS_DEBUG
  493. if (consumed > 0)
  494. dbg() << "consumed " << (size_t)consumed << " bytes";
  495. else
  496. dbg() << "error: " << (int)consumed;
  497. #endif
  498. if (consumed != (i8)Error::NeedMoreData) {
  499. if (consumed < 0) {
  500. dbg() << "Consumed an error: " << (int)consumed;
  501. if (!m_context.critical_error)
  502. m_context.critical_error = (i8)consumed;
  503. m_context.error_code = (Error)consumed;
  504. break;
  505. }
  506. } else {
  507. continue;
  508. }
  509. index += length;
  510. buffer_length -= length;
  511. if (m_context.critical_error) {
  512. dbg() << "Broken connection";
  513. m_context.error_code = Error::BrokenConnection;
  514. break;
  515. }
  516. }
  517. if (m_context.error_code != Error::NoError && m_context.error_code != Error::NeedMoreData) {
  518. dbg() << "consume error: " << (i8)m_context.error_code;
  519. m_context.message_buffer.clear();
  520. return;
  521. }
  522. if (index) {
  523. m_context.message_buffer = m_context.message_buffer.slice(index, m_context.message_buffer.size() - index);
  524. }
  525. }
  526. void TLSv12::ensure_hmac(size_t digest_size, bool local)
  527. {
  528. if (local && m_hmac_local)
  529. return;
  530. if (!local && m_hmac_remote)
  531. return;
  532. auto hash_kind = Crypto::Hash::HashKind::None;
  533. switch (digest_size) {
  534. case Crypto::Hash::SHA1::DigestSize:
  535. hash_kind = Crypto::Hash::HashKind::SHA1;
  536. break;
  537. case Crypto::Hash::SHA256::DigestSize:
  538. hash_kind = Crypto::Hash::HashKind::SHA256;
  539. break;
  540. case Crypto::Hash::SHA512::DigestSize:
  541. hash_kind = Crypto::Hash::HashKind::SHA512;
  542. break;
  543. default:
  544. dbg() << "Failed to find a suitable hash for size " << digest_size;
  545. break;
  546. }
  547. auto hmac = make<Crypto::Authentication::HMAC<Crypto::Hash::Manager>>(ByteBuffer::wrap(local ? m_context.crypto.local_mac : m_context.crypto.remote_mac, digest_size), hash_kind);
  548. if (local)
  549. m_hmac_local = move(hmac);
  550. else
  551. m_hmac_remote = move(hmac);
  552. }
  553. bool Certificate::is_valid() const
  554. {
  555. auto now = Core::DateTime::now();
  556. if (!not_before.is_empty()) {
  557. if (now.is_before(not_before)) {
  558. dbg() << "certificate expired (not yet valid, signed for " << not_before << ")";
  559. return false;
  560. }
  561. }
  562. if (!not_after.is_empty()) {
  563. if (!now.is_before(not_after)) {
  564. dbg() << "certificate expired (expiry date " << not_after << ")";
  565. return false;
  566. }
  567. }
  568. return true;
  569. }
  570. void TLSv12::try_disambiguate_error() const
  571. {
  572. dbg() << "Possible failure cause(s): ";
  573. switch ((AlertDescription)m_context.critical_error) {
  574. case AlertDescription::HandshakeFailure:
  575. if (!m_context.cipher_spec_set) {
  576. dbg() << "- No cipher suite in common with " << m_context.SNI;
  577. } else {
  578. dbg() << "- Unknown internal issue";
  579. }
  580. break;
  581. case AlertDescription::InsufficientSecurity:
  582. dbg() << "- No cipher suite in common with " << m_context.SNI << " (the server is oh so secure)";
  583. break;
  584. case AlertDescription::ProtocolVersion:
  585. dbg() << "- The server refused to negotiate with TLS 1.2 :(";
  586. break;
  587. case AlertDescription::UnexpectedMessage:
  588. dbg() << "- We sent an invalid message for the state we're in.";
  589. break;
  590. case AlertDescription::BadRecordMAC:
  591. dbg() << "- Bad MAC record from our side.";
  592. dbg() << "- Ciphertext wasn't an even multiple of the block length.";
  593. dbg() << "- Bad block cipher padding.";
  594. dbg() << "- If both sides are compliant, the only cause is messages being corrupted in the network.";
  595. break;
  596. case AlertDescription::RecordOverflow:
  597. dbg() << "- Sent a ciphertext record which has a length bigger than 18432 bytes.";
  598. dbg() << "- Sent record decrypted to a compressed record that has a length bigger than 18432 bytes.";
  599. dbg() << "- If both sides are compliant, the only cause is messages being corrupted in the network.";
  600. break;
  601. case AlertDescription::DecompressionFailure:
  602. dbg() << "- We sent invalid input for decompression (e.g. data that would expand to excessive length)";
  603. break;
  604. case AlertDescription::IllegalParameter:
  605. dbg() << "- We sent a parameter in the handshake that is out of range or inconsistent with the other parameters.";
  606. break;
  607. case AlertDescription::DecodeError:
  608. dbg() << "- The message we sent cannot be decoded because a field was out of range or the length was incorrect.";
  609. dbg() << "- If both sides are compliant, the only cause is messages being corrupted in the network.";
  610. break;
  611. case AlertDescription::DecryptError:
  612. dbg() << "- A handshake crypto operation failed. This includes signature verification and validating Finished.";
  613. break;
  614. case AlertDescription::AccessDenied:
  615. dbg() << "- The certificate is valid, but once access control was applied, the sender decided to stop negotiation.";
  616. break;
  617. case AlertDescription::InternalError:
  618. dbg() << "- No one knows, but it isn't a protocol failure.";
  619. break;
  620. case AlertDescription::DecryptionFailed:
  621. case AlertDescription::NoCertificate:
  622. case AlertDescription::ExportRestriction:
  623. dbg() << "- No one knows, the server sent a non-compliant alert.";
  624. break;
  625. default:
  626. dbg() << "- No one knows.";
  627. break;
  628. }
  629. }
  630. TLSv12::TLSv12(Core::Object* parent, Version version)
  631. : Core::Socket(Core::Socket::Type::TCP, parent)
  632. {
  633. m_context.version = version;
  634. m_context.is_server = false;
  635. m_context.tls_buffer = ByteBuffer::create_uninitialized(0);
  636. #ifdef SOCK_NONBLOCK
  637. int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  638. #else
  639. int fd = socket(AF_INET, SOCK_STREAM, 0);
  640. int option = 1;
  641. ioctl(fd, FIONBIO, &option);
  642. #endif
  643. if (fd < 0) {
  644. set_error(errno);
  645. } else {
  646. set_fd(fd);
  647. set_mode(IODevice::ReadWrite);
  648. set_error(0);
  649. }
  650. }
  651. bool TLSv12::add_client_key(const ByteBuffer& certificate_pem_buffer, const ByteBuffer& rsa_key) // FIXME: This should not be bound to RSA
  652. {
  653. if (certificate_pem_buffer.is_empty() || rsa_key.is_empty()) {
  654. return true;
  655. }
  656. auto decoded_certificate = Crypto::decode_pem(certificate_pem_buffer, 0);
  657. if (decoded_certificate.is_empty()) {
  658. dbg() << "Certificate not PEM";
  659. return false;
  660. }
  661. auto maybe_certificate = parse_asn1(decoded_certificate);
  662. if (!maybe_certificate.has_value()) {
  663. dbg() << "Invalid certificate";
  664. return false;
  665. }
  666. Crypto::PK::RSA rsa(rsa_key);
  667. auto certificate = maybe_certificate.value();
  668. certificate.private_key = rsa.private_key();
  669. return add_client_key(certificate);
  670. }
  671. }