IncomingPacket.cpp 60 KB

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