MSEHandshake.cc 18 KB

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