Removed meshcmd actions: amtacm, amtscript, amtdiscover.
Ylian Saint-Hilaire committed
Oct 29, 2020 at 12:59 UTC
06f0f8cb432260a90ff831d0ea2ea5b1bfc4c95d
4 files changed
+33
-742
agents/MeshCmd-signed.exe
Binary files a/agents/MeshCmd-signed.exe and b/agents/MeshCmd-signed.exe differ
agents/MeshCmd64-signed.exe
Binary files a/agents/MeshCmd64-signed.exe and b/agents/MeshCmd64-signed.exe differ
agents/meshcmd.js
+33
-341
@@ -113,7 +113,7 @@ function run(argv) {
113
//console.log('addedModules = ' + JSON.stringify(addedModules));
114
var actionpath = 'meshaction.txt';
115
if (args.actionfile != null) { actionpath = args.actionfile; }
116
- var actions = ['HELP', 'ROUTE', 'MICROLMS', 'AMTCONFIG', 'AMTSCAN', 'AMTPOWER', 'AMTFEATURES', 'AMTNETWORK', 'AMTLOADWEBAPP', 'AMTLOADSMALLWEBAPP', 'AMTLOADLARGEWEBAPP', 'AMTCLEARWEBAPP', 'AMTSTORAGESTATE', 'AMTINFO', 'AMTINFODEBUG', 'AMTVERSIONS', 'AMTHASHES', 'AMTSAVESTATE', 'AMTSCRIPT', 'AMTUUID', 'AMTCCM', 'AMTACM', 'AMTDEACTIVATE', 'AMTACMDEACTIVATE', 'SMBIOS', 'RAWSMBIOS', 'MESHCOMMANDER', 'AMTAUDITLOG', 'AMTEVENTLOG', 'AMTPRESENCE', 'AMTWIFI', 'AMTWAKE'];
116
+ var actions = ['HELP', 'ROUTE', 'MICROLMS', 'AMTCONFIG', 'AMTSCAN', 'AMTPOWER', 'AMTFEATURES', 'AMTNETWORK', 'AMTLOADWEBAPP', 'AMTLOADSMALLWEBAPP', 'AMTLOADLARGEWEBAPP', 'AMTCLEARWEBAPP', 'AMTSTORAGESTATE', 'AMTINFO', 'AMTINFODEBUG', 'AMTVERSIONS', 'AMTHASHES', 'AMTSAVESTATE', 'AMTUUID', 'AMTCCM', 'AMTDEACTIVATE', 'AMTACMDEACTIVATE', 'SMBIOS', 'RAWSMBIOS', 'MESHCOMMANDER', 'AMTAUDITLOG', 'AMTEVENTLOG', 'AMTPRESENCE', 'AMTWIFI', 'AMTWAKE'];
117
118
// Load the action file
119
var actionfile = null;
@@ -133,7 +133,6 @@ function run(argv) {
133
if ((typeof args.username) == 'string') { settings.username = args.username; }
134
if ((typeof args.password) == 'string') { settings.password = args.password; }
135
if ((typeof args.url) == 'string') { settings.url = args.url; }
136
- if ((typeof args.profile) == 'string') { settings.profile = args.profile; }
136
if ((typeof args.type) == 'string') { settings.type = args.type; }
137
if ((typeof args.user) == 'string') { settings.username = args.user; }
138
if ((typeof args.pass) == 'string') { settings.password = args.pass; }
@@ -184,7 +183,6 @@ function run(argv) {
183
console.log(' AmtVersions - Show all Intel ME version information.');
184
console.log(' AmtHashes - Show all Intel AMT trusted activation hashes.');
185
console.log(' AmtCCM - Activate Intel AMT into Client Control Mode.');
187
- console.log(' AmtACM - Activate Intel AMT into Admin Control Mode.');
186
console.log(' AmtDeactivate - Deactivate Intel AMT if activated in Client Control mode.');
187
console.log(' AmtAcmDeactivate - Deactivate Intel AMT if activated in Admin Control mode.');
188
console.log('\r\nValid local or remote actions:');
@@ -198,7 +196,6 @@ function run(argv) {
196
console.log(' AmtSaveState - Save all Intel AMT WSMAN object to file.');
197
console.log(' AmtPresence - Heartbeat a local Intel AMT watchdog agent.');
198
console.log(' AmtPower - Perform remote Intel AMT power operation.');
201
- console.log(' AmtScript - Run .mescript on Intel AMT.');
199
console.log(' AmtIDER - Mount local disk image to remote computer.');
200
console.log(' AmtFeatures - Intel AMT features & user consent.');
201
console.log(' AmtNetwork - Intel AMT network interface settings.');
@@ -242,24 +239,12 @@ function run(argv) {
239
console.log('AmtCCM will attempt to activate Intel AMT on this computer into client control mode (CCM). The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. Intel AMT must be in "pre-provisioning" state for this command to work and a administrator password must be provided.');
240
console.log('\r\nPossible arguments:\r\n');
241
console.log(' --password [password] Admin password used to activate Intel AMT.');
245
- console.log('\r\nor:\r\n');
246
- console.log(' --url [wss://server] Url to the activation server.');
247
- console.log(' --tag [string] Optional string sent to the server during activation.');
248
- console.log(' --serverhttpshash [hash] Optional TLS server certificate hash.');
249
- console.log(' --profile [string] Optional profile used for server activation.');
242
} else if (action == 'amtconfig') {
243
console.log('AmtConfig will attempt to activate and configure Intel AMT on this computer. The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. Example usage:\r\n\r\n meshcmd amtconfig --url [url]');
244
console.log('\r\nPossible arguments:\r\n');
245
console.log(' --url [wss://server] The address of the MeshCentral server.');
246
console.log(' --id [groupid] The device group identifier.');
247
console.log(' --serverhttpshash [hash] Optional TLS server certificate hash.');
256
- } else if (action == 'amtacm') {
257
- console.log('AmtACM will attempt to activate Intel AMT on this computer into admin control mode (ACM). The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. Intel AMT must be in "pre-provisioning" state for this command to work. Example usage:\r\n\r\n meshcmd amtacm --url [url]');
258
- console.log('\r\nPossible arguments:\r\n');
259
- console.log(' --url [wss://server] The address of the Intel AMT activation server.');
260
- console.log(' --tag [string] Optional string sent to the server during activation.');
261
- console.log(' --serverhttpshash [hash] Optional TLS server certificate hash.');
262
- console.log(' --profile [string] Optional profile used for server activation.');
248
} else if (action == 'amtdeactivate') {
249
console.log('AmtDeactivate will attempt to deactivate Intel AMT on this computer when in client control mode (CCM). The command must be run on a computer with Intel AMT, must run as administrator and the Intel management driver must be installed. Intel AMT must be activated in client control mode for this command to work. Example usage:\r\n\r\n meshcmd amtdeactivate');
250
} else if (action == 'amtacmdeactivate') {
@@ -310,14 +295,6 @@ function run(argv) {
295
console.log(' --user [username] The Intel AMT login username, admin is default.');
296
console.log(' --pass [password] The Intel AMT login password.');
297
console.log(' --agent [uuid] The unique identifier of the watchdog agent.');
313
- } else if (action == 'amtscript') {
314
- console.log('AmtScript will run a .mescript file on the local or remote Intel AMT. Script files can be built using the MeshCommander script editor and be used to setup or perform actions on Intel AMT. Example usage:\r\n\r\n meshcmd amtscript --script myscript.mescript --host 1.2.3.4 --user admin --pass mypassword --tls');
315
- console.log('\r\nPossible arguments:\r\n');
316
- console.log(' --script [filename] The script file to run on Intel AMT.');
317
- console.log(' --host [hostname] The IP address or DNS name of Intel AMT, 127.0.0.1 is default.');
318
- console.log(' --user [username] The Intel AMT login username, admin is default.');
319
- console.log(' --pass [password] The Intel AMT login password.');
320
- console.log(' --tls Specifies that TLS must be used.');
298
} else if (action == 'amtpower') {
299
console.log('AmtPower will get current pwoer state or send a reboot command to a remote Intel AMT device. Example usage:\r\n\r\n meshcmd amtpower --reset --host 1.2.3.4 --user admin --pass mypassword --tls');
300
console.log('\r\nRequired arguments:\r\n');
@@ -413,7 +390,7 @@ function run(argv) {
390
console.log(' --auth Wifi Authentication method (4 - WPA, 6 - WPA2/RSN) - default 6');
391
console.log(' --enc Wifi Encryption type (3 - TKIP, 4 - CCMP) - default 3');
392
console.log(' --psk Wifi password/pre-shared key');
416
- console.log(' --del [profile-name] Delete new Wifi profile');
393
+ console.log(' --del [profile-name] Delete new Wifi profile');
394
} else if (action == 'amtwake') {
395
console.log('AmtWake is used to view/set/remote Intel AMT Wake Alarms. Example usage:\r\n\r\n meshcmd amtwake --host 1.2.3.4 --user admin --pass mypassword --list');
396
console.log('\r\nRequired arguments:\r\n');
@@ -622,14 +599,6 @@ function run(argv) {
599
if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { settings.username = 'admin'; }
600
if ((settings.agent == null) || (typeof settings.agent != 'string') || (settings.agent == '')) { console.log('No or invalid \"agent\" specified, use --agent [agent].'); exit(1); return; }
601
performAmtAgentPresence();
625
- } else if (settings.action == 'amtscript') {
626
- // Start running a MEScript
627
- if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
628
- if ((settings.hostname == null) || (typeof settings.hostname != 'string') || (settings.hostname == '')) { settings.hostname = '127.0.0.1'; }
629
- if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { settings.username = 'admin'; }
630
- //if ((settings.script == null) || (typeof settings.script != 'string') || (settings.script == '')) { if (mescriptJSON != '') { settings.scriptjson = mescriptJSON; } else { console.log('No or invalid \"script\" file specified, use --script [filename].'); exit(1); return; } }
631
- if ((settings.script == null) || (typeof settings.script != 'string') || (settings.script == '')) { console.log('No or invalid \"script\" file specified, use --script [filename].'); exit(1); return; }
632
- startMeScript();
602
} else if (settings.action == 'amtuuid') {
603
// Start running
604
if (settings.hostname != null) {
@@ -648,23 +617,11 @@ function run(argv) {
617
configureAmt();
618
} else if (settings.action == 'amtccm') {
619
// Start activation to CCM
651
- if (((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) && ((settings.url == null) || (typeof settings.url != 'string') || (settings.url == ''))) { console.log('No or invalid parameters specified, use --password [password] or --url [url].'); exit(1); return; }
652
- if ((typeof settings.profile != 'string') || (settings.profile == '')) { settings.profile = null; }
620
+ if (((settings.password == null) || (typeof settings.password != 'string') || (settings.password == ''))) { console.log('No or invalid parameters specified, use --password [password] or --url [url].'); exit(1); return; }
621
settings.protocol = 'http:';
622
settings.localport = 16992;
623
debug(1, "Settings: " + JSON.stringify(settings));
656
- if (settings.password != null) { activeToCCM(); } else { activeToACM(); }
657
- } else if (settings.action == 'amtacm') {
658
- // Start activation to ACM
659
- if ((settings.url == null) || (typeof settings.url != 'string') || (settings.url == '')) { console.log('No activation server URL specified, use --url [url].'); exit(1); return; }
660
- if ((typeof settings.profile != 'string') || (settings.profile == '')) { settings.profile = null; }
661
- debug(1, "Settings: " + JSON.stringify(settings));
662
- activeToACM();
663
- } else if (settings.action == 'amtdiscover') {
664
- // Intel AMT server discovery, tell the server the state of Intel AMT.
665
- if ((settings.url == null) || (typeof settings.url != 'string') || (settings.url == '')) { console.log('No activation server URL specified, use --url [url].'); exit(1); return; }
666
- debug(1, "Settings: " + JSON.stringify(settings));
667
- activeToACM();
624
+ activeToCCM();
625
} else if (settings.action == 'amtdeactivate') {
626
// Deactivate CCM
627
debug(1, "Settings: " + JSON.stringify(settings));
@@ -712,7 +669,7 @@ function run(argv) {
669
} else { settings.hostname = '127.0.0.1'; }
670
readAmtAuditLog();
671
} else if (settings.action == 'amteventlog') { // Read the Intel AMT audit log
715
- if (settings.hostname != null) {
672
+ if (settings.hostname != null) {
673
if ((settings.password == null) || (typeof settings.password != 'string') || (settings.password == '')) { console.log('No or invalid \"password\" specified, use --password [password].'); exit(1); return; }
674
if ((settings.username == null) || (typeof settings.username != 'string') || (settings.username == '')) { settings.username = 'admin'; }
675
} else { settings.hostname = '127.0.0.1'; }
@@ -739,7 +696,7 @@ function run(argv) {
696
if ((args.ssid == null) || (typeof args.ssid != 'string') || args.ssid == '') { console.log("Wifi SSID is required."); exit(1); return; }
697
if ((args.psk == null) || (typeof args.psk != 'string') || args.psk == '') { console.log("Wifi password is required."); exit(1); return; }
698
}
742
- if (args.del !=null) {
699
+ if (args.del != null) {
700
if ((settings.name == null) || (typeof settings.name != 'string') || settings.name == '') { console.log("Wifi profile name is required."); exit(1); return; }
701
}
702
performAmtWifiConfig(args);
@@ -938,7 +895,7 @@ function readAmtEventLogEx2(stack, messages) {
895
} exit(1);
896
});
897
}
941
- else{
898
+ else {
899
console.log('Invalid action, usage:\r\n\r\n meshcmd help amtauditlog');
900
exit(1);
901
}
@@ -1017,7 +974,7 @@ function readAmtAuditLogEx2(stack, response, status) {
974
} exit(1);
975
});
976
}
1020
- else{
977
+ else {
978
console.log('Invalid action, usage:\r\n\r\n meshcmd help amtauditlog');
979
exit(1);
980
}
@@ -1238,7 +1195,6 @@ function activeToCCMEx3(stack, name, responses, status) {
1195
1196
1197
1241
-
1198
//
1199
// Deactivate Intel AMT ACM
1200
//
@@ -1304,229 +1260,6 @@ function getTrustedHashes(amtMei, func, tag) {
1260
});
1261
}
1262
1307
-//
1308
-// Activate Intel AMT to with server (ACM or CCM)
1309
-//
1310
-
1311
-function activeToACM() {
1312
- console.log('Starting Intel AMT activation attempt...');
1313
- settings.noconsole = true;
1314
-
1315
- // Display Intel AMT version and activation state
1316
- mestate = {};
1317
- var amtMeiModule, amtMei;
1318
- try { amtMeiModule = require('amt-mei'); amtMei = new amtMeiModule(); } catch (ex) { console.log(ex); exit(1); return; }
1319
- amtMei.on('error', function (e) { console.log('ERROR: ' + e); exit(1); return; });
1320
- try {
1321
- amtMei.getProvisioningState(function (result) { if (result) { mestate.ProvisioningState = result; } });
1322
- amtMei.getVersion(function (val) { mestate.vers = {}; if (val != null) { for (var version in val.Versions) { mestate.vers[val.Versions[version].Description] = val.Versions[version].Version; } } });
1323
- amtMei.getLanInterfaceSettings(0, function (result) { if (result) { mestate.net0 = result; } });
1324
- amtMei.getUuid(function (result) { if ((result != null) && (result.uuid != null)) { mestate.uuid = result.uuid; } });
1325
- amtMei.getControlMode(function (result) { if (result != null) { mestate.controlMode = result.controlMode; } }); // controlMode: 0 = NoActivated, 1 = CCM, 2 = ACM
1326
- amtMei.getDnsSuffix(function (result) {
1327
- if ((mestate.vers == null) || (mestate.vers['AMT'] == null)) { console.log("Unable to get Intel AMT version."); exit(100); return; }
1328
- if (mestate.ProvisioningState == null) { console.log("Unable to read Intel AMT activation state."); exit(100); return; }
1329
- if ((settings.action != 'amtdiscover') && (mestate.controlMode == 2)) { console.log("Intel AMT already activation in admin control mode."); exit(100); return; }
1330
- if (mestate.uuid == null) { console.log("Unable to get Intel AMT UUID."); exit(100); return; }
1331
- var fqdn = null;
1332
- if ((mestate.net0 == null) && (meinfo.net0.enabled != 0)) { console.log("No Intel AMT wired interface, can't perform ACM activation."); exit(100); return; }
1333
- if (result) { fqdn = result; } // If Intel AMT has a trusted DNS suffix set, use that one.
1334
- else {
1335
- // Look for the DNS suffix for the Intel AMT Ethernet interface
1336
- var interfaces = require('os').networkInterfaces();
1337
- for (var i in interfaces) {
1338
- for (var j in interfaces[i]) {
1339
- if ((interfaces[i][j].mac == mestate.net0.mac) && (interfaces[i][j].fqdn != null) && (interfaces[i][j].fqdn != '')) { fqdn = interfaces[i][j].fqdn; }
1340
- }
1341
- }
1342
- }
1343
- if (fqdn != null) {
1344
- settings.fqdn = fqdn;
1345
- settings.uuid = mestate.uuid;
1346
- getTrustedHashes(amtMei, function () { startLms(getFwNonce, amtMei); });
1347
- } else {
1348
- console.log("Trusted DNS suffix not set, can't perform ACM activation."); exit(100); return;
1349
- }
1350
- });
1351
- } catch (ex) { console.log("Unable to perform MEI operations, try running as administrator."); exit(1); return; }
1352
-}
1353
-
1354
-// Gets the FWNonce from AMT and saves it to a file.
1355
-function getFwNonce() {
1356
- osamtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], function (stack, name, responses, status) {
1357
- if (status != 200) { console.log("Unable to get firmware activation nonce, status=" + status); exit(100); return; }
1358
- var fwNonce = responses['IPS_HostBasedSetupService'].response['ConfigurationNonce'];
1359
- var digestRealm = responses['AMT_GeneralSettings'].response['DigestRealm'];
1360
- var allowedModes = responses['IPS_HostBasedSetupService'].response['AllowedControlModes']; // 1 = CCM, 2 = ACM
1361
- activeToACMEx(fwNonce, settings.fqdn, digestRealm, settings.uuid, allowedModes);
1362
- });
1363
-}
1364
-
1365
-// Connect to the activation server and perform ACM activation
1366
-function activeToACMEx(fwNonce, dnsSuffix, digestRealm, uuid, allowedModes) {
1367
- console.log('FQDN: ' + dnsSuffix);
1368
- console.log('UUID: ' + uuid);
1369
- console.log('Realm: ' + digestRealm);
1370
- console.log('Nonce: ' + fwNonce);
1371
- console.log('Connecting to ' + settings.url);
1372
-
1373
- // Establish WebSocket connection to activation server
1374
- var options = http.parseUri(settings.url);
1375
- options.checkServerIdentity = onVerifyServer;
1376
- options.rejectUnauthorized = false;
1377
- var connection = http.request(options);
1378
- connection.on('upgrade', function (response, socket) {
1379
- settings.xxsocket = socket;
1380
- if (settings.action == 'amtdiscover') { console.log('Connected, performing discovery...'); } else { console.log('Connected, requesting activation...'); }
1381
- socket.on('end', function () { console.log('Connection closed'); exit(0); });
1382
- socket.on('error', function () { console.log('Connection error'); exit(100); });
1383
- socket.on('data', function (data) {
1384
- // Parse and check the response
1385
- var cmd = null;
1386
- try { cmd = JSON.parse(data); } catch (ex) { console.log('Unable to parse server response: ' + data); exit(100); return; }
1387
- if (typeof cmd != 'object') { console.log('Invalid server response: ' + cmd); exit(100); return; }
1388
- if (typeof cmd.errorText == 'string') { console.log('Server error: ' + cmd.errorText); exit(100); return; }
1389
- if (typeof cmd.messageText == 'string') { console.log('Server: ' + cmd.messageText); return; }
1390
- switch (cmd.action) {
1391
- case 'acmactivate': {
1392
- // Server responded with ACM activation response
1393
- if (typeof cmd.signature != 'string') { console.log('Invalid server signature'); exit(100); return; }
1394
- if (typeof cmd.password != 'string') { console.log('Invalid server password'); exit(100); return; }
1395
- if (typeof cmd.nonce != 'string') { console.log('Invalid server nonce'); exit(100); return; }
1396
- if (typeof cmd.certs != 'object') { console.log('Invalid server certificates'); exit(100); return; }
1397
- settings.xxprofileScript = cmd.profileScript;
1398
- settings.xxrawpassword = cmd.rawpassword;
1399
-
1400
- cmd.index = 0;
1401
- // If we are in CCM mode, deactivate.
1402
- if (mestate.controlMode == 1) {
1403
- amtMei.unprovision(1, function (status) {
1404
- if (status == 0) {
1405
- console.log('Intel AMT CCM deactivated, holding 10 seconds...');
1406
- // We are ready to go, perform ACM activation.
1407
- settings.xxTimer = setTimeout(function () { performAcmActivation(cmd, AcmActivationCompleted); }, 10000);
1408
- } else {
1409
- console.log('Intel AMT CCM deactivation error ' + status); exit(1); return;
1410
- }
1411
- });
1412
- } else {
1413
- // We are ready to go, perform ACM activation.
1414
- performAcmActivation(cmd, AcmActivationCompleted);
1415
- }
1416
- break;
1417
- }
1418
- case 'ccmactivate': {
1419
- // Server responded with CCM activation response
1420
- if (typeof cmd.password != 'string') { console.log('Invalid server password'); exit(100); return; }
1421
- settings.xxprofileScript = cmd.profileScript;
1422
- settings.xxrawpassword = cmd.rawpassword;
1423
-
1424
- // If we are already in CCM mode, deactivate.
1425
- if (mestate.controlMode == 1) {
1426
- amtMei.unprovision(1, function (status) {
1427
- if (status == 0) {
1428
- console.log('Intel AMT CCM deactivated, holding 10 seconds...');
1429
- // We are ready to go, perform CCM activation.
1430
- settings.xxTimer = setTimeout(function () { osamtstack.IPS_HostBasedSetupService_Setup(2, cmd.password, null, null, null, null, performCcmActivation); }, 10000);
1431
- } else {
1432
- console.log('Intel AMT CCM deactivation error ' + status); exit(1); return;
1433
- }
1434
- });
1435
- } else {
1436
- // We are ready to go, perform CCM activation.
1437
- osamtstack.IPS_HostBasedSetupService_Setup(2, cmd.password, null, null, null, null, performCcmActivation);
1438
- }
1439
- break;
1440
- }
1441
- case 'amtdiscover': {
1442
- console.log('Done.');
1443
- exit(0);
1444
- break;
1445
- }
1446
- default: {
1447
- console.log('Invalid server response, command: ' + cmd.action); exit(100);
1448
- break;
1449
- }
1450
- }
1451
- });
1452
-
1453
- var action = 'acmactivate';
1454
- if (settings.action == 'amtccm') { action = 'ccmactivate'; }
1455
- if (settings.action == 'amtdiscover') { action = 'amtdiscover'; }
1456
- socket.write({ client: 'meshcmd', version: 1, action: action, fqdn: dnsSuffix, realm: digestRealm, nonce: fwNonce, uuid: uuid, profile: settings.profile, hashes: trustedHashes, tag: settings.tag, name: settings.name, ver: mestate.vers['AMT'], build: mestate.vers['Build Number'], sku: parseInt(mestate.vers['Sku']), modes: allowedModes, currentMode: mestate.controlMode, hostname: require('os').hostname() });
1457
- });
1458
- connection.end();
1459
-}
1460
-
1461
-function performCcmActivation(stack, name, responses, status) {
1462
- if (status != 200) {
1463
- settings.xxsocket.write({ client: 'meshcmd', version: 1, action: 'ccmactivate-failed', uuid: mestate.uuid });
1464
- console.log('Failed to activate, status ' + status);
1465
- } else if (responses.Body.ReturnValue != 0) {
1466
- settings.xxsocket.write({ client: 'meshcmd', version: 1, action: 'ccmactivate-failed', uuid: mestate.uuid });
1467
- console.log('Intel AMT CCM activation failed: ' + responses.Body.ReturnValueStr);
1468
- } else {
1469
- settings.xxsocket.write({ client: 'meshcmd', version: 1, action: 'ccmactivate-success', uuid: mestate.uuid });
1470
- if ((settings.xxprofileScript !== null) && (settings.xxrawpassword != null)) {
1471
- console.log("Intel AMT CCM activation success, applying profile...");
1472
- settings.scriptjson = settings.xxprofileScript;
1473
- settings.password = settings.xxrawpassword; // This is only going to work if the server sends the raw password
1474
- settings.username = 'admin';
1475
- startMeScriptEx(function () { console.log('Intel AMT profile applied.'); socket.end(); exit(0); }, stack);
1476
- return;
1477
- } else {
1478
- console.log('Intel AMT CCM activation success.');
1479
- settings.xxsocket.end();
1480
- exit(0);
1481
- return;
1482
- }
1483
- }
1484
- settings.xxsocket.end();
1485
- exit(1);
1486
-}
1487
-
1488
-function AcmActivationCompleted(result) {
1489
- if (result == false) {
1490
- console.log('Intel AMT ACM activation failed.');
1491
- settings.xxsocket.write({ client: 'meshcmd', version: 1, action: 'acmactivate-failed', uuid: mestate.uuid });
1492
- settings.xxsocket.end();
1493
- exit(1);
1494
- } else {
1495
- if ((settings.xxprofileScript !== null) && (settings.xxrawpassword != null)) {
1496
- console.log('Intel AMT ACM activation success, applying profile...');
1497
- settings.scriptjson = settings.xxprofileScript;
1498
- settings.password = settings.xxrawpassword; // This is only going to work if the server sends the raw password
1499
- settings.username = 'admin';
1500
- startMeScriptEx(function () { console.log('Intel AMT profile applied.'); settings.xxsocket.end(); exit(0); }, stack);
1501
- } else {
1502
- console.log('Intel AMT ACM activation success.');
1503
- settings.xxsocket.write({ client: 'meshcmd', version: 1, action: 'acmactivate-success', uuid: mestate.uuid });
1504
- settings.xxsocket.end();
1505
- exit(0);
1506
- }
1507
- }
1508
-}
1509
-
1510
-// Recursive function to inject the provisioning certificates into AMT in the proper order and completes ACM activation
1511
-function performAcmActivation(acmdata, func) {
1512
- var leaf = (acmdata.index == 0), root = (acmdata.index == (acmdata.certs.length - 1));
1513
- if ((acmdata.index < acmdata.certs.length) && (acmdata.certs[acmdata.index] != null)) {
1514
- osamtstack.IPS_HostBasedSetupService_AddNextCertInChain(acmdata.certs[acmdata.index], leaf, root, function (stack, name, responses, status) {
1515
- if (status !== 200) { console.log('AddNextCertInChain error, status=' + status); exit(1); return; }
1516
- else if (responses['Body']['ReturnValue'] !== 0) { console.log('AddNextCertInChain error: ' + responses['Body']['ReturnValue']); exit(1); return; }
1517
- else { acmdata.index++; performAcmActivation(acmdata, func); }
1518
- });
1519
- } else {
1520
- //console.log(acmdata.password, acmdata.nonce, acmdata.signature);
1521
- osamtstack.IPS_HostBasedSetupService_AdminSetup(2, acmdata.password, acmdata.nonce, 2, acmdata.signature,
1522
- function (stack, name, responses, status) {
1523
- if (status !== 200) { console.log('Error, AdminSetup status: ' + status); }
1524
- else if (responses['Body']['ReturnValue'] != 0) { console.log('Error, AdminSetup return value: ' + responses['Body']['ReturnValue']); }
1525
- func((status == 200) && (responses['Body']['ReturnValue'] == 0));
1526
- }
1527
- );
1528
- }
1529
-}
1263
1264
//
1265
// Get AMT UUID
@@ -1557,45 +1290,6 @@ function getAmtUuidEx() {
1290
}
1291
1292
1560
-//
1561
-// Run MESCRIPT
1562
-//
1563
-
1564
-// Run a .mescript targeting local or remote Intel AMT.
1565
-function startMeScript() {
1566
- // See if MicroLMS needs to be started
1567
- if ((settings.hostname == '127.0.0.1') || (settings.hostname.toLowerCase() == 'localhost')) { settings.noconsole = true; startLms(startMeScriptEx); return; } else { startMeScriptEx(); }
1568
-}
1569
-
1570
-function startMeScriptEx(callback, amtstack) {
1571
- //console.log('Running script...');
1572
- var transport = require('amt-wsman-duk');
1573
- var wsman = require('amt-wsman');
1574
- var amt = require('amt');
1575
- if (!wsstack) { wsstack = new wsman(transport, settings.hostname, settings.tls ? 16993 : 16992, settings.username, settings.password, settings.tls); }
1576
- if (!amtstack) { amtstack = new amt(wsstack); }
1577
- //IntelAmtEntireStateProgress = 101;
1578
- //amtstack.onProcessChanged = onWsmanProcessChanged;
1579
-
1580
- var scriptData = null;
1581
- if (settings.script != null) {
1582
- try { scriptData = fs.readFileSync(settings.script); } catch (e) { console.log('Unable to read script file (1): ' + settings.script + '.'); exit(1); return; }
1583
- } else {
1584
- scriptData = settings.scriptjson;
1585
- }
1586
- if (scriptData == null) { console.log('Unable to read script file (2): ' + settings.script + '.'); exit(1); return; }
1587
- try { scriptData = JSON.parse(scriptData); } catch (e) { console.log('Unable to read script file (3): ' + settings.script + '.'); exit(1); return; }
1588
- if (scriptData.mescript == null) { console.log('Unable to read script file (4): ' + settings.script + '.'); exit(1); return; }
1589
- var scriptData = Buffer.from(scriptData.mescript, 'base64');
1590
-
1591
- var scriptModule = require('amt-script');
1592
- var script = scriptModule.setup(scriptData, {})
1593
- script.amtstack = amtstack;
1594
- script.start();
1595
- script.onCompleted = function () { if (callback) { callback(); } exit(1); }
1596
-}
1597
-
1598
-
1293
//
1294
// FETCH ALL INTEL AMT STATE
1295
//
@@ -1616,7 +1310,6 @@ function saveEntireAmtState2() {
1310
amtstack.BatchEnum(null, AllWsman, saveEntireAmtStateOk2, null, true);
1311
amtstack.GetAuditLog(saveEntireAmtStateOk3);
1312
amtstack.GetMessageLog(saveEntireAmtStateOk4);
1619
-
1313
}
1314
1315
// Save the entire Intel AMT state
@@ -1625,8 +1318,7 @@ function saveEntireAmtState() {
1318
if ((settings.hostname == '127.0.0.1') || (settings.hostname.toLowerCase() == 'localhost')) {
1319
settings.noconsole = true;
1320
startLms().then(saveEntireAmtState2);
1628
- }
1629
- else {
1321
+ } else {
1322
saveEntireAmtState2();
1323
}
1324
}
@@ -2633,31 +2325,31 @@ function performAmtWifiConfig0(state, args) {
2325
}
2326
2327
function performAmtWifiConfig1(stack, name, response, status, args) {
2636
- if ( status == 200 ) {
2637
- var wifiAuthMethod = {1: "Other", 2: "Open", 3: "Shared Key", 4: "WPA PSK", 5: "WPA 802.1x", 6: "WPA2 PSK", 7: "WPA2 802.1x", 32768 : "WPA3 802.1x"};
2638
- var wifiEncMethod = {1: "Other", 2: "WEP", 3: "TKIP", 4: "CCMP", 5: "None"}
2328
+ if (status == 200) {
2329
+ var wifiAuthMethod = { 1: "Other", 2: "Open", 3: "Shared Key", 4: "WPA PSK", 5: "WPA 802.1x", 6: "WPA2 PSK", 7: "WPA2 802.1x", 32768: "WPA3 802.1x" };
2330
+ var wifiEncMethod = { 1: "Other", 2: "WEP", 3: "TKIP", 4: "CCMP", 5: "None" }
2331
var wifiProfiles = {};
2332
for (var y in response['CIM_WiFiEndpointSettings'].responses) {
2333
var z = response['CIM_WiFiEndpointSettings'].responses[y];
2334
var n = z['ElementName'];
2643
- wifiProfiles[n]= {'Priority': z['Priority'], 'SSID':z['SSID'],'AuthenticationMethod': z['AuthenticationMethod'], 'EncryptionMethod': z['EncryptionMethod']};
2335
+ wifiProfiles[n] = { 'Priority': z['Priority'], 'SSID': z['SSID'], 'AuthenticationMethod': z['AuthenticationMethod'], 'EncryptionMethod': z['EncryptionMethod'] };
2336
}
2337
2338
if (args) {
2339
if (args.list) {
2340
console.log('List of Intel AMT Wifi profiles:');
2649
- if (wifiProfiles.length==0) {
2341
+ if (wifiProfiles.length == 0) {
2342
console.log('No Wifi profiles is stored.');
2343
}
2344
for (var t in wifiProfiles) {
2345
var w = wifiProfiles[t];
2654
- console.log('Profile Name: '+t+'; Priority: '+w['Priority']+ '; SSID: '+w['SSID']+'; Security: '+wifiAuthMethod[w['AuthenticationMethod']]+'/'+wifiEncMethod[w['EncryptionMethod']]);
2346
+ console.log('Profile Name: ' + t + '; Priority: ' + w['Priority'] + '; SSID: ' + w['SSID'] + '; Security: ' + wifiAuthMethod[w['AuthenticationMethod']] + '/' + wifiEncMethod[w['EncryptionMethod']]);
2347
}
2348
process.exit(0);
2349
} else if (args.add) {
2658
- if (args.auth==null) {args.auth=6}//if not set, default to WPA2 PSK
2659
- if (args.enc==null) {args.enc=3}//if not set, default to TKIP
2660
- if (args.priority==null) {args.priority=0}//if not set, default to 0
2350
+ if (args.auth == null) { args.auth = 6; } // if not set, default to WPA2 PSK
2351
+ if (args.enc == null) { args.enc = 3; } // if not set, default to TKIP
2352
+ if (args.priority == null) { args.priority = 0; } // if not set, default to 0
2353
2354
var wifiep = {
2355
__parameterType: 'reference',
@@ -2670,40 +2362,40 @@ function performAmtWifiConfig1(stack, name, response, status, args) {
2362
__namespace: 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpointSettings',
2363
ElementName: args.name,
2364
InstanceID: 'Intel(r) AMT:WiFi Endpoint Settings ' + args.name,
2673
- AuthenticationMethod: args.auth,
2365
+ AuthenticationMethod: args.auth,
2366
EncryptionMethod: args.enc,
2367
SSID: args.ssid,
2368
Priority: args.priority,
2369
PSKPassPhrase: args.psk
2678
- }
2679
- stack.AMT_WiFiPortConfigurationService_AddWiFiSettings(wifiep, wifiepsettinginput, null, null, null,
2680
- function(stck, nm, resp, sts) {
2681
- if (sts==200) {
2370
+ }
2371
+ stack.AMT_WiFiPortConfigurationService_AddWiFiSettings(wifiep, wifiepsettinginput, null, null, null,
2372
+ function (stck, nm, resp, sts) {
2373
+ if (sts == 200) {
2374
console.log("Wifi profile " + args.name + " successfully added.");
2375
} else {
2376
console.log("Failed to add wifi profile " + args.name + ".");
2377
}
2378
process.exit(0);
2687
- });
2379
+ });
2380
} else if (args.del) {
2689
- if (wifiProfiles[args.name]==null) {
2690
- console.log("Profile "+args.name+" could not be found.");
2381
+ if (wifiProfiles[args.name] == null) {
2382
+ console.log("Profile " + args.name + " could not be found.");
2383
process.exit(0);
2384
}
2693
- stack.Delete('CIM_WiFiEndpointSettings', { InstanceID : 'Intel(r) AMT:WiFi Endpoint Settings ' + args.name },
2694
- function(stck, nm, resp, sts){
2695
- if (sts==200) {
2385
+ stack.Delete('CIM_WiFiEndpointSettings', { InstanceID: 'Intel(r) AMT:WiFi Endpoint Settings ' + args.name },
2386
+ function (stck, nm, resp, sts) {
2387
+ if (sts == 200) {
2388
console.log("Wifi profile " + args.name + " successfully deleted.");
2389
} else {
2390
console.log("Failed to delete wifi profile " + args.name + ".");
2391
}
2392
process.exit(0);
2701
- },
2702
- 0, 1);
2393
+ },
2394
+ 0, 1);
2395
}
2396
} else {
2397
process.exit(0);
2706
- }
2398
+ }
2399
} else {
2400
console.log("Error, status " + status + ".");
2401
process.exit(1);
@@ -2787,7 +2479,7 @@ function performAmtWakeConfig1(stack, name, response, status, args) {
2479
if (sts == 200) { console.log("Done."); } else { console.log("Failed to delete wake alarm " + args.del + "."); }
2480
process.exit(0);
2481
},
2790
- 0, 1);
2482
+ 0, 1);
2483
} else if (args.add) {
2484
// Add a wake alarm
2485
var alarmFound = false;
agents/modules_meshcmd/amt-script.js
deleted
-401
@@ -1,401 +0,0 @@
1
-/*
2
-Copyright 2018-2020 Intel Corporation
3
-
4
-Licensed under the Apache License, Version 2.0 (the "License");
5
-you may not use this file except in compliance with the License.
6
-You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
-Unless required by applicable law or agreed to in writing, software
11
-distributed under the License is distributed on an "AS IS" BASIS,
12
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
-See the License for the specific language governing permissions and
14
-limitations under the License.
15
-*/
16
-
17
-/**
18
-* @fileoverview Script Compiler / Decompiler / Runner
19
-* @author Ylian Saint-Hilaire
20
-* @version v0.1.0e
21
-*/
22
-
23
-// Core functions
24
-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'];
25
-
26
-// functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
27
-script_functionTable2 = ['encodeuri', 'decodeuri', 'passwordcheck', 'atob', 'btoa', 'hex2str', 'str2hex', 'random', 'md5', 'maketoarray', 'readshort', 'readshortx', 'readint', 'readsint', 'readintx', 'shorttostr', 'shorttostrx', 'inttostr', 'inttostrx'];
28
-
29
-// functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
30
-script_functionTableX2 = [encodeURI, decodeURI, passwordcheck, atob, btoa, hex2rstr, rstr2hex, random, rstr_md5, MakeToArray, ReadShort, ReadShortX, ReadInt, ReadSInt, ReadIntX, ShortToStr, ShortToStrX, IntToStr, IntToStrX];
31
-
32
-
33
-function MakeToArray(v) { if (!v || v == null || typeof v == 'object') return v; return [v]; }
34
-function ReadShort(v, p) { return (v[p] << 8) + v[p + 1]; }
35
-function ReadShortX(v, p) { return (v[p + 1] << 8) + v[p]; }
36
-function ReadInt(v, p) { return (v[p] * 0x1000000) + (v[p + 1] << 16) + (v[p + 2] << 8) + v[p + 3]; } // We use "*0x1000000" instead of "<<24" because the shift converts the number to signed int32.
37
-function ReadSInt(v, p) { return (v[p] << 24) + (v[p + 1] << 16) + (v[p + 2] << 8) + v[p + 3]; }
38
-function ReadIntX(v, p) { return (v[p + 3] * 0x1000000) + (v[p + 2] << 16) + (v[p + 1] << 8) + v[p]; }
39
-function ShortToStr(v) { return String.fromCharCode((v >> 8) & 0xFF, v & 0xFF); }
40
-function ShortToStrX(v) { return String.fromCharCode(v & 0xFF, (v >> 8) & 0xFF); }
41
-function IntToStr(v) { return String.fromCharCode((v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF); }
42
-function IntToStrX(v) { return String.fromCharCode(v & 0xFF, (v >> 8) & 0xFF, (v >> 16) & 0xFF, (v >> 24) & 0xFF); }
43
-//function ShortToStr(v) { var b = Buffer.alloc(2); b.writeInt16BE(v); return b; }
44
-//function ShortToStrX(v) { var b = Buffer.alloc(2); b.writeInt16LE(v); return b; }
45
-//function IntToStr(v) { var b = Buffer.alloc(4); b.writeInt32BE(v); return b; }
46
-//function IntToStrX(v) { var b = Buffer.alloc(4); b.writeInt32LE(v); return b; }
47
-function btoa(x) { return Buffer.from(x).toString('base64');}
48
-function atob(x) { var z = null; try { z = Buffer.from(x, 'base64').toString(); } catch (e) { console.log(e); } return z; }
49
-function passwordcheck(p) { if (p.length < 8) return false; var upper = 0, lower = 0, number = 0, nonalpha = 0; for (var i in p) { var c = p.charCodeAt(i); if ((c > 64) && (c < 91)) { upper = 1; } else if ((c > 96) && (c < 123)) { lower = 1; } else if ((c > 47) && (c < 58)) { number = 1; } else { nonalpha = 1; } } return ((upper + lower + number + nonalpha) == 4); }
50
-function hex2rstr(x) { Buffer.from(x, 'hex').toString(); }
51
-function rstr2hex(x) { Buffer.from(x).toString('hex'); }
52
-function random() { return Math.floor(Math.random()*max); }
53
-function rstr_md5(str) { return hex2rstr(hex_md5(str)); }
54
-function getItem(x, y, z) { for (var i in x) { if (x[i][y] == z) return x[i]; } return null; }
55
-
56
-var httpErrorTable = {
57
- 200: 'OK',
58
- 401: 'Authentication Error',
59
- 408: 'Timeout Error',
60
- 601: 'WSMAN Parsing Error',
61
- 602: 'Unable to parse HTTP response header',
62
- 603: 'Unexpected HTTP enum response',
63
- 604: 'Unexpected HTTP pull response',
64
- 998: 'Invalid TLS certificate'
65
-}
66
-
67
-// Setup the script state
68
-module.exports.setup = function(binary, startvars) {
69
- var obj = { startvars: startvars, onCompleted: null };
70
- if (binary.length < 6) { console.error('Invalid script length'); return null; } // Script must have at least 6 byte header
71
- if (ReadInt(binary, 0) != 0x247D2945) { console.error('Invalid binary script'); return null; } // Check the script magic header
72
- if (ReadShort(binary, 4) > 1) { console.error('Unsupported script version'); return null; } // Check the script version
73
- obj.script = binary.slice(6);
74
-
75
- // Reset the script to the start
76
- obj.reset = function (stepspeed) {
77
- obj.stop();
78
- obj.ip = 0;
79
- obj.variables = startvars;
80
- obj.state = 1;
81
- }
82
-
83
- // Start the script
84
- obj.start = function (stepspeed) {
85
- obj.stop();
86
- if (stepspeed == null) { obj.stepspeed = 10; } else { obj.stepspeed = stepspeed; }
87
- if (obj.stepspeed > 0) { obj.timer = setInterval(function () { obj.step() }, obj.stepspeed); }
88
- }
89
-
90
- // Stop the script
91
- obj.stop = function () {
92
- if (obj.timer != null) { clearInterval(obj.timer); }
93
- obj.timer = null;
94
- obj.stepspeed = 0;
95
- }
96
-
97
- // function used to load and store variable values
98
- obj.getVar = function (name) { if (name == undefined) return undefined; return obj.getVarEx(name.split('.'), obj.variables); }
99
- 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; } }
100
- obj.setVar = function (name, val) { obj.setVarEx(name.split('.'), obj.variables, val); }
101
- obj.setVarEx = function (name, vars, val) { if (name.length == 1) { vars[name[0]] = val; } else { obj.setVarEx(name.slice(1), vars[name[0]], val); } }
102
-
103
- // Run the script one step forward
104
- obj.step = function () {
105
- if (obj.state != 1) return;
106
- if (obj.ip < obj.script.length) {
107
- var cmdid = ReadShort(obj.script, obj.ip);
108
- var cmdlen = ReadShort(obj.script, obj.ip + 2);
109
- var argcount = ReadShort(obj.script, obj.ip + 4);
110
- var argptr = obj.ip + 6;
111
- var args = [];
112
-
113
- // Clear all temp variables (This is optional)
114
- for (var i in obj.variables) { if (i.startsWith('__')) { delete obj.variables[i]; } }
115
-
116
- // Loop on each argument, moving forward by the argument length each time
117
- for (var i = 0; i < argcount; i++) {
118
- var arglen = ReadShort(obj.script, argptr);
119
- var argval = obj.script.slice(argptr + 2, argptr + 2 + arglen);
120
- var argtyp = argval[0];
121
- argval = argval.slice(1);
122
- if (argtyp < 2) {
123
- // Get the value and replace all {var} with variable values
124
- argval = argval.toString();
125
- if (argval != null) { while (argval.split("{").length > 1) { var t = argval.split("{").pop().split("}").shift(); argval = argval.replace('{' + t + '}', obj.getVar(t)); } }
126
- if (argtyp == 1) { obj.variables['__' + i] = decodeURI(argval); argval = '__' + i; } // If argtyp is 1, this is a literal. Store in temp variable.
127
- args.push(argval);
128
- }
129
- if (argtyp == 2 || argtyp == 3) {
130
- obj.variables['__' + i] = ReadSInt(argval, 0);
131
- args.push('__' + i);
132
- }
133
- argptr += (2 + arglen);
134
- }
135
-
136
- // Move instruction pointer forward by command size
137
- obj.ip += cmdlen;
138
-
139
- // Get all variable values
140
- var argsval = [];
141
- for (var i = 0; i < 10; i++) { argsval.push(obj.getVar(args[i])); }
142
- var storeInArg0;
143
- try {
144
- if (cmdid < 10000) {
145
- // Lets run the actual command
146
- switch (cmdid) {
147
- case 0: // nop
148
- break;
149
- case 1: // jump(label) or jump(label, a, compare, b)
150
- if (argsval[2]) {
151
- if (
152
- (argsval[2] == '<' && argsval[1] < argsval[3]) ||
153
- (argsval[2] == '<=' && argsval[1] <= argsval[3]) ||
154
- (argsval[2] == '!=' && argsval[1] != argsval[3]) ||
155
- (argsval[2] == '=' && argsval[1] == argsval[3]) ||
156
- (argsval[2] == '>=' && argsval[1] >= argsval[3]) ||
157
- (argsval[2] == '>' && argsval[1] > argsval[3])
158
- ) {
159
- obj.ip = argsval[0];
160
- }
161
- } else {
162
- obj.ip = argsval[0]; // Set the instruction pointer to the new location in the script
163
- }
164
- break;
165
- case 2: // set(variable, value)
166
- if (args[1] == undefined) delete obj.variables[args[0]]; else obj.setVar(args[0], argsval[1]);
167
- break;
168
- case 3: // print(message)
169
- var v = obj.toString(argsval[0]);
170
- if (v.indexOf('INFO: ') == 0) { v = v.substring(6); }
171
- if (v.indexOf('SUCCESS: ') == 0) { v = v.substring(9); }
172
- if (obj.onConsole) { obj.onConsole(v, obj); } else { console.log(v); }
173
- // Q(obj.consoleid).value += () + '\n'); Q(obj.console).scrollTop = Q(obj.console).scrollHeight;
174
- break;
175
- case 4: // dialog(title, content, buttons)
176
- obj.state = 2;
177
- obj.dialog = true;
178
- setDialogMode(11, argsval[0], argsval[2], obj.xxStepDialogOk, argsval[1], obj);
179
- break;
180
- case 5: // getitem(a, b, c)
181
- for (var i in argsval[1]) { if (argsval[1][i][argsval[2]] == argsval[3]) { storeInArg0 = i; } };
182
- break;
183
- case 6: // substr(variable_dest, variable_src, index, len)
184
- storeInArg0 = argsval[1].substr(argsval[2], argsval[3]);
185
- break;
186
- case 7: // indexOf(variable_dest, variable_src, index, len)
187
- storeInArg0 = argsval[1].indexOf(argsval[2]);
188
- break;
189
- case 8: // split(variable_dest, variable_src, separator)
190
- storeInArg0 = argsval[1].split(argsval[2]);
191
- break;
192
- case 9: // join(variable_dest, variable_src, separator)
193
- storeInArg0 = argsval[1].join(argsval[2]);
194
- break;
195
- case 10: // length(variable_dest, variable_src)
196
- if (argsval[1] == null) { storeInArg0 = 0; } else { storeInArg0 = argsval[1].length; }
197
- break;
198
- case 11: // jsonparse(variable_dest, json)
199
- storeInArg0 = JSON.parse(argsval[1]);
200
- break;
201
- case 12: // jsonstr(variable_dest, variable_src)
202
- storeInArg0 = JSON.stringify(argsval[1]);
203
- break;
204
- case 13: // add(variable_dest, variable_src, value)
205
- storeInArg0 = (argsval[1] + argsval[2]);
206
- break;
207
- case 14: // substract(variable_dest, variable_src, value)
208
- storeInArg0 = (argsval[1] - argsval[2]);
209
- break;
210
- case 15: // parseInt(variable_dest, variable_src)
211
- storeInArg0 = parseInt(argsval[1]);
212
- break;
213
- case 16: // wsbatchenum(name, objectList)
214
- obj.state = 2;
215
- obj.amtstack.BatchEnum(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
216
- break;
217
- case 17: // wsput(name, args)
218
- obj.state = 2;
219
- obj.amtstack.Put(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
220
- break;
221
- case 18: // wscreate(name, args)
222
- obj.state = 2;
223
- obj.amtstack.Create(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
224
- break;
225
- case 19: // wsdelete(name, args)
226
- obj.state = 2;
227
- obj.amtstack.Delete(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
228
- break;
229
- case 20: // wsexec(name, method, args, selectors)
230
- obj.state = 2;
231
- obj.amtstack.Exec(argsval[0], argsval[1], argsval[2], obj.xxWsmanReturn, obj, 0, argsval[3]);
232
- break;
233
- case 21: // Script Speed
234
- obj.stepspeed = argsval[0];
235
- if (obj.timer != null) { clearInterval(obj.timer); obj.timer = setInterval(function () { obj.step() }, obj.stepspeed); }
236
- break;
237
- case 22: // wssubscribe(name, delivery, url, selectors, opaque, user, pass)
238
- obj.state = 2;
239
- obj.amtstack.Subscribe(argsval[0], argsval[1], argsval[2], obj.xxWsmanReturn, obj, 0, argsval[3], argsval[4], argsval[5], argsval[6]);
240
- break;
241
- case 23: // wsunsubscribe(name, selectors)
242
- obj.state = 2;
243
- obj.amtstack.UnSubscribe(argsval[0], obj.xxWsmanReturn, obj, 0, argsval[1]);
244
- break;
245
- case 24: // readchar(str, pos)
246
- console.log(argsval[1], argsval[2], argsval[1].charCodeAt(argsval[2]));
247
- storeInArg0 = argsval[1].charCodeAt(argsval[2]);
248
- break;
249
- case 25: // signWithDummyCa
250
- // Not supported
251
- break;
252
- default: {
253
- obj.state = 9;
254
- console.error("Script Error, unknown command: " + cmdid);
255
- }
256
- }
257
- } else {
258
- if (cmdid < 20000) {
259
- // functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
260
- storeInArg0 = script_functionTableX2[cmdid - 10000](argsval[1], argsval[2], argsval[3], argsval[4], argsval[5], argsval[6]);
261
- } else {
262
- // Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
263
- //if (script_functionTableX3 && script_functionTableX3[cmdid - 20000]) {
264
- // 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.
265
- //}
266
- }
267
- }
268
- if (storeInArg0 != undefined) obj.setVar(args[0], storeInArg0);
269
- } catch (e) {
270
- if (typeof e == 'object') { e = e.message; }
271
- obj.setVar('_exception', e);
272
- }
273
- }
274
-
275
- if (obj.state == 1 && obj.ip >= obj.script.length) { obj.state = 0; obj.stop(); if (obj.onCompleted) { obj.onCompleted(); } }
276
- if (obj.onStep) obj.onStep(obj);
277
- return obj;
278
- }
279
-
280
- obj.xxStepDialogOk = function (button) {
281
- obj.variables['DialogSelect'] = button;
282
- obj.state = 1;
283
- obj.dialog = false;
284
- if (obj.onStep) obj.onStep(obj);
285
- }
286
-
287
- obj.xxWsmanReturn = function (stack, name, responses, status) {
288
- obj.setVar(name, responses);
289
- obj.setVar('wsman_result', status);
290
- obj.setVar('wsman_result_str', ((httpErrorTable[status]) ? (httpErrorTable[status]) : ('Error #' + status)));
291
- obj.state = 1;
292
- if (obj.onStep) obj.onStep(obj);
293
- }
294
-
295
- obj.toString = function (x) { if (typeof x == 'object') return JSON.stringify(x); return x; }
296
-
297
- obj.reset();
298
- return obj;
299
-}
300
-
301
-// Argument types: 0 = Variable, 1 = String, 2 = Integer, 3 = Label
302
-module.exports.compile = function(script, onmsg) {
303
- var r = '', scriptlines = script.split('\n'), labels = {}, labelswap = [], swaps = [];
304
- // Go thru each script line and encode it
305
- for (var i in scriptlines) {
306
- var scriptline = scriptlines[i];
307
- if (scriptline.startsWith('##SWAP ')) { var x = scriptline.split(' '); if (x.length == 3) { swaps[x[1]] = x[2]; } } // Add a swap instance
308
- if (scriptline[0] == '#' || scriptline.length == 0) continue; // Skip comments & blank lines
309
- for (var x in swaps) { scriptline = scriptline.split(x).join(swaps[x]); } // Apply all swaps
310
- var keywords = scriptline.match(/"[^"]*"|[^\s"]+/g);
311
- if (keywords.length == 0) continue; // Skip blank lines
312
- if (scriptline[0] == ':') { labels[keywords[0].toUpperCase()] = r.length; continue; } // Mark a label position
313
- var funcIndex = script_functionTable1.indexOf(keywords[0].toLowerCase());
314
- if (funcIndex == -1) { funcIndex = script_functionTable2.indexOf(keywords[0].toLowerCase()); if (funcIndex >= 0) funcIndex += 10000; }
315
- if (funcIndex == -1) { if (onmsg) { onmsg("Unabled to compile, unknown command: " + keywords[0]); } return ''; }
316
- // Encode CommandId, CmdSize, ArgCount, Arg1Len, Arg1, Arg2Len, Arg2...
317
- var cmd = ShortToStr(keywords.length - 1);
318
- for (var j in keywords) {
319
- if (j == 0) continue;
320
- if (keywords[j][0] == ':') {
321
- labelswap.push([keywords[j], r.length + cmd.length + 7]); // Add a label swap
322
- cmd += ShortToStr(5) + String.fromCharCode(3) + IntToStr(0xFFFFFFFF); // Put an empty label
323
- } else {
324
- var argint = parseInt(keywords[j]);
325
- if (argint == keywords[j]) {
326
- cmd += ShortToStr(5) + String.fromCharCode(2) + IntToStr(argint);
327
- } else {
328
- if (keywords[j][0] == '"' && keywords[j][keywords[j].length - 1] == '"') {
329
- cmd += ShortToStr(keywords[j].length - 1) + String.fromCharCode(1) + keywords[j].substring(1, keywords[j].length - 1);
330
- } else {
331
- cmd += ShortToStr(keywords[j].length + 1) + String.fromCharCode(0) + keywords[j];
332
- }
333
- }
334
- }
335
- }
336
- cmd = ShortToStr(funcIndex) + ShortToStr(cmd.length + 4) + cmd;
337
- r += cmd;
338
- }
339
- // Perform all the needed label swaps
340
- for (i in labelswap) {
341
- var label = labelswap[i][0].toUpperCase(), position = labelswap[i][1], target = labels[label];
342
- if (target == undefined) { if (onmsg) { onmsg("Unabled to compile, unknown label: " + label); } return ''; }
343
- r = r.substr(0, position) + IntToStr(target) + r.substr(position + 4);
344
- }
345
- return IntToStr(0x247D2945) + ShortToStr(1) + r;
346
-}
347
-
348
-// Decompile the script, intended for debugging only
349
-module.exports.decompile = function(binary, onecmd) {
350
- var r = '', ptr = 6, labelcount = 0, labels = {};
351
- if (onecmd >= 0) {
352
- ptr = onecmd; // If we are decompiling just one command, set the ptr to that command.
353
- } else {
354
- if (binary.length < 6) { return '# Invalid script length'; }
355
- var magic = ReadInt(binary, 0);
356
- var version = ReadShort(binary, 4);
357
- if (magic != 0x247D2945) { return '# Invalid binary script: ' + magic; }
358
- if (version != 1) { return '# Invalid script version'; }
359
- }
360
- // Loop on each command, moving forward by the command length each time.
361
- while (ptr < binary.length) {
362
- var cmdid = ReadShort(binary, ptr);
363
- var cmdlen = ReadShort(binary, ptr + 2);
364
- var argcount = ReadShort(binary, ptr + 4);
365
- var argptr = ptr + 6;
366
- var argstr = '';
367
- if (!(onecmd >= 0)) r += ":label" + (ptr - 6) + "\n";
368
- // Loop on each argument, moving forward by the argument length each time
369
- for (var i = 0; i < argcount; i++) {
370
- var arglen = ReadShort(binary, argptr);
371
- var argval = binary.substring(argptr + 2, argptr + 2 + arglen);
372
- var argtyp = argval.charCodeAt(0);
373
- if (argtyp == 0) { argstr += ' ' + argval.substring(1); } // Variable
374
- else if (argtyp == 1) { argstr += ' \"' + argval.substring(1) + '\"'; } // String
375
- else if (argtyp == 2) { argstr += ' ' + ReadInt(argval, 1); } // Integer
376
- else if (argtyp == 3) { // Label
377
- var target = ReadInt(argval, 1);
378
- var label = labels[target];
379
- if (!label) { label = ":label" + target; labels[label] = target; }
380
- argstr += ' ' + label;
381
- }
382
- argptr += (2 + arglen);
383
- }
384
- // Go in the script function table to decode the function
385
- if (cmdid < 10000) {
386
- r += script_functionTable1[cmdid] + argstr + "\n";
387
- } else {
388
- if ((cmdid >= 10000) && (cmdid < 10000)) { r += script_functionTable2[cmdid - 10000] + argstr + "\n"; }
389
- }
390
- ptr += cmdlen;
391
- if (onecmd >= 0) return r; // If we are decompiling just one command, exit now
392
- }
393
- // Remove all unused labels
394
- var scriptlines = r.split('\n');
395
- r = '';
396
- for (var i in scriptlines) {
397
- var line = scriptlines[i];
398
- if (line[0] != ':') { r += line + '\n'; } else { if (labels[line]) { r += line + '\n'; } }
399
- }
400
- return r;
401
-}