Added DNS multi-tenancy support

This commit is contained in:
Ylian Saint-Hilaire 2018-01-02 16:52:49 -08:00
parent 69268dcd4a
commit eb363f0cee
16 changed files with 2168 additions and 107 deletions

File diff suppressed because one or more lines are too long

View File

@ -469,8 +469,8 @@ function createMeshCore(agent) {
// If this is upload data, save it to file // If this is upload data, save it to file
if (this.httprequest.uploadFile) { if (this.httprequest.uploadFile) {
try { fs.writeSync(this.httprequest.uploadFile, data); } catch (e) { this.write(JSON.stringify({ action: 'uploaderror' })); return; } // Write to the file, if there is a problem, error out. try { fs.writeSync(this.httprequest.uploadFile, data); } catch (e) { this.write(new Buffer(JSON.stringify({ action: 'uploaderror' }))); return; } // Write to the file, if there is a problem, error out.
this.write(JSON.stringify({ action: 'uploadack', reqid: this.httprequest.uploadFileid })); // Ask for more data this.write(new Buffer(JSON.stringify({ action: 'uploadack', reqid: this.httprequest.uploadFileid }))); // Ask for more data
return; return;
} }
// If this is a download, send more of the file // If this is a download, send more of the file
@ -587,7 +587,7 @@ function createMeshCore(agent) {
try { cmd = JSON.parse(data); } catch (e) { }; try { cmd = JSON.parse(data); } catch (e) { };
if ((cmd == null) || (cmd.action == undefined)) { return; } if ((cmd == null) || (cmd.action == undefined)) { return; }
if ((cmd.path != null) && (process.platform != 'win32') && (cmd.path[0] != '/')) { cmd.path = '/' + cmd.path; } // Add '/' to paths on non-windows if ((cmd.path != null) && (process.platform != 'win32') && (cmd.path[0] != '/')) { cmd.path = '/' + cmd.path; } // Add '/' to paths on non-windows
console.log(objToString(cmd, 0, '.')); //console.log(objToString(cmd, 0, '.'));
switch (cmd.action) { switch (cmd.action) {
case 'ls': { case 'ls': {
/* /*
@ -603,7 +603,7 @@ function createMeshCore(agent) {
// Send the folder content to the browser // Send the folder content to the browser
var response = getDirectoryInfo(cmd.path); var response = getDirectoryInfo(cmd.path);
if (cmd.reqid != undefined) { response.reqid = cmd.reqid; } if (cmd.reqid != undefined) { response.reqid = cmd.reqid; }
this.write(JSON.stringify(response)); this.write(new Buffer(JSON.stringify(response)));
/* /*
// Start the directory watcher // Start the directory watcher
@ -642,10 +642,10 @@ function createMeshCore(agent) {
if (cmd.path == undefined) break; if (cmd.path == undefined) break;
var filepath = cmd.name ? obj.path.join(cmd.path, cmd.name) : cmd.path; var filepath = cmd.name ? obj.path.join(cmd.path, cmd.name) : cmd.path;
//console.log('Download: ' + filepath); //console.log('Download: ' + filepath);
try { this.httprequest.downloadFile = fs.openSync(filepath, 'rbN'); } catch (e) { this.write(JSON.stringify({ action: 'downloaderror', reqid: cmd.reqid })); break; } try { this.httprequest.downloadFile = fs.openSync(filepath, 'rbN'); } catch (e) { this.write(new Buffer(JSON.stringify({ action: 'downloaderror', reqid: cmd.reqid }))); break; }
this.httprequest.downloadFileId = cmd.reqid; this.httprequest.downloadFileId = cmd.reqid;
this.httprequest.downloadFilePtr = 0; this.httprequest.downloadFilePtr = 0;
if (this.httprequest.downloadFile) { this.write(JSON.stringify({ action: 'downloadstart', reqid: this.httprequest.downloadFileId })); } if (this.httprequest.downloadFile) { this.write(new Buffer(JSON.stringify({ action: 'downloadstart', reqid: this.httprequest.downloadFileId }))); }
break; break;
} }
case 'download2': { case 'download2': {
@ -662,9 +662,9 @@ function createMeshCore(agent) {
if (this.httprequest.uploadFile != undefined) { fs.closeSync(this.httprequest.uploadFile); this.httprequest.uploadFile = undefined; } if (this.httprequest.uploadFile != undefined) { fs.closeSync(this.httprequest.uploadFile); this.httprequest.uploadFile = undefined; }
if (cmd.path == undefined) break; if (cmd.path == undefined) break;
var filepath = cmd.name ? obj.path.join(cmd.path, cmd.name) : cmd.path; var filepath = cmd.name ? obj.path.join(cmd.path, cmd.name) : cmd.path;
try { this.httprequest.uploadFile = fs.openSync(filepath, 'wbN'); } catch (e) { this.write(JSON.stringify({ action: 'uploaderror', reqid: cmd.reqid })); break; } try { this.httprequest.uploadFile = fs.openSync(filepath, 'wbN'); } catch (e) { this.write(new Buffer(JSON.stringify({ action: 'uploaderror', reqid: cmd.reqid }))); break; }
this.httprequest.uploadFileid = cmd.reqid; this.httprequest.uploadFileid = cmd.reqid;
if (this.httprequest.uploadFile) { this.write(JSON.stringify({ action: 'uploadstart', reqid: this.httprequest.uploadFileid })); } if (this.httprequest.uploadFile) { this.write(new Buffer(JSON.stringify({ action: 'uploadstart', reqid: this.httprequest.uploadFileid }))); }
break; break;
} }
} }

View File

@ -0,0 +1,991 @@
/**
* @fileoverview Intel(r) AMT Communication StackXX
* @author Ylian Saint-Hilaire
* @version v0.2.0b
*/
/**
* Construct a AmtStackCreateService object, this ia the main Intel AMT communication stack.
* @constructor
*/
function AmtStackCreateService(wsmanStack) {
var obj = new Object();
obj.wsman = wsmanStack;
obj.pfx = ["http://intel.com/wbem/wscim/1/amt-schema/1/", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/", "http://intel.com/wbem/wscim/1/ips-schema/1/"];
obj.PendingEnums = [];
obj.PendingBatchOperations = 0;
obj.ActiveEnumsCount = 0;
obj.MaxActiveEnumsCount = 1; // Maximum number of enumerations that can be done at the same time.
obj.onProcessChanged = null;
var _MaxProcess = 0;
var _LastProcess = 0;
// Return the number of pending actions
obj.GetPendingActions = function () { return (obj.PendingEnums.length * 2) + (obj.ActiveEnumsCount) + obj.wsman.comm.PendingAjax.length + obj.wsman.comm.ActiveAjaxCount + obj.PendingBatchOperations; }
// Private Method, Update the current processing status, this gives the application an idea of what progress is being done by the WSMAN stack
function _up() {
var x = obj.GetPendingActions();
if (_MaxProcess < x) _MaxProcess = x;
if (obj.onProcessChanged != null && _LastProcess != x) {
//console.log("Process Old=" + _LastProcess + ", New=" + x + ", PEnums=" + obj.PendingEnums.length + ", AEnums=" + obj.ActiveEnumsCount + ", PAjax=" + obj.wsman.comm.PendingAjax.length + ", AAjax=" + obj.wsman.comm.ActiveAjaxCount + ", PBatch=" + obj.PendingBatchOperations);
_LastProcess = x;
obj.onProcessChanged(x, _MaxProcess);
}
if (x == 0) _MaxProcess = 0;
}
// Perform a WSMAN "SUBSCRIBE" operation.
obj.Subscribe = function (name, delivery, url, callback, tag, pri, selectors, opaque, user, pass) { obj.wsman.ExecSubscribe(obj.CompleteName(name), delivery, url, function (ws, resuri, response, xstatus) { _up(); callback(obj, name, response, xstatus, tag); }, 0, pri, selectors, opaque, user, pass); _up(); }
// Perform a WSMAN "UNSUBSCRIBE" operation.
obj.UnSubscribe = function (name, callback, tag, pri, selectors) { obj.wsman.ExecUnSubscribe(obj.CompleteName(name), function (ws, resuri, response, xstatus) { _up(); callback(obj, name, response, xstatus, tag); }, 0, pri, selectors); _up(); }
// Perform a WSMAN "GET" operation.
obj.Get = function (name, callback, tag, pri) { obj.wsman.ExecGet(obj.CompleteName(name), function (ws, resuri, response, xstatus) { _up(); callback(obj, name, response, xstatus, tag); }, 0, pri); _up(); }
// Perform a WSMAN "PUT" operation.
obj.Put = function (name, putobj, callback, tag, pri, selectors) { obj.wsman.ExecPut(obj.CompleteName(name), putobj, function (ws, resuri, response, xstatus) { _up(); callback(obj, name, response, xstatus, tag); }, 0, pri, selectors); _up(); }
// Perform a WSMAN "CREATE" operation.
obj.Create = function (name, putobj, callback, tag, pri) { obj.wsman.ExecCreate(obj.CompleteName(name), putobj, function (ws, resuri, response, xstatus) { _up(); callback(obj, name, response, xstatus, tag); }, 0, pri); _up(); }
// Perform a WSMAN "DELETE" operation.
obj.Delete = function (name, putobj, callback, tag, pri) { obj.wsman.ExecDelete(obj.CompleteName(name), putobj, function (ws, resuri, response, xstatus) { _up(); callback(obj, name, response, xstatus, tag); }, 0, pri); _up(); }
// Perform a WSMAN method call operation.
obj.Exec = function (name, method, args, callback, tag, pri, selectors) { obj.wsman.ExecMethod(obj.CompleteName(name), method, args, function (ws, resuri, response, xstatus) { _up(); callback(obj, name, obj.CompleteExecResponse(response), xstatus, tag); }, 0, pri, selectors); _up(); }
// Perform a WSMAN method call operation.
obj.ExecWithXml = function (name, method, args, callback, tag, pri, selectors) { obj.wsman.ExecMethodXml(obj.CompleteName(name), method, execArgumentsToXml(args), function (ws, resuri, response, xstatus) { _up(); callback(obj, name, obj.CompleteExecResponse(response), xstatus, tag); }, 0, pri, selectors); _up(); }
// Perform a WSMAN "ENUMERATE" operation.
obj.Enum = function (name, callback, tag, pri) {
if (obj.ActiveEnumsCount < obj.MaxActiveEnumsCount) {
obj.ActiveEnumsCount++; obj.wsman.ExecEnum(obj.CompleteName(name), function (ws, resuri, response, xstatus, tag0) { _up(); _EnumStartSink(name, response, callback, resuri, xstatus, tag0); }, tag, pri);
} else {
obj.PendingEnums.push([name, callback, tag, pri]);
}
_up();
}
// Private method
function _EnumStartSink(name, response, callback, resuri, status, tag, pri) {
if (status != 200) { callback(obj, name, null, status, tag); _EnumDoNext(1); return; }
if (response == null || response.Header["Method"] != "EnumerateResponse" || !response.Body["EnumerationContext"]) { callback(obj, name, null, 603, tag); _EnumDoNext(1); return; }
var enumctx = response.Body["EnumerationContext"];
obj.wsman.ExecPull(resuri, enumctx, function (ws, resuri, response, xstatus) { _EnumContinueSink(name, response, callback, resuri, [], xstatus, tag, pri); });
}
// Private method
function _EnumContinueSink(name, response, callback, resuri, items, status, tag, pri) {
if (status != 200) { callback(obj, name, null, status, tag); _EnumDoNext(1); return; }
if (response == null || response.Header["Method"] != "PullResponse") { callback(obj, name, null, 604, tag); _EnumDoNext(1); return; }
for (var i in response.Body["Items"]) {
if (response.Body["Items"][i] instanceof Array) {
for (var j in response.Body["Items"][i]) { items.push(response.Body["Items"][i][j]); }
} else {
items.push(response.Body["Items"][i]);
}
}
if (response.Body["EnumerationContext"]) {
var enumctx = response.Body["EnumerationContext"];
obj.wsman.ExecPull(resuri, enumctx, function (ws, resuri, response, xstatus) { _EnumContinueSink(name, response, callback, resuri, items, xstatus, tag, 1); });
} else {
_EnumDoNext(1);
callback(obj, name, items, status, tag);
_up();
}
}
// Private method
function _EnumDoNext(dec) {
obj.ActiveEnumsCount -= dec;
if (obj.ActiveEnumsCount >= obj.MaxActiveEnumsCount || obj.PendingEnums.length == 0) return;
var x = obj.PendingEnums.shift();
obj.Enum(x[0], x[1], x[2]);
_EnumDoNext(0);
}
// Perform a batch of WSMAN "ENUM" operations.
obj.BatchEnum = function (batchname, names, callback, tag, continueOnError, pri) {
obj.PendingBatchOperations += (names.length * 2);
_BatchNextEnum(batchname, Clone(names), callback, tag, {}, continueOnError, pri); _up();
}
function Clone(v) { return JSON.parse(JSON.stringify(v)); }
// Request each enum in the batch, stopping if something does not return status 200
function _BatchNextEnum(batchname, names, callback, tag, results, continueOnError, pri) {
obj.PendingBatchOperations -= 2;
var n = names.shift(), f = obj.Enum;
if (n[0] == '*') { f = obj.Get; n = n.substring(1); } // If the name starts with a star, do a GET instead of an ENUM. This will reduce round trips.
//console.log((f == obj.Get?'Get ':'Enum ') + n);
// Perform a GET/ENUM action
f(n, function (stack, name, responses, status, tag0) {
tag0[2][name] = { response: (responses==null?null:responses.Body), responses: responses, status: status };
if (tag0[1].length == 0 || status == 401 || (continueOnError != true && status != 200 && status != 400)) { obj.PendingBatchOperations -= (names.length * 2); _up(); callback(obj, batchname, tag0[2], status, tag); }
else { _up(); _BatchNextEnum(batchname, names, callback, tag, tag0[2], pri); }
}, [batchname, names, results], pri);
_up();
}
// Perform a batch of WSMAN "GET" operations.
obj.BatchGet = function (batchname, names, callback, tag, pri) {
_FetchNext({ name: batchname, names: names, callback: callback, current: 0, responses: {}, tag: tag, pri: pri }); _up();
}
// Private method
function _FetchNext(batch) {
if (batch.names.length <= batch.current) {
batch.callback(obj, batch.name, batch.responses, 200, batch.tag);
} else {
obj.wsman.ExecGet(obj.CompleteName(batch.names[batch.current]), function (ws, resuri, response, xstatus) { _Fetched(batch, response, xstatus); }, batch.pri);
batch.current++;
}
_up();
}
// Private method
function _Fetched(batch, response, status) {
if (response == null || status != 200) {
batch.callback(obj, batch.name, null, status, batch.tag);
} else {
batch.responses[response.Header["Method"]] = response;
_FetchNext(batch);
}
}
// Private method
obj.CompleteName = function(name) {
if (name.indexOf("AMT_") == 0) return obj.pfx[0] + name;
if (name.indexOf("CIM_") == 0) return obj.pfx[1] + name;
if (name.indexOf("IPS_") == 0) return obj.pfx[2] + name;
}
obj.CompleteExecResponse = function (resp) {
if (resp && resp != null && resp.Body && (resp.Body["ReturnValue"] != undefined)) { resp.Body.ReturnValueStr = obj.AmtStatusToStr(resp.Body["ReturnValue"]); }
return resp;
}
obj.RequestPowerStateChange = function (PowerState, callback_func) {
obj.CIM_PowerManagementService_RequestPowerStateChange(PowerState, "<Address xmlns=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">http://schemas.xmlsoap.org/ws/2004/08/addressing</Address><ReferenceParameters xmlns=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"><ResourceURI xmlns=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystem</ResourceURI><SelectorSet xmlns=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\"><Selector Name=\"CreationClassName\">CIM_ComputerSystem</Selector><Selector Name=\"Name\">ManagedSystem</Selector></SelectorSet></ReferenceParameters>", null, null, callback_func);
}
obj.SetBootConfigRole = function (Role, callback_func) {
obj.CIM_BootService_SetBootConfigRole("<Address xmlns=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">http://schemas.xmlsoap.org/ws/2004/08/addressing</Address><ReferenceParameters xmlns=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"><ResourceURI xmlns=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting</ResourceURI><SelectorSet xmlns=\"http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd\"><Selector Name=\"InstanceID\">Intel(r) AMT: Boot Configuration 0</Selector></SelectorSet></ReferenceParameters>", Role, callback_func);
}
// Cancel all pending queries with given status
obj.CancelAllQueries = function (s) {
obj.wsman.CancelAllQueries(s);
}
// Auto generated methods
obj.AMT_AgentPresenceWatchdog_RegisterAgent = function (callback_func) { obj.Exec("AMT_AgentPresenceWatchdog", "RegisterAgent", {}, callback_func); }
obj.AMT_AgentPresenceWatchdog_AssertPresence = function (SequenceNumber, callback_func) { obj.Exec("AMT_AgentPresenceWatchdog", "AssertPresence", { "SequenceNumber": SequenceNumber }, callback_func); }
obj.AMT_AgentPresenceWatchdog_AssertShutdown = function (SequenceNumber, callback_func) { obj.Exec("AMT_AgentPresenceWatchdog", "AssertShutdown", { "SequenceNumber": SequenceNumber }, callback_func); }
obj.AMT_AgentPresenceWatchdog_AddAction = function (OldState, NewState, EventOnTransition, ActionSd, ActionEac, callback_func, tag, pri, selectors) { obj.Exec("AMT_AgentPresenceWatchdog", "AddAction", { "OldState": OldState, "NewState": NewState, "EventOnTransition": EventOnTransition, "ActionSd": ActionSd, "ActionEac": ActionEac }, callback_func, tag, pri, selectors); }
obj.AMT_AgentPresenceWatchdog_DeleteAllActions = function (callback_func, tag, pri, selectors) { obj.Exec("AMT_AgentPresenceWatchdog", "DeleteAllActions", {}, callback_func, tag, pri, selectors); }
obj.AMT_AgentPresenceWatchdogAction_GetActionEac = function (callback_func) { obj.Exec("AMT_AgentPresenceWatchdogAction", "GetActionEac", {}, callback_func); }
obj.AMT_AgentPresenceWatchdogVA_RegisterAgent = function (callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "RegisterAgent", {}, callback_func); }
obj.AMT_AgentPresenceWatchdogVA_AssertPresence = function (SequenceNumber, callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "AssertPresence", { "SequenceNumber": SequenceNumber }, callback_func); }
obj.AMT_AgentPresenceWatchdogVA_AssertShutdown = function (SequenceNumber, callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "AssertShutdown", { "SequenceNumber": SequenceNumber }, callback_func); }
obj.AMT_AgentPresenceWatchdogVA_AddAction = function (OldState, NewState, EventOnTransition, ActionSd, ActionEac, callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "AddAction", { "OldState": OldState, "NewState": NewState, "EventOnTransition": EventOnTransition, "ActionSd": ActionSd, "ActionEac": ActionEac }, callback_func); }
obj.AMT_AgentPresenceWatchdogVA_DeleteAllActions = function (_method_dummy, callback_func) { obj.Exec("AMT_AgentPresenceWatchdogVA", "DeleteAllActions", { "_method_dummy": _method_dummy }, callback_func); }
obj.AMT_AuditLog_ClearLog = function (callback_func) { obj.Exec("AMT_AuditLog", "ClearLog", {}, callback_func); }
obj.AMT_AuditLog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_AuditLog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.AMT_AuditLog_ReadRecords = function (StartIndex, callback_func, tag) { obj.Exec("AMT_AuditLog", "ReadRecords", { "StartIndex": StartIndex }, callback_func, tag); }
obj.AMT_AuditLog_SetAuditLock = function (LockTimeoutInSeconds, Flag, Handle, callback_func) { obj.Exec("AMT_AuditLog", "SetAuditLock", { "LockTimeoutInSeconds": LockTimeoutInSeconds, "Flag": Flag, "Handle": Handle }, callback_func); }
obj.AMT_AuditLog_ExportAuditLogSignature = function (SigningMechanism, callback_func) { obj.Exec("AMT_AuditLog", "ExportAuditLogSignature", { "SigningMechanism": SigningMechanism }, callback_func); }
obj.AMT_AuditLog_SetSigningKeyMaterial = function (SigningMechanismType, SigningKey, LengthOfCertificates, Certificates, callback_func) { obj.Exec("AMT_AuditLog", "SetSigningKeyMaterial", { "SigningMechanismType": SigningMechanismType, "SigningKey": SigningKey, "LengthOfCertificates": LengthOfCertificates, "Certificates": Certificates }, callback_func); }
obj.AMT_AuditPolicyRule_SetAuditPolicy = function (Enable, AuditedAppID, EventID, PolicyType, callback_func) { obj.Exec("AMT_AuditPolicyRule", "SetAuditPolicy", { "Enable": Enable, "AuditedAppID": AuditedAppID, "EventID": EventID, "PolicyType": PolicyType }, callback_func); }
obj.AMT_AuditPolicyRule_SetAuditPolicyBulk = function (Enable, AuditedAppID, EventID, PolicyType, callback_func) { obj.Exec("AMT_AuditPolicyRule", "SetAuditPolicyBulk", { "Enable": Enable, "AuditedAppID": AuditedAppID, "EventID": EventID, "PolicyType": PolicyType }, callback_func); }
obj.AMT_AuthorizationService_AddUserAclEntryEx = function (DigestUsername, DigestPassword, KerberosUserSid, AccessPermission, Realms, callback_func) { obj.Exec("AMT_AuthorizationService", "AddUserAclEntryEx", { "DigestUsername": DigestUsername, "DigestPassword": DigestPassword, "KerberosUserSid": KerberosUserSid, "AccessPermission": AccessPermission, "Realms": Realms }, callback_func); }
obj.AMT_AuthorizationService_EnumerateUserAclEntries = function (StartIndex, callback_func) { obj.Exec("AMT_AuthorizationService", "EnumerateUserAclEntries", { "StartIndex": StartIndex }, callback_func); }
obj.AMT_AuthorizationService_GetUserAclEntryEx = function (Handle, callback_func, tag) { obj.Exec("AMT_AuthorizationService", "GetUserAclEntryEx", { "Handle": Handle }, callback_func, tag); }
obj.AMT_AuthorizationService_UpdateUserAclEntryEx = function (Handle, DigestUsername, DigestPassword, KerberosUserSid, AccessPermission, Realms, callback_func) { obj.Exec("AMT_AuthorizationService", "UpdateUserAclEntryEx", { "Handle": Handle, "DigestUsername": DigestUsername, "DigestPassword": DigestPassword, "KerberosUserSid": KerberosUserSid, "AccessPermission": AccessPermission, "Realms": Realms }, callback_func); }
obj.AMT_AuthorizationService_RemoveUserAclEntry = function (Handle, callback_func) { obj.Exec("AMT_AuthorizationService", "RemoveUserAclEntry", { "Handle": Handle }, callback_func); }
obj.AMT_AuthorizationService_SetAdminAclEntryEx = function (Username, DigestPassword, callback_func) { obj.Exec("AMT_AuthorizationService", "SetAdminAclEntryEx", { "Username": Username, "DigestPassword": DigestPassword }, callback_func); }
obj.AMT_AuthorizationService_GetAdminAclEntry = function (callback_func) { obj.Exec("AMT_AuthorizationService", "GetAdminAclEntry", {}, callback_func); }
obj.AMT_AuthorizationService_GetAdminAclEntryStatus = function (callback_func) { obj.Exec("AMT_AuthorizationService", "GetAdminAclEntryStatus", {}, callback_func); }
obj.AMT_AuthorizationService_GetAdminNetAclEntryStatus = function (callback_func) { obj.Exec("AMT_AuthorizationService", "GetAdminNetAclEntryStatus", {}, callback_func); }
obj.AMT_AuthorizationService_SetAclEnabledState = function (Handle, Enabled, callback_func, tag) { obj.Exec("AMT_AuthorizationService", "SetAclEnabledState", { "Handle": Handle, "Enabled": Enabled }, callback_func, tag); }
obj.AMT_AuthorizationService_GetAclEnabledState = function (Handle, callback_func, tag) { obj.Exec("AMT_AuthorizationService", "GetAclEnabledState", { "Handle": Handle }, callback_func, tag); }
obj.AMT_EndpointAccessControlService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.AMT_EndpointAccessControlService_GetPosture = function (PostureType, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "GetPosture", { "PostureType": PostureType }, callback_func); }
obj.AMT_EndpointAccessControlService_GetPostureHash = function (PostureType, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "GetPostureHash", { "PostureType": PostureType }, callback_func); }
obj.AMT_EndpointAccessControlService_UpdatePostureState = function (UpdateType, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "UpdatePostureState", { "UpdateType": UpdateType }, callback_func); }
obj.AMT_EndpointAccessControlService_GetEacOptions = function (callback_func) { obj.Exec("AMT_EndpointAccessControlService", "GetEacOptions", {}, callback_func); }
obj.AMT_EndpointAccessControlService_SetEacOptions = function (EacVendors, PostureHashAlgorithm, callback_func) { obj.Exec("AMT_EndpointAccessControlService", "SetEacOptions", { "EacVendors": EacVendors, "PostureHashAlgorithm": PostureHashAlgorithm }, callback_func); }
obj.AMT_EnvironmentDetectionSettingData_SetSystemDefensePolicy = function (Policy, callback_func) { obj.Exec("AMT_EnvironmentDetectionSettingData", "SetSystemDefensePolicy", { "Policy": Policy }, callback_func); }
obj.AMT_EnvironmentDetectionSettingData_EnableVpnRouting = function (Enable, callback_func) { obj.Exec("AMT_EnvironmentDetectionSettingData", "EnableVpnRouting", { "Enable": Enable }, callback_func); }
obj.AMT_EthernetPortSettings_SetLinkPreference = function (LinkPreference, Timeout, callback_func) { obj.Exec("AMT_EthernetPortSettings", "SetLinkPreference", { "LinkPreference": LinkPreference, "Timeout": Timeout }, callback_func); }
obj.AMT_HeuristicPacketFilterStatistics_ResetSelectedStats = function (SelectedStatistics, callback_func) { obj.Exec("AMT_HeuristicPacketFilterStatistics", "ResetSelectedStats", { "SelectedStatistics": SelectedStatistics }, callback_func); }
obj.AMT_KerberosSettingData_GetCredentialCacheState = function (callback_func) { obj.Exec("AMT_KerberosSettingData", "GetCredentialCacheState", {}, callback_func); }
obj.AMT_KerberosSettingData_SetCredentialCacheState = function (Enable, callback_func) { obj.Exec("AMT_KerberosSettingData", "SetCredentialCacheState", { "Enable": Enable }, callback_func); }
obj.AMT_MessageLog_CancelIteration = function (IterationIdentifier, callback_func) { obj.Exec("AMT_MessageLog", "CancelIteration", { "IterationIdentifier": IterationIdentifier }, callback_func); }
obj.AMT_MessageLog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_MessageLog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.AMT_MessageLog_ClearLog = function (callback_func) { obj.Exec("AMT_MessageLog", "ClearLog", { }, callback_func); }
obj.AMT_MessageLog_GetRecords = function (IterationIdentifier, MaxReadRecords, callback_func, tag) { obj.Exec("AMT_MessageLog", "GetRecords", { "IterationIdentifier": IterationIdentifier, "MaxReadRecords": MaxReadRecords }, callback_func, tag); }
obj.AMT_MessageLog_GetRecord = function (IterationIdentifier, PositionToNext, callback_func) { obj.Exec("AMT_MessageLog", "GetRecord", { "IterationIdentifier": IterationIdentifier, "PositionToNext": PositionToNext }, callback_func); }
obj.AMT_MessageLog_PositionAtRecord = function (IterationIdentifier, MoveAbsolute, RecordNumber, callback_func) { obj.Exec("AMT_MessageLog", "PositionAtRecord", { "IterationIdentifier": IterationIdentifier, "MoveAbsolute": MoveAbsolute, "RecordNumber": RecordNumber }, callback_func); }
obj.AMT_MessageLog_PositionToFirstRecord = function (callback_func, tag) { obj.Exec("AMT_MessageLog", "PositionToFirstRecord", {}, callback_func, tag); }
obj.AMT_MessageLog_FreezeLog = function (Freeze, callback_func) { obj.Exec("AMT_MessageLog", "FreezeLog", { "Freeze": Freeze }, callback_func); }
obj.AMT_PublicKeyManagementService_AddCRL = function (Url, SerialNumbers, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddCRL", { "Url": Url, "SerialNumbers": SerialNumbers }, callback_func); }
obj.AMT_PublicKeyManagementService_ResetCRLList = function (_method_dummy, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "ResetCRLList", { "_method_dummy": _method_dummy }, callback_func); }
obj.AMT_PublicKeyManagementService_AddCertificate = function (CertificateBlob, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddCertificate", { "CertificateBlob": CertificateBlob }, callback_func); }
obj.AMT_PublicKeyManagementService_AddTrustedRootCertificate = function (CertificateBlob, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddTrustedRootCertificate", { "CertificateBlob": CertificateBlob }, callback_func); }
obj.AMT_PublicKeyManagementService_AddKey = function (KeyBlob, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "AddKey", { "KeyBlob": KeyBlob }, callback_func); }
obj.AMT_PublicKeyManagementService_GeneratePKCS10Request = function (KeyPair, DNName, Usage, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "GeneratePKCS10Request", { "KeyPair": KeyPair, "DNName": DNName, "Usage": Usage }, callback_func); }
obj.AMT_PublicKeyManagementService_GeneratePKCS10RequestEx = function (KeyPair, SigningAlgorithm, NullSignedCertificateRequest, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "GeneratePKCS10RequestEx", { "KeyPair": KeyPair, "SigningAlgorithm": SigningAlgorithm, "NullSignedCertificateRequest": NullSignedCertificateRequest }, callback_func); }
obj.AMT_PublicKeyManagementService_GenerateKeyPair = function (KeyAlgorithm, KeyLength, callback_func) { obj.Exec("AMT_PublicKeyManagementService", "GenerateKeyPair", { "KeyAlgorithm": KeyAlgorithm, "KeyLength": KeyLength }, callback_func); }
obj.AMT_RedirectionService_RequestStateChange = function (RequestedState, callback_func) { obj.Exec("AMT_RedirectionService", "RequestStateChange", { "RequestedState": RequestedState }, callback_func); }
obj.AMT_RedirectionService_TerminateSession = function (SessionType, callback_func) { obj.Exec("AMT_RedirectionService", "TerminateSession", { "SessionType": SessionType }, callback_func); }
obj.AMT_RemoteAccessService_AddMpServer = function (AccessInfo, InfoFormat, Port, AuthMethod, Certificate, Username, Password, CN, callback_func) { obj.Exec("AMT_RemoteAccessService", "AddMpServer", { "AccessInfo": AccessInfo, "InfoFormat": InfoFormat, "Port": Port, "AuthMethod": AuthMethod, "Certificate": Certificate, "Username": Username, "Password": Password, "CN": CN }, callback_func); }
obj.AMT_RemoteAccessService_AddRemoteAccessPolicyRule = function (Trigger, TunnelLifeTime, ExtendedData, MpServer, callback_func) { obj.Exec("AMT_RemoteAccessService", "AddRemoteAccessPolicyRule", { "Trigger": Trigger, "TunnelLifeTime": TunnelLifeTime, "ExtendedData": ExtendedData, "MpServer": MpServer }, callback_func); }
obj.AMT_RemoteAccessService_CloseRemoteAccessConnection = function (_method_dummy, callback_func) { obj.Exec("AMT_RemoteAccessService", "CloseRemoteAccessConnection", { "_method_dummy": _method_dummy }, callback_func); }
obj.AMT_SetupAndConfigurationService_CommitChanges = function (_method_dummy, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "CommitChanges", { "_method_dummy": _method_dummy }, callback_func); }
obj.AMT_SetupAndConfigurationService_Unprovision = function (ProvisioningMode, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "Unprovision", { "ProvisioningMode": ProvisioningMode }, callback_func); }
obj.AMT_SetupAndConfigurationService_PartialUnprovision = function (_method_dummy, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "PartialUnprovision", { "_method_dummy": _method_dummy }, callback_func); }
obj.AMT_SetupAndConfigurationService_ResetFlashWearOutProtection = function (_method_dummy, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "ResetFlashWearOutProtection", { "_method_dummy": _method_dummy }, callback_func); }
obj.AMT_SetupAndConfigurationService_ExtendProvisioningPeriod = function (Duration, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "ExtendProvisioningPeriod", { "Duration": Duration }, callback_func); }
obj.AMT_SetupAndConfigurationService_SetMEBxPassword = function (Password, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "SetMEBxPassword", { "Password": Password }, callback_func); }
obj.AMT_SetupAndConfigurationService_SetTLSPSK = function (PID, PPS, callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "SetTLSPSK", { "PID": PID, "PPS": PPS }, callback_func); }
obj.AMT_SetupAndConfigurationService_GetProvisioningAuditRecord = function (callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "GetProvisioningAuditRecord", {}, callback_func); }
obj.AMT_SetupAndConfigurationService_GetUuid = function (callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "GetUuid", {}, callback_func); }
obj.AMT_SetupAndConfigurationService_GetUnprovisionBlockingComponents = function (callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "GetUnprovisionBlockingComponents", {}, callback_func); }
obj.AMT_SetupAndConfigurationService_GetProvisioningAuditRecordV2 = function (callback_func) { obj.Exec("AMT_SetupAndConfigurationService", "GetProvisioningAuditRecordV2", {}, callback_func); }
obj.AMT_SystemDefensePolicy_GetTimeout = function (callback_func) { obj.Exec("AMT_SystemDefensePolicy", "GetTimeout", {}, callback_func); }
obj.AMT_SystemDefensePolicy_SetTimeout = function (Timeout, callback_func) { obj.Exec("AMT_SystemDefensePolicy", "SetTimeout", { "Timeout": Timeout }, callback_func); }
obj.AMT_SystemDefensePolicy_UpdateStatistics = function (NetworkInterface, ResetOnRead, callback_func, tag, pri, selectors) { obj.Exec("AMT_SystemDefensePolicy", "UpdateStatistics", { "NetworkInterface": NetworkInterface, "ResetOnRead": ResetOnRead }, callback_func, tag, pri, selectors); }
obj.AMT_SystemPowerScheme_SetPowerScheme = function (callback_func, schemeInstanceId, tag) { obj.Exec("AMT_SystemPowerScheme", "SetPowerScheme", {}, callback_func, tag, 0, { "InstanceID": schemeInstanceId }); }
obj.AMT_TimeSynchronizationService_GetLowAccuracyTimeSynch = function (callback_func, tag) { obj.Exec("AMT_TimeSynchronizationService", "GetLowAccuracyTimeSynch", {}, callback_func, tag); }
obj.AMT_TimeSynchronizationService_SetHighAccuracyTimeSynch = function (Ta0, Tm1, Tm2, callback_func, tag) { obj.Exec("AMT_TimeSynchronizationService", "SetHighAccuracyTimeSynch", { "Ta0": Ta0, "Tm1": Tm1, "Tm2": Tm2 }, callback_func, tag); }
obj.AMT_UserInitiatedConnectionService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_UserInitiatedConnectionService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.AMT_WebUIService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("AMT_WebUIService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.AMT_WiFiPortConfigurationService_AddWiFiSettings = function (WiFiEndpoint, WiFiEndpointSettingsInput, IEEE8021xSettingsInput, ClientCredential, CACredential, callback_func) { obj.ExecWithXml("AMT_WiFiPortConfigurationService", "AddWiFiSettings", { "WiFiEndpoint": WiFiEndpoint, "WiFiEndpointSettingsInput": WiFiEndpointSettingsInput, "IEEE8021xSettingsInput": IEEE8021xSettingsInput, "ClientCredential": ClientCredential, "CACredential": CACredential }, callback_func); }
obj.AMT_WiFiPortConfigurationService_UpdateWiFiSettings = function (WiFiEndpointSettings, WiFiEndpointSettingsInput, IEEE8021xSettingsInput, ClientCredential, CACredential, callback_func) { obj.ExecWithXml("AMT_WiFiPortConfigurationService", "UpdateWiFiSettings", { "WiFiEndpointSettings": WiFiEndpointSettings, "WiFiEndpointSettingsInput": WiFiEndpointSettingsInput, "IEEE8021xSettingsInput": IEEE8021xSettingsInput, "ClientCredential": ClientCredential, "CACredential": CACredential }, callback_func); }
obj.AMT_WiFiPortConfigurationService_DeleteAllITProfiles = function (_method_dummy, callback_func) { obj.Exec("AMT_WiFiPortConfigurationService", "DeleteAllITProfiles", { "_method_dummy": _method_dummy }, callback_func); }
obj.AMT_WiFiPortConfigurationService_DeleteAllUserProfiles = function (_method_dummy, callback_func) { obj.Exec("AMT_WiFiPortConfigurationService", "DeleteAllUserProfiles", { "_method_dummy": _method_dummy }, callback_func); }
obj.CIM_Account_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_Account", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.CIM_AccountManagementService_CreateAccount = function (System, AccountTemplate, callback_func) { obj.Exec("CIM_AccountManagementService", "CreateAccount", { "System": System, "AccountTemplate": AccountTemplate }, callback_func); }
obj.CIM_BootConfigSetting_ChangeBootOrder = function (Source, callback_func) { obj.Exec("CIM_BootConfigSetting", "ChangeBootOrder", { "Source": Source }, callback_func); }
obj.CIM_BootService_SetBootConfigRole = function (BootConfigSetting, Role, callback_func) { obj.Exec("CIM_BootService", "SetBootConfigRole", { "BootConfigSetting": BootConfigSetting, "Role": Role }, callback_func, 0, 1); }
obj.CIM_Card_ConnectorPower = function (Connector, PoweredOn, callback_func) { obj.Exec("CIM_Card", "ConnectorPower", { "Connector": Connector, "PoweredOn": PoweredOn }, callback_func); }
obj.CIM_Card_IsCompatible = function (ElementToCheck, callback_func) { obj.Exec("CIM_Card", "IsCompatible", { "ElementToCheck": ElementToCheck }, callback_func); }
obj.CIM_Chassis_IsCompatible = function (ElementToCheck, callback_func) { obj.Exec("CIM_Chassis", "IsCompatible", { "ElementToCheck": ElementToCheck }, callback_func); }
obj.CIM_Fan_SetSpeed = function (DesiredSpeed, callback_func) { obj.Exec("CIM_Fan", "SetSpeed", { "DesiredSpeed": DesiredSpeed }, callback_func); }
obj.CIM_KVMRedirectionSAP_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_KVMRedirectionSAP", "RequestStateChange", { "RequestedState": RequestedState/*, "TimeoutPeriod": TimeoutPeriod */}, callback_func); }
obj.CIM_MediaAccessDevice_LockMedia = function (Lock, callback_func) { obj.Exec("CIM_MediaAccessDevice", "LockMedia", { "Lock": Lock }, callback_func); }
obj.CIM_MediaAccessDevice_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_MediaAccessDevice", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
obj.CIM_MediaAccessDevice_Reset = function (callback_func) { obj.Exec("CIM_MediaAccessDevice", "Reset", {}, callback_func); }
obj.CIM_MediaAccessDevice_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_MediaAccessDevice", "EnableDevice", { "Enabled": Enabled }, callback_func); }
obj.CIM_MediaAccessDevice_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_MediaAccessDevice", "OnlineDevice", { "Online": Online }, callback_func); }
obj.CIM_MediaAccessDevice_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_MediaAccessDevice", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
obj.CIM_MediaAccessDevice_SaveProperties = function (callback_func) { obj.Exec("CIM_MediaAccessDevice", "SaveProperties", {}, callback_func); }
obj.CIM_MediaAccessDevice_RestoreProperties = function (callback_func) { obj.Exec("CIM_MediaAccessDevice", "RestoreProperties", {}, callback_func); }
obj.CIM_MediaAccessDevice_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_MediaAccessDevice", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.CIM_PhysicalFrame_IsCompatible = function (ElementToCheck, callback_func) { obj.Exec("CIM_PhysicalFrame", "IsCompatible", { "ElementToCheck": ElementToCheck }, callback_func); }
obj.CIM_PhysicalPackage_IsCompatible = function (ElementToCheck, callback_func) { obj.Exec("CIM_PhysicalPackage", "IsCompatible", { "ElementToCheck": ElementToCheck }, callback_func); }
obj.CIM_PowerManagementService_RequestPowerStateChange = function (PowerState, ManagedElement, Time, TimeoutPeriod, callback_func) { obj.Exec("CIM_PowerManagementService", "RequestPowerStateChange", { "PowerState": PowerState, "ManagedElement": ManagedElement, "Time": Time, "TimeoutPeriod": TimeoutPeriod }, callback_func, 0, 1); }
obj.CIM_PowerSupply_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_PowerSupply", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
obj.CIM_PowerSupply_Reset = function (callback_func) { obj.Exec("CIM_PowerSupply", "Reset", {}, callback_func); }
obj.CIM_PowerSupply_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_PowerSupply", "EnableDevice", { "Enabled": Enabled }, callback_func); }
obj.CIM_PowerSupply_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_PowerSupply", "OnlineDevice", { "Online": Online }, callback_func); }
obj.CIM_PowerSupply_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_PowerSupply", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
obj.CIM_PowerSupply_SaveProperties = function (callback_func) { obj.Exec("CIM_PowerSupply", "SaveProperties", {}, callback_func); }
obj.CIM_PowerSupply_RestoreProperties = function (callback_func) { obj.Exec("CIM_PowerSupply", "RestoreProperties", {}, callback_func); }
obj.CIM_PowerSupply_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_PowerSupply", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.CIM_Processor_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_Processor", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
obj.CIM_Processor_Reset = function (callback_func) { obj.Exec("CIM_Processor", "Reset", {}, callback_func); }
obj.CIM_Processor_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_Processor", "EnableDevice", { "Enabled": Enabled }, callback_func); }
obj.CIM_Processor_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_Processor", "OnlineDevice", { "Online": Online }, callback_func); }
obj.CIM_Processor_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_Processor", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
obj.CIM_Processor_SaveProperties = function (callback_func) { obj.Exec("CIM_Processor", "SaveProperties", {}, callback_func); }
obj.CIM_Processor_RestoreProperties = function (callback_func) { obj.Exec("CIM_Processor", "RestoreProperties", {}, callback_func); }
obj.CIM_Processor_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_Processor", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.CIM_RecordLog_ClearLog = function (callback_func) { obj.Exec("CIM_RecordLog", "ClearLog", {}, callback_func); }
obj.CIM_RecordLog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_RecordLog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.CIM_RedirectionService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_RedirectionService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.CIM_Sensor_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_Sensor", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
obj.CIM_Sensor_Reset = function (callback_func) { obj.Exec("CIM_Sensor", "Reset", {}, callback_func); }
obj.CIM_Sensor_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_Sensor", "EnableDevice", { "Enabled": Enabled }, callback_func); }
obj.CIM_Sensor_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_Sensor", "OnlineDevice", { "Online": Online }, callback_func); }
obj.CIM_Sensor_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_Sensor", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
obj.CIM_Sensor_SaveProperties = function (callback_func) { obj.Exec("CIM_Sensor", "SaveProperties", {}, callback_func); }
obj.CIM_Sensor_RestoreProperties = function (callback_func) { obj.Exec("CIM_Sensor", "RestoreProperties", {}, callback_func); }
obj.CIM_Sensor_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_Sensor", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.CIM_StatisticalData_ResetSelectedStats = function (SelectedStatistics, callback_func) { obj.Exec("CIM_StatisticalData", "ResetSelectedStats", { "SelectedStatistics": SelectedStatistics }, callback_func); }
obj.CIM_Watchdog_KeepAlive = function (callback_func) { obj.Exec("CIM_Watchdog", "KeepAlive", {}, callback_func); }
obj.CIM_Watchdog_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_Watchdog", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
obj.CIM_Watchdog_Reset = function (callback_func) { obj.Exec("CIM_Watchdog", "Reset", {}, callback_func); }
obj.CIM_Watchdog_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_Watchdog", "EnableDevice", { "Enabled": Enabled }, callback_func); }
obj.CIM_Watchdog_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_Watchdog", "OnlineDevice", { "Online": Online }, callback_func); }
obj.CIM_Watchdog_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_Watchdog", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
obj.CIM_Watchdog_SaveProperties = function (callback_func) { obj.Exec("CIM_Watchdog", "SaveProperties", {}, callback_func); }
obj.CIM_Watchdog_RestoreProperties = function (callback_func) { obj.Exec("CIM_Watchdog", "RestoreProperties", {}, callback_func); }
obj.CIM_Watchdog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_Watchdog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.CIM_WiFiPort_SetPowerState = function (PowerState, Time, callback_func) { obj.Exec("CIM_WiFiPort", "SetPowerState", { "PowerState": PowerState, "Time": Time }, callback_func); }
obj.CIM_WiFiPort_Reset = function (callback_func) { obj.Exec("CIM_WiFiPort", "Reset", {}, callback_func); }
obj.CIM_WiFiPort_EnableDevice = function (Enabled, callback_func) { obj.Exec("CIM_WiFiPort", "EnableDevice", { "Enabled": Enabled }, callback_func); }
obj.CIM_WiFiPort_OnlineDevice = function (Online, callback_func) { obj.Exec("CIM_WiFiPort", "OnlineDevice", { "Online": Online }, callback_func); }
obj.CIM_WiFiPort_QuiesceDevice = function (Quiesce, callback_func) { obj.Exec("CIM_WiFiPort", "QuiesceDevice", { "Quiesce": Quiesce }, callback_func); }
obj.CIM_WiFiPort_SaveProperties = function (callback_func) { obj.Exec("CIM_WiFiPort", "SaveProperties", {}, callback_func); }
obj.CIM_WiFiPort_RestoreProperties = function (callback_func) { obj.Exec("CIM_WiFiPort", "RestoreProperties", {}, callback_func); }
obj.CIM_WiFiPort_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("CIM_WiFiPort", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.IPS_HostBasedSetupService_Setup = function (NetAdminPassEncryptionType, NetworkAdminPassword, McNonce, Certificate, SigningAlgorithm, DigitalSignature, callback_func) { obj.Exec("IPS_HostBasedSetupService", "Setup", { "NetAdminPassEncryptionType": NetAdminPassEncryptionType, "NetworkAdminPassword": NetworkAdminPassword, "McNonce": McNonce, "Certificate": Certificate, "SigningAlgorithm": SigningAlgorithm, "DigitalSignature": DigitalSignature }, callback_func); }
obj.IPS_HostBasedSetupService_AddNextCertInChain = function (NextCertificate, IsLeafCertificate, IsRootCertificate, callback_func) { obj.Exec("IPS_HostBasedSetupService", "AddNextCertInChain", { "NextCertificate": NextCertificate, "IsLeafCertificate": IsLeafCertificate, "IsRootCertificate": IsRootCertificate }, callback_func); }
obj.IPS_HostBasedSetupService_AdminSetup = function (NetAdminPassEncryptionType, NetworkAdminPassword, McNonce, SigningAlgorithm, DigitalSignature, callback_func) { obj.Exec("IPS_HostBasedSetupService", "AdminSetup", { "NetAdminPassEncryptionType": NetAdminPassEncryptionType, "NetworkAdminPassword": NetworkAdminPassword, "McNonce": McNonce, "SigningAlgorithm": SigningAlgorithm, "DigitalSignature": DigitalSignature }, callback_func); }
obj.IPS_HostBasedSetupService_UpgradeClientToAdmin = function (McNonce, SigningAlgorithm, DigitalSignature, callback_func) { obj.Exec("IPS_HostBasedSetupService", "UpgradeClientToAdmin", { "McNonce": McNonce, "SigningAlgorithm": SigningAlgorithm, "DigitalSignature": DigitalSignature }, callback_func); }
obj.IPS_HostBasedSetupService_DisableClientControlMode = function (_method_dummy, callback_func) { obj.Exec("IPS_HostBasedSetupService", "DisableClientControlMode", { "_method_dummy": _method_dummy }, callback_func); }
obj.IPS_KVMRedirectionSettingData_TerminateSession = function (callback_func) { obj.Exec("IPS_KVMRedirectionSettingData", "TerminateSession", {}, callback_func); }
obj.IPS_OptInService_StartOptIn = function (callback_func) { obj.Exec("IPS_OptInService", "StartOptIn", {}, callback_func); }
obj.IPS_OptInService_CancelOptIn = function (callback_func) { obj.Exec("IPS_OptInService", "CancelOptIn", {}, callback_func); }
obj.IPS_OptInService_SendOptInCode = function (OptInCode, callback_func) { obj.Exec("IPS_OptInService", "SendOptInCode", { "OptInCode": OptInCode }, callback_func); }
obj.IPS_OptInService_StartService = function (callback_func) { obj.Exec("IPS_OptInService", "StartService", {}, callback_func); }
obj.IPS_OptInService_StopService = function (callback_func) { obj.Exec("IPS_OptInService", "StopService", {}, callback_func); }
obj.IPS_OptInService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("IPS_OptInService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.IPS_ProvisioningRecordLog_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("IPS_ProvisioningRecordLog", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.IPS_ProvisioningRecordLog_ClearLog = function (_method_dummy, callback_func) { obj.Exec("IPS_ProvisioningRecordLog", "ClearLog", { "_method_dummy": _method_dummy }, callback_func); }
obj.IPS_SecIOService_RequestStateChange = function (RequestedState, TimeoutPeriod, callback_func) { obj.Exec("IPS_SecIOService", "RequestStateChange", { "RequestedState": RequestedState, "TimeoutPeriod": TimeoutPeriod }, callback_func); }
obj.AmtStatusToStr = function (code) { if (obj.AmtStatusCodes[code]) return obj.AmtStatusCodes[code]; else return "UNKNOWN_ERROR" }
obj.AmtStatusCodes = {
0x0000: "SUCCESS",
0x0001: "INTERNAL_ERROR",
0x0002: "NOT_READY",
0x0003: "INVALID_PT_MODE",
0x0004: "INVALID_MESSAGE_LENGTH",
0x0005: "TABLE_FINGERPRINT_NOT_AVAILABLE",
0x0006: "INTEGRITY_CHECK_FAILED",
0x0007: "UNSUPPORTED_ISVS_VERSION",
0x0008: "APPLICATION_NOT_REGISTERED",
0x0009: "INVALID_REGISTRATION_DATA",
0x000A: "APPLICATION_DOES_NOT_EXIST",
0x000B: "NOT_ENOUGH_STORAGE",
0x000C: "INVALID_NAME",
0x000D: "BLOCK_DOES_NOT_EXIST",
0x000E: "INVALID_BYTE_OFFSET",
0x000F: "INVALID_BYTE_COUNT",
0x0010: "NOT_PERMITTED",
0x0011: "NOT_OWNER",
0x0012: "BLOCK_LOCKED_BY_OTHER",
0x0013: "BLOCK_NOT_LOCKED",
0x0014: "INVALID_GROUP_PERMISSIONS",
0x0015: "GROUP_DOES_NOT_EXIST",
0x0016: "INVALID_MEMBER_COUNT",
0x0017: "MAX_LIMIT_REACHED",
0x0018: "INVALID_AUTH_TYPE",
0x0019: "AUTHENTICATION_FAILED",
0x001A: "INVALID_DHCP_MODE",
0x001B: "INVALID_IP_ADDRESS",
0x001C: "INVALID_DOMAIN_NAME",
0x001D: "UNSUPPORTED_VERSION",
0x001E: "REQUEST_UNEXPECTED",
0x001F: "INVALID_TABLE_TYPE",
0x0020: "INVALID_PROVISIONING_STATE",
0x0021: "UNSUPPORTED_OBJECT",
0x0022: "INVALID_TIME",
0x0023: "INVALID_INDEX",
0x0024: "INVALID_PARAMETER",
0x0025: "INVALID_NETMASK",
0x0026: "FLASH_WRITE_LIMIT_EXCEEDED",
0x0027: "INVALID_IMAGE_LENGTH",
0x0028: "INVALID_IMAGE_SIGNATURE",
0x0029: "PROPOSE_ANOTHER_VERSION",
0x002A: "INVALID_PID_FORMAT",
0x002B: "INVALID_PPS_FORMAT",
0x002C: "BIST_COMMAND_BLOCKED",
0x002D: "CONNECTION_FAILED",
0x002E: "CONNECTION_TOO_MANY",
0x002F: "RNG_GENERATION_IN_PROGRESS",
0x0030: "RNG_NOT_READY",
0x0031: "CERTIFICATE_NOT_READY",
0x0400: "DISABLED_BY_POLICY",
0x0800: "NETWORK_IF_ERROR_BASE",
0x0801: "UNSUPPORTED_OEM_NUMBER",
0x0802: "UNSUPPORTED_BOOT_OPTION",
0x0803: "INVALID_COMMAND",
0x0804: "INVALID_SPECIAL_COMMAND",
0x0805: "INVALID_HANDLE",
0x0806: "INVALID_PASSWORD",
0x0807: "INVALID_REALM",
0x0808: "STORAGE_ACL_ENTRY_IN_USE",
0x0809: "DATA_MISSING",
0x080A: "DUPLICATE",
0x080B: "EVENTLOG_FROZEN",
0x080C: "PKI_MISSING_KEYS",
0x080D: "PKI_GENERATING_KEYS",
0x080E: "INVALID_KEY",
0x080F: "INVALID_CERT",
0x0810: "CERT_KEY_NOT_MATCH",
0x0811: "MAX_KERB_DOMAIN_REACHED",
0x0812: "UNSUPPORTED",
0x0813: "INVALID_PRIORITY",
0x0814: "NOT_FOUND",
0x0815: "INVALID_CREDENTIALS",
0x0816: "INVALID_PASSPHRASE",
0x0818: "NO_ASSOCIATION",
0x081B: "AUDIT_FAIL",
0x081C: "BLOCKING_COMPONENT",
0x0821: "USER_CONSENT_REQUIRED",
0x1000: "APP_INTERNAL_ERROR",
0x1001: "NOT_INITIALIZED",
0x1002: "LIB_VERSION_UNSUPPORTED",
0x1003: "INVALID_PARAM",
0x1004: "RESOURCES",
0x1005: "HARDWARE_ACCESS_ERROR",
0x1006: "REQUESTOR_NOT_REGISTERED",
0x1007: "NETWORK_ERROR",
0x1008: "PARAM_BUFFER_TOO_SHORT",
0x1009: "COM_NOT_INITIALIZED_IN_THREAD",
0x100A: "URL_REQUIRED"
}
//
// Methods used for getting the event log
//
obj.GetMessageLog = function (func, tag) {
obj.AMT_MessageLog_PositionToFirstRecord(_GetMessageLog0, [func, tag, []]);
}
function _GetMessageLog0(stack, name, responses, status, tag) {
if (status != 200 || responses.Body["ReturnValue"] != '0') { tag[0](obj, null, tag[2]); return; }
obj.AMT_MessageLog_GetRecords(responses.Body["IterationIdentifier"], 390, _GetMessageLog1, tag);
}
function _GetMessageLog1(stack, name, responses, status, tag) {
if (status != 200 || responses.Body["ReturnValue"] != '0') { tag[0](obj, null, tag[2]); return; }
var i, j, x, e, AmtMessages = tag[2], t = new Date(), TimeStamp, ra = responses.Body["RecordArray"];
if (typeof ra === 'string') { responses.Body["RecordArray"] = [responses.Body["RecordArray"]]; }
for (i in ra) {
e = Buffer.from(ra[i], 'base64');
if (e != null) {
TimeStamp = ReadIntXBuf(e, 0);
if ((TimeStamp > 0) && (TimeStamp < 0xFFFFFFFF)) {
x = { 'DeviceAddress': e[4], 'EventSensorType': e[5], 'EventType': e[6], 'EventOffset': e[7], 'EventSourceType': e[8], 'EventSeverity': e[9], 'SensorNumber': e[10], 'Entity': e[11], 'EntityInstance': e[12], 'EventData': [], 'Time': new Date((TimeStamp + (t.getTimezoneOffset() * 60)) * 1000) };
for (j = 13; j < 21; j++) { x['EventData'].push(e[j]); }
x['EntityStr'] = _SystemEntityTypes[x['Entity']];
x['Desc'] = _GetEventDetailStr(x['EventSensorType'], x['EventOffset'], x['EventData'], x['Entity']);
if (!x['EntityStr']) x['EntityStr'] = "Unknown";
AmtMessages.push(x);
}
}
}
if (responses.Body["NoMoreRecords"] != true) { obj.AMT_MessageLog_GetRecords(responses.Body["IterationIdentifier"], 390, _GetMessageLog1, [tag[0], AmtMessages, tag[2]]); } else { tag[0](obj, AmtMessages, tag[2]); }
}
var _EventTrapSourceTypes = "Platform firmware (e.g. BIOS)|SMI handler|ISV system management software|Alert ASIC|IPMI|BIOS vendor|System board set vendor|System integrator|Third party add-in|OSV|NIC|System management card".split('|');
var _SystemFirmwareError = "Unspecified.|No system memory is physically installed in the system.|No usable system memory, all installed memory has experienced an unrecoverable failure.|Unrecoverable hard-disk/ATAPI/IDE device failure.|Unrecoverable system-board failure.|Unrecoverable diskette subsystem failure.|Unrecoverable hard-disk controller failure.|Unrecoverable PS/2 or USB keyboard failure.|Removable boot media not found.|Unrecoverable video controller failure.|No video device detected.|Firmware (BIOS) ROM corruption detected.|CPU voltage mismatch (processors that share same supply have mismatched voltage requirements)|CPU speed matching failure".split('|');
var _SystemFirmwareProgress = "Unspecified.|Memory initialization.|Starting hard-disk initialization and test|Secondary processor(s) initialization|User authentication|User-initiated system setup|USB resource configuration|PCI resource configuration|Option ROM initialization|Video initialization|Cache initialization|SM Bus initialization|Keyboard controller initialization|Embedded controller/management controller initialization|Docking station attachment|Enabling docking station|Docking station ejection|Disabling docking station|Calling operating system wake-up vector|Starting operating system boot process|Baseboard or motherboard initialization|reserved|Floppy initialization|Keyboard test|Pointing device test|Primary processor initialization".split('|');
var _SystemEntityTypes = "Unspecified|Other|Unknown|Processor|Disk|Peripheral|System management module|System board|Memory module|Processor module|Power supply|Add in card|Front panel board|Back panel board|Power system board|Drive backplane|System internal expansion board|Other system board|Processor board|Power unit|Power module|Power management board|Chassis back panel board|System chassis|Sub chassis|Other chassis board|Disk drive bay|Peripheral bay|Device bay|Fan cooling|Cooling unit|Cable interconnect|Memory device|System management software|BIOS|Intel(r) ME|System bus|Group|Intel(r) ME|External environment|Battery|Processing blade|Connectivity switch|Processor/memory module|I/O module|Processor I/O module|Management controller firmware|IPMI channel|PCI bus|PCI express bus|SCSI bus|SATA/SAS bus|Processor front side bus".split('|');
obj.RealmNames = "||Redirection|PT Administration|Hardware Asset|Remote Control|Storage|Event Manager|Storage Admin|Agent Presence Local|Agent Presence Remote|Circuit Breaker|Network Time|General Information|Firmware Update|EIT|LocalUN|Endpoint Access Control|Endpoint Access Control Admin|Event Log Reader|Audit Log|ACL Realm|||Local System".split('|');
obj.WatchdogCurrentStates = { 1: 'Not Started', 2: 'Stopped', 4: 'Running', 8: 'Expired', 16: 'Suspended' };
function _GetEventDetailStr(eventSensorType, eventOffset, eventDataField, entity) {
if (eventSensorType == 15)
{
if (eventDataField[0] == 235) return "Invalid Data";
if (eventOffset == 0) return _SystemFirmwareError[eventDataField[1]];
return _SystemFirmwareProgress[eventDataField[1]];
}
if (eventSensorType == 18 && eventDataField[0] == 170) // System watchdog event
{
return "Agent watchdog " + char2hex(eventDataField[4]) + char2hex(eventDataField[3]) + char2hex(eventDataField[2]) + char2hex(eventDataField[1]) + "-" + char2hex(eventDataField[6]) + char2hex(eventDataField[5]) + "-... changed to " + obj.WatchdogCurrentStates[eventDataField[7]];
}
//if (eventSensorType == 5 && eventOffset == 0) // System chassis
//{
// return "Case intrusion";
//}
//if (eventSensorType == 192 && eventOffset == 0 && eventDataField[0] == 170 && eventDataField[1] == 48)
//{
// if (eventDataField[2] == 0) return "A remote Serial Over LAN session was established.";
// if (eventDataField[2] == 1) return "Remote Serial Over LAN session finished. User control was restored.";
// if (eventDataField[2] == 2) return "A remote IDE-Redirection session was established.";
// if (eventDataField[2] == 3) return "Remote IDE-Redirection session finished. User control was restored.";
//}
//if (eventSensorType == 36)
//{
// long handle = ((long)(eventDataField[1]) << 24) + ((long)(eventDataField[2]) << 16) + ((long)(eventDataField[3]) << 8) + (long)(eventDataField[4]);
// string nic = string.Format("#{0}", eventDataField[0]);
// if (eventDataField[0] == 0xAA) nic = "wired"; // TODO: Add wireless *****
// //if (eventDataField[0] == 0xAA) nic = "wireless";
// if (handle == 4294967293) { return string.Format("All received packet filter was matched on {0} interface.", nic); }
// if (handle == 4294967292) { return string.Format("All outbound packet filter was matched on {0} interface.", nic); }
// if (handle == 4294967290) { return string.Format("Spoofed packet filter was matched on {0} interface.", nic); }
// return string.Format("Filter {0} was matched on {1} interface.", handle, nic);
//}
//if (eventSensorType == 192)
//{
// if (eventDataField[2] == 0) return "Security policy invoked. Some or all network traffic (TX) was stopped.";
// if (eventDataField[2] == 2) return "Security policy invoked. Some or all network traffic (RX) was stopped.";
// return "Security policy invoked.";
//}
//if (eventSensorType == 193)
//{
// if (eventDataField[0] == 0xAA && eventDataField[1] == 0x30 && eventDataField[2] == 0x00 && eventDataField[3] == 0x00) { return "User request for remote connection."; }
// if (eventDataField[0] == 0xAA && eventDataField[1] == 0x20 && eventDataField[2] == 0x03 && eventDataField[3] == 0x01) { return "EAC error: attempt to get posture while NAC in Intel(r) AMT is disabled."; // eventDataField = 0xAA20030100000000 }
// if (eventDataField[0] == 0xAA && eventDataField[1] == 0x20 && eventDataField[2] == 0x04 && eventDataField[3] == 0x00) { return "Certificate revoked. "; }
//}
if (eventSensorType == 6) return "Authentication failed " + (eventDataField[1] + (eventDataField[2] << 8)) + " times. The system may be under attack.";
if (eventSensorType == 30) return "No bootable media";
if (eventSensorType == 32) return "Operating system lockup or power interrupt";
if (eventSensorType == 35) return "System boot failure";
if (eventSensorType == 37) return "System firmware started (at least one CPU is properly executing).";
return "Unknown Sensor Type #" + eventSensorType;
}
// ###BEGIN###{AuditLog}
// Useful link: https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm?turl=WordDocuments%2Fsecurityadminevents.htm
var _AmtAuditStringTable =
{
16: 'Security Admin',
17: 'RCO',
18: 'Redirection Manager',
19: 'Firmware Update Manager',
20: 'Security Audit Log',
21: 'Network Time',
22: 'Network Administration',
23: 'Storage Administration',
24: 'Event Manager',
25: 'Circuit Breaker Manager',
26: 'Agent Presence Manager',
27: 'Wireless Configuration',
28: 'EAC',
29: 'KVM',
30: 'User Opt-In Events',
32: 'Screen Blanking',
33: 'Watchdog Events',
1600: 'Provisioning Started',
1601: 'Provisioning Completed',
1602: 'ACL Entry Added',
1603: 'ACL Entry Modified',
1604: 'ACL Entry Removed',
1605: 'ACL Access with Invalid Credentials',
1606: 'ACL Entry State',
1607: 'TLS State Changed',
1608: 'TLS Server Certificate Set',
1609: 'TLS Server Certificate Remove',
1610: 'TLS Trusted Root Certificate Added',
1611: 'TLS Trusted Root Certificate Removed',
1612: 'TLS Preshared Key Set',
1613: 'Kerberos Settings Modified',
1614: 'Kerberos Master Key Modified',
1615: 'Flash Wear out Counters Reset',
1616: 'Power Package Modified',
1617: 'Set Realm Authentication Mode',
1618: 'Upgrade Client to Admin Control Mode',
1619: 'Unprovisioning Started',
1700: 'Performed Power Up',
1701: 'Performed Power Down',
1702: 'Performed Power Cycle',
1703: 'Performed Reset',
1704: 'Set Boot Options',
1800: 'IDER Session Opened',
1801: 'IDER Session Closed',
1802: 'IDER Enabled',
1803: 'IDER Disabled',
1804: 'SoL Session Opened',
1805: 'SoL Session Closed',
1806: 'SoL Enabled',
1807: 'SoL Disabled',
1808: 'KVM Session Started',
1809: 'KVM Session Ended',
1810: 'KVM Enabled',
1811: 'KVM Disabled',
1812: 'VNC Password Failed 3 Times',
1900: 'Firmware Updated',
1901: 'Firmware Update Failed',
2000: 'Security Audit Log Cleared',
2001: 'Security Audit Policy Modified',
2002: 'Security Audit Log Disabled',
2003: 'Security Audit Log Enabled',
2004: 'Security Audit Log Exported',
2005: 'Security Audit Log Recovered',
2100: 'Intel&reg; ME Time Set',
2200: 'TCPIP Parameters Set',
2201: 'Host Name Set',
2202: 'Domain Name Set',
2203: 'VLAN Parameters Set',
2204: 'Link Policy Set',
2205: 'IPv6 Parameters Set',
2300: 'Global Storage Attributes Set',
2301: 'Storage EACL Modified',
2302: 'Storage FPACL Modified',
2303: 'Storage Write Operation',
2400: 'Alert Subscribed',
2401: 'Alert Unsubscribed',
2402: 'Event Log Cleared',
2403: 'Event Log Frozen',
2500: 'CB Filter Added',
2501: 'CB Filter Removed',
2502: 'CB Policy Added',
2503: 'CB Policy Removed',
2504: 'CB Default Policy Set',
2505: 'CB Heuristics Option Set',
2506: 'CB Heuristics State Cleared',
2600: 'Agent Watchdog Added',
2601: 'Agent Watchdog Removed',
2602: 'Agent Watchdog Action Set',
2700: 'Wireless Profile Added',
2701: 'Wireless Profile Removed',
2702: 'Wireless Profile Updated',
2800: 'EAC Posture Signer SET',
2801: 'EAC Enabled',
2802: 'EAC Disabled',
2803: 'EAC Posture State',
2804: 'EAC Set Options',
2900: 'KVM Opt-in Enabled',
2901: 'KVM Opt-in Disabled',
2902: 'KVM Password Changed',
2903: 'KVM Consent Succeeded',
2904: 'KVM Consent Failed',
3000: 'Opt-In Policy Change',
3001: 'Send Consent Code Event',
3002: 'Start Opt-In Blocked Event'
}
// Return human readable extended audit log data
// TODO: Just put some of them here, but many more still need to be added, helpful link here:
// https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm?turl=WordDocuments%2Fsecurityadminevents.htm
obj.GetAuditLogExtendedDataStr = function (id, data) {
if ((id == 1602 || id == 1604) && data.charCodeAt(0) == 0) { return data.substring(2, 2 + data.charCodeAt(1)); } // ACL Entry Added/Removed (Digest)
if (id == 1603) { if (data.charCodeAt(1) == 0) { return data.substring(3); } return null; } // ACL Entry Modified
if (id == 1605) { return ["Invalid ME access", "Invalid MEBx access"][data.charCodeAt(0)]; } // ACL Access with Invalid Credentials
if (id == 1606) { var r = ["Disabled", "Enabled"][data.charCodeAt(0)]; if (data.charCodeAt(1) == 0) { r += ", " + data.substring(3); } return r;} // ACL Entry State
if (id == 1607) { return "Remote " + ["NoAuth", "ServerAuth", "MutualAuth"][data.charCodeAt(0)] + ", Local " + ["NoAuth", "ServerAuth", "MutualAuth"][data.charCodeAt(1)]; } // TLS State Changed
if (id == 1617) { return obj.RealmNames[ReadInt(data, 0)] + ", " + ["NoAuth", "Auth", "Disabled"][data.charCodeAt(4)]; } // Set Realm Authentication Mode
if (id == 1619) { return ["BIOS", "MEBx", "Local MEI", "Local WSMAN", "Remote WSAMN"][data.charCodeAt(0)]; } // Intel AMT Unprovisioning Started
if (id == 1900) { return "From " + ReadShort(data, 0) + "." + ReadShort(data, 2) + "." + ReadShort(data, 4) + "." + ReadShort(data, 6) + " to " + ReadShort(data, 8) + "." + ReadShort(data, 10) + "." + ReadShort(data, 12) + "." + ReadShort(data, 14); } // Firmware Updated
if (id == 2100) { var t4 = new Date(); t4.setTime(ReadInt(data, 0) * 1000 + (new Date().getTimezoneOffset() * 60000)); return t4.toLocaleString(); } // Intel AMT Time Set
if (id == 3000) { return "From " + ["None", "KVM", "All"][data.charCodeAt(0)] + " to " + ["None", "KVM", "All"][data.charCodeAt(1)]; } // Opt-In Policy Change
if (id == 3001) { return ["Success", "Failed 3 times"][data.charCodeAt(0)]; } // Send Consent Code Event
return null;
}
obj.GetAuditLog = function (func) {
obj.AMT_AuditLog_ReadRecords(1, _GetAuditLog0, [func, []]);
}
function MakeToArray(v) { if (!v || v == null || typeof v == 'object') return v; return [v]; }
function ReadShort(v, p) { return (v.charCodeAt(p) << 8) + v.charCodeAt(p + 1); }
function ReadInt(v, p) { return (v.charCodeAt(p) * 0x1000000) + (v.charCodeAt(p + 1) << 16) + (v.charCodeAt(p + 2) << 8) + v.charCodeAt(p + 3); } // We use "*0x1000000" instead of "<<24" because the shift converts the number to signed int32.
function ReadIntX(v, p) { return (v.charCodeAt(p + 3) * 0x1000000) + (v.charCodeAt(p + 2) << 16) + (v.charCodeAt(p + 1) << 8) + v.charCodeAt(p); }
function ReadIntXBuf(v, p) { return (v[p + 3] * 0x1000000) + (v[p + 2] << 16) + (v[p + 1] << 8) + v[p]; }
function btoa(x) { return Buffer.from(x).toString('base64'); }
function atob(x) {
var z = null;
try {
z = Buffer.from(x, 'base64').toString();
} catch (e) { console.log(e); }
return z;
}
function _GetAuditLog0(stack, name, responses, status, tag) {
if (status != 200) { tag[0](obj, [], status); return; }
var ptr, i, e, x, r = tag[1], t = new Date(), TimeStamp;
if (responses.Body['RecordsReturned'] > 0) {
responses.Body['EventRecords'] = MakeToArray(responses.Body['EventRecords']);
for (i in responses.Body['EventRecords']) {
e = null;
try {
e = atob(responses.Body['EventRecords'][i]);
} catch (e) {
console.log(e + " " + responses.Body['EventRecords'][i])
}
x = { 'AuditAppID': ReadShort(e, 0), 'EventID': ReadShort(e, 2), 'InitiatorType': e.charCodeAt(4) };
x['AuditApp'] = _AmtAuditStringTable[x['AuditAppID']];
x['Event'] = _AmtAuditStringTable[(x['AuditAppID'] * 100) + x['EventID']];
if (!x['Event']) x['Event'] = '#' + x['EventID'];
// Read and process the initiator
if (x['InitiatorType'] == 0) {
// HTTP digest
var userlen = e.charCodeAt(5);
x['Initiator'] = e.substring(6, 6 + userlen);
ptr = 6 + userlen;
}
if (x['InitiatorType'] == 1) {
// Kerberos
x['KerberosUserInDomain'] = ReadInt(e, 5);
var userlen = e.charCodeAt(9);
x['Initiator'] = GetSidString(e.substring(10, 10 + userlen));
ptr = 10 + userlen;
}
if (x['InitiatorType'] == 2) {
// Local
x['Initiator'] = '<i>Local</i>';
ptr = 5;
}
if (x['InitiatorType'] == 3) {
// KVM Default Port
x['Initiator'] = '<i>KVM Default Port</i>';
ptr = 5;
}
// Read timestamp
TimeStamp = ReadInt(e, ptr);
x['Time'] = new Date((TimeStamp + (t.getTimezoneOffset() * 60)) * 1000);
ptr += 4;
// Read network access
x['MCLocationType'] = e.charCodeAt(ptr++);
var netlen = e.charCodeAt(ptr++);
x['NetAddress'] = e.substring(ptr, ptr + netlen);
// Read extended data
ptr += netlen;
var exlen = e.charCodeAt(ptr++);
x['Ex'] = e.substring(ptr, ptr + exlen);
x['ExStr'] = obj.GetAuditLogExtendedDataStr((x['AuditAppID'] * 100) + x['EventID'], x['Ex']);
r.push(x);
}
}
if (responses.Body['TotalRecordCount'] > r.length) {
obj.AMT_AuditLog_ReadRecords(r.length + 1, _GetAuditLog0, [tag[0], r]);
} else {
tag[0](obj, r, status);
}
}
// ###END###{AuditLog}
/*
// ###BEGIN###{Certificates}
// Forge MD5
function hex_md5(str) { return forge.md.md5.create().update(str).digest().toHex(); }
// ###END###{Certificates}
// ###BEGIN###{!Certificates}
// TinyMD5 from https://github.com/jbt/js-crypto
// Perform MD5 setup
var md5_k = [];
for (var i = 0; i < 64;) { md5_k[i] = 0 | (Math.abs(Math.sin(++i)) * 4294967296); }
// Perform MD5 on raw string and return hex
function hex_md5(str) {
var b, c, d, j,
x = [],
str2 = unescape(encodeURI(str)),
a = str2.length,
h = [b = 1732584193, c = -271733879, ~b, ~c],
i = 0;
for (; i <= a;) x[i >> 2] |= (str2.charCodeAt(i) || 128) << 8 * (i++ % 4);
x[str = (a + 8 >> 6) * 16 + 14] = a * 8;
i = 0;
for (; i < str; i += 16) {
a = h; j = 0;
for (; j < 64;) {
a = [
d = a[3],
((b = a[1] | 0) +
((d = (
(a[0] +
[
b & (c = a[2]) | ~b & d,
d & b | ~d & c,
b ^ c ^ d,
c ^ (b | ~d)
][a = j >> 4]
) +
(md5_k[j] +
(x[[
j,
5 * j + 1,
3 * j + 5,
7 * j
][a] % 16 + i] | 0)
)
)) << (a = [
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,
6, 10, 15, 21
][4 * a + j++ % 4]) | d >>> 32 - a)
),
b,
c
];
}
for (j = 4; j;) h[--j] = h[j] + a[j];
}
str = '';
for (; j < 32;) str += ((h[j >> 3] >> ((1 ^ j++ & 7) * 4)) & 15).toString(16);
return str;
}
// ###END###{!Certificates}
// Perform MD5 on raw string and return raw string result
function rstr_md5(str) { return hex2rstr(hex_md5(str)); }
*/
/*
Convert arguments into selector set and body XML. Used by AMT_WiFiPortConfigurationService_UpdateWiFiSettings.
args = {
"WiFiEndpoint": {
__parameterType: 'reference',
__resourceUri: 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpoint',
Name: 'WiFi Endpoint 0'
},
"WiFiEndpointSettingsInput":
{
__parameterType: 'instance',
__namespace: 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpointSettings',
ElementName: document.querySelector('#editProfile-profileName').value,
InstanceID: 'Intel(r) AMT:WiFi Endpoint Settings ' + document.querySelector('#editProfile-profileName').value,
AuthenticationMethod: document.querySelector('#editProfile-networkAuthentication').value,
//BSSType: 3, // Intel(r) AMT supports only infrastructure networks
EncryptionMethod: document.querySelector('#editProfile-encryption').value,
SSID: document.querySelector('#editProfile-networkName').value,
Priority: 100,
PSKPassPhrase: document.querySelector('#editProfile-passPhrase').value
},
"IEEE8021xSettingsInput": null,
"ClientCredential": null,
"CACredential": null
},
*/
function execArgumentsToXml(args) {
if (args === undefined || args === null) return null;
var result = '';
for (var argName in args) {
var arg = args[argName];
if (!arg) continue;
if (arg['__parameterType'] === 'reference') result += referenceToXml(argName, arg);
else result += instanceToXml(argName, arg);
//if(arg['__isInstance']) result += instanceToXml(argName, arg);
}
return result;
}
/**
* Convert JavaScript object into XML
<r:WiFiEndpointSettingsInput xmlns:q="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpointSettings">
<q:ElementName>Wireless-Profile-Admin</q:ElementName>
<q:InstanceID>Intel(r) AMT:WiFi Endpoint Settings Wireless-Profile-Admin</q:InstanceID>
<q:AuthenticationMethod>6</q:AuthenticationMethod>
<q:EncryptionMethod>4</q:EncryptionMethod>
<q:Priority>100</q:Priority>
<q:PSKPassPhrase>P@ssw0rd</q:PSKPassPhrase>
</r:WiFiEndpointSettingsInput>
*/
function instanceToXml(instanceName, inInstance) {
if (inInstance === undefined || inInstance === null) return null;
var hasNamespace = !!inInstance['__namespace'];
var startTag = hasNamespace ? '<q:' : '<';
var endTag = hasNamespace ? '</q:' : '</';
var namespaceDef = hasNamespace ? (' xmlns:q="' + inInstance['__namespace'] + '"') : '';
var result = '<r:' + instanceName + namespaceDef + '>';
for (var prop in inInstance) {
if (!inInstance.hasOwnProperty(prop) || prop.indexOf('__') === 0) continue;
if (typeof inInstance[prop] === 'function' || Array.isArray(inInstance[prop])) continue;
if (typeof inInstance[prop] === 'object') {
//result += startTag + prop +'>' + instanceToXml('prop', inInstance[prop]) + endTag + prop +'>';
console.error('only convert one level down...');
}
else {
result += startTag + prop + '>' + inInstance[prop].toString() + endTag + prop + '>';
}
}
result += '</r:' + instanceName + '>';
return result;
}
/**
* Convert a selector set into XML. Expect no nesting.
* {
* selectorName : selectorValue,
* selectorName : selectorValue,
* ... ...
* }
<r:WiFiEndpoint>
<a:Address>http://192.168.1.103:16992/wsman</a:Address>
<a:ReferenceParameters>
<w:ResourceURI>http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpoint</w:ResourceURI>
<w:SelectorSet>
<w:Selector Name="Name">WiFi Endpoint 0</w:Selector>
</w:SelectorSet>
</a:ReferenceParameters>
</r:WiFiEndpoint>
*/
function referenceToXml(referenceName, inReference) {
if (inReference === undefined || inReference === null) return null;
var result = '<r:' + referenceName + '><a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + inReference['__resourceUri'] + '</w:ResourceURI><w:SelectorSet>';
for (var selectorName in inReference) {
if (!inReference.hasOwnProperty(selectorName) || selectorName.indexOf('__') === 0) continue;
if (typeof inReference[selectorName] === 'function' ||
typeof inReference[selectorName] === 'object' ||
Array.isArray(inReference[selectorName]))
continue;
result += '<w:Selector Name="' + selectorName + '">' + inReference[selectorName].toString() + '</w:Selector>';
}
result += '</w:SelectorSet></a:ReferenceParameters></r:' + referenceName + '>';
return result;
}
// Convert a byte array of SID into string
function GetSidString(sid) {
var r = "S-" + sid.charCodeAt(0) + "-" + sid.charCodeAt(7);
for (var i = 2; i < (sid.length / 4) ; i++) r += "-" + ReadIntX(sid, i * 4);
return r;
}
// Convert a SID readable string into bytes
function GetSidByteArray(sidString) {
if (!sidString || sidString == null) return null;
var sidParts = sidString.split('-');
// Make sure the SID has at least 4 parts and starts with 'S'
if (sidParts.length < 4 || (sidParts[0] != 's' && sidParts[0] != 'S')) return null;
// Check that each part of the SID is really an integer
for (var i = 1; i < sidParts.length; i++) { var y = parseInt(sidParts[i]); if (y != sidParts[i]) return null; sidParts[i] = y; }
// Version (8 bit) + Id count (8 bit) + 48 bit in big endian -- DO NOT use bitwise right shift operator. JavaScript converts the number into a 32 bit integer before shifting. In real world, it's highly likely this part is always 0.
var r = String.fromCharCode(sidParts[1]) + String.fromCharCode(sidParts.length - 3) + ShortToStr(Math.floor(sidParts[2] / Math.pow(2, 32))) + IntToStr((sidParts[2]) & 0xFFFF);
// the rest are in 32 bit in little endian
for (var i = 3; i < sidParts.length; i++) r += IntToStrX(sidParts[i]);
return r;
}
return obj;
}
module.exports = AmtStackCreateService;

View File

@ -0,0 +1,440 @@
/**
* @fileoverview Script Compiler / Decompiler / Runner
* @author Ylian Saint-Hilaire
* @version v0.1.0e
*/
// Core functions
script_functionTable1 = ['nop', 'jump', 'set', 'print', 'dialog', 'getitem', 'substr', 'indexof', 'split', 'join', 'length', 'jsonparse', 'jsonstr', 'add', 'substract', 'parseint', 'wsbatchenum', 'wsput', 'wscreate', 'wsdelete', 'wsexec', 'scriptspeed', 'wssubscribe', 'wsunsubscribe', 'readchar', 'signwithdummyca'];
// functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
script_functionTable2 = ['encodeuri', 'decodeuri', 'passwordcheck', 'atob', 'btoa', 'hex2str', 'str2hex', 'random', 'md5', 'maketoarray', 'readshort', 'readshortx', 'readint', 'readsint', 'readintx', 'shorttostr', 'shorttostrx', 'inttostr', 'inttostrx'];
// functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
script_functionTableX2 = [encodeURI, decodeURI, passwordcheck, window.atob.bind(window), window.btoa.bind(window), hex2rstr, rstr2hex, random, rstr_md5, MakeToArray, ReadShort, ReadShortX, ReadInt, ReadSInt, ReadIntX, ShortToStr, ShortToStrX, IntToStr, IntToStrX];
// Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
script_functionTable3 = ['pullsystemstatus', 'pulleventlog', 'pullauditlog', 'pullcertificates', 'pullwatchdog', 'pullsystemdefense', 'pullhardware', 'pulluserinfo', 'pullremoteaccess', 'highlightblock', 'disconnect', 'getsidstring', 'getsidbytearray', 'pulleventsubscriptions'];
// Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
script_functionTableX3 = [
PullSystemStatus
,
// ###BEGIN###{EventLog}
PullEventLog
// ###END###{EventLog}
,
// ###BEGIN###{AuditLog}
PullAuditLog
// ###END###{AuditLog}
,
// ###BEGIN###{Certificates}
PullCertificates
// ###END###{Certificates}
,
// ###BEGIN###{AgentPresence}
PullWatchdog
// ###END###{AgentPresence}
,
// ###BEGIN###{SystemDefense}
PullSystemDefense
// ###END###{SystemDefense}
,
// ###BEGIN###{HardwareInfo}
PullHardware
// ###END###{HardwareInfo}
,
PullUserInfo
,
// ###BEGIN###{RemoteAccess}
PullRemoteAccess
// ###END###{RemoteAccess}
,
// ###BEGIN###{Scripting-Editor}
script_HighlightBlock
// ###END###{Scripting-Editor}
,
// ###BEGIN###{ComputerSelector}
disconnect
// ###END###{ComputerSelector}
,
function (runner, x) { return GetSidString(x); }
,
function (runner, x) { return GetSidByteArray(x); }
,
// ###BEGIN###{EventSubscriptions}
PullEventSubscriptions
// ###END###{EventSubscriptions}
];
// Setup the script state
function script_setup(binary, startvars) {
var obj = { startvars:startvars };
if (binary.length < 6) { console.error('Invalid script length'); return null; } // Script must have at least 6 byte header
if (ReadInt(binary, 0) != 0x247D2945) { console.error('Invalid binary script'); return null; } // Check the script magic header
if (ReadShort(binary, 4) > 1) { console.error('Unsupported script version'); return null; } // Check the script version
obj.script = binary.substring(6);
// obj.onStep;
// obj.onConsole;
// Reset the script to the start
obj.reset = function (stepspeed) {
obj.stop();
obj.ip = 0;
obj.variables = startvars;
obj.state = 1;
}
// Start the script
obj.start = function (stepspeed) {
obj.stop();
obj.stepspeed = stepspeed;
if (stepspeed > 0) { obj.timer = setInterval(function () { obj.step() }, stepspeed); }
}
// Stop the script
obj.stop = function () {
if (obj.timer != null) { clearInterval(obj.timer); }
obj.timer = null;
obj.stepspeed = 0;
}
// function used to load and store variable values
obj.getVar = function (name) { if (name == undefined) return undefined; return obj.getVarEx(name.split('.'), obj.variables); }
obj.getVarEx = function (name, val) { try { if (name == undefined) return undefined; if (name.length == 0) return val; return obj.getVarEx(name.slice(1), val[name[0]]); } catch (e) { return null; } }
obj.setVar = function (name, val) { obj.setVarEx(name.split('.'), obj.variables, val); }
obj.setVarEx = function (name, vars, val) { if (name.length == 1) { vars[name[0]] = val; } else { obj.setVarEx(name.slice(1), vars[name[0]], val); } }
// Run the script one step forward
obj.step = function () {
if (obj.state != 1) return;
if (obj.ip < obj.script.length) {
var cmdid = ReadShort(obj.script, obj.ip);
var cmdlen = ReadShort(obj.script, obj.ip + 2);
var argcount = ReadShort(obj.script, obj.ip + 4);
var argptr = obj.ip + 6;
var args = [];
// Clear all temp variables (This is optional)
for (var i in obj.variables) { if (i.startsWith('__')) { delete obj.variables[i]; } }
// Loop on each argument, moving forward by the argument length each time
for (var i = 0; i < argcount; i++) {
var arglen = ReadShort(obj.script, argptr);
var argval = obj.script.substring(argptr + 2, argptr + 2 + arglen);
var argtyp = argval.charCodeAt(0);
argval = argval.substring(1);
if (argtyp < 2) {
// Get the value and replace all {var} with variable values
while (argval.split("{").length > 1) { var t = argval.split("{").pop().split("}").shift(); argval = argval.replace('{' + t + '}', obj.getVar(t)); }
if (argtyp == 1) { obj.variables['__' + i] = decodeURI(argval); argval = '__' + i; } // If argtyp is 1, this is a literal. Store in temp variable.
args.push(argval);
}
if (argtyp == 2 || argtyp == 3) {
obj.variables['__' + i] = ReadSInt(argval, 0);
args.push('__' + i);
}
argptr += (2 + arglen);
}
// Move instruction pointer forward by command size
obj.ip += cmdlen;
// Get all variable values
var argsval = [];
for (var i = 0; i < 10; i++) { argsval.push(obj.getVar(args[i])); }
var storeInArg0;
try {
if (cmdid < 10000) {
// Lets run the actual command
switch (cmdid) {
case 0: // nop
break;
case 1: // jump(label) or jump(label, a, compare, b)
if (argsval[2]) {
if (
(argsval[2] == '<' && argsval[1] < argsval[3]) ||
(argsval[2] == '<=' && argsval[1] <= argsval[3]) ||
(argsval[2] == '!=' && argsval[1] != argsval[3]) ||
(argsval[2] == '=' && argsval[1] == argsval[3]) ||
(argsval[2] == '>=' && argsval[1] >= argsval[3]) ||
(argsval[2] == '>' && argsval[1] > argsval[3])
) { obj.ip = argsval[0]; }
} else {
obj.ip = argsval[0]; // Set the instruction pointer to the new location in the script
}
break;
case 2: // set(variable, value)
if (args[1] == undefined) delete obj.variables[args[0]]; else obj.setVar(args[0], argsval[1]);
break;
case 3: // print(message)
if (obj.onConsole) { obj.onConsole(obj.toString(argsval[0]), obj); } else { console.log(obj.toString(argsval[0])); }
// Q(obj.consoleid).value += () + '\n'); Q(obj.console).scrollTop = Q(obj.console).scrollHeight;
break;
case 4: // dialog(title, content, buttons)
obj.state = 2;
obj.dialog = true;
setDialogMode(11, argsval[0], argsval[2], obj.xxStepDialogOk, argsval[1], obj);
break;
case 5: // getitem(a, b, c)
for (var i in argsval[1]) { if (argsval[1][i][argsval[2]] == argsval[3]) { storeInArg0 = i; } };
break;
case 6: // substr(variable_dest, variable_src, index, len)
storeInArg0 = argsval[1].substr(argsval[2], argsval[3]);
break;
case 7: // indexOf(variable_dest, variable_src, index, len)
storeInArg0 = argsval[1].indexOf(argsval[2]);
break;
case 8: // split(variable_dest, variable_src, separator)
storeInArg0 = argsval[1].split(argsval[2]);
break;
case 9: // join(variable_dest, variable_src, separator)
storeInArg0 = argsval[1].join(argsval[2]);
break;
case 10: // length(variable_dest, variable_src)
storeInArg0 = argsval[1].length;
break;
case 11: // jsonparse(variable_dest, json)
storeInArg0 = JSON.parse(argsval[1]);
break;
case 12: // jsonstr(variable_dest, variable_src)
storeInArg0 = JSON.stringify(argsval[1]);
break;
case 13: // add(variable_dest, variable_src, value)
storeInArg0 = (argsval[1] + argsval[2]);
break;
case 14: // substract(variable_dest, variable_src, value)
storeInArg0 = (argsval[1] - argsval[2]);
break;
case 15: // parseInt(variable_dest, variable_src)
storeInArg0 = parseInt(argsval[1]);
break;
case 16: // wsbatchenum(name, objectList)
obj.state = 2;
obj.amtstack.BatchEnum(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
break;
case 17: // wsput(name, args)
obj.state = 2;
obj.amtstack.Put(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
break;
case 18: // wscreate(name, args)
obj.state = 2;
obj.amtstack.Create(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
break;
case 19: // wsdelete(name, args)
obj.state = 2;
obj.amtstack.Delete(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
break;
case 20: // wsexec(name, method, args, selectors)
obj.state = 2;
obj.amtstack.Exec(argsval[0], argsval[1], argsval[2], obj.xxWsmanReturn, obj, 0, argsval[3]);
break;
case 21: // Script Speed
obj.stepspeed = argsval[0];
if (obj.timer != null) { clearInterval(obj.timer); obj.timer = setInterval(function () { obj.step() }, obj.stepspeed); }
break;
case 22: // wssubscribe(name, delivery, url, selectors, opaque, user, pass)
obj.state = 2;
obj.amtstack.Subscribe(argsval[0], argsval[1], argsval[2], obj.xxWsmanReturn, obj, 0, argsval[3], argsval[4], argsval[5], argsval[6]);
break;
case 23: // wsunsubscribe(name, selectors)
obj.state = 2;
obj.amtstack.UnSubscribe(argsval[0], obj.xxWsmanReturn, obj, 0, argsval[1]);
break;
case 24: // readchar(str, pos)
console.log(argsval[1], argsval[2], argsval[1].charCodeAt(argsval[2]));
storeInArg0 = argsval[1].charCodeAt(argsval[2]);
break;
case 25: // signWithDummyCa
// ###BEGIN###{Certificates}
obj.state = 2;
// DERKey, xxCaPrivateKey, certattributes, issuerattributes
amtcert_signWithCaKey(argsval[0], null, argsval[1], { 'CN': 'Untrusted Root Certificate' }, obj.xxSignWithDummyCaReturn);
// ###END###{Certificates}
break;
default: {
obj.state = 9;
console.error("Script Error, unknown command: " + cmdid);
}
}
} else {
if (cmdid < 20000) {
// functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
storeInArg0 = script_functionTableX2[cmdid - 10000](argsval[1], argsval[2], argsval[3], argsval[4], argsval[5], argsval[6]);
} else {
// Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
if (script_functionTableX3 && script_functionTableX3[cmdid - 20000]) {
storeInArg0 = script_functionTableX3[cmdid - 20000](obj, argsval[1], argsval[2], argsval[3], argsval[4], argsval[5], argsval[6]); // Note that optional calls start with "obj" as first argument.
}
}
}
if (storeInArg0 != undefined) obj.setVar(args[0], storeInArg0);
} catch (e) {
if (typeof e == 'object') { e = e.message; }
obj.setVar('_exception', e);
}
}
if (obj.state == 1 && obj.ip >= obj.script.length) { obj.state = 0; obj.stop(); }
if (obj.onStep) obj.onStep(obj);
return obj;
}
obj.xxStepDialogOk = function (button) {
obj.variables['DialogSelect'] = button;
obj.state = 1;
obj.dialog = false;
if (obj.onStep) obj.onStep(obj);
}
// ###BEGIN###{**ClosureAdvancedMode}
obj.xxWsmanReturnFix = function (x) {
if (!x || x == null) return;
if (x.Header) { x['Header'] = x.Header; delete x.Header; }
if (x.Body) { x['Body'] = x.Body; delete x.Body; }
if (x.Responses) { x['Responses'] = x.Responses; delete x.Responses; }
if (x.Response) { x['Response'] = x.Response; delete x.Response; }
if (x.ReturnValueStr) { x['ReturnValueStr'] = x.ReturnValueStr; delete x.ReturnValueStr; }
}
// ###END###{**ClosureAdvancedMode}
obj.xxWsmanReturn = function (stack, name, responses, status) {
// ###BEGIN###{**ClosureAdvancedMode}
// This is required when Google Closure is used
if (responses) {
obj.xxWsmanReturnFix(responses);
for (var i in responses) {
obj.xxWsmanReturnFix(responses[i]);
for (var j in responses[i]) { obj.xxWsmanReturnFix(responses[i][j]); }
}
}
// ###END###{**ClosureAdvancedMode}
obj.setVar(name, responses);
obj.setVar('wsman_result', status);
obj.setVar('wsman_result_str', ((httpErrorTable[status]) ? (httpErrorTable[status]) : ('Error #' + status)));
obj.state = 1;
if (obj.onStep) obj.onStep(obj);
}
// ###BEGIN###{Certificates}
obj.xxSignWithDummyCaReturn = function (cert) {
obj.setVar('signed_cert', btoa(_arrayBufferToString(cert)));
obj.state = 1;
if (obj.onStep) obj.onStep(obj);
}
// ###END###{Certificates}
obj.toString = function (x) { if (typeof x == 'object') return JSON.stringify(x); return x; }
obj.reset();
return obj;
}
// Argument types: 0 = Variable, 1 = String, 2 = Integer, 3 = Label
function script_compile(script, onmsg) {
var r = '', scriptlines = script.split('\n'), labels = {}, labelswap = [], swaps = [];
// Go thru each script line and encode it
for (var i in scriptlines) {
var scriptline = scriptlines[i];
if (scriptline.startsWith('##SWAP ')) { var x = scriptline.split(' '); if (x.length == 3) { swaps[x[1]] = x[2]; } } // Add a swap instance
if (scriptline[0] == '#' || scriptline.length == 0) continue; // Skip comments & blank lines
for (var x in swaps) { scriptline = scriptline.split(x).join(swaps[x]); } // Apply all swaps
var keywords = scriptline.match(/"[^"]*"|[^\s"]+/g);
if (keywords.length == 0) continue; // Skip blank lines
if (scriptline[0] == ':') { labels[keywords[0].toUpperCase()] = r.length; continue; } // Mark a label position
var funcIndex = script_functionTable1.indexOf(keywords[0].toLowerCase());
if (funcIndex == -1) { funcIndex = script_functionTable2.indexOf(keywords[0].toLowerCase()); if (funcIndex >= 0) funcIndex += 10000; }
if (funcIndex == -1) { funcIndex = script_functionTable3.indexOf(keywords[0].toLowerCase()); if (funcIndex >= 0) funcIndex += 20000; } // Optional methods
if (funcIndex == -1) { if (onmsg) { onmsg("Unabled to compile, unknown command: " + keywords[0]); } return ''; }
// Encode CommandId, CmdSize, ArgCount, Arg1Len, Arg1, Arg2Len, Arg2...
var cmd = ShortToStr(keywords.length - 1);
for (var j in keywords) {
if (j == 0) continue;
if (keywords[j][0] == ':') {
labelswap.push([keywords[j], r.length + cmd.length + 7]); // Add a label swap
cmd += ShortToStr(5) + String.fromCharCode(3) + IntToStr(0xFFFFFFFF); // Put an empty label
} else {
var argint = parseInt(keywords[j]);
if (argint == keywords[j]) {
cmd += ShortToStr(5) + String.fromCharCode(2) + IntToStr(argint);
} else {
if (keywords[j][0] == '"' && keywords[j][keywords[j].length - 1] == '"') {
cmd += ShortToStr(keywords[j].length - 1) + String.fromCharCode(1) + keywords[j].substring(1, keywords[j].length - 1);
} else {
cmd += ShortToStr(keywords[j].length + 1) + String.fromCharCode(0) + keywords[j];
}
}
}
}
cmd = ShortToStr(funcIndex) + ShortToStr(cmd.length + 4) + cmd;
r += cmd;
}
// Perform all the needed label swaps
for (i in labelswap) {
var label = labelswap[i][0].toUpperCase(), position = labelswap[i][1], target = labels[label];
if (target == undefined) { if (onmsg) { onmsg("Unabled to compile, unknown label: " + label); } return ''; }
r = r.substr(0, position) + IntToStr(target) + r.substr(position + 4);
}
return IntToStr(0x247D2945) + ShortToStr(1) + r;
}
// Decompile the script, intended for debugging only
function script_decompile(binary, onecmd) {
var r = '', ptr = 6, labelcount = 0, labels = {};
if (onecmd >= 0) {
ptr = onecmd; // If we are decompiling just one command, set the ptr to that command.
} else {
if (binary.length < 6) { return '# Invalid script length'; }
var magic = ReadInt(binary, 0);
var version = ReadShort(binary, 4);
if (magic != 0x247D2945) { return '# Invalid binary script: ' + magic; }
if (version != 1) { return '# Invalid script version'; }
}
// Loop on each command, moving forward by the command length each time.
while (ptr < binary.length) {
var cmdid = ReadShort(binary, ptr);
var cmdlen = ReadShort(binary, ptr + 2);
var argcount = ReadShort(binary, ptr + 4);
var argptr = ptr + 6;
var argstr = '';
if (!(onecmd >= 0)) r += ":label" + (ptr - 6) + "\n";
// Loop on each argument, moving forward by the argument length each time
for (var i = 0; i < argcount; i++) {
var arglen = ReadShort(binary, argptr);
var argval = binary.substring(argptr + 2, argptr + 2 + arglen);
var argtyp = argval.charCodeAt(0);
if (argtyp == 0) { argstr += ' ' + argval.substring(1); } // Variable
else if (argtyp == 1) { argstr += ' \"' + argval.substring(1) + '\"'; } // String
else if (argtyp == 2) { argstr += ' ' + ReadInt(argval, 1); } // Integer
else if (argtyp == 3) { // Label
var target = ReadInt(argval, 1);
var label = labels[target];
if (!label) { label = ":label" + target; labels[label] = target; }
argstr += ' ' + label;
}
argptr += (2 + arglen);
}
// Go in the script function table to decode the function
if (cmdid < 10000) {
r += script_functionTable1[cmdid] + argstr + "\n";
} else {
if (cmdid >= 20000) {
r += script_functionTable3[cmdid - 20000] + argstr + "\n"; // Optional methods
} else {
r += script_functionTable2[cmdid - 10000] + argstr + "\n";
}
}
ptr += cmdlen;
if (onecmd >= 0) return r; // If we are decompiling just one command, exit now
}
// Remove all unused labels
var scriptlines = r.split('\n');
r = '';
for (var i in scriptlines) {
var line = scriptlines[i];
if (line[0] != ':') { r += line + '\n'; } else { if (labels[line]) { r += line + '\n'; } }
}
return r;
}

View File

@ -0,0 +1,316 @@
/**
* @description Intel(r) AMT WSMAN Stack
* @author Ylian Saint-Hilaire
* @version v0.2.0
*/
// Construct a MeshServer object
function WsmanStackCreateService(CreateWsmanComm, host, port, user, pass, tls, extra) {
var obj = {};
//obj.onDebugMessage = null; // Set to a function if you want to get debug messages.
obj.NextMessageId = 1; // Next message number, used to label WSMAN calls.
obj.Address = '/wsman';
obj.comm = new CreateWsmanComm(host, port, user, pass, tls, extra);
obj.PerformAjax = function (postdata, callback, tag, pri, namespaces) {
if (namespaces == null) namespaces = '';
obj.comm.PerformAjax('<?xml version=\"1.0\" encoding=\"utf-8\"?><Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns=\"http://www.w3.org/2003/05/soap-envelope\" ' + namespaces + '><Header><a:Action>' + postdata, function (data, status, tag) {
if (status != 200) { callback(obj, null, { Header: { HttpError: status } }, status, tag); return; }
var wsresponse = obj.ParseWsman(data);
if (!wsresponse || wsresponse == null) { callback(obj, null, { Header: { HttpError: status } }, 601, tag); } else { callback(obj, wsresponse.Header["ResourceURI"], wsresponse, 200, tag); }
}, tag, pri);
}
// Private method
//obj.Debug = function (msg) { /*console.log(msg);*/ }
// Cancel all pending queries with given status
obj.CancelAllQueries = function (s) { obj.comm.CancelAllQueries(s); }
// Get the last element of a URI string
obj.GetNameFromUrl = function (resuri) {
var x = resuri.lastIndexOf("/");
return (x == -1)?resuri:resuri.substring(x + 1);
}
// Perform a WSMAN Subscribe operation
obj.ExecSubscribe = function (resuri, delivery, url, callback, tag, pri, selectors, opaque, user, pass) {
var digest = "", digest2 = "", opaque = "";
if (user != null && pass != null) { digest = '<t:IssuedTokens xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust" xmlns:se="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><t:RequestSecurityTokenResponse><t:TokenType>http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#UsernameToken</t:TokenType><t:RequestedSecurityToken><se:UsernameToken><se:Username>' + user + '</se:Username><se:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd#PasswordText">' + pass + '</se:Password></se:UsernameToken></t:RequestedSecurityToken></t:RequestSecurityTokenResponse></t:IssuedTokens>'; digest2 = '<w:Auth Profile="http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/http/digest"/>'; }
if (opaque != null) { opaque = '<a:ReferenceParameters><m:arg>' + opaque + '</m:arg></a:ReferenceParameters>'; }
if (delivery == 'PushWithAck') { delivery = 'dmtf.org/wbem/wsman/1/wsman/PushWithAck'; } else if (delivery == 'Push') { delivery = 'xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push'; }
var data = "http://schemas.xmlsoap.org/ws/2004/08/eventing/Subscribe</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>" + _PutObjToSelectorsXml(selectors) + digest + '</Header><Body><e:Subscribe><e:Delivery Mode="http://schemas.' + delivery + '"><e:NotifyTo><a:Address>' + url + '</a:Address>' + opaque + '</e:NotifyTo>' + digest2 + '</e:Delivery></e:Subscribe>';
obj.PerformAjax(data + "</Body></Envelope>", callback, tag, pri, 'xmlns:e="http://schemas.xmlsoap.org/ws/2004/08/eventing" xmlns:m="http://x.com"');
}
// Perform a WSMAN UnSubscribe operation
obj.ExecUnSubscribe = function (resuri, callback, tag, pri, selectors) {
var data = "http://schemas.xmlsoap.org/ws/2004/08/eventing/Unsubscribe</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>" + _PutObjToSelectorsXml(selectors) + '</Header><Body><e:Unsubscribe/>';
obj.PerformAjax(data + "</Body></Envelope>", callback, tag, pri, 'xmlns:e="http://schemas.xmlsoap.org/ws/2004/08/eventing"');
}
// Perform a WSMAN PUT operation
obj.ExecPut = function (resuri, putobj, callback, tag, pri, selectors) {
var data = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Put</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60.000S</w:OperationTimeout>" + _PutObjToSelectorsXml(selectors) + '</Header><Body>' + _PutObjToBodyXml(resuri, putobj);
obj.PerformAjax(data + "</Body></Envelope>", callback, tag, pri);
}
// Perform a WSMAN CREATE operation
obj.ExecCreate = function (resuri, putobj, callback, tag, pri, selectors) {
var objname = obj.GetNameFromUrl(resuri);
var data = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout>" + _PutObjToSelectorsXml(selectors) + "</Header><Body><g:" + objname + " xmlns:g=\"" + resuri + "\">";
for (var n in putobj) { data += "<g:" + n + ">" + putobj[n] + "</g:" + n + ">" }
obj.PerformAjax(data + "</g:" + objname + "></Body></Envelope>", callback, tag, pri);
}
// Perform a WSMAN DELETE operation
obj.ExecDelete = function (resuri, putobj, callback, tag, pri) {
var data = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout>" + _PutObjToSelectorsXml(putobj) + "</Header><Body /></Envelope>";
obj.PerformAjax(data, callback, tag, pri);
}
// Perform a WSMAN GET operation
obj.ExecGet = function (resuri, callback, tag, pri) {
obj.PerformAjax("http://schemas.xmlsoap.org/ws/2004/09/transfer/Get</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout></Header><Body /></Envelope>", callback, tag, pri);
}
// Perform a WSMAN method call operation
obj.ExecMethod = function (resuri, method, args, callback, tag, pri, selectors) {
var argsxml = "";
for (var i in args) { if (args[i] != null) { if (Array.isArray(args[i])) { for (var x in args[i]) { argsxml += "<r:" + i + ">" + args[i][x] + "</r:" + i + ">"; } } else { argsxml += "<r:" + i + ">" + args[i] + "</r:" + i + ">"; } } }
obj.ExecMethodXml(resuri, method, argsxml, callback, tag, pri, selectors);
}
// Perform a WSMAN method call operation. The arguments are already formatted in XML.
obj.ExecMethodXml = function (resuri, method, argsxml, callback, tag, pri, selectors) {
obj.PerformAjax(resuri + "/" + method + "</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout>" + _PutObjToSelectorsXml(selectors) + "</Header><Body><r:" + method + '_INPUT' + " xmlns:r=\"" + resuri + "\">" + argsxml + "</r:" + method + "_INPUT></Body></Envelope>", callback, tag, pri);
}
// Perform a WSMAN ENUM operation
obj.ExecEnum = function (resuri, callback, tag, pri) {
obj.PerformAjax("http://schemas.xmlsoap.org/ws/2004/09/enumeration/Enumerate</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout></Header><Body><Enumerate xmlns=\"http://schemas.xmlsoap.org/ws/2004/09/enumeration\" /></Body></Envelope>", callback, tag, pri);
}
// Perform a WSMAN PULL operation
obj.ExecPull = function (resuri, enumctx, callback, tag, pri) {
obj.PerformAjax("http://schemas.xmlsoap.org/ws/2004/09/enumeration/Pull</a:Action><a:To>" + obj.Address + "</a:To><w:ResourceURI>" + resuri + "</w:ResourceURI><a:MessageID>" + (obj.NextMessageId++) + "</a:MessageID><a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo><w:OperationTimeout>PT60S</w:OperationTimeout></Header><Body><Pull xmlns=\"http://schemas.xmlsoap.org/ws/2004/09/enumeration\"><EnumerationContext>" + enumctx + "</EnumerationContext><MaxElements>999</MaxElements><MaxCharacters>99999</MaxCharacters></Pull></Body></Envelope>", callback, tag, pri);
}
// Private method
obj.ParseWsman = function (xml) {
try {
if (!xml.childNodes) xml = _turnToXml(xml);
var r = { Header:{} }, header = xml.getElementsByTagName("Header")[0], t;
if (!header) header = xml.getElementsByTagName("a:Header")[0];
if (!header) return null;
for (var i = 0; i < header.childNodes.length; i++) {
var child = header.childNodes[i];
r.Header[child.localName] = child.textContent;
}
var body = xml.getElementsByTagName("Body")[0];
if (!body) body = xml.getElementsByTagName("a:Body")[0];
if (!body) return null;
if (body.childNodes.length > 0) {
t = body.childNodes[0].localName;
if (t.indexOf("_OUTPUT") == t.length - 7) { t = t.substring(0, t.length - 7); }
r.Header['Method'] = t;
r.Body = _ParseWsmanRec(body.childNodes[0]);
}
return r;
} catch (e) {
console.log("Unable to parse XML: " + xml);
return null;
}
}
// Private method
function _ParseWsmanRec(node) {
var data, r = {};
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
if ((child.childElementCount == null) || (child.childElementCount == 0)) { data = child.textContent; } else { data = _ParseWsmanRec(child); }
if (data == 'true') data = true; // Convert 'true' into true
if (data == 'false') data = false; // Convert 'false' into false
if ((parseInt(data) + '') === data) data = parseInt(data); // Convert integers
var childObj = data;
if ((child.attributes != null) && (child.attributes.length > 0)) {
childObj = { 'Value': data };
for(var j = 0; j < child.attributes.length; j++) {
childObj['@' + child.attributes[j].name] = child.attributes[j].value;
}
}
if (r[child.localName] instanceof Array) { r[child.localName].push(childObj); }
else if (r[child.localName] == null) { r[child.localName] = childObj; }
else { r[child.localName] = [r[child.localName], childObj]; }
}
return r;
}
function _PutObjToBodyXml(resuri, putObj) {
if (!resuri || putObj == null) return '';
var objname = obj.GetNameFromUrl(resuri);
var result = '<r:' + objname + ' xmlns:r="' + resuri + '">';
for (var prop in putObj) {
if (!putObj.hasOwnProperty(prop) || prop.indexOf('__') === 0 || prop.indexOf('@') === 0) continue;
if (putObj[prop] == null || typeof putObj[prop] === 'function') continue;
if (typeof putObj[prop] === 'object' && putObj[prop]['ReferenceParameters']) {
result += '<r:' + prop + '><a:Address>' + putObj[prop].Address + '</a:Address><a:ReferenceParameters><w:ResourceURI>' + putObj[prop]['ReferenceParameters']["ResourceURI"] + '</w:ResourceURI><w:SelectorSet>';
var selectorArray = putObj[prop]['ReferenceParameters']['SelectorSet']['Selector'];
if (Array.isArray(selectorArray)) {
for (var i=0; i< selectorArray.length; i++) {
result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray[i]) + '>' + selectorArray[i]['Value'] + '</w:Selector>';
}
}
else {
result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray) + '>' + selectorArray['Value'] + '</w:Selector>';
}
result += '</w:SelectorSet></a:ReferenceParameters></r:' + prop + '>';
}
else {
if (Array.isArray(putObj[prop])) {
for (var i = 0; i < putObj[prop].length; i++) {
result += '<r:' + prop + '>' + putObj[prop][i].toString() + '</r:' + prop + '>';
}
} else {
result += '<r:' + prop + '>' + putObj[prop].toString() + '</r:' + prop + '>';
}
}
}
result += '</r:' + objname + '>';
return result;
}
/*
convert
{ @Name: 'InstanceID', @AttrName: 'Attribute Value'}
into
' Name="InstanceID" AttrName="Attribute Value" '
*/
function _ObjectToXmlAttributes(objWithAttributes) {
if(!objWithAttributes) return '';
var result = ' ';
for (var propName in objWithAttributes) {
if (!objWithAttributes.hasOwnProperty(propName) || propName.indexOf('@') !== 0) continue;
result += propName.substring(1) + '="' + objWithAttributes[propName] + '" ';
}
return result;
}
function _PutObjToSelectorsXml(selectorSet) {
if (!selectorSet) return '';
if (typeof selectorSet == 'string') return selectorSet;
if (selectorSet['InstanceID']) return "<w:SelectorSet><w:Selector Name=\"InstanceID\">" + selectorSet['InstanceID'] + "</w:Selector></w:SelectorSet>";
var result = '<w:SelectorSet>';
for(var propName in selectorSet) {
if (!selectorSet.hasOwnProperty(propName)) continue;
result += '<w:Selector Name="' + propName + '">';
if (selectorSet[propName]['ReferenceParameters']) {
result += '<a:EndpointReference>';
result += '<a:Address>' + selectorSet[propName]['Address'] + '</a:Address><a:ReferenceParameters><w:ResourceURI>' + selectorSet[propName]['ReferenceParameters']['ResourceURI'] + '</w:ResourceURI><w:SelectorSet>';
var selectorArray = selectorSet[propName]['ReferenceParameters']['SelectorSet']['Selector'];
if (Array.isArray(selectorArray)) {
for (var i = 0; i < selectorArray.length; i++) {
result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray[i]) + '>' + selectorArray[i]['Value'] + '</w:Selector>';
}
}
else {
result += '<w:Selector' + _ObjectToXmlAttributes(selectorArray) + '>' + selectorArray['Value'] + '</w:Selector>';
}
result += '</w:SelectorSet></a:ReferenceParameters></a:EndpointReference>';
} else {
result += selectorSet[propName];
}
result += '</w:Selector>';
}
result += '</w:SelectorSet>';
return result;
}
// This is a drop-in replacement to _turnToXml() that works without xml parser dependency.
Object.defineProperty(Array.prototype, "peek", { value: function () { return (this.length > 0 ? this[this.length - 1] : null); } });
function _treeBuilder() {
this.tree = [];
this.push = function (element) { this.tree.push(element); };
this.pop = function () { var element = this.tree.pop(); if (this.tree.length > 0) { var x = this.tree.peek(); x.childNodes.push(element); x.childElementCount = x.childNodes.length; } return (element); };
this.peek = function () { return (this.tree.peek()); }
this.addNamespace = function (prefix, namespace) { this.tree.peek().nsTable[prefix] = namespace; if (this.tree.peek().attributes.length > 0) { for (var i = 0; i < this.tree.peek().attributes; ++i) { var a = this.tree.peek().attributes[i]; if (prefix == '*' && a.name == a.localName) { a.namespace = namespace; } else if (prefix != '*' && a.name != a.localName) { var pfx = a.name.split(':')[0]; if (pfx == prefix) { a.namespace = namespace; } } } } }
this.getNamespace = function (prefix) { for (var i = this.tree.length - 1; i >= 0; --i) { if (this.tree[i].nsTable[prefix] != null) { return (this.tree[i].nsTable[prefix]); } } return null; }
}
function _turnToXml(text) { if (text == null) return null; return ({ childNodes: [_turnToXmlRec(text)], getElementsByTagName: _getElementsByTagName, getChildElementsByTagName: _getChildElementsByTagName, getElementsByTagNameNS: _getElementsByTagNameNS }); }
function _getElementsByTagNameNS(ns, name) { var ret = []; _xmlTraverseAllRec(this.childNodes, function (node) { if (node.localName == name && (node.namespace == ns || ns == '*')) { ret.push(node); } }); return ret; }
function _getElementsByTagName(name) { var ret = []; _xmlTraverseAllRec(this.childNodes, function (node) { if (node.localName == name) { ret.push(node); } }); return ret; }
function _getChildElementsByTagName(name) { var ret = []; if (this.childNodes != null) { for (var node in this.childNodes) { if (this.childNodes[node].localName == name) { ret.push(this.childNodes[node]); } } } return (ret); }
function _getChildElementsByTagNameNS(ns, name) { var ret = []; if (this.childNodes != null) { for (var node in this.childNodes) { if (this.childNodes[node].localName == name && (ns == '*' || this.childNodes[node].namespace == ns)) { ret.push(this.childNodes[node]); } } } return (ret); }
function _xmlTraverseAllRec(nodes, func) { for (var i in nodes) { func(nodes[i]); if (nodes[i].childNodes) { _xmlTraverseAllRec(nodes[i].childNodes, func); } } }
function _turnToXmlRec(text) {
var elementStack = new _treeBuilder(), lastElement = null, x1 = text.split('<'), ret = [], element = null, currentElementName = null;
for (var i in x1) {
var x2 = x1[i].split('>'), x3 = x2[0].split(' '), elementName = x3[0];
if ((elementName.length > 0) && (elementName[0] != '?')) {
if (elementName[0] != '/') {
var attributes = [], localName, localname2 = elementName.split(' ')[0].split(':'), localName = (localname2.length > 1) ? localname2[1] : localname2[0];
Object.defineProperty(attributes, "get",
{
value: function () {
if (arguments.length == 1) {
for (var a in this) { if (this[a].name == arguments[0]) { return (this[a]); } }
}
else if (arguments.length == 2) {
for (var a in this) { if (this[a].name == arguments[1] && (arguments[0] == '*' || this[a].namespace == arguments[0])) { return (this[a]); } }
}
else {
throw ('attributes.get(): Invalid number of parameters');
}
}
});
elementStack.push({ name: elementName, localName: localName, getChildElementsByTagName: _getChildElementsByTagName, getElementsByTagNameNS: _getElementsByTagNameNS, getChildElementsByTagNameNS: _getChildElementsByTagNameNS, attributes: attributes, childNodes: [], nsTable: {} });
// Parse Attributes
if (x3.length > 0) {
var skip = false;
for (var j in x3) {
if (x3[j] == '/') {
// This is an empty Element
elementStack.peek().namespace = elementStack.peek().name == elementStack.peek().localName ? elementStack.getNamespace('*') : elementStack.getNamespace(elementStack.peek().name.substring(0, elementStack.peek().name.indexOf(':')));
elementStack.peek().textContent = '';
lastElement = elementStack.pop();
skip = true;
break;
}
var k = x3[j].indexOf('=');
if (k > 0) {
var attrName = x3[j].substring(0, k);
var attrValue = x3[j].substring(k + 2, x3[j].length - 1);
var attrNS = elementStack.getNamespace('*');
if (attrName == 'xmlns') {
elementStack.addNamespace('*', attrValue);
attrNS = attrValue;
} else if (attrName.startsWith('xmlns:')) {
elementStack.addNamespace(attrName.substring(6), attrValue);
} else {
var ax = attrName.split(':');
if (ax.length == 2) { attrName = ax[1]; attrNS = elementStack.getNamespace(ax[0]); }
}
var x = { name: attrName, value: attrValue }
if (attrNS != null) x.namespace = attrNS;
elementStack.peek().attributes.push(x);
}
}
if (skip) { continue; }
}
elementStack.peek().namespace = elementStack.peek().name == elementStack.peek().localName ? elementStack.getNamespace('*') : elementStack.getNamespace(elementStack.peek().name.substring(0, elementStack.peek().name.indexOf(':')));
if (x2[1]) { elementStack.peek().textContent = x2[1]; }
} else { lastElement = elementStack.pop(); }
}
}
return lastElement;
}
return obj;
}
module.exports = WsmanStackCreateService;

