IncomingPacket.cpp 49 KB

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