Network.cpp 56 KB

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