Network.cpp 60 KB

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