PacketDecoder.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "Constants.hpp"
  28. #include "RuntimeEnvironment.hpp"
  29. #include "Topology.hpp"
  30. #include "PacketDecoder.hpp"
  31. #include "Switch.hpp"
  32. #include "Peer.hpp"
  33. #include "NodeConfig.hpp"
  34. #include "Filter.hpp"
  35. #include "Service.hpp"
  36. /*
  37. * The big picture:
  38. *
  39. * tryDecode() gets called for a given fully-assembled packet until it returns
  40. * true or the packet's time to live has been exceeded. The state machine must
  41. * therefore be re-entrant if it ever returns false. Take care here!
  42. *
  43. * Stylistic note:
  44. *
  45. * There's a lot of unnecessary if nesting. It's mostly to allow TRACE to
  46. * print informative messages on every possible reason something gets
  47. * rejected or fails.
  48. */
  49. namespace ZeroTier {
  50. bool PacketDecoder::tryDecode(const RuntimeEnvironment *_r)
  51. throw(std::out_of_range,std::runtime_error)
  52. {
  53. if ((!encrypted())&&(verb() == Packet::VERB_HELLO)) {
  54. // Unencrypted HELLOs are handled here since they are used to
  55. // populate our identity cache in the first place. Thus we might get
  56. // a HELLO for someone for whom we don't have a Peer record.
  57. TRACE("HELLO from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  58. return _doHELLO(_r);
  59. }
  60. SharedPtr<Peer> peer = _r->topology->getPeer(source());
  61. if (peer) {
  62. // Resume saved state?
  63. if (_step == DECODE_WAITING_FOR_MULTICAST_FRAME_ORIGINAL_SENDER_LOOKUP) {
  64. // In this state we have already authenticated and decrypted the
  65. // packet and are waiting for the lookup of the original sender
  66. // for a multicast frame. So check to see if we've got it.
  67. return _doMULTICAST_FRAME(_r,peer);
  68. }
  69. // No saved state? Verify MAC before we proceed.
  70. if (!hmacVerify(peer->macKey())) {
  71. TRACE("dropped packet from %s(%s), HMAC authentication failed (size: %u)",source().toString().c_str(),_remoteAddress.toString().c_str(),size());
  72. return true;
  73. }
  74. // If MAC authentication passed, decrypt and uncompress
  75. if (encrypted()) {
  76. decrypt(peer->cryptKey());
  77. } else {
  78. // Unencrypted is tolerated in case we want to run this on
  79. // devices where squeezing out cycles matters. HMAC is
  80. // what's really important. But log it in debug to catch any
  81. // packets being mistakenly sent in the clear.
  82. TRACE("ODD: %s from %s(%s) wasn't encrypted",Packet::verbString(verb()),source().toString().c_str(),_remoteAddress.toString().c_str());
  83. }
  84. if (!uncompress()) {
  85. TRACE("dropped packet from %s(%s), compressed data invalid",source().toString().c_str(),_remoteAddress.toString().c_str());
  86. return true;
  87. }
  88. Packet::Verb v = verb();
  89. // Once a packet is determined to be basically valid, it can be used
  90. // to passively learn a new network path to the sending peer. It
  91. // also results in statistics updates.
  92. peer->onReceive(_r,_localPort,_remoteAddress,hops(),v,Utils::now());
  93. switch(v) {
  94. case Packet::VERB_NOP:
  95. TRACE("NOP from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  96. return true;
  97. case Packet::VERB_HELLO:
  98. return _doHELLO(_r); // encrypted HELLO is technically allowed, but kind of pointless... :)
  99. case Packet::VERB_ERROR:
  100. return _doERROR(_r,peer);
  101. case Packet::VERB_OK:
  102. return _doOK(_r,peer);
  103. case Packet::VERB_WHOIS:
  104. return _doWHOIS(_r,peer);
  105. case Packet::VERB_RENDEZVOUS:
  106. return _doRENDEZVOUS(_r,peer);
  107. case Packet::VERB_FRAME:
  108. return _doFRAME(_r,peer);
  109. case Packet::VERB_MULTICAST_LIKE:
  110. return _doMULTICAST_LIKE(_r,peer);
  111. case Packet::VERB_MULTICAST_FRAME:
  112. return _doMULTICAST_FRAME(_r,peer);
  113. case Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE:
  114. return _doNETWORK_MEMBERSHIP_CERTIFICATE(_r,peer);
  115. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  116. return _doNETWORK_CONFIG_REQUEST(_r,peer);
  117. case Packet::VERB_NETWORK_CONFIG_REFRESH:
  118. return _doNETWORK_CONFIG_REFRESH(_r,peer);
  119. default:
  120. // This might be something from a new or old version of the protocol.
  121. // Technically it passed HMAC so the packet is still valid, but we
  122. // ignore it.
  123. TRACE("ignored unrecognized verb %.2x from %s(%s)",(unsigned int)v,source().toString().c_str(),_remoteAddress.toString().c_str());
  124. return true;
  125. }
  126. } else {
  127. _step = DECODE_WAITING_FOR_SENDER_LOOKUP; // should already be this...
  128. _r->sw->requestWhois(source());
  129. return false;
  130. }
  131. }
  132. void PacketDecoder::_CBaddPeerFromHello(void *arg,const SharedPtr<Peer> &p,Topology::PeerVerifyResult result)
  133. {
  134. _CBaddPeerFromHello_Data *req = (_CBaddPeerFromHello_Data *)arg;
  135. const RuntimeEnvironment *_r = req->renv;
  136. try {
  137. switch(result) {
  138. case Topology::PEER_VERIFY_ACCEPTED_NEW:
  139. case Topology::PEER_VERIFY_ACCEPTED_ALREADY_HAVE:
  140. case Topology::PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS: {
  141. _r->sw->doAnythingWaitingForPeer(p);
  142. Packet outp(req->source,_r->identity.address(),Packet::VERB_OK);
  143. outp.append((unsigned char)Packet::VERB_HELLO);
  144. outp.append(req->helloPacketId);
  145. outp.append(req->helloTimestamp);
  146. outp.encrypt(p->cryptKey());
  147. outp.hmacSet(p->macKey());
  148. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  149. } break;
  150. case Topology::PEER_VERIFY_REJECTED_INVALID_IDENTITY: {
  151. Packet outp(req->source,_r->identity.address(),Packet::VERB_ERROR);
  152. outp.append((unsigned char)Packet::VERB_HELLO);
  153. outp.append(req->helloPacketId);
  154. outp.append((unsigned char)Packet::ERROR_IDENTITY_INVALID);
  155. outp.encrypt(p->cryptKey());
  156. outp.hmacSet(p->macKey());
  157. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  158. } break;
  159. case Topology::PEER_VERIFY_REJECTED_DUPLICATE:
  160. case Topology::PEER_VERIFY_REJECTED_DUPLICATE_TRIAGED: {
  161. Packet outp(req->source,_r->identity.address(),Packet::VERB_ERROR);
  162. outp.append((unsigned char)Packet::VERB_HELLO);
  163. outp.append(req->helloPacketId);
  164. outp.append((unsigned char)Packet::ERROR_IDENTITY_COLLISION);
  165. outp.encrypt(p->cryptKey());
  166. outp.hmacSet(p->macKey());
  167. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  168. } break;
  169. }
  170. } catch ( ... ) {
  171. TRACE("unexpected exception in addPeer() result callback for peer received via HELLO");
  172. }
  173. delete req;
  174. }
  175. void PacketDecoder::_CBaddPeerFromWhois(void *arg,const SharedPtr<Peer> &p,Topology::PeerVerifyResult result)
  176. {
  177. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)arg;
  178. try {
  179. switch(result) {
  180. case Topology::PEER_VERIFY_ACCEPTED_NEW:
  181. case Topology::PEER_VERIFY_ACCEPTED_ALREADY_HAVE:
  182. case Topology::PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS:
  183. _r->sw->doAnythingWaitingForPeer(p);
  184. break;
  185. default:
  186. break;
  187. }
  188. } catch ( ... ) {
  189. TRACE("unexpected exception in addPeer() result callback for peer received via OK(WHOIS)");
  190. }
  191. }
  192. bool PacketDecoder::_doERROR(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  193. {
  194. try {
  195. #ifdef ZT_TRACE
  196. Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  197. Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  198. TRACE("ERROR %s from %s(%s) in-re %s",Packet::errorString(errorCode),source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  199. #endif
  200. // TODO (sorta):
  201. // The fact is that the protocol works fine without error handling.
  202. // The only error that really needs to be handled here is duplicate
  203. // identity collision, which if it comes from a supernode should cause
  204. // us to restart and regenerate a new identity.
  205. } catch (std::exception &ex) {
  206. TRACE("dropped ERROR from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  207. } catch ( ... ) {
  208. TRACE("dropped ERROR from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  209. }
  210. return true;
  211. }
  212. bool PacketDecoder::_doHELLO(const RuntimeEnvironment *_r)
  213. {
  214. try {
  215. //unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  216. unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  217. unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  218. unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  219. uint64_t timestamp = at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  220. Identity id(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  221. // Create a new candidate peer that we might decide to add to our
  222. // database. We create it now since we want its keys to send replies
  223. // even in the error case, and the code for keying is in Peer.
  224. SharedPtr<Peer> candidate(new Peer(_r->identity,id));
  225. candidate->setPathAddress(_remoteAddress,false);
  226. // The initial sniff test... is the identity valid, and is it
  227. // the sender's identity?
  228. if ((id.address().isReserved())||(id.address() != source())) {
  229. #ifdef ZT_TRACE
  230. if (id.address().isReserved()) {
  231. TRACE("rejected HELLO from %s(%s): identity has reserved address",source().toString().c_str(),_remoteAddress.toString().c_str());
  232. } else {
  233. TRACE("rejected HELLO from %s(%s): identity is not for sender of packet (HELLO is a self-announcement)",source().toString().c_str(),_remoteAddress.toString().c_str());
  234. }
  235. #endif
  236. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  237. outp.append((unsigned char)Packet::VERB_HELLO);
  238. outp.append(packetId());
  239. outp.append((unsigned char)((id.address().isReserved()) ? Packet::ERROR_IDENTITY_INVALID : Packet::ERROR_INVALID_REQUEST));
  240. outp.encrypt(candidate->cryptKey());
  241. outp.hmacSet(candidate->macKey());
  242. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  243. return true;
  244. }
  245. // Is this a HELLO for a peer we already know? If so just update its
  246. // packet receive stats and send an OK.
  247. SharedPtr<Peer> existingPeer(_r->topology->getPeer(id.address()));
  248. if ((existingPeer)&&(existingPeer->identity() == id)) {
  249. existingPeer->onReceive(_r,_localPort,_remoteAddress,hops(),Packet::VERB_HELLO,Utils::now());
  250. existingPeer->setRemoteVersion(vMajor,vMinor,vRevision);
  251. Packet outp(source(),_r->identity.address(),Packet::VERB_OK);
  252. outp.append((unsigned char)Packet::VERB_HELLO);
  253. outp.append(packetId());
  254. outp.append(timestamp);
  255. outp.encrypt(existingPeer->cryptKey());
  256. outp.hmacSet(existingPeer->macKey());
  257. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  258. return true;
  259. }
  260. // Otherwise we call addPeer() and set up a callback to handle the verdict.
  261. // Topology evaluates the peer in the background, possibly doing the entire
  262. // expensive analysis before determining whether to add it to the database.
  263. _CBaddPeerFromHello_Data *arg = new _CBaddPeerFromHello_Data;
  264. arg->renv = _r;
  265. arg->source = source();
  266. arg->remoteAddress = _remoteAddress;
  267. arg->localPort = _localPort;
  268. arg->vMajor = vMajor;
  269. arg->vMinor = vMinor;
  270. arg->vRevision = vRevision;
  271. arg->helloPacketId = packetId();
  272. arg->helloTimestamp = timestamp;
  273. _r->topology->addPeer(candidate,&PacketDecoder::_CBaddPeerFromHello,arg);
  274. } catch (std::exception &ex) {
  275. TRACE("dropped HELLO from %s(%s): %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  276. } catch ( ... ) {
  277. TRACE("dropped HELLO from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  278. }
  279. return true;
  280. }
  281. bool PacketDecoder::_doOK(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  282. {
  283. try {
  284. Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  285. switch(inReVerb) {
  286. case Packet::VERB_HELLO: {
  287. // OK from HELLO permits computation of latency.
  288. unsigned int latency = std::min((unsigned int)(Utils::now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP)),(unsigned int)0xffff);
  289. TRACE("%s(%s): OK(HELLO), latency: %u",source().toString().c_str(),_remoteAddress.toString().c_str(),latency);
  290. peer->setLatency(_remoteAddress,latency);
  291. } break;
  292. case Packet::VERB_WHOIS: {
  293. TRACE("%s(%s): OK(%s)",source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  294. if (_r->topology->isSupernode(source())) {
  295. // Right now, only supernodes are queried for WHOIS so we only
  296. // accept OK(WHOIS) from supernodes. Otherwise peers could
  297. // potentially cache-poison. A more elegant but memory-intensive
  298. // solution would be to remember packet IDs of WHOIS requests.
  299. _r->topology->addPeer(SharedPtr<Peer>(new Peer(_r->identity,Identity(*this,ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY))),&PacketDecoder::_CBaddPeerFromWhois,const_cast<void *>((const void *)_r));
  300. }
  301. } break;
  302. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  303. SharedPtr<Network> nw(_r->nc->network(at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID)));
  304. if ((nw)&&(nw->controller() == source())) {
  305. // Only accept OK(NETWORK_CONFIG_REQUEST) from masters for
  306. // networks we have.
  307. unsigned int dictlen = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN);
  308. std::string dict((const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT,dictlen),dictlen);
  309. if (dict.length()) {
  310. Network::Config netconf(dict);
  311. if ((netconf.networkId() == nw->id())&&(netconf.peerAddress() == _r->identity.address())) { // sanity check
  312. LOG("got network configuration for network %.16llx from %s",(unsigned long long)nw->id(),source().toString().c_str());
  313. nw->setConfiguration(netconf);
  314. }
  315. }
  316. }
  317. } break;
  318. default:
  319. //TRACE("%s(%s): OK(%s)",source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  320. break;
  321. }
  322. } catch (std::exception &ex) {
  323. TRACE("dropped OK from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  324. } catch ( ... ) {
  325. TRACE("dropped OK from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  326. }
  327. return true;
  328. }
  329. bool PacketDecoder::_doWHOIS(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  330. {
  331. if (payloadLength() == ZT_ADDRESS_LENGTH) {
  332. SharedPtr<Peer> p(_r->topology->getPeer(Address(payload(),ZT_ADDRESS_LENGTH)));
  333. if (p) {
  334. Packet outp(source(),_r->identity.address(),Packet::VERB_OK);
  335. outp.append((unsigned char)Packet::VERB_WHOIS);
  336. outp.append(packetId());
  337. p->identity().serialize(outp,false);
  338. outp.encrypt(peer->cryptKey());
  339. outp.hmacSet(peer->macKey());
  340. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  341. TRACE("sent WHOIS response to %s for %s",source().toString().c_str(),Address(payload(),ZT_ADDRESS_LENGTH).toString().c_str());
  342. } else {
  343. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  344. outp.append((unsigned char)Packet::VERB_WHOIS);
  345. outp.append(packetId());
  346. outp.append((unsigned char)Packet::ERROR_NOT_FOUND);
  347. outp.append(payload(),ZT_ADDRESS_LENGTH);
  348. outp.encrypt(peer->cryptKey());
  349. outp.hmacSet(peer->macKey());
  350. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  351. TRACE("sent WHOIS ERROR to %s for %s (not found)",source().toString().c_str(),Address(payload(),ZT_ADDRESS_LENGTH).toString().c_str());
  352. }
  353. } else {
  354. TRACE("dropped WHOIS from %s(%s): missing or invalid address",source().toString().c_str(),_remoteAddress.toString().c_str());
  355. }
  356. return true;
  357. }
  358. bool PacketDecoder::_doRENDEZVOUS(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  359. {
  360. try {
  361. /*
  362. * At the moment, we only obey RENDEZVOUS if it comes from a designated
  363. * supernode. If relay offloading is implemented to scale the net, this
  364. * will need reconsideration.
  365. *
  366. * The reason is that RENDEZVOUS could technically be used to cause a
  367. * peer to send a weird encrypted UDP packet to an arbitrary IP:port.
  368. * The sender of RENDEZVOUS has no control over the content of this
  369. * packet, but it's still maybe something we want to not allow just
  370. * anyone to order due to possible DDOS or network forensic implications.
  371. * So if we diversify relays, we'll need some way of deciding whether the
  372. * sender is someone we should trust with a RENDEZVOUS hint. Or maybe
  373. * we just need rate limiting to prevent DDOS and amplification attacks.
  374. */
  375. if (_r->topology->isSupernode(source())) {
  376. Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  377. SharedPtr<Peer> withPeer(_r->topology->getPeer(with));
  378. if (withPeer) {
  379. unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  380. unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  381. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  382. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  383. TRACE("RENDEZVOUS from %s says %s might be at %s, starting NAT-t",source().toString().c_str(),with.toString().c_str(),atAddr.toString().c_str());
  384. _r->sw->contact(withPeer,atAddr);
  385. } else {
  386. TRACE("dropped corrupt RENDEZVOUS from %s(%s) (bad address or port)",source().toString().c_str(),_remoteAddress.toString().c_str());
  387. }
  388. } else {
  389. TRACE("ignored RENDEZVOUS from %s(%s) to meet unknown peer %s",source().toString().c_str(),_remoteAddress.toString().c_str(),with.toString().c_str());
  390. }
  391. } else {
  392. TRACE("ignored RENDEZVOUS from %s(%s): source not supernode",source().toString().c_str(),_remoteAddress.toString().c_str());
  393. }
  394. } catch (std::exception &ex) {
  395. TRACE("dropped RENDEZVOUS from %s(%s): %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  396. } catch ( ... ) {
  397. TRACE("dropped RENDEZVOUS from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  398. }
  399. return true;
  400. }
  401. bool PacketDecoder::_doFRAME(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  402. {
  403. try {
  404. SharedPtr<Network> network(_r->nc->network(at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID)));
  405. if (network) {
  406. if (network->isAllowed(source())) {
  407. unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  408. if ((etherType != ZT_ETHERTYPE_ARP)&&(etherType != ZT_ETHERTYPE_IPV4)&&(etherType != ZT_ETHERTYPE_IPV6)) {
  409. TRACE("dropped FRAME from %s: unsupported ethertype",source().toString().c_str());
  410. } else if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  411. network->tap().put(source().toMAC(),network->tap().mac(),etherType,data() + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD,size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD);
  412. }
  413. } else {
  414. TRACE("dropped FRAME from %s(%s): not a member of closed network %llu",source().toString().c_str(),_remoteAddress.toString().c_str(),network->id());
  415. }
  416. } else {
  417. TRACE("dropped FRAME from %s(%s): network %llu unknown",source().toString().c_str(),_remoteAddress.toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID));
  418. }
  419. } catch (std::exception &ex) {
  420. TRACE("dropped FRAME from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  421. } catch ( ... ) {
  422. TRACE("dropped FRAME from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  423. }
  424. return true;
  425. }
  426. bool PacketDecoder::_doMULTICAST_LIKE(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  427. {
  428. try {
  429. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  430. unsigned int numAccepted = 0;
  431. uint64_t now = Utils::now();
  432. // Iterate through 18-byte network,MAC,ADI tuples:
  433. while ((ptr + 18) <= size()) {
  434. uint64_t nwid = at<uint64_t>(ptr); ptr += 8;
  435. SharedPtr<Network> network(_r->nc->network(nwid));
  436. if ((network)&&(network->isAllowed(source()))) {
  437. MAC mac(field(ptr,6)); ptr += 6;
  438. uint32_t adi = at<uint32_t>(ptr); ptr += 4;
  439. //TRACE("peer %s likes multicast group %s:%.8lx on network %llu",source().toString().c_str(),mac.toString().c_str(),(unsigned long)adi,nwid);
  440. _r->multicaster->likesMulticastGroup(nwid,MulticastGroup(mac,adi),source(),now);
  441. ++numAccepted;
  442. } else {
  443. ptr += 10;
  444. TRACE("ignored MULTICAST_LIKE from %s(%s): network %.16llx unknown, or sender is not a member of network",source().toString().c_str(),_remoteAddress.toString().c_str(),(unsigned long long)nwid);
  445. }
  446. }
  447. Packet outp(source(),_r->identity.address(),Packet::VERB_OK);
  448. outp.append((unsigned char)Packet::VERB_MULTICAST_LIKE);
  449. outp.append(packetId());
  450. outp.append((uint16_t)numAccepted);
  451. outp.encrypt(peer->cryptKey());
  452. outp.hmacSet(peer->macKey());
  453. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  454. } catch (std::exception &ex) {
  455. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  456. } catch ( ... ) {
  457. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  458. }
  459. return true;
  460. }
  461. bool PacketDecoder::_doMULTICAST_FRAME(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  462. {
  463. try {
  464. SharedPtr<Network> network(_r->nc->network(at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID)));
  465. if (network) {
  466. if (network->isAllowed(source())) {
  467. if (size() > ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD) {
  468. Address originalSubmitterAddress(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SUBMITTER_ADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  469. MAC fromMac(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6));
  470. MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DESTINATION_MAC,6)),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ADI));
  471. unsigned int hops = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_HOP_COUNT];
  472. unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  473. unsigned int datalen = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD_LENGTH);
  474. unsigned int signaturelen = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SIGNATURE_LENGTH);
  475. unsigned char *dataAndSignature = field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD,datalen + signaturelen);
  476. uint64_t mccrc = Multicaster::computeMulticastDedupCrc(network->id(),fromMac,mg,etherType,dataAndSignature,datalen);
  477. uint64_t now = Utils::now();
  478. bool isDuplicate = _r->multicaster->checkDuplicate(mccrc,now);
  479. if (originalSubmitterAddress == _r->identity.address()) {
  480. // Technically should not happen, since the original submitter is
  481. // excluded from consideration as a propagation recipient.
  482. TRACE("dropped boomerang MULTICAST_FRAME received from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  483. } else if ((!isDuplicate)||(_r->topology->amSupernode())) {
  484. //
  485. // If I am a supernode, I will repeatedly propagate duplicates. That's
  486. // because supernodes are used to bridge sparse multicast groups. Non-
  487. // supernodes will ignore duplicates completely.
  488. //
  489. // TODO: supernodes should keep a local bloom filter too and OR it with
  490. // the bloom from the packet in order to pick different recipients each
  491. // time a multicast returns to them for repropagation.
  492. //
  493. SharedPtr<Peer> originalSubmitter(_r->topology->getPeer(originalSubmitterAddress));
  494. if (!originalSubmitter) {
  495. TRACE("requesting WHOIS on original multicast frame submitter %s",originalSubmitterAddress.toString().c_str());
  496. _r->sw->requestWhois(originalSubmitterAddress);
  497. _step = DECODE_WAITING_FOR_MULTICAST_FRAME_ORIGINAL_SENDER_LOOKUP;
  498. return false; // try again if/when we get OK(WHOIS)
  499. } else if (Multicaster::verifyMulticastPacket(originalSubmitter->identity(),network->id(),fromMac,mg,etherType,dataAndSignature,datalen,dataAndSignature + datalen,signaturelen)) {
  500. _r->multicaster->addToDedupHistory(mccrc,now);
  501. // Even if we are a supernode, we still don't repeatedly inject
  502. // duplicates into our own tap.
  503. if (!isDuplicate)
  504. network->tap().put(fromMac,mg.mac(),etherType,dataAndSignature,datalen);
  505. if (++hops < ZT_MULTICAST_PROPAGATION_DEPTH) {
  506. Address upstream(source()); // save this since we mangle it
  507. Multicaster::MulticastBloomFilter bloom(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_BLOOM_FILTER,ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES));
  508. SharedPtr<Peer> propPeers[ZT_MULTICAST_PROPAGATION_BREADTH];
  509. unsigned int np = _r->multicaster->pickNextPropagationPeers(
  510. *(_r->prng),
  511. *(_r->topology),
  512. network->id(),
  513. mg,
  514. originalSubmitterAddress,
  515. upstream,
  516. bloom,
  517. ZT_MULTICAST_PROPAGATION_BREADTH,
  518. propPeers,
  519. now);
  520. // In a bit of a hack, we re-use this packet to repeat it
  521. // to our multicast propagation recipients. Afterwords we
  522. // return true just to be sure this is the end of this
  523. // packet's life cycle, since it is now mangled.
  524. setSource(_r->identity.address());
  525. (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_HOP_COUNT] = hops;
  526. memcpy(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_BLOOM_FILTER,ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES),bloom.data(),ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES);
  527. compress();
  528. for(unsigned int i=0;i<np;++i) {
  529. //TRACE("propagating multicast from original node %s: %s -> %s",originalSubmitterAddress.toString().c_str(),upstream.toString().c_str(),propPeers[i]->address().toString().c_str());
  530. // Re-use this packet to re-send multicast frame to everyone
  531. // downstream from us.
  532. newInitializationVector();
  533. setDestination(propPeers[i]->address());
  534. _r->sw->send(*this,true);
  535. }
  536. return true;
  537. } else {
  538. //TRACE("terminating MULTICAST_FRAME propagation from %s(%s): max depth reached",source().toString().c_str(),_remoteAddress.toString().c_str());
  539. }
  540. } else {
  541. LOG("rejected MULTICAST_FRAME from %s(%s) due to failed signature check (falsely claims origin %s)",source().toString().c_str(),_remoteAddress.toString().c_str(),originalSubmitterAddress.toString().c_str());
  542. }
  543. } else {
  544. TRACE("dropped redundant MULTICAST_FRAME from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  545. }
  546. } else {
  547. TRACE("dropped MULTICAST_FRAME from %s(%s): invalid short packet",source().toString().c_str(),_remoteAddress.toString().c_str());
  548. }
  549. } else {
  550. TRACE("dropped MULTICAST_FRAME from %s(%s): not a member of closed network %llu",source().toString().c_str(),_remoteAddress.toString().c_str(),network->id());
  551. }
  552. } else {
  553. TRACE("dropped MULTICAST_FRAME from %s(%s): network %llu unknown or we are not a member",source().toString().c_str(),_remoteAddress.toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID));
  554. }
  555. } catch (std::exception &ex) {
  556. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  557. } catch ( ... ) {
  558. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  559. }
  560. return true;
  561. }
  562. bool PacketDecoder::_doNETWORK_MEMBERSHIP_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  563. {
  564. // TODO: not implemented yet, will be needed for private networks.
  565. return true;
  566. }
  567. bool PacketDecoder::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  568. {
  569. char tmp[128];
  570. try {
  571. uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  572. #ifndef __WINDOWS__
  573. if (_r->netconfService) {
  574. unsigned int dictLen = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN);
  575. Dictionary request;
  576. if (dictLen)
  577. request["meta"] = std::string((const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,dictLen),dictLen);
  578. request["type"] = "netconf-request";
  579. request["peerId"] = peer->identity().toString(false);
  580. sprintf(tmp,"%llx",(unsigned long long)nwid);
  581. request["nwid"] = tmp;
  582. sprintf(tmp,"%llx",(unsigned long long)packetId());
  583. request["requestId"] = tmp;
  584. //TRACE("to netconf:\n%s",request.toString().c_str());
  585. _r->netconfService->send(request);
  586. } else {
  587. #endif // !__WINDOWS__
  588. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  589. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  590. outp.append(packetId());
  591. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  592. outp.append(nwid);
  593. outp.encrypt(peer->cryptKey());
  594. outp.hmacSet(peer->macKey());
  595. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  596. #ifndef __WINDOWS__
  597. }
  598. #endif // !__WINDOWS__
  599. } catch (std::exception &exc) {
  600. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
  601. } catch ( ... ) {
  602. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  603. }
  604. return true;
  605. }
  606. bool PacketDecoder::_doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  607. {
  608. try {
  609. uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REFRESH_IDX_NETWORK_ID);
  610. SharedPtr<Network> nw(_r->nc->network(nwid));
  611. if ((nw)&&(source() == nw->controller())) // only respond to requests from controller
  612. nw->requestConfiguration();
  613. } catch (std::exception &exc) {
  614. TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
  615. } catch ( ... ) {
  616. TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  617. }
  618. return true;
  619. }
  620. } // namespace ZeroTier