Network.cpp 41 KB

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