EmbeddedNetworkController.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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 <stdint.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <time.h>
  23. #ifndef _WIN32
  24. #include <sys/time.h>
  25. #endif
  26. #include <sys/types.h>
  27. #include <algorithm>
  28. #include <utility>
  29. #include <stdexcept>
  30. #include <set>
  31. #include <map>
  32. #include "../include/ZeroTierOne.h"
  33. #include "../node/Constants.hpp"
  34. #include "EmbeddedNetworkController.hpp"
  35. #include "../node/Node.hpp"
  36. #include "../node/Utils.hpp"
  37. #include "../node/CertificateOfMembership.hpp"
  38. #include "../node/NetworkConfig.hpp"
  39. #include "../node/Dictionary.hpp"
  40. #include "../node/InetAddress.hpp"
  41. #include "../node/MAC.hpp"
  42. #include "../node/Address.hpp"
  43. using json = nlohmann::json;
  44. // API version reported via JSON control plane
  45. #define ZT_NETCONF_CONTROLLER_API_VERSION 3
  46. // Number of requests to remember in member history
  47. #define ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH 24
  48. // Min duration between requests for an address/nwid combo to prevent floods
  49. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  50. // Nodes are considered active if they've queried in less than this long
  51. #define ZT_NETCONF_NODE_ACTIVE_THRESHOLD (ZT_NETWORK_AUTOCONF_DELAY * 2)
  52. namespace ZeroTier {
  53. // JSON blob I/O
  54. /*
  55. static json _readJson(const std::string &path)
  56. {
  57. std::string buf;
  58. if (OSUtils::readFile(path.c_str(),buf)) {
  59. try {
  60. return json::parse(buf);
  61. } catch ( ... ) {}
  62. }
  63. return json::object();
  64. }
  65. static bool _writeJson(const std::string &path,const json &obj)
  66. {
  67. return OSUtils::writeFile(path.c_str(),obj.dump(2));
  68. }
  69. */
  70. // Get JSON values as unsigned integers, strings, or booleans, doing type conversion if possible
  71. static uint64_t _jI(const json &jv,const uint64_t dfl)
  72. {
  73. if (jv.is_number()) {
  74. return (uint64_t)jv;
  75. } else if (jv.is_string()) {
  76. std::string s = jv;
  77. return Utils::strToU64(s.c_str());
  78. } else if (jv.is_boolean()) {
  79. return ((bool)jv ? 1ULL : 0ULL);
  80. }
  81. return dfl;
  82. }
  83. static bool _jB(const json &jv,const bool dfl)
  84. {
  85. if (jv.is_boolean()) {
  86. return (bool)jv;
  87. } else if (jv.is_number()) {
  88. return ((uint64_t)jv > 0ULL);
  89. } else if (jv.is_string()) {
  90. std::string s = jv;
  91. if (s.length() > 0) {
  92. switch(s[0]) {
  93. case 't':
  94. case 'T':
  95. case '1':
  96. return true;
  97. }
  98. }
  99. return false;
  100. }
  101. return dfl;
  102. }
  103. static std::string _jS(const json &jv,const char *dfl)
  104. {
  105. if (jv.is_string()) {
  106. return jv;
  107. } else if (jv.is_number()) {
  108. char tmp[64];
  109. Utils::snprintf(tmp,sizeof(tmp),"%llu",(uint64_t)jv);
  110. return tmp;
  111. } else if (jv.is_boolean()) {
  112. return ((bool)jv ? std::string("1") : std::string("0"));
  113. }
  114. return std::string((dfl) ? dfl : "");
  115. }
  116. static json _renderRule(ZT_VirtualNetworkRule &rule)
  117. {
  118. char tmp[128];
  119. json r = json::object();
  120. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rule.t & 0x3f);
  121. switch(rt) {
  122. case ZT_NETWORK_RULE_ACTION_DROP:
  123. r["type"] = "ACTION_DROP";
  124. break;
  125. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  126. r["type"] = "ACTION_ACCEPT";
  127. break;
  128. case ZT_NETWORK_RULE_ACTION_TEE:
  129. r["type"] = "ACTION_TEE";
  130. r["address"] = Address(rule.v.fwd.address).toString();
  131. r["flags"] = (unsigned int)rule.v.fwd.flags;
  132. r["length"] = (unsigned int)rule.v.fwd.length;
  133. break;
  134. case ZT_NETWORK_RULE_ACTION_WATCH:
  135. r["type"] = "ACTION_WATCH";
  136. r["address"] = Address(rule.v.fwd.address).toString();
  137. r["flags"] = (unsigned int)rule.v.fwd.flags;
  138. r["length"] = (unsigned int)rule.v.fwd.length;
  139. break;
  140. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  141. r["type"] = "ACTION_REDIRECT";
  142. r["address"] = Address(rule.v.fwd.address).toString();
  143. r["flags"] = (unsigned int)rule.v.fwd.flags;
  144. break;
  145. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG:
  146. r["type"] = "ACTION_DEBUG_LOG";
  147. break;
  148. default:
  149. break;
  150. }
  151. if (r.size() == 0) {
  152. switch(rt) {
  153. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  154. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  155. r["zt"] = Address(rule.v.zt).toString();
  156. break;
  157. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  158. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  159. r["zt"] = Address(rule.v.zt).toString();
  160. break;
  161. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  162. r["type"] = "MATCH_VLAN_ID";
  163. r["vlanId"] = (unsigned int)rule.v.vlanId;
  164. break;
  165. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  166. r["type"] = "MATCH_VLAN_PCP";
  167. r["vlanPcp"] = (unsigned int)rule.v.vlanPcp;
  168. break;
  169. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  170. r["type"] = "MATCH_VLAN_DEI";
  171. r["vlanDei"] = (unsigned int)rule.v.vlanDei;
  172. break;
  173. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  174. r["type"] = "MATCH_MAC_SOURCE";
  175. Utils::snprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  176. r["mac"] = tmp;
  177. break;
  178. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  179. r["type"] = "MATCH_MAC_DEST";
  180. Utils::snprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  181. r["mac"] = tmp;
  182. break;
  183. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  184. r["type"] = "MATCH_IPV4_SOURCE";
  185. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString();
  186. break;
  187. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  188. r["type"] = "MATCH_IPV4_DEST";
  189. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString();
  190. break;
  191. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  192. r["type"] = "MATCH_IPV6_SOURCE";
  193. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString();
  194. break;
  195. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  196. r["type"] = "MATCH_IPV6_DEST";
  197. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString();
  198. break;
  199. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  200. r["type"] = "MATCH_IP_TOS";
  201. r["ipTos"] = (unsigned int)rule.v.ipTos;
  202. break;
  203. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  204. r["type"] = "MATCH_IP_PROTOCOL";
  205. r["ipProtocol"] = (unsigned int)rule.v.ipProtocol;
  206. break;
  207. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  208. r["type"] = "MATCH_ETHERTYPE";
  209. r["etherType"] = (unsigned int)rule.v.etherType;
  210. break;
  211. case ZT_NETWORK_RULE_MATCH_ICMP:
  212. r["type"] = "MATCH_ICMP";
  213. r["icmpType"] = (unsigned int)rule.v.icmp.type;
  214. if ((rule.v.icmp.flags & 0x01) != 0)
  215. r["icmpCode"] = (unsigned int)rule.v.icmp.code;
  216. else r["icmpCode"] = json();
  217. break;
  218. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  219. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  220. r["start"] = (unsigned int)rule.v.port[0];
  221. r["end"] = (unsigned int)rule.v.port[1];
  222. break;
  223. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  224. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  225. r["start"] = (unsigned int)rule.v.port[0];
  226. r["end"] = (unsigned int)rule.v.port[1];
  227. break;
  228. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  229. r["type"] = "MATCH_CHARACTERISTICS";
  230. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics);
  231. r["mask"] = tmp;
  232. break;
  233. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  234. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  235. r["start"] = (unsigned int)rule.v.frameSize[0];
  236. r["end"] = (unsigned int)rule.v.frameSize[1];
  237. break;
  238. case ZT_NETWORK_RULE_MATCH_RANDOM:
  239. r["type"] = "MATCH_RANDOM";
  240. r["probability"] = (unsigned long)rule.v.randomProbability;
  241. break;
  242. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  243. r["type"] = "MATCH_TAGS_DIFFERENCE";
  244. r["id"] = rule.v.tag.id;
  245. r["value"] = rule.v.tag.value;
  246. break;
  247. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  248. r["type"] = "MATCH_TAGS_BITWISE_AND";
  249. r["id"] = rule.v.tag.id;
  250. r["value"] = rule.v.tag.value;
  251. break;
  252. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  253. r["type"] = "MATCH_TAGS_BITWISE_OR";
  254. r["id"] = rule.v.tag.id;
  255. r["value"] = rule.v.tag.value;
  256. break;
  257. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  258. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  259. r["id"] = rule.v.tag.id;
  260. r["value"] = rule.v.tag.value;
  261. break;
  262. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL:
  263. r["type"] = "MATCH_TAGS_EQUAL";
  264. r["id"] = rule.v.tag.id;
  265. r["value"] = rule.v.tag.value;
  266. break;
  267. default:
  268. break;
  269. }
  270. if (r.size() > 0) {
  271. r["not"] = ((rule.t & 0x80) != 0);
  272. r["or"] = ((rule.t & 0x40) != 0);
  273. }
  274. }
  275. return r;
  276. }
  277. static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
  278. {
  279. if (!r.is_object())
  280. return false;
  281. const std::string t(_jS(r["type"],""));
  282. memset(&rule,0,sizeof(ZT_VirtualNetworkRule));
  283. if (_jB(r["not"],false))
  284. rule.t = 0x80;
  285. else rule.t = 0x00;
  286. if (_jB(r["or"],false))
  287. rule.t |= 0x40;
  288. if (t == "ACTION_DROP") {
  289. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  290. return true;
  291. } else if (t == "ACTION_ACCEPT") {
  292. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  293. return true;
  294. } else if (t == "ACTION_TEE") {
  295. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  296. rule.v.fwd.address = Utils::hexStrToU64(_jS(r["address"],"0").c_str()) & 0xffffffffffULL;
  297. rule.v.fwd.flags = (uint32_t)(_jI(r["flags"],0ULL) & 0xffffffffULL);
  298. rule.v.fwd.length = (uint16_t)(_jI(r["length"],0ULL) & 0xffffULL);
  299. return true;
  300. } else if (t == "ACTION_WATCH") {
  301. rule.t |= ZT_NETWORK_RULE_ACTION_WATCH;
  302. rule.v.fwd.address = Utils::hexStrToU64(_jS(r["address"],"0").c_str()) & 0xffffffffffULL;
  303. rule.v.fwd.flags = (uint32_t)(_jI(r["flags"],0ULL) & 0xffffffffULL);
  304. rule.v.fwd.length = (uint16_t)(_jI(r["length"],0ULL) & 0xffffULL);
  305. return true;
  306. } else if (t == "ACTION_REDIRECT") {
  307. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  308. rule.v.fwd.address = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  309. rule.v.fwd.flags = (uint32_t)(_jI(r["flags"],0ULL) & 0xffffffffULL);
  310. return true;
  311. } else if (t == "ACTION_DEBUG_LOG") {
  312. rule.t |= ZT_NETWORK_RULE_ACTION_DEBUG_LOG;
  313. return true;
  314. } else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  315. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  316. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  317. return true;
  318. } else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  319. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  320. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  321. return true;
  322. } else if (t == "MATCH_VLAN_ID") {
  323. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  324. rule.v.vlanId = (uint16_t)(_jI(r["vlanId"],0ULL) & 0xffffULL);
  325. return true;
  326. } else if (t == "MATCH_VLAN_PCP") {
  327. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  328. rule.v.vlanPcp = (uint8_t)(_jI(r["vlanPcp"],0ULL) & 0xffULL);
  329. return true;
  330. } else if (t == "MATCH_VLAN_DEI") {
  331. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  332. rule.v.vlanDei = (uint8_t)(_jI(r["vlanDei"],0ULL) & 0xffULL);
  333. return true;
  334. } else if (t == "MATCH_MAC_SOURCE") {
  335. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  336. const std::string mac(_jS(r["mac"],"0"));
  337. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  338. return true;
  339. } else if (t == "MATCH_MAC_DEST") {
  340. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  341. const std::string mac(_jS(r["mac"],"0"));
  342. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  343. return true;
  344. } else if (t == "MATCH_IPV4_SOURCE") {
  345. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  346. InetAddress ip(_jS(r["ip"],"0.0.0.0"));
  347. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  348. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  349. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  350. return true;
  351. } else if (t == "MATCH_IPV4_DEST") {
  352. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  353. InetAddress ip(_jS(r["ip"],"0.0.0.0"));
  354. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  355. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  356. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  357. return true;
  358. } else if (t == "MATCH_IPV6_SOURCE") {
  359. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  360. InetAddress ip(_jS(r["ip"],"::0"));
  361. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  362. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  363. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  364. return true;
  365. } else if (t == "MATCH_IPV6_DEST") {
  366. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  367. InetAddress ip(_jS(r["ip"],"::0"));
  368. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  369. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  370. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  371. return true;
  372. } else if (t == "MATCH_IP_TOS") {
  373. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  374. rule.v.ipTos = (uint8_t)(_jI(r["ipTos"],0ULL) & 0xffULL);
  375. return true;
  376. } else if (t == "MATCH_IP_PROTOCOL") {
  377. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  378. rule.v.ipProtocol = (uint8_t)(_jI(r["ipProtocol"],0ULL) & 0xffULL);
  379. return true;
  380. } else if (t == "MATCH_ETHERTYPE") {
  381. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  382. rule.v.etherType = (uint16_t)(_jI(r["etherType"],0ULL) & 0xffffULL);
  383. return true;
  384. } else if (t == "MATCH_ICMP") {
  385. rule.t |= ZT_NETWORK_RULE_MATCH_ICMP;
  386. rule.v.icmp.type = (uint8_t)(_jI(r["icmpType"],0ULL) & 0xffULL);
  387. json &code = r["icmpCode"];
  388. if (code.is_null()) {
  389. rule.v.icmp.code = 0;
  390. rule.v.icmp.flags = 0x00;
  391. } else {
  392. rule.v.icmp.code = (uint8_t)(_jI(code,0ULL) & 0xffULL);
  393. rule.v.icmp.flags = 0x01;
  394. }
  395. return true;
  396. } else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  397. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  398. rule.v.port[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  399. rule.v.port[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  400. return true;
  401. } else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  402. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  403. rule.v.port[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  404. rule.v.port[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  405. return true;
  406. } else if (t == "MATCH_CHARACTERISTICS") {
  407. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  408. if (r.count("mask")) {
  409. json &v = r["mask"];
  410. if (v.is_number()) {
  411. rule.v.characteristics = v;
  412. } else {
  413. std::string tmp = v;
  414. rule.v.characteristics = Utils::hexStrToU64(tmp.c_str());
  415. }
  416. }
  417. return true;
  418. } else if (t == "MATCH_FRAME_SIZE_RANGE") {
  419. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  420. rule.v.frameSize[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  421. rule.v.frameSize[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  422. return true;
  423. } else if (t == "MATCH_RANDOM") {
  424. rule.t |= ZT_NETWORK_RULE_MATCH_RANDOM;
  425. rule.v.randomProbability = (uint32_t)(_jI(r["probability"],0ULL) & 0xffffffffULL);
  426. } else if (t == "MATCH_TAGS_DIFFERENCE") {
  427. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE;
  428. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  429. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  430. return true;
  431. } else if (t == "MATCH_TAGS_BITWISE_AND") {
  432. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  433. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  434. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  435. return true;
  436. } else if (t == "MATCH_TAGS_BITWISE_OR") {
  437. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  438. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  439. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  440. return true;
  441. } else if (t == "MATCH_TAGS_BITWISE_XOR") {
  442. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  443. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  444. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  445. return true;
  446. } else if (t == "MATCH_TAGS_EQUAL") {
  447. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_EQUAL;
  448. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  449. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  450. return true;
  451. }
  452. return false;
  453. }
  454. EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *dbPath) :
  455. _db(dbPath),
  456. _node(node)
  457. {
  458. OSUtils::mkdir(dbPath);
  459. OSUtils::lockDownFile(dbPath,true); // networks might contain auth tokens, etc., so restrict directory permissions
  460. }
  461. EmbeddedNetworkController::~EmbeddedNetworkController()
  462. {
  463. }
  464. NetworkController::ResultCode EmbeddedNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData,NetworkConfig &nc)
  465. {
  466. if (((!signingId)||(!signingId.hasPrivate()))||(signingId.address().toInt() != (nwid >> 24))) {
  467. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  468. }
  469. const uint64_t now = OSUtils::now();
  470. // Check rate limit circuit breaker to prevent flooding
  471. {
  472. Mutex::Lock _l(_lastRequestTime_m);
  473. uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
  474. if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  475. return NetworkController::NETCONF_QUERY_IGNORE;
  476. lrt = now;
  477. }
  478. char nwids[24];
  479. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  480. json network;
  481. json member;
  482. {
  483. Mutex::Lock _l(_db_m);
  484. network = _db.get("network",nwids,0);
  485. member = _db.get("network",nwids,"member",identity.address().toString(),0);
  486. }
  487. if (!network.size())
  488. return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
  489. _initMember(member);
  490. {
  491. std::string haveIdStr(_jS(member["identity"],""));
  492. if (haveIdStr.length() > 0) {
  493. // If we already know this member's identity perform a full compare. This prevents
  494. // a "collision" from being able to auth onto our network in place of an already
  495. // known member.
  496. try {
  497. if (Identity(haveIdStr.c_str()) != identity)
  498. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  499. } catch ( ... ) {
  500. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  501. }
  502. } else {
  503. // If we do not yet know this member's identity, learn it.
  504. member["identity"] = identity.toString(false);
  505. }
  506. }
  507. // These are always the same, but make sure they are set
  508. member["id"] = identity.address().toString();
  509. member["address"] = member["id"];
  510. member["nwid"] = network["id"];
  511. // Determine whether and how member is authorized
  512. const char *authorizedBy = (const char *)0;
  513. if (_jB(member["authorized"],false)) {
  514. authorizedBy = "memberIsAuthorized";
  515. } else if (!_jB(network["private"],true)) {
  516. authorizedBy = "networkIsPublic";
  517. if (!member.count("authorized")) {
  518. member["authorized"] = true;
  519. json ah;
  520. ah["a"] = true;
  521. ah["by"] = authorizedBy;
  522. ah["ts"] = now;
  523. ah["ct"] = json();
  524. ah["c"] = json();
  525. member["authHistory"].push_back(ah);
  526. member["lastModified"] = now;
  527. json &revj = member["revision"];
  528. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  529. }
  530. } else {
  531. char presentedAuth[512];
  532. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  533. presentedAuth[511] = (char)0; // sanity check
  534. // Check for bearer token presented by member
  535. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  536. const char *const presentedToken = presentedAuth + 6;
  537. json &authTokens = network["authTokens"];
  538. if (authTokens.is_array()) {
  539. for(unsigned long i=0;i<authTokens.size();++i) {
  540. json &token = authTokens[i];
  541. if (token.is_object()) {
  542. const uint64_t expires = _jI(token["expires"],0ULL);
  543. const uint64_t maxUses = _jI(token["maxUsesPerMember"],0ULL);
  544. std::string tstr = _jS(token["token"],"");
  545. if (((expires == 0ULL)||(expires > now))&&(tstr == presentedToken)) {
  546. bool usable = (maxUses == 0);
  547. if (!usable) {
  548. uint64_t useCount = 0;
  549. json &ahist = member["authHistory"];
  550. if (ahist.is_array()) {
  551. for(unsigned long j=0;j<ahist.size();++j) {
  552. json &ah = ahist[j];
  553. if ((_jS(ah["ct"],"") == "token")&&(_jS(ah["c"],"") == tstr)&&(_jB(ah["a"],false)))
  554. ++useCount;
  555. }
  556. }
  557. usable = (useCount < maxUses);
  558. }
  559. if (usable) {
  560. authorizedBy = "token";
  561. member["authorized"] = true;
  562. json ah;
  563. ah["a"] = true;
  564. ah["by"] = authorizedBy;
  565. ah["ts"] = now;
  566. ah["ct"] = "token";
  567. ah["c"] = tstr;
  568. member["authHistory"].push_back(ah);
  569. member["lastModified"] = now;
  570. json &revj = member["revision"];
  571. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  572. }
  573. }
  574. }
  575. }
  576. }
  577. }
  578. }
  579. }
  580. // Log this request
  581. {
  582. json rlEntry = json::object();
  583. rlEntry["ts"] = now;
  584. rlEntry["authorized"] = (authorizedBy) ? true : false;
  585. rlEntry["authorizedBy"] = (authorizedBy) ? authorizedBy : "";
  586. rlEntry["clientMajorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  587. rlEntry["clientMinorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  588. rlEntry["clientRevision"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  589. rlEntry["clientProtocolVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  590. if (fromAddr)
  591. rlEntry["fromAddr"] = fromAddr.toString();
  592. json recentLog = json::array();
  593. recentLog.push_back(rlEntry);
  594. json &oldLog = member["recentLog"];
  595. if (oldLog.is_array()) {
  596. for(unsigned long i=0;i<oldLog.size();++i) {
  597. recentLog.push_back(oldLog[i]);
  598. if (recentLog.size() >= ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
  599. break;
  600. }
  601. }
  602. member["recentLog"] = recentLog;
  603. }
  604. // If they are not authorized, STOP!
  605. if (!authorizedBy) {
  606. Mutex::Lock _l(_db_m);
  607. _db.put("network",nwids,"member",identity.address().toString(),member);
  608. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  609. }
  610. // -------------------------------------------------------------------------
  611. // If we made it this far, they are authorized.
  612. // -------------------------------------------------------------------------
  613. _NetworkMemberInfo nmi;
  614. _getNetworkMemberInfo(now,nwid,nmi);
  615. // Compute credential TTL. This is the "moving window" for COM agreement and
  616. // the global TTL for Capability and Tag objects. (The same value is used
  617. // for both.) This is computed by reference to the last time we deauthorized
  618. // a member, since within the time period since this event any temporal
  619. // differences are not particularly relevant.
  620. uint64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
  621. if (now > nmi.mostRecentDeauthTime)
  622. credentialtmd += (now - nmi.mostRecentDeauthTime);
  623. if (credentialtmd > ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA)
  624. credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  625. nc.networkId = nwid;
  626. nc.type = _jB(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  627. nc.timestamp = now;
  628. nc.credentialTimeMaxDelta = credentialtmd;
  629. nc.revision = _jI(network["revision"],0ULL);
  630. nc.issuedTo = identity.address();
  631. if (_jB(network["enableBroadcast"],true)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  632. if (_jB(network["allowPassiveBridging"],false)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
  633. Utils::scopy(nc.name,sizeof(nc.name),_jS(network["name"],"").c_str());
  634. nc.multicastLimit = (unsigned int)_jI(network["multicastLimit"],32ULL);
  635. for(std::set<Address>::const_iterator ab(nmi.activeBridges.begin());ab!=nmi.activeBridges.end();++ab)
  636. nc.addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  637. json &v4AssignMode = network["v4AssignMode"];
  638. json &v6AssignMode = network["v6AssignMode"];
  639. json &ipAssignmentPools = network["ipAssignmentPools"];
  640. json &routes = network["routes"];
  641. json &rules = network["rules"];
  642. json &capabilities = network["capabilities"];
  643. json &memberCapabilities = member["capabilities"];
  644. json &memberTags = member["tags"];
  645. if (rules.is_array()) {
  646. for(unsigned long i=0;i<rules.size();++i) {
  647. if (nc.ruleCount >= ZT_MAX_NETWORK_RULES)
  648. break;
  649. if (_parseRule(rules[i],nc.rules[nc.ruleCount]))
  650. ++nc.ruleCount;
  651. }
  652. }
  653. if ((memberCapabilities.is_array())&&(memberCapabilities.size() > 0)&&(capabilities.is_array())) {
  654. std::map< uint64_t,json * > capsById;
  655. for(unsigned long i=0;i<capabilities.size();++i) {
  656. json &cap = capabilities[i];
  657. if (cap.is_object())
  658. capsById[_jI(cap["id"],0ULL) & 0xffffffffULL] = &cap;
  659. }
  660. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  661. const uint64_t capId = _jI(memberCapabilities[i],0ULL) & 0xffffffffULL;
  662. json *cap = capsById[capId];
  663. if ((cap->is_object())&&(cap->size() > 0)) {
  664. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  665. unsigned int caprc = 0;
  666. json &caprj = (*cap)["rules"];
  667. if ((caprj.is_array())&&(caprj.size() > 0)) {
  668. for(unsigned long j=0;j<caprj.size();++j) {
  669. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  670. break;
  671. if (_parseRule(caprj[j],capr[caprc]))
  672. ++caprc;
  673. }
  674. }
  675. nc.capabilities[nc.capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  676. if (nc.capabilities[nc.capabilityCount].sign(signingId,identity.address()))
  677. ++nc.capabilityCount;
  678. if (nc.capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  679. break;
  680. }
  681. }
  682. }
  683. if (memberTags.is_array()) {
  684. std::map< uint32_t,uint32_t > tagsById;
  685. for(unsigned long i=0;i<memberTags.size();++i) {
  686. json &t = memberTags[i];
  687. if ((t.is_array())&&(t.size() == 2))
  688. tagsById[(uint32_t)(_jI(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(_jI(t[1],0ULL) & 0xffffffffULL);
  689. }
  690. for(std::map< uint32_t,uint32_t >::const_iterator t(tagsById.begin());t!=tagsById.end();++t) {
  691. if (nc.tagCount >= ZT_MAX_NETWORK_TAGS)
  692. break;
  693. nc.tags[nc.tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  694. if (nc.tags[nc.tagCount].sign(signingId))
  695. ++nc.tagCount;
  696. }
  697. }
  698. if (routes.is_array()) {
  699. for(unsigned long i=0;i<routes.size();++i) {
  700. if (nc.routeCount >= ZT_MAX_NETWORK_ROUTES)
  701. break;
  702. json &route = routes[i];
  703. json &target = route["target"];
  704. json &via = route["via"];
  705. if (target.is_string()) {
  706. const InetAddress t(target.get<std::string>());
  707. InetAddress v;
  708. if (via.is_string()) v.fromString(via.get<std::string>());
  709. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  710. ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
  711. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  712. if (v.ss_family == t.ss_family)
  713. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  714. ++nc.routeCount;
  715. }
  716. }
  717. }
  718. }
  719. const bool noAutoAssignIps = _jB(member["noAutoAssignIps"],false);
  720. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  721. if ((_jB(v6AssignMode["rfc4193"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  722. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  723. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  724. }
  725. if ((_jB(v6AssignMode["6plane"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  726. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  727. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  728. }
  729. }
  730. bool haveManagedIpv4AutoAssignment = false;
  731. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  732. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  733. if (ipAssignments.is_array()) {
  734. for(unsigned long i=0;i<ipAssignments.size();++i) {
  735. if (!ipAssignments[i].is_string())
  736. continue;
  737. std::string ips = ipAssignments[i];
  738. InetAddress ip(ips);
  739. // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
  740. // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
  741. // of user error / poor UX.
  742. int routedNetmaskBits = 0;
  743. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  744. if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
  745. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  746. }
  747. if (routedNetmaskBits > 0) {
  748. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  749. ip.setPort(routedNetmaskBits);
  750. nc.staticIps[nc.staticIpCount++] = ip;
  751. }
  752. if (ip.ss_family == AF_INET)
  753. haveManagedIpv4AutoAssignment = true;
  754. else if (ip.ss_family == AF_INET6)
  755. haveManagedIpv6AutoAssignment = true;
  756. }
  757. }
  758. } else {
  759. ipAssignments = json::array();
  760. }
  761. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(_jB(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  762. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  763. json &pool = ipAssignmentPools[p];
  764. if (pool.is_object()) {
  765. InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
  766. InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
  767. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  768. uint64_t s[2],e[2],x[2],xx[2];
  769. memcpy(s,ipRangeStart.rawIpData(),16);
  770. memcpy(e,ipRangeEnd.rawIpData(),16);
  771. s[0] = Utils::ntoh(s[0]);
  772. s[1] = Utils::ntoh(s[1]);
  773. e[0] = Utils::ntoh(e[0]);
  774. e[1] = Utils::ntoh(e[1]);
  775. x[0] = s[0];
  776. x[1] = s[1];
  777. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  778. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  779. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  780. xx[0] = Utils::hton(x[0]);
  781. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  782. } else {
  783. // Otherwise pick random addresses -- this technically doesn't explore the whole range if the lower 64 bit range is >= 1 but that won't matter since that would be huge anyway
  784. Utils::getSecureRandom((void *)xx,16);
  785. if ((e[0] > s[0]))
  786. xx[0] %= (e[0] - s[0]);
  787. else xx[0] = 0;
  788. if ((e[1] > s[1]))
  789. xx[1] %= (e[1] - s[1]);
  790. else xx[1] = 0;
  791. xx[0] = Utils::hton(x[0] + xx[0]);
  792. xx[1] = Utils::hton(x[1] + xx[1]);
  793. }
  794. InetAddress ip6((const void *)xx,16,0);
  795. // Check if this IP is within a local-to-Ethernet routed network
  796. int routedNetmaskBits = 0;
  797. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  798. if ( (!nc.routes[rk].via.ss_family) && (nc.routes[rk].target.ss_family == AF_INET6) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip6)) )
  799. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  800. }
  801. // If it's routed, then try to claim and assign it and if successful end loop
  802. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip6))) {
  803. ipAssignments.push_back(ip6.toIpString());
  804. member["ipAssignments"] = ipAssignments;
  805. ip6.setPort((unsigned int)routedNetmaskBits);
  806. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  807. nc.staticIps[nc.staticIpCount++] = ip6;
  808. haveManagedIpv6AutoAssignment = true;
  809. break;
  810. }
  811. }
  812. }
  813. }
  814. }
  815. }
  816. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(_jB(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  817. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  818. json &pool = ipAssignmentPools[p];
  819. if (pool.is_object()) {
  820. InetAddress ipRangeStartIA(_jS(pool["ipRangeStart"],""));
  821. InetAddress ipRangeEndIA(_jS(pool["ipRangeEnd"],""));
  822. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  823. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  824. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  825. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  826. continue;
  827. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  828. // Start with the LSB of the member's address
  829. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  830. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  831. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  832. ++ipTrialCounter;
  833. if ((ip & 0x000000ff) == 0x000000ff)
  834. continue; // don't allow addresses that end in .255
  835. // Check if this IP is within a local-to-Ethernet routed network
  836. int routedNetmaskBits = -1;
  837. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  838. if (nc.routes[rk].target.ss_family == AF_INET) {
  839. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
  840. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
  841. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  842. routedNetmaskBits = targetBits;
  843. break;
  844. }
  845. }
  846. }
  847. // If it's routed, then try to claim and assign it and if successful end loop
  848. const InetAddress ip4(Utils::hton(ip),0);
  849. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip4))) {
  850. ipAssignments.push_back(ip4.toIpString());
  851. member["ipAssignments"] = ipAssignments;
  852. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  853. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
  854. v4ip->sin_family = AF_INET;
  855. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  856. v4ip->sin_addr.s_addr = Utils::hton(ip);
  857. }
  858. haveManagedIpv4AutoAssignment = true;
  859. break;
  860. }
  861. }
  862. }
  863. }
  864. }
  865. }
  866. CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
  867. if (com.sign(signingId)) {
  868. nc.com = com;
  869. } else {
  870. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  871. }
  872. {
  873. Mutex::Lock _l(_db_m);
  874. _db.put("network",nwids,"member",identity.address().toString(),member);
  875. }
  876. return NetworkController::NETCONF_QUERY_OK;
  877. }
  878. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  879. const std::vector<std::string> &path,
  880. const std::map<std::string,std::string> &urlArgs,
  881. const std::map<std::string,std::string> &headers,
  882. const std::string &body,
  883. std::string &responseBody,
  884. std::string &responseContentType)
  885. {
  886. if ((path.size() > 0)&&(path[0] == "network")) {
  887. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  888. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  889. char nwids[24];
  890. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  891. json network;
  892. {
  893. Mutex::Lock _l(_db_m);
  894. network = _db.get("network",nwids,0);
  895. }
  896. if (!network.size())
  897. return 404;
  898. if (path.size() >= 3) {
  899. if (path[2] == "member") {
  900. if (path.size() >= 4) {
  901. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  902. json member;
  903. {
  904. Mutex::Lock _l(_db_m);
  905. member = _db.get("network",nwids,"member",Address(address).toString(),0);
  906. }
  907. if (!member.size())
  908. return 404;
  909. _addMemberNonPersistedFields(member,OSUtils::now());
  910. responseBody = member.dump(2);
  911. responseContentType = "application/json";
  912. return 200;
  913. } else {
  914. Mutex::Lock _l(_db_m);
  915. responseBody = "{";
  916. std::string pfx(std::string("network/") + nwids + "member/");
  917. _db.filter(pfx,120000,[&responseBody](const std::string &n,const json &member) {
  918. if (member.size() > 0) {
  919. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  920. responseBody.append(_jS(member["id"],""));
  921. responseBody.append("\":");
  922. responseBody.append(_jS(member["revision"],"0"));
  923. }
  924. return true; // never delete
  925. });
  926. responseBody.push_back('}');
  927. responseContentType = "application/json";
  928. return 200;
  929. }
  930. } else if ((path[2] == "test")&&(path.size() >= 4)) {
  931. Mutex::Lock _l(_circuitTests_m);
  932. std::map< uint64_t,_CircuitTestEntry >::iterator cte(_circuitTests.find(Utils::hexStrToU64(path[3].c_str())));
  933. if ((cte != _circuitTests.end())&&(cte->second.test)) {
  934. responseBody = "[";
  935. responseBody.append(cte->second.jsonResults);
  936. responseBody.push_back(']');
  937. responseContentType = "application/json";
  938. return 200;
  939. } // else 404
  940. } // else 404
  941. } else {
  942. const uint64_t now = OSUtils::now();
  943. _NetworkMemberInfo nmi;
  944. _getNetworkMemberInfo(now,nwid,nmi);
  945. _addNetworkNonPersistedFields(network,now,nmi);
  946. responseBody = network.dump(2);
  947. responseContentType = "application/json";
  948. return 200;
  949. }
  950. } else if (path.size() == 1) {
  951. /*
  952. std::vector<std::string> networks(OSUtils::listSubdirectories((_path + ZT_PATH_SEPARATOR_S + "network").c_str()));
  953. for(auto i(networks.begin());i!=networks.end();++i) {
  954. if (i->length() == 16) {
  955. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  956. responseBody.append(*i);
  957. responseBody.append("\"");
  958. }
  959. }
  960. */
  961. responseBody.push_back(']');
  962. responseContentType = "application/json";
  963. return 200;
  964. } // else 404
  965. } else {
  966. char tmp[4096];
  967. Utils::snprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now());
  968. responseBody = tmp;
  969. responseContentType = "application/json";
  970. return 200;
  971. }
  972. return 404;
  973. }
  974. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  975. const std::vector<std::string> &path,
  976. const std::map<std::string,std::string> &urlArgs,
  977. const std::map<std::string,std::string> &headers,
  978. const std::string &body,
  979. std::string &responseBody,
  980. std::string &responseContentType)
  981. {
  982. if (path.empty())
  983. return 404;
  984. json b;
  985. try {
  986. b = json::parse(body);
  987. if (!b.is_object()) {
  988. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  989. responseContentType = "application/json";
  990. return 400;
  991. }
  992. } catch (std::exception &exc) {
  993. responseBody = std::string("{ \"message\": \"body JSON is invalid: ") + exc.what() + "\" }";
  994. responseContentType = "application/json";
  995. return 400;
  996. } catch ( ... ) {
  997. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  998. responseContentType = "application/json";
  999. return 400;
  1000. }
  1001. const uint64_t now = OSUtils::now();
  1002. if (path[0] == "network") {
  1003. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1004. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1005. char nwids[24];
  1006. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  1007. if (path.size() >= 3) {
  1008. json network;
  1009. {
  1010. Mutex::Lock _l(_db_m);
  1011. network = _db.get("network",nwids,0);
  1012. }
  1013. if (!network.size())
  1014. return 404;
  1015. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1016. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1017. char addrs[24];
  1018. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  1019. json member;
  1020. {
  1021. Mutex::Lock _l(_db_m);
  1022. member = _db.get("network",nwids,"member",Address(address).toString(),0);
  1023. }
  1024. if (!member.size())
  1025. return 404;
  1026. _initMember(member);
  1027. try {
  1028. if (b.count("activeBridge")) member["activeBridge"] = _jB(b["activeBridge"],false);
  1029. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = _jB(b["noAutoAssignIps"],false);
  1030. if ((b.count("identity"))&&(!member.count("identity"))) member["identity"] = _jS(b["identity"],""); // allow identity to be populated only if not already known
  1031. if (b.count("authorized")) {
  1032. const bool newAuth = _jB(b["authorized"],false);
  1033. if (newAuth != _jB(member["authorized"],false)) {
  1034. member["authorized"] = newAuth;
  1035. json ah;
  1036. ah["a"] = newAuth;
  1037. ah["by"] = "api";
  1038. ah["ts"] = now;
  1039. ah["ct"] = json();
  1040. ah["c"] = json();
  1041. member["authHistory"].push_back(ah);
  1042. }
  1043. }
  1044. if (b.count("ipAssignments")) {
  1045. json &ipa = b["ipAssignments"];
  1046. if (ipa.is_array()) {
  1047. json mipa(json::array());
  1048. for(unsigned long i=0;i<ipa.size();++i) {
  1049. std::string ips = ipa[i];
  1050. InetAddress ip(ips);
  1051. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  1052. mipa.push_back(ip.toIpString());
  1053. }
  1054. }
  1055. member["ipAssignments"] = mipa;
  1056. }
  1057. }
  1058. if (b.count("tags")) {
  1059. json &tags = b["tags"];
  1060. if (tags.is_array()) {
  1061. std::map<uint64_t,uint64_t> mtags;
  1062. for(unsigned long i=0;i<tags.size();++i) {
  1063. auto tag = tags[i];
  1064. if ((tag.is_array())&&(tag.size() == 2))
  1065. mtags[_jI(tag[0],0ULL) & 0xffffffffULL] = _jI(tag[1],0ULL) & 0xffffffffULL;
  1066. }
  1067. json mtagsa = json::array();
  1068. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  1069. json ta = json::array();
  1070. ta.push_back(t->first);
  1071. ta.push_back(t->second);
  1072. mtagsa.push_back(ta);
  1073. }
  1074. member["tags"] = mtagsa;
  1075. }
  1076. }
  1077. if (b.count("capabilities")) {
  1078. json &capabilities = b["capabilities"];
  1079. if (capabilities.is_array()) {
  1080. json mcaps = json::array();
  1081. for(unsigned long i=0;i<capabilities.size();++i) {
  1082. mcaps.push_back(_jI(capabilities[i],0ULL));
  1083. }
  1084. std::sort(mcaps.begin(),mcaps.end());
  1085. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  1086. member["capabilities"] = mcaps;
  1087. }
  1088. }
  1089. } catch ( ... ) {
  1090. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  1091. responseContentType = "application/json";
  1092. return 400;
  1093. }
  1094. member["id"] = addrs;
  1095. member["address"] = addrs; // legacy
  1096. member["nwid"] = nwids;
  1097. member["lastModified"] = now;
  1098. json &revj = member["revision"];
  1099. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  1100. {
  1101. Mutex::Lock _l(_db_m);
  1102. _db.put("network",nwids,"member",Address(address).toString(),member);
  1103. }
  1104. // Add non-persisted fields
  1105. member["clock"] = now;
  1106. responseBody = member.dump(2);
  1107. responseContentType = "application/json";
  1108. return 200;
  1109. } else if ((path.size() == 3)&&(path[2] == "test")) {
  1110. Mutex::Lock _l(_circuitTests_m);
  1111. ZT_CircuitTest *test = (ZT_CircuitTest *)malloc(sizeof(ZT_CircuitTest));
  1112. memset(test,0,sizeof(ZT_CircuitTest));
  1113. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  1114. test->credentialNetworkId = nwid;
  1115. test->ptr = (void *)this;
  1116. json hops = b["hops"];
  1117. if (hops.is_array()) {
  1118. for(unsigned long i=0;i<hops.size();++i) {
  1119. auto hops2 = hops[i];
  1120. if (hops2.is_array()) {
  1121. for(unsigned long j=0;j<hops2.size();++j) {
  1122. std::string s = hops2[j];
  1123. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1124. }
  1125. } else if (hops2.is_string()) {
  1126. std::string s = hops2;
  1127. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1128. }
  1129. }
  1130. }
  1131. test->reportAtEveryHop = (_jB(b["reportAtEveryHop"],true) ? 1 : 0);
  1132. if (!test->hopCount) {
  1133. ::free((void *)test);
  1134. responseBody = "{ \"message\": \"a test must contain at least one hop\" }";
  1135. responseContentType = "application/json";
  1136. return 400;
  1137. }
  1138. test->timestamp = OSUtils::now();
  1139. _CircuitTestEntry &te = _circuitTests[test->testId];
  1140. te.test = test;
  1141. te.jsonResults = "";
  1142. if (_node)
  1143. _node->circuitTestBegin(test,&(EmbeddedNetworkController::_circuitTestCallback));
  1144. else return 500;
  1145. char json[1024];
  1146. Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
  1147. responseBody = json;
  1148. responseContentType = "application/json";
  1149. return 200;
  1150. } // else 404
  1151. } else {
  1152. // POST to network ID
  1153. json network;
  1154. {
  1155. Mutex::Lock _l(_db_m);
  1156. // Magic ID ending with ______ picks a random unused network ID
  1157. if (path[1].substr(10) == "______") {
  1158. nwid = 0;
  1159. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  1160. uint64_t nwidPostfix = 0;
  1161. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  1162. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  1163. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1164. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  1165. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)tryNwid);
  1166. if (_db.get("network",nwids,120000).size() <= 0) {
  1167. nwid = tryNwid;
  1168. break;
  1169. }
  1170. }
  1171. if (!nwid)
  1172. return 503;
  1173. }
  1174. network = _db.get("network",nwids,0);
  1175. if (!network.size())
  1176. return 404;
  1177. }
  1178. _initNetwork(network);
  1179. try {
  1180. if (b.count("name")) network["name"] = _jS(b["name"],"");
  1181. if (b.count("private")) network["private"] = _jB(b["private"],true);
  1182. if (b.count("enableBroadcast")) network["enableBroadcast"] = _jB(b["enableBroadcast"],false);
  1183. if (b.count("allowPassiveBridging")) network["allowPassiveBridging"] = _jB(b["allowPassiveBridging"],false);
  1184. if (b.count("multicastLimit")) network["multicastLimit"] = _jI(b["multicastLimit"],32ULL);
  1185. if (b.count("v4AssignMode")) {
  1186. json nv4m;
  1187. json &v4m = b["v4AssignMode"];
  1188. if (v4m.is_string()) { // backward compatibility
  1189. nv4m["zt"] = (_jS(v4m,"") == "zt");
  1190. } else if (v4m.is_object()) {
  1191. nv4m["zt"] = _jB(v4m["zt"],false);
  1192. } else nv4m["zt"] = false;
  1193. network["v4AssignMode"] = nv4m;
  1194. }
  1195. if (b.count("v6AssignMode")) {
  1196. json nv6m;
  1197. json &v6m = b["v6AssignMode"];
  1198. if (!nv6m.is_object()) nv6m = json::object();
  1199. if (v6m.is_string()) { // backward compatibility
  1200. std::vector<std::string> v6ms(Utils::split(_jS(v6m,"").c_str(),",","",""));
  1201. std::sort(v6ms.begin(),v6ms.end());
  1202. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  1203. nv6m["rfc4193"] = false;
  1204. nv6m["zt"] = false;
  1205. nv6m["6plane"] = false;
  1206. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  1207. if (*i == "rfc4193")
  1208. nv6m["rfc4193"] = true;
  1209. else if (*i == "zt")
  1210. nv6m["zt"] = true;
  1211. else if (*i == "6plane")
  1212. nv6m["6plane"] = true;
  1213. }
  1214. } else if (v6m.is_object()) {
  1215. if (v6m.count("rfc4193")) nv6m["rfc4193"] = _jB(v6m["rfc4193"],false);
  1216. if (v6m.count("zt")) nv6m["zt"] = _jB(v6m["zt"],false);
  1217. if (v6m.count("6plane")) nv6m["6plane"] = _jB(v6m["6plane"],false);
  1218. } else {
  1219. nv6m["rfc4193"] = false;
  1220. nv6m["zt"] = false;
  1221. nv6m["6plane"] = false;
  1222. }
  1223. network["v6AssignMode"] = nv6m;
  1224. }
  1225. if (b.count("routes")) {
  1226. json &rts = b["routes"];
  1227. if (rts.is_array()) {
  1228. json nrts = json::array();
  1229. for(unsigned long i=0;i<rts.size();++i) {
  1230. json &rt = rts[i];
  1231. if (rt.is_object()) {
  1232. json &target = rt["target"];
  1233. json &via = rt["via"];
  1234. if (target.is_string()) {
  1235. InetAddress t(target.get<std::string>());
  1236. InetAddress v;
  1237. if (via.is_string()) v.fromString(via.get<std::string>());
  1238. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  1239. json tmp;
  1240. tmp["target"] = t.toString();
  1241. if (v.ss_family == t.ss_family)
  1242. tmp["via"] = v.toIpString();
  1243. else tmp["via"] = json();
  1244. nrts.push_back(tmp);
  1245. }
  1246. }
  1247. }
  1248. }
  1249. network["routes"] = nrts;
  1250. }
  1251. }
  1252. if (b.count("ipAssignmentPools")) {
  1253. json &ipp = b["ipAssignmentPools"];
  1254. if (ipp.is_array()) {
  1255. json nipp = json::array();
  1256. for(unsigned long i=0;i<ipp.size();++i) {
  1257. auto ip = ipp[i];
  1258. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  1259. InetAddress f(_jS(ip["ipRangeStart"],""));
  1260. InetAddress t(_jS(ip["ipRangeEnd"],""));
  1261. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  1262. json tmp = json::object();
  1263. tmp["ipRangeStart"] = f.toIpString();
  1264. tmp["ipRangeEnd"] = t.toIpString();
  1265. nipp.push_back(tmp);
  1266. }
  1267. }
  1268. }
  1269. network["ipAssignmentPools"] = nipp;
  1270. }
  1271. }
  1272. if (b.count("rules")) {
  1273. json &rules = b["rules"];
  1274. if (rules.is_array()) {
  1275. json nrules = json::array();
  1276. for(unsigned long i=0;i<rules.size();++i) {
  1277. json &rule = rules[i];
  1278. if (rule.is_object()) {
  1279. ZT_VirtualNetworkRule ztr;
  1280. if (_parseRule(rule,ztr))
  1281. nrules.push_back(_renderRule(ztr));
  1282. }
  1283. }
  1284. network["rules"] = nrules;
  1285. }
  1286. }
  1287. if (b.count("authTokens")) {
  1288. json &authTokens = b["authTokens"];
  1289. if (authTokens.is_array()) {
  1290. json nat = json::array();
  1291. for(unsigned long i=0;i<authTokens.size();++i) {
  1292. json &token = authTokens[i];
  1293. if (token.is_object()) {
  1294. std::string tstr = token["token"];
  1295. if (tstr.length() > 0) {
  1296. json t = json::object();
  1297. t["token"] = tstr;
  1298. t["expires"] = _jI(token["expires"],0ULL);
  1299. t["maxUsesPerMember"] = _jI(token["maxUsesPerMember"],0ULL);
  1300. nat.push_back(t);
  1301. }
  1302. }
  1303. }
  1304. network["authTokens"] = nat;
  1305. }
  1306. }
  1307. if (b.count("capabilities")) {
  1308. json &capabilities = b["capabilities"];
  1309. if (capabilities.is_array()) {
  1310. std::map< uint64_t,json > ncaps;
  1311. for(unsigned long i=0;i<capabilities.size();++i) {
  1312. json &cap = capabilities[i];
  1313. if (cap.is_object()) {
  1314. json ncap = json::object();
  1315. const uint64_t capId = _jI(cap["id"],0ULL);
  1316. ncap["id"] = capId;
  1317. json &rules = cap["rules"];
  1318. json nrules = json::array();
  1319. if (rules.is_array()) {
  1320. for(unsigned long i=0;i<rules.size();++i) {
  1321. json rule = rules[i];
  1322. if (rule.is_object()) {
  1323. ZT_VirtualNetworkRule ztr;
  1324. if (_parseRule(rule,ztr))
  1325. nrules.push_back(_renderRule(ztr));
  1326. }
  1327. }
  1328. }
  1329. ncap["rules"] = nrules;
  1330. ncaps[capId] = ncap;
  1331. }
  1332. }
  1333. json ncapsa = json::array();
  1334. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c)
  1335. ncapsa.push_back(c->second);
  1336. network["capabilities"] = ncapsa;
  1337. }
  1338. }
  1339. } catch ( ... ) {
  1340. responseBody = "{ \"message\": \"exception occurred while parsing body variables\" }";
  1341. responseContentType = "application/json";
  1342. return 400;
  1343. }
  1344. network["id"] = nwids;
  1345. network["nwid"] = nwids; // legacy
  1346. json &rev = network["revision"];
  1347. network["revision"] = (rev.is_number() ? ((uint64_t)rev + 1ULL) : 1ULL);
  1348. network["lastModified"] = now;
  1349. {
  1350. Mutex::Lock _l(_db_m);
  1351. _db.put("network",nwids,network);
  1352. }
  1353. _NetworkMemberInfo nmi;
  1354. _getNetworkMemberInfo(now,nwid,nmi);
  1355. _addNetworkNonPersistedFields(network,now,nmi);
  1356. responseBody = network.dump(2);
  1357. responseContentType = "application/json";
  1358. return 200;
  1359. } // else 404
  1360. } // else 404
  1361. } // else 404
  1362. return 404;
  1363. }
  1364. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  1365. const std::vector<std::string> &path,
  1366. const std::map<std::string,std::string> &urlArgs,
  1367. const std::map<std::string,std::string> &headers,
  1368. const std::string &body,
  1369. std::string &responseBody,
  1370. std::string &responseContentType)
  1371. {
  1372. if (path.empty())
  1373. return 404;
  1374. if (path[0] == "network") {
  1375. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1376. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1377. char nwids[24];
  1378. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  1379. json network;
  1380. {
  1381. Mutex::Lock _l(_db_m);
  1382. network = _db.get("network",nwids,0);
  1383. }
  1384. if (!network.size())
  1385. return 404;
  1386. if (path.size() >= 3) {
  1387. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1388. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1389. Mutex::Lock _l(_db_m);
  1390. json member = _db.get("network",nwids,"member",Address(address).toString(),0);
  1391. if (!member.size())
  1392. return 404;
  1393. _db.erase("network",nwids,"member",Address(address).toString());
  1394. responseBody = member.dump(2);
  1395. responseContentType = "application/json";
  1396. return 200;
  1397. }
  1398. } else {
  1399. Mutex::Lock _l(_db_m);
  1400. std::string pfx("network/"); pfx.append(nwids);
  1401. _db.filter(pfx,120000,[](const std::string &n,const json &obj) {
  1402. return false; // delete
  1403. });
  1404. responseBody = network.dump(2);
  1405. responseContentType = "application/json";
  1406. return 200;
  1407. }
  1408. } // else 404
  1409. } // else 404
  1410. return 404;
  1411. }
  1412. void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1413. {
  1414. char tmp[65535];
  1415. EmbeddedNetworkController *const self = reinterpret_cast<EmbeddedNetworkController *>(test->ptr);
  1416. if (!test)
  1417. return;
  1418. if (!report)
  1419. return;
  1420. Mutex::Lock _l(self->_circuitTests_m);
  1421. std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
  1422. if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
  1423. self->_node->circuitTestEnd(test);
  1424. ::free((void *)test);
  1425. return;
  1426. }
  1427. Utils::snprintf(tmp,sizeof(tmp),
  1428. "%s{\n"
  1429. "\t\"timestamp\": %llu," ZT_EOL_S
  1430. "\t\"testId\": \"%.16llx\"," ZT_EOL_S
  1431. "\t\"upstream\": \"%.10llx\"," ZT_EOL_S
  1432. "\t\"current\": \"%.10llx\"," ZT_EOL_S
  1433. "\t\"receivedTimestamp\": %llu," ZT_EOL_S
  1434. "\t\"sourcePacketId\": \"%.16llx\"," ZT_EOL_S
  1435. "\t\"flags\": %llu," ZT_EOL_S
  1436. "\t\"sourcePacketHopCount\": %u," ZT_EOL_S
  1437. "\t\"errorCode\": %u," ZT_EOL_S
  1438. "\t\"vendor\": %d," ZT_EOL_S
  1439. "\t\"protocolVersion\": %u," ZT_EOL_S
  1440. "\t\"majorVersion\": %u," ZT_EOL_S
  1441. "\t\"minorVersion\": %u," ZT_EOL_S
  1442. "\t\"revision\": %u," ZT_EOL_S
  1443. "\t\"platform\": %d," ZT_EOL_S
  1444. "\t\"architecture\": %d," ZT_EOL_S
  1445. "\t\"receivedOnLocalAddress\": \"%s\"," ZT_EOL_S
  1446. "\t\"receivedFromRemoteAddress\": \"%s\"" ZT_EOL_S
  1447. "}",
  1448. ((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
  1449. (unsigned long long)report->timestamp,
  1450. (unsigned long long)test->testId,
  1451. (unsigned long long)report->upstream,
  1452. (unsigned long long)report->current,
  1453. (unsigned long long)OSUtils::now(),
  1454. (unsigned long long)report->sourcePacketId,
  1455. (unsigned long long)report->flags,
  1456. report->sourcePacketHopCount,
  1457. report->errorCode,
  1458. (int)report->vendor,
  1459. report->protocolVersion,
  1460. report->majorVersion,
  1461. report->minorVersion,
  1462. report->revision,
  1463. (int)report->platform,
  1464. (int)report->architecture,
  1465. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1466. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
  1467. cte->second.jsonResults.append(tmp);
  1468. }
  1469. void EmbeddedNetworkController::_getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi)
  1470. {
  1471. char pfx[256];
  1472. Utils::snprintf(pfx,sizeof(pfx),"network/%.16llx/member",nwid);
  1473. Mutex::Lock _l(_db_m);
  1474. _db.filter(pfx,120000,[&nmi,&now](const std::string &n,const json &member) {
  1475. try {
  1476. if (_jB(member["authorized"],false)) {
  1477. ++nmi.authorizedMemberCount;
  1478. if (member.count("recentLog")) {
  1479. const json &mlog = member["recentLog"];
  1480. if ((mlog.is_array())&&(mlog.size() > 0)) {
  1481. const json &mlog1 = mlog[0];
  1482. if (mlog1.is_object()) {
  1483. if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
  1484. ++nmi.activeMemberCount;
  1485. }
  1486. }
  1487. }
  1488. if (_jB(member["activeBridge"],false)) {
  1489. nmi.activeBridges.insert(_jS(member["id"],"0000000000"));
  1490. }
  1491. if (member.count("ipAssignments")) {
  1492. const json &mips = member["ipAssignments"];
  1493. if (mips.is_array()) {
  1494. for(unsigned long i=0;i<mips.size();++i) {
  1495. InetAddress mip(_jS(mips[i],""));
  1496. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  1497. nmi.allocatedIps.insert(mip);
  1498. }
  1499. }
  1500. }
  1501. } else {
  1502. nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(member["lastDeauthorizedTime"],0ULL));
  1503. }
  1504. } catch ( ... ) {}
  1505. return true;
  1506. });
  1507. }
  1508. } // namespace ZeroTier