mirror of
https://github.com/Ylianst/MeshCentral.git
synced 2024-11-22 12:52:50 +03:00
Server improvements, first Intel AMT CCM activation.
This commit is contained in:
parent
d92d5bcb9b
commit
1549c1ab39
1
agents/meshcmd.min.js
vendored
1
agents/meshcmd.min.js
vendored
File diff suppressed because one or more lines are too long
@ -88,16 +88,13 @@ function createMeshCore(agent) {
|
||||
var net = require('net');
|
||||
var fs = require('fs');
|
||||
var rtc = require('ILibWebRTC');
|
||||
var amt = null;
|
||||
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;
|
||||
var amtPolicy = null;
|
||||
|
||||
// If we are running in Duktape, agent will be null
|
||||
@ -165,33 +162,25 @@ function createMeshCore(agent) {
|
||||
if (mesh.isControlChannelConnected) { mesh.SendCommand({ "action": "smbios", "value": SMBiosTablesRaw }); }
|
||||
|
||||
// If SMBios tables say that AMT is present, try to connect MEI
|
||||
if (SMBiosTables.amtInfo && (SMBiosTables.amtInfo.AMT == true)) { resetMei(); }
|
||||
if (SMBiosTables.amtInfo && (SMBiosTables.amtInfo.AMT == true)) {
|
||||
var amtmodule = require('amt-manage');
|
||||
amt = new amtmodule(mesh, db, true);
|
||||
amt.onStateChange = function (state) { if (state == 2) { sendPeriodicServerUpdate(1); } }
|
||||
if (amtPolicy != null) { amt.setPolicy(amtPolicy); }
|
||||
amt.start();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (ex) { sendConsoleText(ex); }
|
||||
} catch (ex) { sendConsoleText("ex1: " + ex); }
|
||||
|
||||
// Try to load up the WIFI scanner
|
||||
try {
|
||||
var wifiScannerLib = require('wifi-scanner');
|
||||
wifiScanner = new wifiScannerLib();
|
||||
wifiScanner.on('accessPoint', function (data) { sendConsoleText(data); });
|
||||
wifiScanner.on('accessPoint', function (data) { sendConsoleText("wifiScanner: " + data); });
|
||||
} catch (ex) { wifiScannerLib = null; wifiScanner = null; }
|
||||
|
||||
// Try to load Intel AMT policy
|
||||
try { amtPolicy = JSON.parse(db.Get('amtPolicy')); } catch (ex) { amtPolicy = null; }
|
||||
|
||||
// Try to load up the MEI module
|
||||
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; }
|
||||
}
|
||||
|
||||
// Get our location (lat/long) using our public IP address
|
||||
var getIpLocationDataExInProgress = false;
|
||||
var getIpLocationDataExCounts = [0, 0];
|
||||
@ -459,7 +448,7 @@ function createMeshCore(agent) {
|
||||
case 'pskill': {
|
||||
// Kill a process
|
||||
if (data.value) {
|
||||
try { process.kill(data.value); } catch (e) { sendConsoleText(JSON.stringify(e)); }
|
||||
try { process.kill(data.value); } catch (e) { sendConsoleText("pskill: " + JSON.stringify(e)); }
|
||||
}
|
||||
break;
|
||||
}
|
||||
@ -528,6 +517,7 @@ function createMeshCore(agent) {
|
||||
// Store the latest Intel AMT policy
|
||||
amtPolicy = data.amtPolicy;
|
||||
if (data.amtPolicy != null) { db.Put('amtPolicy', JSON.stringify(data.amtPolicy)); } else { db.Put('amtPolicy', null); }
|
||||
if (amt != null) { amt.setPolicy(amtPolicy); }
|
||||
break;
|
||||
}
|
||||
case 'getScript': {
|
||||
@ -1160,20 +1150,22 @@ function createMeshCore(agent) {
|
||||
break;
|
||||
}
|
||||
case 'amtreset': {
|
||||
resetMei();
|
||||
resetMicroLms();
|
||||
response = 'Done.';
|
||||
if (amt != null) { amt.reset(); response = 'Done.'; }
|
||||
break;
|
||||
}
|
||||
case 'amtlmsreset': {
|
||||
if (amt != null) { amt.lmsreset(); response = 'Done.'; }
|
||||
break;
|
||||
}
|
||||
case 'amtccm': {
|
||||
if (amtMei == null) { response = 'Intel AMT not supported.'; } else {
|
||||
if (amt == null) { response = 'Intel AMT not supported.'; } else {
|
||||
if (args['_'].length != 1) { response = 'Proper usage: amtccm (adminPassword)'; } // Display usage
|
||||
else { activeToCCM(args['_'][0]); }
|
||||
else { amt.setPolicy({ type: 0 }); amt.activeToCCM(args['_'][0]); }
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'amtdeactivate': {
|
||||
if (amtMei == null) { response = 'Intel AMT not supported.'; } else { deactivateCCM(); }
|
||||
if (amt == null) { response = 'Intel AMT not supported.'; } else { amt.setPolicy({ type: 0 }); amt.deactivateCCM(); }
|
||||
break;
|
||||
}
|
||||
case 'amtpolicy': {
|
||||
@ -1267,7 +1259,7 @@ function createMeshCore(agent) {
|
||||
}
|
||||
case 'info': { // Return information about the agent and agent core module
|
||||
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 (amt != null) { response += '\r\nBuilt-in LMS: ' + ['Disabled', 'Connecting..', 'Connected'][amt.lmsstate] + '.'; }
|
||||
if (meshCoreObj.osdesc) { response += '\r\nOS: ' + meshCoreObj.osdesc + '.'; }
|
||||
response += '\r\nModules: ' + addedModules.join(', ') + '.';
|
||||
response += '\r\nServer Connection: ' + mesh.isControlChannelConnected + ', State: ' + meshServerConnectionState + '.';
|
||||
@ -1487,11 +1479,13 @@ function createMeshCore(agent) {
|
||||
break;
|
||||
}
|
||||
case 'amt': { // Show Intel AMT status
|
||||
getAmtInfo(function (state) {
|
||||
var resp = 'Intel AMT not detected.';
|
||||
if (state != null) { resp = objToString(state, 0, ' ', true); }
|
||||
sendConsoleText(resp, sessionid);
|
||||
});
|
||||
if (amt != null) {
|
||||
amt.getAmtInfo(function (state) {
|
||||
var resp = 'Intel AMT not detected.';
|
||||
if (state != null) { resp = objToString(state, 0, ' ', true); }
|
||||
sendConsoleText(resp, sessionid);
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'netinfo': { // Show network interface information
|
||||
@ -1646,9 +1640,9 @@ function createMeshCore(agent) {
|
||||
if (meshServerConnectionState == 0) return; // Not connected to server, do nothing.
|
||||
if (!flags) { flags = 0xFFFFFFFF; }
|
||||
|
||||
if (flags & 1) {
|
||||
if ((flags & 1) && (amt != null)) {
|
||||
// If we have a connected MEI, get Intel ME information
|
||||
getAmtInfo(function (meinfo) {
|
||||
amt.getAmtInfo(function (meinfo) {
|
||||
try {
|
||||
if (meinfo == null) return;
|
||||
var intelamt = {}, p = false;
|
||||
@ -1675,59 +1669,6 @@ function createMeshCore(agent) {
|
||||
}
|
||||
}
|
||||
|
||||
// Get Intel AMT information using MEI
|
||||
function getAmtInfo(func) {
|
||||
if (amtMei == null || amtMeiConnected != 2) { if (func != null) { func(null); } return; }
|
||||
try {
|
||||
amtMeiTmpState = { Flags: 0 }; // Flags: 1=EHBC, 2=CCM, 4=ACM
|
||||
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.getMACAddresses(function (result) { if (result) { amtMeiTmpState.mac = result; } });
|
||||
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; }
|
||||
}
|
||||
|
||||
// Called on MicroLMS Intel AMT user notification
|
||||
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; } // SOL
|
||||
case 'iAMT0052': { if (amtMessageArg == '1') { notify = 'Intel® AMT KVM connected'; } else if (amtMessageArg == '2') { notify = 'Intel® AMT KVM disconnected'; } break; } // KVM
|
||||
default: { break; }
|
||||
}
|
||||
|
||||
// Send to the entire mesh, no sessionid or userid specified.
|
||||
if (notify != null) { mesh.SendCommand({ "action": "msg", "type": "notify", "value": notify, "tag": "general" }); }
|
||||
}
|
||||
|
||||
function resetMicroLms() {
|
||||
// Launch LMS
|
||||
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('bind', function (map) { });
|
||||
amtLms.on('notify', function (data, options, str, code) {
|
||||
if (code == 'iAMT0052-3') {
|
||||
obj.kvmGetData();
|
||||
} else {
|
||||
//if (str != null) { sendConsoleText('Intel AMT LMS: ' + str); }
|
||||
handleAmtNotification(data);
|
||||
}
|
||||
});
|
||||
} catch (e) { amtLmsState = -1; amtLms = null; }
|
||||
}
|
||||
|
||||
// Starting function
|
||||
obj.start = function () {
|
||||
@ -1739,7 +1680,7 @@ function createMeshCore(agent) {
|
||||
//var args = parseArgs(process.argv);
|
||||
//console.log(args);
|
||||
|
||||
resetMicroLms();
|
||||
//resetMicroLms();
|
||||
|
||||
// Setup logged in user monitoring (THIS IS BROKEN IN WIN7)
|
||||
try {
|
||||
@ -1778,323 +1719,6 @@ function createMeshCore(agent) {
|
||||
s.data = onWebSocketData;
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// KVM Data Channel
|
||||
//
|
||||
|
||||
obj.setupMeiOsAdmin = function (func, state) {
|
||||
if ((amtMei == null) || (amtMeiConnected != 2)) { return; } // If there is no MEI, don't bother with this.
|
||||
amtMei.getLocalSystemAccount(function (x) {
|
||||
if (x == null) return;
|
||||
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);
|
||||
obj.osamtstack = new amt(oswsstack);
|
||||
if (func) { func(state); }
|
||||
//var AllWsman = "CIM_SoftwareIdentity,IPS_SecIOService,IPS_ScreenSettingData,IPS_ProvisioningRecordLog,IPS_HostBasedSetupService,IPS_HostIPSettings,IPS_IPv6PortSettings".split(',');
|
||||
//obj.osamtstack.BatchEnum(null, AllWsman, startLmsWsmanResponse, null, true);
|
||||
//*************************************
|
||||
// Setup KVM data channel if this is Intel AMT 12 or above
|
||||
amtMei.getVersion(function (x) {
|
||||
if (x == null) return;
|
||||
var amtver = null;
|
||||
try { for (var i in x.Versions) { if (x.Versions[i].Description == 'AMT') amtver = parseInt(x.Versions[i].Version.split('.')[0]); } } catch (e) { }
|
||||
if ((amtver != null) && (amtver >= 12)) {
|
||||
obj.kvmGetData('skip'); // Clear any previous data, this is a dummy read to about handling old data.
|
||||
obj.kvmTempTimer = setInterval(function () { obj.kvmGetData(); }, 2000); // Start polling for KVM data.
|
||||
obj.kvmSetData(JSON.stringify({ action: 'restart', ver: 1 })); // Send a restart command to advise the console if present that MicroLMS just started.
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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 });
|
||||
//webRtcDesktop.kvm.on('end', function () { console.log('WebRTC DataChannel closed2'); obj.webRtcCleanUp(); });
|
||||
//webRtcDesktop.rtcchannel.on('data', function (data) { console.log('WebRTC data: ' + data); });
|
||||
});
|
||||
obj.kvmSetData(JSON.stringify({ action: 'answer', ver: 1, sdp: webRtcDesktop.webrtc.setOffer(data.sdp) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Polyfill path.join
|
||||
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('/');
|
||||
}
|
||||
};
|
||||
|
||||
// Process KVM control channel data
|
||||
obj.kvmCtrlData = function(channel, cmd) {
|
||||
if (cmd.length > 0 && cmd.charCodeAt(0) != 123) {
|
||||
// This is upload data
|
||||
if (this.fileupload != null) {
|
||||
cmd = Buffer.from(cmd, 'base64');
|
||||
var header = cmd.readUInt32BE(0);
|
||||
if ((header == 0x01000000) || (header == 0x01000001)) {
|
||||
fs.writeSync(this.fileupload.fp, cmd.slice(4));
|
||||
channel.write({ action: 'upload', sub: 'ack', reqid: this.fileupload.reqid });
|
||||
if (header == 0x01000001) { fs.closeSync(this.fileupload.fp); this.fileupload = null; } // Close the file
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
//console.log('KVM Ctrl Data', cmd);
|
||||
//sendConsoleText('KVM Ctrl Data: ' + cmd);
|
||||
|
||||
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; } // Add '/' to paths on non-windows
|
||||
switch (cmd.action) {
|
||||
case 'ping': {
|
||||
// This is a keep alive
|
||||
channel.write({ action: 'pong' });
|
||||
break;
|
||||
}
|
||||
case 'lock': {
|
||||
// Lock the current user out of the desktop
|
||||
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': {
|
||||
/*
|
||||
// Close the watcher if required
|
||||
var samepath = ((this.httprequest.watcher != undefined) && (cmd.path == this.httprequest.watcher.path));
|
||||
if ((this.httprequest.watcher != undefined) && (samepath == false)) {
|
||||
//console.log('Closing watcher: ' + this.httprequest.watcher.path);
|
||||
//this.httprequest.watcher.close(); // TODO: This line causes the agent to crash!!!!
|
||||
delete this.httprequest.watcher;
|
||||
}
|
||||
*/
|
||||
|
||||
// Send the folder content to the browser
|
||||
var response = getDirectoryInfo(cmd.path);
|
||||
if (cmd.reqid != undefined) { response.reqid = cmd.reqid; }
|
||||
channel.write(response);
|
||||
|
||||
/*
|
||||
// Start the directory watcher
|
||||
if ((cmd.path != '') && (samepath == false)) {
|
||||
var watcher = fs.watch(cmd.path, onFileWatcher);
|
||||
watcher.tunnel = this.httprequest;
|
||||
watcher.path = cmd.path;
|
||||
this.httprequest.watcher = watcher;
|
||||
//console.log('Starting watcher: ' + this.httprequest.watcher.path);
|
||||
}
|
||||
*/
|
||||
break;
|
||||
}
|
||||
case 'mkdir': {
|
||||
// Create a new empty folder
|
||||
fs.mkdirSync(cmd.path);
|
||||
break;
|
||||
}
|
||||
case 'rm': {
|
||||
// Remove many files or folders
|
||||
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': {
|
||||
// Rename a file or folder
|
||||
try { fs.renameSync(path.join(cmd.path, cmd.oldname), path.join(cmd.path, cmd.newname)); } catch (e) { console.log(e); }
|
||||
break;
|
||||
}
|
||||
case 'download': {
|
||||
// Download a file, to browser
|
||||
var sendNextBlock = 0;
|
||||
if (cmd.sub == 'start') { // Setup the download
|
||||
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)) { // Download commands
|
||||
if (cmd.sub == 'startack') { sendNextBlock = 8; } else if (cmd.sub == 'stop') { delete this.filedownload; } else if (cmd.sub == 'ack') { sendNextBlock = 1; }
|
||||
}
|
||||
// Send the next download block(s)
|
||||
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(0x01000001, 0); fs.closeSync(this.filedownload.f); delete this.filedownload; sendNextBlock = 0; } else { buf.writeInt32BE(0x01000000, 0); }
|
||||
channel.write(buf.slice(0, len + 4).toString('base64')); // Write as Base64
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'upload': {
|
||||
// Upload a file, from browser
|
||||
if (cmd.sub == 'start') { // Start the upload
|
||||
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') { // Stop the upload
|
||||
if (this.fileupload != null) { fs.closeSync(this.fileupload.fp); this.fileupload = null; }
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'copy': {
|
||||
// Copy a bunch of files from scpath to dspath
|
||||
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': {
|
||||
// Move a bunch of files from scpath to dspath
|
||||
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 () { });
|
||||
}
|
||||
|
||||
// Delete a directory with a files and directories within it
|
||||
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()) { // recurse
|
||||
deleteFolderRecursive(curPath, true);
|
||||
} else { // delete file
|
||||
fs.unlinkSync(curPath);
|
||||
}
|
||||
});
|
||||
}
|
||||
fs.unlinkSync(path);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
//
|
||||
// Deactivate Intel AMT CCM
|
||||
//
|
||||
|
||||
// When called, this will use MEI to deactivate Intel AMT when it's in CCM mode. Simply calls "unprovision" on MEI and checks the return code.
|
||||
function deactivateCCM() {
|
||||
amtMei.unprovision(1, function (status) { if (status == 0) { sendConsoleText('Success deactivating Intel AMT CCM.'); } else { sendConsoleText('Intel AMT CCM deactivation error: ' + status); } });
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// Activate Intel AMT to CCM
|
||||
//
|
||||
|
||||
function activeToCCM(adminpass) {
|
||||
sendConsoleText('Trying to get local account info...');
|
||||
amtMei.getLocalSystemAccount(function (x) {
|
||||
if (x.user && x.pass) {
|
||||
sendConsoleText('Intel AMT local account info: User=' + x.user + ', Pass=' + 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);
|
||||
sendConsoleText('Trying to get Intel AMT activation information...');
|
||||
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 information, 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;
|
||||
}
|
||||
|
||||
|
1
agents/meshcore.min.js
vendored
1
agents/meshcore.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcmd_min/amt-lme.min.js
vendored
1
agents/modules_meshcmd_min/amt-lme.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcmd_min/amt-mei.min.js
vendored
1
agents/modules_meshcmd_min/amt-mei.min.js
vendored
File diff suppressed because one or more lines are too long
@ -1 +0,0 @@
|
||||
function AMTScanner(){var a=require("events").inherits(this);a.createEvent("found");this.dgram=require("dgram");this.buildRmcpPing=function(c){var b=Buffer.from("06000006000011BE80000000","hex");b[9]=c;return b};this.parseRmcpPacket=function(h,b,g,d){if(b==null||b.length<20){return}var f={};if(((b[12]==0)||(b[13]!=0)||(b[14]!=1)||(b[15]!=87))&&(b[21]&32)){f.servertag=b[9];f.minorVersion=b[18]&15;f.majorVersion=(b[18]>>4)&15;f.provisioningState=b[19]&3;var e=(b[16]*256)+b[17];var c=((b[19]&4)!=0)?true:false;f.openPorts=[e];f.address=g.address;if(c==true){f.openPorts=[16992,16993]}if(d!==undefined){d(h,f)}}};this.parseIPv4Range=function(f){if(f==undefined||f==null){return null}var g=f.split("-");if(g.length==2){return{min:this.parseIpv4Addr(g[0]),max:this.parseIpv4Addr(g[1])}}g=f.split("/");if(g.length==2){var c=this.parseIpv4Addr(g[0]),e=parseInt(g[1]),d=0;if(e<=16||e>32){return null}e=32-e;for(var b=0;b<e;b++){d=(d<<1);d++}return{min:c&(4294967295-d),max:(c&(4294967295-d))+d}}g=this.parseIpv4Addr(f);if(g==null){return null}return{min:g,max:g}};this.parseIpv4Addr=function(b){var c=b.split(".");if(c.length==4){return(parseInt(c[0])<<24)+(parseInt(c[1])<<16)+(parseInt(c[2])<<8)+(parseInt(c[3])<<0)}return null};this.IPv4NumToStr=function(b){return((b>>24)&255)+"."+((b>>16)&255)+"."+((b>>8)&255)+"."+(b&255)};this.scan=function(d,g){var c=this.parseIPv4Range(d);var e=this.buildRmcpPing(0);var f=this.dgram.createSocket({type:"udp4"});f.parent=this;f.scanResults=[];f.on("error",function(i){console.log("Error:"+i)});f.on("message",function(i,j){if(j.size>4){this.parent.parseRmcpPacket(this,i,j,function(l,k){l.scanResults.push(k)})}});f.on("listening",function(){for(var j=c.min;j<=c.max;j++){f.send(e,623,f.parent.IPv4NumToStr(j))}});f.bind({address:"0.0.0.0",port:0,exclusive:true});var h=setTimeout(function b(){f.close();f.parent.emit("found",f.scanResults);delete f},g)}}module.exports=AMTScanner;
|
1
agents/modules_meshcmd_min/amt-script.min.js
vendored
1
agents/modules_meshcmd_min/amt-script.min.js
vendored
File diff suppressed because one or more lines are too long
@ -1 +0,0 @@
|
||||
function CreateWsmanComm(){var a={};a.PendingAjax=[];a.ActiveAjaxCount=0;a.MaxActiveAjaxCount=1;a.FailAllError=0;a.digest=null;a.RequestCount=0;if(arguments.length==1&&typeof(arguments[0]=="object")){a.host=arguments[0].host;a.port=arguments[0].port;a.authToken=arguments[0].authToken;a.tls=arguments[0].tls}else{a.host=arguments[0];a.port=arguments[1];a.user=arguments[2];a.pass=arguments[3];a.tls=arguments[4]}a.PerformAjax=function(d,c,f,e,g,b){if((a.ActiveAjaxCount==0||((a.ActiveAjaxCount<a.MaxActiveAjaxCount)&&(a.challengeParams!=null)))&&a.PendingAjax.length==0){a.PerformAjaxEx(d,c,f,g,b)}else{if(e==1){a.PendingAjax.unshift([d,c,f,g,b])}else{a.PendingAjax.push([d,c,f,g,b])}}};a.PerformNextAjax=function(){if(a.ActiveAjaxCount>=a.MaxActiveAjaxCount||a.PendingAjax.length==0){return}var b=a.PendingAjax.shift();a.PerformAjaxEx(b[0],b[1],b[2],b[3],b[4]);a.PerformNextAjax()};a.PerformAjaxEx=function(d,c,g,h,b){if(a.FailAllError!=0){if(a.FailAllError!=999){a.gotNextMessagesError({status:a.FailAllError},"error",null,[d,c,g])}return}if(!d){d=""}if(a.digest==null){if(a.authToken){a.digest=require("http-digest").create({authToken:a.authToken})}else{a.digest=require("http-digest").create(a.user,a.pass)}a.digest.http=require("http")}var f={protocol:(a.tls==1?"https:":"http:"),method:"POST",host:a.host,path:"/wsman",port:a.port,rejectUnauthorized:false,checkServerIdentity:function(i){console.log("checkServerIdentity",JSON.stringify(i))}};var e=a.digest.request(f);e.on("error",function(i){a.gotNextMessagesError({status:600},"error",null,[d,c,g])});e.on("response",function(i){if(i.statusCode!=200){a.gotNextMessagesError({status:i.statusCode},"error",null,[d,c,g])}else{i.acc="";i.on("data",function(j){this.acc+=j});i.on("end",function(){a.gotNextMessages(i.acc,"success",{status:i.statusCode},[d,c,g])})}});e.end(d);a.ActiveAjaxCount++;return e};a.pendingAjaxCall=[];a.gotNextMessages=function(c,e,d,b){a.ActiveAjaxCount--;if(a.FailAllError==999){return}if(a.FailAllError!=0){b[1](null,a.FailAllError,b[2]);return}if(d.status!=200){b[1](null,d.status,b[2]);return}b[1](c,200,b[2]);a.PerformNextAjax()};a.gotNextMessagesError=function(d,e,c,b){a.ActiveAjaxCount--;if(a.FailAllError==999){return}if(a.FailAllError!=0){b[1](null,a.FailAllError,b[2]);return}if(a.FailAllError!=999){b[1]({Header:{HttpError:d.status}},d.status,b[2])}a.PerformNextAjax()};a.CancelAllQueries=function(b){while(a.PendingAjax.length>0){var c=a.PendingAjax.shift();c[1](null,b,c[2])}};return a}module.exports=CreateWsmanComm;
|
1
agents/modules_meshcmd_min/amt-wsman.min.js
vendored
1
agents/modules_meshcmd_min/amt-wsman.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcmd_min/amt-xml.min.js
vendored
1
agents/modules_meshcmd_min/amt-xml.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcmd_min/amt.min.js
vendored
1
agents/modules_meshcmd_min/amt.min.js
vendored
File diff suppressed because one or more lines are too long
@ -1 +0,0 @@
|
||||
var GM=require("_GenericMarshal");function processManager(){this._ObjectID="process-manager";switch(process.platform){case"win32":this._kernel32=GM.CreateNativeProxy("kernel32.dll");this._kernel32.CreateMethod("GetLastError");this._kernel32.CreateMethod("CreateToolhelp32Snapshot");this._kernel32.CreateMethod("Process32First");this._kernel32.CreateMethod("Process32Next");break;case"linux":case"darwin":this._childProcess=require("child_process");break;default:throw (process.platform+" not supported");break}this.enumerateProcesses=function a(){var d=require("promise");var e=new d(function(g,f){this._res=g;this._rej=f});this.getProcesses(function(g,f){f._res(g)},e);return(e)};this.getProcesses=function b(d){switch(process.platform){default:throw ("Enumerating processes on "+process.platform+" not supported");break;case"win32":var n={};var e=this._kernel32.CreateToolhelp32Snapshot(2,0);var g=GM.CreateVariable(304);g.toBuffer().writeUInt32LE(304,0);var j=this._kernel32.Process32First(e,g);while(j.Val){n[g.Deref(8,4).toBuffer().readUInt32LE(0)]={pid:g.Deref(8,4).toBuffer().readUInt32LE(0),cmd:g.Deref(GM.PointerSize==4?36:44,260).String};j=this._kernel32.Process32Next(e,g)}if(d){d.apply(this,[n])}break;case"linux":if(!this._psp){this._psp={}}var l=this._childProcess.execFile("/bin/ps",["ps","-uxa"],{type:this._childProcess.SpawnTypes.TERM});this._psp[l.pid]=l;l.Parent=this;l.ps="";l.callback=d;l.args=[];for(var f=1;f<arguments.length;++f){l.args.push(arguments[f])}l.on("exit",function k(){delete this.Parent._psp[this.pid];var r={},q=this.ps.split("\x0D\x0A"),o={},p=0;for(var h in q){var t=q[h].split(" ");var s=[];for(var u in t){if(h==0&&t[u]){o[t[u]]=p++}if(h>0&&t[u]){s.push(t[u])}}if(h>0){if(s[o.PID]){r[s[o.PID]]={pid:o.PID,user:s[o.USER],cmd:s[o.COMMAND]}}}}if(this.callback){this.args.unshift(r);this.callback.apply(this.parent,this.args)}});l.stdout.on("data",function(h){this.parent.ps+=h.toString()});break;case"darwin":var m=require("promise");var l=new m(function(i,h){this._res=i;this._rej=h});l.pm=this;l.callback=d;l.args=[];for(var f=1;f<arguments.length;++f){l.args.push(arguments[f])}l.child=this._childProcess.execFile("/bin/ps",["ps","-xa"]);l.child.promise=l;l.child.stdout.ps="";l.child.stdout.on("data",function(h){this.ps+=h.toString()});l.child.on("exit",function(){var p=this.stdout.ps.split("\n");var q=p[0].split("PID")[0].length+3;var h=p[0].split("CMD")[0].length;var r={};for(var o=1;o<p.length;++o){if(p[o].length>0){r[p[o].substring(0,q).trim()]={pid:p[o].substring(0,q).trim(),cmd:p[o].substring(h)}}}this.promise._res(r)});l.then(function(h){this.args.unshift(h);this.callback.apply(this.pm,this.args)});break}};this.getProcessInfo=function c(g){switch(process.platform){default:throw ("getProcessInfo() not supported for "+process.platform);break;case"linux":var h=require("fs").readFileSync("/proc/"+g+"/status");var e={};var f=h.toString().split("\n");for(var d in f){var j=f[d].split(":");if(j.length>1){j[1]=j[1].trim()}e[j[0]]=j[1]}return(e);break}}}module.exports=new processManager();
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
1
agents/modules_meshcmd_min/smbios.min.js
vendored
1
agents/modules_meshcmd_min/smbios.min.js
vendored
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
536
agents/modules_meshcore/amt-manage.js
Normal file
536
agents/modules_meshcore/amt-manage.js
Normal file
@ -0,0 +1,536 @@
|
||||
/*
|
||||
Copyright 2018-2019 Intel Corporation
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Intel(r) AMT Management
|
||||
* @author Ylian Saint-Hilaire
|
||||
* @version v0.1.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* Construct a AmtStackCreateService object, this ia the main Intel AMT communication stack.
|
||||
* @constructor
|
||||
*/
|
||||
function AmtManager(agent, db, isdebug) {
|
||||
var sendConsole = function (msg) { agent.SendCommand({ "action": "msg", "type": "console", "value": msg }); }
|
||||
var debug = function (msg) { if (isdebug) { sendConsole('amt-manager: ' + msg); } }
|
||||
var amtMei = null, amtMeiState = 0;
|
||||
var amtLms = null, amtLmsState = 0;
|
||||
var amtGetVersionResult = null;
|
||||
var oswsstack = null;
|
||||
var osamtstack = null;
|
||||
var amtpolicy = null;
|
||||
var obj = this;
|
||||
obj.state = 0;
|
||||
obj.lmsstate = 0;
|
||||
obj.onStateChange = null;
|
||||
obj.setDebug = function (x) { isdebug = x; }
|
||||
|
||||
// Set current Intel AMT activation policy
|
||||
obj.setPolicy = function (policy) {
|
||||
if (JSON.stringify(amtpolicy) != JSON.stringify(policy)) {
|
||||
amtpolicy = policy;
|
||||
//debug('AMT policy set: ' + JSON.stringify(policy));
|
||||
obj.applyPolicy();
|
||||
}
|
||||
}
|
||||
|
||||
// Try to load up the MEI module
|
||||
var rebindToMeiRetrys = 0;
|
||||
obj.reset = function () {
|
||||
++rebindToMeiRetrys;
|
||||
amtMei = null, amtMeiState = 0, amtLms = null, amtLmsState = 0, obj.state = 0, obj.lmsstate = 0;
|
||||
//debug('Binding to MEI');
|
||||
try {
|
||||
var amtMeiLib = require('amt-mei');
|
||||
amtMei = new amtMeiLib();
|
||||
amtMei.on('error', function (e) { debug('MEI error'); amtMei = null; amtMeiState = -1; obj.state = -1; obj.onStateChange(amtMeiState); });
|
||||
amtMei.getVersion(function (result) {
|
||||
if (result == null) {
|
||||
amtMeiState = -1;
|
||||
obj.state = -1;
|
||||
if (obj.onStateChange != null) { obj.onStateChange(amtMeiState); }
|
||||
if (rebindToMeiRetrys < 10) { setTimeout(obj.reset, 10000); }
|
||||
} else {
|
||||
amtGetVersionResult = result;
|
||||
amtMeiState = 2;
|
||||
obj.state = 2;
|
||||
rebindToMeiRetrys = 0;
|
||||
if (obj.onStateChange != null) { obj.onStateChange(amtMeiState); }
|
||||
//debug('MEI binded');
|
||||
obj.lmsreset();
|
||||
}
|
||||
});
|
||||
} catch (ex) { debug('MEI exception: ' + ex); amtMei = null; amtMeiState = -1; obj.state = -1; }
|
||||
}
|
||||
|
||||
// Get Intel AMT information using MEI
|
||||
var amtMeiTmpState = null;
|
||||
obj.getAmtInfo = function(func) {
|
||||
if ((amtMei == null) || (amtMeiState < 2)) { if (func != null) { func(null); } return; }
|
||||
try {
|
||||
amtMeiTmpState = { Flags: 0 }; // Flags: 1=EHBC, 2=CCM, 4=ACM
|
||||
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.getMACAddresses(function (result) { if (result) { amtMeiTmpState.mac = result; } });
|
||||
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; }
|
||||
}
|
||||
|
||||
// Called on MicroLMS Intel AMT user notification
|
||||
var handleAmtNotification = function(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; } // SOL
|
||||
case 'iAMT0052': { if (amtMessageArg == '1') { notify = 'Intel® AMT KVM connected'; } else if (amtMessageArg == '2') { notify = 'Intel® AMT KVM disconnected'; } break; } // KVM
|
||||
default: { break; }
|
||||
}
|
||||
|
||||
// Sent to the entire group, no sessionid or userid specified.
|
||||
if (notify != null) { agent.SendCommand({ "action": "msg", "type": "notify", "value": notify, "tag": "general" }); }
|
||||
}
|
||||
|
||||
// Launch LMS
|
||||
obj.lmsreset = function () {
|
||||
//debug('Binding to LMS');
|
||||
var amtLms = null, amtLmsState = 0;
|
||||
obj.lmsstate = 0;
|
||||
try {
|
||||
var lme_heci = require('amt-lme');
|
||||
amtLmsState = 1;
|
||||
obj.lmsstate = 1;
|
||||
amtLms = new lme_heci();
|
||||
amtLms.on('error', function (e) { amtLmsState = 0; obj.lmsstate = 0; amtLms = null; debug('LMS error'); setupMeiOsAdmin(1); });
|
||||
amtLms.on('connect', function () { amtLmsState = 2; obj.lmsstate = 2; debug('LMS connected'); setupMeiOsAdmin(2); });
|
||||
//amtLms.on('bind', function (map) { });
|
||||
amtLms.on('notify', function (data, options, str, code) {
|
||||
//debug('LMS notify');
|
||||
if (code == 'iAMT0052-3') {
|
||||
kvmGetData();
|
||||
} else {
|
||||
//if (str != null) { debug('Intel AMT LMS: ' + str); }
|
||||
handleAmtNotification(data);
|
||||
}
|
||||
});
|
||||
} catch (e) { amtLmsState = -1; obj.lmsstate = -1; amtLms = null; }
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// KVM Data Channel
|
||||
//
|
||||
|
||||
var setupMeiOsAdmin = function (state) {
|
||||
//debug('Setup MEI OS Admin');
|
||||
if ((amtMei == null) || (amtMeiState < 2) || (amtGetVersionResult == null)) { return; } // If there is no MEI, don't bother with obj.
|
||||
amtMei.getLocalSystemAccount(function (x) {
|
||||
if (x == null) return;
|
||||
//debug('getLocalSystemAccount ' + JSON.stringify(x));
|
||||
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);
|
||||
//if (func) { func(state); }
|
||||
|
||||
// We got the $$OsAdmin account setup.
|
||||
amtMeiState = 3;
|
||||
obj.state = 3;
|
||||
if (obj.onStateChange != null) { obj.onStateChange(amtMeiState); }
|
||||
obj.applyPolicy();
|
||||
|
||||
//var AllWsman = "CIM_SoftwareIdentity,IPS_SecIOService,IPS_ScreenSettingData,IPS_ProvisioningRecordLog,IPS_HostBasedSetupService,IPS_HostIPSettings,IPS_IPv6PortSettings".split(',');
|
||||
//osamtstack.BatchEnum(null, AllWsman, startLmsWsmanResponse, null, true);
|
||||
//*************************************
|
||||
// Setup KVM data channel if this is Intel AMT 12 or above
|
||||
var amtver = null;
|
||||
try { for (var i in amtGetVersionResult.Versions) { if (amtGetVersionResult.Versions[i].Description == 'AMT') amtver = parseInt(amtGetVersionResult.Versions[i].Version.split('.')[0]); } } catch (e) { }
|
||||
if ((amtver != null) && (amtver >= 12)) {
|
||||
debug('KVM data channel setup');
|
||||
kvmGetData('skip'); // Clear any previous data, this is a dummy read to about handling old data.
|
||||
obj.kvmTempTimer = setInterval(function () { kvmGetData(); }, 2000); // Start polling for KVM data.
|
||||
kvmSetData(JSON.stringify({ action: 'restart', ver: 1 })); // Send a restart command to advise the console if present that MicroLMS just started.
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var kvmGetData = function (tag) {
|
||||
osamtstack.IPS_KVMRedirectionSettingData_DataChannelRead(obj.kvmDataGetResponse, tag);
|
||||
}
|
||||
|
||||
var 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;
|
||||
var kvmProcessData = function (realms, messageId, val) {
|
||||
var data = null;
|
||||
try { data = JSON.parse(val) } catch (e) { }
|
||||
if ((data != null) && (data.action)) {
|
||||
if (data.action == 'present') { 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 });
|
||||
//webRtcDesktop.kvm.on('end', function () { debug('WebRTC DataChannel closed2'); obj.webRtcCleanUp(); });
|
||||
//webRtcDesktop.rtcchannel.on('data', function (data) { debug('WebRTC data: ' + data); });
|
||||
});
|
||||
kvmSetData(JSON.stringify({ action: 'answer', ver: 1, sdp: webRtcDesktop.webrtc.setOffer(data.sdp) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process KVM control channel data
|
||||
var kvmCtrlData = function (channel, cmd) {
|
||||
if (cmd.length > 0 && cmd.charCodeAt(0) != 123) {
|
||||
// This is upload data
|
||||
if (obj.fileupload != null) {
|
||||
cmd = Buffer.from(cmd, 'base64');
|
||||
var header = cmd.readUInt32BE(0);
|
||||
if ((header == 0x01000000) || (header == 0x01000001)) {
|
||||
fs.writeSync(obj.fileupload.fp, cmd.slice(4));
|
||||
channel.write({ action: 'upload', sub: 'ack', reqid: obj.fileupload.reqid });
|
||||
if (header == 0x01000001) { fs.closeSync(obj.fileupload.fp); obj.fileupload = null; } // Close the file
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
debug('KVM Ctrl Data: ' + cmd);
|
||||
//sendConsoleText('KVM Ctrl Data: ' + cmd);
|
||||
|
||||
try { cmd = JSON.parse(cmd); } catch (ex) { debug('Invalid JSON: ' + cmd); return; }
|
||||
if ((cmd.path != null) && (process.platform != 'win32') && (cmd.path[0] != '/')) { cmd.path = '/' + cmd.path; } // Add '/' to paths on non-windows
|
||||
switch (cmd.action) {
|
||||
case 'ping': {
|
||||
// This is a keep alive
|
||||
channel.write({ action: 'pong' });
|
||||
break;
|
||||
}
|
||||
case 'lock': {
|
||||
// Lock the current user out of the desktop
|
||||
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': {
|
||||
/*
|
||||
// Close the watcher if required
|
||||
var samepath = ((obj.httprequest.watcher != undefined) && (cmd.path == obj.httprequest.watcher.path));
|
||||
if ((obj.httprequest.watcher != undefined) && (samepath == false)) {
|
||||
//console.log('Closing watcher: ' + obj.httprequest.watcher.path);
|
||||
//obj.httprequest.watcher.close(); // TODO: This line causes the agent to crash!!!!
|
||||
delete obj.httprequest.watcher;
|
||||
}
|
||||
*/
|
||||
|
||||
// Send the folder content to the browser
|
||||
var response = getDirectoryInfo(cmd.path);
|
||||
if (cmd.reqid != undefined) { response.reqid = cmd.reqid; }
|
||||
channel.write(response);
|
||||
|
||||
/*
|
||||
// Start the directory watcher
|
||||
if ((cmd.path != '') && (samepath == false)) {
|
||||
var watcher = fs.watch(cmd.path, onFileWatcher);
|
||||
watcher.tunnel = obj.httprequest;
|
||||
watcher.path = cmd.path;
|
||||
obj.httprequest.watcher = watcher;
|
||||
//console.log('Starting watcher: ' + obj.httprequest.watcher.path);
|
||||
}
|
||||
*/
|
||||
break;
|
||||
}
|
||||
case 'mkdir': {
|
||||
// Create a new empty folder
|
||||
fs.mkdirSync(cmd.path);
|
||||
break;
|
||||
}
|
||||
case 'rm': {
|
||||
// Remove many files or folders
|
||||
for (var i in cmd.delfiles) {
|
||||
var fullpath = path.join(cmd.path, cmd.delfiles[i]);
|
||||
try { fs.unlinkSync(fullpath); } catch (e) { debug(e); }
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'rename': {
|
||||
// Rename a file or folder
|
||||
try { fs.renameSync(path.join(cmd.path, cmd.oldname), path.join(cmd.path, cmd.newname)); } catch (e) { debug(e); }
|
||||
break;
|
||||
}
|
||||
case 'download': {
|
||||
// Download a file, to browser
|
||||
var sendNextBlock = 0;
|
||||
if (cmd.sub == 'start') { // Setup the download
|
||||
if (obj.filedownload != null) { channel.write({ action: 'download', sub: 'cancel', id: obj.filedownload.id }); delete obj.filedownload; }
|
||||
obj.filedownload = { id: cmd.id, path: cmd.path, ptr: 0 }
|
||||
try { obj.filedownload.f = fs.openSync(obj.filedownload.path, 'rbN'); } catch (e) { channel.write({ action: 'download', sub: 'cancel', id: obj.filedownload.id }); delete obj.filedownload; }
|
||||
if (obj.filedownload) { channel.write({ action: 'download', sub: 'start', id: cmd.id }); }
|
||||
} else if ((obj.filedownload != null) && (cmd.id == obj.filedownload.id)) { // Download commands
|
||||
if (cmd.sub == 'startack') { sendNextBlock = 8; } else if (cmd.sub == 'stop') { delete obj.filedownload; } else if (cmd.sub == 'ack') { sendNextBlock = 1; }
|
||||
}
|
||||
// Send the next download block(s)
|
||||
while (sendNextBlock > 0) {
|
||||
sendNextBlock--;
|
||||
var buf = Buffer.alloc(4096);
|
||||
var len = fs.readSync(obj.filedownload.f, buf, 4, 4092, null);
|
||||
obj.filedownload.ptr += len;
|
||||
if (len < 4092) { buf.writeInt32BE(0x01000001, 0); fs.closeSync(obj.filedownload.f); delete obj.filedownload; sendNextBlock = 0; } else { buf.writeInt32BE(0x01000000, 0); }
|
||||
channel.write(buf.slice(0, len + 4).toString('base64')); // Write as Base64
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'upload': {
|
||||
// Upload a file, from browser
|
||||
if (cmd.sub == 'start') { // Start the upload
|
||||
if (obj.fileupload != null) { fs.closeSync(obj.fileupload.fp); }
|
||||
if (!cmd.path || !cmd.name) break;
|
||||
obj.fileupload = { reqid: cmd.reqid };
|
||||
var filepath = path.join(cmd.path, cmd.name);
|
||||
try { obj.fileupload.fp = fs.openSync(filepath, 'wbN'); } catch (e) { }
|
||||
if (obj.fileupload.fp) { channel.write({ action: 'upload', sub: 'start', reqid: obj.fileupload.reqid }); } else { obj.fileupload = null; channel.write({ action: 'upload', sub: 'error', reqid: obj.fileupload.reqid }); }
|
||||
}
|
||||
else if (cmd.sub == 'cancel') { // Stop the upload
|
||||
if (obj.fileupload != null) { fs.closeSync(obj.fileupload.fp); obj.fileupload = null; }
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'copy': {
|
||||
// Copy a bunch of files from scpath to dspath
|
||||
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': {
|
||||
// Move a bunch of files from scpath to dspath
|
||||
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: {
|
||||
debug('Invalid KVM command: ' + cmd);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var webRtcCleanUp = function () {
|
||||
debug('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;
|
||||
}
|
||||
|
||||
var kvmSetData = function (x) {
|
||||
osamtstack.IPS_KVMRedirectionSettingData_DataChannelWrite(Buffer.from(x).toString('base64'), function () { });
|
||||
}
|
||||
|
||||
// Delete a directory with a files and directories within it
|
||||
var deleteFolderRecursive = function(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()) { // recurse
|
||||
deleteFolderRecursive(curPath, true);
|
||||
} else { // delete file
|
||||
fs.unlinkSync(curPath);
|
||||
}
|
||||
});
|
||||
}
|
||||
fs.unlinkSync(path);
|
||||
}
|
||||
};
|
||||
|
||||
// Polyfill path.join
|
||||
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('/');
|
||||
}
|
||||
};
|
||||
|
||||
function md5hex(str) { return require('MD5Stream').create().syncHash(str).toString('hex'); }
|
||||
|
||||
//
|
||||
// Deactivate Intel AMT CCM
|
||||
//
|
||||
|
||||
// When called, this will use MEI to deactivate Intel AMT when it's in CCM mode. Simply calls "unprovision" on MEI and checks the return code.
|
||||
obj.deactivateCCM = function() {
|
||||
amtMei.unprovision(1, function (status) {
|
||||
if (status == 0) {
|
||||
debug('Success deactivating Intel AMT CCM.');
|
||||
agent.SendCommand({ "action": "coreinfo", "intelamt": { "state": 0, "flags": 0 } });
|
||||
applyPolicyTimer = setTimeout(obj.applyPolicy, 8000);
|
||||
} else {
|
||||
debug('Intel AMT CCM deactivation error: ' + status);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Activate Intel AMT to CCM
|
||||
//
|
||||
|
||||
function makePass(length) {
|
||||
var text = "", possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); }
|
||||
return text;
|
||||
}
|
||||
|
||||
obj.activeToCCM = function (adminpass) {
|
||||
if ((adminpass == null) || (adminpass == '')) { adminpass = 'P@0s' + makePass(23); }
|
||||
intelAmtAdminPass = adminpass;
|
||||
//debug('Trying to get local account info...');
|
||||
amtMei.getLocalSystemAccount(function (x) {
|
||||
if ((x != null) && x.user && x.pass) {
|
||||
//debug('Intel AMT local account info: User=' + x.user + ', Pass=' + 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);
|
||||
//debug('Trying to get Intel AMT activation information...');
|
||||
osamtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], activeToCCMEx2, adminpass);
|
||||
} else {
|
||||
debug('Unable to get $$OsAdmin password.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var activeToCCMEx2 = function(stack, name, responses, status, adminpass) {
|
||||
if (status != 200) { debug('Failed to fetch activation information, status ' + status); }
|
||||
else if (responses['IPS_HostBasedSetupService'].response['AllowedControlModes'].length != 2) { debug('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); }
|
||||
}
|
||||
|
||||
var activeToCCMEx3 = function(stack, name, responses, status) {
|
||||
if (status != 200) { debug('Failed to activate, status ' + status); }
|
||||
else if (responses.Body.ReturnValue != 0) { debug('Client control mode activation failed: ' + responses.Body.ReturnValueStr); }
|
||||
else {
|
||||
debug('Intel AMT CCM activation success.');
|
||||
db.Put('amtCCMPass', intelAmtAdminPass);
|
||||
agent.SendCommand({ "action": "coreinfo", "intelamt": { "state": 2, "flags": 2, "user": "admin", "pass": intelAmtAdminPass } });
|
||||
}
|
||||
applyPolicyTimer = setTimeout(obj.applyPolicy, 8000);
|
||||
}
|
||||
|
||||
obj.start = function () {
|
||||
// Try to load Intel AMT policy
|
||||
var amtPolicy = null;
|
||||
try { amtPolicy = JSON.parse(db.Get('amtPolicy')); } catch (ex) { debug('Exception loading amtPolicy'); }
|
||||
//if (amtPolicy == null) { debug('no amtPolicy'); } else { debug('Loaded amtPolicy: ' + JSON.stringify(amtPolicy)); }
|
||||
try { intelAmtAdminPass = db.Get('amtCCMPass'); } catch (ex) { }
|
||||
if (typeof intelAmtAdminPass != 'string') { intelAmtAdminPass = null; }
|
||||
obj.reset();
|
||||
}
|
||||
|
||||
// Apply Intel AMT policy
|
||||
var intelAmtAdminPass, wsstack, amtstack, applyPolicyTimer;
|
||||
obj.applyPolicy = function () {
|
||||
applyPolicyTimer = null;
|
||||
if ((amtMeiState != 3) || (typeof amtpolicy != 'object') || (typeof amtpolicy.type != 'number') || (amtpolicy.type == 0)) return;
|
||||
if ((amtpolicy.password != null) && (amtpolicy.password != '')) { intelAmtAdminPass = amtpolicy.password; }
|
||||
obj.getAmtInfo(function (meinfo) {
|
||||
if ((amtpolicy.type == 1) && (meinfo.ProvisioningState == 2)) {
|
||||
// CCM Deactivation Policy.
|
||||
wsstack = null;
|
||||
amtstack = null;
|
||||
obj.deactivateCCM();
|
||||
} else if ((amtpolicy.type == 2) && (meinfo.ProvisioningState == 0)) {
|
||||
// CCM Activation Policy
|
||||
wsstack = null;
|
||||
amtstack = null;
|
||||
if ((amtpolicy.password == null) || (amtpolicy.password == '')) { intelAmtAdminPass = null; }
|
||||
obj.activeToCCM(intelAmtAdminPass);
|
||||
} else if ((amtpolicy.type == 2) && (meinfo.ProvisioningState == 2) && (intelAmtAdminPass != null)) {
|
||||
// Perform password test
|
||||
var transport = require('amt-wsman-duk');
|
||||
var wsman = require('amt-wsman');
|
||||
var amt = require('amt');
|
||||
wsstack = new wsman(transport, '127.0.0.1', 16992, 'admin', intelAmtAdminPass, false);
|
||||
amtstack = new amt(wsstack);
|
||||
try { amtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], wsmanPassTestResponse); } catch (ex) { debug(ex); }
|
||||
} else {
|
||||
// Other possible cases...
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var wsmanPassTestResponse = function (stack, name, responses, status) {
|
||||
if (status != 200) {
|
||||
if (amtpolicy.badpass == 1) { obj.deactivateCCM(); } // Something went wrong, reactivate.
|
||||
} else {
|
||||
// Success, make sure
|
||||
debug('SUCCESS!');
|
||||
// TODO: Check Intel AMT Features need to be enabled & if Intel AMT CIRA needs to be setup
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = AmtManager;
|
@ -20,6 +20,7 @@ function amt_heci() {
|
||||
emitterUtils.createEvent('error');
|
||||
|
||||
var heci = require('heci');
|
||||
var sendConsole = function (msg) { require('MeshAgent').SendCommand({ "action": "msg", "type": "console", "value": msg }); }
|
||||
|
||||
this._ObjectID = "pthi";
|
||||
this._rq = new Q();
|
||||
|
1
agents/modules_meshcore_min/amt-lme.min.js
vendored
1
agents/modules_meshcore_min/amt-lme.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcore_min/amt-mei.min.js
vendored
1
agents/modules_meshcore_min/amt-mei.min.js
vendored
File diff suppressed because one or more lines are too long
@ -1 +0,0 @@
|
||||
function AMTScanner(){var a=require("events").inherits(this);a.createEvent("found");this.dgram=require("dgram");this.buildRmcpPing=function(c){var b=Buffer.from("06000006000011BE80000000","hex");b[9]=c;return b};this.parseRmcpPacket=function(h,b,g,d){if(b==null||b.length<20){return}var f={};if(((b[12]==0)||(b[13]!=0)||(b[14]!=1)||(b[15]!=87))&&(b[21]&32)){f.servertag=b[9];f.minorVersion=b[18]&15;f.majorVersion=(b[18]>>4)&15;f.provisioningState=b[19]&3;var e=(b[16]*256)+b[17];var c=((b[19]&4)!=0)?true:false;f.openPorts=[e];f.address=g.address;if(c==true){f.openPorts=[16992,16993]}if(d!==undefined){d(h,f)}}};this.parseIPv4Range=function(f){if(f==undefined||f==null){return null}var g=f.split("-");if(g.length==2){return{min:this.parseIpv4Addr(g[0]),max:this.parseIpv4Addr(g[1])}}g=f.split("/");if(g.length==2){var c=this.parseIpv4Addr(g[0]),e=parseInt(g[1]),d=0;if(e<=16||e>32){return null}e=32-e;for(var b=0;b<e;b++){d=(d<<1);d++}return{min:c&(4294967295-d),max:(c&(4294967295-d))+d}}g=this.parseIpv4Addr(f);if(g==null){return null}return{min:g,max:g}};this.parseIpv4Addr=function(b){var c=b.split(".");if(c.length==4){return(parseInt(c[0])<<24)+(parseInt(c[1])<<16)+(parseInt(c[2])<<8)+(parseInt(c[3])<<0)}return null};this.IPv4NumToStr=function(b){return((b>>24)&255)+"."+((b>>16)&255)+"."+((b>>8)&255)+"."+(b&255)};this.scan=function(d,g){var c=this.parseIPv4Range(d);var e=this.buildRmcpPing(0);var f=this.dgram.createSocket({type:"udp4"});f.parent=this;f.scanResults=[];f.on("error",function(i){console.log("Error:"+i)});f.on("message",function(i,j){if(j.size>4){this.parent.parseRmcpPacket(this,i,j,function(l,k){l.scanResults.push(k)})}});f.on("listening",function(){for(var j=c.min;j<=c.max;j++){f.send(e,623,f.parent.IPv4NumToStr(j))}});f.bind({address:"0.0.0.0",port:0,exclusive:true});var h=setTimeout(function b(){f.close();f.parent.emit("found",f.scanResults);delete f},g)}}module.exports=AMTScanner;
|
@ -1 +0,0 @@
|
||||
function CreateWsmanComm(){var a={};a.PendingAjax=[];a.ActiveAjaxCount=0;a.MaxActiveAjaxCount=1;a.FailAllError=0;a.digest=null;a.RequestCount=0;if(arguments.length==1&&typeof(arguments[0]=="object")){a.host=arguments[0].host;a.port=arguments[0].port;a.authToken=arguments[0].authToken;a.tls=arguments[0].tls}else{a.host=arguments[0];a.port=arguments[1];a.user=arguments[2];a.pass=arguments[3];a.tls=arguments[4]}a.PerformAjax=function(d,c,f,e,g,b){if((a.ActiveAjaxCount==0||((a.ActiveAjaxCount<a.MaxActiveAjaxCount)&&(a.challengeParams!=null)))&&a.PendingAjax.length==0){a.PerformAjaxEx(d,c,f,g,b)}else{if(e==1){a.PendingAjax.unshift([d,c,f,g,b])}else{a.PendingAjax.push([d,c,f,g,b])}}};a.PerformNextAjax=function(){if(a.ActiveAjaxCount>=a.MaxActiveAjaxCount||a.PendingAjax.length==0){return}var b=a.PendingAjax.shift();a.PerformAjaxEx(b[0],b[1],b[2],b[3],b[4]);a.PerformNextAjax()};a.PerformAjaxEx=function(d,c,g,h,b){if(a.FailAllError!=0){if(a.FailAllError!=999){a.gotNextMessagesError({status:a.FailAllError},"error",null,[d,c,g])}return}if(!d){d=""}if(a.digest==null){if(a.authToken){a.digest=require("http-digest").create({authToken:a.authToken})}else{a.digest=require("http-digest").create(a.user,a.pass)}a.digest.http=require("http")}var f={protocol:(a.tls==1?"https:":"http:"),method:"POST",host:a.host,path:"/wsman",port:a.port,rejectUnauthorized:false,checkServerIdentity:function(i){console.log("checkServerIdentity",JSON.stringify(i))}};var e=a.digest.request(f);e.on("error",function(i){a.gotNextMessagesError({status:600},"error",null,[d,c,g])});e.on("response",function(i){if(i.statusCode!=200){a.gotNextMessagesError({status:i.statusCode},"error",null,[d,c,g])}else{i.acc="";i.on("data",function(j){this.acc+=j});i.on("end",function(){a.gotNextMessages(i.acc,"success",{status:i.statusCode},[d,c,g])})}});e.end(d);a.ActiveAjaxCount++;return e};a.pendingAjaxCall=[];a.gotNextMessages=function(c,e,d,b){a.ActiveAjaxCount--;if(a.FailAllError==999){return}if(a.FailAllError!=0){b[1](null,a.FailAllError,b[2]);return}if(d.status!=200){b[1](null,d.status,b[2]);return}b[1](c,200,b[2]);a.PerformNextAjax()};a.gotNextMessagesError=function(d,e,c,b){a.ActiveAjaxCount--;if(a.FailAllError==999){return}if(a.FailAllError!=0){b[1](null,a.FailAllError,b[2]);return}if(a.FailAllError!=999){b[1]({Header:{HttpError:d.status}},d.status,b[2])}a.PerformNextAjax()};a.CancelAllQueries=function(b){while(a.PendingAjax.length>0){var c=a.PendingAjax.shift();c[1](null,b,c[2])}};return a}module.exports=CreateWsmanComm;
|
1
agents/modules_meshcore_min/amt-wsman.min.js
vendored
1
agents/modules_meshcore_min/amt-wsman.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcore_min/amt-xml.min.js
vendored
1
agents/modules_meshcore_min/amt-xml.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcore_min/amt.min.js
vendored
1
agents/modules_meshcore_min/amt.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcore_min/clipboard.min.js
vendored
1
agents/modules_meshcore_min/clipboard.min.js
vendored
@ -1 +0,0 @@
|
||||
var promise=require("promise");function nativeAddModule(a){var c=getJSModule(a);var b="duk_peval_string_noresult(ctx, \"addModule('"+a+"', Buffer.from('"+Buffer.from(c).toString("base64")+"', 'base64').toString());\");";module.exports(b)}function lin_readtext(){var d=new promise(function(h,g){this._res=h;this._rej=g});try{require("monitor-info")}catch(b){d._rej(b);return(d)}var f=require("monitor-info")._X11;if(!f){d._rej("X11 required for Clipboard Manipulation")}else{var e=31;var a=0;var c=require("monitor-info")._gm;d._getInfoPromise=require("monitor-info").getInfo();d._getInfoPromise._masterPromise=d;d._getInfoPromise.then(function(g){if(g.length>0){var h=f.XWhitePixel(g[0].display,g[0].screenId).Val;this._masterPromise.CLIPID=f.XInternAtom(g[0].display,c.CreateVariable("CLIPBOARD"),0);this._masterPromise.FMTID=f.XInternAtom(g[0].display,c.CreateVariable("UTF8_STRING"),0);this._masterPromise.PROPID=f.XInternAtom(g[0].display,c.CreateVariable("XSEL_DATA"),0);this._masterPromise.INCRID=f.XInternAtom(g[0].display,c.CreateVariable("INCR"),0);this._masterPromise.ROOTWIN=f.XRootWindow(g[0].display,g[0].screenId);this._masterPromise.FAKEWIN=f.XCreateSimpleWindow(g[0].display,this._masterPromise.ROOTWIN,0,0,g[0].right,5,0,h,h);f.XSync(g[0].display,0);f.XConvertSelection(g[0].display,this._masterPromise.CLIPID,this._masterPromise.FMTID,this._masterPromise.PROPID,this._masterPromise.FAKEWIN,0);f.XSync(g[0].display,0);this._masterPromise.DescriptorEvent=require("DescriptorEvents").addDescriptor(f.XConnectionNumber(g[0].display).Val,{readset:true});this._masterPromise.DescriptorEvent._masterPromise=this._masterPromise;this._masterPromise.DescriptorEvent._display=g[0].display;this._masterPromise.DescriptorEvent.on("readset",function(j){var o=c.CreateVariable(1024);while(f.XPending(this._display).Val){f.XNextEventSync(this._display,o);if(o.Deref(0,4).toBuffer().readUInt32LE()==e){var k=c.CreatePointer();var i=c.CreatePointer();var m=c.CreatePointer();var n=c.CreatePointer();var l=c.CreatePointer();f.XGetWindowProperty(this._display,this._masterPromise.FAKEWIN,this._masterPromise.PROPID,0,65535,0,a,k,i,m,n,l);this._masterPromise._res(l.Deref().String);f.XFree(l.Deref());f.XDestroyWindow(this._display,this._masterPromise.FAKEWIN);this.removeDescriptor(j);break}}})}})}return(d)}function lin_copytext(){}function win_readtext(){var g="";var a=1;var b=require("_GenericMarshal");var i=b.CreateNativeProxy("user32.dll");var e=b.CreateNativeProxy("kernel32.dll");e.CreateMethod("GlobalAlloc");e.CreateMethod("GlobalLock");e.CreateMethod("GlobalUnlock");i.CreateMethod("OpenClipboard");i.CreateMethod("CloseClipboard");i.CreateMethod("GetClipboardData");i.OpenClipboard(0);var c=i.GetClipboardData(a);if(c.Val!=0){var d=e.GlobalLock(c);g=d.String;e.GlobalUnlock(c)}i.CloseClipboard();var f=new promise(function(j,h){this._res=j;this._rej=h});f._res(g);return(f)}function win_copytext(i){var c=2;var a=1;var b=require("_GenericMarshal");var j=b.CreateNativeProxy("user32.dll");var f=b.CreateNativeProxy("kernel32.dll");f.CreateMethod("GlobalAlloc");f.CreateMethod("GlobalLock");f.CreateMethod("GlobalUnlock");j.CreateMethod("OpenClipboard");j.CreateMethod("EmptyClipboard");j.CreateMethod("CloseClipboard");j.CreateMethod("SetClipboardData");var d=f.GlobalAlloc(c,i.length+2);d.autoFree(false);var e=f.GlobalLock(d);e.autoFree(false);var g=Buffer.alloc(i.length+1);Buffer.from(i).copy(g);g.copy(e.Deref(0,i.length+1).toBuffer());f.GlobalUnlock(d);j.OpenClipboard(0);j.EmptyClipboard();j.SetClipboardData(a,d);j.CloseClipboard()}switch(process.platform){case"win32":module.exports=win_copytext;module.exports.read=win_readtext;break;case"linux":module.exports=lin_copytext;module.exports.read=lin_readtext;break;case"darwin":break}module.exports.nativeAddModule=nativeAddModule;
|
@ -1 +0,0 @@
|
||||
try{Object.defineProperty(Array.prototype,"peek",{value:function(){return(this.length>0?this[this.length-1]:undefined)}})}catch(e){}function dbus(a,b){this._ObjectID="linux-dbus";require("events").EventEmitter.call(this,true).createEvent("signal");Object.defineProperty(this,"uid",{value:b});this._child=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM,uid:b==null?-1:b});this._child.stdin.write("dbus-monitor --session \"type='signal', interface='"+a+'\'" | ( while read X; do echo "$X"; done )\n');this._child.stdout.dbus=this;this._child.stdout.on("data",function(c){if(!this.ready){this.ready=true;return}var f=[];var g=c.toString().split("\r\n");for(var d in g){if(g[d]==""){this.dbus.preParseRecords(f);f=[]}else{f.push(g[d])}}});this.preParseRecords=function(d){var f=[];for(var c in d){if(d[c].startsWith("signal ")){if(f.length>0){this.parseRecords(f)}f=[]}f.push(d[c])}if(f.length>0){this.parseRecords(f)}};this.parseRecords=function(d){if(d[0].startsWith("signal ")){var g={};var h=d[0].split(" ");h.shift();for(var c in h){var f=h[c].split("=");if(f.length==2){g[f[0]]=f[1]}}d.shift();g.data=d;this.parseSignal(g)}};this.parseSignal=function(f){var c=f.data;f.data=[];for(var d=0;d<c.length;++d){if(c[d].startsWith("array ")){f.data.push([]);for(d=d+1;d<c.length;++d){this.parseSignal2(c[d],f.data.peek())}}else{this.parseSignal2(c[d],f.data)}}this.emit("signal",f)};this.parseSignal2=function(c,d){if(c.startsWith("string ")){d.push(JSON.parse(c.slice(7)))}else{if(c.startsWith("boolean ")){d.push(JSON.parse(c.slice(8)))}}}}module.exports=dbus;
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1 +0,0 @@
|
||||
function powerMonitor(){this._ObjectID="power-monitor";require("events").EventEmitter.call(this,true).createEvent("changed").createEvent("sx").createEvent("batteryLevel").createEvent("acdc").createEvent("display");this._i=setImmediate(function(a){require("user-sessions");delete a._i},this)}module.exports=new powerMonitor();
|
@ -1 +0,0 @@
|
||||
var GM=require("_GenericMarshal");function processManager(){this._ObjectID="process-manager";switch(process.platform){case"win32":this._kernel32=GM.CreateNativeProxy("kernel32.dll");this._kernel32.CreateMethod("GetLastError");this._kernel32.CreateMethod("CreateToolhelp32Snapshot");this._kernel32.CreateMethod("Process32First");this._kernel32.CreateMethod("Process32Next");break;case"linux":case"darwin":this._childProcess=require("child_process");break;default:throw (process.platform+" not supported");break}this.enumerateProcesses=function a(){var d=require("promise");var e=new d(function(g,f){this._res=g;this._rej=f});this.getProcesses(function(g,f){f._res(g)},e);return(e)};this.getProcesses=function b(d){switch(process.platform){default:throw ("Enumerating processes on "+process.platform+" not supported");break;case"win32":var n={};var e=this._kernel32.CreateToolhelp32Snapshot(2,0);var g=GM.CreateVariable(304);g.toBuffer().writeUInt32LE(304,0);var j=this._kernel32.Process32First(e,g);while(j.Val){n[g.Deref(8,4).toBuffer().readUInt32LE(0)]={pid:g.Deref(8,4).toBuffer().readUInt32LE(0),cmd:g.Deref(GM.PointerSize==4?36:44,260).String};j=this._kernel32.Process32Next(e,g)}if(d){d.apply(this,[n])}break;case"linux":if(!this._psp){this._psp={}}var l=this._childProcess.execFile("/bin/ps",["ps","-uxa"],{type:this._childProcess.SpawnTypes.TERM});this._psp[l.pid]=l;l.Parent=this;l.ps="";l.callback=d;l.args=[];for(var f=1;f<arguments.length;++f){l.args.push(arguments[f])}l.on("exit",function k(){delete this.Parent._psp[this.pid];var r={},q=this.ps.split("\x0D\x0A"),o={},p=0;for(var h in q){var t=q[h].split(" ");var s=[];for(var u in t){if(h==0&&t[u]){o[t[u]]=p++}if(h>0&&t[u]){s.push(t[u])}}if(h>0){if(s[o.PID]){r[s[o.PID]]={pid:o.PID,user:s[o.USER],cmd:s[o.COMMAND]}}}}if(this.callback){this.args.unshift(r);this.callback.apply(this.parent,this.args)}});l.stdout.on("data",function(h){this.parent.ps+=h.toString()});break;case"darwin":var m=require("promise");var l=new m(function(i,h){this._res=i;this._rej=h});l.pm=this;l.callback=d;l.args=[];for(var f=1;f<arguments.length;++f){l.args.push(arguments[f])}l.child=this._childProcess.execFile("/bin/ps",["ps","-xa"]);l.child.promise=l;l.child.stdout.ps="";l.child.stdout.on("data",function(h){this.ps+=h.toString()});l.child.on("exit",function(){var p=this.stdout.ps.split("\n");var q=p[0].split("PID")[0].length+3;var h=p[0].split("CMD")[0].length;var r={};for(var o=1;o<p.length;++o){if(p[o].length>0){r[p[o].substring(0,q).trim()]={pid:p[o].substring(0,q).trim(),cmd:p[o].substring(h)}}}this.promise._res(r)});l.then(function(h){this.args.unshift(h);this.callback.apply(this.pm,this.args)});break}};this.getProcessInfo=function c(g){switch(process.platform){default:throw ("getProcessInfo() not supported for "+process.platform);break;case"linux":var h=require("fs").readFileSync("/proc/"+g+"/status");var e={};var f=h.toString().split("\n");for(var d in f){var j=f[d].split(":");if(j.length>1){j[1]=j[1].trim()}e[j[0]]=j[1]}return(e);break}}}module.exports=new processManager();
|
File diff suppressed because one or more lines are too long
1
agents/modules_meshcore_min/smbios.min.js
vendored
1
agents/modules_meshcore_min/smbios.min.js
vendored
File diff suppressed because one or more lines are too long
1
agents/modules_meshcore_min/toaster.min.js
vendored
1
agents/modules_meshcore_min/toaster.min.js
vendored
@ -1 +0,0 @@
|
||||
var toasters={};function Toaster(){this._ObjectID="toaster";this.Toast=function a(l,b){var h={};var d=require("events").inherits(h);d.createEvent("Dismissed");h.title=l;h.caption=b;if(process.platform=="win32"){d.createEvent("Clicked");var j=require("user-sessions").Current();for(var f in j){console.log(j[f])}try{console.log("Attempting Toast Mechanism 1");h._child=require("ScriptContainer").Create({processIsolation:true,sessionId:j.Active[0].SessionId})}catch(c){console.log(c);console.log("Attempting Toast Mechanism 2");h._child=require("ScriptContainer").Create({processIsolation:true})}h._child.parent=h;h._child.on("exit",function(e){this.parent.emit("Dismissed");delete this.parent._child});h._child.addModule("win-console",getJSModule("win-console"));h._child.addModule("win-message-pump",getJSModule("win-message-pump"));var k=" try{ var toast = require('win-console'); var balloon = toast.SetTrayIcon({ szInfo: '"+b+"', szInfoTitle: '"+l+"', balloonOnly: true }); balloon.on('ToastDismissed', function(){process.exit();}); } catch(e) { require('ScriptContainer').send(e); } require('ScriptContainer').send('done'); ";h._child.ExecuteString(k);toasters[h._hashCode()]=h;h.on("Dismissed",function(){delete toasters[this._hashCode()]});console.log("Returning");return(h)}else{if(!require("fs").existsSync("/usr/bin/notify-send")){throw ("Toast not supported on this platform")}Object.defineProperty(h,"_sessions",{value:require("user-sessions").Current(function g(e){this._cchild=require("child_process").execFile("/usr/bin/whoami",["whoami"],{type:require("child_process").SpawnTypes.TERM});this._cchild.stdout.on("data",function(i){if(i.toString().split("\r\n")[0]=="root"){if(e[":0"].State!="Connected"&&e[":0"].State!="Active"){this.parent.parent.Parent.emit("Dismissed");return}this.parent.parent._notify=require("child_process").execFile("/bin/sh",["sh"],{type:require("child_process").SpawnTypes.TERM});this.parent.parent._notify.stdin.write("su - "+e[":0"].Username+" -c \"DISPLAY=:0 notify-send '"+this.parent.parent.Parent.title+"' '"+this.parent.parent.Parent.caption+"'\"\n");this.parent.parent._notify.stdin.write("exit\n");this.parent.parent._notify.stdout.on("data",function(n){})}else{this.parent.parent._notify=require("child_process").execFile("/usr/bin/notify-send",["notify-send",this.parent.parent.Parent.title,this.parent.parent.Parent.caption],{type:require("child_process").SpawnTypes.TERM});this.parent.parent._notify.stdout.on("data",function(n){})}this.parent.parent.Parent._timeout=setTimeout(function m(n){n.emit("Dismissed")},10000,this.parent.parent.Parent)});this._cchild.parent=this})});h._sessions.Parent=h;toasters[h._hashCode()]=h;h.on("Dismissed",function(){delete toasters[this._hashCode()]});return(h)}}}module.exports=new Toaster();
|
File diff suppressed because one or more lines are too long
@ -1 +0,0 @@
|
||||
function _Scan(){var f=this.Marshal.CreatePointer();this.Native.WlanEnumInterfaces(this.Handle,0,f);var a=f.Deref().Deref(0,4).toBuffer().readUInt32LE(0);var d=f.Deref().Deref(8,532);var c=d.Deref(16,512).AnsiString;var e;switch(d.Deref(528,4).toBuffer().readUInt32LE(0)){case 0:e="NOT READY";break;case 1:e="CONNECTED";break;case 2:e="AD-HOC";break;case 3:e="DISCONNECTING";break;case 4:e="DISCONNECTED";break;case 5:e="ASSOCIATING";break;case 6:e="DISCOVERING";break;case 7:e="AUTHENTICATING";break;default:e="UNKNOWN";break}var b=d.Deref(0,16);if(this.Native.WlanScan(this.Handle,b,0,0,0).Val==0){return(true)}else{return(false)}}function AccessPoint(d,a,c,b){this.ssid=d;this.bssid=a;this.rssi=c;this.lq=b}AccessPoint.prototype.toString=function(){return(this.ssid+" ["+this.bssid+"]: "+this.lq)};function OnNotify(g){var h=g.Deref(0,4).toBuffer().readUInt32LE(0);var f=g.Deref(4,4).toBuffer().readUInt32LE(0);var c=g.Deref(8,16);if((h&8)&&(f==7)){var a=this.Parent.Marshal.CreatePointer();var k=this.Parent.Native.GetBSSList(this.Parent.Handle,c,0,3,0,0,a).Val;if(k==0){var n=a.Deref().Deref(0,4).toBuffer().readUInt32LE(0);var j=a.Deref().Deref(4,4).toBuffer().readUInt32LE(0);for(i=0;i<j;++i){var d=a.Deref().Deref(8+(360*i),360);var m=d.Deref(4,32).String.trim();var b=d.Deref(40,6).HexString2;var l=d.Deref(56,4).toBuffer().readUInt32LE(0);var e=d.Deref(60,4).toBuffer().readUInt32LE(0);this.Parent.emit("Scan",new AccessPoint(m,b,l,e))}}}}function Wireless(){var a=require("events").inherits(this);this.Marshal=require("_GenericMarshal");this.Native=this.Marshal.CreateNativeProxy("wlanapi.dll");this.Native.CreateMethod("WlanOpenHandle");this.Native.CreateMethod("WlanGetNetworkBssList","GetBSSList");this.Native.CreateMethod("WlanRegisterNotification");this.Native.CreateMethod("WlanEnumInterfaces");this.Native.CreateMethod("WlanScan");this.Native.CreateMethod("WlanQueryInterface");var c=this.Marshal.CreatePointer();var b=this.Marshal.CreatePointer();this.Native.WlanOpenHandle(2,0,c,b);this.Handle=b.Deref();this._NOTIFY_PROXY_OBJECT=this.Marshal.CreateCallbackProxy(OnNotify,2);this._NOTIFY_PROXY_OBJECT.Parent=this;var d=this.Marshal.CreatePointer();var e=this.Native.WlanRegisterNotification(this.Handle,65535,0,this._NOTIFY_PROXY_OBJECT.Callback,this._NOTIFY_PROXY_OBJECT.State,0,d);a.createEvent("Scan");a.addMethod("Scan",_Scan);this.GetConnectedNetwork=function(){var n=this.Marshal.CreatePointer();console.log("Success = "+this.Native.WlanEnumInterfaces(this.Handle,0,n).Val);var h=n.Deref().Deref(0,4).toBuffer().readUInt32LE(0);var m=n.Deref().Deref(8,532);var l=m.Deref(16,512).AnsiString;var o=m.Deref(528,4).toBuffer().readUInt32LE(0);if(m.Deref(528,4).toBuffer().readUInt32LE(0)==1){var j=this.Marshal.CreatePointer();var q=this.Marshal.CreatePointer();var s=this.Marshal.CreatePointer();var k=m.Deref(0,16);var r=this.Native.WlanQueryInterface(this.Handle,k,7,0,j,q,s).Val;if(r==0){var f=q.Deref().Deref(524,32).String;var g=q.Deref().Deref(560,6).HexString;var p=q.Deref().Deref(576,4).toBuffer().readUInt32LE(0);return(new AccessPoint(f,g,0,p))}}throw ("GetConnectedNetworks: FAILED (not associated to a network)")};return(this)}module.exports=new Wireless();
|
@ -1 +0,0 @@
|
||||
var MemoryStream=require("MemoryStream");var WindowsChildScript='var parent = require("ScriptContainer");var Wireless = require("wifi-scanner-windows");Wireless.on("Scan", function (ap) { parent.send(ap); });Wireless.Scan();';function AccessPoint(c,a,b){this.ssid=c;this.bssid=a;this.lq=b}AccessPoint.prototype.toString=function(){return("["+this.bssid+"]: "+this.ssid+" ("+this.lq+")")};function WiFiScanner(){var a=require("events").inherits(this);a.createEvent("accessPoint");this.hasWireless=function(){var d=false;var b=require("os").networkInterfaces();for(var c in b){if(b[c][0].type=="wireless"){d=true;break}}return(d)};this.Scan=function(){if(process.platform=="win32"){this.master=require("ScriptContainer").Create(15,ContainerPermissions.DEFAULT);this.master.parent=this;this.master.on("data",function(e){this.parent.emit("accessPoint",new AccessPoint(e.ssid,e.bssid,e.lq))});this.master.addModule("wifi-scanner-windows",getJSModule("wifi-scanner-windows"));this.master.ExecuteString(WindowsChildScript)}else{if(process.platform=="linux"){var c=require("os").networkInterfaces();var d=null;for(var b in c){if(c[b][0].type=="wireless"){d=b;break}}if(d!=null){this.child=require("child_process").execFile("/sbin/iwlist",["iwlist",d,"scan"]);this.child.parent=this;this.child.ms=new MemoryStream();this.child.ms.parent=this.child;this.child.stdout.on("data",function(e){this.parent.ms.write(e)});this.child.on("exit",function(){this.ms.end()});this.child.ms.on("end",function(){var l=this.buffer.toString();tokens=l.split(" - Address: ");for(var h in tokens){if(h==0){continue}var i=tokens[h].split("\n");var e=i[0];var f;var g;for(var j in i){j=i[j].trim();j=j.trim();if(j.startsWith("ESSID:")){g=j.slice(7,j.length-1);if(g=="<hidden>"){g=""}}if(j.startsWith("Signal level=")){f=j.slice(13,j.length-4)}else{if(j.startsWith("Quality=")){f=j.slice(8,10);var k=j.slice(11,13)}}}this.parent.parent.emit("accessPoint",new AccessPoint(g,e,f))}})}}}}}module.exports=WiFiScanner;
|
@ -1 +0,0 @@
|
||||
var TrayIconFlags={NIF_MESSAGE:1,NIF_ICON:2,NIF_TIP:4,NIF_STATE:8,NIF_INFO:16,NIF_GUID:32,NIF_REALTIME:64,NIF_SHOWTIP:128,NIM_ADD:0,NIM_MODIFY:1,NIM_DELETE:2,NIM_SETFOCUS:3,NIM_SETVERSION:4};var NOTIFYICON_VERSION_4=4;var MessageTypes={WM_APP:32768,WM_USER:1024};function WindowsConsole(){if(process.platform=="win32"){this._ObjectID="win-console";this._Marshal=require("_GenericMarshal");this._kernel32=this._Marshal.CreateNativeProxy("kernel32.dll");this._user32=this._Marshal.CreateNativeProxy("user32.dll");this._kernel32.CreateMethod("GetConsoleWindow");this._kernel32.CreateMethod("GetCurrentThread");this._user32.CreateMethod("ShowWindow");this._user32.CreateMethod("LoadImageA");this._user32.CreateMethod({method:"GetMessageA",threadDispatch:1});this._shell32=this._Marshal.CreateNativeProxy("Shell32.dll");this._shell32.CreateMethod("Shell_NotifyIconA");this._handle=this._kernel32.GetConsoleWindow();this.minimize=function(){this._user32.ShowWindow(this._handle,6)};this.restore=function(){this._user32.ShowWindow(this._handle,9)};this.hide=function(){this._user32.ShowWindow(this._handle,0)};this.show=function(){this._user32.ShowWindow(this._handle,5)};this._loadicon=function(c){var b=this._user32.LoadImageA(0,this._Marshal.CreateVariable(c),1,0,0,16|32768|64);return(b)};this.SetTrayIcon=function a(h){var b=this._Marshal.CreateVariable(this._Marshal.PointerSize==4?508:528);b.toBuffer().writeUInt32LE(b._size,0);var n=TrayIconFlags.NIF_TIP|TrayIconFlags.NIF_MESSAGE;h.filter=MessageTypes.WM_APP+1;b.Deref(this._Marshal.PointerSize==4?16:24,4).toBuffer().writeUInt32LE(h.filter);if(!h.noBalloon){n|=TrayIconFlags.NIF_INFO}if(h.icon){n|=TrayIconFlags.NIF_ICON;var c=b.Deref(this._Marshal.PointerSize==4?20:32,this._Marshal.PointerSize);h.icon.pointerBuffer().copy(c.toBuffer())}b.Deref(this._Marshal.PointerSize*2,4).toBuffer().writeUInt32LE(1);b.Deref(this._Marshal.PointerSize==4?12:20,4).toBuffer().writeUInt32LE(n);b.Deref(this._Marshal.PointerSize==4?416:432,4).toBuffer().writeUInt32LE(NOTIFYICON_VERSION_4);var m=b.Deref(this._Marshal.PointerSize==4?24:40,128);var k=b.Deref(this._Marshal.PointerSize==4?160:176,256);var l=b.Deref(this._Marshal.PointerSize==4?420:436,64);if(h.szTip){Buffer.from(h.szTip).copy(m.toBuffer())}if(h.szInfo){Buffer.from(h.szInfo).copy(k.toBuffer())}if(h.szInfoTitle){Buffer.from(h.szInfoTitle).copy(l.toBuffer())}var d=require("win-message-pump");retVal={_ObjectID:"WindowsConsole.TrayIcon",MessagePump:new d(h)};var j=require("events").inherits(retVal);j.createEvent("ToastClicked");j.createEvent("IconHover");j.createEvent("ToastDismissed");retVal.Options=h;retVal.MessagePump.TrayIcon=retVal;retVal.MessagePump.NotifyData=b;retVal.MessagePump.WindowsConsole=this;retVal.MessagePump.on("exit",function e(o){console.log("Pump Exited");if(this.TrayIcon){this.TrayIcon.remove()}});retVal.MessagePump.on("hwnd",function f(o){h.hwnd=o;o.pointerBuffer().copy(this.NotifyData.Deref(this.WindowsConsole._Marshal.PointerSize,this.WindowsConsole._Marshal.PointerSize).toBuffer());if(this.WindowsConsole._shell32.Shell_NotifyIconA(TrayIconFlags.NIM_ADD,this.NotifyData).Val==0){}});retVal.MessagePump.on("message",function g(p){if(p.message==this.TrayIcon.Options.filter){var o=false;if(p.wparam==1&&p.lparam==1029){this.TrayIcon.emit("ToastClicked");o=true}if(p.wparam==1&&p.lparam==512){this.TrayIcon.emit("IconHover");o=true}if(this.TrayIcon.Options.balloonOnly&&p.wparam==1&&(p.lparam==1028||p.lparam==1029)){this.TrayIcon.emit("ToastDismissed");this.TrayIcon.remove();o=true}if(!o){console.log(p)}}});retVal.remove=function i(){this.MessagePump.WindowsConsole._shell32.Shell_NotifyIconA(TrayIconFlags.NIM_DELETE,this.MessagePump.NotifyData);this.MessagePump.stop();delete this.MessagePump.TrayIcon;delete this.MessagePump};return(retVal)}}}module.exports=new WindowsConsole();
|
@ -1 +0,0 @@
|
||||
var WH_CALLWNDPROC=4;var WM_QUIT=18;var GM=require("_GenericMarshal");function WindowsMessagePump(d){this._ObjectID="win-message-pump";this._options=d;var b=require("events").inherits(this);b.createEvent("hwnd");b.createEvent("error");b.createEvent("message");b.createEvent("exit");this._msg=GM.CreateVariable(GM.PointerSize==4?28:48);this._kernel32=GM.CreateNativeProxy("Kernel32.dll");this._kernel32.mp=this;this._kernel32.CreateMethod("GetLastError");this._kernel32.CreateMethod("GetModuleHandleA");this._user32=GM.CreateNativeProxy("User32.dll");this._user32.mp=this;this._user32.CreateMethod("GetMessageA");this._user32.CreateMethod("CreateWindowExA");this._user32.CreateMethod("TranslateMessage");this._user32.CreateMethod("DispatchMessageA");this._user32.CreateMethod("RegisterClassExA");this._user32.CreateMethod("DefWindowProcA");this._user32.CreateMethod("PostMessageA");this.wndclass=GM.CreateVariable(GM.PointerSize==4?48:80);this.wndclass.mp=this;this.wndclass.hinstance=this._kernel32.GetModuleHandleA(0);this.wndclass.cname=GM.CreateVariable("MainWWWClass");this.wndclass.wndproc=GM.GetGenericGlobalCallback(4);this.wndclass.wndproc.mp=this;this.wndclass.toBuffer().writeUInt32LE(this.wndclass._size);this.wndclass.cname.pointerBuffer().copy(this.wndclass.Deref(GM.PointerSize==4?40:64,GM.PointerSize).toBuffer());this.wndclass.wndproc.pointerBuffer().copy(this.wndclass.Deref(8,GM.PointerSize).toBuffer());this.wndclass.hinstance.pointerBuffer().copy(this.wndclass.Deref(GM.PointerSize==4?20:24,GM.PointerSize).toBuffer());this.wndclass.wndproc.on("GlobalCallback",function c(h,i,g,f){if(this.mp._hwnd!=null&&this.mp._hwnd.Val==h.Val){this.mp.emit("message",{message:i.Val,wparam:g.Val,lparam:f.Val,lparam_hex:f.pointerBuffer().toString("hex")});return(this.mp._user32.DefWindowProcA(h,i,g,f))}else{if(this.mp._hwnd==null&&this.CallingThread()==this.mp._user32.RegisterClassExA.async.threadId()){return(this.mp._user32.DefWindowProcA(h,i,g,f))}}});this._user32.RegisterClassExA.async(this.wndclass).then(function(){this.nativeProxy.CreateWindowExA.async(this.nativeProxy.RegisterClassExA.async,136,this.nativeProxy.mp.wndclass.cname,0,8388608,0,0,100,100,0,0,0,0).then(function(f){if(f.Val==0){this.nativeProxy.mp.emit("error","Error creating hidden window")}else{this.nativeProxy.mp._hwnd=f;this.nativeProxy.mp.emit("hwnd",f);this.nativeProxy.mp._startPump()}})});this._startPump=function a(){this._user32.GetMessageA.async(this._user32.RegisterClassExA.async,this._msg,this._hwnd,0,0).then(function(f){if(f.Val>0){this.nativeProxy.TranslateMessage.async(this.nativeProxy.RegisterClassExA.async,this.nativeProxy.mp._msg).then(function(){this.nativeProxy.DispatchMessageA.async(this.nativeProxy.RegisterClassExA.async,this.nativeProxy.mp._msg).then(function(){this.nativeProxy.mp._startPump()})})}else{delete this.nativeProxy.mp._hwnd;this.nativeProxy.mp.emit("exit",0)}},function(f){this.nativeProxy.mp.stop()})};this.stop=function e(){if(this._hwnd){this._user32.PostMessageA(this._hwnd,WM_QUIT,0,0)}}}module.exports=WindowsMessagePump;
|
@ -1 +0,0 @@
|
||||
var KEY_QUERY_VALUE=1;var KEY_ENUMERATE_SUB_KEYS=8;var KEY_WRITE=131078;var KEY_DATA_TYPES={REG_NONE:0,REG_SZ:1,REG_EXPAND_SZ:2,REG_BINARY:3,REG_DWORD:4,REG_DWORD_BIG_ENDIAN:5,REG_LINK:6,REG_MULTI_SZ:7,REG_RESOURCE_LIST:8,REG_FULL_RESOURCE_DESCRIPTOR:9,REG_RESOURCE_REQUIREMENTS_LIST:10,REG_QWORD:11};function windows_registry(){this._ObjectId="win-registry";this._marshal=require("_GenericMarshal");this._AdvApi=this._marshal.CreateNativeProxy("Advapi32.dll");this._AdvApi.CreateMethod("RegCreateKeyExA");this._AdvApi.CreateMethod("RegEnumKeyExA");this._AdvApi.CreateMethod("RegEnumValueA");this._AdvApi.CreateMethod("RegOpenKeyExA");this._AdvApi.CreateMethod("RegQueryInfoKeyA");this._AdvApi.CreateMethod("RegQueryValueExA");this._AdvApi.CreateMethod("RegCloseKey");this._AdvApi.CreateMethod("RegDeleteKeyA");this._AdvApi.CreateMethod("RegDeleteValueA");this._AdvApi.CreateMethod("RegSetValueExA");this.HKEY={Root:Buffer.from("80000000","hex").swap32(),CurrentUser:Buffer.from("80000001","hex").swap32(),LocalMachine:Buffer.from("80000002","hex").swap32(),Users:Buffer.from("80000003","hex").swap32()};this.QueryKey=function b(o,A,q){var l;var m=this._marshal.CreatePointer();var s=this._marshal.CreateVariable(4);var E=this._marshal.CreateVariable(4);var n=this._marshal.CreatePointer(o);var C=null;if(q){q=this._marshal.CreateVariable(q)}if(!A){A=""}if((l=this._AdvApi.RegOpenKeyExA(n,this._marshal.CreateVariable(A),0,KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,m).Val)!=0){throw ("Opening Registry Key: "+A+" => Returned Error: "+l)}if((A==""&&!q)||!q){var B={subkeys:[],values:[]};var d=this._marshal.CreateVariable(1024);var f=this._marshal.CreateVariable(1024);var g=this._marshal.CreateVariable(32768);var j=this._marshal.CreateVariable(4);var x=this._marshal.CreateVariable(4);var e=this._marshal.CreateVariable(4);e.toBuffer().writeUInt32LE(1024);var y=this._marshal.CreateVariable(4);var z=this._marshal.CreateVariable(4);var u=this._marshal.CreateVariable(4);var t=this._marshal.CreateVariable(4);var w=this._marshal.CreateVariable(4);var v=this._marshal.CreateVariable(4);var D=this._marshal.CreateVariable(4);var r=this._marshal.CreateVariable(8);C=this._AdvApi.RegQueryInfoKeyA(m.Deref(),d,e,0,y,u,t,z,w,v,D,r);if(C.Val!=0){throw ("RegQueryInfoKeyA() returned error: "+C.Val)}for(var p=0;p<y.toBuffer().readUInt32LE();++p){x.toBuffer().writeUInt32LE(1024);C=this._AdvApi.RegEnumKeyExA(m.Deref(),p,f,x,0,0,0,r);if(C.Val==0){B.subkeys.push(f.String)}}for(var p=0;p<z.toBuffer().readUInt32LE();++p){j.toBuffer().writeUInt32LE(32768);if(this._AdvApi.RegEnumValueA(m.Deref(),p,g,j,0,0,0,0).Val==0){B.values.push(g.String)}}return(B)}if(this._AdvApi.RegQueryValueExA(m.Deref(),q,0,0,0,s).Val==0){var k=this._marshal.CreateVariable(s.toBuffer().readUInt32LE());if(this._AdvApi.RegQueryValueExA(m.Deref(),q,0,E,k,s).Val==0){switch(E.toBuffer().readUInt32LE()){case KEY_DATA_TYPES.REG_DWORD:C=k.toBuffer().readUInt32LE();break;case KEY_DATA_TYPES.REG_DWORD_BIG_ENDIAN:C=k.toBuffer().readUInt32BE();break;case KEY_DATA_TYPES.REG_SZ:C=k.String;break;case KEY_DATA_TYPES.REG_BINARY:default:C=k.toBuffer();C._data=k;break}}}else{this._AdvApi.RegCloseKey(m.Deref());throw ("Not Found")}this._AdvApi.RegCloseKey(m.Deref());return(C)};this.WriteKey=function c(g,j,i,l){var k;var f=this._marshal.CreatePointer();if(this._AdvApi.RegCreateKeyExA(this._marshal.CreatePointer(g),this._marshal.CreateVariable(j),0,0,0,KEY_WRITE,0,f,0).Val!=0){throw ("Error Opening Registry Key: "+j)}var d;var e;switch(typeof(l)){case"boolean":e=KEY_DATA_TYPES.REG_DWORD;d=this._marshal.CreateVariable(4);d.toBuffer().writeUInt32LE(l?1:0);break;case"number":e=KEY_DATA_TYPES.REG_DWORD;d=this._marshal.CreateVariable(4);d.toBuffer().writeUInt32LE(l);break;case"string":e=KEY_DATA_TYPES.REG_SZ;d=this._marshal.CreateVariable(l);break;default:e=KEY_DATA_TYPES.REG_BINARY;d=this._marshal.CreateVariable(l.length);l.copy(d.toBuffer());break}if(this._AdvApi.RegSetValueExA(f.Deref(),this._marshal.CreateVariable(i),0,e,d,d._size).Val!=0){this._AdvApi.RegCloseKey(f.Deref());throw ("Error writing reg key: "+i)}this._AdvApi.RegCloseKey(f.Deref())};this.DeleteKey=function a(e,g,f){if(!f){if(this._AdvApi.RegDeleteKeyA(this._marshal.CreatePointer(e),this._marshal.CreateVariable(g)).Val!=0){throw ("Error Deleting Key: "+g)}}else{var d=this._marshal.CreatePointer();var i;if(this._AdvApi.RegOpenKeyExA(this._marshal.CreatePointer(e),this._marshal.CreateVariable(g),0,KEY_QUERY_VALUE|KEY_WRITE,d).Val!=0){throw ("Error Opening Registry Key: "+g)}if((i=this._AdvApi.RegDeleteValueA(d.Deref(),this._marshal.CreateVariable(f)).Val)!=0){this._AdvApi.RegCloseKey(d.Deref());throw ("Error["+i+"] Deleting Key: "+g+"."+f)}this._AdvApi.RegCloseKey(d.Deref())}}}module.exports=new windows_registry();
|
File diff suppressed because one or more lines are too long
@ -64,7 +64,7 @@ module.exports.CreateLetsEncrypt = function (parent) {
|
||||
if (obj.parent.redirserver.port == 80) { obj.parent.redirserver.app.use('/', obj.le.middleware()); obj.redirWebServerHooked = true; }
|
||||
|
||||
obj.getCertificate = function (certs, func) {
|
||||
if (certs.CommonName == 'un-configured') { console.log("ERROR: Use --cert to setup the default server name before using Let's Encrypt."); func(certs); return; }
|
||||
if (certs.CommonName.indexOf('.') == -1) { console.log("ERROR: Use --cert to setup the default server name before using Let's Encrypt."); func(certs); return; }
|
||||
if (obj.parent.config.letsencrypt == null) { func(certs); return; }
|
||||
if (obj.parent.config.letsencrypt.email == null) { console.log("ERROR: Let's Encrypt email address not specified."); func(certs); return; }
|
||||
if ((obj.parent.redirserver == null) || (obj.parent.redirserver.port !== 80)) { console.log("ERROR: Redirection web server must be active on port 80 for Let's Encrypt to work."); func(certs); return; }
|
||||
|
@ -1056,6 +1056,8 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
|
||||
}
|
||||
if ((command.intelamt.host != null) && (device.intelamt.host != command.intelamt.host)) { changes.push('AMT host'); device.intelamt.host = command.intelamt.host; change = 1; log = 1; }
|
||||
if ((command.intelamt.uuid != null) && (device.intelamt.uuid != command.intelamt.uuid)) { changes.push('AMT uuid'); device.intelamt.uuid = command.intelamt.uuid; change = 1; log = 1; }
|
||||
if ((command.intelamt.user != null) && (device.intelamt.user != command.intelamt.user)) { changes.push('AMT user'); device.intelamt.user = command.intelamt.user; change = 1; log = 1; }
|
||||
if ((command.intelamt.pass != null) && (device.intelamt.pass != command.intelamt.pass)) { changes.push('AMT pass'); device.intelamt.pass = command.intelamt.pass; change = 1; log = 1; }
|
||||
}
|
||||
if ((command.users != null) && (device.users != command.users)) { device.users = command.users; change = 1; } // Don't save this to the db.
|
||||
if ((mesh.mtype == 2) && (!obj.args.wanonly)) {
|
||||
|
@ -702,7 +702,7 @@ function CreateMeshCentralServer(config, args) {
|
||||
var i;
|
||||
|
||||
// If the certificate is un-configured, force LAN-only mode
|
||||
if (obj.certificates.CommonName == 'un-configured') { /*console.log('Server name not configured, running in LAN-only mode.');*/ obj.args.lanonly = true; }
|
||||
if (obj.certificates.CommonName.indexOf('.') == -1) { /*console.log('Server name not configured, running in LAN-only mode.');*/ obj.args.lanonly = true; }
|
||||
|
||||
// Write server version and run mode
|
||||
var productionMode = (process.env.NODE_ENV && (process.env.NODE_ENV == 'production'));
|
||||
|
@ -126,7 +126,7 @@ module.exports.CreateMeshMail = function (parent) {
|
||||
// Send account check mail
|
||||
obj.sendAccountCheckMail = function (domain, username, email) {
|
||||
var template = getTemplateEx('account-check', domain);
|
||||
if ((template == null) || (template.htmlSubject == null) || (template.txtSubject == null) || (parent.certificates == null) || (parent.certificates.CommonName == null) || (parent.certificates.CommonName == 'un-configured')) return; // If the server name is not set, no reset possible.
|
||||
if ((template == null) || (template.htmlSubject == null) || (template.txtSubject == null) || (parent.certificates == null) || (parent.certificates.CommonName == null) || (parent.certificates.CommonName.indexOf('.') == -1)) return; // If the server name is not set, no reset possible.
|
||||
|
||||
// Set all the options.
|
||||
var options = { username: username, email: email, servername: domain.title };
|
||||
@ -140,7 +140,7 @@ module.exports.CreateMeshMail = function (parent) {
|
||||
// Send account reset mail
|
||||
obj.sendAccountResetMail = function (domain, username, email) {
|
||||
var template = getTemplateEx('account-reset', domain);
|
||||
if ((template == null) || (template.htmlSubject == null) || (template.txtSubject == null) || (parent.certificates == null) || (parent.certificates.CommonName == null) || (parent.certificates.CommonName == 'un-configured')) return; // If the server name is not set, don't validate the email address.
|
||||
if ((template == null) || (template.htmlSubject == null) || (template.txtSubject == null) || (parent.certificates == null) || (parent.certificates.CommonName == null) || (parent.certificates.CommonName.indexOf('.') == -1)) return; // If the server name is not set, don't validate the email address.
|
||||
|
||||
// Set all the options.
|
||||
var options = { username: username, email: email, servername: domain.title };
|
||||
@ -154,7 +154,7 @@ module.exports.CreateMeshMail = function (parent) {
|
||||
// Send agent invite mail
|
||||
obj.sendAgentInviteMail = function (domain, username, email, meshid, name, os, msg, flags) {
|
||||
var template = getTemplateEx('mesh-invite', domain);
|
||||
if ((template == null) || (template.htmlSubject == null) || (template.txtSubject == null) || (parent.certificates == null) || (parent.certificates.CommonName == null) || (parent.certificates.CommonName == 'un-configured')) return; // If the server name is not set, don't validate the email address.
|
||||
if ((template == null) || (template.htmlSubject == null) || (template.txtSubject == null) || (parent.certificates == null) || (parent.certificates.CommonName == null) || (parent.certificates.CommonName.indexOf('.') == -1)) return; // If the server name is not set, don't validate the email address.
|
||||
|
||||
// Set all the template replacement options and generate the final email text (both in txt and html formats).
|
||||
var options = { username: username, name: name, email: email, installflags: flags, msg: msg, meshid: meshid, meshidhex: meshid.split('/')[2], servername: domain.title };
|
||||
|
@ -70,7 +70,7 @@ module.exports.CreateMeshScanner = function (parent) {
|
||||
server4.bind(bindOptions, function () {
|
||||
try {
|
||||
var doscan = true;
|
||||
try { this.setBroadcast(true); this.setMulticastTTL(128); this.addMembership(membershipIPv4); } catch (e) { doscan = false; }
|
||||
try { this.setBroadcast(true); this.setMulticastTTL(128); this.addMembership(membershipIPv4, this.xxlocal); } catch (e) { doscan = false; }
|
||||
this.on('error', function (error) { console.log('Error: ' + error); });
|
||||
this.on('message', function (msg, info) { onUdpPacket(msg, info, this); });
|
||||
if (doscan == true) { obj.performScan(this); obj.performScan(this); }
|
||||
@ -101,7 +101,7 @@ module.exports.CreateMeshScanner = function (parent) {
|
||||
server6.bind(bindOptions, function () {
|
||||
try {
|
||||
var doscan = true;
|
||||
try { this.setBroadcast(true); this.setMulticastTTL(128); this.addMembership(membershipIPv6); } catch (e) { doscan = false; }
|
||||
try { this.setBroadcast(true); this.setMulticastTTL(128); this.addMembership(membershipIPv6, this.xxlocal); } catch (e) { doscan = false; }
|
||||
this.on('error', function (error) { console.log('Error: ' + error); });
|
||||
this.on('message', function (msg, info) { onUdpPacket(msg, info, this); });
|
||||
if (doscan == true) { obj.performScan(this); obj.performScan(this); }
|
||||
@ -140,13 +140,13 @@ module.exports.CreateMeshScanner = function (parent) {
|
||||
// Build the IPv4 response
|
||||
var url = (parent.args.notls ? 'ws' : 'wss') + '://%s:' + parent.args.port + '/agent.ashx';
|
||||
obj.multicastPacket4 = Buffer.from("MeshCentral2|" + obj.agentCertificateHashHex + '|' + url, 'ascii');
|
||||
if (parent.certificates.CommonName != "un-configured") { url = (parent.args.notls ? 'ws' : 'wss') + '://' + parent.certificates.CommonName + ':' + parent.args.port + '/agent.ashx'; }
|
||||
if (parent.certificates.CommonName.indexOf('.') != -1) { url = (parent.args.notls ? 'ws' : 'wss') + '://' + parent.certificates.CommonName + ':' + parent.args.port + '/agent.ashx'; }
|
||||
obj.multicastPacket4x = Buffer.from("MeshCentral2|" + obj.agentCertificateHashHex + '|' + url + '|' + name + '|' + info, 'ascii');
|
||||
|
||||
// Build the IPv6 response
|
||||
url = (parent.args.notls ? 'ws' : 'wss') + '://[%s]:' + parent.args.port + '/agent.ashx';
|
||||
obj.multicastPacket6 = Buffer.from("MeshCentral2|" + obj.agentCertificateHashHex + '|' + url, 'ascii');
|
||||
if (parent.certificates.CommonName != "un-configured") { url = (parent.args.notls ? 'ws' : 'wss') + '://' + parent.certificates.CommonName + ':' + parent.args.port + '/agent.ashx'; }
|
||||
if (parent.certificates.CommonName.indexOf('.') != -1) { url = (parent.args.notls ? 'ws' : 'wss') + '://' + parent.certificates.CommonName + ':' + parent.args.port + '/agent.ashx'; }
|
||||
obj.multicastPacket6x = Buffer.from("MeshCentral2|" + obj.agentCertificateHashHex + '|' + url + '|' + name + '|' + info, 'ascii');
|
||||
|
||||
setupServers();
|
||||
|
20
meshuser.js
20
meshuser.js
@ -1653,7 +1653,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'inviteAgent':
|
||||
{
|
||||
if ((obj.parent.parent.mailserver == null) || (obj.args.lanonly == true)) return; // This operation requires the email server
|
||||
if ((obj.parent.parent.certificates.CommonName == null) || (obj.parent.parent.certificates.CommonName == 'un-configured')) return; // Server name must be configured
|
||||
if ((obj.parent.parent.certificates.CommonName == null) || (obj.parent.parent.certificates.CommonName.indexOf('.') == -1)) return; // Server name must be configured
|
||||
if (obj.common.validateString(command.meshid, 1, 1024) == false) break; // Check meshid
|
||||
if ((command.meshid.split('/').length != 3) || (command.meshid.split('/')[1] != domain.id)) return; // Invalid domain, operation only valid for current domain
|
||||
|
||||
@ -1722,7 +1722,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'otpauth-request':
|
||||
{
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if (twoStepLoginSupported) {
|
||||
// Request a one time password to be setup
|
||||
const otplib = require('otplib');
|
||||
@ -1734,7 +1734,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'otpauth-setup':
|
||||
{
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if (twoStepLoginSupported) {
|
||||
// Perform the one time password setup
|
||||
const otplib = require('otplib');
|
||||
@ -1756,7 +1756,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'otpauth-clear':
|
||||
{
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if (twoStepLoginSupported) {
|
||||
// Clear the one time password secret
|
||||
if (user.otpsecret) {
|
||||
@ -1775,7 +1775,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'otpauth-getpasswords':
|
||||
{
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if (twoStepLoginSupported == false) break;
|
||||
|
||||
// Perform a sub-action
|
||||
@ -1806,7 +1806,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'otp-hkey-get':
|
||||
{
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if (twoStepLoginSupported == false) break;
|
||||
|
||||
// Send back the list of keys we have, just send the list of names and index
|
||||
@ -1819,7 +1819,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'otp-hkey-remove':
|
||||
{
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if (twoStepLoginSupported == false || command.index == null) break;
|
||||
|
||||
// Remove a key
|
||||
@ -1839,7 +1839,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
// Yubico API id and signature key can be requested from https://upgrade.yubico.com/getapikey/
|
||||
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if ((twoStepLoginSupported == false) || (typeof command.otp != 'string')) {
|
||||
ws.send(JSON.stringify({ action: 'otp-hkey-yubikey-add', result: false, name: command.name }));
|
||||
break;
|
||||
@ -1885,7 +1885,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'otp-hkey-setup-request':
|
||||
{
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if (twoStepLoginSupported == false) break;
|
||||
|
||||
// Build list of known keys
|
||||
@ -1908,7 +1908,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
|
||||
case 'otp-hkey-setup-response':
|
||||
{
|
||||
// Check is 2-step login is supported
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName != 'un-configured') && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly !== true) && (obj.args.nousers !== true));
|
||||
if ((twoStepLoginSupported == false) || (command.response == null) || (command.name == null) || (obj.hardwareKeyRegistrationRequest == null)) break;
|
||||
|
||||
// Check the key registration request
|
||||
|
58
mpsserver.js
58
mpsserver.js
@ -157,19 +157,19 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
|
||||
// Event the new node
|
||||
var device2 = common.Clone(device);
|
||||
if (device2.intelamt.pass != undefined) delete device2.intelamt.pass; // Remove the Intel AMT password before eventing this.
|
||||
if (device2.intelamt.pass != null) delete device2.intelamt.pass; // Remove the Intel AMT password before eventing this.
|
||||
var change = 'CIRA added device ' + socket.tag.name + ' to mesh ' + mesh.name;
|
||||
obj.parent.DispatchEvent(['*', socket.tag.meshid], obj, { etype: 'node', action: 'addnode', node: device2, msg: change, domain: domainid });
|
||||
} else {
|
||||
// New CIRA connection for unknown node, disconnect.
|
||||
console.log('CIRA connection for unknown node with incorrect mesh type. meshid: ' + socket.tag.meshid);
|
||||
console.log('CIRA connection for unknown node with incorrect group type. meshid: ' + socket.tag.meshid);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Node is already present
|
||||
var node = nodes[0];
|
||||
if ((node.intelamt != undefined) && (node.intelamt.state == 2)) { socket.tag.host = node.intelamt.host; }
|
||||
if ((node.intelamt != null) && (node.intelamt.state == 2)) { socket.tag.host = node.intelamt.host; }
|
||||
}
|
||||
|
||||
// Add the connection to the MPS connection list
|
||||
@ -177,7 +177,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
obj.parent.SetConnectivityState(socket.tag.meshid, socket.tag.nodeid, socket.tag.connectTime, 2, 7); // TODO: Right now report power state as "present" (7) until we can poll.
|
||||
});
|
||||
} else {
|
||||
console.log('ERROR: Intel AMT CIRA connected with unknown meshid: ' + socket.tag.meshid);
|
||||
console.log('ERROR: Intel AMT CIRA connected with unknown groupid: ' + socket.tag.meshid);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
@ -242,7 +242,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
Debug(3, 'MPS:USERAUTH_REQUEST user=' + username + ', service=' + serviceName + ', method=' + methodName + ', password=' + password);
|
||||
|
||||
// Check the CIRA password
|
||||
if ((args.mpspass != undefined) && (password != args.mpspass)) { Debug(1, 'MPS:Incorrect password', username, password); SendUserAuthFail(socket); return -1; }
|
||||
if ((args.mpspass != null) && (password != args.mpspass)) { Debug(1, 'MPS:Incorrect password', username, password); SendUserAuthFail(socket); return -1; }
|
||||
|
||||
// Check the CIRA username, which should be the start of the MeshID.
|
||||
if (usernameLen != 16) { Debug(1, 'MPS:Username length not 16', username, password); SendUserAuthFail(socket); return -1; }
|
||||
@ -269,19 +269,19 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
|
||||
// Event the new node
|
||||
var device2 = common.Clone(device);
|
||||
if (device2.intelamt.pass != undefined) delete device2.intelamt.pass; // Remove the Intel AMT password before eventing this.
|
||||
var change = 'CIRA added device ' + socket.tag.name + ' to mesh ' + mesh.name;
|
||||
if (device2.intelamt.pass != null) delete device2.intelamt.pass; // Remove the Intel AMT password before eventing this.
|
||||
var change = 'CIRA added device ' + socket.tag.name + ' to group ' + mesh.name;
|
||||
obj.parent.DispatchEvent(['*', socket.tag.meshid], obj, { etype: 'node', action: 'addnode', node: device2, msg: change, domain: mesh.domain });
|
||||
} else {
|
||||
// New CIRA connection for unknown node, disconnect.
|
||||
console.log('CIRA connection for unknown node with incorrect mesh type. meshid: ' + socket.tag.meshid);
|
||||
console.log('CIRA connection for unknown node with incorrect group type. meshid: ' + socket.tag.meshid);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Node is already present
|
||||
var node = nodes[0];
|
||||
if ((node.intelamt != undefined) && (node.intelamt.state == 2)) { socket.tag.host = node.intelamt.host; }
|
||||
if ((node.intelamt != null) && (node.intelamt.state == 2)) { socket.tag.host = node.intelamt.host; }
|
||||
}
|
||||
|
||||
// Add the connection to the MPS connection list
|
||||
@ -294,14 +294,14 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
obj.db.getAmtUuidNode(mesh._id, socket.tag.SystemId, function (err, nodes) { // TODO: May need to optimize this request with indexes
|
||||
if (nodes.length == 0) {
|
||||
// New CIRA connection for unknown node, disconnect.
|
||||
console.log('CIRA connection for unknown node. meshid: ' + mesh._id + ', uuid: ' + systemid);
|
||||
console.log('CIRA connection for unknown node. groupid: ' + mesh._id + ', uuid: ' + systemid);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Node is present
|
||||
var node = nodes[0];
|
||||
if ((node.intelamt != undefined) && (node.intelamt.state == 2)) { socket.tag.host = node.intelamt.host; }
|
||||
if ((node.intelamt != null) && (node.intelamt.state == 2)) { socket.tag.host = node.intelamt.host; }
|
||||
socket.tag.nodeid = node._id;
|
||||
socket.tag.meshid = mesh._id;
|
||||
socket.tag.connectTime = Date.now();
|
||||
@ -313,7 +313,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
});
|
||||
} else { // Unknown mesh type
|
||||
// New CIRA connection for unknown node, disconnect.
|
||||
console.log('CIRA connection to a unknown mesh type. meshid: ' + socket.tag.meshid);
|
||||
console.log('CIRA connection to a unknown group type. groupid: ' + socket.tag.meshid);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
@ -341,9 +341,8 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
if (len < 14 + requestLen + addrLen) return 0;
|
||||
var addr = data.substring(10 + requestLen, 10 + requestLen + addrLen);
|
||||
var port = common.ReadInt(data, 10 + requestLen + addrLen);
|
||||
if (addr == '') addr = undefined;
|
||||
Debug(2, 'MPS:GLOBAL_REQUEST', request, addr + ':' + port);
|
||||
ChangeHostname(socket, addr);
|
||||
ChangeHostname(socket, addr, socket.tag.SystemId);
|
||||
if (socket.tag.boundPorts.indexOf(port) == -1) { socket.tag.boundPorts.push(port); }
|
||||
SendTcpForwardSuccessReply(socket, port);
|
||||
return 14 + requestLen + addrLen;
|
||||
@ -428,7 +427,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
var WindowSize = common.ReadInt(data, 9);
|
||||
socket.tag.activetunnels++;
|
||||
var cirachannel = socket.tag.channels[RecipientChannel];
|
||||
if (cirachannel == undefined) { /*console.log("MPS Error in CHANNEL_OPEN_CONFIRMATION: Unable to find channelid " + RecipientChannel);*/ return 17; }
|
||||
if (cirachannel == null) { /*console.log("MPS Error in CHANNEL_OPEN_CONFIRMATION: Unable to find channelid " + RecipientChannel);*/ return 17; }
|
||||
cirachannel.amtchannelid = SenderChannel;
|
||||
cirachannel.sendcredits = cirachannel.amtCiraWindow = WindowSize;
|
||||
Debug(3, 'MPS:CHANNEL_OPEN_CONFIRMATION', RecipientChannel, SenderChannel, WindowSize);
|
||||
@ -438,7 +437,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
} else {
|
||||
cirachannel.state = 2;
|
||||
// Send any pending data
|
||||
if (cirachannel.sendBuffer != undefined) {
|
||||
if (cirachannel.sendBuffer != null) {
|
||||
if (cirachannel.sendBuffer.length <= cirachannel.sendcredits) {
|
||||
// Send the entire pending buffer
|
||||
SendChannelData(cirachannel.socket, cirachannel.amtchannelid, cirachannel.sendBuffer);
|
||||
@ -464,7 +463,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
var ReasonCode = common.ReadInt(data, 5);
|
||||
Debug(3, 'MPS:CHANNEL_OPEN_FAILURE', RecipientChannel, ReasonCode);
|
||||
var cirachannel = socket.tag.channels[RecipientChannel];
|
||||
if (cirachannel == undefined) { console.log("MPS Error in CHANNEL_OPEN_FAILURE: Unable to find channelid " + RecipientChannel); return 17; }
|
||||
if (cirachannel == null) { console.log("MPS Error in CHANNEL_OPEN_FAILURE: Unable to find channelid " + RecipientChannel); return 17; }
|
||||
if (cirachannel.state > 0) {
|
||||
cirachannel.state = 0;
|
||||
if (cirachannel.onStateChange) { cirachannel.onStateChange(cirachannel, cirachannel.state); }
|
||||
@ -478,7 +477,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
var RecipientChannel = common.ReadInt(data, 1);
|
||||
Debug(3, 'MPS:CHANNEL_CLOSE', RecipientChannel);
|
||||
var cirachannel = socket.tag.channels[RecipientChannel];
|
||||
if (cirachannel == undefined) { console.log("MPS Error in CHANNEL_CLOSE: Unable to find channelid " + RecipientChannel); return 5; }
|
||||
if (cirachannel == null) { console.log("MPS Error in CHANNEL_CLOSE: Unable to find channelid " + RecipientChannel); return 5; }
|
||||
socket.tag.activetunnels--;
|
||||
if (cirachannel.state > 0) {
|
||||
cirachannel.state = 0;
|
||||
@ -493,10 +492,10 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
var RecipientChannel = common.ReadInt(data, 1);
|
||||
var ByteToAdd = common.ReadInt(data, 5);
|
||||
var cirachannel = socket.tag.channels[RecipientChannel];
|
||||
if (cirachannel == undefined) { console.log("MPS Error in CHANNEL_WINDOW_ADJUST: Unable to find channelid " + RecipientChannel); return 9; }
|
||||
if (cirachannel == null) { console.log("MPS Error in CHANNEL_WINDOW_ADJUST: Unable to find channelid " + RecipientChannel); return 9; }
|
||||
cirachannel.sendcredits += ByteToAdd;
|
||||
Debug(3, 'MPS:CHANNEL_WINDOW_ADJUST', RecipientChannel, ByteToAdd, cirachannel.sendcredits);
|
||||
if (cirachannel.state == 2 && cirachannel.sendBuffer != undefined) {
|
||||
if (cirachannel.state == 2 && cirachannel.sendBuffer != null) {
|
||||
// Compute how much data we can send
|
||||
if (cirachannel.sendBuffer.length <= cirachannel.sendcredits) {
|
||||
// Send the entire pending buffer
|
||||
@ -521,7 +520,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
if (len < (9 + LengthOfData)) return 0;
|
||||
Debug(4, 'MPS:CHANNEL_DATA', RecipientChannel, LengthOfData);
|
||||
var cirachannel = socket.tag.channels[RecipientChannel];
|
||||
if (cirachannel == undefined) { console.log("MPS Error in CHANNEL_DATA: Unable to find channelid " + RecipientChannel); return 9 + LengthOfData; }
|
||||
if (cirachannel == null) { console.log("MPS Error in CHANNEL_DATA: Unable to find channelid " + RecipientChannel); return 9 + LengthOfData; }
|
||||
cirachannel.amtpendingcredits += LengthOfData;
|
||||
if (cirachannel.onData) cirachannel.onData(cirachannel, data.substring(9, 9 + LengthOfData));
|
||||
if (cirachannel.amtpendingcredits > (cirachannel.ciraWindow / 2)) {
|
||||
@ -600,7 +599,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
|
||||
function SendChannelOpen(socket, direct, channelid, windowsize, target, targetport, source, sourceport) {
|
||||
var connectionType = ((direct == true) ? "direct-tcpip" : "forwarded-tcpip");
|
||||
if ((target == null) || (target == undefined)) target = ''; // TODO: Reports of target being undefined that causes target.length to fail. This is a hack.
|
||||
if ((target == null) || (target == null)) target = ''; // TODO: Reports of target being undefined that causes target.length to fail. This is a hack.
|
||||
Write(socket, String.fromCharCode(APFProtocol.CHANNEL_OPEN) + common.IntToStr(connectionType.length) + connectionType + common.IntToStr(channelid) + common.IntToStr(windowsize) + common.IntToStr(-1) + common.IntToStr(target.length) + target + common.IntToStr(targetport) + common.IntToStr(source.length) + source + common.IntToStr(sourceport));
|
||||
}
|
||||
|
||||
@ -650,9 +649,9 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
// This function writes data to this CIRA channel
|
||||
cirachannel.write = function (data) {
|
||||
if (cirachannel.state == 0) return false;
|
||||
if (cirachannel.state == 1 || cirachannel.sendcredits == 0 || cirachannel.sendBuffer != undefined) {
|
||||
if (cirachannel.state == 1 || cirachannel.sendcredits == 0 || cirachannel.sendBuffer != null) {
|
||||
// Channel is connected, but we are out of credits. Add the data to the outbound buffer.
|
||||
if (cirachannel.sendBuffer == undefined) { cirachannel.sendBuffer = data; } else { cirachannel.sendBuffer += data; }
|
||||
if (cirachannel.sendBuffer == null) { cirachannel.sendBuffer = data; } else { cirachannel.sendBuffer += data; }
|
||||
return true;
|
||||
}
|
||||
// Compute how much data we can send
|
||||
@ -683,7 +682,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
return cirachannel;
|
||||
};
|
||||
|
||||
function ChangeHostname(socket, host) {
|
||||
function ChangeHostname(socket, host, systemid) {
|
||||
if (socket.tag.host === host) return; // Nothing to change
|
||||
socket.tag.host = host;
|
||||
|
||||
@ -693,7 +692,7 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
var node = nodes[0];
|
||||
|
||||
// See if any changes need to be made
|
||||
if ((node.intelamt != undefined) && (node.intelamt.host == host) && (node.name != '') && (node.intelamt.state == 2)) return;
|
||||
if ((node.intelamt != null) && (node.intelamt.host == host) && (node.name != null) && (node.name != '') && (node.intelamt.state == 2)) return;
|
||||
|
||||
// Get the mesh for this device
|
||||
obj.db.Get(node.meshid, function (err, meshes) {
|
||||
@ -705,14 +704,15 @@ module.exports.CreateMpsServer = function (parent, db, args, certificates) {
|
||||
event.msg = +": ";
|
||||
|
||||
// Make the change & save
|
||||
if (node.intelamt == undefined) node.intelamt = {};
|
||||
if (node.intelamt == null) node.intelamt = {};
|
||||
node.intelamt.host = host;
|
||||
node.intelamt.state = 2; // Set the state to activated, since this is pretty obvious, we have a CIRA connection.
|
||||
if (node.name == '') { node.name = host.split('.')[0]; }
|
||||
if (((node.name == null) || (node.name == '')) && (host != null) && (host != '')) { node.name = host.split('.')[0]; } // If this system has no name, set it to the start of the domain name.
|
||||
if (((node.name == null) || (node.name == '')) && (systemid != null)) { node.name = systemid; } // If this system still has no name, set it to the system GUID.
|
||||
obj.db.Set(node);
|
||||
|
||||
// Event the node change
|
||||
event.msg = 'CIRA changed device ' + node.name + ' from mesh ' + mesh.name + ': ' + changes.join(', ');
|
||||
event.msg = 'CIRA changed device ' + node.name + ' from group ' + mesh.name + ': ' + changes.join(', ');
|
||||
var node2 = common.Clone(node);
|
||||
if (node2.intelamt && node2.intelamt.pass) delete node2.intelamt.pass; // Remove the Intel AMT password before eventing this.
|
||||
event.node = node2;
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "meshcentral",
|
||||
"version": "0.2.9-o",
|
||||
"version": "0.2.9-p",
|
||||
"keywords": [
|
||||
"Remote Management",
|
||||
"Intel AMT",
|
||||
|
@ -34,7 +34,7 @@ module.exports.CreateRedirServer = function (parent, db, args, func) {
|
||||
var host = req.headers.host;
|
||||
if (obj.certificates != null) {
|
||||
host = obj.certificates.CommonName;
|
||||
if ((obj.certificates.CommonName == "sample.org") || (obj.certificates.CommonName == "un-configured")) { host = req.headers.host; }
|
||||
if (obj.certificates.CommonName.indexOf('.') == -1) { host = req.headers.host; }
|
||||
}
|
||||
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
|
||||
if (req.headers && req.headers.host && (req.headers.host.split(":")[0].toLowerCase() == "localhost")) {
|
||||
|
@ -2516,7 +2516,7 @@
|
||||
|
||||
setDialogMode(2, "Add Mesh Agent", 2, null, x, 'fileDownload');
|
||||
var servername = serverinfo.name;
|
||||
if ((servername == 'un-configured') || ((features & 2) != 0)) { servername = window.location.hostname; } // If the server name is not set or it's in LAN-only mode, use the URL hostname as server name.
|
||||
if ((servername.indexOf('.') == -1) || ((features & 2) != 0)) { servername = window.location.hostname; } // If the server name is not set or it's in LAN-only mode, use the URL hostname as server name.
|
||||
|
||||
var noProxy = ((features & 0x2000) != 0)?'--no-proxy ':''; // Server asked that agent be installed to preferably not use a HTTP proxy.
|
||||
if (serverinfo.https == true) {
|
||||
|
10
webserver.js
10
webserver.js
@ -326,7 +326,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
|
||||
|
||||
// Check the 2-step auth token
|
||||
function checkUserOneTimePassword(req, domain, user, token, hwtoken, func) {
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.certificates.CommonName != 'un-configured') && (obj.args.nousers !== true));
|
||||
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.nousers !== true));
|
||||
if (twoStepLoginSupported == false) { func(true); return; };
|
||||
|
||||
// Check U2F hardware key
|
||||
@ -1073,13 +1073,13 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
|
||||
if (domain.userQuota == -1) { features += 0x00000008; } // No server files mode
|
||||
if (obj.args.mpstlsoffload) { features += 0x00000010; } // No mutual-auth CIRA
|
||||
if ((parent.config != null) && (parent.config.settings != null) && (parent.config.settings.allowframing == true)) { features += 0x00000020; } // 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 += 0x00000040; } // Email invites
|
||||
if ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true)) { features += 0x00000040; } // Email invites
|
||||
if (obj.args.webrtc == true) { features += 0x00000080; } // Enable WebRTC (Default false for now)
|
||||
if (obj.args.clickonce !== false) { features += 0x00000100; } // Enable ClickOnce (Default true)
|
||||
if (obj.args.allowhighqualitydesktop == true) { features += 0x00000200; } // Enable AllowHighQualityDesktop (Default false)
|
||||
if (obj.args.lanonly == true || obj.args.mpsport == 0) { features += 0x00000400; } // No CIRA
|
||||
if ((obj.parent.serverSelfWriteAllowed == true) && (user != null) && (user.siteadmin == 0xFFFFFFFF)) { features += 0x00000800; } // Server can self-write (Allows self-update)
|
||||
if ((domain.auth != 'sspi') && (obj.parent.certificates.CommonName != 'un-configured') && (obj.args.nousers !== true)) { features += 0x00001000; } // 2-step login supported
|
||||
if ((domain.auth != 'sspi') && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.nousers !== true)) { features += 0x00001000; } // 2-step login supported
|
||||
if (domain.agentnoproxy === true) { features += 0x00002000; } // Indicates that agents should be installed without using a HTTP proxy
|
||||
if (domain.yubikey && domain.yubikey.id && domain.yubikey.secret) { features += 0x00004000; } // Indicates Yubikey support
|
||||
if (domain.geolocation == true) { features += 0x00008000; } // Enable geo-location features
|
||||
@ -1188,14 +1188,14 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
|
||||
if (obj.args.tlsoffload != null) return true; // We are using TLS offload, a real cert is likely used.
|
||||
if (obj.parent.config.letsencrypt != null) return true; // We are using Let's Encrypt, real cert in use.
|
||||
if (obj.certificates.WebIssuer.indexOf('MeshCentralRoot-') == 0) return false; // Our cert is issued by self-signed cert.
|
||||
if (obj.certificates.CommonName == 'un-configured') return false; // Out cert is named with a fake name
|
||||
if (obj.certificates.CommonName.indexOf('.') == -1) return false; // Our cert is named with a fake name
|
||||
return true; // This is a guess
|
||||
}
|
||||
|
||||
// Get the link to the root certificate if needed
|
||||
function getRootCertLink() {
|
||||
// Check if the HTTPS certificate is issued from MeshCentralRoot, if so, add download link to root certificate.
|
||||
if ((obj.args.notls == null) && (obj.args.tlsoffload == null) && (obj.parent.config.letsencrypt == null) && (obj.tlsSniCredentials == null) && (obj.certificates.WebIssuer.indexOf('MeshCentralRoot-') == 0) && (obj.certificates.CommonName != 'un-configured')) { return '<a href=/MeshServerRootCert.cer title="Download the root certificate for this server">Root Certificate</a>'; }
|
||||
if ((obj.args.notls == null) && (obj.args.tlsoffload == null) && (obj.parent.config.letsencrypt == null) && (obj.tlsSniCredentials == null) && (obj.certificates.WebIssuer.indexOf('MeshCentralRoot-') == 0) && (obj.certificates.CommonName.indexOf('.') != -1)) { return '<a href=/MeshServerRootCert.cer title="Download the root certificate for this server">Root Certificate</a>'; }
|
||||
return '';
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user