Network.cpp 59 KB

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