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