MSEHandshake.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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.pushStr(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.pushStr(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.pushStr(std::string(&md[0], &md[sizeof(md)]));
  243. createReq23Hash(md, _infoHash);
  244. _socketBuffer.pushStr(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::vector<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::vector<SharedHandle<DownloadContext> >::const_iterator i =
  434. downloadContexts.begin(), eoi = downloadContexts.end();
  435. i != eoi; ++i) {
  436. unsigned char md[20];
  437. const BDE& torrentAttrs = (*i)->getAttribute(bittorrent::BITTORRENT);
  438. createReq23Hash(md, torrentAttrs[bittorrent::INFO_HASH].uc());
  439. if(memcmp(md, rbufptr, sizeof(md)) == 0) {
  440. if(_logger->debug()) {
  441. _logger->debug("CUID#%d - info hash found: %s", _cuid,
  442. util::toHex
  443. (torrentAttrs[bittorrent::INFO_HASH].s()).c_str());
  444. }
  445. downloadContext = *i;
  446. break;
  447. }
  448. }
  449. if(downloadContext.isNull()) {
  450. throw DL_ABORT_EX("Unknown info hash.");
  451. }
  452. initCipher(bittorrent::getInfoHash(downloadContext));
  453. // decrypt VC
  454. rbufptr += 20;
  455. verifyVC(rbufptr);
  456. // decrypt crypto_provide
  457. rbufptr += VC_LENGTH;
  458. {
  459. unsigned char cryptoProvide[CRYPTO_BITFIELD_LENGTH];
  460. _decryptor->decrypt(cryptoProvide, sizeof(cryptoProvide),
  461. rbufptr, sizeof(cryptoProvide));
  462. // TODO choose the crypto type based on the preference.
  463. // For now, choose ARC4.
  464. if(cryptoProvide[3]&CRYPTO_PLAIN_TEXT &&
  465. _option->get(PREF_BT_MIN_CRYPTO_LEVEL) == V_PLAIN) {
  466. if(_logger->debug()) {
  467. _logger->debug("CUID#%d - peer provides plaintext.", _cuid);
  468. }
  469. _negotiatedCryptoType = CRYPTO_PLAIN_TEXT;
  470. } else if(cryptoProvide[3]&CRYPTO_ARC4) {
  471. if(_logger->debug()) {
  472. _logger->debug("CUID#%d - peer provides ARC4.", _cuid);
  473. }
  474. _negotiatedCryptoType = CRYPTO_ARC4;
  475. }
  476. if(_negotiatedCryptoType == CRYPTO_NONE) {
  477. throw DL_ABORT_EX
  478. (StringFormat("CUID#%d - No supported crypto type provided.", _cuid).str());
  479. }
  480. }
  481. // decrypt PadC length
  482. rbufptr += CRYPTO_BITFIELD_LENGTH;
  483. _padLength = verifyPadLength(rbufptr, "PadC");
  484. // reset _rbufLength
  485. _rbufLength = 0;
  486. return true;
  487. }
  488. bool MSEHandshake::receiveReceiverIALength()
  489. {
  490. size_t r = 2-_rbufLength;
  491. assert(r > 0);
  492. if(r > receiveNBytes(r)) {
  493. return false;
  494. }
  495. _iaLength = decodeLength16(_rbuf);
  496. if(_logger->debug()) {
  497. _logger->debug("CUID#%d - len(IA)=%u.", _cuid, _iaLength);
  498. }
  499. // reset _rbufLength
  500. _rbufLength = 0;
  501. return true;
  502. }
  503. bool MSEHandshake::receiveReceiverIA()
  504. {
  505. if(_iaLength == 0) {
  506. return true;
  507. }
  508. size_t r = _iaLength-_rbufLength;
  509. if(r > receiveNBytes(r)) {
  510. return false;
  511. }
  512. delete [] _ia;
  513. _ia = new unsigned char[_iaLength];
  514. _decryptor->decrypt(_ia, _iaLength, _rbuf, _iaLength);
  515. if(_logger->debug()) {
  516. _logger->debug("CUID#%d - IA received.", _cuid);
  517. }
  518. // reset _rbufLength
  519. _rbufLength = 0;
  520. return true;
  521. }
  522. bool MSEHandshake::sendReceiverStep2()
  523. {
  524. if(_socketBuffer.sendBufferIsEmpty()) {
  525. // buffer is filled in this order:
  526. // VC(VC_LENGTH bytes),
  527. // cryptoSelect(CRYPTO_BITFIELD_LENGTH bytes),
  528. // len(padD)(2bytes),
  529. // padD(len(padD)bytes <= MAX_PAD_LENGTH)
  530. unsigned char buffer[VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2+MAX_PAD_LENGTH];
  531. // VC
  532. memcpy(buffer, VC, sizeof(VC));
  533. // crypto_select
  534. unsigned char cryptoSelect[CRYPTO_BITFIELD_LENGTH];
  535. memset(cryptoSelect, 0, sizeof(cryptoSelect));
  536. cryptoSelect[3] = _negotiatedCryptoType;
  537. memcpy(buffer+VC_LENGTH, cryptoSelect, sizeof(cryptoSelect));
  538. // len(padD)
  539. uint16_t padDLength = SimpleRandomizer::getInstance()->getRandomNumber(MAX_PAD_LENGTH+1);
  540. {
  541. uint16_t padDLengthBE = htons(padDLength);
  542. memcpy(buffer+VC_LENGTH+CRYPTO_BITFIELD_LENGTH, &padDLengthBE,
  543. sizeof(padDLengthBE));
  544. }
  545. // padD, all zeroed
  546. memset(buffer+VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2, 0, padDLength);
  547. encryptAndSendData(buffer, VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2+padDLength);
  548. }
  549. _socketBuffer.send();
  550. return _socketBuffer.sendBufferIsEmpty();
  551. }
  552. uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf, const char* padName)
  553. {
  554. if(_logger->debug()) {
  555. _logger->debug("CUID#%d - Verifying Pad length for %s", _cuid, padName);
  556. }
  557. uint16_t padLength = decodeLength16(padlenbuf);
  558. if(_logger->debug()) {
  559. _logger->debug("CUID#%d - len(%s)=%u", _cuid, padName, padLength);
  560. }
  561. if(padLength > 512) {
  562. throw DL_ABORT_EX
  563. (StringFormat("Too large %s length: %u", padName, padLength).str());
  564. }
  565. return padLength;
  566. }
  567. void MSEHandshake::verifyVC(const unsigned char* vcbuf)
  568. {
  569. if(_logger->debug()) {
  570. _logger->debug("CUID#%d - Verifying VC.", _cuid);
  571. }
  572. unsigned char vc[VC_LENGTH];
  573. _decryptor->decrypt(vc, sizeof(vc), vcbuf, sizeof(vc));
  574. if(memcmp(VC, vc, sizeof(VC)) != 0) {
  575. throw DL_ABORT_EX
  576. (StringFormat("Invalid VC: %s", util::toHex(vc, VC_LENGTH).c_str()).str());
  577. }
  578. }
  579. void MSEHandshake::verifyReq1Hash(const unsigned char* req1buf)
  580. {
  581. if(_logger->debug()) {
  582. _logger->debug("CUID#%d - Verifying req hash.", _cuid);
  583. }
  584. unsigned char md[20];
  585. createReq1Hash(md);
  586. if(memcmp(md, req1buf, sizeof(md)) != 0) {
  587. throw DL_ABORT_EX("Invalid req1 hash found.");
  588. }
  589. }
  590. size_t MSEHandshake::receiveNBytes(size_t bytes)
  591. {
  592. size_t r = bytes;
  593. if(r > 0) {
  594. if(!_socket->isReadable(0)) {
  595. return 0;
  596. }
  597. _socket->readData(_rbuf+_rbufLength, r);
  598. if(r == 0 && !_socket->wantRead() && !_socket->wantWrite()) {
  599. throw DL_ABORT_EX(EX_EOF_FROM_PEER);
  600. }
  601. _rbufLength += r;
  602. }
  603. return r;
  604. }
  605. } // namespace aria2