IncomingPacket.cpp 47 KB

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