UNPKG

js-confuser

Version:

JavaScript Obfuscation Tool.

232 lines (217 loc) 14.7 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var t = _interopRequireWildcard(require("@babel/types")); var _NameGen = require("../../utils/NameGen"); var _template = _interopRequireDefault(require("../../templates/template")); var _order = require("../../order"); var _constants = require("../../constants"); var _astUtils = require("../../utils/ast-utils"); var _getGlobalTemplate = require("../../templates/getGlobalTemplate"); var _randomUtils = require("../../utils/random-utils"); var _assert = require("assert"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } var ignoreGlobals = new Set(["require", "__dirname", "eval", "arguments", _constants.variableFunctionName].concat(_toConsumableArray(_constants.reservedIdentifiers))); var _default = exports["default"] = function _default(_ref) { var Plugin = _ref.Plugin; var me = Plugin(_order.Order.GlobalConcealing, { changeData: { globals: 0, nativeFunctions: 0 } }); var globalMapping = new Map(), globalFnName = me.getPlaceholder() + "_getGlobal", globalVarName = me.getPlaceholder() + "_globalVar", gen = new _NameGen.NameGen(); // Create the getGlobal function using a template function createGlobalConcealingFunction() { // Create fake global mappings var fakeCount = (0, _randomUtils.getRandomInteger)(20, 40); for (var i = 0; i < fakeCount; i++) { var fakeName = (0, _randomUtils.getRandomString)((0, _randomUtils.getRandomInteger)(6, 8)); globalMapping.set(gen.generate(), fakeName); } var createSwitchStatement = function createSwitchStatement() { var cases = Array.from(globalMapping.keys()).map(function (originalName) { var mappedKey = globalMapping.get(originalName); return t.switchCase(t.stringLiteral(mappedKey), [t.returnStatement(t.memberExpression(t.identifier(globalVarName), t.stringLiteral(originalName), true))]); }); return t.switchStatement(t.identifier("mapping"), cases); }; return t.functionDeclaration(t.identifier(globalFnName), [t.identifier("mapping")], t.blockStatement([createSwitchStatement()])); } return { visitor: { Program: { exit: function exit(programPath) { var illegalGlobals = new Set(); var pendingReplacements = new Map(); programPath.traverse({ Identifier: function Identifier(identifierPath) { if (!(0, _astUtils.isVariableIdentifier)(identifierPath)) return; var identifierName = identifierPath.node.name; if (ignoreGlobals.has(identifierName)) return; var binding = identifierPath.scope.getBinding(identifierName); if (binding) { illegalGlobals.add(identifierName); return; } if (!identifierPath.scope.hasGlobal(identifierName)) { return; } var assignmentChild = identifierPath.find(function (p) { var _p$parentPath; return (_p$parentPath = p.parentPath) === null || _p$parentPath === void 0 ? void 0 : _p$parentPath.isAssignmentExpression(); }); if (assignmentChild && t.isAssignmentExpression(assignmentChild.parent) && assignmentChild.parent.left === assignmentChild.node && !t.isMemberExpression(identifierPath.parent)) { illegalGlobals.add(identifierName); return; } if (!pendingReplacements.has(identifierName)) { pendingReplacements.set(identifierName, [identifierPath]); } else { pendingReplacements.get(identifierName).push(identifierPath); } } }); // Remove illegal globals illegalGlobals.forEach(function (globalName) { pendingReplacements["delete"](globalName); }); var _iterator = _createForOfIteratorHelper(pendingReplacements), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _step$value = _slicedToArray(_step.value, 2), globalName = _step$value[0], paths = _step$value[1]; var mapping = globalMapping.get(globalName); if (!mapping) { // Allow user to disable custom global variables if (!me.computeProbabilityMap(me.options.globalConcealing, globalName)) continue; mapping = gen.generate(); globalMapping.set(globalName, mapping); } // Replace global reference with getGlobal("name") var callExpression = t.callExpression(t.identifier(globalFnName), [t.stringLiteral(mapping)]); var nativeFunctionName = me.globalState.internals.nativeFunctionName; var _iterator2 = _createForOfIteratorHelper(paths), _step2; try { var _loop = function _loop() { var path = _step2.value; var replaceExpression = t.cloneNode(callExpression); me.skip(replaceExpression); if ( // Native Function will only be populated if tamper protection is enabled nativeFunctionName && // Avoid maximum call stack error !path.find(function (p) { return p.node[_constants.MULTI_TRANSFORM] || me.isSkipped(p); })) { // First extract the member expression chain var nameAndPropertyPath = [globalName]; var cursorPath = path; var callExpressionPath = null; var checkForCallExpression = function checkForCallExpression() { var _cursorPath$parentPat; if ((_cursorPath$parentPat = cursorPath.parentPath) !== null && _cursorPath$parentPat !== void 0 && _cursorPath$parentPat.isCallExpression() && cursorPath.key === "callee") { callExpressionPath = cursorPath.parentPath; return true; } }; if (!checkForCallExpression()) { var _cursorPath; cursorPath = (_cursorPath = cursorPath) === null || _cursorPath === void 0 ? void 0 : _cursorPath.parentPath; while ((_cursorPath2 = cursorPath) !== null && _cursorPath2 !== void 0 && _cursorPath2.isMemberExpression()) { var _cursorPath2; var propertyString = (0, _astUtils.getMemberExpressionPropertyAsString)(cursorPath.node); if (!propertyString || typeof propertyString !== "string") { break; } nameAndPropertyPath.push(propertyString); if (checkForCallExpression()) break; cursorPath = cursorPath.parentPath; } } // Eligible member-expression/identifier if (callExpressionPath) { // Check user's custom implementation shouldTransform = me.obfuscator.shouldTransformNativeFunction(nameAndPropertyPath); if (shouldTransform) { path.replaceWith(replaceExpression); // console.log("Hello World") -> // checkNative(getGlobal("console")["log"])("Hello World") // Parent-most member expression must be wrapped // This to preserve proper 'this' binding in member expression invocations var callee = callExpressionPath.get("callee"); var callArgs = [callee.node]; if (callee.isMemberExpression()) { var additionalPropertyString = (0, _astUtils.getMemberExpressionPropertyAsString)(callee.node); (0, _assert.ok)(additionalPropertyString, "Expected additional property to be a string"); callee = callee.get("object"); callArgs = [callee.node, t.stringLiteral(additionalPropertyString)]; } // Method supports two signatures: // checkNative(fetch)(...) // checkNative(console, "log")(...) callExpressionPath.get("callee").replaceWith(me.skip(t.callExpression(t.identifier(nativeFunctionName), callArgs))); me.changeData.nativeFunctions++; return 1; // continue } } } me.changeData.globals++; // Regular replacement // console -> getGlobal("console") path.replaceWith(replaceExpression); }, shouldTransform; for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { if (_loop()) continue; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } // No globals changed, no need to insert the getGlobal function } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (globalMapping.size === 0) return; // The Global Concealing function returns the global variable from the specified parameter var globalConcealingFunction = createGlobalConcealingFunction(); (0, _astUtils.prepend)(programPath, globalConcealingFunction); var getGlobalVarFnName = me.getPlaceholder() + "_getGlobalVarFn"; // Insert the get global function (0, _astUtils.prepend)(programPath, (0, _getGlobalTemplate.createGetGlobalTemplate)(me, programPath).compile({ getGlobalFnName: getGlobalVarFnName })); // Call the get global function and store result in 'globalVarName' (0, _astUtils.prepend)(programPath, new _template["default"]("var ".concat(globalVarName, " = ").concat(getGlobalVarFnName, "()")).single()); } } } }; };