index.js 17 KB

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