Network.cpp 56 KB

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