MSEHandshake.cc 18 KB

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