VariableDeclarationObfuscator.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import * as estraverse from 'estraverse';
  2. import * as ESTree from 'estree';
  3. import { ICustomNode } from "../interfaces/custom-nodes/ICustomNode";
  4. import { IOptions } from "../interfaces/IOptions";
  5. import { NodeType } from "../enums/NodeType";
  6. import { AbstractNodeObfuscator } from './AbstractNodeObfuscator';
  7. import { IdentifierReplacer } from "./replacers/IdentifierReplacer";
  8. import { Nodes } from "../Nodes";
  9. import { NodeUtils } from "../NodeUtils";
  10. /**
  11. * replaces:
  12. * var variable = 1;
  13. * variable++;
  14. *
  15. * on:
  16. * var _0x12d45f = 1;
  17. * _0x12d45f++;
  18. *
  19. */
  20. export class VariableDeclarationObfuscator extends AbstractNodeObfuscator {
  21. /**
  22. * @type {IdentifierReplacer}
  23. */
  24. private identifierReplacer: IdentifierReplacer;
  25. /**
  26. * @param nodes
  27. * @param options
  28. */
  29. constructor(nodes: Map <string, ICustomNode>, options: IOptions) {
  30. super(nodes, options);
  31. this.identifierReplacer = new IdentifierReplacer(this.nodes, this.options);
  32. }
  33. /**
  34. * @param variableDeclarationNode
  35. * @param parentNode
  36. */
  37. public obfuscateNode (variableDeclarationNode: ESTree.VariableDeclaration, parentNode: ESTree.Node): void {
  38. if (parentNode.type === NodeType.Program) {
  39. return;
  40. }
  41. this.storeVariableNames(variableDeclarationNode);
  42. this.replaceVariableNames(variableDeclarationNode, parentNode);
  43. }
  44. /**
  45. * @param variableDeclarationNode
  46. */
  47. private storeVariableNames (variableDeclarationNode: ESTree.VariableDeclaration): void {
  48. variableDeclarationNode.declarations
  49. .forEach((declarationNode: ESTree.VariableDeclarator) => {
  50. NodeUtils.typedReplace(declarationNode.id, NodeType.Identifier, {
  51. leave: (node: ESTree.Identifier) => this.identifierReplacer.storeNames(node.name)
  52. });
  53. });
  54. }
  55. /**
  56. * @param variableDeclarationNode
  57. * @param variableParentNode
  58. */
  59. private replaceVariableNames (variableDeclarationNode: ESTree.VariableDeclaration, variableParentNode: ESTree.Node): void {
  60. let scopeNode: ESTree.Node = variableDeclarationNode.kind === 'var' ? NodeUtils.getBlockScopeOfNode(
  61. variableDeclarationNode
  62. ) : variableParentNode;
  63. estraverse.replace(scopeNode, {
  64. enter: (node: ESTree.Node, parentNode: ESTree.Node): any => {
  65. if (!node.obfuscated && Nodes.isReplaceableIdentifierNode(node, parentNode)) {
  66. node.name = this.identifierReplacer.replace(node.name);
  67. }
  68. }
  69. });
  70. }
  71. }