-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
peunion.py
189 lines (144 loc) · 6.49 KB
/
peunion.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from IPacker import IPacker
from lib.utils import *
import random
import string
import os
import tempfile
import shutil
import pefile
class PackerPEunion(IPacker):
default_peunion_args = ' -s -m'
peunion_cmdline_template = '<command> <infile> <outfile> -d'
metadata = {
'author': 'Martin Fischer / bytecode77 <[email protected]>',
'url': 'https://bytecode77.com/pe-union',
'description': 'Encrypts executables (x86 or .NET x86/x64), which are decrypted at runtime and executed in-memory',
'licensing': 'freeware',
'type': PackerType.PECompressor,
'input': ['PE', '.NET'],
'output': ['PE', ],
}
default_options = {
}
def __init__(self, logger, options):
self.peunion_args = PackerPEunion.default_peunion_args
self.logger = logger
self.options = options
@staticmethod
def get_name():
return 'PEunion'
def help(self, parser):
if parser != None:
parser.add_argument('--peunion-path', metavar='PATH',
dest='peunion_path', help='(required) Path to PEunion peubuild.exe executable.')
parser.add_argument('--peunion-native86-project-path', metavar='PATH',
dest='peunion_native86_project_path', help='(required) Path to PEunion Native x86 (RunPE) build project (.peu).')
parser.add_argument('--peunion-dotnet86-project-path', metavar='PATH',
dest='peunion_dotnet86_project_path', help='(required) Path to PEunion .NET x86 (Invoke) build project (.peu).')
parser.add_argument('--peunion-dotnet64-project-path', metavar='PATH',
dest='peunion_dotnet64_project_path', help='(required) Path to PEunion .NET x64 (Invoke) build project (.peu).')
else:
self.options['peunion_path'] = os.path.abspath(configPath(self.options['peunion_path']))
if not os.path.isfile(self.options['peunion_path']):
self.logger.fatal('--peunion-path option must be specified!')
@ensureInputFileIsPE
def process(self, arch, infile, outfile):
path, ext = os.path.splitext(infile)
cwd = ''
peudir = ''
newinfile = ''
try:
cwd = os.getcwd()
base = os.path.dirname(path)
dotnet = isDotNetExecutable(infile)
exe = isValidPE(infile)
projectPath = ''
if dotnet:
if arch == 'x86':
projectPath = self.options.get('peunion_dotnet86_project_path', '')
elif arch == 'x64':
projectPath = self.options.get('peunion_dotnet64_project_path', '')
else:
if arch == 'x86':
projectPath = self.options.get('peunion_native86_project_path', '')
elif arch == 'x64':
self.logger.fatal('PEunion does not support Native x64 executables. It can only work with x86 native Executables & .NET x86/x64')
tpl = ''
with open(projectPath, 'r', encoding='utf8') as f:
outlines = []
for line in f.readlines():
line = line.strip()
if len(line) == 0 or '=' not in line:
outlines.append(line)
else:
parts = [x.strip() for x in line.split('=')]
if len(parts) > 2:
self.logger.fatal(f'Invalid project specification. It was supposed to contain only one "=" equal sign.')
if parts[0].lower() == 'path':
parts[1] = infile
outlines.append(' = '.join([x.strip() for x in parts]))
tpl = '\n'.join(outlines)
newinfile = ''
peudir = os.path.join(os.path.dirname(newinfile), '.peu')
with tempfile.NamedTemporaryFile(delete=False, suffix='.peu') as tmp:
newinfile = tmp.name
tmp.write(tpl.encode())
self.logger.dbg(f'Project written to file: {newinfile}')
self.logger.dbg(f'''
------------------------------------------------
{tpl}
------------------------------------------------
''')
cmd = IPacker.build_cmdline(
PackerPEunion.peunion_cmdline_template,
self.options['peunion_path'],
PackerPEunion.default_peunion_args,
newinfile,
outfile
)
out = shell(self.logger, cmd,
output=self.options['verbose'] or self.options['debug'],
timeout=self.options['timeout']
)
tmpoutfile = os.path.join(os.path.dirname(newinfile), os.path.basename(infile))
if os.path.isfile(tmpoutfile):
shutil.move(tmpoutfile, outfile)
status = os.path.isfile(outfile)
if not status:
self.logger.err('Something went wrong: there is no output artefact ({})!\n'.format(
outfile
))
if len(out) > 0 and not (self.options['verbose'] or self.options['debug']):
self.logger.info(f'''{PackerPEunion.get_name()} returned:
----------------------------------------
{out}
----------------------------------------
''', forced=True, noprefix=True)
else:
shutil.move(newinfile, outfile)
return os.path.isfile(outfile)
except Exception as e:
raise
finally:
if len(newinfile) > 0 and os.path.isfile(newinfile):
os.remove(newinfile)
if len(peudir) > 0 and os.path.isdir(peudir):
shutil.rmtree(peudir)
if len(cwd) > 0:
self.logger.dbg(
'reverted to original working directory "{}"'.format(cwd))
os.chdir(cwd)
status = os.path.isfile(outfile)
if not status:
self.logger.err('Something went wrong: there is no output artefact ({})!\n'.format(
outfile
))
if len(out) > 0 and not (self.options['verbose'] or self.options['debug']):
self.logger.info(f'''{PackerPEunion.get_name()} returned:
----------------------------------------
{out}
----------------------------------------
''', forced=True, noprefix=True)
return status