PacketDecoder.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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 "../version.h"
  28. #include "Constants.hpp"
  29. #include "RuntimeEnvironment.hpp"
  30. #include "Topology.hpp"
  31. #include "PacketDecoder.hpp"
  32. #include "Switch.hpp"
  33. #include "Peer.hpp"
  34. #include "NodeConfig.hpp"
  35. #include "Filter.hpp"
  36. #include "Service.hpp"
  37. namespace ZeroTier {
  38. bool PacketDecoder::tryDecode(const RuntimeEnvironment *_r)
  39. throw(std::out_of_range,std::runtime_error)
  40. {
  41. if ((!encrypted())&&(verb() == Packet::VERB_HELLO)) {
  42. // Unencrypted HELLOs are handled here since they are used to
  43. // populate our identity cache in the first place. _doHELLO() is special
  44. // in that it contains its own authentication logic.
  45. TRACE("HELLO from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  46. return _doHELLO(_r);
  47. }
  48. SharedPtr<Peer> peer = _r->topology->getPeer(source());
  49. if (peer) {
  50. // Resume saved intermediate decode state?
  51. if (_step == DECODE_WAITING_FOR_MULTICAST_FRAME_ORIGINAL_SENDER_LOOKUP) {
  52. // In this state we have already authenticated and decrypted the
  53. // packet and are waiting for the lookup of the original sender
  54. // for a multicast frame. So check to see if we've got it.
  55. return _doMULTICAST_FRAME(_r,peer);
  56. }
  57. if (!dearmor(peer->key())) {
  58. TRACE("dropped packet from %s(%s), MAC authentication failed (size: %u)",source().toString().c_str(),_remoteAddress.toString().c_str(),size());
  59. return true;
  60. }
  61. if (!uncompress()) {
  62. TRACE("dropped packet from %s(%s), compressed data invalid",source().toString().c_str(),_remoteAddress.toString().c_str());
  63. return true;
  64. }
  65. Packet::Verb v = verb();
  66. // Once a packet is determined to be basically valid, it can be used
  67. // to passively learn a new network path to the sending peer. It
  68. // also results in statistics updates.
  69. peer->onReceive(_r,_localPort,_remoteAddress,hops(),v,Utils::now());
  70. switch(v) {
  71. case Packet::VERB_NOP:
  72. TRACE("NOP from %s(%s)",source().toString().c_str(),_remoteAddress.toString().c_str());
  73. return true;
  74. case Packet::VERB_HELLO:
  75. return _doHELLO(_r); // legal, but why? :)
  76. case Packet::VERB_ERROR:
  77. return _doERROR(_r,peer);
  78. case Packet::VERB_OK:
  79. return _doOK(_r,peer);
  80. case Packet::VERB_WHOIS:
  81. return _doWHOIS(_r,peer);
  82. case Packet::VERB_RENDEZVOUS:
  83. return _doRENDEZVOUS(_r,peer);
  84. case Packet::VERB_FRAME:
  85. return _doFRAME(_r,peer);
  86. case Packet::VERB_PROXY_FRAME:
  87. return _doPROXY_FRAME(_r,peer);
  88. case Packet::VERB_MULTICAST_FRAME:
  89. return _doMULTICAST_FRAME(_r,peer);
  90. case Packet::VERB_MULTICAST_LIKE:
  91. return _doMULTICAST_LIKE(_r,peer);
  92. case Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE:
  93. return _doNETWORK_MEMBERSHIP_CERTIFICATE(_r,peer);
  94. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  95. return _doNETWORK_CONFIG_REQUEST(_r,peer);
  96. case Packet::VERB_NETWORK_CONFIG_REFRESH:
  97. return _doNETWORK_CONFIG_REFRESH(_r,peer);
  98. default:
  99. // This might be something from a new or old version of the protocol.
  100. // Technically it passed MAC so the packet is still valid, but we
  101. // ignore it.
  102. TRACE("ignored unrecognized verb %.2x from %s(%s)",(unsigned int)v,source().toString().c_str(),_remoteAddress.toString().c_str());
  103. return true;
  104. }
  105. } else {
  106. _step = DECODE_WAITING_FOR_SENDER_LOOKUP; // should already be this...
  107. _r->sw->requestWhois(source());
  108. return false;
  109. }
  110. }
  111. void PacketDecoder::_CBaddPeerFromHello(void *arg,const SharedPtr<Peer> &p,Topology::PeerVerifyResult result)
  112. {
  113. _CBaddPeerFromHello_Data *req = (_CBaddPeerFromHello_Data *)arg;
  114. const RuntimeEnvironment *_r = req->renv;
  115. try {
  116. switch(result) {
  117. case Topology::PEER_VERIFY_ACCEPTED_NEW:
  118. case Topology::PEER_VERIFY_ACCEPTED_ALREADY_HAVE:
  119. case Topology::PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS: {
  120. _r->sw->doAnythingWaitingForPeer(p);
  121. Packet outp(req->source,_r->identity.address(),Packet::VERB_OK);
  122. outp.append((unsigned char)Packet::VERB_HELLO);
  123. outp.append(req->helloPacketId);
  124. outp.append(req->helloTimestamp);
  125. outp.append((unsigned char)ZT_PROTO_VERSION);
  126. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  127. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  128. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  129. outp.armor(p->key(),true);
  130. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  131. } break;
  132. case Topology::PEER_VERIFY_REJECTED_INVALID_IDENTITY: {
  133. Packet outp(req->source,_r->identity.address(),Packet::VERB_ERROR);
  134. outp.append((unsigned char)Packet::VERB_HELLO);
  135. outp.append(req->helloPacketId);
  136. outp.append((unsigned char)Packet::ERROR_IDENTITY_INVALID);
  137. outp.armor(p->key(),true);
  138. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  139. } break;
  140. case Topology::PEER_VERIFY_REJECTED_DUPLICATE:
  141. case Topology::PEER_VERIFY_REJECTED_DUPLICATE_TRIAGED: {
  142. Packet outp(req->source,_r->identity.address(),Packet::VERB_ERROR);
  143. outp.append((unsigned char)Packet::VERB_HELLO);
  144. outp.append(req->helloPacketId);
  145. outp.append((unsigned char)Packet::ERROR_IDENTITY_COLLISION);
  146. outp.armor(p->key(),true);
  147. _r->demarc->send(req->localPort,req->remoteAddress,outp.data(),outp.size(),-1);
  148. } break;
  149. }
  150. } catch ( ... ) {
  151. TRACE("unexpected exception in addPeer() result callback for peer received via HELLO");
  152. }
  153. delete req;
  154. }
  155. void PacketDecoder::_CBaddPeerFromWhois(void *arg,const SharedPtr<Peer> &p,Topology::PeerVerifyResult result)
  156. {
  157. const RuntimeEnvironment *_r = (const RuntimeEnvironment *)arg;
  158. try {
  159. switch(result) {
  160. case Topology::PEER_VERIFY_ACCEPTED_NEW:
  161. case Topology::PEER_VERIFY_ACCEPTED_ALREADY_HAVE:
  162. case Topology::PEER_VERIFY_ACCEPTED_DISPLACED_INVALID_ADDRESS:
  163. _r->sw->doAnythingWaitingForPeer(p);
  164. break;
  165. default:
  166. break;
  167. }
  168. } catch ( ... ) {
  169. TRACE("unexpected exception in addPeer() result callback for peer received via OK(WHOIS)");
  170. }
  171. }
  172. bool PacketDecoder::_doERROR(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  173. {
  174. try {
  175. Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  176. Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  177. TRACE("ERROR %s from %s(%s) in-re %s",Packet::errorString(errorCode),source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  178. switch(errorCode) {
  179. case Packet::ERROR_OBJ_NOT_FOUND:
  180. if (inReVerb == Packet::VERB_WHOIS) {
  181. // TODO: abort WHOIS if sender is a supernode
  182. }
  183. break;
  184. case Packet::ERROR_IDENTITY_COLLISION:
  185. case Packet::ERROR_IDENTITY_INVALID:
  186. // TODO: if it comes from a supernode, regenerate a new identity
  187. break;
  188. case Packet::ERROR_NO_MEMBER_CERTIFICATE:
  189. // TODO: send member certificate
  190. break;
  191. default:
  192. break;
  193. }
  194. } catch (std::exception &ex) {
  195. TRACE("dropped ERROR from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  196. } catch ( ... ) {
  197. TRACE("dropped ERROR from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  198. }
  199. return true;
  200. }
  201. bool PacketDecoder::_doHELLO(const RuntimeEnvironment *_r)
  202. {
  203. try {
  204. //unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  205. unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  206. unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  207. unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  208. uint64_t timestamp = at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  209. Identity id(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  210. // Initial sniff test for valid addressing and that this is indeed the
  211. // submitter's identity.
  212. if ((id.address().isReserved())||(id.address() != source())) {
  213. #ifdef ZT_TRACE
  214. if (id.address().isReserved()) {
  215. TRACE("dropped HELLO from %s(%s): identity has reserved address",source().toString().c_str(),_remoteAddress.toString().c_str());
  216. } else {
  217. TRACE("dropped HELLO from %s(%s): identity is not for sender of packet (HELLO is a self-announcement)",source().toString().c_str(),_remoteAddress.toString().c_str());
  218. }
  219. #endif
  220. return true;
  221. }
  222. // Is this a HELLO for a peer we already know? If so just update its
  223. // packet receive stats and send an OK.
  224. SharedPtr<Peer> existingPeer(_r->topology->getPeer(id.address()));
  225. if ((existingPeer)&&(existingPeer->identity() == id)) {
  226. existingPeer->onReceive(_r,_localPort,_remoteAddress,hops(),Packet::VERB_HELLO,Utils::now());
  227. existingPeer->setRemoteVersion(vMajor,vMinor,vRevision);
  228. Packet outp(source(),_r->identity.address(),Packet::VERB_OK);
  229. outp.append((unsigned char)Packet::VERB_HELLO);
  230. outp.append(packetId());
  231. outp.append(timestamp);
  232. outp.armor(existingPeer->key(),true);
  233. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  234. return true;
  235. }
  236. SharedPtr<Peer> candidate(new Peer(_r->identity,id));
  237. candidate->setPathAddress(_remoteAddress,false);
  238. candidate->setRemoteVersion(vMajor,vMinor,vRevision);
  239. _CBaddPeerFromHello_Data *arg = new _CBaddPeerFromHello_Data;
  240. arg->renv = _r;
  241. arg->source = source();
  242. arg->remoteAddress = _remoteAddress;
  243. arg->localPort = _localPort;
  244. arg->vMajor = vMajor;
  245. arg->vMinor = vMinor;
  246. arg->vRevision = vRevision;
  247. arg->helloPacketId = packetId();
  248. arg->helloTimestamp = timestamp;
  249. _r->topology->addPeer(candidate,&PacketDecoder::_CBaddPeerFromHello,arg);
  250. } catch (std::exception &ex) {
  251. TRACE("dropped HELLO from %s(%s): %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  252. } catch ( ... ) {
  253. TRACE("dropped HELLO from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  254. }
  255. return true;
  256. }
  257. bool PacketDecoder::_doOK(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  258. {
  259. try {
  260. Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  261. switch(inReVerb) {
  262. case Packet::VERB_HELLO: {
  263. // OK from HELLO permits computation of latency.
  264. unsigned int latency = std::min((unsigned int)(Utils::now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP)),(unsigned int)0xffff);
  265. unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  266. unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  267. unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  268. TRACE("%s(%s): OK(HELLO), latency: %u, version %u.%u.%u",source().toString().c_str(),_remoteAddress.toString().c_str(),latency,vMajor,vMinor,vRevision);
  269. peer->setLatency(_remoteAddress,latency);
  270. peer->setRemoteVersion(vMajor,vMinor,vRevision);
  271. } break;
  272. case Packet::VERB_WHOIS: {
  273. TRACE("%s(%s): OK(%s)",source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  274. if (_r->topology->isSupernode(source())) {
  275. // Right now, only supernodes are queried for WHOIS so we only
  276. // accept OK(WHOIS) from supernodes. Otherwise peers could
  277. // potentially cache-poison.
  278. _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));
  279. }
  280. } break;
  281. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  282. SharedPtr<Network> nw(_r->nc->network(at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID)));
  283. if ((nw)&&(nw->controller() == source())) {
  284. // OK(NETWORK_CONFIG_REQUEST) is only accepted from a network's
  285. // controller.
  286. unsigned int dictlen = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN);
  287. std::string dict((const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT,dictlen),dictlen);
  288. if (dict.length()) {
  289. Network::Config netconf(dict);
  290. TRACE("got network configuration for network %.16llx from %s",(unsigned long long)nw->id(),source().toString().c_str());
  291. nw->setConfiguration(netconf);
  292. }
  293. }
  294. } break;
  295. default:
  296. //TRACE("%s(%s): OK(%s)",source().toString().c_str(),_remoteAddress.toString().c_str(),Packet::verbString(inReVerb));
  297. break;
  298. }
  299. } catch (std::exception &ex) {
  300. TRACE("dropped OK from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  301. } catch ( ... ) {
  302. TRACE("dropped OK from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  303. }
  304. return true;
  305. }
  306. bool PacketDecoder::_doWHOIS(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  307. {
  308. if (payloadLength() == ZT_ADDRESS_LENGTH) {
  309. SharedPtr<Peer> p(_r->topology->getPeer(Address(payload(),ZT_ADDRESS_LENGTH)));
  310. if (p) {
  311. Packet outp(source(),_r->identity.address(),Packet::VERB_OK);
  312. outp.append((unsigned char)Packet::VERB_WHOIS);
  313. outp.append(packetId());
  314. p->identity().serialize(outp,false);
  315. outp.armor(peer->key(),true);
  316. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  317. TRACE("sent WHOIS response to %s for %s",source().toString().c_str(),Address(payload(),ZT_ADDRESS_LENGTH).toString().c_str());
  318. } else {
  319. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  320. outp.append((unsigned char)Packet::VERB_WHOIS);
  321. outp.append(packetId());
  322. outp.append((unsigned char)Packet::ERROR_OBJ_NOT_FOUND);
  323. outp.append(payload(),ZT_ADDRESS_LENGTH);
  324. outp.armor(peer->key(),true);
  325. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  326. TRACE("sent WHOIS ERROR to %s for %s (not found)",source().toString().c_str(),Address(payload(),ZT_ADDRESS_LENGTH).toString().c_str());
  327. }
  328. } else {
  329. TRACE("dropped WHOIS from %s(%s): missing or invalid address",source().toString().c_str(),_remoteAddress.toString().c_str());
  330. }
  331. return true;
  332. }
  333. bool PacketDecoder::_doRENDEZVOUS(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  334. {
  335. try {
  336. /*
  337. * At the moment, we only obey RENDEZVOUS if it comes from a designated
  338. * supernode. If relay offloading is implemented to scale the net, this
  339. * will need reconsideration.
  340. *
  341. * The reason is that RENDEZVOUS could technically be used to cause a
  342. * peer to send a weird encrypted UDP packet to an arbitrary IP:port.
  343. * The sender of RENDEZVOUS has no control over the content of this
  344. * packet, but it's still maybe something we want to not allow just
  345. * anyone to order due to possible DDOS or network forensic implications.
  346. * So if we diversify relays, we'll need some way of deciding whether the
  347. * sender is someone we should trust with a RENDEZVOUS hint.
  348. */
  349. if (_r->topology->isSupernode(source())) {
  350. Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  351. SharedPtr<Peer> withPeer(_r->topology->getPeer(with));
  352. if (withPeer) {
  353. unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  354. unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  355. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  356. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  357. 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());
  358. _r->sw->contact(withPeer,atAddr);
  359. } else {
  360. TRACE("dropped corrupt RENDEZVOUS from %s(%s) (bad address or port)",source().toString().c_str(),_remoteAddress.toString().c_str());
  361. }
  362. } else {
  363. TRACE("ignored RENDEZVOUS from %s(%s) to meet unknown peer %s",source().toString().c_str(),_remoteAddress.toString().c_str(),with.toString().c_str());
  364. }
  365. } else {
  366. TRACE("ignored RENDEZVOUS from %s(%s): source not supernode",source().toString().c_str(),_remoteAddress.toString().c_str());
  367. }
  368. } catch (std::exception &ex) {
  369. TRACE("dropped RENDEZVOUS from %s(%s): %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  370. } catch ( ... ) {
  371. TRACE("dropped RENDEZVOUS from %s(%s): unexpected exception",source().toString().c_str(),_remoteAddress.toString().c_str());
  372. }
  373. return true;
  374. }
  375. bool PacketDecoder::_doFRAME(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  376. {
  377. try {
  378. SharedPtr<Network> network(_r->nc->network(at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID)));
  379. if (network) {
  380. if (network->isAllowed(source())) {
  381. unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  382. if (network->permitsEtherType(etherType)) {
  383. network->tap().put(source().toMAC(),network->tap().mac(),etherType,data() + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD,size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD);
  384. } else if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  385. TRACE("dropped FRAME from %s: ethernet type %u not allowed on network %.16llx",source().toString().c_str(),etherType,(unsigned long long)network->id());
  386. }
  387. // Source moves "closer" to us in multicast propagation priority when
  388. // we receive unicast frames from it. This is called "implicit social
  389. // ordering" in other docs.
  390. _r->mc->bringCloser(network->id(),source());
  391. } else {
  392. TRACE("dropped FRAME from %s(%s): not a member of closed network %llu",source().toString().c_str(),_remoteAddress.toString().c_str(),network->id());
  393. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  394. outp.append((unsigned char)Packet::VERB_FRAME);
  395. outp.append(packetId());
  396. outp.append((unsigned char)Packet::ERROR_NO_MEMBER_CERTIFICATE);
  397. outp.append(network->id());
  398. outp.armor(peer->key(),true);
  399. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  400. }
  401. } else {
  402. 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));
  403. }
  404. } catch (std::exception &ex) {
  405. TRACE("dropped FRAME from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  406. } catch ( ... ) {
  407. TRACE("dropped FRAME from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  408. }
  409. return true;
  410. }
  411. bool PacketDecoder::_doPROXY_FRAME(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  412. {
  413. // TODO: bridging is not implemented yet
  414. return true;
  415. }
  416. bool PacketDecoder::_doMULTICAST_FRAME(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  417. {
  418. try {
  419. Address origin(Address(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ORIGIN,ZT_PROTO_VERB_MULTICAST_FRAME_LEN_ORIGIN),ZT_ADDRESS_LENGTH));
  420. SharedPtr<Peer> originPeer(_r->topology->getPeer(origin));
  421. if (!originPeer) {
  422. _r->sw->requestWhois(origin);
  423. _step = DECODE_WAITING_FOR_MULTICAST_FRAME_ORIGINAL_SENDER_LOOKUP; // causes processing to come back here
  424. return false;
  425. }
  426. uint16_t depth = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH);
  427. unsigned char *fifo = field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_FIFO,ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO);
  428. unsigned char *bloom = field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM,ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_BLOOM);
  429. uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID);
  430. uint16_t bloomNonce = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_BLOOM_NONCE);
  431. unsigned int prefixBits = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX_BITS];
  432. unsigned int prefix = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_PREFIX);
  433. uint64_t guid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GUID);
  434. MAC sourceMac(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,ZT_PROTO_VERB_MULTICAST_FRAME_LEN_SOURCE_MAC));
  435. MulticastGroup dest(MAC(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC,ZT_PROTO_VERB_MULTICAST_FRAME_LEN_DEST_MAC)),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI));
  436. unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  437. unsigned int frameLen = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME_LEN);
  438. unsigned char *frame = field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME,frameLen);
  439. unsigned int signatureLen = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME + frameLen);
  440. unsigned char *signature = field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME + frameLen + 2,signatureLen);
  441. unsigned int signedPartLen = (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME - ZT_PROTO_VERB_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION) + frameLen;
  442. if (!originPeer->identity().verify(field(ZT_PROTO_VERB_MULTICAST_FRAME_IDX__START_OF_SIGNED_PORTION,signedPartLen),signedPartLen,signature,signatureLen)) {
  443. TRACE("dropped MULTICAST_FRAME from %s(%s): failed signature verification, claims to be from %s",source().toString().c_str(),_remoteAddress.toString().c_str(),origin.toString().c_str());
  444. return true;
  445. }
  446. if (!dest.mac().isMulticast()) {
  447. TRACE("dropped MULTICAST_FRAME from %s(%s): %s is not a multicast/broadcast address",source().toString().c_str(),_remoteAddress.toString().c_str(),dest.mac().toString().c_str());
  448. return true;
  449. }
  450. if ((origin == _r->identity.address())||(_r->mc->deduplicate(nwid,guid))) {
  451. TRACE("dropped MULTICAST_FRAME from %s(%s): duplicate",source().toString().c_str(),_remoteAddress.toString().c_str());
  452. return true;
  453. }
  454. bool rateLimitsExceeded = false;
  455. SharedPtr<Network> network(_r->nc->network(nwid));
  456. if (network) {
  457. if (!network->isAllowed(origin)) {
  458. TRACE("didn't inject MULTICAST_FRAME from %s(%s) into %.16llx: sender %s not allowed or we don't have a certificate",source().toString().c_str(),nwid,_remoteAddress.toString().c_str(),origin.toString().c_str());
  459. Packet outp(source(),_r->identity.address(),Packet::VERB_ERROR);
  460. outp.append((unsigned char)Packet::VERB_FRAME);
  461. outp.append(packetId());
  462. outp.append((unsigned char)Packet::ERROR_NO_MEMBER_CERTIFICATE);
  463. outp.append(nwid);
  464. outp.armor(peer->key(),true);
  465. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  466. // We do not terminate here, since if the member just has an out of
  467. // date cert or hasn't sent us a cert yet we still want to propagate
  468. // the message so multicast works.
  469. } else if ((!network->permitsBridging())&&(!origin.wouldHaveMac(sourceMac))) {
  470. TRACE("didn't inject MULTICAST_FRAME from %s(%s) into %.16llx: source mac %s doesn't belong to %s, and bridging is not supported on network",source().toString().c_str(),nwid,_remoteAddress.toString().c_str(),sourceMac.toString().c_str(),origin.toString().c_str());
  471. } else if (!network->permitsEtherType(etherType)) {
  472. TRACE("didn't inject MULTICAST_FRAME from %s(%s) into %.16llx: ethertype %u is not allowed",source().toString().c_str(),nwid,_remoteAddress.toString().c_str(),etherType);
  473. } else if (network->updateAndCheckMulticastBalance(origin,dest,frameLen)) {
  474. network->tap().put(sourceMac,dest.mac(),etherType,frame,frameLen);
  475. } else {
  476. rateLimitsExceeded = true;
  477. }
  478. }
  479. // We can only really know if rate limit was exceeded if we're a member of
  480. // this network. This will nearly always be true for anyone getting a
  481. // multicast except supernodes, so the net effect will be to truncate
  482. // multicast propagation if the rate limit is exceeded.
  483. if (rateLimitsExceeded) {
  484. TRACE("dropped MULTICAST_FRAME from %s(%s): rate limits exceeded for sender %s",source().toString().c_str(),_remoteAddress.toString().c_str(),origin.toString().c_str());
  485. return true;
  486. }
  487. if (++depth > ZT_MULTICAST_MAX_PROPAGATION_DEPTH) {
  488. TRACE("dropped MULTICAST_FRAME from %s(%s): max propagation depth reached",source().toString().c_str(),_remoteAddress.toString().c_str());
  489. return true;
  490. }
  491. setAt(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_PROPAGATION_DEPTH,(uint16_t)depth);
  492. // New FIFO with room for one extra, since head will be next hop
  493. unsigned char newFifo[ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO + ZT_ADDRESS_LENGTH];
  494. unsigned char *newFifoPtr = newFifo;
  495. unsigned char *newFifoEnd = newFifoPtr + sizeof(newFifo);
  496. for(unsigned int i=0;i<ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO;) {
  497. unsigned int j = i;
  498. i += ZT_ADDRESS_LENGTH;
  499. unsigned char zm = 0;
  500. while (j != i)
  501. zm |= (*(newFifoPtr++) = fifo[j++]);
  502. if (!zm) // stop at zero address
  503. break;
  504. }
  505. // Add any next hops we know about to FIFO
  506. _r->mc->getNextHops(nwid,dest,Multicaster::AddToPropagationQueue(&newFifoPtr,newFifoEnd,bloom,bloomNonce,origin,prefixBits,prefix));
  507. // Zero-terminate new FIFO if not completely full
  508. while (newFifoPtr != newFifoEnd)
  509. *(newFifoPtr++) = (unsigned char)0;
  510. // First element in newFifo[] is next hop
  511. Address nextHop(newFifo,ZT_ADDRESS_LENGTH);
  512. if (!nextHop)
  513. nextHop = _r->topology->getBestSupernode(&origin,1,true); // exclude origin in case it's itself a supernode
  514. if ((!nextHop)||(nextHop == _r->identity.address())) { // check against our addr is a sanity check
  515. TRACE("not forwarding MULTICAST_FRAME from %s(%s): no next hop",source().toString().c_str(),_remoteAddress.toString().c_str());
  516. return true;
  517. }
  518. // The rest of newFifo[] goes back into the packet
  519. memcpy(fifo,newFifo + ZT_ADDRESS_LENGTH,ZT_PROTO_VERB_MULTICAST_FRAME_LEN_PROPAGATION_FIFO);
  520. // Send to next hop, reusing this packet as scratch space
  521. newInitializationVector();
  522. setDestination(nextHop);
  523. setSource(_r->identity.address());
  524. compress(); // note: bloom filters and empty FIFOs are highly compressable!
  525. _r->sw->send(*this,true);
  526. return true;
  527. } catch (std::exception &ex) {
  528. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  529. } catch ( ... ) {
  530. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  531. }
  532. return true;
  533. }
  534. bool PacketDecoder::_doMULTICAST_LIKE(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  535. {
  536. try {
  537. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  538. if (ptr >= size())
  539. return true;
  540. uint64_t now = Utils::now();
  541. Address src(source());
  542. // Iterate through 18-byte network,MAC,ADI tuples
  543. for(;;) {
  544. _r->mc->likesGroup(at<uint64_t>(ptr),src,MulticastGroup(MAC(field(ptr + 8,6)),at<uint32_t>(ptr + 14)),now);
  545. if ((ptr += 18) >= size())
  546. break;
  547. }
  548. } catch (std::exception &ex) {
  549. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),ex.what());
  550. } catch ( ... ) {
  551. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  552. }
  553. return true;
  554. }
  555. bool PacketDecoder::_doNETWORK_MEMBERSHIP_CERTIFICATE(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  556. {
  557. // TODO: not implemented yet, will be needed for private networks.
  558. return true;
  559. }
  560. bool PacketDecoder::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  561. {
  562. try {
  563. uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  564. #ifndef __WINDOWS__
  565. if (_r->netconfService) {
  566. char tmp[128];
  567. unsigned int dictLen = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN);
  568. Dictionary request;
  569. if (dictLen)
  570. request["meta"] = std::string((const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,dictLen),dictLen);
  571. request["type"] = "netconf-request";
  572. request["peerId"] = peer->identity().toString(false);
  573. Utils::snprintf(tmp,sizeof(tmp),"%llx",(unsigned long long)nwid);
  574. request["nwid"] = tmp;
  575. Utils::snprintf(tmp,sizeof(tmp),"%llx",(unsigned long long)packetId());
  576. request["requestId"] = tmp;
  577. //TRACE("to netconf:\n%s",request.toString().c_str());
  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.armor(peer->key(),true);
  587. _r->demarc->send(_localPort,_remoteAddress,outp.data(),outp.size(),-1);
  588. #ifndef __WINDOWS__
  589. }
  590. #endif // !__WINDOWS__
  591. } catch (std::exception &exc) {
  592. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
  593. } catch ( ... ) {
  594. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  595. }
  596. return true;
  597. }
  598. bool PacketDecoder::_doNETWORK_CONFIG_REFRESH(const RuntimeEnvironment *_r,const SharedPtr<Peer> &peer)
  599. {
  600. try {
  601. uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REFRESH_IDX_NETWORK_ID);
  602. SharedPtr<Network> nw(_r->nc->network(nwid));
  603. if ((nw)&&(source() == nw->controller())) // only respond to requests from controller
  604. nw->requestConfiguration();
  605. } catch (std::exception &exc) {
  606. TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception: %s",source().toString().c_str(),_remoteAddress.toString().c_str(),exc.what());
  607. } catch ( ... ) {
  608. TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception: (unknown)",source().toString().c_str(),_remoteAddress.toString().c_str());
  609. }
  610. return true;
  611. }
  612. } // namespace ZeroTier