Network.cpp 57 KB

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