IncomingPacket.cpp 59 KB

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