IncomingPacket.cpp 65 KB

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