Network.cpp 56 KB

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