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