-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibc_tool.py
More file actions
executable file
·3913 lines (3566 loc) · 141 KB
/
Copy pathlibc_tool.py
File metadata and controls
executable file
·3913 lines (3566 loc) · 141 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
#!/usr/bin/env python3
import os
import re
import json
import gzip
import lzma
import shutil
import sys
import hashlib
import subprocess
import tarfile
import tempfile
import socket
import importlib.util
import urllib.request
import urllib.error
from contextlib import contextmanager
from concurrent.futures import ThreadPoolExecutor
from functools import partial
ORIGINAL_ARGV = sys.argv[1:]
PWN_IMPORT_ERROR = None
try:
from pwn import *
except Exception as e:
PWN_IMPORT_ERROR = e
class _FallbackContext:
cache_dir = None
log_level = 'info'
@contextmanager
def local(self, **_kwargs):
yield self
class _FallbackLog:
def _emit(self, level, message):
sys.stderr.write(f"[{level}] {message}\n")
def debug(self, message):
self._emit('*', message)
def info(self, message):
self._emit('*', message)
def warning(self, message):
self._emit('!', message)
def error(self, message):
self._emit('x', message)
def failure(self, message):
self._emit('-', message)
def success(self, message):
self._emit('+', message)
class _FallbackText:
pass
context = _FallbackContext()
log = _FallbackLog()
text = _FallbackText()
ELF = None
libcdb = None
LIBC_DB_PATH = "/home/starlight/CtfTools/libc-database/db"
LIBC_INDEX_CACHE = "/home/starlight/CtfTools/libc-database/db/.index_cache.json"
CACHE_SCHEMA_VERSION = 5
INDEX_BUILD_MAX_WORKERS = 8
FILE_ANALYSIS_CACHE = {}
ELF_FAST_INFO_CACHE = {}
COMMON_LIBC_SYMBOLS = [
'__libc_start_main',
'system',
'puts',
'printf',
'__isoc99_scanf',
'read',
'write',
'open',
'execve',
]
MATCH_TYPE_RANK = {
'exact_sha1': 50,
'exact': 40,
'symbol_address': 30,
'partial': 20,
'version': 10,
}
UBUNTU_GLIBC_MAP = {
"16.04": "2.23", "16.10": "2.24", "17.04": "2.25", "17.10": "2.26",
"18.04": "2.27", "18.10": "2.28", "19.04": "2.29", "19.10": "2.30",
"20.04": "2.31", "20.10": "2.32", "21.04": "2.33", "21.10": "2.34",
"22.04": "2.35", "22.10": "2.36", "23.04": "2.37", "23.10": "2.38",
"24.04": "2.39", "24.10": "2.40", "25.04": "2.41", "25.10": "2.42"
}
UBUNTU_CODENAME_MAP = {
"16.04": "xenial", "16.10": "yakkety", "17.04": "zesty", "17.10": "artful",
"18.04": "bionic", "18.10": "cosmic", "19.04": "disco", "19.10": "eoan",
"20.04": "focal", "20.10": "groovy", "21.04": "hirsute", "21.10": "impish",
"22.04": "jammy", "22.10": "kinetic", "23.04": "lunar", "23.10": "mantic",
"24.04": "noble", "24.10": "oracular", "25.04": "plucky", "25.10": "questing",
}
DEBIAN_GLIBC_MAP = {
"6": "2.11",
"7": "2.13",
"8": "2.19",
"9": "2.24",
"10": "2.28",
"11": "2.31",
"12": "2.36",
"13": "2.41",
}
DEBIAN_CODENAME_MAP = {
"6": "squeeze",
"7": "wheezy",
"8": "jessie",
"9": "stretch",
"10": "buster",
"11": "bullseye",
"12": "bookworm",
"13": "trixie",
"14": "forky",
"squeeze": "squeeze",
"wheezy": "wheezy",
"jessie": "jessie",
"stretch": "stretch",
"buster": "buster",
"bullseye": "bullseye",
"bookworm": "bookworm",
"trixie": "trixie",
"forky": "forky",
"sid": "sid",
"unstable": "sid",
"testing": "testing",
}
DEBIAN_CODENAME_SEARCH_ORDER = [
"trixie",
"bookworm",
"bullseye",
"buster",
"stretch",
"jessie",
"wheezy",
"squeeze",
"forky",
"sid",
"testing",
]
DEBIAN_GCC_RELEASE_MAP = {
"14.2.0": "13",
"12.2.0": "12",
"10.2.1": "11",
"10.2.0": "11",
"8.3.0": "10",
"6.3.0": "9",
"4.9.2": "8",
"4.8.4": "8",
"4.7.2": "7",
"4.4.7": "7",
}
SONAME_PACKAGE_HINTS = {
"libgcc_s.so.1": ["libgcc1", "libgcc-s1"],
"libstdc++.so.6": ["libstdc++6"],
"libseccomp.so.2": ["libseccomp2"],
}
ABI_VERSION_PREFIXES_BY_SONAME = {
"libstdc++.so.6": ("GLIBCXX_", "CXXABI_"),
"libgcc_s.so.1": ("GCC_",),
}
ABI_VERSION_TOKEN_RE = re.compile(
r'\b(?:GLIBCXX|CXXABI|GCC)_[0-9][A-Za-z0-9_.]*\b'
r'|\bGLIBC_(?:[0-9][A-Za-z0-9_.]*|ABI_[A-Za-z0-9_]+)\b'
)
GLIBC_RUNTIME_PREFIXES = ('GLIBC_',)
ANSI_CODES = {
"reset": "\033[0m",
"bold": "\033[1m",
"dim": "\033[2m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"magenta": "\033[35m",
"cyan": "\033[36m",
}
def stream_supports_color(stream):
if os.environ.get("NO_COLOR") is not None:
return False
force_color = os.environ.get("FORCE_COLOR")
if force_color is not None and force_color != "0":
return True
if os.environ.get("TERM", "").lower() == "dumb":
return False
try:
return stream.isatty()
except Exception:
return False
def colorize(text, *styles, stream):
text = str(text)
styler = getattr(globals().get('text'), "_".join(styles), None)
if callable(styler):
return styler(text)
if not stream_supports_color(stream):
return text
prefix = "".join(ANSI_CODES[name] for name in styles if name in ANSI_CODES)
if not prefix:
return text
return f"{prefix}{text}{ANSI_CODES['reset']}"
def stdout_style(text, *styles):
return colorize(text, *styles, stream=sys.stdout)
def stderr_style(text, *styles):
return colorize(text, *styles, stream=sys.stderr)
def stdout_heading(text):
return stdout_style(text, "bold", "blue")
def stdout_number(value):
return stdout_style(value, "bold", "yellow")
def stdout_path(text):
return stdout_style(text, "bold", "cyan")
def stdout_ok(text):
return stdout_style(text, "bold", "green")
def stderr_name(text):
return stderr_style(text, "bold", "cyan")
def stderr_path(text):
return stderr_style(text, "bold", "cyan")
def stderr_number(value):
return stderr_style(value, "bold", "yellow")
def stderr_version(value):
return stderr_style(value, "bold", "magenta")
def stderr_hash(value):
return stderr_style(value, "bold", "green")
def stderr_choice(value):
return stderr_style(value, "bold", "blue")
def stderr_hint(text):
return stderr_style(text, "bold", "green")
def ensure_pwntools_cache_dir():
if context.cache_dir:
return context.cache_dir
cache_bases = [
os.environ.get("XDG_CACHE_HOME"),
'/tmp',
os.path.join(os.getcwd(), '.cache'),
os.path.join(os.path.expanduser("~"), ".cache"),
]
cache_suffix = f".pwntools-cache-{sys.version_info.major}.{sys.version_info.minor}"
for base in cache_bases:
if not base:
continue
cache_dir = os.path.join(base, cache_suffix)
try:
os.makedirs(cache_dir, exist_ok=True)
except OSError:
continue
if not os.access(cache_dir, os.W_OK):
continue
context.cache_dir = cache_dir
if context.cache_dir:
return context.cache_dir
return None
def find_rust_core_binary():
candidates = []
env_path = os.environ.get("LIBC_TOOL_CORE")
if env_path:
candidates.append(env_path)
script_dir = os.path.dirname(os.path.abspath(__file__))
candidates.extend([
os.path.join(script_dir, 'libc_tool_core'),
os.path.join(script_dir, 'target', 'release', 'libc_tool_core'),
os.path.join(os.getcwd(), 'target', 'release', 'libc_tool_core'),
])
path_candidate = shutil.which('libc_tool_core')
if path_candidate:
candidates.append(path_candidate)
for candidate in candidates:
if candidate and os.path.isfile(candidate) and os.access(candidate, os.X_OK):
return candidate
return None
def run_rust_core(args, input_text, timeout=10):
core_path = find_rust_core_binary()
if not core_path:
return None
try:
result = subprocess.run(
[core_path] + list(args),
input=input_text or '',
capture_output=True,
text=True,
timeout=timeout,
env=readelf_env(),
)
except Exception as e:
log.debug(f"Rust core 执行失败: {e}")
return None
if result.returncode != 0:
detail = (result.stderr or result.stdout or '').strip()
log.debug(f"Rust core 返回失败: {detail}")
return None
return result.stdout
def inspect_elf_fast(elf_path):
abs_path = os.path.abspath(elf_path)
try:
stat_result = os.stat(abs_path)
except OSError:
return None
cache_key = (abs_path, stat_result.st_mtime_ns, stat_result.st_size)
cached = ELF_FAST_INFO_CACHE.get(cache_key)
if cached is not None:
return cached
core_output = run_rust_core(['inspect-elf', abs_path], '', timeout=5)
if core_output is None:
return None
try:
info = json.loads(core_output)
except json.JSONDecodeError as e:
log.debug(f"Rust core ELF JSON 解析失败: {e}")
return None
if not isinstance(info, dict):
return None
info.setdefault('build_id', None)
info.setdefault('arch', 'unknown')
info.setdefault('has_dynamic', False)
info.setdefault('has_debug', False)
info.setdefault('needed', [])
ELF_FAST_INFO_CACHE[cache_key] = info
return info
def libc_tool_cache_targets():
targets = []
cache_dir = ensure_pwntools_cache_dir()
if cache_dir:
for name in ('libc_tool_extra_libs', 'libcdb_libs', 'libcdb_dbg', 'libcdb'):
targets.append(os.path.join(cache_dir, name))
targets.append(LIBC_INDEX_CACHE)
return list(dict.fromkeys(targets))
def path_size(path):
if not os.path.exists(path):
return 0
if os.path.isfile(path) or os.path.islink(path):
try:
return os.path.getsize(path)
except OSError:
return 0
total = 0
for root, _dirs, files in os.walk(path):
for file_name in files:
file_path = os.path.join(root, file_name)
try:
total += os.path.getsize(file_path)
except OSError:
pass
return total
def format_bytes(size):
value = float(size)
for unit in ('B', 'KB', 'MB', 'GB'):
if value < 1024 or unit == 'GB':
if unit == 'B':
return f"{int(value)}{unit}"
return f"{value:.2f}{unit}"
value /= 1024
return f"{value:.2f}GB"
def clear_libc_tool_cache():
removed = []
skipped = []
total_size = 0
for target in libc_tool_cache_targets():
if not os.path.exists(target):
skipped.append(target)
continue
size = path_size(target)
try:
if os.path.isdir(target) and not os.path.islink(target):
shutil.rmtree(target)
else:
os.unlink(target)
except OSError as e:
log.warning(f"清理缓存失败: {stderr_path(target)} ({e})")
continue
total_size += size
removed.append((target, size))
return {
'removed': removed,
'skipped': skipped,
'bytes': total_size,
}
def readelf_env():
env = os.environ.copy()
env["LC_ALL"] = "C"
env["LANG"] = "C"
return env
def is_libc_family_name(name):
basename = os.path.basename(name).lower()
return (
basename.startswith("libc")
or basename in {"ld.so", "ld-linux.so.2", "ld-linux-x86-64.so.2"}
or re.fullmatch(r"ld-\d+(?:\.\d+)*\.so", basename) is not None
)
def is_shared_object_artifact(name):
basename = os.path.basename(name)
return (
re.search(r"\.so(?:\.[^/]+)*$", basename) is not None
or basename.startswith("ld-linux")
or re.fullmatch(r"ld-\d+(?:\.\d+)*\.so", basename) is not None
)
def guess_package_names_from_soname(soname):
candidates = list(SONAME_PACKAGE_HINTS.get(soname, ()))
match = re.match(r"^(lib[^/]+)\.so(?:\.([0-9][^/]*))?$", soname)
if match:
stem, abi = match.groups()
normalized = stem.replace("_", "-")
if abi:
candidates.extend([
f"{normalized}{abi}",
f"{normalized}-{abi}",
])
candidates.append(normalized)
deduped = []
seen = set()
for item in candidates:
if item and item not in seen:
deduped.append(item)
seen.add(item)
return deduped
def normalize_soname_list(items):
normalized = []
seen = set()
for item in items or ():
soname = (item or '').strip()
if not soname:
continue
if '.so' not in soname:
raise ValueError(f"无效的 soname: {item}")
if soname not in seen:
normalized.append(soname)
seen.add(soname)
return normalized
def parse_package_hint_specs(specs):
hints = {}
for raw_spec in specs or ():
spec = (raw_spec or '').strip()
if not spec:
continue
if '=' not in spec:
raise ValueError(f"无效的 --package-hint,期望 SONAME=PKG1,PKG2: {raw_spec}")
soname, package_blob = spec.split('=', 1)
soname = soname.strip()
if not soname or '.so' not in soname:
raise ValueError(f"无效的 --package-hint soname: {raw_spec}")
packages = []
for package_name in package_blob.split(','):
package_name = package_name.strip()
if not package_name:
continue
packages.append(package_name)
if not packages:
raise ValueError(f"无效的 --package-hint 包名列表: {raw_spec}")
target = hints.setdefault(soname, [])
for package_name in packages:
if package_name not in target:
target.append(package_name)
return hints
def normalize_package_name_list(items):
normalized = []
seen = set()
for item in items or ():
for raw_name in str(item).split(','):
package_name = raw_name.strip()
if not package_name:
continue
if not re.fullmatch(r"[A-Za-z0-9.+-]+", package_name):
raise ValueError(f"无效的包名: {package_name}")
if package_name not in seen:
normalized.append(package_name)
seen.add(package_name)
return normalized
def guess_package_names_from_soname_with_hints(soname, package_hints=None):
candidates = []
for item in (package_hints or {}).get(soname, ()):
if item not in candidates:
candidates.append(item)
for item in guess_package_names_from_soname(soname):
if item not in candidates:
candidates.append(item)
return candidates
def get_needed_shared_libraries(elf_path):
fast_info = inspect_elf_fast(elf_path)
if fast_info is not None and fast_info.get('needed'):
return list(dict.fromkeys(fast_info.get('needed') or []))
try:
result = subprocess.run(
['readelf', '-d', elf_path],
capture_output=True,
text=True,
check=False,
env=readelf_env(),
)
except Exception:
return []
if result.returncode != 0:
return []
needed = re.findall(r"Shared library:\s+\[(.+?)\]", result.stdout)
return list(dict.fromkeys(needed))
def get_requested_shared_libraries(elf_path=None, extra_needed=None):
requested = []
seen = set()
if elf_path and os.path.exists(elf_path):
for soname in get_needed_shared_libraries(elf_path):
if soname not in seen:
requested.append(soname)
seen.add(soname)
for soname in normalize_soname_list(extra_needed):
if soname not in seen:
requested.append(soname)
seen.add(soname)
return requested
def find_associated_elf_for_libc(libc_path):
parent_dir = os.path.dirname(os.path.abspath(libc_path))
if not parent_dir or not os.path.isdir(parent_dir):
return None
candidates = []
for entry in sorted(os.listdir(parent_dir)):
entry_path = os.path.join(parent_dir, entry)
if not os.path.isfile(entry_path):
continue
if os.path.abspath(entry_path) == os.path.abspath(libc_path):
continue
if is_libc_family_name(entry):
continue
if not is_elf_file(entry_path):
continue
needed = get_needed_shared_libraries(entry_path)
if 'libc.so.6' in needed:
candidates.append(entry_path)
if len(candidates) == 1:
log.info(f"自动关联 ELF: {stderr_path(candidates[0])}")
return candidates[0]
if len(candidates) > 1:
preferred = [path for path in candidates if os.access(path, os.X_OK)]
if len(preferred) == 1:
log.info(f"自动关联 ELF: {stderr_path(preferred[0])}")
return preferred[0]
log.warning("同目录存在多个 ELF,跳过额外依赖自动补全")
return None
def resolve_reference_elf(input_path):
if not input_path or not os.path.exists(input_path):
return None
if is_elf_file(input_path) and not is_libc_family_name(input_path):
return input_path
return find_associated_elf_for_libc(input_path)
def resolve_reference_elf_arg(input_path, explicit_elf=None):
if explicit_elf:
return os.path.abspath(explicit_elf)
return resolve_reference_elf(input_path)
def list_default_libc_candidates(search_dir):
if not search_dir or not os.path.isdir(search_dir):
return []
candidates = []
for entry in sorted(os.listdir(search_dir)):
entry_path = os.path.join(search_dir, entry)
if not os.path.isfile(entry_path):
continue
if not is_libc_family_name(entry):
continue
if not is_elf_file(entry_path):
continue
candidates.append(entry_path)
return candidates
def choose_default_libc_candidate(candidates):
if not candidates:
return None
versioned = [
path for path in candidates
if re.fullmatch(r"libc-\d+(?:\.\d+)*\.so", os.path.basename(path)) is not None
]
if len(versioned) == 1:
return versioned[0]
if len(versioned) > 1:
return None
canonical = [
path for path in candidates
if os.path.basename(path) == 'libc.so.6'
]
if len(canonical) == 1:
return canonical[0]
if len(canonical) > 1:
return None
libc_named = [
path for path in candidates
if os.path.basename(path).startswith('libc')
]
if len(libc_named) == 1:
return libc_named[0]
if len(candidates) == 1:
return candidates[0]
return None
def auto_resolve_input_file(input_path=None, reference_elf=None):
if input_path:
return os.path.abspath(input_path), []
search_dir = (
os.path.dirname(os.path.abspath(reference_elf))
if reference_elf else
os.getcwd()
)
candidates = list_default_libc_candidates(search_dir)
selected = choose_default_libc_candidate(candidates)
return selected, candidates
def get_download_target_dir(input_path, reference_elf=None):
preferred_path = reference_elf or input_path
if preferred_path:
base_dir = os.path.dirname(os.path.abspath(preferred_path))
else:
base_dir = os.getcwd()
return os.path.join(base_dir, 'libc_dir')
def get_directory_entry_names(target_dir):
try:
return {entry.name for entry in os.scandir(target_dir)}
except FileNotFoundError:
return set()
except NotADirectoryError:
return set()
def has_named_artifact(target_dir, name):
return name in get_directory_entry_names(target_dir)
def abi_version_prefixes_for_soname(soname):
return ABI_VERSION_PREFIXES_BY_SONAME.get(soname, ())
def abi_version_sort_key(token):
prefix, _sep, version = str(token).partition('_')
parts = []
for part in re.findall(r'\d+|[A-Za-z]+|[^A-Za-z\d]+', version):
if part.isdigit():
parts.append((0, int(part)))
else:
parts.append((1, part))
return prefix, tuple(parts)
def extract_abi_version_tokens(text_value, prefixes=None):
prefixes = tuple(prefixes or ())
core_output = run_rust_core(['extract-abi-tokens'] + list(prefixes), text_value or '')
if core_output is not None:
return {line.strip() for line in core_output.splitlines() if line.strip()}
tokens = set(ABI_VERSION_TOKEN_RE.findall(text_value or ''))
if prefixes:
tokens = {token for token in tokens if token.startswith(prefixes)}
return tokens
def parse_version_needs_by_file(readelf_version_output):
needs = {}
current_file = None
for line in (readelf_version_output or '').splitlines():
file_match = re.search(r'\bFile:\s+(\S+)', line)
if file_match:
current_file = file_match.group(1)
needs.setdefault(current_file, set())
if not current_file:
continue
for token in extract_abi_version_tokens(line):
needs.setdefault(current_file, set()).add(token)
return needs
def get_required_abi_versions_by_soname(elf_path):
if not elf_path or not os.path.exists(elf_path):
return {}
analysis = cached_file_analysis(elf_path)
needs_by_file = parse_version_needs_by_file(analysis.get('readelf_version', ''))
result = {}
fallback_text = "\n".join((
analysis.get('readelf_version', ''),
analysis.get('objdump_t', ''),
))
for soname, prefixes in ABI_VERSION_PREFIXES_BY_SONAME.items():
required = set()
for needed_file, tokens in needs_by_file.items():
if needed_file == soname:
required.update(token for token in tokens if token.startswith(prefixes))
if not required:
required.update(extract_abi_version_tokens(fallback_text, prefixes=prefixes))
if required:
result[soname] = required
return result
def get_required_abi_versions_for_soname(elf_path, soname):
prefixes = abi_version_prefixes_for_soname(soname)
if not prefixes:
return set()
return set(get_required_abi_versions_by_soname(elf_path).get(soname, set()))
def get_provided_abi_versions(library_path, soname=None):
prefixes = abi_version_prefixes_for_soname(soname) if soname else None
if not library_path or not os.path.exists(library_path):
return set()
analysis = cached_file_analysis(library_path)
text_value = "\n".join((
analysis.get('readelf_version', ''),
analysis.get('strings', ''),
analysis.get('objdump_t', ''),
))
return extract_abi_version_tokens(text_value, prefixes=prefixes)
def get_required_versions_from_needed_file(elf_path, needed_file, prefixes=None):
if not elf_path or not os.path.exists(elf_path):
return set()
needs_by_file = parse_version_needs_by_file(
cached_file_analysis(elf_path).get('readelf_version', '')
)
return extract_abi_version_tokens(
"\n".join(sorted(needs_by_file.get(needed_file, set()))),
prefixes=prefixes,
)
def get_required_libc_runtime_versions(library_path):
return get_required_versions_from_needed_file(
library_path,
'libc.so.6',
prefixes=GLIBC_RUNTIME_PREFIXES,
)
def get_provided_libc_runtime_versions(libc_path):
if not libc_path or not os.path.exists(libc_path):
return set()
analysis = cached_file_analysis(libc_path)
provided = set()
provided.update(extract_abi_version_tokens(
analysis.get('strings', ''),
prefixes=GLIBC_RUNTIME_PREFIXES,
))
provided.update(extract_abi_version_tokens(
analysis.get('readelf_version', ''),
prefixes=GLIBC_RUNTIME_PREFIXES,
))
provided.update(extract_abi_version_tokens(
analysis.get('objdump_t', ''),
prefixes=GLIBC_RUNTIME_PREFIXES,
))
return provided
def check_library_libc_runtime_compatibility(library_path, runtime_libc_path):
if not library_path or not os.path.exists(library_path):
return {
'ok': False,
'reason': 'missing',
'required': set(),
'provided': set(),
'missing': set(),
}
if not runtime_libc_path or not os.path.exists(runtime_libc_path):
return {
'ok': False,
'reason': 'runtime_libc_missing',
'required': set(),
'provided': set(),
'missing': set(),
}
required = get_required_libc_runtime_versions(library_path)
if not required:
return {
'ok': True,
'reason': 'no_runtime_version_requirement',
'required': required,
'provided': set(),
'missing': set(),
}
provided = get_provided_libc_runtime_versions(runtime_libc_path)
missing = required - provided
return {
'ok': not missing,
'reason': 'ok' if not missing else 'missing_runtime_versions',
'required': required,
'provided': provided,
'missing': missing,
}
def summarize_abi_versions(tokens, limit=4):
ordered = sorted(tokens or (), key=abi_version_sort_key)
if not ordered:
return '-'
if len(ordered) <= limit:
return ', '.join(ordered)
head = ', '.join(ordered[:limit])
return f"{head}, ... ({len(ordered)} 个)"
def find_library_artifact(root_dir, soname, require_dynamic=False):
if not root_dir or not soname or not os.path.isdir(root_dir):
return None
candidates = []
for root, _dirs, files in os.walk(root_dir):
for file_name in sorted(files):
if file_name == soname:
priority = 0
elif file_name.startswith(soname + '.'):
priority = 1
else:
continue
candidate = os.path.join(root, file_name)
if not os.path.isfile(candidate):
continue
if require_dynamic and is_elf_file(candidate) and not elf_has_dynamic_section(candidate):
continue
candidates.append((priority, len(file_name), candidate))
if not candidates:
return None
candidates.sort()
return candidates[0][2]
def check_library_abi_satisfaction(library_path, soname, required_versions=None):
required = set(required_versions or ())
if not library_path or not os.path.exists(library_path):
return {
'ok': False,
'reason': 'missing',
'required': required,
'provided': set(),
'missing': required,
}
if is_elf_file(library_path) and not elf_has_dynamic_section(library_path):
return {
'ok': False,
'reason': 'no_dynamic_section',
'required': required,
'provided': set(),
'missing': required,
}
if not required:
return {
'ok': True,
'reason': 'no_version_requirement',
'required': required,
'provided': set(),
'missing': set(),
}
provided = get_provided_abi_versions(library_path, soname=soname)
missing = required - provided
return {
'ok': not missing,
'reason': 'ok' if not missing else 'missing_versions',
'required': required,
'provided': provided,
'missing': missing,
}
def library_satisfies_abi_requirements(library_path, soname, elf_path=None, required_versions=None):
if required_versions is None:
required_versions = get_required_abi_versions_for_soname(elf_path, soname)
return check_library_abi_satisfaction(library_path, soname, required_versions=required_versions)
def library_satisfies_runtime_libc(library_path, runtime_libc_path):
return check_library_libc_runtime_compatibility(library_path, runtime_libc_path)
def get_missing_needed_libraries(elf_path, target_dir, extra_needed=None):
missing = []
present_names = get_directory_entry_names(target_dir)
required_versions_by_soname = get_required_abi_versions_by_soname(elf_path)
runtime_libc_path = find_library_artifact(target_dir, 'libc.so.6', require_dynamic=True)
for soname in get_requested_shared_libraries(elf_path, extra_needed=extra_needed):
if soname == 'libc.so.6':
continue
if soname in present_names:
library_path = find_library_artifact(target_dir, soname)
status = library_satisfies_abi_requirements(
library_path,
soname,
required_versions=required_versions_by_soname.get(soname, set()),
)
if status['ok']:
runtime_status = library_satisfies_runtime_libc(library_path, runtime_libc_path)
if runtime_status['ok']:
continue
missing.append(soname)
continue
missing.append(soname)
return missing
def find_nearest_existing_parent(path):
current = os.path.abspath(path)
while not os.path.exists(current):
parent = os.path.dirname(current)
if parent == current:
return None
current = parent
return current
def module_check(name):
try:
spec = importlib.util.find_spec(name)
except Exception:
spec = None
if spec is None:
return False, None
return True, spec.origin
def command_check(name):
path = shutil.which(name)
return bool(path), path
def tcp_probe(host, port, timeout=3):
try:
with socket.create_connection((host, port), timeout=timeout):
return True, f"{host}:{port}"
except Exception as e:
return False, str(e)
def append_doctor_check(checks, name, status, detail, required=True):
checks.append({
'name': name,
'status': status,
'detail': detail,
'required': required,
})
def run_doctor():
checks = []
append_doctor_check(
checks,
'python_version',
'ok',
f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
)
append_doctor_check(
checks,
'locale',
'ok',
f"LANG={os.environ.get('LANG', '') or '-'} LC_ALL={os.environ.get('LC_ALL', '') or '-'} readelf=LC_ALL=C",
)
pwn_ok = PWN_IMPORT_ERROR is None
append_doctor_check(
checks,
'python_module:pwn',
'ok' if pwn_ok else 'error',
'pwntools 已加载' if pwn_ok else f'缺少 pwntools: {PWN_IMPORT_ERROR}',
)
for module_name, required in [('unix_ar', False), ('zstandard', False)]:
ok, origin = module_check(module_name)
append_doctor_check(
checks,
f'python_module:{module_name}',
'ok' if ok else 'warning',
origin or '未安装',
required=required,
)
for cmd in ('readelf', 'objdump', 'strings'):
ok, path = command_check(cmd)