View File

@ -0,0 +1,101 @@
/**
* @description WSMAN communication using duktape http
* @author Ylian Saint-Hilaire
* @version v0.2.0c
*/
// Construct a WSMAN communication object
function CreateWsmanComm(host, port, user, pass, tls, extra) {
var obj = {};
obj.PendingAjax = []; // List of pending AJAX calls. When one frees up, another will start.
obj.ActiveAjaxCount = 0; // Number of currently active AJAX calls
obj.MaxActiveAjaxCount = 1; // Maximum number of activate AJAX calls at the same time.
obj.FailAllError = 0; // Set this to non-zero to fail all AJAX calls with that error status, 999 causes responses to be silent.
obj.host = host;
obj.port = port;
obj.user = user;
obj.pass = pass;
obj.tls = tls;
obj.digest = null;
// Private method
// pri = priority, if set to 1, the call is high priority and put on top of the stack.
obj.PerformAjax = function (postdata, callback, tag, pri, url, action) {
if ((obj.ActiveAjaxCount == 0 || ((obj.ActiveAjaxCount < obj.MaxActiveAjaxCount) && (obj.challengeParams != null))) && obj.PendingAjax.length == 0) {
// There are no pending AJAX calls, perform the call now.
obj.PerformAjaxEx(postdata, callback, tag, url, action);
} else {
// If this is a high priority call, put this call in front of the array, otherwise put it in the back.
if (pri == 1) { obj.PendingAjax.unshift([postdata, callback, tag, url, action]); } else { obj.PendingAjax.push([postdata, callback, tag, url, action]); }
}
}
// Private method
obj.PerformNextAjax = function () {
if (obj.ActiveAjaxCount >= obj.MaxActiveAjaxCount || obj.PendingAjax.length == 0) return;
var x = obj.PendingAjax.shift();
obj.PerformAjaxEx(x[0], x[1], x[2], x[3], x[4]);
obj.PerformNextAjax();
}
// Private method
obj.PerformAjaxEx = function (postdata, callback, tag, url, action) {
if (obj.FailAllError != 0) { if (obj.FailAllError != 999) { obj.gotNextMessagesError({ status: obj.FailAllError }, 'error', null, [postdata, callback, tag]); } return; }
if (!postdata) postdata = "";
// console.log("SEND: " + postdata); // DEBUG
// We are in a DukTape environement
if (obj.digest == null) { obj.digest = require('http-digest').create(obj.user, obj.pass); obj.digest.http = require('http'); }
var request = { protocol: (obj.tls == 1 ? 'https:' : 'http:'), method: 'POST', host: obj.host, path: '/wsman', port: obj.port };
var req = obj.digest.request(request,
function (response) {
if (response.statusCode != 200) {
console.log('ERR:' + JSON.stringify(response));
obj.gotNextMessagesError({ status: response.statusCode }, 'error', null, [postdata, callback, tag]);
} else {
response.acc = '';
response.on('data', function (data2) { this.acc += data2; });
response.on('end', function () { obj.gotNextMessages(response.acc, 'success', { status: response.statusCode }, [postdata, callback, tag]); });
}
});
req.on('error', function (e) { console.log(JSON.stringify(e)); obj.gotNextMessagesError({ status: 600 }, 'error', null, [postdata, callback, tag]); });
// Send POST body, this work with binary.
req.write(postdata);
req.end();
return req;
}
// AJAX specific private method
obj.pendingAjaxCall = [];
// Private method
obj.gotNextMessages = function (data, status, request, callArgs) {
obj.ActiveAjaxCount--;
if (obj.FailAllError == 999) return;
//console.log("RECV: " + data); // DEBUG
if (obj.FailAllError != 0) { callArgs[1](null, obj.FailAllError, callArgs[2]); return; }
if (request.status != 200) { callArgs[1](null, request.status, callArgs[2]); return; }
callArgs[1](data, 200, callArgs[2]);
obj.PerformNextAjax();
}
// Private method
obj.gotNextMessagesError = function (request, status, errorThrown, callArgs) {
obj.ActiveAjaxCount--;
if (obj.FailAllError == 999) return;
if (obj.FailAllError != 0) { callArgs[1](null, obj.FailAllError, callArgs[2]); return; }
// if (s != 200) { console.log("ERROR, status=" + status + "\r\n\r\nreq=" + callArgs[0]); } // Debug: Display the request & response if something did not work.
if (obj.FailAllError != 999) { callArgs[1]({ Header: { HttpError: request.status } }, request.status, callArgs[2]); }
obj.PerformNextAjax();
}
// Cancel all pending queries with given status
obj.CancelAllQueries = function (s) {
while (obj.PendingAjax.length > 0) { var x = obj.PendingAjax.shift(); x[1](null, s, x[2]); }
}
return obj;
}
module.exports = CreateWsmanComm;

