Network.cpp 55 KB

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