Network.cpp 46 KB

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