index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. //
  2. // ZeroTier One - Global Peer to Peer Ethernet
  3. // Copyright (C) 2011-2014 ZeroTier Networks LLC
  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. var config = require('./config.js');
  28. // Fields in netconf response dictionary
  29. var ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES = "et";
  30. var ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID = "nwid";
  31. var ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP = "ts";
  32. var ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO = "id";
  33. var ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_PREFIX_BITS = "mpb";
  34. var ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_DEPTH = "md";
  35. var ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES = "mr";
  36. var ZT_NETWORKCONFIG_DICT_KEY_PRIVATE = "p";
  37. var ZT_NETWORKCONFIG_DICT_KEY_NAME = "n";
  38. var ZT_NETWORKCONFIG_DICT_KEY_DESC = "d";
  39. var ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC = "v4s";
  40. var ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC = "v6s";
  41. var ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP = "com";
  42. var ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST = "eb";
  43. // Path to zerotier-idtool binary, invoked to enerate certificates of membership
  44. var ZEROTIER_IDTOOL = '/usr/local/bin/zerotier-idtool';
  45. // From Constants.hpp in node/
  46. var ZT_NETWORK_AUTOCONF_DELAY = 60000;
  47. var ZT_NETWORK_CERTIFICATE_TTL_WINDOW = (ZT_NETWORK_AUTOCONF_DELAY * 4);
  48. // Connect to redis, assuming database 0 and no auth (for now)
  49. var async = require('async');
  50. var redis = require('redis');
  51. var DB = redis.createClient();
  52. DB.on("error",function(err) { console.error('redis query error: '+err); });
  53. DB.select(config.redisDb,function() {});
  54. // Global variables -- these are initialized on startup or netconf-init message
  55. var netconfSigningIdentity = null; // identity of netconf master, with private key portion
  56. // spawn() function to launch sub-processes
  57. var spawn = require('child_process').spawn;
  58. // Returns true for fields that are "true" according to ZT redis schema
  59. function ztDbTrue(v) { return ((v === '1')||(v === 'true')||(v > 0)); }
  60. //
  61. // ZeroTier One Dictionary -- encoding-compatible with Dictionary in C++ code base
  62. //
  63. function Dictionary(fromStr)
  64. {
  65. var self = this;
  66. this.data = {};
  67. this._esc = function(data) {
  68. var es = '';
  69. for(var i=0;i<data.length;++i) {
  70. var c = data.charAt(i);
  71. switch(c) {
  72. case '\0': es += '\\0'; break;
  73. case '\r': es += '\\r'; break;
  74. case '\n': es += '\\n'; break;
  75. case '\\': es += '\\\\'; break;
  76. case '=': es += '\\='; break;
  77. default: es += c; break;
  78. }
  79. }
  80. return es;
  81. };
  82. this._unesc = function(s) {
  83. if (typeof s !== 'string')
  84. return '';
  85. var uns = '';
  86. var escapeState = false;
  87. for(var i=0;i<s.length;++i) {
  88. var c = s.charAt(i);
  89. if (escapeState) {
  90. escapeState = false;
  91. switch(c) {
  92. case '0': uns += '\0'; break;
  93. case 'r': uns += '\r'; break;
  94. case 'n': uns += '\n'; break;
  95. default: uns += c; break;
  96. }
  97. } else{
  98. if ((c !== '\r')&&(c !== '\n')&&(c !== '\0')) {
  99. if (c === '\\')
  100. escapeState = true;
  101. else uns += c;
  102. }
  103. }
  104. }
  105. return uns;
  106. };
  107. this.toString = function() {
  108. var str = '';
  109. for(var key in self.data) {
  110. str += self._esc(key);
  111. str += '=';
  112. var value = self.data[key];
  113. if (value)
  114. str += self._esc(value.toString());
  115. str += '\n';
  116. }
  117. return str;
  118. };
  119. this.fromString = function(str) {
  120. self.data = {};
  121. if (typeof str !== 'string')
  122. return self;
  123. var lines = str.split('\n');
  124. for(var l=0;l<lines.length;++l) {
  125. var escapeState = false;
  126. var eqAt = 0;
  127. for(;eqAt<lines[l].length;++eqAt) {
  128. var c = lines[l].charAt(eqAt);
  129. if (escapeState)
  130. escapeState = false;
  131. else if (c === '\\')
  132. escapeState = true;
  133. else if (c === '=')
  134. break;
  135. }
  136. var k = self._unesc(lines[l].substr(0,eqAt));
  137. ++eqAt;
  138. if ((k)&&(k.length > 0))
  139. self.data[k] = self._unesc((eqAt < lines[l].length) ? lines[l].substr(eqAt) : '');
  140. }
  141. return self;
  142. };
  143. if ((typeof fromStr === 'string')&&(fromStr.length > 0))
  144. self.fromString(fromStr);
  145. };
  146. //
  147. // Identity implementation using zerotier-idtool as subprocess to do actual crypto work
  148. //
  149. function Identity(idstr)
  150. {
  151. var self = this;
  152. this.str = '';
  153. this.fields = [];
  154. this.toString = function() {
  155. return self.str;
  156. };
  157. this.address = function() {
  158. return ((self.fields.length > 0) ? self.fields[0] : '0000000000');
  159. };
  160. this.fromString = function(str) {
  161. self.str = '';
  162. self.fields = [];
  163. if (typeof str !== 'string')
  164. return;
  165. for(var i=0;i<str.length;++i) {
  166. if ("0123456789abcdef:".indexOf(str.charAt(i)) < 0)
  167. return; // invalid character in identity
  168. }
  169. var fields = str.split(':');
  170. if ((fields.length < 3)||(fields[0].length !== 10)||(fields[1] !== '0'))
  171. return;
  172. self.str = str;
  173. self.fields = fields;
  174. };
  175. this.isValid = function() {
  176. return (! ((self.fields.length < 3)||(self.fields[0].length !== 10)||(self.fields[1] !== '0')) );
  177. };
  178. this.hasPrivate = function() {
  179. return ((self.isValid())&&(self.fields.length >= 4));
  180. };
  181. if (typeof idstr === 'string')
  182. self.fromString(idstr);
  183. };
  184. //
  185. // Invokes zerotier-idtool to generate certificates for private networks
  186. //
  187. function generateCertificateOfMembership(nwid,peerAddress,callback)
  188. {
  189. // The first fields of these COM tuples come from
  190. // CertificateOfMembership.hpp's enum of required
  191. // certificate default fields.
  192. var comTimestamp = '0,' + Date.now().toString(16) + ',' + ZT_NETWORK_CERTIFICATE_TTL_WINDOW.toString(16);
  193. var comNwid = '1,' + nwid + ',0';
  194. var comIssuedTo = '2,' + peerAddress + ',ffffffffffffffff';
  195. var cert = '';
  196. var certErr = '';
  197. var idtool = spawn(ZEROTIER_IDTOOL,[ 'mkcom',netconfSigningIdentity,comTimestamp,comNwid,comIssuedTo ]);
  198. idtool.stdout.on('data',function(data) {
  199. cert += data;
  200. });
  201. idtool.stderr.on('data',function(data) {
  202. certErr += data;
  203. });
  204. idtool.on('close',function(exitCode) {
  205. if (certErr.length > 0)
  206. console.error('zerotier-idtool stderr returned: '+certErr);
  207. return callback((cert.length > 0) ? cert : null,exitCode);
  208. });
  209. }
  210. //
  211. // Message handler for messages over ZeroTier One service bus
  212. //
  213. function doNetconfInit(message)
  214. {
  215. netconfSigningIdentity = new Identity(message.data['netconfId']);
  216. if (!netconfSigningIdentity.hasPrivate()) {
  217. netconfSigningIdentity = null;
  218. console.error('got invalid netconf signing identity in netconf-init');
  219. } // else console.error('got netconf-init, running! id: '+netconfSigningIdentity.address());
  220. }
  221. function doNetconfRequest(message)
  222. {
  223. if ((netconfSigningIdentity === null)||(!netconfSigningIdentity.hasPrivate())) {
  224. console.error('got netconf-request before netconf-init, ignored');
  225. return;
  226. }
  227. var peerId = new Identity(message.data['peerId']);
  228. var nwid = message.data['nwid'];
  229. var requestId = message.data['requestId'];
  230. if ((!peerId)||(!peerId.isValid())||(!nwid)||(nwid.length !== 16)||(!requestId)) {
  231. console.error('missing one or more required fields in netconf-request');
  232. return;
  233. }
  234. var networkKey = 'zt1:network:'+nwid+':~';
  235. var memberKey = 'zt1:network:'+nwid+':member:'+peerId.address()+':~';
  236. var ipAssignmentsKey = 'zt1:network:'+nwid+':ipAssignments';
  237. var network = null;
  238. var member = null;
  239. var authorized = false;
  240. var v4NeedAssign = false;
  241. var v6NeedAssign = false;
  242. var v4Assignments = [];
  243. var v6Assignments = [];
  244. var ipAssignments = []; // both v4 and v6
  245. async.series([function(next) {
  246. // network lookup
  247. DB.hgetall(networkKey,function(err,obj) {
  248. network = obj;
  249. return next(null);
  250. });
  251. },function(next) {
  252. // member lookup
  253. if ((!network)||(!('id' in network))||(network['id'] !== nwid))
  254. return next(null);
  255. DB.hgetall(memberKey,function(err,obj) {
  256. if (err)
  257. return next(err);
  258. if (obj) {
  259. // Update existing member record with new last seen time, etc.
  260. member = obj;
  261. authorized = ((!ztDbTrue(network['private'])) || ztDbTrue(member['authorized']));
  262. var updatedFields = {
  263. 'lastSeen': Date.now(),
  264. 'authorized': authorized ? '1' : '0' // reset authorized to unhide in UI, since UI uses -1 to hide
  265. };
  266. if (message.data['from'])
  267. updatedFields['lastAt'] = message.data['from'];
  268. if (message.data['clientVersion'])
  269. updatedFields['clientVersion'] = message.data['clientVersion'];
  270. if (message.data['clientOs'])
  271. updatedFields['clientOs'] = message.data['clientOs'];
  272. DB.hmset(memberKey,updatedFields,next);
  273. } else {
  274. // Add member record to network for newly seen peer
  275. authorized = ztDbTrue(network['private']) ? false : true; // public networks authorize everyone by default
  276. var now = Date.now().toString();
  277. member = {
  278. 'id': peerId.address(),
  279. 'nwid': nwid,
  280. 'authorized': authorized ? '1' : '0',
  281. 'identity': peerId.toString(),
  282. 'firstSeen': now,
  283. 'lastSeen': now
  284. };
  285. if (message.data['from'])
  286. member['lastAt'] = message.data['from'];
  287. if (message.data['clientVersion'])
  288. member['clientVersion'] = message.data['clientVersion'];
  289. if (message.data['clientOs'])
  290. member['clientOs'] = message.data['clientOs'];
  291. DB.hmset(memberKey,member,next);
  292. }
  293. });
  294. },function(next) {
  295. // Figure out which IP address auto-assignments we need to look up or make
  296. if (!authorized)
  297. return next(null);
  298. v4NeedAssign = (network['v4AssignMode'] === 'zt');
  299. v6NeedAssign = (network['v6AssignMode'] === 'zt');
  300. var ipacsv = member['ipAssignments'];
  301. if (ipacsv) {
  302. var ipa = ipacsv.split(',');
  303. for(var i=0;i<ipa.length;++i) {
  304. if (ipa[i]) {
  305. ipAssignments.push(ipa[i]);
  306. if ((ipa[i].indexOf('.') > 0)&&(v4NeedAssign))
  307. v4Assignments.push(ipa[i]);
  308. else if ((ipa[i].indexOf(':') > 0)&&(v6NeedAssign))
  309. v6Assignments.push(ipa[i]);
  310. }
  311. }
  312. }
  313. return next(null);
  314. },function(next) {
  315. // assign IPv4 if needed
  316. if ((!authorized)||(!v4NeedAssign)||(v4Assignments.length > 0))
  317. return next(null);
  318. var peerAddress = peerId.address();
  319. var ipnetwork = 0;
  320. var netmask = 0;
  321. var netmaskBits = 0;
  322. var v4pool = network['v4AssignPool']; // technically csv but only one netblock currently supported
  323. if (v4pool) {
  324. var v4poolSplit = v4pool.split('/');
  325. if (v4poolSplit.length === 2) {
  326. var networkSplit = v4poolSplit[0].split('.');
  327. if (networkSplit.length === 4) {
  328. ipnetwork |= (parseInt(networkSplit[0],10) << 24) & 0xff000000;
  329. ipnetwork |= (parseInt(networkSplit[1],10) << 16) & 0x00ff0000;
  330. ipnetwork |= (parseInt(networkSplit[2],10) << 8) & 0x0000ff00;
  331. ipnetwork |= parseInt(networkSplit[3],10) & 0x000000ff;
  332. netmaskBits = parseInt(v4poolSplit[1],10);
  333. if (netmaskBits > 32)
  334. netmaskBits = 32; // sanity check
  335. for(var i=0;i<netmaskBits;++i)
  336. netmask |= (0x80000000 >> i);
  337. netmask &= 0xffffffff;
  338. }
  339. }
  340. }
  341. if ((ipnetwork === 0)||(netmask === 0xffffffff))
  342. return next(null);
  343. var invmask = netmask ^ 0xffffffff;
  344. var abcd = 0;
  345. var ipAssignmentAttempts = 0;
  346. async.whilst(
  347. function() { return ((v4Assignments.length === 0)&&(ipAssignmentAttempts < 1000)); },
  348. function(next2) {
  349. ++ipAssignmentAttempts;
  350. // Generate or increment IP address source bits
  351. if (abcd === 0) {
  352. var a = parseInt(peerAddress.substr(2,2),16) & 0xff;
  353. var b = parseInt(peerAddress.substr(4,2),16) & 0xff;
  354. var c = parseInt(peerAddress.substr(6,2),16) & 0xff;
  355. var d = parseInt(peerAddress.substr(8,2),16) & 0xff;
  356. abcd = (a << 24) | (b << 16) | (c << 8) | d;
  357. } else ++abcd;
  358. if ((abcd & 0xff) === 0)
  359. abcd |= 1;
  360. abcd &= 0xffffffff;
  361. // Derive an IP to test and generate assignment ip/bits string
  362. var ip = (abcd & invmask) | (ipnetwork & netmask);
  363. var assignment = ((ip >> 24) & 0xff).toString(10) + '.' + ((ip >> 16) & 0xff).toString(10) + '.' + ((ip >> 8) & 0xff).toString(10) + '.' + (ip & 0xff).toString(10) + '/' + netmaskBits.toString(10);
  364. // Check :ipAssignments to see if this IP is already taken
  365. DB.hget(ipAssignmentsKey,assignment,function(err,value) {
  366. if (err)
  367. return next2(err);
  368. // IP is already taken, try again via async.whilst()
  369. if ((value)&&(value !== peerAddress))
  370. return next2(null); // if someone's already got this IP, keep looking
  371. v4Assignments.push(assignment);
  372. ipAssignments.push(assignment);
  373. // Save assignment to :ipAssignments hash
  374. DB.hset(ipAssignmentsKey,assignment,peerAddress,function(err) {
  375. if (err)
  376. return next2(err);
  377. // Save updated CSV list of assignments to member record
  378. var ipacsv = ipAssignments.join(',');
  379. member['ipAssignments'] = ipacsv;
  380. DB.hset(memberKey,'ipAssignments',ipacsv,next2);
  381. });
  382. });
  383. },
  384. next
  385. );
  386. },function(next) {
  387. // assign IPv6 if needed -- TODO
  388. if ((!authorized)||(!v6NeedAssign)||(v6Assignments.length > 0))
  389. return next(null);
  390. return next(null);
  391. }],function(err) {
  392. if (err) {
  393. console.error('error answering netconf-request for '+peerId.address()+': '+err);
  394. return;
  395. }
  396. var response = new Dictionary();
  397. response.data['peer'] = peerId.address();
  398. response.data['nwid'] = nwid;
  399. response.data['type'] = 'netconf-response';
  400. response.data['requestId'] = requestId;
  401. if (authorized) {
  402. var certificateOfMembership = null;
  403. var privateNetwork = ztDbTrue(network['private']);
  404. async.series([function(next) {
  405. // Generate certificate of membership if necessary
  406. if (privateNetwork) {
  407. generateCertificateOfMembership(nwid,peerId.address(),function(cert,exitCode) {
  408. if (cert) {
  409. certificateOfMembership = cert;
  410. return next(null);
  411. } else return next(new Error('zerotier-idtool returned '+exitCode));
  412. });
  413. } else return next(null);
  414. }],function(err) {
  415. // Send response to parent process
  416. if (err) {
  417. console.error('unable to generate certificate for peer '+peerId.address()+' on network '+nwid+': '+err);
  418. response.data['error'] = 'ACCESS_DENIED'; // unable to generate certificate
  419. } else {
  420. var netconf = new Dictionary();
  421. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES] = network['etherTypes'];
  422. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID] = nwid;
  423. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP] = Date.now().toString(16);
  424. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO] = peerId.address();
  425. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_PREFIX_BITS] = 0;
  426. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_DEPTH] = 0;
  427. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES] = '';
  428. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_PRIVATE] = privateNetwork ? '1' : '0';
  429. if (network['name'])
  430. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_NAME] = network['name'];
  431. if (network['desc'])
  432. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_DESC] = network['desc'];
  433. if ((v4NeedAssign)&&(v4Assignments.length > 0))
  434. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC] = v4Assignments.join(',');
  435. if ((v6NeedAssign)&&(v6Assignments.length > 0))
  436. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC] = v6Assignments.join(',');
  437. if (certificateOfMembership !== null)
  438. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = certificateOfMembership;
  439. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST] = ztDbTrue(network['enableBroadcast']) ? '1' : '0';
  440. response.data['netconf'] = netconf.toString();
  441. }
  442. process.stdout.write(response.toString()+'\n');
  443. });
  444. } else {
  445. // Peer not authorized to join network
  446. response.data['error'] = 'ACCESS_DENIED';
  447. process.stdout.write(response.toString()+'\n');
  448. }
  449. });
  450. }
  451. function handleMessage(dictStr)
  452. {
  453. var message = new Dictionary(dictStr);
  454. if (!('type' in message.data)) {
  455. console.error('ignored message without request type field');
  456. return;
  457. } else if (message.data['type'] === 'netconf-init') {
  458. doNetconfInit(message);
  459. } else if (message.data['type'] === 'netconf-request') {
  460. doNetconfRequest(message);
  461. } else {
  462. console.error('ignored unrecognized message type: '+message.data['type']);
  463. }
  464. };
  465. //
  466. // Read stream of double-CR-terminated dictionaries from stdin until close/EOF
  467. //
  468. var stdinReadBuffer = '';
  469. process.stdin.on('readable',function() {
  470. var chunk = process.stdin.read();
  471. if (chunk)
  472. stdinReadBuffer += chunk;
  473. for(;;) {
  474. var boundary = stdinReadBuffer.indexOf('\n\n');
  475. if (boundary >= 0) {
  476. handleMessage(stdinReadBuffer.substr(0,boundary + 1));
  477. stdinReadBuffer = stdinReadBuffer.substr(boundary + 2);
  478. } else break;
  479. }
  480. });
  481. process.stdin.on('end',function() {
  482. //process.exit(0);
  483. });
  484. process.stdin.on('close',function() {
  485. //process.exit(0);
  486. });
  487. process.stdin.on('error',function() {
  488. //process.exit(0);
  489. });
  490. // Tell ZeroTier One that the service is running, solicit netconf-init
  491. process.stdout.write('type=ready\n\n');