-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathchal.js
More file actions
175 lines (155 loc) · 4.55 KB
/
Copy pathchal.js
File metadata and controls
175 lines (155 loc) · 4.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import * as parser from "@babel/parser";
import _traverse from "@babel/traverse";
import _generate from "@babel/generator";
import * as _minify from "babel-minify";
const minify = _minify.default;
const traverse = _traverse.default;
const generate = _generate.default;
import readline from "readline";
class Jail {
constructor() {
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
this.getInput();
}
async getInput() {
const kvPair = await this.promptForInput('Enter key value pair ["key","value"]: ');
const kvPairObj = this.parseKvPair(kvPair);
if (!kvPairObj) {
this.rl.close();
return;
}
const helper = await this.promptForInput('Enter helper method: ');
if (!this.isSafeHelper(helper)) {
this.rl.close();
return;
}
const code = await this.promptForInput("Enter JavaScript code (one line): ");
this.processInput(code, kvPairObj, helper);
this.rl.close();
}
isSafeHelper(weapon) {
const BLACKLISTED = ["replace", "replaceAll"]; // js evaluator ptsd
if (weapon in String.prototype && !(weapon in Object.prototype) && !BLACKLISTED.includes(weapon)) {
return weapon;
}
console.log("Invalid helper method");
return null;
}
promptForInput(prompt) {
return new Promise((resolve) => {
this.rl.question(prompt, resolve);
});
}
parseKvPair(kvPairStr) {
try {
const parsed = JSON.parse(kvPairStr);
if (!Array.isArray(parsed) || parsed.length !== 2 || typeof parsed[0] !== "string" || !["string", "number", "boolean"].includes(typeof parsed[1])) {
throw new Error("Invalid key value pair");
}
return {
[parsed[0]]: parsed[1],
}
} catch (error) {
console.log("Error parsing key value pair:", error.message);
return null
}
}
minifyCode(code) {
try {
const result = minify(code, {});
if (result.error) {
throw result.error;
}
return result
} catch (error) {
throw new Error("Error during minification: " + error.message);
}
}
processInput(code, kvPairObj, helper) {
try {
const ast = this.parseCodeToAST(code, kvPairObj)
const isSafe = this.checkSafe(ast);
if (!isSafe) {
throw new Error("Unsafe code detected!");
}
const { code: codeToEval } = this.generateCodeFromAST(ast, code);
this.evaluateCode(codeToEval, helper);
} catch (error) {
console.log("Error:", error.message);
}
}
parseCodeToAST(code, kvPairObj) {
return parser.parse(code, {
...kvPairObj,
attachComment: false,
sourceType: "module",
plugins: [],
});
}
checkSafe(ast) {
return this.noBlacklistedNodes(ast) && this.isStaticallyEvaluable(ast);
}
noBlacklistedNodes(ast) {
let failed = false;
let numCalls = 0;
traverse(ast, {
CallExpression(path) {
numCalls++;
const callee = path.get("callee");
if (!callee.isIdentifier({ name: "__HELPER__" }) || numCalls > 1) {
failed = true;
path.stop();
}
},
"Literal|OptionalCallExpression|ObjectExpression|FunctionExpression|Import|TaggedTemplateExpression|TemplateElement|UnaryExpression|AssignmentExpression|OptionalMemberExpression|SpreadElement|ArrayExpression|NewExpression|Declaration|FunctionDeclaration|MemberExpression|ArrowFunctionExpression|DebuggerStatement|RestElement|WithStatement"(
path
) {
console.log("Blacklisted node detected:", path.type);
failed = true;
path.stop();
}
});
return !failed;
}
isStaticallyEvaluable(ast) {
let isConfident = true;
traverse(ast, {
Program(path) {
const body = path.get("body");
for (const node of body) {
if (!node.isExpressionWrapper()) {
isConfident = false;
break;
}
const { confident } = node.evaluate();
if (!confident) {
isConfident = false;
break;
}
}
path.stop();
},
});
return isConfident;
}
generateCodeFromAST(ast, originalCode) {
return this.minifyCode(generate(ast, {}, originalCode).code);
}
evaluateCode(code, helper) {
try {
const newCode = `
const __HELPER__ = function (str, ...args){
if (typeof str !== "string") return
return str["${helper}"](...args)
};
${code}`
eval(newCode);
} catch (error) {
console.log("Error evaluating code:", error.message);
}
}
}
new Jail();