IncomingPacket.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <stdlib.h>
  29. #include "../version.h"
  30. #include "../include/ZeroTierOne.h"
  31. #include "Constants.hpp"
  32. #include "RuntimeEnvironment.hpp"
  33. #include "IncomingPacket.hpp"
  34. #include "Topology.hpp"
  35. #include "Switch.hpp"
  36. #include "Peer.hpp"
  37. #include "NetworkController.hpp"
  38. #include "SelfAwareness.hpp"
  39. #include "Salsa20.hpp"
  40. #include "SHA512.hpp"
  41. #include "World.hpp"
  42. #include "Node.hpp"
  43. #include "CertificateOfMembership.hpp"
  44. #include "CertificateOfRepresentation.hpp"
  45. #include "Capability.hpp"
  46. #include "Tag.hpp"
  47. #include "Revocation.hpp"
  48. #include "Trace.hpp"
  49. namespace ZeroTier {
  50. bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr)
  51. {
  52. const Address sourceAddress(source());
  53. try {
  54. // Check for trusted paths or unencrypted HELLOs (HELLO is the only packet sent in the clear)
  55. const unsigned int c = cipher();
  56. bool trusted = false;
  57. if (c == ZT_PROTO_CIPHER_SUITE__NO_CRYPTO_TRUSTED_PATH) {
  58. // If this is marked as a packet via a trusted path, check source address and path ID.
  59. // Obviously if no trusted paths are configured this always returns false and such
  60. // packets are dropped on the floor.
  61. const uint64_t tpid = trustedPathId();
  62. if (RR->topology->shouldInboundPathBeTrusted(_path->address(),tpid)) {
  63. RR->t->incomingPacketTrustedPath(tPtr,_path,packetId(),sourceAddress,tpid,true);
  64. trusted = true;
  65. } else {
  66. RR->t->incomingPacketTrustedPath(tPtr,_path,packetId(),sourceAddress,tpid,false);
  67. return true;
  68. }
  69. } else if ((c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)&&(verb() == Packet::VERB_HELLO)) {
  70. // Only HELLO is allowed in the clear, but will still have a MAC
  71. return _doHELLO(RR,tPtr,false);
  72. }
  73. const SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,sourceAddress));
  74. if (peer) {
  75. if (!trusted) {
  76. if (!dearmor(peer->key())) {
  77. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,packetId(),sourceAddress,hops());
  78. return true;
  79. }
  80. }
  81. if (!uncompress()) {
  82. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),Packet::VERB_NOP,"LZ4 decompression failed");
  83. return true;
  84. }
  85. const Packet::Verb v = verb();
  86. switch(v) {
  87. //case Packet::VERB_NOP:
  88. default: // ignore unknown verbs, but if they pass auth check they are "received"
  89. peer->received(tPtr,_path,hops(),packetId(),v,0,Packet::VERB_NOP,false,0);
  90. return true;
  91. case Packet::VERB_HELLO: return _doHELLO(RR,tPtr,true);
  92. case Packet::VERB_ERROR: return _doERROR(RR,tPtr,peer);
  93. case Packet::VERB_OK: return _doOK(RR,tPtr,peer);
  94. case Packet::VERB_WHOIS: return _doWHOIS(RR,tPtr,peer);
  95. case Packet::VERB_RENDEZVOUS: return _doRENDEZVOUS(RR,tPtr,peer);
  96. case Packet::VERB_FRAME: return _doFRAME(RR,tPtr,peer);
  97. case Packet::VERB_EXT_FRAME: return _doEXT_FRAME(RR,tPtr,peer);
  98. case Packet::VERB_ECHO: return _doECHO(RR,tPtr,peer);
  99. case Packet::VERB_MULTICAST_LIKE: return _doMULTICAST_LIKE(RR,tPtr,peer);
  100. case Packet::VERB_NETWORK_CREDENTIALS: return _doNETWORK_CREDENTIALS(RR,tPtr,peer);
  101. case Packet::VERB_NETWORK_CONFIG_REQUEST: return _doNETWORK_CONFIG_REQUEST(RR,tPtr,peer);
  102. case Packet::VERB_NETWORK_CONFIG: return _doNETWORK_CONFIG(RR,tPtr,peer);
  103. case Packet::VERB_MULTICAST_GATHER: return _doMULTICAST_GATHER(RR,tPtr,peer);
  104. case Packet::VERB_MULTICAST_FRAME: return _doMULTICAST_FRAME(RR,tPtr,peer);
  105. case Packet::VERB_PUSH_DIRECT_PATHS: return _doPUSH_DIRECT_PATHS(RR,tPtr,peer);
  106. case Packet::VERB_USER_MESSAGE: return _doUSER_MESSAGE(RR,tPtr,peer);
  107. case Packet::VERB_REMOTE_TRACE: return _doREMOTE_TRACE(RR,tPtr,peer);
  108. }
  109. } else {
  110. RR->sw->requestWhois(tPtr,sourceAddress);
  111. return false;
  112. }
  113. } catch ( ... ) {
  114. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),sourceAddress,hops(),verb(),"unexpected exception in tryDecode()");
  115. return true;
  116. }
  117. }
  118. bool IncomingPacket::_doERROR(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  119. {
  120. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB];
  121. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID);
  122. const Packet::ErrorCode errorCode = (Packet::ErrorCode)(*this)[ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE];
  123. uint64_t networkId = 0;
  124. /* Security note: we do not gate doERROR() with expectingReplyTo() to
  125. * avoid having to log every outgoing packet ID. Instead we put the
  126. * logic to determine whether we should consider an ERROR in each
  127. * error handler. In most cases these are only trusted in specific
  128. * circumstances. */
  129. switch(errorCode) {
  130. case Packet::ERROR_OBJ_NOT_FOUND:
  131. // Object not found, currently only meaningful from network controllers.
  132. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  133. const 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_UNSUPPORTED_OPERATION:
  139. // This can be sent in response to any operation, though right now we only
  140. // consider it meaningful from network controllers. This would indicate
  141. // that the queried node does not support acting as a controller.
  142. if (inReVerb == Packet::VERB_NETWORK_CONFIG_REQUEST) {
  143. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  144. if ((network)&&(network->controller() == peer->address()))
  145. network->setNotFound();
  146. }
  147. break;
  148. case Packet::ERROR_IDENTITY_COLLISION:
  149. // FIXME: for federation this will need a payload with a signature or something.
  150. if (RR->topology->isUpstream(peer->identity()))
  151. RR->node->postEvent(tPtr,ZT_EVENT_FATAL_ERROR_IDENTITY_COLLISION);
  152. break;
  153. case Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE: {
  154. // Peers can send this in response to frames if they do not have a recent enough COM from us
  155. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  156. const SharedPtr<Network> network(RR->node->network(networkId));
  157. const uint64_t now = RR->node->now();
  158. if ( (network) && (network->config().com) && (peer->rateGateIncomingComRequest(now)) )
  159. network->pushCredentialsNow(tPtr,peer->address(),now);
  160. } break;
  161. case Packet::ERROR_NETWORK_ACCESS_DENIED_: {
  162. // Network controller: network access denied.
  163. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)));
  164. if ((network)&&(network->controller() == peer->address()))
  165. network->setAccessDenied();
  166. } break;
  167. case Packet::ERROR_UNWANTED_MULTICAST: {
  168. // Members of networks can use this error to indicate that they no longer
  169. // want to receive multicasts on a given channel.
  170. networkId = at<uint64_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD);
  171. const SharedPtr<Network> network(RR->node->network(networkId));
  172. if ((network)&&(network->gate(tPtr,peer))) {
  173. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 8,6),6),at<uint32_t>(ZT_PROTO_VERB_ERROR_IDX_PAYLOAD + 14));
  174. RR->mc->remove(network->id(),mg,peer->address());
  175. }
  176. } break;
  177. default: break;
  178. }
  179. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_ERROR,inRePacketId,inReVerb,false,networkId);
  180. return true;
  181. }
  182. bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool alreadyAuthenticated)
  183. {
  184. const uint64_t now = RR->node->now();
  185. const uint64_t pid = packetId();
  186. const Address fromAddress(source());
  187. const unsigned int protoVersion = (*this)[ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION];
  188. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION];
  189. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION];
  190. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO_IDX_REVISION);
  191. const uint64_t timestamp = at<uint64_t>(ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP);
  192. Identity id;
  193. unsigned int ptr = ZT_PROTO_VERB_HELLO_IDX_IDENTITY + id.deserialize(*this,ZT_PROTO_VERB_HELLO_IDX_IDENTITY);
  194. if (protoVersion < ZT_PROTO_VERSION_MIN) {
  195. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"protocol version too old");
  196. return true;
  197. }
  198. if (fromAddress != id.address()) {
  199. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"identity/address mismatch");
  200. return true;
  201. }
  202. SharedPtr<Peer> peer(RR->topology->getPeer(tPtr,id.address()));
  203. if (peer) {
  204. // We already have an identity with this address -- check for collisions
  205. if (!alreadyAuthenticated) {
  206. if (peer->identity() != id) {
  207. // Identity is different from the one we already have -- address collision
  208. // Check rate limits
  209. if (!RR->node->rateGateIdentityVerification(now,_path->address()))
  210. return true;
  211. uint8_t key[ZT_PEER_SECRET_KEY_LENGTH];
  212. if (RR->identity.agree(id,key,ZT_PEER_SECRET_KEY_LENGTH)) {
  213. if (dearmor(key)) { // ensure packet is authentic, otherwise drop
  214. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"address collision");
  215. Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
  216. outp.append((uint8_t)Packet::VERB_HELLO);
  217. outp.append((uint64_t)pid);
  218. outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
  219. outp.armor(key,true,_path->nextOutgoingCounter());
  220. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  221. } else {
  222. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops());
  223. }
  224. } else {
  225. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops());
  226. }
  227. return true;
  228. } else {
  229. // Identity is the same as the one we already have -- check packet integrity
  230. if (!dearmor(peer->key())) {
  231. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops());
  232. return true;
  233. }
  234. // Continue at // VALID
  235. }
  236. } // else if alreadyAuthenticated then continue at // VALID
  237. } else {
  238. // We don't already have an identity with this address -- validate and learn it
  239. // Sanity check: this basically can't happen
  240. if (alreadyAuthenticated) {
  241. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"illegal alreadyAuthenticated state");
  242. return true;
  243. }
  244. // Check rate limits
  245. if (!RR->node->rateGateIdentityVerification(now,_path->address())) {
  246. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"rate limit exceeded");
  247. return true;
  248. }
  249. // Check packet integrity and MAC (this is faster than locallyValidate() so do it first to filter out total crap)
  250. SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
  251. if (!dearmor(newPeer->key())) {
  252. RR->t->incomingPacketMessageAuthenticationFailure(tPtr,_path,pid,fromAddress,hops());
  253. return true;
  254. }
  255. // Check that identity's address is valid as per the derivation function
  256. if (!id.locallyValidate()) {
  257. RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"invalid identity");
  258. return true;
  259. }
  260. peer = RR->topology->addPeer(tPtr,newPeer);
  261. // Continue at // VALID
  262. }
  263. // VALID -- if we made it here, packet passed identity and authenticity checks!
  264. // Get external surface address if present (was not in old versions)
  265. InetAddress externalSurfaceAddress;
  266. if (ptr < size()) {
  267. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  268. if ((externalSurfaceAddress)&&(hops() == 0))
  269. RR->sa->iam(tPtr,id.address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(id),now);
  270. }
  271. // Get primary planet world ID and world timestamp if present
  272. uint64_t planetWorldId = 0;
  273. uint64_t planetWorldTimestamp = 0;
  274. if ((ptr + 16) <= size()) {
  275. planetWorldId = at<uint64_t>(ptr); ptr += 8;
  276. planetWorldTimestamp = at<uint64_t>(ptr); ptr += 8;
  277. }
  278. std::vector< std::pair<uint64_t,uint64_t> > moonIdsAndTimestamps;
  279. if (ptr < size()) {
  280. // Remainder of packet, if present, is encrypted
  281. cryptField(peer->key(),ptr,size() - ptr);
  282. // Get moon IDs and timestamps if present
  283. if ((ptr + 2) <= size()) {
  284. const unsigned int numMoons = at<uint16_t>(ptr); ptr += 2;
  285. for(unsigned int i=0;i<numMoons;++i) {
  286. if ((World::Type)(*this)[ptr++] == World::TYPE_MOON)
  287. moonIdsAndTimestamps.push_back(std::pair<uint64_t,uint64_t>(at<uint64_t>(ptr),at<uint64_t>(ptr + 8)));
  288. ptr += 16;
  289. }
  290. }
  291. // Certificates of representation (if present)
  292. if ((ptr + 2) <= size()) {
  293. if (at<uint16_t>(ptr) > 0) {
  294. CertificateOfRepresentation cor;
  295. ptr += 2;
  296. ptr += cor.deserialize(*this,ptr);
  297. } else ptr += 2;
  298. }
  299. }
  300. // Send OK(HELLO) with an echo of the packet's timestamp and some of the same
  301. // information about us: version, sent-to address, etc.
  302. Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
  303. outp.append((unsigned char)Packet::VERB_HELLO);
  304. outp.append((uint64_t)pid);
  305. outp.append((uint64_t)timestamp);
  306. outp.append((unsigned char)ZT_PROTO_VERSION);
  307. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MAJOR);
  308. outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
  309. outp.append((uint16_t)ZEROTIER_ONE_VERSION_REVISION);
  310. if (protoVersion >= 5) {
  311. _path->address().serialize(outp);
  312. } else {
  313. /* LEGACY COMPATIBILITY HACK:
  314. *
  315. * For a while now (since 1.0.3), ZeroTier has recognized changes in
  316. * its network environment empirically by examining its external network
  317. * address as reported by trusted peers. In versions prior to 1.1.0
  318. * (protocol version < 5), they did this by saving a snapshot of this
  319. * information (in SelfAwareness.hpp) keyed by reporting device ID and
  320. * address type.
  321. *
  322. * This causes problems when clustering is combined with symmetric NAT.
  323. * Symmetric NAT remaps ports, so different endpoints in a cluster will
  324. * report back different exterior addresses. Since the old code keys
  325. * this by device ID and not sending physical address and compares the
  326. * entire address including port, it constantly thinks its external
  327. * surface is changing and resets connections when talking to a cluster.
  328. *
  329. * In new code we key by sending physical address and device and we also
  330. * take the more conservative position of only interpreting changes in
  331. * IP address (neglecting port) as a change in network topology that
  332. * necessitates a reset. But we can make older clients work here by
  333. * nulling out the port field. Since this info is only used for empirical
  334. * detection of link changes, it doesn't break anything else.
  335. */
  336. InetAddress tmpa(_path->address());
  337. tmpa.setPort(0);
  338. tmpa.serialize(outp);
  339. }
  340. const unsigned int worldUpdateSizeAt = outp.size();
  341. outp.addSize(2); // make room for 16-bit size field
  342. if ((planetWorldId)&&(RR->topology->planetWorldTimestamp() > planetWorldTimestamp)&&(planetWorldId == RR->topology->planetWorldId())) {
  343. RR->topology->planet().serialize(outp,false);
  344. }
  345. if (moonIdsAndTimestamps.size() > 0) {
  346. std::vector<World> moons(RR->topology->moons());
  347. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  348. for(std::vector< std::pair<uint64_t,uint64_t> >::const_iterator i(moonIdsAndTimestamps.begin());i!=moonIdsAndTimestamps.end();++i) {
  349. if (i->first == m->id()) {
  350. if (m->timestamp() > i->second)
  351. m->serialize(outp,false);
  352. break;
  353. }
  354. }
  355. }
  356. }
  357. outp.setAt<uint16_t>(worldUpdateSizeAt,(uint16_t)(outp.size() - (worldUpdateSizeAt + 2)));
  358. const unsigned int corSizeAt = outp.size();
  359. outp.addSize(2);
  360. RR->topology->appendCertificateOfRepresentation(outp);
  361. outp.setAt(corSizeAt,(uint16_t)(outp.size() - (corSizeAt + 2)));
  362. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  363. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  364. peer->setRemoteVersion(protoVersion,vMajor,vMinor,vRevision); // important for this to go first so received() knows the version
  365. peer->received(tPtr,_path,hops(),pid,Packet::VERB_HELLO,0,Packet::VERB_NOP,false,0);
  366. return true;
  367. }
  368. bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  369. {
  370. const Packet::Verb inReVerb = (Packet::Verb)(*this)[ZT_PROTO_VERB_OK_IDX_IN_RE_VERB];
  371. const uint64_t inRePacketId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID);
  372. uint64_t networkId = 0;
  373. if (!RR->node->expectingReplyTo(inRePacketId))
  374. return true;
  375. switch(inReVerb) {
  376. case Packet::VERB_HELLO: {
  377. const uint64_t latency = RR->node->now() - at<uint64_t>(ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP);
  378. if (latency > ZT_HELLO_MAX_ALLOWABLE_LATENCY)
  379. return true;
  380. const unsigned int vProto = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION];
  381. const unsigned int vMajor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION];
  382. const unsigned int vMinor = (*this)[ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION];
  383. const unsigned int vRevision = at<uint16_t>(ZT_PROTO_VERB_HELLO__OK__IDX_REVISION);
  384. if (vProto < ZT_PROTO_VERSION_MIN)
  385. return true;
  386. InetAddress externalSurfaceAddress;
  387. unsigned int ptr = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
  388. // Get reported external surface address if present
  389. if (ptr < size())
  390. ptr += externalSurfaceAddress.deserialize(*this,ptr);
  391. // Handle planet or moon updates if present
  392. if ((ptr + 2) <= size()) {
  393. const unsigned int worldsLen = at<uint16_t>(ptr); ptr += 2;
  394. if (RR->topology->shouldAcceptWorldUpdateFrom(peer->address())) {
  395. const unsigned int endOfWorlds = ptr + worldsLen;
  396. while (ptr < endOfWorlds) {
  397. World w;
  398. ptr += w.deserialize(*this,ptr);
  399. RR->topology->addWorld(tPtr,w,false);
  400. }
  401. } else {
  402. ptr += worldsLen;
  403. }
  404. }
  405. // Handle certificate of representation if present
  406. if ((ptr + 2) <= size()) {
  407. if (at<uint16_t>(ptr) > 0) {
  408. CertificateOfRepresentation cor;
  409. ptr += 2;
  410. ptr += cor.deserialize(*this,ptr);
  411. } else ptr += 2;
  412. }
  413. if (!hops())
  414. peer->addDirectLatencyMeasurment((unsigned int)latency);
  415. peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
  416. if ((externalSurfaceAddress)&&(hops() == 0))
  417. RR->sa->iam(tPtr,peer->address(),_path->localSocket(),_path->address(),externalSurfaceAddress,RR->topology->isUpstream(peer->identity()),RR->node->now());
  418. } break;
  419. case Packet::VERB_WHOIS:
  420. if (RR->topology->isUpstream(peer->identity())) {
  421. const Identity id(*this,ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY);
  422. RR->sw->doAnythingWaitingForPeer(tPtr,RR->topology->addPeer(tPtr,SharedPtr<Peer>(new Peer(RR,RR->identity,id))));
  423. }
  424. break;
  425. case Packet::VERB_NETWORK_CONFIG_REQUEST: {
  426. networkId = at<uint64_t>(ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  427. const SharedPtr<Network> network(RR->node->network(networkId));
  428. if (network)
  429. network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PROTO_VERB_OK_IDX_PAYLOAD);
  430. } break;
  431. case Packet::VERB_MULTICAST_GATHER: {
  432. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID);
  433. const SharedPtr<Network> network(RR->node->network(networkId));
  434. if (network) {
  435. 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));
  436. const unsigned int count = at<uint16_t>(ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS + 4);
  437. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,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));
  438. }
  439. } break;
  440. case Packet::VERB_MULTICAST_FRAME: {
  441. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS];
  442. networkId = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID);
  443. 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));
  444. const SharedPtr<Network> network(RR->node->network(networkId));
  445. if (network) {
  446. unsigned int offset = 0;
  447. if ((flags & 0x01) != 0) { // deprecated but still used by older peers
  448. CertificateOfMembership com;
  449. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS);
  450. if (com)
  451. network->addCredential(tPtr,com);
  452. }
  453. if ((flags & 0x02) != 0) {
  454. // OK(MULTICAST_FRAME) includes implicit gather results
  455. offset += ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS;
  456. unsigned int totalKnown = at<uint32_t>(offset); offset += 4;
  457. unsigned int count = at<uint16_t>(offset); offset += 2;
  458. RR->mc->addMultiple(tPtr,RR->node->now(),networkId,mg,field(offset,count * 5),count,totalKnown);
  459. }
  460. }
  461. } break;
  462. default: break;
  463. }
  464. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_OK,inRePacketId,inReVerb,false,networkId);
  465. return true;
  466. }
  467. bool IncomingPacket::_doWHOIS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  468. {
  469. if ((!RR->topology->amRoot())&&(!peer->rateGateInboundWhoisRequest(RR->node->now())))
  470. return true;
  471. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  472. outp.append((unsigned char)Packet::VERB_WHOIS);
  473. outp.append(packetId());
  474. unsigned int count = 0;
  475. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD;
  476. while ((ptr + ZT_ADDRESS_LENGTH) <= size()) {
  477. const Address addr(field(ptr,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  478. ptr += ZT_ADDRESS_LENGTH;
  479. const Identity id(RR->topology->getIdentity(tPtr,addr));
  480. if (id) {
  481. id.serialize(outp,false);
  482. ++count;
  483. } else {
  484. // Request unknown WHOIS from upstream from us (if we have one)
  485. RR->sw->requestWhois(tPtr,addr);
  486. }
  487. }
  488. if (count > 0) {
  489. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  490. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  491. }
  492. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_WHOIS,0,Packet::VERB_NOP,false,0);
  493. return true;
  494. }
  495. bool IncomingPacket::_doRENDEZVOUS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  496. {
  497. if (RR->topology->isUpstream(peer->identity())) {
  498. const Address with(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  499. const SharedPtr<Peer> rendezvousWith(RR->topology->getPeer(tPtr,with));
  500. if (rendezvousWith) {
  501. const unsigned int port = at<uint16_t>(ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT);
  502. const unsigned int addrlen = (*this)[ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN];
  503. if ((port > 0)&&((addrlen == 4)||(addrlen == 16))) {
  504. const InetAddress atAddr(field(ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS,addrlen),addrlen,port);
  505. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr,with,_path->localSocket(),atAddr)) {
  506. const uint64_t junk = RR->node->prng();
  507. RR->node->putPacket(tPtr,_path->localSocket(),atAddr,&junk,4,2); // send low-TTL junk packet to 'open' local NAT(s) and stateful firewalls
  508. rendezvousWith->attemptToContactAt(tPtr,_path->localSocket(),atAddr,RR->node->now(),false,0);
  509. }
  510. }
  511. }
  512. }
  513. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_RENDEZVOUS,0,Packet::VERB_NOP,false,0);
  514. return true;
  515. }
  516. bool IncomingPacket::_doFRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  517. {
  518. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID);
  519. const SharedPtr<Network> network(RR->node->network(nwid));
  520. bool trustEstablished = false;
  521. if (network) {
  522. if (network->gate(tPtr,peer)) {
  523. trustEstablished = true;
  524. if (size() > ZT_PROTO_VERB_FRAME_IDX_PAYLOAD) {
  525. const unsigned int etherType = at<uint16_t>(ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE);
  526. const MAC sourceMac(peer->address(),nwid);
  527. const unsigned int frameLen = size() - ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  528. const uint8_t *const frameData = reinterpret_cast<const uint8_t *>(data()) + ZT_PROTO_VERB_FRAME_IDX_PAYLOAD;
  529. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),sourceMac,network->mac(),frameData,frameLen,etherType,0) > 0)
  530. RR->node->putFrame(tPtr,nwid,network->userPtr(),sourceMac,network->mac(),etherType,0,(const void *)frameData,frameLen);
  531. }
  532. } else {
  533. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  534. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_FRAME,true);
  535. }
  536. } else {
  537. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  538. }
  539. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_FRAME,0,Packet::VERB_NOP,trustEstablished,nwid);
  540. return true;
  541. }
  542. bool IncomingPacket::_doEXT_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  543. {
  544. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID);
  545. const SharedPtr<Network> network(RR->node->network(nwid));
  546. if (network) {
  547. const unsigned int flags = (*this)[ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS];
  548. unsigned int comLen = 0;
  549. if ((flags & 0x01) != 0) { // inline COM with EXT_FRAME is deprecated but still used with old peers
  550. CertificateOfMembership com;
  551. comLen = com.deserialize(*this,ZT_PROTO_VERB_EXT_FRAME_IDX_COM);
  552. if (com)
  553. network->addCredential(tPtr,com);
  554. }
  555. if (!network->gate(tPtr,peer)) {
  556. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,true);
  557. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  558. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false,nwid);
  559. return true;
  560. }
  561. if (size() > ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD) {
  562. const unsigned int etherType = at<uint16_t>(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE);
  563. 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);
  564. 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);
  565. const unsigned int frameLen = size() - (comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD);
  566. const uint8_t *const frameData = (const uint8_t *)field(comLen + ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD,frameLen);
  567. if ((!from)||(from == network->mac())) {
  568. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  569. return true;
  570. }
  571. switch (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to,frameData,frameLen,etherType,0)) {
  572. case 1:
  573. if (from != MAC(peer->address(),nwid)) {
  574. if (network->config().permitsBridging(peer->address())) {
  575. network->learnBridgeRoute(from,peer->address());
  576. } else {
  577. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (remote)");
  578. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  579. return true;
  580. }
  581. } else if (to != network->mac()) {
  582. if (to.isMulticast()) {
  583. if (network->config().multicastLimit == 0) {
  584. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"multicast disabled");
  585. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  586. return true;
  587. }
  588. } else if (!network->config().permitsBridging(RR->identity.address())) {
  589. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_EXT_FRAME,from,to,"bridging not allowed (local)");
  590. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  591. return true;
  592. }
  593. }
  594. // fall through -- 2 means accept regardless of bridging checks or other restrictions
  595. case 2:
  596. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to,etherType,0,(const void *)frameData,frameLen);
  597. break;
  598. }
  599. }
  600. if ((flags & 0x10) != 0) { // ACK requested
  601. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  602. outp.append((uint8_t)Packet::VERB_EXT_FRAME);
  603. outp.append((uint64_t)packetId());
  604. outp.append((uint64_t)nwid);
  605. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  606. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  607. }
  608. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,true,nwid);
  609. } else {
  610. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_EXT_FRAME,0,Packet::VERB_NOP,false,nwid);
  611. }
  612. return true;
  613. }
  614. bool IncomingPacket::_doECHO(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  615. {
  616. if (!peer->rateGateEchoRequest(RR->node->now()))
  617. return true;
  618. const uint64_t pid = packetId();
  619. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  620. outp.append((unsigned char)Packet::VERB_ECHO);
  621. outp.append((uint64_t)pid);
  622. if (size() > ZT_PACKET_IDX_PAYLOAD)
  623. outp.append(reinterpret_cast<const unsigned char *>(data()) + ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  624. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  625. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  626. peer->received(tPtr,_path,hops(),pid,Packet::VERB_ECHO,0,Packet::VERB_NOP,false,0);
  627. return true;
  628. }
  629. bool IncomingPacket::_doMULTICAST_LIKE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  630. {
  631. const uint64_t now = RR->node->now();
  632. uint64_t authOnNetwork[256]; // cache for approved network IDs
  633. unsigned int authOnNetworkCount = 0;
  634. SharedPtr<Network> network;
  635. bool trustEstablished = false;
  636. // Iterate through 18-byte network,MAC,ADI tuples
  637. for(unsigned int ptr=ZT_PACKET_IDX_PAYLOAD;ptr<size();ptr+=18) {
  638. const uint64_t nwid = at<uint64_t>(ptr);
  639. bool auth = false;
  640. for(unsigned int i=0;i<authOnNetworkCount;++i) {
  641. if (nwid == authOnNetwork[i]) {
  642. auth = true;
  643. break;
  644. }
  645. }
  646. if (!auth) {
  647. if ((!network)||(network->id() != nwid))
  648. network = RR->node->network(nwid);
  649. const bool authOnNet = ((network)&&(network->gate(tPtr,peer)));
  650. if (!authOnNet)
  651. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  652. trustEstablished |= authOnNet;
  653. if (authOnNet||RR->mc->cacheAuthorized(peer->address(),nwid,now)) {
  654. auth = true;
  655. if (authOnNetworkCount < 256) // sanity check, packets can't really be this big
  656. authOnNetwork[authOnNetworkCount++] = nwid;
  657. }
  658. }
  659. if (auth) {
  660. const MulticastGroup group(MAC(field(ptr + 8,6),6),at<uint32_t>(ptr + 14));
  661. RR->mc->add(tPtr,now,nwid,group,peer->address());
  662. }
  663. }
  664. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_LIKE,0,Packet::VERB_NOP,trustEstablished,(network) ? network->id() : 0);
  665. return true;
  666. }
  667. bool IncomingPacket::_doNETWORK_CREDENTIALS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  668. {
  669. if (!peer->rateGateCredentialsReceived(RR->node->now()))
  670. return true;
  671. CertificateOfMembership com;
  672. Capability cap;
  673. Tag tag;
  674. Revocation revocation;
  675. CertificateOfOwnership coo;
  676. bool trustEstablished = false;
  677. SharedPtr<Network> network;
  678. unsigned int p = ZT_PACKET_IDX_PAYLOAD;
  679. while ((p < size())&&((*this)[p] != 0)) {
  680. p += com.deserialize(*this,p);
  681. if (com) {
  682. network = RR->node->network(com.networkId());
  683. if (network) {
  684. switch (network->addCredential(tPtr,com)) {
  685. case Membership::ADD_REJECTED:
  686. break;
  687. case Membership::ADD_ACCEPTED_NEW:
  688. case Membership::ADD_ACCEPTED_REDUNDANT:
  689. trustEstablished = true;
  690. break;
  691. case Membership::ADD_DEFERRED_FOR_WHOIS:
  692. return false;
  693. }
  694. } else RR->mc->addCredential(tPtr,com,false);
  695. }
  696. }
  697. ++p; // skip trailing 0 after COMs if present
  698. if (p < size()) { // older ZeroTier versions do not send capabilities, tags, or revocations
  699. const unsigned int numCapabilities = at<uint16_t>(p); p += 2;
  700. for(unsigned int i=0;i<numCapabilities;++i) {
  701. p += cap.deserialize(*this,p);
  702. if ((!network)||(network->id() != cap.networkId()))
  703. network = RR->node->network(cap.networkId());
  704. if (network) {
  705. switch (network->addCredential(tPtr,cap)) {
  706. case Membership::ADD_REJECTED:
  707. break;
  708. case Membership::ADD_ACCEPTED_NEW:
  709. case Membership::ADD_ACCEPTED_REDUNDANT:
  710. trustEstablished = true;
  711. break;
  712. case Membership::ADD_DEFERRED_FOR_WHOIS:
  713. return false;
  714. }
  715. }
  716. }
  717. if (p >= size()) return true;
  718. const unsigned int numTags = at<uint16_t>(p); p += 2;
  719. for(unsigned int i=0;i<numTags;++i) {
  720. p += tag.deserialize(*this,p);
  721. if ((!network)||(network->id() != tag.networkId()))
  722. network = RR->node->network(tag.networkId());
  723. if (network) {
  724. switch (network->addCredential(tPtr,tag)) {
  725. case Membership::ADD_REJECTED:
  726. break;
  727. case Membership::ADD_ACCEPTED_NEW:
  728. case Membership::ADD_ACCEPTED_REDUNDANT:
  729. trustEstablished = true;
  730. break;
  731. case Membership::ADD_DEFERRED_FOR_WHOIS:
  732. return false;
  733. }
  734. }
  735. }
  736. if (p >= size()) return true;
  737. const unsigned int numRevocations = at<uint16_t>(p); p += 2;
  738. for(unsigned int i=0;i<numRevocations;++i) {
  739. p += revocation.deserialize(*this,p);
  740. if ((!network)||(network->id() != revocation.networkId()))
  741. network = RR->node->network(revocation.networkId());
  742. if (network) {
  743. switch(network->addCredential(tPtr,peer->address(),revocation)) {
  744. case Membership::ADD_REJECTED:
  745. break;
  746. case Membership::ADD_ACCEPTED_NEW:
  747. case Membership::ADD_ACCEPTED_REDUNDANT:
  748. trustEstablished = true;
  749. break;
  750. case Membership::ADD_DEFERRED_FOR_WHOIS:
  751. return false;
  752. }
  753. }
  754. }
  755. if (p >= size()) return true;
  756. const unsigned int numCoos = at<uint16_t>(p); p += 2;
  757. for(unsigned int i=0;i<numCoos;++i) {
  758. p += coo.deserialize(*this,p);
  759. if ((!network)||(network->id() != coo.networkId()))
  760. network = RR->node->network(coo.networkId());
  761. if (network) {
  762. switch(network->addCredential(tPtr,coo)) {
  763. case Membership::ADD_REJECTED:
  764. break;
  765. case Membership::ADD_ACCEPTED_NEW:
  766. case Membership::ADD_ACCEPTED_REDUNDANT:
  767. trustEstablished = true;
  768. break;
  769. case Membership::ADD_DEFERRED_FOR_WHOIS:
  770. return false;
  771. }
  772. }
  773. }
  774. }
  775. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_NETWORK_CREDENTIALS,0,Packet::VERB_NOP,trustEstablished,(network) ? network->id() : 0);
  776. return true;
  777. }
  778. bool IncomingPacket::_doNETWORK_CONFIG_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  779. {
  780. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID);
  781. const unsigned int hopCount = hops();
  782. const uint64_t requestPacketId = packetId();
  783. if (RR->localNetworkController) {
  784. const unsigned int metaDataLength = (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN <= size()) ? at<uint16_t>(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN) : 0;
  785. const char *metaDataBytes = (metaDataLength != 0) ? (const char *)field(ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT,metaDataLength) : (const char *)0;
  786. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> metaData(metaDataBytes,metaDataLength);
  787. RR->localNetworkController->request(nwid,(hopCount > 0) ? InetAddress() : _path->address(),requestPacketId,peer->identity(),metaData);
  788. } else {
  789. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_ERROR);
  790. outp.append((unsigned char)Packet::VERB_NETWORK_CONFIG_REQUEST);
  791. outp.append(requestPacketId);
  792. outp.append((unsigned char)Packet::ERROR_UNSUPPORTED_OPERATION);
  793. outp.append(nwid);
  794. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  795. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  796. }
  797. peer->received(tPtr,_path,hopCount,requestPacketId,Packet::VERB_NETWORK_CONFIG_REQUEST,0,Packet::VERB_NOP,false,nwid);
  798. return true;
  799. }
  800. bool IncomingPacket::_doNETWORK_CONFIG(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  801. {
  802. const SharedPtr<Network> network(RR->node->network(at<uint64_t>(ZT_PACKET_IDX_PAYLOAD)));
  803. if (network) {
  804. const uint64_t configUpdateId = network->handleConfigChunk(tPtr,packetId(),source(),*this,ZT_PACKET_IDX_PAYLOAD);
  805. if (configUpdateId) {
  806. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  807. outp.append((uint8_t)Packet::VERB_ECHO);
  808. outp.append((uint64_t)packetId());
  809. outp.append((uint64_t)network->id());
  810. outp.append((uint64_t)configUpdateId);
  811. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  812. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  813. }
  814. }
  815. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_NETWORK_CONFIG,0,Packet::VERB_NOP,false,(network) ? network->id() : 0);
  816. return true;
  817. }
  818. bool IncomingPacket::_doMULTICAST_GATHER(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  819. {
  820. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID);
  821. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS];
  822. const MulticastGroup mg(MAC(field(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC,6),6),at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI));
  823. const unsigned int gatherLimit = at<uint32_t>(ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT);
  824. const SharedPtr<Network> network(RR->node->network(nwid));
  825. if ((flags & 0x01) != 0) {
  826. try {
  827. CertificateOfMembership com;
  828. com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_GATHER_IDX_COM);
  829. if (com) {
  830. if (network)
  831. network->addCredential(tPtr,com);
  832. else RR->mc->addCredential(tPtr,com,false);
  833. }
  834. } catch ( ... ) {} // discard invalid COMs
  835. }
  836. const bool trustEstablished = ((network)&&(network->gate(tPtr,peer)));
  837. if (!trustEstablished)
  838. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  839. if ( ( trustEstablished || RR->mc->cacheAuthorized(peer->address(),nwid,RR->node->now()) ) && (gatherLimit > 0) ) {
  840. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_OK);
  841. outp.append((unsigned char)Packet::VERB_MULTICAST_GATHER);
  842. outp.append(packetId());
  843. outp.append(nwid);
  844. mg.mac().appendTo(outp);
  845. outp.append((uint32_t)mg.adi());
  846. const unsigned int gatheredLocally = RR->mc->gather(peer->address(),nwid,mg,outp,gatherLimit);
  847. if (gatheredLocally > 0) {
  848. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  849. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  850. }
  851. }
  852. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_GATHER,0,Packet::VERB_NOP,trustEstablished,nwid);
  853. return true;
  854. }
  855. bool IncomingPacket::_doMULTICAST_FRAME(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  856. {
  857. const uint64_t nwid = at<uint64_t>(ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID);
  858. const unsigned int flags = (*this)[ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS];
  859. const SharedPtr<Network> network(RR->node->network(nwid));
  860. if (network) {
  861. // Offset -- size of optional fields added to position of later fields
  862. unsigned int offset = 0;
  863. if ((flags & 0x01) != 0) {
  864. // This is deprecated but may still be sent by old peers
  865. CertificateOfMembership com;
  866. offset += com.deserialize(*this,ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM);
  867. if (com)
  868. network->addCredential(tPtr,com);
  869. }
  870. if (!network->gate(tPtr,peer)) {
  871. RR->t->incomingNetworkAccessDenied(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,true);
  872. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  873. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false,nwid);
  874. return true;
  875. }
  876. unsigned int gatherLimit = 0;
  877. if ((flags & 0x02) != 0) {
  878. gatherLimit = at<uint32_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT);
  879. offset += 4;
  880. }
  881. MAC from;
  882. if ((flags & 0x04) != 0) {
  883. from.setTo(field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC,6),6);
  884. offset += 6;
  885. } else {
  886. from.fromAddress(peer->address(),nwid);
  887. }
  888. 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));
  889. const unsigned int etherType = at<uint16_t>(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE);
  890. const unsigned int frameLen = size() - (offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME);
  891. if (network->config().multicastLimit == 0) {
  892. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"multicast disabled");
  893. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false,nwid);
  894. return true;
  895. }
  896. if ((frameLen > 0)&&(frameLen <= ZT_MAX_MTU)) {
  897. if (!to.mac().isMulticast()) {
  898. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"destination not multicast");
  899. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  900. return true;
  901. }
  902. if ((!from)||(from.isMulticast())||(from == network->mac())) {
  903. RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_MULTICAST_FRAME,"invalid source MAC");
  904. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  905. return true;
  906. }
  907. if (from != MAC(peer->address(),nwid)) {
  908. if (network->config().permitsBridging(peer->address())) {
  909. network->learnBridgeRoute(from,peer->address());
  910. } else {
  911. RR->t->incomingNetworkFrameDropped(tPtr,network,_path,packetId(),size(),peer->address(),Packet::VERB_MULTICAST_FRAME,from,to.mac(),"bridging not allowed (remote)");
  912. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid); // trustEstablished because COM is okay
  913. return true;
  914. }
  915. }
  916. const uint8_t *const frameData = (const uint8_t *)field(offset + ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME,frameLen);
  917. if (network->filterIncomingPacket(tPtr,peer,RR->identity.address(),from,to.mac(),frameData,frameLen,etherType,0) > 0)
  918. RR->node->putFrame(tPtr,nwid,network->userPtr(),from,to.mac(),etherType,0,(const void *)frameData,frameLen);
  919. }
  920. if (gatherLimit) {
  921. Packet outp(source(),RR->identity.address(),Packet::VERB_OK);
  922. outp.append((unsigned char)Packet::VERB_MULTICAST_FRAME);
  923. outp.append(packetId());
  924. outp.append(nwid);
  925. to.mac().appendTo(outp);
  926. outp.append((uint32_t)to.adi());
  927. outp.append((unsigned char)0x02); // flag 0x02 = contains gather results
  928. if (RR->mc->gather(peer->address(),nwid,to,outp,gatherLimit)) {
  929. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  930. _path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
  931. }
  932. }
  933. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,true,nwid);
  934. } else {
  935. _sendErrorNeedCredentials(RR,tPtr,peer,nwid);
  936. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_MULTICAST_FRAME,0,Packet::VERB_NOP,false,nwid);
  937. }
  938. return true;
  939. }
  940. bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  941. {
  942. const uint64_t now = RR->node->now();
  943. // First, subject this to a rate limit
  944. if (!peer->rateGatePushDirectPaths(now)) {
  945. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false,0);
  946. return true;
  947. }
  948. // Second, limit addresses by scope and type
  949. uint8_t countPerScope[ZT_INETADDRESS_MAX_SCOPE+1][2]; // [][0] is v4, [][1] is v6
  950. memset(countPerScope,0,sizeof(countPerScope));
  951. unsigned int count = at<uint16_t>(ZT_PACKET_IDX_PAYLOAD);
  952. unsigned int ptr = ZT_PACKET_IDX_PAYLOAD + 2;
  953. while (count--) { // if ptr overflows Buffer will throw
  954. // TODO: some flags are not yet implemented
  955. unsigned int flags = (*this)[ptr++];
  956. unsigned int extLen = at<uint16_t>(ptr); ptr += 2;
  957. ptr += extLen; // unused right now
  958. unsigned int addrType = (*this)[ptr++];
  959. unsigned int addrLen = (*this)[ptr++];
  960. switch(addrType) {
  961. case 4: {
  962. const InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
  963. if (
  964. ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  965. (!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  966. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  967. {
  968. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  969. peer->redirect(tPtr,_path->localSocket(),a,now);
  970. } else if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  971. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false,0);
  972. }
  973. }
  974. } break;
  975. case 6: {
  976. const InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
  977. if (
  978. ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_FORGET_PATH) == 0) && // not being told to forget
  979. (!( ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) == 0) && (peer->hasActivePathTo(now,a)) )) && // not already known
  980. (RR->node->shouldUsePathForZeroTierTraffic(tPtr,peer->address(),_path->localSocket(),a)) ) // should use path
  981. {
  982. if ((flags & ZT_PUSH_DIRECT_PATHS_FLAG_CLUSTER_REDIRECT) != 0) {
  983. peer->redirect(tPtr,_path->localSocket(),a,now);
  984. } else if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
  985. peer->attemptToContactAt(tPtr,InetAddress(),a,now,false,0);
  986. }
  987. }
  988. } break;
  989. }
  990. ptr += addrLen;
  991. }
  992. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_PUSH_DIRECT_PATHS,0,Packet::VERB_NOP,false,0);
  993. return true;
  994. }
  995. bool IncomingPacket::_doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  996. {
  997. if (likely(size() >= (ZT_PACKET_IDX_PAYLOAD + 8))) {
  998. ZT_UserMessage um;
  999. um.origin = peer->address().toInt();
  1000. um.typeId = at<uint64_t>(ZT_PACKET_IDX_PAYLOAD);
  1001. um.data = reinterpret_cast<const void *>(reinterpret_cast<const uint8_t *>(data()) + ZT_PACKET_IDX_PAYLOAD + 8);
  1002. um.length = size() - (ZT_PACKET_IDX_PAYLOAD + 8);
  1003. RR->node->postEvent(tPtr,ZT_EVENT_USER_MESSAGE,reinterpret_cast<const void *>(&um));
  1004. }
  1005. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_USER_MESSAGE,0,Packet::VERB_NOP,false,0);
  1006. return true;
  1007. }
  1008. bool IncomingPacket::_doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
  1009. {
  1010. ZT_RemoteTrace rt;
  1011. const char *ptr = reinterpret_cast<const char *>(data()) + ZT_PACKET_IDX_PAYLOAD;
  1012. const char *const eof = reinterpret_cast<const char *>(data()) + size();
  1013. rt.origin = peer->address().toInt();
  1014. rt.data = const_cast<char *>(ptr); // start of first string
  1015. while (ptr < eof) {
  1016. if (!*ptr) { // end of string
  1017. rt.len = (unsigned int)(ptr - rt.data);
  1018. if ((rt.len > 0)&&(rt.len <= ZT_MAX_REMOTE_TRACE_SIZE)) {
  1019. RR->node->postEvent(tPtr,ZT_EVENT_REMOTE_TRACE,&rt);
  1020. }
  1021. rt.data = const_cast<char *>(++ptr); // start of next string, if any
  1022. } else {
  1023. ++ptr;
  1024. }
  1025. }
  1026. peer->received(tPtr,_path,hops(),packetId(),Packet::VERB_REMOTE_TRACE,0,Packet::VERB_NOP,false,0);
  1027. return true;
  1028. }
  1029. void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid)
  1030. {
  1031. const uint64_t now = RR->node->now();
  1032. if (peer->rateGateOutgoingComRequest(now)) {
  1033. Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
  1034. outp.append((uint8_t)verb());
  1035. outp.append(packetId());
  1036. outp.append((uint8_t)Packet::ERROR_NEED_MEMBERSHIP_CERTIFICATE);
  1037. outp.append(nwid);
  1038. outp.armor(peer->key(),true,_path->nextOutgoingCounter());
  1039. _path->send(RR,tPtr,outp.data(),outp.size(),now);
  1040. }
  1041. }
  1042. } // namespace ZeroTier