Network.cpp 56 KB

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