Network.cpp 58 KB

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