/
typecast.py
68 lines (57 loc) · 1.76 KB
/
typecast.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import string
from refinery.lib.patterns import formats
from refinery.units.obfuscation import Deobfuscator
from refinery.units.obfuscation.ps1 import string_quote, Ps1StringLiterals
class deob_ps1_typecast(Deobfuscator):
"""
Replaces sequences like [Char]120 to their string representation, in this
case the string "x".
"""
def deobfuscate(self, data):
strlit = Ps1StringLiterals(data)
@strlit.outside
def strip_typecast(m): return m[1]
data = re.sub(
FR'\[(?:string|char\[\])\]\s*({formats.ps1str!s})',
strip_typecast,
data,
flags=re.IGNORECASE
)
@strlit.outside
def char_literal(match):
c = chr(int(match[1]))
if c == "'":
return '''"'"'''
return F"'{c}'"
data = re.sub(
R'\[char\]\s*0*(0x[0-9a-f]+|\d+)',
char_literal,
data,
flags=re.IGNORECASE
)
def char_array(match):
result = bytes(int(x, 0) for x in match[1].split(','))
try:
result = result.decode('ascii')
if not all(x in string.printable or x.isspace() for x in result):
raise ValueError
except ValueError:
return match[0]
else:
return string_quote(result)
data = re.sub(
R'\s*'.join([
R'\[char\[\]\]',
R'\((',
R'(?:\s*(?:0x[0-9a-f]+|\d+)\s*,)+',
R'(?:0x[0-9a-f]+|\d+)',
R')\)'
]),
char_array,
data,
flags=re.IGNORECASE
)
return data