Network.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #include <stdio.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <math.h>
  22. #include "Constants.hpp"
  23. #include "../version.h"
  24. #include "Network.hpp"
  25. #include "RuntimeEnvironment.hpp"
  26. #include "MAC.hpp"
  27. #include "Address.hpp"
  28. #include "InetAddress.hpp"
  29. #include "Switch.hpp"
  30. #include "Buffer.hpp"
  31. #include "Packet.hpp"
  32. #include "NetworkController.hpp"
  33. #include "Node.hpp"
  34. #include "Peer.hpp"
  35. // Uncomment to enable ZT_NETWORK_RULE_ACTION_DEBUG_LOG rule output to STDOUT
  36. #define ZT_RULES_ENGINE_DEBUGGING 1
  37. /*
  38. {
  39. "name": "filter_log_test",
  40. "private": true,
  41. "v4AssignMode": {
  42. "zt": true
  43. },
  44. "v6AssignMode": {
  45. "rfc4193": true,
  46. "zt": false,
  47. "6plane": false
  48. },
  49. "routes": [
  50. { "target": "10.140.140.0/24", "via": null }
  51. ],
  52. "ipAssignmentPools": [
  53. { "ipRangeStart": "10.140.140.2", "ipRangeEnd": "10.140.140.254" }
  54. ],
  55. "rules": [
  56. { "type": "MATCH_ETHERTYPE", "etherType": 0x0800 },
  57. { "type": "ACTION_DEBUG_LOG" },
  58. { "type": "MATCH_ETHERTYPE", "etherType": 0x0800, "not": true },
  59. { "type": "ACTION_DEBUG_LOG" },
  60. { "type": "ACTION_ACCEPT" }
  61. ]
  62. }
  63. */
  64. namespace ZeroTier {
  65. #ifdef ZT_RULES_ENGINE_DEBUGGING
  66. #define FILTER_TRACE(f,...) { Utils::snprintf(dpbuf,sizeof(dpbuf),f,##__VA_ARGS__); dlog.push_back(std::string(dpbuf)); }
  67. static const char *_rtn(const ZT_VirtualNetworkRuleType rt)
  68. {
  69. switch(rt) {
  70. case ZT_NETWORK_RULE_ACTION_DROP: return "ACTION_DROP";
  71. case ZT_NETWORK_RULE_ACTION_ACCEPT: return "ACTION_ACCEPT";
  72. case ZT_NETWORK_RULE_ACTION_TEE: return "ACTION_TEE";
  73. case ZT_NETWORK_RULE_ACTION_REDIRECT: return "ACTION_REDIRECT";
  74. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG: return "ACTION_DEBUG_LOG";
  75. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS: return "MATCH_SOURCE_ZEROTIER_ADDRESS";
  76. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS: return "MATCH_DEST_ZEROTIER_ADDRESS";
  77. case ZT_NETWORK_RULE_MATCH_VLAN_ID: return "MATCH_VLAN_ID";
  78. case ZT_NETWORK_RULE_MATCH_VLAN_PCP: return "MATCH_VLAN_PCP";
  79. case ZT_NETWORK_RULE_MATCH_VLAN_DEI: return "MATCH_VLAN_DEI";
  80. case ZT_NETWORK_RULE_MATCH_ETHERTYPE: return "MATCH_ETHERTYPE";
  81. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE: return "MATCH_MAC_SOURCE";
  82. case ZT_NETWORK_RULE_MATCH_MAC_DEST: return "MATCH_MAC_DEST";
  83. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE: return "MATCH_IPV4_SOURCE";
  84. case ZT_NETWORK_RULE_MATCH_IPV4_DEST: return "MATCH_IPV4_DEST";
  85. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE: return "MATCH_IPV6_SOURCE";
  86. case ZT_NETWORK_RULE_MATCH_IPV6_DEST: return "MATCH_IPV6_DEST";
  87. case ZT_NETWORK_RULE_MATCH_IP_TOS: return "MATCH_IP_TOS";
  88. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL: return "MATCH_IP_PROTOCOL";
  89. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE: return "MATCH_IP_SOURCE_PORT_RANGE";
  90. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE: return "MATCH_IP_DEST_PORT_RANGE";
  91. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: return "MATCH_CHARACTERISTICS";
  92. default: return "BAD_RULE_TYPE";
  93. }
  94. }
  95. #else
  96. #define FILTER_TRACE(f,...) {}
  97. #endif // ZT_RULES_ENGINE_DEBUGGING
  98. // Returns true if packet appears valid; pos and proto will be set
  99. static bool _ipv6GetPayload(const uint8_t *frameData,unsigned int frameLen,unsigned int &pos,unsigned int &proto)
  100. {
  101. if (frameLen < 40)
  102. return false;
  103. pos = 40;
  104. proto = frameData[6];
  105. while (pos <= frameLen) {
  106. switch(proto) {
  107. case 0: // hop-by-hop options
  108. case 43: // routing
  109. case 60: // destination options
  110. case 135: // mobility options
  111. if ((pos + 8) > frameLen)
  112. return false; // invalid!
  113. proto = frameData[pos];
  114. pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
  115. break;
  116. //case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
  117. //case 50:
  118. //case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
  119. default:
  120. return true;
  121. }
  122. }
  123. return false; // overflow == invalid
  124. }
  125. // 0 == no match, -1 == match/drop, 1 == match/accept
  126. static int _doZtFilter(
  127. const RuntimeEnvironment *RR,
  128. const bool noRedirect,
  129. const NetworkConfig &nconf,
  130. const bool inbound,
  131. const Address &ztSource,
  132. const Address &ztDest,
  133. const MAC &macSource,
  134. const MAC &macDest,
  135. const uint8_t *frameData,
  136. const unsigned int frameLen,
  137. const unsigned int etherType,
  138. const unsigned int vlanId,
  139. const ZT_VirtualNetworkRule *rules,
  140. const unsigned int ruleCount,
  141. const Tag *localTags,
  142. const unsigned int localTagCount,
  143. const uint32_t *remoteTagIds,
  144. const uint32_t *remoteTagValues,
  145. const unsigned int remoteTagCount,
  146. const Tag **relevantLocalTags, // pointer array must be at least [localTagCount] in size
  147. unsigned int &relevantLocalTagCount)
  148. {
  149. // For each set of rules we start by assuming that they match (since no constraints
  150. // yields a 'match all' rule).
  151. uint8_t thisSetMatches = 1;
  152. #ifdef ZT_RULES_ENGINE_DEBUGGING
  153. std::vector<std::string> dlog;
  154. char dpbuf[1024];
  155. #endif
  156. for(unsigned int rn=0;rn<ruleCount;++rn) {
  157. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x7f);
  158. uint8_t thisRuleMatches = 0;
  159. switch(rt) {
  160. // Actions -------------------------------------------------------------
  161. // An action is performed if thisSetMatches is true, and if not
  162. // (or if the action is non-terminating) we start a new set of rules.
  163. case ZT_NETWORK_RULE_ACTION_DROP:
  164. if (thisSetMatches) {
  165. return -1; // match, drop packet
  166. } else {
  167. thisRuleMatches = 1;
  168. thisSetMatches = 1; // no match, evaluate next set
  169. }
  170. break;
  171. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  172. if (thisSetMatches) {
  173. return 1; // match, accept packet
  174. } else {
  175. thisRuleMatches = 1;
  176. thisSetMatches = 1; // no match, evaluate next set
  177. }
  178. break;
  179. case ZT_NETWORK_RULE_ACTION_TEE:
  180. case ZT_NETWORK_RULE_ACTION_REDIRECT: {
  181. if (!noRedirect) {
  182. Packet outp(Address(rules[rn].v.fwd.address),RR->identity.address(),Packet::VERB_EXT_FRAME);
  183. outp.append(nconf.networkId);
  184. outp.append((uint8_t)( ((rt == ZT_NETWORK_RULE_ACTION_REDIRECT) ? 0x04 : 0x02) | (inbound ? 0x08 : 0x00) ));
  185. macDest.appendTo(outp);
  186. macSource.appendTo(outp);
  187. outp.append((uint16_t)etherType);
  188. outp.append(frameData,(rules[rn].v.fwd.length != 0) ? ((frameLen < (unsigned int)rules[rn].v.fwd.length) ? frameLen : (unsigned int)rules[rn].v.fwd.length) : frameLen);
  189. outp.compress();
  190. RR->sw->send(outp,true);
  191. }
  192. if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
  193. return -1; // match, drop packet (we redirected it)
  194. } else {
  195. thisRuleMatches = 1;
  196. thisSetMatches = 1; // TEE does not terminate evaluation
  197. }
  198. } break;
  199. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG:
  200. #ifdef ZT_RULES_ENGINE_DEBUGGING
  201. if (thisSetMatches) {
  202. printf("[FILTER] MATCH %s->%s %.2x:%.2x:%.2x:%.2x:%.2x:%.2x->%.2x:%.2x:%.2x:%.2x:%.2x:%.2x inbound=%d noRedirect=%d frameLen=%u etherType=%u" ZT_EOL_S,
  203. ztSource.toString().c_str(),
  204. ztDest.toString().c_str(),
  205. (unsigned int)macSource[0],
  206. (unsigned int)macSource[1],
  207. (unsigned int)macSource[2],
  208. (unsigned int)macSource[3],
  209. (unsigned int)macSource[4],
  210. (unsigned int)macSource[5],
  211. (unsigned int)macDest[0],
  212. (unsigned int)macDest[1],
  213. (unsigned int)macDest[2],
  214. (unsigned int)macDest[3],
  215. (unsigned int)macDest[4],
  216. (unsigned int)macDest[5],
  217. (int)inbound,
  218. (int)noRedirect,
  219. frameLen,
  220. etherType
  221. );
  222. for(std::vector<std::string>::iterator m(dlog.begin());m!=dlog.end();++m)
  223. printf(" %s" ZT_EOL_S,m->c_str());
  224. dlog.clear();
  225. }
  226. #endif // ZT_RULES_ENGINE_DEBUGGING
  227. thisRuleMatches = 1;
  228. thisSetMatches = 1; // DEBUG_LOG does not terminate evaluation
  229. break;
  230. // Rules ---------------------------------------------------------------
  231. // thisSetMatches is the binary AND of the result of all rules in a set
  232. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  233. FILTER_TRACE("%u %s param0=%.10llx",rn,_rtn(rt),rules[rn].v.zt);
  234. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
  235. break;
  236. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  237. FILTER_TRACE("%u %s param0=%.10llx",rn,_rtn(rt),rules[rn].v.zt);
  238. thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
  239. break;
  240. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  241. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.vlanId);
  242. thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
  243. break;
  244. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  245. // NOT SUPPORTED YET
  246. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.vlanPcp);
  247. thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
  248. break;
  249. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  250. // NOT SUPPORTED YET
  251. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.vlanDei);
  252. thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
  253. break;
  254. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  255. FILTER_TRACE("%u %s param0=%u etherType=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.etherType,etherType);
  256. thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
  257. break;
  258. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  259. FILTER_TRACE("%u %s param0=%.12llx",rn,_rtn(rt),rules[rn].v.mac);
  260. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macSource);
  261. break;
  262. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  263. FILTER_TRACE("%u %s param0=%.12llx",rn,_rtn(rt),rules[rn].v.mac);
  264. thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac,6) == macDest);
  265. break;
  266. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  267. FILTER_TRACE("%u %s param0=%s",rn,_rtn(rt),InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).toString().c_str());
  268. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  269. 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)));
  270. } else {
  271. thisRuleMatches = 0;
  272. }
  273. break;
  274. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  275. FILTER_TRACE("%u %s param0=%s",rn,_rtn(rt),InetAddress((const void *)&(rules[rn].v.ipv4.ip),4,rules[rn].v.ipv4.mask).toString().c_str());
  276. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  277. 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)));
  278. } else {
  279. thisRuleMatches = 0;
  280. }
  281. break;
  282. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  283. FILTER_TRACE("%u %s param0=%s",rn,_rtn(rt),InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).toString().c_str());
  284. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  285. 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)));
  286. } else {
  287. thisRuleMatches = 0;
  288. }
  289. break;
  290. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  291. FILTER_TRACE("%u %s param0=%s",rn,_rtn(rt),InetAddress((const void *)rules[rn].v.ipv6.ip,16,rules[rn].v.ipv6.mask).toString().c_str());
  292. if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  293. 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)));
  294. } else {
  295. thisRuleMatches = 0;
  296. }
  297. break;
  298. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  299. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.ipTos);
  300. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  301. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((frameData[1] & 0xfc) >> 2));
  302. } else if ((etherType == ZT_ETHERTYPE_IPV6)&&(frameLen >= 40)) {
  303. const uint8_t trafficClass = ((frameData[0] << 4) & 0xf0) | ((frameData[1] >> 4) & 0x0f);
  304. thisRuleMatches = (uint8_t)(rules[rn].v.ipTos == ((trafficClass & 0xfc) >> 2));
  305. } else {
  306. thisRuleMatches = 0;
  307. }
  308. break;
  309. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  310. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.ipProtocol);
  311. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  312. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
  313. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  314. unsigned int pos = 0,proto = 0;
  315. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  316. thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
  317. } else {
  318. thisRuleMatches = 0;
  319. }
  320. } else {
  321. thisRuleMatches = 0;
  322. }
  323. break;
  324. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  325. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  326. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)) {
  327. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  328. int p = -1;
  329. switch(frameData[9]) { // IP protocol number
  330. // All these start with 16-bit source and destination port in that order
  331. case 0x06: // TCP
  332. case 0x11: // UDP
  333. case 0x84: // SCTP
  334. case 0x88: // UDPLite
  335. if (frameLen > (headerLen + 4)) {
  336. unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
  337. p = (int)frameData[pos++] << 8;
  338. p |= (int)frameData[pos];
  339. }
  340. break;
  341. }
  342. FILTER_TRACE("%u %s param0=%u param1=%u port==%u proto==%u etherType=%u (IPv4)",rn,_rtn(rt),(unsigned int)rules[rn].v.port[0],(unsigned int)rules[rn].v.port[1],p,(unsigned int)frameData[9],etherType);
  343. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  344. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  345. unsigned int pos = 0,proto = 0;
  346. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  347. int p = -1;
  348. switch(proto) { // IP protocol number
  349. // All these start with 16-bit source and destination port in that order
  350. case 0x06: // TCP
  351. case 0x11: // UDP
  352. case 0x84: // SCTP
  353. case 0x88: // UDPLite
  354. if (frameLen > (pos + 4)) {
  355. if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) pos += 2;
  356. p = (int)frameData[pos++] << 8;
  357. p |= (int)frameData[pos];
  358. }
  359. break;
  360. }
  361. FILTER_TRACE("%u %s param0=%u param1=%u port==%u proto=%u etherType=%u (IPv6)",rn,_rtn(rt),(unsigned int)rules[rn].v.port[0],(unsigned int)rules[rn].v.port[1],p,proto,etherType);
  362. thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0])&&(p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
  363. } else {
  364. FILTER_TRACE("%u %s param0=%u param1=%u port=0 proto=0 etherType=%u (IPv6 parse failed)",rn,_rtn(rt),(unsigned int)rules[rn].v.port[0],(unsigned int)rules[rn].v.port[1],etherType);
  365. thisRuleMatches = 0;
  366. }
  367. } else {
  368. FILTER_TRACE("%u %s param0=%u param1=%u port=0 proto=0 etherType=%u (not IPv4 or IPv6)",rn,_rtn(rt),(unsigned int)rules[rn].v.port[0],(unsigned int)rules[rn].v.port[1],etherType);
  369. thisRuleMatches = 0;
  370. }
  371. break;
  372. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
  373. uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
  374. if (macDest.isMulticast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_MULTICAST;
  375. if (macDest.isBroadcast()) cf |= ZT_RULE_PACKET_CHARACTERISTICS_BROADCAST;
  376. if ((etherType == ZT_ETHERTYPE_IPV4)&&(frameLen >= 20)&&(frameData[9] == 0x06)) {
  377. const unsigned int headerLen = 4 * (frameData[0] & 0xf);
  378. cf |= (uint64_t)frameData[headerLen + 13];
  379. cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
  380. } else if (etherType == ZT_ETHERTYPE_IPV6) {
  381. unsigned int pos = 0,proto = 0;
  382. if (_ipv6GetPayload(frameData,frameLen,pos,proto)) {
  383. if ((proto == 0x06)&&(frameLen > (pos + 14))) {
  384. cf |= (uint64_t)frameData[pos + 13];
  385. cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
  386. }
  387. }
  388. }
  389. FILTER_TRACE("%u %s param0=%.16llx param1=%.16llx actual=%.16llx",rn,_rtn(rt),rules[rn].v.characteristics[0],rules[rn].v.characteristics[1],cf);
  390. thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics[0]) == rules[rn].v.characteristics[1]);
  391. } break;
  392. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  393. FILTER_TRACE("%u %s param0=%u param1=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.frameSize[0],(unsigned int)rules[rn].v.frameSize[1]);
  394. thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0])&&(frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
  395. break;
  396. case ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS:
  397. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  398. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  399. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR: {
  400. FILTER_TRACE("%u %s param0=%u",rn,_rtn(rt),(unsigned int)rules[rn].v.tag.value);
  401. const Tag *lt = (const Tag *)0;
  402. for(unsigned int i=0;i<localTagCount;++i) {
  403. if (rules[rn].v.tag.id == localTags[i].id()) {
  404. lt = &(localTags[i]);
  405. break;
  406. }
  407. }
  408. if (!lt) {
  409. thisRuleMatches = 0;
  410. } else {
  411. const uint32_t *rtv = (const uint32_t *)0;
  412. for(unsigned int i=0;i<remoteTagCount;++i) {
  413. if (rules[rn].v.tag.id == remoteTagIds[i]) {
  414. rtv = &(remoteTagValues[i]);
  415. break;
  416. }
  417. }
  418. if (!rtv) {
  419. thisRuleMatches = 0;
  420. } else {
  421. if (rt == ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS) {
  422. const uint32_t sameness = (lt->value() > *rtv) ? (lt->value() - *rtv) : (*rtv - lt->value());
  423. thisRuleMatches = (uint8_t)(sameness <= rules[rn].v.tag.value);
  424. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
  425. thisRuleMatches = (uint8_t)((lt->value() & *rtv) <= rules[rn].v.tag.value);
  426. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
  427. thisRuleMatches = (uint8_t)((lt->value() | *rtv) <= rules[rn].v.tag.value);
  428. } else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
  429. thisRuleMatches = (uint8_t)((lt->value() ^ *rtv) <= rules[rn].v.tag.value);
  430. } else { // sanity check, can't really happen
  431. thisRuleMatches = 0;
  432. }
  433. if (thisRuleMatches) {
  434. relevantLocalTags[relevantLocalTagCount++] = lt;
  435. }
  436. }
  437. }
  438. } break;
  439. }
  440. // thisSetMatches remains true if the current rule matched (or did NOT match if NOT bit is set)
  441. thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t & 0x80) >> 7));
  442. FILTER_TRACE("%u %s/%u thisRuleMatches==%u thisSetMatches==%u",rn,_rtn(rt),(unsigned int)rt,(unsigned int)thisRuleMatches,(unsigned int)thisSetMatches);
  443. }
  444. return 0;
  445. }
  446. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL),0);
  447. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr) :
  448. RR(renv),
  449. _uPtr(uptr),
  450. _id(nwid),
  451. _mac(renv->identity.address(),nwid),
  452. _portInitialized(false),
  453. _inboundConfigPacketId(0),
  454. _lastConfigUpdate(0),
  455. _lastRequestedConfiguration(0),
  456. _destroyed(false),
  457. _netconfFailure(NETCONF_FAILURE_NONE),
  458. _portError(0)
  459. {
  460. char confn[128];
  461. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  462. bool gotConf = false;
  463. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dconf = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
  464. NetworkConfig *nconf = new NetworkConfig();
  465. try {
  466. std::string conf(RR->node->dataStoreGet(confn));
  467. if (conf.length()) {
  468. dconf->load(conf.c_str());
  469. if (nconf->fromDictionary(*dconf)) {
  470. this->setConfiguration(*nconf,false);
  471. _lastConfigUpdate = 0; // we still want to re-request a new config from the network
  472. gotConf = true;
  473. }
  474. }
  475. } catch ( ... ) {} // ignore invalids, we'll re-request
  476. delete nconf;
  477. delete dconf;
  478. if (!gotConf) {
  479. // Save a one-byte CR to persist membership while we request a real netconf
  480. RR->node->dataStorePut(confn,"\n",1,false);
  481. }
  482. if (!_portInitialized) {
  483. ZT_VirtualNetworkConfig ctmp;
  484. _externalConfig(&ctmp);
  485. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  486. _portInitialized = true;
  487. }
  488. }
  489. Network::~Network()
  490. {
  491. ZT_VirtualNetworkConfig ctmp;
  492. _externalConfig(&ctmp);
  493. char n[128];
  494. if (_destroyed) {
  495. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
  496. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  497. RR->node->dataStoreDelete(n);
  498. } else {
  499. RR->node->configureVirtualNetworkPort(_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN,&ctmp);
  500. }
  501. }
  502. bool Network::filterOutgoingPacket(
  503. const bool noRedirect,
  504. const Address &ztSource,
  505. const Address &ztDest,
  506. const MAC &macSource,
  507. const MAC &macDest,
  508. const uint8_t *frameData,
  509. const unsigned int frameLen,
  510. const unsigned int etherType,
  511. const unsigned int vlanId)
  512. {
  513. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  514. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  515. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  516. unsigned int relevantLocalTagCount = 0;
  517. Mutex::Lock _l(_lock);
  518. Membership &m = _memberships[ztDest];
  519. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  520. switch(_doZtFilter(RR,noRedirect,_config,false,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  521. case -1:
  522. return false;
  523. case 1:
  524. if (ztDest)
  525. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,(const Capability *)0,relevantLocalTags,relevantLocalTagCount);
  526. return true;
  527. }
  528. for(unsigned int c=0;c<_config.capabilityCount;++c) {
  529. relevantLocalTagCount = 0;
  530. switch (_doZtFilter(RR,noRedirect,_config,false,ztSource,ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.capabilities[c].rules(),_config.capabilities[c].ruleCount(),_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  531. case -1:
  532. return false;
  533. case 1:
  534. if (ztDest)
  535. m.sendCredentialsIfNeeded(RR,RR->node->now(),ztDest,_config.com,&(_config.capabilities[c]),relevantLocalTags,relevantLocalTagCount);
  536. return true;
  537. }
  538. }
  539. return false;
  540. }
  541. bool Network::filterIncomingPacket(
  542. const SharedPtr<Peer> &sourcePeer,
  543. const Address &ztDest,
  544. const MAC &macSource,
  545. const MAC &macDest,
  546. const uint8_t *frameData,
  547. const unsigned int frameLen,
  548. const unsigned int etherType,
  549. const unsigned int vlanId)
  550. {
  551. uint32_t remoteTagIds[ZT_MAX_NETWORK_TAGS];
  552. uint32_t remoteTagValues[ZT_MAX_NETWORK_TAGS];
  553. const Tag *relevantLocalTags[ZT_MAX_NETWORK_TAGS];
  554. unsigned int relevantLocalTagCount = 0;
  555. Mutex::Lock _l(_lock);
  556. Membership &m = _memberships[ztDest];
  557. const unsigned int remoteTagCount = m.getAllTags(_config,remoteTagIds,remoteTagValues,ZT_MAX_NETWORK_TAGS);
  558. switch (_doZtFilter(RR,false,_config,true,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,_config.rules,_config.ruleCount,_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  559. case -1:
  560. return false;
  561. case 1:
  562. return true;
  563. }
  564. Membership::CapabilityIterator mci(m);
  565. const Capability *c;
  566. while ((c = mci.next(_config))) {
  567. relevantLocalTagCount = 0;
  568. switch(_doZtFilter(RR,false,_config,false,sourcePeer->address(),ztDest,macSource,macDest,frameData,frameLen,etherType,vlanId,c->rules(),c->ruleCount(),_config.tags,_config.tagCount,remoteTagIds,remoteTagValues,remoteTagCount,relevantLocalTags,relevantLocalTagCount)) {
  569. case -1:
  570. return false;
  571. case 1:
  572. return true;
  573. }
  574. }
  575. return false;
  576. }
  577. bool Network::subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const
  578. {
  579. Mutex::Lock _l(_lock);
  580. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  581. return true;
  582. else if (includeBridgedGroups)
  583. return _multicastGroupsBehindMe.contains(mg);
  584. else return false;
  585. }
  586. void Network::multicastSubscribe(const MulticastGroup &mg)
  587. {
  588. {
  589. Mutex::Lock _l(_lock);
  590. if (std::binary_search(_myMulticastGroups.begin(),_myMulticastGroups.end(),mg))
  591. return;
  592. _myMulticastGroups.push_back(mg);
  593. std::sort(_myMulticastGroups.begin(),_myMulticastGroups.end());
  594. }
  595. _announceMulticastGroups();
  596. }
  597. void Network::multicastUnsubscribe(const MulticastGroup &mg)
  598. {
  599. Mutex::Lock _l(_lock);
  600. std::vector<MulticastGroup> nmg;
  601. for(std::vector<MulticastGroup>::const_iterator i(_myMulticastGroups.begin());i!=_myMulticastGroups.end();++i) {
  602. if (*i != mg)
  603. nmg.push_back(*i);
  604. }
  605. if (nmg.size() != _myMulticastGroups.size())
  606. _myMulticastGroups.swap(nmg);
  607. }
  608. bool Network::tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer)
  609. {
  610. Mutex::Lock _l(_lock);
  611. if (
  612. (_isAllowed(peer)) ||
  613. (peer->address() == this->controller()) ||
  614. (RR->topology->isUpstream(peer->identity()))
  615. ) {
  616. _announceMulticastGroupsTo(peer,_allMulticastGroups());
  617. return true;
  618. }
  619. return false;
  620. }
  621. bool Network::applyConfiguration(const NetworkConfig &conf)
  622. {
  623. if (_destroyed) // sanity check
  624. return false;
  625. try {
  626. if ((conf.networkId == _id)&&(conf.issuedTo == RR->identity.address())) {
  627. ZT_VirtualNetworkConfig ctmp;
  628. bool portInitialized;
  629. {
  630. Mutex::Lock _l(_lock);
  631. _config = conf;
  632. _lastConfigUpdate = RR->node->now();
  633. _netconfFailure = NETCONF_FAILURE_NONE;
  634. _externalConfig(&ctmp);
  635. portInitialized = _portInitialized;
  636. _portInitialized = true;
  637. }
  638. _portError = RR->node->configureVirtualNetworkPort(_id,&_uPtr,(portInitialized) ? ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE : ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP,&ctmp);
  639. return true;
  640. } else {
  641. TRACE("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  642. }
  643. } catch (std::exception &exc) {
  644. TRACE("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  645. } catch ( ... ) {
  646. TRACE("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  647. }
  648. return false;
  649. }
  650. int Network::setConfiguration(const NetworkConfig &nconf,bool saveToDisk)
  651. {
  652. try {
  653. {
  654. Mutex::Lock _l(_lock);
  655. if (_config == nconf)
  656. return 1; // OK config, but duplicate of what we already have
  657. }
  658. if (applyConfiguration(nconf)) {
  659. if (saveToDisk) {
  660. char n[64];
  661. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  662. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> d;
  663. if (nconf.toDictionary(d,false))
  664. RR->node->dataStorePut(n,(const void *)d.data(),d.sizeBytes(),true);
  665. }
  666. return 2; // OK and configuration has changed
  667. }
  668. } catch ( ... ) {
  669. TRACE("ignored invalid configuration for network %.16llx",(unsigned long long)_id);
  670. }
  671. return 0;
  672. }
  673. void Network::handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize)
  674. {
  675. std::string newConfig;
  676. if ((_inboundConfigPacketId == inRePacketId)&&(totalSize < ZT_NETWORKCONFIG_DICT_CAPACITY)&&((chunkIndex + chunkSize) <= totalSize)) {
  677. Mutex::Lock _l(_lock);
  678. _inboundConfigChunks[chunkIndex].append((const char *)data,chunkSize);
  679. unsigned int totalWeHave = 0;
  680. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  681. totalWeHave += (unsigned int)c->second.length();
  682. if (totalWeHave == totalSize) {
  683. TRACE("have all chunks for network config request %.16llx, assembling...",inRePacketId);
  684. for(std::map<unsigned int,std::string>::iterator c(_inboundConfigChunks.begin());c!=_inboundConfigChunks.end();++c)
  685. newConfig.append(c->second);
  686. _inboundConfigPacketId = 0;
  687. _inboundConfigChunks.clear();
  688. } else if (totalWeHave > totalSize) {
  689. _inboundConfigPacketId = 0;
  690. _inboundConfigChunks.clear();
  691. }
  692. } else {
  693. return;
  694. }
  695. if ((newConfig.length() > 0)&&(newConfig.length() < ZT_NETWORKCONFIG_DICT_CAPACITY)) {
  696. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> *dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>(newConfig.c_str());
  697. NetworkConfig *nc = new NetworkConfig();
  698. try {
  699. Identity controllerId(RR->topology->getIdentity(this->controller()));
  700. if (controllerId) {
  701. if (nc->fromDictionary(*dict)) {
  702. this->setConfiguration(*nc,true);
  703. } else {
  704. TRACE("error parsing new config with length %u: deserialization of NetworkConfig failed (certificate error?)",(unsigned int)newConfig.length());
  705. }
  706. }
  707. delete nc;
  708. delete dict;
  709. } catch ( ... ) {
  710. TRACE("error parsing new config with length %u: unexpected exception",(unsigned int)newConfig.length());
  711. delete nc;
  712. delete dict;
  713. throw;
  714. }
  715. }
  716. }
  717. void Network::requestConfiguration()
  718. {
  719. // Sanity limit: do not request more often than once per second
  720. const uint64_t now = RR->node->now();
  721. if ((now - _lastRequestedConfiguration) < 1000ULL)
  722. return;
  723. _lastRequestedConfiguration = RR->node->now();
  724. const Address ctrl(controller());
  725. Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> rmd;
  726. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,(uint64_t)ZT_NETWORKCONFIG_VERSION);
  727. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,(uint64_t)ZT_PROTO_VERSION);
  728. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MAJOR);
  729. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,(uint64_t)ZEROTIER_ONE_VERSION_MINOR);
  730. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,(uint64_t)ZEROTIER_ONE_VERSION_REVISION);
  731. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_RULES,(uint64_t)ZT_MAX_NETWORK_RULES);
  732. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_CAPABILITIES,(uint64_t)ZT_MAX_NETWORK_CAPABILITIES);
  733. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_CAPABILITY_RULES,(uint64_t)ZT_MAX_CAPABILITY_RULES);
  734. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_MAX_NETWORK_TAGS,(uint64_t)ZT_MAX_NETWORK_TAGS);
  735. rmd.add(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_FLAGS,(uint64_t)0);
  736. if (ctrl == RR->identity.address()) {
  737. if (RR->localNetworkController) {
  738. NetworkConfig nconf;
  739. switch(RR->localNetworkController->doNetworkConfigRequest(InetAddress(),RR->identity,RR->identity,_id,rmd,nconf)) {
  740. case NetworkController::NETCONF_QUERY_OK:
  741. this->setConfiguration(nconf,true);
  742. return;
  743. case NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND:
  744. this->setNotFound();
  745. return;
  746. case NetworkController::NETCONF_QUERY_ACCESS_DENIED:
  747. this->setAccessDenied();
  748. return;
  749. default:
  750. return;
  751. }
  752. } else {
  753. this->setNotFound();
  754. return;
  755. }
  756. }
  757. TRACE("requesting netconf for network %.16llx from controller %s",(unsigned long long)_id,ctrl.toString().c_str());
  758. Packet outp(ctrl,RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  759. outp.append((uint64_t)_id);
  760. const unsigned int rmdSize = rmd.sizeBytes();
  761. outp.append((uint16_t)rmdSize);
  762. outp.append((const void *)rmd.data(),rmdSize);
  763. if (_config) {
  764. outp.append((uint64_t)_config.revision);
  765. outp.append((uint64_t)_config.timestamp);
  766. } else {
  767. outp.append((unsigned char)0,16);
  768. }
  769. outp.compress();
  770. RR->sw->send(outp,true);
  771. // Expect replies with this in-re packet ID
  772. _inboundConfigPacketId = outp.packetId();
  773. _inboundConfigChunks.clear();
  774. }
  775. void Network::clean()
  776. {
  777. const uint64_t now = RR->node->now();
  778. Mutex::Lock _l(_lock);
  779. if (_destroyed)
  780. return;
  781. {
  782. Hashtable< MulticastGroup,uint64_t >::Iterator i(_multicastGroupsBehindMe);
  783. MulticastGroup *mg = (MulticastGroup *)0;
  784. uint64_t *ts = (uint64_t *)0;
  785. while (i.next(mg,ts)) {
  786. if ((now - *ts) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  787. _multicastGroupsBehindMe.erase(*mg);
  788. }
  789. }
  790. {
  791. Address *a = (Address *)0;
  792. Membership *m = (Membership *)0;
  793. Hashtable<Address,Membership>::Iterator i(_memberships);
  794. while (i.next(a,m)) {
  795. if ((now - m->clean(now)) > ZT_MEMBERSHIP_EXPIRATION_TIME)
  796. _memberships.erase(*a);
  797. }
  798. }
  799. }
  800. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  801. {
  802. Mutex::Lock _l(_lock);
  803. _remoteBridgeRoutes[mac] = addr;
  804. // Anti-DOS circuit breaker to prevent nodes from spamming us with absurd numbers of bridge routes
  805. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  806. Hashtable< Address,unsigned long > counts;
  807. Address maxAddr;
  808. unsigned long maxCount = 0;
  809. MAC *m = (MAC *)0;
  810. Address *a = (Address *)0;
  811. // Find the address responsible for the most entries
  812. {
  813. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  814. while (i.next(m,a)) {
  815. const unsigned long c = ++counts[*a];
  816. if (c > maxCount) {
  817. maxCount = c;
  818. maxAddr = *a;
  819. }
  820. }
  821. }
  822. // Kill this address from our table, since it's most likely spamming us
  823. {
  824. Hashtable<MAC,Address>::Iterator i(_remoteBridgeRoutes);
  825. while (i.next(m,a)) {
  826. if (*a == maxAddr)
  827. _remoteBridgeRoutes.erase(*m);
  828. }
  829. }
  830. }
  831. }
  832. void Network::learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  833. {
  834. Mutex::Lock _l(_lock);
  835. const unsigned long tmp = (unsigned long)_multicastGroupsBehindMe.size();
  836. _multicastGroupsBehindMe.set(mg,now);
  837. if (tmp != _multicastGroupsBehindMe.size())
  838. _announceMulticastGroups();
  839. }
  840. void Network::destroy()
  841. {
  842. Mutex::Lock _l(_lock);
  843. _destroyed = true;
  844. }
  845. ZT_VirtualNetworkStatus Network::_status() const
  846. {
  847. // assumes _lock is locked
  848. if (_portError)
  849. return ZT_NETWORK_STATUS_PORT_ERROR;
  850. switch(_netconfFailure) {
  851. case NETCONF_FAILURE_ACCESS_DENIED:
  852. return ZT_NETWORK_STATUS_ACCESS_DENIED;
  853. case NETCONF_FAILURE_NOT_FOUND:
  854. return ZT_NETWORK_STATUS_NOT_FOUND;
  855. case NETCONF_FAILURE_NONE:
  856. return ((_config) ? ZT_NETWORK_STATUS_OK : ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION);
  857. default:
  858. return ZT_NETWORK_STATUS_PORT_ERROR;
  859. }
  860. }
  861. void Network::_externalConfig(ZT_VirtualNetworkConfig *ec) const
  862. {
  863. // assumes _lock is locked
  864. ec->nwid = _id;
  865. ec->mac = _mac.toInt();
  866. if (_config)
  867. Utils::scopy(ec->name,sizeof(ec->name),_config.name);
  868. else ec->name[0] = (char)0;
  869. ec->status = _status();
  870. ec->type = (_config) ? (_config.isPrivate() ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC) : ZT_NETWORK_TYPE_PRIVATE;
  871. ec->mtu = ZT_IF_MTU;
  872. ec->dhcp = 0;
  873. std::vector<Address> ab(_config.activeBridges());
  874. ec->bridge = ((_config.allowPassiveBridging())||(std::find(ab.begin(),ab.end(),RR->identity.address()) != ab.end())) ? 1 : 0;
  875. ec->broadcastEnabled = (_config) ? (_config.enableBroadcast() ? 1 : 0) : 0;
  876. ec->portError = _portError;
  877. ec->netconfRevision = (_config) ? (unsigned long)_config.revision : 0;
  878. ec->assignedAddressCount = 0;
  879. for(unsigned int i=0;i<ZT_MAX_ZT_ASSIGNED_ADDRESSES;++i) {
  880. if (i < _config.staticIpCount) {
  881. memcpy(&(ec->assignedAddresses[i]),&(_config.staticIps[i]),sizeof(struct sockaddr_storage));
  882. ++ec->assignedAddressCount;
  883. } else {
  884. memset(&(ec->assignedAddresses[i]),0,sizeof(struct sockaddr_storage));
  885. }
  886. }
  887. ec->routeCount = 0;
  888. for(unsigned int i=0;i<ZT_MAX_NETWORK_ROUTES;++i) {
  889. if (i < _config.routeCount) {
  890. memcpy(&(ec->routes[i]),&(_config.routes[i]),sizeof(ZT_VirtualNetworkRoute));
  891. ++ec->routeCount;
  892. } else {
  893. memset(&(ec->routes[i]),0,sizeof(ZT_VirtualNetworkRoute));
  894. }
  895. }
  896. }
  897. bool Network::_isAllowed(const SharedPtr<Peer> &peer) const
  898. {
  899. // Assumes _lock is locked
  900. try {
  901. if (_config) {
  902. const Membership *const m = _memberships.get(peer->address());
  903. if (m)
  904. return m->isAllowedOnNetwork(_config);
  905. }
  906. } catch ( ... ) {
  907. TRACE("isAllowed() check failed for peer %s: unexpected exception",peer->address().toString().c_str());
  908. }
  909. return false;
  910. }
  911. class _MulticastAnnounceAll
  912. {
  913. public:
  914. _MulticastAnnounceAll(const RuntimeEnvironment *renv,Network *nw) :
  915. _now(renv->node->now()),
  916. _controller(nw->controller()),
  917. _network(nw),
  918. _anchors(nw->config().anchors()),
  919. _upstreamAddresses(renv->topology->upstreamAddresses())
  920. {}
  921. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  922. {
  923. if ( (_network->_isAllowed(p)) || // FIXME: this causes multicast LIKEs for public networks to get spammed, which isn't terrible but is a bit stupid
  924. (p->address() == _controller) ||
  925. (std::find(_upstreamAddresses.begin(),_upstreamAddresses.end(),p->address()) != _upstreamAddresses.end()) ||
  926. (std::find(_anchors.begin(),_anchors.end(),p->address()) != _anchors.end()) ) {
  927. peers.push_back(p);
  928. }
  929. }
  930. std::vector< SharedPtr<Peer> > peers;
  931. private:
  932. const uint64_t _now;
  933. const Address _controller;
  934. Network *const _network;
  935. const std::vector<Address> _anchors;
  936. const std::vector<Address> _upstreamAddresses;
  937. };
  938. void Network::_announceMulticastGroups()
  939. {
  940. // Assumes _lock is locked
  941. std::vector<MulticastGroup> allMulticastGroups(_allMulticastGroups());
  942. _MulticastAnnounceAll gpfunc(RR,this);
  943. RR->topology->eachPeer<_MulticastAnnounceAll &>(gpfunc);
  944. for(std::vector< SharedPtr<Peer> >::const_iterator i(gpfunc.peers.begin());i!=gpfunc.peers.end();++i)
  945. _announceMulticastGroupsTo(*i,allMulticastGroups);
  946. }
  947. void Network::_announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups)
  948. {
  949. // Assumes _lock is locked
  950. // Anyone we announce multicast groups to will need our COM to authenticate GATHER requests.
  951. {
  952. Membership *m = _memberships.get(peer->address());
  953. if (m)
  954. m->sendCredentialsIfNeeded(RR,RR->node->now(),peer->address(),_config.com,(const Capability *)0,(const Tag **)0,0);
  955. }
  956. Packet outp(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  957. for(std::vector<MulticastGroup>::const_iterator mg(allMulticastGroups.begin());mg!=allMulticastGroups.end();++mg) {
  958. if ((outp.size() + 24) >= ZT_PROTO_MAX_PACKET_LENGTH) {
  959. outp.compress();
  960. RR->sw->send(outp,true);
  961. outp.reset(peer->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  962. }
  963. // network ID, MAC, ADI
  964. outp.append((uint64_t)_id);
  965. mg->mac().appendTo(outp);
  966. outp.append((uint32_t)mg->adi());
  967. }
  968. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  969. outp.compress();
  970. RR->sw->send(outp,true);
  971. }
  972. }
  973. std::vector<MulticastGroup> Network::_allMulticastGroups() const
  974. {
  975. // Assumes _lock is locked
  976. std::vector<MulticastGroup> mgs;
  977. mgs.reserve(_myMulticastGroups.size() + _multicastGroupsBehindMe.size() + 1);
  978. mgs.insert(mgs.end(),_myMulticastGroups.begin(),_myMulticastGroups.end());
  979. _multicastGroupsBehindMe.appendKeys(mgs);
  980. if ((_config)&&(_config.enableBroadcast()))
  981. mgs.push_back(Network::BROADCAST);
  982. std::sort(mgs.begin(),mgs.end());
  983. mgs.erase(std::unique(mgs.begin(),mgs.end()),mgs.end());
  984. return mgs;
  985. }
  986. } // namespace ZeroTier