Network.cpp 53 KB

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