IncomingPacket.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #include <stdio.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include "../version.h"
  22. #include "../include/ZeroTierOne.h"
  23. #include "Constants.hpp"
  24. #include "RuntimeEnvironment.hpp"
  25. #include "IncomingPacket.hpp"
  26. #include "Topology.hpp"
  27. #include "Switch.hpp"
  28. #include "Peer.hpp"
  29. #include "NetworkController.hpp"
  30. #include "SelfAwareness.hpp"
  31. #include "Salsa20.hpp"
  32. #include "SHA512.hpp"
  33. #include "World.hpp"
  34. #include "Cluster.hpp"
  35. #include "Node.hpp"
  36. #include "CertificateOfMembership.hpp"
  37. #include "Capability.hpp"
  38. #include "Tag.hpp"
  39. #include "Revocation.hpp"
  40. namespace ZeroTier {
  41. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR)
  42. {
  43. const Address sourceAddress(source());
  44. try {
  45. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  46. const unsigned int c = cipher();
  47. bool trusted = false;
  48. if (c == ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH) {
  49. // If this is marked as a packet via a trusted path, check source address and path ID.
  50. // Obviously if no trusted paths are configured this always returns false and such
  51. // packets are dropped on the floor.
  52. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),trustedPathId())) {
  53. trusted = true;
  54. TRACE("TRUSTED PATH packet approved from %s(%s), trusted path ID %llx",sourceAddress.toString().c_str(),_path->address().toString().c_str(),trustedPathId());
  55. } else {
  56. TRACE("dropped packet from %s(%s), cipher set to trusted path mode but path %llx@%s is not trusted!",sourceAddress.toString().c_str(),_path->address().toString().c_str(),trustedPathId(),_path->address().toString().c_str());
  57. return true;
  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,false);
  62. }
  63. const SharedPtr<Peer> peer(RR->topology->getPeer(sourceAddress));
  64. if (peer) {
  65. if (!trusted) {
  66. if (!dearmor(peer->key())) {
  67. TRACE("dropped packet from %s(%s), MAC authentication failed (size: %u)",sourceAddress.toString().c_str(),_path->address().toString().c_str(),size());
  68. return true;
  69. }
  70. }
  71. if (!uncompress()) {
  72. TRACE("dropped packet from %s(%s), compressed data invalid",sourceAddress.toString().c_str(),_path->address().toString().c_str());
  73. return true;
  74. }
  75. const Packet::Verb v = verb();
  76. //TRACE("<< %s from %s(%s)",Packet::verbString(v),sourceAddress.toString().c_str(),_path->address().toString().c_str());
  77. switch(v) {
  78. //case Packet::VERB_NOP:
  79. default: // ignore unknown verbs, but if they pass auth check they are "received"
  80. peer->received(_path,hops(),packetId(),v,0,Packet::VERB_NOP,false);
  81. return true;
  82. case Packet::VERB_HELLO: return _doHELLO(RR,true);
  83. case Packet::VERB_ERROR: return _doERROR(RR,peer);
  84. case Packet::VERB_OK: return _doOK(RR,peer);
  85. case Packet::VERB_WHOIS: return _doWHOIS(RR,peer);
  86. case Packet::VERB_RENDEZVOUS: return _doRENDEZVOUS(RR,peer);
  87. case Packet::VERB_FRAME: return _doFRAME(RR,peer);
  88. case Packet::VERB_EXT_FRAME: return _doEXT_FRAME(RR,peer);
  89. case Packet::VERB_ECHO: return _doECHO(RR,peer);
  90. case Packet::VERB_MULTICAST_LIKE: return _doMULTICAST_LIKE(RR,peer);
  91. case Packet::VERB_NETWORK_CREDENTIALS: return _doNETWORK_CREDENTIALS(RR,peer);
  92. case Packet::VERB_NETWORK_CONFIG_REQUEST: return _doNETWORK_CONFIG_REQUEST(RR,peer);
  93. case Packet::VERB_NETWORK_CONFIG: return _doNETWORK_CONFIG(RR,peer);
  94. case Packet::VERB_MULTICAST_GATHER: return _doMULTICAST_GATHER(RR,peer);
  95. case Packet::VERB_MULTICAST_FRAME: return _doMULTICAST_FRAME(RR,peer);
  96. case Packet::VERB_PUSH_DIRECT_PATHS: return _doPUSH_DIRECT_PATHS(RR,peer);
  97. case Packet::VERB_CIRCUIT_TEST: return _doCIRCUIT_TEST(RR,peer);
  98. case Packet::VERB_CIRCUIT_TEST_REPORT: return _doCIRCUIT_TEST_REPORT(RR,peer);
  99. case Packet::VERB_USER_MESSAGE: return _doUSER_MESSAGE(RR,peer);
  100. }
  101. } else {
  102. RR->sw->requestWhois(sourceAddress);
  103. return false;
  104. }
  105. } catch ( ... ) {
  106. // Exceptions are more informatively caught in _do...() handlers but
  107. // this outer try/catch will catch anything else odd.
  108. TRACE("dropped ??? from %s(%s): unexpected exception in tryDecode()",sourceAddress.toString().c_str(),_path->address().toString().c_str());
  109. return true;
  110. }
  111. }
  112. bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  113. {
  114. try {
  115. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  116. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  117. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  118. //TRACE("ERROR %s from %s(%s) in-re %s",Packet::errorString(errorCode),peer->address().toString().c_str(),_path->address().toString().c_str(),Packet::verbString(inReVerb));
  119. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  120. * avoid having to log every outgoing packet ID. Instead we put the
  121. * logic to determine whether we should consider an ERROR in each
  122. * error handler. In most cases these are only trusted in specific
  123. * circumstances. */
  124. switch(errorCode) {
  125. case Packet::ERROR_OBJ_NOT_FOUND:
  126. // Object not found, currently only meaningful from network controllers.
  127. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  128. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  129. if ((network)&&(network->controller() == peer->address()))
  130. network->setNotFound();
  131. }
  132. break;
  133. case Packet::ERROR_UNSUPPORTED_OPERATION:
  134. // This can be sent in response to any operation, though right now we only
  135. // consider it meaningful from network controllers. This would indicate
  136. // that the queried node does not support acting as a controller.
  137. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  138. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  139. if ((network)&&(network->controller() == peer->address()))
  140. network->setNotFound();
  141. }
  142. break;
  143. case Packet::ERROR_IDENTITY_COLLISION:
  144. // FIXME: for federation this will need a payload with a signature or something.
  145. if (RR->topology->isUpstream(peer->identity()))
  146. RR->node->postEvent(ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION);
  147. break;
  148. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  149. // Peers can send this in response to frames if they do not have a recent enough COM from us
  150. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  151. const uint64_t now = RR->node->now();
  152. if ( (network) && (network->config().com) && (peer->rateGateIncomingComRequest(now)) )
  153. network->pushCredentialsNow(peer->address(),now);
  154. } break;
  155. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  156. // Network controller: network access denied.
  157. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  158. if ((network)&&(network->controller() == peer->address()))
  159. network->setAccessDenied();
  160. } break;
  161. case Packet::ERROR_UNWANTED_MULTICAST: {
  162. // Members of networks can use this error to indicate that they no longer
  163. // want to receive multicasts on a given channel.
  164. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  165. if ((network)&&(network->gate(peer))) {
  166. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8,6),6),at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  167. TRACE("%.16llx: peer %s unsubscrubed from multicast group %s",network->id(),peer->address().toString().c_str(),mg.toString().c_str());
  168. RR->mc->remove(network->id(),mg,peer->address());
  169. }
  170. } break;
  171. default: break;
  172. }
  173. peer->received(_path,hops(),packetId(),Packet::VERB_ERROR,inRePacketId,inReVerb,false);
  174. } catch ( ... ) {
  175. TRACE("dropped ERROR from %s(%s): unexpected exception",peer->address().toString().c_str(),_path->address().toString().c_str());
  176. }
  177. return true;
  178. }
  179. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,const bool alreadyAuthenticated)
  180. {
  181. try {
  182. const uint64_t now = RR->node->now();
  183. const uint64_t pid = packetId();
  184. const Address fromAddress(source());
  185. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  186. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  187. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  188. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  189. const uint64_t timestamp = at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  190. Identity id;
  191. InetAddress externalSurfaceAddress;
  192. uint64_t planetWorldId = 0;
  193. uint64_t planetWorldTimestamp = 0;
  194. std::vector< std::pair<uint64_t,uint64_t> > moonIdsAndTimestamps;
  195. {
  196. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  197. // Get external surface address if present (was not in old versions)
  198. if (ptr < size())
  199. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  200. // Get primary planet world ID and world timestamp if present
  201. if ((ptr + 16) <= size()) {
  202. planetWorldId = at<uint64_t>(ptr); ptr += 8;
  203. planetWorldTimestamp = at<uint64_t>(ptr);
  204. }
  205. // Get moon IDs and timestamps if present
  206. if ((ptr + 2) <= size()) {
  207. unsigned int numMoons = at<uint16_t>(ptr); ptr += 2;
  208. for(unsigned int i=0;i<numMoons;++i) {
  209. if ((World::Type)(*this)[ptr++] == World::TYPE_MOON)
  210. moonIdsAndTimestamps.push_back(std::pair<uint64_t,uint64_t>(at<uint64_t>(ptr),at<uint64_t>(ptr + 8)));
  211. ptr += 16;
  212. }
  213. }
  214. }
  215. if (fromAddress != id.address()) {
  216. TRACE("dropped HELLO from %s(%s): identity not for sending address",fromAddress.toString().c_str(),_path->address().toString().c_str());
  217. return true;
  218. }
  219. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  220. TRACE("dropped HELLO from %s(%s): protocol version too old",id.address().toString().c_str(),_path->address().toString().c_str());
  221. return true;
  222. }
  223. SharedPtr<Peer> peer(RR->topology->getPeer(id.address()));
  224. if (peer) {
  225. // We already have an identity with this address -- check for collisions
  226. if (!alreadyAuthenticated) {
  227. if (peer->identity() != id) {
  228. // Identity is different from the one we already have -- address collision
  229. // Check rate limits
  230. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  231. return true;
  232. uint8_t key[ZT_PEER_SECRET_KEY_LENGTH];
  233. if (RR->identity.agree(id,key,ZT_PEER_SECRET_KEY_LENGTH)) {
  234. if (dearmor(key)) { // ensure packet is authentic, otherwise drop
  235. TRACE("rejected HELLO from %s(%s): address already claimed",id.address().toString().c_str(),_path->address().toString().c_str());
  236. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  237. outp.append((uint8_t)Packet::VERB_HELLO);
  238. outp.append((uint64_t)pid);
  239. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  240. outp.armor(key,true);
  241. _path->send(RR,outp.data(),outp.size(),RR->node->now());
  242. } else {
  243. TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_path->address().toString().c_str());
  244. }
  245. } else {
  246. TRACE("rejected HELLO from %s(%s): key agreement failed",id.address().toString().c_str(),_path->address().toString().c_str());
  247. }
  248. return true;
  249. } else {
  250. // Identity is the same as the one we already have -- check packet integrity
  251. if (!dearmor(peer->key())) {
  252. TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_path->address().toString().c_str());
  253. return true;
  254. }
  255. // Continue at // VALID
  256. }
  257. } // else if alreadyAuthenticated then continue at // VALID
  258. } else {
  259. // We don't already have an identity with this address -- validate and learn it
  260. // Sanity check: this basically can't happen
  261. if (alreadyAuthenticated) {
  262. TRACE("dropped HELLO from %s(%s): somehow already authenticated with unknown peer?",id.address().toString().c_str(),_path->address().toString().c_str());
  263. return true;
  264. }
  265. // Check rate limits
  266. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  267. return true;
  268. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  269. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  270. if (!dearmor(newPeer->key())) {
  271. TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_path->address().toString().c_str());
  272. return true;
  273. }
  274. // Check that identity's address is valid as per the derivation function
  275. if (!id.locallyValidate()) {
  276. TRACE("dropped HELLO from %s(%s): identity invalid",id.address().toString().c_str(),_path->address().toString().c_str());
  277. return true;
  278. }
  279. peer = RR->topology->addPeer(newPeer);
  280. // Continue at // VALID
  281. }
  282. // VALID -- if we made it here, packet passed identity and authenticity checks!
  283. // Learn our external surface address from other peers to help us negotiate symmetric NATs
  284. // and detect changes to our global IP that can trigger path renegotiation.
  285. if ((externalSurfaceAddress)&&(hops() == 0))
  286. RR->sa->iam(id.address(),_path->localAddress(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(id),now);
  287. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  288. outp.append((unsigned char)Packet::VERB_HELLO);
  289. outp.append((uint64_t)pid);
  290. outp.append((uint64_t)timestamp);
  291. outp.append((unsigned char)ZT_PROTO_VERSION);
  292. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  293. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  294. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  295. if (protoVersion >= 5) {
  296. _path->address().serialize(outp);
  297. } else {
  298. /* LEGACY COMPATIBILITY HACK:
  299. *
  300. * For a while now (since 1.0.3), ZeroTier has recognized changes in
  301. * its network environment empirically by examining its external network
  302. * address as reported by trusted peers. In versions prior to 1.1.0
  303. * (protocol version < 5), they did this by saving a snapshot of this
  304. * information (in SelfAwareness.hpp) keyed by reporting device ID and
  305. * address type.
  306. *
  307. * This causes problems when clustering is combined with symmetric NAT.
  308. * Symmetric NAT remaps ports, so different endpoints in a cluster will
  309. * report back different exterior addresses. Since the old code keys
  310. * this by device ID and not sending physical address and compares the
  311. * entire address including port, it constantly thinks its external
  312. * surface is changing and resets connections when talking to a cluster.
  313. *
  314. * In new code we key by sending physical address and device and we also
  315. * take the more conservative position of only interpreting changes in
  316. * IP address (neglecting port) as a change in network topology that
  317. * necessitates a reset. But we can make older clients work here by
  318. * nulling out the port field. Since this info is only used for empirical
  319. * detection of link changes, it doesn't break anything else.
  320. */
  321. InetAddress tmpa(_path->address());
  322. tmpa.setPort(0);
  323. tmpa.serialize(outp);
  324. }
  325. const unsigned int worldUpdateSizeAt = outp.size();
  326. outp.addSize(2); // make room for 16-bit size field
  327. if ((planetWorldId)&&(RR->topology->planetWorldTimestamp() > planetWorldTimestamp)&&(planetWorldId == RR->topology->planetWorldId())) {
  328. RR->topology->planet().serialize(outp,false);
  329. }
  330. if (moonIdsAndTimestamps.size() > 0) {
  331. std::vector<World> moons(RR->topology->moons());
  332. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  333. for(std::vector< std::pair<uint64_t,uint64_t> >::const_iterator i(moonIdsAndTimestamps.begin());i!=moonIdsAndTimestamps.end();++i) {
  334. if (i->first == m->id()) {
  335. if (m->timestamp() > i->second)
  336. m->serialize(outp,false);
  337. break;
  338. }
  339. }
  340. }
  341. }
  342. outp.setAt<uint16_t>(worldUpdateSizeAt,(uint16_t)(outp.size() - (worldUpdateSizeAt + 2)));
  343. outp.armor(peer->key(),true);
  344. _path->send(RR,outp.data(),outp.size(),now);
  345. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  346. peer->received(_path,hops(),pid,Packet::VERB_HELLO,0,Packet::VERB_NOP,false);
  347. } catch ( ... ) {
  348. TRACE("dropped HELLO from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  349. }
  350. return true;
  351. }
  352. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  353. {
  354. try {
  355. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  356. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  357. if (!RR->node->expectingReplyTo(inRePacketId)) {
  358. TRACE("%s(%s): OK(%s) DROPPED: not expecting reply to %.16llx",peer->address().toString().c_str(),_path->address().toString().c_str(),Packet::verbString(inReVerb),packetId());
  359. return true;
  360. }
  361. //TRACE("%s(%s): OK(%s)",peer->address().toString().c_str(),_path->address().toString().c_str(),Packet::verbString(inReVerb));
  362. switch(inReVerb) {
  363. case Packet::VERB_HELLO: {
  364. const unsigned int latency = std::min((unsigned int)(RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP)),(unsigned int)0xffff);
  365. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  366. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  367. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  368. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  369. if (vProto < ZT_PROTO_VERSION_MIN) {
  370. TRACE("%s(%s): OK(HELLO) dropped, protocol version too old",source().toString().c_str(),_path->address().toString().c_str());
  371. return true;
  372. }
  373. InetAddress externalSurfaceAddress;
  374. unsigned int ptr = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
  375. // Get reported external surface address if present (was not on old versions)
  376. if (ptr < size())
  377. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  378. // Handle planet or moon updates if present (older versions don't send this)
  379. if ((ptr + 2) <= size()) {
  380. const unsigned int worldLen = at<uint16_t>(ptr); ptr += 2;
  381. const unsigned int endOfWorlds = ptr + worldLen;
  382. while (ptr < endOfWorlds) {
  383. World w;
  384. w.deserialize(*this,ptr);
  385. RR->topology->addWorld(w,true);
  386. }
  387. }
  388. TRACE("%s(%s): OK(HELLO), version %u.%u.%u, latency %u, reported external address %s",source().toString().c_str(),_path->address().toString().c_str(),vMajor,vMinor,vRevision,latency,((externalSurfaceAddress) ? externalSurfaceAddress.toString().c_str() : "(none)"));
  389. peer->addDirectLatencyMeasurment(latency);
  390. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  391. if ((externalSurfaceAddress)&&(hops() == 0))
  392. RR->sa->iam(peer->address(),_path->localAddress(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(peer->identity()),RR->node->now());
  393. } break;
  394. case Packet::VERB_WHOIS:
  395. if (RR->topology->isUpstream(peer->identity())) {
  396. const Identity id(*this,ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY);
  397. RR->sw->doAnythingWaitingForPeer(RR->topology->addPeer(SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  398. }
  399. break;
  400. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  401. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD)));
  402. if (network)
  403. network->handleConfigChunk(*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  404. } break;
  405. case Packet::VERB_MULTICAST_GATHER: {
  406. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  407. const SharedPtr<Network> network(RR->node->network(nwid));
  408. if (network) {
  409. 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));
  410. //TRACE("%s(%s): OK(MULTICAST_GATHER) %.16llx/%s length %u",source().toString().c_str(),_path->address().toString().c_str(),nwid,mg.toString().c_str(),size());
  411. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  412. RR->mc->addMultiple(RR->node->now(),nwid,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));
  413. }
  414. } break;
  415. case Packet::VERB_MULTICAST_FRAME: {
  416. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  417. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  418. 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));
  419. //TRACE("%s(%s): OK(MULTICAST_FRAME) %.16llx/%s flags %.2x",peer->address().toString().c_str(),_path->address().toString().c_str(),nwid,mg.toString().c_str(),flags);
  420. const SharedPtr<Network> network(RR->node->network(nwid));
  421. if (network) {
  422. unsigned int offset = 0;
  423. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  424. CertificateOfMembership com;
  425. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  426. if (com)
  427. network->addCredential(com);
  428. }
  429. if ((flags & 0x02) != 0) {
  430. // OK(MULTICAST_FRAME) includes implicit gather results
  431. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  432. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  433. unsigned int count = at<uint16_t>(offset); offset += 2;
  434. RR->mc->addMultiple(RR->node->now(),nwid,mg,field(offset,count * 5),count,totalKnown);
  435. }
  436. }
  437. } break;
  438. default: break;
  439. }
  440. peer->received(_path,hops(),packetId(),Packet::VERB_OK,inRePacketId,inReVerb,false);
  441. } catch ( ... ) {
  442. TRACE("dropped OK from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  443. }
  444. return true;
  445. }
  446. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  447. {
  448. try {
  449. if (!peer->rateGateInboundWhoisRequest(RR->node->now())) {
  450. TRACE("dropped WHOIS from %s(%s): rate limit circuit breaker tripped",source().toString().c_str(),_path->address().toString().c_str());
  451. return true;
  452. }
  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(addr));
  462. if (id) {
  463. id.serialize(outp,false);
  464. ++count;
  465. } else {
  466. RR->sw->requestWhois(addr);
  467. #ifdef ZT_ENABLE_CLUSTER
  468. // Distribute WHOIS queries across a cluster if we do not know the ID.
  469. // This may result in duplicate OKs to the querying peer, which is fine.
  470. if (RR->cluster)
  471. RR->cluster->sendDistributedQuery(*this);
  472. #endif
  473. }
  474. }
  475. if (count > 0) {
  476. outp.armor(peer->key(),true);
  477. _path->send(RR,outp.data(),outp.size(),RR->node->now());
  478. }
  479. peer->received(_path,hops(),packetId(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,false);
  480. } catch ( ... ) {
  481. TRACE("dropped WHOIS from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  482. }
  483. return true;
  484. }
  485. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  486. {
  487. try {
  488. if (!RR->topology->isUpstream(peer->identity())) {
  489. TRACE("RENDEZVOUS from %s ignored since source is not upstream",peer->address().toString().c_str());
  490. } else {
  491. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  492. const SharedPtr<Peer> rendezvousWith(RR->topology->getPeer(with));
  493. if (rendezvousWith) {
  494. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  495. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  496. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  497. const InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  498. if (RR->node->shouldUsePathForZeroTierTraffic(with,_path->localAddress(),atAddr)) {
  499. RR->node->putPacket(_path->localAddress(),atAddr,"ABRE",4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  500. rendezvousWith->attemptToContactAt(_path->localAddress(),atAddr,RR->node->now());
  501. TRACE("RENDEZVOUS from %s says %s might be at %s, sent verification attempt",peer->address().toString().c_str(),with.toString().c_str(),atAddr.toString().c_str());
  502. } else {
  503. TRACE("RENDEZVOUS from %s says %s might be at %s, ignoring since path is not suitable",peer->address().toString().c_str(),with.toString().c_str(),atAddr.toString().c_str());
  504. }
  505. } else {
  506. TRACE("dropped corrupt RENDEZVOUS from %s(%s) (bad address or port)",peer->address().toString().c_str(),_path->address().toString().c_str());
  507. }
  508. } else {
  509. TRACE("ignored RENDEZVOUS from %s(%s) to meet unknown peer %s",peer->address().toString().c_str(),_path->address().toString().c_str(),with.toString().c_str());
  510. }
  511. }
  512. peer->received(_path,hops(),packetId(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,false);
  513. } catch ( ... ) {
  514. TRACE("dropped RENDEZVOUS from %s(%s): unexpected exception",peer->address().toString().c_str(),_path->address().toString().c_str());
  515. }
  516. return true;
  517. }
  518. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  519. {
  520. try {
  521. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  522. const SharedPtr<Network> network(RR->node->network(nwid));
  523. bool trustEstablished = false;
  524. if (network) {
  525. if (network->gate(peer)) {
  526. trustEstablished = true;
  527. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  528. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  529. const MAC sourceMac(peer->address(),nwid);
  530. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  531. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  532. if (network->filterIncomingPacket(peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  533. RR->node->putFrame(nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  534. }
  535. } else {
  536. TRACE("dropped FRAME from %s(%s): not a member of private network %.16llx",peer->address().toString().c_str(),_path->address().toString().c_str(),(unsigned long long)network->id());
  537. _sendErrorNeedCredentials(RR,peer,nwid);
  538. }
  539. } else {
  540. TRACE("dropped FRAME from %s(%s): we are not a member of network %.16llx",source().toString().c_str(),_path->address().toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID));
  541. _sendErrorNeedCredentials(RR,peer,nwid);
  542. }
  543. peer->received(_path,hops(),packetId(),Packet::VERB_FRAME,0,Packet::VERB_NOP,trustEstablished);
  544. } catch ( ... ) {
  545. TRACE("dropped FRAME from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  546. }
  547. return true;
  548. }
  549. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  550. {
  551. try {
  552. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  553. const SharedPtr<Network> network(RR->node->network(nwid));
  554. if (network) {
  555. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  556. unsigned int comLen = 0;
  557. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  558. CertificateOfMembership com;
  559. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  560. if (com)
  561. network->addCredential(com);
  562. }
  563. if (!network->gate(peer)) {
  564. TRACE("dropped EXT_FRAME from %s(%s): not a member of private network %.16llx",peer->address().toString().c_str(),_path->address().toString().c_str(),network->id());
  565. _sendErrorNeedCredentials(RR,peer,nwid);
  566. peer->received(_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false);
  567. return true;
  568. }
  569. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  570. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  571. 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);
  572. 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);
  573. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  574. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  575. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  576. TRACE("dropped EXT_FRAME from %s@%s(%s) to %s: invalid source MAC %s",from.toString().c_str(),peer->address().toString().c_str(),_path->address().toString().c_str(),to.toString().c_str(),from.toString().c_str());
  577. peer->received(_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true); // trustEstablished because COM is okay
  578. return true;
  579. }
  580. switch (network->filterIncomingPacket(peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  581. case 1:
  582. if (from != MAC(peer->address(),nwid)) {
  583. if (network->config().permitsBridging(peer->address())) {
  584. network->learnBridgeRoute(from,peer->address());
  585. } else {
  586. TRACE("dropped EXT_FRAME from %s@%s(%s) to %s: sender not allowed to bridge into %.16llx",from.toString().c_str(),peer->address().toString().c_str(),_path->address().toString().c_str(),to.toString().c_str(),network->id());
  587. peer->received(_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true); // trustEstablished because COM is okay
  588. return true;
  589. }
  590. } else if (to != network->mac()) {
  591. if (to.isMulticast()) {
  592. if (network->config().multicastLimit == 0) {
  593. TRACE("dropped EXT_FRAME from %s@%s(%s) to %s: network %.16llx does not allow multicast",from.toString().c_str(),peer->address().toString().c_str(),_path->address().toString().c_str(),to.toString().c_str(),network->id());
  594. peer->received(_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true); // trustEstablished because COM is okay
  595. return true;
  596. }
  597. } else if (!network->config().permitsBridging(RR->identity.address())) {
  598. TRACE("dropped EXT_FRAME from %s@%s(%s) to %s: I cannot bridge to %.16llx or bridging disabled on network",from.toString().c_str(),peer->address().toString().c_str(),_path->address().toString().c_str(),to.toString().c_str(),network->id());
  599. peer->received(_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true); // trustEstablished because COM is okay
  600. return true;
  601. }
  602. }
  603. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  604. case 2:
  605. RR->node->putFrame(nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  606. break;
  607. }
  608. }
  609. if ((flags & 0x10) != 0) { // ACK requested
  610. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  611. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  612. outp.append((uint64_t)packetId());
  613. outp.append((uint64_t)nwid);
  614. outp.armor(peer->key(),true);
  615. _path->send(RR,outp.data(),outp.size(),RR->node->now());
  616. }
  617. peer->received(_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true);
  618. } else {
  619. TRACE("dropped EXT_FRAME from %s(%s): we are not connected to network %.16llx",source().toString().c_str(),_path->address().toString().c_str(),at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID));
  620. _sendErrorNeedCredentials(RR,peer,nwid);
  621. peer->received(_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false);
  622. }
  623. } catch ( ... ) {
  624. TRACE("dropped EXT_FRAME from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  625. }
  626. return true;
  627. }
  628. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  629. {
  630. try {
  631. if (!peer->rateGateEchoRequest(RR->node->now())) {
  632. TRACE("dropped ECHO from %s(%s): rate limit circuit breaker tripped",source().toString().c_str(),_path->address().toString().c_str());
  633. return true;
  634. }
  635. const uint64_t pid = packetId();
  636. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  637. outp.append((unsigned char)Packet::VERB_ECHO);
  638. outp.append((uint64_t)pid);
  639. if (size() > ZT_PACKET_IDX_PAYLOAD)
  640. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  641. outp.armor(peer->key(),true);
  642. _path->send(RR,outp.data(),outp.size(),RR->node->now());
  643. peer->received(_path,hops(),pid,Packet::VERB_ECHO,0,Packet::VERB_NOP,false);
  644. } catch ( ... ) {
  645. TRACE("dropped ECHO from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  646. }
  647. return true;
  648. }
  649. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  650. {
  651. try {
  652. const uint64_t now = RR->node->now();
  653. uint64_t authOnNetwork[256]; // cache for approved network IDs
  654. unsigned int authOnNetworkCount = 0;
  655. SharedPtr<Network> network;
  656. bool trustEstablished = false;
  657. // Iterate through 18-byte network,MAC,ADI tuples
  658. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) {
  659. const uint64_t nwid = at<uint64_t>(ptr);
  660. bool auth = false;
  661. for(unsigned int i=0;i<authOnNetworkCount;++i) {
  662. if (nwid == authOnNetwork[i]) {
  663. auth = true;
  664. break;
  665. }
  666. }
  667. if (!auth) {
  668. if ((!network)||(network->id() != nwid))
  669. network = RR->node->network(nwid);
  670. const bool authOnNet = ((network)&&(network->gate(peer)));
  671. if (!authOnNet)
  672. _sendErrorNeedCredentials(RR,peer,nwid);
  673. trustEstablished |= authOnNet;
  674. if (authOnNet||RR->mc->cacheAuthorized(peer->address(),nwid,now)) {
  675. auth = true;
  676. if (authOnNetworkCount < 256) // sanity check, packets can't really be this big
  677. authOnNetwork[authOnNetworkCount++] = nwid;
  678. }
  679. }
  680. if (auth) {
  681. const MulticastGroup group(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14));
  682. RR->mc->add(now,nwid,group,peer->address());
  683. }
  684. }
  685. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,trustEstablished);
  686. } catch ( ... ) {
  687. TRACE("dropped MULTICAST_LIKE from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  688. }
  689. return true;
  690. }
  691. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  692. {
  693. try {
  694. if (!peer->rateGateCredentialsReceived(RR->node->now())) {
  695. TRACE("dropped NETWORK_CREDENTIALS from %s(%s): rate limit circuit breaker tripped",source().toString().c_str(),_path->address().toString().c_str());
  696. return true;
  697. }
  698. CertificateOfMembership com;
  699. Capability cap;
  700. Tag tag;
  701. Revocation revocation;
  702. bool trustEstablished = false;
  703. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  704. while ((p < size())&&((*this)[p])) {
  705. p += com.deserialize(*this,p);
  706. if (com) {
  707. const SharedPtr<Network> network(RR->node->network(com.networkId()));
  708. if (network) {
  709. switch (network->addCredential(com)) {
  710. case Membership::ADD_REJECTED:
  711. break;
  712. case Membership::ADD_ACCEPTED_NEW:
  713. case Membership::ADD_ACCEPTED_REDUNDANT:
  714. trustEstablished = true;
  715. break;
  716. case Membership::ADD_DEFERRED_FOR_WHOIS:
  717. return false;
  718. }
  719. } else RR->mc->addCredential(com,false);
  720. }
  721. }
  722. ++p; // skip trailing 0 after COMs if present
  723. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  724. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  725. for(unsigned int i=0;i<numCapabilities;++i) {
  726. p += cap.deserialize(*this,p);
  727. const SharedPtr<Network> network(RR->node->network(cap.networkId()));
  728. if (network) {
  729. switch (network->addCredential(cap)) {
  730. case Membership::ADD_REJECTED:
  731. break;
  732. case Membership::ADD_ACCEPTED_NEW:
  733. case Membership::ADD_ACCEPTED_REDUNDANT:
  734. trustEstablished = true;
  735. break;
  736. case Membership::ADD_DEFERRED_FOR_WHOIS:
  737. return false;
  738. }
  739. }
  740. }
  741. const unsigned int numTags = at<uint16_t>(p); p += 2;
  742. for(unsigned int i=0;i<numTags;++i) {
  743. p += tag.deserialize(*this,p);
  744. const SharedPtr<Network> network(RR->node->network(tag.networkId()));
  745. if (network) {
  746. switch (network->addCredential(tag)) {
  747. case Membership::ADD_REJECTED:
  748. break;
  749. case Membership::ADD_ACCEPTED_NEW:
  750. case Membership::ADD_ACCEPTED_REDUNDANT:
  751. trustEstablished = true;
  752. break;
  753. case Membership::ADD_DEFERRED_FOR_WHOIS:
  754. return false;
  755. }
  756. }
  757. }
  758. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  759. for(unsigned int i=0;i<numRevocations;++i) {
  760. p += revocation.deserialize(*this,p);
  761. const SharedPtr<Network> network(RR->node->network(revocation.networkId()));
  762. if (network) {
  763. switch(network->addCredential(peer->address(),revocation)) {
  764. case Membership::ADD_REJECTED:
  765. break;
  766. case Membership::ADD_ACCEPTED_NEW:
  767. case Membership::ADD_ACCEPTED_REDUNDANT:
  768. trustEstablished = true;
  769. break;
  770. case Membership::ADD_DEFERRED_FOR_WHOIS:
  771. return false;
  772. }
  773. }
  774. }
  775. }
  776. peer->received(_path,hops(),packetId(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,trustEstablished);
  777. } catch (std::exception &exc) {
  778. TRACE("dropped NETWORK_CREDENTIALS from %s(%s): %s",source().toString().c_str(),_path->address().toString().c_str(),exc.what());
  779. } catch ( ... ) {
  780. TRACE("dropped NETWORK_CREDENTIALS from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  781. }
  782. return true;
  783. }
  784. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  785. {
  786. try {
  787. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  788. const unsigned int hopCount = hops();
  789. const uint64_t requestPacketId = packetId();
  790. if (RR->localNetworkController) {
  791. const unsigned int metaDataLength = at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN);
  792. const char *metaDataBytes = (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength);
  793. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  794. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  795. } else {
  796. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  797. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  798. outp.append(requestPacketId);
  799. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  800. outp.append(nwid);
  801. outp.armor(peer->key(),true);
  802. _path->send(RR,outp.data(),outp.size(),RR->node->now());
  803. }
  804. peer->received(_path,hopCount,requestPacketId,Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,false);
  805. } catch (std::exception &exc) {
  806. fprintf(stderr,"WARNING: network config request failed with exception: %s" ZT_EOL_S,exc.what());
  807. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): %s",source().toString().c_str(),_path->address().toString().c_str(),exc.what());
  808. } catch ( ... ) {
  809. fprintf(stderr,"WARNING: network config request failed with exception: unknown exception" ZT_EOL_S);
  810. TRACE("dropped NETWORK_CONFIG_REQUEST from %s(%s): unknown exception",source().toString().c_str(),_path->address().toString().c_str());
  811. }
  812. return true;
  813. }
  814. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  815. {
  816. try {
  817. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  818. if (network) {
  819. const uint64_t configUpdateId = network->handleConfigChunk(*this,ZT_PACKET_IDX_PAYLOAD);
  820. if (configUpdateId) {
  821. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  822. outp.append((uint8_t)Packet::VERB_ECHO);
  823. outp.append((uint64_t)packetId());
  824. outp.append((uint64_t)network->id());
  825. outp.append((uint64_t)configUpdateId);
  826. outp.armor(peer->key(),true);
  827. _path->send(RR,outp.data(),outp.size(),RR->node->now());
  828. }
  829. }
  830. peer->received(_path,hops(),packetId(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,false);
  831. } catch ( ... ) {
  832. TRACE("dropped NETWORK_CONFIG_REFRESH from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  833. }
  834. return true;
  835. }
  836. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  837. {
  838. try {
  839. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  840. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  841. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  842. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  843. //TRACE("<<MC %s(%s) GATHER up to %u in %.16llx/%s",source().toString().c_str(),_path->address().toString().c_str(),gatherLimit,nwid,mg.toString().c_str());
  844. const SharedPtr<Network> network(RR->node->network(nwid));
  845. if ((flags & 0x01) != 0) {
  846. try {
  847. CertificateOfMembership com;
  848. com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  849. if (com) {
  850. if (network)
  851. network->addCredential(com);
  852. else RR->mc->addCredential(com,false);
  853. }
  854. } catch ( ... ) {
  855. TRACE("MULTICAST_GATHER from %s(%s): discarded invalid COM",peer->address().toString().c_str(),_path->address().toString().c_str());
  856. }
  857. }
  858. const bool trustEstablished = ((network)&&(network->gate(peer)));
  859. if (!trustEstablished)
  860. _sendErrorNeedCredentials(RR,peer,nwid);
  861. if ( ( trustEstablished || RR->mc->cacheAuthorized(peer->address(),nwid,RR->node->now()) ) && (gatherLimit > 0) ) {
  862. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  863. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  864. outp.append(packetId());
  865. outp.append(nwid);
  866. mg.mac().appendTo(outp);
  867. outp.append((uint32_t)mg.adi());
  868. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  869. if (gatheredLocally > 0) {
  870. outp.armor(peer->key(),true);
  871. _path->send(RR,outp.data(),outp.size(),RR->node->now());
  872. }
  873. // If we are a member of a cluster, distribute this GATHER across it
  874. #ifdef ZT_ENABLE_CLUSTER
  875. if ((RR->cluster)&&(gatheredLocally < gatherLimit))
  876. RR->cluster->sendDistributedQuery(*this);
  877. #endif
  878. }
  879. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,trustEstablished);
  880. } catch ( ... ) {
  881. TRACE("dropped MULTICAST_GATHER from %s(%s): unexpected exception",peer->address().toString().c_str(),_path->address().toString().c_str());
  882. }
  883. return true;
  884. }
  885. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  886. {
  887. try {
  888. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID);
  889. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS];
  890. const SharedPtr<Network> network(RR->node->network(nwid));
  891. if (network) {
  892. // Offset -- size of optional fields added to position of later fields
  893. unsigned int offset = 0;
  894. if ((flags & 0x01) != 0) {
  895. // This is deprecated but may still be sent by old peers
  896. CertificateOfMembership com;
  897. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM);
  898. if (com)
  899. network->addCredential(com);
  900. }
  901. if (!network->gate(peer)) {
  902. TRACE("dropped MULTICAST_FRAME from %s(%s): not a member of private network %.16llx",peer->address().toString().c_str(),_path->address().toString().c_str(),(unsigned long long)network->id());
  903. _sendErrorNeedCredentials(RR,peer,nwid);
  904. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false);
  905. return true;
  906. }
  907. if (network->config().multicastLimit == 0) {
  908. TRACE("dropped MULTICAST_FRAME from %s(%s): network %.16llx does not allow multicast",peer->address().toString().c_str(),_path->address().toString().c_str(),(unsigned long long)network->id());
  909. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false);
  910. return true;
  911. }
  912. unsigned int gatherLimit = 0;
  913. if ((flags & 0x02) != 0) {
  914. gatherLimit = at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT);
  915. offset += 4;
  916. }
  917. MAC from;
  918. if ((flags & 0x04) != 0) {
  919. from.setTo(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6),6);
  920. offset += 6;
  921. } else {
  922. from.fromAddress(peer->address(),nwid);
  923. }
  924. 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));
  925. const unsigned int etherType = at<uint16_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  926. const unsigned int frameLen = size() - (offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME);
  927. //TRACE("<<MC FRAME %.16llx/%s from %s@%s flags %.2x length %u",nwid,to.toString().c_str(),from.toString().c_str(),peer->address().toString().c_str(),flags,frameLen);
  928. if ((frameLen > 0)&&(frameLen <= ZT_IF_MTU)) {
  929. if (!to.mac().isMulticast()) {
  930. TRACE("dropped MULTICAST_FRAME from %s@%s(%s) to %s: destination is unicast, must use FRAME or EXT_FRAME",from.toString().c_str(),peer->address().toString().c_str(),_path->address().toString().c_str(),to.toString().c_str());
  931. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true); // trustEstablished because COM is okay
  932. return true;
  933. }
  934. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  935. TRACE("dropped MULTICAST_FRAME from %s@%s(%s) to %s: invalid source MAC",from.toString().c_str(),peer->address().toString().c_str(),_path->address().toString().c_str(),to.toString().c_str());
  936. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true); // trustEstablished because COM is okay
  937. return true;
  938. }
  939. if (from != MAC(peer->address(),nwid)) {
  940. if (network->config().permitsBridging(peer->address())) {
  941. network->learnBridgeRoute(from,peer->address());
  942. } else {
  943. TRACE("dropped MULTICAST_FRAME from %s@%s(%s) to %s: sender not allowed to bridge into %.16llx",from.toString().c_str(),peer->address().toString().c_str(),_path->address().toString().c_str(),to.toString().c_str(),network->id());
  944. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true); // trustEstablished because COM is okay
  945. return true;
  946. }
  947. }
  948. const uint8_t *const frameData = (const uint8_t *)field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME,frameLen);
  949. if (network->filterIncomingPacket(peer,RR->identity.address(),from,to.mac(),frameData,frameLen,etherType,0) > 0) {
  950. RR->node->putFrame(nwid,network->userPtr(),from,to.mac(),etherType,0,(const void *)frameData,frameLen);
  951. }
  952. }
  953. if (gatherLimit) {
  954. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  955. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  956. outp.append(packetId());
  957. outp.append(nwid);
  958. to.mac().appendTo(outp);
  959. outp.append((uint32_t)to.adi());
  960. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  961. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  962. outp.armor(peer->key(),true);
  963. _path->send(RR,outp.data(),outp.size(),RR->node->now());
  964. }
  965. }
  966. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true);
  967. } else {
  968. _sendErrorNeedCredentials(RR,peer,nwid);
  969. peer->received(_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false);
  970. }
  971. } catch ( ... ) {
  972. TRACE("dropped MULTICAST_FRAME from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  973. }
  974. return true;
  975. }
  976. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  977. {
  978. try {
  979. const uint64_t now = RR->node->now();
  980. // First, subject this to a rate limit
  981. if (!peer->rateGatePushDirectPaths(now)) {
  982. TRACE("dropped PUSH_DIRECT_PATHS from %s(%s): circuit breaker tripped",source().toString().c_str(),_path->address().toString().c_str());
  983. peer->received(_path,hops(),packetId(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false);
  984. return true;
  985. }
  986. // Second, limit addresses by scope and type
  987. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  988. memset(countPerScope,0,sizeof(countPerScope));
  989. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  990. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  991. while (count--) { // if ptr overflows Buffer will throw
  992. // TODO: some flags are not yet implemented
  993. unsigned int flags = (*this)[ptr++];
  994. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  995. ptr += extLen; // unused right now
  996. unsigned int addrType = (*this)[ptr++];
  997. unsigned int addrLen = (*this)[ptr++];
  998. switch(addrType) {
  999. case 4: {
  1000. InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  1001. bool redundant = false;
  1002. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  1003. peer->setClusterOptimal(a);
  1004. } else {
  1005. redundant = peer->hasActivePathTo(now,a);
  1006. }
  1007. if ( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && (!redundant) && (RR->node->shouldUsePathForZeroTierTraffic(peer->address(),_path->localAddress(),a)) ) {
  1008. if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  1009. TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
  1010. peer->attemptToContactAt(InetAddress(),a,now);
  1011. } else {
  1012. TRACE("ignoring contact for %s at %s -- too many per scope",peer->address().toString().c_str(),a.toString().c_str());
  1013. }
  1014. }
  1015. } break;
  1016. case 6: {
  1017. InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  1018. bool redundant = false;
  1019. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  1020. peer->setClusterOptimal(a);
  1021. } else {
  1022. redundant = peer->hasActivePathTo(now,a);
  1023. }
  1024. if ( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && (!redundant) && (RR->node->shouldUsePathForZeroTierTraffic(peer->address(),_path->localAddress(),a)) ) {
  1025. if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  1026. TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
  1027. peer->attemptToContactAt(InetAddress(),a,now);
  1028. } else {
  1029. TRACE("ignoring contact for %s at %s -- too many per scope",peer->address().toString().c_str(),a.toString().c_str());
  1030. }
  1031. }
  1032. } break;
  1033. }
  1034. ptr += addrLen;
  1035. }
  1036. peer->received(_path,hops(),packetId(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false);
  1037. } catch ( ... ) {
  1038. TRACE("dropped PUSH_DIRECT_PATHS from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  1039. }
  1040. return true;
  1041. }
  1042. bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  1043. {
  1044. try {
  1045. const Address originatorAddress(field(ZT_PACKET_IDX_PAYLOAD,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  1046. SharedPtr<Peer> originator(RR->topology->getPeer(originatorAddress));
  1047. if (!originator) {
  1048. RR->sw->requestWhois(originatorAddress);
  1049. return false;
  1050. }
  1051. const unsigned int flags = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 5);
  1052. const uint64_t timestamp = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 7);
  1053. const uint64_t testId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 15);
  1054. // Tracks total length of variable length fields, initialized to originator credential length below
  1055. unsigned int vlf;
  1056. // Originator credentials -- right now only a network ID for which the originator is controller or is authorized by controller is allowed
  1057. const unsigned int originatorCredentialLength = vlf = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 23);
  1058. uint64_t originatorCredentialNetworkId = 0;
  1059. if (originatorCredentialLength >= 1) {
  1060. switch((*this)[ZT_PACKET_IDX_PAYLOAD + 25]) {
  1061. case 0x01: { // 64-bit network ID, originator must be controller
  1062. if (originatorCredentialLength >= 9)
  1063. originatorCredentialNetworkId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 26);
  1064. } break;
  1065. default: break;
  1066. }
  1067. }
  1068. // Add length of "additional fields," which are currently unused
  1069. vlf += at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 25 + vlf);
  1070. // Verify signature -- only tests signed by their originators are allowed
  1071. const unsigned int signatureLength = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 27 + vlf);
  1072. if (!originator->identity().verify(field(ZT_PACKET_IDX_PAYLOAD,27 + vlf),27 + vlf,field(ZT_PACKET_IDX_PAYLOAD + 29 + vlf,signatureLength),signatureLength)) {
  1073. TRACE("dropped CIRCUIT_TEST from %s(%s): signature by originator %s invalid",source().toString().c_str(),_path->address().toString().c_str(),originatorAddress.toString().c_str());
  1074. peer->received(_path,hops(),packetId(),Packet::VERB_CIRCUIT_TEST,0,Packet::VERB_NOP,false);
  1075. return true;
  1076. }
  1077. vlf += signatureLength;
  1078. // Save this length so we can copy the immutable parts of this test
  1079. // into the one we send along to next hops.
  1080. const unsigned int lengthOfSignedPortionAndSignature = 29 + vlf;
  1081. // Add length of second "additional fields" section.
  1082. vlf += at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 29 + vlf);
  1083. uint64_t reportFlags = 0;
  1084. // Check credentials (signature already verified)
  1085. if (originatorCredentialNetworkId) {
  1086. SharedPtr<Network> network(RR->node->network(originatorCredentialNetworkId));
  1087. if ((!network)||(!network->config().circuitTestingAllowed(originatorAddress))) {
  1088. TRACE("dropped CIRCUIT_TEST from %s(%s): originator %s specified network ID %.16llx as credential, and we don't belong to that network or originator is not allowed'",source().toString().c_str(),_path->address().toString().c_str(),originatorAddress.toString().c_str(),originatorCredentialNetworkId);
  1089. peer->received(_path,hops(),packetId(),Packet::VERB_CIRCUIT_TEST,0,Packet::VERB_NOP,false);
  1090. return true;
  1091. }
  1092. if (network->gate(peer))
  1093. reportFlags |= ZT_CIRCUIT_TEST_REPORT_FLAGS_UPSTREAM_AUTHORIZED_IN_PATH;
  1094. } else {
  1095. TRACE("dropped CIRCUIT_TEST from %s(%s): originator %s did not specify a credential or credential type",source().toString().c_str(),_path->address().toString().c_str(),originatorAddress.toString().c_str());
  1096. peer->received(_path,hops(),packetId(),Packet::VERB_CIRCUIT_TEST,0,Packet::VERB_NOP,false);
  1097. return true;
  1098. }
  1099. const uint64_t now = RR->node->now();
  1100. unsigned int breadth = 0;
  1101. Address nextHop[256]; // breadth is a uin8_t, so this is the max
  1102. InetAddress nextHopBestPathAddress[256];
  1103. unsigned int remainingHopsPtr = ZT_PACKET_IDX_PAYLOAD + 33 + vlf;
  1104. if ((ZT_PACKET_IDX_PAYLOAD + 31 + vlf) < size()) {
  1105. // unsigned int nextHopFlags = (*this)[ZT_PACKET_IDX_PAYLOAD + 31 + vlf]
  1106. breadth = (*this)[ZT_PACKET_IDX_PAYLOAD + 32 + vlf];
  1107. for(unsigned int h=0;h<breadth;++h) {
  1108. nextHop[h].setTo(field(remainingHopsPtr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  1109. remainingHopsPtr += ZT_ADDRESS_LENGTH;
  1110. SharedPtr<Peer> nhp(RR->topology->getPeer(nextHop[h]));
  1111. if (nhp) {
  1112. SharedPtr<Path> nhbp(nhp->getBestPath(now,false));
  1113. if ((nhbp)&&(nhbp->alive(now)))
  1114. nextHopBestPathAddress[h] = nhbp->address();
  1115. }
  1116. }
  1117. }
  1118. // Report back to originator, depending on flags and whether we are last hop
  1119. if ( ((flags & 0x01) != 0) || ((breadth == 0)&&((flags & 0x02) != 0)) ) {
  1120. Packet outp(originatorAddress,RR->identity.address(),Packet::VERB_CIRCUIT_TEST_REPORT);
  1121. outp.append((uint64_t)timestamp);
  1122. outp.append((uint64_t)testId);
  1123. outp.append((uint64_t)0); // field reserved for future use
  1124. outp.append((uint8_t)ZT_VENDOR_ZEROTIER);
  1125. outp.append((uint8_t)ZT_PROTO_VERSION);
  1126. outp.append((uint8_t)ZEROTIER_ONE_VERSION_MAJOR);
  1127. outp.append((uint8_t)ZEROTIER_ONE_VERSION_MINOR);
  1128. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  1129. outp.append((uint16_t)ZT_PLATFORM_UNSPECIFIED);
  1130. outp.append((uint16_t)ZT_ARCHITECTURE_UNSPECIFIED);
  1131. outp.append((uint16_t)0); // error code, currently unused
  1132. outp.append((uint64_t)reportFlags);
  1133. outp.append((uint64_t)packetId());
  1134. peer->address().appendTo(outp);
  1135. outp.append((uint8_t)hops());
  1136. _path->localAddress().serialize(outp);
  1137. _path->address().serialize(outp);
  1138. outp.append((uint16_t)0); // no additional fields
  1139. outp.append((uint8_t)breadth);
  1140. for(unsigned int h=0;h<breadth;++h) {
  1141. nextHop[h].appendTo(outp);
  1142. nextHopBestPathAddress[h].serialize(outp); // appends 0 if null InetAddress
  1143. }
  1144. RR->sw->send(outp,true);
  1145. }
  1146. // If there are next hops, forward the test along through the graph
  1147. if (breadth > 0) {
  1148. Packet outp(Address(),RR->identity.address(),Packet::VERB_CIRCUIT_TEST);
  1149. outp.append(field(ZT_PACKET_IDX_PAYLOAD,lengthOfSignedPortionAndSignature),lengthOfSignedPortionAndSignature);
  1150. outp.append((uint16_t)0); // no additional fields
  1151. if (remainingHopsPtr < size())
  1152. outp.append(field(remainingHopsPtr,size() - remainingHopsPtr),size() - remainingHopsPtr);
  1153. for(unsigned int h=0;h<breadth;++h) {
  1154. if (RR->identity.address() != nextHop[h]) { // next hops that loop back to the current hop are not valid
  1155. outp.newInitializationVector();
  1156. outp.setDestination(nextHop[h]);
  1157. RR->sw->send(outp,true);
  1158. }
  1159. }
  1160. }
  1161. peer->received(_path,hops(),packetId(),Packet::VERB_CIRCUIT_TEST,0,Packet::VERB_NOP,false);
  1162. } catch ( ... ) {
  1163. TRACE("dropped CIRCUIT_TEST from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  1164. }
  1165. return true;
  1166. }
  1167. bool IncomingPacket::_doCIRCUIT_TEST_REPORT(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  1168. {
  1169. try {
  1170. ZT_CircuitTestReport report;
  1171. memset(&report,0,sizeof(report));
  1172. report.current = peer->address().toInt();
  1173. report.upstream = Address(field(ZT_PACKET_IDX_PAYLOAD + 52,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH).toInt();
  1174. report.testId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 8);
  1175. report.timestamp = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  1176. report.sourcePacketId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 44);
  1177. report.flags = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD + 36);
  1178. report.sourcePacketHopCount = (*this)[ZT_PACKET_IDX_PAYLOAD + 57]; // end of fixed length headers: 58
  1179. report.errorCode = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 34);
  1180. report.vendor = (enum ZT_Vendor)((*this)[ZT_PACKET_IDX_PAYLOAD + 24]);
  1181. report.protocolVersion = (*this)[ZT_PACKET_IDX_PAYLOAD + 25];
  1182. report.majorVersion = (*this)[ZT_PACKET_IDX_PAYLOAD + 26];
  1183. report.minorVersion = (*this)[ZT_PACKET_IDX_PAYLOAD + 27];
  1184. report.revision = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 28);
  1185. report.platform = (enum ZT_Platform)at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 30);
  1186. report.architecture = (enum ZT_Architecture)at<uint16_t>(ZT_PACKET_IDX_PAYLOAD + 32);
  1187. const unsigned int receivedOnLocalAddressLen = reinterpret_cast<InetAddress *>(&(report.receivedOnLocalAddress))->deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 58);
  1188. const unsigned int receivedFromRemoteAddressLen = reinterpret_cast<InetAddress *>(&(report.receivedFromRemoteAddress))->deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 58 + receivedOnLocalAddressLen);
  1189. unsigned int nhptr = ZT_PACKET_IDX_PAYLOAD + 58 + receivedOnLocalAddressLen + receivedFromRemoteAddressLen;
  1190. nhptr += at<uint16_t>(nhptr) + 2; // add "additional field" length, which right now will be zero
  1191. report.nextHopCount = (*this)[nhptr++];
  1192. if (report.nextHopCount > ZT_CIRCUIT_TEST_MAX_HOP_BREADTH) // sanity check, shouldn't be possible
  1193. report.nextHopCount = ZT_CIRCUIT_TEST_MAX_HOP_BREADTH;
  1194. for(unsigned int h=0;h<report.nextHopCount;++h) {
  1195. report.nextHops[h].address = Address(field(nhptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH).toInt(); nhptr += ZT_ADDRESS_LENGTH;
  1196. nhptr += reinterpret_cast<InetAddress *>(&(report.nextHops[h].physicalAddress))->deserialize(*this,nhptr);
  1197. }
  1198. RR->node->postCircuitTestReport(&report);
  1199. peer->received(_path,hops(),packetId(),Packet::VERB_CIRCUIT_TEST_REPORT,0,Packet::VERB_NOP,false);
  1200. } catch ( ... ) {
  1201. TRACE("dropped CIRCUIT_TEST_REPORT from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  1202. }
  1203. return true;
  1204. }
  1205. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer)
  1206. {
  1207. try {
  1208. if (size() >= (ZT_PACKET_IDX_PAYLOAD + 8)) {
  1209. ZT_UserMessage um;
  1210. um.origin = peer->address().toInt();
  1211. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  1212. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  1213. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  1214. RR->node->postEvent(ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  1215. }
  1216. peer->received(_path,hops(),packetId(),Packet::VERB_CIRCUIT_TEST_REPORT,0,Packet::VERB_NOP,false);
  1217. } catch ( ... ) {
  1218. TRACE("dropped CIRCUIT_TEST_REPORT from %s(%s): unexpected exception",source().toString().c_str(),_path->address().toString().c_str());
  1219. }
  1220. return true;
  1221. }
  1222. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,const SharedPtr<Peer> &peer,const uint64_t nwid)
  1223. {
  1224. const uint64_t now = RR->node->now();
  1225. if (peer->rateGateOutgoingComRequest(now)) {
  1226. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  1227. outp.append((uint8_t)verb());
  1228. outp.append(packetId());
  1229. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  1230. outp.append(nwid);
  1231. outp.armor(peer->key(),true);
  1232. _path->send(RR,outp.data(),outp.size(),now);
  1233. }
  1234. }
  1235. } // namespace ZeroTier