Network.cpp 54 KB

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