Network.cpp 44 KB

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