Network.cpp 55 KB

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