SqliteNetworkConfigMaster.cpp 15 KB

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