Network.cpp 55 KB

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