IncomingPacket.cpp 67 KB

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