IncomingPacket.cpp 60 KB

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