Network.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  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. // IPv6 NDP requires special handling, since the src and dest IPs in the packet are empty or link-local.
  497. unsigned int pos = 0,proto = 0;
  498. if ( (frameLen >= (40 + 8 + 16)) && (frameData[6] == 0x3a) && ((frameData[40] == 0x87)||(frameData[40] == 0x88)) ) {
  499. if (frameData[40] == 0x87) {
  500. // Neighbor solicitations contain no reliable source address, so we implement a small
  501. // hack by considering them authenticated. Otherwise you would pretty much have to do
  502. // this manually in the rule set for IPv6 to work at all.
  503. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  504. } else {
  505. // Neighbor advertisements on the other hand can absolutely be authenticated.
  506. src.set((const void *)(frameData + 40 + 8),16,0);
  507. }
  508. } else {
  509. // Other IPv6 packets can be handled normally
  510. src.set((const void *)(frameData + 8),16,0);
  511. }
  512. } else if ((etherType == ZT_ETHERTYPE_ARP)&&(frameLen >= 28)) {
  513. src.set((const void *)(frameData + 14),4,0);
  514. }
  515. if (inbound) {
  516. if (membership) {
  517. if ((src)&&(membership->hasCertificateOfOwnershipFor(nconf,src)))
  518. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  519. if (membership->hasCertificateOfOwnershipFor(nconf,macSource))
  520. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_MAC_AUTHENTICATED;
  521. }
  522. } else {
  523. for(unsigned int i=0;i<nconf.certificateOfOwnershipCount;++i) {
  524. if ((src)&&(nconf.certificatesOfOwnership[i].owns(src)))
  525. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  526. if (nconf.certificatesOfOwnership[i].owns(macSource))
  527. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_MAC_AUTHENTICATED;
  528. }
  529. }
  530. }
  531. cf |= ownershipVerificationMask;
  532. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  533. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  534. cf |= (uint64_t)frameData[headerLen + 13];
  535. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  536. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  537. unsigned int pos = 0,proto = 0;
  538. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  539. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  540. cf |= (uint64_t)frameData[pos + 13];
  541. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  542. }
  543. }
  544. }
  545. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics) != 0);
  546. 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);
  547. } break;
  548. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  549. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  550. 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);
  551. break;
  552. case ZT_NETWORK_RULE_MATCH_RANDOM:
  553. thisRuleMatches = (uint8_t)((uint32_t)(RR->node->prng() & 0xffffffffULL) <= rules[rn].v.randomProbability);
  554. FILTER_TRACE("%u %s %c -> %u",rn,_rtn(rt),(((rules[rn].t & 0x80) != 0) ? '!' : '='),(unsigned int)thisRuleMatches);
  555. break;
  556. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  557. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  558. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  559. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  560. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL: {
  561. const Tag *const localTag = std::lower_bound(&(nconf.tags[0]),&(nconf.tags[nconf.tagCount]),rules[rn].v.tag.id,Tag::IdComparePredicate());
  562. if ((localTag != &(nconf.tags[nconf.tagCount]))&&(localTag->id() == rules[rn].v.tag.id)) {
  563. const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
  564. if (remoteTag) {
  565. const uint32_t ltv = localTag->value();
  566. const uint32_t rtv = remoteTag->value();
  567. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE) {
  568. const uint32_t diff = (ltv > rtv) ? (ltv - rtv) : (rtv - ltv);
  569. thisRuleMatches = (uint8_t)(diff <= rules[rn].v.tag.value);
  570. 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);
  571. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  572. thisRuleMatches = (uint8_t)((ltv & rtv) == rules[rn].v.tag.value);
  573. 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);
  574. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  575. thisRuleMatches = (uint8_t)((ltv | rtv) == rules[rn].v.tag.value);
  576. 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);
  577. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  578. thisRuleMatches = (uint8_t)((ltv ^ rtv) == rules[rn].v.tag.value);
  579. 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);
  580. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_EQUAL) {
  581. thisRuleMatches = (uint8_t)((ltv == rules[rn].v.tag.value)&&(rtv == rules[rn].v.tag.value));
  582. 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);
  583. } else { // sanity check, can't really happen
  584. thisRuleMatches = 0;
  585. }
  586. } else {
  587. if ((inbound)&&(!superAccept)) {
  588. thisRuleMatches = 0;
  589. 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);
  590. } else {
  591. thisRuleMatches = 1;
  592. 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);
  593. }
  594. }
  595. } else {
  596. thisRuleMatches = 0;
  597. 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);
  598. }
  599. } break;
  600. // The result of an unsupported MATCH is configurable at the network
  601. // level via a flag.
  602. default:
  603. thisRuleMatches = (uint8_t)((nconf.flags & ZT_NETWORKCONFIG_FLAG_RULES_RESULT_OF_UNSUPPORTED_MATCH) != 0);
  604. break;
  605. }
  606. if ((rules[rn].t & 0x40))
  607. thisSetMatches |= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
  608. else thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
  609. }
  610. return DOZTFILTER_NO_MATCH;
  611. }
  612. } // anonymous namespace
  613. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  614. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  615. RR(renv),
  616. _uPtr(uptr),
  617. _id(nwid),
  618. _lastAnnouncedMulticastGroupsUpstream(0),
  619. _mac(renv->identity.address(),nwid),
  620. _portInitialized(false),
  621. _lastConfigUpdate(0),
  622. _destroyed(false),
  623. _netconfFailure(NETCONF_FAILURE_NONE),
  624. _portError(0)
  625. {
  626. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i)
  627. _incomingConfigChunks[i].ts = 0;
  628. char confn[128];
  629. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  630. bool gotConf = false;
  631. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  632. NetworkConfig *nconf = new NetworkConfig();
  633. try {
  634. std::string conf(RR->node->dataStoreGet(confn));
  635. if (conf.length()) {
  636. dconf->load(conf.c_str());
  637. if (nconf->fromDictionary(*dconf)) {
  638. this->setConfiguration(*nconf,false);
  639. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  640. gotConf = true;
  641. }
  642. }
  643. } catch ( ... ) {} // ignore invalids, we'll re-request
  644. delete nconf;
  645. delete dconf;
  646. if (!gotConf) {
  647. // Save a one-byte CR to persist membership while we request a real netconf
  648. RR->node->dataStorePut(confn,"\n",1,false);
  649. }
  650. if (!_portInitialized) {
  651. ZT_VirtualNetworkConfig ctmp;
  652. _externalConfig(&ctmp);
  653. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  654. _portInitialized = true;
  655. }
  656. }
  657. Network::~Network()
  658. {
  659. ZT_VirtualNetworkConfig ctmp;
  660. _externalConfig(&ctmp);
  661. char n[128];
  662. if (_destroyed) {
  663. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  664. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  665. RR->node->dataStoreDelete(n);
  666. } else {
  667. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  668. }
  669. }
  670. bool Network::filterOutgoingPacket(
  671. const bool noTee,
  672. const Address &ztSource,
  673. const Address &ztDest,
  674. const MAC &macSource,
  675. const MAC &macDest,
  676. const uint8_t *frameData,
  677. const unsigned int frameLen,
  678. const unsigned int etherType,
  679. const unsigned int vlanId)
  680. {
  681. const uint64_t now = RR->node->now();
  682. Address ztFinalDest(ztDest);
  683. int localCapabilityIndex = -1;
  684. bool accept = false;
  685. Mutex::Lock _l(_lock);
  686. Membership *const membership = (ztDest) ? _memberships.get(ztDest) : (Membership *)0;
  687. Address cc;
  688. unsigned int ccLength = 0;
  689. bool ccWatch = false;
  690. switch(_doZtFilter(RR,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch)) {
  691. case DOZTFILTER_NO_MATCH:
  692. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  693. ztFinalDest = ztDest; // sanity check, shouldn't be possible if there was no match
  694. Address cc2;
  695. unsigned int ccLength2 = 0;
  696. bool ccWatch2 = false;
  697. 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)) {
  698. case DOZTFILTER_NO_MATCH:
  699. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  700. break;
  701. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  702. case DOZTFILTER_ACCEPT:
  703. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  704. localCapabilityIndex = (int)c;
  705. accept = true;
  706. if ((!noTee)&&(cc2)) {
  707. Membership &m2 = _membership(cc2);
  708. m2.pushCredentials(RR,now,cc2,_config,localCapabilityIndex,false);
  709. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  710. outp.append(_id);
  711. outp.append((uint8_t)(ccWatch2 ? 0x16 : 0x02));
  712. macDest.appendTo(outp);
  713. macSource.appendTo(outp);
  714. outp.append((uint16_t)etherType);
  715. outp.append(frameData,ccLength2);
  716. outp.compress();
  717. RR->sw->send(outp,true);
  718. }
  719. break;
  720. }
  721. if (accept)
  722. break;
  723. }
  724. break;
  725. case DOZTFILTER_DROP:
  726. return false;
  727. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  728. case DOZTFILTER_ACCEPT:
  729. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side
  730. accept = true;
  731. break;
  732. }
  733. if (accept) {
  734. if (membership)
  735. membership->pushCredentials(RR,now,ztDest,_config,localCapabilityIndex,false);
  736. if ((!noTee)&&(cc)) {
  737. Membership &m2 = _membership(cc);
  738. m2.pushCredentials(RR,now,cc,_config,localCapabilityIndex,false);
  739. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  740. outp.append(_id);
  741. outp.append((uint8_t)(ccWatch ? 0x16 : 0x02));
  742. macDest.appendTo(outp);
  743. macSource.appendTo(outp);
  744. outp.append((uint16_t)etherType);
  745. outp.append(frameData,ccLength);
  746. outp.compress();
  747. RR->sw->send(outp,true);
  748. }
  749. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  750. Membership &m2 = _membership(ztFinalDest);
  751. m2.pushCredentials(RR,now,ztFinalDest,_config,localCapabilityIndex,false);
  752. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  753. outp.append(_id);
  754. outp.append((uint8_t)0x04);
  755. macDest.appendTo(outp);
  756. macSource.appendTo(outp);
  757. outp.append((uint16_t)etherType);
  758. outp.append(frameData,frameLen);
  759. outp.compress();
  760. RR->sw->send(outp,true);
  761. return false; // DROP locally, since we redirected
  762. } else {
  763. return true;
  764. }
  765. } else {
  766. return false;
  767. }
  768. }
  769. int Network::filterIncomingPacket(
  770. const SharedPtr<Peer> &sourcePeer,
  771. const Address &ztDest,
  772. const MAC &macSource,
  773. const MAC &macDest,
  774. const uint8_t *frameData,
  775. const unsigned int frameLen,
  776. const unsigned int etherType,
  777. const unsigned int vlanId)
  778. {
  779. Address ztFinalDest(ztDest);
  780. int accept = 0;
  781. Mutex::Lock _l(_lock);
  782. Membership &membership = _membership(sourcePeer->address());
  783. Address cc;
  784. unsigned int ccLength = 0;
  785. bool ccWatch = false;
  786. switch (_doZtFilter(RR,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch)) {
  787. case DOZTFILTER_NO_MATCH: {
  788. Membership::CapabilityIterator mci(membership,_config);
  789. const Capability *c;
  790. while ((c = mci.next())) {
  791. ztFinalDest = ztDest; // sanity check, should be unmodified if there was no match
  792. Address cc2;
  793. unsigned int ccLength2 = 0;
  794. bool ccWatch2 = false;
  795. switch(_doZtFilter(RR,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),cc2,ccLength2,ccWatch2)) {
  796. case DOZTFILTER_NO_MATCH:
  797. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  798. break;
  799. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
  800. case DOZTFILTER_ACCEPT:
  801. accept = 1; // ACCEPT
  802. break;
  803. case DOZTFILTER_SUPER_ACCEPT:
  804. accept = 2; // super-ACCEPT
  805. break;
  806. }
  807. if (accept) {
  808. if (cc2) {
  809. _membership(cc2).pushCredentials(RR,RR->node->now(),cc2,_config,-1,false);
  810. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  811. outp.append(_id);
  812. outp.append((uint8_t)(ccWatch2 ? 0x1c : 0x08));
  813. macDest.appendTo(outp);
  814. macSource.appendTo(outp);
  815. outp.append((uint16_t)etherType);
  816. outp.append(frameData,ccLength2);
  817. outp.compress();
  818. RR->sw->send(outp,true);
  819. }
  820. break;
  821. }
  822. }
  823. } break;
  824. case DOZTFILTER_DROP:
  825. return 0; // DROP
  826. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  827. case DOZTFILTER_ACCEPT:
  828. accept = 1; // ACCEPT
  829. break;
  830. case DOZTFILTER_SUPER_ACCEPT:
  831. accept = 2; // super-ACCEPT
  832. break;
  833. }
  834. if (accept) {
  835. if (cc) {
  836. _membership(cc).pushCredentials(RR,RR->node->now(),cc,_config,-1,false);
  837. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  838. outp.append(_id);
  839. outp.append((uint8_t)(ccWatch ? 0x1c : 0x08));
  840. macDest.appendTo(outp);
  841. macSource.appendTo(outp);
  842. outp.append((uint16_t)etherType);
  843. outp.append(frameData,ccLength);
  844. outp.compress();
  845. RR->sw->send(outp,true);
  846. }
  847. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  848. _membership(ztFinalDest).pushCredentials(RR,RR->node->now(),ztFinalDest,_config,-1,false);
  849. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  850. outp.append(_id);
  851. outp.append((uint8_t)0x0a);
  852. macDest.appendTo(outp);
  853. macSource.appendTo(outp);
  854. outp.append((uint16_t)etherType);
  855. outp.append(frameData,frameLen);
  856. outp.compress();
  857. RR->sw->send(outp,true);
  858. return 0; // DROP locally, since we redirected
  859. }
  860. }
  861. return accept;
  862. }
  863. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  864. {
  865. Mutex::Lock _l(_lock);
  866. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  867. return true;
  868. else if (includeBridgedGroups)
  869. return _multicastGroupsBehindMe.contains(mg);
  870. return false;
  871. }
  872. void Network::multicastSubscribe(const MulticastGroup &mg)
  873. {
  874. Mutex::Lock _l(_lock);
  875. if (!std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg)) {
  876. _myMulticastGroups.insert(std::upper_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg),mg);
  877. _sendUpdatesToMembers(&mg);
  878. }
  879. }
  880. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  881. {
  882. Mutex::Lock _l(_lock);
  883. std::vector<MulticastGroup>::iterator i(std::lower_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg));
  884. if ( (i != _myMulticastGroups.end()) && (*i == mg) )
  885. _myMulticastGroups.erase(i);
  886. }
  887. uint64_t Network::handleConfigChunk(const uint64_t packetId,const Address &source,const Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &chunk,unsigned int ptr)
  888. {
  889. const unsigned int start = ptr;
  890. ptr += 8; // skip network ID, which is already obviously known
  891. const unsigned int chunkLen = chunk.at<uint16_t>(ptr); ptr += 2;
  892. const void *chunkData = chunk.field(ptr,chunkLen); ptr += chunkLen;
  893. NetworkConfig *nc = (NetworkConfig *)0;
  894. uint64_t configUpdateId;
  895. {
  896. Mutex::Lock _l(_lock);
  897. _IncomingConfigChunk *c = (_IncomingConfigChunk *)0;
  898. uint64_t chunkId = 0;
  899. unsigned long totalLength,chunkIndex;
  900. if (ptr < chunk.size()) {
  901. const bool fastPropagate = ((chunk[ptr++] & 0x01) != 0);
  902. configUpdateId = chunk.at<uint64_t>(ptr); ptr += 8;
  903. totalLength = chunk.at<uint32_t>(ptr); ptr += 4;
  904. chunkIndex = chunk.at<uint32_t>(ptr); ptr += 4;
  905. if (((chunkIndex + chunkLen) > totalLength)||(totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)) { // >= since we need room for a null at the end
  906. TRACE("discarded chunk from %s: invalid length or length overflow",source.toString().c_str());
  907. return 0;
  908. }
  909. if ((chunk[ptr] != 1)||(chunk.at<uint16_t>(ptr + 1) != ZT_C25519_SIGNATURE_LEN)) {
  910. TRACE("discarded chunk from %s: unrecognized signature type",source.toString().c_str());
  911. return 0;
  912. }
  913. const uint8_t *sig = reinterpret_cast<const uint8_t *>(chunk.field(ptr + 3,ZT_C25519_SIGNATURE_LEN));
  914. // We can use the signature, which is unique per chunk, to get a per-chunk ID for local deduplication use
  915. for(unsigned int i=0;i<16;++i)
  916. reinterpret_cast<uint8_t *>(&chunkId)[i & 7] ^= sig[i];
  917. // Find existing or new slot for this update and check if this is a duplicate chunk
  918. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  919. if (_incomingConfigChunks[i].updateId == configUpdateId) {
  920. c = &(_incomingConfigChunks[i]);
  921. for(unsigned long j=0;j<c->haveChunks;++j) {
  922. if (c->haveChunkIds[j] == chunkId)
  923. return 0;
  924. }
  925. break;
  926. } else if ((!c)||(_incomingConfigChunks[i].ts < c->ts)) {
  927. c = &(_incomingConfigChunks[i]);
  928. }
  929. }
  930. // If it's not a duplicate, check chunk signature
  931. const Identity controllerId(RR->topology->getIdentity(controller()));
  932. if (!controllerId) { // we should always have the controller identity by now, otherwise how would we have queried it the first time?
  933. TRACE("unable to verify chunk from %s: don't have controller identity",source.toString().c_str());
  934. return 0;
  935. }
  936. if (!controllerId.verify(chunk.field(start,ptr - start),ptr - start,sig,ZT_C25519_SIGNATURE_LEN)) {
  937. TRACE("discarded chunk from %s: signature check failed",source.toString().c_str());
  938. return 0;
  939. }
  940. #ifdef ZT_ENABLE_CLUSTER
  941. if ((source)&&(RR->cluster))
  942. RR->cluster->broadcastNetworkConfigChunk(chunk.field(start,chunk.size() - start),chunk.size() - start);
  943. #endif
  944. // New properly verified chunks can be flooded "virally" through the network
  945. if (fastPropagate) {
  946. Address *a = (Address *)0;
  947. Membership *m = (Membership *)0;
  948. Hashtable<Address,Membership>::Iterator i(_memberships);
  949. while (i.next(a,m)) {
  950. if ((*a != source)&&(*a != controller())) {
  951. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CONFIG);
  952. outp.append(reinterpret_cast<const uint8_t *>(chunk.data()) + start,chunk.size() - start);
  953. RR->sw->send(outp,true);
  954. }
  955. }
  956. }
  957. } else if ((source == controller())||(!source)) { // since old chunks aren't signed, only accept from controller itself (or via cluster backplane)
  958. // Legacy support for OK(NETWORK_CONFIG_REQUEST) from older controllers
  959. chunkId = packetId;
  960. configUpdateId = chunkId;
  961. totalLength = chunkLen;
  962. chunkIndex = 0;
  963. if (totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)
  964. return 0;
  965. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  966. if ((!c)||(_incomingConfigChunks[i].ts < c->ts))
  967. c = &(_incomingConfigChunks[i]);
  968. }
  969. #ifdef ZT_ENABLE_CLUSTER
  970. if ((source)&&(RR->cluster))
  971. RR->cluster->broadcastNetworkConfigChunk(chunk.field(start,chunk.size() - start),chunk.size() - start);
  972. #endif
  973. } else {
  974. TRACE("discarded single-chunk unsigned legacy config: this is only allowed if the sender is the controller itself");
  975. return 0;
  976. }
  977. ++c->ts; // newer is higher, that's all we need
  978. if (c->updateId != configUpdateId) {
  979. c->updateId = configUpdateId;
  980. c->haveChunks = 0;
  981. c->haveBytes = 0;
  982. }
  983. if (c->haveChunks >= ZT_NETWORK_MAX_UPDATE_CHUNKS)
  984. return false;
  985. c->haveChunkIds[c->haveChunks++] = chunkId;
  986. memcpy(c->data.unsafeData() + chunkIndex,chunkData,chunkLen);
  987. c->haveBytes += chunkLen;
  988. if (c->haveBytes == totalLength) {
  989. c->data.unsafeData()[c->haveBytes] = (char)0; // ensure null terminated
  990. nc = new NetworkConfig();
  991. try {
  992. if (!nc->fromDictionary(c->data)) {
  993. delete nc;
  994. nc = (NetworkConfig *)0;
  995. }
  996. } catch ( ... ) {
  997. delete nc;
  998. nc = (NetworkConfig *)0;
  999. }
  1000. }
  1001. }
  1002. if (nc) {
  1003. this->setConfiguration(*nc,true);
  1004. delete nc;
  1005. return configUpdateId;
  1006. } else {
  1007. return 0;
  1008. }
  1009. return 0;
  1010. }
  1011. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  1012. {
  1013. // _lock is NOT locked when this is called
  1014. try {
  1015. if ((nconf.issuedTo != RR->identity.address())||(nconf.networkId != _id))
  1016. return 0;
  1017. if (_config == nconf)
  1018. return 1; // OK config, but duplicate of what we already have
  1019. ZT_VirtualNetworkConfig ctmp;
  1020. bool oldPortInitialized;
  1021. {
  1022. Mutex::Lock _l(_lock);
  1023. _config = nconf;
  1024. _lastConfigUpdate = RR->node->now();
  1025. _netconfFailure = NETCONF_FAILURE_NONE;
  1026. oldPortInitialized = _portInitialized;
  1027. _portInitialized = true;
  1028. _externalConfig(&ctmp);
  1029. }
  1030. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(oldPortInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  1031. if (saveToDisk) {
  1032. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *d = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  1033. try {
  1034. char n[64];
  1035. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  1036. if (nconf.toDictionary(*d,false))
  1037. RR->node->dataStorePut(n,(const void *)d->data(),d->sizeBytes(),true);
  1038. } catch ( ... ) {}
  1039. delete d;
  1040. }
  1041. return 2; // OK and configuration has changed
  1042. } catch ( ... ) {
  1043. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  1044. }
  1045. return 0;
  1046. }
  1047. void Network::requestConfiguration()
  1048. {
  1049. /* ZeroTier addresses can't begin with 0xff, so this is used to mark controllerless
  1050. * network IDs. Controllerless network IDs only support unicast IPv6 using the 6plane
  1051. * addressing scheme and have the following format: 0xffSSSSEEEE000000 where SSSS
  1052. * is the 16-bit starting IP port range allowed and EEEE is the 16-bit ending IP port
  1053. * range allowed. Remaining digits are reserved for future use and must be zero. */
  1054. if ((_id >> 56) == 0xff) {
  1055. const uint16_t startPortRange = (uint16_t)((_id >> 40) & 0xffff);
  1056. const uint16_t endPortRange = (uint16_t)((_id >> 24) & 0xffff);
  1057. if (((_id & 0xffffff) == 0)&&(endPortRange >= startPortRange)) {
  1058. NetworkConfig *const nconf = new NetworkConfig();
  1059. nconf->networkId = _id;
  1060. nconf->timestamp = RR->node->now();
  1061. nconf->credentialTimeMaxDelta = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1062. nconf->revision = 1;
  1063. nconf->issuedTo = RR->identity.address();
  1064. nconf->flags = ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1065. nconf->staticIpCount = 1;
  1066. nconf->ruleCount = 14;
  1067. nconf->staticIps[0] = InetAddress::makeIpv66plane(_id,RR->identity.address().toInt());
  1068. // Drop everything but IPv6
  1069. nconf->rules[0].t = (uint8_t)ZT_NETWORK_RULE_MATCH_ETHERTYPE | 0x80; // NOT
  1070. nconf->rules[0].v.etherType = 0x86dd; // IPv6
  1071. nconf->rules[1].t = (uint8_t)ZT_NETWORK_RULE_ACTION_DROP;
  1072. // Allow ICMPv6
  1073. nconf->rules[2].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  1074. nconf->rules[2].v.ipProtocol = 0x3a; // ICMPv6
  1075. nconf->rules[3].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1076. // Allow destination ports within range
  1077. nconf->rules[4].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  1078. nconf->rules[4].v.ipProtocol = 0x11; // UDP
  1079. nconf->rules[5].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL | 0x40; // OR
  1080. nconf->rules[5].v.ipProtocol = 0x06; // TCP
  1081. nconf->rules[6].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  1082. nconf->rules[6].v.port[0] = startPortRange;
  1083. nconf->rules[6].v.port[1] = endPortRange;
  1084. nconf->rules[7].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1085. // Allow non-SYN TCP packets to permit non-connection-initiating traffic
  1086. nconf->rules[8].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS | 0x80; // NOT
  1087. nconf->rules[8].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_SYN;
  1088. nconf->rules[9].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1089. // Also allow SYN+ACK which are replies to SYN
  1090. nconf->rules[10].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  1091. nconf->rules[10].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_SYN;
  1092. nconf->rules[11].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  1093. nconf->rules[11].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_ACK;
  1094. nconf->rules[12].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1095. nconf->rules[13].t = (uint8_t)ZT_NETWORK_RULE_ACTION_DROP;
  1096. nconf->type = ZT_NETWORK_TYPE_PUBLIC;
  1097. Utils::snprintf(nconf->name,sizeof(nconf->name),"adhoc-%.04x-%.04x",(int)startPortRange,(int)endPortRange);
  1098. this->setConfiguration(*nconf,false);
  1099. delete nconf;
  1100. } else {
  1101. this->setNotFound();
  1102. }
  1103. return;
  1104. }
  1105. const Address ctrl(controller());
  1106. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  1107. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  1108. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_VENDOR,(uint64_t)ZT_VENDOR_ZEROTIER);
  1109. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  1110. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  1111. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  1112. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  1113. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  1114. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  1115. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  1116. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  1117. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  1118. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,(uint64_t)ZT_RULES_ENGINE_REVISION);
  1119. if (ctrl == RR->identity.address()) {
  1120. if (RR->localNetworkController) {
  1121. RR->localNetworkController->request(_id,InetAddress(),0xffffffffffffffffULL,RR->identity,rmd);
  1122. } else {
  1123. this->setNotFound();
  1124. }
  1125. return;
  1126. }
  1127. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,ctrl.toString().c_str());
  1128. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  1129. outp.append((uint64_t)_id);
  1130. const unsigned int rmdSize = rmd.sizeBytes();
  1131. outp.append((uint16_t)rmdSize);
  1132. outp.append((const void *)rmd.data(),rmdSize);
  1133. if (_config) {
  1134. outp.append((uint64_t)_config.revision);
  1135. outp.append((uint64_t)_config.timestamp);
  1136. } else {
  1137. outp.append((unsigned char)0,16);
  1138. }
  1139. RR->node->expectReplyTo(outp.packetId());
  1140. outp.compress();
  1141. RR->sw->send(outp,true);
  1142. }
  1143. bool Network::gate(const SharedPtr<Peer> &peer)
  1144. {
  1145. const uint64_t now = RR->node->now();
  1146. Mutex::Lock _l(_lock);
  1147. try {
  1148. if (_config) {
  1149. Membership *m = _memberships.get(peer->address());
  1150. if ( (_config.isPublic()) || ((m)&&(m->isAllowedOnNetwork(_config))) ) {
  1151. if (!m)
  1152. m = &(_membership(peer->address()));
  1153. if (m->shouldLikeMulticasts(now)) {
  1154. m->pushCredentials(RR,now,peer->address(),_config,-1,false);
  1155. _announceMulticastGroupsTo(peer->address(),_allMulticastGroups());
  1156. m->likingMulticasts(now);
  1157. }
  1158. return true;
  1159. }
  1160. }
  1161. } catch ( ... ) {
  1162. TRACE("gate() check failed for peer %s: unexpected exception",peer->address().toString().c_str());
  1163. }
  1164. return false;
  1165. }
  1166. void Network::clean()
  1167. {
  1168. const uint64_t now = RR->node->now();
  1169. Mutex::Lock _l(_lock);
  1170. if (_destroyed)
  1171. return;
  1172. {
  1173. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  1174. MulticastGroup *mg = (MulticastGroup *)0;
  1175. uint64_t *ts = (uint64_t *)0;
  1176. while (i.next(mg,ts)) {
  1177. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  1178. _multicastGroupsBehindMe.erase(*mg);
  1179. }
  1180. }
  1181. {
  1182. Address *a = (Address *)0;
  1183. Membership *m = (Membership *)0;
  1184. Hashtable<Address,Membership>::Iterator i(_memberships);
  1185. while (i.next(a,m)) {
  1186. if (!RR->topology->getPeerNoCache(*a))
  1187. _memberships.erase(*a);
  1188. }
  1189. }
  1190. }
  1191. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  1192. {
  1193. Mutex::Lock _l(_lock);
  1194. _remoteBridgeRoutes[mac] = addr;
  1195. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  1196. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  1197. Hashtable< Address,unsigned long > counts;
  1198. Address maxAddr;
  1199. unsigned long maxCount = 0;
  1200. MAC *m = (MAC *)0;
  1201. Address *a = (Address *)0;
  1202. // Find the address responsible for the most entries
  1203. {
  1204. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1205. while (i.next(m,a)) {
  1206. const unsigned long c = ++counts[*a];
  1207. if (c > maxCount) {
  1208. maxCount = c;
  1209. maxAddr = *a;
  1210. }
  1211. }
  1212. }
  1213. // Kill this address from our table, since it's most likely spamming us
  1214. {
  1215. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1216. while (i.next(m,a)) {
  1217. if (*a == maxAddr)
  1218. _remoteBridgeRoutes.erase(*m);
  1219. }
  1220. }
  1221. }
  1222. }
  1223. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  1224. {
  1225. Mutex::Lock _l(_lock);
  1226. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  1227. _multicastGroupsBehindMe.set(mg,now);
  1228. if (tmp != _multicastGroupsBehindMe.size())
  1229. _sendUpdatesToMembers(&mg);
  1230. }
  1231. Membership::AddCredentialResult Network::addCredential(const CertificateOfMembership &com)
  1232. {
  1233. if (com.networkId() != _id)
  1234. return Membership::ADD_REJECTED;
  1235. const Address a(com.issuedTo());
  1236. Mutex::Lock _l(_lock);
  1237. Membership &m = _membership(a);
  1238. const Membership::AddCredentialResult result = m.addCredential(RR,_config,com);
  1239. if ((result == Membership::ADD_ACCEPTED_NEW)||(result == Membership::ADD_ACCEPTED_REDUNDANT)) {
  1240. m.pushCredentials(RR,RR->node->now(),a,_config,-1,false);
  1241. RR->mc->addCredential(com,true);
  1242. }
  1243. return result;
  1244. }
  1245. Membership::AddCredentialResult Network::addCredential(const Address &sentFrom,const Revocation &rev)
  1246. {
  1247. if (rev.networkId() != _id)
  1248. return Membership::ADD_REJECTED;
  1249. Mutex::Lock _l(_lock);
  1250. Membership &m = _membership(rev.target());
  1251. const Membership::AddCredentialResult result = m.addCredential(RR,_config,rev);
  1252. if ((result == Membership::ADD_ACCEPTED_NEW)&&(rev.fastPropagate())) {
  1253. Address *a = (Address *)0;
  1254. Membership *m = (Membership *)0;
  1255. Hashtable<Address,Membership>::Iterator i(_memberships);
  1256. while (i.next(a,m)) {
  1257. if ((*a != sentFrom)&&(*a != rev.signer())) {
  1258. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1259. outp.append((uint8_t)0x00); // no COM
  1260. outp.append((uint16_t)0); // no capabilities
  1261. outp.append((uint16_t)0); // no tags
  1262. outp.append((uint16_t)1); // one revocation!
  1263. rev.serialize(outp);
  1264. RR->sw->send(outp,true);
  1265. }
  1266. }
  1267. }
  1268. return result;
  1269. }
  1270. void Network::destroy()
  1271. {
  1272. Mutex::Lock _l(_lock);
  1273. _destroyed = true;
  1274. }
  1275. ZT_VirtualNetworkStatus Network::_status() const
  1276. {
  1277. // assumes _lock is locked
  1278. if (_portError)
  1279. return ZT_NETWORK_STATUS_PORT_ERROR;
  1280. switch(_netconfFailure) {
  1281. case NETCONF_FAILURE_ACCESS_DENIED:
  1282. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  1283. case NETCONF_FAILURE_NOT_FOUND:
  1284. return ZT_NETWORK_STATUS_NOT_FOUND;
  1285. case NETCONF_FAILURE_NONE:
  1286. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  1287. default:
  1288. return ZT_NETWORK_STATUS_PORT_ERROR;
  1289. }
  1290. }
  1291. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  1292. {
  1293. // assumes _lock is locked
  1294. ec->nwid = _id;
  1295. ec->mac = _mac.toInt();
  1296. if (_config)
  1297. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  1298. else ec->name[0] = (char)0;
  1299. ec->status = _status();
  1300. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  1301. ec->mtu = ZT_IF_MTU;
  1302. ec->physicalMtu = ZT_UDP_DEFAULT_PAYLOAD_MTU - (ZT_PACKET_IDX_PAYLOAD + 16);
  1303. ec->dhcp = 0;
  1304. std::vector<Address> ab(_config.activeBridges());
  1305. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  1306. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  1307. ec->portError = _portError;
  1308. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  1309. ec->assignedAddressCount = 0;
  1310. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  1311. if (i < _config.staticIpCount) {
  1312. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  1313. ++ec->assignedAddressCount;
  1314. } else {
  1315. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  1316. }
  1317. }
  1318. ec->routeCount = 0;
  1319. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  1320. if (i < _config.routeCount) {
  1321. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  1322. ++ec->routeCount;
  1323. } else {
  1324. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  1325. }
  1326. }
  1327. }
  1328. void Network::_sendUpdatesToMembers(const MulticastGroup *const newMulticastGroup)
  1329. {
  1330. // Assumes _lock is locked
  1331. const uint64_t now = RR->node->now();
  1332. std::vector<MulticastGroup> groups;
  1333. if (newMulticastGroup)
  1334. groups.push_back(*newMulticastGroup);
  1335. else groups = _allMulticastGroups();
  1336. if ((newMulticastGroup)||((now - _lastAnnouncedMulticastGroupsUpstream) >= ZT_MULTICAST_ANNOUNCE_PERIOD)) {
  1337. if (!newMulticastGroup)
  1338. _lastAnnouncedMulticastGroupsUpstream = now;
  1339. // Announce multicast groups to upstream peers (roots, etc.) and also send
  1340. // them our COM so that MULTICAST_GATHER can be authenticated properly.
  1341. const std::vector<Address> upstreams(RR->topology->upstreamAddresses());
  1342. for(std::vector<Address>::const_iterator a(upstreams.begin());a!=upstreams.end();++a) {
  1343. if (_config.com) {
  1344. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1345. _config.com.serialize(outp);
  1346. outp.append((uint8_t)0x00);
  1347. RR->sw->send(outp,true);
  1348. }
  1349. _announceMulticastGroupsTo(*a,groups);
  1350. }
  1351. // Also announce to controller, and send COM to simplify and generalize behavior even though in theory it does not need it
  1352. const Address c(controller());
  1353. if ( (std::find(upstreams.begin(),upstreams.end(),c) == upstreams.end()) && (!_memberships.contains(c)) ) {
  1354. if (_config.com) {
  1355. Packet outp(c,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1356. _config.com.serialize(outp);
  1357. outp.append((uint8_t)0x00);
  1358. RR->sw->send(outp,true);
  1359. }
  1360. _announceMulticastGroupsTo(c,groups);
  1361. }
  1362. }
  1363. // Make sure that all "network anchors" have Membership records so we will
  1364. // push multicasts to them. Note that _membership() also does this but in a
  1365. // piecemeal on-demand fashion.
  1366. const std::vector<Address> anchors(_config.anchors());
  1367. for(std::vector<Address>::const_iterator a(anchors.begin());a!=anchors.end();++a)
  1368. _membership(*a);
  1369. // Send credentials and multicast LIKEs to members, upstreams, and controller
  1370. {
  1371. Address *a = (Address *)0;
  1372. Membership *m = (Membership *)0;
  1373. Hashtable<Address,Membership>::Iterator i(_memberships);
  1374. while (i.next(a,m)) {
  1375. m->pushCredentials(RR,now,*a,_config,-1,false);
  1376. if ( ((newMulticastGroup)||(m->shouldLikeMulticasts(now))) && (m->isAllowedOnNetwork(_config)) ) {
  1377. if (!newMulticastGroup)
  1378. m->likingMulticasts(now);
  1379. _announceMulticastGroupsTo(*a,groups);
  1380. }
  1381. }
  1382. }
  1383. }
  1384. void Network::_announceMulticastGroupsTo(const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  1385. {
  1386. // Assumes _lock is locked
  1387. Packet outp(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1388. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  1389. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  1390. outp.compress();
  1391. RR->sw->send(outp,true);
  1392. outp.reset(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1393. }
  1394. // network ID, MAC, ADI
  1395. outp.append((uint64_t)_id);
  1396. mg->mac().appendTo(outp);
  1397. outp.append((uint32_t)mg->adi());
  1398. }
  1399. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  1400. outp.compress();
  1401. RR->sw->send(outp,true);
  1402. }
  1403. }
  1404. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  1405. {
  1406. // Assumes _lock is locked
  1407. std::vector<MulticastGroup> mgs;
  1408. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  1409. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  1410. _multicastGroupsBehindMe.appendKeys(mgs);
  1411. if ((_config)&&(_config.enableBroadcast()))
  1412. mgs.push_back(Network::BROADCAST);
  1413. std::sort(mgs.begin(),mgs.end());
  1414. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  1415. return mgs;
  1416. }
  1417. Membership &Network::_membership(const Address &a)
  1418. {
  1419. // assumes _lock is locked
  1420. return _memberships[a];
  1421. }
  1422. } // namespace ZeroTier