Network.cpp 57 KB

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