IncomingPacket.cpp 60 KB

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