Added database merge feature.

Ylian Saint-Hilaire committed Feb 15, 2019 at 14:50 UTC 45a50db52c02f8ef57464e5ee95147ddc25f6f5e
4 files changed +68 -23
meshagent.js
+1 -1
@@ -425,7 +425,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
425 var adminUser = obj.parent.users['user/' + domain.id + '/' + obj.domain.orphanagentuser.toLowerCase()];
426 if ((adminUser != null) && (adminUser.siteadmin == 0xFFFFFFFF)) {
427 // Mesh name is hex instead of base64
428 - var meshname = Buffer.from(obj.meshid, 'base64').toString('hex').substring(0, 18);
428 + var meshname = obj.meshid.substring(0, 18);
429
430 // Create a new mesh for this device
431 var links = {};
meshcentral.js
+59 -2
@@ -96,7 +96,7 @@ function CreateMeshCentralServer(config, args) {
96 try { require('./pass').hash('test', function () { }); } catch (e) { console.log('Old version of node, must upgrade.'); return; } // TODO: Not sure if this test works or not.
97
98 // Check for invalid arguments
99 - var validArguments = ['_', 'notls', 'user', 'port', 'aliasport', 'mpsport', 'mpsaliasport', 'redirport', 'cert', 'mpscert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'shownodes', 'showmeshes', 'showevents', 'showpower', 'clearpower', 'showiplocations', 'help', 'exactports', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpsdebug', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbexportmin', 'dbimport', 'dbencryptkey', 'selfupdate', 'tlsoffload', 'userallowedip', 'userblockedip', 'swarmallowedip', 'agentallowedip', 'agentblockedip', 'fastcert', 'swarmport', 'swarmdebug', 'logintoken', 'logintokenkey', 'logintokengen', 'logintokengen', 'mailtokengen', 'admin', 'unadmin', 'sessionkey', 'sessiontime', 'minify', 'minifycore', 'dblistconfigfiles', 'dbshowconfigfile', 'dbpushconfigfiles', 'dbpullconfigfiles', 'dbdeleteconfigfiles', 'configkey', 'loadconfigfromdb'];
99 + var validArguments = ['_', 'notls', 'user', 'port', 'aliasport', 'mpsport', 'mpsaliasport', 'redirport', 'cert', 'mpscert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'shownodes', 'showmeshes', 'showevents', 'showpower', 'clearpower', 'showiplocations', 'help', 'exactports', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpsdebug', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbexportmin', 'dbimport', 'dbmerge', 'dbencryptkey', 'selfupdate', 'tlsoffload', 'userallowedip', 'userblockedip', 'swarmallowedip', 'agentallowedip', 'agentblockedip', 'fastcert', 'swarmport', 'swarmdebug', 'logintoken', 'logintokenkey', 'logintokengen', 'logintokengen', 'mailtokengen', 'admin', 'unadmin', 'sessionkey', 'sessiontime', 'minify', 'minifycore', 'dblistconfigfiles', 'dbshowconfigfile', 'dbpushconfigfiles', 'dbpullconfigfiles', 'dbdeleteconfigfiles', 'configkey', 'loadconfigfromdb'];
100 for (var arg in obj.args) { obj.args[arg.toLocaleLowerCase()] = obj.args[arg]; if (validArguments.indexOf(arg.toLocaleLowerCase()) == -1) { console.log('Invalid argument "' + arg + '", use --help.'); return; } }
101 if (obj.args.mongodb == true) { console.log('Must specify: --mongodb [connectionstring] \r\nSee https://docs.mongodb.com/manual/reference/connection-string/ for MongoDB connection string.'); return; }
102 for (i in obj.config.settings) { obj.args[i] = obj.config.settings[i]; } // Place all settings into arguments, arguments have already been placed into settings so arguments take precedence.
@@ -353,7 +353,7 @@ function CreateMeshCentralServer(config, args) {
353 // Import the entire database from a JSON file
354 if (obj.args.dbimport == true) { obj.args.dbimport = obj.getConfigFilePath('meshcentral.db.json'); }
355 var json = null, json2 = "", badCharCount = 0;
356 - try { json = obj.fs.readFileSync(obj.args.dbimport, { encoding: 'utf8' }); } catch (e) { console.log('Invalid JSON file: ' + obj.args.dbimport + '.'); process.exit(); }
356 + try { json = obj.fs.readFileSync(obj.args.dbimport, { encoding: 'utf8' }); } catch (e) { console.log('Invalid JSON file: ' + obj.args.dbimport + ': ' + e); process.exit(); }
357 for (i = 0; i < json.length; i++) { if (json.charCodeAt(i) >= 32) { json2 += json[i]; } else { var tt = json.charCodeAt(i); if (tt != 10 && tt != 13) { badCharCount++; } } } // Remove all bad chars
358 if (badCharCount > 0) { console.log(badCharCount + ' invalid character(s) where removed.'); }
359 try { json = JSON.parse(json2); } catch (e) { console.log('Invalid JSON format: ' + obj.args.dbimport + ': ' + e); process.exit(); }
@@ -363,6 +363,63 @@ function CreateMeshCentralServer(config, args) {
363 obj.db.RemoveAll(function () { obj.db.InsertMany(json, function (err) { if (err != null) { console.log(err); } else { console.log('Imported ' + json.length + ' objects(s) from ' + obj.args.dbimport + '.'); } process.exit(); }); });
364 return;
365 }
366 + if (obj.args.dbmerge) {
367 + // Import the entire database from a JSON file
368 + if (obj.args.dbmerge == true) { obj.args.dbmerge = obj.getConfigFilePath('meshcentral.db.json'); }
369 + var json = null, json2 = "", badCharCount = 0;
370 + try { json = obj.fs.readFileSync(obj.args.dbmerge, { encoding: 'utf8' }); } catch (e) { console.log('Invalid JSON file: ' + obj.args.dbmerge + ': ' + e); process.exit(); }
371 + for (i = 0; i < json.length; i++) { if (json.charCodeAt(i) >= 32) { json2 += json[i]; } else { var tt = json.charCodeAt(i); if (tt != 10 && tt != 13) { badCharCount++; } } } // Remove all bad chars
372 + if (badCharCount > 0) { console.log(badCharCount + ' invalid character(s) where removed.'); }
373 + try { json = JSON.parse(json2); } catch (e) { console.log('Invalid JSON format: ' + obj.args.dbmerge + ': ' + e); process.exit(); }
374 + if ((json == null) || (typeof json.length != 'number') || (json.length < 1)) { console.log('Invalid JSON format: ' + obj.args.dbimport + '.'); }
375 +
376 + // Get all users from current database
377 + obj.db.GetAllType('user', function (err, docs) {
378 + var users = {}, usersCount = 0;
379 + for (var i in docs) { users[docs[i]._id] = docs[i]; usersCount++; }
380 +
381 + // Fetch all meshes from the database
382 + obj.db.GetAllType('mesh', function (err, docs) {
383 + obj.common.unEscapeAllLinksFieldName(docs);
384 + var meshes = {}, meshesCount = 0;
385 + for (var i in docs) { meshes[docs[i]._id] = docs[i]; meshesCount++; }
386 + console.log('Loaded ' + usersCount + ' users and ' + meshesCount + ' meshes.');
387 + // Look at each object in the import file
388 + var objectToAdd = [];
389 + for (var i in json) {
390 + var newobj = json[i];
391 + if (newobj.type == 'user') {
392 + // Check if the user already exists
393 + var existingUser = users[newobj._id];
394 + if (existingUser) {
395 + // Merge the links
396 + for (var j in newobj.links) {
397 + if ((existingUser.links == null) || (existingUser.links[j] == null)) {
398 + if (existingUser.links == null) { existingUser.links = {}; }
399 + existingUser.links[j] = newobj.links[j];
400 + }
401 + }
402 + if (existingUser.name == 'admin') { existingUser.links = {}; }
403 + objectToAdd.push(existingUser); // Add this user
404 + } else {
405 + objectToAdd.push(newobj); // Add this user
406 + }
407 + } else if (newobj.type == 'mesh') {
408 + // Add this object after escaping
409 + objectToAdd.push(obj.common.escapeLinksFieldName(newobj));
410 + } // Don't add nodes.
411 + }
412 + console.log('Importing ' + objectToAdd.length + ' object(s)...');
413 + var pendingCalls = 1;
414 + for (var i in objectToAdd) {
415 + pendingCalls++;
416 + obj.db.Set(objectToAdd[i], function (err) { if (err != null) { console.log(err); } else { if (--pendingCalls == 0) { process.exit(); } } });
417 + }
418 + if (--pendingCalls == 0) { process.exit(); }
419 + });
420 + });
421 + return;
422 + }
423
424 // Load configuration for database if needed
425 if (obj.args.loadconfigfromdb) {
package.json
+2 -1
@@ -1,6 +1,6 @@
1 {
2 "name": "meshcentral",
3 - "version": "0.2.8-l",
3 + "version": "0.2.8-m",
4 "keywords": [
5 "Remote Management",
6 "Intel AMT",
@@ -38,6 +38,7 @@
38 "ipcheck": "^0.1.0",
39 "meshcentral": "*",
40 "minimist": "^1.2.0",
41 + "mongojs": "^2.6.0",
42 "multiparty": "^4.2.1",
43 "nedb": "^1.8.0",
44 "node-forge": "^0.7.6",
webserver.js
+6 -19
@@ -177,7 +177,6 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
177
178 function EscapeHtml(x) { if (typeof x == "string") return x.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;'); if (typeof x == "boolean") return x; if (typeof x == "number") return x; }
179 //function EscapeHtmlBreaks(x) { if (typeof x == "string") return x.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/\r/g, '<br />').replace(/\n/g, '').replace(/\t/g, '&nbsp;&nbsp;'); if (typeof x == "boolean") return x; if (typeof x == "number") return x; }
180 -
180 // Fetch all users from the database, keep this in memory
181 obj.db.GetAllType('user', function (err, docs) {
182 var domainUserCount = {}, i = 0;
@@ -2188,6 +2187,11 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2187 res.removeHeader("X-Powered-By");
2188 var domain = req.xdomain = getDomain(req);
2189
2190 + // If this domain has configured headers, use them.
2191 + // Example headers: { 'Strict-Transport-Security': 'max-age=360000;includeSubDomains' };
2192 + // { 'Referrer-Policy': 'no-referrer', 'x-frame-options': 'SAMEORIGIN', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src http: ws: data: 'self';script-src http: 'unsafe-inline';style-src http: 'unsafe-inline'" };
2193 + if ((domain != null) && (domain.httpheaders != null) && (typeof domain.httpheaders == object)) { res.set(domain.httpheaders); }
2194 +
2195 // Detect if this is a file sharing domain, if so, just share files.
2196 if ((domain != null) && (domain.share != null)) {
2197 var rpath;
@@ -2200,24 +2204,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2204 obj.fs.exists(obj.path.join(domain.share, rpath), function (exists) { if (exists == true) { res.sendfile(rpath, { root: domain.share }); } else { res.sendStatus(404); } });
2205 }
2206 } else {
2203 - // Two more headers to take a look at:
2204 - // 'Public-Key-Pins': 'pin-sha256="X3pGTSOuJeEVw989IJ/cEtXUEmy52zs1TZQrU06KUKg="; max-age=10'
2205 - // 'strict-transport-security': 'max-age=31536000; includeSubDomains'
2206 - var headers = null;
2207 - if (isTrustedCert() == false) {
2208 - // Default headers if no TLS is used
2209 - //headers = { 'Referrer-Policy': 'no-referrer', 'x-frame-options': 'SAMEORIGIN', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src http: ws: data: 'self';script-src http: 'unsafe-inline';style-src http: 'unsafe-inline'" };
2210 - } else {
2211 - // Default headers if TLS is used
2212 - //headers = { 'Referrer-Policy': 'no-referrer', 'x-frame-options': 'SAMEORIGIN', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src https: wss: data: 'self';script-src https: 'unsafe-inline';style-src https: 'unsafe-inline'" };
2213 -
2214 - if (typeof obj.args.httpsstrict == 'number') {
2215 - // Set Strict-Transport-Security if we are using a trusted certificate or TLS offload.
2216 - headers = { 'Strict-Transport-Security': 'max-age=' + obj.args.httpsstrict + ';includeSubDomains' };
2217 - }
2218 - }
2219 - if (parent.config.settings.accesscontrolalloworigin != null) { headers['Access-Control-Allow-Origin'] = parent.config.settings.accesscontrolalloworigin; }
2220 - res.set(headers);
2207 + //if (parent.config.settings.accesscontrolalloworigin != null) { headers['Access-Control-Allow-Origin'] = parent.config.settings.accesscontrolalloworigin; }
2208 return next();
2209 }
2210 });