Skip to content

Commit

Permalink
Python3 compatability
Browse files Browse the repository at this point in the history
  • Loading branch information
KevTheHermit committed Feb 11, 2019
1 parent f2db28b commit 262122f
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 75 deletions.
22 changes: 11 additions & 11 deletions bunnyducky.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
import os
import sys
from optparse import OptionParser
Expand All @@ -23,26 +23,26 @@
(options, args) = parser.parse_args()

if len(args) < 1:
print "[!] You need to select an Ducky Script"
print("[!] You need to select an Ducky Script")
parser.print_help()
sys.exit()

input_line = args[0]
language = options.lang_file

if not language:
print "[!] You need to specify a supported language"
print("[!] You need to specify a supported language")
parser.print_help()
print "[+] Supported Languages"
print("[+] Supported Languages")
for lang in common.list_languages():
print " [-] {0}".format(lang.split('.')[0])
print(" [-] {0}".format(lang.split('.')[0]))
sys.exit()

if "{0}.json".format(language) not in common.list_languages():
print "[!] Language {0} is not supported at this time.".format(language)
print "[+] Supported Languages"
print("[!] Language {0} is not supported at this time.".format(language))
print("[+] Supported Languages")
for lang in common.list_languages():
print " [-] {0}".format(lang.split('.')[0])
print(" [-] {0}".format(lang.split('.')[0]))
parser.print_help()
sys.exit()

Expand All @@ -51,10 +51,10 @@
# shoudl be a filename
try:
duck_filename = os.path.join(base_path, input_line)
print "[+] Opening File: ", duck_filename
print("[+] Opening File: ", duck_filename)
duck_text = open(duck_filename, 'rb').read()
except Exception as e:
print "[!] Error opening ducky file {0} : {1}".format(duck_filename, e)
print("[!] Error opening ducky file {0} : {1}".format(duck_filename, e))

else:
# Should be valid duck language
Expand All @@ -63,5 +63,5 @@
try:
encoder.encode_script(duck_text, language, bunny=True)
except Exception as e:
print e
print(e)

31 changes: 22 additions & 9 deletions ducktoolkit/decoder.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,58 @@
#!/usr/local/bin/python
#!/usr/local/bin/python3
import os
import sys
import json
from common import decoder_command_keys
from binascii import hexlify
from .common import decoder_command_keys

major_version = sys.version_info[0]

def decode_script(duck_lang, ducky_bin):
lang_dir = os.path.join(os.path.dirname(__file__), 'languages')
language_dict = os.path.join(lang_dir, '{0}.json'.format(duck_lang))
lang_file = json.load(open(language_dict))
ducky_hex = ducky_bin.encode('hex')
ducky_hex = hexlify(ducky_bin)
decoded_bin = ""
duck_decoded = ""


for i in range(0, len(ducky_hex), 4):
decoded_key = ""
last_key = duck_decoded
duck_decoded = ducky_hex[i:i+4]

#print(last_key, duck_decoded)

for key, value in lang_file.iteritems():
for key, value in lang_file.items():



# Convert value from new format
try:
new_value = value.split(',')
if len(new_value) == 3:
value = '{0}{1}'.format(new_value[2], new_value[0])
except:
continue

if major_version == 3:
value = bytes(value, 'utf-8')


except Exception as e:
continue


# Fix for spacing in STRING statements
if duck_decoded == "2c00":
if duck_decoded == b"2c00":
decoded_key = " "

elif duck_decoded == "00ff" and last_key != "00ff":
elif duck_decoded == b"00ff" and last_key !=b"00ff":
decoded_key = "DELAY"

elif duck_decoded == value:
decoded_key = key

else:
if duck_decoded[-2:] == "00":
if duck_decoded[-2:] == b"00":
if duck_decoded[:2] == value:
if len(key) == 1:
decoded_key = key
Expand Down
76 changes: 47 additions & 29 deletions ducktoolkit/encoder.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
#!/usr/local/bin/python
#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import os
import cStringIO
import io
import sys
import json
import time
from common import convert_hex
import binascii
from .common import convert_hex

major_version = sys.version_info[0]

DEBUG = False

Expand All @@ -19,18 +23,23 @@ def hidg_write(elements):


def parse_text(duck_text, lang_file, bunny):

if major_version == 3:
# COnvert the lang file to bytes
lang_file = { key.encode(): val.encode() for key, val in lang_file.items() }

line_count = 0
encoded_file = []
duck_text = duck_text.replace("\r", "")
duck_text = duck_text.replace(b"\r", b"")
cmd = instruction = False

default_delay = 0

for line in duck_text.split('\n'):
for line in duck_text.split(b'\n'):
if len(line) > 0:

