IncomingPacket.cpp 64 KB

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