IncomingPacket.cpp 63 KB

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