-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBjornWpaSecHarvester.py
188 lines (165 loc) · 6.74 KB
/
BjornWpaSecHarvester.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import os
import logging
import time
import subprocess
from urllib.request import Request, urlopen
import requests
from dotenv import load_dotenv
import shutil # Required for file operations like copyfile
# Constants for file names
POTFILE = os.getenv("POTFILE", "wpa-sec.founds.potfile")
CRACKED_FILE = os.getenv("CRACKED_FILE", "my-cracked.txt")
NETWORKS_FILE = os.getenv("NETWORKS_FILE", "networks.txt")
DONE_FILE = os.getenv("DONE_FILE", "networks_done.txt")
# Setup logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
def download_file(url, cookie_value, output_file):
"""
Downloads a file from the given URL using a cookie for authentication.
"""
try:
logger.info("Starting file download...")
req = Request(url, headers={'Cookie': f'key={cookie_value}'})
with urlopen(req) as response, open(output_file, "wb") as out_file:
out_file.write(response.read())
logger.info(f"File {output_file} downloaded successfully.")
except Exception as e:
logger.error(f"Error downloading file {output_file}: {e}")
raise
def process_potfile(input_file, unique_networks):
"""
Processes the potfile and extracts unique networks.
"""
try:
with open(input_file, "r", encoding="utf-8") as potfile:
lines = potfile.readlines()
for line in lines:
parts = line.strip().split(":")
if len(parts) >= 4:
unique_networks.add(":".join(parts[2:4]))
logger.info(f"Processed {input_file} and extracted unique networks.")
except FileNotFoundError:
logger.warning(f"File {input_file} not found. Skipping processing.")
except UnicodeDecodeError as e:
logger.error(f"Error decoding {input_file}: {e}")
def process_cracked_file(input_file, unique_networks):
"""
Adds networks from the cracked file to the set of unique networks.
"""
try:
with open(input_file, "r", encoding="utf-8") as cracked_file:
lines = cracked_file.readlines()
for line in lines:
unique_networks.add(line.strip())
logger.info(f"Processed {input_file} and added networks to the set.")
except FileNotFoundError:
logger.warning(f"File {input_file} not found. Continuing without it.")
def save_unique_networks(output_file, unique_networks):
"""
Saves the set of unique networks to a file.
"""
try:
with open(output_file, "w", encoding="utf-8") as output:
for network in sorted(unique_networks):
output.write(f"{network}\n")
logger.info(f"Processing {output_file}")
except OSError as e:
logger.error(f"Error saving {output_file}: {e}")
def send_to_discord(webhook_url, file_path):
"""
Sends a file to Discord using a webhook URL.
"""
try:
with open(file_path, "rb") as file:
response = requests.post(webhook_url, files={"file": file})
if response.status_code == 204:
logger.info(f"File {file_path} successfully sent to Discord.")
else:
logger.warning(f"Failed to send {file_path}. HTTP status code: {response.status_code}")
except Exception as e:
logger.error(f"Error sending file {file_path} to Discord: {e}")
def manage_networks(input_file, done_file):
"""Adds new networks to the Wi-Fi configuration using nmcli."""
if not shutil.which("nmcli"):
logger.error("nmcli is not installed. Please install it and try again.")
return
try:
with open(input_file, "r") as f:
all_networks = set(line.strip() for line in f if line.strip())
except FileNotFoundError:
logger.error(f"Input file {input_file} not found.")
return
try:
with open(done_file, "r") as f:
processed_networks = set(line.strip() for line in f if line.strip())
except FileNotFoundError:
processed_networks = set()
new_networks = all_networks - processed_networks
if not new_networks:
logger.info("No new unique networks found. All networks have already been processed.")
return
# Zapisywanie nowych sieci, jeśli istnieją
try:
with open(done_file, "a") as f:
for network in new_networks:
f.write(f"{network}\n")
logger.info(f"Unique networks saved to {done_file}.")
except IOError as e:
logger.error(f"Failed to save unique networks to {done_file}: {e}")
return
try:
result = subprocess.run(
["nmcli", "-t", "-f", "DEVICE,TYPE", "device", "status"],
capture_output=True,
text=True,
check=True
)
wifi_device = next(
(line.split(":")[0] for line in result.stdout.splitlines() if "wifi" in line),
None
)
if not wifi_device:
logger.error("No Wi-Fi device found.")
return
except subprocess.CalledProcessError as e:
logger.error(f"Error while detecting Wi-Fi device: {e}")
return
for network in new_networks:
try:
ssid, password = network.split(":")
if not (8 <= len(password) <= 63):
logger.warning(f"Skipping network {ssid}: Password must be 8-63 characters long.")
continue
command = [
"sudo", "nmcli", "connection", "add", "type", "wifi", "ifname", wifi_device,
"con-name", ssid, "ssid", ssid, "wifi-sec.key-mgmt", "wpa-psk", "wifi-sec.psk", password,
"connection.autoconnect", "yes"
]
subprocess.run(command, check=True)
time.sleep(1)
except ValueError:
logger.warning(f"Invalid line format in network: {network}")
except subprocess.CalledProcessError as e:
logger.error(f"Error adding network {network}: {e}")
def main():
load_dotenv() # Load environment variables from .env file
logger.info("The gates to Valhalla have been opened, let the Harvester begin...")
# Read environment variables
cookie_value = os.getenv("COOKIE_VALUE", "")
url = os.getenv("URL", "")
discord_webhook_url = os.getenv("DISCORD_WEBHOOK_URL", "")
unique_networks = set()
try:
if url and cookie_value:
download_file(url, cookie_value, POTFILE)
process_potfile(POTFILE, unique_networks)
process_cracked_file(CRACKED_FILE, unique_networks)
save_unique_networks(NETWORKS_FILE, unique_networks)
if discord_webhook_url:
send_to_discord(discord_webhook_url, NETWORKS_FILE)
manage_networks(NETWORKS_FILE, DONE_FILE)
except Exception as e:
logger.error(f"An error occurred: {e}")
if __name__ == "__main__":
main()