2
0

Network.cpp 61 KB

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