IncomingPacket.cpp 47 KB

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