Network.cpp 56 KB

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