EmbeddedNetworkController.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdint.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <time.h>
  31. #ifndef _WIN32
  32. #include <sys/time.h>
  33. #endif
  34. #include <sys/types.h>
  35. #include <algorithm>
  36. #include <utility>
  37. #include <stdexcept>
  38. #include <map>
  39. #include <thread>
  40. #include <memory>
  41. #include "../include/ZeroTierOne.h"
  42. #include "../version.h"
  43. #include "EmbeddedNetworkController.hpp"
  44. #include "../node/Node.hpp"
  45. #include "../node/CertificateOfMembership.hpp"
  46. #include "../node/NetworkConfig.hpp"
  47. #include "../node/Dictionary.hpp"
  48. #include "../node/MAC.hpp"
  49. using json = nlohmann::json;
  50. // API version reported via JSON control plane
  51. #define ZT_NETCONF_CONTROLLER_API_VERSION 4
  52. // Min duration between requests for an address/nwid combo to prevent floods
  53. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  54. // Global maximum size of arrays in JSON objects
  55. #define ZT_CONTROLLER_MAX_ARRAY_SIZE 16384
  56. namespace ZeroTier {
  57. namespace {
  58. static json _renderRule(ZT_VirtualNetworkRule &rule)
  59. {
  60. char tmp[128];
  61. json r = json::object();
  62. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rule.t & 0x3f);
  63. switch(rt) {
  64. case ZT_NETWORK_RULE_ACTION_DROP:
  65. r["type"] = "ACTION_DROP";
  66. break;
  67. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  68. r["type"] = "ACTION_ACCEPT";
  69. break;
  70. case ZT_NETWORK_RULE_ACTION_TEE:
  71. r["type"] = "ACTION_TEE";
  72. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  73. r["flags"] = (unsigned int)rule.v.fwd.flags;
  74. r["length"] = (unsigned int)rule.v.fwd.length;
  75. break;
  76. case ZT_NETWORK_RULE_ACTION_WATCH:
  77. r["type"] = "ACTION_WATCH";
  78. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  79. r["flags"] = (unsigned int)rule.v.fwd.flags;
  80. r["length"] = (unsigned int)rule.v.fwd.length;
  81. break;
  82. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  83. r["type"] = "ACTION_REDIRECT";
  84. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  85. r["flags"] = (unsigned int)rule.v.fwd.flags;
  86. break;
  87. case ZT_NETWORK_RULE_ACTION_BREAK:
  88. r["type"] = "ACTION_BREAK";
  89. break;
  90. default:
  91. break;
  92. }
  93. if (r.size() == 0) {
  94. switch(rt) {
  95. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  96. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  97. r["zt"] = Address(rule.v.zt).toString(tmp);
  98. break;
  99. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  100. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  101. r["zt"] = Address(rule.v.zt).toString(tmp);
  102. break;
  103. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  104. r["type"] = "MATCH_VLAN_ID";
  105. r["vlanId"] = (unsigned int)rule.v.vlanId;
  106. break;
  107. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  108. r["type"] = "MATCH_VLAN_PCP";
  109. r["vlanPcp"] = (unsigned int)rule.v.vlanPcp;
  110. break;
  111. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  112. r["type"] = "MATCH_VLAN_DEI";
  113. r["vlanDei"] = (unsigned int)rule.v.vlanDei;
  114. break;
  115. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  116. r["type"] = "MATCH_MAC_SOURCE";
  117. OSUtils::ztsnprintf(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]);
  118. r["mac"] = tmp;
  119. break;
  120. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  121. r["type"] = "MATCH_MAC_DEST";
  122. OSUtils::ztsnprintf(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]);
  123. r["mac"] = tmp;
  124. break;
  125. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  126. r["type"] = "MATCH_IPV4_SOURCE";
  127. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString(tmp);
  128. break;
  129. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  130. r["type"] = "MATCH_IPV4_DEST";
  131. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString(tmp);
  132. break;
  133. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  134. r["type"] = "MATCH_IPV6_SOURCE";
  135. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString(tmp);
  136. break;
  137. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  138. r["type"] = "MATCH_IPV6_DEST";
  139. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString(tmp);
  140. break;
  141. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  142. r["type"] = "MATCH_IP_TOS";
  143. r["mask"] = (unsigned int)rule.v.ipTos.mask;
  144. r["start"] = (unsigned int)rule.v.ipTos.value[0];
  145. r["end"] = (unsigned int)rule.v.ipTos.value[1];
  146. break;
  147. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  148. r["type"] = "MATCH_IP_PROTOCOL";
  149. r["ipProtocol"] = (unsigned int)rule.v.ipProtocol;
  150. break;
  151. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  152. r["type"] = "MATCH_ETHERTYPE";
  153. r["etherType"] = (unsigned int)rule.v.etherType;
  154. break;
  155. case ZT_NETWORK_RULE_MATCH_ICMP:
  156. r["type"] = "MATCH_ICMP";
  157. r["icmpType"] = (unsigned int)rule.v.icmp.type;
  158. if ((rule.v.icmp.flags & 0x01) != 0)
  159. r["icmpCode"] = (unsigned int)rule.v.icmp.code;
  160. else r["icmpCode"] = json();
  161. break;
  162. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  163. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  164. r["start"] = (unsigned int)rule.v.port[0];
  165. r["end"] = (unsigned int)rule.v.port[1];
  166. break;
  167. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  168. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  169. r["start"] = (unsigned int)rule.v.port[0];
  170. r["end"] = (unsigned int)rule.v.port[1];
  171. break;
  172. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  173. r["type"] = "MATCH_CHARACTERISTICS";
  174. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics);
  175. r["mask"] = tmp;
  176. break;
  177. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  178. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  179. r["start"] = (unsigned int)rule.v.frameSize[0];
  180. r["end"] = (unsigned int)rule.v.frameSize[1];
  181. break;
  182. case ZT_NETWORK_RULE_MATCH_RANDOM:
  183. r["type"] = "MATCH_RANDOM";
  184. r["probability"] = (unsigned long)rule.v.randomProbability;
  185. break;
  186. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  187. r["type"] = "MATCH_TAGS_DIFFERENCE";
  188. r["id"] = rule.v.tag.id;
  189. r["value"] = rule.v.tag.value;
  190. break;
  191. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  192. r["type"] = "MATCH_TAGS_BITWISE_AND";
  193. r["id"] = rule.v.tag.id;
  194. r["value"] = rule.v.tag.value;
  195. break;
  196. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  197. r["type"] = "MATCH_TAGS_BITWISE_OR";
  198. r["id"] = rule.v.tag.id;
  199. r["value"] = rule.v.tag.value;
  200. break;
  201. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  202. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  203. r["id"] = rule.v.tag.id;
  204. r["value"] = rule.v.tag.value;
  205. break;
  206. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL:
  207. r["type"] = "MATCH_TAGS_EQUAL";
  208. r["id"] = rule.v.tag.id;
  209. r["value"] = rule.v.tag.value;
  210. break;
  211. case ZT_NETWORK_RULE_MATCH_TAG_SENDER:
  212. r["type"] = "MATCH_TAG_SENDER";
  213. r["id"] = rule.v.tag.id;
  214. r["value"] = rule.v.tag.value;
  215. break;
  216. case ZT_NETWORK_RULE_MATCH_TAG_RECEIVER:
  217. r["type"] = "MATCH_TAG_RECEIVER";
  218. r["id"] = rule.v.tag.id;
  219. r["value"] = rule.v.tag.value;
  220. break;
  221. case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE:
  222. r["type"] = "INTEGER_RANGE";
  223. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.intRange.start);
  224. r["start"] = tmp;
  225. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.intRange.start + (uint64_t)rule.v.intRange.end);
  226. r["end"] = tmp;
  227. r["idx"] = rule.v.intRange.idx;
  228. r["little"] = ((rule.v.intRange.format & 0x80) != 0);
  229. r["bits"] = (rule.v.intRange.format & 63) + 1;
  230. break;
  231. default:
  232. break;
  233. }
  234. if (r.size() > 0) {
  235. r["not"] = ((rule.t & 0x80) != 0);
  236. r["or"] = ((rule.t & 0x40) != 0);
  237. }
  238. }
  239. return r;
  240. }
  241. static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
  242. {
  243. if (!r.is_object())
  244. return false;
  245. const std::string t(OSUtils::jsonString(r["type"],""));
  246. memset(&rule,0,sizeof(ZT_VirtualNetworkRule));
  247. if (OSUtils::jsonBool(r["not"],false))
  248. rule.t = 0x80;
  249. else rule.t = 0x00;
  250. if (OSUtils::jsonBool(r["or"],false))
  251. rule.t |= 0x40;
  252. bool tag = false;
  253. if (t == "ACTION_DROP") {
  254. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  255. return true;
  256. } else if (t == "ACTION_ACCEPT") {
  257. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  258. return true;
  259. } else if (t == "ACTION_TEE") {
  260. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  261. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  262. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  263. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"],0ULL) & 0xffffULL);
  264. return true;
  265. } else if (t == "ACTION_WATCH") {
  266. rule.t |= ZT_NETWORK_RULE_ACTION_WATCH;
  267. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  268. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  269. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"],0ULL) & 0xffffULL);
  270. return true;
  271. } else if (t == "ACTION_REDIRECT") {
  272. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  273. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  274. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  275. return true;
  276. } else if (t == "ACTION_BREAK") {
  277. rule.t |= ZT_NETWORK_RULE_ACTION_BREAK;
  278. return true;
  279. } else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  280. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  281. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"],"0").c_str()) & 0xffffffffffULL;
  282. return true;
  283. } else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  284. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  285. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"],"0").c_str()) & 0xffffffffffULL;
  286. return true;
  287. } else if (t == "MATCH_VLAN_ID") {
  288. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  289. rule.v.vlanId = (uint16_t)(OSUtils::jsonInt(r["vlanId"],0ULL) & 0xffffULL);
  290. return true;
  291. } else if (t == "MATCH_VLAN_PCP") {
  292. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  293. rule.v.vlanPcp = (uint8_t)(OSUtils::jsonInt(r["vlanPcp"],0ULL) & 0xffULL);
  294. return true;
  295. } else if (t == "MATCH_VLAN_DEI") {
  296. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  297. rule.v.vlanDei = (uint8_t)(OSUtils::jsonInt(r["vlanDei"],0ULL) & 0xffULL);
  298. return true;
  299. } else if (t == "MATCH_MAC_SOURCE") {
  300. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  301. const std::string mac(OSUtils::jsonString(r["mac"],"0"));
  302. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  303. return true;
  304. } else if (t == "MATCH_MAC_DEST") {
  305. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  306. const std::string mac(OSUtils::jsonString(r["mac"],"0"));
  307. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  308. return true;
  309. } else if (t == "MATCH_IPV4_SOURCE") {
  310. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  311. InetAddress ip(OSUtils::jsonString(r["ip"],"0.0.0.0").c_str());
  312. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  313. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  314. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  315. return true;
  316. } else if (t == "MATCH_IPV4_DEST") {
  317. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  318. InetAddress ip(OSUtils::jsonString(r["ip"],"0.0.0.0").c_str());
  319. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  320. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  321. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  322. return true;
  323. } else if (t == "MATCH_IPV6_SOURCE") {
  324. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  325. InetAddress ip(OSUtils::jsonString(r["ip"],"::0").c_str());
  326. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  327. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  328. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  329. return true;
  330. } else if (t == "MATCH_IPV6_DEST") {
  331. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  332. InetAddress ip(OSUtils::jsonString(r["ip"],"::0").c_str());
  333. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  334. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  335. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  336. return true;
  337. } else if (t == "MATCH_IP_TOS") {
  338. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  339. rule.v.ipTos.mask = (uint8_t)(OSUtils::jsonInt(r["mask"],0ULL) & 0xffULL);
  340. rule.v.ipTos.value[0] = (uint8_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffULL);
  341. rule.v.ipTos.value[1] = (uint8_t)(OSUtils::jsonInt(r["end"],0ULL) & 0xffULL);
  342. return true;
  343. } else if (t == "MATCH_IP_PROTOCOL") {
  344. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  345. rule.v.ipProtocol = (uint8_t)(OSUtils::jsonInt(r["ipProtocol"],0ULL) & 0xffULL);
  346. return true;
  347. } else if (t == "MATCH_ETHERTYPE") {
  348. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  349. rule.v.etherType = (uint16_t)(OSUtils::jsonInt(r["etherType"],0ULL) & 0xffffULL);
  350. return true;
  351. } else if (t == "MATCH_ICMP") {
  352. rule.t |= ZT_NETWORK_RULE_MATCH_ICMP;
  353. rule.v.icmp.type = (uint8_t)(OSUtils::jsonInt(r["icmpType"],0ULL) & 0xffULL);
  354. json &code = r["icmpCode"];
  355. if (code.is_null()) {
  356. rule.v.icmp.code = 0;
  357. rule.v.icmp.flags = 0x00;
  358. } else {
  359. rule.v.icmp.code = (uint8_t)(OSUtils::jsonInt(code,0ULL) & 0xffULL);
  360. rule.v.icmp.flags = 0x01;
  361. }
  362. return true;
  363. } else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  364. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  365. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  366. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  367. return true;
  368. } else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  369. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  370. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  371. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  372. return true;
  373. } else if (t == "MATCH_CHARACTERISTICS") {
  374. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  375. if (r.count("mask")) {
  376. json &v = r["mask"];
  377. if (v.is_number()) {
  378. rule.v.characteristics = v;
  379. } else {
  380. std::string tmp = v;
  381. rule.v.characteristics = Utils::hexStrToU64(tmp.c_str());
  382. }
  383. }
  384. return true;
  385. } else if (t == "MATCH_FRAME_SIZE_RANGE") {
  386. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  387. rule.v.frameSize[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  388. rule.v.frameSize[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  389. return true;
  390. } else if (t == "MATCH_RANDOM") {
  391. rule.t |= ZT_NETWORK_RULE_MATCH_RANDOM;
  392. rule.v.randomProbability = (uint32_t)(OSUtils::jsonInt(r["probability"],0ULL) & 0xffffffffULL);
  393. return true;
  394. } else if (t == "MATCH_TAGS_DIFFERENCE") {
  395. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE;
  396. tag = true;
  397. } else if (t == "MATCH_TAGS_BITWISE_AND") {
  398. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  399. tag = true;
  400. } else if (t == "MATCH_TAGS_BITWISE_OR") {
  401. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  402. tag = true;
  403. } else if (t == "MATCH_TAGS_BITWISE_XOR") {
  404. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  405. tag = true;
  406. } else if (t == "MATCH_TAGS_EQUAL") {
  407. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_EQUAL;
  408. tag = true;
  409. } else if (t == "MATCH_TAG_SENDER") {
  410. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_SENDER;
  411. tag = true;
  412. } else if (t == "MATCH_TAG_RECEIVER") {
  413. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_RECEIVER;
  414. tag = true;
  415. } else if (t == "INTEGER_RANGE") {
  416. json &s = r["start"];
  417. if (s.is_string()) {
  418. std::string tmp = s;
  419. rule.v.intRange.start = Utils::hexStrToU64(tmp.c_str());
  420. } else {
  421. rule.v.intRange.start = OSUtils::jsonInt(s,0ULL);
  422. }
  423. json &e = r["end"];
  424. if (e.is_string()) {
  425. std::string tmp = e;
  426. rule.v.intRange.end = (uint32_t)(Utils::hexStrToU64(tmp.c_str()) - rule.v.intRange.start);
  427. } else {
  428. rule.v.intRange.end = (uint32_t)(OSUtils::jsonInt(e,0ULL) - rule.v.intRange.start);
  429. }
  430. rule.v.intRange.idx = (uint16_t)OSUtils::jsonInt(r["idx"],0ULL);
  431. rule.v.intRange.format = (OSUtils::jsonBool(r["little"],false)) ? 0x80 : 0x00;
  432. rule.v.intRange.format |= (uint8_t)((OSUtils::jsonInt(r["bits"],1ULL) - 1) & 63);
  433. }
  434. if (tag) {
  435. rule.v.tag.id = (uint32_t)(OSUtils::jsonInt(r["id"],0ULL) & 0xffffffffULL);
  436. rule.v.tag.value = (uint32_t)(OSUtils::jsonInt(r["value"],0ULL) & 0xffffffffULL);
  437. return true;
  438. }
  439. return false;
  440. }
  441. } // anonymous namespace
  442. EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *dbPath, int listenPort, MQConfig *mqc) :
  443. _startTime(OSUtils::now()),
  444. _listenPort(listenPort),
  445. _node(node),
  446. _path(dbPath),
  447. _sender((NetworkController::Sender *)0),
  448. _mqc(mqc)
  449. {
  450. }
  451. EmbeddedNetworkController::~EmbeddedNetworkController()
  452. {
  453. std::lock_guard<std::mutex> l(_threads_l);
  454. _queue.stop();
  455. for(auto t=_threads.begin();t!=_threads.end();++t)
  456. t->join();
  457. }
  458. void EmbeddedNetworkController::init(const Identity &signingId,Sender *sender)
  459. {
  460. char tmp[64];
  461. _signingId = signingId;
  462. _sender = sender;
  463. _signingIdAddressString = signingId.address().toString(tmp);
  464. #ifdef ZT_CONTROLLER_USE_LIBPQ
  465. if ((_path.length() > 9)&&(_path.substr(0,9) == "postgres:"))
  466. _db.reset(new PostgreSQL(this,_signingId,_path.substr(9).c_str(), _listenPort, _mqc));
  467. else // else use FileDB after endif
  468. #endif
  469. _db.reset(new FileDB(this,_signingId,_path.c_str()));
  470. _db->waitForReady();
  471. }
  472. void EmbeddedNetworkController::request(
  473. uint64_t nwid,
  474. const InetAddress &fromAddr,
  475. uint64_t requestPacketId,
  476. const Identity &identity,
  477. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  478. {
  479. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  480. return;
  481. _startThreads();
  482. _RQEntry *qe = new _RQEntry;
  483. qe->nwid = nwid;
  484. qe->requestPacketId = requestPacketId;
  485. qe->fromAddr = fromAddr;
  486. qe->identity = identity;
  487. qe->metaData = metaData;
  488. qe->type = _RQEntry::RQENTRY_TYPE_REQUEST;
  489. _queue.post(qe);
  490. }
  491. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  492. const std::vector<std::string> &path,
  493. const std::map<std::string,std::string> &urlArgs,
  494. const std::map<std::string,std::string> &headers,
  495. const std::string &body,
  496. std::string &responseBody,
  497. std::string &responseContentType)
  498. {
  499. if (!_db)
  500. return 500;
  501. if ((path.size() > 0)&&(path[0] == "network")) {
  502. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  503. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  504. json network;
  505. if (!_db->get(nwid,network))
  506. return 404;
  507. if (path.size() >= 3) {
  508. if (path[2] == "member") {
  509. if (path.size() >= 4) {
  510. // Get member
  511. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  512. json member;
  513. if (!_db->get(nwid,network,address,member))
  514. return 404;
  515. responseBody = OSUtils::jsonDump(member);
  516. responseContentType = "application/json";
  517. } else {
  518. // List members and their revisions
  519. responseBody = "{";
  520. std::vector<json> members;
  521. if (_db->get(nwid,network,members)) {
  522. responseBody.reserve((members.size() + 2) * 32);
  523. std::string mid;
  524. for(auto member=members.begin();member!=members.end();++member) {
  525. mid = (*member)["id"];
  526. char tmp[128];
  527. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s\"%s\":%llu",(responseBody.length() > 1) ? "," : "",mid.c_str(),(unsigned long long)OSUtils::jsonInt((*member)["revision"],0));
  528. responseBody.append(tmp);
  529. }
  530. }
  531. responseBody.push_back('}');
  532. responseContentType = "application/json";
  533. }
  534. return 200;
  535. } // else 404
  536. } else {
  537. // Get network
  538. responseBody = OSUtils::jsonDump(network);
  539. responseContentType = "application/json";
  540. return 200;
  541. }
  542. } else if (path.size() == 1) {
  543. // List networks
  544. std::vector<uint64_t> networkIds;
  545. _db->networks(networkIds);
  546. char tmp[64];
  547. responseBody = "[";
  548. responseBody.reserve((networkIds.size() + 1) * 24);
  549. for(std::vector<uint64_t>::const_iterator i(networkIds.begin());i!=networkIds.end();++i) {
  550. if (responseBody.length() > 1)
  551. responseBody.push_back(',');
  552. OSUtils::ztsnprintf(tmp,sizeof(tmp),"\"%.16llx\"",(unsigned long long)*i);
  553. responseBody.append(tmp);
  554. }
  555. responseBody.push_back(']');
  556. responseContentType = "application/json";
  557. return 200;
  558. } // else 404
  559. } else {
  560. // Controller status
  561. char tmp[4096];
  562. const bool dbOk = _db->isReady();
  563. OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"databaseReady\": %s\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now(),dbOk ? "true" : "false");
  564. responseBody = tmp;
  565. responseContentType = "application/json";
  566. return dbOk ? 200 : 503;
  567. }
  568. return 404;
  569. }
  570. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  571. const std::vector<std::string> &path,
  572. const std::map<std::string,std::string> &urlArgs,
  573. const std::map<std::string,std::string> &headers,
  574. const std::string &body,
  575. std::string &responseBody,
  576. std::string &responseContentType)
  577. {
  578. if (!_db)
  579. return 500;
  580. if (path.empty())
  581. return 404;
  582. json b;
  583. try {
  584. b = OSUtils::jsonParse(body);
  585. if (!b.is_object()) {
  586. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  587. responseContentType = "application/json";
  588. return 400;
  589. }
  590. } catch ( ... ) {
  591. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  592. responseContentType = "application/json";
  593. return 400;
  594. }
  595. const int64_t now = OSUtils::now();
  596. if (path[0] == "network") {
  597. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  598. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  599. char nwids[24];
  600. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  601. if (path.size() >= 3) {
  602. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  603. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  604. char addrs[24];
  605. OSUtils::ztsnprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  606. json member,network;
  607. _db->get(nwid,network,address,member);
  608. json origMember(member); // for detecting changes
  609. DB::initMember(member);
  610. try {
  611. if (b.count("activeBridge")) member["activeBridge"] = OSUtils::jsonBool(b["activeBridge"],false);
  612. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = OSUtils::jsonBool(b["noAutoAssignIps"],false);
  613. if (b.count("remoteTraceTarget")) {
  614. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  615. if (rtt.length() == 10) {
  616. member["remoteTraceTarget"] = rtt;
  617. } else {
  618. member["remoteTraceTarget"] = json();
  619. }
  620. }
  621. if (b.count("remoteTraceLevel")) member["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  622. if (b.count("authorized")) {
  623. const bool newAuth = OSUtils::jsonBool(b["authorized"],false);
  624. if (newAuth != OSUtils::jsonBool(member["authorized"],false)) {
  625. member["authorized"] = newAuth;
  626. member[((newAuth) ? "lastAuthorizedTime" : "lastDeauthorizedTime")] = now;
  627. if (newAuth) {
  628. member["lastAuthorizedCredentialType"] = "api";
  629. member["lastAuthorizedCredential"] = json();
  630. }
  631. }
  632. }
  633. if (b.count("ipAssignments")) {
  634. json &ipa = b["ipAssignments"];
  635. if (ipa.is_array()) {
  636. json mipa(json::array());
  637. for(unsigned long i=0;i<ipa.size();++i) {
  638. std::string ips = ipa[i];
  639. InetAddress ip(ips.c_str());
  640. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  641. char tmpip[64];
  642. mipa.push_back(ip.toIpString(tmpip));
  643. if (mipa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  644. break;
  645. }
  646. }
  647. member["ipAssignments"] = mipa;
  648. }
  649. }
  650. if (b.count("tags")) {
  651. json &tags = b["tags"];
  652. if (tags.is_array()) {
  653. std::map<uint64_t,uint64_t> mtags;
  654. for(unsigned long i=0;i<tags.size();++i) {
  655. json &tag = tags[i];
  656. if ((tag.is_array())&&(tag.size() == 2))
  657. mtags[OSUtils::jsonInt(tag[0],0ULL) & 0xffffffffULL] = OSUtils::jsonInt(tag[1],0ULL) & 0xffffffffULL;
  658. }
  659. json mtagsa = json::array();
  660. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  661. json ta = json::array();
  662. ta.push_back(t->first);
  663. ta.push_back(t->second);
  664. mtagsa.push_back(ta);
  665. if (mtagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  666. break;
  667. }
  668. member["tags"] = mtagsa;
  669. }
  670. }
  671. if (b.count("capabilities")) {
  672. json &capabilities = b["capabilities"];
  673. if (capabilities.is_array()) {
  674. json mcaps = json::array();
  675. for(unsigned long i=0;i<capabilities.size();++i) {
  676. mcaps.push_back(OSUtils::jsonInt(capabilities[i],0ULL));
  677. if (mcaps.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  678. break;
  679. }
  680. std::sort(mcaps.begin(),mcaps.end());
  681. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  682. member["capabilities"] = mcaps;
  683. }
  684. }
  685. } catch ( ... ) {
  686. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  687. responseContentType = "application/json";
  688. return 400;
  689. }
  690. member["id"] = addrs;
  691. member["address"] = addrs; // legacy
  692. member["nwid"] = nwids;
  693. DB::cleanMember(member);
  694. _db->save(&origMember,member);
  695. responseBody = OSUtils::jsonDump(member);
  696. responseContentType = "application/json";
  697. return 200;
  698. } // else 404
  699. } else {
  700. // POST to network ID
  701. // Magic ID ending with ______ picks a random unused network ID
  702. if (path[1].substr(10) == "______") {
  703. nwid = 0;
  704. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  705. uint64_t nwidPostfix = 0;
  706. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  707. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  708. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  709. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  710. if (!_db->hasNetwork(tryNwid)) {
  711. nwid = tryNwid;
  712. break;
  713. }
  714. }
  715. if (!nwid)
  716. return 503;
  717. }
  718. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  719. json network;
  720. _db->get(nwid,network);
  721. json origNetwork(network); // for detecting changes
  722. DB::initNetwork(network);
  723. try {
  724. if (b.count("name")) network["name"] = OSUtils::jsonString(b["name"],"");
  725. if (b.count("private")) network["private"] = OSUtils::jsonBool(b["private"],true);
  726. if (b.count("enableBroadcast")) network["enableBroadcast"] = OSUtils::jsonBool(b["enableBroadcast"],false);
  727. if (b.count("multicastLimit")) network["multicastLimit"] = OSUtils::jsonInt(b["multicastLimit"],32ULL);
  728. if (b.count("mtu")) network["mtu"] = std::max(std::min((unsigned int)OSUtils::jsonInt(b["mtu"],ZT_DEFAULT_MTU),(unsigned int)ZT_MAX_MTU),(unsigned int)ZT_MIN_MTU);
  729. if (b.count("remoteTraceTarget")) {
  730. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  731. if (rtt.length() == 10) {
  732. network["remoteTraceTarget"] = rtt;
  733. } else {
  734. network["remoteTraceTarget"] = json();
  735. }
  736. }
  737. if (b.count("remoteTraceLevel")) network["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  738. if (b.count("v4AssignMode")) {
  739. json nv4m;
  740. json &v4m = b["v4AssignMode"];
  741. if (v4m.is_string()) { // backward compatibility
  742. nv4m["zt"] = (OSUtils::jsonString(v4m,"") == "zt");
  743. } else if (v4m.is_object()) {
  744. nv4m["zt"] = OSUtils::jsonBool(v4m["zt"],false);
  745. } else nv4m["zt"] = false;
  746. network["v4AssignMode"] = nv4m;
  747. }
  748. if (b.count("v6AssignMode")) {
  749. json nv6m;
  750. json &v6m = b["v6AssignMode"];
  751. if (!nv6m.is_object()) nv6m = json::object();
  752. if (v6m.is_string()) { // backward compatibility
  753. std::vector<std::string> v6ms(OSUtils::split(OSUtils::jsonString(v6m,"").c_str(),",","",""));
  754. std::sort(v6ms.begin(),v6ms.end());
  755. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  756. nv6m["rfc4193"] = false;
  757. nv6m["zt"] = false;
  758. nv6m["6plane"] = false;
  759. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  760. if (*i == "rfc4193")
  761. nv6m["rfc4193"] = true;
  762. else if (*i == "zt")
  763. nv6m["zt"] = true;
  764. else if (*i == "6plane")
  765. nv6m["6plane"] = true;
  766. }
  767. } else if (v6m.is_object()) {
  768. if (v6m.count("rfc4193")) nv6m["rfc4193"] = OSUtils::jsonBool(v6m["rfc4193"],false);
  769. if (v6m.count("zt")) nv6m["zt"] = OSUtils::jsonBool(v6m["zt"],false);
  770. if (v6m.count("6plane")) nv6m["6plane"] = OSUtils::jsonBool(v6m["6plane"],false);
  771. } else {
  772. nv6m["rfc4193"] = false;
  773. nv6m["zt"] = false;
  774. nv6m["6plane"] = false;
  775. }
  776. network["v6AssignMode"] = nv6m;
  777. }
  778. if (b.count("routes")) {
  779. json &rts = b["routes"];
  780. if (rts.is_array()) {
  781. json nrts = json::array();
  782. for(unsigned long i=0;i<rts.size();++i) {
  783. json &rt = rts[i];
  784. if (rt.is_object()) {
  785. json &target = rt["target"];
  786. json &via = rt["via"];
  787. if (target.is_string()) {
  788. InetAddress t(target.get<std::string>().c_str());
  789. InetAddress v;
  790. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  791. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  792. json tmp;
  793. char tmp2[64];
  794. tmp["target"] = t.toString(tmp2);
  795. if (v.ss_family == t.ss_family)
  796. tmp["via"] = v.toIpString(tmp2);
  797. else tmp["via"] = json();
  798. nrts.push_back(tmp);
  799. if (nrts.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  800. break;
  801. }
  802. }
  803. }
  804. }
  805. network["routes"] = nrts;
  806. }
  807. }
  808. if (b.count("ipAssignmentPools")) {
  809. json &ipp = b["ipAssignmentPools"];
  810. if (ipp.is_array()) {
  811. json nipp = json::array();
  812. for(unsigned long i=0;i<ipp.size();++i) {
  813. json &ip = ipp[i];
  814. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  815. InetAddress f(OSUtils::jsonString(ip["ipRangeStart"],"").c_str());
  816. InetAddress t(OSUtils::jsonString(ip["ipRangeEnd"],"").c_str());
  817. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  818. json tmp = json::object();
  819. char tmp2[64];
  820. tmp["ipRangeStart"] = f.toIpString(tmp2);
  821. tmp["ipRangeEnd"] = t.toIpString(tmp2);
  822. nipp.push_back(tmp);
  823. if (nipp.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  824. break;
  825. }
  826. }
  827. }
  828. network["ipAssignmentPools"] = nipp;
  829. }
  830. }
  831. if (b.count("rules")) {
  832. json &rules = b["rules"];
  833. if (rules.is_array()) {
  834. json nrules = json::array();
  835. for(unsigned long i=0;i<rules.size();++i) {
  836. json &rule = rules[i];
  837. if (rule.is_object()) {
  838. ZT_VirtualNetworkRule ztr;
  839. if (_parseRule(rule,ztr)) {
  840. nrules.push_back(_renderRule(ztr));
  841. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  842. break;
  843. }
  844. }
  845. }
  846. network["rules"] = nrules;
  847. }
  848. }
  849. if (b.count("authTokens")) {
  850. json &authTokens = b["authTokens"];
  851. if (authTokens.is_object()) {
  852. json nat;
  853. for(json::iterator t(authTokens.begin());t!=authTokens.end();++t) {
  854. if ((t.value().is_number())&&(t.value() >= 0))
  855. nat[t.key()] = t.value();
  856. }
  857. network["authTokens"] = nat;
  858. } else {
  859. network["authTokens"] = {{}};
  860. }
  861. }
  862. if (b.count("capabilities")) {
  863. json &capabilities = b["capabilities"];
  864. if (capabilities.is_array()) {
  865. std::map< uint64_t,json > ncaps;
  866. for(unsigned long i=0;i<capabilities.size();++i) {
  867. json &cap = capabilities[i];
  868. if (cap.is_object()) {
  869. json ncap = json::object();
  870. const uint64_t capId = OSUtils::jsonInt(cap["id"],0ULL);
  871. ncap["id"] = capId;
  872. ncap["default"] = OSUtils::jsonBool(cap["default"],false);
  873. json &rules = cap["rules"];
  874. json nrules = json::array();
  875. if (rules.is_array()) {
  876. for(unsigned long i=0;i<rules.size();++i) {
  877. json &rule = rules[i];
  878. if (rule.is_object()) {
  879. ZT_VirtualNetworkRule ztr;
  880. if (_parseRule(rule,ztr)) {
  881. nrules.push_back(_renderRule(ztr));
  882. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  883. break;
  884. }
  885. }
  886. }
  887. }
  888. ncap["rules"] = nrules;
  889. ncaps[capId] = ncap;
  890. }
  891. }
  892. json ncapsa = json::array();
  893. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c) {
  894. ncapsa.push_back(c->second);
  895. if (ncapsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  896. break;
  897. }
  898. network["capabilities"] = ncapsa;
  899. }
  900. }
  901. if (b.count("tags")) {
  902. json &tags = b["tags"];
  903. if (tags.is_array()) {
  904. std::map< uint64_t,json > ntags;
  905. for(unsigned long i=0;i<tags.size();++i) {
  906. json &tag = tags[i];
  907. if (tag.is_object()) {
  908. json ntag = json::object();
  909. const uint64_t tagId = OSUtils::jsonInt(tag["id"],0ULL);
  910. ntag["id"] = tagId;
  911. json &dfl = tag["default"];
  912. if (dfl.is_null())
  913. ntag["default"] = dfl;
  914. else ntag["default"] = OSUtils::jsonInt(dfl,0ULL);
  915. ntags[tagId] = ntag;
  916. }
  917. }
  918. json ntagsa = json::array();
  919. for(std::map< uint64_t,json >::iterator t(ntags.begin());t!=ntags.end();++t) {
  920. ntagsa.push_back(t->second);
  921. if (ntagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  922. break;
  923. }
  924. network["tags"] = ntagsa;
  925. }
  926. }
  927. } catch ( ... ) {
  928. responseBody = "{ \"message\": \"exception occurred while parsing body variables\" }";
  929. responseContentType = "application/json";
  930. return 400;
  931. }
  932. network["id"] = nwids;
  933. network["nwid"] = nwids; // legacy
  934. DB::cleanNetwork(network);
  935. _db->save(&origNetwork,network);
  936. responseBody = OSUtils::jsonDump(network);
  937. responseContentType = "application/json";
  938. return 200;
  939. } // else 404
  940. } // else 404
  941. }
  942. return 404;
  943. }
  944. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  945. const std::vector<std::string> &path,
  946. const std::map<std::string,std::string> &urlArgs,
  947. const std::map<std::string,std::string> &headers,
  948. const std::string &body,
  949. std::string &responseBody,
  950. std::string &responseContentType)
  951. {
  952. if (!_db)
  953. return 500;
  954. if (path.empty())
  955. return 404;
  956. if (path[0] == "network") {
  957. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  958. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  959. if (path.size() >= 3) {
  960. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  961. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  962. json network,member;
  963. _db->get(nwid,network,address,member);
  964. _db->eraseMember(nwid, address);
  965. {
  966. std::lock_guard<std::mutex> l(_memberStatus_l);
  967. _memberStatus.erase(_MemberStatusKey(nwid,address));
  968. }
  969. if (!member.size())
  970. return 404;
  971. responseBody = OSUtils::jsonDump(member);
  972. responseContentType = "application/json";
  973. return 200;
  974. }
  975. } else {
  976. json network;
  977. _db->get(nwid,network);
  978. _db->eraseNetwork(nwid);
  979. {
  980. std::lock_guard<std::mutex> l(_memberStatus_l);
  981. for(auto i=_memberStatus.begin();i!=_memberStatus.end();) {
  982. if (i->first.networkId == nwid)
  983. _memberStatus.erase(i++);
  984. else ++i;
  985. }
  986. }
  987. if (!network.size())
  988. return 404;
  989. responseBody = OSUtils::jsonDump(network);
  990. responseContentType = "application/json";
  991. return 200;
  992. }
  993. } // else 404
  994. } // else 404
  995. return 404;
  996. }
  997. void EmbeddedNetworkController::handleRemoteTrace(const ZT_RemoteTrace &rt)
  998. {
  999. static volatile unsigned long idCounter = 0;
  1000. char id[128],tmp[128];
  1001. std::string k,v;
  1002. if (!_db)
  1003. return;
  1004. try {
  1005. // Convert Dictionary into JSON object
  1006. json d;
  1007. char *saveptr = (char *)0;
  1008. for(char *l=Utils::stok(rt.data,"\n",&saveptr);(l);l=Utils::stok((char *)0,"\n",&saveptr)) {
  1009. char *eq = strchr(l,'=');
  1010. if (eq > l) {
  1011. k.assign(l,(unsigned long)(eq - l));
  1012. v.clear();
  1013. ++eq;
  1014. while (*eq) {
  1015. if (*eq == '\\') {
  1016. ++eq;
  1017. if (*eq) {
  1018. switch(*eq) {
  1019. case 'r': v.push_back('\r'); break;
  1020. case 'n': v.push_back('\n'); break;
  1021. case '0': v.push_back((char)0); break;
  1022. case 'e': v.push_back('='); break;
  1023. default: v.push_back(*eq); break;
  1024. }
  1025. ++eq;
  1026. }
  1027. } else {
  1028. v.push_back(*(eq++));
  1029. }
  1030. }
  1031. if ((k.length() > 0)&&(v.length() > 0))
  1032. d[k] = v;
  1033. }
  1034. }
  1035. const int64_t now = OSUtils::now();
  1036. OSUtils::ztsnprintf(id,sizeof(id),"%.10llx-%.16llx-%.10llx-%.4x",_signingId.address().toInt(),now,rt.origin,(unsigned int)(idCounter++ & 0xffff));
  1037. d["id"] = id;
  1038. d["objtype"] = "trace";
  1039. d["ts"] = now;
  1040. d["nodeId"] = Utils::hex10(rt.origin,tmp);
  1041. _db->save((nlohmann::json *)0,d);
  1042. } catch ( ... ) {
  1043. // drop invalid trace messages if an error occurs
  1044. }
  1045. }
  1046. void EmbeddedNetworkController::onNetworkUpdate(const uint64_t networkId)
  1047. {
  1048. // Send an update to all members of the network that are online
  1049. const int64_t now = OSUtils::now();
  1050. std::lock_guard<std::mutex> l(_memberStatus_l);
  1051. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1052. if ((i->first.networkId == networkId)&&(i->second.online(now))&&(i->second.lastRequestMetaData))
  1053. request(networkId,InetAddress(),0,i->second.identity,i->second.lastRequestMetaData);
  1054. }
  1055. }
  1056. void EmbeddedNetworkController::onNetworkMemberUpdate(const uint64_t networkId,const uint64_t memberId)
  1057. {
  1058. // Push update to member if online
  1059. try {
  1060. std::lock_guard<std::mutex> l(_memberStatus_l);
  1061. _MemberStatus &ms = _memberStatus[_MemberStatusKey(networkId,memberId)];
  1062. if ((ms.online(OSUtils::now()))&&(ms.lastRequestMetaData))
  1063. request(networkId,InetAddress(),0,ms.identity,ms.lastRequestMetaData);
  1064. } catch ( ... ) {}
  1065. }
  1066. void EmbeddedNetworkController::onNetworkMemberDeauthorize(const uint64_t networkId,const uint64_t memberId)
  1067. {
  1068. const int64_t now = OSUtils::now();
  1069. Revocation rev((uint32_t)_node->prng(),networkId,0,now,ZT_REVOCATION_FLAG_FAST_PROPAGATE,Address(memberId),Revocation::CREDENTIAL_TYPE_COM);
  1070. rev.sign(_signingId);
  1071. {
  1072. std::lock_guard<std::mutex> l(_memberStatus_l);
  1073. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1074. if ((i->first.networkId == networkId)&&(i->second.online(now)))
  1075. _node->ncSendRevocation(Address(i->first.nodeId),rev);
  1076. }
  1077. }
  1078. }
  1079. void EmbeddedNetworkController::_request(
  1080. uint64_t nwid,
  1081. const InetAddress &fromAddr,
  1082. uint64_t requestPacketId,
  1083. const Identity &identity,
  1084. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  1085. {
  1086. char nwids[24];
  1087. DB::NetworkSummaryInfo ns;
  1088. json network,member,origMember;
  1089. if (!_db)
  1090. return;
  1091. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  1092. return;
  1093. const int64_t now = OSUtils::now();
  1094. if (requestPacketId) {
  1095. std::lock_guard<std::mutex> l(_memberStatus_l);
  1096. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,identity.address().toInt())];
  1097. if ((now - ms.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  1098. return;
  1099. ms.lastRequestTime = now;
  1100. }
  1101. _db->nodeIsOnline(nwid,identity.address().toInt(),fromAddr);
  1102. Utils::hex(nwid,nwids);
  1103. _db->get(nwid,network,identity.address().toInt(),member,ns);
  1104. if ((!network.is_object())||(network.size() == 0)) {
  1105. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND);
  1106. return;
  1107. }
  1108. origMember = member;
  1109. const bool newMember = ((!member.is_object())||(member.size() == 0));
  1110. DB::initMember(member);
  1111. {
  1112. const std::string haveIdStr(OSUtils::jsonString(member["identity"],""));
  1113. if (haveIdStr.length() > 0) {
  1114. // If we already know this member's identity perform a full compare. This prevents
  1115. // a "collision" from being able to auth onto our network in place of an already
  1116. // known member.
  1117. try {
  1118. if (Identity(haveIdStr.c_str()) != identity) {
  1119. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1120. return;
  1121. }
  1122. } catch ( ... ) {
  1123. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1124. return;
  1125. }
  1126. } else {
  1127. // If we do not yet know this member's identity, learn it.
  1128. char idtmp[1024];
  1129. member["identity"] = identity.toString(false,idtmp);
  1130. }
  1131. }
  1132. // These are always the same, but make sure they are set
  1133. {
  1134. char tmpid[128];
  1135. const std::string addrs(identity.address().toString(tmpid));
  1136. member["id"] = addrs;
  1137. member["address"] = addrs;
  1138. member["nwid"] = nwids;
  1139. }
  1140. // Determine whether and how member is authorized
  1141. bool authorized = false;
  1142. bool autoAuthorized = false;
  1143. json autoAuthCredentialType,autoAuthCredential;
  1144. if (OSUtils::jsonBool(member["authorized"],false)) {
  1145. authorized = true;
  1146. } else if (!OSUtils::jsonBool(network["private"],true)) {
  1147. authorized = true;
  1148. autoAuthorized = true;
  1149. autoAuthCredentialType = "public";
  1150. } else {
  1151. char presentedAuth[512];
  1152. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  1153. presentedAuth[511] = (char)0; // sanity check
  1154. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  1155. const char *const presentedToken = presentedAuth + 6;
  1156. json authTokens(network["authTokens"]);
  1157. json &tokenExpires = authTokens[presentedToken];
  1158. if (tokenExpires.is_number()) {
  1159. if ((tokenExpires == 0)||(tokenExpires > now)) {
  1160. authorized = true;
  1161. autoAuthorized = true;
  1162. autoAuthCredentialType = "token";
  1163. autoAuthCredential = presentedToken;
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. // If we auto-authorized, update member record
  1170. if ((autoAuthorized)&&(authorized)) {
  1171. member["authorized"] = true;
  1172. member["lastAuthorizedTime"] = now;
  1173. member["lastAuthorizedCredentialType"] = autoAuthCredentialType;
  1174. member["lastAuthorizedCredential"] = autoAuthCredential;
  1175. }
  1176. if (authorized) {
  1177. // Update version info and meta-data if authorized and if this is a genuine request
  1178. if (requestPacketId) {
  1179. const uint64_t vMajor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  1180. const uint64_t vMinor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  1181. const uint64_t vRev = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  1182. const uint64_t vProto = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  1183. member["vMajor"] = vMajor;
  1184. member["vMinor"] = vMinor;
  1185. member["vRev"] = vRev;
  1186. member["vProto"] = vProto;
  1187. {
  1188. std::lock_guard<std::mutex> l(_memberStatus_l);
  1189. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,identity.address().toInt())];
  1190. ms.vMajor = (int)vMajor;
  1191. ms.vMinor = (int)vMinor;
  1192. ms.vRev = (int)vRev;
  1193. ms.vProto = (int)vProto;
  1194. ms.lastRequestMetaData = metaData;
  1195. ms.identity = identity;
  1196. }
  1197. }
  1198. } else {
  1199. // If they are not authorized, STOP!
  1200. DB::cleanMember(member);
  1201. _db->save(&origMember,member);
  1202. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1203. return;
  1204. }
  1205. // -------------------------------------------------------------------------
  1206. // If we made it this far, they are authorized.
  1207. // -------------------------------------------------------------------------
  1208. int64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1209. if (now > ns.mostRecentDeauthTime) {
  1210. // If we recently de-authorized a member, shrink credential TTL/max delta to
  1211. // be below the threshold required to exclude it. Cap this to a min/max to
  1212. // prevent jitter or absurdly large values.
  1213. const uint64_t deauthWindow = now - ns.mostRecentDeauthTime;
  1214. if (deauthWindow < ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA) {
  1215. credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
  1216. } else if (deauthWindow < (ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA + 5000ULL)) {
  1217. credentialtmd = deauthWindow - 5000ULL;
  1218. }
  1219. }
  1220. std::unique_ptr<NetworkConfig> nc(new NetworkConfig());
  1221. nc->networkId = nwid;
  1222. nc->type = OSUtils::jsonBool(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  1223. nc->timestamp = now;
  1224. nc->credentialTimeMaxDelta = credentialtmd;
  1225. nc->revision = OSUtils::jsonInt(network["revision"],0ULL);
  1226. nc->issuedTo = identity.address();
  1227. if (OSUtils::jsonBool(network["enableBroadcast"],true)) nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  1228. Utils::scopy(nc->name,sizeof(nc->name),OSUtils::jsonString(network["name"],"").c_str());
  1229. nc->mtu = std::max(std::min((unsigned int)OSUtils::jsonInt(network["mtu"],ZT_DEFAULT_MTU),(unsigned int)ZT_MAX_MTU),(unsigned int)ZT_MIN_MTU);
  1230. nc->multicastLimit = (unsigned int)OSUtils::jsonInt(network["multicastLimit"],32ULL);
  1231. std::string rtt(OSUtils::jsonString(member["remoteTraceTarget"],""));
  1232. if (rtt.length() == 10) {
  1233. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1234. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(member["remoteTraceLevel"],0ULL);
  1235. } else {
  1236. rtt = OSUtils::jsonString(network["remoteTraceTarget"],"");
  1237. if (rtt.length() == 10) {
  1238. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1239. } else {
  1240. nc->remoteTraceTarget.zero();
  1241. }
  1242. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(network["remoteTraceLevel"],0ULL);
  1243. }
  1244. for(std::vector<Address>::const_iterator ab(ns.activeBridges.begin());ab!=ns.activeBridges.end();++ab)
  1245. nc->addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  1246. json &v4AssignMode = network["v4AssignMode"];
  1247. json &v6AssignMode = network["v6AssignMode"];
  1248. json &ipAssignmentPools = network["ipAssignmentPools"];
  1249. json &routes = network["routes"];
  1250. json &rules = network["rules"];
  1251. json &capabilities = network["capabilities"];
  1252. json &tags = network["tags"];
  1253. json &memberCapabilities = member["capabilities"];
  1254. json &memberTags = member["tags"];
  1255. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
  1256. // Old versions with no rules engine support get an allow everything rule.
  1257. // Since rules are enforced bidirectionally, newer versions *will* still
  1258. // enforce rules on the inbound side.
  1259. nc->ruleCount = 1;
  1260. nc->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  1261. } else {
  1262. if (rules.is_array()) {
  1263. for(unsigned long i=0;i<rules.size();++i) {
  1264. if (nc->ruleCount >= ZT_MAX_NETWORK_RULES)
  1265. break;
  1266. if (_parseRule(rules[i],nc->rules[nc->ruleCount]))
  1267. ++nc->ruleCount;
  1268. }
  1269. }
  1270. std::map< uint64_t,json * > capsById;
  1271. if (!memberCapabilities.is_array())
  1272. memberCapabilities = json::array();
  1273. if (capabilities.is_array()) {
  1274. for(unsigned long i=0;i<capabilities.size();++i) {
  1275. json &cap = capabilities[i];
  1276. if (cap.is_object()) {
  1277. const uint64_t id = OSUtils::jsonInt(cap["id"],0ULL) & 0xffffffffULL;
  1278. capsById[id] = &cap;
  1279. if ((newMember)&&(OSUtils::jsonBool(cap["default"],false))) {
  1280. bool have = false;
  1281. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1282. if (id == (OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL)) {
  1283. have = true;
  1284. break;
  1285. }
  1286. }
  1287. if (!have)
  1288. memberCapabilities.push_back(id);
  1289. }
  1290. }
  1291. }
  1292. }
  1293. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1294. const uint64_t capId = OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL;
  1295. std::map< uint64_t,json * >::const_iterator ctmp = capsById.find(capId);
  1296. if (ctmp != capsById.end()) {
  1297. json *cap = ctmp->second;
  1298. if ((cap)&&(cap->is_object())&&(cap->size() > 0)) {
  1299. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  1300. unsigned int caprc = 0;
  1301. json &caprj = (*cap)["rules"];
  1302. if ((caprj.is_array())&&(caprj.size() > 0)) {
  1303. for(unsigned long j=0;j<caprj.size();++j) {
  1304. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  1305. break;
  1306. if (_parseRule(caprj[j],capr[caprc]))
  1307. ++caprc;
  1308. }
  1309. }
  1310. nc->capabilities[nc->capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  1311. if (nc->capabilities[nc->capabilityCount].sign(_signingId,identity.address()))
  1312. ++nc->capabilityCount;
  1313. if (nc->capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  1314. break;
  1315. }
  1316. }
  1317. }
  1318. std::map< uint32_t,uint32_t > memberTagsById;
  1319. if (memberTags.is_array()) {
  1320. for(unsigned long i=0;i<memberTags.size();++i) {
  1321. json &t = memberTags[i];
  1322. if ((t.is_array())&&(t.size() == 2))
  1323. memberTagsById[(uint32_t)(OSUtils::jsonInt(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(OSUtils::jsonInt(t[1],0ULL) & 0xffffffffULL);
  1324. }
  1325. }
  1326. if (tags.is_array()) { // check network tags array for defaults that are not present in member tags
  1327. for(unsigned long i=0;i<tags.size();++i) {
  1328. json &t = tags[i];
  1329. if (t.is_object()) {
  1330. const uint32_t id = (uint32_t)(OSUtils::jsonInt(t["id"],0) & 0xffffffffULL);
  1331. json &dfl = t["default"];
  1332. if ((dfl.is_number())&&(memberTagsById.find(id) == memberTagsById.end())) {
  1333. memberTagsById[id] = (uint32_t)(OSUtils::jsonInt(dfl,0) & 0xffffffffULL);
  1334. json mt = json::array();
  1335. mt.push_back(id);
  1336. mt.push_back(dfl);
  1337. memberTags.push_back(mt); // add default to member tags if not present
  1338. }
  1339. }
  1340. }
  1341. }
  1342. for(std::map< uint32_t,uint32_t >::const_iterator t(memberTagsById.begin());t!=memberTagsById.end();++t) {
  1343. if (nc->tagCount >= ZT_MAX_NETWORK_TAGS)
  1344. break;
  1345. nc->tags[nc->tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  1346. if (nc->tags[nc->tagCount].sign(_signingId))
  1347. ++nc->tagCount;
  1348. }
  1349. }
  1350. if (routes.is_array()) {
  1351. for(unsigned long i=0;i<routes.size();++i) {
  1352. if (nc->routeCount >= ZT_MAX_NETWORK_ROUTES)
  1353. break;
  1354. json &route = routes[i];
  1355. json &target = route["target"];
  1356. json &via = route["via"];
  1357. if (target.is_string()) {
  1358. const InetAddress t(target.get<std::string>().c_str());
  1359. InetAddress v;
  1360. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  1361. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  1362. ZT_VirtualNetworkRoute *r = &(nc->routes[nc->routeCount]);
  1363. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  1364. if (v.ss_family == t.ss_family)
  1365. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  1366. ++nc->routeCount;
  1367. }
  1368. }
  1369. }
  1370. }
  1371. const bool noAutoAssignIps = OSUtils::jsonBool(member["noAutoAssignIps"],false);
  1372. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  1373. if ((OSUtils::jsonBool(v6AssignMode["rfc4193"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1374. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  1375. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1376. }
  1377. if ((OSUtils::jsonBool(v6AssignMode["6plane"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1378. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  1379. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1380. }
  1381. }
  1382. bool haveManagedIpv4AutoAssignment = false;
  1383. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  1384. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  1385. if (ipAssignments.is_array()) {
  1386. for(unsigned long i=0;i<ipAssignments.size();++i) {
  1387. if (ipAssignments[i].is_string()) {
  1388. const std::string ips = ipAssignments[i];
  1389. InetAddress ip(ips.c_str());
  1390. int routedNetmaskBits = -1;
  1391. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1392. if (reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->containsAddress(ip)) {
  1393. const int nb = (int)(reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits());
  1394. if (nb > routedNetmaskBits)
  1395. routedNetmaskBits = nb;
  1396. }
  1397. }
  1398. if (routedNetmaskBits >= 0) {
  1399. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1400. ip.setPort(routedNetmaskBits);
  1401. nc->staticIps[nc->staticIpCount++] = ip;
  1402. }
  1403. if (ip.ss_family == AF_INET)
  1404. haveManagedIpv4AutoAssignment = true;
  1405. else if (ip.ss_family == AF_INET6)
  1406. haveManagedIpv6AutoAssignment = true;
  1407. }
  1408. }
  1409. }
  1410. } else {
  1411. ipAssignments = json::array();
  1412. }
  1413. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(OSUtils::jsonBool(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  1414. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  1415. json &pool = ipAssignmentPools[p];
  1416. if (pool.is_object()) {
  1417. InetAddress ipRangeStart(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1418. InetAddress ipRangeEnd(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1419. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  1420. uint64_t s[2],e[2],x[2],xx[2];
  1421. memcpy(s,ipRangeStart.rawIpData(),16);
  1422. memcpy(e,ipRangeEnd.rawIpData(),16);
  1423. s[0] = Utils::ntoh(s[0]);
  1424. s[1] = Utils::ntoh(s[1]);
  1425. e[0] = Utils::ntoh(e[0]);
  1426. e[1] = Utils::ntoh(e[1]);
  1427. x[0] = s[0];
  1428. x[1] = s[1];
  1429. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  1430. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  1431. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  1432. xx[0] = Utils::hton(x[0]);
  1433. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  1434. } else {
  1435. // 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
  1436. Utils::getSecureRandom((void *)xx,16);
  1437. if ((e[0] > s[0]))
  1438. xx[0] %= (e[0] - s[0]);
  1439. else xx[0] = 0;
  1440. if ((e[1] > s[1]))
  1441. xx[1] %= (e[1] - s[1]);
  1442. else xx[1] = 0;
  1443. xx[0] = Utils::hton(x[0] + xx[0]);
  1444. xx[1] = Utils::hton(x[1] + xx[1]);
  1445. }
  1446. InetAddress ip6((const void *)xx,16,0);
  1447. // Check if this IP is within a local-to-Ethernet routed network
  1448. int routedNetmaskBits = 0;
  1449. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1450. 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)) )
  1451. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits();
  1452. }
  1453. // If it's routed, then try to claim and assign it and if successful end loop
  1454. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip6)) ) {
  1455. char tmpip[64];
  1456. const std::string ipStr(ip6.toIpString(tmpip));
  1457. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1458. ipAssignments.push_back(ipStr);
  1459. member["ipAssignments"] = ipAssignments;
  1460. ip6.setPort((unsigned int)routedNetmaskBits);
  1461. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  1462. nc->staticIps[nc->staticIpCount++] = ip6;
  1463. haveManagedIpv6AutoAssignment = true;
  1464. break;
  1465. }
  1466. }
  1467. }
  1468. }
  1469. }
  1470. }
  1471. }
  1472. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(OSUtils::jsonBool(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  1473. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  1474. json &pool = ipAssignmentPools[p];
  1475. if (pool.is_object()) {
  1476. InetAddress ipRangeStartIA(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1477. InetAddress ipRangeEndIA(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1478. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  1479. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  1480. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  1481. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  1482. continue;
  1483. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1484. // Start with the LSB of the member's address
  1485. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1486. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  1487. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1488. ++ipTrialCounter;
  1489. if ((ip & 0x000000ff) == 0x000000ff) {
  1490. continue; // don't allow addresses that end in .255
  1491. }
  1492. // Check if this IP is within a local-to-Ethernet routed network
  1493. int routedNetmaskBits = -1;
  1494. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1495. if (nc->routes[rk].target.ss_family == AF_INET) {
  1496. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_addr.s_addr));
  1497. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_port));
  1498. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  1499. routedNetmaskBits = targetBits;
  1500. break;
  1501. }
  1502. }
  1503. }
  1504. // If it's routed, then try to claim and assign it and if successful end loop
  1505. const InetAddress ip4(Utils::hton(ip),0);
  1506. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip4)) ) {
  1507. char tmpip[64];
  1508. const std::string ipStr(ip4.toIpString(tmpip));
  1509. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1510. ipAssignments.push_back(ipStr);
  1511. member["ipAssignments"] = ipAssignments;
  1512. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1513. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc->staticIps[nc->staticIpCount++]));
  1514. v4ip->sin_family = AF_INET;
  1515. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  1516. v4ip->sin_addr.s_addr = Utils::hton(ip);
  1517. }
  1518. haveManagedIpv4AutoAssignment = true;
  1519. break;
  1520. }
  1521. }
  1522. }
  1523. }
  1524. }
  1525. }
  1526. }
  1527. // Issue a certificate of ownership for all static IPs
  1528. if (nc->staticIpCount) {
  1529. nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1);
  1530. for(unsigned int i=0;i<nc->staticIpCount;++i)
  1531. nc->certificatesOfOwnership[0].addThing(nc->staticIps[i]);
  1532. nc->certificatesOfOwnership[0].sign(_signingId);
  1533. nc->certificateOfOwnershipCount = 1;
  1534. }
  1535. CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
  1536. if (com.sign(_signingId)) {
  1537. nc->com = com;
  1538. } else {
  1539. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR);
  1540. return;
  1541. }
  1542. DB::cleanMember(member);
  1543. _db->save(&origMember,member);
  1544. _sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
  1545. }
  1546. void EmbeddedNetworkController::_startThreads()
  1547. {
  1548. std::lock_guard<std::mutex> l(_threads_l);
  1549. if (!_threads.empty())
  1550. return;
  1551. const long hwc = std::max((long)std::thread::hardware_concurrency(),(long)1);
  1552. for(long t=0;t<hwc;++t) {
  1553. _threads.emplace_back([this]() {
  1554. for(;;) {
  1555. _RQEntry *qe = (_RQEntry *)0;
  1556. if (!_queue.get(qe))
  1557. break;
  1558. try {
  1559. if (qe) {
  1560. _request(qe->nwid,qe->fromAddr,qe->requestPacketId,qe->identity,qe->metaData);
  1561. delete qe;
  1562. }
  1563. } catch (std::exception &e) {
  1564. fprintf(stderr,"ERROR: exception in controller request handling thread: %s" ZT_EOL_S,e.what());
  1565. } catch ( ... ) {
  1566. fprintf(stderr,"ERROR: exception in controller request handling thread: unknown exception" ZT_EOL_S);
  1567. }
  1568. }
  1569. });
  1570. }
  1571. }
  1572. } // namespace ZeroTier