Network.cpp 62 KB

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