-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshellcrypt.py
More file actions
319 lines (248 loc) · 10.5 KB
/
shellcrypt.py
File metadata and controls
319 lines (248 loc) · 10.5 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
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
#!/usr/bin/env python3
"""
Command Encryption Tool for Assembly Reconnaissance Tools
==========================================================
Encrypts shell commands for use in assembly programs with various crypto methods.
Usage:
# Encrypt a single command
python3 shellcrypt.py -c "whoami" -m xor -k 0xAA
# Encrypt multiple commands from file
python3 shellcrypt.py -f commands.txt -m multibyte -k 0xAA,0xBB,0xCC,0xDD
# Decrypt existing encrypted command
python3 shellcrypt.py -d "0xcf,0xc4,0xdc" -m xor -k 0xAA
# Encrypt with ROT cipher
python3 shellcrypt.py -c "ls -la" -m rot -r 13
# Encrypt with ChaCha20 (uses default key/nonce if not provided)
python3 shellcrypt.py -c "whoami" -m chacha20
# Encrypt with AES-NI (AES-128 ECB)
python3 shellcrypt.py -c "hostname" -m aes
"""
import argparse
import sys
import struct
try:
from Crypto.Cipher import AES
HAS_CRYPTO = True
except ImportError:
HAS_CRYPTO = False
from typing import List, Tuple
def xor_encrypt(data: bytes, key: int) -> bytes:
"""Simple XOR encryption with single byte key."""
return bytes(b ^ key for b in data)
def xor_decrypt(data: bytes, key: int) -> bytes:
"""Simple XOR decryption (same as encryption)."""
return xor_encrypt(data, key)
def multibyte_xor_encrypt(data: bytes, keys: List[int]) -> bytes:
"""Multi-byte XOR encryption with rotating key."""
result = bytearray()
key_index = 0
for byte in data:
result.append(byte ^ keys[key_index])
key_index = (key_index + 1) % len(keys)
return bytes(result)
def multibyte_xor_decrypt(data: bytes, keys: List[int]) -> bytes:
"""Multi-byte XOR decryption (same as encryption)."""
return multibyte_xor_encrypt(data, keys)
def rot_encrypt(data: bytes, rotation: int) -> bytes:
"""ROT cipher encryption (add rotation)."""
return bytes((b + rotation) & 0xFF for b in data)
def rot_decrypt(data: bytes, rotation: int) -> bytes:
"""ROT cipher decryption (subtract rotation)."""
return bytes((b - rotation) & 0xFF for b in data)
def chacha20_encrypt(data: bytes, key: bytes = None) -> bytes:
"""Simplified ChaCha20 encryption for demonstration."""
if key is None:
key = b"thisisaverysecret32bytekey!!!!!"
result = bytearray()
key_byte = key[0]
for byte in data:
result.append(byte ^ key_byte)
key_byte = ((key_byte << 3) | (key_byte >> 5)) & 0xFF
return bytes(result)
def aes_encrypt(data: bytes, key: bytes = None) -> bytes:
"""AES-128 ECB encryption matching the AES-NI implementation."""
if not HAS_CRYPTO:
print("Error: pycryptodome is required for AES encryption.", file=sys.stderr)
print("Install with: pip install pycryptodome", file=sys.stderr)
sys.exit(1)
if key is None:
# Default key matching assembly
key = bytes([0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c])
if len(key) != 16:
key = (key * 16)[:16]
pad_len = 16 - (len(data) % 16)
if pad_len == 0: pad_len = 16
padded_data = data + b'\x00' * pad_len
cipher = AES.new(key, AES.MODE_ECB)
return cipher.encrypt(padded_data)
def format_nasm_bytes(encrypted: bytes, original_cmd: str, label: str = None) -> str:
"""Format encrypted bytes as NASM db directive with length equ."""
hex_bytes = ', '.join(f'0x{b:02x}' for b in encrypted)
length = len(encrypted)
if label:
return f"{label}:\n db {hex_bytes}, 0\n{label}_len equ {length} ; \"{original_cmd}\""
else:
return f" db {hex_bytes}, 0\n ; length: {length}, cmd: \"{original_cmd}\""
def decrypt_for_comment(encrypted: bytes) -> str:
"""Try to decrypt for comment (assumes simple XOR 0xAA for display)."""
try:
decrypted = xor_decrypt(encrypted, 0xAA)
# Only show if it's printable ASCII
if all(32 <= b <= 126 or b == 0 for b in decrypted):
return decrypted.rstrip(b'\x00').decode('ascii', errors='replace')
except:
pass
return "encrypted"
def parse_key(key_str: str) -> int:
"""Parse key string (hex or decimal)."""
if key_str.startswith('0x') or key_str.startswith('0X'):
return int(key_str, 16)
return int(key_str)
def parse_multibyte_key(key_str: str) -> List[int]:
"""Parse multi-byte key string (comma-separated hex/decimal)."""
keys = []
for k in key_str.split(','):
keys.append(parse_key(k.strip()))
return keys
def parse_encrypted_bytes(byte_str: str) -> bytes:
"""Parse encrypted byte string (0xXX,0xYY format)."""
bytes_list = []
for b in byte_str.split(','):
b = b.strip()
if b.startswith('0x') or b.startswith('0X'):
bytes_list.append(int(b, 16))
else:
bytes_list.append(int(b))
return bytes(bytes_list)
def encrypt_command(command: str, method: str, key: bytes = None,
multibyte_key: List[int] = None, rotation: int = None) -> bytes:
"""Encrypt a command string."""
data = command.encode('utf-8')
if method == 'xor':
xor_key = key[0] if key else 0xAA
return xor_encrypt(data, xor_key)
elif method == 'multibyte':
if multibyte_key is None:
multibyte_key = [0xAA, 0xBB, 0xCC, 0xDD] # Default key
return multibyte_xor_encrypt(data, multibyte_key)
elif method == 'rot':
if rotation is None:
rotation = 13 # Default ROT13
return rot_encrypt(data, rotation)
elif method == 'chacha20':
return chacha20_encrypt(data, key)
elif method == 'aes':
return aes_encrypt(data, key)
else:
raise ValueError(f"Unknown method: {method}")
def decrypt_command(encrypted: bytes, method: str, key: bytes = None,
multibyte_key: List[int] = None, rotation: int = None) -> bytes:
"""Decrypt an encrypted command."""
if method == 'xor':
xor_key = key[0] if key else 0xAA
return xor_decrypt(encrypted, xor_key)
elif method == 'multibyte':
if multibyte_key is None:
multibyte_key = [0xAA, 0xBB, 0xCC, 0xDD]
return multibyte_xor_decrypt(encrypted, multibyte_key)
elif method == 'rot':
if rotation is None:
rotation = 13
return rot_decrypt(encrypted, rotation)
elif method == 'chacha20':
return chacha20_encrypt(encrypted, key)
elif method == 'aes':
if not HAS_CRYPTO:
print("Error: pycryptodome is required for AES decryption.", file=sys.stderr)
sys.exit(1)
if key is None:
key = bytes([0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c])
cipher = AES.new(key, AES.MODE_ECB)
return cipher.decrypt(encrypted)
else:
raise ValueError(f"Unknown method: {method}")
def main():
parser = argparse.ArgumentParser(
description='Encrypt/decrypt commands for assembly reconnaissance tools',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__
)
parser.add_argument('-c', '--command', type=str,
help='Command string to encrypt')
parser.add_argument('-f', '--file', type=str,
help='File containing commands (one per line)')
parser.add_argument('-d', '--decrypt', type=str,
help='Decrypt encrypted bytes (format: 0xXX,0xYY,...)')
parser.add_argument('-m', '--method', type=str,
choices=['xor', 'multibyte', 'rot', 'chacha20', 'aes'],
default='xor',
help='Encryption method (default: xor)')
parser.add_argument('-k', '--key', type=str,
help='Encryption key (hex: 0xAA or decimal: 170)')
parser.add_argument('-mk', '--multibyte-key', type=str,
help='Multi-byte key (comma-separated: 0xAA,0xBB,0xCC,0xDD)')
parser.add_argument('-r', '--rotation', type=int, default=13,
help='ROT cipher rotation amount (default: 13)')
parser.add_argument('-l', '--label', type=str,
help='NASM label name (e.g., cmd_whoami)')
parser.add_argument('-o', '--output', type=str,
help='Output file (default: stdout)')
args = parser.parse_args()
# Parse keys
key = None
multibyte_key = None
if args.key:
if args.method in ['chacha20', 'aes']:
key = args.key.encode('utf-8')
else:
key = bytes([parse_key(args.key)])
if args.multibyte_key:
multibyte_key = parse_multibyte_key(args.multibyte_key)
output_lines = []
# Decrypt mode
if args.decrypt:
encrypted = parse_encrypted_bytes(args.decrypt)
decrypted = decrypt_command(encrypted, args.method, key, multibyte_key, args.rotation)
print(f"Decrypted: {decrypted.decode('utf-8', errors='replace')}")
return
# Encrypt mode
commands = []
if args.command:
commands.append((args.command, args.label))
elif args.file:
try:
with open(args.file, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
# Extract label if present (format: label:command)
if ':' in line:
label, cmd = line.split(':', 1)
commands.append((cmd.strip(), label.strip()))
else:
commands.append((line, None))
except FileNotFoundError:
print(f"Error: File '{args.file}' not found", file=sys.stderr)
sys.exit(1)
else:
parser.print_help()
sys.exit(1)
# Encrypt each command
for command, label in commands:
encrypted = encrypt_command(command, args.method, key, multibyte_key, args.rotation)
output_lines.append(format_nasm_bytes(encrypted, command, label))
output_lines.append('') # Blank line between commands
# Output results
output = '\n'.join(output_lines)
if args.output:
try:
with open(args.output, 'w') as f:
f.write(output)
print(f"Encrypted commands written to: {args.output}")
except Exception as e:
print(f"Error writing to file: {e}", file=sys.stderr)
sys.exit(1)
else:
print(output)
if __name__ == '__main__':
main()