Network.cpp 55 KB

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