Network.cpp 41 KB

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