IncomingPacket.cpp 47 KB

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