IncomingPacket.cpp 59 KB

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