MSEHandshake.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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 "MessageDigestHelper.h"
  49. #include "SimpleRandomizer.h"
  50. #include "util.h"
  51. #include "DownloadContext.h"
  52. #include "prefs.h"
  53. #include "Option.h"
  54. #include "StringFormat.h"
  55. #include "bittorrent_helper.h"
  56. namespace aria2 {
  57. const unsigned char* MSEHandshake::PRIME = reinterpret_cast<const unsigned char*>("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563");
  58. const unsigned char* MSEHandshake::GENERATOR = reinterpret_cast<const unsigned char*>("2");
  59. const unsigned char MSEHandshake::VC[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
  60. MSEHandshake::MSEHandshake(int32_t cuid,
  61. const SocketHandle& socket,
  62. const Option* op):
  63. _cuid(cuid),
  64. _socket(socket),
  65. _option(op),
  66. _logger(LogFactory::getInstance()),
  67. _rbufLength(0),
  68. _socketBuffer(socket),
  69. _negotiatedCryptoType(CRYPTO_NONE),
  70. _dh(0),
  71. _initiator(true),
  72. _markerIndex(0),
  73. _padLength(0),
  74. _iaLength(0),
  75. _ia(0)
  76. {}
  77. MSEHandshake::~MSEHandshake()
  78. {
  79. delete _dh;
  80. delete [] _ia;
  81. }
  82. MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType()
  83. {
  84. if(!_socket->isReadable(0)) {
  85. return HANDSHAKE_NOT_YET;
  86. }
  87. size_t r = 20-_rbufLength;
  88. _socket->readData(_rbuf+_rbufLength, r);
  89. if(r == 0 && !_socket->wantRead() && !_socket->wantWrite()) {
  90. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  91. }
  92. _rbufLength += r;
  93. if(_rbufLength < 20) {
  94. return HANDSHAKE_NOT_YET;
  95. }
  96. if(_rbuf[0] == BtHandshakeMessage::PSTR_LENGTH &&
  97. memcmp(BtHandshakeMessage::BT_PSTR, _rbuf+1, 19) == 0) {
  98. if(_logger->debug()) {
  99. _logger->debug("CUID#%d - This is legacy BitTorrent handshake.", _cuid);
  100. }
  101. return HANDSHAKE_LEGACY;
  102. } else {
  103. if(_logger->debug()) {
  104. _logger->debug("CUID#%d - This may be encrypted BitTorrent handshake.",
  105. _cuid);
  106. }
  107. return HANDSHAKE_ENCRYPTED;
  108. }
  109. }
  110. void MSEHandshake::initEncryptionFacility(bool initiator)
  111. {
  112. delete _dh;
  113. _dh = new DHKeyExchange();
  114. _dh->init(PRIME, PRIME_BITS, GENERATOR, 160);
  115. _dh->generatePublicKey();
  116. if(_logger->debug()) {
  117. _logger->debug("CUID#%d - DH initialized.", _cuid);
  118. }
  119. _initiator = initiator;
  120. }
  121. bool MSEHandshake::sendPublicKey()
  122. {
  123. if(_socketBuffer.sendBufferIsEmpty()) {
  124. if(_logger->debug()) {
  125. _logger->debug("CUID#%d - Sending public key.", _cuid);
  126. }
  127. unsigned char buffer[KEY_LENGTH+MAX_PAD_LENGTH];
  128. _dh->getPublicKey(buffer, KEY_LENGTH);
  129. size_t padLength = SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH+1);
  130. _dh->generateNonce(buffer+KEY_LENGTH, padLength);
  131. _socketBuffer.feedSendBuffer(std::string(&buffer[0],
  132. &buffer[KEY_LENGTH+padLength]));
  133. }
  134. _socketBuffer.send();
  135. return _socketBuffer.sendBufferIsEmpty();
  136. }
  137. bool MSEHandshake::receivePublicKey()
  138. {
  139. size_t r = KEY_LENGTH-_rbufLength;
  140. if(r > receiveNBytes(r)) {
  141. return false;
  142. }
  143. if(_logger->debug()) {
  144. _logger->debug("CUID#%d - public key received.", _cuid);
  145. }
  146. // TODO handle exception. in catch, resbufLength = 0;
  147. _dh->computeSecret(_secret, sizeof(_secret), _rbuf, _rbufLength);
  148. // reset _rbufLength
  149. _rbufLength = 0;
  150. return true;
  151. }
  152. void MSEHandshake::initCipher(const unsigned char* infoHash)
  153. {
  154. memcpy(_infoHash, infoHash, INFO_HASH_LENGTH);
  155. //Initialize cipher
  156. unsigned char s[4+KEY_LENGTH+INFO_HASH_LENGTH];
  157. memcpy(s, _initiator?"keyA":"keyB", 4);
  158. memcpy(s+4, _secret, KEY_LENGTH);
  159. memcpy(s+4+KEY_LENGTH, infoHash, INFO_HASH_LENGTH);
  160. unsigned char localCipherKey[20];
  161. MessageDigestHelper::digest(localCipherKey, sizeof(localCipherKey),
  162. MessageDigestContext::SHA1,
  163. s, sizeof(s));
  164. _encryptor.reset(new ARC4Encryptor());
  165. _encryptor->init(localCipherKey, sizeof(localCipherKey));
  166. unsigned char peerCipherKey[20];
  167. memcpy(s, _initiator?"keyB":"keyA", 4);
  168. MessageDigestHelper::digest(peerCipherKey, sizeof(peerCipherKey),
  169. MessageDigestContext::SHA1,
  170. s, sizeof(s));
  171. _decryptor.reset(new ARC4Decryptor());
  172. _decryptor->init(peerCipherKey, sizeof(peerCipherKey));
  173. // discard first 1024 bytes ARC4 output.
  174. unsigned char from[1024];
  175. unsigned char to[1024];
  176. _encryptor->encrypt(to, 1024, from, 1024);
  177. _decryptor->decrypt(to, 1024, from, 1024);
  178. if(_initiator) {
  179. ARC4Encryptor enc;
  180. enc.init(peerCipherKey, sizeof(peerCipherKey));
  181. // discard first 1024 bytes ARC4 output.
  182. enc.encrypt(to, 1024, from, 1024);
  183. enc.encrypt(_initiatorVCMarker, sizeof(_initiatorVCMarker), VC, sizeof(VC));
  184. }
  185. }
  186. void MSEHandshake::encryptAndSendData(const unsigned char* data, size_t length)
  187. {
  188. unsigned char temp[4096];
  189. const unsigned char* dptr = data;
  190. size_t s;
  191. size_t r = length;
  192. while(r > 0) {
  193. s = std::min(r, sizeof(temp));
  194. _encryptor->encrypt(temp, s, dptr, s);
  195. _socketBuffer.feedSendBuffer(std::string(&temp[0], &temp[s]));
  196. dptr += s;
  197. r -= s;
  198. }
  199. }
  200. void MSEHandshake::createReq1Hash(unsigned char* md) const
  201. {
  202. unsigned char buffer[100];
  203. memcpy(buffer, "req1", 4);
  204. memcpy(buffer+4, _secret, KEY_LENGTH);
  205. MessageDigestHelper::digest(md, 20, MessageDigestContext::SHA1,
  206. buffer, 4+KEY_LENGTH);
  207. }
  208. void MSEHandshake::createReq23Hash(unsigned char* md, const unsigned char* infoHash) const
  209. {
  210. unsigned char x[24];
  211. memcpy(x, "req2", 4);
  212. memcpy(x+4, infoHash, INFO_HASH_LENGTH);
  213. unsigned char xh[20];
  214. MessageDigestHelper::digest(xh, sizeof(xh), MessageDigestContext::SHA1,
  215. x, sizeof(x));
  216. unsigned char y[4+96];
  217. memcpy(y, "req3", 4);
  218. memcpy(y+4, _secret, KEY_LENGTH);
  219. unsigned char yh[20];
  220. MessageDigestHelper::digest(yh, sizeof(yh), MessageDigestContext::SHA1,
  221. y, sizeof(y));
  222. for(size_t i = 0; i < 20; ++i) {
  223. md[i] = xh[i]^yh[i];
  224. }
  225. }
  226. uint16_t MSEHandshake::decodeLength16(const unsigned char* buffer)
  227. {
  228. uint16_t be;
  229. _decryptor->decrypt(reinterpret_cast<unsigned char*>(&be),
  230. sizeof(be),
  231. buffer, sizeof(be));
  232. return ntohs(be);
  233. }
  234. bool MSEHandshake::sendInitiatorStep2()
  235. {
  236. if(_socketBuffer.sendBufferIsEmpty()) {
  237. if(_logger->debug()) {
  238. _logger->debug("CUID#%d - Sending negotiation step2.", _cuid);
  239. }
  240. unsigned char md[20];
  241. createReq1Hash(md);
  242. _socketBuffer.feedSendBuffer(std::string(&md[0], &md[sizeof(md)]));
  243. createReq23Hash(md, _infoHash);
  244. _socketBuffer.feedSendBuffer(std::string(&md[0], &md[sizeof(md)]));
  245. {
  246. // buffer is filled in this order:
  247. // VC(VC_LENGTH bytes),
  248. // crypto_provide(CRYPTO_BITFIELD_LENGTH bytes),
  249. // len(padC)(2bytes),
  250. // padC(len(padC)bytes <= MAX_PAD_LENGTH),
  251. // len(IA)(2bytes)
  252. unsigned char buffer[VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2+MAX_PAD_LENGTH+2];
  253. // VC
  254. memcpy(buffer, VC, sizeof(VC));
  255. // crypto_provide
  256. unsigned char cryptoProvide[CRYPTO_BITFIELD_LENGTH];
  257. memset(cryptoProvide, 0, sizeof(cryptoProvide));
  258. if(_option->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  259. cryptoProvide[3] = CRYPTO_PLAIN_TEXT;
  260. }
  261. cryptoProvide[3] |= CRYPTO_ARC4;
  262. memcpy(buffer+VC_LENGTH, cryptoProvide, sizeof(cryptoProvide));
  263. // len(padC)
  264. uint16_t padCLength = SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH+1);
  265. {
  266. uint16_t padCLengthBE = htons(padCLength);
  267. memcpy(buffer+VC_LENGTH+CRYPTO_BITFIELD_LENGTH, &padCLengthBE,
  268. sizeof(padCLengthBE));
  269. }
  270. // padC
  271. memset(buffer+VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2, 0, padCLength);
  272. // len(IA)
  273. // currently, IA is zero-length.
  274. uint16_t iaLength = 0;
  275. {
  276. uint16_t iaLengthBE = htons(iaLength);
  277. memcpy(buffer+VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2+padCLength,
  278. &iaLengthBE,sizeof(iaLengthBE));
  279. }
  280. encryptAndSendData(buffer,
  281. VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2+padCLength+2);
  282. }
  283. }
  284. _socketBuffer.send();
  285. return _socketBuffer.sendBufferIsEmpty();
  286. }
  287. // This function reads exactly until the end of VC marker is reached.
  288. bool MSEHandshake::findInitiatorVCMarker()
  289. {
  290. // 616 is synchronization point of initiator
  291. size_t r = 616-KEY_LENGTH-_rbufLength;
  292. if(!_socket->isReadable(0)) {
  293. return false;
  294. }
  295. _socket->peekData(_rbuf+_rbufLength, r);
  296. if(r == 0) {
  297. if(_socket->wantRead() || _socket->wantWrite()) {
  298. return false;
  299. }
  300. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  301. }
  302. // find vc
  303. {
  304. std::string buf(&_rbuf[0], &_rbuf[_rbufLength+r]);
  305. std::string vc(&_initiatorVCMarker[0], &_initiatorVCMarker[VC_LENGTH]);
  306. if((_markerIndex = buf.find(vc)) == std::string::npos) {
  307. if(616-KEY_LENGTH <= _rbufLength+r) {
  308. throw DL_ABORT_EX("Failed to find VC marker.");
  309. } else {
  310. _socket->readData(_rbuf+_rbufLength, r);
  311. _rbufLength += r;
  312. return false;
  313. }
  314. }
  315. }
  316. assert(_markerIndex+VC_LENGTH-_rbufLength <= r);
  317. size_t toRead = _markerIndex+VC_LENGTH-_rbufLength;
  318. _socket->readData(_rbuf+_rbufLength, toRead);
  319. _rbufLength += toRead;
  320. if(_logger->debug()) {
  321. _logger->debug("CUID#%d - VC marker found at %u", _cuid, _markerIndex);
  322. }
  323. verifyVC(_rbuf+_markerIndex);
  324. // reset _rbufLength
  325. _rbufLength = 0;
  326. return true;
  327. }
  328. bool MSEHandshake::receiveInitiatorCryptoSelectAndPadDLength()
  329. {
  330. size_t r = CRYPTO_BITFIELD_LENGTH+2/* PadD length*/-_rbufLength;
  331. if(r > receiveNBytes(r)) {
  332. return false;
  333. }
  334. //verifyCryptoSelect
  335. unsigned char* rbufptr = _rbuf;
  336. {
  337. unsigned char cryptoSelect[CRYPTO_BITFIELD_LENGTH];
  338. _decryptor->decrypt(cryptoSelect, sizeof(cryptoSelect),
  339. rbufptr, sizeof(cryptoSelect));
  340. if(cryptoSelect[3]&CRYPTO_PLAIN_TEXT &&
  341. _option->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  342. if(_logger->debug()) {
  343. _logger->debug("CUID#%d - peer prefers plaintext.", _cuid);
  344. }
  345. _negotiatedCryptoType = CRYPTO_PLAIN_TEXT;
  346. }
  347. if(cryptoSelect[3]&CRYPTO_ARC4) {
  348. if(_logger->debug()) {
  349. _logger->debug("CUID#%d - peer prefers ARC4", _cuid);
  350. }
  351. _negotiatedCryptoType = CRYPTO_ARC4;
  352. }
  353. if(_negotiatedCryptoType == CRYPTO_NONE) {
  354. throw DL_ABORT_EX
  355. (StringFormat("CUID#%d - No supported crypto type selected.", _cuid).str());
  356. }
  357. }
  358. // padD length
  359. rbufptr += CRYPTO_BITFIELD_LENGTH;
  360. _padLength = verifyPadLength(rbufptr, "PadD");
  361. // reset _rbufLength
  362. _rbufLength = 0;
  363. return true;
  364. }
  365. bool MSEHandshake::receivePad()
  366. {
  367. if(_padLength == 0) {
  368. return true;
  369. }
  370. size_t r = _padLength-_rbufLength;
  371. if(r > receiveNBytes(r)) {
  372. return false;
  373. }
  374. unsigned char temp[MAX_PAD_LENGTH];
  375. _decryptor->decrypt(temp, _padLength, _rbuf, _padLength);
  376. // reset _rbufLength
  377. _rbufLength = 0;
  378. return true;
  379. }
  380. bool MSEHandshake::findReceiverHashMarker()
  381. {
  382. // 628 is synchronization limit of receiver.
  383. size_t r = 628-KEY_LENGTH-_rbufLength;
  384. if(!_socket->isReadable(0)) {
  385. return false;
  386. }
  387. _socket->peekData(_rbuf+_rbufLength, r);
  388. if(r == 0) {
  389. if(_socket->wantRead() || _socket->wantWrite()) {
  390. return false;
  391. }
  392. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  393. }
  394. // find hash('req1', S), S is _secret.
  395. {
  396. std::string buf(&_rbuf[0], &_rbuf[_rbufLength+r]);
  397. unsigned char md[20];
  398. createReq1Hash(md);
  399. std::string req1(&md[0], &md[sizeof(md)]);
  400. if((_markerIndex = buf.find(req1)) == std::string::npos) {
  401. if(628-KEY_LENGTH <= _rbufLength+r) {
  402. throw DL_ABORT_EX("Failed to find hash marker.");
  403. } else {
  404. _socket->readData(_rbuf+_rbufLength, r);
  405. _rbufLength += r;
  406. return false;
  407. }
  408. }
  409. }
  410. assert(_markerIndex+20-_rbufLength <= r);
  411. size_t toRead = _markerIndex+20-_rbufLength;
  412. _socket->readData(_rbuf+_rbufLength, toRead);
  413. _rbufLength += toRead;
  414. if(_logger->debug()) {
  415. _logger->debug("CUID#%d - Hash marker found at %u.", _cuid, _markerIndex);
  416. }
  417. verifyReq1Hash(_rbuf+_markerIndex);
  418. // reset _rbufLength
  419. _rbufLength = 0;
  420. return true;
  421. }
  422. bool MSEHandshake::receiveReceiverHashAndPadCLength
  423. (const std::deque<SharedHandle<DownloadContext> >& downloadContexts)
  424. {
  425. size_t r = 20+VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2/*PadC length*/-_rbufLength;
  426. if(r > receiveNBytes(r)) {
  427. return false;
  428. }
  429. // resolve info hash
  430. // pointing to the position of HASH('req2', SKEY) xor HASH('req3', S)
  431. unsigned char* rbufptr = _rbuf;
  432. SharedHandle<DownloadContext> downloadContext;
  433. for(std::deque<SharedHandle<DownloadContext> >::const_iterator i =
  434. downloadContexts.begin(); i != downloadContexts.end(); ++i) {
  435. unsigned char md[20];
  436. const BDE& torrentAttrs = (*i)->getAttribute(bittorrent::BITTORRENT);
  437. createReq23Hash(md, torrentAttrs[bittorrent::INFO_HASH].uc());
  438. if(memcmp(md, rbufptr, sizeof(md)) == 0) {
  439. if(_logger->debug()) {
  440. _logger->debug("CUID#%d - info hash found: %s", _cuid,
  441. util::toHex
  442. (torrentAttrs[bittorrent::INFO_HASH].s()).c_str());
  443. }
  444. downloadContext = *i;
  445. break;
  446. }
  447. }
  448. if(downloadContext.isNull()) {
  449. throw DL_ABORT_EX("Unknown info hash.");
  450. }
  451. initCipher(bittorrent::getInfoHash(downloadContext));
  452. // decrypt VC
  453. rbufptr += 20;
  454. verifyVC(rbufptr);
  455. // decrypt crypto_provide
  456. rbufptr += VC_LENGTH;
  457. {
  458. unsigned char cryptoProvide[CRYPTO_BITFIELD_LENGTH];
  459. _decryptor->decrypt(cryptoProvide, sizeof(cryptoProvide),
  460. rbufptr, sizeof(cryptoProvide));
  461. // TODO choose the crypto type based on the preference.
  462. // For now, choose ARC4.
  463. if(cryptoProvide[3]&CRYPTO_PLAIN_TEXT &&
  464. _option->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  465. if(_logger->debug()) {
  466. _logger->debug("CUID#%d - peer provides plaintext.", _cuid);
  467. }
  468. _negotiatedCryptoType = CRYPTO_PLAIN_TEXT;
  469. } else if(cryptoProvide[3]&CRYPTO_ARC4) {
  470. if(_logger->debug()) {
  471. _logger->debug("CUID#%d - peer provides ARC4.", _cuid);
  472. }
  473. _negotiatedCryptoType = CRYPTO_ARC4;
  474. }
  475. if(_negotiatedCryptoType == CRYPTO_NONE) {
  476. throw DL_ABORT_EX
  477. (StringFormat("CUID#%d - No supported crypto type provided.", _cuid).str());
  478. }
  479. }
  480. // decrypt PadC length
  481. rbufptr += CRYPTO_BITFIELD_LENGTH;
  482. _padLength = verifyPadLength(rbufptr, "PadC");
  483. // reset _rbufLength
  484. _rbufLength = 0;
  485. return true;
  486. }
  487. bool MSEHandshake::receiveReceiverIALength()
  488. {
  489. size_t r = 2-_rbufLength;
  490. assert(r > 0);
  491. if(r > receiveNBytes(r)) {
  492. return false;
  493. }
  494. _iaLength = decodeLength16(_rbuf);
  495. if(_logger->debug()) {
  496. _logger->debug("CUID#%d - len(IA)=%u.", _cuid, _iaLength);
  497. }
  498. // reset _rbufLength
  499. _rbufLength = 0;
  500. return true;
  501. }
  502. bool MSEHandshake::receiveReceiverIA()
  503. {
  504. if(_iaLength == 0) {
  505. return true;
  506. }
  507. size_t r = _iaLength-_rbufLength;
  508. if(r > receiveNBytes(r)) {
  509. return false;
  510. }
  511. delete [] _ia;
  512. _ia = new unsigned char[_iaLength];
  513. _decryptor->decrypt(_ia, _iaLength, _rbuf, _iaLength);
  514. if(_logger->debug()) {
  515. _logger->debug("CUID#%d - IA received.", _cuid);
  516. }
  517. // reset _rbufLength
  518. _rbufLength = 0;
  519. return true;
  520. }
  521. bool MSEHandshake::sendReceiverStep2()
  522. {
  523. if(_socketBuffer.sendBufferIsEmpty()) {
  524. // buffer is filled in this order:
  525. // VC(VC_LENGTH bytes),
  526. // cryptoSelect(CRYPTO_BITFIELD_LENGTH bytes),
  527. // len(padD)(2bytes),
  528. // padD(len(padD)bytes <= MAX_PAD_LENGTH)
  529. unsigned char buffer[VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2+MAX_PAD_LENGTH];
  530. // VC
  531. memcpy(buffer, VC, sizeof(VC));
  532. // crypto_select
  533. unsigned char cryptoSelect[CRYPTO_BITFIELD_LENGTH];
  534. memset(cryptoSelect, 0, sizeof(cryptoSelect));
  535. cryptoSelect[3] = _negotiatedCryptoType;
  536. memcpy(buffer+VC_LENGTH, cryptoSelect, sizeof(cryptoSelect));
  537. // len(padD)
  538. uint16_t padDLength = SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH+1);
  539. {
  540. uint16_t padDLengthBE = htons(padDLength);
  541. memcpy(buffer+VC_LENGTH+CRYPTO_BITFIELD_LENGTH, &padDLengthBE,
  542. sizeof(padDLengthBE));
  543. }
  544. // padD, all zeroed
  545. memset(buffer+VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2, 0, padDLength);
  546. encryptAndSendData(buffer, VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2+padDLength);
  547. }
  548. _socketBuffer.send();
  549. return _socketBuffer.sendBufferIsEmpty();
  550. }
  551. uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf, const char* padName)
  552. {
  553. if(_logger->debug()) {
  554. _logger->debug("CUID#%d - Verifying Pad length for %s", _cuid, padName);
  555. }
  556. uint16_t padLength = decodeLength16(padlenbuf);
  557. if(_logger->debug()) {
  558. _logger->debug("CUID#%d - len(%s)=%u", _cuid, padName, padLength);
  559. }
  560. if(padLength > 512) {
  561. throw DL_ABORT_EX
  562. (StringFormat("Too large %s length: %u", padName, padLength).str());
  563. }
  564. return padLength;
  565. }
  566. void MSEHandshake::verifyVC(const unsigned char* vcbuf)
  567. {
  568. if(_logger->debug()) {
  569. _logger->debug("CUID#%d - Verifying VC.", _cuid);
  570. }
  571. unsigned char vc[VC_LENGTH];
  572. _decryptor->decrypt(vc, sizeof(vc), vcbuf, sizeof(vc));
  573. if(memcmp(VC, vc, sizeof(VC)) != 0) {
  574. throw DL_ABORT_EX
  575. (StringFormat("Invalid VC: %s", util::toHex(vc, VC_LENGTH).c_str()).str());
  576. }
  577. }
  578. void MSEHandshake::verifyReq1Hash(const unsigned char* req1buf)
  579. {
  580. if(_logger->debug()) {
  581. _logger->debug("CUID#%d - Verifying req hash.", _cuid);
  582. }
  583. unsigned char md[20];
  584. createReq1Hash(md);
  585. if(memcmp(md, req1buf, sizeof(md)) != 0) {
  586. throw DL_ABORT_EX("Invalid req1 hash found.");
  587. }
  588. }
  589. size_t MSEHandshake::receiveNBytes(size_t bytes)
  590. {
  591. size_t r = bytes;
  592. if(r > 0) {
  593. if(!_socket->isReadable(0)) {
  594. return 0;
  595. }
  596. _socket->readData(_rbuf+_rbufLength, r);
  597. if(r == 0 && !_socket->wantRead() && !_socket->wantWrite()) {
  598. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  599. }
  600. _rbufLength += r;
  601. }
  602. return r;
  603. }
  604. } // namespace aria2