View File

@ -126,14 +126,14 @@ module.exports.CertificateOperations = function () {
} }
// Returns the web server TLS certificate and private key, if not present, create demonstration ones. // Returns the web server TLS certificate and private key, if not present, create demonstration ones.
obj.GetMeshServerCertificate = function (directory, args, func) { obj.GetMeshServerCertificate = function (directory, args, config, func) {
var certargs = args.cert; var certargs = args.cert;
var strongCertificate = (args.fastcert ? false : true); var strongCertificate = (args.fastcert ? false : true);
var rcountmax = 5;
// commonName, country, organization // commonName, country, organization
// If the certificates directory does not exist, create it. // If the certificates directory does not exist, create it.
if (!obj.dirExists(directory)) { obj.fs.mkdirSync(directory); } if (!obj.dirExists(directory)) { obj.fs.mkdirSync(directory); }
var r = {}, rcount = 0; var r = {}, rcount = 0;
// If the root certificate already exist, load it // If the root certificate already exist, load it
@ -209,7 +209,7 @@ module.exports.CertificateOperations = function () {
} }
caindex++; caindex++;
} while (caok == true); } while (caok == true);
r.calist = calist; r.ca = calist;
// Decode certificate arguments // Decode certificate arguments
var commonName = 'un-configured', country, organization, forceWebCertGen = 0; var commonName = 'un-configured', country, organization, forceWebCertGen = 0;
@ -220,7 +220,44 @@ module.exports.CertificateOperations = function () {
if (args.length > 2) organization = args[2]; if (args.length > 2) organization = args[2];
} }
if (rcount == 5) { // Look for domains that have DNS names and load their certificates
r.dns = {};
for (var i in config.domains) {
if ((i != '') && (config.domains[i] != null) && (config.domains[i].dns != null)) {
var dnsname = config.domains[i].dns;
if (args.tlsoffload == true) {
// If the web certificate already exist, load it. Load just the certificate since we are in TLS offload situation
if (obj.fileExists(directory + '/webserver-' + i + '-cert-public.crt')) {
r.dns[i] = { cert: obj.fs.readFileSync(directory + '/webserver-' + i + '-cert-public.crt', 'utf8') };
config.domains[i].certs = r.dns[i];
} else {
console.log('WARNING: File "webserver-' + i + '-cert-public.crt" missing, domain "' + i + '" will not work correctly.');
}
} else {
// If the web certificate already exist, load it. Load both certificate and private key
if (obj.fileExists(directory + '/webserver-' + i + '-cert-public.crt') && obj.fileExists(directory + '/webserver-' + i + '-cert-private.key')) {
r.dns[i] = { cert: obj.fs.readFileSync(directory + '/webserver-' + i + '-cert-public.crt', 'utf8'), key: obj.fs.readFileSync(directory + '/webserver-' + i + '-cert-private.key', 'utf8') };
config.domains[i].certs = r.dns[i];
// If CA certificates are present, load them
var caok, caindex = 1, calist = [];
do {
caok = false;
if (obj.fileExists(directory + '/webserver-' + i + '-cert-chain' + caindex + '.crt')) {
var caCertificate = obj.fs.readFileSync(directory + '/webserver-' + i + '-cert-chain' + caindex + '.crt', 'utf8');
calist.push(caCertificate);
caok = true;
}
caindex++;
} while (caok == true);
r.dns[i].ca = calist;
} else {
rcountmax++; // This certificate must be generated
}
}
}
}
if (rcount == rcountmax) {
// Fetch the Intel AMT console name // Fetch the Intel AMT console name
var consoleCertificate = obj.pki.certificateFromPem(r.console.cert); var consoleCertificate = obj.pki.certificateFromPem(r.console.cert);
r.AmtConsoleName = consoleCertificate.subject.getField('CN').value; r.AmtConsoleName = consoleCertificate.subject.getField('CN').value;
@ -239,7 +276,7 @@ module.exports.CertificateOperations = function () {
if (xorganizationField != null) { xorganization = xorganizationField.value; } if (xorganizationField != null) { xorganization = xorganizationField.value; }
if ((r.CommonName == commonName) && (xcountry == country) && (xorganization == organization) && (r.AmtMpsName == commonName)) { if (func != undefined) { func(r); } return r; } else { forceWebCertGen = 1; } // If the certificate matches what we want, keep it. if ((r.CommonName == commonName) && (xcountry == country) && (xorganization == organization) && (r.AmtMpsName == commonName)) { if (func != undefined) { func(r); } return r; } else { forceWebCertGen = 1; } // If the certificate matches what we want, keep it.
} }
//console.log('Generating certificates, may take a few minutes...'); console.log('Generating certificates, may take a few minutes...');
// If a certificate is missing, but web certificate is present and --cert is not used, set the names to be the same as the web certificate // If a certificate is missing, but web certificate is present and --cert is not used, set the names to be the same as the web certificate
if ((certargs == null) && (r.web != null)) { if ((certargs == null) && (r.web != null)) {
@ -333,7 +370,41 @@ module.exports.CertificateOperations = function () {
amtConsoleName = consoleCertAndKey.cert.subject.getField('CN').value; amtConsoleName = consoleCertAndKey.cert.subject.getField('CN').value;
} }
var r = { root: { cert: rootCertificate, key: rootPrivateKey }, web: { cert: webCertificate, key: webPrivateKey }, mps: { cert: mpsCertificate, key: mpsPrivateKey }, agent: { cert: agentCertificate, key: agentPrivateKey }, console: { cert: consoleCertificate, key: consolePrivateKey }, calist: calist, CommonName: commonName, RootName: rootName, AmtConsoleName: amtConsoleName }; var r = { root: { cert: rootCertificate, key: rootPrivateKey }, web: { cert: webCertificate, key: webPrivateKey }, mps: { cert: mpsCertificate, key: mpsPrivateKey }, agent: { cert: agentCertificate, key: agentPrivateKey }, console: { cert: consoleCertificate, key: consolePrivateKey }, ca: calist, CommonName: commonName, RootName: rootName, AmtConsoleName: amtConsoleName, dns: {} };
// Look for domains with DNS names that have no certificates and generated them.
for (var i in config.domains) {
if ((i != '') && (config.domains[i] != null) && (config.domains[i].dns != null)) {
var dnsname = config.domains[i].dns;
if (args.tlsoffload != true) {
// If the web certificate does not exist, create it
if ((obj.fileExists(directory + '/webserver-' + i + '-cert-public.crt') == false) || (obj.fileExists(directory + '/webserver-' + i + '-cert-private.key') == false)) {
console.log('Generating HTTPS certificate for ' + i + '...');
var xwebCertAndKey = obj.IssueWebServerCertificate(rootCertAndKey, false, dnsname, country, organization, null, strongCertificate);
var xwebCertificate = obj.pki.certificateToPem(xwebCertAndKey.cert);
var xwebPrivateKey = obj.pki.privateKeyToPem(xwebCertAndKey.key);
obj.fs.writeFileSync(directory + '/webserver-' + i + '-cert-public.crt', xwebCertificate);
obj.fs.writeFileSync(directory + '/webserver-' + i + '-cert-private.key', xwebPrivateKey);
r.dns[i] = { cert: xwebCertificate, key: xwebPrivateKey };
config.domains[i].certs = r.dns[i];
// If CA certificates are present, load them
var caok, caindex = 1, calist = [];
do {
caok = false;
if (obj.fileExists(directory + '/webserver-' + i + '-cert-chain' + caindex + '.crt')) {
var caCertificate = obj.fs.readFileSync(directory + '/webserver-' + i + '-cert-chain' + caindex + '.crt', 'utf8');
calist.push(caCertificate);
caok = true;
}
caindex++;
} while (caok == true);
r.dns[i].ca = calist;
}
}
}
}
if (func != undefined) { func(r); } if (func != undefined) { func(r); }
return r; return r;
} }

