FunctionDeclarationObfuscator.ts 1.6 KB

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