Network.cpp 66 KB

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