MSEHandshake.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "MSEHandshake.h"
  36. #include <array>
  37. #include <cstring>
  38. #include <cassert>
  39. #include "message.h"
  40. #include "DlAbortEx.h"
  41. #include "LogFactory.h"
  42. #include "Logger.h"
  43. #include "BtHandshakeMessage.h"
  44. #include "SocketCore.h"
  45. #include "a2netcompat.h"
  46. #include "DHKeyExchange.h"
  47. #include "ARC4Encryptor.h"
  48. #include "MessageDigest.h"
  49. #include "message_digest_helper.h"
  50. #include "SimpleRandomizer.h"
  51. #include "util.h"
  52. #include "DownloadContext.h"
  53. #include "prefs.h"
  54. #include "Option.h"
  55. #include "fmt.h"
  56. #include "bittorrent_helper.h"
  57. #include "array_fun.h"
  58. namespace aria2 {
  59. namespace {
  60. const size_t MAX_PAD_LENGTH = 512;
  61. const size_t CRYPTO_BITFIELD_LENGTH = 4;
  62. constexpr auto VC = std::array<unsigned char, MSEHandshake::VC_LENGTH>{};
  63. const unsigned char* PRIME = reinterpret_cast<const unsigned char*>(
  64. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B"
  65. "139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485"
  66. "B576625E7EC6F44C42E9A63A36210000000000090563");
  67. const unsigned char* GENERATOR = reinterpret_cast<const unsigned char*>("2");
  68. } // namespace
  69. MSEHandshake::MSEHandshake(cuid_t cuid,
  70. const std::shared_ptr<SocketCore>& socket,
  71. const Option* op)
  72. : cuid_(cuid),
  73. socket_(socket),
  74. wantRead_(false),
  75. option_(op),
  76. rbufLength_(0),
  77. socketBuffer_(socket),
  78. negotiatedCryptoType_(CRYPTO_NONE),
  79. initiator_(true),
  80. markerIndex_(0),
  81. padLength_(0),
  82. iaLength_(0),
  83. sha1_(MessageDigest::sha1())
  84. {
  85. }
  86. MSEHandshake::~MSEHandshake() {}
  87. MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType()
  88. {
  89. if (rbufLength_ < 20) {
  90. wantRead_ = true;
  91. return HANDSHAKE_NOT_YET;
  92. }
  93. if (rbuf_[0] == BtHandshakeMessage::PSTR_LENGTH &&
  94. memcmp(BtHandshakeMessage::BT_PSTR, rbuf_ + 1, 19) == 0) {
  95. A2_LOG_DEBUG(
  96. fmt("CUID#%" PRId64 " - This is legacy BitTorrent handshake.", cuid_));
  97. return HANDSHAKE_LEGACY;
  98. }
  99. A2_LOG_DEBUG(fmt(
  100. "CUID#%" PRId64 " - This may be encrypted BitTorrent handshake.", cuid_));
  101. return HANDSHAKE_ENCRYPTED;
  102. }
  103. void MSEHandshake::initEncryptionFacility(bool initiator)
  104. {
  105. dh_ = make_unique<DHKeyExchange>();
  106. dh_->init(PRIME, PRIME_BITS, GENERATOR, 160);
  107. dh_->generatePublicKey();
  108. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - DH initialized.", cuid_));
  109. initiator_ = initiator;
  110. }
  111. void MSEHandshake::sendPublicKey()
  112. {
  113. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Sending public key.", cuid_));
  114. auto buf = std::vector<unsigned char>(KEY_LENGTH + MAX_PAD_LENGTH);
  115. dh_->getPublicKey(buf.data(), KEY_LENGTH);
  116. size_t padLength =
  117. SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH + 1);
  118. dh_->generateNonce(buf.data() + KEY_LENGTH, padLength);
  119. buf.resize(KEY_LENGTH + padLength);
  120. socketBuffer_.pushBytes(std::move(buf));
  121. }
  122. void MSEHandshake::read()
  123. {
  124. if (rbufLength_ >= MAX_BUFFER_LENGTH) {
  125. assert(!wantRead_);
  126. return;
  127. }
  128. size_t len = MAX_BUFFER_LENGTH - rbufLength_;
  129. socket_->readData(rbuf_ + rbufLength_, len);
  130. if (len == 0 && !socket_->wantRead() && !socket_->wantWrite()) {
  131. // TODO Should we set graceful in peer?
  132. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  133. }
  134. rbufLength_ += len;
  135. wantRead_ = false;
  136. }
  137. bool MSEHandshake::send()
  138. {
  139. socketBuffer_.send();
  140. return socketBuffer_.sendBufferIsEmpty();
  141. }
  142. void MSEHandshake::shiftBuffer(size_t offset)
  143. {
  144. assert(rbufLength_ >= offset);
  145. memmove(rbuf_, rbuf_ + offset, rbufLength_ - offset);
  146. rbufLength_ -= offset;
  147. }
  148. bool MSEHandshake::receivePublicKey()
  149. {
  150. if (rbufLength_ < KEY_LENGTH) {
  151. wantRead_ = true;
  152. return false;
  153. }
  154. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - public key received.", cuid_));
  155. // TODO handle exception. in catch, resbufLength = 0;
  156. dh_->computeSecret(secret_, sizeof(secret_), rbuf_, KEY_LENGTH);
  157. // shift buffer
  158. shiftBuffer(KEY_LENGTH);
  159. return true;
  160. }
  161. void MSEHandshake::initCipher(const unsigned char* infoHash)
  162. {
  163. memcpy(infoHash_, infoHash, INFO_HASH_LENGTH);
  164. // Initialize cipher
  165. unsigned char s[4 + KEY_LENGTH + INFO_HASH_LENGTH];
  166. memcpy(s, initiator_ ? "keyA" : "keyB", 4);
  167. memcpy(s + 4, secret_, KEY_LENGTH);
  168. memcpy(s + 4 + KEY_LENGTH, infoHash, INFO_HASH_LENGTH);
  169. unsigned char localCipherKey[20];
  170. sha1_->reset();
  171. message_digest::digest(localCipherKey, sizeof(localCipherKey), sha1_.get(), s,
  172. sizeof(s));
  173. encryptor_ = make_unique<ARC4Encryptor>();
  174. encryptor_->init(localCipherKey, sizeof(localCipherKey));
  175. unsigned char peerCipherKey[20];
  176. memcpy(s, initiator_ ? "keyB" : "keyA", 4);
  177. sha1_->reset();
  178. message_digest::digest(peerCipherKey, sizeof(peerCipherKey), sha1_.get(), s,
  179. sizeof(s));
  180. decryptor_ = make_unique<ARC4Encryptor>();
  181. decryptor_->init(peerCipherKey, sizeof(peerCipherKey));
  182. // discard first 1024 bytes ARC4 output.
  183. std::array<unsigned char, 1_k> garbage;
  184. encryptor_->encrypt(garbage.size(), garbage.data(), garbage.data());
  185. decryptor_->encrypt(garbage.size(), garbage.data(), garbage.data());
  186. if (initiator_) {
  187. ARC4Encryptor enc;
  188. enc.init(peerCipherKey, sizeof(peerCipherKey));
  189. // discard first 1024 bytes ARC4 output.
  190. enc.encrypt(garbage.size(), garbage.data(), garbage.data());
  191. enc.encrypt(VC_LENGTH, initiatorVCMarker_, VC.data());
  192. }
  193. }
  194. // Given data is pushed to socketBuffer_ and data will be deleted by
  195. // socketBuffer_.
  196. void MSEHandshake::encryptAndSendData(std::vector<unsigned char> data)
  197. {
  198. encryptor_->encrypt(data.size(), data.data(), data.data());
  199. socketBuffer_.pushBytes(std::move(data));
  200. }
  201. void MSEHandshake::createReq1Hash(unsigned char* md) const
  202. {
  203. unsigned char buffer[100];
  204. memcpy(buffer, "req1", 4);
  205. memcpy(buffer + 4, secret_, KEY_LENGTH);
  206. sha1_->reset();
  207. message_digest::digest(md, 20, sha1_.get(), buffer, 4 + KEY_LENGTH);
  208. }
  209. void MSEHandshake::createReq23Hash(unsigned char* md,
  210. const unsigned char* infoHash) const
  211. {
  212. unsigned char x[24];
  213. memcpy(x, "req2", 4);
  214. memcpy(x + 4, infoHash, INFO_HASH_LENGTH);
  215. unsigned char xh[20];
  216. sha1_->reset();
  217. message_digest::digest(xh, sizeof(xh), sha1_.get(), x, sizeof(x));
  218. unsigned char y[4 + 96];
  219. memcpy(y, "req3", 4);
  220. memcpy(y + 4, secret_, KEY_LENGTH);
  221. unsigned char yh[20];
  222. sha1_->reset();
  223. message_digest::digest(yh, sizeof(yh), sha1_.get(), y, sizeof(y));
  224. for (size_t i = 0; i < 20; ++i) {
  225. md[i] = xh[i] ^ yh[i];
  226. }
  227. }
  228. uint16_t MSEHandshake::decodeLength16(const unsigned char* buffer)
  229. {
  230. uint16_t be;
  231. decryptor_->encrypt(sizeof(be), reinterpret_cast<unsigned char*>(&be),
  232. buffer);
  233. return ntohs(be);
  234. }
  235. void MSEHandshake::sendInitiatorStep2()
  236. {
  237. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Sending negotiation step2.", cuid_));
  238. // Assuming no exception
  239. auto md = std::vector<unsigned char>(20);
  240. createReq1Hash(md.data());
  241. socketBuffer_.pushBytes(std::move(md));
  242. // Assuming no exception
  243. md = std::vector<unsigned char>(20);
  244. createReq23Hash(md.data(), infoHash_);
  245. socketBuffer_.pushBytes(std::move(md));
  246. // buffer is filled in this order:
  247. // VC(VC_LENGTH bytes),
  248. // crypto_provide(CRYPTO_BITFIELD_LENGTH bytes),
  249. // len(padC)(2 bytes),
  250. // padC(len(padC) bytes <= MAX_PAD_LENGTH),
  251. // len(IA)(2 bytes)
  252. auto buffer = std::vector<unsigned char>(VC_LENGTH + CRYPTO_BITFIELD_LENGTH +
  253. 2 + MAX_PAD_LENGTH + 2);
  254. auto ptr = std::begin(buffer);
  255. // VC
  256. ptr += VC_LENGTH;
  257. // crypto_provide
  258. if (!option_->getAsBool(PREF_BT_FORCE_ENCRYPTION) &&
  259. option_->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  260. ptr[3] = CRYPTO_PLAIN_TEXT;
  261. }
  262. ptr[3] |= CRYPTO_ARC4;
  263. ptr += CRYPTO_BITFIELD_LENGTH;
  264. // len(padC)
  265. uint16_t padCLength =
  266. SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH + 1);
  267. uint16_t padCLengthBE = htons(padCLength);
  268. ptr = std::copy_n(reinterpret_cast<unsigned char*>(&padCLengthBE),
  269. sizeof(padCLengthBE), ptr);
  270. // padC
  271. ptr += padCLength;
  272. // len(IA)
  273. // currently, IA is zero-length.
  274. uint16_t iaLength = 0;
  275. {
  276. uint16_t iaLengthBE = htons(iaLength);
  277. ptr = std::copy_n(reinterpret_cast<unsigned char*>(&iaLengthBE),
  278. sizeof(iaLengthBE), ptr);
  279. }
  280. buffer.erase(ptr, std::end(buffer));
  281. encryptAndSendData(std::move(buffer));
  282. }
  283. // This function reads exactly until the end of VC marker is reached.
  284. bool MSEHandshake::findInitiatorVCMarker()
  285. {
  286. // 616 is synchronization point of initiator
  287. // find vc
  288. unsigned char* ptr =
  289. std::search(&rbuf_[0], &rbuf_[rbufLength_], &initiatorVCMarker_[0],
  290. &initiatorVCMarker_[VC_LENGTH]);
  291. if (ptr == &rbuf_[rbufLength_]) {
  292. if (616 - KEY_LENGTH <= rbufLength_) {
  293. throw DL_ABORT_EX("Failed to find VC marker.");
  294. }
  295. else {
  296. wantRead_ = true;
  297. return false;
  298. }
  299. }
  300. markerIndex_ = ptr - rbuf_;
  301. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - VC marker found at %lu", cuid_,
  302. static_cast<unsigned long>(markerIndex_)));
  303. verifyVC(rbuf_ + markerIndex_);
  304. // shift rbuf
  305. shiftBuffer(markerIndex_ + VC_LENGTH);
  306. return true;
  307. }
  308. bool MSEHandshake::receiveInitiatorCryptoSelectAndPadDLength()
  309. {
  310. if (CRYPTO_BITFIELD_LENGTH + 2 /* PadD length*/ > rbufLength_) {
  311. wantRead_ = true;
  312. return false;
  313. }
  314. // verifyCryptoSelect
  315. unsigned char* rbufptr = rbuf_;
  316. decryptor_->encrypt(CRYPTO_BITFIELD_LENGTH, rbufptr, rbufptr);
  317. if ((rbufptr[3] & CRYPTO_PLAIN_TEXT) &&
  318. !option_->getAsBool(PREF_BT_FORCE_ENCRYPTION) &&
  319. option_->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  320. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - peer prefers plaintext.", cuid_));
  321. negotiatedCryptoType_ = CRYPTO_PLAIN_TEXT;
  322. }
  323. if (rbufptr[3] & CRYPTO_ARC4) {
  324. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - peer prefers ARC4", cuid_));
  325. negotiatedCryptoType_ = CRYPTO_ARC4;
  326. }
  327. if (negotiatedCryptoType_ == CRYPTO_NONE) {
  328. throw DL_ABORT_EX(
  329. fmt("CUID#%" PRId64 " - No supported crypto type selected.", cuid_));
  330. }
  331. // padD length
  332. rbufptr += CRYPTO_BITFIELD_LENGTH;
  333. padLength_ = verifyPadLength(rbufptr, "PadD");
  334. // shift rbuf
  335. shiftBuffer(CRYPTO_BITFIELD_LENGTH + 2 /* PadD length*/);
  336. return true;
  337. }
  338. bool MSEHandshake::receivePad()
  339. {
  340. if (padLength_ > rbufLength_) {
  341. wantRead_ = true;
  342. return false;
  343. }
  344. if (padLength_ == 0) {
  345. return true;
  346. }
  347. decryptor_->encrypt(padLength_, rbuf_, rbuf_);
  348. // shift rbuf_
  349. shiftBuffer(padLength_);
  350. return true;
  351. }
  352. bool MSEHandshake::findReceiverHashMarker()
  353. {
  354. // 628 is synchronization limit of receiver.
  355. // find hash('req1', S), S is secret_.
  356. unsigned char md[20];
  357. createReq1Hash(md);
  358. unsigned char* ptr =
  359. std::search(&rbuf_[0], &rbuf_[rbufLength_], &md[0], &md[sizeof(md)]);
  360. if (ptr == &rbuf_[rbufLength_]) {
  361. if (628 - KEY_LENGTH <= rbufLength_) {
  362. throw DL_ABORT_EX("Failed to find hash marker.");
  363. }
  364. else {
  365. wantRead_ = true;
  366. return false;
  367. }
  368. }
  369. markerIndex_ = ptr - rbuf_;
  370. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Hash marker found at %lu.", cuid_,
  371. static_cast<unsigned long>(markerIndex_)));
  372. verifyReq1Hash(rbuf_ + markerIndex_);
  373. // shift rbuf_
  374. shiftBuffer(markerIndex_ + 20);
  375. return true;
  376. }
  377. bool MSEHandshake::receiveReceiverHashAndPadCLength(
  378. const std::vector<std::shared_ptr<DownloadContext>>& downloadContexts)
  379. {
  380. if (20 + VC_LENGTH + CRYPTO_BITFIELD_LENGTH + 2 /*PadC length*/ >
  381. rbufLength_) {
  382. wantRead_ = true;
  383. return false;
  384. }
  385. // resolve info hash
  386. // pointing to the position of HASH('req2', SKEY) xor HASH('req3', S)
  387. unsigned char* rbufptr = rbuf_;
  388. std::shared_ptr<DownloadContext> downloadContext;
  389. for (auto& ctx : downloadContexts) {
  390. unsigned char md[20];
  391. const auto infohash = bittorrent::getInfoHash(ctx);
  392. createReq23Hash(md, infohash);
  393. if (memcmp(md, rbufptr, sizeof(md)) == 0) {
  394. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - info hash found: %s", cuid_,
  395. util::toHex(infohash, INFO_HASH_LENGTH).c_str()));
  396. downloadContext = ctx;
  397. break;
  398. }
  399. }
  400. if (!downloadContext) {
  401. throw DL_ABORT_EX("Unknown info hash.");
  402. }
  403. initCipher(bittorrent::getInfoHash(downloadContext));
  404. // decrypt VC
  405. rbufptr += 20;
  406. verifyVC(rbufptr);
  407. // decrypt crypto_provide
  408. rbufptr += VC_LENGTH;
  409. decryptor_->encrypt(CRYPTO_BITFIELD_LENGTH, rbufptr, rbufptr);
  410. // TODO choose the crypto type based on the preference.
  411. // For now, choose ARC4.
  412. if ((rbufptr[3] & CRYPTO_PLAIN_TEXT) &&
  413. !option_->getAsBool(PREF_BT_FORCE_ENCRYPTION) &&
  414. option_->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  415. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - peer provides plaintext.", cuid_));
  416. negotiatedCryptoType_ = CRYPTO_PLAIN_TEXT;
  417. }
  418. else if (rbufptr[3] & CRYPTO_ARC4) {
  419. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - peer provides ARC4.", cuid_));
  420. negotiatedCryptoType_ = CRYPTO_ARC4;
  421. }
  422. if (negotiatedCryptoType_ == CRYPTO_NONE) {
  423. throw DL_ABORT_EX(
  424. fmt("CUID#%" PRId64 " - No supported crypto type provided.", cuid_));
  425. }
  426. // decrypt PadC length
  427. rbufptr += CRYPTO_BITFIELD_LENGTH;
  428. padLength_ = verifyPadLength(rbufptr, "PadC");
  429. // shift rbuf_
  430. shiftBuffer(20 + VC_LENGTH + CRYPTO_BITFIELD_LENGTH + 2 /*PadC length*/);
  431. return true;
  432. }
  433. bool MSEHandshake::receiveReceiverIALength()
  434. {
  435. if (2 > rbufLength_) {
  436. wantRead_ = true;
  437. return false;
  438. }
  439. iaLength_ = decodeLength16(rbuf_);
  440. if (iaLength_ > BtHandshakeMessage::MESSAGE_LENGTH) {
  441. throw DL_ABORT_EX(fmt("Too large IA length length: %u", iaLength_));
  442. }
  443. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - len(IA)=%u.", cuid_, iaLength_));
  444. // shift rbuf_
  445. shiftBuffer(2);
  446. return true;
  447. }
  448. bool MSEHandshake::receiveReceiverIA()
  449. {
  450. if (iaLength_ == 0) {
  451. return true;
  452. }
  453. if (iaLength_ > rbufLength_) {
  454. wantRead_ = true;
  455. return false;
  456. }
  457. ia_ = std::vector<unsigned char>(iaLength_);
  458. decryptor_->encrypt(iaLength_, ia_.data(), rbuf_);
  459. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - IA received.", cuid_));
  460. // shift rbuf_
  461. shiftBuffer(iaLength_);
  462. return true;
  463. }
  464. void MSEHandshake::sendReceiverStep2()
  465. {
  466. // buffer is filled in this order:
  467. // VC(VC_LENGTH bytes),
  468. // cryptoSelect(CRYPTO_BITFIELD_LENGTH bytes),
  469. // len(padD)(2bytes),
  470. // padD(len(padD)bytes <= MAX_PAD_LENGTH)
  471. auto buffer = std::vector<unsigned char>(VC_LENGTH + CRYPTO_BITFIELD_LENGTH +
  472. 2 + MAX_PAD_LENGTH);
  473. auto ptr = std::begin(buffer);
  474. // VC
  475. ptr += VC_LENGTH;
  476. // crypto_select
  477. ptr[3] = negotiatedCryptoType_;
  478. ptr += CRYPTO_BITFIELD_LENGTH;
  479. // len(padD)
  480. uint16_t padDLength =
  481. SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH + 1);
  482. uint16_t padDLengthBE = htons(padDLength);
  483. ptr = std::copy_n(reinterpret_cast<unsigned char*>(&padDLengthBE),
  484. sizeof(padDLengthBE), ptr);
  485. // padD, all zeroed
  486. ptr += padDLength;
  487. buffer.erase(ptr, std::end(buffer));
  488. encryptAndSendData(std::move(buffer));
  489. }
  490. uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf,
  491. const char* padName)
  492. {
  493. A2_LOG_DEBUG(
  494. fmt("CUID#%" PRId64 " - Verifying Pad length for %s", cuid_, padName));
  495. uint16_t padLength = decodeLength16(padlenbuf);
  496. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - len(%s)=%u", cuid_, padName, padLength));
  497. if (padLength > 512) {
  498. throw DL_ABORT_EX(fmt("Too large %s length: %u", padName, padLength));
  499. }
  500. return padLength;
  501. }
  502. void MSEHandshake::verifyVC(unsigned char* vcbuf)
  503. {
  504. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Verifying VC.", cuid_));
  505. decryptor_->encrypt(VC_LENGTH, vcbuf, vcbuf);
  506. if (!std::equal(std::begin(VC), std::end(VC), vcbuf)) {
  507. throw DL_ABORT_EX(
  508. fmt("Invalid VC: %s", util::toHex(vcbuf, VC_LENGTH).c_str()));
  509. }
  510. }
  511. void MSEHandshake::verifyReq1Hash(const unsigned char* req1buf)
  512. {
  513. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Verifying req hash.", cuid_));
  514. unsigned char md[20];
  515. createReq1Hash(md);
  516. if (memcmp(md, req1buf, sizeof(md)) != 0) {
  517. throw DL_ABORT_EX("Invalid req1 hash found.");
  518. }
  519. }
  520. bool MSEHandshake::getWantWrite() const
  521. {
  522. return !socketBuffer_.sendBufferIsEmpty();
  523. }
  524. std::unique_ptr<ARC4Encryptor> MSEHandshake::popEncryptor()
  525. {
  526. return std::move(encryptor_);
  527. }
  528. std::unique_ptr<ARC4Encryptor> MSEHandshake::popDecryptor()
  529. {
  530. return std::move(decryptor_);
  531. }
  532. } // namespace aria2