SqliteNetworkConfigMaster.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <time.h>
  32. #include <sys/time.h>
  33. #include <sys/types.h>
  34. #include <algorithm>
  35. #include <utility>
  36. #include <stdexcept>
  37. #include "SqliteNetworkConfigMaster.hpp"
  38. #include "../node/Utils.hpp"
  39. #include "../node/CertificateOfMembership.hpp"
  40. #include "../node/NetworkConfig.hpp"
  41. namespace ZeroTier {
  42. SqliteNetworkConfigMaster::SqliteNetworkConfigMaster(const Identity &signingId,const char *dbPath) :
  43. _signingId(signingId),
  44. _dbPath(dbPath),
  45. _db((sqlite3 *)0)
  46. _lock()
  47. {
  48. if (!_signingId.hasPrivate())
  49. throw std::runtime_error("SqliteNetworkConfigMaster signing identity must have a private key");
  50. if (sqlite3_open_v2(dbPath,&_db,SQLITE_OPEN_READWRITE,(const char *)0) != SQLITE_OK)
  51. throw std::runtime_error("SqliteNetworkConfigMaster cannot open database file");
  52. sqlite3_busy_timeout(_db,10000);
  53. }
  54. SqliteNetworkConfigMaster::~SqliteNetworkConfigMaster()
  55. {
  56. Mutex::Lock _l(_lock);
  57. if (_db)
  58. sqlite3_close(_db);
  59. }
  60. NetworkConfigMaster::ResultCode SqliteNetworkConfigMaster::doNetworkConfigRequest(const InetAddress &fromAddr,uint64_t packetId,const Identity &member,uint64_t nwid,const Dictionary &metaData,uint64_t haveTimestamp,Dictionary &netconf)
  61. {
  62. #if 0
  63. char memberKey[128],nwids[24],addrs[16],nwKey[128],revKey[128];
  64. Dictionary memberRecord;
  65. std::string revision,tmps2;
  66. Mutex::Lock _l(_lock);
  67. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  68. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)member.address().toInt());
  69. Utils::snprintf(memberKey,sizeof(memberKey),"zt1:network:%s:member:%s:~",nwids,addrs);
  70. Utils::snprintf(nwKey,sizeof(nwKey),"zt1:network:%s:~",nwids);
  71. Utils::snprintf(revKey,sizeof(revKey),"zt1:network:%s:revision",nwids);
  72. //TRACE("netconf: %s : %s if > %llu",nwids,addrs,(unsigned long long)haveTimestamp);
  73. // Check to make sure network itself exists and is valid
  74. if (!_hget(nwKey,"id",tmps2)) {
  75. netconf["error"] = "Sqlite error retrieving network record ID field";
  76. return NetworkConfigMaster::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  77. }
  78. if (tmps2 != nwids)
  79. return NetworkConfigMaster::NETCONF_QUERY_OBJECT_NOT_FOUND;
  80. // Get network revision
  81. if (!_get(revKey,revision)) {
  82. netconf["error"] = "Sqlite error retrieving network revision";
  83. return NetworkConfigMaster::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  84. }
  85. if (!revision.length())
  86. revision = "0";
  87. // Get network member record for this peer
  88. if (!_hgetall(memberKey,memberRecord)) {
  89. netconf["error"] = "Sqlite error retrieving member record";
  90. return NetworkConfigMaster::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  91. }
  92. // If there is no member record, init a new one -- for public networks this
  93. // auto-authorizes, and for private nets it makes the peer show up in the UI
  94. // so the admin can authorize or delete/hide it.
  95. if ((memberRecord.size() == 0)||(memberRecord.get("id","") != addrs)||(memberRecord.get("nwid","") != nwids)) {
  96. if (!_initNewMember(nwid,member,metaData,memberRecord)) {
  97. netconf["error"] = "_initNewMember() failed";
  98. return NetworkConfigMaster::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  99. }
  100. }
  101. if (memberRecord.getBoolean("authorized")) {
  102. // Get current netconf and netconf timestamp
  103. uint64_t ts = memberRecord.getUInt("netconfTimestamp",0);
  104. std::string netconfStr(memberRecord.get("netconf",""));
  105. netconf.fromString(netconfStr);
  106. // Update statistics for this node
  107. Dictionary upd;
  108. upd.set("netconfClientTimestamp",haveTimestamp);
  109. if (fromAddr)
  110. upd.set("lastAt",fromAddr.toString());
  111. upd.set("lastSeen",Utils::now());
  112. _hmset(memberKey,upd);
  113. // Attempt to generate netconf for this node if there isn't
  114. // one or it's not in step with the network's revision.
  115. if (((ts == 0)||(netconfStr.length() == 0))||(memberRecord.get("netconfRevision","") != revision)) {
  116. std::string errorMessage;
  117. if (!_generateNetconf(nwid,member,metaData,netconf,ts,errorMessage)) {
  118. netconf["error"] = errorMessage;
  119. return NetworkConfigMaster::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  120. }
  121. }
  122. if (ts > haveTimestamp)
  123. return NetworkConfigMaster::NETCONF_QUERY_OK;
  124. else return NetworkConfigMaster::NETCONF_QUERY_OK_BUT_NOT_NEWER;
  125. } else {
  126. return NetworkConfigMaster::NETCONF_QUERY_ACCESS_DENIED;
  127. }
  128. #endif
  129. }
  130. bool SqliteNetworkConfigMaster::_initNewMember(uint64_t nwid,const Identity &member,const Dictionary &metaData,Dictionary &memberRecord)
  131. {
  132. #if 0
  133. char memberKey[128],nwids[24],addrs[16],nwKey[128],membersKey[128];
  134. Dictionary networkRecord;
  135. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  136. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)member.address().toInt());
  137. Utils::snprintf(memberKey,sizeof(memberKey),"zt1:network:%s:member:%s:~",nwids,addrs);
  138. Utils::snprintf(nwKey,sizeof(nwKey),"zt1:network:%s:~",nwids);
  139. Utils::snprintf(membersKey,sizeof(membersKey),"zt1:network:%s:members",nwids);
  140. if (!_hgetall(nwKey,networkRecord)) {
  141. //LOG("netconf: Sqlite error retrieving %s",nwKey);
  142. return false;
  143. }
  144. if (networkRecord.get("id","") != nwids) {
  145. //TRACE("netconf: network %s not found (initNewMember)",nwids);
  146. return false;
  147. }
  148. memberRecord.clear();
  149. memberRecord["id"] = addrs;
  150. memberRecord["nwid"] = nwids;
  151. memberRecord["authorized"] = ((networkRecord.get("private","1") == "0") ? "1" : "0"); // auto-authorize on public networks
  152. memberRecord.set("firstSeen",Utils::now());
  153. memberRecord["identity"] = member.toString(false);
  154. if (!_hmset(memberKey,memberRecord))
  155. return false;
  156. if (!_sadd(membersKey,addrs))
  157. return false;
  158. return true;
  159. #endif
  160. }
  161. bool SqliteNetworkConfigMaster::_generateNetconf(uint64_t nwid,const Identity &member,const Dictionary &metaData,Dictionary &netconf,uint64_t &ts,std::string &errorMessage)
  162. {
  163. #if 0
  164. char memberKey[256],nwids[24],addrs[16],tss[24],nwKey[256],revKey[128],abKey[128],ipaKey[128];
  165. Dictionary networkRecord,memberRecord;
  166. std::string revision;
  167. Utils::snprintf(memberKey,sizeof(memberKey),"zt1:network:%s:member:%s:~",nwids,addrs);
  168. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  169. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)member.address().toInt());
  170. Utils::snprintf(nwKey,sizeof(nwKey),"zt1:network:%s:~",nwids);
  171. Utils::snprintf(revKey,sizeof(revKey),"zt1:network:%s:revision",nwids);
  172. Utils::snprintf(abKey,sizeof(revKey),"zt1:network:%s:activeBridges",nwids);
  173. Utils::snprintf(ipaKey,sizeof(revKey),"zt1:network:%s:ipAssignments",nwids);
  174. if (!_hgetall(nwKey,networkRecord)) {
  175. errorMessage = "Sqlite error retrieving network record";
  176. return false;
  177. }
  178. if (networkRecord.get("id","") != nwids) {
  179. errorMessage = "network IDs do not match in database";
  180. return false;
  181. }
  182. if (!_hgetall(memberKey,memberRecord)) {
  183. errorMessage = "Sqlite error retrieving member record";
  184. return false;
  185. }
  186. if (!_get(revKey,revision)) {
  187. errorMessage = "Sqlite error retrieving network revision";
  188. return false;
  189. }
  190. if (!revision.length())
  191. revision = "0";
  192. bool isPrivate = networkRecord.getBoolean("private",true);
  193. ts = Utils::now();
  194. Utils::snprintf(tss,sizeof(tss),"%llx",ts);
  195. // Core configuration
  196. netconf[ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP] = tss;
  197. netconf[ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID] = nwids;
  198. netconf[ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO] = addrs;
  199. netconf[ZT_NETWORKCONFIG_DICT_KEY_PRIVATE] = isPrivate ? "1" : "0";
  200. netconf[ZT_NETWORKCONFIG_DICT_KEY_NAME] = networkRecord.get("name",nwids);
  201. netconf[ZT_NETWORKCONFIG_DICT_KEY_DESC] = networkRecord.get("desc","");
  202. netconf[ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST] = networkRecord.getBoolean("enableBroadcast",true) ? "1" : "0";
  203. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING] = networkRecord.getBoolean("allowPassiveBridging",false) ? "1" : "0";
  204. netconf[ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES] = networkRecord.get("etherTypes",""); // these are stored as hex comma-delimited list
  205. // Multicast options
  206. netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES] = networkRecord.get("multicastRates","");
  207. uint64_t ml = networkRecord.getHexUInt("multicastLimit",0);
  208. if (ml > 0)
  209. netconf.setHex(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT,ml);
  210. // Active bridge configuration
  211. {
  212. std::string activeBridgeList;
  213. std::vector<std::string> activeBridgeSet;
  214. if (!_smembers(abKey,activeBridgeSet)) {
  215. errorMessage = "Sqlite error retrieving active bridge set";
  216. return false;
  217. }
  218. std::sort(activeBridgeSet.begin(),activeBridgeSet.end());
  219. for(std::vector<std::string>::const_iterator i(activeBridgeSet.begin());i!=activeBridgeSet.end();++i) {
  220. if (i->length() == 10) {
  221. if (activeBridgeList.length() > 0)
  222. activeBridgeList.push_back(',');
  223. activeBridgeList.append(*i);
  224. }
  225. }
  226. if (activeBridgeList.length() > 0)
  227. netconf[ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES] = activeBridgeList;
  228. }
  229. // IP address assignment and auto-assign using the ZeroTier-internal mechanism (not DHCP, etc.)
  230. {
  231. std::string ipAssignments(memberRecord.get("ipAssignments",""));
  232. // Get sorted, separated lists of IPv4 and IPv6 IP address assignments already present
  233. std::vector<InetAddress> ip4s,ip6s;
  234. {
  235. std::vector<std::string> ips(Utils::split(ipAssignments.c_str(),",","",""));
  236. for(std::vector<std::string>::iterator i(ips.begin());i!=ips.end();++i) {
  237. InetAddress a(*i);
  238. if (a.isV4())
  239. ip4s.push_back(a);
  240. else if (a.isV6())
  241. ip6s.push_back(a);
  242. }
  243. }
  244. std::sort(ip4s.begin(),ip4s.end());
  245. std::unique(ip4s.begin(),ip4s.end());
  246. std::sort(ip6s.begin(),ip6s.end());
  247. std::unique(ip6s.begin(),ip6s.end());
  248. // If IPv4 assignment mode is 'zt', send them to the client
  249. if (networkRecord.get("v4AssignMode","") == "zt") {
  250. // If we have no IPv4 addresses and we have an assignment pool, auto-assign
  251. if (ip4s.empty()) {
  252. InetAddress v4AssignPool(networkRecord.get("v4AssignPool",""));
  253. uint32_t pnet = Utils::ntoh(*((const uint32_t *)v4AssignPool.rawIpData()));
  254. unsigned int pbits = v4AssignPool.netmaskBits();
  255. if ((v4AssignPool.isV4())&&(pbits > 0)&&(pbits < 32)&&(pnet != 0)) {
  256. uint32_t pmask = 0xffffffff << (32 - pbits); // netmask over network part
  257. uint32_t invmask = ~pmask; // netmask over "random" part
  258. // Begin exploring the IP space by generating an IP from the ZeroTier address
  259. uint32_t first = (((uint32_t)(member.address().toInt() & 0xffffffffULL)) & invmask) | (pnet & pmask);
  260. if ((first & 0xff) == 0)
  261. first |= 1;
  262. else if ((first & 0xff) == 0xff)
  263. first &= 0xfe;
  264. // Start by trying this first IP
  265. uint32_t abcd = first;
  266. InetAddress ip;
  267. bool gotone = false;
  268. unsigned long sanityCounter = 0;
  269. do {
  270. // Convert to IPv4 InetAddress
  271. uint32_t abcdNetworkByteOrder = Utils::hton(abcd);
  272. ip.set(&abcdNetworkByteOrder,4,pbits);
  273. // Is 'ip' already assigned to another node?
  274. std::string assignment;
  275. if (!_hget(ipaKey,ip.toString().c_str(),assignment)) {
  276. errorMessage = "Sqlite error while checking IP allocation";
  277. return false;
  278. }
  279. if ((assignment.length() != 10)||(assignment == member.address().toString())) {
  280. gotone = true;
  281. break; // not taken!
  282. }
  283. // If we made it here, the IP was taken so increment and mask and try again
  284. ++abcd;
  285. abcd &= invmask;
  286. abcd |= (pnet & pmask);
  287. if ((abcd & 0xff) == 0)
  288. abcd |= 1;
  289. else if ((abcd & 0xff) == 0xff)
  290. abcd &= 0xfe;
  291. // Don't spend insane amounts of time here -- if we have to try this hard, the user
  292. // needs to allocate a larger IP block.
  293. if (++sanityCounter >= 65535)
  294. break;
  295. } while (abcd != first); // keep going until we loop back around to 'first'
  296. // If we got one, add to IP list and claim in database
  297. if (gotone) {
  298. ip4s.push_back(ip);
  299. _hset(ipaKey,ip.toString().c_str(),member.address().toString().c_str());
  300. if (ipAssignments.length() > 0)
  301. ipAssignments.push_back(',');
  302. ipAssignments.append(ip.toString());
  303. _hset(memberKey,"ipAssignments",ipAssignments.c_str());
  304. } else {
  305. char tmp[1024];
  306. Utils::snprintf(tmp,sizeof(tmp),"failed to allocate IP in %s for %s in network %s, need a larger pool!",v4AssignPool.toString().c_str(),addrs,nwids);
  307. errorMessage = tmp;
  308. return false;
  309. }
  310. }
  311. }
  312. // Create comma-delimited list to send to client
  313. std::string v4s;
  314. for(std::vector<InetAddress>::iterator i(ip4s.begin());i!=ip4s.end();++i) {
  315. if (v4s.length() > 0)
  316. v4s.push_back(',');
  317. v4s.append(i->toString());
  318. }
  319. if (v4s.length())
  320. netconf[ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC] = v4s;
  321. }
  322. if (networkRecord.get("v6AssignMode","") == "zt") {
  323. // TODO: IPv6 auto-assign ... not quite baked yet. :)
  324. std::string v6s;
  325. for(std::vector<InetAddress>::iterator i(ip6s.begin());i!=ip6s.end();++i) {
  326. if (v6s.length() > 0)
  327. v6s.push_back(',');
  328. v6s.append(i->toString());
  329. }
  330. if (v6s.length())
  331. netconf[ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC] = v6s;
  332. }
  333. }
  334. // If this is a private network, generate a signed certificate of membership
  335. if (isPrivate) {
  336. CertificateOfMembership com(Utils::strToU64(revision.c_str()),1,nwid,member.address());
  337. if (com.sign(_signingId)) // basically can't fail unless our identity is invalid
  338. netconf[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = com.toString();
  339. else {
  340. errorMessage = "unable to sign COM";
  341. return false;
  342. }
  343. }
  344. // Sign netconf dictionary itself
  345. if (!netconf.sign(_signingId)) {
  346. errorMessage = "unable to sign netconf dictionary";
  347. return false;
  348. }
  349. // Record new netconf in database for re-use on subsequent repeat queries
  350. {
  351. Dictionary upd;
  352. upd["netconf"] = netconf.toString();
  353. upd.set("netconfTimestamp",ts);
  354. upd["netconfRevision"] = revision;
  355. if (!_hmset(memberKey,upd)) {
  356. errorMessage = "Sqlite error updating network record with new netconf dictionary";
  357. return false;
  358. }
  359. }
  360. return true;
  361. #endif
  362. }
  363. } // namespace ZeroTier