Network.cpp 67 KB

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