Skip to content

Instantly share code, notes, and snippets.

@d8aninja
Forked from oaass/filedec.py
Created July 24, 2017 04:54
Show Gist options
  • Save d8aninja/8a6db6f27b8ec0b660fc2b137cde4a8f to your computer and use it in GitHub Desktop.
Save d8aninja/8a6db6f27b8ec0b660fc2b137cde4a8f to your computer and use it in GitHub Desktop.
Helper script to try many different openssl cipher algorithms against a file
#!/usr/bin/env python
import subprocess
import argparse
import os
import sys
def yesno(message_type, default = 'y'):
if message_type == 'DELETE_FILES_IN_FOLDER':
question = 'The folder is not empty. Do you want to delete the files in it?'
valid = {'yes': True, 'y': True, 'no': False, 'n': False}
if default is None:
appendix = '[y/n]'
elif default is 'y':
appendix = '[Y/n]'
else:
appendix = '[y/N]'
message = "[?] %s %s "%(question, appendix)
while True:
sys.stdout.write(message)
input = raw_input().lower()
if not default is None and input is '':
return valid[default]
elif input in valid:
return valid[input]
else:
sys.stdout.write("[*] Invalid option. Please respond with yes/y or no/n\n")
def getCiphers():
ciphers = {
'aes': [],
'bf': [],
'camellia': [],
'cast': [],
'cast5': [],
'des': [],
'desx': [],
'rc2': [],
'rc4': [],
'seed': [],
'other': []
}
tmp = []
proc = subprocess.Popen(['openssl', 'list-cipher-algorithms'], stdout=subprocess.PIPE)
tmp = proc.stdout.read().lower().split('\n')[:-1]
for cipher in tmp:
try:
if len(cipher.split(' => ')) is 2:
cipher = cipher.split(' => ')[1]
group = cipher.split('-')[:1][0]
if cipher not in ciphers[group]:
ciphers[group].append(cipher)
except:
if cipher not in ciphers['other']:
ciphers['other'].append(cipher)
return ciphers
def help(name=None):
print """
Arguments:
-if <file> Encrypted file
-c, --cipher <cipher[,cipher,...]> Comma separated cipher list
-g, --cipher-group <group[,group,...]> Comma separated cipher group list
-a, --all-ciphers Use all ciphers
--pass <password> Decrypt using this password
-
"""
def decrypt(infile, cipher, outfile = None, password = None):
command = ['openssl', 'enc', '-d', '-%s'%(cipher)]
command.append('-in')
command.append(infile)
if not outfile is None:
command.append('-out')
command.append(outfile)
if not password is None:
command.append('-pass')
prefix = 'pass' if not os.path.isfile(password) else 'file'
command.append('%s:%s'%(prefix, password))
subprocess.Popen(command)
def main(args):
if not args.list_ciphers is False:
ciphers = getCiphers()
print ""
for group in sorted(ciphers):
print "[*] Listing ciphers in group '%s'"%(group)
for cipher in sorted(ciphers[group]):
print " %s"%(cipher)
print ""
exit(0)
infile = args.infile
ciphers = args.cipher.split(',') if not args.cipher is None else None
cipher_groups = args.cipher_group.split(',') if not args.cipher_group is None else None
all_ciphers = args.all_ciphers
password = args.password
cipher_list = []
if not ciphers is None:
cipher_list = ciphers
elif not cipher_groups is None:
ciphers = getCiphers()
for group in cipher_groups:
for cipher in ciphers[group]:
cipher_list.append(cipher)
elif not all_ciphers is None:
ciphers = getCiphers()
for group in ciphers:
for cipher in ciphers[group]:
cipher_list.append(cipher)
cipher_list = sorted(cipher_list)
if not os.path.exists('DECRYPTED_FILES'):
print "[*] Attempting to create folder 'DECRYPTED_FILES'"
try:
os.makedirs('DECRYPTED_FILES')
print '[+] Folder successfully created\n'
except:
print '[-] Unable to create folder. Terminating...'
exit(1)
else:
answer = yesno('DELETE_FILES_IN_FOLDER')
if answer:
print '[*] Attempting to clean remove files in folder';
try:
folder = 'DECRYPTED_FILES'
for filename in os.listdir(folder):
filepath = os.path.join(folder, filename)
try:
os.unlink(filepath)
except Exception, e:
print '[!] %s'%(e)
print '[+] All files in DECRYPTED_FILES was successfully deleted. Continuing...'
except:
print '[-] Unable to delete files in DECRYPTED_FILES. Terminating...'
exit(1)
print ""
print '[*] Decryption process started...'
for cipher in cipher_list:
print "[+] Decrypting with cipher '%s'"%(cipher)
outfile = '%s-%s'%(infile, cipher.replace('-', '_'))
decrypt(infile, cipher, 'DECRYPTED_FILES/%s'%(outfile), password)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-infile', metavar='FILE')
parser.add_argument('-c', '--cipher', metavar='', help='<cipher[,cipher,...]>')
parser.add_argument('-g', '--cipher-group', metavar='', help='<group[,group,...]>')
parser.add_argument('-a', '--all-ciphers', help='Try all ciphers', action='store_true')
parser.add_argument('--list-ciphers', help='List available ciphers', action='store_true')
parser.add_argument('--password', help='Password string or filepath')
parser.add_argument('--pass-is-string', help='Force value of --password to not be treated as filepath if a file has the same name', action='store_true')
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment