Network.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #include <stdio.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <math.h>
  22. #include "Constants.hpp"
  23. #include "../version.h"
  24. #include "Network.hpp"
  25. #include "RuntimeEnvironment.hpp"
  26. #include "MAC.hpp"
  27. #include "Address.hpp"
  28. #include "InetAddress.hpp"
  29. #include "Switch.hpp"
  30. #include "Buffer.hpp"
  31. #include "Packet.hpp"
  32. #include "NetworkController.hpp"
  33. #include "Node.hpp"
  34. #include "Peer.hpp"
  35. namespace ZeroTier {
  36. // Returns true if packet appears valid; pos and proto will be set
  37. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  38. {
  39. if (frameLen < 40)
  40. return false;
  41. pos = 40;
  42. proto = frameData[6];
  43. while (pos <= frameLen) {
  44. switch(proto) {
  45. case 0: // hop-by-hop options
  46. case 43: // routing
  47. case 60: // destination options
  48. case 135: // mobility options
  49. if ((pos + 8) > frameLen)
  50. return false; // invalid!
  51. proto = frameData[pos];
  52. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  53. break;
  54. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  55. //case 50:
  56. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  57. default:
  58. return true;
  59. }
  60. }
  61. return false; // overflow == invalid
  62. }
  63. // 0 == no match, -1 == match/drop, 1 == match/accept
  64. static int _doZtFilter(
  65. const RuntimeEnvironment *RR,
  66. const uint64_t nwid,
  67. const bool inbound,
  68. const Address &ztSource,
  69. const Address &ztDest,
  70. const MAC &macSource,
  71. const MAC &macDest,
  72. const uint8_t *frameData,
  73. const unsigned int frameLen,
  74. const unsigned int etherType,
  75. const unsigned int vlanId,
  76. const ZT_VirtualNetworkRule *rules,
  77. const unsigned int ruleCount,
  78. const Tag *localTags,
  79. const unsigned int localTagCount,
  80. const uint32_t *remoteTagIds,
  81. const uint32_t *remoteTagValues,
  82. const unsigned int remoteTagCount,
  83. const Tag **relevantLocalTags, // pointer array must be at least [localTagCount] in size
  84. unsigned int &relevantLocalTagCount)
  85. {
  86. // For each set of rules we start by assuming that they match (since no constraints
  87. // yields a 'match all' rule).
  88. uint8_t thisSetMatches = 1;
  89. for(unsigned int rn=0;rn<ruleCount;++rn) {
  90. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x7f);
  91. uint8_t thisRuleMatches = 0;
  92. switch(rt) {
  93. // Actions -------------------------------------------------------------
  94. // An action is performed if thisSetMatches is true, and if not
  95. // (or if the action is non-terminating) we start a new set of rules.
  96. case ZT_NETWORK_RULE_ACTION_DROP:
  97. if (thisSetMatches) {
  98. return -1; // match, drop packet
  99. } else {
  100. thisSetMatches = 1; // no match, evaluate next set
  101. }
  102. break;
  103. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  104. if (thisSetMatches) {
  105. return 1; // match, accept packet
  106. } else {
  107. thisSetMatches = 1; // no match, evaluate next set
  108. }
  109. break;
  110. case ZT_NETWORK_RULE_ACTION_TEE:
  111. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  112. Packet outp(Address(rules[rn].v.zt),RR->identity.address(),Packet::VERB_EXT_FRAME);
  113. outp.append(nwid);
  114. outp.append((uint8_t)((rt == ZT_NETWORK_RULE_ACTION_REDIRECT) ? 0x04 : 0x02));
  115. macDest.appendTo(outp);
  116. macSource.appendTo(outp);
  117. outp.append((uint16_t)etherType);
  118. outp.append(frameData,frameLen);
  119. outp.compress();
  120. RR->sw->send(outp,true);
  121. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  122. return -1; // match, drop packet (we redirected it)
  123. } else {
  124. thisSetMatches = 1; // TEE does not terminate evaluation
  125. }
  126. } break;
  127. // Rules ---------------------------------------------------------------
  128. // thisSetMatches is the binary AND of the result of all rules in a set
  129. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  130. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  131. break;
  132. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  133. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  134. break;
  135. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  136. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  137. break;
  138. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  139. // NOT SUPPORTED YET
  140. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  141. break;
  142. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  143. // NOT SUPPORTED YET
  144. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  145. break;
  146. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  147. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  148. break;
  149. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  150. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macSource);
  151. break;
  152. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  153. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macDest);
  154. break;
  155. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  156. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  157. thisRuleMatches = (uint8_t)(InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).containsAddress(InetAddress((const void *)(frameData + 12),4,0)));
  158. } else {
  159. thisRuleMatches = 0;
  160. }
  161. break;
  162. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  163. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  164. thisRuleMatches = (uint8_t)(InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).containsAddress(InetAddress((const void *)(frameData + 16),4,0)));
  165. } else {
  166. thisRuleMatches = 0;
  167. }
  168. break;
  169. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  170. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  171. thisRuleMatches = (uint8_t)(InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).containsAddress(InetAddress((const void *)(frameData + 8),16,0)));
  172. } else {
  173. thisRuleMatches = 0;
  174. }
  175. break;
  176. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  177. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  178. thisRuleMatches = (uint8_t)(InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).containsAddress(InetAddress((const void *)(frameData + 24),16,0)));
  179. } else {
  180. thisRuleMatches = 0;
  181. }
  182. break;
  183. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  184. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  185. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((frameData[1] & 0xfc) >> 2));
  186. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  187. const uint8_t trafficClass = ((frameData[0] << 4) & 0xf0) | ((frameData[1] >> 4) & 0x0f);
  188. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((trafficClass & 0xfc) >> 2));
  189. } else {
  190. thisRuleMatches = 0;
  191. }
  192. break;
  193. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  194. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  195. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
  196. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  197. unsigned int pos = 0,proto = 0;
  198. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  199. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
  200. } else {
  201. thisRuleMatches = 0;
  202. }
  203. } else {
  204. thisRuleMatches = 0;
  205. }
  206. break;
  207. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  208. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  209. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  210. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  211. int p = -1;
  212. switch(frameData[9]) { // IP protocol number
  213. // All these start with 16-bit source and destination port in that order
  214. case 0x06: // TCP
  215. case 0x11: // UDP
  216. case 0x84: // SCTP
  217. case 0x88: // UDPLite
  218. if (frameLen > (headerLen + 4)) {
  219. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  220. p = (int)frameData[pos++] << 8;
  221. p |= (int)frameData[pos];
  222. }
  223. break;
  224. }
  225. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  226. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  227. unsigned int pos = 0,proto = 0;
  228. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  229. int p = -1;
  230. switch(proto) { // IP protocol number
  231. // All these start with 16-bit source and destination port in that order
  232. case 0x06: // TCP
  233. case 0x11: // UDP
  234. case 0x84: // SCTP
  235. case 0x88: // UDPLite
  236. if (frameLen > (pos + 4)) {
  237. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) pos += 2;
  238. p = (int)frameData[pos++] << 8;
  239. p |= (int)frameData[pos];
  240. }
  241. break;
  242. }
  243. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  244. } else {
  245. thisRuleMatches = 0;
  246. }
  247. } else {
  248. thisRuleMatches = 0;
  249. }
  250. break;
  251. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  252. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  253. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  254. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  255. cf |= (uint64_t)frameData[headerLen + 13];
  256. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  257. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  258. unsigned int pos = 0,proto = 0;
  259. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  260. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  261. cf |= (uint64_t)frameData[pos + 13];
  262. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  263. }
  264. }
  265. }
  266. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics[0]) == rules[rn].v.characteristics[1]);
  267. } break;
  268. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  269. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  270. break;
  271. case ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS:
  272. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  273. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  274. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: {
  275. const Tag *lt = (const Tag *)0;
  276. for(unsigned int i=0;i<localTagCount;++i) {
  277. if (rules[rn].v.tag.id == localTags[i].id()) {
  278. lt = &(localTags[i]);
  279. break;
  280. }
  281. }
  282. if (!lt) {
  283. thisRuleMatches = 0;
  284. } else {
  285. const uint32_t *rtv = (const uint32_t *)0;
  286. for(unsigned int i=0;i<remoteTagCount;++i) {
  287. if (rules[rn].v.tag.id == remoteTagIds[i]) {
  288. rtv = &(remoteTagValues[i]);
  289. break;
  290. }
  291. }
  292. if (!rtv) {
  293. thisRuleMatches = 0;
  294. } else {
  295. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS) {
  296. const uint32_t sameness = (lt->value() > *rtv) ? (lt->value() - *rtv) : (*rtv - lt->value());
  297. thisRuleMatches = (uint8_t)(sameness <= rules[rn].v.tag.value);
  298. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  299. thisRuleMatches = (uint8_t)((lt->value() & *rtv) <= rules[rn].v.tag.value);
  300. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  301. thisRuleMatches = (uint8_t)((lt->value() | *rtv) <= rules[rn].v.tag.value);
  302. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  303. thisRuleMatches = (uint8_t)((lt->value() ^ *rtv) <= rules[rn].v.tag.value);
  304. } else { // sanity check, can't really happen
  305. thisRuleMatches = 0;
  306. }
  307. if (thisRuleMatches) {
  308. relevantLocalTags[relevantLocalTagCount++] = lt;
  309. }
  310. }
  311. }
  312. } break;
  313. }
  314. // thisSetMatches remains true if the current rule matched (or did NOT match if NOT bit is set)
  315. thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t & 0x80) >> 7));
  316. //TRACE("[%u] %u result==%u set==%u",rn,(unsigned int)rt,(unsigned int)thisRuleMatches,(unsigned int)thisSetMatches);
  317. }
  318. return 0;
  319. }
  320. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  321. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  322. RR(renv),
  323. _uPtr(uptr),
  324. _id(nwid),
  325. _mac(renv->identity.address(),nwid),
  326. _portInitialized(false),
  327. _inboundConfigPacketId(0),
  328. _lastConfigUpdate(0),
  329. _destroyed(false),
  330. _netconfFailure(NETCONF_FAILURE_NONE),
  331. _portError(0)
  332. {
  333. char confn[128];
  334. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  335. if (_id == ZT_TEST_NETWORK_ID) {
  336. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  337. // Save a one-byte CR to persist membership in the test network
  338. RR->node->dataStorePut(confn,"\n",1,false);
  339. } else {
  340. bool gotConf = false;
  341. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  342. NetworkConfig *nconf = new NetworkConfig();
  343. try {
  344. std::string conf(RR->node->dataStoreGet(confn));
  345. if (conf.length()) {
  346. dconf->load(conf.c_str());
  347. if (nconf->fromDictionary(Identity(),*dconf)) {
  348. this->setConfiguration(*nconf,false);
  349. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  350. gotConf = true;
  351. }
  352. }
  353. } catch ( ... ) {} // ignore invalids, we'll re-request
  354. delete nconf;
  355. delete dconf;
  356. if (!gotConf) {
  357. // Save a one-byte CR to persist membership while we request a real netconf
  358. RR->node->dataStorePut(confn,"\n",1,false);
  359. }
  360. }
  361. if (!_portInitialized) {
  362. ZT_VirtualNetworkConfig ctmp;
  363. _externalConfig(&ctmp);
  364. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  365. _portInitialized = true;
  366. }
  367. }
  368. Network::~Network()
  369. {
  370. ZT_VirtualNetworkConfig ctmp;
  371. _externalConfig(&ctmp);
  372. char n[128];
  373. if (_destroyed) {
  374. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  375. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  376. RR->node->dataStoreDelete(n);
  377. } else {
  378. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  379. }
  380. }
  381. bool Network::filterOutgoingPacket(
  382. const Address &ztSource,
  383. const Address &ztDest,
  384. const MAC &macSource,
  385. const MAC &macDest,
  386. const uint8_t *frameData,
  387. const unsigned int frameLen,
  388. const unsigned int etherType,
  389. const unsigned int vlanId)
  390. {
  391. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  392. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  393. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  394. unsigned int relevantLocalTagCount = 0;
  395. Mutex::Lock _l(_lock);
  396. Membership &m = _memberships[ztDest];
  397. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  398. switch(_doZtFilter(RR,_id,false,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  399. case -1:
  400. return false;
  401. case 1:
  402. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,(const Capability *)0,relevantLocalTags,relevantLocalTagCount);
  403. return true;
  404. }
  405. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  406. relevantLocalTagCount = 0;
  407. switch (_doZtFilter(RR,_id,false,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.capabilities[c].rules(),_config.capabilities[c].ruleCount(),_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  408. case -1:
  409. return false;
  410. case 1:
  411. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,&(_config.capabilities[c]),relevantLocalTags,relevantLocalTagCount);
  412. return true;
  413. }
  414. }
  415. return false;
  416. }
  417. bool Network::filterIncomingPacket(
  418. const SharedPtr<Peer> &sourcePeer,
  419. const Address &ztDest,
  420. const MAC &macSource,
  421. const MAC &macDest,
  422. const uint8_t *frameData,
  423. const unsigned int frameLen,
  424. const unsigned int etherType,
  425. const unsigned int vlanId)
  426. {
  427. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  428. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  429. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  430. unsigned int relevantLocalTagCount = 0;
  431. Mutex::Lock _l(_lock);
  432. Membership &m = _memberships[ztDest];
  433. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  434. switch (_doZtFilter(RR,_id,true,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  435. case -1:
  436. return false;
  437. case 1:
  438. return true;
  439. }
  440. Membership::CapabilityIterator mci(m);
  441. const Capability *c;
  442. while ((c = mci.next())) {
  443. relevantLocalTagCount = 0;
  444. switch(_doZtFilter(RR,_id,false,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  445. case -1:
  446. return false;
  447. case 1:
  448. return true;
  449. }
  450. }
  451. return false;
  452. }
  453. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  454. {
  455. Mutex::Lock _l(_lock);
  456. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  457. return true;
  458. else if (includeBridgedGroups)
  459. return _multicastGroupsBehindMe.contains(mg);
  460. else return false;
  461. }
  462. void Network::multicastSubscribe(const MulticastGroup &mg)
  463. {
  464. {
  465. Mutex::Lock _l(_lock);
  466. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  467. return;
  468. _myMulticastGroups.push_back(mg);
  469. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  470. }
  471. _announceMulticastGroups();
  472. }
  473. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  474. {
  475. Mutex::Lock _l(_lock);
  476. std::vector<MulticastGroup> nmg;
  477. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  478. if (*i != mg)
  479. nmg.push_back(*i);
  480. }
  481. if (nmg.size() != _myMulticastGroups.size())
  482. _myMulticastGroups.swap(nmg);
  483. }
  484. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  485. {
  486. Mutex::Lock _l(_lock);
  487. if (
  488. (_isAllowed(peer)) ||
  489. (peer->address() == this->controller()) ||
  490. (RR->topology->isUpstream(peer->identity()))
  491. ) {
  492. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  493. return true;
  494. }
  495. return false;
  496. }
  497. bool Network::applyConfiguration(const NetworkConfig &conf)
  498. {
  499. if (_destroyed) // sanity check
  500. return false;
  501. try {
  502. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  503. ZT_VirtualNetworkConfig ctmp;
  504. bool portInitialized;
  505. {
  506. Mutex::Lock _l(_lock);
  507. _config = conf;
  508. _lastConfigUpdate = RR->node->now();
  509. _netconfFailure = NETCONF_FAILURE_NONE;
  510. _externalConfig(&ctmp);
  511. portInitialized = _portInitialized;
  512. _portInitialized = true;
  513. }
  514. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  515. return true;
  516. } else {
  517. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  518. }
  519. } catch (std::exception &exc) {
  520. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  521. } catch ( ... ) {
  522. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  523. }
  524. return false;
  525. }
  526. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  527. {
  528. try {
  529. {
  530. Mutex::Lock _l(_lock);
  531. if (_config == nconf)
  532. return 1; // OK config, but duplicate of what we already have
  533. }
  534. if (applyConfiguration(nconf)) {
  535. if (saveToDisk) {
  536. char n[64];
  537. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  538. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  539. if (nconf.toDictionary(d,false))
  540. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  541. }
  542. return 2; // OK and configuration has changed
  543. }
  544. } catch ( ... ) {
  545. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  546. }
  547. return 0;
  548. }
  549. void Network::handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize)
  550. {
  551. std::string newConfig;
  552. if ((_inboundConfigPacketId == inRePacketId)&&(totalSize < ZT_NETWORKCONFIG_DICT_CAPACITY)&&((chunkIndex + chunkSize) < totalSize)) {
  553. Mutex::Lock _l(_lock);
  554. TRACE("got %u bytes at position %u of network config request %.16llx, total expected length %u",chunkSize,chunkIndex,inRePacketId,totalSize);
  555. _inboundConfigChunks[chunkIndex].append((const char *)data,chunkSize);
  556. unsigned int totalWeHave = 0;
  557. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  558. totalWeHave += (unsigned int)c->second.length();
  559. if (totalWeHave == totalSize) {
  560. TRACE("have all chunks for network config request %.16llx, assembling...",inRePacketId);
  561. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  562. newConfig.append(c->second);
  563. _inboundConfigPacketId = 0;
  564. _inboundConfigChunks.clear();
  565. } else if (totalWeHave > totalSize) {
  566. _inboundConfigPacketId = 0;
  567. _inboundConfigChunks.clear();
  568. }
  569. }
  570. if (newConfig.length() > 0) {
  571. if (newConfig.length() < ZT_NETWORKCONFIG_DICT_CAPACITY) {
  572. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>(newConfig.c_str());
  573. try {
  574. Identity controllerId(RR->topology->getIdentity(this->controller()));
  575. if (controllerId) {
  576. NetworkConfig nc;
  577. if (nc.fromDictionary(controllerId,*dict))
  578. this->setConfiguration(nc,true);
  579. }
  580. delete dict;
  581. } catch ( ... ) {
  582. delete dict;
  583. throw;
  584. }
  585. }
  586. }
  587. }
  588. void Network::requestConfiguration()
  589. {
  590. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  591. return;
  592. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  593. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  594. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  595. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  596. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  597. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  598. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  599. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  600. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  601. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  602. if (controller() == RR->identity.address()) {
  603. if (RR->localNetworkController) {
  604. NetworkConfig nconf;
  605. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  606. case NetworkController::NETCONF_QUERY_OK:
  607. this->setConfiguration(nconf,true);
  608. return;
  609. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  610. this->setNotFound();
  611. return;
  612. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  613. this->setAccessDenied();
  614. return;
  615. default:
  616. return;
  617. }
  618. } else {
  619. this->setNotFound();
  620. return;
  621. }
  622. }
  623. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  624. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  625. outp.append((uint64_t)_id);
  626. const unsigned int rmdSize = rmd.sizeBytes();
  627. outp.append((uint16_t)rmdSize);
  628. outp.append((const void *)rmd.data(),rmdSize);
  629. outp.append((_config) ? (uint64_t)_config.revision : (uint64_t)0);
  630. outp.compress();
  631. RR->sw->send(outp,true);
  632. // Expect replies with this in-re packet ID
  633. _inboundConfigPacketId = outp.packetId();
  634. _inboundConfigChunks.clear();
  635. }
  636. void Network::clean()
  637. {
  638. const uint64_t now = RR->node->now();
  639. Mutex::Lock _l(_lock);
  640. if (_destroyed)
  641. return;
  642. {
  643. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  644. MulticastGroup *mg = (MulticastGroup *)0;
  645. uint64_t *ts = (uint64_t *)0;
  646. while (i.next(mg,ts)) {
  647. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  648. _multicastGroupsBehindMe.erase(*mg);
  649. }
  650. }
  651. {
  652. Address *a = (Address *)0;
  653. Membership *m = (Membership *)0;
  654. Hashtable<Address,Membership>::Iterator i(_memberships);
  655. while (i.next(a,m)) {
  656. if ((now - m->clean(now)) > ZT_MEMBERSHIP_EXPIRATION_TIME)
  657. _memberships.erase(*a);
  658. }
  659. }
  660. }
  661. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  662. {
  663. Mutex::Lock _l(_lock);
  664. _remoteBridgeRoutes[mac] = addr;
  665. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  666. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  667. Hashtable< Address,unsigned long > counts;
  668. Address maxAddr;
  669. unsigned long maxCount = 0;
  670. MAC *m = (MAC *)0;
  671. Address *a = (Address *)0;
  672. // Find the address responsible for the most entries
  673. {
  674. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  675. while (i.next(m,a)) {
  676. const unsigned long c = ++counts[*a];
  677. if (c > maxCount) {
  678. maxCount = c;
  679. maxAddr = *a;
  680. }
  681. }
  682. }
  683. // Kill this address from our table, since it's most likely spamming us
  684. {
  685. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  686. while (i.next(m,a)) {
  687. if (*a == maxAddr)
  688. _remoteBridgeRoutes.erase(*m);
  689. }
  690. }
  691. }
  692. }
  693. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  694. {
  695. Mutex::Lock _l(_lock);
  696. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  697. _multicastGroupsBehindMe.set(mg,now);
  698. if (tmp != _multicastGroupsBehindMe.size())
  699. _announceMulticastGroups();
  700. }
  701. void Network::destroy()
  702. {
  703. Mutex::Lock _l(_lock);
  704. _destroyed = true;
  705. }
  706. ZT_VirtualNetworkStatus Network::_status() const
  707. {
  708. // assumes _lock is locked
  709. if (_portError)
  710. return ZT_NETWORK_STATUS_PORT_ERROR;
  711. switch(_netconfFailure) {
  712. case NETCONF_FAILURE_ACCESS_DENIED:
  713. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  714. case NETCONF_FAILURE_NOT_FOUND:
  715. return ZT_NETWORK_STATUS_NOT_FOUND;
  716. case NETCONF_FAILURE_NONE:
  717. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  718. default:
  719. return ZT_NETWORK_STATUS_PORT_ERROR;
  720. }
  721. }
  722. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  723. {
  724. // assumes _lock is locked
  725. ec->nwid = _id;
  726. ec->mac = _mac.toInt();
  727. if (_config)
  728. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  729. else ec->name[0] = (char)0;
  730. ec->status = _status();
  731. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  732. ec->mtu = ZT_IF_MTU;
  733. ec->dhcp = 0;
  734. std::vector<Address> ab(_config.activeBridges());
  735. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  736. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  737. ec->portError = _portError;
  738. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  739. ec->assignedAddressCount = 0;
  740. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  741. if (i < _config.staticIpCount) {
  742. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  743. ++ec->assignedAddressCount;
  744. } else {
  745. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  746. }
  747. }
  748. ec->routeCount = 0;
  749. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  750. if (i < _config.routeCount) {
  751. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  752. ++ec->routeCount;
  753. } else {
  754. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  755. }
  756. }
  757. }
  758. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  759. {
  760. // Assumes _lock is locked
  761. try {
  762. if (_config) {
  763. if (_config.isPublic()) {
  764. return true;
  765. } else {
  766. const Membership *m = _memberships.get(peer->address());
  767. if (m)
  768. return _config.com.agreesWith(m->com());
  769. }
  770. }
  771. } catch ( ... ) {
  772. TRACE("isAllowed() check failed for peer %s: unexpected exception: unexpected exception",peer->address().toString().c_str());
  773. }
  774. return false;
  775. }
  776. class _MulticastAnnounceAll
  777. {
  778. public:
  779. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  780. _now(renv->node->now()),
  781. _controller(nw->controller()),
  782. _network(nw),
  783. _anchors(nw->config().anchors()),
  784. _upstreamAddresses(renv->topology->upstreamAddresses())
  785. {}
  786. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  787. {
  788. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  789. (p->address() == _controller) ||
  790. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  791. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  792. peers.push_back(p);
  793. }
  794. }
  795. std::vector< SharedPtr<Peer> > peers;
  796. private:
  797. const uint64_t _now;
  798. const Address _controller;
  799. Network *const _network;
  800. const std::vector<Address> _anchors;
  801. const std::vector<Address> _upstreamAddresses;
  802. };
  803. void Network::_announceMulticastGroups()
  804. {
  805. // Assumes _lock is locked
  806. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  807. _MulticastAnnounceAll gpfunc(RR,this);
  808. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  809. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  810. _announceMulticastGroupsTo(*i,allMulticastGroups);
  811. }
  812. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  813. {
  814. // Assumes _lock is locked
  815. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  816. {
  817. Membership *m = _memberships.get(peer->address());
  818. if (m)
  819. m->sendCredentialsIfNeeded(RR,RR->node->now(),peer->address(),_config.com,(const Capability *)0,(const Tag **)0,0);
  820. }
  821. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  822. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  823. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  824. outp.compress();
  825. RR->sw->send(outp,true);
  826. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  827. }
  828. // network ID, MAC, ADI
  829. outp.append((uint64_t)_id);
  830. mg->mac().appendTo(outp);
  831. outp.append((uint32_t)mg->adi());
  832. }
  833. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  834. outp.compress();
  835. RR->sw->send(outp,true);
  836. }
  837. }
  838. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  839. {
  840. // Assumes _lock is locked
  841. std::vector<MulticastGroup> mgs;
  842. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  843. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  844. _multicastGroupsBehindMe.appendKeys(mgs);
  845. if ((_config)&&(_config.enableBroadcast()))
  846. mgs.push_back(Network::BROADCAST);
  847. std::sort(mgs.begin(),mgs.end());
  848. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  849. return mgs;
  850. }
  851. } // namespace ZeroTier