# REM Comments
if line.startswith('REM') or line.startswith('rem'):
if line.startswith(b'REM') or line.startswith(b'rem'):
continue

# Last Command
Expand All @@ -39,7 +48,7 @@ def parse_text(duck_text, lang_file, bunny):

line_count += 1
line = line.lstrip().rstrip()
parsed_line = line.split(' ', 1)
parsed_line = line.split(b' ', 1)

if len(parsed_line) >= 2:
cmd = parsed_line[0].strip()
Expand All @@ -48,11 +57,13 @@ def parse_text(duck_text, lang_file, bunny):
cmd = parsed_line[0].strip()
instruction = False



if DEBUG:
print "CMD: ", cmd, "Instruction: ", instruction
print("CMD: ", cmd, "Instruction: ", instruction)

# Default Delay
if cmd in ['DEFAULT_DELAY', 'DEFAULTDELAY']:
if cmd in [b'DEFAULT_DELAY', b'DEFAULTDELAY']:
try:
default_delay = int(instruction)
continue
Expand All @@ -62,21 +73,24 @@ def parse_text(duck_text, lang_file, bunny):

# Repeat
repeat_count = 1
if cmd.lower() in ['repeat', 'replay']:
if cmd.lower() in [b'repeat', b'replay']:
try:
repeat_count = int(instruction)
except Exception as e:
print e
error_line = 'Repeat value not valid'
print(e)
error_line = b'Repeat value not valid'

cmd = last_command
instruction = last_instruction

for i in range(repeat_count):
if cmd == 'STRING':
if cmd == b'STRING':
for char in instruction:

elements = lang_file[char].split(',')

if major_version == 3:
char = bytes([char])

elements = lang_file[char].split(b',')
elements = [int(i, 16) for i in elements]
# Bunny Support
if bunny:
Expand All @@ -87,26 +101,28 @@ def parse_text(duck_text, lang_file, bunny):
encoded_file.append(convert_hex(elements[2]))
encoded_file.append(convert_hex(elements[0]))
if DEBUG:
print char, ': ', convert_hex(elements[2]), convert_hex(elements[0])
print(char, ': ', convert_hex(elements[2]), convert_hex(elements[0]))

elif cmd == 'DELAY':
elif cmd == b'DELAY':
#Bunny Support
if bunny:
time.sleep(0.001 * int(instruction))
else:
delay = add_delay(int(instruction))
encoded_file.append(delay)

elif cmd in lang_file.iterkeys():


elif cmd in iter(lang_file.keys()):

elements = lang_file[cmd].split(',')
elements = lang_file[cmd].split(b',')
elements = [int(i, 16) for i in elements]
# Bunny Support
for i in range(5):
elements.append(0)

if instruction:
param = lang_file[instruction].split(',')
param = lang_file[instruction].split(b',')
param = [int(i, 16) for i in param]
elements[0] |= param[0]
elements[2] |= param[2]
Expand All @@ -119,9 +135,9 @@ def parse_text(duck_text, lang_file, bunny):
encoded_file.append(convert_hex(elements[0]))

if DEBUG:
print instruction, ': ', convert_hex(elements[2]), convert_hex(elements[0])
print(instruction, ': ', convert_hex(elements[2]), convert_hex(elements[0]))
else:
err_line = "Command {0} Not in Language File".format(cmd)
err_line = "Command '{0}' is not in the Language File".format(cmd)
return err_line

# Add Default Delay
Expand All @@ -131,6 +147,7 @@ def parse_text(duck_text, lang_file, bunny):
else:
encoded_file.append(add_delay(int(default_delay)))


return encoded_file


Expand Down Expand Up @@ -158,26 +175,27 @@ def encode_script(duck_text, duck_lang, bunny=None):
language_dict = os.path.join(lang_dir, '{0}.json'.format(duck_lang))
lang_file = json.load(open(language_dict))


try:
encoded_file = parse_text(duck_text, lang_file, bunny)
except Exception as e:
print "Error parsing duck_text: {0}".format(e)
print("Error parsing duck_text: {0}".format(e))
return False


if encoded_file and not bunny:
if 'Not in Language' in encoded_file:
if b'not in the Language' in encoded_file:
return encoded_file
else:
try:
encoded_file = "".join(encoded_file)
duck_blob = cStringIO.StringIO()

duck_blob.write(encoded_file.decode('hex'))

duck_blob = io.BytesIO()
write_bytes = encoded_file.encode()
duck_blob.write(write_bytes)
duck_bin = duck_blob.getvalue()
duck_blob.close()
return duck_bin

except Exception as e:
print "Error creating inject.bin: {0}".format(e)
print("Error creating inject.bin: {0}".format(e))
return False
Loading

0 comments on commit 262122f

Please sign in to comment.