Network.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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,nwid);
  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. _lastConfigUpdate(0),
  328. _destroyed(false),
  329. _netconfFailure(NETCONF_FAILURE_NONE),
  330. _portError(0)
  331. {
  332. char confn[128];
  333. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  334. if (_id == ZT_TEST_NETWORK_ID) {
  335. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  336. // Save a one-byte CR to persist membership in the test network
  337. RR->node->dataStorePut(confn,"\n",1,false);
  338. } else {
  339. bool gotConf = false;
  340. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  341. NetworkConfig *nconf = new NetworkConfig();
  342. try {
  343. std::string conf(RR->node->dataStoreGet(confn));
  344. if (conf.length()) {
  345. dconf->load(conf.c_str());
  346. if (nconf->fromDictionary(*dconf)) {
  347. this->setConfiguration(*nconf,false);
  348. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  349. gotConf = true;
  350. }
  351. }
  352. } catch ( ... ) {} // ignore invalids, we'll re-request
  353. delete nconf;
  354. delete dconf;
  355. if (!gotConf) {
  356. // Save a one-byte CR to persist membership while we request a real netconf
  357. RR->node->dataStorePut(confn,"\n",1,false);
  358. }
  359. }
  360. if (!_portInitialized) {
  361. ZT_VirtualNetworkConfig ctmp;
  362. _externalConfig(&ctmp);
  363. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  364. _portInitialized = true;
  365. }
  366. }
  367. Network::~Network()
  368. {
  369. ZT_VirtualNetworkConfig ctmp;
  370. _externalConfig(&ctmp);
  371. char n[128];
  372. if (_destroyed) {
  373. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  374. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  375. RR->node->dataStoreDelete(n);
  376. } else {
  377. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  378. }
  379. }
  380. bool Network::filterOutgoingPacket(
  381. const Address &ztSource,
  382. const Address &ztDest,
  383. const MAC &macSource,
  384. const MAC &macDest,
  385. const uint8_t *frameData,
  386. const unsigned int frameLen,
  387. const unsigned int etherType,
  388. const unsigned int vlanId)
  389. {
  390. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  391. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  392. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  393. unsigned int relevantLocalTagCount = 0;
  394. Mutex::Lock _l(_lock);
  395. Membership &m = _memberships[ztDest];
  396. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  397. 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)) {
  398. case -1:
  399. return false;
  400. case 1:
  401. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,(const Capability *)0,relevantLocalTags,relevantLocalTagCount);
  402. return true;
  403. }
  404. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  405. relevantLocalTagCount = 0;
  406. 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)) {
  407. case -1:
  408. return false;
  409. case 1:
  410. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,&(_config.capabilities[c]),relevantLocalTags,relevantLocalTagCount);
  411. return true;
  412. }
  413. }
  414. return false;
  415. }
  416. bool Network::filterIncomingPacket(
  417. const SharedPtr<Peer> &sourcePeer,
  418. const Address &ztDest,
  419. const MAC &macSource,
  420. const MAC &macDest,
  421. const uint8_t *frameData,
  422. const unsigned int frameLen,
  423. const unsigned int etherType,
  424. const unsigned int vlanId)
  425. {
  426. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  427. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  428. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  429. unsigned int relevantLocalTagCount = 0;
  430. Mutex::Lock _l(_lock);
  431. Membership &m = _memberships[ztDest];
  432. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  433. 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)) {
  434. case -1:
  435. return false;
  436. case 1:
  437. return true;
  438. }
  439. Membership::CapabilityIterator mci(m);
  440. const Capability *c;
  441. while ((c = mci.next())) {
  442. relevantLocalTagCount = 0;
  443. 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)) {
  444. case -1:
  445. return false;
  446. case 1:
  447. return true;
  448. }
  449. }
  450. return false;
  451. }
  452. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  453. {
  454. Mutex::Lock _l(_lock);
  455. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  456. return true;
  457. else if (includeBridgedGroups)
  458. return _multicastGroupsBehindMe.contains(mg);
  459. else return false;
  460. }
  461. void Network::multicastSubscribe(const MulticastGroup &mg)
  462. {
  463. {
  464. Mutex::Lock _l(_lock);
  465. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  466. return;
  467. _myMulticastGroups.push_back(mg);
  468. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  469. }
  470. _announceMulticastGroups();
  471. }
  472. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  473. {
  474. Mutex::Lock _l(_lock);
  475. std::vector<MulticastGroup> nmg;
  476. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  477. if (*i != mg)
  478. nmg.push_back(*i);
  479. }
  480. if (nmg.size() != _myMulticastGroups.size())
  481. _myMulticastGroups.swap(nmg);
  482. }
  483. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  484. {
  485. Mutex::Lock _l(_lock);
  486. if (
  487. (_isAllowed(peer)) ||
  488. (peer->address() == this->controller()) ||
  489. (RR->topology->isUpstream(peer->identity()))
  490. ) {
  491. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  492. return true;
  493. }
  494. return false;
  495. }
  496. bool Network::applyConfiguration(const NetworkConfig &conf)
  497. {
  498. if (_destroyed) // sanity check
  499. return false;
  500. try {
  501. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  502. ZT_VirtualNetworkConfig ctmp;
  503. bool portInitialized;
  504. {
  505. Mutex::Lock _l(_lock);
  506. _config = conf;
  507. _lastConfigUpdate = RR->node->now();
  508. _netconfFailure = NETCONF_FAILURE_NONE;
  509. _externalConfig(&ctmp);
  510. portInitialized = _portInitialized;
  511. _portInitialized = true;
  512. }
  513. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  514. return true;
  515. } else {
  516. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  517. }
  518. } catch (std::exception &exc) {
  519. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  520. } catch ( ... ) {
  521. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  522. }
  523. return false;
  524. }
  525. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  526. {
  527. try {
  528. {
  529. Mutex::Lock _l(_lock);
  530. if (_config == nconf)
  531. return 1; // OK config, but duplicate of what we already have
  532. }
  533. if (applyConfiguration(nconf)) {
  534. if (saveToDisk) {
  535. char n[64];
  536. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  537. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  538. if (nconf.toDictionary(d,false))
  539. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  540. }
  541. return 2; // OK and configuration has changed
  542. }
  543. } catch ( ... ) {
  544. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  545. }
  546. return 0;
  547. }
  548. void Network::requestConfiguration()
  549. {
  550. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, uses locally generated static config
  551. return;
  552. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  553. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  554. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  555. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  556. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  557. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  558. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  559. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  560. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  561. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  562. if (controller() == RR->identity.address()) {
  563. if (RR->localNetworkController) {
  564. NetworkConfig nconf;
  565. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  566. case NetworkController::NETCONF_QUERY_OK:
  567. this->setConfiguration(nconf,true);
  568. return;
  569. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  570. this->setNotFound();
  571. return;
  572. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  573. this->setAccessDenied();
  574. return;
  575. default:
  576. return;
  577. }
  578. } else {
  579. this->setNotFound();
  580. return;
  581. }
  582. }
  583. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,controller().toString().c_str());
  584. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  585. outp.append((uint64_t)_id);
  586. const unsigned int rmdSize = rmd.sizeBytes();
  587. outp.append((uint16_t)rmdSize);
  588. outp.append((const void *)rmd.data(),rmdSize);
  589. outp.append((_config) ? (uint64_t)_config.revision : (uint64_t)0);
  590. outp.compress();
  591. RR->sw->send(outp,true,0);
  592. }
  593. void Network::clean()
  594. {
  595. const uint64_t now = RR->node->now();
  596. Mutex::Lock _l(_lock);
  597. if (_destroyed)
  598. return;
  599. {
  600. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  601. MulticastGroup *mg = (MulticastGroup *)0;
  602. uint64_t *ts = (uint64_t *)0;
  603. while (i.next(mg,ts)) {
  604. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  605. _multicastGroupsBehindMe.erase(*mg);
  606. }
  607. }
  608. {
  609. Address *a = (Address *)0;
  610. Membership *m = (Membership *)0;
  611. Hashtable<Address,Membership>::Iterator i(_memberships);
  612. while (i.next(a,m)) {
  613. if ((now - m->clean(now)) > ZT_MEMBERSHIP_EXPIRATION_TIME)
  614. _memberships.erase(*a);
  615. }
  616. }
  617. }
  618. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  619. {
  620. Mutex::Lock _l(_lock);
  621. _remoteBridgeRoutes[mac] = addr;
  622. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  623. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  624. Hashtable< Address,unsigned long > counts;
  625. Address maxAddr;
  626. unsigned long maxCount = 0;
  627. MAC *m = (MAC *)0;
  628. Address *a = (Address *)0;
  629. // Find the address responsible for the most entries
  630. {
  631. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  632. while (i.next(m,a)) {
  633. const unsigned long c = ++counts[*a];
  634. if (c > maxCount) {
  635. maxCount = c;
  636. maxAddr = *a;
  637. }
  638. }
  639. }
  640. // Kill this address from our table, since it's most likely spamming us
  641. {
  642. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  643. while (i.next(m,a)) {
  644. if (*a == maxAddr)
  645. _remoteBridgeRoutes.erase(*m);
  646. }
  647. }
  648. }
  649. }
  650. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  651. {
  652. Mutex::Lock _l(_lock);
  653. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  654. _multicastGroupsBehindMe.set(mg,now);
  655. if (tmp != _multicastGroupsBehindMe.size())
  656. _announceMulticastGroups();
  657. }
  658. void Network::destroy()
  659. {
  660. Mutex::Lock _l(_lock);
  661. _destroyed = true;
  662. }
  663. ZT_VirtualNetworkStatus Network::_status() const
  664. {
  665. // assumes _lock is locked
  666. if (_portError)
  667. return ZT_NETWORK_STATUS_PORT_ERROR;
  668. switch(_netconfFailure) {
  669. case NETCONF_FAILURE_ACCESS_DENIED:
  670. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  671. case NETCONF_FAILURE_NOT_FOUND:
  672. return ZT_NETWORK_STATUS_NOT_FOUND;
  673. case NETCONF_FAILURE_NONE:
  674. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  675. default:
  676. return ZT_NETWORK_STATUS_PORT_ERROR;
  677. }
  678. }
  679. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  680. {
  681. // assumes _lock is locked
  682. ec->nwid = _id;
  683. ec->mac = _mac.toInt();
  684. if (_config)
  685. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  686. else ec->name[0] = (char)0;
  687. ec->status = _status();
  688. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  689. ec->mtu = ZT_IF_MTU;
  690. ec->dhcp = 0;
  691. std::vector<Address> ab(_config.activeBridges());
  692. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  693. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  694. ec->portError = _portError;
  695. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  696. ec->assignedAddressCount = 0;
  697. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  698. if (i < _config.staticIpCount) {
  699. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  700. ++ec->assignedAddressCount;
  701. } else {
  702. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  703. }
  704. }
  705. ec->routeCount = 0;
  706. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  707. if (i < _config.routeCount) {
  708. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  709. ++ec->routeCount;
  710. } else {
  711. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  712. }
  713. }
  714. }
  715. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  716. {
  717. // Assumes _lock is locked
  718. try {
  719. if (_config) {
  720. if (_config.isPublic()) {
  721. return true;
  722. } else {
  723. const Membership *m = _memberships.get(peer->address());
  724. if (m)
  725. return _config.com.agreesWith(m->com());
  726. }
  727. }
  728. } catch ( ... ) {
  729. TRACE("isAllowed() check failed for peer %s: unexpected exception: unexpected exception",peer->address().toString().c_str());
  730. }
  731. return false;
  732. }
  733. class _MulticastAnnounceAll
  734. {
  735. public:
  736. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  737. _now(renv->node->now()),
  738. _controller(nw->controller()),
  739. _network(nw),
  740. _anchors(nw->config().anchors()),
  741. _upstreamAddresses(renv->topology->upstreamAddresses())
  742. {}
  743. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  744. {
  745. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  746. (p->address() == _controller) ||
  747. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  748. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  749. peers.push_back(p);
  750. }
  751. }
  752. std::vector< SharedPtr<Peer> > peers;
  753. private:
  754. const uint64_t _now;
  755. const Address _controller;
  756. Network *const _network;
  757. const std::vector<Address> _anchors;
  758. const std::vector<Address> _upstreamAddresses;
  759. };
  760. void Network::_announceMulticastGroups()
  761. {
  762. // Assumes _lock is locked
  763. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  764. _MulticastAnnounceAll gpfunc(RR,this);
  765. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  766. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  767. _announceMulticastGroupsTo(*i,allMulticastGroups);
  768. }
  769. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  770. {
  771. // Assumes _lock is locked
  772. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  773. {
  774. Membership *m = _memberships.get(peer->address());
  775. if (m)
  776. m->sendCredentialsIfNeeded(RR,RR->node->now(),peer->address(),_config.com,(const Capability *)0,(const Tag **)0,0);
  777. }
  778. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  779. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  780. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  781. outp.compress();
  782. RR->sw->send(outp,true,0);
  783. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  784. }
  785. // network ID, MAC, ADI
  786. outp.append((uint64_t)_id);
  787. mg->mac().appendTo(outp);
  788. outp.append((uint32_t)mg->adi());
  789. }
  790. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  791. outp.compress();
  792. RR->sw->send(outp,true,0);
  793. }
  794. }
  795. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  796. {
  797. // Assumes _lock is locked
  798. std::vector<MulticastGroup> mgs;
  799. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  800. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  801. _multicastGroupsBehindMe.appendKeys(mgs);
  802. if ((_config)&&(_config.enableBroadcast()))
  803. mgs.push_back(Network::BROADCAST);
  804. std::sort(mgs.begin(),mgs.end());
  805. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  806. return mgs;
  807. }
  808. } // namespace ZeroTier