Network.cpp 56 KB

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