FunctionDeclarationObfuscator.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import * as estraverse from 'estraverse';
  2. import { IFunctionDeclarationNode } from "../interfaces/nodes/IFunctionDeclarationNode";
  3. import { ITreeNode } from "../interfaces/nodes/ITreeNode";
  4. import { NodeObfuscator } from './NodeObfuscator';
  5. import { NodeUtils } from "../NodeUtils";
  6. import { Utils } from '../Utils';
  7. /**
  8. * replaces:
  9. * function foo () { //... };
  10. * foo();
  11. *
  12. * by:
  13. * function _0x12d45f () { //... };
  14. * _0x12d45f();
  15. */
  16. export class FunctionDeclarationObfuscator extends NodeObfuscator {
  17. /**
  18. * @type {Map<string, string>}
  19. */
  20. private functionName: Map <string, string> = new Map <string, string> ();
  21. /**
  22. * @param functionDeclarationNode
  23. * @param parentNode
  24. */
  25. public obfuscateNode (functionDeclarationNode: IFunctionDeclarationNode, parentNode: ITreeNode): void {
  26. if (parentNode.type === 'Program') {
  27. return;
  28. }
  29. this.replaceFunctionName(functionDeclarationNode);
  30. this.replaceFunctionCalls(functionDeclarationNode);
  31. }
  32. /**
  33. * @param functionDeclarationNode
  34. */
  35. private replaceFunctionName (functionDeclarationNode: IFunctionDeclarationNode): void {
  36. estraverse.replace(functionDeclarationNode.id, {
  37. leave: (node: ITreeNode) => {
  38. if (NodeUtils.isIdentifierNode(node)) {
  39. this.functionName.set(node.name, Utils.getRandomVariableName());
  40. node.name = this.functionName.get(node.name);
  41. return;
  42. }
  43. return estraverse.VisitorOption.Skip;
  44. }
  45. });
  46. }
  47. /**
  48. * @param functionDeclarationNode
  49. */
  50. private replaceFunctionCalls (functionDeclarationNode: IFunctionDeclarationNode): void {
  51. let scopeNode: ITreeNode = NodeUtils.getNodeScope(
  52. functionDeclarationNode
  53. );
  54. estraverse.replace(scopeNode, {
  55. enter: (node: ITreeNode, parentNode: ITreeNode) => {
  56. this.replaceNodeIdentifierByNewValue(node, parentNode, this.functionName);
  57. }
  58. });
  59. }
  60. }