IncomingPacket.cpp 47 KB

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