IncomingPacket.cpp 60 KB

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