RLPxHandshake.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file RLPXHandshake.cpp
  15. * @author Alex Leverington <nessence@gmail.com>
  16. * @date 2015
  17. */
  18. #include "Host.h"
  19. #include "Session.h"
  20. #include "Peer.h"
  21. #include "RLPxHandshake.h"
  22. using namespace std;
  23. using namespace dev;
  24. using namespace dev::p2p;
  25. using namespace dev::crypto;
  26. using namespace CryptoPP;
  27. void RLPXHandshake::writeAuth()
  28. {
  29. clog(NetP2PConnect) << "p2p.connect.egress sending auth to " << m_socket->remoteEndpoint();
  30. m_auth.resize(Signature::size + h256::size + Public::size + h256::size + 1);
  31. bytesRef sig(&m_auth[0], Signature::size);
  32. bytesRef hepubk(&m_auth[Signature::size], h256::size);
  33. bytesRef pubk(&m_auth[Signature::size + h256::size], Public::size);
  34. bytesRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size);
  35. // E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x0)
  36. Secret staticShared;
  37. crypto::ecdh::agree(m_host->m_alias.sec(), m_remote, staticShared);
  38. sign(m_ecdhe.seckey(), staticShared.makeInsecure() ^ m_nonce).ref().copyTo(sig);
  39. sha3(m_ecdhe.pubkey().ref(), hepubk);
  40. m_host->m_alias.pub().ref().copyTo(pubk);
  41. m_nonce.ref().copyTo(nonce);
  42. m_auth[m_auth.size() - 1] = 0x0;
  43. encryptECIES(m_remote, &m_auth, m_authCipher);
  44. auto self(shared_from_this());
  45. ba::async_write(m_socket->ref(), ba::buffer(m_authCipher), [this, self](boost::system::error_code ec, std::size_t)
  46. {
  47. transition(ec);
  48. });
  49. }
  50. void RLPXHandshake::writeAck()
  51. {
  52. clog(NetP2PConnect) << "p2p.connect.ingress sending ack to " << m_socket->remoteEndpoint();
  53. m_ack.resize(Public::size + h256::size + 1);
  54. bytesRef epubk(&m_ack[0], Public::size);
  55. bytesRef nonce(&m_ack[Public::size], h256::size);
  56. m_ecdhe.pubkey().ref().copyTo(epubk);
  57. m_nonce.ref().copyTo(nonce);
  58. m_ack[m_ack.size() - 1] = 0x0;
  59. encryptECIES(m_remote, &m_ack, m_ackCipher);
  60. auto self(shared_from_this());
  61. ba::async_write(m_socket->ref(), ba::buffer(m_ackCipher), [this, self](boost::system::error_code ec, std::size_t)
  62. {
  63. transition(ec);
  64. });
  65. }
  66. void RLPXHandshake::writeAckEIP8()
  67. {
  68. clog(NetP2PConnect) << "p2p.connect.ingress sending EIP-8 ack to " << m_socket->remoteEndpoint();
  69. RLPStream rlp;
  70. rlp.appendList(3)
  71. << m_ecdhe.pubkey()
  72. << m_nonce
  73. << c_rlpxVersion;
  74. m_ack = rlp.out();
  75. int padAmount(rand()%100 + 100);
  76. m_ack.resize(m_ack.size() + padAmount, 0);
  77. bytes prefix(2);
  78. toBigEndian<uint16_t>(m_ack.size() + c_eciesOverhead, prefix);
  79. encryptECIES(m_remote, bytesConstRef(&prefix), &m_ack, m_ackCipher);
  80. m_ackCipher.insert(m_ackCipher.begin(), prefix.begin(), prefix.end());
  81. auto self(shared_from_this());
  82. ba::async_write(m_socket->ref(), ba::buffer(m_ackCipher), [this, self](boost::system::error_code ec, std::size_t)
  83. {
  84. transition(ec);
  85. });
  86. }
  87. void RLPXHandshake::setAuthValues(Signature const& _sig, Public const& _remotePubk, h256 const& _remoteNonce, uint64_t _remoteVersion)
  88. {
  89. _remotePubk.ref().copyTo(m_remote.ref());
  90. _remoteNonce.ref().copyTo(m_remoteNonce.ref());
  91. m_remoteVersion = _remoteVersion;
  92. Secret sharedSecret;
  93. crypto::ecdh::agree(m_host->m_alias.sec(), _remotePubk, sharedSecret);
  94. m_remoteEphemeral = recover(_sig, sharedSecret.makeInsecure() ^ _remoteNonce);
  95. }
  96. void RLPXHandshake::readAuth()
  97. {
  98. clog(NetP2PConnect) << "p2p.connect.ingress receiving auth from " << m_socket->remoteEndpoint();
  99. m_authCipher.resize(307);
  100. auto self(shared_from_this());
  101. ba::async_read(m_socket->ref(), ba::buffer(m_authCipher, 307), [this, self](boost::system::error_code ec, std::size_t)
  102. {
  103. if (ec)
  104. transition(ec);
  105. else if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_authCipher), m_auth))
  106. {
  107. bytesConstRef data(&m_auth);
  108. Signature sig(data.cropped(0, Signature::size));
  109. Public pubk(data.cropped(Signature::size + h256::size, Public::size));
  110. h256 nonce(data.cropped(Signature::size + h256::size + Public::size, h256::size));
  111. setAuthValues(sig, pubk, nonce, 4);
  112. transition();
  113. }
  114. else
  115. readAuthEIP8();
  116. });
  117. }
  118. void RLPXHandshake::readAuthEIP8()
  119. {
  120. assert(m_authCipher.size() == 307);
  121. uint16_t size(m_authCipher[0]<<8 | m_authCipher[1]);
  122. clog(NetP2PConnect) << "p2p.connect.ingress receiving " << size << "bytes EIP-8 auth from " << m_socket->remoteEndpoint();
  123. m_authCipher.resize((size_t)size + 2);
  124. auto rest = ba::buffer(ba::buffer(m_authCipher) + 307);
  125. auto self(shared_from_this());
  126. ba::async_read(m_socket->ref(), rest, [this, self](boost::system::error_code ec, std::size_t)
  127. {
  128. bytesConstRef ct(&m_authCipher);
  129. if (ec)
  130. transition(ec);
  131. else if (decryptECIES(m_host->m_alias.sec(), ct.cropped(0, 2), ct.cropped(2), m_auth))
  132. {
  133. RLP rlp(m_auth, RLP::ThrowOnFail | RLP::FailIfTooSmall);
  134. setAuthValues(
  135. rlp[0].toHash<Signature>(),
  136. rlp[1].toHash<Public>(),
  137. rlp[2].toHash<h256>(),
  138. rlp[3].toInt<uint64_t>()
  139. );
  140. m_nextState = AckAuthEIP8;
  141. transition();
  142. }
  143. else
  144. {
  145. clog(NetP2PConnect) << "p2p.connect.ingress auth decrypt failed for" << m_socket->remoteEndpoint();
  146. m_nextState = Error;
  147. transition();
  148. }
  149. });
  150. }
  151. void RLPXHandshake::readAck()
  152. {
  153. clog(NetP2PConnect) << "p2p.connect.egress receiving ack from " << m_socket->remoteEndpoint();
  154. m_ackCipher.resize(210);
  155. auto self(shared_from_this());
  156. ba::async_read(m_socket->ref(), ba::buffer(m_ackCipher, 210), [this, self](boost::system::error_code ec, std::size_t)
  157. {
  158. if (ec)
  159. transition(ec);
  160. else if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_ackCipher), m_ack))
  161. {
  162. bytesConstRef(&m_ack).cropped(0, Public::size).copyTo(m_remoteEphemeral.ref());
  163. bytesConstRef(&m_ack).cropped(Public::size, h256::size).copyTo(m_remoteNonce.ref());
  164. m_remoteVersion = 4;
  165. transition();
  166. }
  167. else
  168. readAckEIP8();
  169. });
  170. }
  171. void RLPXHandshake::readAckEIP8()
  172. {
  173. assert(m_ackCipher.size() == 210);
  174. uint16_t size(m_ackCipher[0]<<8 | m_ackCipher[1]);
  175. clog(NetP2PConnect) << "p2p.connect.egress receiving " << size << "bytes EIP-8 ack from " << m_socket->remoteEndpoint();
  176. m_ackCipher.resize((size_t)size + 2);
  177. auto rest = ba::buffer(ba::buffer(m_ackCipher) + 210);
  178. auto self(shared_from_this());
  179. ba::async_read(m_socket->ref(), rest, [this, self](boost::system::error_code ec, std::size_t)
  180. {
  181. bytesConstRef ct(&m_ackCipher);
  182. if (ec)
  183. transition(ec);
  184. else if (decryptECIES(m_host->m_alias.sec(), ct.cropped(0, 2), ct.cropped(2), m_ack))
  185. {
  186. RLP rlp(m_ack, RLP::ThrowOnFail | RLP::FailIfTooSmall);
  187. m_remoteEphemeral = rlp[0].toHash<Public>();
  188. m_remoteNonce = rlp[1].toHash<h256>();
  189. m_remoteVersion = rlp[2].toInt<uint64_t>();
  190. transition();
  191. }
  192. else
  193. {
  194. clog(NetP2PConnect) << "p2p.connect.egress ack decrypt failed for " << m_socket->remoteEndpoint();
  195. m_nextState = Error;
  196. transition();
  197. }
  198. });
  199. }
  200. void RLPXHandshake::cancel()
  201. {
  202. m_cancel = true;
  203. m_idleTimer.cancel();
  204. m_socket->close();
  205. m_io.reset();
  206. }
  207. void RLPXHandshake::error()
  208. {
  209. auto connected = m_socket->isConnected();
  210. if (connected && !m_socket->remoteEndpoint().address().is_unspecified())
  211. clog(NetP2PConnect) << "Disconnecting " << m_socket->remoteEndpoint() << " (Handshake Failed)";
  212. else
  213. clog(NetP2PConnect) << "Handshake Failed (Connection reset by peer)";
  214. cancel();
  215. }
  216. void RLPXHandshake::transition(boost::system::error_code _ech)
  217. {
  218. // reset timeout
  219. m_idleTimer.cancel();
  220. if (_ech || m_nextState == Error || m_cancel)
  221. {
  222. clog(NetP2PConnect) << "Handshake Failed (I/O Error:" << _ech.message() << ")";
  223. return error();
  224. }
  225. auto self(shared_from_this());
  226. assert(m_nextState != StartSession);
  227. m_idleTimer.expires_from_now(c_timeout);
  228. m_idleTimer.async_wait([this, self](boost::system::error_code const& _ec)
  229. {
  230. if (!_ec)
  231. {
  232. if (!m_socket->remoteEndpoint().address().is_unspecified())
  233. clog(NetP2PConnect) << "Disconnecting " << m_socket->remoteEndpoint() << " (Handshake Timeout)";
  234. cancel();
  235. }
  236. });
  237. if (m_nextState == New)
  238. {
  239. m_nextState = AckAuth;
  240. if (m_originated)
  241. writeAuth();
  242. else
  243. readAuth();
  244. }
  245. else if (m_nextState == AckAuth)
  246. {
  247. m_nextState = WriteHello;
  248. if (m_originated)
  249. readAck();
  250. else
  251. writeAck();
  252. }
  253. else if (m_nextState == AckAuthEIP8)
  254. {
  255. m_nextState = WriteHello;
  256. if (m_originated)
  257. readAck();
  258. else
  259. writeAckEIP8();
  260. }
  261. else if (m_nextState == WriteHello)
  262. {
  263. m_nextState = ReadHello;
  264. clog(NetP2PConnect) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "sending capabilities handshake";
  265. /// This pointer will be freed if there is an error otherwise
  266. /// it will be passed to Host which will take ownership.
  267. m_io.reset(new RLPXFrameCoder(*this));
  268. RLPStream s;
  269. s.append((unsigned)HelloPacket).appendList(5)
  270. << dev::p2p::c_protocolVersion
  271. << m_host->m_clientVersion
  272. << m_host->caps()
  273. << m_host->listenPort()
  274. << m_host->id();
  275. bytes packet;
  276. s.swapOut(packet);
  277. m_io->writeSingleFramePacket(&packet, m_handshakeOutBuffer);
  278. ba::async_write(m_socket->ref(), ba::buffer(m_handshakeOutBuffer), [this, self](boost::system::error_code ec, std::size_t)
  279. {
  280. transition(ec);
  281. });
  282. }
  283. else if (m_nextState == ReadHello)
  284. {
  285. // Authenticate and decrypt initial hello frame with initial RLPXFrameCoder
  286. // and request m_host to start session.
  287. m_nextState = StartSession;
  288. // read frame header
  289. unsigned const handshakeSize = 32;
  290. m_handshakeInBuffer.resize(handshakeSize);
  291. ba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, handshakeSize), [this, self](boost::system::error_code ec, std::size_t)
  292. {
  293. if (ec)
  294. transition(ec);
  295. else
  296. {
  297. if (!m_io)
  298. {
  299. clog(NetP2PWarn) << "Internal error in handshake: RLPXFrameCoder disappeared.";
  300. m_nextState = Error;
  301. transition();
  302. return;
  303. }
  304. /// authenticate and decrypt header
  305. if (!m_io->authAndDecryptHeader(bytesRef(m_handshakeInBuffer.data(), m_handshakeInBuffer.size())))
  306. {
  307. m_nextState = Error;
  308. transition();
  309. return;
  310. }
  311. clog(NetP2PNote) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "recvd hello header";
  312. /// check frame size
  313. bytes& header = m_handshakeInBuffer;
  314. uint32_t frameSize = (uint32_t)(header[2]) | (uint32_t)(header[1])<<8 | (uint32_t)(header[0])<<16;
  315. if (frameSize > 1024)
  316. {
  317. // all future frames: 16777216
  318. clog(NetP2PWarn) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame is too large" << frameSize;
  319. m_nextState = Error;
  320. transition();
  321. return;
  322. }
  323. /// rlp of header has protocol-type, sequence-id[, total-packet-size]
  324. bytes headerRLP(header.size() - 3 - h128::size); // this is always 32 - 3 - 16 = 13. wtf?
  325. bytesConstRef(&header).cropped(3).copyTo(&headerRLP);
  326. /// read padded frame and mac
  327. m_handshakeInBuffer.resize(frameSize + ((16 - (frameSize % 16)) % 16) + h128::size);
  328. ba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, m_handshakeInBuffer.size()), [this, self, headerRLP](boost::system::error_code ec, std::size_t)
  329. {
  330. m_idleTimer.cancel();
  331. if (ec)
  332. transition(ec);
  333. else
  334. {
  335. if (!m_io)
  336. {
  337. clog(NetP2PWarn) << "Internal error in handshake: RLPXFrameCoder disappeared.";
  338. m_nextState = Error;
  339. transition();
  340. return;
  341. }
  342. bytesRef frame(&m_handshakeInBuffer);
  343. if (!m_io->authAndDecryptFrame(frame))
  344. {
  345. clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: decrypt failed";
  346. m_nextState = Error;
  347. transition();
  348. return;
  349. }
  350. PacketType packetType = frame[0] == 0x80 ? HelloPacket : (PacketType)frame[0];
  351. if (packetType != HelloPacket)
  352. {
  353. clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: invalid packet type";
  354. m_nextState = Error;
  355. transition();
  356. return;
  357. }
  358. clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: success. starting session.";
  359. try
  360. {
  361. RLP rlp(frame.cropped(1), RLP::ThrowOnFail | RLP::FailIfTooSmall);
  362. m_host->startPeerSession(m_remote, rlp, move(m_io), m_socket);
  363. }
  364. catch (std::exception const& _e)
  365. {
  366. clog(NetWarn) << "Handshake causing an exception:" << _e.what();
  367. m_nextState = Error;
  368. transition();
  369. }
  370. }
  371. });
  372. }
  373. });
  374. }
  375. }