MSEHandshake.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. const unsigned char VC[] = {0, 0, 0, 0, 0, 0, 0, 0};
  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 = make_unique<unsigned char[]>(KEY_LENGTH + MAX_PAD_LENGTH);
  115. dh_->getPublicKey(buf.get(), KEY_LENGTH);
  116. size_t padLength =
  117. SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH + 1);
  118. dh_->generateNonce(buf.get() + KEY_LENGTH, padLength);
  119. socketBuffer_.pushBytes(buf.release(), KEY_LENGTH + padLength);
  120. }
  121. void MSEHandshake::read()
  122. {
  123. if (rbufLength_ >= MAX_BUFFER_LENGTH) {
  124. assert(!wantRead_);
  125. return;
  126. }
  127. size_t len = MAX_BUFFER_LENGTH - rbufLength_;
  128. socket_->readData(rbuf_ + rbufLength_, len);
  129. if (len == 0 && !socket_->wantRead() && !socket_->wantWrite()) {
  130. // TODO Should we set graceful in peer?
  131. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  132. }
  133. rbufLength_ += len;
  134. wantRead_ = false;
  135. }
  136. bool MSEHandshake::send()
  137. {
  138. socketBuffer_.send();
  139. return socketBuffer_.sendBufferIsEmpty();
  140. }
  141. void MSEHandshake::shiftBuffer(size_t offset)
  142. {
  143. assert(rbufLength_ >= offset);
  144. memmove(rbuf_, rbuf_ + offset, rbufLength_ - offset);
  145. rbufLength_ -= offset;
  146. }
  147. bool MSEHandshake::receivePublicKey()
  148. {
  149. if (rbufLength_ < KEY_LENGTH) {
  150. wantRead_ = true;
  151. return false;
  152. }
  153. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - public key received.", cuid_));
  154. // TODO handle exception. in catch, resbufLength = 0;
  155. dh_->computeSecret(secret_, sizeof(secret_), rbuf_, KEY_LENGTH);
  156. // shift buffer
  157. shiftBuffer(KEY_LENGTH);
  158. return true;
  159. }
  160. void MSEHandshake::initCipher(const unsigned char* infoHash)
  161. {
  162. memcpy(infoHash_, infoHash, INFO_HASH_LENGTH);
  163. // Initialize cipher
  164. unsigned char s[4 + KEY_LENGTH + INFO_HASH_LENGTH];
  165. memcpy(s, initiator_ ? "keyA" : "keyB", 4);
  166. memcpy(s + 4, secret_, KEY_LENGTH);
  167. memcpy(s + 4 + KEY_LENGTH, infoHash, INFO_HASH_LENGTH);
  168. unsigned char localCipherKey[20];
  169. sha1_->reset();
  170. message_digest::digest(localCipherKey, sizeof(localCipherKey), sha1_.get(), s,
  171. sizeof(s));
  172. encryptor_ = make_unique<ARC4Encryptor>();
  173. encryptor_->init(localCipherKey, sizeof(localCipherKey));
  174. unsigned char peerCipherKey[20];
  175. memcpy(s, initiator_ ? "keyB" : "keyA", 4);
  176. sha1_->reset();
  177. message_digest::digest(peerCipherKey, sizeof(peerCipherKey), sha1_.get(), s,
  178. sizeof(s));
  179. decryptor_ = make_unique<ARC4Encryptor>();
  180. decryptor_->init(peerCipherKey, sizeof(peerCipherKey));
  181. // discard first 1024 bytes ARC4 output.
  182. std::array<unsigned char, 1_k> garbage;
  183. encryptor_->encrypt(garbage.size(), garbage.data(), garbage.data());
  184. decryptor_->encrypt(garbage.size(), garbage.data(), garbage.data());
  185. if (initiator_) {
  186. ARC4Encryptor enc;
  187. enc.init(peerCipherKey, sizeof(peerCipherKey));
  188. // discard first 1024 bytes ARC4 output.
  189. enc.encrypt(garbage.size(), garbage.data(), garbage.data());
  190. enc.encrypt(VC_LENGTH, initiatorVCMarker_, VC);
  191. }
  192. }
  193. // Given data is pushed to socketBuffer_ and data will be deleted by
  194. // socketBuffer_.
  195. void MSEHandshake::encryptAndSendData(unsigned char* data, size_t length)
  196. {
  197. encryptor_->encrypt(length, data, data);
  198. socketBuffer_.pushBytes(data, length);
  199. }
  200. void MSEHandshake::createReq1Hash(unsigned char* md) const
  201. {
  202. unsigned char buffer[100];
  203. memcpy(buffer, "req1", 4);
  204. memcpy(buffer + 4, secret_, KEY_LENGTH);
  205. sha1_->reset();
  206. message_digest::digest(md, 20, sha1_.get(), buffer, 4 + KEY_LENGTH);
  207. }
  208. void MSEHandshake::createReq23Hash(unsigned char* md,
  209. const unsigned char* infoHash) const
  210. {
  211. unsigned char x[24];
  212. memcpy(x, "req2", 4);
  213. memcpy(x + 4, infoHash, INFO_HASH_LENGTH);
  214. unsigned char xh[20];
  215. sha1_->reset();
  216. message_digest::digest(xh, sizeof(xh), sha1_.get(), x, sizeof(x));
  217. unsigned char y[4 + 96];
  218. memcpy(y, "req3", 4);
  219. memcpy(y + 4, secret_, KEY_LENGTH);
  220. unsigned char yh[20];
  221. sha1_->reset();
  222. message_digest::digest(yh, sizeof(yh), sha1_.get(), y, sizeof(y));
  223. for (size_t i = 0; i < 20; ++i) {
  224. md[i] = xh[i] ^ yh[i];
  225. }
  226. }
  227. uint16_t MSEHandshake::decodeLength16(const unsigned char* buffer)
  228. {
  229. uint16_t be;
  230. decryptor_->encrypt(sizeof(be), reinterpret_cast<unsigned char*>(&be),
  231. buffer);
  232. return ntohs(be);
  233. }
  234. void MSEHandshake::sendInitiatorStep2()
  235. {
  236. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Sending negotiation step2.", cuid_));
  237. // Assuming no exception
  238. auto md = make_unique<unsigned char[]>((size_t)20);
  239. createReq1Hash(md.get());
  240. socketBuffer_.pushBytes(md.release(), 20);
  241. // Assuming no exception
  242. md = make_unique<unsigned char[]>((size_t)20);
  243. createReq23Hash(md.get(), infoHash_);
  244. socketBuffer_.pushBytes(md.release(), 20);
  245. // buffer is filled in this order:
  246. // VC(VC_LENGTH bytes),
  247. // crypto_provide(CRYPTO_BITFIELD_LENGTH bytes),
  248. // len(padC)(2 bytes),
  249. // padC(len(padC) bytes <= MAX_PAD_LENGTH),
  250. // len(IA)(2 bytes)
  251. auto buffer = make_unique<unsigned char[]>(
  252. 40 + VC_LENGTH + CRYPTO_BITFIELD_LENGTH + 2 + MAX_PAD_LENGTH + 2);
  253. unsigned char* ptr = buffer.get();
  254. // VC
  255. memcpy(ptr, VC, sizeof(VC));
  256. ptr += sizeof(VC);
  257. // crypto_provide
  258. memset(ptr, 0, CRYPTO_BITFIELD_LENGTH);
  259. if (!option_->getAsBool(PREF_BT_FORCE_ENCRYPTION) &&
  260. option_->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  261. ptr[3] = CRYPTO_PLAIN_TEXT;
  262. }
  263. ptr[3] |= CRYPTO_ARC4;
  264. ptr += CRYPTO_BITFIELD_LENGTH;
  265. // len(padC)
  266. uint16_t padCLength =
  267. SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH + 1);
  268. {
  269. uint16_t padCLengthBE = htons(padCLength);
  270. memcpy(ptr, &padCLengthBE, sizeof(padCLengthBE));
  271. }
  272. ptr += 2;
  273. // padC
  274. memset(ptr, 0, padCLength);
  275. ptr += padCLength;
  276. // len(IA)
  277. // currently, IA is zero-length.
  278. uint16_t iaLength = 0;
  279. {
  280. uint16_t iaLengthBE = htons(iaLength);
  281. memcpy(ptr, &iaLengthBE, sizeof(iaLengthBE));
  282. }
  283. ptr += 2;
  284. size_t buflen = ptr - buffer.get();
  285. encryptAndSendData(buffer.release(), buflen);
  286. }
  287. // This function reads exactly until the end of VC marker is reached.
  288. bool MSEHandshake::findInitiatorVCMarker()
  289. {
  290. // 616 is synchronization point of initiator
  291. // find vc
  292. unsigned char* ptr =
  293. std::search(&rbuf_[0], &rbuf_[rbufLength_], &initiatorVCMarker_[0],
  294. &initiatorVCMarker_[VC_LENGTH]);
  295. if (ptr == &rbuf_[rbufLength_]) {
  296. if (616 - KEY_LENGTH <= rbufLength_) {
  297. throw DL_ABORT_EX("Failed to find VC marker.");
  298. }
  299. else {
  300. wantRead_ = true;
  301. return false;
  302. }
  303. }
  304. markerIndex_ = ptr - rbuf_;
  305. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - VC marker found at %lu", cuid_,
  306. static_cast<unsigned long>(markerIndex_)));
  307. verifyVC(rbuf_ + markerIndex_);
  308. // shift rbuf
  309. shiftBuffer(markerIndex_ + VC_LENGTH);
  310. return true;
  311. }
  312. bool MSEHandshake::receiveInitiatorCryptoSelectAndPadDLength()
  313. {
  314. if (CRYPTO_BITFIELD_LENGTH + 2 /* PadD length*/ > rbufLength_) {
  315. wantRead_ = true;
  316. return false;
  317. }
  318. // verifyCryptoSelect
  319. unsigned char* rbufptr = rbuf_;
  320. decryptor_->encrypt(CRYPTO_BITFIELD_LENGTH, rbufptr, rbufptr);
  321. if ((rbufptr[3] & CRYPTO_PLAIN_TEXT) &&
  322. !option_->getAsBool(PREF_BT_FORCE_ENCRYPTION) &&
  323. option_->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  324. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - peer prefers plaintext.", cuid_));
  325. negotiatedCryptoType_ = CRYPTO_PLAIN_TEXT;
  326. }
  327. if (rbufptr[3] & CRYPTO_ARC4) {
  328. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - peer prefers ARC4", cuid_));
  329. negotiatedCryptoType_ = CRYPTO_ARC4;
  330. }
  331. if (negotiatedCryptoType_ == CRYPTO_NONE) {
  332. throw DL_ABORT_EX(
  333. fmt("CUID#%" PRId64 " - No supported crypto type selected.", cuid_));
  334. }
  335. // padD length
  336. rbufptr += CRYPTO_BITFIELD_LENGTH;
  337. padLength_ = verifyPadLength(rbufptr, "PadD");
  338. // shift rbuf
  339. shiftBuffer(CRYPTO_BITFIELD_LENGTH + 2 /* PadD length*/);
  340. return true;
  341. }
  342. bool MSEHandshake::receivePad()
  343. {
  344. if (padLength_ > rbufLength_) {
  345. wantRead_ = true;
  346. return false;
  347. }
  348. if (padLength_ == 0) {
  349. return true;
  350. }
  351. decryptor_->encrypt(padLength_, rbuf_, rbuf_);
  352. // shift rbuf_
  353. shiftBuffer(padLength_);
  354. return true;
  355. }
  356. bool MSEHandshake::findReceiverHashMarker()
  357. {
  358. // 628 is synchronization limit of receiver.
  359. // find hash('req1', S), S is secret_.
  360. unsigned char md[20];
  361. createReq1Hash(md);
  362. unsigned char* ptr =
  363. std::search(&rbuf_[0], &rbuf_[rbufLength_], &md[0], &md[sizeof(md)]);
  364. if (ptr == &rbuf_[rbufLength_]) {
  365. if (628 - KEY_LENGTH <= rbufLength_) {
  366. throw DL_ABORT_EX("Failed to find hash marker.");
  367. }
  368. else {
  369. wantRead_ = true;
  370. return false;
  371. }
  372. }
  373. markerIndex_ = ptr - rbuf_;
  374. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Hash marker found at %lu.", cuid_,
  375. static_cast<unsigned long>(markerIndex_)));
  376. verifyReq1Hash(rbuf_ + markerIndex_);
  377. // shift rbuf_
  378. shiftBuffer(markerIndex_ + 20);
  379. return true;
  380. }
  381. bool MSEHandshake::receiveReceiverHashAndPadCLength(
  382. const std::vector<std::shared_ptr<DownloadContext>>& downloadContexts)
  383. {
  384. if (20 + VC_LENGTH + CRYPTO_BITFIELD_LENGTH + 2 /*PadC length*/ >
  385. rbufLength_) {
  386. wantRead_ = true;
  387. return false;
  388. }
  389. // resolve info hash
  390. // pointing to the position of HASH('req2', SKEY) xor HASH('req3', S)
  391. unsigned char* rbufptr = rbuf_;
  392. std::shared_ptr<DownloadContext> downloadContext;
  393. for (auto& ctx : downloadContexts) {
  394. unsigned char md[20];
  395. const auto infohash = bittorrent::getInfoHash(ctx);
  396. createReq23Hash(md, infohash);
  397. if (memcmp(md, rbufptr, sizeof(md)) == 0) {
  398. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - info hash found: %s", cuid_,
  399. util::toHex(infohash, INFO_HASH_LENGTH).c_str()));
  400. downloadContext = ctx;
  401. break;
  402. }
  403. }
  404. if (!downloadContext) {
  405. throw DL_ABORT_EX("Unknown info hash.");
  406. }
  407. initCipher(bittorrent::getInfoHash(downloadContext));
  408. // decrypt VC
  409. rbufptr += 20;
  410. verifyVC(rbufptr);
  411. // decrypt crypto_provide
  412. rbufptr += VC_LENGTH;
  413. decryptor_->encrypt(CRYPTO_BITFIELD_LENGTH, rbufptr, rbufptr);
  414. // TODO choose the crypto type based on the preference.
  415. // For now, choose ARC4.
  416. if ((rbufptr[3] & CRYPTO_PLAIN_TEXT) &&
  417. !option_->getAsBool(PREF_BT_FORCE_ENCRYPTION) &&
  418. option_->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  419. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - peer provides plaintext.", cuid_));
  420. negotiatedCryptoType_ = CRYPTO_PLAIN_TEXT;
  421. }
  422. else if (rbufptr[3] & CRYPTO_ARC4) {
  423. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - peer provides ARC4.", cuid_));
  424. negotiatedCryptoType_ = CRYPTO_ARC4;
  425. }
  426. if (negotiatedCryptoType_ == CRYPTO_NONE) {
  427. throw DL_ABORT_EX(
  428. fmt("CUID#%" PRId64 " - No supported crypto type provided.", cuid_));
  429. }
  430. // decrypt PadC length
  431. rbufptr += CRYPTO_BITFIELD_LENGTH;
  432. padLength_ = verifyPadLength(rbufptr, "PadC");
  433. // shift rbuf_
  434. shiftBuffer(20 + VC_LENGTH + CRYPTO_BITFIELD_LENGTH + 2 /*PadC length*/);
  435. return true;
  436. }
  437. bool MSEHandshake::receiveReceiverIALength()
  438. {
  439. if (2 > rbufLength_) {
  440. wantRead_ = true;
  441. return false;
  442. }
  443. iaLength_ = decodeLength16(rbuf_);
  444. if (iaLength_ > BtHandshakeMessage::MESSAGE_LENGTH) {
  445. throw DL_ABORT_EX(fmt("Too large IA length length: %u", iaLength_));
  446. }
  447. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - len(IA)=%u.", cuid_, iaLength_));
  448. // shift rbuf_
  449. shiftBuffer(2);
  450. return true;
  451. }
  452. bool MSEHandshake::receiveReceiverIA()
  453. {
  454. if (iaLength_ == 0) {
  455. return true;
  456. }
  457. if (iaLength_ > rbufLength_) {
  458. wantRead_ = true;
  459. return false;
  460. }
  461. ia_ = make_unique<unsigned char[]>(iaLength_);
  462. decryptor_->encrypt(iaLength_, ia_.get(), rbuf_);
  463. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - IA received.", cuid_));
  464. // shift rbuf_
  465. shiftBuffer(iaLength_);
  466. return true;
  467. }
  468. void MSEHandshake::sendReceiverStep2()
  469. {
  470. // buffer is filled in this order:
  471. // VC(VC_LENGTH bytes),
  472. // cryptoSelect(CRYPTO_BITFIELD_LENGTH bytes),
  473. // len(padD)(2bytes),
  474. // padD(len(padD)bytes <= MAX_PAD_LENGTH)
  475. auto buffer = make_unique<unsigned char[]>(
  476. VC_LENGTH + CRYPTO_BITFIELD_LENGTH + 2 + MAX_PAD_LENGTH);
  477. unsigned char* ptr = buffer.get();
  478. // VC
  479. memcpy(ptr, VC, sizeof(VC));
  480. ptr += sizeof(VC);
  481. // crypto_select
  482. memset(ptr, 0, CRYPTO_BITFIELD_LENGTH);
  483. ptr[3] = negotiatedCryptoType_;
  484. ptr += CRYPTO_BITFIELD_LENGTH;
  485. // len(padD)
  486. uint16_t padDLength =
  487. SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH + 1);
  488. uint16_t padDLengthBE = htons(padDLength);
  489. memcpy(ptr, &padDLengthBE, sizeof(padDLengthBE));
  490. ptr += sizeof(padDLengthBE);
  491. // padD, all zeroed
  492. memset(ptr, 0, padDLength);
  493. ptr += padDLength;
  494. size_t buflen = ptr - buffer.get();
  495. encryptAndSendData(buffer.release(), buflen);
  496. }
  497. uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf,
  498. const char* padName)
  499. {
  500. A2_LOG_DEBUG(
  501. fmt("CUID#%" PRId64 " - Verifying Pad length for %s", cuid_, padName));
  502. uint16_t padLength = decodeLength16(padlenbuf);
  503. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - len(%s)=%u", cuid_, padName, padLength));
  504. if (padLength > 512) {
  505. throw DL_ABORT_EX(fmt("Too large %s length: %u", padName, padLength));
  506. }
  507. return padLength;
  508. }
  509. void MSEHandshake::verifyVC(unsigned char* vcbuf)
  510. {
  511. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Verifying VC.", cuid_));
  512. decryptor_->encrypt(VC_LENGTH, vcbuf, vcbuf);
  513. if (memcmp(VC, vcbuf, VC_LENGTH) != 0) {
  514. throw DL_ABORT_EX(
  515. fmt("Invalid VC: %s", util::toHex(vcbuf, VC_LENGTH).c_str()));
  516. }
  517. }
  518. void MSEHandshake::verifyReq1Hash(const unsigned char* req1buf)
  519. {
  520. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Verifying req hash.", cuid_));
  521. unsigned char md[20];
  522. createReq1Hash(md);
  523. if (memcmp(md, req1buf, sizeof(md)) != 0) {
  524. throw DL_ABORT_EX("Invalid req1 hash found.");
  525. }
  526. }
  527. bool MSEHandshake::getWantWrite() const
  528. {
  529. return !socketBuffer_.sendBufferIsEmpty();
  530. }
  531. std::unique_ptr<ARC4Encryptor> MSEHandshake::popEncryptor()
  532. {
  533. return std::move(encryptor_);
  534. }
  535. std::unique_ptr<ARC4Encryptor> MSEHandshake::popDecryptor()
  536. {
  537. return std::move(decryptor_);
  538. }
  539. } // namespace aria2