Network.cpp 67 KB

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