2
0

EmbeddedNetworkController.cpp 61 KB

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