Network.cpp 54 KB

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