Network.cpp 57 KB

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