Network.cpp 54 KB

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