IncomingPacket.cpp 48 KB

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