From cebb0ce63ee454c44f8b5774babedf938db6fe41 Mon Sep 17 00:00:00 2001 From: Ylian Saint-Hilaire Date: Mon, 4 Feb 2019 18:06:01 -0800 Subject: [PATCH] Added server console, KVM jumbo accumulator. --- agents/modules_meshcmd/service-host.js | 16 +-- agents/modules_meshcmd/service-manager.js | 57 ++++----- agents/modules_meshcmd/smbios.js | 19 ++- .../modules_meshcmd_min/service-host.min.js | 2 +- .../service-manager.min.js | 2 +- agents/modules_meshcmd_min/smbios.min.js | 2 +- agents/modules_meshcore/service-manager.js | 61 +++++---- agents/modules_meshcore/smbios.js | 19 ++- .../service-manager.min.js | 2 +- agents/modules_meshcore_min/smbios.min.js | 2 +- meshcentral.js | 2 +- meshuser.js | 75 ++++++++++- public/scripts/agent-desktop-0.0.2.js | 22 +++- public/scripts/agent-redir-ws-0.1.0.js | 2 +- views/default-min.handlebars | 2 +- views/default-mobile-min.handlebars | 2 +- views/default.handlebars | 118 +++++++++++++----- 17 files changed, 275 insertions(+), 130 deletions(-) diff --git a/agents/modules_meshcmd/service-host.js b/agents/modules_meshcmd/service-host.js index 46e9a883..fabc4e81 100644 --- a/agents/modules_meshcmd/service-host.js +++ b/agents/modules_meshcmd/service-host.js @@ -1,5 +1,5 @@ /* -Copyright 2018-2019 Intel Corporation +Copyright 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -187,14 +187,9 @@ function serviceHost(serviceName) console.log(e); process.exit(); } - if (process.platform == 'win32' || process.platform == 'darwin') - { - // Only do this on Windows/MacOS, becuase Linux is async... It'll complete later - console.log(this._ServiceOptions.name + ' installed'); - process.exit(); - } - i = process.argv.length; - serviceOperation = 1; + + console.log(this._ServiceOptions.name + ' installed'); + process.exit(); break; case '-uninstall': if (!this._svcManager) { this._svcManager = new serviceManager(); } @@ -301,9 +296,6 @@ function serviceHost(serviceName) } process.exit(); break; - default: - // Unknown arguments, skip it. - break; } } diff --git a/agents/modules_meshcmd/service-manager.js b/agents/modules_meshcmd/service-manager.js index cd028e63..168fc96e 100644 --- a/agents/modules_meshcmd/service-manager.js +++ b/agents/modules_meshcmd/service-manager.js @@ -1,5 +1,5 @@ /* -Copyright 2018-2019 Intel Corporation +Copyright 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -46,9 +46,6 @@ function parseServiceStatus(token) case 0x00000001: j.state = 'STOPPED'; break; - default: - // Unknown service state - break; } var controlsAccepted = token.Deref((2 * 4), 4).toBuffer().readUInt32LE(); j.controlsAccepted = []; @@ -295,13 +292,14 @@ function serviceManager() require('fs').chmodSync('/etc/init.d/' + options.name, m); this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM }); this._update._moduleName = options.name; - this._update.on('exit', function onUpdateRC_d() { console.log(this._moduleName + ' installed'); process.exit(); }); this._update.stdout.on('data', function (chunk) { }); this._update.stdin.write('update-rc.d ' + options.name + ' defaults\n'); this._update.stdin.write('exit\n'); //update-rc.d meshagent defaults # creates symlinks for rc.d //service meshagent start + this._update.waitExit(); + break; case 'systemd': var serviceDescription = options.description ? options.description : 'MeshCentral Agent'; @@ -313,11 +311,10 @@ function serviceManager() require('fs').writeFileSync('/lib/systemd/system/' + options.name + '.service', '[Unit]\nDescription=' + serviceDescription + '\n[Service]\nExecStart=/usr/local/mesh/' + options.name + '\nStandardOutput=null\nRestart=always\nRestartSec=3\n[Install]\nWantedBy=multi-user.target\nAlias=' + options.name + '.service\n', { flags: 'w' }); this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM }); this._update._moduleName = options.name; - this._update.on('exit', function onUpdateRC_d() { console.log(this._moduleName + ' installed'); process.exit(); }); this._update.stdout.on('data', function (chunk) { }); this._update.stdin.write('systemctl enable ' + options.name + '.service\n'); this._update.stdin.write('exit\n'); - + this._update.waitExit(); break; default: // unknown platform service type break; @@ -416,41 +413,39 @@ function serviceManager() { case 'init': this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM }); - this._update._svcname = name; - this._update.on('exit', function onUninstallExit() { - try { - require('fs').unlinkSync('/etc/init.d/' + this._svcname); - console.log(this._svcname + ' uninstalled'); - - } - catch (e) { - console.log(this._svcname + ' could not be uninstalled') - } - process.exit(); - }); this._update.stdout.on('data', function (chunk) { }); this._update.stdin.write('service ' + name + ' stop\n'); this._update.stdin.write('update-rc.d -f ' + name + ' remove\n'); this._update.stdin.write('exit\n'); + this._update.waitExit(); + try + { + require('fs').unlinkSync('/etc/init.d/' + name); + console.log(name + ' uninstalled'); + + } + catch (e) + { + console.log(name + ' could not be uninstalled', e) + } break; case 'systemd': this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM }); - this._update._svcname = name; - this._update.on('exit', function onUninstallExit() { - try { - require('fs').unlinkSync('/usr/local/mesh/' + this._svcname); - require('fs').unlinkSync('/lib/systemd/system/' + this._svcname + '.service'); - console.log(this._svcname + ' uninstalled'); - } - catch (e) { - console.log(this._svcname + ' could not be uninstalled') - } - process.exit(); - }); this._update.stdout.on('data', function (chunk) { }); this._update.stdin.write('systemctl stop ' + name + '.service\n'); this._update.stdin.write('systemctl disable ' + name + '.service\n'); this._update.stdin.write('exit\n'); + this._update.waitExit(); + try + { + require('fs').unlinkSync('/usr/local/mesh/' + name); + require('fs').unlinkSync('/lib/systemd/system/' + name + '.service'); + console.log(name + ' uninstalled'); + } + catch (e) + { + console.log(name + ' could not be uninstalled', e) + } break; default: // unknown platform service type break; diff --git a/agents/modules_meshcmd/smbios.js b/agents/modules_meshcmd/smbios.js index 28e653bc..91944371 100644 --- a/agents/modules_meshcmd/smbios.js +++ b/agents/modules_meshcmd/smbios.js @@ -1,5 +1,5 @@ /* -Copyright 2018-2019 Intel Corporation +Copyright 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -77,7 +77,8 @@ function SMBiosTables() var SMData; var structcount = 0; - while (SMData && i < SMData.length) { + while (SMData && i < SMData.length) + { var SMtype = SMData[i]; var SMlength = SMData[i + 1]; @@ -88,12 +89,20 @@ function SMBiosTables() ret[SMtype].peek()._strings = []; - while (SMData[i] != 0) { + while (SMData[i] != 0 && i <= SMData.length) + { var strstart = i; // Start of String, find end of string - while (SMData[i++] != 0); - ret[SMtype].peek()._strings.push(SMData.slice(strstart, i).toString().trim()); + while (SMData[i++] != 0 && i <= SMData.length); + try + { + ret[SMtype].peek()._strings.push(SMData.slice(strstart, i).toString().trim()); + } + catch (ee) + { + console.log('oops'); + } } i += (ret[SMtype].peek()._strings.length == 0) ? 2 : 1; ++structcount; diff --git a/agents/modules_meshcmd_min/service-host.min.js b/agents/modules_meshcmd_min/service-host.min.js index 36de3b57..b3a0287a 100644 --- a/agents/modules_meshcmd_min/service-host.min.js +++ b/agents/modules_meshcmd_min/service-host.min.js @@ -1 +1 @@ -var SERVICE_WIN32=16|32;var SERVICE_STATE={STOPPED:1,SERVICE_START_PENDING:2,SERVICE_STOP_PENDING:3,RUNNING:4};var SERVICE_ACCEPT={SERVICE_ACCEPT_STOP:1,SERVICE_ACCEPT_SHUTDOWN:4,SERVICE_ACCEPT_POWEREVENT:64,SERVICE_ACCEPT_SESSIONCHANGE:128};var SERVICE_CONTROL={SERVICE_CONTROL_SHUTDOWN:5,SERVICE_CONTROL_STOP:1,SERVICE_CONTROL_POWEREVENT:13,SERVICE_CONTROL_SESSIONCHANGE:14};var SESSION_CHANGE_TYPE={WTS_CONSOLE_CONNECT:1,WTS_CONSOLE_DISCONNECT:2,WTS_REMOTE_CONNECT:3,WTS_REMOTE_DISCONNECT:4,WTS_SESSION_LOGON:5,WTS_SESSION_LOGOFF:6,WTS_SESSION_LOCK:7,WTS_SESSION_UNLOCK:8,WTS_SESSION_REMOTE_CONTROL:9,WTS_SESSION_CREATE:10,WTS_SESSION_TERMINATE:11};var NO_ERROR=0;var serviceManager=require("service-manager");function serviceHost(e){this._ObjectID="service-host";var a=require("events").inherits(this);a.createEvent("serviceStart");a.createEvent("serviceStop");a.createEvent("normalStart");a.createEvent("session");a.createEvent("powerStateChange");if(process.platform=="win32"){this.GM=require("_GenericMarshal");this.Advapi=this.GM.CreateNativeProxy("Advapi32.dll");this.Advapi.CreateMethod({method:"StartServiceCtrlDispatcherA",threadDispatch:1});this.Advapi.CreateMethod("RegisterServiceCtrlHandlerExA");this.Advapi.CreateMethod("SetServiceStatus");this.Kernel32=this.GM.CreateNativeProxy("Kernel32.dll");this.Kernel32.CreateMethod("GetLastError");this.Ole32=this.GM.CreateNativeProxy("Ole32.dll");this.Ole32.CreateMethod("CoInitializeEx");this.Ole32.CreateMethod("CoUninitialize");this._ServiceName=this.GM.CreateVariable(typeof(e)=="string"?e:e.name);this._ServiceMain=this.GM.GetGenericGlobalCallback(2);this._ServiceMain.Parent=this;this._ServiceMain.GM=this.GM;this._ServiceMain.on("GlobalCallback",function b(f,g){this.Parent._ServiceStatus=this.GM.CreateVariable(28);this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_WIN32);this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_STATE.SERVICE_STOPPED,4);this.Parent._ServiceStatusHandle=this.Parent.Advapi.RegisterServiceCtrlHandlerExA(this.Parent._ServiceName,this.Parent._ServiceControlHandler,this.Parent.GM.StashObject(this.Parent._ServiceControlHandler));if(this.Parent._ServiceStatusHandle.Val==0){process.exit(1)}this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_STATE.SERVICE_START_PENDING,4);this.Parent.Advapi.SetServiceStatus(this.Parent._ServiceStatusHandle,this.Parent._ServiceStatus);this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_STATE.RUNNING,4);this.Parent._ServiceStatus.toBuffer().writeUInt32LE(SERVICE_ACCEPT.SERVICE_ACCEPT_STOP|SERVICE_ACCEPT.SERVICE_ACCEPT_POWEREVENT|SERVICE_ACCEPT.SERVICE_ACCEPT_SESSIONCHANGE,8);this.Parent.Advapi.SetServiceStatus(this.Parent._ServiceStatusHandle,this.Parent._ServiceStatus);this.Parent.Ole32.CoInitializeEx(0,2);this.Parent.on("~",function h(){var j=require("_GenericMarshal");var i=j.CreateNativeProxy("Advapi32.dll");i.CreateMethod("SetServiceStatus");Kernel32=this.GM.CreateNativeProxy("Kernel32.dll");Kernel32.CreateMethod("GetLastError");var k=j.CreateVariable(28);k.toBuffer().writeUInt32LE(SERVICE_WIN32);k.toBuffer().writeUInt32LE(1,4);k.toBuffer().writeUInt32LE(0,8);i.SetServiceStatus(this._ServiceStatusHandle,k);this.Ole32.CoUninitialize()});this.Parent.emit("serviceStart")});this._ServiceControlHandler=this.GM.GetGenericGlobalCallback(4);this._ServiceControlHandler.Parent=this;this._ServiceControlHandler.GM=this.GM;this._ServiceControlHandler.on("GlobalCallback",function c(f,i,h,g){var k=this.Parent.GM.UnstashObject(g);if(k!=null&&k==this){switch(f.Val){case SERVICE_CONTROL.SERVICE_CONTROL_SHUTDOWN:case SERVICE_CONTROL.SERVICE_CONTROL_STOP:this.Parent.emit("serviceStop");return;case SERVICE_CONTROL.SERVICE_CONTROL_SESSIONCHANGE:var l=h.Deref(4,4).toBuffer().readUInt32LE();switch(i.Val){case SESSION_CHANGE_TYPE.WTS_SESSION_LOGON:case SESSION_CHANGE_TYPE.WTS_SESSION_LOGOFF:require("user-sessions").emit("changed");break}break;default:break}this.Parent.Advapi.SetServiceStatus(this.Parent._ServiceStatusHandle,this.Parent._ServiceStatus)}})}if(e){this._ServiceOptions=typeof(e)=="object"?e:{name:e}}else{throw ("Must specify either ServiceName or Options")}if(!this._ServiceOptions.servicePath){this._ServiceOptions.servicePath=process.execPath}this.run=function d(){var r=0;for(var h=0;hStandardOutPath\n"+s.stdout+""):"");var i=(s.startType=="AUTO_START"?"":"");var t=" ProgramArguments\n";t+=" \n";t+=(" /usr/local/mesh_services/"+s.name+"/"+s.name+"\n");if(s.parameters){for(var p in s.parameters){t+=(" "+s.parameters[p]+"\n")}}t+=" \n";var u='\n';u+='\n';u+='\n';u+=" \n";u+=" Label\n";u+=(" "+s.name+"\n");u+=(t+"\n");u+=" WorkingDirectory\n";u+=(" /usr/local/mesh_services/"+s.name+"\n");u+=(z+"\n");u+=" RunAtLoad\n";u+=(i+"\n");u+=" \n";u+="";if(!require("fs").existsSync("/usr/local/mesh_services")){require("fs").mkdirSync("/usr/local/mesh_services")}if(!require("fs").existsSync("/Library/LaunchDaemons/"+s.name+".plist")){if(!require("fs").existsSync("/usr/local/mesh_services/"+s.name)){require("fs").mkdirSync("/usr/local/mesh_services/"+s.name)}if(s.binary){require("fs").writeFileSync("/usr/local/mesh_services/"+s.name+"/"+s.name,s.binary)}else{require("fs").copyFileSync(s.servicePath,"/usr/local/mesh_services/"+s.name+"/"+s.name)}require("fs").writeFileSync("/Library/LaunchDaemons/"+s.name+".plist",u);var q=require("fs").statSync("/usr/local/mesh_services/"+s.name+"/"+s.name).mode;q|=(require("fs").CHMOD_MODES.S_IXUSR|require("fs").CHMOD_MODES.S_IXGRP);require("fs").chmodSync("/usr/local/mesh_services/"+s.name+"/"+s.name,q)}else{throw ("Service: "+s.name+" already exists")}}};this.uninstallService=function f(i){if(!this.isAdmin()){throw ("Uninstalling a service, requires admin")}if(typeof(i)=="object"){i=i.name}if(process.platform=="win32"){var k=this.getService(i);if(k.status.state==undefined||k.status.state=="STOPPED"){if(this.proxy.DeleteService(k._service)==0){throw ("Uninstall Service for: "+i+", failed with error: "+this.proxy2.GetLastError())}else{try{require("fs").unlinkSync(this.getServiceFolder()+"\\"+i+".exe")}catch(h){}}}else{throw ("Cannot uninstall service: "+i+", because it is: "+k.status.state)}}else{if(process.platform=="linux"){switch(this.getServiceType()){case"init":this._update=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this._update._svcname=i;this._update.on("exit",function j(){try{require("fs").unlinkSync("/etc/init.d/"+this._svcname);console.log(this._svcname+" uninstalled")}catch(l){console.log(this._svcname+" could not be uninstalled")}process.exit()});this._update.stdout.on("data",function(l){});this._update.stdin.write("service "+i+" stop\n");this._update.stdin.write("update-rc.d -f "+i+" remove\n");this._update.stdin.write("exit\n");break;case"systemd":this._update=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this._update._svcname=i;this._update.on("exit",function j(){try{require("fs").unlinkSync("/usr/local/mesh/"+this._svcname);require("fs").unlinkSync("/lib/systemd/system/"+this._svcname+".service");console.log(this._svcname+" uninstalled")}catch(l){console.log(this._svcname+" could not be uninstalled")}process.exit()});this._update.stdout.on("data",function(l){});this._update.stdin.write("systemctl stop "+i+".service\n");this._update.stdin.write("systemctl disable "+i+".service\n");this._update.stdin.write("exit\n");break;default:break}}else{if(process.platform=="darwin"){if(require("fs").existsSync("/Library/LaunchDaemons/"+i+".plist")){var g=require("child_process").execFile("/bin/sh",["sh"]);g.stdout.on("data",function(l){});g.stdin.write("launchctl stop "+i+"\n");g.stdin.write("launchctl unload /Library/LaunchDaemons/"+i+".plist\n");g.stdin.write("exit\n");g.waitExit();try{require("fs").unlinkSync("/usr/local/mesh_services/"+i+"/"+i);require("fs").unlinkSync("/Library/LaunchDaemons/"+i+".plist")}catch(h){throw ("Error uninstalling service: "+i+" => "+h)}try{require("fs").rmdirSync("/usr/local/mesh_services/"+i)}catch(h){}}else{throw ("Service: "+i+" does not exist")}}}}};if(process.platform=="linux"){this.getServiceType=function c(){return(require("process-manager").getProcessInfo(1).Name)}}}module.exports=serviceManager; \ No newline at end of file +function parseServiceStatus(d){var b={};var c=d.Deref(0,4).IntVal;b.isFileSystemDriver=((c&2)==2);b.isKernelDriver=((c&1)==1);b.isSharedProcess=((c&32)==32);b.isOwnProcess=((c&16)==16);b.isInteractive=((c&256)==256);switch(d.Deref((1*4),4).toBuffer().readUInt32LE()){case 5:b.state="CONTINUE_PENDING";break;case 6:b.state="PAUSE_PENDING";break;case 7:b.state="PAUSED";break;case 4:b.state="RUNNING";break;case 2:b.state="START_PENDING";break;case 3:b.state="STOP_PENDING";break;case 1:b.state="STOPPED";break}var a=d.Deref((2*4),4).toBuffer().readUInt32LE();b.controlsAccepted=[];if((a&16)==16){b.controlsAccepted.push("SERVICE_CONTROL_NETBINDADD");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDREMOVE");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDENABLE");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDDISABLE")}if((a&8)==8){b.controlsAccepted.push("SERVICE_CONTROL_PARAMCHANGE")}if((a&2)==2){b.controlsAccepted.push("SERVICE_CONTROL_PAUSE");b.controlsAccepted.push("SERVICE_CONTROL_CONTINUE")}if((a&256)==256){b.controlsAccepted.push("SERVICE_CONTROL_PRESHUTDOWN")}if((a&4)==4){b.controlsAccepted.push("SERVICE_CONTROL_SHUTDOWN")}if((a&1)==1){b.controlsAccepted.push("SERVICE_CONTROL_STOP")}if((a&32)==32){b.controlsAccepted.push("SERVICE_CONTROL_HARDWAREPROFILECHANGE")}if((a&64)==64){b.controlsAccepted.push("SERVICE_CONTROL_POWEREVENT")}if((a&128)==128){b.controlsAccepted.push("SERVICE_CONTROL_SESSIONCHANGE")}b.pid=d.Deref((7*4),4).toBuffer().readUInt32LE();return(b)}function serviceManager(){this._ObjectID="service-manager";if(process.platform=="win32"){this.GM=require("_GenericMarshal");this.proxy=this.GM.CreateNativeProxy("Advapi32.dll");this.proxy.CreateMethod("OpenSCManagerA");this.proxy.CreateMethod("EnumServicesStatusExA");this.proxy.CreateMethod("OpenServiceA");this.proxy.CreateMethod("QueryServiceStatusEx");this.proxy.CreateMethod("ControlService");this.proxy.CreateMethod("StartServiceA");this.proxy.CreateMethod("CloseServiceHandle");this.proxy.CreateMethod("CreateServiceA");this.proxy.CreateMethod("ChangeServiceConfig2A");this.proxy.CreateMethod("DeleteService");this.proxy.CreateMethod("AllocateAndInitializeSid");this.proxy.CreateMethod("CheckTokenMembership");this.proxy.CreateMethod("FreeSid");this.proxy2=this.GM.CreateNativeProxy("Kernel32.dll");this.proxy2.CreateMethod("GetLastError");this.isAdmin=function e(){var j=this.GM.CreateVariable(6);j.toBuffer().writeInt8(5,5);var h=this.GM.CreatePointer();var g=false;if(this.proxy.AllocateAndInitializeSid(j,2,32,544,0,0,0,0,0,0,h).Val!=0){var i=this.GM.CreateInteger();if(this.proxy.CheckTokenMembership(0,h.Deref(),i).Val!=0){if(i.toBuffer().readUInt32LE()!=0){g=true}}this.proxy.FreeSid(h.Deref())}return g};this.getProgramFolder=function a(){if(require("os").arch()=="x64"){if(this.GM.PointerSize==4){return process.env["ProgramFiles(x86)"]}return process.env.ProgramFiles}return process.env.ProgramFiles};this.getServiceFolder=function b(){return this.getProgramFolder()+"\\mesh"};this.enumerateService=function(){var o=this.GM.CreatePointer();var k=this.GM.CreatePointer();var l=this.proxy.OpenSCManagerA(0,0,1|4);var h=this.GM.CreatePointer();var t=this.GM.CreatePointer();var q=this.GM.CreatePointer();var u=this.proxy.EnumServicesStatusExA(l,0,48,3,0,0,h,t,q,0);if(h.IntVal<=0){throw ("error enumerating services")}var v=h.IntVal;var s=this.GM.CreateVariable(v);this.proxy.EnumServicesStatusExA(l,0,48,3,s,v,h,t,q,0);console.log("servicesReturned",t.IntVal);var p=k._size;var g=36+(2*p);g+=((p-(g%p))%p);var r=[];for(var m=0;mStandardOutPath\n"+r.stdout+""):"");var i=(r.startType=="AUTO_START"?"":"");var s=" ProgramArguments\n";s+=" \n";s+=(" /usr/local/mesh_services/"+r.name+"/"+r.name+"\n");if(r.parameters){for(var p in r.parameters){s+=(" "+r.parameters[p]+"\n")}}s+=" \n";var t='\n';t+='\n';t+='\n';t+=" \n";t+=" Label\n";t+=(" "+r.name+"\n");t+=(s+"\n");t+=" WorkingDirectory\n";t+=(" /usr/local/mesh_services/"+r.name+"\n");t+=(y+"\n");t+=" RunAtLoad\n";t+=(i+"\n");t+=" \n";t+="";if(!require("fs").existsSync("/usr/local/mesh_services")){require("fs").mkdirSync("/usr/local/mesh_services")}if(!require("fs").existsSync("/Library/LaunchDaemons/"+r.name+".plist")){if(!require("fs").existsSync("/usr/local/mesh_services/"+r.name)){require("fs").mkdirSync("/usr/local/mesh_services/"+r.name)}if(r.binary){require("fs").writeFileSync("/usr/local/mesh_services/"+r.name+"/"+r.name,r.binary)}else{require("fs").copyFileSync(r.servicePath,"/usr/local/mesh_services/"+r.name+"/"+r.name)}require("fs").writeFileSync("/Library/LaunchDaemons/"+r.name+".plist",t);var q=require("fs").statSync("/usr/local/mesh_services/"+r.name+"/"+r.name).mode;q|=(require("fs").CHMOD_MODES.S_IXUSR|require("fs").CHMOD_MODES.S_IXGRP);require("fs").chmodSync("/usr/local/mesh_services/"+r.name+"/"+r.name,q)}else{throw ("Service: "+r.name+" already exists")}}};this.uninstallService=function f(i){if(!this.isAdmin()){throw ("Uninstalling a service, requires admin")}if(typeof(i)=="object"){i=i.name}if(process.platform=="win32"){var j=this.getService(i);if(j.status.state==undefined||j.status.state=="STOPPED"){if(this.proxy.DeleteService(j._service)==0){throw ("Uninstall Service for: "+i+", failed with error: "+this.proxy2.GetLastError())}else{try{require("fs").unlinkSync(this.getServiceFolder()+"\\"+i+".exe")}catch(h){}}}else{throw ("Cannot uninstall service: "+i+", because it is: "+j.status.state)}}else{if(process.platform=="linux"){switch(this.getServiceType()){case"init":this._update=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this._update.stdout.on("data",function(k){});this._update.stdin.write("service "+i+" stop\n");this._update.stdin.write("update-rc.d -f "+i+" remove\n");this._update.stdin.write("exit\n");this._update.waitExit();try{require("fs").unlinkSync("/etc/init.d/"+i);console.log(i+" uninstalled")}catch(h){console.log(i+" could not be uninstalled",h)}break;case"systemd":this._update=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this._update.stdout.on("data",function(k){});this._update.stdin.write("systemctl stop "+i+".service\n");this._update.stdin.write("systemctl disable "+i+".service\n");this._update.stdin.write("exit\n");this._update.waitExit();try{require("fs").unlinkSync("/usr/local/mesh/"+i);require("fs").unlinkSync("/lib/systemd/system/"+i+".service");console.log(i+" uninstalled")}catch(h){console.log(i+" could not be uninstalled",h)}break;default:break}}else{if(process.platform=="darwin"){if(require("fs").existsSync("/Library/LaunchDaemons/"+i+".plist")){var g=require("child_process").execFile("/bin/sh",["sh"]);g.stdout.on("data",function(k){});g.stdin.write("launchctl stop "+i+"\n");g.stdin.write("launchctl unload /Library/LaunchDaemons/"+i+".plist\n");g.stdin.write("exit\n");g.waitExit();try{require("fs").unlinkSync("/usr/local/mesh_services/"+i+"/"+i);require("fs").unlinkSync("/Library/LaunchDaemons/"+i+".plist")}catch(h){throw ("Error uninstalling service: "+i+" => "+h)}try{require("fs").rmdirSync("/usr/local/mesh_services/"+i)}catch(h){}}else{throw ("Service: "+i+" does not exist")}}}}};if(process.platform=="linux"){this.getServiceType=function c(){return(require("process-manager").getProcessInfo(1).Name)}}}module.exports=serviceManager; \ No newline at end of file diff --git a/agents/modules_meshcmd_min/smbios.min.js b/agents/modules_meshcmd_min/smbios.min.js index 618e6256..451b12c3 100644 --- a/agents/modules_meshcmd_min/smbios.min.js +++ b/agents/modules_meshcmd_min/smbios.min.js @@ -1 +1 @@ -try{Object.defineProperty(Array.prototype,"peek",{value:function(){return(this.length>0?this[this.length-1]:undefined)}})}catch(e){}try{Object.defineProperty(String.prototype,"replaceAll",{value:function replaceAll(b,a){return(this.split(b).join(a))}})}catch(e){}var RSMB=1381190978;var memoryLocation={1:"Other",2:"Unknown",3:"System Board",4:"ISA",5:"EISA",6:"PCI",7:"MCA",8:"PCMCIA",9:"Proprietary",10:"NuBus",160:"PC-98/C20",161:"PC-98/C24",162:"PC-98/E",163:"PC-98/LB"};var wakeReason=["Reserved","Other","Unknown","APM Timer","Modem Ring","LAN","Power Switch","PCI","AC Power"];function zeroLeftPad(c,b){if((b==null)&&(typeof(b)!="number")){return null}if(c==null){c=""}var d="";for(var a=0;a1){var r=v[1].split("\x0A\x0A")[0].split("\x0A");var s=[];for(var t in r){var u=r[t].trim().replaceAll(" ","").replaceAll("\x09","");if(!(u[0]=='"')){s.push(u)}}p.write(Buffer.from(s.join(""),"hex"));p.write(Buffer.from("00","hex"))}else{p.write(Buffer.from("0000","hex"))}}var q=p.buffer;q.ms=p;return(q)}}this._parse=function b(n){var m={};var l;var k=0;var n;var r=0;while(n&&k0){var n=l[4].pop();var o=n[20]&64;var s=n[20]&7;if(o){var m={_ObjectID:"SMBiosTables.processorInfo"};m.Processor=q[n[1]];m.MaxSpeed=n.readUInt16LE(16)+" Mhz";if(n[31]){m.Cores=n[31]}if(n[33]){m.Threads=n[33]}m.Populated=1;m.Status=t[s];m.Socket=n._strings[n[0]-1];m.Manufacturer=n._strings[n[3]-1];m.Version=n._strings[n[12]-1];r.push(m)}}return(r)};this.memoryInfo=function f(k){if(!k){throw ("no data")}var n={_ObjectID:"SMBiosTables.memoryInfo"};if(k[16]){var l=k[16].peek();n.location=memoryLocation[l[0]];if((n.maxCapacityKb=l.readUInt32LE(3))==2147483648){n.maxCapacityKb="A really big number"}}return(n)};this.systemInfo=function i(k){if(!k){throw ("no data")}var l={_ObjectID:"SMBiosTables.systemInfo"};if(k[1]){var m=k[1].peek();var n=m.slice(4,20);l.uuid=[zeroLeftPad(n.readUInt32LE(0).toString(16),8),zeroLeftPad(n.readUInt16LE(4).toString(16),4),zeroLeftPad(n.readUInt16LE(6).toString(16),4),zeroLeftPad(n.readUInt16BE(8).toString(16),4),zeroLeftPad(n.slice(10).toString("hex").toLowerCase(),12)].join("-");l.wakeReason=wakeReason[m[20]]}return(l)};this.systemSlots=function j(k){if(!k){throw ("no data")}var l=[];if(k[9]){while(k[9].length>0){var m=k[9].pop();l.push({name:m._strings[m[0]-1]})}}return(l)};this.amtInfo=function c(l){if(!l){throw ("no data")}var n={AMT:false};if(l[130]&&l[130].peek().slice(0,4).toString()=="$AMT"){var k=l[130].peek();n.AMT=k[4]?true:false;if(n.AMT){n.enabled=k[5]?true:false;n.storageRedirection=k[6]?true:false;n.serialOverLan=k[7]?true:false;n.kvm=k[14]?true:false;if(l[131].peek()&&l[131].peek().slice(52,56).toString()=="vPro"){var o=l[131].peek();if(o[0]&4){n.TXT=(o[0]&8)?true:false}if(o[0]&16){n.VMX=(o[0]&32)?true:false}n.MEBX=o.readUInt16LE(10).toString()+"."+o.readUInt16LE(8).toString()+"."+o.readUInt16LE(6).toString()+"."+o.readUInt16LE(4).toString();var m=o.slice(20,32);n.ManagementEngine=m.readUInt16LE(6).toString()+"."+m.readUInt16LE(4).toString()+"."+m.readUInt16LE(2).toString()+"."+m.readUInt16LE(0).toString()}}}return(n)};this.smTableTypes={0:"BIOS information",1:"System information",2:"Baseboard (or Module) information",4:"Processor information",5:"memory controller information",6:"Memory module information",7:"Cache information",8:"Port connector information",9:"System slots",10:"On board devices information",11:"OEM strings",12:"System configuration options",13:"BIOS language information",14:"Group associations",15:"System event log",16:"Physical memory array",17:"Memory device",18:"32bit memory error information",19:"Memory array mapped address",20:"Memory device mapped address",21:"Built-in pointing device",22:"Portable battery",23:"System reset",24:"Hardware security",25:"System power controls",26:"Voltage probe",27:"Cooling device",28:"Temperature probe",29:"Electrical current probe",30:"Out-of-band remote access",31:"Boot integrity services (BIS) entry point",32:"System boot information",33:"64bit memory error information",34:"Management device",35:"Management device component",36:"Management device threshold data",37:"Memory channel",38:"IPMI device information",39:"System power supply",40:"Additional information",41:"Onboard devices extended information",42:"Management controller host interface",126:"Inactive",127:"End-of-table"}}module.exports=new SMBiosTables(); \ No newline at end of file +try{Object.defineProperty(Array.prototype,"peek",{value:function(){return(this.length>0?this[this.length-1]:undefined)}})}catch(e){}try{Object.defineProperty(String.prototype,"replaceAll",{value:function replaceAll(b,a){return(this.split(b).join(a))}})}catch(e){}var RSMB=1381190978;var memoryLocation={1:"Other",2:"Unknown",3:"System Board",4:"ISA",5:"EISA",6:"PCI",7:"MCA",8:"PCMCIA",9:"Proprietary",10:"NuBus",160:"PC-98/C20",161:"PC-98/C24",162:"PC-98/E",163:"PC-98/LB"};var wakeReason=["Reserved","Other","Unknown","APM Timer","Modem Ring","LAN","Power Switch","PCI","AC Power"];function zeroLeftPad(c,b){if((b==null)&&(typeof(b)!="number")){return null}if(c==null){c=""}var d="";for(var a=0;a1){var r=v[1].split("\x0A\x0A")[0].split("\x0A");var s=[];for(var t in r){var u=r[t].trim().replaceAll(" ","").replaceAll("\x09","");if(!(u[0]=='"')){s.push(u)}}p.write(Buffer.from(s.join(""),"hex"));p.write(Buffer.from("00","hex"))}else{p.write(Buffer.from("0000","hex"))}}var q=p.buffer;q.ms=p;return(q)}}this._parse=function b(o){var n={};var m;var l=0;var o;var s=0;while(o&&l0){var n=l[4].pop();var o=n[20]&64;var s=n[20]&7;if(o){var m={_ObjectID:"SMBiosTables.processorInfo"};m.Processor=q[n[1]];m.MaxSpeed=n.readUInt16LE(16)+" Mhz";if(n[31]){m.Cores=n[31]}if(n[33]){m.Threads=n[33]}m.Populated=1;m.Status=t[s];m.Socket=n._strings[n[0]-1];m.Manufacturer=n._strings[n[3]-1];m.Version=n._strings[n[12]-1];r.push(m)}}return(r)};this.memoryInfo=function f(k){if(!k){throw ("no data")}var n={_ObjectID:"SMBiosTables.memoryInfo"};if(k[16]){var l=k[16].peek();n.location=memoryLocation[l[0]];if((n.maxCapacityKb=l.readUInt32LE(3))==2147483648){n.maxCapacityKb="A really big number"}}return(n)};this.systemInfo=function i(k){if(!k){throw ("no data")}var l={_ObjectID:"SMBiosTables.systemInfo"};if(k[1]){var m=k[1].peek();var n=m.slice(4,20);l.uuid=[zeroLeftPad(n.readUInt32LE(0).toString(16),8),zeroLeftPad(n.readUInt16LE(4).toString(16),4),zeroLeftPad(n.readUInt16LE(6).toString(16),4),zeroLeftPad(n.readUInt16BE(8).toString(16),4),zeroLeftPad(n.slice(10).toString("hex").toLowerCase(),12)].join("-");l.wakeReason=wakeReason[m[20]]}return(l)};this.systemSlots=function j(k){if(!k){throw ("no data")}var l=[];if(k[9]){while(k[9].length>0){var m=k[9].pop();l.push({name:m._strings[m[0]-1]})}}return(l)};this.amtInfo=function c(l){if(!l){throw ("no data")}var n={AMT:false};if(l[130]&&l[130].peek().slice(0,4).toString()=="$AMT"){var k=l[130].peek();n.AMT=k[4]?true:false;if(n.AMT){n.enabled=k[5]?true:false;n.storageRedirection=k[6]?true:false;n.serialOverLan=k[7]?true:false;n.kvm=k[14]?true:false;if(l[131].peek()&&l[131].peek().slice(52,56).toString()=="vPro"){var o=l[131].peek();if(o[0]&4){n.TXT=(o[0]&8)?true:false}if(o[0]&16){n.VMX=(o[0]&32)?true:false}n.MEBX=o.readUInt16LE(10).toString()+"."+o.readUInt16LE(8).toString()+"."+o.readUInt16LE(6).toString()+"."+o.readUInt16LE(4).toString();var m=o.slice(20,32);n.ManagementEngine=m.readUInt16LE(6).toString()+"."+m.readUInt16LE(4).toString()+"."+m.readUInt16LE(2).toString()+"."+m.readUInt16LE(0).toString()}}}return(n)};this.smTableTypes={0:"BIOS information",1:"System information",2:"Baseboard (or Module) information",4:"Processor information",5:"memory controller information",6:"Memory module information",7:"Cache information",8:"Port connector information",9:"System slots",10:"On board devices information",11:"OEM strings",12:"System configuration options",13:"BIOS language information",14:"Group associations",15:"System event log",16:"Physical memory array",17:"Memory device",18:"32bit memory error information",19:"Memory array mapped address",20:"Memory device mapped address",21:"Built-in pointing device",22:"Portable battery",23:"System reset",24:"Hardware security",25:"System power controls",26:"Voltage probe",27:"Cooling device",28:"Temperature probe",29:"Electrical current probe",30:"Out-of-band remote access",31:"Boot integrity services (BIS) entry point",32:"System boot information",33:"64bit memory error information",34:"Management device",35:"Management device component",36:"Management device threshold data",37:"Memory channel",38:"IPMI device information",39:"System power supply",40:"Additional information",41:"Onboard devices extended information",42:"Management controller host interface",126:"Inactive",127:"End-of-table"}}module.exports=new SMBiosTables(); \ No newline at end of file diff --git a/agents/modules_meshcore/service-manager.js b/agents/modules_meshcore/service-manager.js index 34c5830d..168fc96e 100644 --- a/agents/modules_meshcore/service-manager.js +++ b/agents/modules_meshcore/service-manager.js @@ -1,5 +1,5 @@ /* -Copyright 2018-2019 Intel Corporation +Copyright 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -46,9 +46,6 @@ function parseServiceStatus(token) case 0x00000001: j.state = 'STOPPED'; break; - default: - // Unknown service status. - break; } var controlsAccepted = token.Deref((2 * 4), 4).toBuffer().readUInt32LE(); j.controlsAccepted = []; @@ -295,13 +292,14 @@ function serviceManager() require('fs').chmodSync('/etc/init.d/' + options.name, m); this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM }); this._update._moduleName = options.name; - this._update.on('exit', function onUpdateRC_d() { console.log(this._moduleName + ' installed'); process.exit(); }); this._update.stdout.on('data', function (chunk) { }); this._update.stdin.write('update-rc.d ' + options.name + ' defaults\n'); this._update.stdin.write('exit\n'); //update-rc.d meshagent defaults # creates symlinks for rc.d //service meshagent start + this._update.waitExit(); + break; case 'systemd': var serviceDescription = options.description ? options.description : 'MeshCentral Agent'; @@ -313,13 +311,12 @@ function serviceManager() require('fs').writeFileSync('/lib/systemd/system/' + options.name + '.service', '[Unit]\nDescription=' + serviceDescription + '\n[Service]\nExecStart=/usr/local/mesh/' + options.name + '\nStandardOutput=null\nRestart=always\nRestartSec=3\n[Install]\nWantedBy=multi-user.target\nAlias=' + options.name + '.service\n', { flags: 'w' }); this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM }); this._update._moduleName = options.name; - this._update.on('exit', function onUpdateRC_d() { console.log(this._moduleName + ' installed'); process.exit(); }); this._update.stdout.on('data', function (chunk) { }); this._update.stdin.write('systemctl enable ' + options.name + '.service\n'); this._update.stdin.write('exit\n'); - + this._update.waitExit(); break; - default: // Unknown platform service type + default: // unknown platform service type break; } } @@ -416,43 +413,41 @@ function serviceManager() { case 'init': this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM }); - this._update._svcname = name; - this._update.on('exit', function onUninstallExit() { - try { - require('fs').unlinkSync('/etc/init.d/' + this._svcname); - console.log(this._svcname + ' uninstalled'); - - } - catch (e) { - console.log(this._svcname + ' could not be uninstalled') - } - process.exit(); - }); this._update.stdout.on('data', function (chunk) { }); this._update.stdin.write('service ' + name + ' stop\n'); this._update.stdin.write('update-rc.d -f ' + name + ' remove\n'); this._update.stdin.write('exit\n'); + this._update.waitExit(); + try + { + require('fs').unlinkSync('/etc/init.d/' + name); + console.log(name + ' uninstalled'); + + } + catch (e) + { + console.log(name + ' could not be uninstalled', e) + } break; case 'systemd': this._update = require('child_process').execFile('/bin/sh', ['sh'], { type: require('child_process').SpawnTypes.TERM }); - this._update._svcname = name; - this._update.on('exit', function onUninstallExit() { - try { - require('fs').unlinkSync('/usr/local/mesh/' + this._svcname); - require('fs').unlinkSync('/lib/systemd/system/' + this._svcname + '.service'); - console.log(this._svcname + ' uninstalled'); - } - catch (e) { - console.log(this._svcname + ' could not be uninstalled') - } - process.exit(); - }); this._update.stdout.on('data', function (chunk) { }); this._update.stdin.write('systemctl stop ' + name + '.service\n'); this._update.stdin.write('systemctl disable ' + name + '.service\n'); this._update.stdin.write('exit\n'); + this._update.waitExit(); + try + { + require('fs').unlinkSync('/usr/local/mesh/' + name); + require('fs').unlinkSync('/lib/systemd/system/' + name + '.service'); + console.log(name + ' uninstalled'); + } + catch (e) + { + console.log(name + ' could not be uninstalled', e) + } break; - default: // Unknown platform service type + default: // unknown platform service type break; } } diff --git a/agents/modules_meshcore/smbios.js b/agents/modules_meshcore/smbios.js index 28e653bc..91944371 100644 --- a/agents/modules_meshcore/smbios.js +++ b/agents/modules_meshcore/smbios.js @@ -1,5 +1,5 @@ /* -Copyright 2018-2019 Intel Corporation +Copyright 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -77,7 +77,8 @@ function SMBiosTables() var SMData; var structcount = 0; - while (SMData && i < SMData.length) { + while (SMData && i < SMData.length) + { var SMtype = SMData[i]; var SMlength = SMData[i + 1]; @@ -88,12 +89,20 @@ function SMBiosTables() ret[SMtype].peek()._strings = []; - while (SMData[i] != 0) { + while (SMData[i] != 0 && i <= SMData.length) + { var strstart = i; // Start of String, find end of string - while (SMData[i++] != 0); - ret[SMtype].peek()._strings.push(SMData.slice(strstart, i).toString().trim()); + while (SMData[i++] != 0 && i <= SMData.length); + try + { + ret[SMtype].peek()._strings.push(SMData.slice(strstart, i).toString().trim()); + } + catch (ee) + { + console.log('oops'); + } } i += (ret[SMtype].peek()._strings.length == 0) ? 2 : 1; ++structcount; diff --git a/agents/modules_meshcore_min/service-manager.min.js b/agents/modules_meshcore_min/service-manager.min.js index 4a9fad63..15a2197f 100644 --- a/agents/modules_meshcore_min/service-manager.min.js +++ b/agents/modules_meshcore_min/service-manager.min.js @@ -1 +1 @@ -function parseServiceStatus(d){var b={};var c=d.Deref(0,4).IntVal;b.isFileSystemDriver=((c&2)==2);b.isKernelDriver=((c&1)==1);b.isSharedProcess=((c&32)==32);b.isOwnProcess=((c&16)==16);b.isInteractive=((c&256)==256);switch(d.Deref((1*4),4).toBuffer().readUInt32LE()){case 5:b.state="CONTINUE_PENDING";break;case 6:b.state="PAUSE_PENDING";break;case 7:b.state="PAUSED";break;case 4:b.state="RUNNING";break;case 2:b.state="START_PENDING";break;case 3:b.state="STOP_PENDING";break;case 1:b.state="STOPPED";break;default:break}var a=d.Deref((2*4),4).toBuffer().readUInt32LE();b.controlsAccepted=[];if((a&16)==16){b.controlsAccepted.push("SERVICE_CONTROL_NETBINDADD");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDREMOVE");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDENABLE");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDDISABLE")}if((a&8)==8){b.controlsAccepted.push("SERVICE_CONTROL_PARAMCHANGE")}if((a&2)==2){b.controlsAccepted.push("SERVICE_CONTROL_PAUSE");b.controlsAccepted.push("SERVICE_CONTROL_CONTINUE")}if((a&256)==256){b.controlsAccepted.push("SERVICE_CONTROL_PRESHUTDOWN")}if((a&4)==4){b.controlsAccepted.push("SERVICE_CONTROL_SHUTDOWN")}if((a&1)==1){b.controlsAccepted.push("SERVICE_CONTROL_STOP")}if((a&32)==32){b.controlsAccepted.push("SERVICE_CONTROL_HARDWAREPROFILECHANGE")}if((a&64)==64){b.controlsAccepted.push("SERVICE_CONTROL_POWEREVENT")}if((a&128)==128){b.controlsAccepted.push("SERVICE_CONTROL_SESSIONCHANGE")}b.pid=d.Deref((7*4),4).toBuffer().readUInt32LE();return(b)}function serviceManager(){this._ObjectID="service-manager";if(process.platform=="win32"){this.GM=require("_GenericMarshal");this.proxy=this.GM.CreateNativeProxy("Advapi32.dll");this.proxy.CreateMethod("OpenSCManagerA");this.proxy.CreateMethod("EnumServicesStatusExA");this.proxy.CreateMethod("OpenServiceA");this.proxy.CreateMethod("QueryServiceStatusEx");this.proxy.CreateMethod("ControlService");this.proxy.CreateMethod("StartServiceA");this.proxy.CreateMethod("CloseServiceHandle");this.proxy.CreateMethod("CreateServiceA");this.proxy.CreateMethod("ChangeServiceConfig2A");this.proxy.CreateMethod("DeleteService");this.proxy.CreateMethod("AllocateAndInitializeSid");this.proxy.CreateMethod("CheckTokenMembership");this.proxy.CreateMethod("FreeSid");this.proxy2=this.GM.CreateNativeProxy("Kernel32.dll");this.proxy2.CreateMethod("GetLastError");this.isAdmin=function e(){var j=this.GM.CreateVariable(6);j.toBuffer().writeInt8(5,5);var h=this.GM.CreatePointer();var g=false;if(this.proxy.AllocateAndInitializeSid(j,2,32,544,0,0,0,0,0,0,h).Val!=0){var i=this.GM.CreateInteger();if(this.proxy.CheckTokenMembership(0,h.Deref(),i).Val!=0){if(i.toBuffer().readUInt32LE()!=0){g=true}}this.proxy.FreeSid(h.Deref())}return g};this.getProgramFolder=function a(){if(require("os").arch()=="x64"){if(this.GM.PointerSize==4){return process.env["ProgramFiles(x86)"]}return process.env.ProgramFiles}return process.env.ProgramFiles};this.getServiceFolder=function b(){return this.getProgramFolder()+"\\mesh"};this.enumerateService=function(){var o=this.GM.CreatePointer();var k=this.GM.CreatePointer();var l=this.proxy.OpenSCManagerA(0,0,1|4);var h=this.GM.CreatePointer();var t=this.GM.CreatePointer();var q=this.GM.CreatePointer();var u=this.proxy.EnumServicesStatusExA(l,0,48,3,0,0,h,t,q,0);if(h.IntVal<=0){throw ("error enumerating services")}var v=h.IntVal;var s=this.GM.CreateVariable(v);this.proxy.EnumServicesStatusExA(l,0,48,3,s,v,h,t,q,0);console.log("servicesReturned",t.IntVal);var p=k._size;var g=36+(2*p);g+=((p-(g%p))%p);var r=[];for(var m=0;mStandardOutPath\n"+s.stdout+""):"");var i=(s.startType=="AUTO_START"?"":"");var t=" ProgramArguments\n";t+=" \n";t+=(" /usr/local/mesh_services/"+s.name+"/"+s.name+"\n");if(s.parameters){for(var p in s.parameters){t+=(" "+s.parameters[p]+"\n")}}t+=" \n";var u='\n';u+='\n';u+='\n';u+=" \n";u+=" Label\n";u+=(" "+s.name+"\n");u+=(t+"\n");u+=" WorkingDirectory\n";u+=(" /usr/local/mesh_services/"+s.name+"\n");u+=(z+"\n");u+=" RunAtLoad\n";u+=(i+"\n");u+=" \n";u+="";if(!require("fs").existsSync("/usr/local/mesh_services")){require("fs").mkdirSync("/usr/local/mesh_services")}if(!require("fs").existsSync("/Library/LaunchDaemons/"+s.name+".plist")){if(!require("fs").existsSync("/usr/local/mesh_services/"+s.name)){require("fs").mkdirSync("/usr/local/mesh_services/"+s.name)}if(s.binary){require("fs").writeFileSync("/usr/local/mesh_services/"+s.name+"/"+s.name,s.binary)}else{require("fs").copyFileSync(s.servicePath,"/usr/local/mesh_services/"+s.name+"/"+s.name)}require("fs").writeFileSync("/Library/LaunchDaemons/"+s.name+".plist",u);var q=require("fs").statSync("/usr/local/mesh_services/"+s.name+"/"+s.name).mode;q|=(require("fs").CHMOD_MODES.S_IXUSR|require("fs").CHMOD_MODES.S_IXGRP);require("fs").chmodSync("/usr/local/mesh_services/"+s.name+"/"+s.name,q)}else{throw ("Service: "+s.name+" already exists")}}};this.uninstallService=function f(i){if(!this.isAdmin()){throw ("Uninstalling a service, requires admin")}if(typeof(i)=="object"){i=i.name}if(process.platform=="win32"){var k=this.getService(i);if(k.status.state==undefined||k.status.state=="STOPPED"){if(this.proxy.DeleteService(k._service)==0){throw ("Uninstall Service for: "+i+", failed with error: "+this.proxy2.GetLastError())}else{try{require("fs").unlinkSync(this.getServiceFolder()+"\\"+i+".exe")}catch(h){}}}else{throw ("Cannot uninstall service: "+i+", because it is: "+k.status.state)}}else{if(process.platform=="linux"){switch(this.getServiceType()){case"init":this._update=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this._update._svcname=i;this._update.on("exit",function j(){try{require("fs").unlinkSync("/etc/init.d/"+this._svcname);console.log(this._svcname+" uninstalled")}catch(l){console.log(this._svcname+" could not be uninstalled")}process.exit()});this._update.stdout.on("data",function(l){});this._update.stdin.write("service "+i+" stop\n");this._update.stdin.write("update-rc.d -f "+i+" remove\n");this._update.stdin.write("exit\n");break;case"systemd":this._update=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this._update._svcname=i;this._update.on("exit",function j(){try{require("fs").unlinkSync("/usr/local/mesh/"+this._svcname);require("fs").unlinkSync("/lib/systemd/system/"+this._svcname+".service");console.log(this._svcname+" uninstalled")}catch(l){console.log(this._svcname+" could not be uninstalled")}process.exit()});this._update.stdout.on("data",function(l){});this._update.stdin.write("systemctl stop "+i+".service\n");this._update.stdin.write("systemctl disable "+i+".service\n");this._update.stdin.write("exit\n");break;default:break}}else{if(process.platform=="darwin"){if(require("fs").existsSync("/Library/LaunchDaemons/"+i+".plist")){var g=require("child_process").execFile("/bin/sh",["sh"]);g.stdout.on("data",function(l){});g.stdin.write("launchctl stop "+i+"\n");g.stdin.write("launchctl unload /Library/LaunchDaemons/"+i+".plist\n");g.stdin.write("exit\n");g.waitExit();try{require("fs").unlinkSync("/usr/local/mesh_services/"+i+"/"+i);require("fs").unlinkSync("/Library/LaunchDaemons/"+i+".plist")}catch(h){throw ("Error uninstalling service: "+i+" => "+h)}try{require("fs").rmdirSync("/usr/local/mesh_services/"+i)}catch(h){}}else{throw ("Service: "+i+" does not exist")}}}}};if(process.platform=="linux"){this.getServiceType=function c(){return(require("process-manager").getProcessInfo(1).Name)}}}module.exports=serviceManager; \ No newline at end of file +function parseServiceStatus(d){var b={};var c=d.Deref(0,4).IntVal;b.isFileSystemDriver=((c&2)==2);b.isKernelDriver=((c&1)==1);b.isSharedProcess=((c&32)==32);b.isOwnProcess=((c&16)==16);b.isInteractive=((c&256)==256);switch(d.Deref((1*4),4).toBuffer().readUInt32LE()){case 5:b.state="CONTINUE_PENDING";break;case 6:b.state="PAUSE_PENDING";break;case 7:b.state="PAUSED";break;case 4:b.state="RUNNING";break;case 2:b.state="START_PENDING";break;case 3:b.state="STOP_PENDING";break;case 1:b.state="STOPPED";break}var a=d.Deref((2*4),4).toBuffer().readUInt32LE();b.controlsAccepted=[];if((a&16)==16){b.controlsAccepted.push("SERVICE_CONTROL_NETBINDADD");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDREMOVE");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDENABLE");b.controlsAccepted.push("SERVICE_CONTROL_NETBINDDISABLE")}if((a&8)==8){b.controlsAccepted.push("SERVICE_CONTROL_PARAMCHANGE")}if((a&2)==2){b.controlsAccepted.push("SERVICE_CONTROL_PAUSE");b.controlsAccepted.push("SERVICE_CONTROL_CONTINUE")}if((a&256)==256){b.controlsAccepted.push("SERVICE_CONTROL_PRESHUTDOWN")}if((a&4)==4){b.controlsAccepted.push("SERVICE_CONTROL_SHUTDOWN")}if((a&1)==1){b.controlsAccepted.push("SERVICE_CONTROL_STOP")}if((a&32)==32){b.controlsAccepted.push("SERVICE_CONTROL_HARDWAREPROFILECHANGE")}if((a&64)==64){b.controlsAccepted.push("SERVICE_CONTROL_POWEREVENT")}if((a&128)==128){b.controlsAccepted.push("SERVICE_CONTROL_SESSIONCHANGE")}b.pid=d.Deref((7*4),4).toBuffer().readUInt32LE();return(b)}function serviceManager(){this._ObjectID="service-manager";if(process.platform=="win32"){this.GM=require("_GenericMarshal");this.proxy=this.GM.CreateNativeProxy("Advapi32.dll");this.proxy.CreateMethod("OpenSCManagerA");this.proxy.CreateMethod("EnumServicesStatusExA");this.proxy.CreateMethod("OpenServiceA");this.proxy.CreateMethod("QueryServiceStatusEx");this.proxy.CreateMethod("ControlService");this.proxy.CreateMethod("StartServiceA");this.proxy.CreateMethod("CloseServiceHandle");this.proxy.CreateMethod("CreateServiceA");this.proxy.CreateMethod("ChangeServiceConfig2A");this.proxy.CreateMethod("DeleteService");this.proxy.CreateMethod("AllocateAndInitializeSid");this.proxy.CreateMethod("CheckTokenMembership");this.proxy.CreateMethod("FreeSid");this.proxy2=this.GM.CreateNativeProxy("Kernel32.dll");this.proxy2.CreateMethod("GetLastError");this.isAdmin=function e(){var j=this.GM.CreateVariable(6);j.toBuffer().writeInt8(5,5);var h=this.GM.CreatePointer();var g=false;if(this.proxy.AllocateAndInitializeSid(j,2,32,544,0,0,0,0,0,0,h).Val!=0){var i=this.GM.CreateInteger();if(this.proxy.CheckTokenMembership(0,h.Deref(),i).Val!=0){if(i.toBuffer().readUInt32LE()!=0){g=true}}this.proxy.FreeSid(h.Deref())}return g};this.getProgramFolder=function a(){if(require("os").arch()=="x64"){if(this.GM.PointerSize==4){return process.env["ProgramFiles(x86)"]}return process.env.ProgramFiles}return process.env.ProgramFiles};this.getServiceFolder=function b(){return this.getProgramFolder()+"\\mesh"};this.enumerateService=function(){var o=this.GM.CreatePointer();var k=this.GM.CreatePointer();var l=this.proxy.OpenSCManagerA(0,0,1|4);var h=this.GM.CreatePointer();var t=this.GM.CreatePointer();var q=this.GM.CreatePointer();var u=this.proxy.EnumServicesStatusExA(l,0,48,3,0,0,h,t,q,0);if(h.IntVal<=0){throw ("error enumerating services")}var v=h.IntVal;var s=this.GM.CreateVariable(v);this.proxy.EnumServicesStatusExA(l,0,48,3,s,v,h,t,q,0);console.log("servicesReturned",t.IntVal);var p=k._size;var g=36+(2*p);g+=((p-(g%p))%p);var r=[];for(var m=0;mStandardOutPath\n"+r.stdout+""):"");var i=(r.startType=="AUTO_START"?"":"");var s=" ProgramArguments\n";s+=" \n";s+=(" /usr/local/mesh_services/"+r.name+"/"+r.name+"\n");if(r.parameters){for(var p in r.parameters){s+=(" "+r.parameters[p]+"\n")}}s+=" \n";var t='\n';t+='\n';t+='\n';t+=" \n";t+=" Label\n";t+=(" "+r.name+"\n");t+=(s+"\n");t+=" WorkingDirectory\n";t+=(" /usr/local/mesh_services/"+r.name+"\n");t+=(y+"\n");t+=" RunAtLoad\n";t+=(i+"\n");t+=" \n";t+="";if(!require("fs").existsSync("/usr/local/mesh_services")){require("fs").mkdirSync("/usr/local/mesh_services")}if(!require("fs").existsSync("/Library/LaunchDaemons/"+r.name+".plist")){if(!require("fs").existsSync("/usr/local/mesh_services/"+r.name)){require("fs").mkdirSync("/usr/local/mesh_services/"+r.name)}if(r.binary){require("fs").writeFileSync("/usr/local/mesh_services/"+r.name+"/"+r.name,r.binary)}else{require("fs").copyFileSync(r.servicePath,"/usr/local/mesh_services/"+r.name+"/"+r.name)}require("fs").writeFileSync("/Library/LaunchDaemons/"+r.name+".plist",t);var q=require("fs").statSync("/usr/local/mesh_services/"+r.name+"/"+r.name).mode;q|=(require("fs").CHMOD_MODES.S_IXUSR|require("fs").CHMOD_MODES.S_IXGRP);require("fs").chmodSync("/usr/local/mesh_services/"+r.name+"/"+r.name,q)}else{throw ("Service: "+r.name+" already exists")}}};this.uninstallService=function f(i){if(!this.isAdmin()){throw ("Uninstalling a service, requires admin")}if(typeof(i)=="object"){i=i.name}if(process.platform=="win32"){var j=this.getService(i);if(j.status.state==undefined||j.status.state=="STOPPED"){if(this.proxy.DeleteService(j._service)==0){throw ("Uninstall Service for: "+i+", failed with error: "+this.proxy2.GetLastError())}else{try{require("fs").unlinkSync(this.getServiceFolder()+"\\"+i+".exe")}catch(h){}}}else{throw ("Cannot uninstall service: "+i+", because it is: "+j.status.state)}}else{if(process.platform=="linux"){switch(this.getServiceType()){case"init":this._update=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this._update.stdout.on("data",function(k){});this._update.stdin.write("service "+i+" stop\n");this._update.stdin.write("update-rc.d -f "+i+" remove\n");this._update.stdin.write("exit\n");this._update.waitExit();try{require("fs").unlinkSync("/etc/init.d/"+i);console.log(i+" uninstalled")}catch(h){console.log(i+" could not be uninstalled",h)}break;case"systemd":this._update=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this._update.stdout.on("data",function(k){});this._update.stdin.write("systemctl stop "+i+".service\n");this._update.stdin.write("systemctl disable "+i+".service\n");this._update.stdin.write("exit\n");this._update.waitExit();try{require("fs").unlinkSync("/usr/local/mesh/"+i);require("fs").unlinkSync("/lib/systemd/system/"+i+".service");console.log(i+" uninstalled")}catch(h){console.log(i+" could not be uninstalled",h)}break;default:break}}else{if(process.platform=="darwin"){if(require("fs").existsSync("/Library/LaunchDaemons/"+i+".plist")){var g=require("child_process").execFile("/bin/sh",["sh"]);g.stdout.on("data",function(k){});g.stdin.write("launchctl stop "+i+"\n");g.stdin.write("launchctl unload /Library/LaunchDaemons/"+i+".plist\n");g.stdin.write("exit\n");g.waitExit();try{require("fs").unlinkSync("/usr/local/mesh_services/"+i+"/"+i);require("fs").unlinkSync("/Library/LaunchDaemons/"+i+".plist")}catch(h){throw ("Error uninstalling service: "+i+" => "+h)}try{require("fs").rmdirSync("/usr/local/mesh_services/"+i)}catch(h){}}else{throw ("Service: "+i+" does not exist")}}}}};if(process.platform=="linux"){this.getServiceType=function c(){return(require("process-manager").getProcessInfo(1).Name)}}}module.exports=serviceManager; \ No newline at end of file diff --git a/agents/modules_meshcore_min/smbios.min.js b/agents/modules_meshcore_min/smbios.min.js index 618e6256..451b12c3 100644 --- a/agents/modules_meshcore_min/smbios.min.js +++ b/agents/modules_meshcore_min/smbios.min.js @@ -1 +1 @@ -try{Object.defineProperty(Array.prototype,"peek",{value:function(){return(this.length>0?this[this.length-1]:undefined)}})}catch(e){}try{Object.defineProperty(String.prototype,"replaceAll",{value:function replaceAll(b,a){return(this.split(b).join(a))}})}catch(e){}var RSMB=1381190978;var memoryLocation={1:"Other",2:"Unknown",3:"System Board",4:"ISA",5:"EISA",6:"PCI",7:"MCA",8:"PCMCIA",9:"Proprietary",10:"NuBus",160:"PC-98/C20",161:"PC-98/C24",162:"PC-98/E",163:"PC-98/LB"};var wakeReason=["Reserved","Other","Unknown","APM Timer","Modem Ring","LAN","Power Switch","PCI","AC Power"];function zeroLeftPad(c,b){if((b==null)&&(typeof(b)!="number")){return null}if(c==null){c=""}var d="";for(var a=0;a1){var r=v[1].split("\x0A\x0A")[0].split("\x0A");var s=[];for(var t in r){var u=r[t].trim().replaceAll(" ","").replaceAll("\x09","");if(!(u[0]=='"')){s.push(u)}}p.write(Buffer.from(s.join(""),"hex"));p.write(Buffer.from("00","hex"))}else{p.write(Buffer.from("0000","hex"))}}var q=p.buffer;q.ms=p;return(q)}}this._parse=function b(n){var m={};var l;var k=0;var n;var r=0;while(n&&k0){var n=l[4].pop();var o=n[20]&64;var s=n[20]&7;if(o){var m={_ObjectID:"SMBiosTables.processorInfo"};m.Processor=q[n[1]];m.MaxSpeed=n.readUInt16LE(16)+" Mhz";if(n[31]){m.Cores=n[31]}if(n[33]){m.Threads=n[33]}m.Populated=1;m.Status=t[s];m.Socket=n._strings[n[0]-1];m.Manufacturer=n._strings[n[3]-1];m.Version=n._strings[n[12]-1];r.push(m)}}return(r)};this.memoryInfo=function f(k){if(!k){throw ("no data")}var n={_ObjectID:"SMBiosTables.memoryInfo"};if(k[16]){var l=k[16].peek();n.location=memoryLocation[l[0]];if((n.maxCapacityKb=l.readUInt32LE(3))==2147483648){n.maxCapacityKb="A really big number"}}return(n)};this.systemInfo=function i(k){if(!k){throw ("no data")}var l={_ObjectID:"SMBiosTables.systemInfo"};if(k[1]){var m=k[1].peek();var n=m.slice(4,20);l.uuid=[zeroLeftPad(n.readUInt32LE(0).toString(16),8),zeroLeftPad(n.readUInt16LE(4).toString(16),4),zeroLeftPad(n.readUInt16LE(6).toString(16),4),zeroLeftPad(n.readUInt16BE(8).toString(16),4),zeroLeftPad(n.slice(10).toString("hex").toLowerCase(),12)].join("-");l.wakeReason=wakeReason[m[20]]}return(l)};this.systemSlots=function j(k){if(!k){throw ("no data")}var l=[];if(k[9]){while(k[9].length>0){var m=k[9].pop();l.push({name:m._strings[m[0]-1]})}}return(l)};this.amtInfo=function c(l){if(!l){throw ("no data")}var n={AMT:false};if(l[130]&&l[130].peek().slice(0,4).toString()=="$AMT"){var k=l[130].peek();n.AMT=k[4]?true:false;if(n.AMT){n.enabled=k[5]?true:false;n.storageRedirection=k[6]?true:false;n.serialOverLan=k[7]?true:false;n.kvm=k[14]?true:false;if(l[131].peek()&&l[131].peek().slice(52,56).toString()=="vPro"){var o=l[131].peek();if(o[0]&4){n.TXT=(o[0]&8)?true:false}if(o[0]&16){n.VMX=(o[0]&32)?true:false}n.MEBX=o.readUInt16LE(10).toString()+"."+o.readUInt16LE(8).toString()+"."+o.readUInt16LE(6).toString()+"."+o.readUInt16LE(4).toString();var m=o.slice(20,32);n.ManagementEngine=m.readUInt16LE(6).toString()+"."+m.readUInt16LE(4).toString()+"."+m.readUInt16LE(2).toString()+"."+m.readUInt16LE(0).toString()}}}return(n)};this.smTableTypes={0:"BIOS information",1:"System information",2:"Baseboard (or Module) information",4:"Processor information",5:"memory controller information",6:"Memory module information",7:"Cache information",8:"Port connector information",9:"System slots",10:"On board devices information",11:"OEM strings",12:"System configuration options",13:"BIOS language information",14:"Group associations",15:"System event log",16:"Physical memory array",17:"Memory device",18:"32bit memory error information",19:"Memory array mapped address",20:"Memory device mapped address",21:"Built-in pointing device",22:"Portable battery",23:"System reset",24:"Hardware security",25:"System power controls",26:"Voltage probe",27:"Cooling device",28:"Temperature probe",29:"Electrical current probe",30:"Out-of-band remote access",31:"Boot integrity services (BIS) entry point",32:"System boot information",33:"64bit memory error information",34:"Management device",35:"Management device component",36:"Management device threshold data",37:"Memory channel",38:"IPMI device information",39:"System power supply",40:"Additional information",41:"Onboard devices extended information",42:"Management controller host interface",126:"Inactive",127:"End-of-table"}}module.exports=new SMBiosTables(); \ No newline at end of file +try{Object.defineProperty(Array.prototype,"peek",{value:function(){return(this.length>0?this[this.length-1]:undefined)}})}catch(e){}try{Object.defineProperty(String.prototype,"replaceAll",{value:function replaceAll(b,a){return(this.split(b).join(a))}})}catch(e){}var RSMB=1381190978;var memoryLocation={1:"Other",2:"Unknown",3:"System Board",4:"ISA",5:"EISA",6:"PCI",7:"MCA",8:"PCMCIA",9:"Proprietary",10:"NuBus",160:"PC-98/C20",161:"PC-98/C24",162:"PC-98/E",163:"PC-98/LB"};var wakeReason=["Reserved","Other","Unknown","APM Timer","Modem Ring","LAN","Power Switch","PCI","AC Power"];function zeroLeftPad(c,b){if((b==null)&&(typeof(b)!="number")){return null}if(c==null){c=""}var d="";for(var a=0;a1){var r=v[1].split("\x0A\x0A")[0].split("\x0A");var s=[];for(var t in r){var u=r[t].trim().replaceAll(" ","").replaceAll("\x09","");if(!(u[0]=='"')){s.push(u)}}p.write(Buffer.from(s.join(""),"hex"));p.write(Buffer.from("00","hex"))}else{p.write(Buffer.from("0000","hex"))}}var q=p.buffer;q.ms=p;return(q)}}this._parse=function b(o){var n={};var m;var l=0;var o;var s=0;while(o&&l0){var n=l[4].pop();var o=n[20]&64;var s=n[20]&7;if(o){var m={_ObjectID:"SMBiosTables.processorInfo"};m.Processor=q[n[1]];m.MaxSpeed=n.readUInt16LE(16)+" Mhz";if(n[31]){m.Cores=n[31]}if(n[33]){m.Threads=n[33]}m.Populated=1;m.Status=t[s];m.Socket=n._strings[n[0]-1];m.Manufacturer=n._strings[n[3]-1];m.Version=n._strings[n[12]-1];r.push(m)}}return(r)};this.memoryInfo=function f(k){if(!k){throw ("no data")}var n={_ObjectID:"SMBiosTables.memoryInfo"};if(k[16]){var l=k[16].peek();n.location=memoryLocation[l[0]];if((n.maxCapacityKb=l.readUInt32LE(3))==2147483648){n.maxCapacityKb="A really big number"}}return(n)};this.systemInfo=function i(k){if(!k){throw ("no data")}var l={_ObjectID:"SMBiosTables.systemInfo"};if(k[1]){var m=k[1].peek();var n=m.slice(4,20);l.uuid=[zeroLeftPad(n.readUInt32LE(0).toString(16),8),zeroLeftPad(n.readUInt16LE(4).toString(16),4),zeroLeftPad(n.readUInt16LE(6).toString(16),4),zeroLeftPad(n.readUInt16BE(8).toString(16),4),zeroLeftPad(n.slice(10).toString("hex").toLowerCase(),12)].join("-");l.wakeReason=wakeReason[m[20]]}return(l)};this.systemSlots=function j(k){if(!k){throw ("no data")}var l=[];if(k[9]){while(k[9].length>0){var m=k[9].pop();l.push({name:m._strings[m[0]-1]})}}return(l)};this.amtInfo=function c(l){if(!l){throw ("no data")}var n={AMT:false};if(l[130]&&l[130].peek().slice(0,4).toString()=="$AMT"){var k=l[130].peek();n.AMT=k[4]?true:false;if(n.AMT){n.enabled=k[5]?true:false;n.storageRedirection=k[6]?true:false;n.serialOverLan=k[7]?true:false;n.kvm=k[14]?true:false;if(l[131].peek()&&l[131].peek().slice(52,56).toString()=="vPro"){var o=l[131].peek();if(o[0]&4){n.TXT=(o[0]&8)?true:false}if(o[0]&16){n.VMX=(o[0]&32)?true:false}n.MEBX=o.readUInt16LE(10).toString()+"."+o.readUInt16LE(8).toString()+"."+o.readUInt16LE(6).toString()+"."+o.readUInt16LE(4).toString();var m=o.slice(20,32);n.ManagementEngine=m.readUInt16LE(6).toString()+"."+m.readUInt16LE(4).toString()+"."+m.readUInt16LE(2).toString()+"."+m.readUInt16LE(0).toString()}}}return(n)};this.smTableTypes={0:"BIOS information",1:"System information",2:"Baseboard (or Module) information",4:"Processor information",5:"memory controller information",6:"Memory module information",7:"Cache information",8:"Port connector information",9:"System slots",10:"On board devices information",11:"OEM strings",12:"System configuration options",13:"BIOS language information",14:"Group associations",15:"System event log",16:"Physical memory array",17:"Memory device",18:"32bit memory error information",19:"Memory array mapped address",20:"Memory device mapped address",21:"Built-in pointing device",22:"Portable battery",23:"System reset",24:"Hardware security",25:"System power controls",26:"Voltage probe",27:"Cooling device",28:"Temperature probe",29:"Electrical current probe",30:"Out-of-band remote access",31:"Boot integrity services (BIS) entry point",32:"System boot information",33:"64bit memory error information",34:"Management device",35:"Management device component",36:"Management device threshold data",37:"Memory channel",38:"IPMI device information",39:"System power supply",40:"Additional information",41:"Onboard devices extended information",42:"Management controller host interface",126:"Inactive",127:"End-of-table"}}module.exports=new SMBiosTables(); \ No newline at end of file diff --git a/meshcentral.js b/meshcentral.js index 11f0aa94..0da4828b 100644 --- a/meshcentral.js +++ b/meshcentral.js @@ -187,7 +187,7 @@ function CreateMeshCentralServer(config, args) { } } }); - xprocess.stdout.on('data', function (data) { if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); } if (data.indexOf('Updating settings folder...') >= 0) { xprocess.xrestart = 1; } else if (data.indexOf('Updating server certificates...') >= 0) { xprocess.xrestart = 1; } else if (data.indexOf('Server Ctrl-C exit...') >= 0) { xprocess.xrestart = 2; } else if (data.indexOf('Starting self upgrade...') >= 0) { xprocess.xrestart = 3; } console.log(data); }); + xprocess.stdout.on('data', function (data) { if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); } if (data.indexOf('Updating settings folder...') >= 0) { xprocess.xrestart = 1; } else if (data.indexOf('Updating server certificates...') >= 0) { xprocess.xrestart = 1; } else if (data.indexOf('Server Ctrl-C exit...') >= 0) { xprocess.xrestart = 2; } else if (data.indexOf('Starting self upgrade...') >= 0) { xprocess.xrestart = 3; } else if (data.indexOf('Server restart...') >= 0) { xprocess.xrestart = 1; } console.log(data); }); xprocess.stderr.on('data', function (data) { if (data.startsWith('le.challenges[tls-sni-01].loopback')) { return; } // Ignore this error output from GreenLock if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); } diff --git a/meshuser.js b/meshuser.js index 673fd2fa..5280b23b 100644 --- a/meshuser.js +++ b/meshuser.js @@ -404,6 +404,55 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use } break; } + case 'serverconsole': + { + // This is a server console message, only process this if full administrator + if (user.siteadmin != 0xFFFFFFFF) break; + + var r = ''; + var args = splitArgs(command.value); + if (args.length == 0) break; + const cmd = args[0].toLowerCase(); + args = parseArgs(args); + + switch (cmd) { + case 'help': { + r = 'Available commands: help, args, resetserver, showconfig, usersessions.'; + break; + } + case 'args': { + r = cmd + ': ' + JSON.stringify(args); + break; + } + case 'usersessions': { + for (var i in obj.parent.wssessions) { + r += (i + ', ' + obj.parent.wssessions[i].length + ' session' + ((obj.parent.wssessions[i].length > 1) ? 'a' : '') + '.
'); + for (var j in obj.parent.wssessions[i]) { + var addr = obj.parent.wssessions[i][j]._socket.remoteAddress; + if (addr.startsWith('::ffff:')) { addr = addr.substring(7); } + r += ' ' + addr + ' --> ' + obj.parent.wssessions[i][j].sessionId + '.
'; + } + } + break; + } + case 'resetserver': { + console.log('Server restart...'); + process.exit(0); + break; + } + case 'showconfig': { + r = JSON.stringify(obj.parent.parent.config, null, 4); + break; + } + default: { // This is an unknown command, return an error message + r = 'Unknown command \"' + cmd + '\", type \"help\" for list of avaialble commands.'; + break; + } + } + + if (r != '') { try { ws.send(JSON.stringify({ action: 'serverconsole', value: r, tag: command.tag })); } catch (ex) { } } + break; + } case 'msg': { // Route this command to a target node @@ -893,7 +942,11 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use obj.db.Set(obj.common.escapeLinksFieldName(mesh)); // Notify mesh change - obj.parent.parent.DispatchEvent(['*', mesh._id, user._id, command.userid], obj, { etype: 'mesh', username: user.name, userid: deluser.name, meshid: mesh._id, name: mesh.name, mtype: mesh.mtype, desc: mesh.desc, action: 'meshchange', links: mesh.links, msg: 'Removed user ' + deluser.name + ' from group ' + mesh.name, domain: domain.id }); + if (deluser != null) { + obj.parent.parent.DispatchEvent(['*', mesh._id, user._id, command.userid], obj, { etype: 'mesh', username: user.name, userid: deluser.name, meshid: mesh._id, name: mesh.name, mtype: mesh.mtype, desc: mesh.desc, action: 'meshchange', links: mesh.links, msg: 'Removed user ' + deluser.name + ' from group ' + mesh.name, domain: domain.id }); + } else { + obj.parent.parent.DispatchEvent(['*', mesh._id, user._id, command.userid], obj, { etype: 'mesh', username: user.name, userid: (deluserid.split('/')[2]), meshid: mesh._id, name: mesh.name, mtype: mesh.mtype, desc: mesh.desc, action: 'meshchange', links: mesh.links, msg: 'Removed user ' + (deluserid.split('/')[2]) + ' from group ' + mesh.name, domain: domain.id }); + } } } break; @@ -1565,5 +1618,25 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use function EscapeHtml(x) { if (typeof x == "string") return x.replace(/&/g, '&').replace(/>/g, '>').replace(//g, '>').replace(/').replace(/\n/g, '').replace(/\t/g, '  '); if (typeof x == "boolean") return x; if (typeof x == "number") return x; } + // Split a string taking into account the quoats. Used for command line parsing + function splitArgs(str) { var myArray = [], myRegexp = /[^\s"]+|"([^"]*)"/gi; do { var match = myRegexp.exec(str); if (match != null) { myArray.push(match[1] ? match[1] : match[0]); } } while (match != null); return myArray; } + function toNumberIfNumber(x) { if ((typeof x == 'string') && (+parseInt(x) === x)) { x = parseInt(x); } return x; } + + // Parse arguments string array into an object + function parseArgs(argv) { + var results = { '_': [] }, current = null; + for (var i = 1, len = argv.length; i < len; i++) { + var x = argv[i]; + if (x.length > 2 && x[0] == '-' && x[1] == '-') { + if (current != null) { results[current] = true; } + current = x.substring(2); + } else { + if (current != null) { results[current] = toNumberIfNumber(x); current = null; } else { results['_'].push(toNumberIfNumber(x)); } + } + } + if (current != null) { results[current] = true; } + return results; + } + return obj; }; \ No newline at end of file diff --git a/public/scripts/agent-desktop-0.0.2.js b/public/scripts/agent-desktop-0.0.2.js index 7558892d..166393f3 100644 --- a/public/scripts/agent-desktop-0.0.2.js +++ b/public/scripts/agent-desktop-0.0.2.js @@ -51,9 +51,11 @@ var CreateAgentRemoteDesktop = function (canvasid, scrolldiv) { obj.onDebugMessage = null; obj.onTouchEnabledChanged = null; obj.onDisplayinfo = null; + obj.accumulator = null; obj.Start = function () { obj.State = 0; + obj.accumulator = null; } obj.Stop = function () { @@ -178,6 +180,11 @@ var CreateAgentRemoteDesktop = function (canvasid, scrolldiv) { } obj.ProcessDataEx = function (str) { + if (obj.accumulator != null) { + str = obj.accumulator + str; + console.log('KVM using accumulated data, total size is now ' + str.length + ' bytes.'); + obj.accumulator = null; + } if (obj.debugmode > 1) { console.log("KRecv(" + str.length + "): " + rstr2hex(str.substring(0, Math.min(str.length, 40)))); } if (str.length < 4) return; var cmdmsg = null, X = 0, Y = 0, command = ReadShort(str, 0), cmdsize = ReadShort(str, 2), jumboAdd = 0; @@ -186,14 +193,23 @@ var CreateAgentRemoteDesktop = function (canvasid, scrolldiv) { if (str.length < 12) return; command = ReadShort(str, 8) cmdsize = ReadInt(str, 4); + console.log('JUMBO cmd=' + command + ', cmdsize=' + cmdsize + ', data received=' + str.length); + if ((cmdsize + 8) > str.length) { + console.log('KVM accumulator set to ' + str.length + ' bytes, need ' + cmdsize + ' bytes.'); + obj.accumulator = str; + return; + } str = str.substring(8); jumboAdd = 8; - //console.log('JUMBO', command, cmdsize, str.length); } if ((cmdsize != str.length) && (obj.debugmode > 0)) { console.log(cmdsize, str.length, cmdsize == str.length); } if ((command >= 18) && (command != 65)) { console.error("Invalid KVM command " + command + " of size " + cmdsize); console.log("Invalid KVM data", str.length, str, rstr2hex(str)); return; } - if (cmdsize > str.length) { console.error("KVM invalid command size", cmdsize, str.length); return; } - //meshOnDebug("KVM Command: " + command + " Len:" + cmdsize); + if (cmdsize > str.length) { + console.log('KVM accumulator set to ' + str.length + ' bytes, need ' + cmdsize + ' bytes.'); + obj.accumulator = str; + return; + } + //console.log("KVM Command: " + command + " Len:" + cmdsize); if (command == 3 || command == 4 || command == 7) { cmdmsg = str.substring(4, cmdsize); diff --git a/public/scripts/agent-redir-ws-0.1.0.js b/public/scripts/agent-redir-ws-0.1.0.js index 059d2f79..e8b8f089 100644 --- a/public/scripts/agent-redir-ws-0.1.0.js +++ b/public/scripts/agent-redir-ws-0.1.0.js @@ -99,7 +99,7 @@ var CreateAgentRedirect = function (meshserver, module, serverPublicNamePort, au obj.webchannel = obj.webrtc.createDataChannel("DataChannel", {}); // { ordered: false, maxRetransmits: 2 } obj.webchannel.onmessage = function (event) { obj.xxOnMessage({ data: event.data }); }; obj.webchannel.onopen = function () { obj.webRtcActive = true; performWebRtcSwitch(); }; - obj.webchannel.onclose = function (event) { /*console.log('WebRTC close');*/ if (obj.webRtcActive) { obj.Stop(); } } + obj.webchannel.onclose = function (event) { if (obj.webRtcActive) { obj.Stop(); } } obj.webrtc.onicecandidate = function (e) { if (e.candidate == null) { try { obj.socket.send(JSON.stringify(obj.webrtcoffer)); } catch (ex) { } // End of candidates, send the offer diff --git a/views/default-min.handlebars b/views/default-min.handlebars index 5b837a6d..bb08c0bc 100644 --- a/views/default-min.handlebars +++ b/views/default-min.handlebars @@ -1 +1 @@ - MeshCentral
{{{title}}}
{{{title2}}}

{{{logoutControl}}}

 

\ No newline at end of file + MeshCentral
{{{title}}}
{{{title2}}}

{{{logoutControl}}}

 

\ No newline at end of file diff --git a/views/default-mobile-min.handlebars b/views/default-mobile-min.handlebars index f646ef07..1a94d0e8 100644 --- a/views/default-mobile-min.handlebars +++ b/views/default-mobile-min.handlebars @@ -1 +1 @@ - MeshCentral
{{{title}}}
{{{title2}}}
\ No newline at end of file + MeshCentral
{{{title}}}
{{{title2}}}
\ No newline at end of file diff --git a/views/default.handlebars b/views/default.handlebars index b5294b5d..37558eeb 100644 --- a/views/default.handlebars +++ b/views/default.handlebars @@ -136,6 +136,15 @@ +
@@ -604,7 +613,7 @@
 
@@ -1334,6 +1343,10 @@ } break; } + case 'serverconsole': { + p15consoleReceive('serverconsole', message.value); + break; + } case 'events': { if ((message.nodeid != null) && (message.nodeid == currentNode._id)) { currentDeviceEvents = message.events; @@ -1676,7 +1689,7 @@ function ondockeypress(e) { if (!xxdialogMode && xxcurrentView == 11 && desktop && Q("DeskControl").checked) return desktop.m.handleKeys(e); if (!xxdialogMode && xxcurrentView == 12 && terminal && terminal.State == 3) return terminal.m.TermHandleKeys(e); - if (!xxdialogMode && xxcurrentView == 15) return agentConsoleHandleKeys(e); + if (!xxdialogMode && ((xxcurrentView == 15) || (xxcurrentView == 115))) return agentConsoleHandleKeys(e); if (!xxdialogMode && xxcurrentView == 4) { if (e.ctrlKey == true || e.altKey == true || e.metaKey == true) return; var processed = 0; @@ -1725,7 +1738,7 @@ if (!xxdialogMode && xxcurrentView == 11 && desktop && Q("DeskControl").checked) { return desktop.m.handleKeyDown(e); } if (!xxdialogMode && xxcurrentView == 12 && terminal && terminal.State == 3) { return terminal.m.TermHandleKeyDown(e); } if (!xxdialogMode && xxcurrentView == 13 && e.keyCode == 116 && p13filetree != null) { haltEvent(e); return false; } // F5 Refresh on files - if (!xxdialogMode && xxcurrentView == 15) { return agentConsoleHandleKeys(e); } + if (!xxdialogMode && ((xxcurrentView == 15) || (xxcurrentView == 115))) { return agentConsoleHandleKeys(e); } if (!xxdialogMode && xxcurrentView == 4) { if (e.keyCode === 8 && userSearchFocus == 0) { var x = Q('UserSearchInput').value; Q('UserSearchInput').value = (x.substring(0, x.length - 1)); processed = 1; } if (e.keyCode === 27) { Q('UserSearchInput').value = ''; processed = 1; } @@ -3209,7 +3222,7 @@ QH('p12deviceName', nname); QH('p13deviceName', nname); QH('p14deviceName', nname); - QH('p15deviceName', nname); + QH('p15deviceName', 'Console - ' + nname); QH('p16deviceName', nname); // Node attributes @@ -5022,27 +5035,43 @@ } var consoleNode; + var consoleServerText = ''; function setupConsole() { - // Setup the console - var samenode = (consoleNode == currentNode); - consoleNode = currentNode; + if (xxcurrentView == 115) { + // Setup server console + var samenode = (consoleNode == 'server'); + consoleNode = 'server'; + + QH('p15deviceName', 'My Server Console'); + QH('p15statetext', ''); + QH('p15coreName', ''); - var mesh = meshes[consoleNode.meshid]; - var meshrights = mesh.links['user/' + domain + '/' + userinfo.name.toLowerCase()].rights; - if ((meshrights & 16) != 0) { - if (consoleNode.consoleText == null) { consoleNode.consoleText = ''; } if (samenode == false) { - QH('p15agentConsoleText', consoleNode.consoleText); + QH('p15agentConsoleText', consoleServerText); Q('p15agentConsoleText').scrollTop = Q('p15agentConsoleText').scrollHeight; } - var online = ((consoleNode.conn & 1) != 0)?true:false; - QH('p15statetext', online?"Agent is online":"Agent is offline"); - QE('p15consoleText', online); - QE('p15uploadCore', online); } else { - QH('p15statetext', 'Access Denied'); - QE('p15consoleText', false); - QE('p15uploadCore', false); + // Setup the console + var samenode = (consoleNode == currentNode); + consoleNode = currentNode; + + var mesh = meshes[consoleNode.meshid]; + var meshrights = mesh.links['user/' + domain + '/' + userinfo.name.toLowerCase()].rights; + if ((meshrights & 16) != 0) { + if (consoleNode.consoleText == null) { consoleNode.consoleText = ''; } + if (samenode == false) { + QH('p15agentConsoleText', consoleNode.consoleText); + Q('p15agentConsoleText').scrollTop = Q('p15agentConsoleText').scrollHeight; + } + var online = ((consoleNode.conn & 1) != 0) ? true : false; + QH('p15statetext', online ? "Agent is online" : "Agent is offline"); + QE('p15consoleText', online); + QE('p15uploadCore', online); + } else { + QH('p15statetext', 'Access Denied'); + QE('p15consoleText', false); + QE('p15uploadCore', false); + } } } @@ -5050,7 +5079,11 @@ function p15consoleClear() { QH('p15agentConsoleText', ''); Q('id_p15consoleClear').blur(); - consoleNode.consoleText = ''; + if (xxcurrentView == 115) { + consoleServerText = ''; + } else { + consoleNode.consoleText = ''; + } } // Send a command to the agent @@ -5059,12 +5092,18 @@ if (e && e.keyCode != 13) return; var v = Q('p15consoleText').value, t = '
> ' + EscapeHtml(Q('p15consoleText').value) + '
'; Q('p15agentConsoleText').innerHTML += t; - consoleNode.consoleText += t; Q('p15agentConsoleText').scrollTop = Q('p15agentConsoleText').scrollHeight; Q('p15consoleText').value = ''; - // Send the command to the mesh agent - meshserver.send({ action: 'msg', type:'console', nodeid: consoleNode._id, value: v }); + if (xxcurrentView == 115) { + // Send the command to the server - TODO: In the future, we may support multiple servers. + consoleServerText += t; + meshserver.send({ action: 'serverconsole', value: v }); + } else { + // Send the command to the mesh agent + consoleNode.consoleText += t; + meshserver.send({ action: 'msg', type: 'console', nodeid: consoleNode._id, value: v }); + } // Add command to history list if (v.length > 0) { @@ -5079,10 +5118,20 @@ // Handle Mesh Agent console data function p15consoleReceive(node, data) { data = '
' + data + '
' - if (node.consoleText == null) { node.consoleText = data; } else { node.consoleText += data; } - if (consoleNode == node) { - Q('p15agentConsoleText').innerHTML += data; - Q('p15agentConsoleText').scrollTop = Q('p15agentConsoleText').scrollHeight; + if (node === 'serverconsole') { + // Server console data + consoleServerText += data; + if (consoleNode == 'server') { + Q('p15agentConsoleText').innerHTML += data; + Q('p15agentConsoleText').scrollTop = Q('p15agentConsoleText').scrollHeight; + } + } else { + // Agent console data + if (node.consoleText == null) { node.consoleText = data; } else { node.consoleText += data; } + if (consoleNode == node) { + Q('p15agentConsoleText').innerHTML += data; + Q('p15agentConsoleText').scrollTop = Q('p15agentConsoleText').scrollHeight; + } } } @@ -6627,8 +6676,8 @@ if (x == 5) { Q('LeftMenuMyFiles').classList.add('lbbuttonsel', 'lbbuttonsel2'); } // My Server - QS('MainMenuMyServer').backgroundColor = ((x == 6) ? "#003366" : "#808080"); - if (x == 6) { Q('LeftMenuMyServer').classList.add('lbbuttonsel', 'lbbuttonsel2'); } + QS('MainMenuMyServer').backgroundColor = (((x == 6) || (x == 115)) ? "#003366" : "#808080"); + if (((x == 6) || (x == 115))) { Q('LeftMenuMyServer').classList.add('lbbuttonsel', 'lbbuttonsel2'); } // column_l max-height if (webPageFullScreen) { @@ -6644,16 +6693,23 @@ } QV('MainSubMenuSpan', x >= 10 && x < 20); - QV('UserDummyMenuSpan', (x < 10) && webPageFullScreen); + QV('UserDummyMenuSpan', (x < 10) && (x != 6) && webPageFullScreen); QV('MeshSubMenuSpan', x >= 20 && x < 30); QV('UserSubMenuSpan', x >= 30 && x < 40); - var panels = { 10: 'MainDev', 11: 'MainDevDesktop', 12: 'MainDevTerminal', 13: 'MainDevFiles', 14: 'MainDevAmt', 15: 'MainDevConsole', 20: 'MeshGeneral', 30: 'UserGeneral', 31: 'UserEvents' }; + QV('ServerSubMenuSpan', x == 6 || x == 115); + var panels = { 10: 'MainDev', 11: 'MainDevDesktop', 12: 'MainDevTerminal', 13: 'MainDevFiles', 14: 'MainDevAmt', 15: 'MainDevConsole', 20: 'MeshGeneral', 30: 'UserGeneral', 31: 'UserEvents', 6: 'ServerGeneral', 115: 'ServerConsole' }; for (var i in panels) { Q(panels[i]).classList.remove('style3x'); Q(panels[i]).classList.remove('style3sel'); Q(panels[i]).classList.add((x == i) ? 'style3sel' : 'style3x'); } + // Panel 115 is weird, it's panel 15 for device console but used as a server console. + if (x == 115) { QV('p15', true); } + QV('p15uploadCore', x != 115); + QV('p15BackButton', x != 115); + if ((x == 15) || (x == 115)) { setupConsole(); } + if (x == 1) masterUpdate(4); // Update the web page title