Network.cpp 44 KB

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