Network.cpp 54 KB

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