2
0

DB.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "DB.hpp"
  14. #include "EmbeddedNetworkController.hpp"
  15. #include <chrono>
  16. #include <algorithm>
  17. #include <stdexcept>
  18. using json = nlohmann::json;
  19. namespace ZeroTier {
  20. void DB::initNetwork(nlohmann::json &network)
  21. {
  22. if (!network.count("private")) network["private"] = true;
  23. if (!network.count("creationTime")) network["creationTime"] = OSUtils::now();
  24. if (!network.count("name")) network["name"] = "";
  25. if (!network.count("multicastLimit")) network["multicastLimit"] = (uint64_t)32;
  26. if (!network.count("enableBroadcast")) network["enableBroadcast"] = true;
  27. if (!network.count("v4AssignMode")) network["v4AssignMode"] = {{"zt",false}};
  28. if (!network.count("v6AssignMode")) network["v6AssignMode"] = {{"rfc4193",false},{"zt",false},{"6plane",false}};
  29. if (!network.count("authTokens")) network["authTokens"] = {{}};
  30. if (!network.count("capabilities")) network["capabilities"] = nlohmann::json::array();
  31. if (!network.count("tags")) network["tags"] = nlohmann::json::array();
  32. if (!network.count("routes")) network["routes"] = nlohmann::json::array();
  33. if (!network.count("ipAssignmentPools")) network["ipAssignmentPools"] = nlohmann::json::array();
  34. if (!network.count("mtu")) network["mtu"] = ZT_DEFAULT_MTU;
  35. if (!network.count("remoteTraceTarget")) network["remoteTraceTarget"] = nlohmann::json();
  36. if (!network.count("removeTraceLevel")) network["remoteTraceLevel"] = 0;
  37. if (!network.count("rulesSource")) network["rulesSource"] = "";
  38. if (!network.count("rules")) {
  39. // If unspecified, rules are set to allow anything and behave like a flat L2 segment
  40. network["rules"] = {{
  41. { "not",false },
  42. { "or", false },
  43. { "type","ACTION_ACCEPT" }
  44. }};
  45. }
  46. if (!network.count("dns")) network["dns"] = nlohmann::json::array();
  47. if (!network.count("ssoEnabled")) network["ssoEnabled"] = false;
  48. if (!network.count("clientId")) network["clientId"] = "";
  49. if (!network.count("authorizationEndpoint")) network["authorizationEndpoint"] = "";
  50. network["objtype"] = "network";
  51. }
  52. void DB::initMember(nlohmann::json &member)
  53. {
  54. if (!member.count("authorized")) member["authorized"] = false;
  55. if (!member.count("ssoExempt")) member["ssoExempt"] = false;
  56. if (!member.count("ipAssignments")) member["ipAssignments"] = nlohmann::json::array();
  57. if (!member.count("activeBridge")) member["activeBridge"] = false;
  58. if (!member.count("tags")) member["tags"] = nlohmann::json::array();
  59. if (!member.count("capabilities")) member["capabilities"] = nlohmann::json::array();
  60. if (!member.count("creationTime")) member["creationTime"] = OSUtils::now();
  61. if (!member.count("noAutoAssignIps")) member["noAutoAssignIps"] = false;
  62. if (!member.count("revision")) member["revision"] = 0ULL;
  63. if (!member.count("lastDeauthorizedTime")) member["lastDeauthorizedTime"] = 0ULL;
  64. if (!member.count("lastAuthorizedTime")) member["lastAuthorizedTime"] = 0ULL;
  65. if (!member.count("lastAuthorizedCredentialType")) member["lastAuthorizedCredentialType"] = nlohmann::json();
  66. if (!member.count("lastAuthorizedCredential")) member["lastAuthorizedCredential"] = nlohmann::json();
  67. if (!member.count("authenticationExpiryTime")) member["authenticationExpiryTime"] = 0LL;
  68. if (!member.count("vMajor")) member["vMajor"] = -1;
  69. if (!member.count("vMinor")) member["vMinor"] = -1;
  70. if (!member.count("vRev")) member["vRev"] = -1;
  71. if (!member.count("vProto")) member["vProto"] = -1;
  72. if (!member.count("remoteTraceTarget")) member["remoteTraceTarget"] = nlohmann::json();
  73. if (!member.count("removeTraceLevel")) member["remoteTraceLevel"] = 0;
  74. member["objtype"] = "member";
  75. }
  76. void DB::cleanNetwork(nlohmann::json &network)
  77. {
  78. network.erase("clock");
  79. network.erase("authorizedMemberCount");
  80. network.erase("activeMemberCount");
  81. network.erase("totalMemberCount");
  82. network.erase("lastModified");
  83. }
  84. void DB::cleanMember(nlohmann::json &member)
  85. {
  86. member.erase("clock");
  87. member.erase("physicalAddr");
  88. member.erase("recentLog");
  89. member.erase("lastModified");
  90. member.erase("lastRequestMetaData");
  91. member.erase("authenticationURL"); // computed
  92. member.erase("authenticationClientID"); // computed
  93. }
  94. DB::DB() {}
  95. DB::~DB() {}
  96. bool DB::get(const uint64_t networkId,nlohmann::json &network)
  97. {
  98. waitForReady();
  99. std::shared_ptr<_Network> nw;
  100. {
  101. std::lock_guard<std::mutex> l(_networks_l);
  102. auto nwi = _networks.find(networkId);
  103. if (nwi == _networks.end())
  104. return false;
  105. nw = nwi->second;
  106. }
  107. {
  108. std::lock_guard<std::mutex> l2(nw->lock);
  109. network = nw->config;
  110. }
  111. return true;
  112. }
  113. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
  114. {
  115. waitForReady();
  116. std::shared_ptr<_Network> nw;
  117. {
  118. std::lock_guard<std::mutex> l(_networks_l);
  119. auto nwi = _networks.find(networkId);
  120. if (nwi == _networks.end())
  121. return false;
  122. nw = nwi->second;
  123. }
  124. {
  125. std::lock_guard<std::mutex> l2(nw->lock);
  126. network = nw->config;
  127. auto m = nw->members.find(memberId);
  128. if (m == nw->members.end())
  129. return false;
  130. member = m->second;
  131. }
  132. return true;
  133. }
  134. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info)
  135. {
  136. waitForReady();
  137. std::shared_ptr<_Network> nw;
  138. {
  139. std::lock_guard<std::mutex> l(_networks_l);
  140. auto nwi = _networks.find(networkId);
  141. if (nwi == _networks.end())
  142. return false;
  143. nw = nwi->second;
  144. }
  145. {
  146. std::lock_guard<std::mutex> l2(nw->lock);
  147. network = nw->config;
  148. _fillSummaryInfo(nw,info);
  149. auto m = nw->members.find(memberId);
  150. if (m == nw->members.end())
  151. return false;
  152. member = m->second;
  153. }
  154. return true;
  155. }
  156. bool DB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
  157. {
  158. waitForReady();
  159. std::shared_ptr<_Network> nw;
  160. {
  161. std::lock_guard<std::mutex> l(_networks_l);
  162. auto nwi = _networks.find(networkId);
  163. if (nwi == _networks.end())
  164. return false;
  165. nw = nwi->second;
  166. }
  167. {
  168. std::lock_guard<std::mutex> l2(nw->lock);
  169. network = nw->config;
  170. for(auto m=nw->members.begin();m!=nw->members.end();++m) {
  171. members.push_back(m->second);
  172. }
  173. }
  174. return true;
  175. }
  176. void DB::networks(std::set<uint64_t> &networks)
  177. {
  178. waitForReady();
  179. std::lock_guard<std::mutex> l(_networks_l);
  180. for(auto n=_networks.begin();n!=_networks.end();++n)
  181. networks.insert(n->first);
  182. }
  183. void DB::networkMemberSSOHasExpired(uint64_t nwid, int64_t now) {
  184. std::lock_guard<std::mutex> l(_networks_l);
  185. auto nw = _networks.find(nwid);
  186. if (nw != _networks.end()) {
  187. nw->second->mostRecentDeauthTime = now;
  188. }
  189. }
  190. void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool notifyListeners)
  191. {
  192. uint64_t memberId = 0;
  193. uint64_t networkId = 0;
  194. bool isAuth = false;
  195. bool wasAuth = false;
  196. std::shared_ptr<_Network> nw;
  197. if (old.is_object()) {
  198. memberId = OSUtils::jsonIntHex(old["id"],0ULL);
  199. networkId = OSUtils::jsonIntHex(old["nwid"],0ULL);
  200. if ((memberId)&&(networkId)) {
  201. {
  202. std::lock_guard<std::mutex> l(_networks_l);
  203. auto nw2 = _networks.find(networkId);
  204. if (nw2 != _networks.end())
  205. nw = nw2->second;
  206. }
  207. if (nw) {
  208. std::lock_guard<std::mutex> l(nw->lock);
  209. if (OSUtils::jsonBool(old["activeBridge"],false))
  210. nw->activeBridgeMembers.erase(memberId);
  211. wasAuth = OSUtils::jsonBool(old["authorized"],false);
  212. if (wasAuth)
  213. nw->authorizedMembers.erase(memberId);
  214. json &ips = old["ipAssignments"];
  215. if (ips.is_array()) {
  216. for(unsigned long i=0;i<ips.size();++i) {
  217. json &ipj = ips[i];
  218. if (ipj.is_string()) {
  219. const std::string ips = ipj;
  220. InetAddress ipa(ips.c_str());
  221. ipa.setPort(0);
  222. nw->allocatedIps.erase(ipa);
  223. }
  224. }
  225. }
  226. }
  227. }
  228. }
  229. if (memberConfig.is_object()) {
  230. if (!nw) {
  231. memberId = OSUtils::jsonIntHex(memberConfig["id"],0ULL);
  232. networkId = OSUtils::jsonIntHex(memberConfig["nwid"],0ULL);
  233. if ((!memberId)||(!networkId))
  234. return;
  235. std::lock_guard<std::mutex> l(_networks_l);
  236. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  237. if (!nw2)
  238. nw2.reset(new _Network);
  239. nw = nw2;
  240. }
  241. {
  242. std::lock_guard<std::mutex> l(nw->lock);
  243. nw->members[memberId] = memberConfig;
  244. if (OSUtils::jsonBool(memberConfig["activeBridge"],false))
  245. nw->activeBridgeMembers.insert(memberId);
  246. isAuth = OSUtils::jsonBool(memberConfig["authorized"],false);
  247. if (isAuth)
  248. nw->authorizedMembers.insert(memberId);
  249. json &ips = memberConfig["ipAssignments"];
  250. if (ips.is_array()) {
  251. for(unsigned long i=0;i<ips.size();++i) {
  252. json &ipj = ips[i];
  253. if (ipj.is_string()) {
  254. const std::string ips = ipj;
  255. InetAddress ipa(ips.c_str());
  256. ipa.setPort(0);
  257. nw->allocatedIps.insert(ipa);
  258. }
  259. }
  260. }
  261. if (!isAuth) {
  262. const int64_t ldt = (int64_t)OSUtils::jsonInt(memberConfig["lastDeauthorizedTime"],0ULL);
  263. if (ldt > nw->mostRecentDeauthTime)
  264. nw->mostRecentDeauthTime = ldt;
  265. }
  266. }
  267. if (notifyListeners) {
  268. std::lock_guard<std::mutex> ll(_changeListeners_l);
  269. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  270. (*i)->onNetworkMemberUpdate(this,networkId,memberId,memberConfig);
  271. }
  272. }
  273. } else if (memberId) {
  274. if (nw) {
  275. std::lock_guard<std::mutex> l(nw->lock);
  276. nw->members.erase(memberId);
  277. }
  278. if (networkId) {
  279. std::lock_guard<std::mutex> l(_networks_l);
  280. auto er = _networkByMember.equal_range(memberId);
  281. for(auto i=er.first;i!=er.second;++i) {
  282. if (i->second == networkId) {
  283. _networkByMember.erase(i);
  284. break;
  285. }
  286. }
  287. }
  288. }
  289. if ((notifyListeners)&&((wasAuth)&&(!isAuth)&&(networkId)&&(memberId))) {
  290. std::lock_guard<std::mutex> ll(_changeListeners_l);
  291. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  292. (*i)->onNetworkMemberDeauthorize(this,networkId,memberId);
  293. }
  294. }
  295. }
  296. void DB::_networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool notifyListeners)
  297. {
  298. if (networkConfig.is_object()) {
  299. const std::string ids = networkConfig["id"];
  300. const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
  301. if (networkId) {
  302. std::shared_ptr<_Network> nw;
  303. {
  304. std::lock_guard<std::mutex> l(_networks_l);
  305. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  306. if (!nw2)
  307. nw2.reset(new _Network);
  308. nw = nw2;
  309. }
  310. {
  311. std::lock_guard<std::mutex> l2(nw->lock);
  312. nw->config = networkConfig;
  313. }
  314. if (notifyListeners) {
  315. std::lock_guard<std::mutex> ll(_changeListeners_l);
  316. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  317. (*i)->onNetworkUpdate(this,networkId,networkConfig);
  318. }
  319. }
  320. }
  321. } else if (old.is_object()) {
  322. const std::string ids = old["id"];
  323. const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
  324. if (networkId) {
  325. std::lock_guard<std::mutex> l(_networks_l);
  326. _networks.erase(networkId);
  327. }
  328. }
  329. }
  330. void DB::_fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info)
  331. {
  332. for(auto ab=nw->activeBridgeMembers.begin();ab!=nw->activeBridgeMembers.end();++ab)
  333. info.activeBridges.push_back(Address(*ab));
  334. std::sort(info.activeBridges.begin(),info.activeBridges.end());
  335. for(auto ip=nw->allocatedIps.begin();ip!=nw->allocatedIps.end();++ip)
  336. info.allocatedIps.push_back(*ip);
  337. std::sort(info.allocatedIps.begin(),info.allocatedIps.end());
  338. info.authorizedMemberCount = (unsigned long)nw->authorizedMembers.size();
  339. info.totalMemberCount = (unsigned long)nw->members.size();
  340. info.mostRecentDeauthTime = nw->mostRecentDeauthTime;
  341. }
  342. } // namespace ZeroTier