MSEHandshake.cc 17 KB

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