MSEHandshake.cc 18 KB

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