PacketDecoder.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. Sometimes it also makes code more explicit and thus
  48. * easier to understand.
  49. */
  50. namespace ZeroTier {
  51. bool PacketDecoder::tryDecode(const RuntimeEnvironment *_r)
  52. throw(std::out_of_range,std::runtime_error)
  53. {
  54. if ((!encrypted())&&(verb() == Packet::VERB_HELLO)) {
  55. // Unencrypted HELLOs are handled here since they are used to
  56. // populate our identity cache in the first place. Thus we might get
  57. // a HELLO for someone for whom we don't have a Peer record.
  58. TRACE("HELLO from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  59. return _doHELLO(_r);
  60. }
  61. SharedPtr<Peer> peer = _r->topology->getPeer(source());
  62. if (peer) {
  63. // Resume saved state?
  64. if (_step == DECODE_WAITING_FOR_MULTICAST_FRAME_ORIGINAL_SENDER_LOOKUP) {
  65. // In this state we have already authenticated and decrypted the
  66. // packet and are waiting for the lookup of the original sender
  67. // for a multicast frame. So check to see if we've got it.
  68. return _doMULTICAST_FRAME(_r,peer);
  69. }
  70. // No saved state? Verify MAC before we proceed.
  71. if (!hmacVerify(peer->macKey())) {
  72. TRACE("dropped packet from %s(%s), HMAC authentication failed (size: %u)",source().toString().c_str(),_remoteAddress.toString().c_str(),size());
  73. return true;
  74. }
  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. switch(result) {
  137. case Topology::PEER_VERIFY_ACCEPTED_NEW:
  138. case Topology::PEER_VERIFY_ACCEPTED_ALREADY_HAVE:
  139. case Topology::PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS: {
  140. _r->sw->doAnythingWaitingForPeer(p);
  141. Packet outp(req->source,_r->identity.address(),Packet::VERB_OK);
  142. outp.append((unsigned char)Packet::VERB_HELLO);
  143. outp.append(req->helloPacketId);
  144. outp.append(req->helloTimestamp);
  145. outp.encrypt(p->cryptKey());
  146. outp.hmacSet(p->macKey());
  147. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  148. } break;
  149. case Topology::PEER_VERIFY_REJECTED_INVALID_IDENTITY: {
  150. Packet outp(req->source,_r->identity.address(),Packet::VERB_ERROR);
  151. outp.append((unsigned char)Packet::VERB_HELLO);
  152. outp.append(req->helloPacketId);
  153. outp.append((unsigned char)Packet::ERROR_IDENTITY_INVALID);
  154. outp.encrypt(p->cryptKey());
  155. outp.hmacSet(p->macKey());
  156. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  157. } break;
  158. case Topology::PEER_VERIFY_REJECTED_DUPLICATE:
  159. case Topology::PEER_VERIFY_REJECTED_DUPLICATE_TRIAGED: {
  160. Packet outp(req->source,_r->identity.address(),Packet::VERB_ERROR);
  161. outp.append((unsigned char)Packet::VERB_HELLO);
  162. outp.append(req->helloPacketId);
  163. outp.append((unsigned char)Packet::ERROR_IDENTITY_COLLISION);
  164. outp.encrypt(p->cryptKey());
  165. outp.hmacSet(p->macKey());
  166. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  167. } break;
  168. }
  169. delete req;
  170. }
  171. void PacketDecoder::_CBaddPeerFromWhois(void *arg,const SharedPtr<Peer> &p,Topology::PeerVerifyResult result)
  172. {
  173. switch(result) {
  174. case Topology::PEER_VERIFY_ACCEPTED_NEW:
  175. case Topology::PEER_VERIFY_ACCEPTED_ALREADY_HAVE:
  176. case Topology::PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS:
  177. ((const RuntimeEnvironment *)arg)->sw->doAnythingWaitingForPeer(p);
  178. break;
  179. default:
  180. break;
  181. }
  182. }
  183. bool PacketDecoder::_doERROR(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  184. {
  185. try {
  186. #ifdef ZT_TRACE
  187. Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  188. Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  189. TRACE("ERROR %s from %s(%s) in-re %s",Packet::errorString(errorCode),source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  190. #endif
  191. // TODO (sorta):
  192. // The fact is that the protocol works fine without error handling.
  193. // The only error that really needs to be handled here is duplicate
  194. // identity collision, which if it comes from a supernode should cause
  195. // us to restart and regenerate a new identity.
  196. } catch (std::exception &ex) {
  197. TRACE("dropped ERROR from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  198. } catch ( ... ) {
  199. TRACE("dropped ERROR from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  200. }
  201. return true;
  202. }
  203. bool PacketDecoder::_doHELLO(const RuntimeEnvironment *_r)
  204. {
  205. try {
  206. //unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  207. unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  208. unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  209. unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  210. uint64_t timestamp = at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  211. Identity id(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  212. // Create a new candidate peer that we might decide to add to our
  213. // database. We create it now since we want its keys to send replies
  214. // even in the error case, and the code for keying is in Peer.
  215. SharedPtr<Peer> candidate(new Peer(_r->identity,id));
  216. candidate->setPathAddress(_remoteAddress,false);
  217. // The initial sniff test... is the identity valid, and is it
  218. // the sender's identity?
  219. if ((id.address().isReserved())||(id.address() != source())) {
  220. #ifdef ZT_TRACE
  221. if (id.address().isReserved()) {
  222. TRACE("rejected HELLO from %s(%s): identity has reserved address",source().toString().c_str(),_remoteAddress.toString().c_str());
  223. } else {
  224. 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());
  225. }
  226. #endif
  227. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  228. outp.append((unsigned char)Packet::VERB_HELLO);
  229. outp.append(packetId());
  230. outp.append((unsigned char)((id.address().isReserved()) ? Packet::ERROR_IDENTITY_INVALID : Packet::ERROR_INVALID_REQUEST));
  231. outp.encrypt(candidate->cryptKey());
  232. outp.hmacSet(candidate->macKey());
  233. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  234. return true;
  235. }
  236. // Is this a HELLO for a peer we already know? If so just update its
  237. // packet receive stats and send an OK.
  238. SharedPtr<Peer> existingPeer(_r->topology->getPeer(id.address()));
  239. if ((existingPeer)&&(existingPeer->identity() == id)) {
  240. existingPeer->onReceive(_r,_localPort,_remoteAddress,hops(),Packet::VERB_HELLO,Utils::now());
  241. existingPeer->setRemoteVersion(vMajor,vMinor,vRevision);
  242. Packet outp(source(),_r->identity.address(),Packet::VERB_OK);
  243. outp.append((unsigned char)Packet::VERB_HELLO);
  244. outp.append(packetId());
  245. outp.append(timestamp);
  246. outp.encrypt(existingPeer->cryptKey());
  247. outp.hmacSet(existingPeer->macKey());
  248. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  249. return true;
  250. }
  251. // Otherwise we call addPeer() and set up a callback to handle the verdict.
  252. // Topology evaluates the peer in the background, possibly doing the entire
  253. // expensive analysis before determining whether to add it to the database.
  254. _CBaddPeerFromHello_Data *arg = new _CBaddPeerFromHello_Data;
  255. arg->renv = _r;
  256. arg->source = source();
  257. arg->remoteAddress = _remoteAddress;
  258. arg->localPort = _localPort;
  259. arg->vMajor = vMajor;
  260. arg->vMinor = vMinor;
  261. arg->vRevision = vRevision;
  262. arg->helloPacketId = packetId();
  263. arg->helloTimestamp = timestamp;
  264. _r->topology->addPeer(candidate,&PacketDecoder::_CBaddPeerFromHello,arg);
  265. } catch (std::exception &ex) {
  266. TRACE("dropped HELLO from %s(%s): %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  267. } catch ( ... ) {
  268. TRACE("dropped HELLO from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  269. }
  270. return true;
  271. }
  272. bool PacketDecoder::_doOK(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  273. {
  274. try {
  275. Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  276. switch(inReVerb) {
  277. case Packet::VERB_HELLO: {
  278. // OK from HELLO permits computation of latency.
  279. unsigned int latency = std::min((unsigned int)(Utils::now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP)),(unsigned int)0xffff);
  280. TRACE("%s(%s): OK(HELLO), latency: %u",source().toString().c_str(),_remoteAddress.toString().c_str(),latency);
  281. peer->setLatency(_remoteAddress,latency);
  282. } break;
  283. case Packet::VERB_WHOIS: {
  284. TRACE("%s(%s): OK(%s)",source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  285. if (_r->topology->isSupernode(source())) {
  286. // Right now, only supernodes are queried for WHOIS so we only
  287. // accept OK(WHOIS) from supernodes. Otherwise peers could
  288. // potentially cache-poison. A more elegant but memory-intensive
  289. // solution would be to remember packet IDs of WHOIS requests.
  290. _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));
  291. }
  292. } break;
  293. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  294. SharedPtr<Network> nw(_r->nc->network(at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID)));
  295. if ((nw)&&(nw->controller() == source())) {
  296. // Only accept OK(NETWORK_CONFIG_REQUEST) from masters for
  297. // networks we have.
  298. unsigned int dictlen = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN);
  299. std::string dict((const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT,dictlen),dictlen);
  300. if (dict.length()) {
  301. Network::Config netconf(dict);
  302. if ((netconf.networkId() == nw->id())&&(netconf.peerAddress() == _r->identity.address())) { // sanity check
  303. LOG("got network configuration for network %.16llx from %s",(unsigned long long)nw->id(),source().toString().c_str());
  304. nw->setConfiguration(netconf);
  305. }
  306. }
  307. }
  308. } break;
  309. default:
  310. //TRACE("%s(%s): OK(%s)",source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  311. break;
  312. }
  313. } catch (std::exception &ex) {
  314. TRACE("dropped OK from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  315. } catch ( ... ) {
  316. TRACE("dropped OK from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  317. }
  318. return true;
  319. }
  320. bool PacketDecoder::_doWHOIS(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  321. {
  322. if (payloadLength() == ZT_ADDRESS_LENGTH) {
  323. SharedPtr<Peer> p(_r->topology->getPeer(Address(payload(),ZT_ADDRESS_LENGTH)));
  324. if (p) {
  325. Packet outp(source(),_r->identity.address(),Packet::VERB_OK);
  326. outp.append((unsigned char)Packet::VERB_WHOIS);
  327. outp.append(packetId());
  328. p->identity().serialize(outp,false);
  329. outp.encrypt(peer->cryptKey());
  330. outp.hmacSet(peer->macKey());
  331. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  332. TRACE("sent WHOIS response to %s for %s",source().toString().c_str(),Address(payload(),ZT_ADDRESS_LENGTH).toString().c_str());
  333. } else {
  334. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  335. outp.append((unsigned char)Packet::VERB_WHOIS);
  336. outp.append(packetId());
  337. outp.append((unsigned char)Packet::ERROR_NOT_FOUND);
  338. outp.append(payload(),ZT_ADDRESS_LENGTH);
  339. outp.encrypt(peer->cryptKey());
  340. outp.hmacSet(peer->macKey());
  341. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  342. TRACE("sent WHOIS ERROR to %s for %s (not found)",source().toString().c_str(),Address(payload(),ZT_ADDRESS_LENGTH).toString().c_str());
  343. }
  344. } else {
  345. TRACE("dropped WHOIS from %s(%s): missing or invalid address",source().toString().c_str(),_remoteAddress.toString().c_str());
  346. }
  347. return true;
  348. }
  349. bool PacketDecoder::_doRENDEZVOUS(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  350. {
  351. try {
  352. //
  353. // At the moment, we only obey RENDEZVOUS if it comes from a designated
  354. // supernode. If relay offloading is implemented to scale the net, this
  355. // will need reconsideration.
  356. //
  357. // The reason is that RENDEZVOUS could technically be used to cause a
  358. // peer to send a weird encrypted UDP packet to an arbitrary IP:port.
  359. // The sender of RENDEZVOUS has no control over the content of this
  360. // packet, but it's still maybe something we want to not allow just
  361. // anyone to order due to possible DDOS or network forensic implications.
  362. // So if we diversify relays, we'll need some way of deciding whether the
  363. // sender is someone we should trust with a RENDEZVOUS hint. Or maybe
  364. // we just need rate limiting to prevent DDOS and amplification attacks.
  365. //
  366. if (_r->topology->isSupernode(source())) {
  367. Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  368. SharedPtr<Peer> withPeer(_r->topology->getPeer(with));
  369. if (withPeer) {
  370. unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  371. unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  372. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  373. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  374. 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());
  375. _r->sw->contact(withPeer,atAddr);
  376. } else {
  377. TRACE("dropped corrupt RENDEZVOUS from %s(%s) (bad address or port)",source().toString().c_str(),_remoteAddress.toString().c_str());
  378. }
  379. } else {
  380. TRACE("ignored RENDEZVOUS from %s(%s) to meet unknown peer %s",source().toString().c_str(),_remoteAddress.toString().c_str(),with.toString().c_str());
  381. }
  382. } else {
  383. TRACE("ignored RENDEZVOUS from %s(%s): source not supernode",source().toString().c_str(),_remoteAddress.toString().c_str());
  384. }
  385. } catch (std::exception &ex) {
  386. TRACE("dropped RENDEZVOUS from %s(%s): %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  387. } catch ( ... ) {
  388. TRACE("dropped RENDEZVOUS from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  389. }
  390. return true;
  391. }
  392. bool PacketDecoder::_doFRAME(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  393. {
  394. try {
  395. SharedPtr<Network> network(_r->nc->network(at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID)));
  396. if (network) {
  397. if (network->isAllowed(source())) {
  398. unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  399. if ((etherType != ZT_ETHERTYPE_ARP)&&(etherType != ZT_ETHERTYPE_IPV4)&&(etherType != ZT_ETHERTYPE_IPV6)) {
  400. TRACE("dropped FRAME from %s: unsupported ethertype",source().toString().c_str());
  401. } else if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  402. network->tap().put(source().toMAC(),network->tap().mac(),etherType,data() + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD,size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD);
  403. }
  404. } else {
  405. TRACE("dropped FRAME from %s(%s): not a member of closed network %llu",source().toString().c_str(),_remoteAddress.toString().c_str(),network->id());
  406. }
  407. } else {
  408. 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));
  409. }
  410. } catch (std::exception &ex) {
  411. TRACE("dropped FRAME from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  412. } catch ( ... ) {
  413. TRACE("dropped FRAME from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  414. }
  415. return true;
  416. }
  417. bool PacketDecoder::_doMULTICAST_LIKE(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  418. {
  419. try {
  420. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  421. unsigned int numAccepted = 0;
  422. uint64_t now = Utils::now();
  423. // Iterate through 18-byte network,MAC,ADI tuples:
  424. while ((ptr + 18) <= size()) {
  425. uint64_t nwid = at<uint64_t>(ptr); ptr += 8;
  426. SharedPtr<Network> network(_r->nc->network(nwid));
  427. if (network) {
  428. if (network->isAllowed(source())) {
  429. MAC mac(field(ptr,6)); ptr += 6;
  430. uint32_t adi = at<uint32_t>(ptr); ptr += 4;
  431. //TRACE("peer %s likes multicast group %s:%.8lx on network %llu",source().toString().c_str(),mac.toString().c_str(),(unsigned long)adi,nwid);
  432. _r->multicaster->likesMulticastGroup(nwid,MulticastGroup(mac,adi),source(),now);
  433. ++numAccepted;
  434. } else {
  435. TRACE("ignored MULTICAST_LIKE from %s(%s): not a member of closed network %llu",source().toString().c_str(),_remoteAddress.toString().c_str(),nwid);
  436. }
  437. } else {
  438. TRACE("ignored MULTICAST_LIKE from %s(%s): network %llu unknown or we are not a member",source().toString().c_str(),_remoteAddress.toString().c_str(),nwid);
  439. }
  440. }
  441. Packet outp(source(),_r->identity.address(),Packet::VERB_OK);
  442. outp.append((unsigned char)Packet::VERB_MULTICAST_LIKE);
  443. outp.append(packetId());
  444. outp.append((uint16_t)numAccepted);
  445. outp.encrypt(peer->cryptKey());
  446. outp.hmacSet(peer->macKey());
  447. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  448. } catch (std::exception &ex) {
  449. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  450. } catch ( ... ) {
  451. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  452. }
  453. return true;
  454. }
  455. bool PacketDecoder::_doMULTICAST_FRAME(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  456. {
  457. try {
  458. SharedPtr<Network> network(_r->nc->network(at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID)));
  459. if (network) {
  460. if (network->isAllowed(source())) {
  461. if (size() > ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD) {
  462. Address originalSubmitterAddress(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SUBMITTER_ADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  463. MAC fromMac(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6));
  464. MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DESTINATION_MAC,6)),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ADI));
  465. unsigned int hops = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_HOP_COUNT];
  466. unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  467. unsigned int datalen = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD_LENGTH);
  468. unsigned int signaturelen = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SIGNATURE_LENGTH);
  469. unsigned char *dataAndSignature = field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PAYLOAD,datalen + signaturelen);
  470. uint64_t mccrc = Multicaster::computeMulticastDedupCrc(network->id(),fromMac,mg,etherType,dataAndSignature,datalen);
  471. uint64_t now = Utils::now();
  472. bool isDuplicate = _r->multicaster->checkDuplicate(mccrc,now);
  473. if (originalSubmitterAddress == _r->identity.address()) {
  474. // Technically should not happen, since the original submitter is
  475. // excluded from consideration as a propagation recipient.
  476. TRACE("dropped boomerang MULTICAST_FRAME received from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  477. } else if ((!isDuplicate)||(_r->topology->amSupernode())) {
  478. //
  479. // If I am a supernode, I will repeatedly propagate duplicates. That's
  480. // because supernodes are used to bridge sparse multicast groups. Non-
  481. // supernodes will ignore duplicates completely.
  482. //
  483. // TODO: supernodes should keep a local bloom filter too and OR it with
  484. // the bloom from the packet in order to pick different recipients each
  485. // time a multicast returns to them for repropagation.
  486. //
  487. SharedPtr<Peer> originalSubmitter(_r->topology->getPeer(originalSubmitterAddress));
  488. if (!originalSubmitter) {
  489. TRACE("requesting WHOIS on original multicast frame submitter %s",originalSubmitterAddress.toString().c_str());
  490. _r->sw->requestWhois(originalSubmitterAddress);
  491. _step = DECODE_WAITING_FOR_MULTICAST_FRAME_ORIGINAL_SENDER_LOOKUP;
  492. return false; // try again if/when we get OK(WHOIS)
  493. } else if (Multicaster::verifyMulticastPacket(originalSubmitter->identity(),network->id(),fromMac,mg,etherType,dataAndSignature,datalen,dataAndSignature + datalen,signaturelen)) {
  494. _r->multicaster->addToDedupHistory(mccrc,now);
  495. // Even if we are a supernode, we still don't repeatedly inject
  496. // duplicates into our own tap.
  497. if (!isDuplicate)
  498. network->tap().put(fromMac,mg.mac(),etherType,dataAndSignature,datalen);
  499. if (++hops < ZT_MULTICAST_PROPAGATION_DEPTH) {
  500. Address upstream(source()); // save this since we mangle it
  501. Multicaster::MulticastBloomFilter bloom(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_BLOOM_FILTER,ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BYTES));
  502. SharedPtr<Peer> propPeers[ZT_MULTICAST_PROPAGATION_BREADTH];
  503. unsigned int np = _r->multicaster->pickNextPropagationPeers(
  504. *(_r->prng),
  505. *(_r->topology),
  506. network->id(),
  507. mg,
  508. originalSubmitterAddress,
  509. upstream,
  510. bloom,
  511. ZT_MULTICAST_PROPAGATION_BREADTH,
  512. propPeers,
  513. now);
  514. // In a bit of a hack, we re-use this packet to repeat it
  515. // to our multicast propagation recipients. Afterwords we
  516. // return true just to be sure this is the end of this
  517. // packet's life cycle, since it is now mangled.
  518. setSource(_r->identity.address());
  519. (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_HOP_COUNT] = hops;
  520. 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);
  521. compress();
  522. for(unsigned int i=0;i<np;++i) {
  523. //TRACE("propagating multicast from original node %s: %s -> %s",originalSubmitterAddress.toString().c_str(),upstream.toString().c_str(),propPeers[i]->address().toString().c_str());
  524. // Re-use this packet to re-send multicast frame to everyone
  525. // downstream from us.
  526. newInitializationVector();
  527. setDestination(propPeers[i]->address());
  528. _r->sw->send(*this,true);
  529. }
  530. return true;
  531. } else {
  532. //TRACE("terminating MULTICAST_FRAME propagation from %s(%s): max depth reached",source().toString().c_str(),_remoteAddress.toString().c_str());
  533. }
  534. } else {
  535. 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());
  536. }
  537. } else {
  538. TRACE("dropped redundant MULTICAST_FRAME from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  539. }
  540. } else {
  541. TRACE("dropped MULTICAST_FRAME from %s(%s): invalid short packet",source().toString().c_str(),_remoteAddress.toString().c_str());
  542. }
  543. } else {
  544. TRACE("dropped MULTICAST_FRAME from %s(%s): not a member of closed network %llu",source().toString().c_str(),_remoteAddress.toString().c_str(),network->id());
  545. }
  546. } else {
  547. 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));
  548. }
  549. } catch (std::exception &ex) {
  550. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  551. } catch ( ... ) {
  552. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  553. }
  554. return true;
  555. }
  556. bool PacketDecoder::_doNETWORK_MEMBERSHIP_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  557. {
  558. // TODO: not implemented yet, will be needed for private networks.
  559. return true;
  560. }
  561. bool PacketDecoder::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  562. {
  563. char tmp[128];
  564. try {
  565. uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  566. #ifndef __WINDOWS__
  567. if (_r->netconfService) {
  568. unsigned int dictLen = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN);
  569. Dictionary request;
  570. if (dictLen)
  571. request["meta"] = std::string((const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,dictLen),dictLen);
  572. request["type"] = "netconf-request";
  573. request["peerId"] = peer->identity().toString(false);
  574. sprintf(tmp,"%llx",(unsigned long long)nwid);
  575. request["nwid"] = tmp;
  576. sprintf(tmp,"%llx",(unsigned long long)packetId());
  577. request["requestId"] = tmp;
  578. _r->netconfService->send(request);
  579. } else {
  580. #endif // !__WINDOWS__
  581. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  582. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  583. outp.append(packetId());
  584. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  585. outp.append(nwid);
  586. outp.encrypt(peer->cryptKey());
  587. outp.hmacSet(peer->macKey());
  588. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  589. TRACE("sent ERROR(NETWORK_CONFIG_REQUEST,UNSUPPORTED_OPERATION) to %s(%s)",peer->address().toString().c_str(),_remoteAddress.toString().c_str());
  590. #ifndef __WINDOWS__
  591. }
  592. #endif // !__WINDOWS__
  593. } catch (std::exception &exc) {
  594. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
  595. } catch ( ... ) {
  596. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  597. }
  598. return true;
  599. }
  600. bool PacketDecoder::_doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  601. {
  602. try {
  603. uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REFRESH_IDX_NETWORK_ID);
  604. SharedPtr<Network> nw(_r->nc->network(nwid));
  605. if ((nw)&&(source() == nw->controller())) // only respond to requests from controller
  606. nw->requestConfiguration();
  607. } catch (std::exception &exc) {
  608. TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
  609. } catch ( ... ) {
  610. TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  611. }
  612. return true;
  613. }
  614. } // namespace ZeroTier