IncomingPacket.cpp 65 KB

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