Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
753 lines (686 loc) · 33.6 KB
/
Copy pathcli.py
File metadata and controls
753 lines (686 loc) · 33.6 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
import os
import sys
import secrets
import shutil
import tarfile
import subprocess
import asyncio
import click
from pathlib import Path
from datetime import datetime, date
# Force UTF-8 streams to avoid encoding crashes on minimal locales
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
from app.config import settings
from app.database.connection import init_db
from app.database import crud
from app.database.models import UserCreate, UserUpdate
from app.core.cert import (
generate_self_signed_cert, generate_panel_cert,
get_cert_info, check_and_renew_panel_cert
)
from app.core.hysteria import (
apply_and_save_config, restart_hysteria,
is_hysteria_running, get_hysteria_version, get_hysteria_logs,
run_systemctl
)
from app.core.firewall import flush_port_hopping, configure_port_hopping, open_firewall_port
from app.core.subscription import build_hy2_uri
from app.core.security import hash_password, generate_secret_path
def run_async(coro):
return asyncio.run(coro)
@click.group()
def cli():
"""InnerBlitz CLI — High-Speed Hysteria 2 Management Console."""
pass
@cli.command("init")
def init_system():
"""Initialize SQLite database and configuration."""
async def _init():
await init_db()
await apply_and_save_config()
p = await crud.get_setting("panel_port", "8080")
h = await crud.get_setting("listen_port", "443")
open_firewall_port(int(p), "tcp")
open_firewall_port(int(h), "udp")
click.echo(click.style("✔ InnerBlitz database & config initialized.", fg="green"))
run_async(_init())
@cli.command("add-user")
@click.option("--username", "-u", required=True, help="Username")
@click.option("--password", "-p", default=None, help="Password (auto-generated if omitted)")
@click.option("--traffic", "-t", default=0.0, type=float, help="Traffic limit in GB (0 = unlimited)")
@click.option("--days", "-d", default=30, type=int, help="Expiration days (0 = unlimited)")
@click.option("--max-ips", default=0, type=int, help="Max simultaneous IPs (0 = unlimited)")
@click.option("--unlimited", is_flag=True, help="Exempt from all limits")
@click.option("--note", default="", help="Optional note")
def add_user(username, password, traffic, days, max_ips, unlimited, note):
"""Create a new proxy user."""
async def _add():
await init_db()
existing = await crud.get_user_by_username(username)
if existing:
click.echo(click.style(f"✖ User '{username}' already exists.", fg="red"))
return
user_in = UserCreate(
username=username,
password=password,
traffic_limit_gb=traffic,
expiration_days=days,
max_ips=max_ips,
unlimited_user=unlimited,
note=note
)
created = await crud.create_user(user_in)
cfg = await crud.get_all_settings()
uri = build_hy2_uri(created, cfg)
click.echo(click.style(f"✔ User '{username}' created successfully!", fg="green"))
click.echo(f"Password: {created['password']}")
click.echo(f"Traffic: {traffic or 'Unlimited'} GB | Expiration: {days or 'Unlimited'} days")
click.echo(f"\nConnection URI:\n{uri}\n")
click.echo(f"Client Portal: /portal/{created['sub_token']}")
run_async(_add())
@cli.command("list-users")
def list_users():
"""List all registered proxy users."""
async def _list():
await init_db()
users = await crud.get_all_users()
if not users:
click.echo("No users registered yet.")
return
click.echo(f"{'User':<15} {'Status':<12} {'Traffic (Used/Max)':<22} {'Days Left':<10} {'Max IPs':<10}")
click.echo("-" * 72)
for u in users:
status = "Blocked" if u["blocked"] else ("Expired" if u["is_expired"] else ("Limit" if u["is_limit_reached"] else "Active"))
max_tr = f"{u['max_traffic_gb']} GB" if u["max_traffic_gb"] > 0 else "Unlimited"
tr_str = f"{u['used_traffic_gb']} / {max_tr}"
days_str = str(u["days_left"]) if u["expiration_days"] > 0 else "∞"
click.echo(f"{u['username']:<15} {status:<12} {tr_str:<22} {days_str:<10} {u['max_ips']:<10}")
run_async(_list())
@cli.command("delete-user")
@click.argument("username")
def delete_user(username):
"""Delete a user."""
async def _del():
await init_db()
ok = await crud.delete_user(username)
if ok:
click.echo(click.style(f"✔ User '{username}' deleted.", fg="green"))
else:
click.echo(click.style(f"✖ User '{username}' not found.", fg="red"))
run_async(_del())
@cli.command("reset-user")
@click.argument("username")
def reset_user(username):
"""Reset user traffic usage to zero."""
async def _reset():
await init_db()
ok = await crud.reset_user_traffic(username)
if ok:
click.echo(click.style(f"✔ Traffic for user '{username}' reset.", fg="green"))
else:
click.echo(click.style(f"✖ User '{username}' not found.", fg="red"))
run_async(_reset())
@cli.command("show-user")
@click.argument("username")
def show_user(username):
"""Display user connection URI and portal link."""
async def _show():
await init_db()
u = await crud.get_user_by_username(username)
if not u:
click.echo(click.style(f"✖ User '{username}' not found.", fg="red"))
return
cfg = await crud.get_all_settings()
uri = build_hy2_uri(u, cfg)
click.echo(click.style(f"=== Connection Info: {username} ===", fg="cyan"))
click.echo(f"URI: {uri}")
click.echo(f"Portal: /portal/{u['sub_token']}")
run_async(_show())
@cli.command("gen-ip-cert")
@click.option("--ip", default=None, help="Server IP or domain")
def gen_cert(ip):
"""Generate self-signed certificate with IP SAN and pinSHA256."""
async def _gen():
await init_db()
server_ip = ip or await crud.get_setting("server_ip", "127.0.0.1")
sni = await crud.get_setting("sni", "bing.com")
cert_p, key_p, sha256_pin = generate_self_signed_cert(server_ip, sni=sni)
await crud.set_settings({"server_ip": server_ip, "cert_sha256": sha256_pin})
await apply_and_save_config()
restart_hysteria()
click.echo(click.style(f"✔ Generated IP certificate for {server_ip} with SNI '{sni}'", fg="green"))
click.echo(f"Certificate: {cert_p}")
click.echo(f"Private Key: {key_p}")
click.echo(f"pinSHA256: {sha256_pin}")
run_async(_gen())
@cli.command("status")
def server_status():
"""Check Hysteria 2 and Panel status."""
active = is_hysteria_running()
ver = get_hysteria_version()
click.echo(f"Hysteria 2 Core: {'RUNNING' if active else 'STOPPED'} (Version: {ver})")
@cli.command("restart")
def restart_services():
"""Restart Hysteria 2 core."""
ok, out = restart_hysteria()
if ok:
click.echo(click.style("✔ Hysteria 2 restarted successfully.", fg="green"))
else:
click.echo(click.style(f"✖ Restart failed: {out}", fg="red"))
@cli.command("set-admin-user")
@click.argument("new_username")
def set_admin_user(new_username):
"""Change admin username for web panel."""
async def _user():
await init_db()
await crud.set_setting("admin_username", new_username.strip())
click.echo(click.style(f"✔ Admin username changed to '{new_username.strip()}'.", fg="green"))
run_async(_user())
@cli.command("set-admin-password")
@click.argument("new_password")
def set_admin_pwd(new_password):
"""Set new admin password for web panel."""
async def _pwd():
await init_db()
h = hash_password(new_password)
await crud.set_setting("admin_password_hash", h)
click.echo(click.style("✔ Admin password updated successfully.", fg="green"))
run_async(_pwd())
@cli.command("set-panel-access")
@click.option("--port", default=None, help="Panel port")
@click.option("--path", default=None, help="Secret URL path")
@click.option("--theme", default=None, help="Decoy theme (nginx, innernode, docs, 404)")
def set_panel_access(port, path, theme):
"""Set custom panel port, secret URL path, and decoy theme."""
async def _set():
await init_db()
updates = {}
if port: updates["panel_port"] = str(port)
if path: updates["panel_secret_path"] = str(path).strip("/ ")
if theme: updates["decoy_theme"] = str(theme)
if updates:
await crud.set_settings(updates)
if port:
try:
open_firewall_port(int(port), "tcp")
except Exception:
pass
run_systemctl("restart", "innerblitz.service")
click.echo(click.style(f"✔ Panel access updated: Port={port or 'unchanged'}, Path=/{path or 'unchanged'}, Decoy Theme={theme or 'unchanged'}", fg="green"))
run_async(_set())
@cli.command("reset-panel-access")
@click.option("--port", default=None, help="Specific port (e.g. 8080)")
@click.option("--path", default=None, help="Specific path (e.g. panel)")
@click.option("--random", "use_random", is_flag=True, help="Generate random high port and random secret path")
@click.option("--reset-2fa", is_flag=True, help="Disable 2FA if locked out")
@click.option("--password", default=None, help="Optional new password")
def reset_panel_access(port, path, use_random, reset_2fa, password):
"""Reset Web Panel port, path, 2FA and admin credentials without clobbering unchanged fields."""
async def _reset():
await init_db()
updates = {}
cur_port = await crud.get_setting("panel_port", "8080")
cur_path = await crud.get_setting("panel_secret_path", "panel")
if use_random:
updates["panel_port"] = str(secrets.randbelow(40000) + 20000)
updates["panel_secret_path"] = generate_secret_path()
updates["decoy_enabled"] = "1"
updates["decoy_theme"] = "nginx"
else:
if port is not None:
updates["panel_port"] = str(port)
elif not password and not reset_2fa:
updates["panel_port"] = "8080"
else:
updates["panel_port"] = cur_port
if path is not None:
updates["panel_secret_path"] = str(path).strip("/ ")
elif not password and not reset_2fa:
updates["panel_secret_path"] = "panel"
else:
updates["panel_secret_path"] = cur_path
if reset_2fa:
updates["totp_enabled"] = "0"
updates["totp_secret"] = ""
updates["tg_2fa_enabled"] = "0"
click.echo(click.style("✔ 2FA authentication disabled.", fg="yellow"))
if password:
updates["admin_password_hash"] = hash_password(password)
click.echo(click.style("✔ Admin password updated.", fg="yellow"))
await crud.set_settings(updates)
try:
open_firewall_port(int(updates["panel_port"]), "tcp")
except Exception:
pass
run_systemctl("restart", "innerblitz.service")
ip = await crud.get_setting("server_ip", "127.0.0.1")
ssl_mode = await crud.get_setting("panel_ssl_mode", "http")
proto = "https" if ssl_mode in ("self_signed_ip", "domain", "https") else "http"
domain = await crud.get_setting("server_domain", "")
host = domain if (ssl_mode == "domain" and domain) else ip
click.echo(click.style("✔ Web panel access successfully updated!", fg="green", bold=True))
click.echo(f"Secret URL: {proto}://{host}:{updates['panel_port']}/{updates['panel_secret_path']}")
click.echo(f"Port: {updates['panel_port']} | Path: /{updates['panel_secret_path']}")
click.echo(click.style("✔ Service innerblitz.service restarted.", fg="green"))
run_async(_reset())
@cli.command("set-hysteria-port")
@click.argument("port", type=int)
def set_hysteria_port_cli(port):
"""Change Hysteria 2 UDP listening port safely."""
async def _p():
await init_db()
await crud.set_setting("listen_port", str(port))
open_firewall_port(port, "udp")
await apply_and_save_config()
ok, out = restart_hysteria()
if ok:
click.echo(click.style(f"✔ Hysteria 2 UDP port changed to {port}. Core restarted.", fg="green"))
else:
click.echo(click.style(f"✖ Failed to restart Hysteria: {out}", fg="red"))
run_async(_p())
@cli.command("set-port-hopping")
@click.option("--enable/--disable", default=None, help="Enable or disable port hopping")
@click.option("--range", "hop_range", default=None, help="Port hopping range (e.g. 20000:50000)")
def set_port_hopping_cli(enable, hop_range):
"""Configure UDP port hopping and firewall redirection rules."""
async def _h():
await init_db()
l_port = int(await crud.get_setting("listen_port", "443"))
cur_range = await crud.get_setting("port_hopping_range", "20000:50000")
cur_on = await crud.get_setting("port_hopping_enabled", "1") == "1"
new_range = hop_range.strip() if hop_range else cur_range
new_on = enable if enable is not None else cur_on
await crud.set_settings({
"port_hopping_range": new_range,
"port_hopping_enabled": "1" if new_on else "0"
})
configure_port_hopping(new_range, l_port, new_on)
await apply_and_save_config()
restart_hysteria()
click.echo(click.style(f"✔ Port hopping updated: {'ENABLED' if new_on else 'DISABLED'} (Range: {new_range})", fg="green"))
run_async(_h())
@cli.command("set-user-password")
@click.argument("username")
@click.argument("new_password")
def set_user_password_cli(username, new_password):
"""Change proxy client password."""
async def _up():
await init_db()
u = await crud.update_user(username, UserUpdate(password=new_password))
if u:
click.echo(click.style(f"✔ Password for user '{username}' successfully updated.", fg="green"))
else:
click.echo(click.style(f"✖ User '{username}' not found.", fg="red"))
run_async(_up())
@cli.command("get-system-info")
def get_system_info_cli():
"""Output system parameters in key=value format for shell menu integration."""
async def _info():
await init_db()
s = await crud.get_all_settings()
users = await crud.get_all_users()
active_u = len([u for u in users if not u.get("blocked") and not u.get("is_expired")])
click.echo(f"LISTEN_PORT={s.get('listen_port', '443')}")
click.echo(f"PORT_HOPPING_ENABLED={s.get('port_hopping_enabled', '1')}")
click.echo(f"PORT_HOPPING_RANGE={s.get('port_hopping_range', '20000:50000')}")
click.echo(f"PANEL_PORT={s.get('panel_port', '8080')}")
click.echo(f"PANEL_SECRET_PATH={s.get('panel_secret_path', 'panel')}")
click.echo(f"PANEL_SSL_MODE={s.get('panel_ssl_mode', 'http')}")
click.echo(f"SERVER_DOMAIN={s.get('server_domain', '')}")
click.echo(f"DECOY_ENABLED={s.get('decoy_enabled', '1')}")
click.echo(f"DECOY_THEME={s.get('decoy_theme', 'nginx')}")
click.echo(f"SNI={s.get('sni', 'bing.com')}")
click.echo(f"CERT_SHA256={s.get('cert_sha256', '')}")
click.echo(f"ADMIN_USERNAME={s.get('admin_username', 'admin')}")
click.echo(f"TLS_TYPE={s.get('tls_type', 'self_signed_ip')}")
click.echo(f"OBFS_TYPE={s.get('obfs_type', 'salamander')}")
click.echo(f"TOTAL_USERS={len(users)}")
click.echo(f"ACTIVE_USERS={active_u}")
run_async(_info())
@cli.command("reset-ports")
@click.option("--port", default=443, type=int, help="Hysteria 2 UDP port [default: 443]")
@click.option("--flush-hopping", is_flag=True, default=True, help="Flush port hopping iptables rules")
def reset_ports(port, flush_hopping):
"""Reset Hysteria 2 ports and flush port hopping firewall rules."""
async def _reset_p():
await init_db()
if flush_hopping:
flush_port_hopping()
click.echo(click.style("✔ Port hopping iptables rules flushed.", fg="yellow"))
await crud.set_settings({
"listen_port": str(port),
"port_hopping_enabled": "0"
})
open_firewall_port(port, "udp")
await apply_and_save_config()
ok, out = restart_hysteria()
if ok:
click.echo(click.style(f"✔ Hysteria 2 ports reset to UDP {port}. Core restarted.", fg="green"))
else:
click.echo(click.style(f"✖ Failed to restart Hysteria: {out}", fg="red"))
run_async(_reset_p())
@cli.command("disable-2fa")
def disable_2fa():
"""Emergency disable 2FA (TOTP and Telegram) to regain panel access."""
async def _dis():
await init_db()
await crud.set_settings({
"totp_enabled": "0",
"totp_secret": "",
"tg_2fa_enabled": "0"
})
click.echo(click.style("✔ All 2FA protections disabled. You can now log in with password only.", fg="green", bold=True))
run_async(_dis())
@cli.command("show-panel-url")
def show_panel_url():
"""Display current secret access URL for Web Panel."""
async def _show():
await init_db()
ip = await crud.get_setting("server_ip", "127.0.0.1")
port = await crud.get_setting("panel_port", "8080")
path = await crud.get_setting("panel_secret_path", "panel")
user = await crud.get_setting("admin_username", "admin")
ssl_mode = await crud.get_setting("panel_ssl_mode", "http")
proto = "https" if ssl_mode in ("self_signed_ip", "domain", "https") else "http"
domain = await crud.get_setting("server_domain", "")
host = domain if (ssl_mode == "domain" and domain) else ip
decoy_on = await crud.get_setting("decoy_enabled", "1") == "1"
theme = await crud.get_setting("decoy_theme", "nginx")
totp_on = await crud.get_setting("totp_enabled", "0") == "1"
tg_on = await crud.get_setting("tg_2fa_enabled", "0") == "1"
click.echo(click.style("\n=== InnerBlitz Stealth Panel Access ===", fg="cyan", bold=True))
click.echo(f"Web Panel URL: {proto}://{host}:{port}/{path}")
click.echo(f"SSL Mode: {ssl_mode.upper()} ({proto.upper()})")
click.echo(f"Secret Path: /{path}")
click.echo(f"Port: {port}")
click.echo(f"Decoy Root URL: {proto}://{host}:{port}/ (Статус: {'Активен' if decoy_on else 'Выключен'}, Тема: {theme})")
click.echo(f"Admin Username: {user}")
click.echo(f"2FA Status: {'Google TOTP' if totp_on else ('Telegram' if tg_on else 'Disabled')}\n")
run_async(_show())
@cli.command("set-panel-ssl")
@click.option("--mode", type=click.Choice(["http", "self_signed_ip", "domain"], case_sensitive=False), required=True, help="Web panel SSL mode")
@click.option("--domain", default=None, help="Domain name if mode is domain")
@click.option("--force-renew", is_flag=True, help="Force immediate certificate generation")
def set_panel_ssl(mode, domain, force_renew):
"""Configure Web Panel SSL mode (HTTP, 6-day self-signed IP cert, or Domain)."""
async def _ssl():
await init_db()
mode_lower = mode.lower()
ip = await crud.get_setting("server_ip", "127.0.0.1")
updates = {"panel_ssl_mode": mode_lower}
if domain:
updates["server_domain"] = domain.strip()
if mode_lower == "self_signed_ip":
generate_panel_cert(ip, valid_days=6)
info = get_cert_info()
click.echo(click.style(f"✔ Generated 6-day IP SAN certificate for {ip}.", fg="green", bold=True))
click.echo(f"Validity: 6 days (expires: {info.get('expiry_iso', '')})")
click.echo("Auto-renewal: enabled (InnerBlitz auto-renews every 6 days)")
elif mode_lower == "domain":
dom = domain or await crud.get_setting("server_domain", "")
if not dom:
click.echo(click.style("✖ Error: Domain name is required for domain SSL mode. Use --domain <name>", fg="red"))
return
generate_panel_cert(dom, valid_days=90)
click.echo(click.style(f"✔ Configured domain certificate for {dom}.", fg="green"))
else:
click.echo(click.style("✔ Web panel SSL disabled. Panel will run over plain HTTP.", fg="yellow"))
await crud.set_settings(updates)
run_systemctl("restart", "innerblitz.service")
click.echo(click.style("✔ Service innerblitz.service restarted.", fg="green"))
run_async(_ssl())
@cli.command("renew-panel-cert")
@click.option("--force", is_flag=True, help="Force regeneration regardless of expiry")
@click.option("--check-only", is_flag=True, help="Check and renew only if < 1 day remaining")
def renew_panel_cert(force, check_only):
"""Renew the 6-day self-signed IP certificate for Web Panel."""
async def _renew():
await init_db()
ssl_mode = await crud.get_setting("panel_ssl_mode", "http")
if ssl_mode != "self_signed_ip" and not force:
click.echo(f"Panel is in '{ssl_mode}' mode. 6-day IP renewal is only active for 'self_signed_ip' mode.")
return
ip = await crud.get_setting("server_ip", "127.0.0.1")
info = get_cert_info()
if check_only and not force:
if info.get("days_left", 0.0) > 1.0 and not info.get("is_expired"):
click.echo(f"Certificate is still valid ({info.get('days_left')} days left). No renewal needed.")
return
cert_p, key_p, sha = generate_panel_cert(ip, valid_days=6)
click.echo(click.style(f"✔ 6-day Web Panel IP certificate successfully renewed for {ip}!", fg="green", bold=True))
click.echo(f"Certificate: {cert_p}")
click.echo(f"SHA-256: {sha}")
run_systemctl("restart", "innerblitz.service")
click.echo(click.style("✔ Service innerblitz.service restarted with new certificate.", fg="green"))
run_async(_renew())
@cli.command("show-panel-ssl")
def show_panel_ssl():
"""Inspect current Web Panel SSL/TLS configuration and certificate status."""
async def _status():
await init_db()
ssl_mode = await crud.get_setting("panel_ssl_mode", "http")
ip = await crud.get_setting("server_ip", "127.0.0.1")
domain = await crud.get_setting("server_domain", "")
info = get_cert_info()
click.echo(click.style("\n=== Web Panel SSL / TLS Status ===", fg="cyan", bold=True))
click.echo(f"SSL Mode: {ssl_mode.upper()}")
click.echo(f"Protocol: {'https://' if ssl_mode in ('self_signed_ip', 'domain', 'https') else 'http://'}")
if ssl_mode == "self_signed_ip":
click.echo(f"Target IP: {ip}")
click.echo("Rotation Schedule: Every 6 days (Automated)")
click.echo(f"Cert Exists: {'Yes' if info.get('exists') else 'No'}")
click.echo(f"Days Remaining: {info.get('days_left', 0.0)} days ({info.get('hours_left', 0.0)} hours)")
click.echo(f"Expires At: {info.get('expiry_iso', 'N/A')}")
click.echo(f"Is Expired: {'YES - RENEWAL REQUIRED' if info.get('is_expired') else 'No'}\n")
elif ssl_mode == "domain":
click.echo(f"Domain Name: {domain or 'Not set'}")
click.echo(f"Cert Exists: {'Yes' if info.get('exists') else 'No'}")
click.echo(f"Days Remaining: {info.get('days_left', 0.0)} days\n")
else:
click.echo("Status: Plain HTTP without certificate (Fast & Clean)\n")
run_async(_status())
@cli.command("toggle-decoy")
@click.option("--enable/--disable", default=True, help="Enable or disable decoy site on root /")
@click.option("--theme", default=None, help="Camouflage theme: nginx, innernode, docs, 404")
def toggle_decoy(enable, theme):
"""Enable or disable Anti-RKN decoy site on root URL /."""
async def _decoy():
await init_db()
updates = {"decoy_enabled": "1" if enable else "0"}
if theme:
updates["decoy_theme"] = theme
await crud.set_settings(updates)
run_systemctl("restart", "innerblitz.service")
click.echo(click.style(f"✔ Anti-RKN Decoy site {'enabled' if enable else 'disabled'} (Theme: {theme or 'unchanged'}).", fg="green"))
run_async(_decoy())
@cli.command("optimize-bbr")
def optimize_bbr():
"""Enable Linux TCP BBR congestion control and optimize UDP buffers for max QUIC speed."""
try:
conf_content = """# InnerBlitz High-Performance Network Tuning for Hysteria 2 QUIC
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.rmem_default = 1048576
net.core.wmem_default = 1048576
net.core.optmem_max = 2048576
net.ipv4.udp_rmem_min = 16384
net.ipv4.udp_wmem_min = 16384
net.ipv4.ip_forward = 1
"""
sysctl_dir = Path("/etc/sysctl.d")
if sysctl_dir.exists():
conf_file = sysctl_dir / "99-innerblitz.conf"
with open(conf_file, "w") as f:
f.write(conf_content)
subprocess.run(["sysctl", "--system"], capture_output=True)
click.echo(click.style("✔ TCP BBR and high-speed UDP buffers successfully applied!", fg="green", bold=True))
else:
click.echo(click.style("✖ /etc/sysctl.d not found (Not a standard Linux OS)", fg="yellow"))
except Exception as e:
click.echo(click.style(f"✖ Failed to configure sysctl: {e}", fg="red"))
@cli.command("backup")
@click.option("--out", default=None, help="Output backup archive path")
def backup_system(out):
"""Create a backup archive of SQLite DB and certificates."""
try:
data_dir = Path(settings.DATA_DIR)
backup_dir = Path("/etc/hysteria/backups")
backup_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
target_file = Path(out) if out else backup_dir / f"innerblitz_backup_{timestamp}.tar.gz"
with tarfile.open(target_file, "w:gz") as tar:
if data_dir.exists():
tar.add(data_dir, arcname="data")
if Path(settings.HYSTERIA_CONFIG_PATH).exists():
tar.add(settings.HYSTERIA_CONFIG_PATH, arcname="config.yaml")
click.echo(click.style(f"✔ Backup created successfully: {target_file}", fg="green", bold=True))
except Exception as e:
click.echo(click.style(f"✖ Backup failed: {e}", fg="red"))
@cli.command("restore")
@click.argument("backup_file")
def restore_system(backup_file):
"""Restore SQLite DB and certificates from backup archive."""
try:
b_path = Path(backup_file)
if not b_path.exists():
click.echo(click.style(f"✖ Backup file not found: {backup_file}", fg="red"))
return
run_systemctl("stop", "innerblitz.service")
run_systemctl("stop", "hysteria-server.service")
with tarfile.open(b_path, "r:gz") as tar:
tar.extractall(path="/etc/hysteria")
run_systemctl("start", "innerblitz.service")
run_systemctl("start", "hysteria-server.service")
click.echo(click.style(f"✔ System restored successfully from {backup_file}!", fg="green", bold=True))
except Exception as e:
click.echo(click.style(f"✖ Restore failed: {e}", fg="red"))
@cli.command("set-sni")
@click.argument("sni_domain")
def set_sni(sni_domain):
"""Set custom SNI domain for clients to disguise traffic and bypass DPI."""
async def _sni():
await init_db()
dom = sni_domain.strip()
server_ip = await crud.get_setting("server_ip", "127.0.0.1")
tls_type = await crud.get_setting("tls_type", "self_signed_ip")
updates = {
"sni": dom,
"masquerade_target": f"https://{dom}"
}
if tls_type == "self_signed_ip":
cert_p, key_p, sha256_pin = generate_self_signed_cert(server_ip, sni=dom)
updates["cert_sha256"] = sha256_pin
await crud.set_settings(updates)
await apply_and_save_config()
restart_hysteria()
click.echo(click.style(f"✔ Client SNI domain set to '{dom}'.", fg="green", bold=True))
if tls_type == "self_signed_ip":
click.echo(f"Certificate regenerated with SAN '{dom}'. pinSHA256: {updates.get('cert_sha256')}")
click.echo(click.style("✔ Hysteria 2 configuration updated and service restarted.", fg="green"))
run_async(_sni())
@cli.command("open-port")
@click.option("--port", "-p", required=True, type=int, help="Port number")
@click.option("--proto", type=click.Choice(["tcp", "udp", "both"], case_sensitive=False), default="tcp", help="Protocol")
@click.option("--comment", default="", help="Optional description")
def open_port_cli(port, proto, comment):
"""Open a port in the firewall and save to allowed list."""
import json
protos = ["tcp", "udp"] if proto.lower() == "both" else [proto.lower()]
for pr in protos:
open_firewall_port(port, pr)
async def _save():
await init_db()
raw = await crud.get_setting("custom_firewall_ports", "[]")
try:
ports = json.loads(raw)
except Exception:
ports = []
if not any(item.get("port") == port and item.get("proto") == proto.lower() for item in ports):
ports.append({"port": port, "proto": proto.lower(), "comment": comment or f"Port {port}", "created_at": datetime.now().strftime("%Y-%m-%d %H:%M")})
await crud.set_setting("custom_firewall_ports", json.dumps(ports))
click.echo(click.style(f"✔ Port {port}/{proto.upper()} successfully opened in firewall!", fg="green"))
run_async(_save())
@cli.command("close-port")
@click.option("--port", "-p", required=True, type=int, help="Port number")
@click.option("--proto", type=click.Choice(["tcp", "udp", "both"], case_sensitive=False), default="tcp", help="Protocol")
def close_port_cli(port, proto):
"""Remove a port rule from the firewall."""
import json
from app.core.firewall import close_firewall_port
protos = ["tcp", "udp"] if proto.lower() == "both" else [proto.lower()]
for pr in protos:
close_firewall_port(port, pr)
async def _remove():
await init_db()
raw = await crud.get_setting("custom_firewall_ports", "[]")
try:
ports = json.loads(raw)
except Exception:
ports = []
ports = [item for item in ports if not (item.get("port") == port and item.get("proto") == proto.lower())]
await crud.set_setting("custom_firewall_ports", json.dumps(ports))
click.echo(click.style(f"✔ Port {port}/{proto.upper()} rule removed from firewall.", fg="yellow"))
run_async(_remove())
@cli.command("list-ports")
def list_ports_cli():
"""List all open system and custom ports in firewall."""
import json
async def _list():
await init_db()
p = await crud.get_setting("panel_port", "8080")
h = await crud.get_setting("listen_port", "443")
hop_on = await crud.get_setting("port_hopping_enabled", "1") == "1"
hop_range = await crud.get_setting("port_hopping_range", "20000:50000")
sni = await crud.get_setting("sni", "bing.com")
raw = await crud.get_setting("custom_firewall_ports", "[]")
try:
c_ports = json.loads(raw)
except Exception:
c_ports = []
click.echo(click.style("\n=== InnerBlitz Port & Firewall Status ===", fg="cyan", bold=True))
click.echo(f"Policy: ACCEPT (Permissive / Все порты открыты без ограничений)")
click.echo(f"Web Panel Port: {p}/TCP")
click.echo(f"Hysteria 2 Port: {h}/UDP")
click.echo(f"Client SNI Domain: {sni}")
click.echo(f"Port Hopping: {'Active (' + hop_range + '/UDP)' if hop_on else 'Disabled'}")
if c_ports:
click.echo("\nCustom Opened Ports:")
for cp in c_ports:
click.echo(f" - {cp['port']}/{cp['proto'].upper()} ({cp.get('comment', '')})")
else:
click.echo("Custom Opened Ports: None")
click.echo("")
run_async(_list())
@cli.command("clear-logs")
def clear_logs_cli():
"""Clear and rotate system journalctl logs."""
from app.core.hysteria import clear_service_logs
ok, msg = clear_service_logs()
if ok:
click.echo(click.style(f"✔ {msg}", fg="green"))
else:
click.echo(click.style(f"✖ {msg}", fg="red"))
@cli.command("set-logging")
@click.option("--level", "-l", type=click.Choice(["debug", "info", "warn", "error"], case_sensitive=False), default="info", help="Log level")
@click.option("--zero-logs", is_flag=True, help="Disable log recording to disk (Zero-Logs privacy mode)")
def set_logging_cli(level, zero_logs):
"""Configure Hysteria log level and privacy mode."""
from app.core.hysteria import configure_service_logging
async def _set():
await init_db()
await crud.set_setting("log_level", level.lower())
await crud.set_setting("zero_logs", "1" if zero_logs else "0")
ok, msg = configure_service_logging(level=level, zero_logs=zero_logs)
if ok:
status = "ZERO-LOGS (Приватный режим: логи отключены)" if zero_logs else f"Уровень: {level.upper()}"
click.echo(click.style(f"✔ Логирование обновлено: {status}", fg="green"))
else:
click.echo(click.style(f"✖ Ошибка настройки: {msg}", fg="red"))
run_async(_set())
if __name__ == "__main__":
cli()