IncomingPacket.cpp 48 KB

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