IncomingPacket.cpp 42 KB

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