FunctionObfuscator.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import * as estraverse from 'estraverse';
  2. import { IFunctionNode } from "../interfaces/nodes/IFunctionNode";
  3. import { INode } from "../interfaces/nodes/INode";
  4. import { NodeObfuscator } from './NodeObfuscator';
  5. import { NodeUtils } from "../NodeUtils";
  6. import { Utils } from '../Utils';
  7. /**
  8. * replaces:
  9. * function foo (argument1) { return argument1; };
  10. *
  11. * on:
  12. * function foo (_0x12d45f) { return _0x12d45f; };
  13. *
  14. */
  15. export class FunctionObfuscator extends NodeObfuscator {
  16. /**
  17. * @type {Map<string, string>}
  18. */
  19. private functionParams: Map <string, string> = new Map <string, string> ();
  20. /**
  21. * @param functionNode
  22. */
  23. public obfuscateNode (functionNode: IFunctionNode): void {
  24. this.replaceFunctionParams(functionNode);
  25. this.replaceFunctionParamsInBody(functionNode);
  26. }
  27. /**
  28. * @param functionNode
  29. */
  30. private replaceFunctionParams (functionNode: IFunctionNode): void {
  31. functionNode.params.forEach((paramsNode: INode) => {
  32. estraverse.replace(paramsNode, {
  33. leave: (node: INode): any => {
  34. if (NodeUtils.isIdentifierNode(node)) {
  35. this.functionParams.set(node.name, Utils.getRandomVariableName());
  36. node.name = this.functionParams.get(node.name);
  37. return;
  38. }
  39. return estraverse.VisitorOption.Skip;
  40. }
  41. });
  42. });
  43. }
  44. /**
  45. * @param functionNode
  46. */
  47. private replaceFunctionParamsInBody (functionNode: IFunctionNode): void {
  48. estraverse.replace(functionNode.body, {
  49. leave: (node: INode, parentNode: INode): any => {
  50. this.replaceNodeIdentifierByNewValue(node, parentNode, this.functionParams);
  51. }
  52. });
  53. }
  54. }