Network.cpp 47 KB

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