IncomingPacket.cpp 49 KB

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