amt-script-0.2.0.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /**
  2. * @fileoverview Script Compiler / Decompiler / Runner
  3. * @author Ylian Saint-Hilaire
  4. * @version v0.1.0e
  5. */
  6. // Core functions
  7. 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'];
  8. // functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  9. script_functionTable2 = ['encodeuri', 'decodeuri', 'passwordcheck', 'atob', 'btoa', 'hex2str', 'str2hex', 'random', 'md5', 'maketoarray', 'readshort', 'readshortx', 'readint', 'readsint', 'readintx', 'shorttostr', 'shorttostrx', 'inttostr', 'inttostrx'];
  10. // functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  11. 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];
  12. // Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  13. script_functionTable3 = ['pullsystemstatus', 'pulleventlog', 'pullauditlog', 'pullcertificates', 'pullwatchdog', 'pullsystemdefense', 'pullhardware', 'pulluserinfo', 'pullremoteaccess', 'highlightblock', 'disconnect', 'getsidstring', 'getsidbytearray'];
  14. // Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  15. script_functionTableX3 = [
  16. PullSystemStatus
  17. ,
  18. // ###BEGIN###{EventLog}
  19. PullEventLog
  20. // ###END###{EventLog}
  21. ,
  22. // ###BEGIN###{AuditLog}
  23. PullAuditLog
  24. // ###END###{AuditLog}
  25. ,
  26. // ###BEGIN###{Certificates}
  27. PullCertificates
  28. // ###END###{Certificates}
  29. ,
  30. // ###BEGIN###{AgentPresence}
  31. PullWatchdog
  32. // ###END###{AgentPresence}
  33. ,
  34. // ###BEGIN###{SystemDefense}
  35. PullSystemDefense
  36. // ###END###{SystemDefense}
  37. ,
  38. // ###BEGIN###{HardwareInfo}
  39. PullHardware
  40. // ###END###{HardwareInfo}
  41. ,
  42. PullUserInfo
  43. ,
  44. // ###BEGIN###{RemoteAccess}
  45. PullRemoteAccess
  46. // ###END###{RemoteAccess}
  47. ,
  48. // ###BEGIN###{Scripting-Editor}
  49. script_HighlightBlock
  50. // ###END###{Scripting-Editor}
  51. ,
  52. // ###BEGIN###{ComputerSelector}
  53. disconnect
  54. // ###END###{ComputerSelector}
  55. ,
  56. function (runner, x) { return GetSidString(x); }
  57. ,
  58. function (runner, x) { return GetSidByteArray(x); }
  59. ];
  60. // Setup the script state
  61. function script_setup(binary, startvars) {
  62. var obj = { startvars:startvars };
  63. if (binary.length < 6) { console.error('Invalid script length'); return null; } // Script must have at least 6 byte header
  64. if (ReadInt(binary, 0) != 0x247D2945) { console.error('Invalid binary script'); return null; } // Check the script magic header
  65. if (ReadShort(binary, 4) > 1) { console.error('Unsupported script version'); return null; } // Check the script version
  66. obj.script = binary.substring(6);
  67. // obj.onStep;
  68. // obj.onConsole;
  69. // Reset the script to the start
  70. obj.reset = function (stepspeed) {
  71. obj.stop();
  72. obj.ip = 0;
  73. obj.variables = startvars;
  74. obj.state = 1;
  75. }
  76. // Start the script
  77. obj.start = function (stepspeed) {
  78. obj.stop();
  79. obj.stepspeed = stepspeed;
  80. if (stepspeed > 0) { obj.timer = setInterval(function () { obj.step() }, stepspeed); }
  81. }
  82. // Stop the script
  83. obj.stop = function () {
  84. if (obj.timer != null) { clearInterval(obj.timer); }
  85. obj.timer = null;
  86. obj.stepspeed = 0;
  87. }
  88. // function used to load and store variable values
  89. obj.getVar = function (name) { if (name == undefined) return undefined; return obj.getVarEx(name.split('.'), obj.variables); }
  90. 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; } }
  91. obj.setVar = function (name, val) { obj.setVarEx(name.split('.'), obj.variables, val); }
  92. obj.setVarEx = function (name, vars, val) { if (name.length == 1) { vars[name[0]] = val; } else { obj.setVarEx(name.slice(1), vars[name[0]], val); } }
  93. // Run the script one step forward
  94. obj.step = function () {
  95. if (obj.state != 1) return;
  96. if (obj.ip < obj.script.length) {
  97. var cmdid = ReadShort(obj.script, obj.ip);
  98. var cmdlen = ReadShort(obj.script, obj.ip + 2);
  99. var argcount = ReadShort(obj.script, obj.ip + 4);
  100. var argptr = obj.ip + 6;
  101. var args = [];
  102. // Clear all temp variables (This is optional)
  103. for (var i in obj.variables) { if (i.startsWith('__')) { delete obj.variables[i]; } }
  104. // Loop on each argument, moving forward by the argument length each time
  105. for (var i = 0; i < argcount; i++) {
  106. var arglen = ReadShort(obj.script, argptr);
  107. var argval = obj.script.substring(argptr + 2, argptr + 2 + arglen);
  108. var argtyp = argval.charCodeAt(0);
  109. argval = argval.substring(1);
  110. if (argtyp < 2) {
  111. // Get the value and replace all {var} with variable values
  112. while (argval.split("{").length > 1) { var t = argval.split("{").pop().split("}").shift(); argval = argval.replace('{' + t + '}', obj.getVar(t)); }
  113. if (argtyp == 1) { obj.variables['__' + i] = decodeURI(argval); argval = '__' + i; } // If argtyp is 1, this is a literal. Store in temp variable.
  114. args.push(argval);
  115. }
  116. if (argtyp == 2 || argtyp == 3) {
  117. obj.variables['__' + i] = ReadSInt(argval, 0);
  118. args.push('__' + i);
  119. }
  120. argptr += (2 + arglen);
  121. }
  122. // Move instruction pointer forward by command size
  123. obj.ip += cmdlen;
  124. // Get all variable values
  125. var argsval = [];
  126. for (var i = 0; i < 10; i++) { argsval.push(obj.getVar(args[i])); }
  127. var storeInArg0;
  128. try {
  129. if (cmdid < 10000) {
  130. // Lets run the actual command
  131. switch (cmdid) {
  132. case 0: // nop
  133. break;
  134. case 1: // jump(label) or jump(label, a, compare, b)
  135. if (argsval[2]) {
  136. if (
  137. (argsval[2] == '<' && argsval[1] < argsval[3]) ||
  138. (argsval[2] == '<=' && argsval[1] <= argsval[3]) ||
  139. (argsval[2] == '!=' && argsval[1] != argsval[3]) ||
  140. (argsval[2] == '=' && argsval[1] == argsval[3]) ||
  141. (argsval[2] == '>=' && argsval[1] >= argsval[3]) ||
  142. (argsval[2] == '>' && argsval[1] > argsval[3])
  143. ) { obj.ip = argsval[0]; }
  144. } else {
  145. obj.ip = argsval[0]; // Set the instruction pointer to the new location in the script
  146. }
  147. break;
  148. case 2: // set(variable, value)
  149. if (args[1] == undefined) delete obj.variables[args[0]]; else obj.setVar(args[0], argsval[1]);
  150. break;
  151. case 3: // print(message)
  152. if (obj.onConsole) { obj.onConsole(obj.toString(argsval[0]), obj); } else { console.log(obj.toString(argsval[0])); }
  153. // Q(obj.consoleid).value += () + '\n'); Q(obj.console).scrollTop = Q(obj.console).scrollHeight;
  154. break;
  155. case 4: // dialog(title, content, buttons)
  156. obj.state = 2;
  157. obj.dialog = true;
  158. setDialogMode(11, argsval[0], argsval[2], obj.xxStepDialogOk, argsval[1], obj);
  159. break;
  160. case 5: // getitem(a, b, c)
  161. for (var i in argsval[1]) { if (argsval[1][i][argsval[2]] == argsval[3]) { storeInArg0 = i; } };
  162. break;
  163. case 6: // substr(variable_dest, variable_src, index, len)
  164. storeInArg0 = argsval[1].substr(argsval[2], argsval[3]);
  165. break;
  166. case 7: // indexOf(variable_dest, variable_src, index, len)
  167. storeInArg0 = argsval[1].indexOf(argsval[2]);
  168. break;
  169. case 8: // split(variable_dest, variable_src, separator)
  170. storeInArg0 = argsval[1].split(argsval[2]);
  171. break;
  172. case 9: // join(variable_dest, variable_src, separator)
  173. storeInArg0 = argsval[1].join(argsval[2]);
  174. break;
  175. case 10: // length(variable_dest, variable_src)
  176. storeInArg0 = argsval[1].length;
  177. break;
  178. case 11: // jsonparse(variable_dest, json)
  179. storeInArg0 = JSON.parse(argsval[1]);
  180. break;
  181. case 12: // jsonstr(variable_dest, variable_src)
  182. storeInArg0 = JSON.stringify(argsval[1]);
  183. break;
  184. case 13: // add(variable_dest, variable_src, value)
  185. storeInArg0 = (argsval[1] + argsval[2]);
  186. break;
  187. case 14: // substract(variable_dest, variable_src, value)
  188. storeInArg0 = (argsval[1] - argsval[2]);
  189. break;
  190. case 15: // parseInt(variable_dest, variable_src)
  191. storeInArg0 = parseInt(argsval[1]);
  192. break;
  193. case 16: // wsbatchenum(name, objectList)
  194. obj.state = 2;
  195. obj.amtstack.BatchEnum(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
  196. break;
  197. case 17: // wsput(name, args)
  198. obj.state = 2;
  199. obj.amtstack.Put(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
  200. break;
  201. case 18: // wscreate(name, args)
  202. obj.state = 2;
  203. obj.amtstack.Create(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
  204. break;
  205. case 19: // wsdelete(name, args)
  206. obj.state = 2;
  207. obj.amtstack.Delete(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
  208. break;
  209. case 20: // wsexec(name, method, args, selectors)
  210. obj.state = 2;
  211. obj.amtstack.Exec(argsval[0], argsval[1], argsval[2], obj.xxWsmanReturn, obj, 0, argsval[3]);
  212. break;
  213. case 21: // Script Speed
  214. obj.stepspeed = argsval[0];
  215. if (obj.timer != null) { clearInterval(obj.timer); obj.timer = setInterval(function () { obj.step() }, obj.stepspeed); }
  216. break;
  217. case 22: // wssubscribe(name, delivery, url, selectors, opaque, user, pass)
  218. obj.state = 2;
  219. obj.amtstack.Subscribe(argsval[0], argsval[1], argsval[2], obj.xxWsmanReturn, obj, 0, argsval[3], argsval[4], argsval[5], argsval[6]);
  220. break;
  221. case 23: // wsunsubscribe(name, selectors)
  222. obj.state = 2;
  223. obj.amtstack.UnSubscribe(argsval[0], obj.xxWsmanReturn, obj, 0, argsval[1]);
  224. break;
  225. case 24: // readchar(str, pos)
  226. console.log(argsval[1], argsval[2], argsval[1].charCodeAt(argsval[2]));
  227. storeInArg0 = argsval[1].charCodeAt(argsval[2]);
  228. break;
  229. case 25: // signWithDummyCa
  230. // ###BEGIN###{Certificates}
  231. obj.state = 2;
  232. // DERKey, xxCaPrivateKey, certattributes, issuerattributes
  233. amtcert_signWithCaKey(argsval[0], null, argsval[1], { 'CN': 'Untrusted Root Certificate' }, obj.xxSignWithDummyCaReturn);
  234. // ###END###{Certificates}
  235. break;
  236. default: {
  237. obj.state = 9;
  238. console.error("Script Error, unknown command: " + cmdid);
  239. }
  240. }
  241. } else {
  242. if (cmdid < 20000) {
  243. // functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  244. storeInArg0 = script_functionTableX2[cmdid - 10000](argsval[1], argsval[2], argsval[3], argsval[4], argsval[5], argsval[6]);
  245. } else {
  246. // Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  247. if (script_functionTableX3 && script_functionTableX3[cmdid - 20000]) {
  248. 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.
  249. }
  250. }
  251. }
  252. if (storeInArg0 != undefined) obj.setVar(args[0], storeInArg0);
  253. } catch (e) {
  254. if (typeof e == 'object') { e = e.message; }
  255. obj.setVar('_exception', e);
  256. }
  257. }
  258. if (obj.state == 1 && obj.ip >= obj.script.length) { obj.state = 0; obj.stop(); }
  259. if (obj.onStep) obj.onStep(obj);
  260. return obj;
  261. }
  262. obj.xxStepDialogOk = function (button) {
  263. obj.variables['DialogSelect'] = button;
  264. obj.state = 1;
  265. obj.dialog = false;
  266. if (obj.onStep) obj.onStep(obj);
  267. }
  268. // ###BEGIN###{**ClosureAdvancedMode}
  269. obj.xxWsmanReturnFix = function (x) {
  270. if (!x || x == null) return;
  271. if (x.Header) { x['Header'] = x.Header; delete x.Header; }
  272. if (x.Body) { x['Body'] = x.Body; delete x.Body; }
  273. if (x.Responses) { x['Responses'] = x.Responses; delete x.Responses; }
  274. if (x.Response) { x['Response'] = x.Response; delete x.Response; }
  275. if (x.ReturnValueStr) { x['ReturnValueStr'] = x.ReturnValueStr; delete x.ReturnValueStr; }
  276. }
  277. // ###END###{**ClosureAdvancedMode}
  278. obj.xxWsmanReturn = function (stack, name, responses, status) {
  279. // ###BEGIN###{**ClosureAdvancedMode}
  280. // This is required when Google Closure is used
  281. if (responses) {
  282. obj.xxWsmanReturnFix(responses);
  283. for (var i in responses) {
  284. obj.xxWsmanReturnFix(responses[i]);
  285. for (var j in responses[i]) { obj.xxWsmanReturnFix(responses[i][j]); }
  286. }
  287. }
  288. // ###END###{**ClosureAdvancedMode}
  289. obj.setVar(name, responses);
  290. obj.setVar('wsman_result', status);
  291. obj.setVar('wsman_result_str', ((httpErrorTable[status]) ? (httpErrorTable[status]) : ('Error #' + status)));
  292. obj.state = 1;
  293. if (obj.onStep) obj.onStep(obj);
  294. }
  295. // ###BEGIN###{Certificates}
  296. obj.xxSignWithDummyCaReturn = function (cert) {
  297. obj.setVar('signed_cert', btoa(_arrayBufferToString(cert)));
  298. obj.state = 1;
  299. if (obj.onStep) obj.onStep(obj);
  300. }
  301. // ###END###{Certificates}
  302. obj.toString = function (x) { if (typeof x == 'object') return JSON.stringify(x); return x; }
  303. obj.reset();
  304. return obj;
  305. }
  306. // Argument types: 0 = Variable, 1 = String, 2 = Integer, 3 = Label
  307. function script_compile(script, onmsg) {
  308. var r = '', scriptlines = script.split('\n'), labels = {}, labelswap = [], swaps = [];
  309. // Go thru each script line and encode it
  310. for (var i in scriptlines) {
  311. var scriptline = scriptlines[i];
  312. if (scriptline.startsWith('##SWAP ')) { var x = scriptline.split(' '); if (x.length == 3) { swaps[x[1]] = x[2]; } } // Add a swap instance
  313. if (scriptline[0] == '#' || scriptline.length == 0) continue; // Skip comments & blank lines
  314. for (var x in swaps) { scriptline = scriptline.split(x).join(swaps[x]); } // Apply all swaps
  315. var keywords = scriptline.match(/"[^"]*"|[^\s"]+/g);
  316. if (keywords.length == 0) continue; // Skip blank lines
  317. if (scriptline[0] == ':') { labels[keywords[0].toUpperCase()] = r.length; continue; } // Mark a label position
  318. var funcIndex = script_functionTable1.indexOf(keywords[0].toLowerCase());
  319. if (funcIndex == -1) { funcIndex = script_functionTable2.indexOf(keywords[0].toLowerCase()); if (funcIndex >= 0) funcIndex += 10000; }
  320. if (funcIndex == -1) { funcIndex = script_functionTable3.indexOf(keywords[0].toLowerCase()); if (funcIndex >= 0) funcIndex += 20000; } // Optional methods
  321. if (funcIndex == -1) { if (onmsg) { onmsg("Unabled to compile, unknown command: " + keywords[0]); } return ''; }
  322. // Encode CommandId, CmdSize, ArgCount, Arg1Len, Arg1, Arg2Len, Arg2...
  323. var cmd = ShortToStr(keywords.length - 1);
  324. for (var j in keywords) {
  325. if (j == 0) continue;
  326. if (keywords[j][0] == ':') {
  327. labelswap.push([keywords[j], r.length + cmd.length + 7]); // Add a label swap
  328. cmd += ShortToStr(5) + String.fromCharCode(3) + IntToStr(0xFFFFFFFF); // Put an empty label
  329. } else {
  330. var argint = parseInt(keywords[j]);
  331. if (argint == keywords[j]) {
  332. cmd += ShortToStr(5) + String.fromCharCode(2) + IntToStr(argint);
  333. } else {
  334. if (keywords[j][0] == '"' && keywords[j][keywords[j].length - 1] == '"') {
  335. cmd += ShortToStr(keywords[j].length - 1) + String.fromCharCode(1) + keywords[j].substring(1, keywords[j].length - 1);
  336. } else {
  337. cmd += ShortToStr(keywords[j].length + 1) + String.fromCharCode(0) + keywords[j];
  338. }
  339. }
  340. }
  341. }
  342. cmd = ShortToStr(funcIndex) + ShortToStr(cmd.length + 4) + cmd;
  343. r += cmd;
  344. }
  345. // Perform all the needed label swaps
  346. for (i in labelswap) {
  347. var label = labelswap[i][0].toUpperCase(), position = labelswap[i][1], target = labels[label];
  348. if (target == undefined) { if (onmsg) { onmsg("Unabled to compile, unknown label: " + label); } return ''; }
  349. r = r.substr(0, position) + IntToStr(target) + r.substr(position + 4);
  350. }
  351. return IntToStr(0x247D2945) + ShortToStr(1) + r;
  352. }
  353. // Decompile the script, intended for debugging only
  354. function script_decompile(binary, onecmd) {
  355. var r = '', ptr = 6, labelcount = 0, labels = {};
  356. if (onecmd >= 0) {
  357. ptr = onecmd; // If we are decompiling just one command, set the ptr to that command.
  358. } else {
  359. if (binary.length < 6) { return '# Invalid script length'; }
  360. var magic = ReadInt(binary, 0);
  361. var version = ReadShort(binary, 4);
  362. if (magic != 0x247D2945) { return '# Invalid binary script: ' + magic; }
  363. if (version != 1) { return '# Invalid script version'; }
  364. }
  365. // Loop on each command, moving forward by the command length each time.
  366. while (ptr < binary.length) {
  367. var cmdid = ReadShort(binary, ptr);
  368. var cmdlen = ReadShort(binary, ptr + 2);
  369. var argcount = ReadShort(binary, ptr + 4);
  370. var argptr = ptr + 6;
  371. var argstr = '';
  372. if (!(onecmd >= 0)) r += ":label" + (ptr - 6) + "\n";
  373. // Loop on each argument, moving forward by the argument length each time
  374. for (var i = 0; i < argcount; i++) {
  375. var arglen = ReadShort(binary, argptr);
  376. var argval = binary.substring(argptr + 2, argptr + 2 + arglen);
  377. var argtyp = argval.charCodeAt(0);
  378. if (argtyp == 0) { argstr += ' ' + argval.substring(1); } // Variable
  379. else if (argtyp == 1) { argstr += ' \"' + argval.substring(1) + '\"'; } // String
  380. else if (argtyp == 2) { argstr += ' ' + ReadInt(argval, 1); } // Integer
  381. else if (argtyp == 3) { // Label
  382. var target = ReadInt(argval, 1);
  383. var label = labels[target];
  384. if (!label) { label = ":label" + target; labels[label] = target; }
  385. argstr += ' ' + label;
  386. }
  387. argptr += (2 + arglen);
  388. }
  389. // Go in the script function table to decode the function
  390. if (cmdid < 10000) {
  391. r += script_functionTable1[cmdid] + argstr + "\n";
  392. } else {
  393. if (cmdid >= 20000) {
  394. r += script_functionTable3[cmdid - 20000] + argstr + "\n"; // Optional methods
  395. } else {
  396. r += script_functionTable2[cmdid - 10000] + argstr + "\n";
  397. }
  398. }
  399. ptr += cmdlen;
  400. if (onecmd >= 0) return r; // If we are decompiling just one command, exit now
  401. }
  402. // Remove all unused labels
  403. var scriptlines = r.split('\n');
  404. r = '';
  405. for (var i in scriptlines) {
  406. var line = scriptlines[i];
  407. if (line[0] != ':') { r += line + '\n'; } else { if (labels[line]) { r += line + '\n'; } }
  408. }
  409. return r;
  410. }