IncomingPacket.cpp 43 KB

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