MSEHandshake.cc 18 KB

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