VariableDeclarationObfuscator.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { NodeObfuscator } from './NodeObfuscator';
  2. import { NodeUtils } from "../NodeUtils";
  3. import { Utils } from '../Utils';
  4. let estraverse = require('estraverse');
  5. /**
  6. * replaces:
  7. * var variable = 1;
  8. * variable++;
  9. *
  10. * by:
  11. * var _0x12d45f = 1;
  12. * _0x12d45f++;
  13. *
  14. */
  15. export class VariableDeclarationObfuscator extends NodeObfuscator {
  16. /**
  17. * @type {Map<string, string>}
  18. */
  19. private variableName: Map <string, string> = new Map <string, string> ();
  20. /**
  21. * @param variableDeclarationNode
  22. * @param parentNode
  23. */
  24. public obfuscateNode (variableDeclarationNode: any, parentNode: any): void {
  25. if (parentNode.type === 'Program') {
  26. return;
  27. }
  28. this.replaceVariableName(variableDeclarationNode);
  29. this.replaceVariableCalls(variableDeclarationNode, parentNode);
  30. }
  31. /**
  32. * @param variableDeclarationNode
  33. */
  34. private replaceVariableName (variableDeclarationNode: any): void {
  35. variableDeclarationNode.declarations.forEach((declarationNode) => {
  36. estraverse.replace(declarationNode, {
  37. enter: (node) => {
  38. if (node.type !== 'VariableDeclarator') {
  39. return;
  40. }
  41. estraverse.replace(node.id, {
  42. enter: (node) => {
  43. this.variableName.set(node.name, Utils.getRandomVariableName());
  44. node.name = this.variableName.get(node.name);
  45. }
  46. });
  47. }
  48. });
  49. });
  50. }
  51. /**
  52. * @param variableDeclarationNode
  53. * @param variableParentNode
  54. */
  55. private replaceVariableCalls (variableDeclarationNode: any, variableParentNode: any): void {
  56. let scopeNode: any,
  57. statementNode: any;
  58. if (variableDeclarationNode.kind === 'var') {
  59. scopeNode = NodeUtils.getNodeScope(
  60. variableDeclarationNode
  61. );
  62. } else {
  63. scopeNode = variableParentNode;
  64. }
  65. estraverse.replace(scopeNode, {
  66. enter: (node, parentNode) => {
  67. this.replaceNodeIdentifierByNewValue(node, parentNode, this.variableName);
  68. }
  69. });
  70. }
  71. }