Network.cpp 41 KB

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