TLSv12.cpp 26 KB

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