Network.cpp 29 KB

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