EmbeddedNetworkController.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  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();
  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();
  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();
  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();
  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();
  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. Utils::snprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  112. r["mac"] = tmp;
  113. break;
  114. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  115. r["type"] = "MATCH_MAC_DEST";
  116. Utils::snprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  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();
  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();
  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();
  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();
  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. Utils::snprintf(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"));
  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"));
  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"));
  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"));
  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. _db(dbPath),
  411. _node(node)
  412. {
  413. }
  414. EmbeddedNetworkController::~EmbeddedNetworkController()
  415. {
  416. _running = false;
  417. std::vector<Thread> t;
  418. {
  419. Mutex::Lock _l(_threads_m);
  420. t = _threads;
  421. }
  422. if (t.size() > 0) {
  423. for(unsigned long i=0,j=(unsigned long)(t.size() * 4);i<j;++i)
  424. _queue.post((_RQEntry *)0);
  425. /*
  426. for(std::vector<Thread>::iterator i(t.begin());i!=t.end();++i)
  427. Thread::join(*i);
  428. */
  429. }
  430. }
  431. void EmbeddedNetworkController::init(const Identity &signingId,Sender *sender)
  432. {
  433. this->_sender = sender;
  434. this->_signingId = signingId;
  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. {
  446. Mutex::Lock _l(_threads_m);
  447. if (_threads.size() == 0) {
  448. long hwc = (long)(std::thread::hardware_concurrency() / 2);
  449. if (hwc < 1)
  450. hwc = 1;
  451. else if (hwc > 16)
  452. hwc = 16;
  453. for(long i=0;i<hwc;++i)
  454. _threads.push_back(Thread::start(this));
  455. }
  456. }
  457. _RQEntry *qe = new _RQEntry;
  458. qe->nwid = nwid;
  459. qe->requestPacketId = requestPacketId;
  460. qe->fromAddr = fromAddr;
  461. qe->identity = identity;
  462. qe->metaData = metaData;
  463. _queue.post(qe);
  464. }
  465. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  466. const std::vector<std::string> &path,
  467. const std::map<std::string,std::string> &urlArgs,
  468. const std::map<std::string,std::string> &headers,
  469. const std::string &body,
  470. std::string &responseBody,
  471. std::string &responseContentType)
  472. {
  473. if ((path.size() > 0)&&(path[0] == "network")) {
  474. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  475. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  476. char nwids[24];
  477. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  478. json network;
  479. if (!_db.getNetwork(nwid,network))
  480. return 404;
  481. if (path.size() >= 3) {
  482. if (path[2] == "member") {
  483. if (path.size() >= 4) {
  484. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  485. json member;
  486. if (!_db.getNetworkMember(nwid,address,member))
  487. return 404;
  488. _addMemberNonPersistedFields(nwid,address,member,OSUtils::now());
  489. responseBody = OSUtils::jsonDump(member);
  490. responseContentType = "application/json";
  491. } else {
  492. responseBody = "{";
  493. _db.eachMember(nwid,[&responseBody](uint64_t networkId,uint64_t nodeId,const json &member) {
  494. if ((member.is_object())&&(member.size() > 0)) {
  495. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  496. responseBody.append(OSUtils::jsonString(member["id"],"0"));
  497. responseBody.append("\":");
  498. responseBody.append(OSUtils::jsonString(member["revision"],"0"));
  499. }
  500. });
  501. responseBody.push_back('}');
  502. responseContentType = "application/json";
  503. }
  504. return 200;
  505. } // else 404
  506. } else {
  507. const uint64_t now = OSUtils::now();
  508. JSONDB::NetworkSummaryInfo ns;
  509. _db.getNetworkSummaryInfo(nwid,ns);
  510. _addNetworkNonPersistedFields(network,now,ns);
  511. responseBody = OSUtils::jsonDump(network);
  512. responseContentType = "application/json";
  513. return 200;
  514. }
  515. } else if (path.size() == 1) {
  516. std::vector<uint64_t> networkIds(_db.networkIds());
  517. std::sort(networkIds.begin(),networkIds.end());
  518. char tmp[64];
  519. responseBody.push_back('[');
  520. for(std::vector<uint64_t>::const_iterator i(networkIds.begin());i!=networkIds.end();++i) {
  521. if (responseBody.length() > 1)
  522. responseBody.push_back(',');
  523. Utils::snprintf(tmp,sizeof(tmp),"\"%.16llx\"",(unsigned long long)*i);
  524. responseBody.append(tmp);
  525. }
  526. responseBody.push_back(']');
  527. responseContentType = "application/json";
  528. return 200;
  529. } // else 404
  530. } else {
  531. char tmp[4096];
  532. Utils::snprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now());
  533. responseBody = tmp;
  534. responseContentType = "application/json";
  535. return 200;
  536. }
  537. return 404;
  538. }
  539. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  540. const std::vector<std::string> &path,
  541. const std::map<std::string,std::string> &urlArgs,
  542. const std::map<std::string,std::string> &headers,
  543. const std::string &body,
  544. std::string &responseBody,
  545. std::string &responseContentType)
  546. {
  547. if (path.empty())
  548. return 404;
  549. json b;
  550. try {
  551. b = OSUtils::jsonParse(body);
  552. if (!b.is_object()) {
  553. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  554. responseContentType = "application/json";
  555. return 400;
  556. }
  557. } catch ( ... ) {
  558. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  559. responseContentType = "application/json";
  560. return 400;
  561. }
  562. const uint64_t now = OSUtils::now();
  563. if (path[0] == "network") {
  564. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  565. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  566. char nwids[24];
  567. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  568. if (path.size() >= 3) {
  569. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  570. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  571. char addrs[24];
  572. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  573. json member;
  574. _db.getNetworkMember(nwid,address,member);
  575. json origMember(member); // for detecting changes
  576. _initMember(member);
  577. try {
  578. if (b.count("activeBridge")) member["activeBridge"] = OSUtils::jsonBool(b["activeBridge"],false);
  579. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = OSUtils::jsonBool(b["noAutoAssignIps"],false);
  580. if (b.count("authorized")) {
  581. const bool newAuth = OSUtils::jsonBool(b["authorized"],false);
  582. if (newAuth != OSUtils::jsonBool(member["authorized"],false)) {
  583. member["authorized"] = newAuth;
  584. member[((newAuth) ? "lastAuthorizedTime" : "lastDeauthorizedTime")] = now;
  585. json ah;
  586. ah["a"] = newAuth;
  587. ah["by"] = "api";
  588. ah["ts"] = now;
  589. ah["ct"] = json();
  590. ah["c"] = json();
  591. member["authHistory"].push_back(ah);
  592. // Member is being de-authorized, so spray Revocation objects to all online members
  593. if (!newAuth) {
  594. Revocation rev((uint32_t)_node->prng(),nwid,0,now,ZT_REVOCATION_FLAG_FAST_PROPAGATE,Address(address),Revocation::CREDENTIAL_TYPE_COM);
  595. rev.sign(_signingId);
  596. Mutex::Lock _l(_memberStatus_m);
  597. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  598. if ((i->first.networkId == nwid)&&(i->second.online(now)))
  599. _node->ncSendRevocation(Address(i->first.nodeId),rev);
  600. }
  601. }
  602. }
  603. }
  604. if (b.count("ipAssignments")) {
  605. json &ipa = b["ipAssignments"];
  606. if (ipa.is_array()) {
  607. json mipa(json::array());
  608. for(unsigned long i=0;i<ipa.size();++i) {
  609. std::string ips = ipa[i];
  610. InetAddress ip(ips);
  611. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  612. mipa.push_back(ip.toIpString());
  613. }
  614. }
  615. member["ipAssignments"] = mipa;
  616. }
  617. }
  618. if (b.count("tags")) {
  619. json &tags = b["tags"];
  620. if (tags.is_array()) {
  621. std::map<uint64_t,uint64_t> mtags;
  622. for(unsigned long i=0;i<tags.size();++i) {
  623. json &tag = tags[i];
  624. if ((tag.is_array())&&(tag.size() == 2))
  625. mtags[OSUtils::jsonInt(tag[0],0ULL) & 0xffffffffULL] = OSUtils::jsonInt(tag[1],0ULL) & 0xffffffffULL;
  626. }
  627. json mtagsa = json::array();
  628. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  629. json ta = json::array();
  630. ta.push_back(t->first);
  631. ta.push_back(t->second);
  632. mtagsa.push_back(ta);
  633. }
  634. member["tags"] = mtagsa;
  635. }
  636. }
  637. if (b.count("capabilities")) {
  638. json &capabilities = b["capabilities"];
  639. if (capabilities.is_array()) {
  640. json mcaps = json::array();
  641. for(unsigned long i=0;i<capabilities.size();++i) {
  642. mcaps.push_back(OSUtils::jsonInt(capabilities[i],0ULL));
  643. }
  644. std::sort(mcaps.begin(),mcaps.end());
  645. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  646. member["capabilities"] = mcaps;
  647. }
  648. }
  649. } catch ( ... ) {
  650. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  651. responseContentType = "application/json";
  652. return 400;
  653. }
  654. member["id"] = addrs;
  655. member["address"] = addrs; // legacy
  656. member["nwid"] = nwids;
  657. _removeMemberNonPersistedFields(member);
  658. if (member != origMember) {
  659. json &revj = member["revision"];
  660. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  661. _db.saveNetworkMember(nwid,address,member);
  662. // Push update to member if online
  663. try {
  664. Mutex::Lock _l(_memberStatus_m);
  665. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,address)];
  666. if ((ms.online(now))&&(ms.lastRequestMetaData))
  667. request(nwid,InetAddress(),0,ms.identity,ms.lastRequestMetaData);
  668. } catch ( ... ) {}
  669. }
  670. _addMemberNonPersistedFields(nwid,address,member,now);
  671. responseBody = OSUtils::jsonDump(member);
  672. responseContentType = "application/json";
  673. return 200;
  674. } else if ((path.size() == 3)&&(path[2] == "test")) {
  675. Mutex::Lock _l(_tests_m);
  676. _tests.push_back(ZT_CircuitTest());
  677. ZT_CircuitTest *const test = &(_tests.back());
  678. memset(test,0,sizeof(ZT_CircuitTest));
  679. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  680. test->credentialNetworkId = nwid;
  681. test->ptr = (void *)this;
  682. json hops = b["hops"];
  683. if (hops.is_array()) {
  684. for(unsigned long i=0;i<hops.size();++i) {
  685. json &hops2 = hops[i];
  686. if (hops2.is_array()) {
  687. for(unsigned long j=0;j<hops2.size();++j) {
  688. std::string s = hops2[j];
  689. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  690. }
  691. ++test->hopCount;
  692. } else if (hops2.is_string()) {
  693. std::string s = hops2;
  694. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  695. ++test->hopCount;
  696. }
  697. }
  698. }
  699. test->reportAtEveryHop = (OSUtils::jsonBool(b["reportAtEveryHop"],true) ? 1 : 0);
  700. if (!test->hopCount) {
  701. _tests.pop_back();
  702. responseBody = "{ \"message\": \"a test must contain at least one hop\" }";
  703. responseContentType = "application/json";
  704. return 400;
  705. }
  706. test->timestamp = OSUtils::now();
  707. if (_node) {
  708. _node->circuitTestBegin((void *)0,test,&(EmbeddedNetworkController::_circuitTestCallback));
  709. } else {
  710. _tests.pop_back();
  711. return 500;
  712. }
  713. char json[512];
  714. Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\",\"timestamp\":%llu}",test->testId,test->timestamp);
  715. responseBody = json;
  716. responseContentType = "application/json";
  717. return 200;
  718. } // else 404
  719. } else {
  720. // POST to network ID
  721. // Magic ID ending with ______ picks a random unused network ID
  722. if (path[1].substr(10) == "______") {
  723. nwid = 0;
  724. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  725. uint64_t nwidPostfix = 0;
  726. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  727. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  728. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  729. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  730. if (!_db.hasNetwork(tryNwid)) {
  731. nwid = tryNwid;
  732. break;
  733. }
  734. }
  735. if (!nwid)
  736. return 503;
  737. }
  738. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  739. json network;
  740. _db.getNetwork(nwid,network);
  741. json origNetwork(network); // for detecting changes
  742. _initNetwork(network);
  743. try {
  744. if (b.count("name")) network["name"] = OSUtils::jsonString(b["name"],"");
  745. if (b.count("private")) network["private"] = OSUtils::jsonBool(b["private"],true);
  746. if (b.count("enableBroadcast")) network["enableBroadcast"] = OSUtils::jsonBool(b["enableBroadcast"],false);
  747. if (b.count("allowPassiveBridging")) network["allowPassiveBridging"] = OSUtils::jsonBool(b["allowPassiveBridging"],false);
  748. if (b.count("multicastLimit")) network["multicastLimit"] = OSUtils::jsonInt(b["multicastLimit"],32ULL);
  749. if (b.count("v4AssignMode")) {
  750. json nv4m;
  751. json &v4m = b["v4AssignMode"];
  752. if (v4m.is_string()) { // backward compatibility
  753. nv4m["zt"] = (OSUtils::jsonString(v4m,"") == "zt");
  754. } else if (v4m.is_object()) {
  755. nv4m["zt"] = OSUtils::jsonBool(v4m["zt"],false);
  756. } else nv4m["zt"] = false;
  757. network["v4AssignMode"] = nv4m;
  758. }
  759. if (b.count("v6AssignMode")) {
  760. json nv6m;
  761. json &v6m = b["v6AssignMode"];
  762. if (!nv6m.is_object()) nv6m = json::object();
  763. if (v6m.is_string()) { // backward compatibility
  764. std::vector<std::string> v6ms(OSUtils::split(OSUtils::jsonString(v6m,"").c_str(),",","",""));
  765. std::sort(v6ms.begin(),v6ms.end());
  766. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  767. nv6m["rfc4193"] = false;
  768. nv6m["zt"] = false;
  769. nv6m["6plane"] = false;
  770. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  771. if (*i == "rfc4193")
  772. nv6m["rfc4193"] = true;
  773. else if (*i == "zt")
  774. nv6m["zt"] = true;
  775. else if (*i == "6plane")
  776. nv6m["6plane"] = true;
  777. }
  778. } else if (v6m.is_object()) {
  779. if (v6m.count("rfc4193")) nv6m["rfc4193"] = OSUtils::jsonBool(v6m["rfc4193"],false);
  780. if (v6m.count("zt")) nv6m["zt"] = OSUtils::jsonBool(v6m["zt"],false);
  781. if (v6m.count("6plane")) nv6m["6plane"] = OSUtils::jsonBool(v6m["6plane"],false);
  782. } else {
  783. nv6m["rfc4193"] = false;
  784. nv6m["zt"] = false;
  785. nv6m["6plane"] = false;
  786. }
  787. network["v6AssignMode"] = nv6m;
  788. }
  789. if (b.count("routes")) {
  790. json &rts = b["routes"];
  791. if (rts.is_array()) {
  792. json nrts = json::array();
  793. for(unsigned long i=0;i<rts.size();++i) {
  794. json &rt = rts[i];
  795. if (rt.is_object()) {
  796. json &target = rt["target"];
  797. json &via = rt["via"];
  798. if (target.is_string()) {
  799. InetAddress t(target.get<std::string>());
  800. InetAddress v;
  801. if (via.is_string()) v.fromString(via.get<std::string>());
  802. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  803. json tmp;
  804. tmp["target"] = t.toString();
  805. if (v.ss_family == t.ss_family)
  806. tmp["via"] = v.toIpString();
  807. else tmp["via"] = json();
  808. nrts.push_back(tmp);
  809. }
  810. }
  811. }
  812. }
  813. network["routes"] = nrts;
  814. }
  815. }
  816. if (b.count("ipAssignmentPools")) {
  817. json &ipp = b["ipAssignmentPools"];
  818. if (ipp.is_array()) {
  819. json nipp = json::array();
  820. for(unsigned long i=0;i<ipp.size();++i) {
  821. json &ip = ipp[i];
  822. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  823. InetAddress f(OSUtils::jsonString(ip["ipRangeStart"],""));
  824. InetAddress t(OSUtils::jsonString(ip["ipRangeEnd"],""));
  825. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  826. json tmp = json::object();
  827. tmp["ipRangeStart"] = f.toIpString();
  828. tmp["ipRangeEnd"] = t.toIpString();
  829. nipp.push_back(tmp);
  830. }
  831. }
  832. }
  833. network["ipAssignmentPools"] = nipp;
  834. }
  835. }
  836. if (b.count("rules")) {
  837. json &rules = b["rules"];
  838. if (rules.is_array()) {
  839. json nrules = json::array();
  840. for(unsigned long i=0;i<rules.size();++i) {
  841. json &rule = rules[i];
  842. if (rule.is_object()) {
  843. ZT_VirtualNetworkRule ztr;
  844. if (_parseRule(rule,ztr))
  845. nrules.push_back(_renderRule(ztr));
  846. }
  847. }
  848. network["rules"] = nrules;
  849. }
  850. }
  851. if (b.count("authTokens")) {
  852. json &authTokens = b["authTokens"];
  853. if (authTokens.is_array()) {
  854. json nat = json::array();
  855. for(unsigned long i=0;i<authTokens.size();++i) {
  856. json &token = authTokens[i];
  857. if (token.is_object()) {
  858. std::string tstr = token["token"];
  859. if (tstr.length() > 0) {
  860. json t = json::object();
  861. t["token"] = tstr;
  862. t["expires"] = OSUtils::jsonInt(token["expires"],0ULL);
  863. t["maxUsesPerMember"] = OSUtils::jsonInt(token["maxUsesPerMember"],0ULL);
  864. nat.push_back(t);
  865. }
  866. }
  867. }
  868. network["authTokens"] = nat;
  869. }
  870. }
  871. if (b.count("capabilities")) {
  872. json &capabilities = b["capabilities"];
  873. if (capabilities.is_array()) {
  874. std::map< uint64_t,json > ncaps;
  875. for(unsigned long i=0;i<capabilities.size();++i) {
  876. json &cap = capabilities[i];
  877. if (cap.is_object()) {
  878. json ncap = json::object();
  879. const uint64_t capId = OSUtils::jsonInt(cap["id"],0ULL);
  880. ncap["id"] = capId;
  881. ncap["default"] = OSUtils::jsonBool(cap["default"],false);
  882. json &rules = cap["rules"];
  883. json nrules = json::array();
  884. if (rules.is_array()) {
  885. for(unsigned long i=0;i<rules.size();++i) {
  886. json &rule = rules[i];
  887. if (rule.is_object()) {
  888. ZT_VirtualNetworkRule ztr;
  889. if (_parseRule(rule,ztr))
  890. nrules.push_back(_renderRule(ztr));
  891. }
  892. }
  893. }
  894. ncap["rules"] = nrules;
  895. ncaps[capId] = ncap;
  896. }
  897. }
  898. json ncapsa = json::array();
  899. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c)
  900. ncapsa.push_back(c->second);
  901. network["capabilities"] = ncapsa;
  902. }
  903. }
  904. if (b.count("tags")) {
  905. json &tags = b["tags"];
  906. if (tags.is_array()) {
  907. std::map< uint64_t,json > ntags;
  908. for(unsigned long i=0;i<tags.size();++i) {
  909. json &tag = tags[i];
  910. if (tag.is_object()) {
  911. json ntag = json::object();
  912. const uint64_t tagId = OSUtils::jsonInt(tag["id"],0ULL);
  913. ntag["id"] = tagId;
  914. json &dfl = tag["default"];
  915. if (dfl.is_null())
  916. ntag["default"] = dfl;
  917. else ntag["default"] = OSUtils::jsonInt(dfl,0ULL);
  918. ntags[tagId] = ntag;
  919. }
  920. }
  921. json ntagsa = json::array();
  922. for(std::map< uint64_t,json >::iterator t(ntags.begin());t!=ntags.end();++t)
  923. ntagsa.push_back(t->second);
  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. _removeNetworkNonPersistedFields(network);
  935. if (network != origNetwork) {
  936. json &revj = network["revision"];
  937. network["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  938. _db.saveNetwork(nwid,network);
  939. // Send an update to all members of the network that are online
  940. Mutex::Lock _l(_memberStatus_m);
  941. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  942. if ((i->first.networkId == nwid)&&(i->second.online(now))&&(i->second.lastRequestMetaData))
  943. request(nwid,InetAddress(),0,i->second.identity,i->second.lastRequestMetaData);
  944. }
  945. }
  946. JSONDB::NetworkSummaryInfo ns;
  947. _db.getNetworkSummaryInfo(nwid,ns);
  948. _addNetworkNonPersistedFields(network,now,ns);
  949. responseBody = OSUtils::jsonDump(network);
  950. responseContentType = "application/json";
  951. return 200;
  952. } // else 404
  953. } // else 404
  954. } else if (path[0] == "ping") {
  955. const uint64_t now = OSUtils::now();
  956. bool first = true;
  957. std::string pong("{\"memberStatus\":{");
  958. {
  959. Mutex::Lock _l(_memberStatus_m);
  960. pong.reserve(64 * _memberStatus.size());
  961. _db.eachId([this,&pong,&now,&first](uint64_t networkId,uint64_t nodeId) {
  962. char tmp[64];
  963. uint64_t lrt = 0ULL;
  964. auto ms = this->_memberStatus.find(_MemberStatusKey(networkId,nodeId));
  965. if (ms != _memberStatus.end())
  966. lrt = ms->second.lastRequestTime;
  967. Utils::snprintf(tmp,sizeof(tmp),"%s\"%.16llx-%.10llx\":%llu",
  968. (first) ? "" : ",",
  969. (unsigned long long)networkId,
  970. (unsigned long long)nodeId,
  971. (unsigned long long)lrt);
  972. pong.append(tmp);
  973. first = false;
  974. });
  975. }
  976. char tmp2[256];
  977. Utils::snprintf(tmp2,sizeof(tmp2),"},\"clock\":%llu,\"startTime\":%llu}",(unsigned long long)now,(unsigned long long)_startTime);
  978. pong.append(tmp2);
  979. _db.writeRaw("pong",pong);
  980. responseBody = "{}";
  981. responseContentType = "application/json";
  982. return 200;
  983. }
  984. return 404;
  985. }
  986. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  987. const std::vector<std::string> &path,
  988. const std::map<std::string,std::string> &urlArgs,
  989. const std::map<std::string,std::string> &headers,
  990. const std::string &body,
  991. std::string &responseBody,
  992. std::string &responseContentType)
  993. {
  994. if (path.empty())
  995. return 404;
  996. if (path[0] == "network") {
  997. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  998. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  999. if (path.size() >= 3) {
  1000. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1001. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1002. json member = _db.eraseNetworkMember(nwid,address);
  1003. {
  1004. Mutex::Lock _l(_memberStatus_m);
  1005. _memberStatus.erase(_MemberStatusKey(nwid,address));
  1006. }
  1007. if (!member.size())
  1008. return 404;
  1009. responseBody = OSUtils::jsonDump(member);
  1010. responseContentType = "application/json";
  1011. return 200;
  1012. }
  1013. } else {
  1014. json network = _db.eraseNetwork(nwid);
  1015. {
  1016. Mutex::Lock _l(_memberStatus_m);
  1017. for(auto i=_memberStatus.begin();i!=_memberStatus.end();) {
  1018. if (i->first.networkId == nwid)
  1019. _memberStatus.erase(i++);
  1020. else ++i;
  1021. }
  1022. }
  1023. if (!network.size())
  1024. return 404;
  1025. responseBody = OSUtils::jsonDump(network);
  1026. responseContentType = "application/json";
  1027. return 200;
  1028. }
  1029. } // else 404
  1030. } // else 404
  1031. return 404;
  1032. }
  1033. void EmbeddedNetworkController::threadMain()
  1034. throw()
  1035. {
  1036. uint64_t lastCircuitTestCheck = 0;
  1037. _RQEntry *qe = (_RQEntry *)0;
  1038. while ((_running)&&((qe = _queue.get()))) {
  1039. try {
  1040. _request(qe->nwid,qe->fromAddr,qe->requestPacketId,qe->identity,qe->metaData);
  1041. } catch ( ... ) {}
  1042. delete qe;
  1043. if (_running) {
  1044. uint64_t now = OSUtils::now();
  1045. if ((now - lastCircuitTestCheck) > ZT_EMBEDDEDNETWORKCONTROLLER_CIRCUIT_TEST_EXPIRATION) {
  1046. lastCircuitTestCheck = now;
  1047. Mutex::Lock _l(_tests_m);
  1048. for(std::list< ZT_CircuitTest >::iterator i(_tests.begin());i!=_tests.end();) {
  1049. if ((now - i->timestamp) > ZT_EMBEDDEDNETWORKCONTROLLER_CIRCUIT_TEST_EXPIRATION) {
  1050. _node->circuitTestEnd(&(*i));
  1051. _tests.erase(i++);
  1052. } else ++i;
  1053. }
  1054. }
  1055. }
  1056. }
  1057. }
  1058. void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1059. {
  1060. char tmp[2048],id[128];
  1061. EmbeddedNetworkController *const self = reinterpret_cast<EmbeddedNetworkController *>(test->ptr);
  1062. if ((!test)||(!report)||(!test->credentialNetworkId)) return; // sanity check
  1063. const uint64_t now = OSUtils::now();
  1064. Utils::snprintf(id,sizeof(id),"network/%.16llx/test/%.16llx-%.16llx-%.10llx-%.10llx",test->credentialNetworkId,test->testId,now,report->upstream,report->current);
  1065. Utils::snprintf(tmp,sizeof(tmp),
  1066. "{\"id\": \"%s\","
  1067. "\"objtype\": \"circuit_test\","
  1068. "\"timestamp\": %llu,"
  1069. "\"networkId\": \"%.16llx\","
  1070. "\"testId\": \"%.16llx\","
  1071. "\"upstream\": \"%.10llx\","
  1072. "\"current\": \"%.10llx\","
  1073. "\"receivedTimestamp\": %llu,"
  1074. "\"sourcePacketId\": \"%.16llx\","
  1075. "\"flags\": %llu,"
  1076. "\"sourcePacketHopCount\": %u,"
  1077. "\"errorCode\": %u,"
  1078. "\"vendor\": %d,"
  1079. "\"protocolVersion\": %u,"
  1080. "\"majorVersion\": %u,"
  1081. "\"minorVersion\": %u,"
  1082. "\"revision\": %u,"
  1083. "\"platform\": %d,"
  1084. "\"architecture\": %d,"
  1085. "\"receivedOnLocalAddress\": \"%s\","
  1086. "\"receivedFromRemoteAddress\": \"%s\","
  1087. "\"receivedFromLinkQuality\": %f}",
  1088. id + 30, // last bit only, not leading path
  1089. (unsigned long long)test->timestamp,
  1090. (unsigned long long)test->credentialNetworkId,
  1091. (unsigned long long)test->testId,
  1092. (unsigned long long)report->upstream,
  1093. (unsigned long long)report->current,
  1094. (unsigned long long)now,
  1095. (unsigned long long)report->sourcePacketId,
  1096. (unsigned long long)report->flags,
  1097. report->sourcePacketHopCount,
  1098. report->errorCode,
  1099. (int)report->vendor,
  1100. report->protocolVersion,
  1101. report->majorVersion,
  1102. report->minorVersion,
  1103. report->revision,
  1104. (int)report->platform,
  1105. (int)report->architecture,
  1106. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1107. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str(),
  1108. ((double)report->receivedFromLinkQuality / (double)ZT_PATH_LINK_QUALITY_MAX));
  1109. self->_db.writeRaw(id,std::string(tmp));
  1110. }
  1111. void EmbeddedNetworkController::_request(
  1112. uint64_t nwid,
  1113. const InetAddress &fromAddr,
  1114. uint64_t requestPacketId,
  1115. const Identity &identity,
  1116. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  1117. {
  1118. char nwids[24];
  1119. JSONDB::NetworkSummaryInfo ns;
  1120. json network,member,origMember;
  1121. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  1122. return;
  1123. const uint64_t now = OSUtils::now();
  1124. if (requestPacketId) {
  1125. Mutex::Lock _l(_memberStatus_m);
  1126. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,identity.address().toInt())];
  1127. if ((now - ms.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  1128. return;
  1129. ms.lastRequestTime = now;
  1130. }
  1131. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  1132. if (!_db.getNetworkAndMember(nwid,identity.address().toInt(),network,member,ns)) {
  1133. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND);
  1134. return;
  1135. }
  1136. origMember = member;
  1137. const bool newMember = ((!member.is_object())||(member.size() == 0));
  1138. _initMember(member);
  1139. {
  1140. std::string haveIdStr(OSUtils::jsonString(member["identity"],""));
  1141. if (haveIdStr.length() > 0) {
  1142. // If we already know this member's identity perform a full compare. This prevents
  1143. // a "collision" from being able to auth onto our network in place of an already
  1144. // known member.
  1145. try {
  1146. if (Identity(haveIdStr.c_str()) != identity) {
  1147. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1148. return;
  1149. }
  1150. } catch ( ... ) {
  1151. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1152. return;
  1153. }
  1154. } else {
  1155. // If we do not yet know this member's identity, learn it.
  1156. member["identity"] = identity.toString(false);
  1157. }
  1158. }
  1159. // These are always the same, but make sure they are set
  1160. {
  1161. const std::string addrs(identity.address().toString());
  1162. member["id"] = addrs;
  1163. member["address"] = addrs;
  1164. member["nwid"] = nwids;
  1165. }
  1166. // Determine whether and how member is authorized
  1167. const char *authorizedBy = (const char *)0;
  1168. bool autoAuthorized = false;
  1169. json autoAuthCredentialType,autoAuthCredential;
  1170. if (OSUtils::jsonBool(member["authorized"],false)) {
  1171. authorizedBy = "memberIsAuthorized";
  1172. } else if (!OSUtils::jsonBool(network["private"],true)) {
  1173. authorizedBy = "networkIsPublic";
  1174. json &ahist = member["authHistory"];
  1175. if ((!ahist.is_array())||(ahist.size() == 0))
  1176. autoAuthorized = true;
  1177. } else {
  1178. char presentedAuth[512];
  1179. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  1180. presentedAuth[511] = (char)0; // sanity check
  1181. // Check for bearer token presented by member
  1182. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  1183. const char *const presentedToken = presentedAuth + 6;
  1184. json &authTokens = network["authTokens"];
  1185. if (authTokens.is_array()) {
  1186. for(unsigned long i=0;i<authTokens.size();++i) {
  1187. json &token = authTokens[i];
  1188. if (token.is_object()) {
  1189. const uint64_t expires = OSUtils::jsonInt(token["expires"],0ULL);
  1190. const uint64_t maxUses = OSUtils::jsonInt(token["maxUsesPerMember"],0ULL);
  1191. std::string tstr = OSUtils::jsonString(token["token"],"");
  1192. if (((expires == 0ULL)||(expires > now))&&(tstr == presentedToken)) {
  1193. bool usable = (maxUses == 0);
  1194. if (!usable) {
  1195. uint64_t useCount = 0;
  1196. json &ahist = member["authHistory"];
  1197. if (ahist.is_array()) {
  1198. for(unsigned long j=0;j<ahist.size();++j) {
  1199. json &ah = ahist[j];
  1200. if ((OSUtils::jsonString(ah["ct"],"") == "token")&&(OSUtils::jsonString(ah["c"],"") == tstr)&&(OSUtils::jsonBool(ah["a"],false)))
  1201. ++useCount;
  1202. }
  1203. }
  1204. usable = (useCount < maxUses);
  1205. }
  1206. if (usable) {
  1207. authorizedBy = "token";
  1208. autoAuthorized = true;
  1209. autoAuthCredentialType = "token";
  1210. autoAuthCredential = tstr;
  1211. }
  1212. }
  1213. }
  1214. }
  1215. }
  1216. }
  1217. }
  1218. }
  1219. // If we auto-authorized, update member record
  1220. if ((autoAuthorized)&&(authorizedBy)) {
  1221. member["authorized"] = true;
  1222. member["lastAuthorizedTime"] = now;
  1223. json ah;
  1224. ah["a"] = true;
  1225. ah["by"] = authorizedBy;
  1226. ah["ts"] = now;
  1227. ah["ct"] = autoAuthCredentialType;
  1228. ah["c"] = autoAuthCredential;
  1229. member["authHistory"].push_back(ah);
  1230. json &revj = member["revision"];
  1231. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  1232. }
  1233. if (authorizedBy) {
  1234. // Update version info and meta-data if authorized and if this is a genuine request
  1235. if (requestPacketId) {
  1236. const uint64_t vMajor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  1237. const uint64_t vMinor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  1238. const uint64_t vRev = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  1239. const uint64_t vProto = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  1240. member["vMajor"] = vMajor;
  1241. member["vMinor"] = vMinor;
  1242. member["vRev"] = vRev;
  1243. member["vProto"] = vProto;
  1244. {
  1245. Mutex::Lock _l(_memberStatus_m);
  1246. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,identity.address().toInt())];
  1247. ms.vMajor = (int)vMajor;
  1248. ms.vMinor = (int)vMinor;
  1249. ms.vRev = (int)vRev;
  1250. ms.vProto = (int)vProto;
  1251. ms.lastRequestMetaData = metaData;
  1252. ms.identity = identity;
  1253. if (fromAddr)
  1254. ms.physicalAddr = fromAddr;
  1255. if (ms.physicalAddr)
  1256. member["physicalAddr"] = ms.physicalAddr.toString();
  1257. }
  1258. }
  1259. } else {
  1260. // If they are not authorized, STOP!
  1261. _removeMemberNonPersistedFields(member);
  1262. if (origMember != member)
  1263. _db.saveNetworkMember(nwid,identity.address().toInt(),member);
  1264. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1265. return;
  1266. }
  1267. // -------------------------------------------------------------------------
  1268. // If we made it this far, they are authorized.
  1269. // -------------------------------------------------------------------------
  1270. uint64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1271. if (now > ns.mostRecentDeauthTime) {
  1272. // If we recently de-authorized a member, shrink credential TTL/max delta to
  1273. // be below the threshold required to exclude it. Cap this to a min/max to
  1274. // prevent jitter or absurdly large values.
  1275. const uint64_t deauthWindow = now - ns.mostRecentDeauthTime;
  1276. if (deauthWindow < ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA) {
  1277. credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
  1278. } else if (deauthWindow < (ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA + 5000ULL)) {
  1279. credentialtmd = deauthWindow - 5000ULL;
  1280. }
  1281. }
  1282. std::auto_ptr<NetworkConfig> nc(new NetworkConfig());
  1283. nc->networkId = nwid;
  1284. nc->type = OSUtils::jsonBool(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  1285. nc->timestamp = now;
  1286. nc->credentialTimeMaxDelta = credentialtmd;
  1287. nc->revision = OSUtils::jsonInt(network["revision"],0ULL);
  1288. nc->issuedTo = identity.address();
  1289. if (OSUtils::jsonBool(network["enableBroadcast"],true)) nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  1290. if (OSUtils::jsonBool(network["allowPassiveBridging"],false)) nc->flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
  1291. Utils::scopy(nc->name,sizeof(nc->name),OSUtils::jsonString(network["name"],"").c_str());
  1292. nc->multicastLimit = (unsigned int)OSUtils::jsonInt(network["multicastLimit"],32ULL);
  1293. for(std::vector<Address>::const_iterator ab(ns.activeBridges.begin());ab!=ns.activeBridges.end();++ab)
  1294. nc->addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  1295. json &v4AssignMode = network["v4AssignMode"];
  1296. json &v6AssignMode = network["v6AssignMode"];
  1297. json &ipAssignmentPools = network["ipAssignmentPools"];
  1298. json &routes = network["routes"];
  1299. json &rules = network["rules"];
  1300. json &capabilities = network["capabilities"];
  1301. json &tags = network["tags"];
  1302. json &memberCapabilities = member["capabilities"];
  1303. json &memberTags = member["tags"];
  1304. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
  1305. // Old versions with no rules engine support get an allow everything rule.
  1306. // Since rules are enforced bidirectionally, newer versions *will* still
  1307. // enforce rules on the inbound side.
  1308. nc->ruleCount = 1;
  1309. nc->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  1310. } else {
  1311. if (rules.is_array()) {
  1312. for(unsigned long i=0;i<rules.size();++i) {
  1313. if (nc->ruleCount >= ZT_MAX_NETWORK_RULES)
  1314. break;
  1315. if (_parseRule(rules[i],nc->rules[nc->ruleCount]))
  1316. ++nc->ruleCount;
  1317. }
  1318. }
  1319. std::map< uint64_t,json * > capsById;
  1320. if (!memberCapabilities.is_array())
  1321. memberCapabilities = json::array();
  1322. if (capabilities.is_array()) {
  1323. for(unsigned long i=0;i<capabilities.size();++i) {
  1324. json &cap = capabilities[i];
  1325. if (cap.is_object()) {
  1326. const uint64_t id = OSUtils::jsonInt(cap["id"],0ULL) & 0xffffffffULL;
  1327. capsById[id] = &cap;
  1328. if ((newMember)&&(OSUtils::jsonBool(cap["default"],false))) {
  1329. bool have = false;
  1330. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1331. if (id == (OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL)) {
  1332. have = true;
  1333. break;
  1334. }
  1335. }
  1336. if (!have)
  1337. memberCapabilities.push_back(id);
  1338. }
  1339. }
  1340. }
  1341. }
  1342. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1343. const uint64_t capId = OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL;
  1344. std::map< uint64_t,json * >::const_iterator ctmp = capsById.find(capId);
  1345. if (ctmp != capsById.end()) {
  1346. json *cap = ctmp->second;
  1347. if ((cap)&&(cap->is_object())&&(cap->size() > 0)) {
  1348. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  1349. unsigned int caprc = 0;
  1350. json &caprj = (*cap)["rules"];
  1351. if ((caprj.is_array())&&(caprj.size() > 0)) {
  1352. for(unsigned long j=0;j<caprj.size();++j) {
  1353. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  1354. break;
  1355. if (_parseRule(caprj[j],capr[caprc]))
  1356. ++caprc;
  1357. }
  1358. }
  1359. nc->capabilities[nc->capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  1360. if (nc->capabilities[nc->capabilityCount].sign(_signingId,identity.address()))
  1361. ++nc->capabilityCount;
  1362. if (nc->capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  1363. break;
  1364. }
  1365. }
  1366. }
  1367. std::map< uint32_t,uint32_t > memberTagsById;
  1368. if (memberTags.is_array()) {
  1369. for(unsigned long i=0;i<memberTags.size();++i) {
  1370. json &t = memberTags[i];
  1371. if ((t.is_array())&&(t.size() == 2))
  1372. memberTagsById[(uint32_t)(OSUtils::jsonInt(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(OSUtils::jsonInt(t[1],0ULL) & 0xffffffffULL);
  1373. }
  1374. }
  1375. if (tags.is_array()) { // check network tags array for defaults that are not present in member tags
  1376. for(unsigned long i=0;i<tags.size();++i) {
  1377. json &t = tags[i];
  1378. if (t.is_object()) {
  1379. const uint32_t id = (uint32_t)(OSUtils::jsonInt(t["id"],0) & 0xffffffffULL);
  1380. json &dfl = t["default"];
  1381. if ((dfl.is_number())&&(memberTagsById.find(id) == memberTagsById.end())) {
  1382. memberTagsById[id] = (uint32_t)(OSUtils::jsonInt(dfl,0) & 0xffffffffULL);
  1383. json mt = json::array();
  1384. mt.push_back(id);
  1385. mt.push_back(dfl);
  1386. memberTags.push_back(mt); // add default to member tags if not present
  1387. }
  1388. }
  1389. }
  1390. }
  1391. for(std::map< uint32_t,uint32_t >::const_iterator t(memberTagsById.begin());t!=memberTagsById.end();++t) {
  1392. if (nc->tagCount >= ZT_MAX_NETWORK_TAGS)
  1393. break;
  1394. nc->tags[nc->tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  1395. if (nc->tags[nc->tagCount].sign(_signingId))
  1396. ++nc->tagCount;
  1397. }
  1398. }
  1399. if (routes.is_array()) {
  1400. for(unsigned long i=0;i<routes.size();++i) {
  1401. if (nc->routeCount >= ZT_MAX_NETWORK_ROUTES)
  1402. break;
  1403. json &route = routes[i];
  1404. json &target = route["target"];
  1405. json &via = route["via"];
  1406. if (target.is_string()) {
  1407. const InetAddress t(target.get<std::string>());
  1408. InetAddress v;
  1409. if (via.is_string()) v.fromString(via.get<std::string>());
  1410. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  1411. ZT_VirtualNetworkRoute *r = &(nc->routes[nc->routeCount]);
  1412. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  1413. if (v.ss_family == t.ss_family)
  1414. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  1415. ++nc->routeCount;
  1416. }
  1417. }
  1418. }
  1419. }
  1420. const bool noAutoAssignIps = OSUtils::jsonBool(member["noAutoAssignIps"],false);
  1421. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  1422. if ((OSUtils::jsonBool(v6AssignMode["rfc4193"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1423. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  1424. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1425. }
  1426. if ((OSUtils::jsonBool(v6AssignMode["6plane"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1427. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  1428. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1429. }
  1430. }
  1431. bool haveManagedIpv4AutoAssignment = false;
  1432. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  1433. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  1434. if (ipAssignments.is_array()) {
  1435. for(unsigned long i=0;i<ipAssignments.size();++i) {
  1436. if (!ipAssignments[i].is_string())
  1437. continue;
  1438. std::string ips = ipAssignments[i];
  1439. InetAddress ip(ips);
  1440. // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
  1441. // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
  1442. // of user error / poor UX.
  1443. int routedNetmaskBits = 0;
  1444. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1445. if ( (!nc->routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->containsAddress(ip)) )
  1446. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits();
  1447. }
  1448. if (routedNetmaskBits > 0) {
  1449. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1450. ip.setPort(routedNetmaskBits);
  1451. nc->staticIps[nc->staticIpCount++] = ip;
  1452. }
  1453. if (ip.ss_family == AF_INET)
  1454. haveManagedIpv4AutoAssignment = true;
  1455. else if (ip.ss_family == AF_INET6)
  1456. haveManagedIpv6AutoAssignment = true;
  1457. }
  1458. }
  1459. } else {
  1460. ipAssignments = json::array();
  1461. }
  1462. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(OSUtils::jsonBool(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  1463. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  1464. json &pool = ipAssignmentPools[p];
  1465. if (pool.is_object()) {
  1466. InetAddress ipRangeStart(OSUtils::jsonString(pool["ipRangeStart"],""));
  1467. InetAddress ipRangeEnd(OSUtils::jsonString(pool["ipRangeEnd"],""));
  1468. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  1469. uint64_t s[2],e[2],x[2],xx[2];
  1470. memcpy(s,ipRangeStart.rawIpData(),16);
  1471. memcpy(e,ipRangeEnd.rawIpData(),16);
  1472. s[0] = Utils::ntoh(s[0]);
  1473. s[1] = Utils::ntoh(s[1]);
  1474. e[0] = Utils::ntoh(e[0]);
  1475. e[1] = Utils::ntoh(e[1]);
  1476. x[0] = s[0];
  1477. x[1] = s[1];
  1478. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  1479. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  1480. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  1481. xx[0] = Utils::hton(x[0]);
  1482. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  1483. } else {
  1484. // 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
  1485. Utils::getSecureRandom((void *)xx,16);
  1486. if ((e[0] > s[0]))
  1487. xx[0] %= (e[0] - s[0]);
  1488. else xx[0] = 0;
  1489. if ((e[1] > s[1]))
  1490. xx[1] %= (e[1] - s[1]);
  1491. else xx[1] = 0;
  1492. xx[0] = Utils::hton(x[0] + xx[0]);
  1493. xx[1] = Utils::hton(x[1] + xx[1]);
  1494. }
  1495. InetAddress ip6((const void *)xx,16,0);
  1496. // Check if this IP is within a local-to-Ethernet routed network
  1497. int routedNetmaskBits = 0;
  1498. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1499. 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)) )
  1500. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits();
  1501. }
  1502. // If it's routed, then try to claim and assign it and if successful end loop
  1503. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip6)) ) {
  1504. ipAssignments.push_back(ip6.toIpString());
  1505. member["ipAssignments"] = ipAssignments;
  1506. ip6.setPort((unsigned int)routedNetmaskBits);
  1507. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  1508. nc->staticIps[nc->staticIpCount++] = ip6;
  1509. haveManagedIpv6AutoAssignment = true;
  1510. break;
  1511. }
  1512. }
  1513. }
  1514. }
  1515. }
  1516. }
  1517. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(OSUtils::jsonBool(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  1518. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  1519. json &pool = ipAssignmentPools[p];
  1520. if (pool.is_object()) {
  1521. InetAddress ipRangeStartIA(OSUtils::jsonString(pool["ipRangeStart"],""));
  1522. InetAddress ipRangeEndIA(OSUtils::jsonString(pool["ipRangeEnd"],""));
  1523. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  1524. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  1525. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  1526. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  1527. continue;
  1528. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1529. // Start with the LSB of the member's address
  1530. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1531. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  1532. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1533. ++ipTrialCounter;
  1534. if ((ip & 0x000000ff) == 0x000000ff)
  1535. continue; // don't allow addresses that end in .255
  1536. // Check if this IP is within a local-to-Ethernet routed network
  1537. int routedNetmaskBits = -1;
  1538. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1539. if (nc->routes[rk].target.ss_family == AF_INET) {
  1540. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_addr.s_addr));
  1541. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_port));
  1542. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  1543. routedNetmaskBits = targetBits;
  1544. break;
  1545. }
  1546. }
  1547. }
  1548. // If it's routed, then try to claim and assign it and if successful end loop
  1549. const InetAddress ip4(Utils::hton(ip),0);
  1550. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip4)) ) {
  1551. ipAssignments.push_back(ip4.toIpString());
  1552. member["ipAssignments"] = ipAssignments;
  1553. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1554. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc->staticIps[nc->staticIpCount++]));
  1555. v4ip->sin_family = AF_INET;
  1556. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  1557. v4ip->sin_addr.s_addr = Utils::hton(ip);
  1558. }
  1559. haveManagedIpv4AutoAssignment = true;
  1560. break;
  1561. }
  1562. }
  1563. }
  1564. }
  1565. }
  1566. }
  1567. // Issue a certificate of ownership for all static IPs
  1568. if (nc->staticIpCount) {
  1569. nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1);
  1570. for(unsigned int i=0;i<nc->staticIpCount;++i)
  1571. nc->certificatesOfOwnership[0].addThing(nc->staticIps[i]);
  1572. nc->certificatesOfOwnership[0].sign(_signingId);
  1573. nc->certificateOfOwnershipCount = 1;
  1574. }
  1575. CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
  1576. if (com.sign(_signingId)) {
  1577. nc->com = com;
  1578. } else {
  1579. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR);
  1580. return;
  1581. }
  1582. _removeMemberNonPersistedFields(member);
  1583. if (member != origMember)
  1584. _db.saveNetworkMember(nwid,identity.address().toInt(),member);
  1585. _sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
  1586. }
  1587. } // namespace ZeroTier