Network.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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. // Uncomment to make the rules engine dump trace info to stdout
  36. //#define ZT_RULES_ENGINE_DEBUGGING 1
  37. namespace ZeroTier {
  38. namespace {
  39. #ifdef ZT_RULES_ENGINE_DEBUGGING
  40. #define FILTER_TRACE(f,...) { Utils::snprintf(dpbuf,sizeof(dpbuf),f,##__VA_ARGS__); dlog.push_back(std::string(dpbuf)); }
  41. static const char *_rtn(const ZT_VirtualNetworkRuleType rt)
  42. {
  43. switch(rt) {
  44. case ZT_NETWORK_RULE_ACTION_DROP: return "ACTION_DROP";
  45. case ZT_NETWORK_RULE_ACTION_ACCEPT: return "ACTION_ACCEPT";
  46. case ZT_NETWORK_RULE_ACTION_TEE: return "ACTION_TEE";
  47. case ZT_NETWORK_RULE_ACTION_WATCH: return "ACTION_WATCH";
  48. case ZT_NETWORK_RULE_ACTION_REDIRECT: return "ACTION_REDIRECT";
  49. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG: return "ACTION_DEBUG_LOG";
  50. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS: return "MATCH_SOURCE_ZEROTIER_ADDRESS";
  51. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS: return "MATCH_DEST_ZEROTIER_ADDRESS";
  52. case ZT_NETWORK_RULE_MATCH_VLAN_ID: return "MATCH_VLAN_ID";
  53. case ZT_NETWORK_RULE_MATCH_VLAN_PCP: return "MATCH_VLAN_PCP";
  54. case ZT_NETWORK_RULE_MATCH_VLAN_DEI: return "MATCH_VLAN_DEI";
  55. case ZT_NETWORK_RULE_MATCH_ETHERTYPE: return "MATCH_ETHERTYPE";
  56. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE: return "MATCH_MAC_SOURCE";
  57. case ZT_NETWORK_RULE_MATCH_MAC_DEST: return "MATCH_MAC_DEST";
  58. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE: return "MATCH_IPV4_SOURCE";
  59. case ZT_NETWORK_RULE_MATCH_IPV4_DEST: return "MATCH_IPV4_DEST";
  60. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE: return "MATCH_IPV6_SOURCE";
  61. case ZT_NETWORK_RULE_MATCH_IPV6_DEST: return "MATCH_IPV6_DEST";
  62. case ZT_NETWORK_RULE_MATCH_IP_TOS: return "MATCH_IP_TOS";
  63. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL: return "MATCH_IP_PROTOCOL";
  64. case ZT_NETWORK_RULE_MATCH_ICMP: return "MATCH_ICMP";
  65. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE: return "MATCH_IP_SOURCE_PORT_RANGE";
  66. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE: return "MATCH_IP_DEST_PORT_RANGE";
  67. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: return "MATCH_CHARACTERISTICS";
  68. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE: return "MATCH_FRAME_SIZE_RANGE";
  69. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE: return "MATCH_TAGS_DIFFERENCE";
  70. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND: return "MATCH_TAGS_BITWISE_AND";
  71. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR: return "MATCH_TAGS_BITWISE_OR";
  72. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: return "MATCH_TAGS_BITWISE_XOR";
  73. default: return "???";
  74. }
  75. }
  76. static const void _dumpFilterTrace(const char *ruleName,uint8_t thisSetMatches,bool inbound,const Address &ztSource,const Address &ztDest,const MAC &macSource,const MAC &macDest,const std::vector<std::string> &dlog,unsigned int frameLen,unsigned int etherType,const char *msg)
  77. {
  78. static volatile unsigned long cnt = 0;
  79. printf("%.6lu %c %s %s frameLen=%u etherType=%u" ZT_EOL_S,
  80. cnt++,
  81. ((thisSetMatches) ? 'Y' : '.'),
  82. ruleName,
  83. ((inbound) ? "INBOUND" : "OUTBOUND"),
  84. frameLen,
  85. etherType
  86. );
  87. for(std::vector<std::string>::const_iterator m(dlog.begin());m!=dlog.end();++m)
  88. printf(" | %s" ZT_EOL_S,m->c_str());
  89. printf(" + %c %s->%s %.2x:%.2x:%.2x:%.2x:%.2x:%.2x->%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" ZT_EOL_S,
  90. ((thisSetMatches) ? 'Y' : '.'),
  91. ztSource.toString().c_str(),
  92. ztDest.toString().c_str(),
  93. (unsigned int)macSource[0],
  94. (unsigned int)macSource[1],
  95. (unsigned int)macSource[2],
  96. (unsigned int)macSource[3],
  97. (unsigned int)macSource[4],
  98. (unsigned int)macSource[5],
  99. (unsigned int)macDest[0],
  100. (unsigned int)macDest[1],
  101. (unsigned int)macDest[2],
  102. (unsigned int)macDest[3],
  103. (unsigned int)macDest[4],
  104. (unsigned int)macDest[5]
  105. );
  106. if (msg)
  107. printf(" + (%s)" ZT_EOL_S,msg);
  108. }
  109. #else
  110. #define FILTER_TRACE(f,...) {}
  111. #endif // ZT_RULES_ENGINE_DEBUGGING
  112. // Returns true if packet appears valid; pos and proto will be set
  113. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  114. {
  115. if (frameLen < 40)
  116. return false;
  117. pos = 40;
  118. proto = frameData[6];
  119. while (pos <= frameLen) {
  120. switch(proto) {
  121. case 0: // hop-by-hop options
  122. case 43: // routing
  123. case 60: // destination options
  124. case 135: // mobility options
  125. if ((pos + 8) > frameLen)
  126. return false; // invalid!
  127. proto = frameData[pos];
  128. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  129. break;
  130. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  131. //case 50:
  132. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  133. default:
  134. return true;
  135. }
  136. }
  137. return false; // overflow == invalid
  138. }
  139. enum _doZtFilterResult
  140. {
  141. DOZTFILTER_NO_MATCH,
  142. DOZTFILTER_DROP,
  143. DOZTFILTER_REDIRECT,
  144. DOZTFILTER_ACCEPT,
  145. DOZTFILTER_SUPER_ACCEPT
  146. };
  147. static _doZtFilterResult _doZtFilter(
  148. const RuntimeEnvironment *RR,
  149. const NetworkConfig &nconf,
  150. const Membership *membership, // can be NULL
  151. const bool inbound,
  152. const Address &ztSource,
  153. Address &ztDest, // MUTABLE -- is changed on REDIRECT actions
  154. const MAC &macSource,
  155. const MAC &macDest,
  156. const uint8_t *const frameData,
  157. const unsigned int frameLen,
  158. const unsigned int etherType,
  159. const unsigned int vlanId,
  160. const ZT_VirtualNetworkRule *rules, // cannot be NULL
  161. const unsigned int ruleCount,
  162. Address &cc, // MUTABLE -- set to TEE destination if TEE action is taken or left alone otherwise
  163. unsigned int &ccLength, // MUTABLE -- set to length of packet payload to TEE
  164. bool &ccWatch) // MUTABLE -- set to true for WATCH target as opposed to normal TEE
  165. {
  166. #ifdef ZT_RULES_ENGINE_DEBUGGING
  167. char dpbuf[1024]; // used by FILTER_TRACE macro
  168. std::vector<std::string> dlog;
  169. #endif // ZT_RULES_ENGINE_DEBUGGING
  170. // The default match state for each set of entries starts as 'true' since an
  171. // ACTION with no MATCH entries preceding it is always taken.
  172. uint8_t thisSetMatches = 1;
  173. for(unsigned int rn=0;rn<ruleCount;++rn) {
  174. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x7f);
  175. // First check if this is an ACTION
  176. if ((unsigned int)rt <= (unsigned int)ZT_NETWORK_RULE_ACTION__MAX_ID) {
  177. if (thisSetMatches) {
  178. switch(rt) {
  179. case ZT_NETWORK_RULE_ACTION_DROP:
  180. #ifdef ZT_RULES_ENGINE_DEBUGGING
  181. _dumpFilterTrace("ACTION_DROP",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  182. #endif // ZT_RULES_ENGINE_DEBUGGING
  183. return DOZTFILTER_DROP;
  184. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  185. #ifdef ZT_RULES_ENGINE_DEBUGGING
  186. _dumpFilterTrace("ACTION_ACCEPT",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  187. #endif // ZT_RULES_ENGINE_DEBUGGING
  188. return DOZTFILTER_ACCEPT; // match, accept packet
  189. // These are initially handled together since preliminary logic is common
  190. case ZT_NETWORK_RULE_ACTION_TEE:
  191. case ZT_NETWORK_RULE_ACTION_WATCH:
  192. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  193. const Address fwdAddr(rules[rn].v.fwd.address);
  194. if (fwdAddr == ztSource) {
  195. #ifdef ZT_RULES_ENGINE_DEBUGGING
  196. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op since source is target");
  197. dlog.clear();
  198. #endif // ZT_RULES_ENGINE_DEBUGGING
  199. } else if (fwdAddr == RR->identity.address()) {
  200. if (inbound) {
  201. #ifdef ZT_RULES_ENGINE_DEBUGGING
  202. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"interpreted as super-ACCEPT on inbound since we are target");
  203. #endif // ZT_RULES_ENGINE_DEBUGGING
  204. return DOZTFILTER_SUPER_ACCEPT;
  205. } else {
  206. #ifdef ZT_RULES_ENGINE_DEBUGGING
  207. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op on outbound since we are target");
  208. dlog.clear();
  209. #endif // ZT_RULES_ENGINE_DEBUGGING
  210. }
  211. } else if (fwdAddr == ztDest) {
  212. #ifdef ZT_RULES_ENGINE_DEBUGGING
  213. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,"skipped as no-op because destination is already target");
  214. dlog.clear();
  215. #endif // ZT_RULES_ENGINE_DEBUGGING
  216. } else {
  217. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  218. #ifdef ZT_RULES_ENGINE_DEBUGGING
  219. _dumpFilterTrace("ACTION_REDIRECT",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  220. #endif // ZT_RULES_ENGINE_DEBUGGING
  221. ztDest = fwdAddr;
  222. return DOZTFILTER_REDIRECT;
  223. } else {
  224. #ifdef ZT_RULES_ENGINE_DEBUGGING
  225. _dumpFilterTrace("ACTION_TEE",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  226. dlog.clear();
  227. #endif // ZT_RULES_ENGINE_DEBUGGING
  228. cc = fwdAddr;
  229. ccLength = (rules[rn].v.fwd.length != 0) ? ((frameLen < (unsigned int)rules[rn].v.fwd.length) ? frameLen : (unsigned int)rules[rn].v.fwd.length) : frameLen;
  230. ccWatch = (rt == ZT_NETWORK_RULE_ACTION_WATCH);
  231. }
  232. }
  233. } continue;
  234. // This is a no-op that exists for use with rules engine tracing and isn't for use in production
  235. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG: // a no-op target specifically for debugging purposes
  236. #ifdef ZT_RULES_ENGINE_DEBUGGING
  237. _dumpFilterTrace("ACTION_DEBUG_LOG",thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  238. dlog.clear();
  239. #endif // ZT_RULES_ENGINE_DEBUGGING
  240. continue;
  241. // Unrecognized ACTIONs are ignored as no-ops
  242. default:
  243. #ifdef ZT_RULES_ENGINE_DEBUGGING
  244. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  245. dlog.clear();
  246. #endif // ZT_RULES_ENGINE_DEBUGGING
  247. continue;
  248. }
  249. } else {
  250. #ifdef ZT_RULES_ENGINE_DEBUGGING
  251. _dumpFilterTrace(_rtn(rt),thisSetMatches,inbound,ztSource,ztDest,macSource,macDest,dlog,frameLen,etherType,(const char *)0);
  252. dlog.clear();
  253. #endif // ZT_RULES_ENGINE_DEBUGGING
  254. thisSetMatches = 1; // reset to default true for next batch of entries
  255. continue;
  256. }
  257. }
  258. // Circuit breaker: skip further MATCH entries up to next ACTION if match state is false
  259. if (!thisSetMatches)
  260. continue;
  261. // If this was not an ACTION evaluate next MATCH and update thisSetMatches with (AND [result])
  262. uint8_t thisRuleMatches = 0;
  263. switch(rt) {
  264. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  265. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  266. FILTER_TRACE("%u %s %c %.10llx==%.10llx -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),rules[rn].v.zt,ztSource.toInt(),(unsigned int)thisRuleMatches);
  267. break;
  268. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  269. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  270. FILTER_TRACE("%u %s %c %.10llx==%.10llx -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),rules[rn].v.zt,ztDest.toInt(),(unsigned int)thisRuleMatches);
  271. break;
  272. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  273. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  274. FILTER_TRACE("%u %s %c %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.vlanId,(unsigned int)vlanId,(unsigned int)thisRuleMatches);
  275. break;
  276. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  277. // NOT SUPPORTED YET
  278. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  279. FILTER_TRACE("%u %s %c %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.vlanPcp,0,(unsigned int)thisRuleMatches);
  280. break;
  281. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  282. // NOT SUPPORTED YET
  283. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  284. FILTER_TRACE("%u %s %c %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.vlanDei,0,(unsigned int)thisRuleMatches);
  285. break;
  286. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  287. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  288. FILTER_TRACE("%u %s %c %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.etherType,etherType,(unsigned int)thisRuleMatches);
  289. break;
  290. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  291. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macSource);
  292. FILTER_TRACE("%u %s %c %.12llx=%.12llx -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),rules[rn].v.mac,macSource.toInt(),(unsigned int)thisRuleMatches);
  293. break;
  294. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  295. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macDest);
  296. FILTER_TRACE("%u %s %c %.12llx=%.12llx -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),rules[rn].v.mac,macDest.toInt(),(unsigned int)thisRuleMatches);
  297. break;
  298. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  299. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  300. 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)));
  301. FILTER_TRACE("%u %s %c %s contains %s -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).toString().c_str(),InetAddress((const void *)(frameData + 12),4,0).toIpString().c_str(),(unsigned int)thisRuleMatches);
  302. } else {
  303. thisRuleMatches = 0;
  304. FILTER_TRACE("%u %s %c [frame not IPv4] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  305. }
  306. break;
  307. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  308. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  309. 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)));
  310. FILTER_TRACE("%u %s %c %s contains %s -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).toString().c_str(),InetAddress((const void *)(frameData + 16),4,0).toIpString().c_str(),(unsigned int)thisRuleMatches);
  311. } else {
  312. thisRuleMatches = 0;
  313. FILTER_TRACE("%u %s %c [frame not IPv4] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  314. }
  315. break;
  316. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  317. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  318. 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)));
  319. FILTER_TRACE("%u %s %c %s contains %s -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).toString().c_str(),InetAddress((const void *)(frameData + 8),16,0).toIpString().c_str(),(unsigned int)thisRuleMatches);
  320. } else {
  321. thisRuleMatches = 0;
  322. FILTER_TRACE("%u %s %c [frame not IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  323. }
  324. break;
  325. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  326. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  327. 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)));
  328. FILTER_TRACE("%u %s %c %s contains %s -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).toString().c_str(),InetAddress((const void *)(frameData + 24),16,0).toIpString().c_str(),(unsigned int)thisRuleMatches);
  329. } else {
  330. thisRuleMatches = 0;
  331. FILTER_TRACE("%u %s %c [frame not IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  332. }
  333. break;
  334. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  335. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  336. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((frameData[1] & 0xfc) >> 2));
  337. FILTER_TRACE("%u %s %c (IPv4) %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.ipTos,(unsigned int)((frameData[1] & 0xfc) >> 2),(unsigned int)thisRuleMatches);
  338. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  339. const uint8_t trafficClass = ((frameData[0] << 4) & 0xf0) | ((frameData[1] >> 4) & 0x0f);
  340. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((trafficClass & 0xfc) >> 2));
  341. FILTER_TRACE("%u %s %c (IPv6) %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.ipTos,(unsigned int)((trafficClass & 0xfc) >> 2),(unsigned int)thisRuleMatches);
  342. } else {
  343. thisRuleMatches = 0;
  344. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  345. }
  346. break;
  347. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  348. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  349. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
  350. FILTER_TRACE("%u %s %c (IPv4) %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.ipProtocol,(unsigned int)frameData[9],(unsigned int)thisRuleMatches);
  351. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  352. unsigned int pos = 0,proto = 0;
  353. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  354. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
  355. FILTER_TRACE("%u %s %c (IPv6) %u==%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.ipProtocol,proto,(unsigned int)thisRuleMatches);
  356. } else {
  357. thisRuleMatches = 0;
  358. FILTER_TRACE("%u %s %c [invalid IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  359. }
  360. } else {
  361. thisRuleMatches = 0;
  362. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  363. }
  364. break;
  365. case ZT_NETWORK_RULE_MATCH_ICMP:
  366. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  367. if (frameData[9] == 0x01) {
  368. const unsigned int ihl = (frameData[0] & 0xf) * 32;
  369. if (frameLen >= (ihl + 2)) {
  370. if (rules[rn].v.icmp.type == frameData[ihl]) {
  371. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  372. thisRuleMatches = (uint8_t)(frameData[ihl+1] == rules[rn].v.icmp.code);
  373. } else {
  374. thisRuleMatches = 1;
  375. }
  376. } else {
  377. thisRuleMatches = 0;
  378. }
  379. FILTER_TRACE("%u %s %c (IPv4) icmp-type:%d==%d icmp-code:%d==%d -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(int)frameData[ihl],(int)rules[rn].v.icmp.type,(int)frameData[ihl+1],(((rules[rn].v.icmp.flags & 0x01) != 0) ? (int)rules[rn].v.icmp.code : -1),(unsigned int)thisRuleMatches);
  380. } else {
  381. thisRuleMatches = 0;
  382. FILTER_TRACE("%u %s %c [IPv4 frame invalid] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  383. }
  384. } else {
  385. thisRuleMatches = 0;
  386. FILTER_TRACE("%u %s %c [frame not ICMP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  387. }
  388. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  389. unsigned int pos = 0,proto = 0;
  390. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  391. if ((proto == 0x3a)&&(frameLen >= (pos+2))) {
  392. if (rules[rn].v.icmp.type == frameData[pos]) {
  393. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  394. thisRuleMatches = (uint8_t)(frameData[pos+1] == rules[rn].v.icmp.code);
  395. } else {
  396. thisRuleMatches = 1;
  397. }
  398. } else {
  399. thisRuleMatches = 0;
  400. }
  401. FILTER_TRACE("%u %s %c (IPv4) icmp-type:%d==%d icmp-code:%d==%d -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(int)frameData[pos],(int)rules[rn].v.icmp.type,(int)frameData[pos+1],(((rules[rn].v.icmp.flags & 0x01) != 0) ? (int)rules[rn].v.icmp.code : -1),(unsigned int)thisRuleMatches);
  402. } else {
  403. thisRuleMatches = 0;
  404. FILTER_TRACE("%u %s %c [frame not ICMPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  405. }
  406. } else {
  407. thisRuleMatches = 0;
  408. FILTER_TRACE("%u %s %c [invalid IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  409. }
  410. } else {
  411. thisRuleMatches = 0;
  412. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  413. }
  414. break;
  415. break;
  416. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  417. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  418. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  419. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  420. int p = -1;
  421. switch(frameData[9]) { // IP protocol number
  422. // All these start with 16-bit source and destination port in that order
  423. case 0x06: // TCP
  424. case 0x11: // UDP
  425. case 0x84: // SCTP
  426. case 0x88: // UDPLite
  427. if (frameLen > (headerLen + 4)) {
  428. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  429. p = (int)frameData[pos++] << 8;
  430. p |= (int)frameData[pos];
  431. }
  432. break;
  433. }
  434. thisRuleMatches = (p >= 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  435. FILTER_TRACE("%u %s %c (IPv4) %d in %d-%d -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),p,(int)rules[rn].v.port[0],(int)rules[rn].v.port[1],(unsigned int)thisRuleMatches);
  436. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  437. unsigned int pos = 0,proto = 0;
  438. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  439. int p = -1;
  440. switch(proto) { // IP protocol number
  441. // All these start with 16-bit source and destination port in that order
  442. case 0x06: // TCP
  443. case 0x11: // UDP
  444. case 0x84: // SCTP
  445. case 0x88: // UDPLite
  446. if (frameLen > (pos + 4)) {
  447. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) pos += 2;
  448. p = (int)frameData[pos++] << 8;
  449. p |= (int)frameData[pos];
  450. }
  451. break;
  452. }
  453. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  454. FILTER_TRACE("%u %s %c (IPv6) %d in %d-%d -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),p,(int)rules[rn].v.port[0],(int)rules[rn].v.port[1],(unsigned int)thisRuleMatches);
  455. } else {
  456. thisRuleMatches = 0;
  457. FILTER_TRACE("%u %s %c [invalid IPv6] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  458. }
  459. } else {
  460. thisRuleMatches = 0;
  461. FILTER_TRACE("%u %s %c [frame not IP] -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='));
  462. }
  463. break;
  464. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  465. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  466. if (macDest.isMulticast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_MULTICAST;
  467. if (macDest.isBroadcast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_BROADCAST;
  468. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  469. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  470. cf |= (uint64_t)frameData[headerLen + 13];
  471. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  472. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  473. unsigned int pos = 0,proto = 0;
  474. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  475. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  476. cf |= (uint64_t)frameData[pos + 13];
  477. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  478. }
  479. }
  480. }
  481. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics[0]) == rules[rn].v.characteristics[1]);
  482. FILTER_TRACE("%u %s %c (%.16llx & %.16llx)==%.16llx -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),cf,rules[rn].v.characteristics[0],rules[rn].v.characteristics[1],(unsigned int)thisRuleMatches);
  483. } break;
  484. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  485. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  486. FILTER_TRACE("%u %s %c %u in %u-%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),frameLen,(unsigned int)rules[rn].v.frameSize[0],(unsigned int)rules[rn].v.frameSize[1],(unsigned int)thisRuleMatches);
  487. break;
  488. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  489. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  490. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  491. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: {
  492. const Tag *const localTag = std::lower_bound(&(nconf.tags[0]),&(nconf.tags[nconf.tagCount]),rules[rn].v.tag.id,Tag::IdComparePredicate());
  493. if ((localTag != &(nconf.tags[nconf.tagCount]))&&(localTag->id() == rules[rn].v.tag.id)) {
  494. const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
  495. if (remoteTag) {
  496. const uint32_t ltv = localTag->value();
  497. const uint32_t rtv = remoteTag->value();
  498. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE) {
  499. const uint32_t diff = (ltv > rtv) ? (ltv - rtv) : (rtv - ltv);
  500. thisRuleMatches = (uint8_t)(diff <= rules[rn].v.tag.value);
  501. FILTER_TRACE("%u %s %c TAG %u local:%u remote:%u difference:%u<=%u -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.tag.id,ltv,rtv,diff,(unsigned int)rules[rn].v.tag.value,thisRuleMatches);
  502. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  503. thisRuleMatches = (uint8_t)((ltv & rtv) == rules[rn].v.tag.value);
  504. FILTER_TRACE("%u %s %c TAG %u local:%.8x & remote:%.8x == %.8x -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.tag.id,ltv,rtv,(unsigned int)rules[rn].v.tag.value,(unsigned int)thisRuleMatches);
  505. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  506. thisRuleMatches = (uint8_t)((ltv | rtv) == rules[rn].v.tag.value);
  507. FILTER_TRACE("%u %s %c TAG %u local:%.8x | remote:%.8x == %.8x -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.tag.id,ltv,rtv,(unsigned int)rules[rn].v.tag.value,(unsigned int)thisRuleMatches);
  508. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  509. thisRuleMatches = (uint8_t)((ltv ^ rtv) == rules[rn].v.tag.value);
  510. FILTER_TRACE("%u %s %c TAG %u local:%.8x ^ remote:%.8x == %.8x -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.tag.id,ltv,rtv,(unsigned int)rules[rn].v.tag.value,(unsigned int)thisRuleMatches);
  511. } else { // sanity check, can't really happen
  512. thisRuleMatches = 0;
  513. }
  514. } else {
  515. if (inbound) {
  516. thisRuleMatches = 0;
  517. FILTER_TRACE("%u %s %c remote tag %u not found -> 0 (inbound side is strict)",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.tag.id);
  518. } else {
  519. thisRuleMatches = 1;
  520. FILTER_TRACE("%u %s %c remote tag %u not found -> 1 (outbound side is not strict)",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.tag.id);
  521. }
  522. }
  523. } else {
  524. thisRuleMatches = 0;
  525. FILTER_TRACE("%u %s %c local tag %u not found -> 0",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)rules[rn].v.tag.id);
  526. }
  527. } break;
  528. // The result of an unsupported MATCH is configurable at the network
  529. // level via a flag.
  530. default:
  531. thisRuleMatches = (uint8_t)((nconf.flags & ZT_NETWORKCONFIG_FLAG_RULES_RESULT_OF_UNSUPPORTED_MATCH) != 0);
  532. break;
  533. }
  534. // State of equals state AND result of last MATCH (possibly NOTed depending on bit 0x80)
  535. thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
  536. }
  537. return DOZTFILTER_NO_MATCH;
  538. }
  539. } // anonymous namespace
  540. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  541. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  542. RR(renv),
  543. _uPtr(uptr),
  544. _id(nwid),
  545. _lastAnnouncedMulticastGroupsUpstream(0),
  546. _mac(renv->identity.address(),nwid),
  547. _portInitialized(false),
  548. _lastConfigUpdate(0),
  549. _destroyed(false),
  550. _netconfFailure(NETCONF_FAILURE_NONE),
  551. _portError(0)
  552. {
  553. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i)
  554. _incomingConfigChunks[i].ts = 0;
  555. char confn[128];
  556. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  557. bool gotConf = false;
  558. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  559. NetworkConfig *nconf = new NetworkConfig();
  560. try {
  561. std::string conf(RR->node->dataStoreGet(confn));
  562. if (conf.length()) {
  563. dconf->load(conf.c_str());
  564. if (nconf->fromDictionary(*dconf)) {
  565. this->_setConfiguration(*nconf,false);
  566. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  567. gotConf = true;
  568. }
  569. }
  570. } catch ( ... ) {} // ignore invalids, we'll re-request
  571. delete nconf;
  572. delete dconf;
  573. if (!gotConf) {
  574. // Save a one-byte CR to persist membership while we request a real netconf
  575. RR->node->dataStorePut(confn,"\n",1,false);
  576. }
  577. if (!_portInitialized) {
  578. ZT_VirtualNetworkConfig ctmp;
  579. _externalConfig(&ctmp);
  580. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  581. _portInitialized = true;
  582. }
  583. }
  584. Network::~Network()
  585. {
  586. ZT_VirtualNetworkConfig ctmp;
  587. _externalConfig(&ctmp);
  588. char n[128];
  589. if (_destroyed) {
  590. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  591. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  592. RR->node->dataStoreDelete(n);
  593. } else {
  594. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  595. }
  596. }
  597. bool Network::filterOutgoingPacket(
  598. const bool noTee,
  599. const Address &ztSource,
  600. const Address &ztDest,
  601. const MAC &macSource,
  602. const MAC &macDest,
  603. const uint8_t *frameData,
  604. const unsigned int frameLen,
  605. const unsigned int etherType,
  606. const unsigned int vlanId)
  607. {
  608. const uint64_t now = RR->node->now();
  609. Address ztFinalDest(ztDest);
  610. int localCapabilityIndex = -1;
  611. bool accept = false;
  612. Mutex::Lock _l(_lock);
  613. Membership *const membership = (ztDest) ? _memberships.get(ztDest) : (Membership *)0;
  614. Address cc;
  615. unsigned int ccLength = 0;
  616. bool ccWatch = false;
  617. switch(_doZtFilter(RR,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch)) {
  618. case DOZTFILTER_NO_MATCH:
  619. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  620. ztFinalDest = ztDest; // sanity check, shouldn't be possible if there was no match
  621. Address cc2;
  622. unsigned int ccLength2 = 0;
  623. bool ccWatch2 = false;
  624. switch (_doZtFilter(RR,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.capabilities[c].rules(),_config.capabilities[c].ruleCount(),cc2,ccLength2,ccWatch2)) {
  625. case DOZTFILTER_NO_MATCH:
  626. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  627. break;
  628. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  629. case DOZTFILTER_ACCEPT:
  630. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  631. localCapabilityIndex = (int)c;
  632. accept = true;
  633. if ((!noTee)&&(cc2)) {
  634. Membership &m2 = _membership(cc2);
  635. m2.pushCredentials(RR,now,cc2,_config,localCapabilityIndex,false);
  636. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  637. outp.append(_id);
  638. outp.append((uint8_t)(ccWatch2 ? 0x16 : 0x02));
  639. macDest.appendTo(outp);
  640. macSource.appendTo(outp);
  641. outp.append((uint16_t)etherType);
  642. outp.append(frameData,ccLength2);
  643. outp.compress();
  644. RR->sw->send(outp,true);
  645. }
  646. break;
  647. }
  648. if (accept)
  649. break;
  650. }
  651. break;
  652. case DOZTFILTER_DROP:
  653. return false;
  654. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  655. case DOZTFILTER_ACCEPT:
  656. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  657. accept = true;
  658. break;
  659. }
  660. if (accept) {
  661. if (membership)
  662. membership->pushCredentials(RR,now,ztDest,_config,localCapabilityIndex,false);
  663. if ((!noTee)&&(cc)) {
  664. Membership &m2 = _membership(cc);
  665. m2.pushCredentials(RR,now,cc,_config,localCapabilityIndex,false);
  666. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  667. outp.append(_id);
  668. outp.append((uint8_t)(ccWatch ? 0x16 : 0x02));
  669. macDest.appendTo(outp);
  670. macSource.appendTo(outp);
  671. outp.append((uint16_t)etherType);
  672. outp.append(frameData,ccLength);
  673. outp.compress();
  674. RR->sw->send(outp,true);
  675. }
  676. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  677. Membership &m2 = _membership(ztFinalDest);
  678. m2.pushCredentials(RR,now,ztFinalDest,_config,localCapabilityIndex,false);
  679. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  680. outp.append(_id);
  681. outp.append((uint8_t)0x04);
  682. macDest.appendTo(outp);
  683. macSource.appendTo(outp);
  684. outp.append((uint16_t)etherType);
  685. outp.append(frameData,frameLen);
  686. outp.compress();
  687. RR->sw->send(outp,true);
  688. return false; // DROP locally, since we redirected
  689. } else {
  690. return true;
  691. }
  692. } else {
  693. return false;
  694. }
  695. }
  696. int Network::filterIncomingPacket(
  697. const SharedPtr<Peer> &sourcePeer,
  698. const Address &ztDest,
  699. const MAC &macSource,
  700. const MAC &macDest,
  701. const uint8_t *frameData,
  702. const unsigned int frameLen,
  703. const unsigned int etherType,
  704. const unsigned int vlanId)
  705. {
  706. Address ztFinalDest(ztDest);
  707. int accept = 0;
  708. Mutex::Lock _l(_lock);
  709. Membership &membership = _membership(sourcePeer->address());
  710. Address cc;
  711. unsigned int ccLength = 0;
  712. bool ccWatch = false;
  713. switch (_doZtFilter(RR,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch)) {
  714. case DOZTFILTER_NO_MATCH: {
  715. Membership::CapabilityIterator mci(membership,_config);
  716. const Capability *c;
  717. while ((c = mci.next())) {
  718. ztFinalDest = ztDest; // sanity check, should be unmodified if there was no match
  719. Address cc2;
  720. unsigned int ccLength2 = 0;
  721. bool ccWatch2 = false;
  722. switch(_doZtFilter(RR,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),cc2,ccLength2,ccWatch2)) {
  723. case DOZTFILTER_NO_MATCH:
  724. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  725. break;
  726. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
  727. case DOZTFILTER_ACCEPT:
  728. accept = 1; // ACCEPT
  729. break;
  730. case DOZTFILTER_SUPER_ACCEPT:
  731. accept = 2; // super-ACCEPT
  732. break;
  733. }
  734. if (accept) {
  735. if (cc2) {
  736. _membership(cc2).pushCredentials(RR,RR->node->now(),cc2,_config,-1,false);
  737. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  738. outp.append(_id);
  739. outp.append((uint8_t)(ccWatch2 ? 0x1c : 0x08));
  740. macDest.appendTo(outp);
  741. macSource.appendTo(outp);
  742. outp.append((uint16_t)etherType);
  743. outp.append(frameData,ccLength2);
  744. outp.compress();
  745. RR->sw->send(outp,true);
  746. }
  747. break;
  748. }
  749. }
  750. } break;
  751. case DOZTFILTER_DROP:
  752. return 0; // DROP
  753. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  754. case DOZTFILTER_ACCEPT:
  755. accept = 1; // ACCEPT
  756. break;
  757. case DOZTFILTER_SUPER_ACCEPT:
  758. accept = 2; // super-ACCEPT
  759. break;
  760. }
  761. if (accept) {
  762. if (cc) {
  763. _membership(cc).pushCredentials(RR,RR->node->now(),cc,_config,-1,false);
  764. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  765. outp.append(_id);
  766. outp.append((uint8_t)(ccWatch ? 0x1c : 0x08));
  767. macDest.appendTo(outp);
  768. macSource.appendTo(outp);
  769. outp.append((uint16_t)etherType);
  770. outp.append(frameData,ccLength);
  771. outp.compress();
  772. RR->sw->send(outp,true);
  773. }
  774. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  775. _membership(ztFinalDest).pushCredentials(RR,RR->node->now(),ztFinalDest,_config,-1,false);
  776. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  777. outp.append(_id);
  778. outp.append((uint8_t)0x0a);
  779. macDest.appendTo(outp);
  780. macSource.appendTo(outp);
  781. outp.append((uint16_t)etherType);
  782. outp.append(frameData,frameLen);
  783. outp.compress();
  784. RR->sw->send(outp,true);
  785. return 0; // DROP locally, since we redirected
  786. }
  787. }
  788. return accept;
  789. }
  790. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  791. {
  792. Mutex::Lock _l(_lock);
  793. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  794. return true;
  795. else if (includeBridgedGroups)
  796. return _multicastGroupsBehindMe.contains(mg);
  797. return false;
  798. }
  799. void Network::multicastSubscribe(const MulticastGroup &mg)
  800. {
  801. Mutex::Lock _l(_lock);
  802. if (!std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg)) {
  803. _myMulticastGroups.insert(std::upper_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg),mg);
  804. _sendUpdatesToMembers(&mg);
  805. }
  806. }
  807. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  808. {
  809. Mutex::Lock _l(_lock);
  810. std::vector<MulticastGroup>::iterator i(std::lower_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg));
  811. if ( (i != _myMulticastGroups.end()) && (*i == mg) )
  812. _myMulticastGroups.erase(i);
  813. }
  814. uint64_t Network::handleConfigChunk(const Packet &chunk,unsigned int ptr)
  815. {
  816. const unsigned int start = ptr;
  817. ptr += 8; // skip network ID, which is already obviously known
  818. const unsigned int chunkLen = chunk.at<uint16_t>(ptr); ptr += 2;
  819. const void *chunkData = chunk.field(ptr,chunkLen); ptr += chunkLen;
  820. Mutex::Lock _l(_lock);
  821. _IncomingConfigChunk *c = (_IncomingConfigChunk *)0;
  822. uint64_t chunkId = 0;
  823. uint64_t configUpdateId;
  824. unsigned long totalLength,chunkIndex;
  825. if (ptr < chunk.size()) {
  826. const bool fastPropagate = ((chunk[ptr++] & 0x01) != 0);
  827. configUpdateId = chunk.at<uint64_t>(ptr); ptr += 8;
  828. totalLength = chunk.at<uint32_t>(ptr); ptr += 4;
  829. chunkIndex = chunk.at<uint32_t>(ptr); ptr += 4;
  830. if (((chunkIndex + chunkLen) > totalLength)||(totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)) { // >= since we need room for a null at the end
  831. TRACE("discarded chunk from %s: invalid length or length overflow",chunk.source().toString().c_str());
  832. return 0;
  833. }
  834. if ((chunk[ptr] != 1)||(chunk.at<uint16_t>(ptr + 1) != ZT_C25519_SIGNATURE_LEN)) {
  835. TRACE("discarded chunk from %s: unrecognized signature type",chunk.source().toString().c_str());
  836. return 0;
  837. }
  838. const uint8_t *sig = reinterpret_cast<const uint8_t *>(chunk.field(ptr + 3,ZT_C25519_SIGNATURE_LEN));
  839. // We can use the signature, which is unique per chunk, to get a per-chunk ID for local deduplication use
  840. for(unsigned int i=0;i<16;++i)
  841. reinterpret_cast<uint8_t *>(&chunkId)[i & 7] ^= sig[i];
  842. // Find existing or new slot for this update and check if this is a duplicate chunk
  843. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  844. if (_incomingConfigChunks[i].updateId == configUpdateId) {
  845. c = &(_incomingConfigChunks[i]);
  846. for(unsigned long j=0;j<c->haveChunks;++j) {
  847. if (c->haveChunkIds[j] == chunkId)
  848. return 0;
  849. }
  850. break;
  851. } else if ((!c)||(_incomingConfigChunks[i].ts < c->ts)) {
  852. c = &(_incomingConfigChunks[i]);
  853. }
  854. }
  855. // If it's not a duplicate, check chunk signature
  856. const Identity controllerId(RR->topology->getIdentity(controller()));
  857. if (!controllerId) { // we should always have the controller identity by now, otherwise how would we have queried it the first time?
  858. TRACE("unable to verify chunk from %s: don't have controller identity",chunk.source().toString().c_str());
  859. return 0;
  860. }
  861. if (!controllerId.verify(chunk.field(start,ptr - start),ptr - start,sig,ZT_C25519_SIGNATURE_LEN)) {
  862. TRACE("discarded chunk from %s: signature check failed",chunk.source().toString().c_str());
  863. return 0;
  864. }
  865. // New properly verified chunks can be flooded "virally" through the network
  866. if (fastPropagate) {
  867. Address *a = (Address *)0;
  868. Membership *m = (Membership *)0;
  869. Hashtable<Address,Membership>::Iterator i(_memberships);
  870. while (i.next(a,m)) {
  871. if ((*a != chunk.source())&&(*a != controller())) {
  872. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CONFIG);
  873. outp.append(reinterpret_cast<const uint8_t *>(chunk.data()) + start,chunk.size() - start);
  874. RR->sw->send(outp,true);
  875. }
  876. }
  877. }
  878. } else if (chunk.source() == controller()) {
  879. // Legacy support for OK(NETWORK_CONFIG_REQUEST) from older controllers
  880. chunkId = chunk.packetId();
  881. configUpdateId = chunkId;
  882. totalLength = chunkLen;
  883. chunkIndex = 0;
  884. if (totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)
  885. return 0;
  886. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  887. if ((!c)||(_incomingConfigChunks[i].ts < c->ts))
  888. c = &(_incomingConfigChunks[i]);
  889. }
  890. } else {
  891. TRACE("discarded single-chunk unsigned legacy config: this is only allowed if the sender is the controller itself");
  892. return 0;
  893. }
  894. ++c->ts; // newer is higher, that's all we need
  895. if (c->updateId != configUpdateId) {
  896. c->updateId = configUpdateId;
  897. c->haveChunks = 0;
  898. c->haveBytes = 0;
  899. }
  900. if (c->haveChunks >= ZT_NETWORK_MAX_UPDATE_CHUNKS)
  901. return false;
  902. c->haveChunkIds[c->haveChunks++] = chunkId;
  903. memcpy(c->data.unsafeData() + chunkIndex,chunkData,chunkLen);
  904. c->haveBytes += chunkLen;
  905. if (c->haveBytes == totalLength) {
  906. c->data.unsafeData()[c->haveBytes] = (char)0; // ensure null terminated
  907. NetworkConfig *const nc = new NetworkConfig();
  908. try {
  909. if (nc->fromDictionary(c->data)) {
  910. this->_setConfiguration(*nc,true);
  911. return configUpdateId;
  912. }
  913. delete nc;
  914. } catch ( ... ) {
  915. delete nc;
  916. }
  917. }
  918. return 0;
  919. }
  920. void Network::requestConfiguration()
  921. {
  922. const Address ctrl(controller());
  923. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  924. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  925. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_VENDOR,(uint64_t)ZT_VENDOR_ZEROTIER);
  926. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  927. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  928. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  929. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  930. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  931. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  932. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  933. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  934. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  935. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,(uint64_t)ZT_RULES_ENGINE_REVISION);
  936. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_RELAY_POLICY,(uint64_t)RR->node->relayPolicy());
  937. if (ctrl == RR->identity.address()) {
  938. if (RR->localNetworkController) {
  939. NetworkConfig nconf;
  940. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  941. case NetworkController::NETCONF_QUERY_OK: {
  942. Mutex::Lock _l(_lock);
  943. this->_setConfiguration(nconf,true);
  944. } return;
  945. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  946. this->setNotFound();
  947. return;
  948. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  949. this->setAccessDenied();
  950. return;
  951. default:
  952. return;
  953. }
  954. } else {
  955. this->setNotFound();
  956. return;
  957. }
  958. }
  959. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,ctrl.toString().c_str());
  960. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  961. outp.append((uint64_t)_id);
  962. const unsigned int rmdSize = rmd.sizeBytes();
  963. outp.append((uint16_t)rmdSize);
  964. outp.append((const void *)rmd.data(),rmdSize);
  965. if (_config) {
  966. outp.append((uint64_t)_config.revision);
  967. outp.append((uint64_t)_config.timestamp);
  968. } else {
  969. outp.append((unsigned char)0,16);
  970. }
  971. RR->node->expectReplyTo(outp.packetId());
  972. outp.compress();
  973. RR->sw->send(outp,true);
  974. }
  975. bool Network::gate(const SharedPtr<Peer> &peer)
  976. {
  977. const uint64_t now = RR->node->now();
  978. Mutex::Lock _l(_lock);
  979. try {
  980. if (_config) {
  981. Membership *m = _memberships.get(peer->address());
  982. if ( (_config.isPublic()) || ((m)&&(m->isAllowedOnNetwork(_config))) ) {
  983. if (!m)
  984. m = &(_membership(peer->address()));
  985. m->pushCredentials(RR,now,peer->address(),_config,-1,false);
  986. if (m->shouldLikeMulticasts(now)) {
  987. _announceMulticastGroupsTo(peer->address(),_allMulticastGroups());
  988. m->likingMulticasts(now);
  989. }
  990. return true;
  991. }
  992. }
  993. } catch ( ... ) {
  994. TRACE("gate() check failed for peer %s: unexpected exception",peer->address().toString().c_str());
  995. }
  996. return false;
  997. }
  998. void Network::clean()
  999. {
  1000. const uint64_t now = RR->node->now();
  1001. Mutex::Lock _l(_lock);
  1002. if (_destroyed)
  1003. return;
  1004. {
  1005. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  1006. MulticastGroup *mg = (MulticastGroup *)0;
  1007. uint64_t *ts = (uint64_t *)0;
  1008. while (i.next(mg,ts)) {
  1009. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  1010. _multicastGroupsBehindMe.erase(*mg);
  1011. }
  1012. }
  1013. {
  1014. Address *a = (Address *)0;
  1015. Membership *m = (Membership *)0;
  1016. Hashtable<Address,Membership>::Iterator i(_memberships);
  1017. while (i.next(a,m)) {
  1018. if (!RR->topology->getPeerNoCache(*a))
  1019. _memberships.erase(*a);
  1020. }
  1021. }
  1022. }
  1023. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  1024. {
  1025. Mutex::Lock _l(_lock);
  1026. _remoteBridgeRoutes[mac] = addr;
  1027. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  1028. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  1029. Hashtable< Address,unsigned long > counts;
  1030. Address maxAddr;
  1031. unsigned long maxCount = 0;
  1032. MAC *m = (MAC *)0;
  1033. Address *a = (Address *)0;
  1034. // Find the address responsible for the most entries
  1035. {
  1036. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1037. while (i.next(m,a)) {
  1038. const unsigned long c = ++counts[*a];
  1039. if (c > maxCount) {
  1040. maxCount = c;
  1041. maxAddr = *a;
  1042. }
  1043. }
  1044. }
  1045. // Kill this address from our table, since it's most likely spamming us
  1046. {
  1047. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1048. while (i.next(m,a)) {
  1049. if (*a == maxAddr)
  1050. _remoteBridgeRoutes.erase(*m);
  1051. }
  1052. }
  1053. }
  1054. }
  1055. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  1056. {
  1057. Mutex::Lock _l(_lock);
  1058. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  1059. _multicastGroupsBehindMe.set(mg,now);
  1060. if (tmp != _multicastGroupsBehindMe.size())
  1061. _sendUpdatesToMembers(&mg);
  1062. }
  1063. Membership::AddCredentialResult Network::addCredential(const CertificateOfMembership &com)
  1064. {
  1065. if (com.networkId() != _id)
  1066. return Membership::ADD_REJECTED;
  1067. const Address a(com.issuedTo());
  1068. Mutex::Lock _l(_lock);
  1069. Membership &m = _membership(a);
  1070. const Membership::AddCredentialResult result = m.addCredential(RR,_config,com);
  1071. if ((result == Membership::ADD_ACCEPTED_NEW)||(result == Membership::ADD_ACCEPTED_REDUNDANT)) {
  1072. m.pushCredentials(RR,RR->node->now(),a,_config,-1,false);
  1073. RR->mc->addCredential(com,true);
  1074. }
  1075. return result;
  1076. }
  1077. Membership::AddCredentialResult Network::addCredential(const Address &sentFrom,const Revocation &rev)
  1078. {
  1079. if (rev.networkId() != _id)
  1080. return Membership::ADD_REJECTED;
  1081. Mutex::Lock _l(_lock);
  1082. Membership &m = _membership(rev.target());
  1083. const Membership::AddCredentialResult result = m.addCredential(RR,_config,rev);
  1084. if ((result == Membership::ADD_ACCEPTED_NEW)&&(rev.fastPropagate())) {
  1085. Address *a = (Address *)0;
  1086. Membership *m = (Membership *)0;
  1087. Hashtable<Address,Membership>::Iterator i(_memberships);
  1088. while (i.next(a,m)) {
  1089. if ((*a != sentFrom)&&(*a != rev.signer())) {
  1090. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1091. outp.append((uint8_t)0x00); // no COM
  1092. outp.append((uint16_t)0); // no capabilities
  1093. outp.append((uint16_t)0); // no tags
  1094. outp.append((uint16_t)1); // one revocation!
  1095. rev.serialize(outp);
  1096. RR->sw->send(outp,true);
  1097. }
  1098. }
  1099. }
  1100. return result;
  1101. }
  1102. void Network::destroy()
  1103. {
  1104. Mutex::Lock _l(_lock);
  1105. _destroyed = true;
  1106. }
  1107. ZT_VirtualNetworkStatus Network::_status() const
  1108. {
  1109. // assumes _lock is locked
  1110. if (_portError)
  1111. return ZT_NETWORK_STATUS_PORT_ERROR;
  1112. switch(_netconfFailure) {
  1113. case NETCONF_FAILURE_ACCESS_DENIED:
  1114. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  1115. case NETCONF_FAILURE_NOT_FOUND:
  1116. return ZT_NETWORK_STATUS_NOT_FOUND;
  1117. case NETCONF_FAILURE_NONE:
  1118. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  1119. default:
  1120. return ZT_NETWORK_STATUS_PORT_ERROR;
  1121. }
  1122. }
  1123. int Network::_setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  1124. {
  1125. // assumes _lock is locked
  1126. try {
  1127. if ((nconf.issuedTo != RR->identity.address())||(nconf.networkId != _id))
  1128. return 0;
  1129. if (_config == nconf)
  1130. return 1; // OK config, but duplicate of what we already have
  1131. ZT_VirtualNetworkConfig ctmp;
  1132. _config = nconf;
  1133. _lastConfigUpdate = RR->node->now();
  1134. _netconfFailure = NETCONF_FAILURE_NONE;
  1135. _externalConfig(&ctmp);
  1136. const bool oldPortInitialized = _portInitialized;
  1137. _portInitialized = true;
  1138. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(oldPortInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  1139. if (saveToDisk) {
  1140. char n[64];
  1141. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  1142. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  1143. if (nconf.toDictionary(d,false))
  1144. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  1145. }
  1146. return 2; // OK and configuration has changed
  1147. } catch ( ... ) {
  1148. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  1149. }
  1150. return 0;
  1151. }
  1152. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  1153. {
  1154. // assumes _lock is locked
  1155. ec->nwid = _id;
  1156. ec->mac = _mac.toInt();
  1157. if (_config)
  1158. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  1159. else ec->name[0] = (char)0;
  1160. ec->status = _status();
  1161. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  1162. ec->mtu = ZT_IF_MTU;
  1163. ec->physicalMtu = ZT_UDP_DEFAULT_PAYLOAD_MTU - (ZT_PACKET_IDX_PAYLOAD + 16);
  1164. ec->dhcp = 0;
  1165. std::vector<Address> ab(_config.activeBridges());
  1166. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  1167. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  1168. ec->portError = _portError;
  1169. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  1170. ec->assignedAddressCount = 0;
  1171. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  1172. if (i < _config.staticIpCount) {
  1173. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  1174. ++ec->assignedAddressCount;
  1175. } else {
  1176. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  1177. }
  1178. }
  1179. ec->routeCount = 0;
  1180. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  1181. if (i < _config.routeCount) {
  1182. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  1183. ++ec->routeCount;
  1184. } else {
  1185. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  1186. }
  1187. }
  1188. }
  1189. void Network::_sendUpdatesToMembers(const MulticastGroup *const newMulticastGroup)
  1190. {
  1191. // Assumes _lock is locked
  1192. const uint64_t now = RR->node->now();
  1193. std::vector<MulticastGroup> groups;
  1194. if (newMulticastGroup)
  1195. groups.push_back(*newMulticastGroup);
  1196. else groups = _allMulticastGroups();
  1197. if ((newMulticastGroup)||((now - _lastAnnouncedMulticastGroupsUpstream) >= ZT_MULTICAST_ANNOUNCE_PERIOD)) {
  1198. if (!newMulticastGroup)
  1199. _lastAnnouncedMulticastGroupsUpstream = now;
  1200. // Announce multicast groups to upstream peers (roots, etc.) and also send
  1201. // them our COM so that MULTICAST_GATHER can be authenticated properly.
  1202. const std::vector<Address> upstreams(RR->topology->upstreamAddresses());
  1203. for(std::vector<Address>::const_iterator a(upstreams.begin());a!=upstreams.end();++a) {
  1204. if (_config.com) {
  1205. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1206. _config.com.serialize(outp);
  1207. outp.append((uint8_t)0x00);
  1208. RR->sw->send(outp,true);
  1209. }
  1210. _announceMulticastGroupsTo(*a,groups);
  1211. }
  1212. // Also announce to controller, and send COM to simplify and generalize behavior even though in theory it does not need it
  1213. const Address c(controller());
  1214. if ( (std::find(upstreams.begin(),upstreams.end(),c) == upstreams.end()) && (!_memberships.contains(c)) ) {
  1215. if (_config.com) {
  1216. Packet outp(c,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1217. _config.com.serialize(outp);
  1218. outp.append((uint8_t)0x00);
  1219. RR->sw->send(outp,true);
  1220. }
  1221. _announceMulticastGroupsTo(c,groups);
  1222. }
  1223. }
  1224. // Make sure that all "network anchors" have Membership records so we will
  1225. // push multicasts to them. Note that _membership() also does this but in a
  1226. // piecemeal on-demand fashion.
  1227. const std::vector<Address> anchors(_config.anchors());
  1228. for(std::vector<Address>::const_iterator a(anchors.begin());a!=anchors.end();++a)
  1229. _membership(*a);
  1230. // Send credentials and multicast LIKEs to members, upstreams, and controller
  1231. {
  1232. Address *a = (Address *)0;
  1233. Membership *m = (Membership *)0;
  1234. Hashtable<Address,Membership>::Iterator i(_memberships);
  1235. while (i.next(a,m)) {
  1236. m->pushCredentials(RR,now,*a,_config,-1,false);
  1237. if ( ((newMulticastGroup)||(m->shouldLikeMulticasts(now))) && (m->isAllowedOnNetwork(_config)) ) {
  1238. if (!newMulticastGroup)
  1239. m->likingMulticasts(now);
  1240. _announceMulticastGroupsTo(*a,groups);
  1241. }
  1242. }
  1243. }
  1244. }
  1245. void Network::_announceMulticastGroupsTo(const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  1246. {
  1247. // Assumes _lock is locked
  1248. Packet outp(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1249. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  1250. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  1251. outp.compress();
  1252. RR->sw->send(outp,true);
  1253. outp.reset(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1254. }
  1255. // network ID, MAC, ADI
  1256. outp.append((uint64_t)_id);
  1257. mg->mac().appendTo(outp);
  1258. outp.append((uint32_t)mg->adi());
  1259. }
  1260. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  1261. outp.compress();
  1262. RR->sw->send(outp,true);
  1263. }
  1264. }
  1265. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  1266. {
  1267. // Assumes _lock is locked
  1268. std::vector<MulticastGroup> mgs;
  1269. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  1270. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  1271. _multicastGroupsBehindMe.appendKeys(mgs);
  1272. if ((_config)&&(_config.enableBroadcast()))
  1273. mgs.push_back(Network::BROADCAST);
  1274. std::sort(mgs.begin(),mgs.end());
  1275. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  1276. return mgs;
  1277. }
  1278. Membership &Network::_membership(const Address &a)
  1279. {
  1280. // assumes _lock is locked
  1281. return _memberships[a];
  1282. }
  1283. } // namespace ZeroTier