index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. 'clientVersion': (message.data['clientVersion']) ? message.data['clientVersion'] : '?.?.?',
  265. 'clientOs': (message.data['clientOs']) ? message.data['clientOs'] : '?'
  266. },next);
  267. } else {
  268. // Add member record to network for newly seen peer
  269. authorized = ztDbTrue(network['private']) ? false : true; // public networks authorize everyone by default
  270. var now = Date.now().toString();
  271. member = {
  272. 'id': peerId.address(),
  273. 'nwid': nwid,
  274. 'authorized': authorized ? '1' : '0',
  275. 'identity': peerId.toString(),
  276. 'firstSeen': now,
  277. 'lastSeen': now,
  278. 'lastAt': fromIpAndPort,
  279. 'clientVersion': (message.data['clientVersion']) ? message.data['clientVersion'] : '?.?.?',
  280. 'clientOs': (message.data['clientOs']) ? message.data['clientOs'] : '?'
  281. };
  282. DB.hmset(memberKey,member,next);
  283. }
  284. });
  285. },function(next) {
  286. // Figure out which IP address auto-assignments we need to look up or make
  287. if (!authorized)
  288. return next(null);
  289. v4NeedAssign = (network['v4AssignMode'] === 'zt');
  290. v6NeedAssign = (network['v6AssignMode'] === 'zt');
  291. var ipacsv = member['ipAssignments'];
  292. if (ipacsv) {
  293. var ipa = ipacsv.split(',');
  294. for(var i=0;i<ipa.length;++i) {
  295. if (ipa[i]) {
  296. ipAssignments.push(ipa[i]);
  297. if ((ipa[i].indexOf('.') > 0)&&(v4NeedAssign))
  298. v4Assignments.push(ipa[i]);
  299. else if ((ipa[i].indexOf(':') > 0)&&(v6NeedAssign))
  300. v6Assignments.push(ipa[i]);
  301. }
  302. }
  303. }
  304. return next(null);
  305. },function(next) {
  306. // assign IPv4 if needed
  307. if ((!authorized)||(!v4NeedAssign)||(v4Assignments.length > 0))
  308. return next(null);
  309. var peerAddress = peerId.address();
  310. var network = 0;
  311. var netmask = 0;
  312. var netmaskBits = 0;
  313. var v4pool = network['v4AssignPool']; // technically csv but only one netblock currently supported
  314. if (v4pool) {
  315. var v4poolSplit = v4Pool.split('/');
  316. if (v4poolSplit.length === 2) {
  317. var networkSplit = v4poolSplit[0].split('.');
  318. if (networkSplit.length === 4) {
  319. network |= (parseInt(networkSplit[0],10) << 24) & 0xff000000;
  320. network |= (parseInt(networkSplit[1],10) << 16) & 0x00ff0000;
  321. network |= (parseInt(networkSplit[2],10) << 8) & 0x0000ff00;
  322. network |= parseInt(networkSplit[3],10) & 0x000000ff;
  323. netmaskBits = parseInt(v4poolSplit[1],10);
  324. if (netmaskBits > 32)
  325. netmaskBits = 32; // sanity check
  326. for(var i=0;i<netmaskBits;++i)
  327. netmask |= (0x80000000 >> i);
  328. netmask &= 0xffffffff;
  329. }
  330. }
  331. }
  332. if ((network === 0)||(netmask === 0xffffffff))
  333. return next(null);
  334. var invmask = netmask ^ 0xffffffff;
  335. var abcd = 0;
  336. var ipAssignmentAttempts = 0;
  337. async.whilst(
  338. function() { return ((v4Assignments.length === 0)&&(ipAssignmentAttempts < 1000)); },
  339. function(next2) {
  340. ++ipAssignmentAttempts;
  341. // Generate or increment IP address source bits
  342. if (abcd === 0) {
  343. var a = parseInt(peerAddress.substr(2,2),16) & 0xff;
  344. var b = parseInt(peerAddress.substr(4,2),16) & 0xff;
  345. var c = parseInt(peerAddress.substr(6,2),16) & 0xff;
  346. var d = parseInt(peerAddress.substr(8,2),16) & 0xff;
  347. abcd = (a << 24) | (b << 16) | (c << 8) | d;
  348. } else ++abcd;
  349. if ((abcd & 0xff) === 0)
  350. abcd |= 1;
  351. abcd &= 0xffffffff;
  352. // Derive an IP to test and generate assignment ip/bits string
  353. var ip = (abcd & invmask) | (network & netmask);
  354. var assignment = ((ip >> 24) & 0xff).toString(10) + '.' + ((ip >> 16) & 0xff).toString(10) + '.' + ((ip >> 8) & 0xff).toString(10) + '.' + (ip & 0xff).toString(10) + '/' + netmaskBits.toString(10);
  355. // Check :ipAssignments to see if this IP is already taken
  356. DB.hget(ipAssignmentsKey,assignment,function(err,value) {
  357. if (err)
  358. return next2(err);
  359. // IP is already taken, try again via async.whilst()
  360. if ((value)&&(value !== peerAddress))
  361. return next2(null); // if someone's already got this IP, keep looking
  362. v4Assignments.push(assignment);
  363. ipAssignments.push(assignment);
  364. // Save assignment to :ipAssignments hash
  365. DB.hset(ipAssignmentsKey,assignment,peerAddress,function(err) {
  366. if (err)
  367. return next2(err);
  368. // Save updated CSV list of assignments to member record
  369. var ipacsv = ipAssignments.join(',');
  370. member['ipAssignments'] = ipacsv;
  371. DB.hset(memberKey,'ipAssignments',ipacsv,next2);
  372. });
  373. });
  374. },
  375. next
  376. );
  377. },function(next) {
  378. // assign IPv6 if needed -- TODO
  379. if ((!authorized)||(!v6NeedAssign)||(v6Assignments.length > 0))
  380. return next(null);
  381. return next(null);
  382. }],function(err) {
  383. if (err) {
  384. console.error('error answering netconf-request for '+peerId.address()+': '+err);
  385. return;
  386. }
  387. var response = new Dictionary();
  388. response.data['peer'] = peerId.address();
  389. response.data['nwid'] = nwid;
  390. response.data['type'] = 'netconf-response';
  391. response.data['requestId'] = requestId;
  392. if (authorized) {
  393. var certificateOfMembership = null;
  394. var privateNetwork = ztDbTrue(network['private']);
  395. async.series([function(next) {
  396. // Generate certificate of membership if necessary
  397. if (privateNetwork) {
  398. generateCertificateOfMembership(nwid,peerId.address(),function(cert,exitCode) {
  399. if (cert) {
  400. certificateOfMembership = cert;
  401. return next(null);
  402. } else return next(new Error('zerotier-idtool returned '+exitCode));
  403. });
  404. } else return next(null);
  405. }],function(err) {
  406. // Send response to parent process
  407. if (err) {
  408. console.error('unable to generate certificate for peer '+peerId.address()+' on network '+nwid+': '+err);
  409. response.data['error'] = 'ACCESS_DENIED'; // unable to generate certificate
  410. } else {
  411. var netconf = new Dictionary();
  412. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES] = network['etherTypes'];
  413. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID] = nwid;
  414. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP] = Date.now().toString(16);
  415. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO] = peerId.address();
  416. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_PREFIX_BITS] = 0;
  417. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_DEPTH] = 0;
  418. //netconf.data[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES] = '';
  419. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_PRIVATE] = privateNetwork ? '1' : '0';
  420. if (network['name'])
  421. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_NAME] = network['name'];
  422. if (network['desc'])
  423. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_DESC] = network['desc'];
  424. if ((v4NeedAssign)&&(v4Assignments.length > 0))
  425. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC] = v4Assignments.join(',');
  426. if ((v6NeedAssign)&&(v6Assignments.length > 0))
  427. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC] = v6Assignments.join(',');
  428. if (certificateOfMembership !== null)
  429. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = certificateOfMembership;
  430. netconf.data[ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST] = ztDbTrue(network['enableBroadcast']) ? '1' : '0';
  431. response.data['netconf'] = netconf.toString();
  432. }
  433. process.stdout.write(response.toString()+'\n');
  434. });
  435. } else {
  436. // Peer not authorized to join network
  437. response.data['error'] = 'ACCESS_DENIED';
  438. process.stdout.write(response.toString()+'\n');
  439. }
  440. });
  441. }
  442. function handleMessage(dictStr)
  443. {
  444. var message = new Dictionary(dictStr);
  445. if (!('type' in message.data)) {
  446. console.error('ignored message without request type field');
  447. return;
  448. } else if (message.data['type'] === 'netconf-init') {
  449. doNetconfInit(message);
  450. } else if (message.data['type'] === 'netconf-request') {
  451. doNetconfRequest(message);
  452. } else {
  453. console.error('ignored unrecognized message type: '+message.data['type']);
  454. }
  455. };
  456. //
  457. // Read stream of double-CR-terminated dictionaries from stdin until close/EOF
  458. //
  459. var stdinReadBuffer = '';
  460. process.stdin.on('readable',function() {
  461. var chunk = process.stdin.read();
  462. if (chunk)
  463. stdinReadBuffer += chunk;
  464. for(;;) {
  465. var boundary = stdinReadBuffer.indexOf('\n\n');
  466. if (boundary >= 0) {
  467. handleMessage(stdinReadBuffer.substr(0,boundary + 1));
  468. stdinReadBuffer = stdinReadBuffer.substr(boundary + 2);
  469. } else break;
  470. }
  471. });
  472. process.stdin.on('end',function() {
  473. //process.exit(0);
  474. });
  475. process.stdin.on('close',function() {
  476. //process.exit(0);
  477. });
  478. process.stdin.on('error',function() {
  479. //process.exit(0);
  480. });
  481. // Tell ZeroTier One that the service is running, solicit netconf-init
  482. process.stdout.write('type=ready\n\n');