IncomingPacket.cpp 63 KB

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