FlowControl.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import Recipe from "./Recipe.js";
  2. import Dish from "./Dish.js";
  3. import Magic from "./lib/Magic.js";
  4. import Utils from "./Utils.js";
  5. /**
  6. * Flow Control operations.
  7. *
  8. * @author n1474335 [n1474335@gmail.com]
  9. * @copyright Crown Copyright 2016
  10. * @license Apache-2.0
  11. *
  12. * @namespace
  13. */
  14. const FlowControl = {
  15. /**
  16. * Fork operation.
  17. *
  18. * @param {Object} state - The current state of the recipe.
  19. * @param {number} state.progress - The current position in the recipe.
  20. * @param {Dish} state.dish - The Dish being operated on.
  21. * @param {Operation[]} state.opList - The list of operations in the recipe.
  22. * @returns {Object} The updated state of the recipe.
  23. */
  24. runFork: async function(state) {
  25. const opList = state.opList,
  26. inputType = opList[state.progress].inputType,
  27. outputType = opList[state.progress].outputType,
  28. input = await state.dish.get(inputType),
  29. ings = opList[state.progress].ingValues,
  30. splitDelim = ings[0],
  31. mergeDelim = ings[1],
  32. ignoreErrors = ings[2],
  33. subOpList = [];
  34. let inputs = [],
  35. i;
  36. if (input)
  37. inputs = input.split(splitDelim);
  38. // Create subOpList for each tranche to operate on
  39. // (all remaining operations unless we encounter a Merge)
  40. for (i = state.progress + 1; i < opList.length; i++) {
  41. if (opList[i].name === "Merge" && !opList[i].disabled) {
  42. break;
  43. } else {
  44. subOpList.push(opList[i]);
  45. }
  46. }
  47. const recipe = new Recipe();
  48. let output = "",
  49. progress = 0;
  50. state.forkOffset += state.progress + 1;
  51. recipe.addOperations(subOpList);
  52. // Take a deep(ish) copy of the ingredient values
  53. const ingValues = subOpList.map(op => JSON.parse(JSON.stringify(op.ingValues)));
  54. // Run recipe over each tranche
  55. for (i = 0; i < inputs.length; i++) {
  56. log.debug(`Entering tranche ${i + 1} of ${inputs.length}`);
  57. // Baseline ing values for each tranche so that registers are reset
  58. subOpList.forEach((op, i) => {
  59. op.ingValues = JSON.parse(JSON.stringify(ingValues[i]));
  60. });
  61. const dish = new Dish();
  62. dish.set(inputs[i], inputType);
  63. try {
  64. progress = await recipe.execute(dish, 0, state);
  65. } catch (err) {
  66. if (!ignoreErrors) {
  67. throw err;
  68. }
  69. progress = err.progress + 1;
  70. }
  71. output += await dish.get(outputType) + mergeDelim;
  72. }
  73. state.dish.set(output, outputType);
  74. state.progress += progress;
  75. return state;
  76. },
  77. /**
  78. * Merge operation.
  79. *
  80. * @param {Object} state - The current state of the recipe.
  81. * @param {number} state.progress - The current position in the recipe.
  82. * @param {Dish} state.dish - The Dish being operated on.
  83. * @param {Operation[]} state.opList - The list of operations in the recipe.
  84. * @returns {Object} The updated state of the recipe.
  85. */
  86. runMerge: function(state) {
  87. // No need to actually do anything here. The fork operation will
  88. // merge when it sees this operation.
  89. return state;
  90. },
  91. /**
  92. * Register operation.
  93. *
  94. * @param {Object} state - The current state of the recipe.
  95. * @param {number} state.progress - The current position in the recipe.
  96. * @param {Dish} state.dish - The Dish being operated on.
  97. * @param {Operation[]} state.opList - The list of operations in the recipe.
  98. * @returns {Object} The updated state of the recipe.
  99. */
  100. runRegister: async function(state) {
  101. const ings = state.opList[state.progress].ingValues,
  102. extractorStr = ings[0],
  103. i = ings[1],
  104. m = ings[2];
  105. let modifiers = "";
  106. if (i) modifiers += "i";
  107. if (m) modifiers += "m";
  108. const extractor = new RegExp(extractorStr, modifiers),
  109. input = await state.dish.get(Dish.STRING),
  110. registers = input.match(extractor);
  111. if (!registers) return state;
  112. if (ENVIRONMENT_IS_WORKER()) {
  113. self.setRegisters(state.forkOffset + state.progress, state.numRegisters, registers.slice(1));
  114. }
  115. /**
  116. * Replaces references to registers (e.g. $R0) with the contents of those registers.
  117. *
  118. * @param {string} str
  119. * @returns {string}
  120. */
  121. function replaceRegister(str) {
  122. // Replace references to registers ($Rn) with contents of registers
  123. return str.replace(/(\\*)\$R(\d{1,2})/g, (match, slashes, regNum) => {
  124. const index = parseInt(regNum, 10) + 1;
  125. if (index <= state.numRegisters || index >= state.numRegisters + registers.length)
  126. return match;
  127. if (slashes.length % 2 !== 0) return match.slice(1); // Remove escape
  128. return slashes + registers[index - state.numRegisters];
  129. });
  130. }
  131. // Step through all subsequent ops and replace registers in args with extracted content
  132. for (let i = state.progress + 1; i < state.opList.length; i++) {
  133. if (state.opList[i].disabled) continue;
  134. let args = state.opList[i].ingValues;
  135. args = args.map(arg => {
  136. if (typeof arg !== "string" && typeof arg !== "object") return arg;
  137. if (typeof arg === "object" && arg.hasOwnProperty("string")) {
  138. arg.string = replaceRegister(arg.string);
  139. return arg;
  140. }
  141. return replaceRegister(arg);
  142. });
  143. state.opList[i].setIngValues(args);
  144. }
  145. state.numRegisters += registers.length - 1;
  146. return state;
  147. },
  148. /**
  149. * Jump operation.
  150. *
  151. * @param {Object} state - The current state of the recipe.
  152. * @param {number} state.progress - The current position in the recipe.
  153. * @param {Dish} state.dish - The Dish being operated on.
  154. * @param {Operation[]} state.opList - The list of operations in the recipe.
  155. * @param {number} state.numJumps - The number of jumps taken so far.
  156. * @returns {Object} The updated state of the recipe.
  157. */
  158. runJump: function(state) {
  159. const ings = state.opList[state.progress].ingValues,
  160. label = ings[0],
  161. maxJumps = ings[1],
  162. jmpIndex = FlowControl._getLabelIndex(label, state);
  163. if (state.numJumps >= maxJumps || jmpIndex === -1) {
  164. log.debug("Maximum jumps reached or label cannot be found");
  165. return state;
  166. }
  167. state.progress = jmpIndex;
  168. state.numJumps++;
  169. log.debug(`Jumping to label '${label}' at position ${jmpIndex} (jumps = ${state.numJumps})`);
  170. return state;
  171. },
  172. /**
  173. * Conditional Jump operation.
  174. *
  175. * @param {Object} state - The current state of the recipe.
  176. * @param {number} state.progress - The current position in the recipe.
  177. * @param {Dish} state.dish - The Dish being operated on.
  178. * @param {Operation[]} state.opList - The list of operations in the recipe.
  179. * @param {number} state.numJumps - The number of jumps taken so far.
  180. * @returns {Object} The updated state of the recipe.
  181. */
  182. runCondJump: async function(state) {
  183. const ings = state.opList[state.progress].ingValues,
  184. dish = state.dish,
  185. regexStr = ings[0],
  186. invert = ings[1],
  187. label = ings[2],
  188. maxJumps = ings[3],
  189. jmpIndex = FlowControl._getLabelIndex(label, state);
  190. if (state.numJumps >= maxJumps || jmpIndex === -1) {
  191. log.debug("Maximum jumps reached or label cannot be found");
  192. return state;
  193. }
  194. if (regexStr !== "") {
  195. const strMatch = await dish.get(Dish.STRING).search(regexStr) > -1;
  196. if (!invert && strMatch || invert && !strMatch) {
  197. state.progress = jmpIndex;
  198. state.numJumps++;
  199. log.debug(`Jumping to label '${label}' at position ${jmpIndex} (jumps = ${state.numJumps})`);
  200. }
  201. }
  202. return state;
  203. },
  204. /**
  205. * Return operation.
  206. *
  207. * @param {Object} state - The current state of the recipe.
  208. * @param {number} state.progress - The current position in the recipe.
  209. * @param {Dish} state.dish - The Dish being operated on.
  210. * @param {Operation[]} state.opList - The list of operations in the recipe.
  211. * @returns {Object} The updated state of the recipe.
  212. */
  213. runReturn: function(state) {
  214. state.progress = state.opList.length;
  215. return state;
  216. },
  217. /**
  218. * Comment operation.
  219. *
  220. * @param {Object} state - The current state of the recipe.
  221. * @param {number} state.progress - The current position in the recipe.
  222. * @param {Dish} state.dish - The Dish being operated on.
  223. * @param {Operation[]} state.opList - The list of operations in the recipe.
  224. * @returns {Object} The updated state of the recipe.
  225. */
  226. runComment: function(state) {
  227. return state;
  228. },
  229. /**
  230. * Magic operation.
  231. *
  232. * @param {Object} state - The current state of the recipe.
  233. * @param {number} state.progress - The current position in the recipe.
  234. * @param {Dish} state.dish - The Dish being operated on.
  235. * @param {Operation[]} state.opList - The list of operations in the recipe.
  236. * @returns {Object} The updated state of the recipe.
  237. */
  238. runMagic: async function(state) {
  239. const ings = state.opList[state.progress].ingValues,
  240. depth = ings[0],
  241. intensive = ings[1],
  242. extLang = ings[2],
  243. dish = state.dish,
  244. currentRecipeConfig = state.opList.map(op => op.getConfig()),
  245. magic = new Magic(dish.get(Dish.ARRAY_BUFFER)),
  246. options = await magic.speculativeExecution(depth, extLang, intensive);
  247. let output = `<table
  248. class='table table-hover table-condensed table-bordered'
  249. style='table-layout: fixed;'>
  250. <tr>
  251. <th>Recipe (click to load)</th>
  252. <th>Result snippet</th>
  253. <th>Properties</th>
  254. </tr>`;
  255. /**
  256. * Returns a CSS colour value based on an integer input.
  257. *
  258. * @param {number} val
  259. * @returns {string}
  260. */
  261. function chooseColour(val) {
  262. if (val < 3) return "green";
  263. if (val < 5) return "goldenrod";
  264. return "red";
  265. }
  266. options.forEach(option => {
  267. // Construct recipe URL
  268. // Replace this Magic op with the generated recipe
  269. const recipeConfig = currentRecipeConfig.slice(0, state.progress)
  270. .concat(option.recipe)
  271. .concat(currentRecipeConfig.slice(state.progress + 1)),
  272. recipeURL = "recipe=" + Utils.encodeURIFragment(Utils.generatePrettyRecipe(recipeConfig));
  273. let language = "",
  274. fileType = "",
  275. matchingOps = "",
  276. useful = "",
  277. entropy = `<span data-toggle="tooltip" data-container="body" title="Shannon Entropy is measured from 0 to 8. High entropy suggests encrypted or compressed data. Normal text is usually around 3.5 to 5.">Entropy: <span style="color: ${chooseColour(option.entropy)}">${option.entropy.toFixed(2)}</span></span>`,
  278. validUTF8 = option.isUTF8 ? "<span data-toggle='tooltip' data-container='body' title='The data could be a valid UTF8 string based on its encoding.'>Valid UTF8</span>\n" : "";
  279. if (option.languageScores[0].probability > 0) {
  280. let likelyLangs = option.languageScores.filter(l => l.probability > 0);
  281. if (likelyLangs.length < 1) likelyLangs = [option.languageScores[0]];
  282. language = "<span data-toggle='tooltip' data-container='body' title='Based on a statistical comparison of the frequency of bytes in various languages. Ordered by likelihood.'>" +
  283. "Possible languages:\n " + likelyLangs.map(lang => {
  284. return Magic.codeToLanguage(lang.lang);
  285. }).join("\n ") + "</span>\n";
  286. }
  287. if (option.fileType) {
  288. fileType = `<span data-toggle="tooltip" data-container="body" title="Based on the presence of magic bytes.">File type: ${option.fileType.mime} (${option.fileType.ext})</span>\n`;
  289. }
  290. if (option.matchingOps.length) {
  291. matchingOps = `Matching ops: ${[...new Set(option.matchingOps.map(op => op.op))].join(", ")}\n`;
  292. }
  293. if (option.useful) {
  294. useful = "<span data-toggle='tooltip' data-container='body' title='This could be an operation that displays data in a useful way, such as rendering an image.'>Useful op detected</span>\n";
  295. }
  296. output += `<tr>
  297. <td><a href="#${recipeURL}">${Utils.generatePrettyRecipe(option.recipe, true)}</a></td>
  298. <td>${Utils.escapeHtml(Utils.printable(Utils.truncate(option.data, 99)))}</td>
  299. <td>${language}${fileType}${matchingOps}${useful}${validUTF8}${entropy}</td>
  300. </tr>`;
  301. });
  302. output += "</table><script type='application/javascript'>$('[data-toggle=\"tooltip\"]').tooltip()</script>";
  303. if (!options.length) {
  304. output = "Nothing of interest could be detected about the input data.\nHave you tried modifying the operation arguments?";
  305. }
  306. dish.set(output, Dish.HTML);
  307. return state;
  308. },
  309. /**
  310. * Returns the index of a label.
  311. *
  312. * @private
  313. * @param {Object} state
  314. * @param {string} name
  315. * @returns {number}
  316. */
  317. _getLabelIndex: function(name, state) {
  318. for (let o = 0; o < state.opList.length; o++) {
  319. const operation = state.opList[o];
  320. if (operation.name === "Label"){
  321. const ings = operation.ingValues;
  322. if (name === ings[0]) {
  323. return o;
  324. }
  325. }
  326. }
  327. return -1;
  328. },
  329. };
  330. export default FlowControl;