Network.cpp 57 KB

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