MSEHandshake.cc 18 KB

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