Network.cpp 53 KB

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