Network.cpp 54 KB

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