MeshCentral/agents/meshcmd.js

1166 lines
702 KiB
JavaScript
Raw Normal View History

2018-01-31 05:23:57 +03:00
/*
Copyright 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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.
*/
/**
* @description MeshCmd, command line tool for Intel AMT and MeshCentral.
* @author Ylian Saint-Hilaire
* @version v0.2.0
*/
2018-03-07 04:50:44 +03:00
//console.displayFinalizerMessages = 1;
2017-11-01 02:19:58 +03:00
var fs = require('fs');
var os = require('os');
var net = require('net');
var http = require('http');
var dgram = require('dgram');
var httpHeaders = require('http-headers');
var tcpserver = null;
var broadcastSockets = {};
var multicastSockets = {};
var discoveryInterval = null;
var membershipIPv4 = '239.255.255.235';
var membershipIPv6 = 'FF02:0:0:0:0:0:0:FE';
var settings = null;
2018-01-31 05:23:57 +03:00
var meshCmdVersion = '***Mesh*Cmd*Version***'; // Dynamically replaced with MeshCentral version
var amtLms = null, amtMei = null, amtMeiState = null;
2018-02-08 05:45:14 +03:00
var wsstack = null, amtstack = null;
var oswsstack = null, osamtstack = null;
2018-03-07 04:50:44 +03:00
var amtMeiTmpState = null;
var SMBiosTables = null;
2018-02-08 05:45:14 +03:00
// MeshCommander for Firmware (GZIP'ed, Base64)
var Small_IntelAmtWebApp = "H4sIAAAAAAAEAHq/e7+Noou/c0hkgCuA0+psjxSHwX+F7ZVbYCZTYMn13vt9FViAnxibM562PPnvJ4+ZBMLkWupYVnn1SpbtVaYWl2/tX681B4FphbysTBwGwROSI7DLtzUaIEXT+Pjnhm/TP/xfP/Q/VnUDhmcCvVxJg9KkD7/8NEVW4kNncis3uDdvbIwkr0C3aNKNKfzVw6HTj52y/8uhwd5eQo1poXQNxmdoMDdcyaFXgU2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+vwigjlUgeyDpPJSdyErCi0jgl65wWE7qcCXH7crRkCN0KQygUDIYjoc2lu5twoDtC+TQcgY1omoLUZqXpMkM55drdosyl3i+oiy2TpyuCs5wSdhHdg7Rb2UQJ2IgiYEdT2KDgV96pait6ygKrq3v
2017-11-01 02:19:58 +03:00
// Check the server certificate fingerprint
function onVerifyServer(clientName, certs) {
2018-01-27 04:01:38 +03:00
if (certs == null) { certs = clientName; } // Temporary thing until we fix duktape
2017-11-01 02:19:58 +03:00
try { for (var i in certs) { if (certs[i].fingerprint.replace(/:/g, '') == settings.serverHttpsHash) { return; } } } catch (e) { }
if (serverhash != null) { console.log('Error: Failed to verify server certificate.'); throw 'Invalid server certificate'; }
2017-11-01 02:19:58 +03:00
}
2018-03-07 04:50:44 +03:00
// Various utility functions
2017-11-01 02:19:58 +03:00
function debug(level, message) { if ((settings.debugLevel != null) && (settings.debugLevel >= level)) { console.log(message); } }
function exit(status) { if (status == null) { status = 0; } try { process.exit(status); } catch (e) { } }
2018-03-07 04:50:44 +03:00
function getInstance(x, y) { for (var i in x) { if (x[i]["InstanceID"] == y) return x[i]; } return null; }
function md5hex(str) { return require('MD5Stream').create().syncHash(str).toString('hex'); }
function guidToStr(g) { return g.substring(6, 8) + g.substring(4, 6) + g.substring(2, 4) + g.substring(0, 2) + "-" + g.substring(10, 12) + g.substring(8, 10) + "-" + g.substring(14, 16) + g.substring(12, 14) + "-" + g.substring(16, 20) + "-" + g.substring(20); }
function parceArguments(argv) { var r = {}; for (var i in argv) { i = parseInt(i); if (argv[i].startsWith('--') == true) { var key = argv[i].substring(2).toLowerCase(), val = true; if (((i + 1) < argv.length) && (argv[i + 1].startsWith('--') == false)) { val = argv[i + 1]; } r[key] = val; } } return r; }
2017-11-03 04:44:27 +03:00
// Convert an object to string with all functions
function objToString(x, p, ret) {
if (ret == undefined) ret = '';
if (p == undefined) p = 0;
if (x == null) { return '[null]'; }
if (p > 8) { return '[...]'; }
if (x == undefined) { return '[undefined]'; }
if (typeof x == 'string') { if (p == 0) return x; return '"' + (x.split('\0')[0]) + '"'; }
if (typeof x == 'buffer') { return '[buffer]'; }
if (typeof x != 'object') { return x; }
var r = '{' + (ret ? '\r\n' : ' ');
for (var i in x) {
if (i != '_ObjectID') { r += (addPad(p + 2, ret) + i + ': ' + objToString(x[i], p + 2, ret) + (ret ? '\r\n' : ' ')); }
}
return r + addPad(p, ret) + '}';
}
// Return p number of spaces
function addPad(p, ret) { var r = ''; for (var i = 0; i < p; i++) { r += ' '; } return r; }
2018-01-31 05:23:57 +03:00
// Parse the incoming arguments
2017-11-01 02:19:58 +03:00
function run(argv) {
if (meshCmdVersion[0] == '*') { meshCmdVersion = ''; } else { meshCmdVersion = ' v' + meshCmdVersion; }
2017-11-03 04:44:27 +03:00
var args = parceArguments(argv);
//console.log(JSON.stringify(argv));
//console.log('addedModules = ' + JSON.stringify(addedModules));
2017-11-01 02:19:58 +03:00
var actionpath = 'meshaction.txt';
2017-11-03 04:44:27 +03:00
if (args.actionfile != null) { actionpath = args.actionfile; }
var actions = ['HELP', 'ROUTE', 'AMTLMS', 'AMTLOADWEBAPP', 'AMTLOADSMALLWEBAPP', 'AMTLOADLARGEWEBAPP', 'AMTCLEARWEBAPP', 'AMTSTORAGESTATE', 'AMTINFO', 'AMTVERSIONS', 'AMTHASHES', 'AMTSAVESTATE', 'AMTSCRIPT', 'AMTUUID', 'AMTCCM', 'AMTDEACTIVATE', 'SMBIOS', 'RAWSMBIOS', 'MESHCOMMANDER', 'AMTAUDITLOG'];
2017-11-01 02:19:58 +03:00
// Load the action file
var actionfile = null;
try { actionfile = fs.readFileSync(actionpath); } catch (e) { }
if ((actionpath != 'meshaction.txt') && (actionfile == null)) { console.log('Unable to load \"' + actionpath + '\". Create this file or specify the location using --actionfile [filename].'); exit(1); return; }
if (actionfile != null) { try { settings = JSON.parse(actionfile); } catch (e) { console.log(actionpath, e); exit(1); return; } } else { if (argv.length >= 2) { settings = { action: argv[1] } } }
2017-12-16 00:43:04 +03:00
if (settings == null) { settings = {}; }
2017-11-01 02:19:58 +03:00
2017-11-03 04:44:27 +03:00
// Set the arguments
2017-12-16 00:43:04 +03:00
if ((typeof args.action) == 'string') { settings.action = args.action; }
2017-11-03 04:44:27 +03:00
if ((typeof args.localport) == 'string') { settings.localport = parseInt(args.localport); }
if ((typeof args.remotenodeid) == 'string') { settings.remoteNodeId = args.remotenodeid; }
if ((typeof args.username) == 'string') { settings.username = args.username; }
if ((typeof args.password) == 'string') { settings.password = args.password; }
if ((typeof args.user) == 'string') { settings.username = args.user; }
if ((typeof args.pass) == 'string') { settings.password = args.pass; }
if ((typeof args.host) == 'string') { settings.hostname = args.host; }
if ((typeof args.hostname) == 'string') { settings.hostname = args.hostname; }
2017-11-03 04:44:27 +03:00
if ((typeof args.serverid) == 'string') { settings.serverId = args.serverid; }
if ((typeof args.serverhttpshash) == 'string') { settings.serverHttpsHash = args.serverhttpshash; }
if ((typeof args.remoteport) == 'string') { settings.remotePort = parseInt(args.remoteport); }
2018-01-26 03:12:53 +03:00
if ((typeof args.out) == 'string') { settings.output = args.out; }
if ((typeof args.output) == 'string') { settings.output = args.output; }
if ((typeof args.debug) == 'string') { settings.debugLevel = parseInt(args.debug); }
if ((typeof args.script) == 'string') { settings.script = args.script; }
2018-01-26 03:28:52 +03:00
if (args.noconsole) { settings.noconsole = true; }
if (args.nocommander) { settings.noconsole = true; }
2018-01-26 03:12:53 +03:00
if (args.lmsdebug) { settings.lmsdebug = true; }
if (args.tls) { settings.tls = true; }
2017-12-16 00:43:04 +03:00
if ((argv.length > 1) && (actions.indexOf(argv[1].toUpperCase()) >= 0)) { settings.action = argv[1]; }
2017-11-03 04:44:27 +03:00
2017-11-01 02:19:58 +03:00
// Validate meshaction.txt
if (settings.action == null) {
console.log('MeshCentral Command (MeshCmd) ' + meshCmdVersion);
console.log('No action specified, use MeshCmd like this:\r\n');
console.log(' meshcmd [action] [arguments...]\r\n');
console.log('Valid MeshCentral actions:');
console.log(' Route - Map a local TCP port to a remote computer.');
console.log('\r\nValid local actions:');
console.log(' SMBios - Display System Management BIOS tables for this computer.');
console.log(' RawSMBios - Display RAW System Management BIOS tables for this computer.');
console.log(' AmtInfo - Show Intel AMT version and activation state.');
console.log(' AmtVersions - Show all Intel ME version information.');
console.log(' AmtHashes - Show all Intel AMT trusted activation hashes.');
console.log(' AmtLMS - Run MicroLMS, allowing local access to Intel AMT.');
console.log(' AmtCCM - Activate Intel AMT into Client Control Mode.');
console.log(' AmtDeactivate - Deactivate Intel AMT if activated in Client Control mode.');
console.log('\r\nValid local or remote actions:');
2018-03-20 03:31:54 +03:00
console.log(' MeshCommander - Launch a local MeshCommander web server.');
console.log(' AmtUUID - Show Intel AMT unique identifier.');
console.log(' AmtAuditLog - Show the Intel AMT audit log.');
console.log(' AmtLoadWebApp - Load MeshCommander in Intel AMT 11.6+ firmware.');
console.log(' AmtClearWebApp - Clear everything from Intel AMT web storage.');
console.log(' AmtStorageState - Show contents of the Intel AMT web storage.');
console.log(' AmtSaveState - Save all Intel AMT WSMAN object to file.');
console.log(' AmtScript - Run .mescript on Intel AMT.');
console.log('\r\nHelp on a specific action using:\r\n');
console.log(' meshcmd help [action]');
exit(1); return;
}
if (settings.action == 'help') {
if (argv.length <= 2) {
actions.shift();
console.log('Help usage:\r\n\r\n MeshCmd help [action]\r\n\r\nValid actions are: ' + actions.join(', ') + '.');
exit(1); return;
}
var action = argv[2].toLowerCase();
if (action == 'route') {
console.log("The route action is used along with a MeshCentral account to map a local TCP port to a remote port on any computer on your MeshCentral account. This action requires many arguments, to avoid specifying them all it's best to download the meshaction.txt file from the web site and place it in the current folder. Example usage:\r\n\r\n (Place meshaction.txt file in current folder)\r\n meshcmd route --pass myAccountPassword");
} else if (action == 'smbios') {
console.log("SMBios action will display this computer's system management BIOS information. Example usage:\r\n\r\n meshcmd smbios --out smbios.txt\r\n");
console.log('\r\Optional arguments:\r\n');
console.log(' --output [filename] Optional filename to write the results to.');
} else if (action == 'rawsmbios') {
console.log("RawSMBios action will display this computer's system management BIOS information in raw hexdecimal form. Example usage:\r\n\r\n meshcmd rawsmbios --out smbios.txt\r\n");
console.log('\r\Optional arguments:\r\n');
console.log(' --output [filename] Optional filename to write the results to.');
} else if (action == 'amtinfo') {
console.log('AmtInfo action will get the version and activation state of Intel AMT on this computer. The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. Example usage:\r\n\r\n meshcmd amtinfo');
} else if ((action == 'amtversion') || (action == 'amtversions')) {
console.log('AmtVersions will display all version information about Intel AMT on this computer. The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. Example usage:\r\n\r\n meshcmd amtversions');
} else if (action == 'amthashes') {
console.log('Amthashes will display all trusted activations hashes for Intel AMT on this computer. The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. These certificates hashes are used by Intel AMT when performing activation into ACM mode. Example usage:\r\n\r\n meshcmd amthashes');
} else if (action == 'amtlms') {
console.log('AmtLMS will state MicroLMS on this computer, allowing local access to Intel AMT on TCP ports 16992 and 16993 when applicable. The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. These certificates hashes are used by Intel AMT when performing activation into ACM mode. Example usage:\r\n\r\n meshcmd amtlms');
2018-03-20 03:31:54 +03:00
console.log('\r\nPossible arguments:\r\n');
console.log(' --noconsole MeshCommander for LMS will no be available on port 16994.');
} else if (action == 'amtccm') {
console.log('AmtCCM will attempt to activate Intel AMT on this computer into client control mode (CCM). The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. Intel AMT must be in "pre-provisioning" state for this command to work and a administrator password must be provided. Example usage:\r\n\r\n meshcmd amtccm --pass mypassword');
} else if (action == 'amtdeactivate') {
console.log('AmtDeactivate will attempt to deactivate Intel AMT on this computer when in client control mode (CCM). The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. Intel AMT must be activated in client control mode for this command to work. Example usage:\r\n\r\n meshcmd amtdeactivate');
} else if (action == 'amtuuid') {
console.log('AmtUUID action will get the unique identifier of the local or remote Intel AMT computer. By default, the local UUID is obtained unless a host is specified. Intel AMT must be activated for this command to work. Example usage:\r\n\r\n meshcmd amtuuid --host 1.2.3.4 --user admin --pass mypassword --tls');
2018-03-20 03:31:54 +03:00
console.log('\r\nPossible arguments:\r\n');
console.log(' --host [hostname] The IP address or DNS name of Intel AMT, 127.0.0.1 is default.');
console.log(' --user [username] The Intel AMT login username, admin is default.');
console.log(' --pass [password] The Intel AMT login password.');
console.log(' --tls Specifies that TLS must be used.');
} else if ((action == 'amtloadwebapp') || (action == 'amtloadsmallwebapp') || (action == 'amtloadlargewebapp') || (action == 'amtclearwebapp') || (action == 'amtstoragestate')) {
console.log('AmtLoadWebApp action will load MeshCommander into Intel AMT 11.6 or higher. If the computer is in ACM mode, MeshCommander will replace the default index.htm on HTTP/16992 or HTTPS/16993. If Intel AMT is in CCM mode, MeshCommander will be installed alongside the default web page and will be accessible in the "Web Applications" section. This action works on Intel AMT 11.6 and higher only. Example usage:\r\n\r\n meshcmd amtloadwebapp --host 1.2.3.4 --user admin --pass mypassword --tls');
2018-03-20 03:31:54 +03:00
console.log('\r\nPossible arguments:\r\n');
console.log(' --host [hostname] The IP address or DNS name of Intel AMT, 127.0.0.1 is default.');
console.log(' --user [username] The Intel AMT login username, admin is default.');
console.log(' --pass [password] The Intel AMT login password.');
console.log(' --tls Specifies that TLS must be used.');
} else if (action == 'amtclearwebstorage') {
console.log('AmtClearWebStorage will clear the web storage of Intel AMT, removing any loaded firmware version of MeshCommander. This command can clear the local or a remote Intel AMT computer. By default, the local computer storage is cleared unless a host is specified. Intel AMT must be activated for this command to work. This action works on Intel AMT 11.6 and higher only. Example usage:\r\n\r\n meshcmd amtclearwebstorage --host 1.2.3.4 --user admin --pass mypassword --tls');
2018-03-20 03:31:54 +03:00
console.log('\r\nPossible arguments:\r\n');
console.log(' --host [hostname] The IP address or DNS name of Intel AMT, 127.0.0.1 is default.');
console.log(' --user [username] The Intel AMT login username, admin is default.');
console.log(' --pass [password] The Intel AMT login password.');
console.log(' --tls Specifies that TLS must be used.');
} else if (action == 'amtstoragestate') {
console.log('AmtStorageState will display the content of the web storage of Intel AMT including any loaded firmware version of MeshCommander. This command can read the storage state of a local or remote Intel AMT computer. By default, the local computer storage state is displayed unless a host is specified. Intel AMT must be activated for this command to work. This action works on Intel AMT 11.6 and higher only. Example usage:\r\n\r\n meshcmd amtstoragestate --host 1.2.3.4 --user admin --pass mypassword --tls');
2018-03-20 03:31:54 +03:00
console.log('\r\nPossible arguments:\r\n');
console.log(' --host [hostname] The IP address or DNS name of Intel AMT, 127.0.0.1 is default.');
console.log(' --user [username] The Intel AMT login username, admin is default.');
console.log(' --pass [password] The Intel AMT login password.');
console.log(' --tls Specifies that TLS must be used.');
} else if (action == 'amtsavestate') {
console.log('AmtSaveState action will fetch all the entire state of Intel AMT and save it as a JSON file. This action will take multiple minutes to perform. The command will fetch the local computer state unless host is specified. Intel AMT must be ativated for this command to work. Example usage:\r\n\r\n meshcmd amtsavestate --host 1.2.3.4 --user admin --pass mypassword --tls --output state.json');
2018-03-20 03:31:54 +03:00
console.log('\r\nPossible arguments:\r\n');
console.log(' --output [filename] The output file for the Intel AMT state in JSON format.');
console.log(' --host [hostname] The IP address or DNS name of Intel AMT, 127.0.0.1 is default.');
console.log(' --user [username] The Intel AMT login username, admin is default.');
console.log(' --pass [password] The Intel AMT login password.');
console.log(' --tls Specifies that TLS must be used.');
} else if (action == 'amtscript') {
console.log('AmtScript will run a .mescript file on the local or remote Intel AMT. Script files can be built using the MeshCommander script editor and be used to setup or perform actions on Intel AMT. Example usage:\r\n\r\n meshcmd amtscript --script myscript.mescript --host 1.2.3.4 --user admin --pass mypassword --tls');
2018-03-20 03:31:54 +03:00
console.log('\r\nPossible arguments:\r\n');
console.log(' --script [filename] The script file to run on Intel AMT.');
console.log(' --host [hostname] The IP address or DNS name of Intel AMT, 127.0.0.1 is default.');
console.log(' --user [username] The Intel AMT login username, admin is default.');
console.log(' --pass [password] The Intel AMT login password.');
console.log(' --tls Specifies that TLS must be used.');
2018-03-20 03:31:54 +03:00
} else if (action == 'meshcommander') {
console.log('This action launched a local web server that hosts MeshCommander, a Intel AMT management console.');
console.log('\r\nPossible arguments:\r\n');
console.log(' --localport [port] Local port used for the web server, 3000 is default.');
} else if (action == 'amtauditlog') {
console.log('AmtAuditLog action will fetch the local or remote audit log. If used localy, no username/password is required. Example usage:\r\n\r\n meshcmd amtauditlog --host 1.2.3.4 --user admin --pass mypassword --tls --output audit.json');
console.log('\r\nPossible arguments:\r\n');
console.log(' --output [filename] The output file for the Intel AMT state in JSON format.');
console.log(' --host [hostname] The IP address or DNS name of Intel AMT, 127.0.0.1 is default.');
console.log(' --user [username] The Intel AMT login username, admin is default.');
console.log(' --pass [password] The Intel AMT login password.');
console.log(' --tls Specifies that TLS must be used.');
} else {
actions.shift();
console.log('Invalid action, usage:\r\n\r\n meshcmd help [action]\r\n\r\nValid actions are: ' + actions.join(', ') + '.');
}
exit(1); return;
}
2017-11-01 02:19:58 +03:00
settings.action = settings.action.toLowerCase();
debug(1, "Settings: " + JSON.stringify(settings));
if (settings.action == 'smbios') {
// Display SM BIOS tables in raw form
SMBiosTables = require('smbios');
SMBiosTables.get(function (data) {
var r = SMBiosTables.parse(data);
var out = objToString(r, 0, '\r\n');
if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, new Buffer(out, 'utf8')); fs.closeSync(file); }
exit(1);
});
} else if (settings.action == 'rawsmbios') {
// Display SM BIOS tables in raw form
SMBiosTables = require('smbios');
SMBiosTables.get(function (data) {
var out = '';
for (var i in data) { var header = false; for (var j in data[i]) { if (data[i][j].length > 0) { if (header == false) { out += ('Table type #' + i + ((SMBiosTables.smTableTypes[i] == null) ? '' : (', ' + SMBiosTables.smTableTypes[i]))) + '\r\n'; header = true; } out += (' ' + data[i][j].toString('hex')) + '\r\n'; } } }
if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, new Buffer(out, 'utf8')); fs.closeSync(file); }
exit(1);
});
} else if (settings.action == 'route') {
2018-01-31 05:23:57 +03:00
// MeshCentral Router, port map local TCP port to a remote computer
if ((settings.localPort == null) || (typeof settings.localPort != 'number') || (settings.localPort < 0) || (settings.localPort > 65535)) { console.log('No or invalid \"localPort\" specified, use --localport [localport].'); exit(1); return; }
if ((settings.remoteNodeId == null) || (typeof settings.remoteNodeId != 'string')) { console.log('No or invalid \"remoteNodeId\" specified.'); exit(1); return; }
if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { console.log('No or invalid \"username\" specified, use --username [username].'); exit(1); return; }
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
if ((settings.serverId == null) || (typeof settings.serverId != 'string') || (settings.serverId.length != 96)) { console.log('No or invalid \"serverId\" specified.'); exit(1); return; }
if ((settings.serverHttpsHash == null) || (typeof settings.serverHttpsHash != 'string') || (settings.serverHttpsHash.length != 96)) { console.log('No or invalid \"serverHttpsHash\" specified.'); exit(1); return; }
if ((settings.remotePort == null) || (typeof settings.remotePort != 'number') || (settings.remotePort < 0) || (settings.remotePort > 65535)) { console.log('No or invalid \"remotePort\" specified, use --remoteport [remoteport].'); exit(1); return; }
if (settings.serverUrl != null) { startRouter(); } else { discoverMeshServer(); } // Start MeshCentral Router
} else if ((settings.action == 'amtloadwebapp') || (settings.action == 'amtloadsmallwebapp') || (settings.action == 'amtloadlargewebapp') || (settings.action == 'amtclearwebapp') || (settings.action == 'amtstoragestate')) { // Intel AMT Web Application Actions
2018-01-31 05:23:57 +03:00
// Intel AMT 11.6+ Load MeshCommander into firmware
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
if ((settings.hostname == null) || (typeof settings.hostname != 'string') || (settings.hostname == '')) { settings.hostname = '127.0.0.1'; }
if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { settings.username = 'admin'; }
settings.protocol = 'http:';
settings.localport = 16992;
debug(1, "Settings: " + JSON.stringify(settings));
digest = require('http-digest').create(settings.username, settings.password);
digest.http = require('http');
2017-12-16 00:43:04 +03:00
if (settings.action == 'amtstoragestate') {
getAmtStorage(function (statusCode, data) { if (statusCode == 200) { console.log("Storage State: " + JSON.stringify(data, null, 2)); exit(); return; } else { console.log("Unable to read storage state."); exit(); return; } });
} else {
2017-12-16 00:43:04 +03:00
if (settings.action == 'amtloadwebapp') { settings.webapp = Medium_IntelAmtWebApp; }
else if (settings.action == 'amtloadsmallwebapp') { settings.webapp = Small_IntelAmtWebApp; }
else if (settings.action == 'amtloadlargewebapp') { settings.webapp = Large_IntelAmtWebApp; }
else if (settings.action == 'amtclearwebapp') { settings.webapp = null; }
nextStepStorageUpload();
}
} else if ((settings.action == 'amtversion') || (settings.action == 'amtversions') || (settings.action == 'amtver')) {
2018-01-31 05:23:57 +03:00
// Display Intel AMT versions
var amtMeiModule = require('amt-mei');
var amtMei = new amtMeiModule();
2018-01-26 03:28:52 +03:00
amtMei.on('error', function (e) { console.log('ERROR: ' + e); exit(1); return; });
2018-03-20 03:31:54 +03:00
amtMei.getVersion(function (val) {
console.log("MEI Version = " + val.BiosVersion.toString());
for (var version in val.Versions) { console.log(val.Versions[version].Description + " = " + val.Versions[version].Version); }
exit(1); return;
});
} else if (settings.action == 'amthashes') {
2018-01-31 05:23:57 +03:00
// Display Intel AMT list of trusted hashes
var amtMeiModule = require('amt-mei');
var amtMei = new amtMeiModule();
2018-01-26 03:28:52 +03:00
amtMei.on('error', function (e) { console.log('ERROR: ' + e); exit(1); return; });
2018-03-20 03:31:54 +03:00
amtMei.getHashHandles(function (handles) {
exitOnCount = handles.length;
for (var i = 0; i < handles.length; ++i) {
this.getCertHashEntry(handles[i], function (result) {
console.log(result.name + ', (' + (result.isDefault ? 'Default' : '') + (result.isActive ? ', Active' : ', Disabled') + ')\r\n ' + result.hashAlgorithmStr + ': ' + result.certificateHash);
if (--exitOnCount == 0) { exit(1); }
});
}
});
} else if (settings.action == 'amtinfo') {
2018-01-31 05:23:57 +03:00
// Display Intel AMT version and activation state
2018-03-20 03:31:54 +03:00
mestate = {};
2018-01-31 05:23:57 +03:00
var amtMeiModule = require('amt-mei');
var amtMei = new amtMeiModule();
2018-01-26 03:28:52 +03:00
amtMei.on('error', function (e) { console.log('ERROR: ' + e); exit(1); return; });
2018-03-20 03:31:54 +03:00
amtMei.getVersion(function (val) { for (var version in val.Versions) { if (val.Versions[version].Description == 'AMT') { mestate.ver = val.Versions[version].Version; } } });
amtMei.getProvisioningState(function (result) { mestate.ProvisioningState = result; });
amtMei.getProvisioningMode(function (result) { mestate.ProvisioningMode = result; });
amtMei.getEHBCState(function (result) { mestate.ehbc = result; });
amtMei.getControlMode(function (result) { mestate.controlmode = result; });
amtMei.getMACAddresses(function (result) { mestate.mac = result; });
amtMei.getDnsSuffix(function (result) {
mestate.dns = result;
var str = 'Intel AMT v' + mestate.ver;
if (mestate.ProvisioningState.stateStr == 'PRE') { str += ', pre-provisioning state'; }
else if (mestate.ProvisioningState.stateStr == 'IN') { str += ', in-provisioning state'; }
else if (mestate.ProvisioningState.stateStr == 'POST') { if (mestate.ProvisioningMode.modeStr == 'ENTERPRISE') { str += ', activated in ' + ["none", "client control mode", "admin control mode", "remote assistance mode"][mestate.controlmode.controlMode]; } else { str += ', activated in ' + mestate.ProvisioningMode.modeStr; } }
if (mestate.ehbc.EHBC == true) { str += ', EHBC enabled'; }
console.log(str + '.');
exit(1);
});
2018-01-03 03:52:49 +03:00
} else if (settings.action == 'amtsavestate') {
2018-01-31 05:23:57 +03:00
// Save the entire state of Intel AMT info a JSON file
2018-01-26 03:12:53 +03:00
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
if ((settings.hostname == null) || (typeof settings.hostname != 'string') || (settings.hostname == '')) { settings.hostname = '127.0.0.1'; }
if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { settings.username = 'admin'; }
if ((settings.output == null) || (typeof settings.output != 'string') || (settings.output == '')) { console.log('No or invalid \"output\" file specified, use --output [filename].'); exit(1); return; }
settings.protocol = 'http:';
settings.localport = 16992;
debug(1, "Settings: " + JSON.stringify(settings));
2018-01-03 03:52:49 +03:00
saveEntireAmtState();
2017-12-16 00:43:04 +03:00
} else if (settings.action == 'amtlms') {
2018-01-31 05:23:57 +03:00
// Start Intel AMT MicroLMS
2018-03-20 03:31:54 +03:00
startLms(function (state) {
console.log(['MicroLMS did not start. MicroLMS must run as administrator or LMS any already be active.', 'MicroLMS started.', 'MicroLMS started, MeshCommander on HTTP/16994.', 'MEI error'][state]); console.log('Press ctrl-c to exit.'); if (state == 0) { exit(0); }
});
} else if (settings.action == 'amtscript') {
// Start running a MEScript
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
if ((settings.hostname == null) || (typeof settings.hostname != 'string') || (settings.hostname == '')) { settings.hostname = '127.0.0.1'; }
if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { settings.username = 'admin'; }
2018-03-07 04:50:44 +03:00
if ((settings.script == null) || (typeof settings.script != 'string') || (settings.script == '')) { if (mescriptJSON != '') { settings.scriptJSON = mescriptJSON; } else { console.log('No or invalid \"script\" file specified, use --script [filename].'); exit(1); return; } }
startMeScript();
2018-03-07 04:50:44 +03:00
} else if (settings.action == 'amtuuid') {
// Start running
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
if ((settings.hostname == null) || (typeof settings.hostname != 'string') || (settings.hostname == '')) { settings.hostname = '127.0.0.1'; }
if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { settings.username = 'admin'; }
settings.protocol = 'http:';
settings.localport = 16992;
debug(1, "Settings: " + JSON.stringify(settings));
getAmtUuid();
} else if (settings.action == 'amtccm') {
// Start activation to CCM
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
settings.protocol = 'http:';
settings.localport = 16992;
debug(1, "Settings: " + JSON.stringify(settings));
activeToCCM();
} else if (settings.action == 'amtdeactivate') {
// Deactivate CCM
debug(1, "Settings: " + JSON.stringify(settings));
deactivateCCM();
} else if (settings.action == 'meshcommander') { // Start MeshCommander
2018-03-20 03:31:54 +03:00
startMeshCommander();
} else if (settings.action == 'amtauditlog') { // Read the Intel AMT audit log
if (settings.hostname != null) {
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { settings.username = 'admin'; }
} else { settings.hostname = '127.0.0.1'; }
readAmtAuditLog();
2017-11-01 02:19:58 +03:00
} else {
console.log('Invalid \"action\" specified.'); exit(1); return;
2017-11-01 02:19:58 +03:00
}
}
2017-11-01 02:19:58 +03:00
//
// Intel AMT Audit Log
//
function readAmtAuditLog() {
// See if MicroLMS needs to be started
if ((settings.hostname == '127.0.0.1') || (settings.hostname.toLowerCase() == 'localhost')) {
settings.noconsole = true; startLms(readAmtAuditLogEx);
} else {
readAmtAuditLogEx(9999);
}
}
function readAmtAuditLogEx(x) {
if (x == 9999) {
var transport = require('amt-wsman-duk');
var wsman = require('amt-wsman');
var amt = require('amt');
wsstack = new wsman(transport, settings.hostname, settings.tls ? 16993 : 16992, settings.username, settings.password, settings.tls);
amtstack = new amt(wsstack);
amtstack.GetAuditLog(readAmtAuditLogEx2);
} else {
osamtstack.GetAuditLog(readAmtAuditLogEx2);
}
}
function readAmtAuditLogEx2(stack, response, status) {
if (status != 200) {
console.log('Unable to get audit log, status = ' + status + '.');
} else {
var out = '';
for (var i in response) {
var name = ((response[i].Initiator != '')?(response[i].Initiator + ': '):'')
out += (response[i].Time + ' - ' + name + response[i].Event + '\r\n');
}
if (settings.output == null) { console.log(out); } else { var file = fs.openSync(settings.output, 'w'); fs.writeSync(file, new Buffer(out, 'utf8')); fs.closeSync(file); }
}
exit(1);
}
2018-03-20 03:31:54 +03:00
//
// MeshCommander local web server
//
function startMeshCommander() {
// MeshCommander Local v0.6.0
var _IntelAmtLocalWebApp_etag = "IH1l5967WLK68i1M/uTj";
var _IntelAmtLocalWebApp = "H4sIAAAAAAAEALxYiVa7PBZ/Fab/WfR88gl0b8Vz6KK2tn93/fc7a4AA0ZAghNLa44vN+kjzCpMUqCB19hn33Nz1d29yb/zrH/5y8qvR1fB+cT2WPObj0xPxU4rYGkPdg8j1WE9VlN9wOgT26YkPGeCMLJDha4yW+g/5wZCH1A8AQyaGkkUJg4TptclYh7YLa5nIjs7gih0LG33LA2EEmR4zR+7UikqHKbN8vw5gJk+AD3WHhj5gsg0ZtBiipKgVw8CjBOqEcpMYkRcphFivIc5SkxhXpCMfuPA4IK7khdDRazZgoLcj9k0QwVbjCD0Orm4T5fLcpTrXtAXi1KT2elNAo++DlVxc0yUMHUyTnodsG5K+Q7n7DvARXvdAiAA+kjyIl5AhCxxJESCRHMEQOSljhN5grxuwvkUxDXsmBtZL3+Q/3JDGxO4lHmKQ2wxdRGRGg56SLzB02Mcq5A6JpZxA8wUxzhpbnmwBjGnMeoTDs9uKuXnuAoZWvvEikrKH7tO3fdSoSqwQ3jHapK5xpwJg24i4PYWTgQnxxkZRgMGah0utlyz0BBGbJqJGCvHLxb3+HoUJspmXJiLV3fNEQjYVFR4HCAuQ+p/WW4vvoLdEEWLQ3oi1bEOLhkAUWhpOKvNNaTiCVdTYP8GXuZLRAKjXNa3/7qmbj8yrasDSQkjSkjIptku1UMx2M1gVS0FVPtYmZYz6vRanvHtawUL3XzHQKhtoVfTzDAabvyPRqEqUK1QTDjK77CCneFVKDl8cRtzZgCLCYFioDQEp6L//LG4nzhfQCG0T4aAVtPvpWckOSX46snPbagerkqIWaHVbSpGEEYEglN0Q2AgSdqDW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bFE16vj3yr+2YqRSzxG/Ust8lqMaB0jMAcjMlMFZB4jcwWgDCRjs9nA/QIm5RyGY7wkbv78a5JRPyuYF4ER6pthndGlbJwx6oPhWSVAEpnROJTRefPHnC/D1Pqf3mllf2EYh2REXpZfA2NkN/mLFakhpyj3PH9mvv7xxcZMpk7Xxp1YyDgOfli4iLQGm7++j9THRmJbacaeOe9pTERPZQ0GrCnq/qPNOYIj1TVo0aWOmdtOmsZMIPxAHcRGieCrtPFpAXgObPm/DxpTgKpDAjQO+MSZIdmZPcBVHsjamaP6rIuq1JJNtmzNZ2ZzSgPQuAEJo6xf2PTalCBl1ONGoz4/JYvzJaoqfLoHkAlAeAcijAKtCsY0slXk3xvFgsRaXX3vH+Spfv7hstKIWo7PtARquQaCdwG92s8NVTzkZh+Df24e479x/j599dvWV1019wfoonvsoHbg1gH085ldnAEmOh0tbYr4thD3ze1Q8hjsyhnGUsmMknyVqflabHksp1EQoEDQL2vF5pikH93cZpiot3tt8NT9AyWO+SOkcqy6sawIeqzIfQzbfCxbfCwHPrUxO5yie5zdsBw3uowkKbWavpzdtuKXMYU6Mhf8YwpDZ51UTr2cwc57CDG+g28eXBpOIVlVe1nOdtiXqb3YldKWEdp2qLuurqMxjjA5F2T2z0vheKVlHUfuT8fw68efF18WAlmqZDqvZbyBH/FcfuTLMG99veL1y59BFl/fQ31eC/gzrVFxdsS5vuxEsp9xpsJZuex8s1MrvpG5rOwVqS1kpgCbyu/brGP2s34Zz5zPbnC7V+9cYnQv+Ws35t2eZr2D9eZPbIJjCniK23ZrP2I4L/4VkFzHDs66QqOHPzJ21bqWOBv6FbNi3D3fCBKnvKq3/k5I2WYHyO047uSngRtZ46zwN1Oe9rBk+7N+xmu7ra+/CjnaTD8+i+C5v0MRoRF3ZaDf12SHXHbuempKE/F82W/0NY7ZXjnqp9Ljcd7qRcBuqGFXp1Bh8tTDfECe/X1Z3WYafqYP4XYyjLz
if (settings.localport == null) { settings.localport = 3000; }
// Start the web server
var http = require('http');
webServer = http.createServer();
webServer.listen(settings.localport);
webServer.wsList = {};
webServer.wsListIndex = 0;
2018-03-20 03:31:54 +03:00
webServer.on('upgrade', function (req, socket, head) {
//console.log("WebSocket for " + req.url.split('?')[0]);
switch (req.url.split('?')[0]) {
case '/webrelay.ashx': // MeshCommander relay channel
var ws = socket.upgradeWebSocket();
socket.ws = ws;
ws.wsIndex = ++webServer.wsListIndex;
webServer.wsList[ws.wsIndex] = ws;
2018-03-20 03:31:54 +03:00
ws.pause();
// We got a new web socket connection, initiate a TCP connection to the target Intel AMT host/port.
var webargs = parseUrlArguments(req.url);
if (webargs.p) { webargs.p = parseInt(webargs.p); }
if (webargs.tls) { webargs.tls = parseInt(webargs.tls); }
if (webargs.tls1only) { webargs.tls1only = parseInt(webargs.tls1only); }
if (webargs.port) { webargs.port = parseInt(webargs.port); }
//console.log('Opening web socket connection to ' + webargs.host + ':' + webargs.port + '.');
if (webargs.tls == 0) {
// If this is TCP (without TLS) set a normal TCP socket
var net = require('net');
ws.forwardclient = net.connect({ host: webargs.host, port: webargs.port })
ws.forwardclient.on('connect', function () { this.pipe(this.ws); this.ws.pipe(this); });
2018-03-20 03:31:54 +03:00
ws.forwardclient.ws = ws;
} else {
// If TLS is going to be used, setup a TLS socket
var tls = require('tls');
var tlsoptions = { host: webargs.host, port: webargs.port, secureProtocol: ((webargs.tls1only == 1) ? 'TLSv1_method' : 'SSLv23_method'), rejectUnauthorized: false };
ws.forwardclient = tls.connect(tlsoptions, function () { this.pipe(this.ws); this.ws.pipe(this); });
2018-03-20 03:31:54 +03:00
ws.forwardclient.ws = ws;
}
break;
default:
socket.end();
break;
}
});
webServer.on('request', function (req, rsp) {
//console.log("WebRequest for " + req.url.split('?')[0]);
switch (req.url.split('?')[0]) {
case '/': // Serve MeshCommander Web Application
var meshcommander = null;
try { meshcommander = fs.readFileSync('meshcommander.htm'); } catch (e) { }
if (meshcommander != null) {
rsp.writeHead(200, 'OK', { Server: 'JSLMS', 'Cache-Control': 'max-age=0, no-cache', 'X-Frame-Options': 'DENY', 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked' });
rsp.end(meshcommander);
} else {
rsp.writeHead(200, 'OK', { Server: 'JSLMS', 'Cache-Control': 'max-age=0, no-cache', 'X-Frame-Options': 'DENY', 'Content-Type': 'text/html', 'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', ETag: _IntelAmtLocalWebApp_etag });
rsp.end(Buffer.from(_IntelAmtLocalWebApp, 'base64'));
}
break;
default: // Unknown request
rsp.statusCode = 404;
rsp.statusMessage = "Not Found";
rsp.end();
break;
}
});
console.log('MeshCommander running on HTTP port ' + settings.localport + '.');
console.log('Press ctrl-c to exit.');
}
2018-03-07 04:50:44 +03:00
//
// 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() {
var amtMeiModule = require('amt-mei');
var amtMei = new amtMeiModule();
amtMei.on('error', function (e) { console.log('ERROR: ' + e); exit(1); return; });
2018-03-20 03:31:54 +03:00
amtMei.unprovision(1, function (status) { if (status == 0) { console.log('Success'); } else { console.log('Error ' + status); } exit(1); });
2018-03-07 04:50:44 +03:00
}
//
// Activate Intel AMT to CCM
//
function activeToCCM() {
// See if MicroLMS needs to be started and setup the $$OsAdmin wsman stack
settings.noconsole = true;
startLms(activeToCCMEx); // TODO: Fix this so that it works even if LMS already running.
}
function activeToCCMEx(state) {
osamtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], activeToCCMEx2);
}
function activeToCCMEx2(stack, name, responses, status) {
if (status != 200) { console.log('Failed to fetch activation status, status ' + status); exit(1); }
else if (responses['IPS_HostBasedSetupService'].response['AllowedControlModes'].length != 2) { console.log('Client control mode activation not allowed'); exit(1); }
else { osamtstack.IPS_HostBasedSetupService_Setup(2, md5hex('admin:' + responses['AMT_GeneralSettings'].response['DigestRealm'] + ':' + settings.password).substring(0,32), null, null, null, null, activeToCCMEx3); }
}
function activeToCCMEx3(stack, name, responses, status) {
if (status != 200) { console.log('Failed to activate, status ' + status); }
else if (responses.Body.ReturnValue != 0) { console.log('Client control mode activation failed: ' + responses.Body.ReturnValueStr); }
else { console.log('Success'); exit(0); }
exit(1);
}
//
// Get AMT UUID
//
// Called to get the UUID of Intel AMT, start by setting up MicroLMS if we are doing the operation on the local computer
function getAmtUuid() {
// See if MicroLMS needs to be started
if ((settings.hostname == '127.0.0.1') || (settings.hostname.toLowerCase() == 'localhost')) { settings.noconsole = true; startLms(getAmtUuidEx); } else { getAmtUuidEx() };
}
// Fetch the computer's UUID by fetching the CIM_ComputerSystemPackage WSMAN object.
function getAmtUuidEx() {
var transport = require('amt-wsman-duk');
var wsman = require('amt-wsman');
var amt = require('amt');
wsstack = new wsman(transport, settings.hostname, settings.tls ? 16993 : 16992, settings.username, settings.password, settings.tls);
amtstack = new amt(wsstack);
amtstack.Get("CIM_ComputerSystemPackage", function (obj, name, response, xstatus, tag) {
if (xstatus == 200) { console.log("GUID: " + guidToStr(response.Body.PlatformGUID.toLowerCase())); } else { console.log("Intel AMT is not available or not activated."); } exit(1);
});
}
//
// Run MESCRIPT
//
2018-03-07 04:50:44 +03:00
// Run a .mescript targeting local or remote Intel AMT.
function startMeScript() {
// See if MicroLMS needs to be started
if ((settings.hostname == '127.0.0.1') || (settings.hostname.toLowerCase() == 'localhost')) { settings.noconsole = true; startLms(startMeScriptEx); return; } else { startMeScriptEx(); }
}
function startMeScriptEx() {
2018-03-07 04:50:44 +03:00
//console.log('Running script...');
var transport = require('amt-wsman-duk');
var wsman = require('amt-wsman');
var amt = require('amt');
wsstack = new wsman(transport, settings.hostname, settings.tls ? 16993 : 16992, settings.username, settings.password, settings.tls);
amtstack = new amt(wsstack);
2018-02-08 05:45:14 +03:00
//IntelAmtEntireStateProgress = 101;
//amtstack.onProcessChanged = onWsmanProcessChanged;
var scriptData = null;
2018-03-07 04:50:44 +03:00
if (settings.script != null) {
try { scriptData = fs.readFileSync(settings.script); } catch (e) { console.log('Unable to read script file (1): ' + settings.script + '.'); exit(1); return; }
} else {
scriptData = settings.scriptJSON;
}
if (scriptData == null) { console.log('Unable to read script file (2): ' + settings.script + '.'); exit(1); return; }
try { scriptData = JSON.parse(scriptData); } catch (e) { console.log('Unable to read script file (3): ' + settings.script + '.'); exit(1); return; }
if (scriptData.mescript == null) { console.log('Unable to read script file (4): ' + settings.script + '.'); exit(1); return; }
var scriptData = Buffer.from(scriptData.mescript, 'base64');
var scriptModule = require('amt-script');
var script = scriptModule.setup(scriptData, {})
script.amtstack = amtstack;
script.start();
2018-03-07 04:50:44 +03:00
script.onCompleted = function () { exit(1);}
}
2018-01-31 05:23:57 +03:00
2018-03-07 04:50:44 +03:00
2018-01-31 05:23:57 +03:00
//
// FETCH ALL INTEL AMT STATE
//
2018-01-03 03:52:49 +03:00
// Save the entire Intel AMT state
function saveEntireAmtState() {
2018-01-26 03:28:52 +03:00
// See if MicroLMS needs to be started
if ((settings.hostname == '127.0.0.1') || (settings.hostname.toLowerCase() == 'localhost')) { settings.noconsole = true; startLms(); }
2018-01-26 03:12:53 +03:00
console.log('Fetching all Intel AMT state, this may take a few minutes...');
2018-01-31 05:23:57 +03:00
var transport = require('amt-wsman-duk');
var wsman = require('amt-wsman');
var amt = require('amt');
2018-01-26 03:12:53 +03:00
wsstack = new wsman(transport, settings.hostname, settings.tls?16993:16992, settings.username, settings.password, settings.tls);
2018-01-03 03:52:49 +03:00
amtstack = new amt(wsstack);
2018-01-26 03:28:52 +03:00
amtstack.onProcessChanged = onWsmanProcessChanged;
//var AllWsman = "AMT_GeneralSystemDefenseCapabilities".split(',');
2018-01-03 03:52:49 +03:00
var AllWsman = "AMT_8021xCredentialContext,AMT_8021XProfile,AMT_ActiveFilterStatistics,AMT_AgentPresenceCapabilities,AMT_AgentPresenceInterfacePolicy,AMT_AgentPresenceService,AMT_AgentPresenceWatchdog,AMT_AgentPresenceWatchdogAction,AMT_AlarmClockService,IPS_AlarmClockOccurrence,AMT_AssetTable,AMT_AssetTableService,AMT_AuditLog,AMT_AuditPolicyRule,AMT_AuthorizationService,AMT_BootCapabilities,AMT_BootSettingData,AMT_ComplexFilterEntryBase,AMT_CRL,AMT_CryptographicCapabilities,AMT_EACCredentialContext,AMT_EndpointAccessControlService,AMT_EnvironmentDetectionInterfacePolicy,AMT_EnvironmentDetectionSettingData,AMT_EthernetPortSettings,AMT_EventLogEntry,AMT_EventManagerService,AMT_EventSubscriber,AMT_FilterEntryBase,AMT_FilterInSystemDefensePolicy,AMT_GeneralSettings,AMT_GeneralSystemDefenseCapabilities,AMT_Hdr8021Filter,AMT_HeuristicPacketFilterInterfacePolicy,AMT_HeuristicPacketFilterSettings,AMT_HeuristicPacketFilterStatistics,AMT_InterfacePolicy,AMT_IPHeadersFilter,AMT_KerberosSettingData,AMT_ManagementPresenceRemoteSAP,AMT_MessageLog,AMT_MPSUsernamePassword,AMT_NetworkFilter,AMT_NetworkPortDefaultSystemDefensePolicy,AMT_NetworkPortSystemDefenseCapabilities,AMT_NetworkPortSystemDefensePolicy,AMT_PCIDevice,AMT_PETCapabilities,AMT_PETFilterForTarget,AMT_PETFilterSetting,AMT_ProvisioningCertificateHash,AMT_PublicKeyCertificate,AMT_PublicKeyManagementCapabilities,AMT_PublicKeyManagementService,AMT_PublicPrivateKeyPair,AMT_RedirectionService,AMT_RemoteAccessCapabilities,AMT_RemoteAccessCredentialContext,AMT_RemoteAccessPolicyAppliesToMPS,AMT_RemoteAccessPolicyRule,AMT_RemoteAccessService,AMT_SetupAndConfigurationService,AMT_SNMPEventSubscriber,AMT_StateTransitionCondition,AMT_SystemDefensePolicy,AMT_SystemDefensePolicyInService,AMT_SystemDefenseService,AMT_SystemPowerScheme,AMT_ThirdPartyDataStorageAdministrationService,AMT_ThirdPartyDataStorageService,AMT_TimeSynchronizationService,AMT_TLSCredentialContext,AMT_TLSProtocolEndpoint,AMT_TLSProtocolEndpointCollection,AMT_TLSSettingData,AMT_TrapTargetForService,AMT_UserInitiatedConnectionService,AMT_WebUIService,AMT_WiFiPortConfigurationService,CIM_AbstractIndicationSubscription,CIM_Account,CIM_AccountManagementCapabilities,CIM_AccountManagementService,CIM_AccountOnSystem,CIM_AdminDomain,CIM_AlertIndication,CIM_AssignedIdentity,CIM_AssociatedPowerManagementService,CIM_AuthenticationService,CIM_AuthorizationService,CIM_BIOSElement,CIM_BIOSFeature,CIM_BIOSFeatureBIOSElements,CIM_BootConfigSetting,CIM_BootService,CIM_BootSettingData,CIM_BootSourceSetting,CIM_Capabilities,CIM_Card,CIM_Chassis,CIM_Chip,CIM_Collection,CIM_Component,CIM_ComputerSystem,CIM_ComputerSystemPackage,CIM_ConcreteComponent,CIM_ConcreteDependency,CIM_Controller,CIM_CoolingDevice,CIM_Credential,CIM_CredentialContext,CIM_CredentialManagementService,CIM_Dependency,CIM_DeviceSAPImplementation,CIM_ElementCapabilities,CIM_ElementConformsToProfile,CIM_ElementLocation,CIM_ElementSettingData,CIM_ElementSoftwareIdentity,CIM_ElementStatisticalData,CIM_EnabledLogicalElement,CIM_EnabledLogicalElementCapabilities,CIM_EthernetPort,CIM_Fan,CIM_FilterCollection,CIM_FilterCollectionSubscription,CIM_HostedAccessPoint,CIM_HostedDependency,CIM_HostedService,CIM_Identity,CIM_IEEE8021xCapabilities,CIM_IEEE8021xSettings,CIM_Indication,CIM_IndicationService,CIM_InstalledSoftwareIdentity,CIM_KVMRedirectionSAP,CIM_LANEndpoint,CIM_ListenerDestination,CIM_ListenerDestinationWSManagement,CIM_Location,CIM_Log,CIM_LogEntry,CIM_LogicalDevice,CIM_LogicalElement,CIM_LogicalPort,CIM_LogicalPortCapabilities,CIM_LogManagesRecord,CIM_ManagedCredential,CIM_ManagedElement,CIM_ManagedSystemElement,CIM_MediaAccessDevice,CIM_MemberOfCollection,CIM_Memory,CIM_MessageLog,CIM_NetworkPort,CIM_NetworkPortCapabilities,CIM_NetworkPortConfigurationService,CIM_OrderedComponent,CIM_OwningCollectionElement,CIM_OwningJobElement,CIM_PCIController,CIM_PhysicalComponent,CIM_PhysicalElement,CIM_PhysicalElementLocation,CIM_PhysicalFrame,CIM_PhysicalMemory,CIM_PhysicalPackage,CIM_Policy,CIM_PolicyAction,CIM_PolicyCondition,CIM_PolicyInSystem,CIM_PolicyRule,CIM_PolicyR
2018-01-26 03:28:52 +03:00
IntelAmtEntireStateProgress = 101;
2018-01-03 03:52:49 +03:00
IntelAmtEntireStateCalls = 3;
IntelAmtEntireState = { 'localtime': Date(), 'utctime': new Date().toUTCString(), 'isotime': new Date().toISOString() };
amtstack.BatchEnum(null, AllWsman, saveEntireAmtStateOk2, null, true);
amtstack.GetAuditLog(saveEntireAmtStateOk3);
amtstack.GetMessageLog(saveEntireAmtStateOk4);
}
2018-01-26 03:28:52 +03:00
function onWsmanProcessChanged(a, b) { var x = Math.floor((a * 100) / b); if (x < IntelAmtEntireStateProgress) { IntelAmtEntireStateProgress = x; console.log((100 - x) + '%'); } }
function saveEntireAmtStateOk2(stack, name, responses, status) { if (status == 600) { console.log('ERROR: Unable to connect to Intel(R) AMT.'); exit(2); } IntelAmtEntireState['wsmanenums'] = responses; saveEntireAmtStateDone(); }
function saveEntireAmtStateOk3(stack, messages, status) { if (status == 600) { console.log('ERROR: Unable to connect to Intel(R) AMT.'); exit(2); } IntelAmtEntireState['auditlog'] = messages; saveEntireAmtStateDone(); }
function saveEntireAmtStateOk4(stack, messages, tag, status) { if (status == 600) { console.log('ERROR: Unable to connect to Intel(R) AMT.'); exit(2); } IntelAmtEntireState['eventlog'] = messages; saveEntireAmtStateDone(); }
2018-01-03 03:52:49 +03:00
2018-01-31 05:23:57 +03:00
// Called when the entire state of Intel AMT is fetched.
2018-01-03 03:52:49 +03:00
function saveEntireAmtStateDone() {
if (--IntelAmtEntireStateCalls != 0) return;
2018-01-26 03:12:53 +03:00
var out = fs.openSync(settings.output, 'w');
fs.writeSync(out, new Buffer(JSON.stringify(IntelAmtEntireState), 'utf8'));
fs.closeSync(out);
console.log('Done, results written to ' + settings.output + '.');
2018-01-03 03:52:49 +03:00
exit(1);
}
2018-01-31 05:23:57 +03:00
//
// FETCH ALL INTEL AMT MEI STATE
//
// Get Intel AMT information using MEI
2018-03-07 04:50:44 +03:00
// TODO: If this call is called many time at once, it's going to cause issues.
function getAmtInfo(func, tag) {
2018-03-07 04:50:44 +03:00
//console.log('getAmtInfo1');
if (amtMei == null) { if (func != null) { func(null, tag); } return; }
2018-03-07 04:50:44 +03:00
amtMeiTmpState = { Flags: 0, TrustedHashes: [] }; // Flags: 1=EHBC, 2=CCM, 4=ACM
amtMei.getProtocolVersion(function (result) { if (result != null) { amtMeiTmpState.MeiVersion = result; } });
amtMei.getVersion(function (val) {
amtMeiTmpState.Versions = {};
if (val != null) {
for (var version in val.Versions) { amtMeiTmpState.Versions[val.Versions[version].Description] = val.Versions[version].Version; }
amtMei.getProvisioningMode(function (result) { if (result != null) { amtMeiTmpState.ProvisioningMode = result.mode; } });
amtMei.getProvisioningState(function (result) { if (result != null) { 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 != null) { amtMeiTmpState.mac = result; } });
amtMei.getDnsSuffix(function (result) { if (result != null) { amtMeiTmpState.dns = result; } });
amtMei.getHashHandles(function (handles) {
exitOnCount = handles.length;
for (var i = 0; i < handles.length; ++i) {
amtMei.getCertHashEntry(handles[i], function (result) {
amtMeiTmpState.TrustedHashes.push({ Active: result.isActive, Default: result.isDefault, HashAlgorithm: result.hashAlgorithm, Name: result.name, Hash: result.certificateHash });
2018-03-07 04:50:44 +03:00
if (--exitOnCount == 0) {
amtMeiTmpState.Notifications = lmsNotifications; amtMeiState = amtMeiTmpState;
//console.log('getAmtInfo2', JSON.stringify(amtMeiState));
if (func != null) { func(amtMeiTmpState, tag); }
amtMeiTmpState = null;
}
});
}
});
} else {
amtMeiState = amtMeiTmpState;
amtMeiState.ProvisioningMode = -858993460;
amtMeiState.TrustedHashes = {};
amtMeiState.Notifications = lmsNotifications;
2018-03-07 04:50:44 +03:00
//console.log('getAmtInfo3', JSON.stringify(amtMeiState));
if (func != null) { func(amtMeiState, tag); }
}
});
}
2018-01-31 05:23:57 +03:00
//
// MicroLMS
//
var lmsControlSockets = {};
var lmsControlSocketsNextId = 1;
var lmsNotifications = [];
2018-03-07 04:50:44 +03:00
var amtLms = null;
2018-01-26 03:28:52 +03:00
function startLms(func) {
2018-01-31 05:23:57 +03:00
var lme_heci = require('amt-lme');
2018-03-07 04:50:44 +03:00
//var amtLms = null;
var http = require('http');
2018-03-07 04:50:44 +03:00
// MeshCommander LMS v0.6.0 with LMS improvements
var _IntelAmtWebApp_etag = "EywwrEJnIclcslSGdOXb";
var _IntelAmtWebApp = "H4sIAAAAAAAEAOy9aVvb2JYo/J1foahuE6ssjG2GEAtBG2MSV5gKQ1LVHC6PJtsqbMmRZIYQftn9cH/S+xfetfYgbU22Seqcvv10n+4K1h7WWnvNe9DW//d//u/um8OzzuWf511pFE3Ge7v4rxRGT2NHHznucBS1GvX6v0G5Y9h7uxMnMqBhNF1zvs7ce/2Ptav2WsefTI3INceOZPle5HiRLve6umMPHZl1icsj5zFaRxyaNTKC0In0WTRY25FFoB3aeO3yaeqw/p4xcfSBH0yMaM12IseKXN8ToY6d6cj3HN3zAeXY9e6kwBnrsgtNZCkCQLo7MYbO+tQbSqPAGeiybURGKy7UTCN0tjdV9/PB2cVD/dOHoa8DJMKIPdO3n54FbmgT43FNfPbvnWAw9h9aI9e2HU8bAGFrA2Pijp9aRuAaY1UaOeN7J3ItQ5VCwwvXQidwB7Rh6H5zWu+nkWb5Yz9omWPDugN6rLth4M88u/UwciMHcAZD11uL/Gmrzh/GziBKngJCUF1be3DMOzeCpjNrtGYZ47E/i1oesCeumg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u6T3NundxWkABnCxS2OrjNAt0qk9A+ee7dQsG12TDQ/CAZiP2GWnpMcO6XDqRA9+cIcGiLqaYgn4rhIK35G+aOaBB7ZY2LmMJQ3Kk74DNuRGT8Wd35d1fk95M0SGnoMyOZ6VGm2jbLiNHVH+h87A8cJ0z1LFoay9CiFCtS0LYmSU1pyNMplskI5fjDtHao+NYEK7MXMLqahwozRMWTRfoCo2Z66nfMMoqdnIO/TUEQV3EBgThzTdnNuUp051wE07ZYnYyvuF
2018-01-31 05:23:57 +03:00
var amtMeiModule = require('amt-mei');
amtMei = new amtMeiModule();
2018-01-26 03:28:52 +03:00
amtMei.on('error', function (e) { console.log('ERROR: ' + e); exit(1); return; });
2018-03-20 03:31:54 +03:00
//console.log("PTHI Connected.");
amtLms = new lme_heci({ debug: settings.lmsdebug });
amtLms.on('error', function (e) {
//console.log('LME connection failed', e);
setupMeiOsAdmin(func, amtLms.connected == false ? 0 : 3);
});
amtLms.on('notify', function (data, options, str, code) {
if (code == 'iAMT0052-3') {
kvmGetData(true);
} else if (str != null) {
var notify = { date: Date.now(), str: str, code: code };
lmsNotifications.push(notify);
while (lmsNotifications.length > 100) { lmsNotifications.shift(); }
var notifyBuf = Buffer.concat([Buffer.from('0900', 'hex'), Buffer.from(JSON.stringify(notify))]) // Add a notification
for (var i in lmsControlSockets) { lmsControlSockets[i].write(notifyBuf); }
}
});
//console.log('LME Connecting...');
amtLms.on('connect', function () {
amtLms.connected = true;
//console.log("LME Connected.");
if (settings.noconsole !== true) {
amtLms.meshCommander = http.createServer();
amtLms.meshCommander.listen(16994);
amtLms.meshCommander.on('upgrade', function (req, socket, head) {
//console.log("WebSocket for " + req.url.split('?')[0]);
switch (req.url.split('?')[0]) {
case '/lms.ashx': // MeshCommander control channel (PTHI)
socket.ws = socket.upgradeWebSocket();
socket.ws.on('data', processLmsControlData);
socket.ws.on('end', function () { if (lmsControlSockets[this.id]) { delete lmsControlSockets[this.id]; /*console.log('removeControl', JSON.stringify(lmsControlSockets));*/ } });
var id = lmsControlSocketsNextId++;
lmsControlSockets[id] = socket.ws;
socket.ws.id = id;
//socket.ws.write(Buffer.concat([Buffer.from('0900', 'hex'), Buffer.from(JSON.stringify(lmsNotifications))])); // Send out full list of notifications
//console.log('addControl', JSON.stringify(lmsControlSockets));
break;
case '/webrelay.ashx': // MeshCommander data channel (LME)
socket.ws = socket.upgradeWebSocket();
amtLms.bindDuplexStream(socket.ws, 'IPv4', 16992);
break;
default:
socket.end();
break;
}
});
amtLms.meshCommander.on('request', function (req, rsp) {
//console.log("WebRequest for " + req.url.split('?')[0]);
switch (req.url.split('?')[0]) {
case '/': // Serve MeshCommander Web Application for LMS
var lmscommander = null;
try { lmscommander = fs.readFileSync('lmscommander.htm'); } catch (e) { }
if (lmscommander != null) {
rsp.writeHead(200, 'OK', { Server: 'JSLMS', 'Cache-Control': 'max-age=0, no-cache', 'X-Frame-Options': 'DENY', 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked' });
rsp.end(lmscommander);
} else {
rsp.writeHead(200, 'OK', { Server: 'JSLMS', 'Cache-Control': 'max-age=0, no-cache', 'X-Frame-Options': 'DENY', 'Content-Type': 'text/html', 'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', ETag: _IntelAmtWebApp_etag });
rsp.end(Buffer.from(_IntelAmtWebApp, 'base64'));
}
break;
default: // Unknown request
rsp.statusCode = 404;
rsp.statusMessage = "Not Found";
rsp.end();
break;
}
2018-03-20 03:31:54 +03:00
});
//console.log("LMS started, MeshCommander on HTTP/16994.");
tempTimer = setTimeout(function () { delete tempTimer; setupMeiOsAdmin(func, 2); }, 100);
//console.logReferenceCount(tempTimer);
} else {
//console.log("LMS started.");
tempTimer = setTimeout(function () { delete tempTimer; setupMeiOsAdmin(func, 1); }, 100);
//console.logReferenceCount(tempTimer);
}
2018-01-26 03:28:52 +03:00
});
}
2018-03-07 04:50:44 +03:00
function setupMeiOsAdmin(func, state) {
amtMei.getLocalSystemAccount(function (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); }
//var AllWsman = "CIM_SoftwareIdentity,IPS_SecIOService,IPS_ScreenSettingData,IPS_ProvisioningRecordLog,IPS_HostBasedSetupService,IPS_HostIPSettings,IPS_IPv6PortSettings".split(',');
//osamtstack.BatchEnum(null, AllWsman, startLmsWsmanResponse, null, true);
2018-03-09 04:58:22 +03:00
tempTimer = setInterval(function () { kvmGetData(true); }, 2000);
kvmGetData(false);
kvmSetData(JSON.stringify({ action: 'restart', ver: 1 }));
2018-03-07 04:50:44 +03:00
});
}
2018-03-09 04:58:22 +03:00
function kvmGetData(tag) {
osamtstack.IPS_KVMRedirectionSettingData_DataChannelRead(kvmDataGetResponse, tag);
}
function kvmDataGetResponse(stack, name, response, status, tag) {
if ((tag == true) && (status == 200) && (response.Body.ReturnValue == 0)) {
var val = null;
try { val = Buffer.from(response.Body.DataMessage, 'base64').toString(); } catch (e) { return }
if (val != null) kvmProcessData(response.Body.RealmsBitmap, response.Body.MessageId, val);
}
}
var webRtcDesktop = null;
function kvmProcessData(realms, messageId, val) {
//console.log('kvmProcessData', 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 })); }
if (data.action == 'offer') {
webRtcDesktop = {};
var rtc = require('ILibWebRTC');
webRtcDesktop.webrtc = rtc.createConnection();
webRtcDesktop.webrtc.on('connected', function () { });
webRtcDesktop.webrtc.on('disconnected', function () { webRtcCleanUp(); });
webRtcDesktop.webrtc.on('dataChannel', function (rtcchannel) {
webRtcDesktop.rtcchannel = rtcchannel;
var kvmmodule = require('meshDesktop');
webRtcDesktop.kvm = kvmmodule.getRemoteDesktopStream();
webRtcDesktop.kvm.pipe(webRtcDesktop.rtcchannel, { end: false });
webRtcDesktop.rtcchannel.pipe(webRtcDesktop.kvm, { end: false });
webRtcDesktop.rtcchannel.on('end', function () { webRtcCleanUp(); });
//webRtcDesktop.kvm.on('end', function () { console.log('WebRTC DataChannel closed2'); webRtcCleanUp(); });
//webRtcDesktop.rtcchannel.on('data', function (data) { console.log('WebRTC data: ' + data); });
});
kvmSetData(JSON.stringify({ action: 'answer', ver: 1, sdp: webRtcDesktop.webrtc.setOffer(data.sdp) }));
}
}
}
function 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;
}
function kvmSetData(x) {
osamtstack.IPS_KVMRedirectionSettingData_DataChannelWrite(Buffer.from(x).toString('base64'), function () { });
}
2018-02-08 05:45:14 +03:00
function startLmsWsmanResponse(stack, name, responses, status) {
if (status == 600) { console.log('ERROR: Unable to connect to Intel(R) AMT.'); }
else if (status != 200) { console.log('ERROR: Unable to get object from Intel(R) AMT, status = ' + status + '.'); }
2018-03-07 04:50:44 +03:00
else {
//console.log(JSON.stringify(responses), status);
var amtlogicalelements = responses["CIM_SoftwareIdentity"].responses;
if (amtlogicalelements.length > 0) {
var v = getInstance(amtlogicalelements, "AMT")["VersionString"];
amtversion = parseInt(v.split('.')[0]);
amtversionmin = parseInt(v.split('.')[1]);
//console.log(amtversion, amtversionmin);
}
}
2018-02-08 05:45:14 +03:00
}
2018-01-31 05:23:57 +03:00
// Process commands in the LMS control channel
// Command 9 is add a notification.
function processLmsControlData(data) {
if (data.length < 2) return;
var cmdid = data.readUInt16LE(0);
switch (cmdid) {
case 1: // Request basic Intel AMT information (CMD = 1)
2018-01-31 05:23:57 +03:00
{ getAmtInfo(function (meinfo, socket) { meinfo.LoginMode = 2; socket.write(Buffer.concat([Buffer.from('0100', 'hex'), Buffer.from(JSON.stringify(meinfo))])); }, this); break; }
case 2: // Intel AMT MEI Unprovision (CMD = 2)
2018-01-31 05:23:57 +03:00
{ if (data.length < 6) break; amtMei.unprovision(data.readUInt32LE(2), function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(2, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
case 3: // Intel AMT MEI GetLocalSystemAccount (CMD = 3)
2018-01-31 05:23:57 +03:00
{ amtMei.getLocalSystemAccount(function (account, socket) {socket.write(Buffer.concat([Buffer.from('030000000000', 'hex'), account.raw])); }, this); break; }
case 4: // Instruct Intel AMT to start remote configuration (CMD = 4)
2018-01-31 05:23:57 +03:00
{ amtMei.startConfiguration(function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
case 5: // Instruct Intel AMT to stop remote configuration (CMD = 5)
2018-01-31 05:23:57 +03:00
{ amtMei.stopConfiguration(function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
case 6: // Instruct Intel AMT connect CIRA (CMD = 6)
2018-01-31 05:23:57 +03:00
{ amtMei.openUserInitiatedConnection(function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
case 7: // Instruct Intel AMT disconnect CIRA (CMD = 7)
2018-01-31 05:23:57 +03:00
{ amtMei.closeUserInitiatedConnection(function (status, socket) { var data = new Buffer(6); data.writeUInt16LE(7, 0); data.writeUInt32LE(status, 2); socket.write(data); }, this); break; }
case 8: // Get Intel AMT CIRA State (CMD = 8)
2018-01-31 05:23:57 +03:00
{ amtMei.getRemoteAccessConnectionStatus(function (state, socket) { var data = new Buffer(6); data.writeUInt16LE(8, 0); data.writeUInt32LE(state.status, 2); socket.write(Buffer.concat([data, state.raw])); }, this); break; }
}
2017-11-01 02:19:58 +03:00
}
2018-01-31 05:23:57 +03:00
//
// MeshCentral TCP port router
//
2017-11-01 02:19:58 +03:00
function startRouter() {
tcpserver = net.createServer(OnTcpClientConnected);
2018-03-09 04:58:22 +03:00
tcpserver.on('error', function (e) { console.log('ERROR: ' + JSON.stringify(e)); exit(0); return; });
2017-11-01 02:19:58 +03:00
tcpserver.listen(settings.localPort, function () {
// We started listening.
if (settings.remoteName == null) {
console.log('Redirecting local port ' + settings.localPort + ' to remote port ' + settings.remotePort + '.');
} else {
console.log('Redirecting local port ' + settings.localPort + ' to ' + settings.remoteName + ':' + settings.remotePort + '.');
}
2018-03-20 03:31:54 +03:00
console.log('Press ctrl-c to exit.');
2017-11-01 02:19:58 +03:00
// If settings has a "cmd", run it now.
//process.exec("notepad.exe");
});
}
// Called when a TCP connect is received on the local port. Launch a tunnel.
function OnTcpClientConnected(c) {
try {
// 'connection' listener
debug(1, 'Client connected');
c.on('end', function () { disconnectTunnel(this, this.websocket, 'Client closed'); });
c.pause();
try {
options = http.parseUri(settings.serverUrl + '?user=' + settings.username + '&pass=' + settings.password + '&nodeid=' + settings.remoteNodeId + '&tcpport=' + settings.remotePort);
} catch (e) { console.log('Unable to parse \"serverUrl\".'); process.exit(1); return; }
2017-11-01 02:19:58 +03:00
options.checkServerIdentity = onVerifyServer;
2018-01-27 04:01:38 +03:00
options.rejectUnauthorized = false;
2017-11-01 02:19:58 +03:00
c.websocket = http.request(options);
c.websocket.tcp = c;
c.websocket.tunneling = false;
c.websocket.upgrade = OnWebSocket;
2018-01-27 04:01:38 +03:00
c.websocket.on('error', function (e) { console.log('ERROR: ' + JSON.stringify(e)); });
2017-11-01 02:19:58 +03:00
c.websocket.end();
} catch (e) { debug(2, e); }
}
// Disconnect both TCP & WebSocket connections and display a message.
function disconnectTunnel(tcp, ws, msg) {
if (ws != null) { try { ws.end(); } catch (e) { debug(2, e); } }
if (tcp != null) { try { tcp.end(); } catch (e) { debug(2, e); } }
debug(1, 'Tunnel disconnected: ' + msg);
}
// Called when the web socket gets connected
function OnWebSocket(msg, s, head) {
debug(1, 'Websocket connected');
s.on('data', function (msg) {
if (this.parent.tunneling == false) {
msg = msg.toString();
if (msg == 'c') {
this.parent.tunneling = true; this.pipe(this.parent.tcp); this.parent.tcp.pipe(this); debug(1, 'Tunnel active');
} else if ((msg.length > 6) && (msg.substring(0, 6) == 'error:')) {
console.log(msg.substring(6));
disconnectTunnel(this.tcp, this, msg.substring(6));
}
}
});
s.on('error', function (msg) { disconnectTunnel(this.tcp, this, 'Websocket error'); });
s.on('close', function (msg) { disconnectTunnel(this.tcp, this, 'Websocket closed'); });
s.parent = this;
}
// Try to discover the location of the mesh server
function discoverMeshServer() { console.log('Looking for server...'); discoveryInterval = setInterval(discoverMeshServerOnce, 5000); discoverMeshServerOnce(); }
// Try to discover the location of the mesh server only once
function discoverMeshServerOnce() {
var interfaces = os.networkInterfaces();
for (var adapter in interfaces) {
if (interfaces.hasOwnProperty(adapter)) {
for (var i = 0; i < interfaces[adapter].length; ++i) {
2017-11-01 02:19:58 +03:00
var addr = interfaces[adapter][i];
multicastSockets[i] = dgram.createSocket({ type: (addr.family == "IPv4" ? "udp4" : "udp6") });
multicastSockets[i].bind({ address: addr.address, exclusive: false });
if (addr.family == "IPv4") {
multicastSockets[i].addMembership(membershipIPv4);
//multicastSockets[i].setMulticastLoopback(true);
multicastSockets[i].once('message', OnMulticastMessage);
multicastSockets[i].send(settings.serverId, 16989, membershipIPv4);
}
}
}
}
}
// Called when a multicast packet is received
function OnMulticastMessage(msg, rinfo) {
var m = msg.toString().split('|');
if ((m.length == 3) && (m[0] == 'MeshCentral2') && (m[1] == settings.serverId)) {
settings.serverUrl = m[2].replace('%s', rinfo.address).replace('/agent.ashx', '/meshrelay.ashx');
console.log('Found server at ' + settings.serverUrl + '.');
if (discoveryInterval != null) { clearInterval(discoveryInterval); discoveryInterval = null; }
startRouter();
}
}
2018-01-31 05:23:57 +03:00
//
// PUSH MESHCOMMANDER INTO FIRMWARE
//
function nextStepStorageUpload() {
debug(3, "nextStepStorageUpload");
getAmtStorage(function (statusCode, data) {
if (statusCode == 200) {
debug(2, "getAmtStorage: " + JSON.stringify(data, null, 2));
if ((data['content'] != null) && (data['content']['index.htm'] != null)) { nextStepStorageUpload3('index.htm'); }
else if ((data['content'] != null) && (data['content']['logon.htm'] != null)) { nextStepStorageUpload3('logon.htm'); }
else if ((data['content'] != null) && (data['content']['logon.htm'] != null)) { nextStepStorageUpload3('logon.htm'); }
else { nextStepStorageUpload2('index.htm', null); }
} else {
console.log("Unable to read storage state.");
exit();
return;
}
});
}
function nextStepStorageUpload2(uploadName, linkName) {
debug(3, "nextStepStorageUpload2");
if (settings.webapp == null) { console.log("Done."); exit(); return; } else {
console.log("Uploading MeshCommander...");
pushToStorage(uploadName, linkName, Buffer.from(settings.webapp, 'base64'), function (statusCode) {
if (statusCode == 500) { console.log("Error, check that computer is powered on."); exit(); return; }
if (statusCode != 200) {
if (uploadName == 'index.htm') {
nextStepStorageUpload2('mesh/commander/console', 'MeshCommander');
} else {
console.log("Unable to upload MeshCommander, status = " + statusCode + "."); exit(); return;
}
} else {
console.log("Verifying MeshCommander...");
verifyStorage(uploadName, Buffer.from(settings.webapp, 'base64'), function (verified) {
if (verified == true) { console.log('Done.'); } else { console.log('MeshCommander verification failed.'); }
exit(); return;
});
}
});
}
}
function nextStepStorageUpload3(deleteName) {
console.log("Deleting " + deleteName + " from storage...");
deleteStorage(deleteName, function (statusCode) {
if (statusCode == 500) { console.log("Error, check that computer is powered on."); exit(); return; }
if (statusCode == 200) { nextStepStorageUpload(); } else { console.log("Unable to delete " + deleteName + "."); exit(); return; }
});
}
// Fetch the Intel AMT storage document
function getAmtStorage(func, noretry) {
var req = digest.request({ protocol: settings.protocol, method: "GET", host: settings.hostname, path: "/amt-storage/", port: settings.localport },
function (response) {
if (response.statusCode != 200) { console.log("Unable to connect to Intel(R) AMT."); func(response.statusCode, null); }
response.on('data', function (chunk) { if (response.acc == null) { response.acc = chunk; } else { response.acc += chunk; } });
response.on('end', function () {
var data = response.acc.toString(), len, data2, amtstorage = null;
try {
do { len = data.length; data2 = data; data = data2.replace('\x00', ''); } while (data != data2); // Remove all zero's, this is needed because firmware sometimes returns garbage we must fix.
do { len = data.length; data2 = data; data = data2.replace('\x22\x01\x22', '\x22\x22'); } while (data != data2); // "\x01", this is needed because firmware sometimes returns garbage we must fix.
amtstorage = JSON.parse(data);
} catch (e) { console.log("Error: Unable to parse Intel AMT response."); func(null); }
if (func != null) { func(response.statusCode, amtstorage); }
});
});
req.on('error', function (e) { console.log("Error occured: " + JSON.stringify(e)); if (noretry == true) { if (func != null) { func(null); } } else { getAmtStorage(func, true); } });
req.end();
}
// Fetch the Intel AMT storage document
function pushToStorage(name, linkname, data, func, ptr) {
if (ptr == null) { ptr = 0; }
2018-01-26 03:12:53 +03:00
var req = digest.request({ protocol: settings.protocol, method: "PUT", host: settings.hostname, path: ("/amt-storage/" + name + ((ptr != 0) ? '?append=' : '')), port: settings.localport } );
req.on('error', function (e) { console.log("Error occured: " + JSON.stringify(e)); if (func != null) { func(null); } });
2018-01-26 03:12:53 +03:00
req.on('response', function (response) {
debug(1, 'Chunk Done', data.length, ptr);
if ((response.statusCode == 200) && (ptr < data.length)) { pushToStorage(name, linkname, data, func, ptr); } else { if (func != null) { func(response.statusCode); } }
});
var header = (ptr > 0) ? '<metadata></metadata>' : '<metadata><headers><h>Content-Encoding:gzip</h><h>Content-Type:text/html</h></headers>' + ((linkname != null) ? ('<link>' + linkname + '</link>') : '') + '</metadata>';
var blocklen = ((data.length - ptr) > (7000 - header.length)) ? (7000 - header.length) : (data.length - ptr);
req.write(Buffer.concat([new Buffer(header), data.slice(ptr, ptr + blocklen)]));
ptr += blocklen;
req.end();
}
// Fetch the Intel AMT storage document
function verifyStorage(name, data, func) {
2018-01-26 03:12:53 +03:00
var req = digest.request({ protocol: settings.protocol, method: "GET", host: settings.hostname, path: ("/amt-storage/" + name), port: settings.localport });
req.on('error', function (e) { console.log("Verify error occured: " + JSON.stringify(e)); if (func != null) { func(null); } });
2018-01-26 03:12:53 +03:00
req.on('response', function (response) {
response.ptr = 0;
response.ok = true;
2018-01-27 04:01:38 +03:00
response.on('data', function (data2) { if (data2.toString('hex') != data.slice(response.ptr, response.ptr + data2.length).toString('hex')) { response.ok = false; console.log('Verifiy failed (' + response.ptr + ', ' + data2.length + ').'); } response.ptr += data2.length; });
2018-01-26 03:12:53 +03:00
response.on('end', function () { if (func != null) { func(response.ok); } });
});
req.end();
}
// Fetch the Intel AMT storage document
function deleteStorage(name, func, noretry) {
2018-01-26 03:12:53 +03:00
var req = digest.request({ protocol: settings.protocol, method: "DELETE", host: settings.hostname, path: "/amt-storage/" + name, port: settings.localport } );
req.on('error', function (e) { if ((e == 'Error: Socket was unexpectedly closed') && (noretry != true)) { deleteStorage(name, func, true); } else { if (func != null) { if (e.statusCode) { func(e.statusCode); } else { func(null); } } } });
2018-01-26 03:12:53 +03:00
req.on('response', function (response) { if (func != null) { func(response.statusCode); } });
req.end();
}
2018-03-20 03:31:54 +03:00
// Parse URL arguments
function parseUrlArguments(url) {
var r = {}, x = url.split('?');
if (x.length < 2) return r;
x = x[1].split('&');
for (var i in x) { var j = x[i].indexOf('='); if (j > 0) { r[x[i].substring(0, j).toLowerCase()] = x[i].substring(j + 1); } }
return r;
}
// Remove a element from a array
function removeItemFromArray(array, element) {
const index = array.indexOf(element);
if (index !== -1) { array.splice(index, 1); }
}
2018-01-31 05:23:57 +03:00
// Run MeshCmd
2018-01-26 03:28:52 +03:00
try { run(process.argv); } catch (e) { console.log('ERROR: ' + e); }