Network.cpp 57 KB

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