Network.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include <math.h>
  17. #include "../include/ZeroTierDebug.h"
  18. #include "ECC.hpp"
  19. #include "Constants.hpp"
  20. #include "../version.h"
  21. #include "Network.hpp"
  22. #include "RuntimeEnvironment.hpp"
  23. #include "MAC.hpp"
  24. #include "Address.hpp"
  25. #include "InetAddress.hpp"
  26. #include "Switch.hpp"
  27. #include "Buffer.hpp"
  28. #include "Packet.hpp"
  29. #include "NetworkController.hpp"
  30. #include "Node.hpp"
  31. #include "Peer.hpp"
  32. #include "Trace.hpp"
  33. #include "Metrics.hpp"
  34. #include <set>
  35. namespace ZeroTier {
  36. namespace {
  37. // Returns true if packet appears valid; pos and proto will be set
  38. static inline bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  39. {
  40. if (frameLen < 40) {
  41. return false;
  42. }
  43. pos = 40;
  44. proto = frameData[6];
  45. while (pos <= frameLen) {
  46. switch(proto) {
  47. case 0: // hop-by-hop options
  48. case 43: // routing
  49. case 60: // destination options
  50. case 135: // mobility options
  51. if ((pos + 8) > frameLen) {
  52. return false; // invalid!
  53. }
  54. proto = frameData[pos];
  55. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  56. break;
  57. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  58. //case 50:
  59. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  60. default:
  61. return true;
  62. }
  63. }
  64. return false; // overflow == invalid
  65. }
  66. enum _doZtFilterResult
  67. {
  68. DOZTFILTER_NO_MATCH,
  69. DOZTFILTER_DROP,
  70. DOZTFILTER_REDIRECT,
  71. DOZTFILTER_ACCEPT,
  72. DOZTFILTER_SUPER_ACCEPT
  73. };
  74. static _doZtFilterResult _doZtFilter(
  75. const RuntimeEnvironment *RR,
  76. Trace::RuleResultLog &rrl,
  77. const NetworkConfig &nconf,
  78. const Membership *membership, // can be NULL
  79. const bool inbound,
  80. const Address &ztSource,
  81. Address &ztDest, // MUTABLE -- is changed on REDIRECT actions
  82. const MAC &macSource,
  83. const MAC &macDest,
  84. const uint8_t *const frameData,
  85. const unsigned int frameLen,
  86. const unsigned int etherType,
  87. const unsigned int vlanId,
  88. const ZT_VirtualNetworkRule *rules, // cannot be NULL
  89. const unsigned int ruleCount,
  90. Address &cc, // MUTABLE -- set to TEE destination if TEE action is taken or left alone otherwise
  91. unsigned int &ccLength, // MUTABLE -- set to length of packet payload to TEE
  92. bool &ccWatch, // MUTABLE -- set to true for WATCH target as opposed to normal TEE
  93. uint8_t &qosBucket) // MUTABLE -- set to the value of the argument provided to PRIORITY
  94. {
  95. // Set to true if we are a TEE/REDIRECT/WATCH target
  96. bool superAccept = false;
  97. // The default match state for each set of entries starts as 'true' since an
  98. // ACTION with no MATCH entries preceding it is always taken.
  99. uint8_t thisSetMatches = 1;
  100. uint8_t skipDrop = 0;
  101. rrl.clear();
  102. // uncomment for easier debugging fprintf
  103. // if (!ztDest) { return DOZTFILTER_ACCEPT; }
  104. #ifdef ZT_TRACE
  105. //char buf[40], buf2[40];
  106. //fprintf(stderr, "\nsrc %s dest %s inbound: %d ethertype %u", ztSource.toString(buf), ztDest.toString(buf2), inbound, etherType);
  107. #endif
  108. for(unsigned int rn=0;rn<ruleCount;++rn) {
  109. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x3f);
  110. #ifdef ZT_TRACE
  111. //fprintf(stderr, "\n%02u %02d", rn, rt);
  112. #endif
  113. // First check if this is an ACTION
  114. if ((unsigned int)rt <= (unsigned int)ZT_NETWORK_RULE_ACTION__MAX_ID) {
  115. if (thisSetMatches) {
  116. switch(rt) {
  117. case ZT_NETWORK_RULE_ACTION_PRIORITY:
  118. qosBucket = (rules[rn].v.qosBucket <= 8) ? rules[rn].v.qosBucket : 4; // 4 = default bucket (no priority)
  119. return DOZTFILTER_ACCEPT;
  120. case ZT_NETWORK_RULE_ACTION_DROP: {
  121. if (!!skipDrop) {
  122. #ifdef ZT_TRACE
  123. //fprintf(stderr, "\tskip Drop");
  124. #endif
  125. skipDrop = 0; continue;
  126. }
  127. #ifdef ZT_TRACE
  128. //fprintf(stderr, "\tDrop\n");
  129. #endif
  130. return DOZTFILTER_DROP;
  131. }
  132. case ZT_NETWORK_RULE_ACTION_ACCEPT: {
  133. #ifdef ZT_TRACE
  134. //fprintf(stderr, "\tAccept\n");
  135. #endif
  136. return (superAccept ? DOZTFILTER_SUPER_ACCEPT : DOZTFILTER_ACCEPT); // match, accept packet
  137. }
  138. // These are initially handled together since preliminary logic is common
  139. case ZT_NETWORK_RULE_ACTION_TEE:
  140. case ZT_NETWORK_RULE_ACTION_WATCH:
  141. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  142. const Address fwdAddr(rules[rn].v.fwd.address);
  143. if (fwdAddr == ztSource) {
  144. // Skip as no-op since source is target
  145. } else if (fwdAddr == RR->identity.address()) {
  146. if (inbound) {
  147. return DOZTFILTER_SUPER_ACCEPT;
  148. } else {
  149. }
  150. } else if (fwdAddr == ztDest) {
  151. } else {
  152. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  153. ztDest = fwdAddr;
  154. return DOZTFILTER_REDIRECT;
  155. } else {
  156. cc = fwdAddr;
  157. ccLength = (rules[rn].v.fwd.length != 0) ? ((frameLen < (unsigned int)rules[rn].v.fwd.length) ? frameLen : (unsigned int)rules[rn].v.fwd.length) : frameLen;
  158. ccWatch = (rt == ZT_NETWORK_RULE_ACTION_WATCH);
  159. }
  160. }
  161. } continue;
  162. case ZT_NETWORK_RULE_ACTION_BREAK:
  163. return DOZTFILTER_NO_MATCH;
  164. // Unrecognized ACTIONs are ignored as no-ops
  165. default:
  166. continue;
  167. }
  168. } else {
  169. // If this is an incoming packet and we are a TEE or REDIRECT target, we should
  170. // super-accept if we accept at all. This will cause us to accept redirected or
  171. // tee'd packets in spite of MAC and ZT addressing checks.
  172. if (inbound) {
  173. switch(rt) {
  174. case ZT_NETWORK_RULE_ACTION_TEE:
  175. case ZT_NETWORK_RULE_ACTION_WATCH:
  176. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  177. if (RR->identity.address() == rules[rn].v.fwd.address) {
  178. superAccept = true;
  179. }
  180. break;
  181. default:
  182. break;
  183. }
  184. }
  185. thisSetMatches = 1; // reset to default true for next batch of entries
  186. continue;
  187. }
  188. }
  189. // Circuit breaker: no need to evaluate an AND if the set's match state
  190. // is currently false since anything AND false is false.
  191. if ((!thisSetMatches)&&(!(rules[rn].t & 0x40))) {
  192. rrl.logSkipped(rn,thisSetMatches);
  193. continue;
  194. }
  195. // If this was not an ACTION evaluate next MATCH and update thisSetMatches with (AND [result])
  196. uint8_t thisRuleMatches = 0;
  197. uint64_t ownershipVerificationMask = 1; // this magic value means it hasn't been computed yet -- this is done lazily the first time it's needed
  198. uint8_t hardYes = (rules[rn].t >> 7) ^ 1; // XOR with the NOT bit of the rule
  199. uint8_t hardNo = (rules[rn].t >> 7) ^ 0;
  200. switch(rt) {
  201. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  202. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  203. break;
  204. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  205. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  206. break;
  207. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  208. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  209. break;
  210. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  211. // NOT SUPPORTED YET
  212. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  213. break;
  214. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  215. // NOT SUPPORTED YET
  216. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  217. break;
  218. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  219. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macSource);
  220. break;
  221. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  222. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macDest);
  223. break;
  224. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  225. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  226. 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)));
  227. } else {
  228. thisRuleMatches = hardNo;
  229. }
  230. break;
  231. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  232. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  233. 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)));
  234. } else {
  235. thisRuleMatches = hardNo;
  236. }
  237. break;
  238. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  239. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  240. 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)));
  241. } else {
  242. thisRuleMatches = hardNo;
  243. }
  244. break;
  245. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  246. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  247. 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)));
  248. } else {
  249. thisRuleMatches = hardNo;
  250. }
  251. break;
  252. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  253. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  254. const uint8_t tosMasked = frameData[1] & rules[rn].v.ipTos.mask;
  255. thisRuleMatches = (uint8_t)((tosMasked >= rules[rn].v.ipTos.value[0])&&(tosMasked <= rules[rn].v.ipTos.value[1]));
  256. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  257. const uint8_t tosMasked = (((frameData[0] << 4) & 0xf0) | ((frameData[1] >> 4) & 0x0f)) & rules[rn].v.ipTos.mask;
  258. thisRuleMatches = (uint8_t)((tosMasked >= rules[rn].v.ipTos.value[0])&&(tosMasked <= rules[rn].v.ipTos.value[1]));
  259. } else {
  260. thisRuleMatches = hardNo;
  261. }
  262. break;
  263. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  264. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  265. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
  266. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  267. unsigned int pos = 0,proto = 0;
  268. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  269. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
  270. } else {
  271. thisRuleMatches = hardNo;
  272. }
  273. } else {
  274. thisRuleMatches = hardNo;
  275. }
  276. break;
  277. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  278. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  279. break;
  280. case ZT_NETWORK_RULE_MATCH_ICMP:
  281. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  282. if (frameData[9] == 0x01) { // IP protocol == ICMP
  283. const unsigned int ihl = (frameData[0] & 0xf) * 4;
  284. if (frameLen >= (ihl + 2)) {
  285. if (rules[rn].v.icmp.type == frameData[ihl]) {
  286. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  287. thisRuleMatches = (uint8_t)(frameData[ihl+1] == rules[rn].v.icmp.code);
  288. } else {
  289. thisRuleMatches = hardYes;
  290. }
  291. } else {
  292. thisRuleMatches = hardNo;
  293. }
  294. } else {
  295. thisRuleMatches = hardNo;
  296. }
  297. } else {
  298. thisRuleMatches = hardNo;
  299. }
  300. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  301. unsigned int pos = 0,proto = 0;
  302. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  303. if ((proto == 0x3a)&&(frameLen >= (pos+2))) {
  304. if (rules[rn].v.icmp.type == frameData[pos]) {
  305. if ((rules[rn].v.icmp.flags & 0x01) != 0) {
  306. thisRuleMatches = (uint8_t)(frameData[pos+1] == rules[rn].v.icmp.code);
  307. } else {
  308. thisRuleMatches = hardYes;
  309. }
  310. } else {
  311. thisRuleMatches = hardNo;
  312. }
  313. } else {
  314. thisRuleMatches = hardNo;
  315. }
  316. } else {
  317. thisRuleMatches = hardNo;
  318. }
  319. } else {
  320. thisRuleMatches = hardNo;
  321. }
  322. break;
  323. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  324. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  325. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  326. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  327. int p = -1;
  328. switch(frameData[9]) { // IP protocol number
  329. // All these start with 16-bit source and destination port in that order
  330. case 0x06: // TCP
  331. case 0x11: // UDP
  332. case 0x84: // SCTP
  333. case 0x88: // UDPLite
  334. if (frameLen > (headerLen + 4)) {
  335. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  336. p = (int)frameData[pos++] << 8;
  337. p |= (int)frameData[pos];
  338. }
  339. break;
  340. }
  341. thisRuleMatches = (p >= 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  342. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  343. unsigned int pos = 0,proto = 0;
  344. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  345. int p = -1;
  346. switch(proto) { // IP protocol number
  347. // All these start with 16-bit source and destination port in that order
  348. case 0x06: // TCP
  349. case 0x11: // UDP
  350. case 0x84: // SCTP
  351. case 0x88: // UDPLite
  352. if (frameLen > (pos + 4)) {
  353. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) {
  354. pos += 2;
  355. }
  356. p = (int)frameData[pos++] << 8;
  357. p |= (int)frameData[pos];
  358. }
  359. break;
  360. }
  361. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  362. } else {
  363. thisRuleMatches = hardNo;
  364. }
  365. } else {
  366. thisRuleMatches = hardNo;
  367. }
  368. break;
  369. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  370. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  371. if (macDest.isMulticast()) {
  372. cf |= ZT_RULE_PACKET_CHARACTERISTICS_MULTICAST;
  373. }
  374. if (macDest.isBroadcast()) {
  375. cf |= ZT_RULE_PACKET_CHARACTERISTICS_BROADCAST;
  376. }
  377. if (ownershipVerificationMask == 1) {
  378. ownershipVerificationMask = 0;
  379. InetAddress src;
  380. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  381. src.set((const void *)(frameData + 12),4,0);
  382. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  383. // IPv6 NDP requires special handling, since the src and dest IPs in the packet are empty or link-local.
  384. if ( (frameLen >= (40 + 8 + 16)) && (frameData[6] == 0x3a) && ((frameData[40] == 0x87)||(frameData[40] == 0x88)) ) {
  385. if (frameData[40] == 0x87) {
  386. // Neighbor solicitations contain no reliable source address, so we implement a small
  387. // hack by considering them authenticated. Otherwise you would pretty much have to do
  388. // this manually in the rule set for IPv6 to work at all.
  389. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  390. } else {
  391. // Neighbor advertisements on the other hand can absolutely be authenticated.
  392. src.set((const void *)(frameData + 40 + 8),16,0);
  393. }
  394. } else {
  395. // Other IPv6 packets can be handled normally
  396. src.set((const void *)(frameData + 8),16,0);
  397. }
  398. } else if ((etherType == ZT_ETHERTYPE_ARP)&&(frameLen >= 28)) {
  399. src.set((const void *)(frameData + 14),4,0);
  400. }
  401. if (inbound) {
  402. if (membership) {
  403. if ((src)&&(membership->hasCertificateOfOwnershipFor<InetAddress>(nconf,src))) {
  404. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  405. }
  406. if (membership->hasCertificateOfOwnershipFor<MAC>(nconf,macSource)) {
  407. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_MAC_AUTHENTICATED;
  408. }
  409. }
  410. } else {
  411. for(unsigned int i=0;i<nconf.certificateOfOwnershipCount;++i) {
  412. if ((src)&&(nconf.certificatesOfOwnership[i].owns(src))) {
  413. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
  414. }
  415. if (nconf.certificatesOfOwnership[i].owns(macSource)) {
  416. ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_MAC_AUTHENTICATED;
  417. }
  418. }
  419. }
  420. }
  421. cf |= ownershipVerificationMask;
  422. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  423. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  424. cf |= (uint64_t)frameData[headerLen + 13];
  425. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  426. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  427. unsigned int pos = 0,proto = 0;
  428. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  429. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  430. cf |= (uint64_t)frameData[pos + 13];
  431. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  432. }
  433. }
  434. }
  435. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics) != 0);
  436. } break;
  437. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  438. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  439. break;
  440. case ZT_NETWORK_RULE_MATCH_RANDOM:
  441. thisRuleMatches = (uint8_t)((uint32_t)(RR->node->prng() & 0xffffffffULL) <= rules[rn].v.randomProbability);
  442. break;
  443. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  444. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  445. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  446. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  447. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL: {
  448. const Tag *const localTag = std::lower_bound(&(nconf.tags[0]),&(nconf.tags[nconf.tagCount]),rules[rn].v.tag.id,Tag::IdComparePredicate());
  449. if ((localTag != &(nconf.tags[nconf.tagCount]))&&(localTag->id() == rules[rn].v.tag.id)) {
  450. const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
  451. #ifdef ZT_TRACE
  452. /*fprintf(stderr, "\tlocal tag [%u: %u] remote tag [%u: %u] match [%u]",
  453. !!localTag ? localTag->id() : 0,
  454. !!localTag ? localTag->value() : 0,
  455. !!remoteTag ? remoteTag->id() : 0,
  456. !!remoteTag ? remoteTag->value() : 0,
  457. thisRuleMatches);*/
  458. #endif
  459. if (remoteTag) {
  460. const uint32_t ltv = localTag->value();
  461. const uint32_t rtv = remoteTag->value();
  462. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE) {
  463. const uint32_t diff = (ltv > rtv) ? (ltv - rtv) : (rtv - ltv);
  464. thisRuleMatches = (uint8_t)(diff <= rules[rn].v.tag.value);
  465. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  466. thisRuleMatches = (uint8_t)((ltv & rtv) == rules[rn].v.tag.value);
  467. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  468. thisRuleMatches = (uint8_t)((ltv | rtv) == rules[rn].v.tag.value);
  469. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  470. thisRuleMatches = (uint8_t)((ltv ^ rtv) == rules[rn].v.tag.value);
  471. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_EQUAL) {
  472. thisRuleMatches = (uint8_t)((ltv == rules[rn].v.tag.value)&&(rtv == rules[rn].v.tag.value));
  473. } else { // sanity check, can't really happen
  474. thisRuleMatches = hardNo;
  475. }
  476. } else {
  477. if ((inbound)&&(!superAccept)) {
  478. thisRuleMatches = hardNo;
  479. #ifdef ZT_TRACE
  480. //fprintf(stderr, "\tinbound ");
  481. #endif
  482. } else {
  483. // Outbound side is not strict since if we have to match both tags and
  484. // we are sending a first packet to a recipient, we probably do not know
  485. // about their tags yet. They will filter on inbound and we will filter
  486. // once we get their tag. If we are a tee/redirect target we are also
  487. // not strict since we likely do not have these tags.
  488. skipDrop = 1;
  489. thisRuleMatches = hardYes;
  490. #ifdef ZT_TRACE
  491. //fprintf(stderr, "\toutbound ");
  492. #endif
  493. }
  494. }
  495. } else {
  496. thisRuleMatches = hardNo;
  497. }
  498. } break;
  499. case ZT_NETWORK_RULE_MATCH_TAG_SENDER:
  500. case ZT_NETWORK_RULE_MATCH_TAG_RECEIVER: {
  501. const Tag *const localTag = std::lower_bound(&(nconf.tags[0]),&(nconf.tags[nconf.tagCount]),rules[rn].v.tag.id,Tag::IdComparePredicate());
  502. #ifdef ZT_TRACE
  503. /*const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
  504. fprintf(stderr, "\tlocal tag [%u: %u] remote tag [%u: %u] match [%u]",
  505. !!localTag ? localTag->id() : 0,
  506. !!localTag ? localTag->value() : 0,
  507. !!remoteTag ? remoteTag->id() : 0,
  508. !!remoteTag ? remoteTag->value() : 0,
  509. thisRuleMatches);*/
  510. #endif
  511. if (superAccept) {
  512. skipDrop = 1;
  513. thisRuleMatches = hardYes;
  514. } else if ( ((rt == ZT_NETWORK_RULE_MATCH_TAG_SENDER)&&(inbound)) || ((rt == ZT_NETWORK_RULE_MATCH_TAG_RECEIVER)&&(!inbound)) ) {
  515. const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
  516. if (remoteTag) {
  517. thisRuleMatches = (uint8_t)(remoteTag->value() == rules[rn].v.tag.value);
  518. } else {
  519. if (rt == ZT_NETWORK_RULE_MATCH_TAG_RECEIVER) {
  520. // If we are checking the receiver and this is an outbound packet, we
  521. // can't be strict since we may not yet know the receiver's tag.
  522. skipDrop = 1;
  523. thisRuleMatches = hardYes;
  524. } else {
  525. thisRuleMatches = hardNo;
  526. }
  527. }
  528. } else { // sender and outbound or receiver and inbound
  529. if ((localTag != &(nconf.tags[nconf.tagCount]))&&(localTag->id() == rules[rn].v.tag.id)) {
  530. thisRuleMatches = (uint8_t)(localTag->value() == rules[rn].v.tag.value);
  531. } else {
  532. thisRuleMatches = hardNo;
  533. }
  534. }
  535. } break;
  536. case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE: {
  537. uint64_t integer = 0;
  538. const unsigned int bits = (rules[rn].v.intRange.format & 63) + 1;
  539. const unsigned int bytes = ((bits + 8 - 1) / 8); // integer ceiling of division by 8
  540. if ((rules[rn].v.intRange.format & 0x80) == 0) {
  541. // Big-endian
  542. unsigned int idx = rules[rn].v.intRange.idx + (8 - bytes);
  543. const unsigned int eof = idx + bytes;
  544. if (eof <= frameLen) {
  545. while (idx < eof) {
  546. integer <<= 8;
  547. integer |= frameData[idx++];
  548. }
  549. }
  550. integer &= 0xffffffffffffffffULL >> (64 - bits);
  551. } else {
  552. // Little-endian
  553. unsigned int idx = rules[rn].v.intRange.idx;
  554. const unsigned int eof = idx + bytes;
  555. if (eof <= frameLen) {
  556. while (idx < eof) {
  557. integer >>= 8;
  558. integer |= ((uint64_t)frameData[idx++]) << 56;
  559. }
  560. }
  561. integer >>= (64 - bits);
  562. }
  563. thisRuleMatches = (uint8_t)((integer >= rules[rn].v.intRange.start)&&(integer <= (rules[rn].v.intRange.start + (uint64_t)rules[rn].v.intRange.end)));
  564. } break;
  565. // The result of an unsupported MATCH is configurable at the network
  566. // level via a flag.
  567. default:
  568. thisRuleMatches = (uint8_t)((nconf.flags & ZT_NETWORKCONFIG_FLAG_RULES_RESULT_OF_UNSUPPORTED_MATCH) != 0);
  569. break;
  570. }
  571. rrl.log(rn,thisRuleMatches,thisSetMatches);
  572. if ((rules[rn].t & 0x40)) {
  573. thisSetMatches |= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
  574. } else {
  575. thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
  576. }
  577. }
  578. return DOZTFILTER_NO_MATCH;
  579. }
  580. } // anonymous namespace
  581. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  582. Network::Network(const RuntimeEnvironment *renv,void *tPtr,uint64_t nwid,void *uptr,const NetworkConfig *nconf) :
  583. RR(renv),
  584. _uPtr(uptr),
  585. _id(nwid),
  586. _nwidStr(OSUtils::networkIDStr(nwid)),
  587. _lastAnnouncedMulticastGroupsUpstream(0),
  588. _mac(renv->identity.address(),nwid),
  589. _portInitialized(false),
  590. _lastConfigUpdate(0),
  591. _destroyed(false),
  592. _netconfFailure(NETCONF_FAILURE_NONE),
  593. _portError(0),
  594. _num_multicast_groups{Metrics::network_num_multicast_groups.Add({{"network_id", _nwidStr}})},
  595. _incoming_packets_accepted{Metrics::network_packets.Add({{"direction","rx"},{"network_id", _nwidStr},{"accepted","yes"}})},
  596. _incoming_packets_dropped{Metrics::network_packets.Add({{"direction","rx"},{"network_id", _nwidStr},{"accepted","no"}})},
  597. _outgoing_packets_accepted{Metrics::network_packets.Add({{"direction","tx"},{"network_id", _nwidStr},{"accepted","yes"}})},
  598. _outgoing_packets_dropped{Metrics::network_packets.Add({{"direction","tx"},{"network_id", _nwidStr},{"accepted","no"}})}
  599. {
  600. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  601. _incomingConfigChunks[i].ts = 0;
  602. }
  603. if (nconf) {
  604. this->setConfiguration(tPtr,*nconf,false);
  605. _lastConfigUpdate = 0; // still want to re-request since it's likely outdated
  606. } else {
  607. uint64_t tmp[2];
  608. tmp[0] = nwid;
  609. tmp[1] = 0;
  610. bool got = false;
  611. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  612. try {
  613. int n = RR->node->stateObjectGet(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp,dict->unsafeData(),ZT_NETWORKCONFIG_DICT_CAPACITY - 1);
  614. if (n > 1) {
  615. NetworkConfig *nconf = new NetworkConfig();
  616. try {
  617. if (nconf->fromDictionary(*dict)) {
  618. this->setConfiguration(tPtr,*nconf,false);
  619. _lastConfigUpdate = 0; // still want to re-request an update since it's likely outdated
  620. got = true;
  621. }
  622. } catch ( ... ) {}
  623. delete nconf;
  624. }
  625. } catch ( ... ) {}
  626. delete dict;
  627. if (!got) {
  628. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp,"\n",1);
  629. }
  630. }
  631. if (!_portInitialized) {
  632. ZT_VirtualNetworkConfig ctmp;
  633. memset(&ctmp, 0, sizeof(ZT_VirtualNetworkConfig));
  634. _externalConfig(&ctmp);
  635. _portError = RR->node->configureVirtualNetworkPort(tPtr,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  636. _portInitialized = true;
  637. }
  638. Metrics::network_num_joined++;
  639. }
  640. Network::~Network()
  641. {
  642. ZT_VirtualNetworkConfig ctmp;
  643. _externalConfig(&ctmp);
  644. Metrics::network_num_joined--;
  645. if (_destroyed) {
  646. // This is done in Node::leave() so we can pass tPtr properly
  647. //RR->node->configureVirtualNetworkPort((void *)0,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  648. } else {
  649. RR->node->configureVirtualNetworkPort((void *)0,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  650. }
  651. }
  652. bool Network::filterOutgoingPacket(
  653. void *tPtr,
  654. const bool noTee,
  655. const Address &ztSource,
  656. const Address &ztDest,
  657. const MAC &macSource,
  658. const MAC &macDest,
  659. const uint8_t *frameData,
  660. const unsigned int frameLen,
  661. const unsigned int etherType,
  662. const unsigned int vlanId,
  663. uint8_t &qosBucket)
  664. {
  665. Address ztFinalDest(ztDest);
  666. int localCapabilityIndex = -1;
  667. int accept = 0;
  668. Trace::RuleResultLog rrl,crrl;
  669. Address cc;
  670. unsigned int ccLength = 0;
  671. bool ccWatch = false;
  672. Mutex::Lock _l(_lock);
  673. Membership *const membership = (ztDest) ? _memberships.get(ztDest) : (Membership *)0;
  674. switch(_doZtFilter(RR,rrl,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch,qosBucket)) {
  675. case DOZTFILTER_NO_MATCH: {
  676. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  677. ztFinalDest = ztDest; // sanity check, shouldn't be possible if there was no match
  678. Address cc2;
  679. unsigned int ccLength2 = 0;
  680. bool ccWatch2 = false;
  681. switch (_doZtFilter(RR,crrl,_config,membership,false,ztSource,ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.capabilities[c].rules(),_config.capabilities[c].ruleCount(),cc2,ccLength2,ccWatch2,qosBucket)) {
  682. case DOZTFILTER_NO_MATCH:
  683. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  684. break;
  685. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  686. case DOZTFILTER_ACCEPT:
  687. case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side in capabilities
  688. localCapabilityIndex = (int)c;
  689. accept = 1;
  690. if ((!noTee)&&(cc2)) {
  691. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  692. outp.append(_id);
  693. outp.append((uint8_t)(ccWatch2 ? 0x16 : 0x02));
  694. macDest.appendTo(outp);
  695. macSource.appendTo(outp);
  696. outp.append((uint16_t)etherType);
  697. outp.append(frameData,ccLength2);
  698. outp.compress();
  699. RR->sw->send(tPtr,outp,true);
  700. }
  701. break;
  702. }
  703. if (accept) {
  704. break;
  705. }
  706. }
  707. } break;
  708. case DOZTFILTER_DROP:
  709. if (_config.remoteTraceTarget) {
  710. RR->t->networkFilter(tPtr,*this,rrl,(Trace::RuleResultLog *)0,(Capability *)0,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,noTee,false,0);
  711. }
  712. return false;
  713. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  714. case DOZTFILTER_ACCEPT:
  715. accept = 1;
  716. break;
  717. case DOZTFILTER_SUPER_ACCEPT:
  718. accept = 2;
  719. break;
  720. }
  721. if (accept) {
  722. _outgoing_packets_accepted++;
  723. if ((!noTee)&&(cc)) {
  724. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  725. outp.append(_id);
  726. outp.append((uint8_t)(ccWatch ? 0x16 : 0x02));
  727. macDest.appendTo(outp);
  728. macSource.appendTo(outp);
  729. outp.append((uint16_t)etherType);
  730. outp.append(frameData,ccLength);
  731. outp.compress();
  732. RR->sw->send(tPtr,outp,true);
  733. }
  734. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  735. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  736. outp.append(_id);
  737. outp.append((uint8_t)0x04);
  738. macDest.appendTo(outp);
  739. macSource.appendTo(outp);
  740. outp.append((uint16_t)etherType);
  741. outp.append(frameData,frameLen);
  742. outp.compress();
  743. RR->sw->send(tPtr,outp,true);
  744. if (_config.remoteTraceTarget) {
  745. RR->t->networkFilter(tPtr,*this,rrl,(localCapabilityIndex >= 0) ? &crrl : (Trace::RuleResultLog *)0,(localCapabilityIndex >= 0) ? &(_config.capabilities[localCapabilityIndex]) : (Capability *)0,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,noTee,false,0);
  746. }
  747. return false; // DROP locally, since we redirected
  748. } else {
  749. if (_config.remoteTraceTarget) {
  750. RR->t->networkFilter(tPtr,*this,rrl,(localCapabilityIndex >= 0) ? &crrl : (Trace::RuleResultLog *)0,(localCapabilityIndex >= 0) ? &(_config.capabilities[localCapabilityIndex]) : (Capability *)0,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,noTee,false,1);
  751. }
  752. return true;
  753. }
  754. } else {
  755. _outgoing_packets_dropped++;
  756. if (_config.remoteTraceTarget) {
  757. RR->t->networkFilter(tPtr,*this,rrl,(localCapabilityIndex >= 0) ? &crrl : (Trace::RuleResultLog *)0,(localCapabilityIndex >= 0) ? &(_config.capabilities[localCapabilityIndex]) : (Capability *)0,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,noTee,false,0);
  758. }
  759. return false;
  760. }
  761. }
  762. int Network::filterIncomingPacket(
  763. void *tPtr,
  764. const SharedPtr<Peer> &sourcePeer,
  765. const Address &ztDest,
  766. const MAC &macSource,
  767. const MAC &macDest,
  768. const uint8_t *frameData,
  769. const unsigned int frameLen,
  770. const unsigned int etherType,
  771. const unsigned int vlanId)
  772. {
  773. Address ztFinalDest(ztDest);
  774. Trace::RuleResultLog rrl,crrl;
  775. int accept = 0;
  776. Address cc;
  777. unsigned int ccLength = 0;
  778. bool ccWatch = false;
  779. const Capability *c = (Capability *)0;
  780. uint8_t qosBucket = 255; // For incoming packets this is a dummy value
  781. Mutex::Lock _l(_lock);
  782. Membership &membership = _membership(sourcePeer->address());
  783. switch (_doZtFilter(RR,rrl,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,cc,ccLength,ccWatch,qosBucket)) {
  784. case DOZTFILTER_NO_MATCH: {
  785. Membership::CapabilityIterator mci(membership,_config);
  786. while ((c = mci.next())) {
  787. ztFinalDest = ztDest; // sanity check, should be unmodified if there was no match
  788. Address cc2;
  789. unsigned int ccLength2 = 0;
  790. bool ccWatch2 = false;
  791. switch(_doZtFilter(RR,crrl,_config,&membership,true,sourcePeer->address(),ztFinalDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),cc2,ccLength2,ccWatch2,qosBucket)) {
  792. case DOZTFILTER_NO_MATCH:
  793. case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
  794. break;
  795. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
  796. case DOZTFILTER_ACCEPT:
  797. accept = 1; // ACCEPT
  798. break;
  799. case DOZTFILTER_SUPER_ACCEPT:
  800. accept = 2; // super-ACCEPT
  801. break;
  802. }
  803. if (accept) {
  804. if (cc2) {
  805. Packet outp(cc2,RR->identity.address(),Packet::VERB_EXT_FRAME);
  806. outp.append(_id);
  807. outp.append((uint8_t)(ccWatch2 ? 0x1c : 0x08));
  808. macDest.appendTo(outp);
  809. macSource.appendTo(outp);
  810. outp.append((uint16_t)etherType);
  811. outp.append(frameData,ccLength2);
  812. outp.compress();
  813. RR->sw->send(tPtr,outp,true);
  814. }
  815. break;
  816. }
  817. }
  818. } break;
  819. case DOZTFILTER_DROP:
  820. if (_config.remoteTraceTarget) {
  821. RR->t->networkFilter(tPtr,*this,rrl,(Trace::RuleResultLog *)0,(Capability *)0,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,0);
  822. }
  823. return 0; // DROP
  824. case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
  825. case DOZTFILTER_ACCEPT:
  826. accept = 1; // ACCEPT
  827. break;
  828. case DOZTFILTER_SUPER_ACCEPT:
  829. accept = 2; // super-ACCEPT
  830. break;
  831. }
  832. if (accept) {
  833. _incoming_packets_accepted++;
  834. if (cc) {
  835. Packet outp(cc,RR->identity.address(),Packet::VERB_EXT_FRAME);
  836. outp.append(_id);
  837. outp.append((uint8_t)(ccWatch ? 0x1c : 0x08));
  838. macDest.appendTo(outp);
  839. macSource.appendTo(outp);
  840. outp.append((uint16_t)etherType);
  841. outp.append(frameData,ccLength);
  842. outp.compress();
  843. RR->sw->send(tPtr,outp,true);
  844. }
  845. if ((ztDest != ztFinalDest)&&(ztFinalDest)) {
  846. Packet outp(ztFinalDest,RR->identity.address(),Packet::VERB_EXT_FRAME);
  847. outp.append(_id);
  848. outp.append((uint8_t)0x0a);
  849. macDest.appendTo(outp);
  850. macSource.appendTo(outp);
  851. outp.append((uint16_t)etherType);
  852. outp.append(frameData,frameLen);
  853. outp.compress();
  854. RR->sw->send(tPtr,outp,true);
  855. if (_config.remoteTraceTarget) {
  856. RR->t->networkFilter(tPtr,*this,rrl,(c) ? &crrl : (Trace::RuleResultLog *)0,c,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,0);
  857. }
  858. return 0; // DROP locally, since we redirected
  859. }
  860. } else {
  861. _incoming_packets_dropped++;
  862. }
  863. if (_config.remoteTraceTarget) {
  864. RR->t->networkFilter(tPtr,*this,rrl,(c) ? &crrl : (Trace::RuleResultLog *)0,c,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,false,true,accept);
  865. }
  866. return accept;
  867. }
  868. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  869. {
  870. Mutex::Lock _l(_lock);
  871. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg)) {
  872. return true;
  873. } else if (includeBridgedGroups) {
  874. return _multicastGroupsBehindMe.contains(mg);
  875. }
  876. return false;
  877. }
  878. void Network::multicastSubscribe(void *tPtr,const MulticastGroup &mg)
  879. {
  880. Mutex::Lock _l(_lock);
  881. if (!std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg)) {
  882. _myMulticastGroups.insert(std::upper_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg),mg);
  883. _sendUpdatesToMembers(tPtr,&mg);
  884. _num_multicast_groups++;
  885. }
  886. }
  887. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  888. {
  889. Mutex::Lock _l(_lock);
  890. std::vector<MulticastGroup>::iterator i(std::lower_bound(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg));
  891. if ( (i != _myMulticastGroups.end()) && (*i == mg) ) {
  892. _myMulticastGroups.erase(i);
  893. _num_multicast_groups--;
  894. }
  895. }
  896. uint64_t Network::handleConfigChunk(void *tPtr,const uint64_t packetId,const Address &source,const Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &chunk,unsigned int ptr)
  897. {
  898. if (_destroyed) {
  899. return 0;
  900. }
  901. const unsigned int start = ptr;
  902. ptr += 8; // skip network ID, which is already obviously known
  903. const unsigned int chunkLen = chunk.at<uint16_t>(ptr);
  904. ptr += 2;
  905. const void *chunkData = chunk.field(ptr,chunkLen);
  906. ptr += chunkLen;
  907. NetworkConfig *nc = (NetworkConfig *)0;
  908. uint64_t configUpdateId;
  909. {
  910. Mutex::Lock _l(_lock);
  911. _IncomingConfigChunk *c = (_IncomingConfigChunk *)0;
  912. uint64_t chunkId = 0;
  913. unsigned long totalLength,chunkIndex;
  914. if (ptr < chunk.size()) {
  915. const bool fastPropagate = ((chunk[ptr++] & 0x01) != 0);
  916. configUpdateId = chunk.at<uint64_t>(ptr);
  917. ptr += 8;
  918. totalLength = chunk.at<uint32_t>(ptr);
  919. ptr += 4;
  920. chunkIndex = chunk.at<uint32_t>(ptr);
  921. ptr += 4;
  922. if (((chunkIndex + chunkLen) > totalLength)||(totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY)) { // >= since we need room for a null at the end
  923. return 0;
  924. }
  925. if ((chunk[ptr] != 1)||(chunk.at<uint16_t>(ptr + 1) != ZT_ECC_SIGNATURE_LEN)) {
  926. return 0;
  927. }
  928. const uint8_t *sig = reinterpret_cast<const uint8_t *>(chunk.field(ptr + 3,ZT_ECC_SIGNATURE_LEN));
  929. // We can use the signature, which is unique per chunk, to get a per-chunk ID for local deduplication use
  930. for(unsigned int i=0;i<16;++i) {
  931. reinterpret_cast<uint8_t *>(&chunkId)[i & 7] ^= sig[i];
  932. }
  933. // Find existing or new slot for this update and check if this is a duplicate chunk
  934. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  935. if (_incomingConfigChunks[i].updateId == configUpdateId) {
  936. c = &(_incomingConfigChunks[i]);
  937. for(unsigned long j=0;j<c->haveChunks;++j) {
  938. if (c->haveChunkIds[j] == chunkId) {
  939. return 0;
  940. }
  941. }
  942. break;
  943. } else if ((!c)||(_incomingConfigChunks[i].ts < c->ts)) {
  944. c = &(_incomingConfigChunks[i]);
  945. }
  946. }
  947. // If it's not a duplicate, check chunk signature
  948. const Identity controllerId(RR->topology->getIdentity(tPtr,controller()));
  949. if (!controllerId) { // we should always have the controller identity by now, otherwise how would we have queried it the first time?
  950. return 0;
  951. }
  952. if (!controllerId.verify(chunk.field(start,ptr - start),ptr - start,sig,ZT_ECC_SIGNATURE_LEN)) {
  953. return 0;
  954. }
  955. // New properly verified chunks can be flooded "virally" through the network
  956. if (fastPropagate) {
  957. Address *a = (Address *)0;
  958. Membership *m = (Membership *)0;
  959. Hashtable<Address,Membership>::Iterator i(_memberships);
  960. while (i.next(a,m)) {
  961. if ((*a != source)&&(*a != controller())) {
  962. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CONFIG);
  963. outp.append(reinterpret_cast<const uint8_t *>(chunk.data()) + start,chunk.size() - start);
  964. RR->sw->send(tPtr,outp,true);
  965. }
  966. }
  967. }
  968. } else if ((source == controller())||(!source)) { // since old chunks aren't signed, only accept from controller itself (or via cluster backplane)
  969. // Legacy support for OK(NETWORK_CONFIG_REQUEST) from older controllers
  970. chunkId = packetId;
  971. configUpdateId = chunkId;
  972. totalLength = chunkLen;
  973. chunkIndex = 0;
  974. if (totalLength >= ZT_NETWORKCONFIG_DICT_CAPACITY) {
  975. return 0;
  976. }
  977. for(int i=0;i<ZT_NETWORK_MAX_INCOMING_UPDATES;++i) {
  978. if ((!c)||(_incomingConfigChunks[i].ts < c->ts)) {
  979. c = &(_incomingConfigChunks[i]);
  980. }
  981. }
  982. } else {
  983. // Single-chunk unsigned legacy configs are only allowed from the controller itself
  984. return 0;
  985. }
  986. ++c->ts; // newer is higher, that's all we need
  987. if (c->updateId != configUpdateId) {
  988. c->updateId = configUpdateId;
  989. c->haveChunks = 0;
  990. c->haveBytes = 0;
  991. }
  992. if (c->haveChunks >= ZT_NETWORK_MAX_UPDATE_CHUNKS) {
  993. return false;
  994. }
  995. c->haveChunkIds[c->haveChunks++] = chunkId;
  996. memcpy(c->data.unsafeData() + chunkIndex,chunkData,chunkLen);
  997. c->haveBytes += chunkLen;
  998. if (c->haveBytes == totalLength) {
  999. c->data.unsafeData()[c->haveBytes] = (char)0; // ensure null terminated
  1000. nc = new NetworkConfig();
  1001. try {
  1002. if (!nc->fromDictionary(c->data)) {
  1003. delete nc;
  1004. nc = (NetworkConfig *)0;
  1005. }
  1006. } catch ( ... ) {
  1007. delete nc;
  1008. nc = (NetworkConfig *)0;
  1009. }
  1010. }
  1011. }
  1012. if (nc) {
  1013. this->setConfiguration(tPtr, *nc, true);
  1014. delete nc;
  1015. return configUpdateId;
  1016. } else {
  1017. return 0;
  1018. }
  1019. return 0;
  1020. }
  1021. int Network::setConfiguration(void *tPtr,const NetworkConfig &nconf,bool saveToDisk)
  1022. {
  1023. if (_destroyed) {
  1024. return 0;
  1025. }
  1026. // _lock is NOT locked when this is called
  1027. try {
  1028. if ((nconf.issuedTo != RR->identity.address())||(nconf.networkId != _id)) {
  1029. return 0; // invalid config that is not for us or not for this network
  1030. }
  1031. if (_config == nconf) {
  1032. return 1; // OK config, but duplicate of what we already have
  1033. }
  1034. ZT_VirtualNetworkConfig ctmp;
  1035. bool oldPortInitialized;
  1036. { // do things that require lock here, but unlock before calling callbacks
  1037. Mutex::Lock _l(_lock);
  1038. _config = nconf;
  1039. _lastConfigUpdate = RR->node->now();
  1040. _netconfFailure = NETCONF_FAILURE_NONE;
  1041. oldPortInitialized = _portInitialized;
  1042. _portInitialized = true;
  1043. _externalConfig(&ctmp);
  1044. }
  1045. _portError = RR->node->configureVirtualNetworkPort(tPtr,_id,&_uPtr,(oldPortInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  1046. _authenticationURL = nconf.authenticationURL;
  1047. if (saveToDisk) {
  1048. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *const d = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  1049. try {
  1050. if (nconf.toDictionary(*d,false)) {
  1051. uint64_t tmp[2];
  1052. tmp[0] = _id;
  1053. tmp[1] = 0;
  1054. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_NETWORK_CONFIG,tmp,d->data(),d->sizeBytes());
  1055. }
  1056. } catch ( ... ) {}
  1057. delete d;
  1058. }
  1059. return 2; // OK and configuration has changed
  1060. } catch ( ... ) {} // ignore invalid configs
  1061. return 0;
  1062. }
  1063. void Network::requestConfiguration(void *tPtr)
  1064. {
  1065. if (_destroyed) {
  1066. return;
  1067. }
  1068. if ((_id >> 56) == 0xff) {
  1069. if ((_id & 0xffffff) == 0) {
  1070. const uint16_t startPortRange = (uint16_t)((_id >> 40) & 0xffff);
  1071. const uint16_t endPortRange = (uint16_t)((_id >> 24) & 0xffff);
  1072. if (endPortRange >= startPortRange) {
  1073. NetworkConfig *const nconf = new NetworkConfig();
  1074. nconf->networkId = _id;
  1075. nconf->timestamp = RR->node->now();
  1076. nconf->credentialTimeMaxDelta = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1077. nconf->revision = 1;
  1078. nconf->issuedTo = RR->identity.address();
  1079. nconf->flags = ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1080. nconf->mtu = ZT_DEFAULT_MTU;
  1081. nconf->multicastLimit = 0;
  1082. nconf->staticIpCount = 1;
  1083. nconf->ruleCount = 14;
  1084. nconf->staticIps[0] = InetAddress::makeIpv66plane(_id,RR->identity.address().toInt());
  1085. // Drop everything but IPv6
  1086. nconf->rules[0].t = (uint8_t)ZT_NETWORK_RULE_MATCH_ETHERTYPE | 0x80; // NOT
  1087. nconf->rules[0].v.etherType = 0x86dd; // IPv6
  1088. nconf->rules[1].t = (uint8_t)ZT_NETWORK_RULE_ACTION_DROP;
  1089. // Allow ICMPv6
  1090. nconf->rules[2].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  1091. nconf->rules[2].v.ipProtocol = 0x3a; // ICMPv6
  1092. nconf->rules[3].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1093. // Allow destination ports within range
  1094. nconf->rules[4].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  1095. nconf->rules[4].v.ipProtocol = 0x11; // UDP
  1096. nconf->rules[5].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_PROTOCOL | 0x40; // OR
  1097. nconf->rules[5].v.ipProtocol = 0x06; // TCP
  1098. nconf->rules[6].t = (uint8_t)ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  1099. nconf->rules[6].v.port[0] = startPortRange;
  1100. nconf->rules[6].v.port[1] = endPortRange;
  1101. nconf->rules[7].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1102. // Allow non-SYN TCP packets to permit non-connection-initiating traffic
  1103. nconf->rules[8].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS | 0x80; // NOT
  1104. nconf->rules[8].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_SYN;
  1105. nconf->rules[9].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1106. // Also allow SYN+ACK which are replies to SYN
  1107. nconf->rules[10].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  1108. nconf->rules[10].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_SYN;
  1109. nconf->rules[11].t = (uint8_t)ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  1110. nconf->rules[11].v.characteristics = ZT_RULE_PACKET_CHARACTERISTICS_TCP_ACK;
  1111. nconf->rules[12].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1112. nconf->rules[13].t = (uint8_t)ZT_NETWORK_RULE_ACTION_DROP;
  1113. nconf->type = ZT_NETWORK_TYPE_PUBLIC;
  1114. nconf->name[0] = 'a';
  1115. nconf->name[1] = 'd';
  1116. nconf->name[2] = 'h';
  1117. nconf->name[3] = 'o';
  1118. nconf->name[4] = 'c';
  1119. nconf->name[5] = '-';
  1120. Utils::hex((uint16_t)startPortRange,nconf->name + 6);
  1121. nconf->name[10] = '-';
  1122. Utils::hex((uint16_t)endPortRange,nconf->name + 11);
  1123. nconf->name[15] = (char)0;
  1124. this->setConfiguration(tPtr,*nconf,false);
  1125. delete nconf;
  1126. } else {
  1127. this->setNotFound(tPtr);
  1128. }
  1129. } else if ((_id & 0xff) == 0x01) {
  1130. // ffAAaaaaaaaaaa01 -- where AA is the IPv4 /8 to use and aaaaaaaaaa is the anchor node for multicast gather and replication
  1131. const uint64_t myAddress = RR->identity.address().toInt();
  1132. const uint64_t networkHub = (_id >> 8) & 0xffffffffffULL;
  1133. uint8_t ipv4[4];
  1134. ipv4[0] = (uint8_t)((_id >> 48) & 0xff);
  1135. ipv4[1] = (uint8_t)((myAddress >> 16) & 0xff);
  1136. ipv4[2] = (uint8_t)((myAddress >> 8) & 0xff);
  1137. ipv4[3] = (uint8_t)(myAddress & 0xff);
  1138. char v4ascii[24];
  1139. Utils::decimal(ipv4[0],v4ascii);
  1140. NetworkConfig *const nconf = new NetworkConfig();
  1141. nconf->networkId = _id;
  1142. nconf->timestamp = RR->node->now();
  1143. nconf->credentialTimeMaxDelta = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1144. nconf->revision = 1;
  1145. nconf->issuedTo = RR->identity.address();
  1146. nconf->flags = ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1147. nconf->mtu = ZT_DEFAULT_MTU;
  1148. nconf->multicastLimit = 1024;
  1149. nconf->specialistCount = (networkHub == 0) ? 0 : 1;
  1150. nconf->staticIpCount = 2;
  1151. nconf->ruleCount = 1;
  1152. if (networkHub != 0) {
  1153. nconf->specialists[0] = networkHub;
  1154. }
  1155. nconf->staticIps[0] = InetAddress::makeIpv66plane(_id,myAddress);
  1156. nconf->staticIps[1].set(ipv4,4,8);
  1157. nconf->rules[0].t = (uint8_t)ZT_NETWORK_RULE_ACTION_ACCEPT;
  1158. nconf->type = ZT_NETWORK_TYPE_PUBLIC;
  1159. nconf->name[0] = 'a';
  1160. nconf->name[1] = 'd';
  1161. nconf->name[2] = 'h';
  1162. nconf->name[3] = 'o';
  1163. nconf->name[4] = 'c';
  1164. nconf->name[5] = '-';
  1165. unsigned long nn = 6;
  1166. while ((nconf->name[nn] = v4ascii[nn - 6])) {
  1167. ++nn;
  1168. }
  1169. nconf->name[nn++] = '.';
  1170. nconf->name[nn++] = '0';
  1171. nconf->name[nn++] = '.';
  1172. nconf->name[nn++] = '0';
  1173. nconf->name[nn++] = '.';
  1174. nconf->name[nn++] = '0';
  1175. nconf->name[nn++] = (char)0;
  1176. this->setConfiguration(tPtr,*nconf,false);
  1177. delete nconf;
  1178. }
  1179. return;
  1180. }
  1181. const Address ctrl(controller());
  1182. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  1183. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  1184. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_VENDOR,(uint64_t)ZT_VENDOR_ZEROTIER);
  1185. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  1186. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  1187. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  1188. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  1189. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  1190. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  1191. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  1192. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  1193. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  1194. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,(uint64_t)ZT_RULES_ENGINE_REVISION);
  1195. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_OS_ARCH,ZT_TARGET_NAME);
  1196. RR->t->networkConfigRequestSent(tPtr,*this,ctrl);
  1197. if (ctrl == RR->identity.address()) {
  1198. if (RR->localNetworkController) {
  1199. RR->localNetworkController->request(_id,InetAddress(),0xffffffffffffffffULL,RR->identity,rmd);
  1200. } else {
  1201. this->setNotFound(tPtr);
  1202. }
  1203. return;
  1204. }
  1205. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  1206. outp.append((uint64_t)_id);
  1207. const unsigned int rmdSize = rmd.sizeBytes();
  1208. outp.append((uint16_t)rmdSize);
  1209. outp.append((const void *)rmd.data(),rmdSize);
  1210. if (_config) {
  1211. outp.append((uint64_t)_config.revision);
  1212. outp.append((uint64_t)_config.timestamp);
  1213. } else {
  1214. outp.append((unsigned char)0,16);
  1215. }
  1216. outp.compress();
  1217. RR->node->expectReplyTo(outp.packetId());
  1218. RR->sw->send(tPtr,outp,true);
  1219. }
  1220. bool Network::gate(void *tPtr,const SharedPtr<Peer> &peer)
  1221. {
  1222. const int64_t now = RR->node->now();
  1223. //int64_t comTimestamp = 0;
  1224. //int64_t comRevocationThreshold = 0;
  1225. Mutex::Lock _l(_lock);
  1226. try {
  1227. if (_config) {
  1228. Membership *m = _memberships.get(peer->address());
  1229. //if (m) {
  1230. // comTimestamp = m->comTimestamp();
  1231. // comRevocationThreshold = m->comRevocationThreshold();
  1232. //}
  1233. if ( (_config.isPublic()) || ((m)&&(m->isAllowedOnNetwork(_config, peer->identity()))) ) {
  1234. if (!m) {
  1235. m = &(_membership(peer->address()));
  1236. }
  1237. if (m->multicastLikeGate(now)) {
  1238. _announceMulticastGroupsTo(tPtr,peer->address(),_allMulticastGroups());
  1239. }
  1240. return true;
  1241. }
  1242. }
  1243. } catch ( ... ) {}
  1244. //printf("%.16llx %.10llx not allowed, COM ts %lld revocation %lld\n", _id, peer->address().toInt(), comTimestamp, comRevocationThreshold); fflush(stdout);
  1245. return false;
  1246. }
  1247. bool Network::recentlyAssociatedWith(const Address &addr)
  1248. {
  1249. Mutex::Lock _l(_lock);
  1250. const Membership *m = _memberships.get(addr);
  1251. return ((m)&&(m->recentlyAssociated(RR->node->now())));
  1252. }
  1253. void Network::clean()
  1254. {
  1255. const int64_t now = RR->node->now();
  1256. Mutex::Lock _l(_lock);
  1257. if (_destroyed) {
  1258. return;
  1259. }
  1260. {
  1261. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  1262. MulticastGroup *mg = (MulticastGroup *)0;
  1263. uint64_t *ts = (uint64_t *)0;
  1264. while (i.next(mg,ts)) {
  1265. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2)) {
  1266. _multicastGroupsBehindMe.erase(*mg);
  1267. }
  1268. }
  1269. }
  1270. {
  1271. Address *a = (Address *)0;
  1272. Membership *m = (Membership *)0;
  1273. Hashtable<Address,Membership>::Iterator i(_memberships);
  1274. while (i.next(a,m)) {
  1275. if (!RR->topology->getPeerNoCache(*a)) {
  1276. _memberships.erase(*a);
  1277. } else {
  1278. m->clean(now,_config);
  1279. }
  1280. }
  1281. }
  1282. }
  1283. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  1284. {
  1285. Mutex::Lock _l(_lock);
  1286. _remoteBridgeRoutes[mac] = addr;
  1287. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  1288. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  1289. Hashtable< Address,unsigned long > counts;
  1290. Address maxAddr;
  1291. unsigned long maxCount = 0;
  1292. MAC *m = (MAC *)0;
  1293. Address *a = (Address *)0;
  1294. // Find the address responsible for the most entries
  1295. {
  1296. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1297. while (i.next(m,a)) {
  1298. const unsigned long c = ++counts[*a];
  1299. if (c > maxCount) {
  1300. maxCount = c;
  1301. maxAddr = *a;
  1302. }
  1303. }
  1304. }
  1305. // Kill this address from our table, since it's most likely spamming us
  1306. {
  1307. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  1308. while (i.next(m,a)) {
  1309. if (*a == maxAddr) {
  1310. _remoteBridgeRoutes.erase(*m);
  1311. }
  1312. }
  1313. }
  1314. }
  1315. }
  1316. void Network::learnBridgedMulticastGroup(void *tPtr,const MulticastGroup &mg,int64_t now)
  1317. {
  1318. Mutex::Lock _l(_lock);
  1319. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  1320. _multicastGroupsBehindMe.set(mg,now);
  1321. if (tmp != _multicastGroupsBehindMe.size()) {
  1322. _sendUpdatesToMembers(tPtr,&mg);
  1323. }
  1324. }
  1325. Membership::AddCredentialResult Network::addCredential(void *tPtr,const CertificateOfMembership &com)
  1326. {
  1327. if (com.networkId() != _id) {
  1328. return Membership::ADD_REJECTED;
  1329. }
  1330. Mutex::Lock _l(_lock);
  1331. return _membership(com.issuedTo()).addCredential(RR,tPtr,_config,com);
  1332. }
  1333. Membership::AddCredentialResult Network::addCredential(void *tPtr,const Address &sentFrom,const Revocation &rev)
  1334. {
  1335. if (rev.networkId() != _id) {
  1336. return Membership::ADD_REJECTED;
  1337. }
  1338. Mutex::Lock _l(_lock);
  1339. Membership &m = _membership(rev.target());
  1340. const Membership::AddCredentialResult result = m.addCredential(RR,tPtr,_config,rev);
  1341. if ((result == Membership::ADD_ACCEPTED_NEW)&&(rev.fastPropagate())) {
  1342. Address *a = (Address *)0;
  1343. Membership *m = (Membership *)0;
  1344. Hashtable<Address,Membership>::Iterator i(_memberships);
  1345. while (i.next(a,m)) {
  1346. if ((*a != sentFrom)&&(*a != rev.signer())) {
  1347. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1348. outp.append((uint8_t)0x00); // no COM
  1349. outp.append((uint16_t)0); // no capabilities
  1350. outp.append((uint16_t)0); // no tags
  1351. outp.append((uint16_t)1); // one revocation!
  1352. rev.serialize(outp);
  1353. outp.append((uint16_t)0); // no certificates of ownership
  1354. RR->sw->send(tPtr,outp,true);
  1355. }
  1356. }
  1357. }
  1358. return result;
  1359. }
  1360. void Network::destroy()
  1361. {
  1362. Mutex::Lock _l(_lock);
  1363. _destroyed = true;
  1364. }
  1365. ZT_VirtualNetworkStatus Network::_status() const
  1366. {
  1367. // assumes _lock is locked
  1368. if (_portError) {
  1369. return ZT_NETWORK_STATUS_PORT_ERROR;
  1370. }
  1371. switch(_netconfFailure) {
  1372. case NETCONF_FAILURE_ACCESS_DENIED:
  1373. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  1374. case NETCONF_FAILURE_NOT_FOUND:
  1375. return ZT_NETWORK_STATUS_NOT_FOUND;
  1376. case NETCONF_FAILURE_NONE:
  1377. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  1378. case NETCONF_FAILURE_AUTHENTICATION_REQUIRED:
  1379. return ZT_NETWORK_STATUS_AUTHENTICATION_REQUIRED;
  1380. default:
  1381. return ZT_NETWORK_STATUS_PORT_ERROR;
  1382. }
  1383. }
  1384. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  1385. {
  1386. // assumes _lock is locked
  1387. ec->nwid = _id;
  1388. ec->mac = _mac.toInt();
  1389. if (_config) {
  1390. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  1391. } else {
  1392. ec->name[0] = (char)0;
  1393. }
  1394. ec->status = _status();
  1395. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  1396. ec->mtu = (_config) ? _config.mtu : ZT_DEFAULT_MTU;
  1397. ec->dhcp = 0;
  1398. std::vector<Address> ab(_config.activeBridges());
  1399. ec->bridge = (std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end()) ? 1 : 0;
  1400. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  1401. ec->portError = _portError;
  1402. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  1403. ec->assignedAddressCount = 0;
  1404. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  1405. if (i < _config.staticIpCount) {
  1406. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  1407. ++ec->assignedAddressCount;
  1408. } else {
  1409. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  1410. }
  1411. }
  1412. ec->routeCount = 0;
  1413. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  1414. if (i < _config.routeCount) {
  1415. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  1416. ++ec->routeCount;
  1417. } else {
  1418. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  1419. }
  1420. }
  1421. ec->multicastSubscriptionCount = (unsigned int)_myMulticastGroups.size();
  1422. for(unsigned long i=0;i<(unsigned long)_myMulticastGroups.size();++i) {
  1423. ec->multicastSubscriptions[i].mac = _myMulticastGroups[i].mac().toInt();
  1424. ec->multicastSubscriptions[i].adi = _myMulticastGroups[i].adi();
  1425. }
  1426. memcpy(&ec->dns, &_config.dns, sizeof(ZT_VirtualNetworkDNS));
  1427. Utils::scopy(ec->authenticationURL, sizeof(ec->authenticationURL), _authenticationURL.c_str());
  1428. ec->ssoVersion = _config.ssoVersion;
  1429. ec->authenticationExpiryTime = _config.authenticationExpiryTime;
  1430. ec->ssoEnabled = _config.ssoEnabled;
  1431. Utils::scopy(ec->centralAuthURL, sizeof(ec->centralAuthURL), _config.centralAuthURL);
  1432. Utils::scopy(ec->issuerURL, sizeof(ec->issuerURL), _config.issuerURL);
  1433. Utils::scopy(ec->ssoNonce, sizeof(ec->ssoNonce), _config.ssoNonce);
  1434. Utils::scopy(ec->ssoState, sizeof(ec->ssoState), _config.ssoState);
  1435. Utils::scopy(ec->ssoClientID, sizeof(ec->ssoClientID), _config.ssoClientID);
  1436. Utils::scopy(ec->ssoProvider, sizeof(ec->ssoProvider), _config.ssoProvider);
  1437. }
  1438. void Network::_sendUpdatesToMembers(void *tPtr,const MulticastGroup *const newMulticastGroup)
  1439. {
  1440. // Assumes _lock is locked
  1441. const int64_t now = RR->node->now();
  1442. std::vector<MulticastGroup> groups;
  1443. if (newMulticastGroup) {
  1444. groups.push_back(*newMulticastGroup);
  1445. } else {
  1446. groups = _allMulticastGroups();
  1447. }
  1448. std::vector<Address> alwaysAnnounceTo;
  1449. if ((newMulticastGroup)||((now - _lastAnnouncedMulticastGroupsUpstream) >= ZT_MULTICAST_ANNOUNCE_PERIOD)) {
  1450. if (!newMulticastGroup) {
  1451. _lastAnnouncedMulticastGroupsUpstream = now;
  1452. }
  1453. alwaysAnnounceTo = _config.alwaysContactAddresses();
  1454. if (std::find(alwaysAnnounceTo.begin(),alwaysAnnounceTo.end(),controller()) == alwaysAnnounceTo.end()) {
  1455. alwaysAnnounceTo.push_back(controller());
  1456. }
  1457. const std::vector<Address> upstreams(RR->topology->upstreamAddresses());
  1458. for(std::vector<Address>::const_iterator a(upstreams.begin());a!=upstreams.end();++a) {
  1459. if (std::find(alwaysAnnounceTo.begin(),alwaysAnnounceTo.end(),*a) == alwaysAnnounceTo.end()) {
  1460. alwaysAnnounceTo.push_back(*a);
  1461. }
  1462. }
  1463. std::sort(alwaysAnnounceTo.begin(),alwaysAnnounceTo.end());
  1464. for(std::vector<Address>::const_iterator a(alwaysAnnounceTo.begin());a!=alwaysAnnounceTo.end();++a) {
  1465. /*
  1466. // push COM to non-members so they can do multicast request auth
  1467. if ( (_config.com) && (!_memberships.contains(*a)) && (*a != RR->identity.address()) ) {
  1468. Packet outp(*a,RR->identity.address(),Packet::VERB_NETWORK_CREDENTIALS);
  1469. _config.com.serialize(outp);
  1470. outp.append((uint8_t)0x00);
  1471. outp.append((uint16_t)0); // no capabilities
  1472. outp.append((uint16_t)0); // no tags
  1473. outp.append((uint16_t)0); // no revocations
  1474. outp.append((uint16_t)0); // no certificates of ownership
  1475. RR->sw->send(tPtr,outp,true);
  1476. }
  1477. */
  1478. _announceMulticastGroupsTo(tPtr,*a,groups);
  1479. }
  1480. }
  1481. {
  1482. Address *a = (Address *)0;
  1483. Membership *m = (Membership *)0;
  1484. Hashtable<Address,Membership>::Iterator i(_memberships);
  1485. while (i.next(a,m)) {
  1486. const Identity remoteIdentity(RR->topology->getIdentity(tPtr, *a));
  1487. if (remoteIdentity) {
  1488. if ( ( m->multicastLikeGate(now) || (newMulticastGroup) ) && (m->isAllowedOnNetwork(_config, remoteIdentity)) && (!std::binary_search(alwaysAnnounceTo.begin(),alwaysAnnounceTo.end(),*a)) ) {
  1489. _announceMulticastGroupsTo(tPtr,*a,groups);
  1490. }
  1491. }
  1492. }
  1493. }
  1494. }
  1495. void Network::_announceMulticastGroupsTo(void *tPtr,const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  1496. {
  1497. // Assumes _lock is locked
  1498. Packet *const outp = new Packet(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1499. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  1500. if ((outp->size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  1501. outp->compress();
  1502. RR->sw->send(tPtr,*outp,true);
  1503. outp->reset(peer,RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  1504. }
  1505. // network ID, MAC, ADI
  1506. outp->append((uint64_t)_id);
  1507. mg->mac().appendTo(*outp);
  1508. outp->append((uint32_t)mg->adi());
  1509. }
  1510. if (outp->size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  1511. outp->compress();
  1512. RR->sw->send(tPtr,*outp,true);
  1513. }
  1514. delete outp;
  1515. }
  1516. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  1517. {
  1518. // Assumes _lock is locked
  1519. std::vector<MulticastGroup> mgs;
  1520. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  1521. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  1522. _multicastGroupsBehindMe.appendKeys(mgs);
  1523. if ((_config)&&(_config.enableBroadcast())) {
  1524. mgs.push_back(Network::BROADCAST);
  1525. }
  1526. std::sort(mgs.begin(),mgs.end());
  1527. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  1528. return mgs;
  1529. }
  1530. Membership &Network::_membership(const Address &a)
  1531. {
  1532. // assumes _lock is locked
  1533. return _memberships[a];
  1534. }
  1535. void Network::setAuthenticationRequired(void *tPtr, const char* issuerURL, const char* centralEndpoint, const char* clientID, const char *ssoProvider, const char* nonce, const char* state)
  1536. {
  1537. Mutex::Lock _l(_lock);
  1538. _netconfFailure = NETCONF_FAILURE_AUTHENTICATION_REQUIRED;
  1539. _config.ssoEnabled = true;
  1540. _config.ssoVersion = 1;
  1541. Utils::scopy(_config.issuerURL, sizeof(_config.issuerURL), issuerURL);
  1542. Utils::scopy(_config.centralAuthURL, sizeof(_config.centralAuthURL), centralEndpoint);
  1543. Utils::scopy(_config.ssoClientID, sizeof(_config.ssoClientID), clientID);
  1544. Utils::scopy(_config.ssoNonce, sizeof(_config.ssoNonce), nonce);
  1545. Utils::scopy(_config.ssoState, sizeof(_config.ssoState), state);
  1546. Utils::scopy(_config.ssoProvider, sizeof(_config.ssoProvider), ssoProvider);
  1547. _sendUpdateEvent(tPtr);
  1548. }
  1549. void Network::_sendUpdateEvent(void *tPtr) {
  1550. ZT_VirtualNetworkConfig ctmp;
  1551. _externalConfig(&ctmp);
  1552. RR->node->configureVirtualNetworkPort(tPtr, _id, &_uPtr, (_portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP, &ctmp);
  1553. }
  1554. } // namespace ZeroTier