-
Notifications
You must be signed in to change notification settings - Fork 0
/
antijsfuck.py
355 lines (315 loc) · 10 KB
/
antijsfuck.py
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import html
import math
import re
import time
from urllib import parse
default_date = 'Mon Nov 12 2018 15:54:05 GMT+0800'
def date(millisecond):
weekday, month, day, tm, year = time.ctime(millisecond/1000).split()
if int(day) < 10:
day = '0'+day
return ' '.join((weekday, month, day, year, tm, 'GMT+0800'))
class Node():
def __init__(self, kind, value, raw):
self.kind = kind
self.value = value
self.raw = raw
def __str__(self):
return f'Node {self.kind} {self.value}'
class JSObject():
def __init__(self, kind, value=None):
self.kind = kind
self.value = value
def __str__(self):
if isinstance(self.value, list):
value = '['+','.join(str(x) for x in self.value)+']'
elif isinstance(self.value, tuple):
value = '('+','.join(str(x) for x in self.value)+')'
else:
value = self.value
return f'JSObject {self.kind} {value}'
class JSCode():
def __init__(self, code):
self.code = code
def __str__(self):
return f'JSCode {self.code}'
def bool2number(b):
if b is True:
return 1
if b is False:
return 0
return b
def array2string(a):
return ','.join(o2string(x) for x in a)
def bool2string(b):
if b is True:
return 'true'
if b is False:
return 'false'
def numberToString(n, b):
if b < 2 or b > 36:
raise Exception()
series = '0123456789abcdefghijklmnopqrstuvwxyz'
result = ''
while True:
q, r = divmod(n, b)
result = series[r]+result
if q == 0:
break
n = q
return result
def int_like(o: JSObject):
if o.kind == 'Number' and isinstance(o.value, int) or o.kind == 'String' and re.match(r'[\+\-]?\d+', o.value):
return True
return False
def o2string(o: JSObject, base=None):
if o.kind == 'String':
return o.value
if o.kind == 'Number':
if math.isnan(o.value):
return 'NaN'
if o.value == math.inf:
return 'Infinity'
if base is None:
return str(o.value)
return numberToString(o.value, base)
if o.kind == 'Array':
return array2string(o.value)
if o.kind == 'Boolean':
return bool2string(o.value)
if o.kind == 'undefined':
return 'undefined'
if o.kind == 'Function':
if o.value in ('filter', 'String', 'Array', 'Boolean', 'RegExp', 'Number', 'Function', 'fill'):
return 'function '+o.value+'() { [native code] }'
if o.kind == 'Object':
if o.value == 'this':
return '[object Window]'
if o.value == 'Array Iterator':
return '[object Array Iterator]'
if o.value == '{}':
return '[object Object]'
if o.kind == 'Date':
return date(o.value)
if o.kind == 'RegExp':
return o.value
raise NotImplementedError(f'{o} to String failed')
# a+b
def add(a, b):
to_stringer = ('Array', 'Function', 'Object', 'String', 'RegExp', 'Date')
if a is None:
return b
if a.kind in to_stringer or b.kind in to_stringer:
return JSObject('String', o2string(a)+o2string(b))
if a.kind in ('Number', 'Boolean') and b.kind == 'undefined' or a.kind == 'undefined' and b.kind in ('Number', 'Boolean'):
return JSObject('Number', math.nan)
if a.kind == 'Number' and b.kind == 'Number':
return JSObject('Number', a.value+b.value)
if a.kind == 'Boolean' and b.kind in ('Boolean', 'Number') or a.kind == 'Number' and b.kind == 'Boolean':
return JSObject('Number', bool2number(a.value)+bool2number(b.value))
raise NotImplementedError(f'{a} + {b} failed')
# !
def reverse(o: JSObject):
if o.kind == 'Array': # ![1]=false
return JSObject('Boolean', False)
if o.kind == 'Boolean': # !false=true
return JSObject('Boolean', not o.value)
if o.kind == 'Number':
if o.value == 0 or math.isnan(o.value): # !0=true,!NaN=true
return JSObject('Boolean', True)
return JSObject('Boolean', False) # !1=false
raise NotImplementedError(f'! {o} failed')
def call(a, b):
if a is None and b.kind == 'Function' and isinstance(b.value, tuple) and b.value[0] == 'toString':
return JSObject('String', '[object Undefined]')
if isinstance(b, JSObject) and b.kind == 'Array' and b.value[0].kind == 'String':
if b.value[0].value == 'constructor':
return JSObject('Function', a.kind)
if b.value[0].value == 'toString':
return JSObject('Function', ('toString', a))
if a.kind == 'Array' and b.kind == 'Array':
if b.value[0].kind == 'Array':
return JSObject('undefined')
if b.value[0].kind == 'String':
if b.value[0].value == 'filter':
return JSObject('Function', 'filter')
if b.value[0].value == 'concat':
return JSObject('Function', ('concat', a))
if b.value[0].value == 'fill':
return JSObject('Function', 'fill')
if b.value[0].value == 'entries':
return JSObject('Function', 'entries')
if b.value[0].value == 'slice':
return JSObject('Function', ('slice', a))
if a.kind == 'String':
if b.kind == 'Array':
if int_like(b.value[0]):
return JSObject('String', a.value[int(b.value[0].value)])
if b.value[0].kind == 'String':
if b.value[0].value in ('italics', 'fontcolor', 'link', 'slice'):
return JSObject('Function', (b.value[0].value, a))
if b.kind == 'Function' and \
isinstance(b.value, tuple) and b.value[0] == 'slice' and b.value[1].kind == 'Array':
return JSObject('Array', [JSObject('String', x) for x in a.value])
if a.kind == 'Function':
# f()
if a.value == 'escape':
return JSObject('String', parse.quote(o2string(b)))
if a.value == 'unescape':
return JSObject('String', parse.unquote(b.value))
if a.value == 'Function':
if b is None:
return JSObject('Function', JSObject('String', ''))
if b.kind == 'String':
m = re.match(r'return(\s\S.*|[\/\{]\S+)', b.value)
if m:
return_value = m.group(1).strip()
return JSObject('Function', ('return', return_value))
return JSObject('Function', b)
if a.value == 'Array':
if b is None:
return JSObject('Array', [])
if b.kind == 'String':
return JSObject('Array', [b])
# potential bug: not distinguish f[] and f([])
if a.value == 'String' and b.kind == 'Array' and b.value[0].kind == 'String':
if b.value[0].value == 'fromCharCode':
return JSObject('Function', 'fromCharCode')
if b.value[0].value == 'name':
return JSObject('String', 'String')
if a.value == 'Date':
# I'm too lazy to generate a real time
return JSObject('String', default_date)
if a.value == 'RegExp':
return JSObject('RegExp', '/(?:)/')
if a.value == 'fromCharCode':
return JSObject('String', chr(int(b.value)))
if a.value == 'eval':
if b is None:
return JSCode('')
if b.kind == 'String':
return JSCode(b.value)
if a.value == 'entries':
return JSObject('Object', 'Array Iterator')
if isinstance(a.value, tuple):
if a.value[0] == 'return':
return_value = a.value[1]
if return_value in ('escape', 'unescape', 'italics', 'Date', 'eval'):
return JSObject('Function', return_value)
if return_value == 'this':
return JSObject('Object', 'this')
if return_value[0] == '/':
return JSObject('RegExp', return_value)
if return_value[0] == '{':
return JSObject('Object', return_value)
m = re.match(r'new\s+Date\((\d+)\)', return_value)
if m:
return JSObject('Date', int(m.group(1)))
if a.value[0] == 'italics':
return JSObject('String', f'<i>{a.value[1].value}</i>')
if a.value[0] == 'fontcolor':
return JSObject('String', f'<font color="undefined">{a.value[1].value}</font>')
if a.value[0] == 'concat' and b.kind == 'Array':
return JSObject('Array', a.value[1].value+b.value)
if a.value[0] == 'toString':
if b is None:
return JSObject('String', o2string(a.value[1]))
if int_like(b):
return JSObject('String', o2string(a.value[1], int(b.value)))
if a.value[0] == 'link':
return JSObject('String', f'<a href="{html.escape(b.value)}">{a.value[1].value}</a>')
if a.value[0] == 'slice' and int_like(b):
return JSObject('String', a.value[1].value[int(b.value)])
if a.value[0] == 'call':
return call(b, a.value[1])
if b is None and isinstance(a.value, JSObject) and a.value.kind == 'String':
return JSCode(a.value.value)
# f.g
if isinstance(b, JSObject) and b.kind == 'Array':
if b.value[0].value == 'call':
return JSObject('Function', ('call', a))
raise NotImplementedError(f'{a} call {b} failed')
# +
def positive(o):
if o.kind == 'Array':
if len(o.value) == 0: # +[]=0
return JSObject('Number', 0)
if o.value[0].kind == 'Number': # +[1]=1
return JSObject('Number', o.value[0].value)
if o.value[0].kind == 'Boolean': # +[true]=NaN
return JSObject('Number', math.nan)
if o.kind == 'Boolean': # +false=0
return JSObject('Number', bool2number(o.value))
if o.kind == 'String': # +"1"=1
try:
value = int(o.value)
except:
value = float(o.value)
return JSObject('Number', value)
raise NotImplementedError(f'+ {o} failed')
def evaluate_term(o):
if o[0] == '!':
return reverse(evaluate_term(o[1:]))
if o[0] == '+':
return positive(evaluate_term(o[1:]))
evaluated = [evaluate(item) for item in o]
result = evaluated[0]
for item in evaluated[1:]:
result = call(result, item)
return result
def evaluate_list(o):
if len(o) == 0:
return None
start = 0
now = 0
terms = []
while now < len(o):
if o[now] == '#':
terms.append(evaluate_term(o[start:now]))
start = now+1
now = start
now += 1
terms.append(evaluate_term(o[start:now]))
result = None
for term in terms:
result = add(result, term)
return result
def evaluate(o):
if isinstance(o, list):
return evaluate_list(o)
if not isinstance(o, Node):
raise Exception()
if o.kind == '[':
value = evaluate(o.value)
return JSObject('Array', [value] if value else [])
if o.kind == '(':
return evaluate(o.value)
def fight(jsfuck_code):
# build simple AST
stack = []
aux = []
pairs = {']': '[', ')': '('}
for index, c in enumerate(jsfuck_code):
if c in ('[', '(', '!'):
stack.append(c)
aux.append(index)
elif c in pairs:
left = pairs[c]
i = len(stack)-1
while stack[i] != left:
i -= 1
node = Node(left, stack[i+1:], jsfuck_code[aux[i]:index+1])
stack = stack[:i]
stack.append(node)
aux = aux[:i]
aux.append(None)
elif c == '+':
if len(stack) > 0 and isinstance(stack[-1], Node):
stack.append('#')
aux.append(None)
else:
stack.append('+')
aux.append(None)
else:
raise Exception(f'not jsfuck character {c}')
return evaluate(stack)