2
0

IncomingPacket.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <stdlib.h>
  29. #include "../version.h"
  30. #include "../include/ZeroTierOne.h"
  31. #include "Constants.hpp"
  32. #include "RuntimeEnvironment.hpp"
  33. #include "IncomingPacket.hpp"
  34. #include "Topology.hpp"
  35. #include "Switch.hpp"
  36. #include "Peer.hpp"
  37. #include "NetworkController.hpp"
  38. #include "SelfAwareness.hpp"
  39. #include "Salsa20.hpp"
  40. #include "SHA512.hpp"
  41. #include "World.hpp"
  42. #include "Node.hpp"
  43. #include "CertificateOfMembership.hpp"
  44. #include "Capability.hpp"
  45. #include "Tag.hpp"
  46. #include "Revocation.hpp"
  47. #include "Trace.hpp"
  48. namespace ZeroTier {
  49. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr)
  50. {
  51. const Address sourceAddress(source());
  52. try {
  53. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  54. const unsigned int c = cipher();
  55. bool trusted = false;
  56. if (c == ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH) {
  57. // If this is marked as a packet via a trusted path, check source address and path ID.
  58. // Obviously if no trusted paths are configured this always returns false and such
  59. // packets are dropped on the floor.
  60. const uint64_t tpid = trustedPathId();
  61. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),tpid)) {
  62. trusted = true;
  63. } else {
  64. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"path not trusted");
  65. return true;
  66. }
  67. } else if ((c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  68. // Only HELLO is allowed in the clear, but will still have a MAC
  69. return _doHELLO(RR,tPtr,false);
  70. }
  71. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,sourceAddress));
  72. if (peer) {
  73. if (!trusted) {
  74. if (!dearmor(peer->key())) {
  75. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"invalid MAC");
  76. return true;
  77. }
  78. }
  79. if (!uncompress()) {
  80. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),Packet::VERB_NOP,"LZ4 decompression failed");
  81. return true;
  82. }
  83. const Packet::Verb v = verb();
  84. switch(v) {
  85. //case Packet::VERB_NOP:
  86. default: // ignore unknown verbs, but if they pass auth check they are "received"
  87. peer->received(tPtr,_path,hops(),packetId(),v,0,Packet::VERB_NOP,false,0);
  88. return true;
  89. case Packet::VERB_HELLO: return _doHELLO(RR,tPtr,true);
  90. case Packet::VERB_ERROR: return _doERROR(RR,tPtr,peer);
  91. case Packet::VERB_OK: return _doOK(RR,tPtr,peer);
  92. case Packet::VERB_WHOIS: return _doWHOIS(RR,tPtr,peer);
  93. case Packet::VERB_RENDEZVOUS: return _doRENDEZVOUS(RR,tPtr,peer);
  94. case Packet::VERB_FRAME: return _doFRAME(RR,tPtr,peer);
  95. case Packet::VERB_EXT_FRAME: return _doEXT_FRAME(RR,tPtr,peer);
  96. case Packet::VERB_ECHO: return _doECHO(RR,tPtr,peer);
  97. case Packet::VERB_MULTICAST_LIKE: return _doMULTICAST_LIKE(RR,tPtr,peer);
  98. case Packet::VERB_NETWORK_CREDENTIALS: return _doNETWORK_CREDENTIALS(RR,tPtr,peer);
  99. case Packet::VERB_NETWORK_CONFIG_REQUEST: return _doNETWORK_CONFIG_REQUEST(RR,tPtr,peer);
  100. case Packet::VERB_NETWORK_CONFIG: return _doNETWORK_CONFIG(RR,tPtr,peer);
  101. case Packet::VERB_MULTICAST_GATHER: return _doMULTICAST_GATHER(RR,tPtr,peer);
  102. case Packet::VERB_MULTICAST_FRAME: return _doMULTICAST_FRAME(RR,tPtr,peer);
  103. case Packet::VERB_PUSH_DIRECT_PATHS: return _doPUSH_DIRECT_PATHS(RR,tPtr,peer);
  104. case Packet::VERB_USER_MESSAGE: return _doUSER_MESSAGE(RR,tPtr,peer);
  105. case Packet::VERB_REMOTE_TRACE: return _doREMOTE_TRACE(RR,tPtr,peer);
  106. }
  107. } else {
  108. RR->sw->requestWhois(tPtr,RR->node->now(),sourceAddress);
  109. return false;
  110. }
  111. } catch ( ... ) {
  112. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  113. return true;
  114. }
  115. }
  116. bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  117. {
  118. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  119. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  120. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  121. uint64_t networkId = 0;
  122. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  123. * avoid having to log every outgoing packet ID. Instead we put the
  124. * logic to determine whether we should consider an ERROR in each
  125. * error handler. In most cases these are only trusted in specific
  126. * circumstances. */
  127. switch(errorCode) {
  128. case Packet::ERROR_OBJ_NOT_FOUND:
  129. // Object not found, currently only meaningful from network controllers.
  130. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  131. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  132. if ((network)&&(network->controller() == peer->address()))
  133. network->setNotFound();
  134. }
  135. break;
  136. case Packet::ERROR_UNSUPPORTED_OPERATION:
  137. // This can be sent in response to any operation, though right now we only
  138. // consider it meaningful from network controllers. This would indicate
  139. // that the queried node does not support acting as a controller.
  140. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  141. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  142. if ((network)&&(network->controller() == peer->address()))
  143. network->setNotFound();
  144. }
  145. break;
  146. case Packet::ERROR_IDENTITY_COLLISION:
  147. // FIXME: for federation this will need a payload with a signature or something.
  148. if (RR->topology->isUpstream(peer->identity()))
  149. RR->node->postEvent(tPtr,ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION);
  150. break;
  151. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  152. // Peers can send this in response to frames if they do not have a recent enough COM from us
  153. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  154. const SharedPtr<Network> network(RR->node->network(networkId));
  155. const int64_t now = RR->node->now();
  156. if ( (network) && (network->config().com) && (peer->rateGateIncomingComRequest(now)) )
  157. network->pushCredentialsNow(tPtr,peer->address(),now);
  158. } break;
  159. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  160. // Network controller: network access denied.
  161. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  162. if ((network)&&(network->controller() == peer->address()))
  163. network->setAccessDenied();
  164. } break;
  165. case Packet::ERROR_UNWANTED_MULTICAST: {
  166. // Members of networks can use this error to indicate that they no longer
  167. // want to receive multicasts on a given channel.
  168. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  169. const SharedPtr<Network> network(RR->node->network(networkId));
  170. if ((network)&&(network->gate(tPtr,peer))) {
  171. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8,6),6),at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  172. RR->mc->remove(network->id(),mg,peer->address());
  173. }
  174. } break;
  175. default: break;
  176. }
  177. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_ERROR,inRePacketId,inReVerb,false,networkId);
  178. return true;
  179. }
  180. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool alreadyAuthenticated)
  181. {
  182. const int64_t now = RR->node->now();
  183. const uint64_t pid = packetId();
  184. const Address fromAddress(source());
  185. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  186. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  187. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  188. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  189. const int64_t timestamp = at<int64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  190. Identity id;
  191. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  192. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  193. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"protocol version too old");
  194. return true;
  195. }
  196. if (fromAddress != id.address()) {
  197. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"identity/address mismatch");
  198. return true;
  199. }
  200. SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,id.address()));
  201. if (peer) {
  202. // We already have an identity with this address -- check for collisions
  203. if (!alreadyAuthenticated) {
  204. if (peer->identity() != id) {
  205. // Identity is different from the one we already have -- address collision
  206. // Check rate limits
  207. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  208. return true;
  209. uint8_t key[ZT_PEER_SECRET_KEY_LENGTH];
  210. if (RR->identity.agree(id,key,ZT_PEER_SECRET_KEY_LENGTH)) {
  211. if (dearmor(key)) { // ensure packet is authentic, otherwise drop
  212. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"address collision");
  213. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  214. outp.append((uint8_t)Packet::VERB_HELLO);
  215. outp.append((uint64_t)pid);
  216. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  217. outp.armor(key,true,_path->nextOutgoingCounter());
  218. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  219. } else {
  220. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  221. }
  222. } else {
  223. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid identity");
  224. }
  225. return true;
  226. } else {
  227. // Identity is the same as the one we already have -- check packet integrity
  228. if (!dearmor(peer->key())) {
  229. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  230. return true;
  231. }
  232. // Continue at // VALID
  233. }
  234. } // else if alreadyAuthenticated then continue at // VALID
  235. } else {
  236. // We don't already have an identity with this address -- validate and learn it
  237. // Sanity check: this basically can't happen
  238. if (alreadyAuthenticated) {
  239. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"illegal alreadyAuthenticated state");
  240. return true;
  241. }
  242. // Check rate limits
  243. if (!RR->node->rateGateIdentityVerification(now,_path->address())) {
  244. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"rate limit exceeded");
  245. return true;
  246. }
  247. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  248. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  249. if (!dearmor(newPeer->key())) {
  250. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  251. return true;
  252. }
  253. // Check that identity's address is valid as per the derivation function
  254. if (!id.locallyValidate()) {
  255. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"invalid identity");
  256. return true;
  257. }
  258. peer = RR->topology->addPeer(tPtr,newPeer);
  259. // Continue at // VALID
  260. }
  261. // VALID -- if we made it here, packet passed identity and authenticity checks!
  262. // Get external surface address if present (was not in old versions)
  263. InetAddress externalSurfaceAddress;
  264. if (ptr < size()) {
  265. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  266. if ((externalSurfaceAddress)&&(hops() == 0))
  267. RR->sa->iam(tPtr,id.address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(id),now);
  268. }
  269. // Get primary planet world ID and world timestamp if present
  270. uint64_t planetWorldId = 0;
  271. uint64_t planetWorldTimestamp = 0;
  272. if ((ptr + 16) <= size()) {
  273. planetWorldId = at<uint64_t>(ptr); ptr += 8;
  274. planetWorldTimestamp = at<uint64_t>(ptr); ptr += 8;
  275. }
  276. std::vector< std::pair<uint64_t,uint64_t> > moonIdsAndTimestamps;
  277. if (ptr < size()) {
  278. // Remainder of packet, if present, is encrypted
  279. cryptField(peer->key(),ptr,size() - ptr);
  280. // Get moon IDs and timestamps if present
  281. if ((ptr + 2) <= size()) {
  282. const unsigned int numMoons = at<uint16_t>(ptr); ptr += 2;
  283. for(unsigned int i=0;i<numMoons;++i) {
  284. if ((World::Type)(*this)[ptr++] == World::TYPE_MOON)
  285. moonIdsAndTimestamps.push_back(std::pair<uint64_t,uint64_t>(at<uint64_t>(ptr),at<uint64_t>(ptr + 8)));
  286. ptr += 16;
  287. }
  288. }
  289. }
  290. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  291. // information about us: version, sent-to address, etc.
  292. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  293. outp.append((unsigned char)Packet::VERB_HELLO);
  294. outp.append((uint64_t)pid);
  295. outp.append((uint64_t)timestamp);
  296. outp.append((unsigned char)ZT_PROTO_VERSION);
  297. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  298. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  299. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  300. if (protoVersion >= 5) {
  301. _path->address().serialize(outp);
  302. } else {
  303. /* LEGACY COMPATIBILITY HACK:
  304. *
  305. * For a while now (since 1.0.3), ZeroTier has recognized changes in
  306. * its network environment empirically by examining its external network
  307. * address as reported by trusted peers. In versions prior to 1.1.0
  308. * (protocol version < 5), they did this by saving a snapshot of this
  309. * information (in SelfAwareness.hpp) keyed by reporting device ID and
  310. * address type.
  311. *
  312. * This causes problems when clustering is combined with symmetric NAT.
  313. * Symmetric NAT remaps ports, so different endpoints in a cluster will
  314. * report back different exterior addresses. Since the old code keys
  315. * this by device ID and not sending physical address and compares the
  316. * entire address including port, it constantly thinks its external
  317. * surface is changing and resets connections when talking to a cluster.
  318. *
  319. * In new code we key by sending physical address and device and we also
  320. * take the more conservative position of only interpreting changes in
  321. * IP address (neglecting port) as a change in network topology that
  322. * necessitates a reset. But we can make older clients work here by
  323. * nulling out the port field. Since this info is only used for empirical
  324. * detection of link changes, it doesn't break anything else.
  325. */
  326. InetAddress tmpa(_path->address());
  327. tmpa.setPort(0);
  328. tmpa.serialize(outp);
  329. }
  330. const unsigned int worldUpdateSizeAt = outp.size();
  331. outp.addSize(2); // make room for 16-bit size field
  332. if ((planetWorldId)&&(RR->topology->planetWorldTimestamp() > planetWorldTimestamp)&&(planetWorldId == RR->topology->planetWorldId())) {
  333. RR->topology->planet().serialize(outp,false);
  334. }
  335. if (moonIdsAndTimestamps.size() > 0) {
  336. std::vector<World> moons(RR->topology->moons());
  337. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  338. for(std::vector< std::pair<uint64_t,uint64_t> >::const_iterator i(moonIdsAndTimestamps.begin());i!=moonIdsAndTimestamps.end();++i) {
  339. if (i->first == m->id()) {
  340. if (m->timestamp() > i->second)
  341. m->serialize(outp,false);
  342. break;
  343. }
  344. }
  345. }
  346. }
  347. outp.setAt<uint16_t>(worldUpdateSizeAt,(uint16_t)(outp.size() - (worldUpdateSizeAt + 2)));
  348. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  349. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  350. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  351. peer->received(tPtr,_path,hops(),pid,Packet::VERB_HELLO,0,Packet::VERB_NOP,false,0);
  352. return true;
  353. }
  354. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  355. {
  356. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  357. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  358. uint64_t networkId = 0;
  359. if (!RR->node->expectingReplyTo(inRePacketId))
  360. return true;
  361. switch(inReVerb) {
  362. case Packet::VERB_HELLO: {
  363. const uint64_t latency = RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  364. if (latency > ZT_HELLO_MAX_ALLOWABLE_LATENCY)
  365. return true;
  366. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  367. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  368. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  369. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  370. if (vProto < ZT_PROTO_VERSION_MIN)
  371. return true;
  372. InetAddress externalSurfaceAddress;
  373. unsigned int ptr = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
  374. // Get reported external surface address if present
  375. if (ptr < size())
  376. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  377. // Handle planet or moon updates if present
  378. if ((ptr + 2) <= size()) {
  379. const unsigned int worldsLen = at<uint16_t>(ptr); ptr += 2;
  380. if (RR->topology->shouldAcceptWorldUpdateFrom(peer->address())) {
  381. const unsigned int endOfWorlds = ptr + worldsLen;
  382. while (ptr < endOfWorlds) {
  383. World w;
  384. ptr += w.deserialize(*this,ptr);
  385. RR->topology->addWorld(tPtr,w,false);
  386. }
  387. } else {
  388. ptr += worldsLen;
  389. }
  390. }
  391. if (!hops())
  392. peer->addDirectLatencyMeasurment((unsigned int)latency);
  393. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  394. if ((externalSurfaceAddress)&&(hops() == 0))
  395. RR->sa->iam(tPtr,peer->address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(peer->identity()),RR->node->now());
  396. } break;
  397. case Packet::VERB_WHOIS:
  398. if (RR->topology->isUpstream(peer->identity())) {
  399. const Identity id(*this,ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY);
  400. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->addPeer(tPtr,SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  401. }
  402. break;
  403. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  404. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  405. const SharedPtr<Network> network(RR->node->network(networkId));
  406. if (network)
  407. network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  408. } break;
  409. case Packet::VERB_MULTICAST_GATHER: {
  410. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  411. const SharedPtr<Network> network(RR->node->network(networkId));
  412. if (network) {
  413. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI));
  414. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  415. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 6,count * 5),count,at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS));
  416. }
  417. } break;
  418. case Packet::VERB_MULTICAST_FRAME: {
  419. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  420. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  421. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI));
  422. const SharedPtr<Network> network(RR->node->network(networkId));
  423. if (network) {
  424. unsigned int offset = 0;
  425. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  426. CertificateOfMembership com;
  427. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  428. if (com)
  429. network->addCredential(tPtr,com);
  430. }
  431. if ((flags & 0x02) != 0) {
  432. // OK(MULTICAST_FRAME) includes implicit gather results
  433. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  434. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  435. unsigned int count = at<uint16_t>(offset); offset += 2;
  436. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(offset,count * 5),count,totalKnown);
  437. }
  438. }
  439. } break;
  440. default: break;
  441. }
  442. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_OK,inRePacketId,inReVerb,false,networkId);
  443. return true;
  444. }
  445. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  446. {
  447. if ((!RR->topology->amRoot())&&(!peer->rateGateInboundWhoisRequest(RR->node->now())))
  448. return true;
  449. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  450. outp.append((unsigned char)Packet::VERB_WHOIS);
  451. outp.append(packetId());
  452. unsigned int count = 0;
  453. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  454. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  455. const Address addr(field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  456. ptr += ZT_ADDRESS_LENGTH;
  457. const Identity id(RR->topology->getIdentity(tPtr,addr));
  458. if (id) {
  459. id.serialize(outp,false);
  460. ++count;
  461. } else {
  462. // Request unknown WHOIS from upstream from us (if we have one)
  463. RR->sw->requestWhois(tPtr,RR->node->now(),addr);
  464. }
  465. }
  466. if (count > 0) {
  467. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  468. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  469. }
  470. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,false,0);
  471. return true;
  472. }
  473. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  474. {
  475. if (RR->topology->isUpstream(peer->identity())) {
  476. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  477. const SharedPtr<Peer> rendezvousWith(RR->topology->getPeer(tPtr,with));
  478. if (rendezvousWith) {
  479. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  480. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  481. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  482. const InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  483. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,with,_path->localSocket(),atAddr)) {
  484. const uint64_t junk = RR->node->prng();
  485. RR->node->putPacket(tPtr,_path->localSocket(),atAddr,&junk,4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  486. rendezvousWith->attemptToContactAt(tPtr,_path->localSocket(),atAddr,RR->node->now(),false,0);
  487. }
  488. }
  489. }
  490. }
  491. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,false,0);
  492. return true;
  493. }
  494. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  495. {
  496. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  497. const SharedPtr<Network> network(RR->node->network(nwid));
  498. bool trustEstablished = false;
  499. if (network) {
  500. if (network->gate(tPtr,peer)) {
  501. trustEstablished = true;
  502. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  503. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  504. const MAC sourceMac(peer->address(),nwid);
  505. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  506. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  507. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  508. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  509. }
  510. } else {
  511. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  512. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_FRAME,true);
  513. }
  514. } else {
  515. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  516. }
  517. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_FRAME,0,Packet::VERB_NOP,trustEstablished,nwid);
  518. return true;
  519. }
  520. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  521. {
  522. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  523. const SharedPtr<Network> network(RR->node->network(nwid));
  524. if (network) {
  525. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  526. unsigned int comLen = 0;
  527. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  528. CertificateOfMembership com;
  529. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  530. if (com)
  531. network->addCredential(tPtr,com);
  532. }
  533. if (!network->gate(tPtr,peer)) {
  534. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  535. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  536. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false,nwid);
  537. return true;
  538. }
  539. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  540. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  541. const MAC to(field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_TO,ZT_PROTO_VERB_EXT_FRAME_LEN_TO),ZT_PROTO_VERB_EXT_FRAME_LEN_TO);
  542. const MAC from(field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_FROM,ZT_PROTO_VERB_EXT_FRAME_LEN_FROM),ZT_PROTO_VERB_EXT_FRAME_LEN_FROM);
  543. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  544. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  545. if ((!from)||(from == network->mac())) {
  546. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  547. return true;
  548. }
  549. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  550. case 1:
  551. if (from != MAC(peer->address(),nwid)) {
  552. if (network->config().permitsBridging(peer->address())) {
  553. network->learnBridgeRoute(from,peer->address());
  554. } else {
  555. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  556. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  557. return true;
  558. }
  559. } else if (to != network->mac()) {
  560. if (to.isMulticast()) {
  561. if (network->config().multicastLimit == 0) {
  562. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  563. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  564. return true;
  565. }
  566. } else if (!network->config().permitsBridging(RR->identity.address())) {
  567. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  568. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  569. return true;
  570. }
  571. }
  572. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  573. case 2:
  574. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  575. break;
  576. }
  577. }
  578. if ((flags & 0x10) != 0) { // ACK requested
  579. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  580. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  581. outp.append((uint64_t)packetId());
  582. outp.append((uint64_t)nwid);
  583. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  584. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  585. }
  586. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid);
  587. } else {
  588. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false,nwid);
  589. }
  590. return true;
  591. }
  592. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  593. {
  594. if (!peer->rateGateEchoRequest(RR->node->now()))
  595. return true;
  596. const uint64_t pid = packetId();
  597. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  598. outp.append((unsigned char)Packet::VERB_ECHO);
  599. outp.append((uint64_t)pid);
  600. if (size() > ZT_PACKET_IDX_PAYLOAD)
  601. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  602. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  603. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  604. peer->received(tPtr,_path,hops(),pid,Packet::VERB_ECHO,0,Packet::VERB_NOP,false,0);
  605. return true;
  606. }
  607. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  608. {
  609. const int64_t now = RR->node->now();
  610. uint64_t authOnNetwork[256]; // cache for approved network IDs
  611. unsigned int authOnNetworkCount = 0;
  612. SharedPtr<Network> network;
  613. bool trustEstablished = false;
  614. // Iterate through 18-byte network,MAC,ADI tuples
  615. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) {
  616. const uint64_t nwid = at<uint64_t>(ptr);
  617. bool auth = false;
  618. for(unsigned int i=0;i<authOnNetworkCount;++i) {
  619. if (nwid == authOnNetwork[i]) {
  620. auth = true;
  621. break;
  622. }
  623. }
  624. if (!auth) {
  625. if ((!network)||(network->id() != nwid))
  626. network = RR->node->network(nwid);
  627. const bool authOnNet = ((network)&&(network->gate(tPtr,peer)));
  628. if (!authOnNet)
  629. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  630. trustEstablished |= authOnNet;
  631. if (authOnNet||RR->mc->cacheAuthorized(peer->address(),nwid,now)) {
  632. auth = true;
  633. if (authOnNetworkCount < 256) // sanity check, packets can't really be this big
  634. authOnNetwork[authOnNetworkCount++] = nwid;
  635. }
  636. }
  637. if (auth) {
  638. const MulticastGroup group(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14));
  639. RR->mc->add(tPtr,now,nwid,group,peer->address());
  640. }
  641. }
  642. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,trustEstablished,(network) ? network->id() : 0);
  643. return true;
  644. }
  645. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  646. {
  647. if (!peer->rateGateCredentialsReceived(RR->node->now()))
  648. return true;
  649. CertificateOfMembership com;
  650. Capability cap;
  651. Tag tag;
  652. Revocation revocation;
  653. CertificateOfOwnership coo;
  654. bool trustEstablished = false;
  655. SharedPtr<Network> network;
  656. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  657. while ((p < size())&&((*this)[p] != 0)) {
  658. p += com.deserialize(*this,p);
  659. if (com) {
  660. network = RR->node->network(com.networkId());
  661. if (network) {
  662. switch (network->addCredential(tPtr,com)) {
  663. case Membership::ADD_REJECTED:
  664. break;
  665. case Membership::ADD_ACCEPTED_NEW:
  666. case Membership::ADD_ACCEPTED_REDUNDANT:
  667. trustEstablished = true;
  668. break;
  669. case Membership::ADD_DEFERRED_FOR_WHOIS:
  670. return false;
  671. }
  672. } else RR->mc->addCredential(tPtr,com,false);
  673. }
  674. }
  675. ++p; // skip trailing 0 after COMs if present
  676. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  677. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  678. for(unsigned int i=0;i<numCapabilities;++i) {
  679. p += cap.deserialize(*this,p);
  680. if ((!network)||(network->id() != cap.networkId()))
  681. network = RR->node->network(cap.networkId());
  682. if (network) {
  683. switch (network->addCredential(tPtr,cap)) {
  684. case Membership::ADD_REJECTED:
  685. break;
  686. case Membership::ADD_ACCEPTED_NEW:
  687. case Membership::ADD_ACCEPTED_REDUNDANT:
  688. trustEstablished = true;
  689. break;
  690. case Membership::ADD_DEFERRED_FOR_WHOIS:
  691. return false;
  692. }
  693. }
  694. }
  695. if (p >= size()) return true;
  696. const unsigned int numTags = at<uint16_t>(p); p += 2;
  697. for(unsigned int i=0;i<numTags;++i) {
  698. p += tag.deserialize(*this,p);
  699. if ((!network)||(network->id() != tag.networkId()))
  700. network = RR->node->network(tag.networkId());
  701. if (network) {
  702. switch (network->addCredential(tPtr,tag)) {
  703. case Membership::ADD_REJECTED:
  704. break;
  705. case Membership::ADD_ACCEPTED_NEW:
  706. case Membership::ADD_ACCEPTED_REDUNDANT:
  707. trustEstablished = true;
  708. break;
  709. case Membership::ADD_DEFERRED_FOR_WHOIS:
  710. return false;
  711. }
  712. }
  713. }
  714. if (p >= size()) return true;
  715. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  716. for(unsigned int i=0;i<numRevocations;++i) {
  717. p += revocation.deserialize(*this,p);
  718. if ((!network)||(network->id() != revocation.networkId()))
  719. network = RR->node->network(revocation.networkId());
  720. if (network) {
  721. switch(network->addCredential(tPtr,peer->address(),revocation)) {
  722. case Membership::ADD_REJECTED:
  723. break;
  724. case Membership::ADD_ACCEPTED_NEW:
  725. case Membership::ADD_ACCEPTED_REDUNDANT:
  726. trustEstablished = true;
  727. break;
  728. case Membership::ADD_DEFERRED_FOR_WHOIS:
  729. return false;
  730. }
  731. }
  732. }
  733. if (p >= size()) return true;
  734. const unsigned int numCoos = at<uint16_t>(p); p += 2;
  735. for(unsigned int i=0;i<numCoos;++i) {
  736. p += coo.deserialize(*this,p);
  737. if ((!network)||(network->id() != coo.networkId()))
  738. network = RR->node->network(coo.networkId());
  739. if (network) {
  740. switch(network->addCredential(tPtr,coo)) {
  741. case Membership::ADD_REJECTED:
  742. break;
  743. case Membership::ADD_ACCEPTED_NEW:
  744. case Membership::ADD_ACCEPTED_REDUNDANT:
  745. trustEstablished = true;
  746. break;
  747. case Membership::ADD_DEFERRED_FOR_WHOIS:
  748. return false;
  749. }
  750. }
  751. }
  752. }
  753. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,trustEstablished,(network) ? network->id() : 0);
  754. return true;
  755. }
  756. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  757. {
  758. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  759. const unsigned int hopCount = hops();
  760. const uint64_t requestPacketId = packetId();
  761. if (RR->localNetworkController) {
  762. const unsigned int metaDataLength = (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN <= size()) ? at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN) : 0;
  763. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  764. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  765. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  766. } else {
  767. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  768. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  769. outp.append(requestPacketId);
  770. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  771. outp.append(nwid);
  772. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  773. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  774. }
  775. peer->received(tPtr,_path,hopCount,requestPacketId,Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,false,nwid);
  776. return true;
  777. }
  778. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  779. {
  780. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  781. if (network) {
  782. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PACKET_IDX_PAYLOAD);
  783. if (configUpdateId) {
  784. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  785. outp.append((uint8_t)Packet::VERB_ECHO);
  786. outp.append((uint64_t)packetId());
  787. outp.append((uint64_t)network->id());
  788. outp.append((uint64_t)configUpdateId);
  789. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  790. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  791. }
  792. }
  793. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,false,(network) ? network->id() : 0);
  794. return true;
  795. }
  796. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  797. {
  798. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  799. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  800. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  801. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  802. const SharedPtr<Network> network(RR->node->network(nwid));
  803. if ((flags & 0x01) != 0) {
  804. try {
  805. CertificateOfMembership com;
  806. com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  807. if (com) {
  808. if (network)
  809. network->addCredential(tPtr,com);
  810. else RR->mc->addCredential(tPtr,com,false);
  811. }
  812. } catch ( ... ) {} // discard invalid COMs
  813. }
  814. const bool trustEstablished = ((network)&&(network->gate(tPtr,peer)));
  815. if (!trustEstablished)
  816. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  817. if ( ( trustEstablished || RR->mc->cacheAuthorized(peer->address(),nwid,RR->node->now()) ) && (gatherLimit > 0) ) {
  818. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  819. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  820. outp.append(packetId());
  821. outp.append(nwid);
  822. mg.mac().appendTo(outp);
  823. outp.append((uint32_t)mg.adi());
  824. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  825. if (gatheredLocally > 0) {
  826. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  827. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  828. }
  829. }
  830. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,trustEstablished,nwid);
  831. return true;
  832. }
  833. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  834. {
  835. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID);
  836. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS];
  837. const SharedPtr<Network> network(RR->node->network(nwid));
  838. if (network) {
  839. // Offset -- size of optional fields added to position of later fields
  840. unsigned int offset = 0;
  841. if ((flags & 0x01) != 0) {
  842. // This is deprecated but may still be sent by old peers
  843. CertificateOfMembership com;
  844. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM);
  845. if (com)
  846. network->addCredential(tPtr,com);
  847. }
  848. if (!network->gate(tPtr,peer)) {
  849. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,true);
  850. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  851. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false,nwid);
  852. return true;
  853. }
  854. unsigned int gatherLimit = 0;
  855. if ((flags & 0x02) != 0) {
  856. gatherLimit = at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT);
  857. offset += 4;
  858. }
  859. MAC from;
  860. if ((flags & 0x04) != 0) {
  861. from.setTo(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6),6);
  862. offset += 6;
  863. } else {
  864. from.fromAddress(peer->address(),nwid);
  865. }
  866. const MulticastGroup to(MAC(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC,6),6),at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI));
  867. const unsigned int etherType = at<uint16_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  868. const unsigned int frameLen = size() - (offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME);
  869. if (network->config().multicastLimit == 0) {
  870. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"multicast disabled");
  871. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false,nwid);
  872. return true;
  873. }
  874. if ((frameLen > 0)&&(frameLen <= ZT_MAX_MTU)) {
  875. if (!to.mac().isMulticast()) {
  876. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"destination not multicast");
  877. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  878. return true;
  879. }
  880. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  881. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"invalid source MAC");
  882. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  883. return true;
  884. }
  885. if (from != MAC(peer->address(),nwid)) {
  886. if (network->config().permitsBridging(peer->address())) {
  887. network->learnBridgeRoute(from,peer->address());
  888. } else {
  889. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"bridging not allowed (remote)");
  890. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  891. return true;
  892. }
  893. }
  894. const uint8_t *const frameData = (const uint8_t *)field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME,frameLen);
  895. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to.mac(),frameData,frameLen,etherType,0) > 0)
  896. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to.mac(),etherType,0,(const void *)frameData,frameLen);
  897. }
  898. if (gatherLimit) {
  899. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  900. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  901. outp.append(packetId());
  902. outp.append(nwid);
  903. to.mac().appendTo(outp);
  904. outp.append((uint32_t)to.adi());
  905. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  906. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  907. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  908. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  909. }
  910. }
  911. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid);
  912. } else {
  913. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  914. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false,nwid);
  915. }
  916. return true;
  917. }
  918. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  919. {
  920. const int64_t now = RR->node->now();
  921. // First, subject this to a rate limit
  922. if (!peer->rateGatePushDirectPaths(now)) {
  923. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false,0);
  924. return true;
  925. }
  926. // Second, limit addresses by scope and type
  927. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  928. memset(countPerScope,0,sizeof(countPerScope));
  929. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  930. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  931. while (count--) { // if ptr overflows Buffer will throw
  932. // TODO: some flags are not yet implemented
  933. unsigned int flags = (*this)[ptr++];
  934. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  935. ptr += extLen; // unused right now
  936. unsigned int addrType = (*this)[ptr++];
  937. unsigned int addrLen = (*this)[ptr++];
  938. switch(addrType) {
  939. case 4: {
  940. const InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  941. if (
  942. ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  943. (!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  944. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  945. {
  946. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  947. peer->redirect(tPtr,_path->localSocket(),a,now);
  948. } else if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  949. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false,0);
  950. }
  951. }
  952. } break;
  953. case 6: {
  954. const InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  955. if (
  956. ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  957. (!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  958. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  959. {
  960. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  961. peer->redirect(tPtr,_path->localSocket(),a,now);
  962. } else if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  963. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false,0);
  964. }
  965. }
  966. } break;
  967. }
  968. ptr += addrLen;
  969. }
  970. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false,0);
  971. return true;
  972. }
  973. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  974. {
  975. if (likely(size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  976. ZT_UserMessage um;
  977. um.origin = peer->address().toInt();
  978. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  979. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  980. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  981. RR->node->postEvent(tPtr,ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  982. }
  983. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_USER_MESSAGE,0,Packet::VERB_NOP,false,0);
  984. return true;
  985. }
  986. bool IncomingPacket::_doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  987. {
  988. ZT_RemoteTrace rt;
  989. const char *ptr = reinterpret_cast<const char *>(data()) + ZT_PACKET_IDX_PAYLOAD;
  990. const char *const eof = reinterpret_cast<const char *>(data()) + size();
  991. rt.origin = peer->address().toInt();
  992. rt.data = const_cast<char *>(ptr); // start of first string
  993. while (ptr < eof) {
  994. if (!*ptr) { // end of string
  995. rt.len = (unsigned int)(ptr - rt.data);
  996. if ((rt.len > 0)&&(rt.len <= ZT_MAX_REMOTE_TRACE_SIZE)) {
  997. RR->node->postEvent(tPtr,ZT_EVENT_REMOTE_TRACE,&rt);
  998. }
  999. rt.data = const_cast<char *>(++ptr); // start of next string, if any
  1000. } else {
  1001. ++ptr;
  1002. }
  1003. }
  1004. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_REMOTE_TRACE,0,Packet::VERB_NOP,false,0);
  1005. return true;
  1006. }
  1007. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid)
  1008. {
  1009. const int64_t now = RR->node->now();
  1010. if (peer->rateGateOutgoingComRequest(now)) {
  1011. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  1012. outp.append((uint8_t)verb());
  1013. outp.append(packetId());
  1014. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  1015. outp.append(nwid);
  1016. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  1017. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  1018. }
  1019. }
  1020. } // namespace ZeroTier