Network.cpp 67 KB

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