forked from BigNerd95/RouterOS-Backup-Tools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ROSbackup.py
375 lines (294 loc) · 12 KB
/
ROSbackup.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python3
# RouterOS Backup Tools by BigNerd95
import sys, os, struct
from random import randrange
from argparse import ArgumentParser, FileType
from Crypto.Cipher import ARC4
from Crypto.Hash import SHA
# RouterOS constants
MAGIC_ENCRYPTED = 0x7291A8EF
MAGIC_PLAINTEXT = 0xB1A1AC88
RC4_SKIP = 0x300
#####################
# support functions #
#####################
def get_header(input_file):
input_file.seek(0, 0)
data = input_file.read(8)
header = struct.unpack('<II', data)
return header[0], header[1]
def get_salt(input_file):
input_file.seek(8, 0)
data = input_file.read(32)
salt = struct.unpack('<32s', data)
return salt[0]
def get_magic_check(input_file):
input_file.seek(40, 0)
data = input_file.read(4)
magic_check = struct.unpack('<4s', data)
return magic_check[0]
def check_password(cipher, magic_check):
data = cipher.decrypt(magic_check)
decrypted_magic_check = struct.unpack('<I', data)
return decrypted_magic_check[0] == MAGIC_PLAINTEXT
def make_salt(size):
return bytes([randrange(256) for _ in range(size)])
def setup_cipher(salt, password):
key = SHA.new(salt + bytes(password, 'ascii')).digest()
cipher = ARC4.new(key)
cipher.encrypt(bytes(RC4_SKIP)) # skip stream start
return cipher
def extract_data(input_file):
raw_len = input_file.read(4)
if len(raw_len) != 4:
raise EOFError('EOF')
data_len = struct.unpack('<I', raw_len)[0]
raw_data = input_file.read(data_len)
if len(raw_data) != data_len:
raise EOFError('EOF')
return raw_data
def create_write_file(path, data):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
f.write(data)
def get_file_list(path):
file_list = []
original_path = os.getcwd()
os.chdir(path)
for root, dirs, files in os.walk("."):
file_path = root.split(os.sep)[1:]
file_path = '/'.join(file_path)
if file_path:
file_path += '/'
for file in files:
# check if both idx and dat files exist
if file.endswith(".idx") and file[:-3] + "dat" in files:
file_list.append(file_path + file[:-4])
os.chdir(original_path)
return file_list
def write_data(output_file, data):
data_len = struct.pack('<I', len(data))
output_file.write(data_len)
output_file.write(data)
##################
# core functions #
##################
def decrypt_backup(input_file, output_file, cipher):
input_file.seek(44, 0) # skip magic, length, salt, magic_check
output_file.seek(0, 0)
magic = struct.pack('<I', MAGIC_PLAINTEXT)
output_file.write(magic + bytes(4)) # magic, length offset
while True:
chunk = input_file.read(1024)
if not chunk:
break
output_file.write(cipher.decrypt(chunk))
length = struct.pack('<I', output_file.tell()) # length
output_file.seek(4, 0)
output_file.write(length)
def encrypt_backup(input_file, output_file, cipher, salt):
input_file.seek(8, 0) # skip magic, length
output_file.seek(0, 0)
magic = struct.pack('<I', MAGIC_ENCRYPTED)
output_file.write(magic + bytes(4) + salt) # magic, length offset, salt
magic_check = struct.pack('<I', MAGIC_PLAINTEXT)
output_file.write(cipher.encrypt(magic_check))
while True:
chunk = input_file.read(1024)
if not chunk:
break
output_file.write(cipher.encrypt(chunk))
length = struct.pack('<I', output_file.tell()) # length
output_file.seek(4, 0)
output_file.write(length)
def unpack_files(input_file, file_length, path):
count = 0
input_file.seek(8, 0) # skip magic, length
path = os.path.join(path, '')
if os.path.exists(path):
print("Directory", os.path.basename(path) , "already exists, cannot extract!")
return count
while input_file.tell() < file_length:
try:
name = extract_data(input_file).decode('ascii')
idx = extract_data(input_file)
dat = extract_data(input_file)
create_write_file(path + name + '.idx', idx)
create_write_file(path + name + '.dat', dat)
count += 1
except EOFError:
print("Unexpected End of File!")
break
return count
def pack_files(path, file_names, output_file):
output_file.seek(0, 0)
magic = struct.pack('<I', MAGIC_PLAINTEXT)
output_file.write(magic + bytes(4)) # magic, length offset
path = os.path.join(path, '')
for name in file_names:
with open(path + name + '.idx', "rb") as idx_file:
idx = idx_file.read()
with open(path + name + '.dat', "rb") as dat_file:
dat = dat_file.read()
write_data(output_file, name.encode('ascii'))
write_data(output_file, idx)
write_data(output_file, dat)
length = struct.pack('<I', output_file.tell()) # length
output_file.seek(4, 0)
output_file.write(length)
##################
# main functions #
##################
def info(input_file):
print('** Backup Info **')
magic, length = get_header(input_file)
if magic == MAGIC_ENCRYPTED:
print("RouterOS Encrypted Backup")
print("Length:", length, "bytes")
salt = get_salt(input_file)
print("Salt (hex):", salt.hex())
elif magic == MAGIC_PLAINTEXT:
print("RouterOS Plaintext Backup")
print("Length:", length, "bytes")
else:
print("Invalid file!")
input_file.close()
def decrypt(input_file, output_file, password):
print('** Decrypt Backup **')
magic, length = get_header(input_file)
if magic == MAGIC_ENCRYPTED:
print("RouterOS Encrypted Backup")
print("Length:", length, "bytes")
salt = get_salt(input_file)
print("Salt (hex):", salt.hex())
cipher = setup_cipher(salt, password)
magic_check = get_magic_check(input_file)
if check_password(cipher, magic_check):
print("Correct password!")
print("Decrypting...")
decrypt_backup(input_file, output_file, cipher)
print("Decrypted correctly")
else:
print("Wrong password!")
print("Cannot decrypt!")
elif magic == MAGIC_PLAINTEXT:
print("RouterOS Plaintext Backup")
print("No decryption needed!")
else:
print("Invalid file!")
print("Cannot decrypt!")
input_file.close()
output_file.close()
def recover(input_file, wordlist):
print('** Recover Backup Password **')
magic, length = get_header(input_file)
if magic == MAGIC_ENCRYPTED:
print("RouterOS Encrypted Backup")
print("Length:", length, "bytes")
salt = get_salt(input_file)
print("Salt (hex):", salt.hex())
wordlist_file = open(wordlist)
for line in wordlist_file:
password = line.strip()
cipher = setup_cipher(salt, password)
magic_check = get_magic_check(input_file)
if check_password(cipher, magic_check):
print("Correct password: ", password)
break
elif magic == MAGIC_PLAINTEXT:
print("RouterOS Plaintext Backup")
print("No decryption needed!")
else:
print("Invalid file!")
print("Cannot decrypt!")
input_file.close()
wordlist_file.close()
def encrypt(input_file, output_file, password):
print('** Encrypt Backup **')
magic, length = get_header(input_file)
if magic == MAGIC_ENCRYPTED:
print("RouterOS Encrypted Backup")
print("No encryption needed!")
elif magic == MAGIC_PLAINTEXT:
print("RouterOS Plaintext Backup")
print("Length:", length, "bytes")
salt = make_salt(32)
print("Generated Salt (hex):", salt.hex())
cipher = setup_cipher(salt, password)
print("Encrypting...")
encrypt_backup(input_file, output_file, cipher, salt)
print("Encrypted correctly")
else:
print("Invalid file!")
print("Cannot encrypt!")
input_file.close()
output_file.close()
def unpack(input_file, unpack_directory):
print('** Unpack Backup **')
magic, length = get_header(input_file)
if magic == MAGIC_ENCRYPTED:
print("RouterOS Encrypted Backup")
print("Cannot unpack encrypted backup!")
print("Decrypt backup first!")
elif magic == MAGIC_PLAINTEXT:
print("RouterOS Plaintext Backup")
print("Length:", length, "bytes")
print("Extracting backup...")
files_num = unpack_files(input_file, length, unpack_directory)
if files_num > 0:
print("Wrote", files_num, "files pair in:", unpack_directory)
else:
print("Invalid file!")
print("Cannot unpack!")
input_file.close()
def pack(output_file, pack_directory):
print('** Pack Backup **')
file_names = get_file_list(pack_directory)
if len(file_names) > 0:
print("Creating plaintext backup with", len(file_names), "files pair...")
pack_files(pack_directory, file_names, output_file)
print("Done!")
else:
print("Error! No IDX and DAT files found!")
output_file.close()
def parse_cli():
parser = ArgumentParser(description='** RouterOS Backup Tools by BigNerd95 **')
subparser = parser.add_subparsers(dest='subparser_name')
infoParser = subparser.add_parser('info', help='Backup info')
infoParser.add_argument('-i', '--input', required=True, metavar='INPUT_FILE', type=FileType('rb'))
decryptParser = subparser.add_parser('decrypt', help='Decrypt backup')
decryptParser.add_argument('-i', '--input', required=True, metavar='INPUT_FILE', type=FileType('rb'))
decryptParser.add_argument('-o', '--output', required=True, metavar='OUTPUT_FILE', type=FileType('wb'))
decryptParser.add_argument('-p', '--password', required=True, metavar='PASSWORD')
encryptParser = subparser.add_parser('encrypt', help='Encrypt backup')
encryptParser.add_argument('-i', '--input', required=True, metavar='INPUT_FILE', type=FileType('rb'))
encryptParser.add_argument('-o', '--output', required=True, metavar='OUTPUT_FILE', type=FileType('wb'))
encryptParser.add_argument('-p', '--password', required=True, metavar='PASSWORD')
recoverParser = subparser.add_parser('recover', help='Recover backup password')
recoverParser.add_argument('-i', '--input', required=True, metavar='INPUT_FILE', type=FileType('rb'))
recoverParser.add_argument('-w', '--wordlist', required=True, metavar='WORDLIST')
unpackParser = subparser.add_parser('unpack', help='Unpack backup')
unpackParser.add_argument('-i', '--input', required=True, metavar='INPUT_FILE', type=FileType('rb'))
unpackParser.add_argument('-d', '--directory', required=True, metavar='UNPACK_DIRECTORY')
packParser = subparser.add_parser('pack', help='Unpack backup')
packParser.add_argument('-d', '--directory', required=True, metavar='PACK_DIRECTORY')
packParser.add_argument('-o', '--output', required=True, metavar='OUTPUT_FILE', type=FileType('wb'))
if len(sys.argv) < 2:
parser.print_help()
return parser.parse_args()
def main():
args = parse_cli()
if args.subparser_name == 'info':
info(args.input)
elif args.subparser_name == 'decrypt':
decrypt(args.input, args.output, args.password)
elif args.subparser_name == 'encrypt':
encrypt(args.input, args.output, args.password)
elif args.subparser_name == 'recover':
recover(args.input, args.wordlist)
elif args.subparser_name == 'unpack':
unpack(args.input, args.directory)
elif args.subparser_name == 'pack':
pack(args.output, args.directory)
if __name__ == '__main__':
main()