-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
4083 lines (3624 loc) · 154 KB
/
scanner.py
File metadata and controls
4083 lines (3624 loc) · 154 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
# === Minecraft Scanner by Cev-API ===
import shodan
import socket
import struct
import json
import re
import os
import random
import time
import shutil
from concurrent.futures import ThreadPoolExecutor, as_completed
from colorama import init, Fore, Style
import nbtlib
from nbtlib import Compound, String, Byte
# Hide console window
if os.name == "nt": __import__("ctypes").windll.user32.ShowWindow(__import__("ctypes").windll.kernel32.GetConsoleWindow(), 0)
# Tkinter + threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import threading
import base64
import io
try:
from PIL import Image, ImageTk
_PIL_AVAILABLE = True
except Exception:
_PIL_AVAILABLE = False
import hashlib
import uuid
import zlib
init(autoreset=True)
SHODAN_KEY_PATH = os.path.join(os.getcwd(), "shodan_key.txt")
GLOBAL_IP_LOG = "ips.txt"
TIMEOUT = 3
PROTOCOL_VERSION = 772
MAX_WORKERS = 100
SERVERS_DAT_PATH = os.path.expandvars(r"%APPDATA%\.minecraft\servers.dat")
BACKUP_PATH = SERVERS_DAT_PATH + ".bak"
IGNORE_FILE = "ignore.txt"
SAVED_FILE = "saved.txt"
DEFAULT_JSONL_FILE = "minecraft_servers.json"
USER_LOG_FILE = "user_log.json"
SERVER_MONITOR_FILE = "server_monitor_log.json"
DEFAULT_MONITOR_INTERVAL = 60
CRACKED_CACHE_FILE = "known_cracked_servers.json"
CRACKED_LOG_FILE = "cracked_scan.log"
CRACKED_VERIFY_WORKERS = 10
_CRACKED_CACHE_LOCK = threading.Lock()
def _load_cracked_cache():
if not os.path.exists(CRACKED_CACHE_FILE):
return {}
try:
with open(CRACKED_CACHE_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
return {}
_CRACKED_CACHE = _load_cracked_cache()
def _save_cracked_cache_locked():
try:
with open(CRACKED_CACHE_FILE, "w", encoding="utf-8") as f:
json.dump(_CRACKED_CACHE, f, indent=2)
except Exception:
pass
def get_cached_cracked_entry(ip_port):
with _CRACKED_CACHE_LOCK:
entry = _CRACKED_CACHE.get(ip_port)
return dict(entry) if entry else None
def record_cracked_server(ip_port, message="", extra=None):
data = {
"message": message or "",
"first_seen": time.time(),
"last_seen": time.time()
}
if isinstance(extra, dict):
data.update({
"motd": extra.get("motd", ""),
"version": extra.get("version", ""),
"players": extra.get("players", 0),
"max_players": extra.get("max_players", 0)
})
with _CRACKED_CACHE_LOCK:
existing = _CRACKED_CACHE.get(ip_port)
if existing:
data["first_seen"] = existing.get("first_seen", data["first_seen"])
_CRACKED_CACHE[ip_port] = data
_save_cracked_cache_locked()
try:
ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
line = f"{ts} | {ip_port} | {message or 'CRACKED'}\n"
with open(CRACKED_LOG_FILE, "a", encoding="utf-8") as f:
f.write(line)
except Exception:
pass
ICON_ENABLED = True
ICON_SIZE = 24
ICON_COL_EXTRA_PAD = 24
ICON_FETCH_TIMEOUT = 2
ICON_THREADS = 10
ICON_PLACEHOLDER = "#ffffff"
SKIP_CRACKED_VERSION_KEYWORDS = tuple(
s.lower() for s in (
"proxy",
"e4mc",
"maintenance",
"maintainance",
"§4maintenance"
)
)
# ========================================
def _load_key_from_cwd():
if os.path.exists(SHODAN_KEY_PATH):
with open(SHODAN_KEY_PATH, "r", encoding="utf-8") as f:
k = f.readline().strip()
return k or None
return None
def _save_key_to_cwd(k: str):
with open(SHODAN_KEY_PATH, "w", encoding="utf-8") as f:
f.write(k.strip() + "\n")
def ensure_shodan_key_ui(parent) -> str | None:
"""
Main-thread only. If no key file exists, prompt the user and save it.
Returns the key or None if the user cancels.
"""
key = _load_key_from_cwd()
if key:
return key
key = simpledialog.askstring(
"Shodan API Key",
"Enter your Shodan API key:",
parent=parent,
show="*" # hides the text while typing
)
if key:
_save_key_to_cwd(key)
return key.strip()
return None
# ========================================
def _extract_ip_port_from_text(s):
m = re.search(r'([0-9a-zA-Z\.\-]+):([0-9]{1,5})', s.strip())
if not m:
return None
return f"{m.group(1)}:{int(m.group(2))}"
def load_ignore_set():
s = set()
if os.path.exists(IGNORE_FILE):
with open(IGNORE_FILE, "r", encoding="utf-8") as f:
for line in f:
ip_port = _extract_ip_port_from_text(line)
if ip_port:
s.add(ip_port)
return s
IGNORE_SET = load_ignore_set()
def is_ignored(ip_port):
return ip_port in IGNORE_SET
def refresh_ignore_set(ip_port_added=None): #
global IGNORE_SET
if ip_port_added:
IGNORE_SET.add(ip_port_added)
else:
IGNORE_SET = load_ignore_set()
# ========================================
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def ask_yes_no(prompt):
return input(f"{prompt} (y/n): ").strip().lower().startswith('y')
def sanitize_query_for_filename(query):
return re.sub(r'[^a-zA-Z0-9]+', '_', query.strip().lower()).strip('_')
def is_valid_ip_port(entry):
return re.match(r"^\d{1,3}(\.\d{1,3}){3}:\d{1,5}$", entry)
def get_ip_only(line_or_ip): #
if " |" in line_or_ip:
line_or_ip = line_or_ip.split(" |")[0]
return _extract_ip_port_from_text(line_or_ip) or line_or_ip
# Common formatter so all tabs show exactly the same line format
def format_result_line(ip_port, motd, players_online, players_max, version): #
return f"{ip_port} | MOTD: {sanitize_motd(motd)} | Players: {players_online}/{players_max} | Version: {version}"
# Sorting helpers for Treeviews
def _players_key(val): # "6/73" -> 6
try:
return int(str(val).split("/", 1)[0])
except:
return -1
def _ip_key(val): # "a.b.c.d:port" -> (a,b,c,d,port)
s = str(val)
try:
host, port = s.split(":")
port = int(port)
except:
host, port = s, 0
parts = host.split(".")
if len(parts) == 4 and all(p.isdigit() for p in parts):
try:
return tuple(int(p) for p in parts) + (port,)
except:
return (0, 0, 0, 0, port)
return (999, 999, 999, 999, str(host), port)
def _version_key(val): # "1.21.1" -> (1,21,1)
t = []
for token in str(val).strip().split("."):
if token.isdigit():
t.append(int(token))
else:
nums = re.findall(r'\d+', token)
t.extend(int(n) for n in nums) if nums else t.append(0)
return tuple(t) if t else (0,)
def make_tree_sortable(tree, column_key_funcs): #
sort_state = {} # col -> bool
def sort_by(col):
reverse = sort_state.get(col, False)
rows = [(column_key_funcs.get(col, str)(tree.set(iid, col)), iid) for iid in tree.get_children("")]
rows.sort(reverse=reverse)
for idx, (_, iid) in enumerate(rows):
tree.move(iid, "", idx)
sort_state[col] = not reverse
for col in tree["columns"]:
tree.heading(col, command=lambda c=col: sort_by(c))
# Robust parser for "IP | MOTD: ... | Players: x/y | Version: ..."
def parse_formatted_line(line): #
ip = get_ip_only(line)
motd = ""
players = ""
version = ""
try:
m_motd = re.search(r"\bMOTD:\s*(.*?)\s*\|\s*Players:", line)
if m_motd:
motd = m_motd.group(1).strip()
m_pl = re.search(r"\bPlayers:\s*([^|]+)", line)
if m_pl:
players = m_pl.group(1).strip()
m_ver = re.search(r"\bVersion:\s*(.*)$", line)
if m_ver:
version = m_ver.group(1).strip()
except:
pass
return ip, motd, players, version
def sanitize_motd(m):
m = "" if m is None else str(m)
m = re.sub(r"§[0-9A-FK-ORa-fk-or]", "", m) # strip legacy MC color/style codes
return re.sub(r"\s+", " ", m.replace("\r", " ").replace("\n", " ")).strip()
def should_skip_cracked_probe(entry):
"""
Heuristic skip for proxies/non-standard servers that hang the faux login phase.
"""
version_raw = (entry.get("version") or "")
version_norm = version_raw.strip().lower()
version_plain = sanitize_motd(version_raw).lower()
if version_norm:
for key in SKIP_CRACKED_VERSION_KEYWORDS:
if key in version_norm or key in version_plain:
return True
return False
# ==================== SHODAN ====================
def get_user_query():
user_input = input('\nEnter Shodan Search Query (excluding "minecraft"): ').strip()
if user_input.lower().startswith("minecraft"):
user_input = user_input[len("minecraft"):].strip()
full_query = f"minecraft {user_input}"
return full_query
def search_shodan(query, api_key):
api = shodan.Shodan(api_key)
try:
results = api.search(query)
return results.get('matches', [])
except shodan.APIError as e:
# Let caller decide how to handle (invalid key, rate limit, etc.)
raise
def parse_description_from_raw(data_string):
desc_match = re.search(r"Description:\s*(.*?)\s*Online Players:", data_string, re.DOTALL)
return sanitize_motd(desc_match.group(1).strip() if desc_match else "N/A")
def parse_players(data_string):
match = re.search(r"Online Players:\s*(\d+)\s*Maximum Players:\s*(\d+)", data_string)
if match:
return f"{match.group(1)}/{match.group(2)}"
return "N/A"
def parse_version(data_string):
match = re.search(r"Version:\s*(.*?)\s*\(", data_string)
return match.group(1).strip() if match else "N/A"
def save_shodan_results(servers, filepath):
ip_set = set()
skipped_ignored = 0
with open(filepath, "w", encoding="utf-8") as f:
for server in servers:
ip = server.get("ip_str")
port = server.get("port", 25565)
data = server.get("data", "")
motd = parse_description_from_raw(data)
players = parse_players(data)
version = parse_version(data)
ip_port = f"{ip}:{port}"
if is_ignored(ip_port):
skipped_ignored += 1
continue
ip_set.add(ip_port)
line = f"{ip_port} | MOTD: {motd} | Players: {players} | Version: {version}"
f.write(line + "\n")
update_global_ip_log(ip_set)
if skipped_ignored:
print(Fore.YELLOW + f"Skipped {skipped_ignored} ignored entrie(s).")
def update_global_ip_log(new_entries):
updated_lines = {}
if os.path.exists(GLOBAL_IP_LOG):
with open(GLOBAL_IP_LOG, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
ip = line.strip().split(' |')[0]
updated_lines[ip] = line.strip()
for entry in new_entries:
if entry not in updated_lines and not is_ignored(entry):
updated_lines[entry] = f"{entry} | MOTD: N/A | Players: N/A | Version: N/A"
with open(GLOBAL_IP_LOG, 'w', encoding='utf-8') as f:
for line in sorted(updated_lines.values()):
f.write(line + "\n")
def read_servers(file):
with open(file, 'r', encoding='utf-8') as f:
return [line.strip().split(" |")[0] for line in f if line.strip()]
def split_host_port(entry):
match = re.match(r'^([0-9a-zA-Z\.\-]+):([0-9]+)', entry.strip())
if match:
return match.group(1), int(match.group(2))
raise ValueError(f"Invalid entry format: {entry}")
def _probe_cracked_entry(entry):
ip = entry.get("ip")
if not ip:
return None, "Missing IP"
try:
host, port = split_host_port(ip)
except ValueError as exc:
return None, str(exc)
result, message = is_cracked_server(host, port)
return result, message
def run_cracked_verifier_async(entries, callback, progress_cb=None):
"""
entries: list of ping_server dicts.
callback(entry, result, message, was_cached) invoked from the worker thread.
progress_cb(done, total) invoked after each entry is processed.
"""
def worker():
total = len(entries)
completed = 0
pending = []
for entry in entries:
ip = entry.get("ip")
cached = get_cached_cracked_entry(ip)
if cached:
callback(entry, True, cached.get("message") or "Cached cracked server", True)
completed += 1
if progress_cb:
progress_cb(completed, total)
else:
pending.append(entry)
if not pending:
return
with ThreadPoolExecutor(max_workers=CRACKED_VERIFY_WORKERS) as executor:
future_to_entry = {executor.submit(_probe_cracked_entry, entry): entry for entry in pending}
for fut in as_completed(future_to_entry):
entry = future_to_entry[fut]
try:
result, message = fut.result()
except Exception as exc:
result, message = None, str(exc)
if result is True:
record_cracked_server(entry.get("ip"), message, extra=entry)
callback(entry, result, message, False)
completed += 1
if progress_cb:
progress_cb(completed, total)
if not entries:
return
threading.Thread(target=worker, daemon=True).start()
# ==================== PING ====================
def varint_encode(number):
out = bytearray()
while True:
temp = number & 0b01111111
number >>= 7
if number != 0:
temp |= 0b10000000
out.append(temp)
if number == 0:
break
return bytes(out)
def write_string(s):
encoded = s.encode('utf-8')
return varint_encode(len(encoded)) + encoded
def varint_decode(sock):
number = 0
for i in range(5):
byte = sock.recv(1)
if not byte:
raise IOError("Socket closed")
byte = byte[0]
number |= (byte & 0x7F) << (7 * i)
if not (byte & 0x80):
break
return number
def parse_description(desc):
if isinstance(desc, str):
return sanitize_motd(desc)
elif isinstance(desc, dict):
if 'text' in desc:
return sanitize_motd(desc['text'])
elif 'extra' in desc:
return sanitize_motd(''.join([x.get('text', '') for x in desc['extra']]))
return ''
def ping_server(entry):
try:
host, port = split_host_port(entry)
with socket.create_connection((host, port), timeout=TIMEOUT) as sock:
sock.settimeout(TIMEOUT)
handshake = (
varint_encode(0x00) +
varint_encode(PROTOCOL_VERSION) +
write_string(host) +
struct.pack('>H', port) +
varint_encode(1)
)
sock.send(varint_encode(len(handshake)) + handshake)
sock.send(varint_encode(1) + b'\x00')
_ = varint_decode(sock)
_ = varint_decode(sock)
json_length = varint_decode(sock)
data = sock.recv(json_length).decode('utf-8')
response = json.loads(data)
motd = parse_description(response.get('description', ''))
players = response.get('players', {}).get('online', 0)
max_players = response.get('players', {}).get('max', 0)
# sample is a list of dicts like {"id": "uuid", "name": "playername"}
sample = response.get('players', {}).get('sample', []) or []
# Normalize sample to list of tuples (id, name)
players_sample = []
for p in sample:
try:
pid = str(p.get('id') or "")
pname = str(p.get('name') or "")
players_sample.append((pid, pname))
except Exception:
continue
# cracked detection: if any reported player id matches the offline-mode UUID for that name
def _offline_uuid_for_name(name: str) -> str:
# Replicate Java's UUID.nameUUIDFromBytes("OfflinePlayer:" + name)
h = hashlib.md5()
h.update(b"OfflinePlayer:")
h.update(name.encode('utf-8'))
d = bytearray(h.digest())
# set variant and version bits like Java's nameUUIDFromBytes (version 3)
d[6] = (d[6] & 0x0f) | 0x30
d[8] = (d[8] & 0x3f) | 0x80
return str(uuid.UUID(bytes=bytes(d)))
cracked = False
for pid, pname in players_sample:
if not pname:
continue
try:
off_uuid = _offline_uuid_for_name(pname).replace('-', '').lower()
reported = pid.replace('-', '').lower()
if reported == off_uuid:
cracked = True
break
except Exception:
continue
return {
'ip': f"{host}:{port}",
'players': players,
'max_players': max_players,
'motd': motd,
'version': response.get('version', {}).get('name', 'N/A'),
'players_sample': players_sample,
'cracked': cracked
}
except:
return None
def format_player_list(sample):
"""
Returns a comma-separated string of player names from the sample, or "-" if none.
"""
names = []
for item in sample or []:
name = None
if isinstance(item, (list, tuple)) and len(item) >= 2:
name = item[1]
elif isinstance(item, dict):
name = item.get("name")
if isinstance(name, str) and name.strip():
names.append(name.strip())
return ", ".join(names) if names else "-"
# ==================== CRACKED SERVER CHECKER ====================
PACKET_LENGTH_LIMIT_LOGIN = 100000
DEFAULT_STATUS_PROTOCOL = 773
USERNAME_PATTERN = re.compile(r"^[A-Za-z0-9_]{1,16}$")
def recv_varint(sock):
value = 0
shift = 0
while True:
raw = sock.recv(1)
if not raw:
raise ConnectionError("Socket closed while reading varint")
byte = raw[0]
value |= (byte & 0x7F) << shift
if not (byte & 0x80):
return value
shift += 7
if shift > 35:
raise ValueError("Varint too big")
def recv_exact(sock, length):
data = b""
while len(data) < length:
chunk = sock.recv(length - len(data))
if not chunk:
raise ConnectionError("Socket closed while reading data")
data += chunk
return data
def recv_mc_string(sock):
length = recv_varint(sock)
raw = recv_exact(sock, length)
return raw.decode("utf-8", errors="ignore")
def read_varint_from_bytes(buf, pos):
value = 0
shift = 0
while True:
if pos >= len(buf):
raise ValueError("Buffer ended while reading varint")
byte = buf[pos]
pos += 1
value |= (byte & 0x7F) << shift
if not (byte & 0x80):
break
shift += 7
if shift > 35:
raise ValueError("Varint too big in buffer")
return value, pos
def read_mc_string_from_bytes(buf, pos):
length, pos = read_varint_from_bytes(buf, pos)
end = pos + length
if end > len(buf):
raise ValueError("String length outside buffer")
raw = buf[pos:end]
pos = end
return raw.decode("utf-8", errors="ignore"), pos
def offline_uuid_nodash(name):
h = hashlib.md5()
h.update(b"OfflinePlayer:")
h.update(name.encode("utf-8"))
data = bytearray(h.digest())
data[6] = (data[6] & 0x0F) | 0x30
data[8] = (data[8] & 0x3F) | 0x80
return uuid.UUID(bytes=bytes(data)).hex
def get_server_status_info(host, port=25565):
sock = None
try:
sock = socket.create_connection((host, port), timeout=4)
handshake = (
varint_encode(0) +
varint_encode(DEFAULT_STATUS_PROTOCOL) +
write_string(host) +
struct.pack(">H", port) +
varint_encode(1)
)
sock.sendall(varint_encode(len(handshake)) + handshake)
sock.sendall(varint_encode(1) + b"\x00")
_ = recv_varint(sock)
_ = recv_varint(sock)
json_length = recv_varint(sock)
status_json = recv_exact(sock, json_length).decode("utf-8", errors="ignore")
data = json.loads(status_json)
proto = data.get("version", {}).get("protocol", DEFAULT_STATUS_PROTOCOL)
sample_names = []
sample_hint = None
players = data.get("players") or {}
samples = players.get("sample") or []
any_sample = False
any_offline_match = False
for player in samples:
name = player.get("name")
pid = player.get("id")
if not name or not pid:
continue
any_sample = True
sample_names.append(name)
offline_id = offline_uuid_nodash(name)
reported = pid.replace("-", "").lower()
if offline_id == reported:
any_offline_match = True
if any_sample:
sample_hint = True if any_offline_match else False
else:
sample_hint = None
return proto, sample_names, sample_hint
except Exception:
return DEFAULT_STATUS_PROTOCOL, [], None
finally:
if sock:
try:
sock.close()
except Exception:
pass
def get_server_protocol(host, port=25565):
proto, _, _ = get_server_status_info(host, port)
return proto
def build_login_start(username, protocol):
body = varint_encode(0)
body += write_string(username)
if protocol >= 759:
uid = uuid.uuid4()
body += uid.int.to_bytes(16, "big")
return body
def pick_username(sample_names):
valid = [name for name in sample_names if USERNAME_PATTERN.match(name)]
if valid:
return random.choice(valid)
return "Notch"
def login_probe(host, port=25565):
protocol, sample_names, sample_offline_hint = get_server_status_info(host, port)
username = pick_username(sample_names)
sock = None
saw_encryption_request = False
compression_threshold = -1
try:
sock = socket.create_connection((host, port), timeout=6)
sock.settimeout(2.0)
handshake = (
varint_encode(0) +
varint_encode(protocol) +
write_string(host) +
struct.pack(">H", port) +
varint_encode(2)
)
sock.sendall(varint_encode(len(handshake)) + handshake)
login_start = build_login_start(username, protocol)
sock.sendall(varint_encode(len(login_start)) + login_start)
while True:
packet_length = recv_varint(sock)
if packet_length > PACKET_LENGTH_LIMIT_LOGIN:
raise ValueError("Packet too large")
packet_data = recv_exact(sock, packet_length)
if compression_threshold >= 0:
data_len, pos = read_varint_from_bytes(packet_data, 0)
if data_len == 0:
buf = packet_data[pos:]
else:
buf = zlib.decompress(packet_data[pos:])
else:
buf = packet_data
pos = 0
packet_id, pos = read_varint_from_bytes(buf, 0)
if packet_id == 0x03:
threshold, _ = read_varint_from_bytes(buf, pos)
compression_threshold = threshold
continue
if packet_id == 0x01: # Encryption Request
saw_encryption_request = True
if sample_offline_hint is True:
return True, "CRACKED by players.sample UUID (but got Encryption Request; mixed signals)"
return False, "ONLINE-MODE (Mojang auth required)"
if packet_id == 0x02: # Login Success
msg = f"CRACKED (offline-mode) - login success as {username}"
if sample_offline_hint is True:
msg += " [players.sample also indicates offline-mode]"
elif sample_offline_hint is False:
msg += " [players.sample looks online-mode]"
return True, msg
if packet_id == 0x04: # Login Plugin Request
is_offline = (not saw_encryption_request) or (sample_offline_hint is True)
if is_offline:
return True, "CRACKED (offline-mode behind proxy/login plugin)"
return False, "ONLINE-MODE + login plugin (secure/proxied)"
if packet_id == 0x00: # Disconnect
reason, _ = read_mc_string_from_bytes(buf, pos)
low = (reason or "").lower()
clean = sanitize_motd(reason).lower()
if "whitelist" in clean or "white list" in clean:
return True, f"CRACKED (whitelist message: {sanitize_motd(reason)})"
if "outdated client" in low or "outdated server" in low:
return None, "VERSION MISMATCH (outdated client or server)"
if "rate" in low and "limit" in low:
return None, "RATE-LIMITED, slow down probes"
if sample_offline_hint is True:
return True, f"CRACKED by players.sample UUID (disconnect: {reason})"
if sample_offline_hint is False and saw_encryption_request:
return False, f"ONLINE-MODE (disconnect: {reason})"
return None, f"UNKNOWN MODE (disconnect: {reason})"
# Unknown login packets are ignored.
except socket.timeout:
if sample_offline_hint is True:
return True, "CRACKED by players.sample UUID, but login probe timed out"
return None, "Timed out waiting for login response"
except Exception as exc:
if sample_offline_hint is True:
return True, f"CRACKED by players.sample UUID, but login probe errored: {str(exc)[:60]}"
return None, f"Error: {str(exc)[:80]}"
finally:
if sock:
try:
sock.close()
except Exception:
pass
def is_cracked_server(host, port=25565):
"""
Returns (result, message) where result is True/False/None (cracked/online/unknown).
"""
return login_probe(host, port)
class UserLogManager:
"""
Thread-safe store that tracks the last seen server for each player name.
"""
def __init__(self):
self._entries = {} # player -> {"ip": ..., "motd": ..., "last_seen": ts}
self._lock = threading.Lock()
self._tab = None
self._load_from_disk()
def attach_tab(self, tab: "UserLogTab"):
self._tab = tab
tab.bind_manager(self)
tab.request_refresh(initial=True)
def snapshot(self):
with self._lock:
return [
{
"player": player,
"ip": data["ip"],
"motd": data["motd"],
"last_seen": data["last_seen"]
}
for player, data in self._entries.items()
]
def update_from_result(self, result: dict):
sample = result.get("players_sample") or []
if not sample:
return
ip = result.get("ip", "")
motd = result.get("motd", "")
now = time.time()
changed = False
with self._lock:
for _pid, pname in sample:
player = (pname or "").strip()
if not player:
continue
entry = self._entries.get(player)
if not entry or entry["ip"] != ip or entry["motd"] != motd:
self._entries[player] = {"ip": ip, "motd": motd, "last_seen": now}
else:
self._entries[player]["last_seen"] = now
changed = True
if changed:
self._save_to_disk()
self._notify_tab()
def _notify_tab(self):
if self._tab:
self._tab.request_refresh()
def _load_from_disk(self):
if not os.path.exists(USER_LOG_FILE):
return
try:
with open(USER_LOG_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
return
if not isinstance(data, list):
return
entries = {}
for row in data:
try:
player = (row.get("player") or "").strip()
if not player:
continue
ip = row.get("ip") or ""
motd = row.get("motd") or ""
ts = float(row.get("last_seen") or 0)
entries[player] = {"ip": ip, "motd": motd, "last_seen": ts}
except Exception:
continue
with self._lock:
self._entries = entries
def _save_to_disk(self):
snapshot = self.snapshot()
try:
with open(USER_LOG_FILE, "w", encoding="utf-8") as f:
json.dump(snapshot, f, indent=2)
except Exception:
pass
USER_LOG_MANAGER = UserLogManager()
def fetch_server_favicon_bytes(entry): # returns raw PNG bytes or None
try:
host, port = split_host_port(entry)
with socket.create_connection((host, port), timeout=ICON_FETCH_TIMEOUT) as sock:
sock.settimeout(ICON_FETCH_TIMEOUT)
handshake = (
varint_encode(0x00) +
varint_encode(PROTOCOL_VERSION) +
write_string(host) +
struct.pack('>H', port) +
varint_encode(1)
)
sock.send(varint_encode(len(handshake)) + handshake)
sock.send(varint_encode(1) + b'\x00')
_ = varint_decode(sock)
_ = varint_decode(sock)
json_length = varint_decode(sock)
data = sock.recv(json_length).decode('utf-8')
response = json.loads(data)
fav = response.get('favicon')
if isinstance(fav, str) and fav.startswith('data:image'):
b64 = fav.split(',', 1)[1]
return base64.b64decode(b64)
except Exception:
pass
return None
# GUI-friendly scan with streaming callbacks
def scan_servers_gui(servers, on_start=None, on_result=None, on_progress=None, login_probe=False):
filtered = [s for s in servers if not is_ignored(s)]
results, online_lines, updated_ips = [], [], {}
total, done = len(filtered), 0
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
def task(ip):
if on_start:
try: on_start(ip)
except Exception: pass
return ping_server(ip)
futures = {executor.submit(task, s): s for s in filtered}
for fut in as_completed(futures):
r = fut.result()
done += 1
if r:
results.append(r)
ip_key = r['ip']
line = f"{ip_key} | MOTD: {r['motd']} | Players: {r['players']}/{r['max_players']} | Version: {r['version']}"
updated_ips[ip_key] = line
if r['players'] > 0:
online_lines.append(line)
USER_LOG_MANAGER.update_from_result(r)
if on_result:
try: on_result(r, line)
except Exception: pass
if on_progress:
try: on_progress(done, total)
except Exception: pass
existing = {}
if os.path.exists(GLOBAL_IP_LOG):
with open(GLOBAL_IP_LOG, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
ip = line.strip().split(' |')[0]
existing[ip] = line.strip()
existing.update({k: v for k, v in updated_ips.items() if not is_ignored(k)})
with open(GLOBAL_IP_LOG, 'w', encoding='utf-8') as f:
for line in sorted(existing.values()):
f.write(line + "\n")
return results, online_lines
# ==================== Server Monitor State ====================
def load_server_monitor_state():
if not os.path.exists(SERVER_MONITOR_FILE):
return {"servers": {}}
try:
with open(SERVER_MONITOR_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
return {"servers": {}}
if not isinstance(data, dict):
return {"servers": {}}
data.setdefault("servers", {})
return data
def save_server_monitor_state(state):
try:
with open(SERVER_MONITOR_FILE, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2)
except Exception:
pass
def _ensure_monitor_server_entry(state, ip):