Repository navigation
Expand file tree
/
Copy pathphp2shell_kr.py
More file actions
executable file
·2136 lines (1949 loc) · 111 KB
/
Copy pathphp2shell_kr.py
File metadata and controls
executable file
·2136 lines (1949 loc) · 111 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
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Lee Jongyoung
"""php2shell-kr: PHP2Shell(CVE-2026-109618 / CVE-2026-109619) 로컬 점검 도구.
이 도구는 방어용입니다. 익스플로잇을 포함하지 않고 서버 설정·패키지를 바꾸지 않습니다.
신뢰할 수 있는 PHP 바이너리만 `-n -v` 로 실행합니다(--no-exec 로 끌 수 있음).
네트워크로 아무것도 보내지 않습니다. 조치는 명령으로 '출력'만 합니다.
python3 php2shell_kr.py # 이 서버의 PHP를 찾아 판정과 조치 계획 출력
python3 php2shell_kr.py --json # 기계가 읽는 JSON
python3 php2shell_kr.py --no-exec # 발견한 바이너리를 실행하지 않음(침해 의심 서버)
python3 php2shell_kr.py --root /mnt/img # 마운트한 파일시스템을 오프라인으로 점검
종료 코드: 0 조치 필요 없음 / 1 취약·EOL·재시작 필요 설치가 있음 / 3 확인 불가(권한 등).
표준 라이브러리만 사용하며 Python 3.6 이상에서 동작합니다.
"""
import argparse
import glob
import gzip
import json
import os
import hashlib
import fnmatch
import ntpath
import platform
import re
import shlex
import shutil
import socket
import subprocess
import stat
import sys
import time
import threading
from urllib.parse import urlsplit
__version__ = "1.0.0"
TOOL = "php2shell-kr"
# --- 권고 데이터 -----------------------------------------------------------------
# data/advisory.json 이 있으면 그것을 우선 쓰고(최신 데이터로 교체 가능), 없으면 아래 내장본을 씁니다.
# 내장본은 tools/sync_embedded_advisory.py 가 data/advisory.json 에서 생성합니다.
# BEGIN EMBEDDED ADVISORY
EMBEDDED_ADVISORY = json.loads(r'''{
"name": "PHP2Shell",
"cves": [
"CVE-2026-109618",
"CVE-2026-109619"
],
"cvss_v4": 9.2,
"as_of": "2026-10-23",
"summary_ko": "PHP 엔진의 메모리 안전성 결함으로 인증 없이 원격 코드 실행과 프로세스 메모리 노출이 가능합니다. 웹 요청을 처리하는 모든 SAPI(mod_php, PHP-FPM, php-cgi, FrankenPHP, LiteSpeed)가 해당합니다.",
"affected_range": "5.4 - 8.5 (8.6.0 RC3 이하 포함)",
"fixed_releases": {
"8.2": "8.2.35",
"8.3": "8.3.36",
"8.4": "8.4.27",
"8.5": "8.5.12",
"8.6": "8.6.0RC4"
},
"affected_no_official_fix": {
"eol_no_fix_branches": [
"5.4",
"5.5",
"5.6",
"7.0",
"7.1",
"7.2",
"7.3"
],
"source_backport_only_branches": [
"7.4",
"8.0",
"8.1"
]
},
"source_backport_urls": {
"7.4": "https://github.com/php/php-src/tree/PHP-7.4-CVE-2026-109618-109619",
"8.0": "https://github.com/php/php-src/tree/PHP-8.0-CVE-2026-109618-109619",
"8.1": "https://github.com/php/php-src/tree/PHP-8.1-CVE-2026-109618-109619"
},
"security_support_ends": {
"8.2": "2026-12-31"
},
"first_exploitation_observed": "2026-10-17",
"log_review_since_default": "2026-10-17",
"vendor_patch_evidence_cves": [
"CVE-2026-109618",
"CVE-2026-109619"
],
"interim_mitigation": {
"note_ko": "임시 조치는 일부 공격 경로만 줄이며 완전한 해결이 아닙니다. 업데이트만이 근본 조치입니다.",
"settings": [
{
"key": "session.upload_progress.enabled",
"value": "0",
"applies_to": [
"fpm",
"cgi",
"apache"
],
"admin_only": true
},
{
"key": "memory_limit",
"value": "-1",
"applies_to": [
"fpm",
"cgi",
"apache"
],
"admin_only": true,
"warning_ko": "메모리 상한이 없어지므로 컨테이너·cgroup·systemd MemoryMax 등 OS 수준 상한을 함께 설정해야 합니다. RLIMIT_AS/RLIMIT_DATA는 쓰지 마세요."
},
{
"key": "session.auto_start",
"value": "0",
"applies_to": [
"fpm",
"cgi",
"apache"
],
"admin_only": true,
"source": "Xint",
"warning_ko": "session_start()를 호출하지 않는 페이지의 세션 기능이 멈출 수 있습니다."
},
{
"key": "post_max_size",
"value": "8M",
"applies_to": [
"fpm",
"cgi",
"apache"
],
"admin_only": false,
"note_ko": "업로드가 필요 없으면 8M, 필요하면 32M 수준. upload_max_filesize는 post_max_size보다 작게 유지."
},
{
"key": "fatal_error_backtraces",
"value": "0",
"applies_to": [
"fpm",
"cgi",
"apache"
],
"admin_only": false,
"only_branches": [
"8.5"
]
}
]
},
"sources": [
{
"id": "php-official",
"title": "PHP.net Security advisory: Critical remote code execution vulnerabilities, update now",
"url": "https://www.php.net/archive/2026.php#2026-10-21-5",
"fetched": "2026-10-23"
},
{
"id": "ghsa-109618",
"title": "GHSA-w8hw-w9fx-j79w (CVE-2026-109618)",
"url": "https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w",
"fetched": "2026-10-23"
},
{
"id": "ghsa-109619",
"title": "GHSA-6wmf-4rv5-p3rp (CVE-2026-109619)",
"url": "https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp",
"fetched": "2026-10-23"
},
{
"id": "kisa",
"title": "KISA 보호나라: PHP 보안취약점(PHP2Shell) 관련 기업 보안 대응 수칙 (2026-10-22)",
"url": "https://www.boho.or.kr/kr/bbs/view.do?bbsId=B0000133&menuNo=205020&nttId=72230",
"fetched": "2026-10-23"
},
{
"id": "ncsc-nl",
"title": "NCSC-NL/CERT-EU php2shell operational information",
"url": "https://github.com/NCSC-NL/php2shell",
"fetched": "2026-10-23"
},
{
"id": "sysdig",
"title": "Sysdig: PHP2Shell detection and recommendations",
"url": "https://www.sysdig.com/blog/php2shell-cve-2026-109618-and-cve-2026-109619-detecting-unauthenticated-remote-code-execution-in-php-core",
"fetched": "2026-10-23"
},
{
"id": "xint",
"title": "Xint: PHP2Shell 긴급 대응 방안",
"url": "https://xint.io/ko/blog/php2shell-vulnerability-emergency-response",
"fetched": "2026-10-23"
}
]
}''')
# END EMBEDDED ADVISORY
class Advisory(dict):
"""권고 내용과 별도로 실제로 읽은 데이터의 출처를 보존한다."""
def clean(value):
return re.sub(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]", "?", str(value))
def markdown_value(value):
return clean(value).replace("&", "&").replace("<", "<").replace(">", ">").replace(
"`", "`").replace("|", "|")
def validate_advisory(data):
"""내장 스키마의 알려진 키/타입만 허용하며 코드/제어문자는 거부한다."""
def visit(value, template, key=""):
if type(value) is not type(template):
raise ValueError("권고 데이터 타입 오류: " + key)
if isinstance(value, dict):
if set(value) != set(template):
raise ValueError("권고 데이터 키 오류: " + key)
for child in value:
visit(value[child], template[child], child)
elif isinstance(value, list):
if not value or not template:
raise ValueError("빈 권고 목록: " + key)
if key == "settings" and len(value) != len(template):
raise ValueError("완화 설정 목록 오류")
for index, child in enumerate(value):
visit(child, template[index] if key == "settings" else template[0], key)
elif isinstance(value, str):
if len(value) > 4096 or clean(value) != value:
raise ValueError("권고 데이터 제어문자/길이 오류: " + key)
if key in ("cves", "vendor_patch_evidence_cves"):
valid = re.fullmatch(r"CVE-\d{4}-\d+", value)
elif key == "url" or key in EMBEDDED_ADVISORY["source_backport_urls"]:
url = urlsplit(value)
valid = (url.scheme in ("https", "http") and url.netloc and
not re.search(r"[\s'\"`\\<>]", value))
elif key.endswith("_ko") or key in ("title", "affected_range"):
valid = True
else:
valid = re.fullmatch(r"[0-9A-Za-z.\-+~: /_()]*", value)
if not valid:
raise ValueError("권고 데이터 값 오류: " + key)
elif isinstance(value, float) and not (0 <= value <= 10):
raise ValueError("권고 점수 오류")
visit(data, EMBEDDED_ADVISORY)
if set(data["cves"]) != set(EMBEDDED_ADVISORY["cves"]) or set(
data["vendor_patch_evidence_cves"]) != set(EMBEDDED_ADVISORY["cves"]):
raise ValueError("대상 CVE 불일치")
for branch, version in data["fixed_releases"].items():
if not re.fullmatch(re.escape(branch) + r"\.\d+(?:RC\d+)?", version):
raise ValueError("수정 버전 오류: " + branch)
return data
def load_advisory(path=None):
here = os.path.dirname(os.path.abspath(__file__))
candidates = [path] if path else [os.path.join(here, "data", "advisory.json"),
os.path.join(here, "advisory.json")]
for candidate in candidates:
if path or os.path.lexists(candidate):
raw = read_bytes(candidate, 2000000)
if raw is None:
raise ValueError("권고 데이터를 읽을 수 없습니다: " + clean(candidate))
data = Advisory(validate_advisory(json.loads(raw.decode("utf-8"))))
data.source = {"path": os.path.abspath(candidate), "sha256": hashlib.sha256(raw).hexdigest(),
"custom": bool(path)}
return data
raw = json.dumps(EMBEDDED_ADVISORY, ensure_ascii=False, sort_keys=True).encode("utf-8")
data = Advisory(validate_advisory(EMBEDDED_ADVISORY.copy()))
data.source = {"path": "embedded:" + os.path.abspath(__file__), "sha256": hashlib.sha256(raw).hexdigest(),
"custom": False}
return data
# --- 버전 판정 -------------------------------------------------------------------
_VERSION_RE = re.compile(
r"(?<![\d.])(\d+)\.(\d+)\.(\d+)(?:\.\d+)?(?:[-.]?(alpha|beta|RC|dev)\.?(\d*))?", re.IGNORECASE
)
_PRE_RANK = {"dev": 0, "alpha": 1, "beta": 2, "rc": 3}
_RELEASE_RANK = 9
def parse_version(text):
"""문자열에서 처음 나오는 X.Y.Z(+선택적 사전 릴리스 표기)를 (major, minor, patch, rank, num)로."""
match = _VERSION_RE.search((text or "")[:4096])
if not match:
return None
major, minor, patch = int(match.group(1)), int(match.group(2)), int(match.group(3))
tag = match.group(4)
if tag:
rank = _PRE_RANK[tag.lower()]
num = int(match.group(5)) if match.group(5) else 0
else:
rank, num = _RELEASE_RANK, 0
return (major, minor, patch, rank, num)
def classify(version_text, advisory):
"""업스트림 버전 번호만으로 분류. 벤더 백포트는 따로 판단한다."""
parsed = parse_version(version_text)
if parsed is None:
return "unknown"
major, minor = parsed[0], parsed[1]
branch = "%d.%d" % (major, minor)
if (major, minor) < (5, 4):
return "old_unsupported"
if branch in advisory["affected_no_official_fix"]["source_backport_only_branches"]:
return "eol_backport"
if (major, minor) <= (7, 3):
return "eol_no_fix"
fixed = advisory["fixed_releases"]
if branch in fixed:
return "fixed" if parsed >= parse_version(fixed[branch]) else "vulnerable"
if (major, minor) > (8, 6):
return "fixed"
return "unknown"
def verdict_for(cls, vendor_patch):
if cls == "fixed":
return "fixed"
if cls in ("vulnerable", "eol_backport", "eol_no_fix"):
return "vendor_patched" if vendor_patch == "yes" else "vulnerable"
if cls == "old_unsupported":
return "eol"
return "unknown"
VERDICT_KO = {
"fixed": "수정됨",
"vendor_patched": "벤더 패치 확인",
"vulnerable": "취약",
"eol": "지원 종료(EOL)",
"unknown": "확인 필요",
}
CLASS_KO = {
"fixed": "수정 버전 이상",
"vulnerable": "수정 전 버전",
"eol_backport": "공식 업데이트 없음(7.4/8.0/8.1: 벤더 패치 또는 소스 백포트만)",
"eol_no_fix": "EOL, 어디에도 수정 없음",
"old_unsupported": "5.4 미만, 오래전 지원 종료",
"unknown": "버전을 해석하지 못함",
}
# --- 실행 도우미 -----------------------------------------------------------------
SAFE_PATH = "/usr/sbin:/usr/bin:/sbin:/bin"
OUTPUT_LIMIT = 4096
PS_OUTPUT_LIMIT = 8 * 1024 * 1024 # 프로세스 목록은 4KB 를 훨씬 넘는다. 넘으면 뒤쪽 프로세스(php-fpm 등)를 놓친다
POWERSHELL_TIMEOUT = 90 # 최소 환경의 powershell.exe 는 시작에만 20~30초가 걸린다(실제 Windows 러너에서 측정, 상속 환경은 0.2초)
def privileged():
if os.name == "nt":
import ctypes
return bool(ctypes.windll.shell32.IsUserAnAdmin())
return hasattr(os, "geteuid") and os.geteuid() == 0
def windows_systemroot():
import ctypes
buffer = ctypes.create_unicode_buffer(32768)
length = ctypes.windll.kernel32.GetWindowsDirectoryW(buffer, len(buffer))
if not length or length >= len(buffer):
raise OSError("Windows 시스템 디렉터리를 확인할 수 없습니다")
return buffer.value
def helper_path(name):
if os.path.isabs(name):
return name
if os.name == "nt":
system = os.path.join(windows_systemroot(), "System32")
if name.lower() in ("powershell", "powershell.exe"):
return os.path.join(system, "WindowsPowerShell", "v1.0", "powershell.exe")
return os.path.join(system, name)
return shutil.which(name, path=SAFE_PATH)
def run(cmd, timeout=6, pass_fds=(), limit=OUTPUT_LIMIT):
"""최소 환경, 닫힌 stdin, 제한 시간 및 stdout 상한(기본 4096바이트). stderr는 보관하지 않는다."""
env = {"LC_ALL": "C", "PATH": SAFE_PATH}
if os.name == "nt":
systemroot = windows_systemroot()
env = {"SystemRoot": systemroot, "PATH": os.path.join(systemroot, "System32")}
proc = None
try:
command = list(cmd)
command[0] = helper_path(command[0])
if not command[0]:
return None, ""
options = {"pass_fds": pass_fds} if os.name != "nt" else {}
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
env=env, stdin=subprocess.DEVNULL, bufsize=0, **options)
chunks = []
def collect():
remaining = limit
try:
while remaining:
chunk = os.read(proc.stdout.fileno(), min(1024, remaining))
if not chunk:
return
chunks.append(chunk)
remaining -= len(chunk)
proc.kill()
except (OSError, ValueError):
pass
reader = threading.Thread(target=collect)
reader.daemon = True
reader.start()
try:
code = proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
code = None
reader.join(timeout=1)
proc.stdout.close()
return code, b"".join(chunks).decode("utf-8", "replace")
except (OSError, subprocess.SubprocessError, ValueError):
if proc is not None:
proc.kill()
proc.wait()
return None, ""
def open_directory(path):
"""POSIX: 전체 경로를 디렉터리 FD로 고정하며 중간 링크도 거부한다."""
directory = os.open(os.sep, os.O_RDONLY | os.O_DIRECTORY)
try:
for component in os.path.abspath(path).strip(os.sep).split(os.sep):
if not component:
continue
child = os.open(component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory)
os.close(directory)
directory = child
return directory
except BaseException:
os.close(directory)
raise
def resolve_inside(root, path):
"""루트 밖으로 나가는 링크와 '..'를 거부한다. 링크는 최대 40회만 해석한다."""
root = os.path.realpath(root)
path = os.path.abspath(path)
try:
if os.path.commonpath([root, path]) != root:
return None
except ValueError:
return None
todo = os.path.relpath(path, root).split(os.sep)
parts, links, directories = [], 0, []
try:
if os.name != "nt":
directories.append(open_directory(root))
while todo:
part = todo.pop(0)
if part in ("", "."):
continue
if part == "..":
if not parts:
return None
parts.pop()
if len(directories) > len(parts) + 1:
os.close(directories.pop())
continue
current = os.path.join(root, *(parts + [part]))
info = (os.stat(part, dir_fd=directories[-1], follow_symlinks=False)
if directories else os.lstat(current))
if stat.S_ISLNK(info.st_mode):
links += 1
if links > 40:
return None
target = os.readlink(part, dir_fd=directories[-1]) if directories else os.readlink(current)
if os.path.isabs(target):
if os.path.commonpath([root, target]) != root:
return None
parts = []
while len(directories) > 1:
os.close(directories.pop())
target = os.path.relpath(target, root)
todo = target.split(os.sep) + todo
else:
if getattr(info, "st_file_attributes", 0) & 0x400:
return None
parts.append(part)
if todo and directories:
directories.append(os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
dir_fd=directories[-1]))
return os.path.join(root, *parts)
except (OSError, ValueError):
return None
finally:
for directory in directories:
os.close(directory)
def under(root, path):
if not root or root == "/":
return path
return os.path.join(os.path.realpath(root), path.lstrip("/"))
def safe_glob(root, pattern, notes=None):
if not root:
return glob.glob(pattern)
paths = [os.path.realpath(root)]
for component in pattern.lstrip("/").split("/"):
children = []
for parent in paths:
# 이전 컴포넌트가 바뀌었다면 호스트 쪽을 열거하지 않는다.
resolved_parent = resolve_inside(root, parent)
if resolved_parent is None:
continue
try:
if os.name == "nt":
names = os.listdir(resolved_parent)
else:
directory = open_directory(resolved_parent)
try:
names = os.listdir(directory)
finally:
os.close(directory)
except OSError:
continue
for name in fnmatch.filter(names, component):
candidate = os.path.join(resolved_parent, name)
resolved = resolve_inside(root, candidate)
if resolved is not None:
children.append(resolved)
elif notes is not None:
notes.append("루트 밖/해석 불가 링크 제외: " + clean(candidate))
paths = children
return paths
def open_regular(path, limit, root=None):
"""링크를 먼저 해석한 후 모든 디렉터리를 NOFOLLOW로 열어 교체 경쟁도 차단한다."""
resolved = resolve_inside(root, path) if root else os.path.realpath(path)
# fallback: resolve_inside 가 심볼릭 링크 체인 등을 처리 못 해서 None 을 반환할 때,
# 여전히 루트 안이라면 realpath 로 폴백한다(보안: 루트 밖이면 거부).
if resolved is None and root:
try:
real = os.path.realpath(path)
if os.path.commonpath([os.path.realpath(root), real]) == os.path.realpath(root):
resolved = real
except OSError:
pass
if resolved is None:
return None
flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
directory = None
fd = None
try:
if os.name != "nt":
directory = open_directory(os.path.dirname(resolved))
fd = os.open(os.path.basename(resolved), flags, dir_fd=directory)
else:
fd = os.open(resolved, flags | getattr(os, "O_BINARY", 0))
info = os.fstat(fd)
if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
os.close(fd)
fd = None
return None
handle = os.fdopen(fd, "rb")
fd = None
return handle
except OSError:
if fd is not None:
os.close(fd)
return None
finally:
if directory is not None:
os.close(directory)
def read_bytes(path, limit, root=None):
handle = open_regular(path, limit, root)
if handle is None:
return None
try:
with handle:
data = handle.read(limit + 1)
return data if len(data) <= limit else None
except OSError:
return None
def read_text(path, limit=2000000, root=None):
data = read_bytes(path, min(limit, 2000000), root)
return "\n".join(line[:4096] for line in data.decode("utf-8", "replace").splitlines()) if data is not None else None
# --- Windows 신뢰 판정 (ACL) -----------------------------------------------------
# PowerShell 대신 advapi32 를 직접 부른다: 도구가 PowerShell 에 넘기는 최소 환경에서는 `powershell.exe` 가 명령 하나에
# 20~30초가 걸려(실제 Windows 러너에서 측정: 상속 환경 0.2초) 시간 제한에 걸렸고, 모듈·환경 변수 조작 가능성도 없앤다.
WINDOWS_TRUSTED_OWNERS = frozenset(("S-1-5-18", "S-1-5-32-544", "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"))
WINDOWS_UNTRUSTED_WRITERS = frozenset(("S-1-1-0", "S-1-5-32-545", "S-1-5-11")) # Everyone, Users, Authenticated Users
# WRITE_DATA/ADD_FILE 0x2, APPEND_DATA/ADD_SUBDIRECTORY 0x4, WRITE_EA 0x10, DELETE_CHILD 0x40, WRITE_ATTRIBUTES 0x100,
# DELETE 0x10000, WRITE_DAC 0x40000, WRITE_OWNER 0x80000, GENERIC_WRITE 0x40000000, GENERIC_ALL 0x10000000
WINDOWS_WRITE_MASK = 0x000D0156 | 0x40000000 | 0x10000000
WINDOWS_WRITE_MASK_ANCESTOR = WINDOWS_WRITE_MASK & ~0x6 # 새 파일/하위 폴더 만들기(0x2, 0x4)는 상위 폴더에서는 무시
def windows_acl_trusted(owner, aces, depth):
"""한 경로 구성요소의 ACL 이 신뢰할 만한지. aces: [(ace_type, ace_flags, rights, sid)] 또는 None(NULL DACL = 모두에게 허용).
depth 0 은 파일 자신, 1 은 그 파일이 든 폴더(앱 폴더), 2 이상은 그 위의 상위 폴더다.
파일과 앱 폴더는 전체 쓰기 권한을 본다: 앱 폴더에 새 파일을 만들 수 있으면 DLL 을 심어 실행을 가로챌 수 있다.
더 위의 상위 폴더는 새 파일/하위 폴더 만들기만 허용하는 권한을 무시한다: 기본 C:\\ 의 Authenticated Users:(AD) 가 그 예이며
이것으로는 이미 있는 하위 폴더를 바꾸거나 지울 수 없다. 해석할 수 없는 ACE 는 신뢰하지 않는다.
"""
if owner not in WINDOWS_TRUSTED_OWNERS or aces is None:
return False
mask = WINDOWS_WRITE_MASK if depth <= 1 else WINDOWS_WRITE_MASK_ANCESTOR
for ace_type, ace_flags, rights, sid in aces:
if ace_type == 1: # ACCESS_DENIED: 허용을 줄일 뿐이므로 무시
continue
if ace_type != 0: # ACCESS_ALLOWED 가 아닌 허용 계열(콜백·개체 ACE 등)은 해석하지 않고 거부
return False
if ace_flags & 0x08: # INHERIT_ONLY_ACE: 이 개체가 아니라 자식에게만 적용
continue
if sid in WINDOWS_UNTRUSTED_WRITERS and rights & mask:
return False
return True
def windows_path_trusted(path, acl_reader=None):
"""경로의 모든 구성요소(드라이브 루트까지)가 windows_acl_trusted 를 통과하고 링크가 없는지. 읽을 수 없으면 신뢰하지 않는다."""
reader = acl_reader or _windows_read_acl
current, depth = path, 0
try:
while True:
reparse, owner, aces = reader(current)
if reparse or not windows_acl_trusted(owner, aces, depth):
return False
parent = os.path.dirname(current)
if not parent or parent == current:
return True
current, depth = parent, depth + 1
except (OSError, ValueError):
return False
def _windows_read_acl(path):
"""(재해석 지점 여부, 소유자 SID 문자열, [(ace_type, ace_flags, rights, sid)] 또는 None). Windows 전용."""
import ctypes
from ctypes import wintypes
advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
pvoid = ctypes.c_void_p
advapi32.GetNamedSecurityInfoW.argtypes = [wintypes.LPCWSTR, ctypes.c_int, wintypes.DWORD, ctypes.POINTER(pvoid), ctypes.POINTER(pvoid),
ctypes.POINTER(pvoid), ctypes.POINTER(pvoid), ctypes.POINTER(pvoid)]
advapi32.GetNamedSecurityInfoW.restype = wintypes.DWORD
advapi32.GetAce.argtypes = [pvoid, wintypes.DWORD, ctypes.POINTER(pvoid)]
advapi32.GetAce.restype = wintypes.BOOL
advapi32.ConvertSidToStringSidW.argtypes = [pvoid, ctypes.POINTER(wintypes.LPWSTR)]
advapi32.ConvertSidToStringSidW.restype = wintypes.BOOL
kernel32.LocalFree.argtypes = [pvoid]
kernel32.LocalFree.restype = pvoid
kernel32.GetFileAttributesW.argtypes = [wintypes.LPCWSTR]
kernel32.GetFileAttributesW.restype = wintypes.DWORD
def sid_text(sid):
text = wintypes.LPWSTR()
if not advapi32.ConvertSidToStringSidW(sid, ctypes.byref(text)):
raise ctypes.WinError(ctypes.get_last_error())
try:
return text.value
finally:
kernel32.LocalFree(ctypes.cast(text, pvoid))
attributes = kernel32.GetFileAttributesW(path)
if attributes == 0xFFFFFFFF:
raise ctypes.WinError(ctypes.get_last_error())
owner, dacl, descriptor = pvoid(), pvoid(), pvoid()
# SE_FILE_OBJECT=1, OWNER_SECURITY_INFORMATION=1 | DACL_SECURITY_INFORMATION=4
status = advapi32.GetNamedSecurityInfoW(path, 1, 1 | 4, ctypes.byref(owner), None, ctypes.byref(dacl), None, ctypes.byref(descriptor))
if status != 0:
raise OSError(status, "GetNamedSecurityInfoW 실패")
try:
owner_sid = sid_text(owner)
aces = None
if dacl.value:
aces = []
ace_count = ctypes.c_ushort.from_address(dacl.value + 4).value # ACL.AceCount
for index in range(ace_count):
ace = pvoid()
if not advapi32.GetAce(dacl, index, ctypes.byref(ace)):
raise ctypes.WinError(ctypes.get_last_error())
ace_type = ctypes.c_ubyte.from_address(ace.value).value
ace_flags = ctypes.c_ubyte.from_address(ace.value + 1).value
rights = ctypes.c_uint32.from_address(ace.value + 4).value
# ACCESS_ALLOWED/DENIED_ACE 는 SID 가 마스크 바로 뒤(+8)에 온다. 다른 종류는 SID 를 읽지 않는다
sid = sid_text(pvoid(ace.value + 8)) if ace_type in (0, 1) else None
aces.append((ace_type, ace_flags, rights, sid))
return bool(attributes & 0x400), owner_sid, aces # FILE_ATTRIBUTE_REPARSE_POINT
finally:
kernel32.LocalFree(descriptor)
def trusted_binary(path, stat_fn=os.stat):
"""POSIX root 소유권/권한 검사. stat_fn 주입으로 비특권 테스트 가능. Windows 는 ACL(위 windows_path_trusted)."""
path = os.path.realpath(path)
if os.name == "nt":
return windows_path_trusted(path)
if any(path == p or path.startswith(p + "/") for p in
("/tmp", "/var/tmp", "/private/tmp", "/private/var/tmp", "/dev/shm", "/run/user", "/home", "/Users")):
return False
first = True
try:
while True:
info = stat_fn(path)
if info.st_uid != 0 or info.st_mode & 0o022:
return False
if first and not stat.S_ISREG(info.st_mode):
return False
if not first and not stat.S_ISDIR(info.st_mode):
return False
if path == os.path.dirname(path):
return True
path, first = os.path.dirname(path), False
except OSError:
return False
def ps_literal(value):
return "'" + re.sub(r"['\u2018\u2019\u201a\u201b]", lambda m: m.group(0) * 2, clean(value)) + "'"
def valid_unit(value):
return bool(re.fullmatch(r"[A-Za-z0-9@._:-]+\.(?:service|socket)", value))
def valid_package(value):
return bool(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9+_.:@-]*", value))
# --- 플랫폼 ----------------------------------------------------------------------
def detect_platform(root=None):
system = platform.system()
info = {"system": system, "pretty": "%s %s" % (system, platform.release()), "id": system.lower(),
"container": False, "pkg": None}
if system == "Linux":
osrel = read_text(under(root, "/etc/os-release"), root=root) or ""
values = {}
for line in osrel.splitlines():
if "=" in line:
key, _, value = line.partition("=")
values[key.strip()] = value.strip().strip('"')
info["id"] = values.get("ID", "linux")
info["id_like"] = values.get("ID_LIKE", "")
if values.get("PRETTY_NAME"):
info["pretty"] = values["PRETTY_NAME"]
# 호스트가 컨테이너인지는 실제 호스트를 볼 때만 의미가 있다(--root 로 다른 트리를 점검할 때는 알 수 없음).
if not root:
cgroup = read_text("/proc/1/cgroup") or ""
info["container"] = os.path.exists("/.dockerenv") or "docker" in cgroup or "kubepods" in cgroup
elif system == "Darwin":
info["pretty"] = "macOS %s" % platform.mac_ver()[0]
info["pkg"] = detect_package_manager(info, root)
return info
def detect_package_manager(info, root=None):
ident = set((info.get("id", "") + " " + info.get("id_like", "")).lower().split())
system = info.get("system")
if system == "Darwin":
return "brew"
if system == "Windows":
return "windows"
if system == "FreeBSD":
return "pkg"
if ident & {"debian", "ubuntu"}:
return "apt"
if ident & {"rhel", "fedora", "centos", "rocky", "almalinux", "alma", "amzn", "ol", "oracle"}:
return "dnf" if helper_path("dnf") or not helper_path("yum") else "yum"
if "alpine" in ident:
return "apk"
if ident & {"suse", "sles", "opensuse", "opensuse-leap", "opensuse-tumbleweed"}:
return "zypper"
for tool, name in (("apt-get", "apt"), ("dnf", "dnf"), ("yum", "yum"), ("apk", "apk"), ("zypper", "zypper")):
if helper_path(tool):
return name
return None
# --- 프로세스 열거 ---------------------------------------------------------------
_PHP_EXE_RE = re.compile(r"^(php(-fpm|-cgi|-win)?[0-9.]*|lsphp[0-9.]*|frankenphp)(\.exe)?$", re.IGNORECASE)
_APACHE_EXE_RE = re.compile(r"^(apache2|httpd|httpd\.worker|httpd\.event|httpd\.prefork)(\.exe)?$", re.IGNORECASE)
def sapi_from_name(name):
base = os.path.basename(name).lower()
if base.startswith("php-fpm"):
return "fpm"
if base.startswith("php-cgi") or base.startswith("php-win"):
return "cgi" if base.startswith("php-cgi") else "cli"
if base.startswith("lsphp"):
return "litespeed"
if base.startswith("frankenphp"):
return "frankenphp"
if base.startswith("libphp") or ("php" in base and base.endswith((".so", ".dylib", ".dll"))):
return "apache"
if base.startswith("php"):
return "cli"
return "unknown"
def _boot_time():
stat = read_text("/proc/stat") or ""
for line in stat.splitlines():
if line.startswith("btime "):
return int(line.split()[1])
return None
def linux_processes():
"""/proc 로 PHP 관련 실행 중 프로세스를 찾는다. (processes, 권한 문제 여부)"""
processes = []
denied = 0
boot = _boot_time()
try:
ticks = os.sysconf("SC_CLK_TCK")
except (ValueError, OSError, AttributeError):
ticks = 100
try:
names = os.listdir("/proc")
except OSError:
return processes, True
for name in names:
if not name.isdigit():
continue
base = "/proc/" + name
try:
exe = os.readlink(base + "/exe")
except PermissionError:
exe = None
denied += 1
except OSError:
# 커널 스레드(exe 링크 없음)나 조회 중 종료된 프로세스: 권한 문제가 아니다
exe = None
comm = (read_text(base + "/comm", 256) or "").strip()
label = os.path.basename(exe.replace(" (deleted)", "")) if exe else comm
is_php = bool(_PHP_EXE_RE.match(label)) or bool(_PHP_EXE_RE.match(comm))
is_apache = bool(_APACHE_EXE_RE.match(label)) or bool(_APACHE_EXE_RE.match(comm))
if not (is_php or is_apache):
continue
entry = {"pid": int(name), "exe": exe, "deleted": bool(exe and exe.endswith(" (deleted)")),
"kind": "php" if is_php else "apache", "module": None, "start": None, "unit": None}
if exe:
entry["exe"] = exe.replace(" (deleted)", "")
if is_apache:
for line in (read_text(base + "/maps", 4000000) or "").splitlines():
if "libphp" in line or re.search(r"php\d*apache", line, re.IGNORECASE):
path = line.split(None, 5)[-1].strip() if len(line.split(None, 5)) >= 6 else ""
if path:
entry["module"] = path.replace(" (deleted)", "")
entry["module_deleted"] = path.endswith(" (deleted)")
break
if not entry["module"]:
continue
stat = read_text(base + "/stat", 4096)
if stat and boot:
try:
fields = stat.rsplit(")", 1)[1].split()
entry["start"] = boot + int(fields[19]) / float(ticks)
except (IndexError, ValueError):
pass
cgroup = read_text(base + "/cgroup", 4096) or ""
unit = re.search(r"/([^/\n]+\.service)\b", cgroup)
if unit:
entry["unit"] = unit.group(1)
elif re.search(r"docker|containerd|kubepods|libpod", cgroup):
entry["unit"] = "container"
processes.append(entry)
return processes, denied > 0
def ps_exe_for_pid(pid):
"""프로세스 제목이 바뀐 PHP(php-fpm: master process ...)의 실제 실행 파일 경로. FreeBSD 는 procstat, macOS 는 lsof."""
if helper_path("procstat"):
code, out = run([helper_path("procstat"), "-b", str(pid)], timeout=10)
lines = out.splitlines() if code == 0 else []
if len(lines) >= 2 and lines[1].split() and lines[1].split()[-1].startswith("/"):
return lines[1].split()[-1]
elif platform.system() == "Darwin" and helper_path("lsof"):
code, out = run([helper_path("lsof"), "-a", "-p", str(pid), "-d", "txt", "-Fn"], timeout=10)
for line in (out.splitlines() if code == 0 else []):
if line.startswith("n/"):
return line[1:]
return None
def ps_processes():
"""macOS/BSD: ps 로 PHP 프로세스를 찾는다. 반환: (processes, 일부 프로세스의 실행 파일을 알 수 없었는지)."""
# "-o pid=,command=" 는 FreeBSD 에서 pid 열의 머리글을 ",command=" 로 바꿔 command 열이 없다. -o 를 따로 준다(Linux·macOS·BSD 공통)
code, out = run(["ps", "-ax", "-o", "pid=", "-o", "command="], limit=PS_OUTPUT_LIMIT)
processes = []
if code is None:
return processes, True
unresolved = False
for line in out.splitlines():
parts = line.strip().split(None, 1)
if len(parts) < 2 or not parts[0].isdigit():
continue
command = parts[1]
first = command.split(" ", 1)[0]
exe = first if command.startswith("/") else None
label = os.path.basename(exe) if exe else first
if not exe and label.endswith(":"):
# php-fpm 은 setproctitle 로 "php-fpm: master process (설정)" / "php-fpm: pool www" 처럼 제목을 바꾼다
label = label[:-1]
if _PHP_EXE_RE.match(label):
exe = ps_exe_for_pid(int(parts[0]))
if not exe:
unresolved = True
continue
if _PHP_EXE_RE.match(label) and exe:
processes.append({"pid": int(parts[0]), "exe": exe, "deleted": False, "kind": "php",
"module": None, "start": None, "unit": None})
return processes, unresolved
def windows_processes():
script = ("Get-CimInstance Win32_Process | Where-Object { $_.Name -match '^(php|php-cgi|php-win|httpd)' } | "
"Select-Object ProcessId,Name,ExecutablePath | ConvertTo-Json -Compress")
code, out = run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script], timeout=POWERSHELL_TIMEOUT)
processes = []
if code is None or not out.strip():
return processes, code is None
try:
data = json.loads(out)
except ValueError:
return processes, True
if isinstance(data, dict):
data = [data]
for item in data:
exe = item.get("ExecutablePath")
if exe:
processes.append({"pid": item.get("ProcessId"), "exe": exe, "deleted": False, "kind": "php",
"module": None, "start": None, "unit": None})
return processes, False
def live_processes():
system = platform.system()
if system == "Linux":
return linux_processes()
if system == "Windows":
return windows_processes()
return ps_processes()
# --- 파일 탐색 -------------------------------------------------------------------
POSIX_BINARY_GLOBS = [
"/usr/bin/php*", "/usr/sbin/php-fpm*", "/usr/local/bin/php*", "/usr/local/sbin/php-fpm*",
"/opt/remi/php*/root/usr/bin/php*", "/opt/remi/php*/root/usr/sbin/php-fpm*",
"/opt/plesk/php/*/bin/php*", "/opt/plesk/php/*/sbin/php-fpm*",
"/opt/cpanel/ea-php*/root/usr/bin/php*", "/opt/cpanel/ea-php*/root/usr/sbin/php-fpm*",
"/usr/local/php*/bin/php*", "/usr/local/php*/sbin/php-fpm*",
"/usr/local/lsws/lsphp*/bin/lsphp*", "/usr/local/bin/frankenphp", "/usr/bin/frankenphp",
"/opt/homebrew/bin/php*", "/opt/homebrew/sbin/php-fpm*", "/opt/homebrew/opt/php*/bin/php*",
"/opt/homebrew/opt/php*/sbin/php-fpm*", "/usr/local/opt/php*/bin/php*", "/usr/local/opt/php*/sbin/php-fpm*",
"/Applications/MAMP/bin/php/php*/bin/php*", "/Applications/XAMPP/xamppfiles/bin/php*",
"/opt/lampp/bin/php*", "/opt/lampp/sbin/php-fpm*",
"/usr/lib/apache2/modules/libphp*.so", "/usr/lib64/httpd/modules/libphp*.so",
"/usr/lib/httpd/modules/libphp*.so", "/usr/local/apache2/modules/libphp*.so",
"/usr/lib/apache2/modules/libphp*.dylib", "/opt/homebrew/opt/php*/lib/httpd/modules/libphp*.so",
]
WINDOWS_BINARY_GLOBS = [
"C:\\php*\\php*.exe", "C:\\xampp\\php\\php*.exe", "C:\\wamp*\\bin\\php\\php*\\php*.exe",
"C:\\laragon\\bin\\php\\php*\\php*.exe", "C:\\Program Files\\PHP*\\php*.exe",
"C:\\Program Files (x86)\\PHP*\\php*.exe", "C:\\tools\\php*\\php*.exe",
"C:\\Program Files (x86)\\Plesk\\Additional\\PleskPHP*\\php*.exe",
]
_SKIP_NAMES = re.compile(r"(-config|ize|-dbg|-debug|\.(ini|conf|sample|default|1|md|txt|sh|d)$|^php-fpm\.conf)", re.IGNORECASE)
def _is_binary_candidate(path):
base = os.path.basename(path)
if _SKIP_NAMES.search(base):
return False
try:
if not stat.S_ISREG(os.stat(path).st_mode):
return False
except OSError:
return False
low = base.lower()
if low.endswith((".so", ".dylib", ".dll")):
return low.startswith("libphp") or "apache" in low
return bool(_PHP_EXE_RE.match(base))