Network.cpp 41 KB

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