From 3b2e78cddf98becf94a5102d3d4c3e5a28ee7b6d Mon Sep 17 00:00:00 2001 From: Ylian Saint-Hilaire Date: Wed, 16 Jan 2019 12:04:48 -0800 Subject: [PATCH] Improved user handling with domain auth, email validation. --- agents/meshcore.min.js | 2 +- .../modules_meshcmd_min/user-sessions.min.js | 2 +- .../modules_meshcore_min/user-sessions.min.js | 2 +- meshuser.js | 21 +++--- package.json | 2 +- views/default-min.handlebars | 2 +- views/default-mobile-min.handlebars | 2 +- views/default-mobile.handlebars | 73 +++++++++++++++++-- views/default.handlebars | 17 +++-- views/login-min.handlebars | 2 +- views/login-mobile-min.handlebars | 2 +- webserver.js | 49 ++++++++----- 12 files changed, 128 insertions(+), 48 deletions(-) diff --git a/agents/meshcore.min.js b/agents/meshcore.min.js index dddd9f87..a0da13e1 100644 --- a/agents/meshcore.min.js +++ b/agents/meshcore.min.js @@ -1 +1 @@ -process.on("uncaughtException",function(a){require("MeshAgent").SendCommand({action:"msg",type:"console",value:"uncaughtException1: "+a})});var MESHRIGHT_EDITMESH=1;var MESHRIGHT_MANAGEUSERS=2;var MESHRIGHT_MANAGECOMPUTERS=4;var MESHRIGHT_REMOTECONTROL=8;var MESHRIGHT_AGENTCONSOLE=16;var MESHRIGHT_SERVERFILES=32;var MESHRIGHT_WAKEDEVICE=64;var MESHRIGHT_SETNOTES=128;var MESHRIGHT_REMOTEVIEW=256;function createMeshCore(agent){var obj={};var meshCoreObj={action:"coreinfo",value:"MeshCore v6",caps:14};try{require("os").name().then(function(v){meshCoreObj.osdesc=v})}catch(ex){}var meshServerConnectionState=0;var tunnels={};var lastMeInfo=null;var lastNetworkInfo=null;var lastPublicLocationInfo=null;var selfInfoUpdateTimer=null;var http=require("http");var net=require("net");var fs=require("fs");var rtc=require("ILibWebRTC");var processManager=require("process-manager");var amtMei=null,amtLms=null,amtLmsState=0;var amtMeiConnected=0,amtMeiTmpState=null;var wifiScannerLib=null;var wifiScanner=null;var networkMonitor=null;var amtscanner=null;var nextTunnelIndex=1;var oswsstack=null;var osamtstack=null;if(agent==null){db=require("SimpleDataStore").Shared();sha=require("SHA256Stream");mesh=require("MeshAgent");childProcess=require("child_process");if(mesh.hasKVM==1){try{if((process.platform=="win32")||(process.platform=="darwin")||(require("monitor-info").kvm_x11_support)){meshCoreObj.caps|=1}}catch(ex){}}}else{meshCoreObj.value+="-NodeJS";meshCoreObj.caps=8;mesh=agent.getMeshApi()}try{var AMTScannerModule=require("amt-scanner");amtscanner=new AMTScannerModule()}catch(ex){amtscanner=null}var SMBiosTables=null;var SMBiosTablesRaw=null;try{var SMBiosModule=null;try{SMBiosModule=require("smbios")}catch(ex){}if(SMBiosModule!=null){SMBiosModule.get(function(data){if(data!=null){SMBiosTablesRaw=data;SMBiosTables=require("smbios").parse(data);if(mesh.isControlChannelConnected){mesh.SendCommand({action:"smbios",value:SMBiosTablesRaw})}if(SMBiosTables.amtInfo&&(SMBiosTables.amtInfo.AMT==true)){resetMei()}}})}}catch(ex){sendConsoleText(ex)}try{var wifiScannerLib=require("wifi-scanner");wifiScanner=new wifiScannerLib();wifiScanner.on("accessPoint",function(data){sendConsoleText(data)})}catch(ex){wifiScannerLib=null;wifiScanner=null}function resetMei(){try{var amtMeiLib=require("amt-mei");amtMei=new amtMeiLib();amtMei.on("error",function(e){amtMeiLib=null;amtMei=null;amtMeiConnected=-1;sendConsoleText("MEI Error.")});amtMeiConnected=2;sendPeriodicServerUpdate(1)}catch(ex){amtMeiLib=null;amtMei=null;amtMeiConnected=-1}}var getIpLocationDataExInProgress=false;var getIpLocationDataExCounts=[0,0];function getIpLocationDataEx(func){if(getIpLocationDataExInProgress==true){return false}try{getIpLocationDataExInProgress=true;getIpLocationDataExCounts[0]++;var options=http.parseUri("http://ipinfo.io/json");options.method="GET";http.request(options,function(resp){if(resp.statusCode==200){var geoData="";resp.data=function(geoipdata){geoData+=geoipdata};resp.end=function(){var location=null;try{if(typeof geoData=="string"){var result=JSON.parse(geoData);if(result.ip&&result.loc){location=result}}}catch(e){}if(func){getIpLocationDataExCounts[1]++;func(location)}}}else{func(null)}getIpLocationDataExInProgress=false}).end();return true}catch(e){return false}}function clearGatewayMac(str){if(str==null){return null}var x=JSON.parse(str);for(var i in x.netif){if(x.netif[i].gatewaymac){delete x.netif[i].gatewaymac}}return JSON.stringify(x)}function getIpLocationData(func){var publicLocationInfo=db.Get("publicLocationInfo");if(publicLocationInfo!=null){publicLocationInfo=JSON.parse(publicLocationInfo)}if(publicLocationInfo==null){getIpLocationDataEx(function(locationData){if(locationData!=null){publicLocationInfo={};publicLocationInfo.netInfoStr=lastNetworkInfo;publicLocationInfo.locationData=locationData;var x=db.Put("publicLocationInfo",JSON.stringify(publicLocationInfo));if(func){func(locationData)}}else{if(func){func(null)}}})}else{if(clearGatewayMac(publicLocationInfo.netInfoStr)==clearGatewayMac(lastNetworkInfo)){if(func){func(publicLocationInfo.locationData)}}else{getIpLocationDataEx(function(locationData){if(locationData!=null){publicLocationInfo={};publicLocationInfo.netInfoStr=lastNetworkInfo;publicLocationInfo.locationData=locationData;var x=db.Put("publicLocationInfo",JSON.stringify(publicLocationInfo));if(func){func(locationData)}}else{if(func){func(publicLocationInfo.locationData)}}})}}}if(!String.prototype.endsWith){String.prototype.endsWith=function(searchString,position){var subjectString=this.toString();if(typeof position!=="number"||!isFinite(position)||Math.floor(position)!==position||position>subjectString.length){position=subjectString.length}position-=searchString.length;var lastIndex=subjectString.lastIndexOf(searchString,position);return lastIndex!==-1&&lastIndex===position}}obj.path={join:function(){var x=[];for(var i in arguments){var w=arguments[i];if(w!=null){while(w.endsWith("/")||w.endsWith("\\")){w=w.substring(0,w.length-1)}if(i!=0){while(w.startsWith("/")||w.startsWith("\\")){w=w.substring(1)}}x.push(w)}}if(x.length==0){return"/"}return x.join("/")}};function toNumberIfNumber(x){if((typeof x=="string")&&(+parseInt(x)===x)){x=parseInt(x)}return x}function char2hex(i){return(i+256).toString(16).substr(-2).toUpperCase()}function rstr2hex(input){var r="",i;for(i=0;i8){return"[...]"}if(x==undefined){return"[undefined]"}if(typeof x=="string"){if(p==0){return x}return'"'+x+'"'}if(typeof x=="buffer"){return"[buffer]"}if(typeof x!="object"){return x}var r="{"+(ret?"\r\n":" ");for(var i in x){if(i!="_ObjectID"){r+=(addPad(p+2,pad)+i+": "+objToString(x[i],p+2,pad,ret)+(ret?"\r\n":" "))}}return r+addPad(p,pad)+"}"}function addPad(p,ret){var r="";for(var i=0;i2&&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}function getServerTargetUrl(path){var x=mesh.ServerUrl;if(x==null){return null}if(path==null){path=""}x=http.parseUri(x);if(x==null){return null}return x.protocol+"//"+x.host+":"+x.port+"/"+path}function getServerTargetUrlEx(url){if(url.substring(0,2)=="*/"){return getServerTargetUrl(url.substring(2))}return url}function sendWakeOnLan(hexMac){var count=0;try{var interfaces=require("os").networkInterfaces();var magic="FFFFFFFFFFFF";for(var x=1;x<=16;++x){magic+=hexMac}var magicbin=Buffer.from(magic,"hex");for(var adapter in interfaces){if(interfaces.hasOwnProperty(adapter)){for(var i=0;i0){sendNextBlock--;var buf=new Buffer(4096);var len=fs.readSync(this.filedownload.f,buf,4,4092,null);this.filedownload.ptr+=len;if(len<4092){buf.writeInt32BE(16777217,0);fs.closeSync(this.filedownload.f);delete this.filedownload;sendNextBlock=0}else{buf.writeInt32BE(16777216,0)}this.write(buf.slice(0,len+4))}break;case"upload":if(this.httprequest.uploadFile!=undefined){fs.closeSync(this.httprequest.uploadFile);this.httprequest.uploadFile=undefined}if(cmd.path==undefined){break}var filepath=cmd.name?obj.path.join(cmd.path,cmd.name):cmd.path;try{this.httprequest.uploadFile=fs.openSync(filepath,"wbN")}catch(e){this.write(new Buffer(JSON.stringify({action:"uploaderror",reqid:cmd.reqid})));break}this.httprequest.uploadFileid=cmd.reqid;if(this.httprequest.uploadFile){this.write(new Buffer(JSON.stringify({action:"uploadstart",reqid:this.httprequest.uploadFileid})))}break;case"copy":for(var i in cmd.names){var sc=obj.path.join(cmd.scpath,cmd.names[i]),ds=obj.path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds)}catch(e){}}}break;case"move":for(var i in cmd.names){var sc=obj.path.join(cmd.scpath,cmd.names[i]),ds=obj.path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds);fs.unlinkSync(sc)}catch(e){}}}break;default:break}}}}}}}function onTunnelWebRTCControlData(data){if(typeof data!="string"){return}var obj;try{obj=JSON.parse(data)}catch(e){sendConsoleText("Invalid control JSON on WebRTC: "+data);return}if(obj.type=="close"){try{this.close()}catch(e){}try{this.xrtc.close()}catch(e){}}}function onTunnelControlData(data,ws){var obj;if(ws==null){ws=this}if(typeof data=="string"){try{obj=JSON.parse(data)}catch(e){sendConsoleText("Invalid control JSON: "+data);return}}else{if(typeof data=="object"){obj=data}else{return}}if(obj.action){switch(obj.action){case"lock":try{if(process.platform=="win32"){var child=require("child_process");child.execFile(process.env.windir+"\\system32\\cmd.exe",["/c","RunDll32.exe user32.dll,LockWorkStation"],{type:1})}}catch(e){}break;default:break}return}if(obj.type=="close"){try{ws.close()}catch(e){}}else{if(obj.type=="webrtc0"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.httprequest._term.unpipe(ws)}else{ws.httprequest.process.stdout.unpipe(ws);ws.httprequest.process.stderr.unpipe(ws)}}else{if(ws.httprequest.protocol==2){ws.httprequest.desktop.kvm.unpipe(ws)}else{ws.rtcchannel.httprequest=ws.httprequest;ws.rtcchannel.removeAllListeners("data");ws.rtcchannel.on("data",onTunnelData)}}ws.write('{"ctrlChannel":"102938","type":"webrtc1"}')}else{if(obj.type=="webrtc1"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.unpipe(ws.httprequest._term);ws.rtcchannel.pipe(ws.httprequest._term,{dataTypeSkip:1})}else{ws.unpipe(ws.httprequest.process.stdin);ws.rtcchannel.pipe(ws.httprequest.process.stdin,{dataTypeSkip:1})}ws.resume()}else{if(ws.httprequest.protocol==2){ws.unpipe(ws.httprequest.desktop.kvm);try{ws.webrtc.rtcchannel.pipe(ws.httprequest.desktop.kvm,{dataTypeSkip:1,end:false})}catch(e){sendConsoleText("EX2")}ws.resume()}}ws.write('{"ctrlChannel":"102938","type":"webrtc2"}')}else{if(obj.type=="webrtc2"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.httprequest._term.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false})}else{ws.httprequest.process.stdout.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false});ws.httprequest.process.stderr.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false})}}else{if(ws.httprequest.protocol==2){ws.httprequest.desktop.kvm.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1})}}}else{if(obj.type=="offer"){ws.webrtc=rtc.createConnection();ws.webrtc.websocket=ws;ws.webrtc.on("connected",function(){});ws.webrtc.on("disconnected",function(){});ws.webrtc.on("dataChannel",function(rtcchannel){rtcchannel.xrtc=this;rtcchannel.websocket=this.websocket;this.rtcchannel=rtcchannel;this.websocket.rtcchannel=rtcchannel;this.websocket.rtcchannel.on("data",onTunnelWebRTCControlData);this.websocket.rtcchannel.on("end",function(){this.unpipe(this.websocket.desktop.kvm);this.websocket.httprequest.desktop.kvm.unpipe(this)});this.websocket.write('{"ctrlChannel":"102938","type":"webrtc0"}')});var sdp=null;try{sdp=ws.webrtc.setOffer(obj.sdp)}catch(ex){}if(sdp!=null){ws.write({type:"answer",ctrlChannel:"102938",sdp:sdp})}}}}}}}var consoleWebSockets={};var consoleHttpRequest=null;function consoleHttpResponse(response){response.data=function(data){sendConsoleText(rstr2hex(buf2rstr(data)),this.sessionid);consoleHttpRequest=null};response.close=function(){sendConsoleText("httprequest.response.close",this.sessionid);consoleHttpRequest=null}}function openUserDesktopUrl(url){var child=null;try{switch(process.platform){case"win32":child=require("child_process").execFile(process.env.windir+"\\system32\\cmd.exe",["/c","start",url],{type:childProcess.SpawnTypes.USER});break;case"linux":child=require("child_process").execFile("/usr/bin/xdg-open",["xdg-open",url],{type:require("child_process").SpawnTypes.DETACHED,uid:require("user-sessions").consoleUid()});break;case"darwin":child=require("child_process").execFile("/usr/bin/open",["open",url],{uid:require("user-sessions").consoleUid()});break;default:break}}catch(ex){}return child}function processConsoleCommand(cmd,args,rights,sessionid){try{var response=null;switch(cmd){case"help":response="Available commands: help, info, osinfo,args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock, users, sendcaps, openurl, amtreset, amtccm, amtdeactivate.";break;case"amtreset":resetMei();resetMicroLms();response="Done.";break;case"amtccm":if(amtMei==null){response="Intel AMT not supported."}else{if(args._.length!=1){response="Proper usage: amtccm (adminPassword)"}else{activeToCCM(args._[0])}}break;case"amtdeactivate":if(amtMei==null){response="Intel AMT not supported."}else{deactivateCCM()}break;case"openurl":if(args._.length!=1){response="Proper usage: openurl (url)"}else{if(openUserDesktopUrl(args._[0])==null){response="Failed."}else{response="Success."}}break;case"users":if(meshCoreObj.users==null){response="Active users are unknown."}else{response="Active Users: "+meshCoreObj.users.join(", ")+"."}require("user-sessions").enumerateUsers().then(function(u){for(var i in u){sendConsoleText(u[i])}});break;case"toast":if(process.platform=="win32"){if(args._.length<1){response='Proper usage: toast "message"'}else{require("toaster").Toast("MeshCentral",args._[0]);response="ok"}}else{response="Only supported on Windows."}break;case"setdebug":if(args._.length<1){response="Proper usage: setdebug (target), 0 = Disabled, 1 = StdOut, 2 = This Console, * = All Consoles, 4 = WebLog, 8 = Logfile"}else{if(args._[0]=="*"){console.setDestination(2)}else{console.setDestination(parseInt(args._[0]),sessionid)}}break;case"ps":processManager.getProcesses(function(plist){var x="";for(var i in plist){x+=i+", "+plist[i].cmd+((plist[i].user)?(", "+plist[i].user):"")+"\r\n"}sendConsoleText(x,sessionid)});break;case"kill":if((args._.length<1)){response="Proper usage: kill [pid]"}else{process.kill(parseInt(args._[0]));response="Killed process "+args._[0]+"."}break;case"smbios":if(SMBiosTables==null){response="SMBios tables not available."}else{response=objToString(SMBiosTables,0," ",true)}break;case"rawsmbios":if(SMBiosTablesRaw==null){response="SMBios tables not available."}else{response="";for(var i in SMBiosTablesRaw){var header=false;for(var j in SMBiosTablesRaw[i]){if(SMBiosTablesRaw[i][j].length>0){if(header==false){response+=("Table type #"+i+((require("smbios").smTableTypes[i]==null)?"":(", "+require("smbios").smTableTypes[i])))+"\r\n";header=true}response+=(" "+SMBiosTablesRaw[i][j].toString("hex"))+"\r\n"}}}}break;case"eval":if(args._.length<1){response='Proper usage: eval "JavaScript code"'}else{response=JSON.stringify(mesh.eval(args._[0]))}break;case"notify":if(args._.length!=1){response='Proper usage: notify "message" [--session]'}else{var notification={action:"msg",type:"notify",value:args._[0],tag:"console"};if(args.session){notification.sessionid=sessionid}mesh.SendCommand(notification);response="ok"}break;case"info":response="Current Core: "+meshCoreObj.value+".\r\nAgent Time: "+Date()+".\r\nUser Rights: 0x"+rights.toString(16)+".\r\nPlatform: "+process.platform+".\r\nCapabilities: "+meshCoreObj.caps+".\r\nServer URL: "+mesh.ServerUrl+".";if(amtLmsState>=0){response+="\r\nBuilt-in LMS: "+["Disabled","Connecting..","Connected"][amtLmsState]+"."}if(meshCoreObj.osdesc){response+="\r\nOS: "+meshCoreObj.osdesc+"."}response+="\r\nModules: "+addedModules.join(", ")+".";response+="\r\nServer Connection: "+mesh.isControlChannelConnected+", State: "+meshServerConnectionState+".";response+="\rlastMeInfo: "+lastMeInfo+".";var oldNodeId=db.Get("OldNodeId");if(oldNodeId!=null){response+="\r\nOldNodeID: "+oldNodeId+"."}if(process.platform!="win32"){response+="\r\nX11 support: "+require("monitor-info").kvm_x11_support+"."}break;case"osinfo":var i=1;if(args._.length>0){i=parseInt(args._[0]);if(i>8){i=8}response="Calling "+i+" times."}for(var j=0;j0){meshCoreObj.osdesc=args._[0];mesh.SendCommand(meshCoreObj);response=JSON.stringify(meshCoreObj)}else{response="Proper usage: sendosdesc [os description]"}break;case"args":response="args "+objToString(args,0," ",true);break;case"print":var r=[];for(var i in args._){r.push(args._[i])}console.log(r.join(" "));response="Message printed on agent console.";break;case"type":if(args._.length==0){response="Proper usage: type (filepath) [maxlength]"}else{var max=4096;if((args._.length>1)&&(typeof args._[1]=="number")){max=args._[1]}if(max>4096){max=4096}var buf=Buffer.alloc(max),fd=fs.openSync(args._[0],"r"),r=fs.readSync(fd,buf,0,max);response=buf.toString();var i=response.indexOf("\n");if((i>0)&&(response[i-1]!="\r")){response=response.split("\n").join("\r\n")}if(r==max){response+="..."}fs.closeSync(fd)}break;case"dbkeys":response=JSON.stringify(db.Keys);break;case"dbget":if(db==null){response="Database not accessible.";break}if(args._.length!=1){response="Proper usage: dbget (key)"}else{response=db.Get(args._[0])}break;case"dbset":if(db==null){response="Database not accessible.";break}if(args._.length!=2){response="Proper usage: dbset (key) (value)"}else{var r=db.Put(args._[0],args._[1]);response="Key set: "+r}break;case"dbcompact":if(db==null){response="Database not accessible.";break}var r=db.Compact();response="Database compacted: "+r;break;case"httpget":if(consoleHttpRequest!=null){response="HTTP operation already in progress."}else{if(args._.length!=1){response="Proper usage: httpget (url)"}else{var options=http.parseUri(args._[0]);options.method="GET";if(options==null){response="Invalid url."}else{try{consoleHttpRequest=http.request(options,consoleHttpResponse)}catch(e){response="Invalid HTTP GET request"}consoleHttpRequest.sessionid=sessionid;if(consoleHttpRequest!=null){consoleHttpRequest.end();response="HTTPGET "+options.protocol+"//"+options.host+":"+options.port+options.path}}}}break;case"wslist":response="";for(var i in consoleWebSockets){var httprequest=consoleWebSockets[i];response+="Websocket #"+i+", "+httprequest.url+"\r\n"}if(response==""){response="no websocket sessions."}break;case"wsconnect":if(args._.length==0){response="Proper usage: wsconnect (url)\r\nFor example: wsconnect wss://localhost:443/meshrelay.ashx?id=abc"}else{var httprequest=null;try{var options=http.parseUri(args._[0]);options.rejectUnauthorized=0;httprequest=http.request(options)}catch(e){response="Invalid HTTP websocket request"}if(httprequest!=null){httprequest.upgrade=onWebSocketUpgrade;httprequest.onerror=function(e){sendConsoleText("ERROR: "+JSON.stringify(e))};var index=1;while(consoleWebSockets[index]){index++}httprequest.sessionid=sessionid;httprequest.index=index;httprequest.url=args._[0];consoleWebSockets[index]=httprequest;response="New websocket session #"+index}}break;case"wssend":if(args._.length==0){response="Proper usage: wssend (socketnumber)\r\n";for(var i in consoleWebSockets){var httprequest=consoleWebSockets[i];response+="Websocket #"+i+", "+httprequest.url+"\r\n"}}else{var i=parseInt(args._[0]);var httprequest=consoleWebSockets[i];if(httprequest!=undefined){httprequest.s.write(args._[1]);response="ok"}else{response="Invalid web socket number"}}break;case"wsclose":if(args._.length==0){response="Proper usage: wsclose (socketnumber)"}else{var i=parseInt(args._[0]);var httprequest=consoleWebSockets[i];if(httprequest!=undefined){if(httprequest.s!=null){httprequest.s.end()}else{httprequest.end()}response="ok"}else{response="Invalid web socket number"}}break;case"tunnels":response="";for(var i in tunnels){response+="Tunnel #"+i+", "+tunnels[i].url+"\r\n"}if(response==""){response="No websocket sessions."}break;case"ls":response="";var xpath="*";if(args._.length>0){xpath=obj.path.join(args._[0],"*")}response="List of "+xpath+"\r\n";var results=fs.readdirSync(xpath);for(var i=0;i0){var r="",pstates=["NotActivated","InActivation","Activated"];for(var i in data){var x=data[i];if(r!=""){r+="\r\n"}r+=x.address+" - Intel AMT v"+x.majorVersion+"."+x.minorVersion;if(x.provisioningState<3){r+=(", "+pstates[x.provisioningState])}if(x.provisioningState==2){r+=(", "+x.openPorts.join(", "))}r+="."}}else{r="No Intel AMT found."}sendConsoleText(r)})}}else{response="Intel AMT scanner module not present."}break;case"modules":response=JSON.stringify(addedModules);break;default:response='Unknown command "'+cmd+'", type "help" for list of avaialble commands.';break}}catch(e){response="Command returned an exception error: "+e;console.log(e)}if(response!=null){sendConsoleText(response,sessionid)}}function sendConsoleText(text,sessionid){if(typeof text=="object"){text=JSON.stringify(text)}mesh.SendCommand({action:"msg",type:"console",value:text,sessionid:sessionid})}function handleServerConnection(state){meshServerConnectionState=state;if(meshServerConnectionState==0){if(selfInfoUpdateTimer!=null){clearInterval(selfInfoUpdateTimer);selfInfoUpdateTimer=null}lastSelfInfo=null}else{var oldNodeId=db.Get("OldNodeId");if(oldNodeId!=null){mesh.SendCommand({action:"mc1migration",oldnodeid:oldNodeId})}mesh.SendCommand(meshCoreObj);if(SMBiosTablesRaw!=null){mesh.SendCommand({action:"smbios",value:SMBiosTablesRaw})}meInfoStr=null;sendPeriodicServerUpdate()}}var sendNetworkUpdateNagleTimer=null;function sendNetworkUpdateNagle(){if(sendNetworkUpdateNagleTimer!=null){clearTimeout(sendNetworkUpdateNagleTimer);sendNetworkUpdateNagleTimer=null}sendNetworkUpdateNagleTimer=setTimeout(sendNetworkUpdate,5000)}function sendNetworkUpdate(force){sendNetworkUpdateNagleTimer=null;var netInfo=mesh.NetInfo;netInfo.action="netinfo";var netInfoStr=JSON.stringify(netInfo);if((force==true)||(clearGatewayMac(netInfoStr)!=clearGatewayMac(lastNetworkInfo))){mesh.SendCommand(netInfo);lastNetworkInfo=netInfoStr}}function sendPeriodicServerUpdate(flags){if(meshServerConnectionState==0){return}if(!flags){flags=4294967295}if(flags&1){getAmtInfo(function(meinfo){try{if(meinfo==null){return}var intelamt={},p=false;if(meinfo.Versions&&meinfo.Versions.AMT){intelamt.ver=meinfo.Versions.AMT;p=true}if(meinfo.ProvisioningState){intelamt.state=meinfo.ProvisioningState;p=true}if(meinfo.Flags){intelamt.flags=meinfo.Flags;p=true}if(meinfo.OsHostname){intelamt.host=meinfo.OsHostname;p=true}if(meinfo.UUID){intelamt.uuid=meinfo.UUID;p=true}if(p==true){var meInfoStr=JSON.stringify(intelamt);if(meInfoStr!=lastMeInfo){meshCoreObj.intelamt=intelamt;mesh.SendCommand(meshCoreObj);lastMeInfo=meInfoStr}}}catch(ex){}})}if(flags&2){sendNetworkUpdateNagle(false)}}function getAmtInfo(func){if(amtMei==null||amtMeiConnected!=2){if(func!=null){func(null)}return}try{amtMeiTmpState={Flags:0};amtMei.getProtocolVersion(function(result){if(result!=null){amtMeiTmpState.MeiVersion=result}});amtMei.getVersion(function(result){if(result){amtMeiTmpState.Versions={};for(var version in result.Versions){amtMeiTmpState.Versions[result.Versions[version].Description]=result.Versions[version].Version}}});amtMei.getProvisioningMode(function(result){if(result){amtMeiTmpState.ProvisioningMode=result.mode}});amtMei.getProvisioningState(function(result){if(result){amtMeiTmpState.ProvisioningState=result.state}});amtMei.getEHBCState(function(result){if((result!=null)&&(result.EHBC==true)){amtMeiTmpState.Flags+=1}});amtMei.getControlMode(function(result){if(result!=null){if(result.controlMode==1){amtMeiTmpState.Flags+=2}if(result.controlMode==2){amtMeiTmpState.Flags+=4}}});amtMei.getLanInterfaceSettings(0,function(result){if(result){amtMeiTmpState.net0=result}});amtMei.getLanInterfaceSettings(1,function(result){if(result){amtMeiTmpState.net1=result}});amtMei.getUuid(function(result){if((result!=null)&&(result.uuid!=null)){amtMeiTmpState.UUID=result.uuid}});amtMei.getDnsSuffix(function(result){if(result!=null){amtMeiTmpState.dns=result}if(func!=null){func(amtMeiTmpState)}})}catch(e){if(func!=null){func(null)}return}}function handleAmtNotification(notifyMsg){if((notifyMsg==null)||(notifyMsg.Body==null)||(notifyMsg.Body.MessageID==null)||(notifyMsg.Body.MessageArguments==null)){return null}var amtMessage=notifyMsg.Body.MessageID,amtMessageArg=notifyMsg.Body.MessageArguments[0],notify=null;switch(amtMessage){case"iAMT0050":if(amtMessageArg=="48"){notify="Intel® AMT Serial-over-LAN connected"}else{if(amtMessageArg=="49"){notify="Intel® AMT Serial-over-LAN disconnected"}}break;case"iAMT0052":if(amtMessageArg=="1"){notify="Intel® AMT KVM connected"}else{if(amtMessageArg=="2"){notify="Intel® AMT KVM disconnected"}}break;default:break}if(notify!=null){mesh.SendCommand({action:"msg",type:"notify",value:notify,tag:"general"})}}function resetMicroLms(){try{var lme_heci=require("amt-lme");amtLmsState=1;amtLms=new lme_heci();amtLms.on("error",function(e){amtLmsState=0;amtLms=null;sendConsoleText("LMS Error.");obj.setupMeiOsAdmin(null,1)});amtLms.on("connect",function(){amtLmsState=2;obj.setupMeiOsAdmin(null,2)});amtLms.on("notify",function(data,options,str,code){if(code=="iAMT0052-3"){obj.kvmGetData()}else{handleAmtNotification(data)}})}catch(e){amtLmsState=-1;amtLms=null}}obj.start=function(){mesh.AddCommandHandler(handleServerCommand);mesh.AddConnectHandler(handleServerConnection);resetMicroLms();try{var userSession=require("user-sessions");userSession.on("changed",function onUserSessionChanged(){userSession.enumerateUsers().then(function(users){var u=[],a=users.Active;for(var i=0;i=12)){obj.kvmGetData("skip");obj.kvmTempTimer=setInterval(function(){obj.kvmGetData()},2000);obj.kvmSetData(JSON.stringify({action:"restart",ver:1}))}})})};obj.kvmGetData=function(tag){obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelRead(obj.kvmDataGetResponse,tag)};obj.kvmDataGetResponse=function(stack,name,response,status,tag){if((tag!="skip")&&(status==200)&&(response.Body.ReturnValue==0)){var val=null;try{val=Buffer.from(response.Body.DataMessage,"base64").toString()}catch(e){return}if(val!=null){obj.kvmProcessData(response.Body.RealmsBitmap,response.Body.MessageId,val)}}};var webRtcDesktop=null;obj.kvmProcessData=function(realms,messageId,val){var data=null;try{data=JSON.parse(val)}catch(e){}if((data!=null)&&(data.action)){if(data.action=="present"){obj.kvmSetData(JSON.stringify({action:"present",ver:1,platform:process.platform}))}if(data.action=="offer"){webRtcDesktop={};var rtc=require("ILibWebRTC");webRtcDesktop.webrtc=rtc.createConnection();webRtcDesktop.webrtc.on("connected",function(){});webRtcDesktop.webrtc.on("disconnected",function(){obj.webRtcCleanUp()});webRtcDesktop.webrtc.on("dataChannel",function(rtcchannel){webRtcDesktop.rtcchannel=rtcchannel;webRtcDesktop.kvm=mesh.getRemoteDesktopStream();webRtcDesktop.kvm.pipe(webRtcDesktop.rtcchannel,{dataTypeSkip:1,end:false});webRtcDesktop.rtcchannel.on("end",function(){obj.webRtcCleanUp()});webRtcDesktop.rtcchannel.on("data",function(x){obj.kvmCtrlData(this,x)});webRtcDesktop.rtcchannel.pipe(webRtcDesktop.kvm,{dataTypeSkip:1,end:false})});obj.kvmSetData(JSON.stringify({action:"answer",ver:1,sdp:webRtcDesktop.webrtc.setOffer(data.sdp)}))}}};var path={join:function(){var x=[];for(var i in arguments){var w=arguments[i];if(w!=null){while(w.endsWith("/")||w.endsWith("\\")){w=w.substring(0,w.length-1)}if(i!=0){while(w.startsWith("/")||w.startsWith("\\")){w=w.substring(1)}}x.push(w)}}if(x.length==0){return"/"}return x.join("/")}};obj.kvmCtrlData=function(channel,cmd){if(cmd.length>0&&cmd.charCodeAt(0)!=123){if(this.fileupload!=null){cmd=Buffer.from(cmd,"base64");var header=cmd.readUInt32BE(0);if((header==16777216)||(header==16777217)){fs.writeSync(this.fileupload.fp,cmd.slice(4));channel.write({action:"upload",sub:"ack",reqid:this.fileupload.reqid});if(header==16777217){fs.closeSync(this.fileupload.fp);this.fileupload=null}}}return}try{cmd=JSON.parse(cmd)}catch(ex){console.error("Invalid JSON: "+cmd);return}if((cmd.path!=null)&&(process.platform!="win32")&&(cmd.path[0]!="/")){cmd.path="/"+cmd.path}switch(cmd.action){case"ping":channel.write({action:"pong"});break;case"lock":if(process.platform=="win32"){var child=require("child_process");child.execFile(process.env.windir+"\\system32\\cmd.exe",["/c","RunDll32.exe user32.dll,LockWorkStation"],{type:1})}break;case"ls":var response=getDirectoryInfo(cmd.path);if(cmd.reqid!=undefined){response.reqid=cmd.reqid}channel.write(response);break;case"mkdir":fs.mkdirSync(cmd.path);break;case"rm":for(var i in cmd.delfiles){var fullpath=path.join(cmd.path,cmd.delfiles[i]);try{fs.unlinkSync(fullpath)}catch(e){console.log(e)}}break;case"rename":try{fs.renameSync(path.join(cmd.path,cmd.oldname),path.join(cmd.path,cmd.newname))}catch(e){console.log(e)}break;case"download":var sendNextBlock=0;if(cmd.sub=="start"){if(this.filedownload!=null){channel.write({action:"download",sub:"cancel",id:this.filedownload.id});delete this.filedownload}this.filedownload={id:cmd.id,path:cmd.path,ptr:0};try{this.filedownload.f=fs.openSync(this.filedownload.path,"rbN")}catch(e){channel.write({action:"download",sub:"cancel",id:this.filedownload.id});delete this.filedownload}if(this.filedownload){channel.write({action:"download",sub:"start",id:cmd.id})}}else{if((this.filedownload!=null)&&(cmd.id==this.filedownload.id)){if(cmd.sub=="startack"){sendNextBlock=8}else{if(cmd.sub=="stop"){delete this.filedownload}else{if(cmd.sub=="ack"){sendNextBlock=1}}}}}while(sendNextBlock>0){sendNextBlock--;var buf=Buffer.alloc(4096);var len=fs.readSync(this.filedownload.f,buf,4,4092,null);this.filedownload.ptr+=len;if(len<4092){buf.writeInt32BE(16777217,0);fs.closeSync(this.filedownload.f);delete this.filedownload;sendNextBlock=0}else{buf.writeInt32BE(16777216,0)}channel.write(buf.slice(0,len+4).toString("base64"))}break;case"upload":if(cmd.sub=="start"){if(this.fileupload!=null){fs.closeSync(this.fileupload.fp)}if(!cmd.path||!cmd.name){break}this.fileupload={reqid:cmd.reqid};var filepath=path.join(cmd.path,cmd.name);try{this.fileupload.fp=fs.openSync(filepath,"wbN")}catch(e){}if(this.fileupload.fp){channel.write({action:"upload",sub:"start",reqid:this.fileupload.reqid})}else{this.fileupload=null;channel.write({action:"upload",sub:"error",reqid:this.fileupload.reqid})}}else{if(cmd.sub=="cancel"){if(this.fileupload!=null){fs.closeSync(this.fileupload.fp);this.fileupload=null}}}break;case"copy":for(var i in cmd.names){var sc=path.join(cmd.scpath,cmd.names[i]),ds=path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds)}catch(e){}}}break;case"move":for(var i in cmd.names){var sc=path.join(cmd.scpath,cmd.names[i]),ds=path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds);fs.unlinkSync(sc)}catch(e){}}}break;default:console.log("Invalid KVM command",cmd);sendConsoleText("Invalid KVM command: "+cmd);break}};obj.webRtcCleanUp=function(){sendConsoleText("webRtcCleanUp");if(webRtcDesktop==null){return}if(webRtcDesktop.rtcchannel){try{webRtcDesktop.rtcchannel.close()}catch(e){}try{webRtcDesktop.rtcchannel.removeAllListeners("data")}catch(e){}try{webRtcDesktop.rtcchannel.removeAllListeners("end")}catch(e){}delete webRtcDesktop.rtcchannel}if(webRtcDesktop.webrtc){try{webRtcDesktop.webrtc.close()}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("connected")}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("disconnected")}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("dataChannel")}catch(e){}delete webRtcDesktop.webrtc}if(webRtcDesktop.kvm){try{webRtcDesktop.kvm.end()}catch(e){}delete webRtcDesktop.kvm}webRtcDesktop=null};obj.kvmSetData=function(x){obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelWrite(Buffer.from(x).toString("base64"),function(){})};function deleteFolderRecursive(path,rec){if(fs.existsSync(path)){if(rec==true){fs.readdirSync(obj.path.join(path,"*")).forEach(function(file,index){var curPath=obj.path.join(path,file);if(fs.statSync(curPath).isDirectory()){deleteFolderRecursive(curPath,true)}else{fs.unlinkSync(curPath)}})}fs.unlinkSync(path)}}function deactivateCCM(){amtMei.unprovision(1,function(status){if(status==0){sendConsoleText("Success deactivating Intel AMT CCM.")}else{sendConsoleText("Intel AMT CCM deactivation error: "+status)}})}function activeToCCM(adminpass){amtMei.getLocalSystemAccount(function(x){if(x.user&&x.pass){var transport=require("amt-wsman-duk");var wsman=require("amt-wsman");var amt=require("amt");oswsstack=new wsman(transport,"127.0.0.1",16992,x.user,x.pass,false);osamtstack=new amt(oswsstack);osamtstack.BatchEnum(null,["*AMT_GeneralSettings","*IPS_HostBasedSetupService"],activeToCCMEx2,adminpass)}else{sendConsoleText("Unable to get $$OsAdmin password.")}})}function activeToCCMEx2(stack,name,responses,status,adminpass){if(status!=200){sendConsoleText("Failed to fetch activation status, status "+status)}else{if(responses.IPS_HostBasedSetupService.response.AllowedControlModes.length!=2){sendConsoleText("Client control mode activation not allowed")}else{stack.IPS_HostBasedSetupService_Setup(2,md5hex("admin:"+responses.AMT_GeneralSettings.response.DigestRealm+":"+adminpass).substring(0,32),null,null,null,null,activeToCCMEx3)}}}function activeToCCMEx3(stack,name,responses,status){if(status!=200){sendConsoleText("Failed to activate, status "+status)}else{if(responses.Body.ReturnValue!=0){sendConsoleText("Client control mode activation failed: "+responses.Body.ReturnValueStr)}else{sendConsoleText("Intel AMT CCM activation success")}}}function md5hex(str){return require("MD5Stream").create().syncHash(str).toString("hex")}return obj}try{var xexports=null,mainMeshCore=null;try{xexports=module.exports}catch(e){}if(xexports!=null){module.exports.createMeshCore=createMeshCore}else{mainMeshCore=createMeshCore();mainMeshCore.start(null)}}catch(ex){require("MeshAgent").SendCommand({action:"msg",type:"console",value:"uncaughtException2: "+ex})}; \ No newline at end of file +process.on("uncaughtException",function(a){require("MeshAgent").SendCommand({action:"msg",type:"console",value:"uncaughtException1: "+a})});var MESHRIGHT_EDITMESH=1;var MESHRIGHT_MANAGEUSERS=2;var MESHRIGHT_MANAGECOMPUTERS=4;var MESHRIGHT_REMOTECONTROL=8;var MESHRIGHT_AGENTCONSOLE=16;var MESHRIGHT_SERVERFILES=32;var MESHRIGHT_WAKEDEVICE=64;var MESHRIGHT_SETNOTES=128;var MESHRIGHT_REMOTEVIEW=256;function createMeshCore(agent){var obj={};var meshCoreObj={action:"coreinfo",value:"MeshCore v6",caps:14};try{require("os").name().then(function(v){meshCoreObj.osdesc=v})}catch(ex){}var meshServerConnectionState=0;var tunnels={};var lastMeInfo=null;var lastNetworkInfo=null;var lastPublicLocationInfo=null;var selfInfoUpdateTimer=null;var http=require("http");var net=require("net");var fs=require("fs");var rtc=require("ILibWebRTC");var processManager=require("process-manager");var amtMei=null,amtLms=null,amtLmsState=0;var amtMeiConnected=0,amtMeiTmpState=null;var wifiScannerLib=null;var wifiScanner=null;var networkMonitor=null;var amtscanner=null;var nextTunnelIndex=1;var oswsstack=null;var osamtstack=null;if(agent==null){db=require("SimpleDataStore").Shared();sha=require("SHA256Stream");mesh=require("MeshAgent");childProcess=require("child_process");if(mesh.hasKVM==1){try{if((process.platform=="win32")||(process.platform=="darwin")||(require("monitor-info").kvm_x11_support)){meshCoreObj.caps|=1}}catch(ex){}}}else{meshCoreObj.value+="-NodeJS";meshCoreObj.caps=8;mesh=agent.getMeshApi()}try{var AMTScannerModule=require("amt-scanner");amtscanner=new AMTScannerModule()}catch(ex){amtscanner=null}var SMBiosTables=null;var SMBiosTablesRaw=null;try{var SMBiosModule=null;try{SMBiosModule=require("smbios")}catch(ex){}if(SMBiosModule!=null){SMBiosModule.get(function(data){if(data!=null){SMBiosTablesRaw=data;SMBiosTables=require("smbios").parse(data);if(mesh.isControlChannelConnected){mesh.SendCommand({action:"smbios",value:SMBiosTablesRaw})}if(SMBiosTables.amtInfo&&(SMBiosTables.amtInfo.AMT==true)){resetMei()}}})}}catch(ex){sendConsoleText(ex)}try{var wifiScannerLib=require("wifi-scanner");wifiScanner=new wifiScannerLib();wifiScanner.on("accessPoint",function(data){sendConsoleText(data)})}catch(ex){wifiScannerLib=null;wifiScanner=null}function resetMei(){try{var amtMeiLib=require("amt-mei");amtMei=new amtMeiLib();amtMei.on("error",function(e){amtMeiLib=null;amtMei=null;amtMeiConnected=-1;sendConsoleText("MEI Error.")});amtMeiConnected=2;sendPeriodicServerUpdate(1)}catch(ex){amtMeiLib=null;amtMei=null;amtMeiConnected=-1}}var getIpLocationDataExInProgress=false;var getIpLocationDataExCounts=[0,0];function getIpLocationDataEx(func){if(getIpLocationDataExInProgress==true){return false}try{getIpLocationDataExInProgress=true;getIpLocationDataExCounts[0]++;var options=http.parseUri("http://ipinfo.io/json");options.method="GET";http.request(options,function(resp){if(resp.statusCode==200){var geoData="";resp.data=function(geoipdata){geoData+=geoipdata};resp.end=function(){var location=null;try{if(typeof geoData=="string"){var result=JSON.parse(geoData);if(result.ip&&result.loc){location=result}}}catch(e){}if(func){getIpLocationDataExCounts[1]++;func(location)}}}else{func(null)}getIpLocationDataExInProgress=false}).end();return true}catch(e){return false}}function clearGatewayMac(str){if(str==null){return null}var x=JSON.parse(str);for(var i in x.netif){if(x.netif[i].gatewaymac){delete x.netif[i].gatewaymac}}return JSON.stringify(x)}function getIpLocationData(func){var publicLocationInfo=db.Get("publicLocationInfo");if(publicLocationInfo!=null){publicLocationInfo=JSON.parse(publicLocationInfo)}if(publicLocationInfo==null){getIpLocationDataEx(function(locationData){if(locationData!=null){publicLocationInfo={};publicLocationInfo.netInfoStr=lastNetworkInfo;publicLocationInfo.locationData=locationData;var x=db.Put("publicLocationInfo",JSON.stringify(publicLocationInfo));if(func){func(locationData)}}else{if(func){func(null)}}})}else{if(clearGatewayMac(publicLocationInfo.netInfoStr)==clearGatewayMac(lastNetworkInfo)){if(func){func(publicLocationInfo.locationData)}}else{getIpLocationDataEx(function(locationData){if(locationData!=null){publicLocationInfo={};publicLocationInfo.netInfoStr=lastNetworkInfo;publicLocationInfo.locationData=locationData;var x=db.Put("publicLocationInfo",JSON.stringify(publicLocationInfo));if(func){func(locationData)}}else{if(func){func(publicLocationInfo.locationData)}}})}}}if(!String.prototype.endsWith){String.prototype.endsWith=function(searchString,position){var subjectString=this.toString();if(typeof position!=="number"||!isFinite(position)||Math.floor(position)!==position||position>subjectString.length){position=subjectString.length}position-=searchString.length;var lastIndex=subjectString.lastIndexOf(searchString,position);return lastIndex!==-1&&lastIndex===position}}obj.path={join:function(){var x=[];for(var i in arguments){var w=arguments[i];if(w!=null){while(w.endsWith("/")||w.endsWith("\\")){w=w.substring(0,w.length-1)}if(i!=0){while(w.startsWith("/")||w.startsWith("\\")){w=w.substring(1)}}x.push(w)}}if(x.length==0){return"/"}return x.join("/")}};function toNumberIfNumber(x){if((typeof x=="string")&&(+parseInt(x)===x)){x=parseInt(x)}return x}function char2hex(i){return(i+256).toString(16).substr(-2).toUpperCase()}function rstr2hex(input){var r="",i;for(i=0;i8){return"[...]"}if(x==undefined){return"[undefined]"}if(typeof x=="string"){if(p==0){return x}return'"'+x+'"'}if(typeof x=="buffer"){return"[buffer]"}if(typeof x!="object"){return x}var r="{"+(ret?"\r\n":" ");for(var i in x){if(i!="_ObjectID"){r+=(addPad(p+2,pad)+i+": "+objToString(x[i],p+2,pad,ret)+(ret?"\r\n":" "))}}return r+addPad(p,pad)+"}"}function addPad(p,ret){var r="";for(var i=0;i2&&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}function getServerTargetUrl(path){var x=mesh.ServerUrl;if(x==null){return null}if(path==null){path=""}x=http.parseUri(x);if(x==null){return null}return x.protocol+"//"+x.host+":"+x.port+"/"+path}function getServerTargetUrlEx(url){if(url.substring(0,2)=="*/"){return getServerTargetUrl(url.substring(2))}return url}function sendWakeOnLan(hexMac){var count=0;try{var interfaces=require("os").networkInterfaces();var magic="FFFFFFFFFFFF";for(var x=1;x<=16;++x){magic+=hexMac}var magicbin=Buffer.from(magic,"hex");for(var adapter in interfaces){if(interfaces.hasOwnProperty(adapter)){for(var i=0;i0){sendNextBlock--;var buf=new Buffer(4096);var len=fs.readSync(this.filedownload.f,buf,4,4092,null);this.filedownload.ptr+=len;if(len<4092){buf.writeInt32BE(16777217,0);fs.closeSync(this.filedownload.f);delete this.filedownload;sendNextBlock=0}else{buf.writeInt32BE(16777216,0)}this.write(buf.slice(0,len+4))}break;case"upload":if(this.httprequest.uploadFile!=undefined){fs.closeSync(this.httprequest.uploadFile);this.httprequest.uploadFile=undefined}if(cmd.path==undefined){break}var filepath=cmd.name?obj.path.join(cmd.path,cmd.name):cmd.path;try{this.httprequest.uploadFile=fs.openSync(filepath,"wbN")}catch(e){this.write(new Buffer(JSON.stringify({action:"uploaderror",reqid:cmd.reqid})));break}this.httprequest.uploadFileid=cmd.reqid;if(this.httprequest.uploadFile){this.write(new Buffer(JSON.stringify({action:"uploadstart",reqid:this.httprequest.uploadFileid})))}break;case"copy":for(var i in cmd.names){var sc=obj.path.join(cmd.scpath,cmd.names[i]),ds=obj.path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds)}catch(e){}}}break;case"move":for(var i in cmd.names){var sc=obj.path.join(cmd.scpath,cmd.names[i]),ds=obj.path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds);fs.unlinkSync(sc)}catch(e){}}}break;default:break}}}}}}}function onTunnelWebRTCControlData(data){if(typeof data!="string"){return}var obj;try{obj=JSON.parse(data)}catch(e){sendConsoleText("Invalid control JSON on WebRTC: "+data);return}if(obj.type=="close"){try{this.close()}catch(e){}try{this.xrtc.close()}catch(e){}}}function onTunnelControlData(data,ws){var obj;if(ws==null){ws=this}if(typeof data=="string"){try{obj=JSON.parse(data)}catch(e){sendConsoleText("Invalid control JSON: "+data);return}}else{if(typeof data=="object"){obj=data}else{return}}if(obj.action){switch(obj.action){case"lock":try{if(process.platform=="win32"){var child=require("child_process");child.execFile(process.env.windir+"\\system32\\cmd.exe",["/c","RunDll32.exe user32.dll,LockWorkStation"],{type:1})}}catch(e){}break;default:break}return}if(obj.type=="close"){try{ws.close()}catch(e){}}else{if(obj.type=="webrtc0"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.httprequest._term.unpipe(ws)}else{ws.httprequest.process.stdout.unpipe(ws);ws.httprequest.process.stderr.unpipe(ws)}}else{if(ws.httprequest.protocol==2){ws.httprequest.desktop.kvm.unpipe(ws)}else{ws.rtcchannel.httprequest=ws.httprequest;ws.rtcchannel.removeAllListeners("data");ws.rtcchannel.on("data",onTunnelData)}}ws.write('{"ctrlChannel":"102938","type":"webrtc1"}')}else{if(obj.type=="webrtc1"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.unpipe(ws.httprequest._term);ws.rtcchannel.pipe(ws.httprequest._term,{dataTypeSkip:1})}else{ws.unpipe(ws.httprequest.process.stdin);ws.rtcchannel.pipe(ws.httprequest.process.stdin,{dataTypeSkip:1})}ws.resume()}else{if(ws.httprequest.protocol==2){ws.unpipe(ws.httprequest.desktop.kvm);try{ws.webrtc.rtcchannel.pipe(ws.httprequest.desktop.kvm,{dataTypeSkip:1,end:false})}catch(e){sendConsoleText("EX2")}ws.resume()}}ws.write('{"ctrlChannel":"102938","type":"webrtc2"}')}else{if(obj.type=="webrtc2"){if(ws.httprequest.protocol==1){if(process.platform=="win32"){ws.httprequest._term.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false})}else{ws.httprequest.process.stdout.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false});ws.httprequest.process.stderr.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1,end:false})}}else{if(ws.httprequest.protocol==2){ws.httprequest.desktop.kvm.pipe(ws.webrtc.rtcchannel,{dataTypeSkip:1})}}}else{if(obj.type=="offer"){ws.webrtc=rtc.createConnection();ws.webrtc.websocket=ws;ws.webrtc.on("connected",function(){});ws.webrtc.on("disconnected",function(){});ws.webrtc.on("dataChannel",function(rtcchannel){rtcchannel.xrtc=this;rtcchannel.websocket=this.websocket;this.rtcchannel=rtcchannel;this.websocket.rtcchannel=rtcchannel;this.websocket.rtcchannel.on("data",onTunnelWebRTCControlData);this.websocket.rtcchannel.on("end",function(){this.unpipe(this.websocket.desktop.kvm);this.websocket.httprequest.desktop.kvm.unpipe(this)});this.websocket.write('{"ctrlChannel":"102938","type":"webrtc0"}')});var sdp=null;try{sdp=ws.webrtc.setOffer(obj.sdp)}catch(ex){}if(sdp!=null){ws.write({type:"answer",ctrlChannel:"102938",sdp:sdp})}}}}}}}var consoleWebSockets={};var consoleHttpRequest=null;function consoleHttpResponse(response){response.data=function(data){sendConsoleText(rstr2hex(buf2rstr(data)),this.sessionid);consoleHttpRequest=null};response.close=function(){sendConsoleText("httprequest.response.close",this.sessionid);consoleHttpRequest=null}}function openUserDesktopUrl(url){var child=null;try{switch(process.platform){case"win32":child=require("child_process").execFile(process.env.windir+"\\system32\\cmd.exe",["/c","start",url],{type:childProcess.SpawnTypes.USER});break;case"linux":child=require("child_process").execFile("/usr/bin/xdg-open",["xdg-open",url],{uid:require("user-sessions").consoleUid()});break;case"darwin":child=require("child_process").execFile("/usr/bin/open",["open",url],{uid:require("user-sessions").consoleUid()});break;default:break}}catch(ex){}return child}function processConsoleCommand(cmd,args,rights,sessionid){try{var response=null;switch(cmd){case"help":response="Available commands: help, info, osinfo,args, print, type, dbget, dbset, dbcompact, eval, parseuri, httpget,\r\nwslist, wsconnect, wssend, wsclose, notify, ls, ps, kill, amt, netinfo, location, power, wakeonlan, scanwifi,\r\nscanamt, setdebug, smbios, rawsmbios, toast, lock, users, sendcaps, openurl, amtreset, amtccm, amtdeactivate.";break;case"amtreset":resetMei();resetMicroLms();response="Done.";break;case"amtccm":if(amtMei==null){response="Intel AMT not supported."}else{if(args._.length!=1){response="Proper usage: amtccm (adminPassword)"}else{activeToCCM(args._[0])}}break;case"amtdeactivate":if(amtMei==null){response="Intel AMT not supported."}else{deactivateCCM()}break;case"openurl":if(args._.length!=1){response="Proper usage: openurl (url)"}else{if(openUserDesktopUrl(args._[0])==null){response="Failed."}else{response="Success."}}break;case"users":if(meshCoreObj.users==null){response="Active users are unknown."}else{response="Active Users: "+meshCoreObj.users.join(", ")+"."}require("user-sessions").enumerateUsers().then(function(u){for(var i in u){sendConsoleText(u[i])}});break;case"toast":if(process.platform=="win32"){if(args._.length<1){response='Proper usage: toast "message"'}else{require("toaster").Toast("MeshCentral",args._[0]);response="ok"}}else{response="Only supported on Windows."}break;case"setdebug":if(args._.length<1){response="Proper usage: setdebug (target), 0 = Disabled, 1 = StdOut, 2 = This Console, * = All Consoles, 4 = WebLog, 8 = Logfile"}else{if(args._[0]=="*"){console.setDestination(2)}else{console.setDestination(parseInt(args._[0]),sessionid)}}break;case"ps":processManager.getProcesses(function(plist){var x="";for(var i in plist){x+=i+", "+plist[i].cmd+((plist[i].user)?(", "+plist[i].user):"")+"\r\n"}sendConsoleText(x,sessionid)});break;case"kill":if((args._.length<1)){response="Proper usage: kill [pid]"}else{process.kill(parseInt(args._[0]));response="Killed process "+args._[0]+"."}break;case"smbios":if(SMBiosTables==null){response="SMBios tables not available."}else{response=objToString(SMBiosTables,0," ",true)}break;case"rawsmbios":if(SMBiosTablesRaw==null){response="SMBios tables not available."}else{response="";for(var i in SMBiosTablesRaw){var header=false;for(var j in SMBiosTablesRaw[i]){if(SMBiosTablesRaw[i][j].length>0){if(header==false){response+=("Table type #"+i+((require("smbios").smTableTypes[i]==null)?"":(", "+require("smbios").smTableTypes[i])))+"\r\n";header=true}response+=(" "+SMBiosTablesRaw[i][j].toString("hex"))+"\r\n"}}}}break;case"eval":if(args._.length<1){response='Proper usage: eval "JavaScript code"'}else{response=JSON.stringify(mesh.eval(args._[0]))}break;case"notify":if(args._.length!=1){response='Proper usage: notify "message" [--session]'}else{var notification={action:"msg",type:"notify",value:args._[0],tag:"console"};if(args.session){notification.sessionid=sessionid}mesh.SendCommand(notification);response="ok"}break;case"info":response="Current Core: "+meshCoreObj.value+".\r\nAgent Time: "+Date()+".\r\nUser Rights: 0x"+rights.toString(16)+".\r\nPlatform: "+process.platform+".\r\nCapabilities: "+meshCoreObj.caps+".\r\nServer URL: "+mesh.ServerUrl+".";if(amtLmsState>=0){response+="\r\nBuilt-in LMS: "+["Disabled","Connecting..","Connected"][amtLmsState]+"."}if(meshCoreObj.osdesc){response+="\r\nOS: "+meshCoreObj.osdesc+"."}response+="\r\nModules: "+addedModules.join(", ")+".";response+="\r\nServer Connection: "+mesh.isControlChannelConnected+", State: "+meshServerConnectionState+".";response+="\rlastMeInfo: "+lastMeInfo+".";var oldNodeId=db.Get("OldNodeId");if(oldNodeId!=null){response+="\r\nOldNodeID: "+oldNodeId+"."}if(process.platform!="win32"){response+="\r\nX11 support: "+require("monitor-info").kvm_x11_support+"."}break;case"osinfo":var i=1;if(args._.length>0){i=parseInt(args._[0]);if(i>8){i=8}response="Calling "+i+" times."}for(var j=0;j0){meshCoreObj.osdesc=args._[0];mesh.SendCommand(meshCoreObj);response=JSON.stringify(meshCoreObj)}else{response="Proper usage: sendosdesc [os description]"}break;case"args":response="args "+objToString(args,0," ",true);break;case"print":var r=[];for(var i in args._){r.push(args._[i])}console.log(r.join(" "));response="Message printed on agent console.";break;case"type":if(args._.length==0){response="Proper usage: type (filepath) [maxlength]"}else{var max=4096;if((args._.length>1)&&(typeof args._[1]=="number")){max=args._[1]}if(max>4096){max=4096}var buf=Buffer.alloc(max),fd=fs.openSync(args._[0],"r"),r=fs.readSync(fd,buf,0,max);response=buf.toString();var i=response.indexOf("\n");if((i>0)&&(response[i-1]!="\r")){response=response.split("\n").join("\r\n")}if(r==max){response+="..."}fs.closeSync(fd)}break;case"dbkeys":response=JSON.stringify(db.Keys);break;case"dbget":if(db==null){response="Database not accessible.";break}if(args._.length!=1){response="Proper usage: dbget (key)"}else{response=db.Get(args._[0])}break;case"dbset":if(db==null){response="Database not accessible.";break}if(args._.length!=2){response="Proper usage: dbset (key) (value)"}else{var r=db.Put(args._[0],args._[1]);response="Key set: "+r}break;case"dbcompact":if(db==null){response="Database not accessible.";break}var r=db.Compact();response="Database compacted: "+r;break;case"httpget":if(consoleHttpRequest!=null){response="HTTP operation already in progress."}else{if(args._.length!=1){response="Proper usage: httpget (url)"}else{var options=http.parseUri(args._[0]);options.method="GET";if(options==null){response="Invalid url."}else{try{consoleHttpRequest=http.request(options,consoleHttpResponse)}catch(e){response="Invalid HTTP GET request"}consoleHttpRequest.sessionid=sessionid;if(consoleHttpRequest!=null){consoleHttpRequest.end();response="HTTPGET "+options.protocol+"//"+options.host+":"+options.port+options.path}}}}break;case"wslist":response="";for(var i in consoleWebSockets){var httprequest=consoleWebSockets[i];response+="Websocket #"+i+", "+httprequest.url+"\r\n"}if(response==""){response="no websocket sessions."}break;case"wsconnect":if(args._.length==0){response="Proper usage: wsconnect (url)\r\nFor example: wsconnect wss://localhost:443/meshrelay.ashx?id=abc"}else{var httprequest=null;try{var options=http.parseUri(args._[0]);options.rejectUnauthorized=0;httprequest=http.request(options)}catch(e){response="Invalid HTTP websocket request"}if(httprequest!=null){httprequest.upgrade=onWebSocketUpgrade;httprequest.onerror=function(e){sendConsoleText("ERROR: "+JSON.stringify(e))};var index=1;while(consoleWebSockets[index]){index++}httprequest.sessionid=sessionid;httprequest.index=index;httprequest.url=args._[0];consoleWebSockets[index]=httprequest;response="New websocket session #"+index}}break;case"wssend":if(args._.length==0){response="Proper usage: wssend (socketnumber)\r\n";for(var i in consoleWebSockets){var httprequest=consoleWebSockets[i];response+="Websocket #"+i+", "+httprequest.url+"\r\n"}}else{var i=parseInt(args._[0]);var httprequest=consoleWebSockets[i];if(httprequest!=undefined){httprequest.s.write(args._[1]);response="ok"}else{response="Invalid web socket number"}}break;case"wsclose":if(args._.length==0){response="Proper usage: wsclose (socketnumber)"}else{var i=parseInt(args._[0]);var httprequest=consoleWebSockets[i];if(httprequest!=undefined){if(httprequest.s!=null){httprequest.s.end()}else{httprequest.end()}response="ok"}else{response="Invalid web socket number"}}break;case"tunnels":response="";for(var i in tunnels){response+="Tunnel #"+i+", "+tunnels[i].url+"\r\n"}if(response==""){response="No websocket sessions."}break;case"ls":response="";var xpath="*";if(args._.length>0){xpath=obj.path.join(args._[0],"*")}response="List of "+xpath+"\r\n";var results=fs.readdirSync(xpath);for(var i=0;i0){var r="",pstates=["NotActivated","InActivation","Activated"];for(var i in data){var x=data[i];if(r!=""){r+="\r\n"}r+=x.address+" - Intel AMT v"+x.majorVersion+"."+x.minorVersion;if(x.provisioningState<3){r+=(", "+pstates[x.provisioningState])}if(x.provisioningState==2){r+=(", "+x.openPorts.join(", "))}r+="."}}else{r="No Intel AMT found."}sendConsoleText(r)})}}else{response="Intel AMT scanner module not present."}break;case"modules":response=JSON.stringify(addedModules);break;default:response='Unknown command "'+cmd+'", type "help" for list of avaialble commands.';break}}catch(e){response="Command returned an exception error: "+e;console.log(e)}if(response!=null){sendConsoleText(response,sessionid)}}function sendConsoleText(text,sessionid){if(typeof text=="object"){text=JSON.stringify(text)}mesh.SendCommand({action:"msg",type:"console",value:text,sessionid:sessionid})}function handleServerConnection(state){meshServerConnectionState=state;if(meshServerConnectionState==0){if(selfInfoUpdateTimer!=null){clearInterval(selfInfoUpdateTimer);selfInfoUpdateTimer=null}lastSelfInfo=null}else{var oldNodeId=db.Get("OldNodeId");if(oldNodeId!=null){mesh.SendCommand({action:"mc1migration",oldnodeid:oldNodeId})}mesh.SendCommand(meshCoreObj);if(SMBiosTablesRaw!=null){mesh.SendCommand({action:"smbios",value:SMBiosTablesRaw})}meInfoStr=null;sendPeriodicServerUpdate()}}var sendNetworkUpdateNagleTimer=null;function sendNetworkUpdateNagle(){if(sendNetworkUpdateNagleTimer!=null){clearTimeout(sendNetworkUpdateNagleTimer);sendNetworkUpdateNagleTimer=null}sendNetworkUpdateNagleTimer=setTimeout(sendNetworkUpdate,5000)}function sendNetworkUpdate(force){sendNetworkUpdateNagleTimer=null;var netInfo=mesh.NetInfo;netInfo.action="netinfo";var netInfoStr=JSON.stringify(netInfo);if((force==true)||(clearGatewayMac(netInfoStr)!=clearGatewayMac(lastNetworkInfo))){mesh.SendCommand(netInfo);lastNetworkInfo=netInfoStr}}function sendPeriodicServerUpdate(flags){if(meshServerConnectionState==0){return}if(!flags){flags=4294967295}if(flags&1){getAmtInfo(function(meinfo){try{if(meinfo==null){return}var intelamt={},p=false;if(meinfo.Versions&&meinfo.Versions.AMT){intelamt.ver=meinfo.Versions.AMT;p=true}if(meinfo.ProvisioningState){intelamt.state=meinfo.ProvisioningState;p=true}if(meinfo.Flags){intelamt.flags=meinfo.Flags;p=true}if(meinfo.OsHostname){intelamt.host=meinfo.OsHostname;p=true}if(meinfo.UUID){intelamt.uuid=meinfo.UUID;p=true}if(p==true){var meInfoStr=JSON.stringify(intelamt);if(meInfoStr!=lastMeInfo){meshCoreObj.intelamt=intelamt;mesh.SendCommand(meshCoreObj);lastMeInfo=meInfoStr}}}catch(ex){}})}if(flags&2){sendNetworkUpdateNagle(false)}}function getAmtInfo(func){if(amtMei==null||amtMeiConnected!=2){if(func!=null){func(null)}return}try{amtMeiTmpState={Flags:0};amtMei.getProtocolVersion(function(result){if(result!=null){amtMeiTmpState.MeiVersion=result}});amtMei.getVersion(function(result){if(result){amtMeiTmpState.Versions={};for(var version in result.Versions){amtMeiTmpState.Versions[result.Versions[version].Description]=result.Versions[version].Version}}});amtMei.getProvisioningMode(function(result){if(result){amtMeiTmpState.ProvisioningMode=result.mode}});amtMei.getProvisioningState(function(result){if(result){amtMeiTmpState.ProvisioningState=result.state}});amtMei.getEHBCState(function(result){if((result!=null)&&(result.EHBC==true)){amtMeiTmpState.Flags+=1}});amtMei.getControlMode(function(result){if(result!=null){if(result.controlMode==1){amtMeiTmpState.Flags+=2}if(result.controlMode==2){amtMeiTmpState.Flags+=4}}});amtMei.getLanInterfaceSettings(0,function(result){if(result){amtMeiTmpState.net0=result}});amtMei.getLanInterfaceSettings(1,function(result){if(result){amtMeiTmpState.net1=result}});amtMei.getUuid(function(result){if((result!=null)&&(result.uuid!=null)){amtMeiTmpState.UUID=result.uuid}});amtMei.getDnsSuffix(function(result){if(result!=null){amtMeiTmpState.dns=result}if(func!=null){func(amtMeiTmpState)}})}catch(e){if(func!=null){func(null)}return}}function handleAmtNotification(notifyMsg){if((notifyMsg==null)||(notifyMsg.Body==null)||(notifyMsg.Body.MessageID==null)||(notifyMsg.Body.MessageArguments==null)){return null}var amtMessage=notifyMsg.Body.MessageID,amtMessageArg=notifyMsg.Body.MessageArguments[0],notify=null;switch(amtMessage){case"iAMT0050":if(amtMessageArg=="48"){notify="Intel® AMT Serial-over-LAN connected"}else{if(amtMessageArg=="49"){notify="Intel® AMT Serial-over-LAN disconnected"}}break;case"iAMT0052":if(amtMessageArg=="1"){notify="Intel® AMT KVM connected"}else{if(amtMessageArg=="2"){notify="Intel® AMT KVM disconnected"}}break;default:break}if(notify!=null){mesh.SendCommand({action:"msg",type:"notify",value:notify,tag:"general"})}}function resetMicroLms(){try{var lme_heci=require("amt-lme");amtLmsState=1;amtLms=new lme_heci();amtLms.on("error",function(e){amtLmsState=0;amtLms=null;sendConsoleText("LMS Error.");obj.setupMeiOsAdmin(null,1)});amtLms.on("connect",function(){amtLmsState=2;obj.setupMeiOsAdmin(null,2)});amtLms.on("notify",function(data,options,str,code){if(code=="iAMT0052-3"){obj.kvmGetData()}else{handleAmtNotification(data)}})}catch(e){amtLmsState=-1;amtLms=null}}obj.start=function(){mesh.AddCommandHandler(handleServerCommand);mesh.AddConnectHandler(handleServerConnection);resetMicroLms();try{var userSession=require("user-sessions");userSession.on("changed",function onUserSessionChanged(){userSession.enumerateUsers().then(function(users){var u=[],a=users.Active;for(var i=0;i=12)){obj.kvmGetData("skip");obj.kvmTempTimer=setInterval(function(){obj.kvmGetData()},2000);obj.kvmSetData(JSON.stringify({action:"restart",ver:1}))}})})};obj.kvmGetData=function(tag){obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelRead(obj.kvmDataGetResponse,tag)};obj.kvmDataGetResponse=function(stack,name,response,status,tag){if((tag!="skip")&&(status==200)&&(response.Body.ReturnValue==0)){var val=null;try{val=Buffer.from(response.Body.DataMessage,"base64").toString()}catch(e){return}if(val!=null){obj.kvmProcessData(response.Body.RealmsBitmap,response.Body.MessageId,val)}}};var webRtcDesktop=null;obj.kvmProcessData=function(realms,messageId,val){var data=null;try{data=JSON.parse(val)}catch(e){}if((data!=null)&&(data.action)){if(data.action=="present"){obj.kvmSetData(JSON.stringify({action:"present",ver:1,platform:process.platform}))}if(data.action=="offer"){webRtcDesktop={};var rtc=require("ILibWebRTC");webRtcDesktop.webrtc=rtc.createConnection();webRtcDesktop.webrtc.on("connected",function(){});webRtcDesktop.webrtc.on("disconnected",function(){obj.webRtcCleanUp()});webRtcDesktop.webrtc.on("dataChannel",function(rtcchannel){webRtcDesktop.rtcchannel=rtcchannel;webRtcDesktop.kvm=mesh.getRemoteDesktopStream();webRtcDesktop.kvm.pipe(webRtcDesktop.rtcchannel,{dataTypeSkip:1,end:false});webRtcDesktop.rtcchannel.on("end",function(){obj.webRtcCleanUp()});webRtcDesktop.rtcchannel.on("data",function(x){obj.kvmCtrlData(this,x)});webRtcDesktop.rtcchannel.pipe(webRtcDesktop.kvm,{dataTypeSkip:1,end:false})});obj.kvmSetData(JSON.stringify({action:"answer",ver:1,sdp:webRtcDesktop.webrtc.setOffer(data.sdp)}))}}};var path={join:function(){var x=[];for(var i in arguments){var w=arguments[i];if(w!=null){while(w.endsWith("/")||w.endsWith("\\")){w=w.substring(0,w.length-1)}if(i!=0){while(w.startsWith("/")||w.startsWith("\\")){w=w.substring(1)}}x.push(w)}}if(x.length==0){return"/"}return x.join("/")}};obj.kvmCtrlData=function(channel,cmd){if(cmd.length>0&&cmd.charCodeAt(0)!=123){if(this.fileupload!=null){cmd=Buffer.from(cmd,"base64");var header=cmd.readUInt32BE(0);if((header==16777216)||(header==16777217)){fs.writeSync(this.fileupload.fp,cmd.slice(4));channel.write({action:"upload",sub:"ack",reqid:this.fileupload.reqid});if(header==16777217){fs.closeSync(this.fileupload.fp);this.fileupload=null}}}return}try{cmd=JSON.parse(cmd)}catch(ex){console.error("Invalid JSON: "+cmd);return}if((cmd.path!=null)&&(process.platform!="win32")&&(cmd.path[0]!="/")){cmd.path="/"+cmd.path}switch(cmd.action){case"ping":channel.write({action:"pong"});break;case"lock":if(process.platform=="win32"){var child=require("child_process");child.execFile(process.env.windir+"\\system32\\cmd.exe",["/c","RunDll32.exe user32.dll,LockWorkStation"],{type:1})}break;case"ls":var response=getDirectoryInfo(cmd.path);if(cmd.reqid!=undefined){response.reqid=cmd.reqid}channel.write(response);break;case"mkdir":fs.mkdirSync(cmd.path);break;case"rm":for(var i in cmd.delfiles){var fullpath=path.join(cmd.path,cmd.delfiles[i]);try{fs.unlinkSync(fullpath)}catch(e){console.log(e)}}break;case"rename":try{fs.renameSync(path.join(cmd.path,cmd.oldname),path.join(cmd.path,cmd.newname))}catch(e){console.log(e)}break;case"download":var sendNextBlock=0;if(cmd.sub=="start"){if(this.filedownload!=null){channel.write({action:"download",sub:"cancel",id:this.filedownload.id});delete this.filedownload}this.filedownload={id:cmd.id,path:cmd.path,ptr:0};try{this.filedownload.f=fs.openSync(this.filedownload.path,"rbN")}catch(e){channel.write({action:"download",sub:"cancel",id:this.filedownload.id});delete this.filedownload}if(this.filedownload){channel.write({action:"download",sub:"start",id:cmd.id})}}else{if((this.filedownload!=null)&&(cmd.id==this.filedownload.id)){if(cmd.sub=="startack"){sendNextBlock=8}else{if(cmd.sub=="stop"){delete this.filedownload}else{if(cmd.sub=="ack"){sendNextBlock=1}}}}}while(sendNextBlock>0){sendNextBlock--;var buf=Buffer.alloc(4096);var len=fs.readSync(this.filedownload.f,buf,4,4092,null);this.filedownload.ptr+=len;if(len<4092){buf.writeInt32BE(16777217,0);fs.closeSync(this.filedownload.f);delete this.filedownload;sendNextBlock=0}else{buf.writeInt32BE(16777216,0)}channel.write(buf.slice(0,len+4).toString("base64"))}break;case"upload":if(cmd.sub=="start"){if(this.fileupload!=null){fs.closeSync(this.fileupload.fp)}if(!cmd.path||!cmd.name){break}this.fileupload={reqid:cmd.reqid};var filepath=path.join(cmd.path,cmd.name);try{this.fileupload.fp=fs.openSync(filepath,"wbN")}catch(e){}if(this.fileupload.fp){channel.write({action:"upload",sub:"start",reqid:this.fileupload.reqid})}else{this.fileupload=null;channel.write({action:"upload",sub:"error",reqid:this.fileupload.reqid})}}else{if(cmd.sub=="cancel"){if(this.fileupload!=null){fs.closeSync(this.fileupload.fp);this.fileupload=null}}}break;case"copy":for(var i in cmd.names){var sc=path.join(cmd.scpath,cmd.names[i]),ds=path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds)}catch(e){}}}break;case"move":for(var i in cmd.names){var sc=path.join(cmd.scpath,cmd.names[i]),ds=path.join(cmd.dspath,cmd.names[i]);if(sc!=ds){try{fs.copyFileSync(sc,ds);fs.unlinkSync(sc)}catch(e){}}}break;default:console.log("Invalid KVM command",cmd);sendConsoleText("Invalid KVM command: "+cmd);break}};obj.webRtcCleanUp=function(){sendConsoleText("webRtcCleanUp");if(webRtcDesktop==null){return}if(webRtcDesktop.rtcchannel){try{webRtcDesktop.rtcchannel.close()}catch(e){}try{webRtcDesktop.rtcchannel.removeAllListeners("data")}catch(e){}try{webRtcDesktop.rtcchannel.removeAllListeners("end")}catch(e){}delete webRtcDesktop.rtcchannel}if(webRtcDesktop.webrtc){try{webRtcDesktop.webrtc.close()}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("connected")}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("disconnected")}catch(e){}try{webRtcDesktop.webrtc.removeAllListeners("dataChannel")}catch(e){}delete webRtcDesktop.webrtc}if(webRtcDesktop.kvm){try{webRtcDesktop.kvm.end()}catch(e){}delete webRtcDesktop.kvm}webRtcDesktop=null};obj.kvmSetData=function(x){obj.osamtstack.IPS_KVMRedirectionSettingData_DataChannelWrite(Buffer.from(x).toString("base64"),function(){})};function deleteFolderRecursive(path,rec){if(fs.existsSync(path)){if(rec==true){fs.readdirSync(obj.path.join(path,"*")).forEach(function(file,index){var curPath=obj.path.join(path,file);if(fs.statSync(curPath).isDirectory()){deleteFolderRecursive(curPath,true)}else{fs.unlinkSync(curPath)}})}fs.unlinkSync(path)}}function deactivateCCM(){amtMei.unprovision(1,function(status){if(status==0){sendConsoleText("Success deactivating Intel AMT CCM.")}else{sendConsoleText("Intel AMT CCM deactivation error: "+status)}})}function activeToCCM(adminpass){amtMei.getLocalSystemAccount(function(x){if(x.user&&x.pass){var transport=require("amt-wsman-duk");var wsman=require("amt-wsman");var amt=require("amt");oswsstack=new wsman(transport,"127.0.0.1",16992,x.user,x.pass,false);osamtstack=new amt(oswsstack);osamtstack.BatchEnum(null,["*AMT_GeneralSettings","*IPS_HostBasedSetupService"],activeToCCMEx2,adminpass)}else{sendConsoleText("Unable to get $$OsAdmin password.")}})}function activeToCCMEx2(stack,name,responses,status,adminpass){if(status!=200){sendConsoleText("Failed to fetch activation status, status "+status)}else{if(responses.IPS_HostBasedSetupService.response.AllowedControlModes.length!=2){sendConsoleText("Client control mode activation not allowed")}else{stack.IPS_HostBasedSetupService_Setup(2,md5hex("admin:"+responses.AMT_GeneralSettings.response.DigestRealm+":"+adminpass).substring(0,32),null,null,null,null,activeToCCMEx3)}}}function activeToCCMEx3(stack,name,responses,status){if(status!=200){sendConsoleText("Failed to activate, status "+status)}else{if(responses.Body.ReturnValue!=0){sendConsoleText("Client control mode activation failed: "+responses.Body.ReturnValueStr)}else{sendConsoleText("Intel AMT CCM activation success")}}}function md5hex(str){return require("MD5Stream").create().syncHash(str).toString("hex")}return obj}try{var xexports=null,mainMeshCore=null;try{xexports=module.exports}catch(e){}if(xexports!=null){module.exports.createMeshCore=createMeshCore}else{mainMeshCore=createMeshCore();mainMeshCore.start(null)}}catch(ex){require("MeshAgent").SendCommand({action:"msg",type:"console",value:"uncaughtException2: "+ex})}; \ No newline at end of file diff --git a/agents/modules_meshcmd_min/user-sessions.min.js b/agents/modules_meshcmd_min/user-sessions.min.js index 21bee889..ce18b206 100644 --- a/agents/modules_meshcmd_min/user-sessions.min.js +++ b/agents/modules_meshcmd_min/user-sessions.min.js @@ -1 +1 @@ -var NOTIFY_FOR_THIS_SESSION=0;var NOTIFY_FOR_ALL_SESSIONS=1;var WM_WTSSESSION_CHANGE=689;var WM_POWERBROADCAST=536;var PBT_POWERSETTINGCHANGE=32787;var PBT_APMSUSPEND=4;var PBT_APMRESUMESUSPEND=7;var PBT_APMRESUMEAUTOMATIC=18;var PBT_APMPOWERSTATUSCHANGE=10;var WTS_CONSOLE_CONNECT=(1);var WTS_CONSOLE_DISCONNECT=(2);var WTS_REMOTE_CONNECT=(3);var WTS_REMOTE_DISCONNECT=(4);var WTS_SESSION_LOGON=(5);var WTS_SESSION_LOGOFF=(6);var WTS_SESSION_LOCK=(7);var WTS_SESSION_UNLOCK=(8);var WTS_SESSION_REMOTE_CONTROL=(9);var WTS_SESSION_CREATE=(10);var WTS_SESSION_TERMINATE=(11);var GUID_ACDC_POWER_SOURCE;var GUID_BATTERY_PERCENTAGE_REMAINING;var GUID_CONSOLE_DISPLAY_STATE;function UserSessions(){this._ObjectID="user-sessions";require("events").EventEmitter.call(this,true).createEvent("changed").createEvent("locked").createEvent("unlocked");this.enumerateUsers=function h(){var s=require("promise");var r=new s(function(t,p){this.__resolver=t;this.__rejector=p});r.__handler=function o(p){r.__resolver(p)};try{this.Current(r.__handler)}catch(q){r.__rejector(q)}r.parent=this;return(r)};if(process.platform=="win32"){this._serviceHooked=false;this._marshal=require("_GenericMarshal");this._kernel32=this._marshal.CreateNativeProxy("Kernel32.dll");this._kernel32.CreateMethod("GetLastError");try{this._wts=this._marshal.CreateNativeProxy("Wtsapi32.dll");this._wts.CreateMethod("WTSEnumerateSessionsA");this._wts.CreateMethod("WTSQuerySessionInformationA");this._wts.CreateMethod("WTSRegisterSessionNotification");this._wts.CreateMethod("WTSUnRegisterSessionNotification");this._wts.CreateMethod("WTSFreeMemory")}catch(i){}this._user32=this._marshal.CreateNativeProxy("user32.dll");this._user32.CreateMethod("RegisterPowerSettingNotification");this._user32.CreateMethod("UnregisterPowerSettingNotification");this._rpcrt=this._marshal.CreateNativeProxy("Rpcrt4.dll");this._rpcrt.CreateMethod("UuidFromStringA");this._rpcrt.StringToUUID=function n(o){var p=n.us._marshal.CreateVariable(16);if(n.us._rpcrt.UuidFromStringA(n.us._marshal.CreateVariable(o),p).Val==0){return(p)}else{throw ("Could not convert string to UUID")}};this._rpcrt.StringToUUID.us=this;GUID_ACDC_POWER_SOURCE=this._rpcrt.StringToUUID("5d3e9a59-e9D5-4b00-a6bd-ff34ff516548");GUID_BATTERY_PERCENTAGE_REMAINING=this._rpcrt.StringToUUID("a7ad8041-b45a-4cae-87a3-eecbb468a9e1");GUID_CONSOLE_DISPLAY_STATE=this._rpcrt.StringToUUID("6fe69556-704a-47a0-8f24-c28d936fda47");this.SessionStates=["Active","Connected","ConnectQuery","Shadow","Disconnected","Idle","Listening","Reset","Down","Init"];this.InfoClass={WTSInitialProgram:0,WTSApplicationName:1,WTSWorkingDirectory:2,WTSOEMId:3,WTSSessionId:4,WTSUserName:5,WTSWinStationName:6,WTSDomainName:7,WTSConnectState:8,WTSClientBuildNumber:9,WTSClientName:10,WTSClientDirectory:11,WTSClientProductId:12,WTSClientHardwareId:13,WTSClientAddress:14,WTSClientDisplay:15,WTSClientProtocolType:16,WTSIdleTime:17,WTSLogonTime:18,WTSIncomingBytes:19,WTSOutgoingBytes:20,WTSIncomingFrames:21,WTSOutgoingFrames:22,WTSClientInfo:23,WTSSessionInfo:24,WTSSessionInfoEx:25,WTSConfigInfo:26,WTSValidationInfo:27,WTSSessionAddressV4:28,WTSIsRemoteSession:29};this.getSessionAttribute=function j(s,o){var p=this._marshal.CreatePointer();var q=this._marshal.CreateVariable(4);if(this._wts.WTSQuerySessionInformationA(0,s,o,p,q).Val==0){throw ("Error calling WTSQuerySessionInformation: "+this._kernel32.GetLastError.Val)}var r=p.Deref().String;this._wts.WTSFreeMemory(p.Deref());return(r)};this.Current=function f(o){var u={};var t=this._marshal.CreatePointer();var p=this._marshal.CreateVariable(4);if(this._wts.WTSEnumerateSessionsA(0,0,1,t,p).Val==0){throw ("Error calling WTSEnumerateSessionsA: "+this._kernel32.GetLastError().Val)}for(var q=0;q= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[0]]=s[1]}}return(r)};this._uids=function c(){var o=require("child_process").execFile("/bin/sh",["sh"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("awk -F: '($3 >= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[1]]=s[0]}}return(r)};this.Self=function m(){var q=require("promise");var o=new q(function(r,p){this.__resolver=r;this.__rejector=p;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u"]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(s){this._txt+=s.toString()});this.__child.on("exit",function(s){try{parseInt(this.stdout._txt)}catch(t){this.promise.__rejector("invalid uid");return}var u=parseInt(this.stdout._txt);this.promise.__resolver(u)})});return(o)};this.Current=function f(o){var p={};p._ObjectID="UserSession";Object.defineProperty(p,"_callback",{value:o});Object.defineProperty(p,"_child",{value:require("child_process").execFile("/usr/bin/last",["last","-f","/var/run/utmp"])});p._child.Parent=p;p._child._txt="";p._child.on("exit",function(q){var u=this._txt.split("\n");var A=[];var D={};for(var t in u){if(u[t]){var B=getTokens(u[t]);var z={Username:B[0],SessionId:B[1]};if(B[3].includes("still logged in")){z.State="Active"}else{z.LastActive=B[3]}A.push(z)}}A.pop();var C={};var y=[];for(var t in A){if(A[t].Username!="reboot"){D[A[t].SessionId]=A[t];if(C[A[t].Username]==null){C[A[t].Username]=-1}}}try{require("promise")}catch(r){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(this.Parent._callback){this.Parent._callback.call(this.Parent,D)}return}var x=require("promise");for(var v in C){var w=new x(function(E,s){this.__username=v;this.__resolver=E;this.__rejector=s;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u",v]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(F){this._txt+=F.toString()});this.__child.on("exit",function(F){try{parseInt(this.stdout._txt)}catch(G){this.promise.__rejector("invalid uid");return}var H=parseInt(this.stdout._txt);this.promise.__resolver(H)})});y.push(w)}x.all(y).then(function(E){var F={};for(var s in E){F[E[s].__username]=E[s]._internal.completedArgs[0]}for(var s in D){D[s].uid=F[D[s].Username]}Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}},function(s){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}})});p._child.stdout.Parent=p._child;p._child.stdout.on("data",function(q){this.Parent._txt+=q.toString()});return(p)};this._recheckLoggedInUsers=function a(){this.enumerateUsers().then(function(o){if(o.Active.length>0){if(this.parent._linux_lock_watcher!=null&&this.parent._linux_lock_watcher.uid!=o.Active[0].uid){delete this.parent._linux_lock_watcher}this.parent._linux_lock_watcher=new g(process.env.XDG_CURRENT_DESKTOP=="Unity"?"com.ubuntu.Upstart0_6":"org.gnome.ScreenSaver",o.Active[0].uid);this.parent._linux_lock_watcher.user_session=this.parent;this.parent._linux_lock_watcher.on("signal",function(r){var q=this.user_session.enumerateUsers();q.signalData=r.data[0];q.then(function(p){switch(this.signalData){case true:case"desktop-lock":this.parent.emit("locked",p.Active[0]);break;case false:case"desktop-unlock":this.parent.emit("unlocked",p.Active[0]);break}})})}else{if(this.parent._linux_lock_watcher!=null){delete this.parent._linux_lock_watcher}}})};this.on("changed",this._recheckLoggedInUsers);this._recheckLoggedInUsers()}else{if(process.platform=="darwin"){this._users=function(){var o=require("child_process").execFile("/usr/bin/dscl",["dscl",".","list","/Users","UniqueID"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("exit\n");o.waitExit();var q=o.stdout.str.split("\n");var r,p;var s={};for(p=0;p0;++r){if(!u[s[r].split(" ")[0]]){try{u[s[r].split(" ")[0]]={Username:s[r].split(" ")[0],State:s[r].split("still logged in").length>1?"Active":"Inactive",uid:t.uid[s[r].split(" ")[0]]}}catch(q){}}else{if(u[s[r].split(" ")[0]].State!="Active"&&s[r].split("still logged in").length>1){u[s[r].split(" ")[0]].State="Active"}}}Object.defineProperty(u,"Active",{value:showActiveOnly(u)});if(o){o.call(this,u)}}}}}if(process.platform=="linux"||process.platform=="darwin"){this._self=function b(){var o=require("child_process").execFile("/usr/bin/id",["id","-u"]);o.stdout.str="";o.stdout.on("data",function(p){this.str+=p.toString()});o.waitExit();return(parseInt(o.stdout.str))};this.isRoot=function k(){return(this._self()==0)};this.consoleUid=function e(){var o=process.platform=="darwin"?"console":":0";var p=require("child_process").execFile("/bin/sh",["sh"]);p.stdout.str="";p.stdout.on("data",function(u){this.str+=u.toString()});p.stdin.write("who\nexit\n");p.waitExit();var s=p.stdout.str.split("\n");var t,q,r;for(q in s){t=s[q].split(" ");for(r=1;r0&&t[r]==o){return(parseInt(this._users()[t[0]]))}}}throw ("nobody logged into console")}}}function showActiveOnly(c){var b=[];var e={};var f=[];var d;for(var a in c){if(c[a].State=="Active"){b.push(c[a]);d=(c[a].Domain?(c[a].Domain+"\\"):"")+c[a].Username;if(!e[d]){e[d]=d}}}for(var a in e){f.push(a)}Object.defineProperty(b,"usernames",{value:f});return(b)}function getTokens(d){var a=[];var b;a.push(d.substring(0,(b=d.indexOf(" "))));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}var c=d.substring(b).trim();a.push(c);return(a)}module.exports=new UserSessions(); \ No newline at end of file +var NOTIFY_FOR_THIS_SESSION=0;var NOTIFY_FOR_ALL_SESSIONS=1;var WM_WTSSESSION_CHANGE=689;var WM_POWERBROADCAST=536;var PBT_POWERSETTINGCHANGE=32787;var PBT_APMSUSPEND=4;var PBT_APMRESUMESUSPEND=7;var PBT_APMRESUMEAUTOMATIC=18;var PBT_APMPOWERSTATUSCHANGE=10;var WTS_CONSOLE_CONNECT=(1);var WTS_CONSOLE_DISCONNECT=(2);var WTS_REMOTE_CONNECT=(3);var WTS_REMOTE_DISCONNECT=(4);var WTS_SESSION_LOGON=(5);var WTS_SESSION_LOGOFF=(6);var WTS_SESSION_LOCK=(7);var WTS_SESSION_UNLOCK=(8);var WTS_SESSION_REMOTE_CONTROL=(9);var WTS_SESSION_CREATE=(10);var WTS_SESSION_TERMINATE=(11);var GUID_ACDC_POWER_SOURCE;var GUID_BATTERY_PERCENTAGE_REMAINING;var GUID_CONSOLE_DISPLAY_STATE;function UserSessions(){this._ObjectID="user-sessions";require("events").EventEmitter.call(this,true).createEvent("changed").createEvent("locked").createEvent("unlocked");this.enumerateUsers=function h(){var s=require("promise");var r=new s(function(t,p){this.__resolver=t;this.__rejector=p});r.__handler=function o(p){r.__resolver(p)};try{this.Current(r.__handler)}catch(q){r.__rejector(q)}r.parent=this;return(r)};if(process.platform=="win32"){this._serviceHooked=false;this._marshal=require("_GenericMarshal");this._kernel32=this._marshal.CreateNativeProxy("Kernel32.dll");this._kernel32.CreateMethod("GetLastError");try{this._wts=this._marshal.CreateNativeProxy("Wtsapi32.dll");this._wts.CreateMethod("WTSEnumerateSessionsA");this._wts.CreateMethod("WTSQuerySessionInformationA");this._wts.CreateMethod("WTSRegisterSessionNotification");this._wts.CreateMethod("WTSUnRegisterSessionNotification");this._wts.CreateMethod("WTSFreeMemory")}catch(i){}this._user32=this._marshal.CreateNativeProxy("user32.dll");this._user32.CreateMethod({method:"RegisterPowerSettingNotification",threadDispatch:1});this._user32.CreateMethod("UnregisterPowerSettingNotification");this._rpcrt=this._marshal.CreateNativeProxy("Rpcrt4.dll");this._rpcrt.CreateMethod("UuidFromStringA");this._rpcrt.StringToUUID=function n(o){var p=n.us._marshal.CreateVariable(16);if(n.us._rpcrt.UuidFromStringA(n.us._marshal.CreateVariable(o),p).Val==0){return(p)}else{throw ("Could not convert string to UUID")}};this._rpcrt.StringToUUID.us=this;GUID_ACDC_POWER_SOURCE=this._rpcrt.StringToUUID("5d3e9a59-e9D5-4b00-a6bd-ff34ff516548");GUID_BATTERY_PERCENTAGE_REMAINING=this._rpcrt.StringToUUID("a7ad8041-b45a-4cae-87a3-eecbb468a9e1");GUID_CONSOLE_DISPLAY_STATE=this._rpcrt.StringToUUID("6fe69556-704a-47a0-8f24-c28d936fda47");this.SessionStates=["Active","Connected","ConnectQuery","Shadow","Disconnected","Idle","Listening","Reset","Down","Init"];this.InfoClass={WTSInitialProgram:0,WTSApplicationName:1,WTSWorkingDirectory:2,WTSOEMId:3,WTSSessionId:4,WTSUserName:5,WTSWinStationName:6,WTSDomainName:7,WTSConnectState:8,WTSClientBuildNumber:9,WTSClientName:10,WTSClientDirectory:11,WTSClientProductId:12,WTSClientHardwareId:13,WTSClientAddress:14,WTSClientDisplay:15,WTSClientProtocolType:16,WTSIdleTime:17,WTSLogonTime:18,WTSIncomingBytes:19,WTSOutgoingBytes:20,WTSIncomingFrames:21,WTSOutgoingFrames:22,WTSClientInfo:23,WTSSessionInfo:24,WTSSessionInfoEx:25,WTSConfigInfo:26,WTSValidationInfo:27,WTSSessionAddressV4:28,WTSIsRemoteSession:29};this.getSessionAttribute=function j(s,o){var p=this._marshal.CreatePointer();var q=this._marshal.CreateVariable(4);if(this._wts.WTSQuerySessionInformationA(0,s,o,p,q).Val==0){throw ("Error calling WTSQuerySessionInformation: "+this._kernel32.GetLastError.Val)}var r=p.Deref().String;this._wts.WTSFreeMemory(p.Deref());return(r)};this.Current=function f(o){var u={};var t=this._marshal.CreatePointer();var p=this._marshal.CreateVariable(4);if(this._wts.WTSEnumerateSessionsA(0,0,1,t,p).Val==0){throw ("Error calling WTSEnumerateSessionsA: "+this._kernel32.GetLastError().Val)}for(var q=0;q= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[0]]=s[1]}}return(r)};this._uids=function c(){var o=require("child_process").execFile("/bin/sh",["sh"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("awk -F: '($3 >= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[1]]=s[0]}}return(r)};this.Self=function m(){var q=require("promise");var o=new q(function(r,p){this.__resolver=r;this.__rejector=p;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u"]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(s){this._txt+=s.toString()});this.__child.on("exit",function(s){try{parseInt(this.stdout._txt)}catch(t){this.promise.__rejector("invalid uid");return}var u=parseInt(this.stdout._txt);this.promise.__resolver(u)})});return(o)};this.Current=function f(o){var p={};p._ObjectID="UserSession";Object.defineProperty(p,"_callback",{value:o});Object.defineProperty(p,"_child",{value:require("child_process").execFile("/usr/bin/last",["last","-f","/var/run/utmp"])});p._child.Parent=p;p._child._txt="";p._child.on("exit",function(q){var u=this._txt.split("\n");var A=[];var D={};for(var t in u){if(u[t]){var B=getTokens(u[t]);var z={Username:B[0],SessionId:B[1]};if(B[3].includes("still logged in")){z.State="Active"}else{z.LastActive=B[3]}A.push(z)}}A.pop();var C={};var y=[];for(var t in A){if(A[t].Username!="reboot"){D[A[t].SessionId]=A[t];if(C[A[t].Username]==null){C[A[t].Username]=-1}}}try{require("promise")}catch(r){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(this.Parent._callback){this.Parent._callback.call(this.Parent,D)}return}var x=require("promise");for(var v in C){var w=new x(function(E,s){this.__username=v;this.__resolver=E;this.__rejector=s;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u",v]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(F){this._txt+=F.toString()});this.__child.on("exit",function(F){try{parseInt(this.stdout._txt)}catch(G){this.promise.__rejector("invalid uid");return}var H=parseInt(this.stdout._txt);this.promise.__resolver(H)})});y.push(w)}x.all(y).then(function(E){var F={};for(var s in E){F[E[s].__username]=E[s]._internal.completedArgs[0]}for(var s in D){D[s].uid=F[D[s].Username]}Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}},function(s){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}})});p._child.stdout.Parent=p._child;p._child.stdout.on("data",function(q){this.Parent._txt+=q.toString()});return(p)};this._recheckLoggedInUsers=function a(){this.enumerateUsers().then(function(o){if(o.Active.length>0){if(this.parent._linux_lock_watcher!=null&&this.parent._linux_lock_watcher.uid!=o.Active[0].uid){delete this.parent._linux_lock_watcher}this.parent._linux_lock_watcher=new g(process.env.XDG_CURRENT_DESKTOP=="Unity"?"com.ubuntu.Upstart0_6":"org.gnome.ScreenSaver",o.Active[0].uid);this.parent._linux_lock_watcher.user_session=this.parent;this.parent._linux_lock_watcher.on("signal",function(r){var q=this.user_session.enumerateUsers();q.signalData=r.data[0];q.then(function(p){switch(this.signalData){case true:case"desktop-lock":this.parent.emit("locked",p.Active[0]);break;case false:case"desktop-unlock":this.parent.emit("unlocked",p.Active[0]);break}})})}else{if(this.parent._linux_lock_watcher!=null){delete this.parent._linux_lock_watcher}}})};this.on("changed",this._recheckLoggedInUsers);this._recheckLoggedInUsers()}else{if(process.platform=="darwin"){this._users=function(){var o=require("child_process").execFile("/usr/bin/dscl",["dscl",".","list","/Users","UniqueID"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("exit\n");o.waitExit();var q=o.stdout.str.split("\n");var r,p;var s={};for(p=0;p0;++r){if(!u[s[r].split(" ")[0]]){try{u[s[r].split(" ")[0]]={Username:s[r].split(" ")[0],State:s[r].split("still logged in").length>1?"Active":"Inactive",uid:t.uid[s[r].split(" ")[0]]}}catch(q){}}else{if(u[s[r].split(" ")[0]].State!="Active"&&s[r].split("still logged in").length>1){u[s[r].split(" ")[0]].State="Active"}}}Object.defineProperty(u,"Active",{value:showActiveOnly(u)});if(o){o.call(this,u)}}}}}if(process.platform=="linux"||process.platform=="darwin"){this._self=function b(){var o=require("child_process").execFile("/usr/bin/id",["id","-u"]);o.stdout.str="";o.stdout.on("data",function(p){this.str+=p.toString()});o.waitExit();return(parseInt(o.stdout.str))};this.isRoot=function k(){return(this._self()==0)};this.consoleUid=function e(){var o=process.platform=="darwin"?"console":process.env.DISPLAY;var p=require("child_process").execFile("/bin/sh",["sh"]);p.stdout.str="";p.stdout.on("data",function(u){this.str+=u.toString()});p.stdin.write("who\nexit\n");p.waitExit();var s=p.stdout.str.split("\n");var t,q,r;for(q in s){t=s[q].split(" ");for(r=1;r0&&(t[r]==o||t[r]==("("+o+")"))){return(parseInt(this._users()[t[0]]))}}}throw ("nobody logged into console")}}}function showActiveOnly(c){var b=[];var e={};var f=[];var d;for(var a in c){if(c[a].State=="Active"){b.push(c[a]);d=(c[a].Domain?(c[a].Domain+"\\"):"")+c[a].Username;if(!e[d]){e[d]=d}}}for(var a in e){f.push(a)}Object.defineProperty(b,"usernames",{value:f});return(b)}function getTokens(d){var a=[];var b;a.push(d.substring(0,(b=d.indexOf(" "))));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}var c=d.substring(b).trim();a.push(c);return(a)}module.exports=new UserSessions(); \ No newline at end of file diff --git a/agents/modules_meshcore_min/user-sessions.min.js b/agents/modules_meshcore_min/user-sessions.min.js index 76bea7da..ce18b206 100644 --- a/agents/modules_meshcore_min/user-sessions.min.js +++ b/agents/modules_meshcore_min/user-sessions.min.js @@ -1 +1 @@ -var NOTIFY_FOR_THIS_SESSION=0;var NOTIFY_FOR_ALL_SESSIONS=1;var WM_WTSSESSION_CHANGE=689;var WM_POWERBROADCAST=536;var PBT_POWERSETTINGCHANGE=32787;var PBT_APMSUSPEND=4;var PBT_APMRESUMESUSPEND=7;var PBT_APMRESUMEAUTOMATIC=18;var PBT_APMPOWERSTATUSCHANGE=10;var WTS_CONSOLE_CONNECT=(1);var WTS_CONSOLE_DISCONNECT=(2);var WTS_REMOTE_CONNECT=(3);var WTS_REMOTE_DISCONNECT=(4);var WTS_SESSION_LOGON=(5);var WTS_SESSION_LOGOFF=(6);var WTS_SESSION_LOCK=(7);var WTS_SESSION_UNLOCK=(8);var WTS_SESSION_REMOTE_CONTROL=(9);var WTS_SESSION_CREATE=(10);var WTS_SESSION_TERMINATE=(11);var GUID_ACDC_POWER_SOURCE;var GUID_BATTERY_PERCENTAGE_REMAINING;var GUID_CONSOLE_DISPLAY_STATE;function UserSessions(){this._ObjectID="user-sessions";require("events").EventEmitter.call(this,true).createEvent("changed").createEvent("locked").createEvent("unlocked");this.enumerateUsers=function h(){var s=require("promise");var r=new s(function(t,p){this.__resolver=t;this.__rejector=p});r.__handler=function o(p){r.__resolver(p)};try{this.Current(r.__handler)}catch(q){r.__rejector(q)}r.parent=this;return(r)};if(process.platform=="win32"){this._serviceHooked=false;this._marshal=require("_GenericMarshal");this._kernel32=this._marshal.CreateNativeProxy("Kernel32.dll");this._kernel32.CreateMethod("GetLastError");try{this._wts=this._marshal.CreateNativeProxy("Wtsapi32.dll");this._wts.CreateMethod("WTSEnumerateSessionsA");this._wts.CreateMethod("WTSQuerySessionInformationA");this._wts.CreateMethod("WTSRegisterSessionNotification");this._wts.CreateMethod("WTSUnRegisterSessionNotification");this._wts.CreateMethod("WTSFreeMemory")}catch(i){}this._user32=this._marshal.CreateNativeProxy("user32.dll");this._user32.CreateMethod({method:"RegisterPowerSettingNotification",threadDispatch:1});this._user32.CreateMethod("UnregisterPowerSettingNotification");this._rpcrt=this._marshal.CreateNativeProxy("Rpcrt4.dll");this._rpcrt.CreateMethod("UuidFromStringA");this._rpcrt.StringToUUID=function n(o){var p=n.us._marshal.CreateVariable(16);if(n.us._rpcrt.UuidFromStringA(n.us._marshal.CreateVariable(o),p).Val==0){return(p)}else{throw ("Could not convert string to UUID")}};this._rpcrt.StringToUUID.us=this;GUID_ACDC_POWER_SOURCE=this._rpcrt.StringToUUID("5d3e9a59-e9D5-4b00-a6bd-ff34ff516548");GUID_BATTERY_PERCENTAGE_REMAINING=this._rpcrt.StringToUUID("a7ad8041-b45a-4cae-87a3-eecbb468a9e1");GUID_CONSOLE_DISPLAY_STATE=this._rpcrt.StringToUUID("6fe69556-704a-47a0-8f24-c28d936fda47");this.SessionStates=["Active","Connected","ConnectQuery","Shadow","Disconnected","Idle","Listening","Reset","Down","Init"];this.InfoClass={WTSInitialProgram:0,WTSApplicationName:1,WTSWorkingDirectory:2,WTSOEMId:3,WTSSessionId:4,WTSUserName:5,WTSWinStationName:6,WTSDomainName:7,WTSConnectState:8,WTSClientBuildNumber:9,WTSClientName:10,WTSClientDirectory:11,WTSClientProductId:12,WTSClientHardwareId:13,WTSClientAddress:14,WTSClientDisplay:15,WTSClientProtocolType:16,WTSIdleTime:17,WTSLogonTime:18,WTSIncomingBytes:19,WTSOutgoingBytes:20,WTSIncomingFrames:21,WTSOutgoingFrames:22,WTSClientInfo:23,WTSSessionInfo:24,WTSSessionInfoEx:25,WTSConfigInfo:26,WTSValidationInfo:27,WTSSessionAddressV4:28,WTSIsRemoteSession:29};this.getSessionAttribute=function j(s,o){var p=this._marshal.CreatePointer();var q=this._marshal.CreateVariable(4);if(this._wts.WTSQuerySessionInformationA(0,s,o,p,q).Val==0){throw ("Error calling WTSQuerySessionInformation: "+this._kernel32.GetLastError.Val)}var r=p.Deref().String;this._wts.WTSFreeMemory(p.Deref());return(r)};this.Current=function f(o){var u={};var t=this._marshal.CreatePointer();var p=this._marshal.CreateVariable(4);if(this._wts.WTSEnumerateSessionsA(0,0,1,t,p).Val==0){throw ("Error calling WTSEnumerateSessionsA: "+this._kernel32.GetLastError().Val)}for(var q=0;q= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[0]]=s[1]}}return(r)};this._uids=function c(){var o=require("child_process").execFile("/bin/sh",["sh"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("awk -F: '($3 >= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[1]]=s[0]}}return(r)};this.Self=function m(){var q=require("promise");var o=new q(function(r,p){this.__resolver=r;this.__rejector=p;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u"]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(s){this._txt+=s.toString()});this.__child.on("exit",function(s){try{parseInt(this.stdout._txt)}catch(t){this.promise.__rejector("invalid uid");return}var u=parseInt(this.stdout._txt);this.promise.__resolver(u)})});return(o)};this.Current=function f(o){var p={};p._ObjectID="UserSession";Object.defineProperty(p,"_callback",{value:o});Object.defineProperty(p,"_child",{value:require("child_process").execFile("/usr/bin/last",["last","-f","/var/run/utmp"])});p._child.Parent=p;p._child._txt="";p._child.on("exit",function(q){var u=this._txt.split("\n");var A=[];var D={};for(var t in u){if(u[t]){var B=getTokens(u[t]);var z={Username:B[0],SessionId:B[1]};if(B[3].includes("still logged in")){z.State="Active"}else{z.LastActive=B[3]}A.push(z)}}A.pop();var C={};var y=[];for(var t in A){if(A[t].Username!="reboot"){D[A[t].SessionId]=A[t];if(C[A[t].Username]==null){C[A[t].Username]=-1}}}try{require("promise")}catch(r){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(this.Parent._callback){this.Parent._callback.call(this.Parent,D)}return}var x=require("promise");for(var v in C){var w=new x(function(E,s){this.__username=v;this.__resolver=E;this.__rejector=s;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u",v]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(F){this._txt+=F.toString()});this.__child.on("exit",function(F){try{parseInt(this.stdout._txt)}catch(G){this.promise.__rejector("invalid uid");return}var H=parseInt(this.stdout._txt);this.promise.__resolver(H)})});y.push(w)}x.all(y).then(function(E){var F={};for(var s in E){F[E[s].__username]=E[s]._internal.completedArgs[0]}for(var s in D){D[s].uid=F[D[s].Username]}Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}},function(s){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}})});p._child.stdout.Parent=p._child;p._child.stdout.on("data",function(q){this.Parent._txt+=q.toString()});return(p)};this._recheckLoggedInUsers=function a(){this.enumerateUsers().then(function(o){if(o.Active.length>0){if(this.parent._linux_lock_watcher!=null&&this.parent._linux_lock_watcher.uid!=o.Active[0].uid){delete this.parent._linux_lock_watcher}this.parent._linux_lock_watcher=new g(process.env.XDG_CURRENT_DESKTOP=="Unity"?"com.ubuntu.Upstart0_6":"org.gnome.ScreenSaver",o.Active[0].uid);this.parent._linux_lock_watcher.user_session=this.parent;this.parent._linux_lock_watcher.on("signal",function(r){var q=this.user_session.enumerateUsers();q.signalData=r.data[0];q.then(function(p){switch(this.signalData){case true:case"desktop-lock":this.parent.emit("locked",p.Active[0]);break;case false:case"desktop-unlock":this.parent.emit("unlocked",p.Active[0]);break}})})}else{if(this.parent._linux_lock_watcher!=null){delete this.parent._linux_lock_watcher}}})};this.on("changed",this._recheckLoggedInUsers);this._recheckLoggedInUsers()}else{if(process.platform=="darwin"){this._users=function(){var o=require("child_process").execFile("/usr/bin/dscl",["dscl",".","list","/Users","UniqueID"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("exit\n");o.waitExit();var q=o.stdout.str.split("\n");var r,p;var s={};for(p=0;p0;++r){if(!u[s[r].split(" ")[0]]){try{u[s[r].split(" ")[0]]={Username:s[r].split(" ")[0],State:s[r].split("still logged in").length>1?"Active":"Inactive",uid:t.uid[s[r].split(" ")[0]]}}catch(q){}}else{if(u[s[r].split(" ")[0]].State!="Active"&&s[r].split("still logged in").length>1){u[s[r].split(" ")[0]].State="Active"}}}Object.defineProperty(u,"Active",{value:showActiveOnly(u)});if(o){o.call(this,u)}}}}}if(process.platform=="linux"||process.platform=="darwin"){this._self=function b(){var o=require("child_process").execFile("/usr/bin/id",["id","-u"]);o.stdout.str="";o.stdout.on("data",function(p){this.str+=p.toString()});o.waitExit();return(parseInt(o.stdout.str))};this.isRoot=function k(){return(this._self()==0)};this.consoleUid=function e(){var o=process.platform=="darwin"?"console":":0";var p=require("child_process").execFile("/bin/sh",["sh"]);p.stdout.str="";p.stdout.on("data",function(u){this.str+=u.toString()});p.stdin.write("who\nexit\n");p.waitExit();var s=p.stdout.str.split("\n");var t,q,r;for(q in s){t=s[q].split(" ");for(r=1;r0&&t[r]==o){return(parseInt(this._users()[t[0]]))}}}throw ("nobody logged into console")}}}function showActiveOnly(c){var b=[];var e={};var f=[];var d;for(var a in c){if(c[a].State=="Active"){b.push(c[a]);d=(c[a].Domain?(c[a].Domain+"\\"):"")+c[a].Username;if(!e[d]){e[d]=d}}}for(var a in e){f.push(a)}Object.defineProperty(b,"usernames",{value:f});return(b)}function getTokens(d){var a=[];var b;a.push(d.substring(0,(b=d.indexOf(" "))));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}var c=d.substring(b).trim();a.push(c);return(a)}module.exports=new UserSessions(); \ No newline at end of file +var NOTIFY_FOR_THIS_SESSION=0;var NOTIFY_FOR_ALL_SESSIONS=1;var WM_WTSSESSION_CHANGE=689;var WM_POWERBROADCAST=536;var PBT_POWERSETTINGCHANGE=32787;var PBT_APMSUSPEND=4;var PBT_APMRESUMESUSPEND=7;var PBT_APMRESUMEAUTOMATIC=18;var PBT_APMPOWERSTATUSCHANGE=10;var WTS_CONSOLE_CONNECT=(1);var WTS_CONSOLE_DISCONNECT=(2);var WTS_REMOTE_CONNECT=(3);var WTS_REMOTE_DISCONNECT=(4);var WTS_SESSION_LOGON=(5);var WTS_SESSION_LOGOFF=(6);var WTS_SESSION_LOCK=(7);var WTS_SESSION_UNLOCK=(8);var WTS_SESSION_REMOTE_CONTROL=(9);var WTS_SESSION_CREATE=(10);var WTS_SESSION_TERMINATE=(11);var GUID_ACDC_POWER_SOURCE;var GUID_BATTERY_PERCENTAGE_REMAINING;var GUID_CONSOLE_DISPLAY_STATE;function UserSessions(){this._ObjectID="user-sessions";require("events").EventEmitter.call(this,true).createEvent("changed").createEvent("locked").createEvent("unlocked");this.enumerateUsers=function h(){var s=require("promise");var r=new s(function(t,p){this.__resolver=t;this.__rejector=p});r.__handler=function o(p){r.__resolver(p)};try{this.Current(r.__handler)}catch(q){r.__rejector(q)}r.parent=this;return(r)};if(process.platform=="win32"){this._serviceHooked=false;this._marshal=require("_GenericMarshal");this._kernel32=this._marshal.CreateNativeProxy("Kernel32.dll");this._kernel32.CreateMethod("GetLastError");try{this._wts=this._marshal.CreateNativeProxy("Wtsapi32.dll");this._wts.CreateMethod("WTSEnumerateSessionsA");this._wts.CreateMethod("WTSQuerySessionInformationA");this._wts.CreateMethod("WTSRegisterSessionNotification");this._wts.CreateMethod("WTSUnRegisterSessionNotification");this._wts.CreateMethod("WTSFreeMemory")}catch(i){}this._user32=this._marshal.CreateNativeProxy("user32.dll");this._user32.CreateMethod({method:"RegisterPowerSettingNotification",threadDispatch:1});this._user32.CreateMethod("UnregisterPowerSettingNotification");this._rpcrt=this._marshal.CreateNativeProxy("Rpcrt4.dll");this._rpcrt.CreateMethod("UuidFromStringA");this._rpcrt.StringToUUID=function n(o){var p=n.us._marshal.CreateVariable(16);if(n.us._rpcrt.UuidFromStringA(n.us._marshal.CreateVariable(o),p).Val==0){return(p)}else{throw ("Could not convert string to UUID")}};this._rpcrt.StringToUUID.us=this;GUID_ACDC_POWER_SOURCE=this._rpcrt.StringToUUID("5d3e9a59-e9D5-4b00-a6bd-ff34ff516548");GUID_BATTERY_PERCENTAGE_REMAINING=this._rpcrt.StringToUUID("a7ad8041-b45a-4cae-87a3-eecbb468a9e1");GUID_CONSOLE_DISPLAY_STATE=this._rpcrt.StringToUUID("6fe69556-704a-47a0-8f24-c28d936fda47");this.SessionStates=["Active","Connected","ConnectQuery","Shadow","Disconnected","Idle","Listening","Reset","Down","Init"];this.InfoClass={WTSInitialProgram:0,WTSApplicationName:1,WTSWorkingDirectory:2,WTSOEMId:3,WTSSessionId:4,WTSUserName:5,WTSWinStationName:6,WTSDomainName:7,WTSConnectState:8,WTSClientBuildNumber:9,WTSClientName:10,WTSClientDirectory:11,WTSClientProductId:12,WTSClientHardwareId:13,WTSClientAddress:14,WTSClientDisplay:15,WTSClientProtocolType:16,WTSIdleTime:17,WTSLogonTime:18,WTSIncomingBytes:19,WTSOutgoingBytes:20,WTSIncomingFrames:21,WTSOutgoingFrames:22,WTSClientInfo:23,WTSSessionInfo:24,WTSSessionInfoEx:25,WTSConfigInfo:26,WTSValidationInfo:27,WTSSessionAddressV4:28,WTSIsRemoteSession:29};this.getSessionAttribute=function j(s,o){var p=this._marshal.CreatePointer();var q=this._marshal.CreateVariable(4);if(this._wts.WTSQuerySessionInformationA(0,s,o,p,q).Val==0){throw ("Error calling WTSQuerySessionInformation: "+this._kernel32.GetLastError.Val)}var r=p.Deref().String;this._wts.WTSFreeMemory(p.Deref());return(r)};this.Current=function f(o){var u={};var t=this._marshal.CreatePointer();var p=this._marshal.CreateVariable(4);if(this._wts.WTSEnumerateSessionsA(0,0,1,t,p).Val==0){throw ("Error calling WTSEnumerateSessionsA: "+this._kernel32.GetLastError().Val)}for(var q=0;q= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[0]]=s[1]}}return(r)};this._uids=function c(){var o=require("child_process").execFile("/bin/sh",["sh"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("awk -F: '($3 >= 0) {printf \"%s:%s\\n\", $1, $3}' /etc/passwd\nexit\n");o.waitExit();var p=o.stdout.str.split("\n");var r={},s;for(var q in p){s=p[q].split(":");if(s[0]){r[s[1]]=s[0]}}return(r)};this.Self=function m(){var q=require("promise");var o=new q(function(r,p){this.__resolver=r;this.__rejector=p;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u"]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(s){this._txt+=s.toString()});this.__child.on("exit",function(s){try{parseInt(this.stdout._txt)}catch(t){this.promise.__rejector("invalid uid");return}var u=parseInt(this.stdout._txt);this.promise.__resolver(u)})});return(o)};this.Current=function f(o){var p={};p._ObjectID="UserSession";Object.defineProperty(p,"_callback",{value:o});Object.defineProperty(p,"_child",{value:require("child_process").execFile("/usr/bin/last",["last","-f","/var/run/utmp"])});p._child.Parent=p;p._child._txt="";p._child.on("exit",function(q){var u=this._txt.split("\n");var A=[];var D={};for(var t in u){if(u[t]){var B=getTokens(u[t]);var z={Username:B[0],SessionId:B[1]};if(B[3].includes("still logged in")){z.State="Active"}else{z.LastActive=B[3]}A.push(z)}}A.pop();var C={};var y=[];for(var t in A){if(A[t].Username!="reboot"){D[A[t].SessionId]=A[t];if(C[A[t].Username]==null){C[A[t].Username]=-1}}}try{require("promise")}catch(r){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(this.Parent._callback){this.Parent._callback.call(this.Parent,D)}return}var x=require("promise");for(var v in C){var w=new x(function(E,s){this.__username=v;this.__resolver=E;this.__rejector=s;this.__child=require("child_process").execFile("/usr/bin/id",["id","-u",v]);this.__child.promise=this;this.__child.stdout._txt="";this.__child.stdout.on("data",function(F){this._txt+=F.toString()});this.__child.on("exit",function(F){try{parseInt(this.stdout._txt)}catch(G){this.promise.__rejector("invalid uid");return}var H=parseInt(this.stdout._txt);this.promise.__resolver(H)})});y.push(w)}x.all(y).then(function(E){var F={};for(var s in E){F[E[s].__username]=E[s]._internal.completedArgs[0]}for(var s in D){D[s].uid=F[D[s].Username]}Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}},function(s){Object.defineProperty(D,"Active",{value:showActiveOnly(D)});if(p._callback){p._callback.call(p,D)}})});p._child.stdout.Parent=p._child;p._child.stdout.on("data",function(q){this.Parent._txt+=q.toString()});return(p)};this._recheckLoggedInUsers=function a(){this.enumerateUsers().then(function(o){if(o.Active.length>0){if(this.parent._linux_lock_watcher!=null&&this.parent._linux_lock_watcher.uid!=o.Active[0].uid){delete this.parent._linux_lock_watcher}this.parent._linux_lock_watcher=new g(process.env.XDG_CURRENT_DESKTOP=="Unity"?"com.ubuntu.Upstart0_6":"org.gnome.ScreenSaver",o.Active[0].uid);this.parent._linux_lock_watcher.user_session=this.parent;this.parent._linux_lock_watcher.on("signal",function(r){var q=this.user_session.enumerateUsers();q.signalData=r.data[0];q.then(function(p){switch(this.signalData){case true:case"desktop-lock":this.parent.emit("locked",p.Active[0]);break;case false:case"desktop-unlock":this.parent.emit("unlocked",p.Active[0]);break}})})}else{if(this.parent._linux_lock_watcher!=null){delete this.parent._linux_lock_watcher}}})};this.on("changed",this._recheckLoggedInUsers);this._recheckLoggedInUsers()}else{if(process.platform=="darwin"){this._users=function(){var o=require("child_process").execFile("/usr/bin/dscl",["dscl",".","list","/Users","UniqueID"]);o.stdout.str="";o.stdout.on("data",function(t){this.str+=t.toString()});o.stdin.write("exit\n");o.waitExit();var q=o.stdout.str.split("\n");var r,p;var s={};for(p=0;p0;++r){if(!u[s[r].split(" ")[0]]){try{u[s[r].split(" ")[0]]={Username:s[r].split(" ")[0],State:s[r].split("still logged in").length>1?"Active":"Inactive",uid:t.uid[s[r].split(" ")[0]]}}catch(q){}}else{if(u[s[r].split(" ")[0]].State!="Active"&&s[r].split("still logged in").length>1){u[s[r].split(" ")[0]].State="Active"}}}Object.defineProperty(u,"Active",{value:showActiveOnly(u)});if(o){o.call(this,u)}}}}}if(process.platform=="linux"||process.platform=="darwin"){this._self=function b(){var o=require("child_process").execFile("/usr/bin/id",["id","-u"]);o.stdout.str="";o.stdout.on("data",function(p){this.str+=p.toString()});o.waitExit();return(parseInt(o.stdout.str))};this.isRoot=function k(){return(this._self()==0)};this.consoleUid=function e(){var o=process.platform=="darwin"?"console":process.env.DISPLAY;var p=require("child_process").execFile("/bin/sh",["sh"]);p.stdout.str="";p.stdout.on("data",function(u){this.str+=u.toString()});p.stdin.write("who\nexit\n");p.waitExit();var s=p.stdout.str.split("\n");var t,q,r;for(q in s){t=s[q].split(" ");for(r=1;r0&&(t[r]==o||t[r]==("("+o+")"))){return(parseInt(this._users()[t[0]]))}}}throw ("nobody logged into console")}}}function showActiveOnly(c){var b=[];var e={};var f=[];var d;for(var a in c){if(c[a].State=="Active"){b.push(c[a]);d=(c[a].Domain?(c[a].Domain+"\\"):"")+c[a].Username;if(!e[d]){e[d]=d}}}for(var a in e){f.push(a)}Object.defineProperty(b,"usernames",{value:f});return(b)}function getTokens(d){var a=[];var b;a.push(d.substring(0,(b=d.indexOf(" "))));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}a.push(d.substring(b,(b=d.substring(b).indexOf(" ")+b)));while(d[++b]==" "){}var c=d.substring(b).trim();a.push(c);return(a)}module.exports=new UserSessions(); \ No newline at end of file diff --git a/meshuser.js b/meshuser.js index 812b0550..43941dcc 100644 --- a/meshuser.js +++ b/meshuser.js @@ -199,7 +199,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use var httpport = ((obj.args.aliasport != null) ? obj.args.aliasport : obj.args.port); // Build server information object - var serverinfo = { name: obj.parent.certificates.CommonName, mpsname: obj.parent.certificates.AmtMpsName, mpsport: mpsport, mpspass: obj.args.mpspass, port: httpport, emailcheck: obj.parent.parent.mailserver != null }; + var serverinfo = { name: obj.parent.certificates.CommonName, mpsname: obj.parent.certificates.AmtMpsName, mpsport: mpsport, mpspass: obj.args.mpspass, port: httpport, emailcheck: ((obj.parent.parent.mailserver != null) && (domain.auth != 'sspi')), domainauth: (domain.auth == 'sspi') }; if (obj.args.notls == true) { serverinfo.https = false; } else { serverinfo.https = true; serverinfo.redirport = obj.args.redirport; } // Send server information @@ -470,6 +470,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use case 'changeemail': { // Change the email address + if (domain.auth == 'sspi') return; if (obj.common.validateEmail(command.email, 1, 256) == false) return; if (obj.parent.users[req.session.userid].email != command.email) { // Check if this email is already validated on a different account @@ -501,6 +502,9 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use message.msg = 'Set email of user ' + userinfo.name + ' to ' + user.email; } obj.parent.parent.DispatchEvent(['*', 'server-users', user._id], obj, message); + + // Send the verification email + if ((obj.parent.parent.mailserver != null) && (domain.auth != 'sspi')) { obj.parent.parent.mailserver.sendAccountCheckMail(domain, user.name, user.email); } } }); } @@ -509,15 +513,11 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use case 'verifyemail': { // Send a account email verification email + if (domain.auth == 'sspi') return; if (obj.common.validateString(command.email, 3, 1024) == false) return; - var x = command.email.split('@'); - if ((x.length == 2) && (x[0].length > 0) && (x[1].split('.').length > 1) && (x[1].length > 2)) { - if (obj.parent.users[req.session.userid].email == command.email) { - // Send the verification email - if (obj.parent.parent.mailserver != null) { - obj.parent.parent.mailserver.sendAccountCheckMail(domain, user.name, user.email); - } - } + if ((obj.parent.parent.mailserver != null) && (obj.parent.users[req.session.userid].email == command.email)) { + // Send the verification email + obj.parent.parent.mailserver.sendAccountCheckMail(domain, user.name, user.email); } break; } @@ -738,6 +738,9 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use } case 'createmesh': { + // In some situations, we need a verified email address to create a device group. + if ((obj.parent.parent.mailserver != null) && (domain.auth != 'sspi') && (user.emailVerified !== true) && (user.siteadmin != 0xFFFFFFFF)) return; // User must verify it's email first. + // Create mesh if (obj.common.validateString(command.meshname, 1, 64) == false) break; // Meshname is between 1 and 64 characters if (obj.common.validateString(command.desc, 0, 1024) == false) break; // Mesh description is between 0 and 1024 characters diff --git a/package.json b/package.json index bbc73e1d..8e4cf04a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "meshcentral", - "version": "0.2.6-h", + "version": "0.2.6-i", "keywords": [ "Remote Management", "Intel AMT", diff --git a/views/default-min.handlebars b/views/default-min.handlebars index 4fec6384..6918d682 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 8562dccf..a81b59c6 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-mobile.handlebars b/views/default-mobile.handlebars index 4628519d..130acf4b 100644 --- a/views/default-mobile.handlebars +++ b/views/default-mobile.handlebars @@ -237,12 +237,16 @@

Account actions

+
-
Device Groups ( New )

@@ -560,7 +564,7 @@ \ No newline at end of file + MeshCentral - Login
{{{title}}}
{{{title2}}}

Welcome

Connect to your home or office devices from anywhere in the world using MeshCentral, the real time, open source remote monitoring and management web site. You will need to download and install a management agent on your computers. Once installed, computers will show up in the "My Devices" section of this web site and you will be able to monitor them and take control of them.


\ No newline at end of file diff --git a/views/login-mobile-min.handlebars b/views/login-mobile-min.handlebars index 976100b8..e3ed5c10 100644 --- a/views/login-mobile-min.handlebars +++ b/views/login-mobile-min.handlebars @@ -1 +1 @@ - MeshCentral - Login
{{{title}}}
{{{title2}}}
\ No newline at end of file + MeshCentral - Login
{{{title}}}
{{{title2}}}
\ No newline at end of file diff --git a/webserver.js b/webserver.js index 676b614f..482ce881 100644 --- a/webserver.js +++ b/webserver.js @@ -333,7 +333,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) { function handleLogoutRequest(req, res) { const domain = checkUserIpAddress(req, res); - if (domain == null) return; + if ((domain == null) || (domain.auth == 'sspi')) return; + res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' }); // Destroy the user's session to log them out will be re-created next request if (req.session.userid) { @@ -425,7 +426,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) { function handleCreateAccountRequest(req, res) { const domain = checkUserIpAddress(req, res); - if (domain == null) return; + if ((domain == null) || (domain.auth == 'sspi')) return; + if ((domain.newaccounts === 0) || (domain.newaccounts === false)) { res.sendStatus(401); return; } if (!obj.common.validateUsername(req.body.username, 1, 64) || !obj.common.validateEmail(req.body.email, 1, 256) || !obj.common.validateString(req.body.password1, 1, 256) || !obj.common.validateString(req.body.password2, 1, 256) || (req.body.password1 != req.body.password2) || req.body.username == '~' || !obj.common.checkPasswordRequirements(req.body.password1, domain.passwordrequirements)) { req.session.loginmode = 2; @@ -466,7 +468,10 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) { user.salt = salt; user.hash = hash; obj.db.SetUser(user); - if (obj.parent.mailserver != null) { obj.parent.mailserver.sendAccountCheckMail(domain, user.name, user.email); } + + // Send the verification email + if ((obj.parent.mailserver != null) && (domain.auth != 'sspi') && (obj.common.validateEmail(user.email, 1, 256) == true)) { obj.parent.mailserver.sendAccountCheckMail(domain, user.name, user.email); } + }); obj.parent.DispatchEvent(['*', 'server-users'], obj, { etype: 'user', username: user.name, account: user, action: 'accountcreate', msg: 'Account created, email is ' + req.body.email, domain: domain.id }); } @@ -479,7 +484,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) { // Called to process an account reset request function handleResetAccountRequest(req, res) { const domain = checkUserIpAddress(req, res); - if (domain == null) return; + if ((domain == null) || (domain.auth == 'sspi')) return; + if ((domain.newaccounts === 0) || (domain.newaccounts === false)) { res.sendStatus(401); return; } if (!req.body.email || checkEmail(req.body.email) == false) { req.session.loginmode = 3; @@ -511,7 +517,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) { // Called to process a web based email verification request function handleCheckMailRequest(req, res) { const domain = checkUserIpAddress(req, res); - if (domain == null) return; + if ((domain == null) || (domain.auth == 'sspi')) return; + if (req.query.c != null) { var cookie = obj.parent.decodeCookie(req.query.c, obj.parent.mailserver.mailCookieEncryptionKey, 30); if ((cookie != null) && (cookie.u != null) && (cookie.e != null)) { @@ -614,7 +621,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) { function handleDeleteAccountRequest(req, res) { const domain = checkUserIpAddress(req, res); - if (domain == null) return; + if ((domain == null) || (domain.auth == 'sspi')) return; + // Check if the user is logged and we have all required parameters if (!req.session || !req.session.userid || !req.body.apassword1 || (req.body.apassword1 != req.body.apassword2) || (req.session.domainid != domain.id)) { res.redirect(domain.url); return; } var user = obj.users[req.session.userid]; @@ -658,7 +666,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) { // Handle password changes function handlePasswordChangeRequest(req, res) { const domain = checkUserIpAddress(req, res); - if (domain == null) return; + if ((domain == null) || (domain.auth == 'sspi')) return; + // Check if the user is logged and we have all required parameters if (!req.session || !req.session.userid || !req.body.apassword1 || (req.body.apassword1 != req.body.apassword2) || (req.session.domainid != domain.id)) { res.redirect(domain.url); return; } @@ -795,19 +804,19 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) { // Give the web page a list of supported server features features = 0; - if (obj.args.wanonly == true) { features += 1; } // WAN-only mode - if (obj.args.lanonly == true) { features += 2; } // LAN-only mode - if (obj.args.nousers == true) { features += 4; } // Single user mode - if (domain.userQuota == -1) { features += 8; } // No server files mode - if (obj.args.mpstlsoffload) { features += 16; } // No mutual-auth CIRA - if ((parent.config != null) && (parent.config.settings != null) && (parent.config.settings.allowframing == true)) { features += 32; } // Allow site within iframe - if ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly != true)) { features += 64; } // Email invites - if (obj.args.webrtc == true) { features += 128; } // Enable WebRTC (Default false for now) - if (obj.args.clickonce !== false) { features += 256; } // Enable ClickOnce (Default true) - if (obj.args.allowhighqualitydesktop == true) { features += 512; } // Enable AllowHighQualityDesktop (Default false) - if (obj.args.lanonly == true || obj.args.mpsport == 0) { features += 1024; } // No CIRA - if ((obj.parent.serverSelfWriteAllowed == true) && (user != null) && (user.siteadmin == 0xFFFFFFFF)) { features += 2048; } // Server can self-write (Allows self-update) - if ((domain.auth != 'sspi') && (obj.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true)) { features += 4096; } // 2-step login supported + if (obj.args.wanonly == true) { features += 0x0001; } // WAN-only mode + if (obj.args.lanonly == true) { features += 0x0002; } // LAN-only mode + if (obj.args.nousers == true) { features += 0x0004; } // Single user mode + if (domain.userQuota == -1) { features += 0x0008; } // No server files mode + if (obj.args.mpstlsoffload) { features += 0x0010; } // No mutual-auth CIRA + if ((parent.config != null) && (parent.config.settings != null) && (parent.config.settings.allowframing == true)) { features += 0x0020; } // Allow site within iframe + if ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly != true)) { features += 0x0040; } // Email invites + if (obj.args.webrtc == true) { features += 0x0080; } // Enable WebRTC (Default false for now) + if (obj.args.clickonce !== false) { features += 0x0100; } // Enable ClickOnce (Default true) + if (obj.args.allowhighqualitydesktop == true) { features += 0x0200; } // Enable AllowHighQualityDesktop (Default false) + if (obj.args.lanonly == true || obj.args.mpsport == 0) { features += 0x0400; } // No CIRA + if ((obj.parent.serverSelfWriteAllowed == true) && (user != null) && (user.siteadmin == 0xFFFFFFFF)) { features += 0x0800; } // Server can self-write (Allows self-update) + if ((domain.auth != 'sspi') && (obj.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true)) { features += 0x1000; } // 2-step login supported // Send the master web application if ((!obj.args.user) && (obj.args.nousers != true) && (nologout == false)) { logoutcontrol += ' Logout'; } // If a default user is in use or no user mode, don't display the logout button