Network.cpp 57 KB

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