Network.cpp 29 KB

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