-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityNetworkGUI.py
More file actions
2349 lines (2070 loc) · 102 KB
/
SecurityNetworkGUI.py
File metadata and controls
2349 lines (2070 loc) · 102 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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Security Network - GUI Application (WiFi & Network Security)
# Standalone: all tools embedded, no dependency on SecurityNetwork.py
# Run: py -3 SecurityNetworkGUI.py
import sys
import os
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import threading
import platform
import subprocess
import re
import socket
import time
import random
import string
import uuid
import shutil
import concurrent.futures
import urllib.request
import urllib.parse
import ssl
import hashlib
import base64
import json
from datetime import datetime
from collections import defaultdict
if sys.version_info[0] < 3:
print("Python 3 required. Run: py -3 SecurityNetworkGUI.py")
sys.exit(1)
# ========== Embedded Security Network logic (standalone) ==========
def get_my_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except Exception:
return "127.0.0.1"
def get_arp_table_windows():
try:
out = subprocess.check_output(["arp", "-a"], shell=False, text=True, encoding="utf-8", errors="replace")
return out
except Exception as e:
return str(e)
def parse_arp_table(arp_text):
devices = []
for line in arp_text.splitlines():
match = re.search(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+([0-9a-fA-F\-]{17})", line)
if match:
ip, mac = match.groups()
if not ip.startswith("224.") and not ip.startswith("239."):
devices.append((ip.strip(), mac.strip()))
return devices
def get_connected_devices():
return parse_arp_table(get_arp_table_windows())
def ping_host(ip, timeout=1):
param = "-n" if platform.system().lower() == "windows" else "-c"
try:
subprocess.run(["ping", param, "1", "-w", str(timeout * 1000), ip], capture_output=True, timeout=timeout + 2)
except Exception:
pass
def scan_subnet_arp(my_ip=None):
if my_ip is None:
my_ip = get_my_ip()
parts = my_ip.split(".")
if len(parts) != 4:
return []
base = ".".join(parts[:3])
for i in range(1, 255):
ping_host("%s.%d" % (base, i))
return get_connected_devices()
def get_mac_vendor(mac):
mac_upper = mac.replace("-", ":").upper()[:8]
vendors = {
"00:50:56": "VMware", "00:0C:29": "VMware", "00:1A:2B": "Cisco", "08:00:27": "VirtualBox",
"52:54:00": "QEMU", "DC:A6:32": "Raspberry Pi", "B8:27:EB": "Raspberry Pi", "E4:5F:01": "Raspberry Pi",
"F4:5C:89": "Apple", "00:1E:C2": "Apple", "28:CF:E9": "Apple", "AC:DE:48": "Apple", "D0:03:4B": "Apple",
"00:17:88": "Philips Hue", "94:B9:7E": "TP-Link", "50:C7:BF": "TP-Link", "C0:25:E9": "TP-Link", "F8:1A:67": "TP-Link",
"E4:D3:32": "Xiaomi", "64:CC:2E": "Xiaomi", "34:80:B3": "Intel", "8C:EC:4B": "Intel", "30:65:EC": "Intel",
}
for prefix, name in vendors.items():
if mac_upper.startswith(prefix.replace(":", "")) or mac.replace("-", ":").upper().startswith(prefix):
return name
return "Unknown"
def get_wifi_adapter_name():
if platform.system().lower() != "windows":
return "WiFi"
try:
out = subprocess.check_output(
["netsh", "wlan", "show", "interfaces"],
shell=False, text=True, encoding="utf-8", errors="replace"
)
for line in out.splitlines():
if "Description" in line and ":" in line:
return line.split(":", 1)[-1].strip() or "WiFi"
except Exception:
pass
return "WiFi"
def wifi_analyzer_networks():
if platform.system().lower() != "windows":
return []
try:
out = subprocess.check_output(
["netsh", "wlan", "show", "networks", "mode=bssid"],
shell=False, text=True, encoding="utf-8", errors="replace"
)
except Exception:
return []
networks = []
current = None
for line in out.splitlines():
line_strip = line.strip()
if line_strip.startswith("SSID ") and ":" in line_strip:
if current and current.get("ssid") is not None:
networks.append(dict(current))
ssid = line_strip.split(":", 1)[-1].strip()
current = {"ssid": ssid, "bssid": "", "signal": 0, "channel": 0, "auth": "", "encryption": ""}
elif current is None:
continue
elif line_strip.startswith("BSSID ") and ":" in line_strip:
if current.get("bssid"):
networks.append(dict(current))
current["bssid"] = line_strip.split(":", 1)[-1].strip()
current["signal"] = 0
current["channel"] = 0
elif "Signal" in line_strip and ":" in line_strip:
try:
val = line_strip.split(":", 1)[-1].strip().replace("%", "").strip()
current["signal"] = int(val)
except ValueError:
pass
elif line_strip.startswith("Channel") and ":" in line_strip:
try:
current["channel"] = int(line_strip.split(":", 1)[-1].strip())
except ValueError:
pass
elif "Authentication" in line_strip and ":" in line_strip:
current["auth"] = line_strip.split(":", 1)[-1].strip()
elif "Encryption" in line_strip and ":" in line_strip:
current["encryption"] = line_strip.split(":", 1)[-1].strip()
if current and current.get("ssid") is not None:
networks.append(current)
return networks
def signal_pct_to_dbm(pct):
if pct is None or pct < 0:
pct = 0
if pct > 100:
pct = 100
return -50 - (100 - pct) * 0.5
def channel_to_band(ch):
if not ch or ch <= 0:
return "-"
if ch <= 14:
return "2.4 GHz"
if ch <= 165:
return "5 GHz"
return "6 GHz"
def speed_test(download_url=None, size_mb=1):
if download_url is None:
download_url = "https://speed.hetzner.de/1MB.bin"
try:
import urllib.request
req = urllib.request.Request(download_url, headers={"User-Agent": "SecurityNetwork"})
start = time.time()
with urllib.request.urlopen(req, timeout=30) as r:
data = r.read()
elapsed = time.time() - start
if elapsed <= 0:
return 0, 0, "Too fast to measure"
size_mb_actual = len(data) / (1024 * 1024)
mbps = (len(data) * 8 / 1_000_000) / elapsed
return round(mbps, 2), round(elapsed, 2), "%.2f MB in %.2f s" % (size_mb_actual, elapsed)
except Exception as e:
return 0, 0, str(e)
def get_dns_servers_windows():
try:
out = subprocess.check_output(["ipconfig", "/all"], shell=False, text=True, encoding="utf-8", errors="replace")
servers = re.findall(r"DNS Servers[^\d]*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", out, re.I)
servers += re.findall(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*\(Preferred\)", out, re.I)
return list(dict.fromkeys(servers))
except Exception:
return []
def network_interfaces():
try:
out = subprocess.check_output(["ipconfig", "/all"], shell=False, text=True, encoding="utf-8", errors="replace")
return out[:3000]
except Exception as e:
return str(e)
def random_password(length=16, with_special=True):
chars = string.ascii_letters + string.digits
if with_special:
chars += "!@#$%&*"
return "".join(random.SystemRandom().choice(chars) for _ in range(length))
def password_strength(pwd):
if not pwd:
return "Empty"
score = 0
if len(pwd) >= 8:
score += 1
if len(pwd) >= 12:
score += 1
if any(c.isupper() for c in pwd):
score += 1
if any(c.islower() for c in pwd):
score += 1
if any(c.isdigit() for c in pwd):
score += 1
if any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in pwd):
score += 1
labels = ["Very weak", "Weak", "Fair", "Good", "Strong", "Very strong", "Excellent"]
return labels[min(score, 6)]
def uuid_generate():
return str(uuid.uuid4())
def wifi_saved_profiles():
if platform.system().lower() != "windows":
return "Windows only"
try:
out = subprocess.check_output(
["netsh", "wlan", "show", "profiles"],
shell=False, text=True, encoding="utf-8", errors="replace"
)
return out[:2000]
except Exception as e:
return str(e)
def connection_state_summary():
try:
out = subprocess.check_output(["netstat", "-an"], shell=False, text=True, encoding="utf-8", errors="replace")
counts = {}
for line in out.splitlines():
for state in ["ESTABLISHED", "LISTENING", "TIME_WAIT", "CLOSE_WAIT", "SYN_SENT"]:
if state in line:
counts[state] = counts.get(state, 0) + 1
break
return "\n".join("%s: %d" % (k, v) for k, v in sorted(counts.items(), key=lambda x: -x[1]))
except Exception as e:
return str(e)
def bytes_to_units(n):
try:
n = int(n)
if n < 1024:
return "%d B" % n
if n < 1024 * 1024:
return "%.2f KB" % (n / 1024)
if n < 1024 * 1024 * 1024:
return "%.2f MB" % (n / (1024 * 1024))
return "%.2f GB" % (n / (1024 * 1024 * 1024))
except Exception:
return "Invalid"
def random_ip():
kind = random.choice([1, 2, 3])
if kind == 1:
return "10.%d.%d.%d" % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
if kind == 2:
return "172.%d.%d.%d" % (random.randint(16, 31), random.randint(0, 255), random.randint(0, 255))
return "192.168.%d.%d" % (random.randint(0, 255), random.randint(1, 254))
def user_agent_string():
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
def netstat_summary():
try:
out = subprocess.check_output(["netstat", "-an"], shell=False, text=True, encoding="utf-8", errors="replace")
established = sum(1 for line in out.splitlines() if "ESTABLISHED" in line)
listening = sum(1 for line in out.splitlines() if "LISTENING" in line)
return "ESTABLISHED: %d | LISTENING: %d" % (established, listening)
except Exception as e:
return str(e)
def route_table():
if platform.system().lower() != "windows":
return "Windows: route print"
try:
out = subprocess.check_output(["route", "print"], shell=False, text=True, encoding="utf-8", errors="replace")
return out[:4000]
except Exception as e:
return str(e)
def arp_table_full():
return get_arp_table_windows()
def firewall_status():
if platform.system().lower() != "windows":
return "Windows only"
try:
out = subprocess.check_output(
["netsh", "advfirewall", "show", "currentprofile"],
shell=False, text=True, encoding="utf-8", errors="replace"
)
return out[:1500]
except Exception as e:
return str(e)
def tcp_connect_test(host, port, timeout=3):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect((host, int(port)))
s.close()
return "OK - %s:%s reachable" % (host, port)
except Exception as e:
return "FAIL - %s" % e
# ========== Netcat-style (TCP connect / listen) ==========
def netcat_connect(host, port, send_data=None, timeout=5):
"""Connect to host:port, optionally send data, return received data (like netcat)."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect((host, int(port)))
out = []
if send_data:
s.sendall(send_data.encode("utf-8", errors="replace") if isinstance(send_data, str) else send_data)
try:
while True:
buf = s.recv(4096)
if not buf:
break
out.append(buf.decode("utf-8", errors="replace"))
except socket.timeout:
pass
s.close()
return "Connected to %s:%s\n\nReceived:\n%s" % (host, port, "".join(out)) if out else "Connected to %s:%s (no data received)" % (host, port)
except Exception as e:
return "FAIL - %s" % e
def netcat_listen(port, timeout=30):
"""Listen on port, accept one connection, return received data (like netcat -l)."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(timeout)
s.bind(("0.0.0.0", int(port)))
s.listen(1)
conn, addr = s.accept()
conn.settimeout(5)
out = []
try:
while True:
buf = conn.recv(4096)
if not buf:
break
out.append(buf.decode("utf-8", errors="replace"))
except socket.timeout:
pass
conn.close()
s.close()
return "Connection from %s:%s\n\nReceived:\n%s" % (addr[0], addr[1], "".join(out)) if out else "Connection from %s:%s (no data)" % (addr[0], addr[1])
except socket.timeout:
return "Listen on port %s: timeout (no connection)" % port
except Exception as e:
return "FAIL - %s" % e
def cidr_to_range(cidr):
try:
import ipaddress
net = ipaddress.ip_network(cidr, strict=False)
hosts = list(net.hosts())
if not hosts:
return "No hosts (e.g. /32)"
return "First: %s | Last: %s | Count: %d" % (hosts[0], hosts[-1], len(hosts))
except Exception as e:
return str(e)
def export_wifi_scan_to_file(path=None):
networks = wifi_analyzer_networks()
if path is None:
path = "wifi_scan_export.txt"
try:
with open(path, "w", encoding="utf-8") as f:
f.write("Security Network - WiFi Scan Export\n")
f.write("SSID | BSSID | Channel | Signal | Security\n")
f.write("-" * 60 + "\n")
for n in networks:
f.write("%s | %s | %s | %s | %s\n" % (
n.get("ssid", ""), n.get("bssid", ""), n.get("channel", ""),
n.get("signal", ""), n.get("auth", "")
))
return "Exported %d networks to %s" % (len(networks), path)
except Exception as e:
return str(e)
def export_devices_to_file(path=None):
devices = get_connected_devices()
if path is None:
path = "devices_export.txt"
try:
with open(path, "w", encoding="utf-8") as f:
f.write("Security Network - Devices Export\n")
f.write("IP | MAC | Vendor\n")
f.write("-" * 50 + "\n")
for ip, mac in devices:
f.write("%s | %s | %s\n" % (ip, mac, get_mac_vendor(mac)))
return "Exported %d devices to %s" % (len(devices), path)
except Exception as e:
return str(e)
def dns_servers_in_use():
dns = get_dns_servers_windows()
if not dns:
return "No DNS servers found (ipconfig /all)"
return "DNS in use: " + ", ".join(dns)
def get_drive_info():
"""Get Windows drive letters and info."""
if platform.system().lower() != "windows":
return "Windows only"
try:
drives = []
for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
drive = "%s:\\" % letter
if os.path.exists(drive):
drives.append(drive)
return "Drives: " + ", ".join(drives) if drives else "No drives found"
except Exception as e:
return str(e)
def get_drive_letters_short():
r"""Drive letters only for header display (e.g. C:\, D:\)."""
if platform.system().lower() != "windows":
return ""
try:
drives = [letter + ":\\" for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" if os.path.exists(letter + ":\\")]
return ", ".join(drives) if drives else ""
except Exception:
return ""
def get_hostname():
return socket.gethostname()
def get_gateway_windows():
try:
out = subprocess.check_output(["ipconfig"], shell=False, text=True, encoding="utf-8", errors="replace")
m = re.search(r"Default Gateway[^\d]*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", out, re.I)
return m.group(1) if m else None
except Exception:
return None
def my_public_ip():
try:
req = urllib.request.Request("https://api.ipify.org", headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=5) as r:
return r.read().decode().strip()
except Exception as e:
return "Error: %s" % str(e)
def scan_port(ip, port, timeout=0.5):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
r = s.connect_ex((ip, port))
s.close()
return (port, r == 0)
except Exception:
return (port, False)
def scan_ports(ip, ports=None, timeout=0.5, max_workers=50):
if ports is None:
ports = list(range(1, 1025))
open_ports = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
futures = {ex.submit(scan_port, ip, p, timeout): p for p in ports}
for f in concurrent.futures.as_completed(futures):
port, is_open = f.result()
if is_open:
open_ports.append(port)
return sorted(open_ports)
COMMON_PORTS = {
21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS", 80: "HTTP",
110: "POP3", 143: "IMAP", 443: "HTTPS", 445: "SMB", 3306: "MySQL",
3389: "RDP", 5432: "PostgreSQL", 5900: "VNC", 8080: "HTTP-Alt",
}
def dns_lookup(hostname):
try:
return list(set(socket.gethostbyname_ex(hostname)[2]))
except socket.gaierror:
try:
return [socket.gethostbyname(hostname)]
except Exception:
return []
except Exception as e:
return [str(e)]
def reverse_dns(ip):
try:
return socket.gethostbyaddr(ip)[0]
except Exception as e:
return str(e)
def ping_one(ip, timeout=1):
try:
param = "-n" if platform.system().lower() == "windows" else "-c"
r = subprocess.run(["ping", param, "1", "-w", str(timeout * 1000), ip], capture_output=True, text=True, timeout=timeout + 2)
return r.returncode == 0
except Exception:
return False
def ping_sweep(base_ip, start=1, end=255):
parts = base_ip.split(".")
if len(parts) != 4:
return []
base = ".".join(parts[:3])
alive = []
for i in range(start, min(end + 1, 256)):
ip = "%s.%d" % (base, i)
if ping_one(ip):
alive.append(ip)
return alive
def ping_latency(ip, count=4):
param = "-n" if platform.system().lower() == "windows" else "-c"
try:
out = subprocess.run(["ping", param, str(count), ip], capture_output=True, text=True, timeout=count * 3).stdout
ms = re.findall(r"(?:temps?|time)=?\s*(\d+)\s*ms?", out, re.I)
return [int(m) for m in ms]
except Exception:
return []
def traceroute(host, max_hops=30):
cmd = ["tracert", "-h", str(max_hops), host] if platform.system().lower() == "windows" else ["traceroute", "-m", str(max_hops), host]
try:
out = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
return out.stdout.splitlines() if out.stdout else []
except Exception as e:
return [str(e)]
def whois_lookup(domain_or_ip):
if shutil.which("whois"):
try:
r = subprocess.run(["whois", domain_or_ip], capture_output=True, text=True, timeout=15)
return r.stdout or r.stderr or "No output"
except Exception as e:
return str(e)
return "whois not installed (optional)."
def get_headers(url, timeout=10):
if not url.startswith(("http://", "https://")):
url = "https://" + url
try:
ctx = ssl.create_default_context()
req = urllib.request.Request(url, method="HEAD")
req.add_header("User-Agent", "SecurityNetwork/1.0")
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as r:
return dict(r.headers)
except Exception as e:
return {"Error": str(e)}
def check_security_headers(url):
headers = get_headers(url)
if "Error" in headers:
return [headers["Error"]]
important = ["Strict-Transport-Security", "X-Content-Type-Options", "X-Frame-Options", "Content-Security-Policy", "X-XSS-Protection"]
results = []
for h in important:
for k, v in headers.items():
if k.lower() == h.lower():
results.append("[OK] %s: %s" % (k, v))
break
else:
results.append("[--] Missing: %s" % h)
return results
def http_status(url):
if not url.startswith(("http://", "https://")):
url = "https://" + url
try:
req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=10) as r:
return "UP - Status: %s" % r.status
except urllib.error.HTTPError as e:
return "HTTP %s" % e.code
except Exception as e:
return "DOWN - %s" % e
def ssl_cert_info(host, port=443):
try:
hostname = host.replace("https://", "").replace("http://", "").split("/")[0].split(":")[0]
ctx = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=5) as sock:
with ctx.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
not_after = cert["notAfter"]
return "Valid until: %s" % not_after
except Exception as e:
return str(e)
def subnet_info(cidr):
try:
import ipaddress
net = ipaddress.ip_network(cidr, strict=False)
return {
"network": str(net.network_address),
"netmask": str(net.netmask),
"broadcast": str(net.broadcast_address),
"hosts_count": net.num_addresses - 2,
"first_host": str(list(net.hosts())[0]) if net.num_addresses > 2 else "N/A",
"last_host": str(list(net.hosts())[-1]) if net.num_addresses > 2 else "N/A",
}
except Exception as e:
return {"error": str(e)}
def get_connections_windows():
try:
out = subprocess.check_output(["netstat", "-an"], shell=False, text=True, encoding="utf-8", errors="replace")
lines = []
for line in out.splitlines():
if "ESTABLISHED" in line or "LISTENING" in line:
parts = line.split()
if len(parts) >= 4:
lines.append((parts[0], parts[1], parts[2], parts[3] if len(parts) > 3 else ""))
return lines
except Exception as e:
return [(str(e), "", "", "")]
def wake_on_lan(mac):
mac_clean = mac.replace(":", "").replace("-", "").upper()
if len(mac_clean) != 12:
return "Invalid MAC"
data = bytes.fromhex("FF" * 6 + mac_clean * 16)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(data, ("255.255.255.255", 9))
sock.close()
return "Magic packet sent to %s" % mac
except Exception as e:
return str(e)
def ip_geolocation(ip):
try:
url = "http://ip-api.com/json/%s?fields=country,regionName,city,isp,org,lat,lon" % ip
req = urllib.request.Request(url, headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=5) as r:
d = json.loads(r.read().decode())
return " | ".join("%s: %s" % (k, v) for k, v in d.items() if v)
except Exception as e:
return str(e)
def flush_dns():
try:
if platform.system().lower() == "windows":
out = subprocess.check_output(["ipconfig", "/flushdns"], shell=False, text=True, encoding="utf-8", errors="replace")
return "DNS cache flushed.\n" + out[:500]
return "Run manually: ipconfig /flushdns (Windows)"
except Exception as e:
return str(e)
def renew_dhcp():
try:
if platform.system().lower() == "windows":
out = subprocess.check_output(["ipconfig", "/renew"], shell=False, text=True, encoding="utf-8", errors="replace")
return "DHCP renewed.\n" + out[:500]
return "Run manually: ipconfig /renew (Windows)"
except Exception as e:
return str(e)
def url_encode(s):
return urllib.parse.quote(s, safe="")
def url_decode(s):
return urllib.parse.unquote(s)
def hash_string(s, algo="sha256"):
h = hashlib.new(algo)
h.update(s.encode("utf-8", errors="replace"))
return h.hexdigest()
def file_checksum(path, algo="sha256"):
try:
h = hashlib.new(algo)
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()
except Exception as e:
return str(e)
def base64_encode(s):
return base64.b64encode(s.encode("utf-8", errors="replace")).decode()
def base64_decode(s):
try:
return base64.b64decode(s).decode("utf-8", errors="replace")
except Exception as e:
return str(e)
def hex_encode(s):
return s.encode("utf-8", errors="replace").hex()
def hex_decode(s):
try:
return bytes.fromhex(s.replace(" ", "")).decode("utf-8", errors="replace")
except Exception as e:
return str(e)
def timestamp_to_date(ts):
try:
return datetime.utcfromtimestamp(int(ts)).strftime("%Y-%m-%d %H:%M:%S UTC")
except Exception:
return "Invalid"
def url_expand(url):
if not url.startswith(("http://", "https://")):
url = "https://" + url
try:
req = urllib.request.Request(url, method="GET", headers={"User-Agent": "SecurityNetwork"})
req.add_header("Accept", "*/*")
with urllib.request.urlopen(req, timeout=10) as r:
return r.geturl()
except Exception as e:
return str(e)
def json_validate(s):
try:
json.loads(s)
return "Valid JSON"
except json.JSONDecodeError as e:
return "Invalid: %s" % e
def ip_to_decimal(ip):
try:
parts = ip.split(".")
return str(int(parts[0]) * 256**3 + int(parts[1]) * 256**2 + int(parts[2]) * 256 + int(parts[3]))
except Exception as e:
return str(e)
def decimal_to_ip(dec):
try:
n = int(dec)
return "%d.%d.%d.%d" % ((n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255)
except Exception as e:
return str(e)
def hex_to_binary(hex_str):
try:
return bin(int(hex_str.replace(" ", ""), 16))[2:]
except Exception as e:
return str(e)
def binary_to_hex(bin_str):
try:
return hex(int(bin_str.replace(" ", ""), 2))[2:].upper()
except Exception as e:
return str(e)
def get_listening_ports():
try:
out = subprocess.check_output(["netstat", "-an"], shell=False, text=True, encoding="utf-8", errors="replace")
ports = set()
for line in out.splitlines():
if "LISTENING" in line:
parts = line.split()
if len(parts) >= 2:
addr = parts[1]
if ":" in addr:
port = addr.split(":")[-1]
if port.isdigit():
ports.add(int(port))
return sorted(ports)
except Exception as e:
return [str(e)]
def get_port_process(port):
try:
if platform.system().lower() == "windows":
out = subprocess.check_output(["netstat", "-ano"], shell=False, text=True, encoding="utf-8", errors="replace")
for line in out.splitlines():
if ":%s" % port in line and "LISTENING" in line:
parts = line.split()
if len(parts) >= 5:
pid = parts[-1]
return "Port %s used by PID: %s" % (port, pid)
return "Windows only (netstat -ano)"
except Exception as e:
return str(e)
def get_hosts_file():
try:
hosts_path = r"C:\Windows\System32\drivers\etc\hosts" if platform.system().lower() == "windows" else "/etc/hosts"
with open(hosts_path, "r", encoding="utf-8", errors="replace") as f:
return f.read()[:5000]
except Exception as e:
return str(e)
def get_system_info():
try:
info = []
info.append("OS: %s %s" % (platform.system(), platform.release()))
info.append("Architecture: %s" % platform.machine())
info.append("Processor: %s" % platform.processor())
info.append("Hostname: %s" % get_hostname())
info.append("Python: %s" % platform.python_version())
return "\n".join(info)
except Exception as e:
return str(e)
def wifi_networks_list():
try:
out = subprocess.check_output(["netsh", "wlan", "show", "networks"], shell=False, text=True, encoding="utf-8", errors="replace")
return out
except Exception as e:
return str(e)
# ========== Security tools (WiFi & Network) ==========
def wifi_security_scan():
"""Report WiFi security: open/weak/strong networks."""
networks = wifi_analyzer_networks()
if not networks:
return "No WiFi networks found. Run Scanner first."
lines = ["=== WiFi Security Scan ===\n"]
open_n = [n for n in networks if "Open" in (n.get("auth") or "")]
wep_n = [n for n in networks if "WEP" in (n.get("auth") or "")]
wpa2_n = [n for n in networks if "WPA2" in (n.get("auth") or "") or "WPA3" in (n.get("auth") or "")]
weak_n = [n for n in networks if n not in open_n and n not in wep_n and n not in wpa2_n]
lines.append("Open (no password): %d - RISK\n" % len(open_n))
for n in open_n[:5]:
lines.append(" - %s (%s)\n" % (n.get("ssid", ""), n.get("bssid", "")))
lines.append("WEP (weak): %d - RISK\n" % len(wep_n))
for n in wep_n[:5]:
lines.append(" - %s (%s)\n" % (n.get("ssid", ""), n.get("bssid", "")))
lines.append("WPA2/WPA3 (strong): %d - OK\n" % len(wpa2_n))
if weak_n:
lines.append("Other/weak: %d - check\n" % len(weak_n))
return "".join(lines)
def arp_guard_scan(duration_sec=10):
"""Detect ARP changes (possible spoofing / kick attempt)."""
my_ip = get_my_ip()
history = {}
alerts = []
start = time.time()
while (time.time() - start) < duration_sec:
devices = get_connected_devices()
for ip, mac in devices:
if ip == my_ip:
continue
if ip not in history:
history[ip] = mac
elif history[ip].upper() != mac.upper():
alerts.append("ALERT: %s changed MAC %s -> %s (possible ARP spoofing)" % (ip, history[ip], mac))
history[ip] = mac
time.sleep(2)
if not alerts:
return "ARP Guard: No changes detected in %d sec. OK." % duration_sec
return "ARP Guard - Alerts:\n" + "\n".join(alerts)
def dns_leak_check():
"""Check DNS servers (basic leak check: are you using expected DNS?)."""
dns = get_dns_servers_windows()
my_ip = get_my_ip()
lines = ["=== DNS Check ===\n"]
lines.append("Your DNS: %s\n" % (", ".join(dns) if dns else "None found"))
try:
req = urllib.request.Request("https://api.ipify.org", headers={"User-Agent": "SecurityNetwork"})
with urllib.request.urlopen(req, timeout=5) as r:
pub = r.read().decode().strip()
lines.append("Public IP: %s\n" % pub)
except Exception as e:
lines.append("Public IP: Error %s\n" % e)
if dns:
if "8.8.8.8" in dns or "1.1.1.1" in dns:
lines.append("Using public DNS (Google/Cloudflare).\n")
else:
lines.append("Using ISP/other DNS. No leak test run (use 8.8.8.8 or 1.1.1.1 for privacy).\n")
return "".join(lines)
def listening_ports_security():
"""List listening ports with security note."""
ports = get_listening_ports()
risky = {21: "FTP", 23: "Telnet", 135: "RPC", 445: "SMB", 3389: "RDP", 5900: "VNC"}
lines = ["=== Listening Ports (Security) ===\n"]
for p in ports[:50]:
note = risky.get(p, "")
if note:
lines.append("Port %d - %s - REVIEW (often targeted)\n" % (p, note))
else:
lines.append("Port %d\n" % p)
if len(ports) > 50:
lines.append("... and %d more\n" % (len(ports) - 50))
return "".join(lines)
def security_audit_quick():
"""Quick security audit: firewall, DNS, WiFi, ports."""
lines = ["=== Quick Security Audit ===\n"]
fw = firewall_status()
lines.append("Firewall: %s\n" % ("ON" if "ON" in fw.upper() or "ENABLED" in fw.upper() else "Check - " + fw[:80]))
dns = get_dns_servers_windows()
lines.append("DNS: %s\n" % (", ".join(dns) if dns else "None"))
networks = wifi_analyzer_networks()
open_n = len([n for n in networks if "Open" in (n.get("auth") or "")])
lines.append("WiFi: %d networks, %d open (risk)\n" % (len(networks), open_n))
ports = get_listening_ports()
lines.append("Listening ports: %d\n" % len(ports))
lines.append("Done.\n")
return "".join(lines)
# ========== End embedded logic ==========
APP_NAME = "Security Network"
APP_VERSION = "2.0"
APP_TAGLINE = "WiFi & Network Security"
TITLE = "%s v%s - %s" % (APP_NAME, APP_VERSION, APP_TAGLINE)
def get_adapter():
return get_wifi_adapter_name()
def get_networks():
return wifi_analyzer_networks()
def get_devices():
scan_subnet_arp(get_my_ip())
return get_connected_devices()
def signal_to_dbm(pct):
return int(signal_pct_to_dbm(pct or 0))
def get_vendor(mac):
return get_mac_vendor(mac)
def run_speed_test(callback):
def _run():
try:
mbps, sec, msg = speed_test()
callback(mbps, sec, msg)
except Exception as e:
callback(0, 0, str(e))
threading.Thread(target=_run, daemon=True).start()
class ScannerTab(ttk.Frame):
def __init__(self, parent, **kw):
super().__init__(parent, **kw)
self.setup_ui()
def setup_ui(self):
# Top: data source + Refresh
top = ttk.Frame(self)
top.pack(fill=tk.X, padx=5, pady=5)
ttk.Label(top, text="Showing data from:", font=("Segoe UI", 9)).pack(side=tk.LEFT)
self.adapter_var = tk.StringVar(value=get_adapter())
ttk.Label(top, textvariable=self.adapter_var, font=("Segoe UI", 9, "bold")).pack(side=tk.LEFT, padx=5)
ttk.Button(top, text="Refresh", command=self.refresh).pack(side=tk.RIGHT)
# Main: left sidebar (stats) + table
paned = ttk.PanedWindow(self, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Left sidebar - Filters / Stats
left = ttk.LabelFrame(paned, text="Filters", padding=5)
paned.add(left, weight=0)
self.stat_vars = {}
for key in ["Band", "SSID", "BSSID", "Vendor", "Security", "Signal"]:
f = ttk.Frame(left)
f.pack(fill=tk.X, pady=2)
ttk.Label(f, text="%s:" % key, width=10, anchor=tk.W).pack(side=tk.LEFT)
v = tk.StringVar(value="0")
self.stat_vars[key] = v
ttk.Label(f, textvariable=v, width=6).pack(side=tk.RIGHT)
# Table
right = ttk.Frame(paned)
paned.add(right, weight=1)
cols = ("SSID", "BSSID", "Vendor", "Channel", "Band", "Signal", "Security")
self.tree = ttk.Treeview(right, columns=cols, show="headings", height=12, selectmode="browse")
vsb = ttk.Scrollbar(right, orient=tk.VERTICAL, command=self.tree.yview)
hsb = ttk.Scrollbar(right, orient=tk.HORIZONTAL, command=self.tree.xview)
for c in cols:
self.tree.heading(c, text=c)