IncomingPacket.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "IncomingPacket.hpp"
  14. #include "../include/ZeroTierOne.h"
  15. #include "../version.h"
  16. #include "Bond.hpp"
  17. #include "Capability.hpp"
  18. #include "CertificateOfMembership.hpp"
  19. #include "Constants.hpp"
  20. #include "Metrics.hpp"
  21. #include "NetworkController.hpp"
  22. #include "Node.hpp"
  23. #include "PacketMultiplexer.hpp"
  24. #include "Path.hpp"
  25. #include "Peer.hpp"
  26. #include "Revocation.hpp"
  27. #include "RuntimeEnvironment.hpp"
  28. #include "SHA512.hpp"
  29. #include "Salsa20.hpp"
  30. #include "SelfAwareness.hpp"
  31. #include "Switch.hpp"
  32. #include "Tag.hpp"
  33. #include "Topology.hpp"
  34. #include "Trace.hpp"
  35. #include "World.hpp"
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. namespace ZeroTier {
  40. bool IncomingPacket::tryDecode(const RuntimeEnvironment* RR, void* tPtr, int32_t flowId)
  41. {
  42. const Address sourceAddress(source());
  43. try {
  44. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  45. const unsigned int c = cipher();
  46. if (c == ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH) {
  47. // If this is marked as a packet via a trusted path, check source address and path ID.
  48. // Obviously if no trusted paths are configured this always returns false and such
  49. // packets are dropped on the floor.
  50. const uint64_t tpid = trustedPathId();
  51. if (RR->topology->shouldInboundPathBeTrusted(_path->address(), tpid)) {
  52. _authenticated = true;
  53. }
  54. else {
  55. RR->t->incomingPacketMessageAuthenticationFailure(tPtr, _path, packetId(), sourceAddress, hops(), "path not trusted");
  56. return true;
  57. }
  58. }
  59. else if ((c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE) && (verb() == Packet::VERB_HELLO)) {
  60. // Only HELLO is allowed in the clear, but will still have a MAC
  61. return _doHELLO(RR, tPtr, false);
  62. }
  63. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr, sourceAddress));
  64. if (peer) {
  65. if (! _authenticated) {
  66. if (! dearmor(peer->key(), peer->aesKeys(), RR->identity)) {
  67. RR->t->incomingPacketMessageAuthenticationFailure(tPtr, _path, packetId(), sourceAddress, hops(), "invalid MAC");
  68. peer->recordIncomingInvalidPacket(_path);
  69. return true;
  70. }
  71. }
  72. if (! uncompress()) {
  73. RR->t->incomingPacketInvalid(tPtr, _path, packetId(), sourceAddress, hops(), Packet::VERB_NOP, "LZ4 decompression failed");
  74. return true;
  75. }
  76. _authenticated = true;
  77. const Packet::Verb v = verb();
  78. bool r = true;
  79. switch (v) {
  80. // case Packet::VERB_NOP:
  81. default: // ignore unknown verbs, but if they pass auth check they are "received"
  82. Metrics::pkt_nop_in++;
  83. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), v, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  84. break;
  85. case Packet::VERB_HELLO:
  86. r = _doHELLO(RR, tPtr, true);
  87. break;
  88. case Packet::VERB_ACK:
  89. r = _doACK(RR, tPtr, peer);
  90. break;
  91. case Packet::VERB_QOS_MEASUREMENT:
  92. r = _doQOS_MEASUREMENT(RR, tPtr, peer);
  93. break;
  94. case Packet::VERB_ERROR:
  95. r = _doERROR(RR, tPtr, peer);
  96. break;
  97. case Packet::VERB_OK:
  98. r = _doOK(RR, tPtr, peer);
  99. break;
  100. case Packet::VERB_WHOIS:
  101. r = _doWHOIS(RR, tPtr, peer);
  102. break;
  103. case Packet::VERB_RENDEZVOUS:
  104. r = _doRENDEZVOUS(RR, tPtr, peer);
  105. break;
  106. case Packet::VERB_FRAME:
  107. r = _doFRAME(RR, tPtr, peer, flowId);
  108. break;
  109. case Packet::VERB_EXT_FRAME:
  110. r = _doEXT_FRAME(RR, tPtr, peer, flowId);
  111. break;
  112. case Packet::VERB_ECHO:
  113. r = _doECHO(RR, tPtr, peer);
  114. break;
  115. case Packet::VERB_MULTICAST_LIKE:
  116. r = _doMULTICAST_LIKE(RR, tPtr, peer);
  117. break;
  118. case Packet::VERB_NETWORK_CREDENTIALS:
  119. r = _doNETWORK_CREDENTIALS(RR, tPtr, peer);
  120. break;
  121. case Packet::VERB_NETWORK_CONFIG_REQUEST:
  122. r = _doNETWORK_CONFIG_REQUEST(RR, tPtr, peer);
  123. break;
  124. case Packet::VERB_NETWORK_CONFIG:
  125. r = _doNETWORK_CONFIG(RR, tPtr, peer);
  126. break;
  127. case Packet::VERB_MULTICAST_GATHER:
  128. r = _doMULTICAST_GATHER(RR, tPtr, peer);
  129. break;
  130. case Packet::VERB_MULTICAST_FRAME:
  131. r = _doMULTICAST_FRAME(RR, tPtr, peer);
  132. break;
  133. case Packet::VERB_PUSH_DIRECT_PATHS:
  134. r = _doPUSH_DIRECT_PATHS(RR, tPtr, peer);
  135. break;
  136. case Packet::VERB_USER_MESSAGE:
  137. r = _doUSER_MESSAGE(RR, tPtr, peer);
  138. break;
  139. case Packet::VERB_REMOTE_TRACE:
  140. r = _doREMOTE_TRACE(RR, tPtr, peer);
  141. break;
  142. case Packet::VERB_PATH_NEGOTIATION_REQUEST:
  143. r = _doPATH_NEGOTIATION_REQUEST(RR, tPtr, peer);
  144. break;
  145. }
  146. if (r) {
  147. RR->node->statsLogVerb((unsigned int)v, (unsigned int)size());
  148. return true;
  149. }
  150. return false;
  151. }
  152. else {
  153. RR->sw->requestWhois(tPtr, RR->node->now(), sourceAddress);
  154. return false;
  155. }
  156. }
  157. catch (...) {
  158. RR->t->incomingPacketInvalid(tPtr, _path, packetId(), sourceAddress, hops(), verb(), "unexpected exception in tryDecode()");
  159. return true;
  160. }
  161. }
  162. bool IncomingPacket::_doERROR(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  163. {
  164. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  165. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  166. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  167. uint64_t networkId = 0;
  168. Metrics::pkt_error_in++;
  169. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  170. * avoid having to log every outgoing packet ID. Instead we put the
  171. * logic to determine whether we should consider an ERROR in each
  172. * error handler. In most cases these are only trusted in specific
  173. * circumstances. */
  174. switch (errorCode) {
  175. case Packet::ERROR_OBJ_NOT_FOUND:
  176. // Object not found, currently only meaningful from network controllers.
  177. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  178. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  179. if ((network) && (network->controller() == peer->address())) {
  180. network->setNotFound(tPtr);
  181. }
  182. }
  183. Metrics::pkt_error_obj_not_found_in++;
  184. break;
  185. case Packet::ERROR_UNSUPPORTED_OPERATION:
  186. // This can be sent in response to any operation, though right now we only
  187. // consider it meaningful from network controllers. This would indicate
  188. // that the queried node does not support acting as a controller.
  189. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  190. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  191. if ((network) && (network->controller() == peer->address())) {
  192. network->setNotFound(tPtr);
  193. }
  194. }
  195. Metrics::pkt_error_unsupported_op_in++;
  196. break;
  197. case Packet::ERROR_IDENTITY_COLLISION:
  198. // FIXME: for federation this will need a payload with a signature or something.
  199. if (RR->topology->isUpstream(peer->identity())) {
  200. RR->node->postEvent(tPtr, ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION);
  201. }
  202. Metrics::pkt_error_identity_collision_in++;
  203. break;
  204. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  205. // Peers can send this in response to frames if they do not have a recent enough COM from us
  206. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  207. const SharedPtr<Network> network(RR->node->network(networkId));
  208. const int64_t now = RR->node->now();
  209. if ((network) && (network->config().com)) {
  210. network->peerRequestedCredentials(tPtr, peer->address(), now);
  211. }
  212. Metrics::pkt_error_need_membership_cert_in++;
  213. } break;
  214. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  215. // Network controller: network access denied.
  216. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  217. if ((network) && (network->controller() == peer->address())) {
  218. network->setAccessDenied(tPtr);
  219. }
  220. Metrics::pkt_error_network_access_denied_in++;
  221. } break;
  222. case Packet::ERROR_UNWANTED_MULTICAST: {
  223. // Members of networks can use this error to indicate that they no longer
  224. // want to receive multicasts on a given channel.
  225. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  226. const SharedPtr<Network> network(RR->node->network(networkId));
  227. if ((network) && (network->gate(tPtr, peer))) {
  228. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8, 6), 6), at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  229. RR->mc->remove(network->id(), mg, peer->address());
  230. }
  231. Metrics::pkt_error_unwanted_multicast_in++;
  232. } break;
  233. case Packet::ERROR_NETWORK_AUTHENTICATION_REQUIRED: {
  234. // fprintf(stderr, "\nPacket::ERROR_NETWORK_AUTHENTICATION_REQUIRED\n\n");
  235. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  236. if ((network) && (network->controller() == peer->address())) {
  237. int s = (int)size() - (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8);
  238. if (s > 2) {
  239. const uint16_t errorDataSize = at<uint16_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8);
  240. s -= 2;
  241. if (s >= (int)errorDataSize) {
  242. Dictionary<8192> authInfo(((const char*)this->data()) + (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 10), errorDataSize);
  243. uint64_t authVer = authInfo.getUI(ZT_AUTHINFO_DICT_KEY_VERSION, 0ULL);
  244. if (authVer == 0) {
  245. char authenticationURL[2048];
  246. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_AUTHENTICATION_URL, authenticationURL, sizeof(authenticationURL)) > 0) {
  247. authenticationURL[sizeof(authenticationURL) - 1] = 0; // ensure always zero terminated
  248. network->setAuthenticationRequired(tPtr, authenticationURL);
  249. }
  250. }
  251. else if (authVer == 1) {
  252. char issuerURL[2048] = { 0 };
  253. char centralAuthURL[2048] = { 0 };
  254. char ssoNonce[64] = { 0 };
  255. char ssoState[128] = { 0 };
  256. char ssoClientID[256] = { 0 };
  257. char ssoProvider[64] = { 0 };
  258. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_ISSUER_URL, issuerURL, sizeof(issuerURL)) > 0) {
  259. issuerURL[sizeof(issuerURL) - 1] = 0;
  260. }
  261. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_CENTRAL_ENDPOINT_URL, centralAuthURL, sizeof(centralAuthURL)) > 0) {
  262. centralAuthURL[sizeof(centralAuthURL) - 1] = 0;
  263. }
  264. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_NONCE, ssoNonce, sizeof(ssoNonce)) > 0) {
  265. ssoNonce[sizeof(ssoNonce) - 1] = 0;
  266. }
  267. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_STATE, ssoState, sizeof(ssoState)) > 0) {
  268. ssoState[sizeof(ssoState) - 1] = 0;
  269. }
  270. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_CLIENT_ID, ssoClientID, sizeof(ssoClientID)) > 0) {
  271. ssoClientID[sizeof(ssoClientID) - 1] = 0;
  272. }
  273. if (authInfo.get(ZT_AUTHINFO_DICT_KEY_SSO_PROVIDER, ssoProvider, sizeof(ssoProvider)) > 0) {
  274. ssoProvider[sizeof(ssoProvider) - 1] = 0;
  275. }
  276. else {
  277. strncpy(ssoProvider, "default", sizeof(ssoProvider));
  278. }
  279. network->setAuthenticationRequired(tPtr, issuerURL, centralAuthURL, ssoClientID, ssoProvider, ssoNonce, ssoState);
  280. }
  281. }
  282. }
  283. else {
  284. network->setAuthenticationRequired(tPtr, "");
  285. }
  286. }
  287. Metrics::pkt_error_authentication_required_in++;
  288. } break;
  289. default:
  290. break;
  291. }
  292. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_ERROR, inRePacketId, inReVerb, false, networkId, ZT_QOS_NO_FLOW);
  293. return true;
  294. }
  295. bool IncomingPacket::_doACK(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  296. {
  297. /*
  298. if (! peer->rateGateACK(RR->node->now())) {
  299. return true;
  300. }
  301. int32_t ackedBytes;
  302. if (payloadLength() != sizeof(ackedBytes)) {
  303. return true; // ignore
  304. }
  305. memcpy(&ackedBytes, payload(), sizeof(ackedBytes));
  306. peer->receivedAck(_path, RR->node->now(), Utils::ntoh(ackedBytes));
  307. */
  308. Metrics::pkt_ack_in++;
  309. return true;
  310. }
  311. bool IncomingPacket::_doQOS_MEASUREMENT(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  312. {
  313. Metrics::pkt_qos_in++;
  314. if (! peer->rateGateQoS(RR->node->now(), _path)) {
  315. return true;
  316. }
  317. if (payloadLength() > ZT_QOS_MAX_PACKET_SIZE || payloadLength() < ZT_QOS_MIN_PACKET_SIZE) {
  318. return true; // ignore
  319. }
  320. const int64_t now = RR->node->now();
  321. uint64_t rx_id[ZT_QOS_TABLE_SIZE];
  322. uint16_t rx_ts[ZT_QOS_TABLE_SIZE];
  323. char* begin = (char*)payload();
  324. char* ptr = begin;
  325. int count = 0;
  326. unsigned int len = payloadLength();
  327. // Read packet IDs and latency compensation intervals for each packet tracked by this QoS packet
  328. while (ptr < (begin + len) && (count < ZT_QOS_TABLE_SIZE)) {
  329. memcpy((void*)&rx_id[count], ptr, sizeof(uint64_t));
  330. ptr += sizeof(uint64_t);
  331. memcpy((void*)&rx_ts[count], ptr, sizeof(uint16_t));
  332. ptr += sizeof(uint16_t);
  333. count++;
  334. }
  335. peer->receivedQoS(_path, now, count, rx_id, rx_ts);
  336. return true;
  337. }
  338. bool IncomingPacket::_doHELLO(const RuntimeEnvironment* RR, void* tPtr, const bool alreadyAuthenticated)
  339. {
  340. Metrics::pkt_hello_in++;
  341. const int64_t now = RR->node->now();
  342. const uint64_t pid = packetId();
  343. const Address fromAddress(source());
  344. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  345. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  346. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  347. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  348. const int64_t timestamp = at<int64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  349. Identity id;
  350. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this, ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  351. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  352. RR->t->incomingPacketDroppedHELLO(tPtr, _path, pid, fromAddress, "protocol version too old");
  353. return true;
  354. }
  355. if (fromAddress != id.address()) {
  356. RR->t->incomingPacketDroppedHELLO(tPtr, _path, pid, fromAddress, "identity/address mismatch");
  357. return true;
  358. }
  359. SharedPtr<Peer> peer(RR->topology->getPeer(tPtr, id.address()));
  360. if (peer) {
  361. // We already have an identity with this address -- check for collisions
  362. if (! alreadyAuthenticated) {
  363. if (peer->identity() != id) {
  364. // Identity is different from the one we already have -- address collision
  365. // Check rate limits
  366. if (! RR->node->rateGateIdentityVerification(now, _path->address())) {
  367. return true;
  368. }
  369. uint8_t key[ZT_SYMMETRIC_KEY_SIZE];
  370. if (RR->identity.agree(id, key)) {
  371. if (dearmor(key, peer->aesKeysIfSupported(), RR->identity)) { // ensure packet is authentic, otherwise drop
  372. RR->t->incomingPacketDroppedHELLO(tPtr, _path, pid, fromAddress, "address collision");
  373. Packet outp(id.address(), RR->identity.address(), Packet::VERB_ERROR);
  374. outp.append((uint8_t)Packet::VERB_HELLO);
  375. outp.append((uint64_t)pid);
  376. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  377. outp.armor(key, true, false, peer->aesKeysIfSupported(), peer->identity());
  378. Metrics::pkt_error_out++;
  379. Metrics::pkt_error_identity_collision_out++;
  380. _path->send(RR, tPtr, outp.data(), outp.size(), RR->node->now());
  381. }
  382. else {
  383. RR->t->incomingPacketMessageAuthenticationFailure(tPtr, _path, pid, fromAddress, hops(), "invalid MAC");
  384. }
  385. }
  386. else {
  387. RR->t->incomingPacketMessageAuthenticationFailure(tPtr, _path, pid, fromAddress, hops(), "invalid identity");
  388. }
  389. return true;
  390. }
  391. else {
  392. // Identity is the same as the one we already have -- check packet integrity
  393. if (! dearmor(peer->key(), peer->aesKeysIfSupported(), RR->identity)) {
  394. RR->t->incomingPacketMessageAuthenticationFailure(tPtr, _path, pid, fromAddress, hops(), "invalid MAC");
  395. return true;
  396. }
  397. // Continue at // VALID
  398. }
  399. } // else if alreadyAuthenticated then continue at // VALID
  400. }
  401. else {
  402. // We don't already have an identity with this address -- validate and learn it
  403. // Sanity check: this basically can't happen
  404. if (alreadyAuthenticated) {
  405. RR->t->incomingPacketDroppedHELLO(tPtr, _path, pid, fromAddress, "illegal alreadyAuthenticated state");
  406. return true;
  407. }
  408. // Check rate limits
  409. if (! RR->node->rateGateIdentityVerification(now, _path->address())) {
  410. RR->t->incomingPacketDroppedHELLO(tPtr, _path, pid, fromAddress, "rate limit exceeded");
  411. return true;
  412. }
  413. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  414. SharedPtr<Peer> newPeer(new Peer(RR, RR->identity, id));
  415. if (! dearmor(newPeer->key(), newPeer->aesKeysIfSupported(), RR->identity)) {
  416. RR->t->incomingPacketMessageAuthenticationFailure(tPtr, _path, pid, fromAddress, hops(), "invalid MAC");
  417. return true;
  418. }
  419. // Check that identity's address is valid as per the derivation function
  420. if (! id.locallyValidate()) {
  421. RR->t->incomingPacketDroppedHELLO(tPtr, _path, pid, fromAddress, "invalid identity");
  422. return true;
  423. }
  424. peer = RR->topology->addPeer(tPtr, newPeer);
  425. // Continue at // VALID
  426. }
  427. // VALID -- if we made it here, packet passed identity and authenticity checks!
  428. // Get external surface address if present (was not in old versions)
  429. InetAddress externalSurfaceAddress;
  430. if (ptr < size()) {
  431. ptr += externalSurfaceAddress.deserialize(*this, ptr);
  432. if ((externalSurfaceAddress) && (hops() == 0)) {
  433. RR->sa->iam(tPtr, id.address(), _path->localSocket(), _path->address(), externalSurfaceAddress, RR->topology->isUpstream(id), now);
  434. }
  435. }
  436. // Get primary planet world ID and world timestamp if present
  437. uint64_t planetWorldId = 0;
  438. uint64_t planetWorldTimestamp = 0;
  439. if ((ptr + 16) <= size()) {
  440. planetWorldId = at<uint64_t>(ptr);
  441. ptr += 8;
  442. planetWorldTimestamp = at<uint64_t>(ptr);
  443. ptr += 8;
  444. }
  445. std::vector<std::pair<uint64_t, uint64_t> > moonIdsAndTimestamps;
  446. if (ptr < size()) {
  447. // Remainder of packet, if present, is encrypted
  448. cryptField(peer->key(), ptr, size() - ptr);
  449. // Get moon IDs and timestamps if present
  450. if ((ptr + 2) <= size()) {
  451. const unsigned int numMoons = at<uint16_t>(ptr);
  452. ptr += 2;
  453. for (unsigned int i = 0; i < numMoons; ++i) {
  454. if ((World::Type)(*this)[ptr++] == World::TYPE_MOON) {
  455. moonIdsAndTimestamps.push_back(std::pair<uint64_t, uint64_t>(at<uint64_t>(ptr), at<uint64_t>(ptr + 8)));
  456. }
  457. ptr += 16;
  458. }
  459. }
  460. }
  461. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  462. // information about us: version, sent-to address, etc.
  463. Packet outp(id.address(), RR->identity.address(), Packet::VERB_OK);
  464. outp.append((unsigned char)Packet::VERB_HELLO);
  465. outp.append((uint64_t)pid);
  466. outp.append((uint64_t)timestamp);
  467. outp.append((unsigned char)ZT_PROTO_VERSION);
  468. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  469. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  470. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  471. _path->address().serialize(outp);
  472. const unsigned int worldUpdateSizeAt = outp.size();
  473. outp.addSize(2); // make room for 16-bit size field
  474. if ((planetWorldId) && (RR->topology->planetWorldTimestamp() > planetWorldTimestamp) && (planetWorldId == RR->topology->planetWorldId())) {
  475. RR->topology->planet().serialize(outp, false);
  476. }
  477. if (! moonIdsAndTimestamps.empty()) {
  478. std::vector<World> moons(RR->topology->moons());
  479. for (std::vector<World>::const_iterator m(moons.begin()); m != moons.end(); ++m) {
  480. for (std::vector<std::pair<uint64_t, uint64_t> >::const_iterator i(moonIdsAndTimestamps.begin()); i != moonIdsAndTimestamps.end(); ++i) {
  481. if (i->first == m->id()) {
  482. if (m->timestamp() > i->second) {
  483. m->serialize(outp, false);
  484. }
  485. break;
  486. }
  487. }
  488. }
  489. }
  490. outp.setAt<uint16_t>(worldUpdateSizeAt, (uint16_t)(outp.size() - (worldUpdateSizeAt + 2)));
  491. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), peer->identity());
  492. peer->recordOutgoingPacket(_path, outp.packetId(), outp.payloadLength(), outp.verb(), ZT_QOS_NO_FLOW, now);
  493. Metrics::pkt_ok_out++;
  494. _path->send(RR, tPtr, outp.data(), outp.size(), now);
  495. peer->setRemoteVersion(protoVersion, vMajor, vMinor, vRevision); // important for this to go first so received() knows the version
  496. peer->received(tPtr, _path, hops(), pid, payloadLength(), Packet::VERB_HELLO, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  497. return true;
  498. }
  499. bool IncomingPacket::_doOK(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  500. {
  501. Metrics::pkt_ok_in++;
  502. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  503. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  504. uint64_t networkId = 0;
  505. if (! RR->node->expectingReplyTo(inRePacketId)) {
  506. return true;
  507. }
  508. switch (inReVerb) {
  509. case Packet::VERB_HELLO: {
  510. const uint64_t latency = RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  511. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  512. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  513. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  514. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  515. if (vProto < ZT_PROTO_VERSION_MIN) {
  516. return true;
  517. }
  518. InetAddress externalSurfaceAddress;
  519. unsigned int ptr = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
  520. // Get reported external surface address if present
  521. if (ptr < size()) {
  522. ptr += externalSurfaceAddress.deserialize(*this, ptr);
  523. }
  524. // Handle planet or moon updates if present
  525. if ((ptr + 2) <= size()) {
  526. const unsigned int worldsLen = at<uint16_t>(ptr);
  527. ptr += 2;
  528. if (RR->topology->shouldAcceptWorldUpdateFrom(peer->address())) {
  529. const unsigned int endOfWorlds = ptr + worldsLen;
  530. while (ptr < endOfWorlds) {
  531. World w;
  532. ptr += w.deserialize(*this, ptr);
  533. RR->topology->addWorld(tPtr, w, false);
  534. }
  535. }
  536. else {
  537. ptr += worldsLen;
  538. }
  539. }
  540. if (! hops()) {
  541. _path->updateLatency((unsigned int)latency, RR->node->now());
  542. }
  543. peer->setRemoteVersion(vProto, vMajor, vMinor, vRevision);
  544. if ((externalSurfaceAddress) && (hops() == 0)) {
  545. RR->sa->iam(tPtr, peer->address(), _path->localSocket(), _path->address(), externalSurfaceAddress, RR->topology->isUpstream(peer->identity()), RR->node->now());
  546. }
  547. } break;
  548. case Packet::VERB_WHOIS:
  549. if (RR->topology->isUpstream(peer->identity())) {
  550. const Identity id(*this, ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY);
  551. RR->sw->doAnythingWaitingForPeer(tPtr, RR->topology->addPeer(tPtr, SharedPtr<Peer>(new Peer(RR, RR->identity, id))));
  552. }
  553. break;
  554. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  555. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  556. const SharedPtr<Network> network(RR->node->network(networkId));
  557. if (network) {
  558. network->handleConfigChunk(tPtr, packetId(), source(), *this, ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  559. }
  560. } break;
  561. case Packet::VERB_MULTICAST_GATHER: {
  562. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  563. const SharedPtr<Network> network(RR->node->network(networkId));
  564. if (network) {
  565. 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));
  566. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  567. 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));
  568. }
  569. } break;
  570. case Packet::VERB_MULTICAST_FRAME: {
  571. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  572. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  573. 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));
  574. const SharedPtr<Network> network(RR->node->network(networkId));
  575. if (network) {
  576. unsigned int offset = 0;
  577. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  578. CertificateOfMembership com;
  579. offset += com.deserialize(*this, ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  580. if (com) {
  581. network->addCredential(tPtr, com);
  582. }
  583. }
  584. if ((flags & 0x02) != 0) {
  585. // OK(MULTICAST_FRAME) includes implicit gather results
  586. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  587. unsigned int totalKnown = at<uint32_t>(offset);
  588. offset += 4;
  589. unsigned int count = at<uint16_t>(offset);
  590. offset += 2;
  591. RR->mc->addMultiple(tPtr, RR->node->now(), networkId, mg, field(offset, count * 5), count, totalKnown);
  592. }
  593. }
  594. } break;
  595. default:
  596. break;
  597. }
  598. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_OK, inRePacketId, inReVerb, false, networkId, ZT_QOS_NO_FLOW);
  599. return true;
  600. }
  601. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  602. {
  603. if ((! RR->topology->amUpstream()) && (! peer->rateGateInboundWhoisRequest(RR->node->now()))) {
  604. return true;
  605. }
  606. Metrics::pkt_whois_in++;
  607. Packet outp(peer->address(), RR->identity.address(), Packet::VERB_OK);
  608. outp.append((unsigned char)Packet::VERB_WHOIS);
  609. outp.append(packetId());
  610. unsigned int count = 0;
  611. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  612. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  613. const Address addr(field(ptr, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH);
  614. ptr += ZT_ADDRESS_LENGTH;
  615. const Identity id(RR->topology->getIdentity(tPtr, addr));
  616. if (id) {
  617. id.serialize(outp, false);
  618. ++count;
  619. }
  620. else {
  621. // Request unknown WHOIS from upstream from us (if we have one)
  622. RR->sw->requestWhois(tPtr, RR->node->now(), addr);
  623. }
  624. }
  625. if (count > 0) {
  626. Metrics::pkt_ok_out++;
  627. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), RR->identity);
  628. _path->send(RR, tPtr, outp.data(), outp.size(), RR->node->now());
  629. }
  630. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_WHOIS, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  631. return true;
  632. }
  633. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  634. {
  635. Metrics::pkt_rendezvous_in++;
  636. if (RR->topology->isUpstream(peer->identity())) {
  637. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS, ZT_ADDRESS_LENGTH), ZT_ADDRESS_LENGTH);
  638. const SharedPtr<Peer> rendezvousWith(RR->topology->getPeer(tPtr, with));
  639. if (rendezvousWith) {
  640. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  641. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  642. if ((port > 0) && ((addrlen == 4) || (addrlen == 16))) {
  643. InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS, addrlen), addrlen, port);
  644. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr, with, _path->localSocket(), atAddr)) {
  645. const uint64_t junk = RR->node->prng();
  646. RR->node->putPacket(tPtr, _path->localSocket(), atAddr, &junk, 4, 2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  647. rendezvousWith->attemptToContactAt(tPtr, _path->localSocket(), atAddr, RR->node->now(), false);
  648. }
  649. }
  650. }
  651. }
  652. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_RENDEZVOUS, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  653. return true;
  654. }
  655. // Returns true if packet appears valid; pos and proto will be set
  656. static bool _ipv6GetPayload(const uint8_t* frameData, unsigned int frameLen, unsigned int& pos, unsigned int& proto)
  657. {
  658. if (frameLen < 40) {
  659. return false;
  660. }
  661. pos = 40;
  662. proto = frameData[6];
  663. while (pos <= frameLen) {
  664. switch (proto) {
  665. case 0: // hop-by-hop options
  666. case 43: // routing
  667. case 60: // destination options
  668. case 135: // mobility options
  669. if ((pos + 8) > frameLen) {
  670. return false; // invalid!
  671. }
  672. proto = frameData[pos];
  673. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  674. break;
  675. // case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  676. // case 50:
  677. // case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  678. default:
  679. return true;
  680. }
  681. }
  682. return false; // overflow == invalid
  683. }
  684. bool IncomingPacket::_doFRAME(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer, int32_t flowId)
  685. {
  686. Metrics::pkt_frame_in++;
  687. int32_t _flowId = ZT_QOS_NO_FLOW;
  688. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  689. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  690. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  691. const uint8_t* const frameData = reinterpret_cast<const uint8_t*>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  692. if (etherType == ZT_ETHERTYPE_IPV4 && (frameLen >= 20)) {
  693. uint16_t srcPort = 0;
  694. uint16_t dstPort = 0;
  695. uint8_t proto = (reinterpret_cast<const uint8_t*>(frameData)[9]);
  696. const unsigned int headerLen = 4 * (reinterpret_cast<const uint8_t*>(frameData)[0] & 0xf);
  697. switch (proto) {
  698. case 0x01: // ICMP
  699. // flowId = 0x01;
  700. break;
  701. // All these start with 16-bit source and destination port in that order
  702. case 0x06: // TCP
  703. case 0x11: // UDP
  704. case 0x84: // SCTP
  705. case 0x88: // UDPLite
  706. if (frameLen > (headerLen + 4)) {
  707. unsigned int pos = headerLen + 0;
  708. srcPort = (reinterpret_cast<const uint8_t*>(frameData)[pos++]) << 8;
  709. srcPort |= (reinterpret_cast<const uint8_t*>(frameData)[pos]);
  710. pos++;
  711. dstPort = (reinterpret_cast<const uint8_t*>(frameData)[pos++]) << 8;
  712. dstPort |= (reinterpret_cast<const uint8_t*>(frameData)[pos]);
  713. _flowId = dstPort ^ srcPort ^ proto;
  714. }
  715. break;
  716. }
  717. }
  718. if (etherType == ZT_ETHERTYPE_IPV6 && (frameLen >= 40)) {
  719. uint16_t srcPort = 0;
  720. uint16_t dstPort = 0;
  721. unsigned int pos;
  722. unsigned int proto;
  723. _ipv6GetPayload((const uint8_t*)frameData, frameLen, pos, proto);
  724. switch (proto) {
  725. case 0x3A: // ICMPv6
  726. // flowId = 0x3A;
  727. break;
  728. // All these start with 16-bit source and destination port in that order
  729. case 0x06: // TCP
  730. case 0x11: // UDP
  731. case 0x84: // SCTP
  732. case 0x88: // UDPLite
  733. if (frameLen > (pos + 4)) {
  734. srcPort = (reinterpret_cast<const uint8_t*>(frameData)[pos++]) << 8;
  735. srcPort |= (reinterpret_cast<const uint8_t*>(frameData)[pos]);
  736. pos++;
  737. dstPort = (reinterpret_cast<const uint8_t*>(frameData)[pos++]) << 8;
  738. dstPort |= (reinterpret_cast<const uint8_t*>(frameData)[pos]);
  739. _flowId = dstPort ^ srcPort ^ proto;
  740. }
  741. break;
  742. default:
  743. break;
  744. }
  745. }
  746. }
  747. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  748. const SharedPtr<Network> network(RR->node->network(nwid));
  749. bool trustEstablished = false;
  750. if (network) {
  751. if (network->gate(tPtr, peer)) {
  752. trustEstablished = true;
  753. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  754. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  755. const MAC sourceMac(peer->address(), nwid);
  756. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  757. const uint8_t* const frameData = reinterpret_cast<const uint8_t*>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  758. if (network->filterIncomingPacket(tPtr, peer, RR->identity.address(), sourceMac, network->mac(), frameData, frameLen, etherType, 0) > 0) {
  759. RR->pm->putFrame(tPtr, nwid, network->userPtr(), sourceMac, network->mac(), etherType, 0, (const void*)frameData, frameLen, _flowId);
  760. }
  761. }
  762. }
  763. else {
  764. _sendErrorNeedCredentials(RR, tPtr, peer, nwid);
  765. return false;
  766. }
  767. }
  768. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_FRAME, 0, Packet::VERB_NOP, trustEstablished, nwid, _flowId);
  769. return true;
  770. }
  771. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer, int32_t flowId)
  772. {
  773. Metrics::pkt_ext_frame_in++;
  774. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  775. const SharedPtr<Network> network(RR->node->network(nwid));
  776. if (network) {
  777. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  778. unsigned int comLen = 0;
  779. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  780. CertificateOfMembership com;
  781. comLen = com.deserialize(*this, ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  782. if (com) {
  783. network->addCredential(tPtr, com);
  784. }
  785. }
  786. if (! network->gate(tPtr, peer)) {
  787. RR->t->incomingNetworkAccessDenied(tPtr, network, _path, packetId(), size(), peer->address(), Packet::VERB_EXT_FRAME, true);
  788. _sendErrorNeedCredentials(RR, tPtr, peer, nwid);
  789. return false;
  790. }
  791. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  792. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  793. 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);
  794. 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);
  795. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  796. const uint8_t* const frameData = (const uint8_t*)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD, frameLen);
  797. if ((! from) || (from == network->mac())) {
  798. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_EXT_FRAME, 0, Packet::VERB_NOP, true, nwid, flowId); // trustEstablished because COM is okay
  799. return true;
  800. }
  801. switch (network->filterIncomingPacket(tPtr, peer, RR->identity.address(), from, to, frameData, frameLen, etherType, 0)) {
  802. case 1:
  803. if (from != MAC(peer->address(), nwid)) {
  804. if (network->config().permitsBridging(peer->address())) {
  805. network->learnBridgeRoute(from, peer->address());
  806. }
  807. else {
  808. RR->t->incomingNetworkFrameDropped(tPtr, network, _path, packetId(), size(), peer->address(), Packet::VERB_EXT_FRAME, from, to, "bridging not allowed (remote)");
  809. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_EXT_FRAME, 0, Packet::VERB_NOP, true, nwid, flowId); // trustEstablished because COM is okay
  810. return true;
  811. }
  812. }
  813. else if (to != network->mac()) {
  814. if (to.isMulticast()) {
  815. if (network->config().multicastLimit == 0) {
  816. RR->t->incomingNetworkFrameDropped(tPtr, network, _path, packetId(), size(), peer->address(), Packet::VERB_EXT_FRAME, from, to, "multicast disabled");
  817. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_EXT_FRAME, 0, Packet::VERB_NOP, true, nwid, flowId); // trustEstablished because COM is okay
  818. return true;
  819. }
  820. }
  821. else if (! network->config().permitsBridging(RR->identity.address())) {
  822. RR->t->incomingNetworkFrameDropped(tPtr, network, _path, packetId(), size(), peer->address(), Packet::VERB_EXT_FRAME, from, to, "bridging not allowed (local)");
  823. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_EXT_FRAME, 0, Packet::VERB_NOP, true, nwid, flowId); // trustEstablished because COM is okay
  824. return true;
  825. }
  826. }
  827. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  828. case 2:
  829. RR->pm->putFrame(tPtr, nwid, network->userPtr(), from, to, etherType, 0, (const void*)frameData, frameLen, flowId);
  830. break;
  831. }
  832. }
  833. if ((flags & 0x10) != 0) { // ACK requested
  834. Packet outp(peer->address(), RR->identity.address(), Packet::VERB_OK);
  835. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  836. outp.append((uint64_t)packetId());
  837. outp.append((uint64_t)nwid);
  838. const int64_t now = RR->node->now();
  839. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), peer->identity());
  840. peer->recordOutgoingPacket(_path, outp.packetId(), outp.payloadLength(), outp.verb(), ZT_QOS_NO_FLOW, now);
  841. Metrics::pkt_ok_out++;
  842. _path->send(RR, tPtr, outp.data(), outp.size(), RR->node->now());
  843. }
  844. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_EXT_FRAME, 0, Packet::VERB_NOP, true, nwid, flowId);
  845. }
  846. else {
  847. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_EXT_FRAME, 0, Packet::VERB_NOP, false, nwid, flowId);
  848. }
  849. return true;
  850. }
  851. bool IncomingPacket::_doECHO(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  852. {
  853. Metrics::pkt_echo_in++;
  854. uint64_t now = RR->node->now();
  855. if (! _path->rateGateEchoRequest(now)) {
  856. return true;
  857. }
  858. const uint64_t pid = packetId();
  859. Packet outp(peer->address(), RR->identity.address(), Packet::VERB_OK);
  860. outp.append((unsigned char)Packet::VERB_ECHO);
  861. outp.append((uint64_t)pid);
  862. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  863. outp.append(reinterpret_cast<const unsigned char*>(data()) + ZT_PACKET_IDX_PAYLOAD, size() - ZT_PACKET_IDX_PAYLOAD);
  864. }
  865. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), peer->identity());
  866. peer->recordOutgoingPacket(_path, outp.packetId(), outp.payloadLength(), outp.verb(), ZT_QOS_NO_FLOW, now);
  867. Metrics::pkt_ok_out++;
  868. _path->send(RR, tPtr, outp.data(), outp.size(), RR->node->now());
  869. peer->received(tPtr, _path, hops(), pid, payloadLength(), Packet::VERB_ECHO, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  870. return true;
  871. }
  872. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  873. {
  874. Metrics::pkt_multicast_like_in++;
  875. const int64_t now = RR->node->now();
  876. bool authorized = false;
  877. uint64_t lastNwid = 0;
  878. // Packet contains a series of 18-byte network,MAC,ADI tuples
  879. for (unsigned int ptr = ZT_PACKET_IDX_PAYLOAD; ptr < size(); ptr += 18) {
  880. const uint64_t nwid = at<uint64_t>(ptr);
  881. if (nwid != lastNwid) {
  882. lastNwid = nwid;
  883. SharedPtr<Network> network(RR->node->network(nwid));
  884. if (network) {
  885. authorized = network->gate(tPtr, peer);
  886. }
  887. if (! authorized) {
  888. authorized = ((RR->topology->amUpstream()) || (RR->node->localControllerHasAuthorized(now, nwid, peer->address())));
  889. }
  890. }
  891. if (authorized) {
  892. RR->mc->add(tPtr, now, nwid, MulticastGroup(MAC(field(ptr + 8, 6), 6), at<uint32_t>(ptr + 14)), peer->address());
  893. }
  894. }
  895. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_MULTICAST_LIKE, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  896. return true;
  897. }
  898. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  899. {
  900. Metrics::pkt_network_credentials_in++;
  901. if (! peer->rateGateCredentialsReceived(RR->node->now())) {
  902. return true;
  903. }
  904. CertificateOfMembership com;
  905. Capability cap;
  906. Tag tag;
  907. Revocation revocation;
  908. CertificateOfOwnership coo;
  909. bool trustEstablished = false;
  910. SharedPtr<Network> network;
  911. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  912. while ((p < size()) && ((*this)[p] != 0)) {
  913. p += com.deserialize(*this, p);
  914. if (com) {
  915. network = RR->node->network(com.networkId());
  916. if (network) {
  917. switch (network->addCredential(tPtr, com)) {
  918. case Membership::ADD_REJECTED:
  919. break;
  920. case Membership::ADD_ACCEPTED_NEW:
  921. case Membership::ADD_ACCEPTED_REDUNDANT:
  922. trustEstablished = true;
  923. break;
  924. case Membership::ADD_DEFERRED_FOR_WHOIS:
  925. return false;
  926. }
  927. }
  928. }
  929. }
  930. ++p; // skip trailing 0 after COMs if present
  931. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  932. const unsigned int numCapabilities = at<uint16_t>(p);
  933. p += 2;
  934. for (unsigned int i = 0; i < numCapabilities; ++i) {
  935. p += cap.deserialize(*this, p);
  936. if ((! network) || (network->id() != cap.networkId())) {
  937. network = RR->node->network(cap.networkId());
  938. }
  939. if (network) {
  940. switch (network->addCredential(tPtr, cap)) {
  941. case Membership::ADD_REJECTED:
  942. break;
  943. case Membership::ADD_ACCEPTED_NEW:
  944. case Membership::ADD_ACCEPTED_REDUNDANT:
  945. trustEstablished = true;
  946. break;
  947. case Membership::ADD_DEFERRED_FOR_WHOIS:
  948. return false;
  949. }
  950. }
  951. }
  952. if (p >= size()) {
  953. return true;
  954. }
  955. const unsigned int numTags = at<uint16_t>(p);
  956. p += 2;
  957. for (unsigned int i = 0; i < numTags; ++i) {
  958. p += tag.deserialize(*this, p);
  959. if ((! network) || (network->id() != tag.networkId())) {
  960. network = RR->node->network(tag.networkId());
  961. }
  962. if (network) {
  963. switch (network->addCredential(tPtr, tag)) {
  964. case Membership::ADD_REJECTED:
  965. break;
  966. case Membership::ADD_ACCEPTED_NEW:
  967. case Membership::ADD_ACCEPTED_REDUNDANT:
  968. trustEstablished = true;
  969. break;
  970. case Membership::ADD_DEFERRED_FOR_WHOIS:
  971. return false;
  972. }
  973. }
  974. }
  975. if (p >= size()) {
  976. return true;
  977. }
  978. const unsigned int numRevocations = at<uint16_t>(p);
  979. p += 2;
  980. for (unsigned int i = 0; i < numRevocations; ++i) {
  981. p += revocation.deserialize(*this, p);
  982. if ((! network) || (network->id() != revocation.networkId())) {
  983. network = RR->node->network(revocation.networkId());
  984. }
  985. if (network) {
  986. switch (network->addCredential(tPtr, peer->address(), revocation)) {
  987. case Membership::ADD_REJECTED:
  988. break;
  989. case Membership::ADD_ACCEPTED_NEW:
  990. case Membership::ADD_ACCEPTED_REDUNDANT:
  991. trustEstablished = true;
  992. break;
  993. case Membership::ADD_DEFERRED_FOR_WHOIS:
  994. return false;
  995. }
  996. }
  997. }
  998. if (p >= size()) {
  999. return true;
  1000. }
  1001. const unsigned int numCoos = at<uint16_t>(p);
  1002. p += 2;
  1003. for (unsigned int i = 0; i < numCoos; ++i) {
  1004. p += coo.deserialize(*this, p);
  1005. if ((! network) || (network->id() != coo.networkId())) {
  1006. network = RR->node->network(coo.networkId());
  1007. }
  1008. if (network) {
  1009. switch (network->addCredential(tPtr, coo)) {
  1010. case Membership::ADD_REJECTED:
  1011. break;
  1012. case Membership::ADD_ACCEPTED_NEW:
  1013. case Membership::ADD_ACCEPTED_REDUNDANT:
  1014. trustEstablished = true;
  1015. break;
  1016. case Membership::ADD_DEFERRED_FOR_WHOIS:
  1017. return false;
  1018. }
  1019. }
  1020. }
  1021. }
  1022. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_NETWORK_CREDENTIALS, 0, Packet::VERB_NOP, trustEstablished, (network) ? network->id() : 0, ZT_QOS_NO_FLOW);
  1023. return true;
  1024. }
  1025. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  1026. {
  1027. Metrics::pkt_network_config_request_in++;
  1028. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  1029. const unsigned int hopCount = hops();
  1030. const uint64_t requestPacketId = packetId();
  1031. if (RR->localNetworkController) {
  1032. 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;
  1033. const char* metaDataBytes = (metaDataLength != 0) ? (const char*)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT, metaDataLength) : (const char*)0;
  1034. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes, metaDataLength);
  1035. RR->localNetworkController->request(nwid, (hopCount > 0) ? InetAddress() : _path->address(), requestPacketId, peer->identity(), metaData);
  1036. }
  1037. else {
  1038. Packet outp(peer->address(), RR->identity.address(), Packet::VERB_ERROR);
  1039. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  1040. outp.append(requestPacketId);
  1041. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  1042. outp.append(nwid);
  1043. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), peer->identity());
  1044. Metrics::pkt_error_out++;
  1045. Metrics::pkt_error_unsupported_op_out++;
  1046. _path->send(RR, tPtr, outp.data(), outp.size(), RR->node->now());
  1047. }
  1048. peer->received(tPtr, _path, hopCount, requestPacketId, payloadLength(), Packet::VERB_NETWORK_CONFIG_REQUEST, 0, Packet::VERB_NOP, false, nwid, ZT_QOS_NO_FLOW);
  1049. return true;
  1050. }
  1051. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  1052. {
  1053. Metrics::pkt_network_config_in++;
  1054. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  1055. if (network) {
  1056. const uint64_t configUpdateId = network->handleConfigChunk(tPtr, packetId(), source(), *this, ZT_PACKET_IDX_PAYLOAD);
  1057. if (configUpdateId) {
  1058. Packet outp(peer->address(), RR->identity.address(), Packet::VERB_OK);
  1059. outp.append((uint8_t)Packet::VERB_ECHO);
  1060. outp.append((uint64_t)packetId());
  1061. outp.append((uint64_t)network->id());
  1062. outp.append((uint64_t)configUpdateId);
  1063. const int64_t now = RR->node->now();
  1064. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), peer->identity());
  1065. peer->recordOutgoingPacket(_path, outp.packetId(), outp.payloadLength(), outp.verb(), ZT_QOS_NO_FLOW, now);
  1066. Metrics::pkt_ok_out++;
  1067. _path->send(RR, tPtr, outp.data(), outp.size(), RR->node->now());
  1068. }
  1069. }
  1070. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_NETWORK_CONFIG, 0, Packet::VERB_NOP, false, (network) ? network->id() : 0, ZT_QOS_NO_FLOW);
  1071. return true;
  1072. }
  1073. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  1074. {
  1075. Metrics::pkt_multicast_gather_in++;
  1076. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  1077. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  1078. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC, 6), 6), at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  1079. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  1080. const SharedPtr<Network> network(RR->node->network(nwid));
  1081. if ((flags & 0x01) != 0) {
  1082. try {
  1083. CertificateOfMembership com;
  1084. com.deserialize(*this, ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  1085. if ((com) && (network)) {
  1086. network->addCredential(tPtr, com);
  1087. }
  1088. }
  1089. catch (...) {
  1090. } // discard invalid COMs
  1091. }
  1092. const bool trustEstablished = (network) ? network->gate(tPtr, peer) : false;
  1093. const int64_t now = RR->node->now();
  1094. if ((gatherLimit > 0) && ((trustEstablished) || (RR->topology->amUpstream()) || (RR->node->localControllerHasAuthorized(now, nwid, peer->address())))) {
  1095. Packet outp(peer->address(), RR->identity.address(), Packet::VERB_OK);
  1096. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  1097. outp.append(packetId());
  1098. outp.append(nwid);
  1099. mg.mac().appendTo(outp);
  1100. outp.append((uint32_t)mg.adi());
  1101. const unsigned int gatheredLocally = RR->mc->gather(peer->address(), nwid, mg, outp, gatherLimit);
  1102. if (gatheredLocally > 0) {
  1103. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), peer->identity());
  1104. peer->recordOutgoingPacket(_path, outp.packetId(), outp.payloadLength(), outp.verb(), ZT_QOS_NO_FLOW, now);
  1105. Metrics::pkt_ok_out++;
  1106. _path->send(RR, tPtr, outp.data(), outp.size(), now);
  1107. }
  1108. }
  1109. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_MULTICAST_GATHER, 0, Packet::VERB_NOP, trustEstablished, nwid, ZT_QOS_NO_FLOW);
  1110. return true;
  1111. }
  1112. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  1113. {
  1114. Metrics::pkt_multicast_frame_in++;
  1115. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID);
  1116. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS];
  1117. const SharedPtr<Network> network(RR->node->network(nwid));
  1118. if (network) {
  1119. // Offset -- size of optional fields added to position of later fields
  1120. unsigned int offset = 0;
  1121. if ((flags & 0x01) != 0) {
  1122. // This is deprecated but may still be sent by old peers
  1123. CertificateOfMembership com;
  1124. offset += com.deserialize(*this, ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM);
  1125. if (com) {
  1126. network->addCredential(tPtr, com);
  1127. }
  1128. }
  1129. if (! network->gate(tPtr, peer)) {
  1130. _sendErrorNeedCredentials(RR, tPtr, peer, nwid);
  1131. return false;
  1132. }
  1133. unsigned int gatherLimit = 0;
  1134. if ((flags & 0x02) != 0) {
  1135. gatherLimit = at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT);
  1136. offset += 4;
  1137. }
  1138. MAC from;
  1139. if ((flags & 0x04) != 0) {
  1140. from.setTo(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC, 6), 6);
  1141. offset += 6;
  1142. }
  1143. else {
  1144. from.fromAddress(peer->address(), nwid);
  1145. }
  1146. const MulticastGroup to(MAC(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC, 6), 6), at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI));
  1147. const unsigned int etherType = at<uint16_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  1148. const unsigned int frameLen = size() - (offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME);
  1149. if (network->config().multicastLimit == 0) {
  1150. RR->t->incomingNetworkFrameDropped(tPtr, network, _path, packetId(), size(), peer->address(), Packet::VERB_MULTICAST_FRAME, from, to.mac(), "multicast disabled");
  1151. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_MULTICAST_FRAME, 0, Packet::VERB_NOP, false, nwid, ZT_QOS_NO_FLOW);
  1152. return true;
  1153. }
  1154. if ((frameLen > 0) && (frameLen <= ZT_MAX_MTU)) {
  1155. if (! to.mac().isMulticast()) {
  1156. RR->t->incomingPacketInvalid(tPtr, _path, packetId(), source(), hops(), Packet::VERB_MULTICAST_FRAME, "destination not multicast");
  1157. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_MULTICAST_FRAME, 0, Packet::VERB_NOP, true, nwid, ZT_QOS_NO_FLOW); // trustEstablished because COM is okay
  1158. return true;
  1159. }
  1160. if ((! from) || (from.isMulticast()) || (from == network->mac())) {
  1161. RR->t->incomingPacketInvalid(tPtr, _path, packetId(), source(), hops(), Packet::VERB_MULTICAST_FRAME, "invalid source MAC");
  1162. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_MULTICAST_FRAME, 0, Packet::VERB_NOP, true, nwid, ZT_QOS_NO_FLOW); // trustEstablished because COM is okay
  1163. return true;
  1164. }
  1165. const uint8_t* const frameData = (const uint8_t*)field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME, frameLen);
  1166. if ((flags & 0x08) && (network->config().isMulticastReplicator(RR->identity.address()))) {
  1167. RR->mc->send(tPtr, RR->node->now(), network, peer->address(), to, from, etherType, frameData, frameLen);
  1168. }
  1169. if (from != MAC(peer->address(), nwid)) {
  1170. if (network->config().permitsBridging(peer->address())) {
  1171. network->learnBridgeRoute(from, peer->address());
  1172. }
  1173. else {
  1174. RR->t->incomingNetworkFrameDropped(tPtr, network, _path, packetId(), size(), peer->address(), Packet::VERB_MULTICAST_FRAME, from, to.mac(), "bridging not allowed (remote)");
  1175. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_MULTICAST_FRAME, 0, Packet::VERB_NOP, true, nwid, ZT_QOS_NO_FLOW); // trustEstablished because COM is okay
  1176. return true;
  1177. }
  1178. }
  1179. if (network->filterIncomingPacket(tPtr, peer, RR->identity.address(), from, to.mac(), frameData, frameLen, etherType, 0) > 0) {
  1180. RR->node->putFrame(tPtr, nwid, network->userPtr(), from, to.mac(), etherType, 0, (const void*)frameData, frameLen);
  1181. }
  1182. }
  1183. if (gatherLimit) {
  1184. Packet outp(source(), RR->identity.address(), Packet::VERB_OK);
  1185. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  1186. outp.append(packetId());
  1187. outp.append(nwid);
  1188. to.mac().appendTo(outp);
  1189. outp.append((uint32_t)to.adi());
  1190. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  1191. if (RR->mc->gather(peer->address(), nwid, to, outp, gatherLimit)) {
  1192. const int64_t now = RR->node->now();
  1193. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), peer->identity());
  1194. peer->recordOutgoingPacket(_path, outp.packetId(), outp.payloadLength(), outp.verb(), ZT_QOS_NO_FLOW, now);
  1195. Metrics::pkt_ok_out++;
  1196. _path->send(RR, tPtr, outp.data(), outp.size(), RR->node->now());
  1197. }
  1198. }
  1199. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_MULTICAST_FRAME, 0, Packet::VERB_NOP, true, nwid, ZT_QOS_NO_FLOW);
  1200. }
  1201. return true;
  1202. }
  1203. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  1204. {
  1205. Metrics::pkt_push_direct_paths_in++;
  1206. const int64_t now = RR->node->now();
  1207. if (! peer->rateGatePushDirectPaths(now)) {
  1208. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_PUSH_DIRECT_PATHS, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  1209. return true;
  1210. }
  1211. // Second, limit addresses by scope and type
  1212. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE + 1][2]; // [][0] is v4, [][1] is v6
  1213. memset(countPerScope, 0, sizeof(countPerScope));
  1214. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  1215. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  1216. while (count--) { // if ptr overflows Buffer will throw
  1217. unsigned int flags = (*this)[ptr++];
  1218. unsigned int extLen = at<uint16_t>(ptr);
  1219. ptr += 2;
  1220. ptr += extLen; // unused right now
  1221. unsigned int addrType = (*this)[ptr++];
  1222. unsigned int addrLen = (*this)[ptr++];
  1223. switch (addrType) {
  1224. case 4: {
  1225. const InetAddress a(field(ptr, 4), 4, at<uint16_t>(ptr + 4));
  1226. if (((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  1227. (! (((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now, a)))) && // not already known
  1228. (RR->node->shouldUsePathForZeroTierTraffic(tPtr, peer->address(), _path->localSocket(), a))) // should use path
  1229. {
  1230. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  1231. peer->clusterRedirect(tPtr, _path, a, now);
  1232. }
  1233. else if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  1234. peer->attemptToContactAt(tPtr, InetAddress(), a, now, false);
  1235. }
  1236. }
  1237. } break;
  1238. case 6: {
  1239. const InetAddress a(field(ptr, 16), 16, at<uint16_t>(ptr + 16));
  1240. if (((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  1241. (! (((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now, a)))) && // not already known
  1242. (RR->node->shouldUsePathForZeroTierTraffic(tPtr, peer->address(), _path->localSocket(), a))) // should use path
  1243. {
  1244. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  1245. peer->clusterRedirect(tPtr, _path, a, now);
  1246. }
  1247. else if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  1248. peer->attemptToContactAt(tPtr, InetAddress(), a, now, false);
  1249. }
  1250. }
  1251. } break;
  1252. }
  1253. ptr += addrLen;
  1254. }
  1255. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_PUSH_DIRECT_PATHS, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  1256. return true;
  1257. }
  1258. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  1259. {
  1260. Metrics::pkt_user_message_in++;
  1261. if (likely(size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  1262. ZT_UserMessage um;
  1263. um.origin = peer->address().toInt();
  1264. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  1265. um.data = reinterpret_cast<const void*>(reinterpret_cast<const uint8_t*>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  1266. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  1267. RR->node->postEvent(tPtr, ZT_EVENT_USER_MESSAGE, reinterpret_cast<const void*>(&um));
  1268. }
  1269. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_USER_MESSAGE, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  1270. return true;
  1271. }
  1272. bool IncomingPacket::_doREMOTE_TRACE(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  1273. {
  1274. Metrics::pkt_remote_trace_in++;
  1275. ZT_RemoteTrace rt;
  1276. const char* ptr = reinterpret_cast<const char*>(data()) + ZT_PACKET_IDX_PAYLOAD;
  1277. const char* const eof = reinterpret_cast<const char*>(data()) + size();
  1278. rt.origin = peer->address().toInt();
  1279. rt.data = const_cast<char*>(ptr); // start of first string
  1280. while (ptr < eof) {
  1281. if (! *ptr) { // end of string
  1282. rt.len = (unsigned int)(ptr - rt.data);
  1283. if ((rt.len > 0) && (rt.len <= ZT_MAX_REMOTE_TRACE_SIZE)) {
  1284. RR->node->postEvent(tPtr, ZT_EVENT_REMOTE_TRACE, &rt);
  1285. }
  1286. rt.data = const_cast<char*>(++ptr); // start of next string, if any
  1287. }
  1288. else {
  1289. ++ptr;
  1290. }
  1291. }
  1292. peer->received(tPtr, _path, hops(), packetId(), payloadLength(), Packet::VERB_REMOTE_TRACE, 0, Packet::VERB_NOP, false, 0, ZT_QOS_NO_FLOW);
  1293. return true;
  1294. }
  1295. bool IncomingPacket::_doPATH_NEGOTIATION_REQUEST(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer)
  1296. {
  1297. Metrics::pkt_path_negotiation_request_in++;
  1298. uint64_t now = RR->node->now();
  1299. if (! peer->rateGatePathNegotiation(now, _path)) {
  1300. return true;
  1301. }
  1302. if (payloadLength() != sizeof(int16_t)) {
  1303. return true;
  1304. }
  1305. int16_t remoteUtility = 0;
  1306. memcpy(&remoteUtility, payload(), sizeof(int16_t));
  1307. peer->processIncomingPathNegotiationRequest(now, _path, Utils::ntoh(remoteUtility));
  1308. return true;
  1309. }
  1310. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment* RR, void* tPtr, const SharedPtr<Peer>& peer, const uint64_t nwid)
  1311. {
  1312. Packet outp(source(), RR->identity.address(), Packet::VERB_ERROR);
  1313. outp.append((uint8_t)verb());
  1314. outp.append(packetId());
  1315. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  1316. outp.append(nwid);
  1317. outp.armor(peer->key(), true, false, peer->aesKeysIfSupported(), peer->identity());
  1318. Metrics::pkt_error_out++;
  1319. Metrics::pkt_error_need_membership_cert_out++;
  1320. _path->send(RR, tPtr, outp.data(), outp.size(), RR->node->now());
  1321. }
  1322. } // namespace ZeroTier