2
0

SqliteNetworkConfigMaster.cpp 17 KB

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