Network.cpp 54 KB

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