Repository navigation
Expand file tree
/
Copy pathinstall.py
More file actions
301 lines (232 loc) · 9.88 KB
/
Copy pathinstall.py
File metadata and controls
301 lines (232 loc) · 9.88 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env python3
"""
SSHBouncer Installer — Sets up config, directories, and systemd service.
Usage:
sudo python3 install.py # Interactive install
sudo python3 install.py --uninstall
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Dict
# ─────────────────────────────────────────────
# Constants
# ─────────────────────────────────────────────
INSTALL_DIR = Path("/opt/sshbouncer")
CONFIG_DIR = Path("/etc/sshbouncer")
CONFIG_FILE = CONFIG_DIR / "config.json"
STATE_DIR = Path("/var/lib/sshbouncer")
SYSTEMD_FILE = Path("/etc/systemd/system/sshbouncer.service")
APP_FILES = [
"sshbouncer.py",
"parser.py",
"engine.py",
"actions.py",
"config.py",
"state.py",
"logfollow.py",
"firewall.py",
"notify.py",
]
DEFAULT_CONFIG = {
"auth_log": "auto",
"threshold": 5,
"window_seconds": 300,
"block_enabled": False,
"block_method": "ufw",
"block_duration_minutes": 60,
"email_enabled": False,
"email_to": "",
"email_from": "",
"smtp_server": "localhost",
"smtp_port": 25,
"smtp_tls": False,
"smtp_user": "",
"smtp_pass": "",
"whitelist": ["127.0.0.1"],
"log_file": "/var/log/sshbouncer.log",
"log_level": "INFO",
"cooldown_minutes": 10,
"state_file": str(STATE_DIR / "state.json"),
}
# ─────────────────────────────────────────────
# Utilities
# ─────────────────────────────────────────────
def require_root():
if os.geteuid() != 0:
print("Error: must run installer as root.")
sys.exit(1)
def ask(prompt: str, default: str = "") -> str:
value = input(f"{prompt} [{default}]: ").strip()
return value or default
def ask_yes_no(prompt: str, default: bool = False) -> bool:
hint = "Y/n" if default else "y/N"
value = input(f"{prompt} ({hint}): ").strip().lower()
if not value:
return default
return value in ("y", "yes")
# ─────────────────────────────────────────────
# Config Collection
# ─────────────────────────────────────────────
def collect_config() -> Dict:
config = DEFAULT_CONFIG.copy()
config["threshold"] = int(
ask("Failed login threshold", str(config["threshold"]))
)
config["window_seconds"] = int(
ask("Detection window (seconds)", str(config["window_seconds"]))
)
whitelist = ask("Whitelisted IPs/CIDRs (comma-separated)", ", ".join(config["whitelist"]))
config["whitelist"] = [entry.strip() for entry in whitelist.split(",") if entry.strip()]
config["block_enabled"] = ask_yes_no("Enable IP blocking?", False)
if config["block_enabled"]:
config["block_method"] = ask("Block method (ufw/iptables)", "ufw")
config["block_duration_minutes"] = int(
ask("Block duration (minutes)", str(config["block_duration_minutes"]))
)
config["email_enabled"] = ask_yes_no("Enable email alerts?", False)
if config["email_enabled"]:
config["email_to"] = ask("Alert email")
config["email_from"] = ask("Sender address (blank = sshbouncer@hostname)", "")
config["smtp_server"] = ask("SMTP server", "localhost")
config["smtp_port"] = int(ask("SMTP port", str(config["smtp_port"])))
config["smtp_tls"] = ask_yes_no("Use STARTTLS?", False)
config["smtp_user"] = ask("SMTP username (blank = no auth)", "")
if config["smtp_user"] and not config["smtp_tls"]:
print("SMTP username requires STARTTLS; enabling it so the password is never sent in clear.")
config["smtp_tls"] = True
print(f"SMTP password: add smtp_pass to {CONFIG_FILE} (root-only, mode 0600) after install, "
"or use a systemd LoadCredential= (see README). Do not use Environment= in the unit.")
return config
# ─────────────────────────────────────────────
# File Installation
# ─────────────────────────────────────────────
def create_directories():
for path in (INSTALL_DIR, CONFIG_DIR, STATE_DIR):
path.mkdir(parents=True, exist_ok=True)
def copy_application_files():
source_dir = Path(__file__).resolve().parent / "src"
for filename in APP_FILES:
src = source_dir / filename
dst = INSTALL_DIR / filename
if not src.exists():
print(f"Missing required file: {filename}")
sys.exit(1)
shutil.copy2(src, dst)
os.chmod(dst, 0o755)
print(f"Installed {dst}")
def write_config(config: Dict):
if CONFIG_FILE.exists():
overwrite = ask_yes_no("Config exists. Overwrite?", False)
if not overwrite:
print("Keeping existing config.")
return
with open(CONFIG_FILE, "w") as f:
json.dump(config, f, indent=2)
os.chmod(CONFIG_FILE, 0o600)
print(f"Config written to {CONFIG_FILE}")
# ─────────────────────────────────────────────
# Systemd Setup
# ─────────────────────────────────────────────
def build_systemd_unit() -> str:
return f"""[Unit]
Description=SSHBouncer — Real-Time SSH Intrusion Detection
After=network.target sshd.service
[Service]
Type=simple
ExecStart=/usr/bin/python3 {INSTALL_DIR}/sshbouncer.py -c {CONFIG_FILE}
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
"""
def install_systemd_service():
SYSTEMD_FILE.write_text(build_systemd_unit())
subprocess.run(["systemctl", "daemon-reload"], check=False)
print("Systemd service installed.")
def enable_service():
subprocess.run(["systemctl", "enable", "sshbouncer"], check=False)
print("Service enabled.")
def start_service():
subprocess.run(["systemctl", "start", "sshbouncer"], check=False)
print("Service started.")
def stop_and_disable_service():
subprocess.run(["systemctl", "stop", "sshbouncer"], check=False)
subprocess.run(["systemctl", "disable", "sshbouncer"], check=False)
def load_firewall_lifecycle():
"""Import FirewallLifecycle from the installed copy, falling back to the repo checkout."""
for candidate in (INSTALL_DIR, Path(__file__).resolve().parent / "src"):
if (candidate / "firewall.py").exists():
sys.path.insert(0, str(candidate))
break
from firewall import FirewallLifecycle
return FirewallLifecycle
def remove_firewall_rules() -> bool:
"""Delete every rule this program installed. Returns False if any rule could not be removed."""
FirewallLifecycle = load_firewall_lifecycle()
all_removed = True
for method in ("ufw", "iptables"):
if shutil.which(method) is None:
continue
try:
removed, failed = FirewallLifecycle(method).remove_owned_rules()
except Exception as error: # FirewallError lives in the dynamically loaded module
print(f"WARNING: could not list {method} rules: {error}", file=sys.stderr)
all_removed = False
continue
for ip in removed:
print(f"Removed {method} rule for {ip}")
for ip in failed:
print(f"WARNING: could not remove {method} rule for {ip}", file=sys.stderr)
if failed:
all_removed = False
return all_removed
def remove_installed_files(remove_state: bool):
if SYSTEMD_FILE.exists():
SYSTEMD_FILE.unlink()
if INSTALL_DIR.exists():
shutil.rmtree(INSTALL_DIR)
if remove_state and STATE_DIR.exists():
shutil.rmtree(STATE_DIR)
subprocess.run(["systemctl", "daemon-reload"], check=False)
# ─────────────────────────────────────────────
# High-Level Actions
# ─────────────────────────────────────────────
def run_install():
require_root()
config = collect_config()
create_directories()
copy_application_files()
write_config(config)
install_systemd_service()
if ask_yes_no("Start service now?", True):
enable_service()
start_service()
print("Installation complete.")
def run_uninstall():
require_root()
stop_and_disable_service()
# Rules must go before the state that describes them; if any survive, keep the state as a record.
rules_removed = remove_firewall_rules()
remove_installed_files(remove_state=rules_removed)
print("Uninstall complete.")
print("Config and logs were preserved.")
if not rules_removed:
print(f"Some firewall rules remain; {STATE_DIR} was kept so they can be traced.", file=sys.stderr)
# ─────────────────────────────────────────────
# Entry Point
# ─────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="SSHBouncer Installer")
parser.add_argument("--uninstall", action="store_true")
args = parser.parse_args()
if args.uninstall:
run_uninstall()
else:
run_install()
if __name__ == "__main__":
main()