2
0

IncomingPacket.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include <list>
  17. #include "../include/ZeroTierOne.h"
  18. #include "Constants.hpp"
  19. #include "RuntimeEnvironment.hpp"
  20. #include "IncomingPacket.hpp"
  21. #include "Topology.hpp"
  22. #include "Switch.hpp"
  23. #include "Peer.hpp"
  24. #include "NetworkController.hpp"
  25. #include "SelfAwareness.hpp"
  26. #include "Salsa20.hpp"
  27. #include "Node.hpp"
  28. #include "CertificateOfMembership.hpp"
  29. #include "Capability.hpp"
  30. #include "Tag.hpp"
  31. #include "Revocation.hpp"
  32. #include "Trace.hpp"
  33. namespace ZeroTier {
  34. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr)
  35. {
  36. const Address sourceAddress(source());
  37. try {
  38. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  39. const unsigned int c = cipher();
  40. bool trusted = false;
  41. if (c == ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH) {
  42. // If this is marked as a packet via a trusted path, check source address and path ID.
  43. // Obviously if no trusted paths are configured this always returns false and such
  44. // packets are dropped on the floor.
  45. const uint64_t tpid = trustedPathId();
  46. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),tpid)) {
  47. trusted = true;
  48. } else {
  49. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"path not trusted");
  50. return true;
  51. }
  52. } else if ((c == ZT_PROTO_CIPHER_SUITE__POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  53. // Only HELLO is allowed in the clear, but will still have a MAC
  54. return _doHELLO(RR,tPtr,false);
  55. }
  56. const SharedPtr<Peer> peer(RR->topology->get(sourceAddress));
  57. if (peer) {
  58. if (!trusted) {
  59. if (!dearmor(peer->key())) {
  60. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops(),"invalid MAC");
  61. _path->recordInvalidPacket();
  62. return true;
  63. }
  64. }
  65. if (!uncompress()) {
  66. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),Packet::VERB_NOP,"LZ4 decompression failed");
  67. return true;
  68. }
  69. const Packet::Verb v = verb();
  70. bool r = true;
  71. switch(v) {
  72. //case Packet::VERB_NOP:
  73. default: // ignore unknown verbs, but if they pass auth check they are "received"
  74. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),v,0,Packet::VERB_NOP,0);
  75. break;
  76. case Packet::VERB_HELLO: r = _doHELLO(RR,tPtr,true); break;
  77. case Packet::VERB_ACK: r = _doACK(RR,tPtr,peer); break;
  78. case Packet::VERB_QOS_MEASUREMENT: r = _doQOS_MEASUREMENT(RR,tPtr,peer); break;
  79. case Packet::VERB_ERROR: r = _doERROR(RR,tPtr,peer); break;
  80. case Packet::VERB_OK: r = _doOK(RR,tPtr,peer); break;
  81. case Packet::VERB_WHOIS: r = _doWHOIS(RR,tPtr,peer); break;
  82. case Packet::VERB_RENDEZVOUS: r = _doRENDEZVOUS(RR,tPtr,peer); break;
  83. case Packet::VERB_FRAME: r = _doFRAME(RR,tPtr,peer); break;
  84. case Packet::VERB_EXT_FRAME: r = _doEXT_FRAME(RR,tPtr,peer); break;
  85. case Packet::VERB_ECHO: r = _doECHO(RR,tPtr,peer); break;
  86. case Packet::VERB_MULTICAST_LIKE: r = _doMULTICAST_LIKE(RR,tPtr,peer); break;
  87. case Packet::VERB_NETWORK_CREDENTIALS: r = _doNETWORK_CREDENTIALS(RR,tPtr,peer); break;
  88. case Packet::VERB_NETWORK_CONFIG_REQUEST: r = _doNETWORK_CONFIG_REQUEST(RR,tPtr,peer); break;
  89. case Packet::VERB_NETWORK_CONFIG: r = _doNETWORK_CONFIG(RR,tPtr,peer); break;
  90. case Packet::VERB_MULTICAST_GATHER: r = _doMULTICAST_GATHER(RR,tPtr,peer); break;
  91. case Packet::VERB_MULTICAST_FRAME: r = _doMULTICAST_FRAME(RR,tPtr,peer); break;
  92. case Packet::VERB_PUSH_DIRECT_PATHS: r = _doPUSH_DIRECT_PATHS(RR,tPtr,peer); break;
  93. case Packet::VERB_USER_MESSAGE: r = _doUSER_MESSAGE(RR,tPtr,peer); break;
  94. case Packet::VERB_REMOTE_TRACE: r = _doREMOTE_TRACE(RR,tPtr,peer); break;
  95. case Packet::VERB_SET_LOCATOR: break;
  96. case Packet::VERB_WILL_RELAY: break;
  97. case Packet::VERB_EPHEMERAL_KEY: break;
  98. }
  99. return r;
  100. } else {
  101. RR->sw->requestWhois(tPtr,RR->node->now(),sourceAddress);
  102. return false;
  103. }
  104. } catch (int ztExcCode) {
  105. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  106. return true;
  107. } catch ( ... ) {
  108. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  109. return true;
  110. }
  111. }
  112. bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  113. {
  114. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  115. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  116. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  117. uint64_t networkId = 0;
  118. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  119. * avoid having to log every outgoing packet ID. Instead we put the
  120. * logic to determine whether we should consider an ERROR in each
  121. * error handler. In most cases these are only trusted in specific
  122. * circumstances. */
  123. switch(errorCode) {
  124. case Packet::ERROR_OBJ_NOT_FOUND:
  125. // Object not found, currently only meaningful from network controllers.
  126. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  127. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  128. const SharedPtr<Network> network(RR->node->network(networkId));
  129. if ((network)&&(network->controller() == peer->address()))
  130. network->setNotFound();
  131. }
  132. break;
  133. case Packet::ERROR_UNSUPPORTED_OPERATION:
  134. // This can be sent in response to any operation, though right now we only
  135. // consider it meaningful from network controllers. This would indicate
  136. // that the queried node does not support acting as a controller.
  137. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  138. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  139. const SharedPtr<Network> network(RR->node->network(networkId));
  140. if ((network)&&(network->controller() == peer->address()))
  141. network->setNotFound();
  142. }
  143. break;
  144. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  145. // Peers can send this to ask for a cert for a network.
  146. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  147. const SharedPtr<Network> network(RR->node->network(networkId));
  148. const int64_t now = RR->node->now();
  149. if ((network)&&(network->config().com))
  150. network->pushCredentialsNow(tPtr,peer->address(),now);
  151. } break;
  152. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  153. // Network controller: network access denied.
  154. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  155. const SharedPtr<Network> network(RR->node->network(networkId));
  156. if ((network)&&(network->controller() == peer->address()))
  157. network->setAccessDenied();
  158. } break;
  159. case Packet::ERROR_UNWANTED_MULTICAST: {
  160. // Members of networks can use this error to indicate that they no longer
  161. // want to receive multicasts on a given channel.
  162. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  163. const SharedPtr<Network> network(RR->node->network(networkId));
  164. if ((network)&&(network->gate(tPtr,peer))) {
  165. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8,6),6),at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  166. RR->mc->remove(network->id(),mg,peer->address());
  167. }
  168. } break;
  169. default: break;
  170. }
  171. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_ERROR,inRePacketId,inReVerb,networkId);
  172. return true;
  173. }
  174. bool IncomingPacket::_doACK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  175. {
  176. if (!peer->rateGateACK(RR->node->now()))
  177. return true;
  178. /* Dissect incoming ACK packet. From this we can estimate current throughput of the path, establish known
  179. * maximums and detect packet loss. */
  180. if (peer->localMultipathSupport()) {
  181. int32_t ackedBytes;
  182. if (payloadLength() != sizeof(ackedBytes)) {
  183. return true; // ignore
  184. }
  185. memcpy(&ackedBytes, payload(), sizeof(ackedBytes));
  186. _path->receivedAck(RR->node->now(), Utils::ntoh(ackedBytes));
  187. peer->inferRemoteMultipathEnabled();
  188. }
  189. return true;
  190. }
  191. bool IncomingPacket::_doQOS_MEASUREMENT(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  192. {
  193. if (!peer->rateGateQoS(RR->node->now()))
  194. return true;
  195. /* Dissect incoming QoS packet. From this we can compute latency values and their variance.
  196. * The latency variance is used as a measure of "jitter". */
  197. if (peer->localMultipathSupport()) {
  198. if (payloadLength() > ZT_PATH_MAX_QOS_PACKET_SZ || payloadLength() < ZT_PATH_MIN_QOS_PACKET_SZ) {
  199. return true; // ignore
  200. }
  201. const int64_t now = RR->node->now();
  202. uint64_t rx_id[ZT_PATH_QOS_TABLE_SIZE];
  203. uint16_t rx_ts[ZT_PATH_QOS_TABLE_SIZE];
  204. char *begin = (char *)payload();
  205. char *ptr = begin;
  206. int count = 0;
  207. int len = payloadLength();
  208. // Read packet IDs and latency compensation intervals for each packet tracked by this QoS packet
  209. while (ptr < (begin + len) && (count < ZT_PATH_QOS_TABLE_SIZE)) {
  210. memcpy((void*)&rx_id[count], ptr, sizeof(uint64_t));
  211. ptr+=sizeof(uint64_t);
  212. memcpy((void*)&rx_ts[count], ptr, sizeof(uint16_t));
  213. ptr+=sizeof(uint16_t);
  214. count++;
  215. }
  216. _path->receivedQoS(now, count, rx_id, rx_ts);
  217. peer->inferRemoteMultipathEnabled();
  218. }
  219. return true;
  220. }
  221. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool alreadyAuthenticated)
  222. {
  223. const int64_t now = RR->node->now();
  224. const uint64_t pid = packetId();
  225. const Address fromAddress(source());
  226. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  227. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  228. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  229. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  230. const int64_t timestamp = at<int64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  231. Identity id;
  232. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  233. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  234. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"protocol version too old");
  235. return true;
  236. }
  237. if (fromAddress != id.address()) {
  238. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"identity/address mismatch");
  239. return true;
  240. }
  241. SharedPtr<Peer> peer(RR->topology->get(id.address()));
  242. if (peer) {
  243. // We already have an identity with this address -- check for collisions
  244. if (!alreadyAuthenticated) {
  245. if (peer->identity() != id) {
  246. // Identity is different from the one we already have -- address collision
  247. // Check rate limits
  248. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  249. return true;
  250. uint8_t key[ZT_PEER_SECRET_KEY_LENGTH];
  251. if (RR->identity.agree(id,key)) {
  252. if (dearmor(key)) { // ensure packet is authentic, otherwise drop
  253. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"address collision");
  254. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  255. outp.append((uint8_t)Packet::VERB_HELLO);
  256. outp.append((uint64_t)pid);
  257. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  258. outp.armor(key,true);
  259. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  260. } else {
  261. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  262. }
  263. } else {
  264. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid identity");
  265. }
  266. return true;
  267. } else {
  268. // Identity is the same as the one we already have -- check packet integrity
  269. if (!dearmor(peer->key())) {
  270. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  271. return true;
  272. }
  273. // Continue at // VALID
  274. }
  275. } // else if alreadyAuthenticated then continue at // VALID
  276. } else {
  277. // We don't already have an identity with this address -- validate and learn it
  278. // Sanity check: this basically can't happen
  279. if (alreadyAuthenticated) {
  280. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"illegal alreadyAuthenticated state");
  281. return true;
  282. }
  283. // Check rate limits
  284. if (!RR->node->rateGateIdentityVerification(now,_path->address())) {
  285. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"rate limit exceeded");
  286. return true;
  287. }
  288. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  289. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  290. if (!dearmor(newPeer->key())) {
  291. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops(),"invalid MAC");
  292. return true;
  293. }
  294. // Check that identity's address is valid as per the derivation function
  295. if (!id.locallyValidate()) {
  296. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"invalid identity");
  297. return true;
  298. }
  299. peer = RR->topology->add(newPeer);
  300. // Continue at // VALID
  301. }
  302. // VALID -- if we made it here, packet passed identity and authenticity checks!
  303. // Get address to which this packet was sent to learn our external surface address if packet was direct.
  304. if (hops() == 0) {
  305. InetAddress externalSurfaceAddress;
  306. if (ptr < size()) {
  307. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  308. if ((externalSurfaceAddress)&&(hops() == 0))
  309. RR->sa->iam(tPtr,id.address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isRoot(id),now);
  310. }
  311. }
  312. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  313. // information about us: version, sent-to address, etc.
  314. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  315. outp.append((unsigned char)Packet::VERB_HELLO);
  316. outp.append((uint64_t)pid);
  317. outp.append((uint64_t)timestamp);
  318. outp.append((unsigned char)ZT_PROTO_VERSION);
  319. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  320. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  321. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  322. _path->address().serialize(outp);
  323. outp.armor(peer->key(),true);
  324. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  325. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  326. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_HELLO,0,Packet::VERB_NOP,0);
  327. return true;
  328. }
  329. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  330. {
  331. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  332. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  333. uint64_t networkId = 0;
  334. if (!RR->node->expectingReplyTo(inRePacketId))
  335. return true;
  336. switch(inReVerb) {
  337. case Packet::VERB_HELLO: {
  338. const uint64_t latency = RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  339. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  340. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  341. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  342. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  343. if (vProto < ZT_PROTO_VERSION_MIN)
  344. return true;
  345. if (hops() == 0) {
  346. _path->updateLatency((unsigned int)latency,RR->node->now());
  347. if ((ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2) < size()) {
  348. InetAddress externalSurfaceAddress;
  349. externalSurfaceAddress.deserialize(*this,ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2);
  350. if (externalSurfaceAddress)
  351. RR->sa->iam(tPtr,peer->address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isRoot(peer->identity()),RR->node->now());
  352. }
  353. }
  354. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  355. } break;
  356. case Packet::VERB_WHOIS:
  357. if (RR->topology->isRoot(peer->identity())) {
  358. unsigned int p = ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY;
  359. while (p < size()) {
  360. try {
  361. Identity id;
  362. p += id.deserialize(*this,p);
  363. if (id)
  364. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->add(SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  365. } catch ( ... ) {
  366. break;
  367. }
  368. }
  369. }
  370. break;
  371. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  372. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  373. const SharedPtr<Network> network(RR->node->network(networkId));
  374. if (network)
  375. network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  376. } break;
  377. case Packet::VERB_MULTICAST_GATHER: {
  378. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  379. const SharedPtr<Network> network(RR->node->network(networkId));
  380. if (network) {
  381. 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));
  382. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  383. if (((ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 6) + (count * 5)) <= size())
  384. 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));
  385. }
  386. } break;
  387. case Packet::VERB_MULTICAST_FRAME: {
  388. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  389. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  390. 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));
  391. const SharedPtr<Network> network(RR->node->network(networkId));
  392. if (network) {
  393. unsigned int offset = 0;
  394. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  395. CertificateOfMembership com;
  396. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  397. if (com)
  398. network->addCredential(tPtr,com);
  399. }
  400. if ((flags & 0x02) != 0) {
  401. // OK(MULTICAST_FRAME) includes implicit gather results
  402. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  403. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  404. unsigned int count = at<uint16_t>(offset); offset += 2;
  405. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(offset,count * 5),count,totalKnown);
  406. }
  407. }
  408. } break;
  409. default: break;
  410. }
  411. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_OK,inRePacketId,inReVerb,networkId);
  412. return true;
  413. }
  414. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  415. {
  416. if (!peer->rateGateInboundWhoisRequest(RR->node->now()))
  417. return true;
  418. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  419. outp.append((unsigned char)Packet::VERB_WHOIS);
  420. outp.append(packetId());
  421. unsigned int count = 0;
  422. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  423. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  424. const Address addr(field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  425. ptr += ZT_ADDRESS_LENGTH;
  426. const Identity id(RR->topology->getIdentity(tPtr,addr));
  427. if (id) {
  428. id.serialize(outp,false);
  429. ++count;
  430. } else {
  431. // Request unknown WHOIS from upstream from us (if we have one)
  432. RR->sw->requestWhois(tPtr,RR->node->now(),addr);
  433. }
  434. }
  435. if (count > 0) {
  436. outp.armor(peer->key(),true);
  437. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  438. }
  439. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,0);
  440. return true;
  441. }
  442. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  443. {
  444. if (RR->topology->isRoot(peer->identity())) {
  445. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  446. const SharedPtr<Peer> rendezvousWith(RR->topology->get(with));
  447. if (rendezvousWith) {
  448. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  449. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  450. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  451. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  452. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,with,_path->localSocket(),atAddr)) {
  453. const uint64_t junk = Utils::random();
  454. RR->node->putPacket(tPtr,_path->localSocket(),atAddr,&junk,4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  455. rendezvousWith->sendHELLO(tPtr,_path->localSocket(),atAddr,RR->node->now());
  456. }
  457. }
  458. }
  459. }
  460. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,0);
  461. return true;
  462. }
  463. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  464. {
  465. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  466. const SharedPtr<Network> network(RR->node->network(nwid));
  467. if (network) {
  468. if (network->gate(tPtr,peer)) {
  469. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  470. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  471. const MAC sourceMac(peer->address(),nwid);
  472. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  473. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  474. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  475. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  476. }
  477. } else {
  478. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  479. return false;
  480. }
  481. }
  482. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_FRAME,0,Packet::VERB_NOP,nwid);
  483. return true;
  484. }
  485. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  486. {
  487. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  488. const SharedPtr<Network> network(RR->node->network(nwid));
  489. if (network) {
  490. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  491. unsigned int comLen = 0;
  492. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  493. CertificateOfMembership com;
  494. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  495. if (com)
  496. network->addCredential(tPtr,com);
  497. }
  498. if (!network->gate(tPtr,peer)) {
  499. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  500. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  501. return false;
  502. }
  503. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  504. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  505. 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);
  506. 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);
  507. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  508. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  509. if ((!from)||(from == network->mac())) {
  510. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  511. return true;
  512. }
  513. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  514. case 1:
  515. if (from != MAC(peer->address(),nwid)) {
  516. if (network->config().permitsBridging(peer->address())) {
  517. network->learnBridgeRoute(from,peer->address());
  518. } else {
  519. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  520. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  521. return true;
  522. }
  523. } else if (to != network->mac()) {
  524. if (to.isMulticast()) {
  525. if (network->config().multicastLimit == 0) {
  526. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  527. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  528. return true;
  529. }
  530. } else if (!network->config().permitsBridging(RR->identity.address())) {
  531. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  532. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  533. return true;
  534. }
  535. }
  536. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  537. case 2:
  538. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  539. break;
  540. }
  541. }
  542. if ((flags & 0x10) != 0) { // ACK requested
  543. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  544. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  545. outp.append((uint64_t)packetId());
  546. outp.append((uint64_t)nwid);
  547. outp.armor(peer->key(),true);
  548. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  549. }
  550. }
  551. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,nwid);
  552. return true;
  553. }
  554. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  555. {
  556. if (!peer->rateGateEchoRequest(RR->node->now()))
  557. return true;
  558. const uint64_t pid = packetId();
  559. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  560. outp.append((unsigned char)Packet::VERB_ECHO);
  561. outp.append((uint64_t)pid);
  562. if (size() > ZT_PACKET_IDX_PAYLOAD)
  563. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  564. outp.armor(peer->key(),true);
  565. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  566. peer->received(tPtr,_path,hops(),pid,payloadLength(),Packet::VERB_ECHO,0,Packet::VERB_NOP,0);
  567. return true;
  568. }
  569. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  570. {
  571. const int64_t now = RR->node->now();
  572. bool authorized = false;
  573. uint64_t lastNwid = 0;
  574. // Packet contains a series of 18-byte network,MAC,ADI tuples
  575. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;(ptr+18)<=size();ptr+=18) {
  576. const uint64_t nwid = at<uint64_t>(ptr);
  577. if (nwid != lastNwid) {
  578. lastNwid = nwid;
  579. SharedPtr<Network> network(RR->node->network(nwid));
  580. if (network)
  581. authorized = network->gate(tPtr,peer);
  582. //if (!authorized)
  583. // authorized = ((RR->topology->amUpstream())||(RR->node->localControllerHasAuthorized(now,nwid,peer->address())));
  584. }
  585. if (authorized)
  586. RR->mc->add(tPtr,now,nwid,MulticastGroup(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14)),peer->address());
  587. }
  588. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,0);
  589. return true;
  590. }
  591. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  592. {
  593. if (!peer->rateGateCredentialsReceived(RR->node->now()))
  594. return true;
  595. CertificateOfMembership com;
  596. Capability cap;
  597. Tag tag;
  598. Revocation revocation;
  599. CertificateOfOwnership coo;
  600. SharedPtr<Network> network;
  601. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  602. while ((p < size())&&((*this)[p] != 0)) {
  603. p += com.deserialize(*this,p);
  604. if (com) {
  605. network = RR->node->network(com.networkId());
  606. if (network) {
  607. if (network->addCredential(tPtr,com) == Membership::ADD_DEFERRED_FOR_WHOIS)
  608. return false;
  609. }
  610. }
  611. }
  612. ++p; // skip trailing 0 after COMs if present
  613. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  614. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  615. for(unsigned int i=0;i<numCapabilities;++i) {
  616. p += cap.deserialize(*this,p);
  617. if ((!network)||(network->id() != cap.networkId()))
  618. network = RR->node->network(cap.networkId());
  619. if (network) {
  620. if (network->addCredential(tPtr,cap) == Membership::ADD_DEFERRED_FOR_WHOIS)
  621. return false;
  622. }
  623. }
  624. if (p >= size()) return true;
  625. const unsigned int numTags = at<uint16_t>(p); p += 2;
  626. for(unsigned int i=0;i<numTags;++i) {
  627. p += tag.deserialize(*this,p);
  628. if ((!network)||(network->id() != tag.networkId()))
  629. network = RR->node->network(tag.networkId());
  630. if (network) {
  631. if (network->addCredential(tPtr,tag) == Membership::ADD_DEFERRED_FOR_WHOIS)
  632. return false;
  633. }
  634. }
  635. if (p >= size()) return true;
  636. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  637. for(unsigned int i=0;i<numRevocations;++i) {
  638. p += revocation.deserialize(*this,p);
  639. if ((!network)||(network->id() != revocation.networkId()))
  640. network = RR->node->network(revocation.networkId());
  641. if (network) {
  642. if (network->addCredential(tPtr,peer->address(),revocation) == Membership::ADD_DEFERRED_FOR_WHOIS)
  643. return false;
  644. }
  645. }
  646. if (p >= size()) return true;
  647. const unsigned int numCoos = at<uint16_t>(p); p += 2;
  648. for(unsigned int i=0;i<numCoos;++i) {
  649. p += coo.deserialize(*this,p);
  650. if ((!network)||(network->id() != coo.networkId()))
  651. network = RR->node->network(coo.networkId());
  652. if (network) {
  653. if (network->addCredential(tPtr,coo) == Membership::ADD_DEFERRED_FOR_WHOIS)
  654. return false;
  655. }
  656. }
  657. }
  658. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,(network) ? network->id() : 0);
  659. return true;
  660. }
  661. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  662. {
  663. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  664. const unsigned int hopCount = hops();
  665. const uint64_t requestPacketId = packetId();
  666. if (RR->localNetworkController) {
  667. 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;
  668. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  669. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  670. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  671. } else {
  672. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  673. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  674. outp.append(requestPacketId);
  675. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  676. outp.append(nwid);
  677. outp.armor(peer->key(),true);
  678. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  679. }
  680. peer->received(tPtr,_path,hopCount,requestPacketId,payloadLength(),Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,nwid);
  681. return true;
  682. }
  683. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  684. {
  685. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  686. if (network) {
  687. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PACKET_IDX_PAYLOAD);
  688. if (configUpdateId) {
  689. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  690. outp.append((uint8_t)Packet::VERB_ECHO);
  691. outp.append((uint64_t)packetId());
  692. outp.append((uint64_t)network->id());
  693. outp.append((uint64_t)configUpdateId);
  694. outp.armor(peer->key(),true);
  695. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  696. }
  697. }
  698. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,(network) ? network->id() : 0);
  699. return true;
  700. }
  701. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  702. {
  703. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  704. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  705. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  706. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  707. const SharedPtr<Network> network(RR->node->network(nwid));
  708. if ((flags & 0x01) != 0) {
  709. try {
  710. CertificateOfMembership com;
  711. com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  712. if ((com)&&(network))
  713. network->addCredential(tPtr,com);
  714. } catch ( ... ) {} // discard invalid COMs
  715. }
  716. if (network) {
  717. if (!network->gate(tPtr,peer)) {
  718. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  719. return false;
  720. }
  721. }
  722. const int64_t now = RR->node->now();
  723. if (gatherLimit) {
  724. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  725. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  726. outp.append(packetId());
  727. outp.append(nwid);
  728. mg.mac().appendTo(outp);
  729. outp.append((uint32_t)mg.adi());
  730. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  731. if (gatheredLocally > 0) {
  732. outp.armor(peer->key(),true);
  733. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  734. }
  735. }
  736. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,nwid);
  737. return true;
  738. }
  739. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  740. {
  741. unsigned int offset = ZT_PACKET_IDX_PAYLOAD;
  742. const uint64_t nwid = at<uint64_t>(offset); offset += 8;
  743. const unsigned int flags = (*this)[offset]; ++offset;
  744. const SharedPtr<Network> network(RR->node->network(nwid));
  745. if (network) {
  746. if ((flags & 0x01) != 0) {
  747. // This is deprecated but may still be sent by old peers
  748. CertificateOfMembership com;
  749. offset += com.deserialize(*this,offset);
  750. if (com)
  751. network->addCredential(tPtr,com);
  752. }
  753. if (!network->gate(tPtr,peer)) {
  754. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  755. return false;
  756. }
  757. unsigned int gatherLimit = 0;
  758. if ((flags & 0x02) != 0) {
  759. gatherLimit = at<uint32_t>(offset); offset += 4;
  760. }
  761. MAC from;
  762. if ((flags & 0x04) != 0) {
  763. from.setTo(field(offset,6),6); offset += 6;
  764. } else {
  765. from.fromAddress(peer->address(),nwid);
  766. }
  767. const unsigned int recipientsOffset = offset;
  768. std::list<Address> recipients;
  769. if ((flags & 0x08) != 0) {
  770. const unsigned int rc = at<uint16_t>(offset); offset += 2;
  771. for(unsigned int i=0;i<rc;++i) {
  772. const Address a(field(offset,5),5);
  773. if ((a != peer->address())&&(a != RR->identity.address())) {
  774. recipients.push_back(a);
  775. }
  776. offset += 5;
  777. }
  778. }
  779. const unsigned int afterRecipientsOffset = offset;
  780. const MulticastGroup to(MAC(field(offset,6),6),at<uint32_t>(offset + 6)); offset += 10;
  781. const unsigned int etherType = at<uint16_t>(offset); offset += 2;
  782. const unsigned int frameLen = size() - offset;
  783. if (network->config().multicastLimit == 0) {
  784. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"multicast disabled");
  785. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  786. return true;
  787. }
  788. if (!to.mac().isMulticast()) {
  789. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"destination not multicast");
  790. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  791. return true;
  792. }
  793. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  794. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"invalid source MAC");
  795. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  796. return true;
  797. }
  798. if ((frameLen > 0)&&(frameLen <= ZT_MAX_MTU)) {
  799. const uint8_t *const frameData = ((const uint8_t *)unsafeData()) + offset;
  800. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to.mac(),frameData,frameLen,etherType,0) > 0) {
  801. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to.mac(),etherType,0,(const void *)frameData,frameLen);
  802. }
  803. }
  804. if (!recipients.empty()) {
  805. // TODO
  806. /*
  807. const std::vector<Address> anchors = network->config().anchors();
  808. const bool amAnchor = (std::find(anchors.begin(),anchors.end(),RR->identity.address()) != anchors.end());
  809. for(std::list<Address>::iterator ra(recipients.begin());ra!=recipients.end();) {
  810. SharedPtr<Peer> recipient(RR->topology->get(*ra));
  811. if ((recipient)&&((recipient->remoteVersionProtocol() < 10)||(amAnchor))) {
  812. Packet outp(*ra,RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  813. outp.append(field(ZT_PACKET_IDX_PAYLOAD,recipientsOffset - ZT_PACKET_IDX_PAYLOAD),recipientsOffset - ZT_PACKET_IDX_PAYLOAD);
  814. outp.append(field(afterRecipientsOffset,size() - afterRecipientsOffset),size() - afterRecipientsOffset);
  815. RR->sw->send(tPtr,outp,true);
  816. recipients.erase(ra++);
  817. } else ++ra;
  818. }
  819. if (!recipients.empty()) {
  820. Packet outp(recipients.front(),RR->identity.address(),Packet::VERB_MULTICAST_FRAME);
  821. recipients.pop_front();
  822. outp.append(field(ZT_PACKET_IDX_PAYLOAD,recipientsOffset - ZT_PACKET_IDX_PAYLOAD),recipientsOffset - ZT_PACKET_IDX_PAYLOAD);
  823. if (!recipients.empty()) {
  824. outp.append((uint16_t)recipients.size());
  825. for(std::list<Address>::iterator ra(recipients.begin());ra!=recipients.end();++ra)
  826. ra->appendTo(outp);
  827. }
  828. outp.append(field(afterRecipientsOffset,size() - afterRecipientsOffset),size() - afterRecipientsOffset);
  829. RR->sw->send(tPtr,outp,true);
  830. }
  831. */
  832. }
  833. if (gatherLimit) { // DEPRECATED but still supported
  834. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  835. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  836. outp.append(packetId());
  837. outp.append(nwid);
  838. to.mac().appendTo(outp);
  839. outp.append((uint32_t)to.adi());
  840. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  841. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  842. outp.armor(peer->key(),true);
  843. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  844. }
  845. }
  846. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,nwid);
  847. return true;
  848. } else {
  849. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  850. return false;
  851. }
  852. }
  853. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  854. {
  855. const int64_t now = RR->node->now();
  856. // First, subject this to a rate limit
  857. if (!peer->rateGatePushDirectPaths(now)) {
  858. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,0);
  859. return true;
  860. }
  861. // Second, limit addresses by scope and type
  862. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  863. memset(countPerScope,0,sizeof(countPerScope));
  864. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  865. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  866. while (count--) { // if ptr overflows Buffer will throw
  867. /* unsigned int flags = (*this)[ptr++]; */ ++ptr;
  868. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  869. ptr += extLen; // unused right now
  870. unsigned int addrType = (*this)[ptr++];
  871. unsigned int addrLen = (*this)[ptr++];
  872. switch(addrType) {
  873. case 4: {
  874. const InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  875. if ((!peer->hasActivePathTo(now,a)) && // not already known
  876. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),-1,a)) ) // should use path
  877. {
  878. if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  879. peer->sendHELLO(tPtr,-1,a,now);
  880. }
  881. } break;
  882. case 6: {
  883. const InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  884. if ((!peer->hasActivePathTo(now,a)) && // not already known
  885. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),-1,a)) ) // should use path
  886. {
  887. if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
  888. peer->sendHELLO(tPtr,-1,a,now);
  889. }
  890. } break;
  891. }
  892. ptr += addrLen;
  893. }
  894. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,0);
  895. return true;
  896. }
  897. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  898. {
  899. if (likely(size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  900. ZT_UserMessage um;
  901. um.origin = peer->address().toInt();
  902. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  903. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  904. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  905. RR->node->postEvent(tPtr,ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  906. }
  907. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_USER_MESSAGE,0,Packet::VERB_NOP,0);
  908. return true;
  909. }
  910. bool IncomingPacket::_doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  911. {
  912. ZT_RemoteTrace rt;
  913. const char *ptr = reinterpret_cast<const char *>(data()) + ZT_PACKET_IDX_PAYLOAD;
  914. const char *const eof = reinterpret_cast<const char *>(data()) + size();
  915. rt.origin = peer->address().toInt();
  916. rt.data = const_cast<char *>(ptr); // start of first string
  917. while (ptr < eof) {
  918. if (!*ptr) { // end of string
  919. rt.len = (unsigned int)(ptr - rt.data);
  920. if ((rt.len > 0)&&(rt.len <= ZT_MAX_REMOTE_TRACE_SIZE)) {
  921. RR->node->postEvent(tPtr,ZT_EVENT_REMOTE_TRACE,&rt);
  922. }
  923. rt.data = const_cast<char *>(++ptr); // start of next string, if any
  924. } else {
  925. ++ptr;
  926. }
  927. }
  928. peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_REMOTE_TRACE,0,Packet::VERB_NOP,0);
  929. return true;
  930. }
  931. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid)
  932. {
  933. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  934. outp.append((uint8_t)verb());
  935. outp.append(packetId());
  936. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  937. outp.append(nwid);
  938. outp.armor(peer->key(),true);
  939. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  940. }
  941. } // namespace ZeroTier