1
db.js
View File

@ -91,6 +91,7 @@ module.exports.CreateDB = function (args, datapath) {
obj.GetUserWithVerifiedEmail = function (domain, email, func) { obj.file.find({ type: 'user', domain: domain, email: email, emailVerified: true }, { type: 0 }, func); } obj.GetUserWithVerifiedEmail = function (domain, email, func) { obj.file.find({ type: 'user', domain: domain, email: email, emailVerified: true }, { type: 0 }, func); }
obj.Remove = function (id) { obj.file.remove({ _id: id }); } obj.Remove = function (id) { obj.file.remove({ _id: id }); }
obj.RemoveAll = function (func) { obj.file.remove({}, { multi: true }, func); } obj.RemoveAll = function (func) { obj.file.remove({}, { multi: true }, func); }
obj.RemoveAllOfType = function (type, func) { obj.file.remove({ type: type }, { multi: true }, func); }
obj.InsertMany = function (data, func) { obj.file.insert(data, func); } obj.InsertMany = function (data, func) { obj.file.insert(data, func); }
obj.StoreEvent = function (ids, source, event) { obj.file.insert(event); } obj.StoreEvent = function (ids, source, event) { obj.file.insert(event); }
obj.GetEvents = function (ids, domain, func) { if (obj.databaseType == 1) { obj.file.find({ type: 'event', domain: domain, ids: { $in: ids } }, { type: 0, _id: 0 }).sort({ time: -1 }).exec(func); } else { obj.file.find({ type: 'event', domain: domain, ids: { $in: ids } }, { type: 0, _id: 0 }).sort({ time: -1 }, func) } } obj.GetEvents = function (ids, domain, func) { if (obj.databaseType == 1) { obj.file.find({ type: 'event', domain: domain, ids: { $in: ids } }, { type: 0, _id: 0 }).sort({ time: -1 }).exec(func); } else { obj.file.find({ type: 'event', domain: domain, ids: { $in: ids } }, { type: 0, _id: 0 }).sort({ time: -1 }, func) } }

View File

@ -72,7 +72,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
obj.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0)); // Command 10, ask mesh agent to clear the core obj.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0)); // Command 10, ask mesh agent to clear the core
} else { } else {
// Update new core // Update new core
if (obj.agentExeInfo.amt == true) { if (obj.parent.parent.meshAgentsArchitectureNumbers[obj.agentInfo.agentId].amt == true) {
obj.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0) + obj.parent.parent.defaultMeshCoreHash + obj.parent.parent.defaultMeshCore); // Command 10, ask mesh agent to set the core (with MEI support) obj.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0) + obj.parent.parent.defaultMeshCoreHash + obj.parent.parent.defaultMeshCore); // Command 10, ask mesh agent to set the core (with MEI support)
} else { } else {
obj.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0) + obj.parent.parent.defaultMeshCoreNoMeiHash + obj.parent.parent.defaultMeshCoreNoMei); // Command 10, ask mesh agent to set the core (No MEI) obj.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0) + obj.parent.parent.defaultMeshCoreNoMeiHash + obj.parent.parent.defaultMeshCoreNoMei); // Command 10, ask mesh agent to set the core (No MEI)
@ -157,7 +157,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
obj.receivedCommands += 1; // Agent can't send the same command twice on the same connection ever. Block DOS attack path. obj.receivedCommands += 1; // Agent can't send the same command twice on the same connection ever. Block DOS attack path.
// Check that the server hash matches our own web certificate hash (SHA386) // Check that the server hash matches our own web certificate hash (SHA386)
if (obj.parent.webCertificateHash != msg.substring(2, 50)) { console.log('Agent connected with bad web certificate hash, holding connection (' + obj.remoteaddr + ').'); return; } if (getWebCertHash(obj.domain) != msg.substring(2, 50)) { console.log('Agent connected with bad web certificate hash, holding connection (' + obj.remoteaddr + ').'); return; }
// Use our server private key to sign the ServerHash + AgentNonce + ServerNonce // Use our server private key to sign the ServerHash + AgentNonce + ServerNonce
var privateKey, certasn1; var privateKey, certasn1;
@ -239,14 +239,14 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
// Start authenticate the mesh agent by sending a auth nonce & server TLS cert hash. // Start authenticate the mesh agent by sending a auth nonce & server TLS cert hash.
// Send 384 bits SHA384 hash of TLS cert public key + 384 bits nonce // Send 384 bits SHA384 hash of TLS cert public key + 384 bits nonce
obj.nonce = obj.forge.random.getBytesSync(48); obj.nonce = obj.forge.random.getBytesSync(48);
obj.send(obj.common.ShortToStr(1) + parent.webCertificateHash + obj.nonce); // Command 1, hash + nonce obj.send(obj.common.ShortToStr(1) + getWebCertHash(obj.domain) + obj.nonce); // Command 1, hash + nonce
// Once we get all the information about an agent, run this to hook everything up to the server // Once we get all the information about an agent, run this to hook everything up to the server
function completeAgentConnection() { function completeAgentConnection() {
if (obj.authenticated =! 1 || obj.meshid == null) return; if (obj.authenticated =! 1 || obj.meshid == null) return;
// Check that the mesh exists // Check that the mesh exists
obj.db.Get(obj.dbMeshKey, function (err, meshes) { obj.db.Get(obj.dbMeshKey, function (err, meshes) {
if (meshes.length == 0) { console.log('Agent connected with invalid domain/mesh, holding connection (' + obj.remoteaddr + ').'); return; } // If we disconnect, the agnet will just reconnect. We need to log this or tell agent to connect in a few hours. if (meshes.length == 0) { console.log('Agent connected with invalid domain/mesh, holding connection (' + obj.remoteaddr + ', ' + obj.dbMeshKey + ').'); return; } // If we disconnect, the agnet will just reconnect. We need to log this or tell agent to connect in a few hours.
var mesh = meshes[0]; var mesh = meshes[0];
if (mesh.mtype != 2) { console.log('Agent connected with invalid mesh type, holding connection (' + obj.remoteaddr + ').'); return; } // If we disconnect, the agnet will just reconnect. We need to log this or tell agent to connect in a few hours. if (mesh.mtype != 2) { console.log('Agent connected with invalid mesh type, holding connection (' + obj.remoteaddr + ').'); return; } // If we disconnect, the agnet will just reconnect. We need to log this or tell agent to connect in a few hours.
@ -270,16 +270,17 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
if (device.agent == null) { if (device.agent == null) {
device.agent = { ver: obj.agentInfo.agentVersion, id: obj.agentInfo.agentId, caps: obj.agentInfo.capabilities }; change = 1; device.agent = { ver: obj.agentInfo.agentVersion, id: obj.agentInfo.agentId, caps: obj.agentInfo.capabilities }; change = 1;
} else { } else {
var changes = [], change = 0; var changes = [], change = 0, log = 0;
if (device.agent.ver != obj.agentInfo.agentVersion) { device.agent.ver = obj.agentInfo.agentVersion; change = 1; changes.push('agent version'); } if (device.agent.ver != obj.agentInfo.agentVersion) { device.agent.ver = obj.agentInfo.agentVersion; change = 1; changes.push('agent version'); }
if (device.agent.id != obj.agentInfo.agentId) { device.agent.id = obj.agentInfo.agentId; change = 1; changes.push('agent type'); } if (device.agent.id != obj.agentInfo.agentId) { device.agent.id = obj.agentInfo.agentId; change = 1; changes.push('agent type'); }
if ((device.agent.caps & 24) != (obj.agentInfo.capabilities & 24)) { device.agent.caps = obj.agentInfo.capabilities; change = 1; changes.push('agent capabilities'); } // If agent console or javascript support changes, update capabilities if ((device.agent.caps & 24) != (obj.agentInfo.capabilities & 24)) { device.agent.caps = obj.agentInfo.capabilities; change = 1; changes.push('agent capabilities'); } // If agent console or javascript support changes, update capabilities
if (device.meshid != obj.dbMeshKey) { device.meshid = obj.dbMeshKey; change = 1; changes.push('agent meshid'); } // TODO: If the meshid changes, we need to event a device add/remove on both meshes if (device.meshid != obj.dbMeshKey) { device.meshid = obj.dbMeshKey; change = 1; log = 1; changes.push('agent meshid'); } // TODO: If the meshid changes, we need to event a device add/remove on both meshes
if (change == 1) { if (change == 1) {
obj.db.Set(device); obj.db.Set(device);
// Event the node change // Event the node change
var event = { etype: 'node', action: 'changenode', nodeid: obj.dbNodeKey, domain: domain.id, msg: 'Changed device ' + device.name + ' from mesh ' + mesh.name + ': ' + changes.join(', ') }; var event = { etype: 'node', action: 'changenode', nodeid: obj.dbNodeKey, domain: domain.id };
if (log == 0) { event.nolog = 1; } else { event.msg = 'Changed device ' + device.name + ' from mesh ' + mesh.name + ': ' + changes.join(', '); }
var device2 = obj.common.Clone(device); var device2 = obj.common.Clone(device);
if (device2.intelamt && device2.intelamt.pass) delete device2.intelamt.pass; // Remove the Intel AMT password before eventing this. if (device2.intelamt && device2.intelamt.pass) delete device2.intelamt.pass; // Remove the Intel AMT password before eventing this.
event.node = device; event.node = device;
@ -355,10 +356,17 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
}); });
} }
// Get the web certificate hash for the speficied domain
function getWebCertHash(domain) {
//var hash = obj.parent.webCertificateHashs[domain.id];
//if (hash == null) return obj.parent.webCertificateHash; else return hash;
return obj.parent.webCertificateHash;
}
// Verify the agent signature // Verify the agent signature
function processAgentSignature(msg) { function processAgentSignature(msg) {
var md = obj.forge.md.sha384.create(); // TODO: Switch this to SHA384 on node instead of forge. var md = obj.forge.md.sha384.create(); // TODO: Switch this to SHA384 on node instead of forge.
md.update(obj.parent.webCertificateHash, 'binary'); md.update(getWebCertHash(obj.domain), 'binary');
md.update(obj.nonce, 'binary'); md.update(obj.nonce, 'binary');
md.update(obj.agentnonce, 'binary'); md.update(obj.agentnonce, 'binary');
if (obj.unauth.nodeCert.publicKey.verify(md.digest().bytes(), msg) == false) { return false; } if (obj.unauth.nodeCert.publicKey.verify(md.digest().bytes(), msg) == false) { return false; }

View File

@ -72,7 +72,7 @@ function CreateMeshCentralServer() {
try { require('./pass').hash('test', function () { }); } catch (e) { console.log('Old version of node, must upgrade.'); return; } // TODO: Not sure if this test works or not. try { require('./pass').hash('test', function () { }); } catch (e) { console.log('Old version of node, must upgrade.'); return; } // TODO: Not sure if this test works or not.
// Check for invalid arguments // Check for invalid arguments
var validArguments = ['_', 'notls', 'user', 'port', 'mpsport', 'redirport', 'cert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'shownodes', 'showmeshes', 'showevents', 'showpower', 'showiplocations', 'help', 'exactports', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpsdebug', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbimport', 'selfupdate', 'tlsoffload', 'userallowedip', 'fastcert', 'swarmport', 'swarmdebug', 'logintoken', 'logintokenkey', 'logintokengen', 'logintokengen', 'mailtokengen']; var validArguments = ['_', 'notls', 'user', 'port', 'mpsport', 'redirport', 'cert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'shownodes', 'showmeshes', 'showevents', 'showpower', 'clearpower', 'showiplocations', 'help', 'exactports', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpsdebug', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbimport', 'selfupdate', 'tlsoffload', 'userallowedip', 'fastcert', 'swarmport', 'swarmdebug', 'logintoken', 'logintokenkey', 'logintokengen', 'logintokengen', 'mailtokengen'];
for (var arg in obj.args) { obj.args[arg.toLocaleLowerCase()] = obj.args[arg]; if (validArguments.indexOf(arg.toLocaleLowerCase()) == -1) { console.log('Invalid argument "' + arg + '", use --help.'); return; } } for (var arg in obj.args) { obj.args[arg.toLocaleLowerCase()] = obj.args[arg]; if (validArguments.indexOf(arg.toLocaleLowerCase()) == -1) { console.log('Invalid argument "' + arg + '", use --help.'); return; } }
if (obj.args.mongodb == true) { console.log('Must specify: --mongodb [connectionstring] \r\nSee https://docs.mongodb.com/manual/reference/connection-string/ for MongoDB connection string.'); return; } if (obj.args.mongodb == true) { console.log('Must specify: --mongodb [connectionstring] \r\nSee https://docs.mongodb.com/manual/reference/connection-string/ for MongoDB connection string.'); return; }
@ -204,12 +204,14 @@ function CreateMeshCentralServer() {
// Validate the domains, this is used for multi-hosting // Validate the domains, this is used for multi-hosting
if (obj.config.domains == null) { obj.config.domains = {}; } if (obj.config.domains == null) { obj.config.domains = {}; }
if (obj.config.domains[''] == null) { obj.config.domains[''] = {}; } if (obj.config.domains[''] == null) { obj.config.domains[''] = {}; }
if (obj.config.domains[''].dns != null) { console.log("ERROR: Default domain can't have a DNS name."); return; }
var xdomains = {}; for (var i in obj.config.domains) { if (!obj.config.domains[i].title) { obj.config.domains[i].title = 'MeshCentral'; } if (!obj.config.domains[i].title2) { obj.config.domains[i].title2 = '2.0 Beta 2'; } xdomains[i.toLowerCase()] = obj.config.domains[i]; } obj.config.domains = xdomains; var xdomains = {}; for (var i in obj.config.domains) { if (!obj.config.domains[i].title) { obj.config.domains[i].title = 'MeshCentral'; } if (!obj.config.domains[i].title2) { obj.config.domains[i].title2 = '2.0 Beta 2'; } xdomains[i.toLowerCase()] = obj.config.domains[i]; } obj.config.domains = xdomains;
var bannedDomains = ['public', 'private', 'images', 'scripts', 'styles', 'views']; // List of banned domains var bannedDomains = ['public', 'private', 'images', 'scripts', 'styles', 'views']; // List of banned domains
for (var i in obj.config.domains) { for (var j in bannedDomains) { if (i == bannedDomains[j]) { console.log("ERROR: Domain '" + i + "' is not allowed domain name in ./data/config.json."); return; } } } for (var i in obj.config.domains) { for (var j in bannedDomains) { if (i == bannedDomains[j]) { console.log("ERROR: Domain '" + i + "' is not allowed domain name in ./data/config.json."); return; } } }
for (var i in obj.config.domains) { for (var i in obj.config.domains) {
for (var j in obj.config.domains[i]) { obj.config.domains[i][j.toLocaleLowerCase()] = obj.config.domains[i][j]; } // LowerCase all domain keys for (var j in obj.config.domains[i]) { if (j.toLocaleLowerCase() !== j) { obj.config.domains[i][j.toLocaleLowerCase()] = obj.config.domains[i][j]; delete obj.config.domains[i][j]; } } // LowerCase all domain keys
obj.config.domains[i].url = (i == '') ? '/' : ('/' + i + '/'); obj.config.domains[i].id = i; if (obj.config.domains[i].dns == null) { obj.config.domains[i].url = (i == '') ? '/' : ('/' + i + '/'); } else { obj.config.domains[i].url = '/'; }
obj.config.domains[i].id = i;
if (typeof obj.config.domains[i].userallowedip == 'string') { obj.config.domains[i].userallowedip = null; if (obj.config.domains[i].userallowedip != "") { obj.config.domains[i].userallowedip = obj.config.domains[i].userallowedip.split(','); } } if (typeof obj.config.domains[i].userallowedip == 'string') { obj.config.domains[i].userallowedip = null; if (obj.config.domains[i].userallowedip != "") { obj.config.domains[i].userallowedip = obj.config.domains[i].userallowedip.split(','); } }
} }
@ -235,6 +237,7 @@ function CreateMeshCentralServer() {
if (obj.args.showmeshes) { obj.db.GetAllType('mesh', function (err, docs) { console.log(docs); process.exit(); }); return; } if (obj.args.showmeshes) { obj.db.GetAllType('mesh', function (err, docs) { console.log(docs); process.exit(); }); return; }
if (obj.args.showevents) { obj.db.GetAllType('event', function (err, docs) { console.log(docs); process.exit(); }); return; } if (obj.args.showevents) { obj.db.GetAllType('event', function (err, docs) { console.log(docs); process.exit(); }); return; }
if (obj.args.showpower) { obj.db.GetAllType('power', function (err, docs) { console.log(docs); process.exit(); }); return; } if (obj.args.showpower) { obj.db.GetAllType('power', function (err, docs) { console.log(docs); process.exit(); }); return; }
if (obj.args.clearpower) { obj.db.RemoveAllOfType('power', function () { process.exit(); }); return; }
if (obj.args.showiplocations) { obj.db.GetAllType('iploc', function (err, docs) { console.log(docs); process.exit(); }); return; } if (obj.args.showiplocations) { obj.db.GetAllType('iploc', function (err, docs) { console.log(docs); process.exit(); }); return; }
if (obj.args.logintoken) { obj.getLoginToken(obj.args.logintoken, function (r) { console.log(r); process.exit(); }); return; } if (obj.args.logintoken) { obj.getLoginToken(obj.args.logintoken, function (r) { console.log(r); process.exit(); }); return; }
if (obj.args.logintokenkey) { obj.showLoginTokenKey(function (r) { console.log(r); process.exit(); }); return; } if (obj.args.logintokenkey) { obj.showLoginTokenKey(function (r) { console.log(r); process.exit(); }); return; }
@ -266,8 +269,11 @@ function CreateMeshCentralServer() {
obj.db.cleanup(); obj.db.cleanup();
// Set all nodes to power state of unknown (0) // Set all nodes to power state of unknown (0)
// TODO: This time for this message can be earlier: When server closed or last time did an update to the db. if (obj.multiServer == null) {
obj.db.file.insert({ type: 'power', time: Date.now(), node: '*', power: 0 }); obj.db.file.insert({ type: 'power', time: Date.now(), node: '*', power: 0, s: 1 });
} else {
obj.db.file.insert({ type: 'power', time: Date.now(), node: '*', power: 0, s: 1, server: obj.multiServer.serverid });
}
// Read or setup database configuration values // Read or setup database configuration values
obj.db.Get('dbconfig', function (err, dbconfig) { obj.db.Get('dbconfig', function (err, dbconfig) {
@ -300,14 +306,21 @@ function CreateMeshCentralServer() {
obj.updateMeshCmd(); obj.updateMeshCmd();
// Load server certificates // Load server certificates
obj.certificateOperations.GetMeshServerCertificate(obj.datapath, obj.args, function (certs) { obj.certificateOperations.GetMeshServerCertificate(obj.datapath, obj.args, obj.config, function (certs) {
obj.certificates = certs; obj.certificates = certs;
// If the certificate is un-configured, force LAN-only mode // 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 == 'un-configured') { console.log('Server name not configured, running in LAN-only mode.'); obj.args.lanonly = true; }
// Check that no sub-domains have the same DNS as the parent
for (var i in obj.config.domains) {
if ((obj.config.domains[i].dns != null) && (obj.certificates.CommonName.toLowerCase() === obj.config.domains[i].dns.toLowerCase())) {
console.log("ERROR: Server sub-domain can't have same DNS name as the parent."); process.exit(0); return;
}
}
// Load the list of mesh agents and install scripts // Load the list of mesh agents and install scripts
if (obj.args.noagentupdate == 1) { for (var i in meshAgentsArchitectureNumbers) { meshAgentsArchitectureNumbers[i].update = false; } } if (obj.args.noagentupdate == 1) { for (var i in obj.meshAgentsArchitectureNumbers) { obj.meshAgentsArchitectureNumbers[i].update = false; } }
obj.updateMeshAgentsTable(function () { obj.updateMeshAgentsTable(function () {
obj.updateMeshAgentInstallScripts(); obj.updateMeshAgentInstallScripts();
@ -370,7 +383,7 @@ function CreateMeshCentralServer() {
obj.DispatchEvent(['*'], obj, { etype: 'server', action: 'started', msg: 'Server started' }) obj.DispatchEvent(['*'], obj, { etype: 'server', action: 'started', msg: 'Server started' })
// Load the login cookie encryption key from the database if allowed // Load the login cookie encryption key from the database if allowed
if ((obj.config) && (obj.config.settings) && (obj.config.settings.loginTokenOk == true)) { if ((obj.config) && (obj.config.settings) && (obj.config.settings.allowLoginToken == true)) {
obj.db.Get('LoginCookieEncryptionKey', function (err, docs) { obj.db.Get('LoginCookieEncryptionKey', function (err, docs) {
if ((docs.length > 0) && (docs[0].key != null) && (obj.args.logintokengen == null)) { if ((docs.length > 0) && (docs[0].key != null) && (obj.args.logintokengen == null)) {
obj.loginCookieEncryptionKey = Buffer.from(docs[0].key, 'hex'); obj.loginCookieEncryptionKey = Buffer.from(docs[0].key, 'hex');
@ -418,7 +431,9 @@ function CreateMeshCentralServer() {
obj.DispatchEvent(['*'], obj, { etype: 'server', action: 'stopped', msg: 'Server stopped' }) obj.DispatchEvent(['*'], obj, { etype: 'server', action: 'stopped', msg: 'Server stopped' })
// Set all nodes to power state of unknown (0) // Set all nodes to power state of unknown (0)
obj.db.file.insert({ type: 'power', time: Date.now(), node: '*', power: 0 }, function () { var record = { type: 'power', time: Date.now(), node: '*', power: 0, s: 2 };
if (obj.multiServer != null) { record.server = obj.multiServer.serverid; }
obj.db.file.insert(record, function () {
if (restoreFile) { if (restoreFile) {
obj.debug(1, 'Server stopped, updating settings: ' + restoreFile); obj.debug(1, 'Server stopped, updating settings: ' + restoreFile);
console.log('Updating settings folder...'); console.log('Updating settings folder...');
@ -571,7 +586,9 @@ function CreateMeshCentralServer() {
eventConnectChange = 1; eventConnectChange = 1;
// Set new power state in database // Set new power state in database
obj.db.file.insert({ type: 'power', time: connectTime, node: nodeid, power: powerState, oldPower: oldPowerState }); var record = { type: 'power', time: connectTime, node: nodeid, power: powerState };
if (oldPowerState != null) record.oldPower = oldPowerState;
obj.db.file.insert(record);
} }
// Event the node connection change // Event the node connection change
@ -596,7 +613,14 @@ function CreateMeshCentralServer() {
if (connectType == 1) { state.agentPower = powerState; } else if (connectType == 2) { state.ciraPower = powerState; } else if (connectType == 4) { state.amtPower = powerState; } if (connectType == 1) { state.agentPower = powerState; } else if (connectType == 2) { state.ciraPower = powerState; } else if (connectType == 4) { state.amtPower = powerState; }
var powerState = 0; var powerState = 0;
if ((state.connectivity & 1) != 0) { powerState = state.agentPower; } else if ((state.connectivity & 2) != 0) { powerState = state.ciraPower; } else if ((state.connectivity & 4) != 0) { powerState = state.amtPower; } if ((state.connectivity & 1) != 0) { powerState = state.agentPower; } else if ((state.connectivity & 2) != 0) { powerState = state.ciraPower; } else if ((state.connectivity & 4) != 0) { powerState = state.amtPower; }
if ((state.powerState == null) || (state.powerState != powerState)) { state.powerState = powerState; } if ((state.powerState == null) || (state.powerState != powerState)) {
state.powerState = powerState;
// Set new power state in database
var record = { type: 'power', time: connectTime, node: nodeid, power: powerState, server: obj.multiServer.serverid };
if (oldPowerState != null) record.oldPower = oldPowerState;
obj.db.file.insert(record);
}
// Update the combined node state // Update the combined node state
var x = {}; x[nodeid] = 1; var x = {}; x[nodeid] = 1;
@ -773,7 +797,8 @@ function CreateMeshCentralServer() {
} }
// List of possible mesh agents // List of possible mesh agents
var meshAgentsArchitectureNumbers = { obj.meshAgentsArchitectureNumbers = {
0: { id: 0, localname: 'Unknown', rname: 'meshconsole.exe', desc: 'Unknown agent', update: false, amt: true },
1: { id: 1, localname: 'MeshConsole.exe', rname: 'meshconsole.exe', desc: 'Windows x86-32 console', update: true, amt: true }, 1: { id: 1, localname: 'MeshConsole.exe', rname: 'meshconsole.exe', desc: 'Windows x86-32 console', update: true, amt: true },
2: { id: 2, localname: 'MeshConsole64.exe', rname: 'meshconsole.exe', desc: 'Windows x86-64 console', update: true, amt: true }, 2: { id: 2, localname: 'MeshConsole64.exe', rname: 'meshconsole.exe', desc: 'Windows x86-64 console', update: true, amt: true },
3: { id: 3, localname: 'MeshService.exe', rname: 'meshagent.exe', desc: 'Windows x86-32 service', update: true, amt: true }, 3: { id: 3, localname: 'MeshService.exe', rname: 'meshagent.exe', desc: 'Windows x86-32 service', update: true, amt: true },
@ -804,9 +829,9 @@ function CreateMeshCentralServer() {
// Update the list of available mesh agents // Update the list of available mesh agents
obj.updateMeshAgentsTable = function (func) { obj.updateMeshAgentsTable = function (func) {
var archcount = 0; var archcount = 0;
for (var archid in meshAgentsArchitectureNumbers) { archcount++; } for (var archid in obj.meshAgentsArchitectureNumbers) { archcount++; }
for (var archid in meshAgentsArchitectureNumbers) { for (var archid in obj.meshAgentsArchitectureNumbers) {
var agentpath = obj.path.join(__dirname, 'agents', meshAgentsArchitectureNumbers[archid].localname); var agentpath = obj.path.join(__dirname, 'agents', obj.meshAgentsArchitectureNumbers[archid].localname);
var stream = null; var stream = null;
try { try {
stream = obj.fs.createReadStream(agentpath); stream = obj.fs.createReadStream(agentpath);
@ -827,7 +852,7 @@ function CreateMeshCentralServer() {
if (stats != null) { obj.meshAgentBinaries[this.info.id].size = stats.size; } if (stats != null) { obj.meshAgentBinaries[this.info.id].size = stats.size; }
if ((--archcount == 0) && (func != null)) { func(); } if ((--archcount == 0) && (func != null)) { func(); }
}); });
stream.info = meshAgentsArchitectureNumbers[archid]; stream.info = obj.meshAgentsArchitectureNumbers[archid];
stream.agentpath = agentpath; stream.agentpath = agentpath;
stream.hash = obj.crypto.createHash('sha384', stream); stream.hash = obj.crypto.createHash('sha384', stream);
} catch (e) { if ((--archcount == 0) && (func != null)) { func(); } } } catch (e) { if ((--archcount == 0) && (func != null)) { func(); } }
@ -836,6 +861,7 @@ function CreateMeshCentralServer() {
// Generate a time limited user login token // Generate a time limited user login token
obj.getLoginToken = function (userid, func) { obj.getLoginToken = function (userid, func) {
if ((userid == null) || (typeof userid != 'string')) { func('Invalid userid.'); return; }
var x = userid.split('/'); var x = userid.split('/');
if (x == null || x.length != 3 || x[0] != 'user') { func('Invalid userid.'); return; } if (x == null || x.length != 3 || x[0] != 'user') { func('Invalid userid.'); return; }
obj.db.Get(userid, function (err, docs) { obj.db.Get(userid, function (err, docs) {
@ -972,7 +998,7 @@ process.on('SIGINT', function () { if (meshserver != null) { meshserver.Stop();
// Build the list of required modules // Build the list of required modules
var modules = ['nedb', 'https', 'unzip', 'xmldom', 'express', 'mongojs', 'archiver', 'minimist', 'nodemailer', 'multiparty', 'node-forge', 'express-ws', 'compression', 'body-parser', 'connect-redis', 'express-session', 'express-handlebars']; var modules = ['nedb', 'https', 'unzip', 'xmldom', 'express', 'mongojs', 'archiver', 'minimist', 'nodemailer', 'multiparty', 'node-forge', 'express-ws', 'compression', 'body-parser', 'connect-redis', 'express-session', 'express-handlebars'];
if (require('os').platform() == 'win32') { modules.push("node-windows"); } if (require('os').platform() == 'win32') { modules.push("node-sspi"); modules.push("node-windows"); }
// Run as a command line, if we are not using service arguments, don't need to install the service package. // Run as a command line, if we are not using service arguments, don't need to install the service package.
var meshserver = null; var meshserver = null;

View File

@ -1,6 +1,6 @@
{ {
"name": "meshcentral", "name": "meshcentral",
"version": "0.1.1-h", "version": "0.1.1-r",
"keywords": [ "keywords": [
"Remote Management", "Remote Management",
"Intel AMT", "Intel AMT",
@ -46,6 +46,7 @@
"xmldom": "^0.1.27" "xmldom": "^0.1.27"
}, },
"optionalDependencies": { "optionalDependencies": {
"node-sspi": "^0.2.2",
"node-windows": "^0.1.14", "node-windows": "^0.1.14",
"mongojs": "^2.4.0" "mongojs": "^2.4.0"
}, },

View File

@ -1133,8 +1133,6 @@ var CreateAmtRedirect = function (module) {
obj.user = null; obj.user = null;
obj.pass = null; obj.pass = null;
obj.authuri = "/RedirectionService"; obj.authuri = "/RedirectionService";
obj.tlsv1only = 0;
obj.inDataCount = 0;
obj.connectstate = 0; obj.connectstate = 0;
obj.protocol = module.protocol; // 1 = SOL, 2 = KVM, 3 = IDER obj.protocol = module.protocol; // 1 = SOL, 2 = KVM, 3 = IDER
@ -1154,9 +1152,7 @@ var CreateAmtRedirect = function (module) {
obj.user = user; obj.user = user;
obj.pass = pass; obj.pass = pass;
obj.connectstate = 0; obj.connectstate = 0;
obj.inDataCount = 0; obj.socket = new WebSocket(window.location.protocol.replace("http", "ws") + "//" + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + "/webrelay.ashx?p=2&host=" + host + "&port=" + port + "&tls=" + tls + ((user == '*') ? "&serverauth=1" : "") + ((typeof pass === "undefined") ? ("&serverauth=1&user=" + user) : "")); // The "p=2" indicates to the relay that this is a REDIRECTION session
console.log('obj.tlsv1onlyx', obj.tlsv1only);
obj.socket = new WebSocket(window.location.protocol.replace("http", "ws") + "//" + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + "/webrelay.ashx?p=2&host=" + host + "&port=" + port + "&tls=" + tls + "&tls1only=" + obj.tlsv1only + ((user == '*') ? "&serverauth=1" : "") + ((typeof pass === "undefined") ? ("&serverauth=1&user=" + user) : "")); // The "p=2" indicates to the relay that this is a REDIRECTION session
obj.socket.onopen = obj.xxOnSocketConnected; obj.socket.onopen = obj.xxOnSocketConnected;
obj.socket.onmessage = obj.xxOnMessage; obj.socket.onmessage = obj.xxOnMessage;
obj.socket.onclose = obj.xxOnSocketClosed; obj.socket.onclose = obj.xxOnSocketClosed;
@ -1173,8 +1169,6 @@ var CreateAmtRedirect = function (module) {
} }
obj.xxOnMessage = function (e) { obj.xxOnMessage = function (e) {
obj.inDataCount++;
if (typeof e.data == 'object') { if (typeof e.data == 'object') {
var f = new FileReader(); var f = new FileReader();
if (f.readAsBinaryString) { if (f.readAsBinaryString) {
@ -1389,18 +1383,8 @@ var CreateAmtRedirect = function (module) {
obj.xxOnSocketClosed = function () { obj.xxOnSocketClosed = function () {
//obj.Debug("Redir Socket Closed"); //obj.Debug("Redir Socket Closed");
console.log('obj.tlsv1only', obj.tlsv1only);
if ((obj.inDataCount == 0) && (obj.tlsv1only == 0)) {
obj.tlsv1only = 1;
obj.socket = new WebSocket(window.location.protocol.replace("http", "ws") + "//" + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + "/webrelay.ashx?p=2&host=" + host + "&port=" + port + "&tls=" + tls + "&tls1only=" + obj.tlsv1only + ((user == '*') ? "&serverauth=1" : "") + ((typeof pass === "undefined") ? ("&serverauth=1&user=" + user) : "")); // The "p=2" indicates to the relay that this is a REDIRECTION session
obj.socket.onopen = obj.xxOnSocketConnected;
obj.socket.onmessage = obj.xxOnMessage;
obj.socket.onclose = obj.xxOnSocketClosed;
} else {
obj.Stop(); obj.Stop();
} }
}
obj.xxStateChange = function(newstate) { obj.xxStateChange = function(newstate) {
if (obj.State == newstate) return; if (obj.State == newstate) return;
@ -33091,7 +33075,7 @@ if (typeof module !== "undefined" && module.exports) {
var amtwirelessif = -1; // Set to the interface index for the wireless interface, -1 if no wireless. var amtwirelessif = -1; // Set to the interface index for the wireless interface, -1 if no wireless.
var currentMeshNode = null; var currentMeshNode = null;
var webcompilerfeatures = ['AgentPresence','Alarms','AuditLog','Certificates','EventLog','EventSubscriptions','FileSaver','HardwareInfo','Look-MeshCentral','Mode-MeshCentral2','NetworkSettings','PowerControl','PowerControl-Advanced','RemoteAccess','Scripting','Scripting-Editor','Storage','SystemDefense','VersionWarning','Wireless','WsmanBrowser']; var webcompilerfeatures = ['AgentPresence','Alarms','AuditLog','Certificates','ComputerSelectorToolbar','EventLog','EventSubscriptions','FileSaver','HardwareInfo','Look-MeshCentral','Mode-MeshCentral2','NetworkSettings','PowerControl','PowerControl-Advanced','RemoteAccess','Scripting','Scripting-Editor','Storage','SystemDefense','VersionWarning','Wireless','WsmanBrowser'];
var StatusStrs = ['Disconnected', 'Connecting...', 'Setup...', 'Connected']; var StatusStrs = ['Disconnected', 'Connecting...', 'Setup...', 'Connected'];
var scriptstate; var scriptstate;
@ -33463,7 +33447,7 @@ if (typeof module !== "undefined" && module.exports) {
//if (amtversion > 5) query.push("IPS_IPv6PortSettings", "*CIM_KVMRedirectionSAP", "*IPS_OptInService"); //if (amtversion > 5) query.push("IPS_IPv6PortSettings", "*CIM_KVMRedirectionSAP", "*IPS_OptInService");
amtstack.BatchEnum("", query, processSystemStatus, true); amtstack.BatchEnum("", query, processSystemStatus, true);
if (x == 1 && amtsysstate && amtsysstate['AMT_EthernetPortSettings'].responses.length > 1) PullWireless(); if (x == 1) PullWireless();
} }
function processSystemTime(stack, name, responses, status) { function processSystemTime(stack, name, responses, status) {
@ -33637,9 +33621,9 @@ if (typeof module !== "undefined" && module.exports) {
for (var y in amtsysstate['AMT_EthernetPortSettings'].responses) { for (var y in amtsysstate['AMT_EthernetPortSettings'].responses) {
var z = amtsysstate['AMT_EthernetPortSettings'].responses[y]; var z = amtsysstate['AMT_EthernetPortSettings'].responses[y];
if ((y == 0) && (z["MACAddress"] == "00-00-00-00-00-00")) { continue; } // On computers with only wireless, the wired interface will have a null MAC, skip it.
if (y == 0) systemdefense++;
if (z['WLANLinkProtectionLevel'] || (y == 1)) { amtwirelessif = y; } // Set the wireless interface, this seems to cover new wireless only computers and older computers with dual interfaces. if (z['WLANLinkProtectionLevel'] || (y == 1)) { amtwirelessif = y; } // Set the wireless interface, this seems to cover new wireless only computers and older computers with dual interfaces.
if ((y == 0) && (amtwirelessif != y) && (z["MACAddress"] == "00-00-00-00-00-00")) { continue; } // On computers with only wireless, the wired interface will have a null MAC, skip it.
if (y == 0) systemdefense++;
x += "<br><h2>" + ((amtwirelessif == y)?'Wireless':'Wired') + " Interface</h2>"; x += "<br><h2>" + ((amtwirelessif == y)?'Wireless':'Wired') + " Interface</h2>";
x += TableStart(); x += TableStart();

View File

@ -47,6 +47,7 @@ var CreateAgentRemoteDesktop = function (canvasid, scrolldiv) {
obj.onConnectCountChanged = null; obj.onConnectCountChanged = null;
obj.onDebugMessage = null; obj.onDebugMessage = null;
obj.onTouchEnabledChanged = null; obj.onTouchEnabledChanged = null;
obj.onDisplayinfo = null;
obj.Start = function () { obj.Start = function () {
obj.State = 0; obj.State = 0;
@ -200,29 +201,20 @@ var CreateAgentRemoteDesktop = function (canvasid, scrolldiv) {
obj.Send(String.fromCharCode(0x00, 0x0E, 0x00, 0x04)); obj.Send(String.fromCharCode(0x00, 0x0E, 0x00, 0x04));
break; break;
case 11: // GetDisplays case 11: // GetDisplays
var dcount = ((str.charCodeAt(4) & 0xFF) << 8) + (str.charCodeAt(5) & 0xFF); var myOptions = [], dcount = ((str.charCodeAt(4) & 0xFF) << 8) + (str.charCodeAt(5) & 0xFF);
if (dcount == 0) { if (dcount > 0) {
// One display present
if (document.getElementById('termdisplays') != null) document.getElementById('termdisplays').style.display = 'none';
if (document.getElementById('termdisplays2') != null) document.getElementById('termdisplays2').style.display = 'none';
} else {
// Many displays present // Many displays present
var seldisp = ((str.charCodeAt(6 + (dcount * 2)) & 0xFF) << 8) + (str.charCodeAt(7 + (dcount * 2)) & 0xFF); var selitem = 0, seldisp = ((str.charCodeAt(6 + (dcount * 2)) & 0xFF) << 8) + (str.charCodeAt(7 + (dcount * 2)) & 0xFF);
var selitem = 0;
var myOptions = [];
for (var i = 0; i < dcount; i++) { for (var i = 0; i < dcount; i++) {
var disp = ((str.charCodeAt(6 + (i * 2)) & 0xFF) << 8) + (str.charCodeAt(7 + (i * 2)) & 0xFF); var disp = ((str.charCodeAt(6 + (i * 2)) & 0xFF) << 8) + (str.charCodeAt(7 + (i * 2)) & 0xFF);
if (disp == 65535) { if (disp == 65535) { myOptions.push('All Displays'); } else { myOptions.push('Display ' + disp); }
myOptions.push('All Displays');
} else {
myOptions.push('Display ' + disp);
}
if (disp == seldisp) selitem = i; if (disp == seldisp) selitem = i;
} }
} }
// TODO if (obj.onDisplayinfo != null) { obj.onDisplayinfo(obj, myOptions, selitem); }
break; break;
case 12: // SetDisplay case 12: // SetDisplay
console.log('SetDisplayConfirm');
break; break;
case 14: // KVM_INIT_TOUCH case 14: // KVM_INIT_TOUCH
obj.touchenabled = 1; obj.touchenabled = 1;
@ -339,7 +331,7 @@ var CreateAgentRemoteDesktop = function (canvasid, scrolldiv) {
} }
obj.GetDisplayNumbers = function () { obj.Send(String.fromCharCode(0x00, 0x0B, 0x00, 0x04)); } // Get Terminal display obj.GetDisplayNumbers = function () { obj.Send(String.fromCharCode(0x00, 0x0B, 0x00, 0x04)); } // Get Terminal display
obj.SetDisplay = function (number) { obj.Send(String.fromCharCode(0x00, 0x0C, 0x00, 0x06, number >> 8, number & 0xFF)); } // Set Terminal display obj.SetDisplay = function (number) { console.log('SetDisplay', number); obj.Send(String.fromCharCode(0x00, 0x0C, 0x00, 0x06, number >> 8, number & 0xFF)); } // Set Terminal display
obj.intToStr = function (x) { return String.fromCharCode((x >> 24) & 0xFF, (x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF); } obj.intToStr = function (x) { return String.fromCharCode((x >> 24) & 0xFF, (x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF); }
obj.shortToStr = function (x) { return String.fromCharCode((x >> 8) & 0xFF, x & 0xFF); } obj.shortToStr = function (x) { return String.fromCharCode((x >> 8) & 0xFF, x & 0xFF); }

View File

@ -2,6 +2,7 @@ MeshCentral
=========== ===========
For more information, [visit MeshCommander.com/MeshCentral2](http://www.meshcommander.com/meshcentral2). For more information, [visit MeshCommander.com/MeshCentral2](http://www.meshcommander.com/meshcentral2).
Download the [full PDF user's guide](http://info.meshcentral.com/downloads/meshcentral2/MeshCentral2UserGuide.pdf) with more information on installing, configuring and running MeshCentral2.
This is a full computer management web site. With MeshCentral, you can run your own web server and it to remotely manage and control computers on a local network or anywhere on the internet. Once you get the server started, will create a mesh (a group of computers) and then download and install a mesh agent on each computer you want to manage. A minute later, the new computer will show up on the web site and you can take control of it, etc. MeshCentral includes full web-based remote desktop, terminal and file management capability. This is a full computer management web site. With MeshCentral, you can run your own web server and it to remotely manage and control computers on a local network or anywhere on the internet. Once you get the server started, will create a mesh (a group of computers) and then download and install a mesh agent on each computer you want to manage. A minute later, the new computer will show up on the web site and you can take control of it, etc. MeshCentral includes full web-based remote desktop, terminal and file management capability.

View File

@ -331,6 +331,9 @@
</tr> </tr>
<tr id=deskarea4> <tr id=deskarea4>
<td style="padding-top:2px;padding-bottom:2px;background:#C0C0C0"> <td style="padding-top:2px;padding-bottom:2px;background:#C0C0C0">
<div style="float:right;text-align:right">
<select id="termdisplays" style="display:none" onchange="deskSetDisplay(event)" onclick="deskGetDisplayNumbers(event)"></select>&nbsp;
</div>
<div> <div>
&nbsp; &nbsp;
<input id="DeskCAD" type="button" value="Ctrl-Alt-Del" onkeypress="return false" onkeydown="return false" onclick="sendCAD()">&nbsp; <input id="DeskCAD" type="button" value="Ctrl-Alt-Del" onkeypress="return false" onkeydown="return false" onclick="sendCAD()">&nbsp;
@ -773,7 +776,7 @@
xdr.open("HEAD", window.location.href); xdr.open("HEAD", window.location.href);
xdr.timeout = 15000; xdr.timeout = 15000;
xdr.onload = function () { reload(); }; xdr.onload = function () { reload(); };
xdr.onerror = xdr.ontimeout = function () { console.log('error'); setTimeout(serverPoll, 10000); }; xdr.onerror = xdr.ontimeout = function () { setTimeout(serverPoll, 10000); };
xdr.send(); xdr.send();
} }
@ -2917,6 +2920,7 @@
desktop.onStateChanged = onDesktopStateChange; desktop.onStateChanged = onDesktopStateChange;
desktop.m.CompressionLevel = desktopsettings.quality; // Number from 1 to 100. 50 or less is best. desktop.m.CompressionLevel = desktopsettings.quality; // Number from 1 to 100. 50 or less is best.
desktop.m.ScalingLevel = desktopsettings.scaling; desktop.m.ScalingLevel = desktopsettings.scaling;
desktop.m.onDisplayinfo = deskDisplayInfo;
desktop.Start(desktopNode._id); desktop.Start(desktopNode._id);
desktop.contype = 1; desktop.contype = 1;
} }
@ -2942,6 +2946,7 @@
delete desktop; delete desktop;
desktop = null; desktop = null;
QV('DeskFocus', false); QV('DeskFocus', false);
QV('termdisplays', false);
deskFocusBtn.value = 'All Focus'; deskFocusBtn.value = 'All Focus';
if (fullscreen == true) { deskToggleFull(); } if (fullscreen == true) { deskToggleFull(); }
break; break;
@ -3058,6 +3063,20 @@
Q("Desk")['toBlob'](function (blob) { saveAs(blob, n + ".jpg"); }); Q("Desk")['toBlob'](function (blob) { saveAs(blob, n + ".jpg"); });
} }
function deskDisplayInfo(sender, info, selDisplay, selItem) {
var txt = Q('termdisplays').value;
if (info.length > 0) { var options = ''; for (var x in info) { options += '<option' + ((txt == info[x])?' selected':'') + '>' + info[x] + '</option>'; } QH('termdisplays', options); }
QV('termdisplays', info.length > 0);
}
function deskGetDisplayNumbers(e) { desktop.m.GetDisplayNumbers(); }
function deskSetDisplay(e) {
var display = 0, txt = Q('termdisplays').value;
if (txt == "All Displays") display = 65535; else display = parseInt(txt.substring(8));
desktop.m.SetDisplay(display);
}
function dmousedown(e) { if (!xxdialogMode && desktop != null) desktop.m.mousedown(e) } function dmousedown(e) { if (!xxdialogMode && desktop != null) desktop.m.mousedown(e) }
function dmouseup(e) { if (!xxdialogMode && desktop != null) desktop.m.mouseup(e) } function dmouseup(e) { if (!xxdialogMode && desktop != null) desktop.m.mouseup(e) }
function dmousemove(e) { if (!xxdialogMode && desktop != null) desktop.m.mousemove(e) } function dmousemove(e) { if (!xxdialogMode && desktop != null) desktop.m.mousemove(e) }

View File

@ -67,6 +67,9 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
obj.users = {}; obj.users = {};
obj.meshes = {}; obj.meshes = {};
obj.userAllowedIp = args.userallowedip; // List of allowed IP addresses for users obj.userAllowedIp = args.userallowedip; // List of allowed IP addresses for users
obj.tlsSniCredentials;
obj.dnsDomains = {};
// Mesh Rights // Mesh Rights
const MESHRIGHT_EDITMESH = 1; const MESHRIGHT_EDITMESH = 1;
@ -84,8 +87,15 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
const SITERIGHT_FILEACCESS = 8; const SITERIGHT_FILEACCESS = 8;
const SITERIGHT_SERVERUPDATE = 16; const SITERIGHT_SERVERUPDATE = 16;
// Setup SSPI authentication if needed
if ((obj.parent.platform == 'win32') && (obj.args.nousers != true) && (obj.parent.config != null) && (obj.parent.config.domains != null)) {
for (var i in obj.parent.config.domains) { if (obj.parent.config.domains[i].auth == 'sspi') { var nodeSSPI = require('node-sspi'); obj.parent.config.domains[i].sspi = new nodeSSPI({ retrieveGroups: true, offerBasic: false }); } }
}
// Perform hash on web certificate and agent certificate // Perform hash on web certificate and agent certificate
obj.webCertificateHash = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.web.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' }); obj.webCertificateHash = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.web.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' });
obj.webCertificateHashs = { '': obj.webCertificateHash };
for (var i in obj.parent.config.domains) { if (obj.parent.config.domains[i].dns != null) { obj.webCertificateHashs[i] = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.parent.config.domains[i].certs.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' }); } }
obj.webCertificateHashBase64 = new Buffer(parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.web.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' }), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); obj.webCertificateHashBase64 = new Buffer(parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.web.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' }), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
obj.agentCertificateHashHex = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.agent.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'hex' }); obj.agentCertificateHashHex = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.agent.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'hex' });
obj.agentCertificateHashBase64 = new Buffer(parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.agent.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' }), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); obj.agentCertificateHashBase64 = new Buffer(parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.agent.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' }), 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
@ -112,6 +122,15 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
obj.crypto.randomBytes(16, function (err, buf) { obj.httpAuthRealm = buf.toString('hex'); }); obj.crypto.randomBytes(16, function (err, buf) { obj.httpAuthRealm = buf.toString('hex'); });
obj.crypto.randomBytes(48, function (err, buf) { obj.relayRandom = buf; }); obj.crypto.randomBytes(48, function (err, buf) { obj.relayRandom = buf; });
// Setup DNS domain TLS SNI credentials
{
var dnscount = 0;
obj.tlsSniCredentials = {};
for (var i in obj.certificates.dns) { if (obj.parent.config.domains[i].dns != null) { obj.dnsDomains[obj.parent.config.domains[i].dns.toLowerCase()] = obj.parent.config.domains[i]; obj.tlsSniCredentials[obj.parent.config.domains[i].dns] = obj.crypto.createCredentials(obj.certificates.dns[i]).context; dnscount++; } }
if (dnscount > 0) { obj.tlsSniCredentials[''] = obj.crypto.createCredentials({ cert: obj.certificates.web.cert, key: obj.certificates.web.key, ca: obj.certificates.ca }).context; } else { obj.tlsSniCredentials = null; }
}
function TlsSniCallback(name, cb) { var c = obj.tlsSniCredentials[name]; if (c != null) { cb(null, c); } else { cb(null, obj.tlsSniCredentials['']); } }
function EscapeHtml(x) { if (typeof x == "string") return x.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;'); if (typeof x == "boolean") return x; if (typeof x == "number") return x; } function EscapeHtml(x) { if (typeof x == "string") return x.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;'); if (typeof x == "boolean") return x; if (typeof x == "number") return x; }
function EscapeHtmlBreaks(x) { if (typeof x == "string") return x.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/\r/g, '<br />').replace(/\n/g, '').replace(/\t/g, '&nbsp;&nbsp;'); if (typeof x == "boolean") return x; if (typeof x == "number") return x; } function EscapeHtmlBreaks(x) { if (typeof x == "string") return x.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/\r/g, '<br />').replace(/\n/g, '').replace(/\t/g, '&nbsp;&nbsp;'); if (typeof x == "boolean") return x; if (typeof x == "number") return x; }
@ -120,9 +139,13 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
obj.expressWs = require('express-ws')(obj.app); obj.expressWs = require('express-ws')(obj.app);
} else { } else {
// Setup the HTTP server with TLS // Setup the HTTP server with TLS
//var certOperations = require('./certoperations.js').CertificateOperations(); if (obj.tlsSniCredentials != null) {
//var webServerCert = certOperations.GetWebServerCertificate('./data', 'SampleServer.org', 'US', 'SampleOrg'); // We have multiple web server certificate used depending on the domain name
obj.tlsServer = require('https').createServer({ cert: obj.certificates.web.cert, key: obj.certificates.web.key, ca: obj.certificates.calist, rejectUnauthorized: true }, obj.app); obj.tlsServer = require('https').createServer({ SNICallback: TlsSniCallback, cert: obj.certificates.web.cert, key: obj.certificates.web.key, ca: obj.certificates.ca, rejectUnauthorized: true }, obj.app);
} else {
// We have a single web server certificate
obj.tlsServer = require('https').createServer({ cert: obj.certificates.web.cert, key: obj.certificates.web.key, ca: obj.certificates.ca, rejectUnauthorized: true }, obj.app);
}
obj.expressWs = require('express-ws')(obj.app, obj.tlsServer); obj.expressWs = require('express-ws')(obj.app, obj.tlsServer);
} }
@ -245,9 +268,11 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
// Return the current domain of the request // Return the current domain of the request
function getDomain(req) { function getDomain(req) {
if (req.headers.host != null) { var d = obj.dnsDomains[req.headers.host.toLowerCase()]; if (d != null) return d; } // If this is a DNS name domain, return it here.
var x = req.url.split('/'); var x = req.url.split('/');
if (x.length < 2) return parent.config.domains['']; if (x.length < 2) return parent.config.domains[''];
if (parent.config.domains[x[1].toLowerCase()]) return parent.config.domains[x[1].toLowerCase()]; var d = parent.config.domains[x[1].toLowerCase()];
if ((d != null) && (d.dns == null)) return parent.config.domains[x[1].toLowerCase()];
return parent.config.domains['']; return parent.config.domains[''];
} }
@ -554,9 +579,23 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
if (domain == null) return; if (domain == null) return;
if (!obj.args) { res.sendStatus(500); return; } if (!obj.args) { res.sendStatus(500); return; }
var domain = getDomain(req); var domain = getDomain(req);
if ((domain.sspi != null) && ((req.query.login == null) || (obj.parent.loginCookieEncryptionKey == null))) {
// Login using SSPI
domain.sspi.authenticate(req, res, function (err) { if ((err != null) || (req.connection.user == null)) { res.end('Authentication Required...'); } else { handleRootRequestEx(req, res, domain); } })
} else {
// Login using a different system
handleRootRequestEx(req, res, domain);
}
}
function handleRootRequestEx(req, res, domain) {
var nologout = false;
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' }); res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
// Check if we have an incomplete domain name in the path // Check if we have an incomplete domain name in the path
if (domain.id != '' && req.url.split('/').length == 2) { res.redirect(domain.url); return; } if ((domain.id != '') && (domain.dns == null) && (req.url.split('/').length == 2)) { res.redirect(domain.url); return; }
if (obj.args.nousers == true) { if (obj.args.nousers == true) {
// If in single user mode, setup things here. // If in single user mode, setup things here.
if (req.session && req.session.loginmode) { delete req.session.loginmode; } if (req.session && req.session.loginmode) { delete req.session.loginmode; }
@ -583,7 +622,33 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
req.session.domainid = domain.id; req.session.domainid = domain.id;
req.session.currentNode = ''; req.session.currentNode = '';
} }
} else if (domain.sspi != null) {
// SSPI login (Windows only)
//console.log(req.connection.user, req.connection.userSid);
if ((req.connection.user == null) || (req.connection.userSid == null)) {
res.sendStatus(404); return;
} else {
nologout = true;
req.session.userid = 'user/' + domain.id + '/' + req.connection.user;
req.session.usersid = req.connection.userSid;
req.session.usersGroups = req.connection.userGroups;
req.session.domainid = domain.id;
req.session.currentNode = '';
// Check if this user exists, create it if not.
var user = obj.users[req.session.userid];
if ((user == null) || (user.sid != req.session.usersid)) {
// Create the domain user
var usercount = 0, user = { type: 'user', _id: req.session.userid, name: req.connection.user, domain: domain.id, sid: req.session.usersid };
for (var i in obj.users) { if (obj.users[i].domain == domain.id) { usercount++; } }
if (usercount == 0) { user.siteadmin = 0xFFFFFFFF; } // If this is the first user, give the account site admin.
obj.users[req.session.userid] = user;
obj.db.SetUser(user);
obj.parent.DispatchEvent(['*', 'server-users'], obj, { etype: 'user', username: req.connection.user, account: user, action: 'accountcreate', msg: 'Domain account created, user ' + req.connection.user, domain: domain.id })
} }
}
}
// If a user is logged in, serve the default app, otherwise server the login app. // If a user is logged in, serve the default app, otherwise server the login app.
if (req.session && req.session.userid) { if (req.session && req.session.userid) {
if (req.session.domainid != domain.id) { req.session.destroy(function () { res.redirect(domain.url); }); return; } // Check is the session is for the correct domain if (req.session.domainid != domain.id) { req.session.destroy(function () { res.redirect(domain.url); }); return; } // Check is the session is for the correct domain
@ -613,16 +678,16 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
if (obj.args.nousers == true) { features += 4; } // Single user mode if (obj.args.nousers == true) { features += 4; } // Single user mode
if (domain.userQuota == -1) { features += 8; } // No server files mode if (domain.userQuota == -1) { features += 8; } // No server files mode
if (obj.args.tlsoffload == true) { features += 16; } // No mutual-auth CIRA if (obj.args.tlsoffload == true) { features += 16; } // No mutual-auth CIRA
if (parent.config.settings.allowFraming == true) { features += 32; } // Allow site within iframe if ((parent.config != null) && (parent.config.settings != null) && (parent.config.settings.allowFraming == true)) { features += 32; } // Allow site within iframe
if ((!obj.args.user) && (obj.args.nousers != true)) { logoutcontrol += ' <a href=' + domain.url + 'logout?' + Math.random() + ' style=color:white>Logout</a>'; } // If a default user is in use or no user mode, don't display the logout button if ((!obj.args.user) && (obj.args.nousers != true) && (nologout == false)) { logoutcontrol += ' <a href=' + domain.url + 'logout?' + Math.random() + ' style=color:white>Logout</a>'; } // If a default user is in use or no user mode, don't display the logout button
res.render(obj.path.join(__dirname, 'views/default'), { viewmode: viewmode, currentNode: currentNode, logoutControl: logoutcontrol, title: domain.title, title2: domain.title2, domainurl: domain.url, domain: domain.id, debuglevel: parent.debugLevel, serverDnsName: obj.certificates.CommonName, serverRedirPort: args.redirport, serverPublicPort: args.port, noServerBackup: (args.noserverbackup == 1 ? 1 : 0), features: features, mpspass: args.mpspass, webcerthash: obj.webCertificateHashBase64 }); res.render(obj.path.join(__dirname, 'views/default'), { viewmode: viewmode, currentNode: currentNode, logoutControl: logoutcontrol, title: domain.title, title2: domain.title2, domainurl: domain.url, domain: domain.id, debuglevel: parent.debugLevel, serverDnsName: getWebServerName(domain), serverRedirPort: args.redirport, serverPublicPort: args.port, noServerBackup: (args.noserverbackup == 1 ? 1 : 0), features: features, mpspass: args.mpspass, webcerthash: obj.webCertificateHashBase64 });
} else { } else {
// Send back the login application // Send back the login application
var loginmode = req.session.loginmode; var loginmode = req.session.loginmode;
delete req.session.loginmode; // Clear this state, if the user hits refresh, we want to go back to the login page. delete req.session.loginmode; // Clear this state, if the user hits refresh, we want to go back to the login page.
var features = 0; var features = 0;
if (parent.config.settings.allowFraming == true) { features += 32; } // Allow site within iframe if ((parent.config != null) && (parent.config.settings != null) && (parent.config.settings.allowFraming == true)) { features += 32; } // Allow site within iframe
res.render(obj.path.join(__dirname, 'views/login'), { loginmode: loginmode, rootCertLink: getRootCertLink(), title: domain.title, title2: domain.title2, newAccount: domain.newaccounts, newAccountPass: (((domain.newaccountspass == null) || (domain.newaccountspass == '')) ? 0 : 1), serverDnsName: obj.certificates.CommonName, serverPublicPort: obj.args.port, emailcheck: obj.parent.mailserver != null, features: features }); res.render(obj.path.join(__dirname, 'views/login'), { loginmode: loginmode, rootCertLink: getRootCertLink(), title: domain.title, title2: domain.title2, newAccount: domain.newaccounts, newAccountPass: (((domain.newaccountspass == null) || (domain.newaccountspass == '')) ? 0 : 1), serverDnsName: getWebServerName(domain), serverPublicPort: obj.args.port, emailcheck: obj.parent.mailserver != null, features: features });
} }
} }
@ -1377,7 +1442,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
debugLevel: 0 debugLevel: 0
} }
if (user != null) { meshaction.username = user.name; } if (user != null) { meshaction.username = user.name; }
if (obj.args.lanonly != true) { meshaction.serverUrl = ((obj.args.notls == true) ? 'ws://' : 'wss://') + obj.certificates.CommonName + ':' + obj.args.port + '/' + ((domain.id == '') ? '' : ('/' + domain.id)) + 'meshrelay.ashx'; } if (obj.args.lanonly != true) { meshaction.serverUrl = ((obj.args.notls == true) ? 'ws://' : 'wss://') + getWebServerName(domain) + ':' + obj.args.port + '/' + ((domain.id == '') ? '' : ('/' + domain.id)) + 'meshrelay.ashx'; }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename=meshaction.txt' }); res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename=meshaction.txt' });
res.send(JSON.stringify(meshaction, null, ' ')); res.send(JSON.stringify(meshaction, null, ' '));
}); });
@ -1391,7 +1456,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
debugLevel: 0 debugLevel: 0
} }
if (user != null) { meshaction.username = user.name; } if (user != null) { meshaction.username = user.name; }
if (obj.args.lanonly != true) { meshaction.serverUrl = ((obj.args.notls == true) ? 'ws://' : 'wss://') + obj.certificates.CommonName + ':' + obj.args.port + '/' + ((domain.id == '') ? '' : ('/' + domain.id)) + 'meshrelay.ashx'; } if (obj.args.lanonly != true) { meshaction.serverUrl = ((obj.args.notls == true) ? 'ws://' : 'wss://') + getWebServerName(domain) + ':' + obj.args.port + '/' + ((domain.id == '') ? '' : ('/' + domain.id)) + 'meshrelay.ashx'; }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename=meshaction.txt' }); res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename=meshaction.txt' });
res.send(JSON.stringify(meshaction, null, ' ')); res.send(JSON.stringify(meshaction, null, ' '));
} else { } else {
@ -1413,6 +1478,12 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
} }
} }
// Get the web server hostname. This may change if using a domain with a DNS name.
function getWebServerName(domain) {
if (domain.dns != null) return domain.dns;
return obj.certificates.CommonName;
}
// Handle a request to download a mesh settings // Handle a request to download a mesh settings
obj.handleMeshSettingsRequest = function (req, res) { obj.handleMeshSettingsRequest = function (req, res) {
var domain = checkUserIpAddress(req, res); var domain = checkUserIpAddress(req, res);
@ -1432,10 +1503,11 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
var meshidhex = new Buffer(req.query.id.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase(); var meshidhex = new Buffer(req.query.id.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
var serveridhex = new Buffer(obj.agentCertificateHashBase64.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase(); var serveridhex = new Buffer(obj.agentCertificateHashBase64.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
var xdomain = domain.id; // Build the agent connection URL. If we are using a sub-domain or one with a DNS, we need to craft the URL correctly.
var xdomain = (domain.dns == null) ? domain.id : '';
if (xdomain != '') xdomain += "/"; if (xdomain != '') xdomain += "/";
var meshsettings = "MeshName=" + mesh.name + "\r\nMeshType=" + mesh.mtype + "\r\nMeshID=0x" + meshidhex + "\r\nServerID=" + serveridhex + "\r\n"; var meshsettings = "MeshName=" + mesh.name + "\r\nMeshType=" + mesh.mtype + "\r\nMeshID=0x" + meshidhex + "\r\nServerID=" + serveridhex + "\r\n";
if (obj.args.lanonly != true) { meshsettings += "MeshServer=ws" + (obj.args.notls ? '' : 's') + "://" + certificates.CommonName + ":" + obj.args.port + "/" + xdomain + "agent.ashx\r\n"; } else { meshsettings += "MeshServer=local"; } if (obj.args.lanonly != true) { meshsettings += "MeshServer=ws" + (obj.args.notls ? '' : 's') + "://" + getWebServerName(domain) + ":" + obj.args.port + "/" + xdomain + "agent.ashx\r\n"; } else { meshsettings += "MeshServer=local"; }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=meshagent.msh' }); res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=meshagent.msh' });
res.send(meshsettings); res.send(meshsettings);
@ -1489,7 +1561,7 @@ module.exports.CreateWebServer = function (parent, db, args, secret, certificate
obj.app.ws(url + 'meshrelay.ashx', function (ws, req) { try { obj.meshRelayHandler.CreateMeshRelay(obj, ws, req, getDomain(req)); } catch (e) { console.log(e); } }); obj.app.ws(url + 'meshrelay.ashx', function (ws, req) { try { obj.meshRelayHandler.CreateMeshRelay(obj, ws, req, getDomain(req)); } catch (e) { console.log(e); } });
// Receive mesh agent connections // Receive mesh agent connections
obj.app.ws(url + 'agent.ashx', function (ws, req) { try { var domain = getDomain(req); obj.meshAgentHandler.CreateMeshAgent(obj, obj.db, ws, req, obj.args, domain); } catch (e) { console.log(e); } }); obj.app.ws(url + 'agent.ashx', function (ws, req) { try { obj.meshAgentHandler.CreateMeshAgent(obj, obj.db, ws, req, obj.args, getDomain(req)); } catch (e) { console.log(e); } });
obj.app.get(url + 'stop', function (req, res) { res.send('Stopping Server, <a href="' + url + '">click here to login</a>.'); setTimeout(function () { parent.Stop(); }, 500); }); obj.app.get(url + 'stop', function (req, res) { res.send('Stopping Server, <a href="' + url + '">click here to login</a>.'); setTimeout(function () { parent.Stop(); }, 500); });