之前有個網站被人在根目錄塞了一個 PHP 檔,我一直不知道對方是怎麼放進去的。直到這次替部落格做安全盤查,跑了一次權限檢查才看懂:網站自己的 PHP,就能寫入 wp-includes 裡 3122 個位置。
上一篇〈WordPress 安全檢查:xmlrpc.php 14 分鐘被試 1547 次密碼後,我補上的五個洞〉擋掉了上傳資料夾的 PHP。這篇處理的是另一半:根目錄和核心資料夾。
檔案是怎麼被塞進根目錄的
WordPress 的 PHP 由 PHP-FPM 執行,身分通常是 www-data。攻擊者只要能讓網站執行一段 PHP,或登入後台,那段程式就有 www-data 的權限,能寫入 www-data 可寫的每一個資料夾。
常見的入口有幾種:
- 外掛或佈景主題的上傳漏洞。
- 管理員密碼被猜中,從後台的外掛上傳或檔案編輯器寫入 PHP。
- FTP、SSH、主機控制台的帳號外洩。
- 同一個主機帳號下的其他網站先被入侵。
上傳資料夾已經用 nginx 禁止執行 PHP,但根目錄的 .php 會照常被執行。檔案只要放得進去,就能用。
我的網站實際的權限
檢查結果是這樣:
| 位置 | PHP 可寫入 |
|---|---|
| 根目錄 | 16 處 |
wp-admin |
611 處 |
wp-includes |
3122 處 |
wp-content/themes |
442 處 |
wp-content/plugins |
91 處 |
原因是檔案的擁有者是我的帳號,群組是 www-data,權限是 664(資料夾 775)。群組有寫入權,所以 PHP 也能寫。
還有兩個更直接的問題。wp-config.php 的擁有者是 www-data,PHP 可以改寫它,而它每次載入頁面都會執行。plugins 裡也有 20 個檔案屬於 www-data。另外,後台的佈景主題與外掛檔案編輯器是開著的。
常見做法:裝安全外掛檢查
安全外掛可以檢查權限,但它沒辦法替你鎖起來。
外掛本身也是 PHP,用 www-data 執行。如果外掛有能力把權限拿掉,代表 www-data 也有能力把權限加回來,攻擊者的程式一樣做得到。真正的鎖,要由 www-data 以外的帳號來上。
另一個限制是,外掛從網站內部檢查。網站一旦被入侵,外掛本身也可能被改,一直回報正常。所以我另外寫了一支在主機上執行的檢查程式。
用檢查程式找出可寫入的位置
wp-security-check.py 只用 Python 內建函式庫,只看不改。在主機上用自己的帳號執行:
python3 wp-security-check.py /var/www/example --url https://example.com
它依擁有者、群組和權限位元,判斷 www-data 能不能寫入每一個檔案,並列出修正指令。同時也會比對核心檔案的官方檢查碼、找出根目錄多出來的 PHP 檔、上傳資料夾裡的 PHP,以及 wp-content 裡常見的後門寫法。
為了確認它真的抓得到,我做了一個假的網站目錄,在根目錄、wp-includes、上傳資料夾各放一個 PHP 檔,再加兩個含後門寫法的外掛檔。全部被列出來,結束代碼是 2。
wp-security-check.py 完整程式碼
```python #!/usr/bin/env python3 """WordPress 主機端安全檢查(只看不改)。 用法: python3 tools/wp-security-check.py /srv/blogdev.da2ai.net python3 tools/wp-security-check.py /srv/blogdev.da2ai.net --url https://blogdev.da2ai.net python3 tools/wp-security-check.py --web-user www-data --json 檢查項目: 1. 核心檔案:和 api.wordpress.org 的官方檢查碼比對,列出被改過、缺少、 以及 wp-admin、wp-includes 裡多出來的檔案。 2. 根目錄:官方清單沒有的檔案(特別是 .php)。 3. 寫入權限:PHP(網站執行身分,預設 www-data)能不能寫入根目錄、 wp-content 本身、wp-admin、wp-includes、themes、plugins、wp-config.php。 4. wp-config.php:其他帳號讀不讀得到、有沒有關掉後台檔案編輯器。 5. 上傳資料夾裡有沒有 .php。 6. wp-content 裡常見的後門寫法(只是線索,要人工確認)。 7. 加 --url 時:從公開網址測試 .git、.env、wp-config.php、xmlrpc.php、 使用者清單讀不讀得到。 從網站外部(以 w220 之類的帳號)執行,網站本身被入侵也不影響檢查結果。 這支程式不修改任何檔案;建議的修正指令要自己確認後再執行。 結束代碼:0 全部正常;1 有「注意」;2 有「問題」。 """ import argparse import grp import hashlib import json import os import pwd import re import stat import sys import urllib.error import urllib.request OK, WARN, BAD, INFO = '正常', '注意', '問題', '資訊' LEVEL = {OK: 0, INFO: 0, WARN: 1, BAD: 2} # 根目錄裡不在官方清單、但屬於正常情況的檔案 ROOT_ALLOW = {'wp-config.php', '.htaccess', 'robots.txt', 'favicon.ico', 'ads.txt', 'BingSiteAuth.xml', '.user.ini', 'php.ini'} # 常見後門寫法(出現不代表一定是後門,要人工看) BACKDOOR = [ (r'eval\s*\(\s*(base64_decode|gzinflate|gzuncompress|str_rot13)\s*\(', 'eval 解碼後執行'), (r'(assert|eval|system|exec|shell_exec|passthru|popen)\s*\(\s*\$_(GET|POST|REQUEST|COOKIE)', '直接執行請求內容'), (r'\$_(GET|POST|REQUEST|COOKIE)\s*\[[^\]]+\]\s*\(', '用請求內容當函式名稱'), (r'preg_replace\s*\(\s*[\'"](.).*\1[a-z]*e[a-z]*[\'"]', 'preg_replace /e'), (r'create_function\s*\(', 'create_function'), (r'move_uploaded_file\s*\(.*\$_FILES', '上傳檔案寫入(檔案管理器、上傳工具常見)'), ] SCAN_EXT = ('.php', '.phtml', '.phar', '.inc') class Report: def __init__(self): self.sections = [] def section(self, title): self.sections.append({'title': title, 'items': []}) def add(self, level, name, detail='', fix='', files=None): self.sections[-1]['items'].append( {'level': level, 'name': name, 'detail': detail, 'fix': fix, 'files': files or []}) def worst(self): return max((LEVEL[i['level']] for s in self.sections for i in s['items']), default=0) def counts(self): c = {OK: 0, WARN: 0, BAD: 0, INFO: 0} for s in self.sections: for i in s['items']: c[i['level']] += 1 return c def print(self): for s in self.sections: print(f'\n== {s["title"]} ==') for i in s['items']: line = f'[{i["level"]}] {i["name"]}' if i['detail']: line += f':{i["detail"]}' print(line) for f in i['files'][:20]: print(f' {f}') if len(i['files']) > 20: print(f' …另外 {len(i["files"]) - 20} 個') if i['fix']: for fl in i['fix'].splitlines(): print(f' 建議:{fl}' if fl == i['fix'].splitlines()[0] else f' {fl}') c = self.counts() print(f'\n結果:問題 {c[BAD]}、注意 {c[WARN]}、正常 {c[OK]}、資訊 {c[INFO]}') # ---------- 權限 ---------- def web_identity(user): p = pwd.getpwnam(user) gids = {p.pw_gid} | {g.gr_gid for g in grp.getgrall() if user in g.gr_mem} return p.pw_uid, gids def writable_by(path, uid, gids): """依擁有者、群組、權限位元判斷該身分能不能寫入(不含 ACL)。""" st = os.lstat(path) if uid == 0: return True if st.st_uid == uid: return bool(st.st_mode & stat.S_IWUSR) if st.st_gid in gids: return bool(st.st_mode & stat.S_IWGRP) return bool(st.st_mode & stat.S_IWOTH) def owner_of(path): st = os.lstat(path) try: u = pwd.getpwuid(st.st_uid).pw_name except KeyError: u = str(st.st_uid) try: g = grp.getgrgid(st.st_gid).gr_name except KeyError: g = str(st.st_gid) return f'{u}:{g} {stat.S_IMODE(st.st_mode):o}' def walk_writable(base, uid, gids, recursive=True): hits = [] if not os.path.exists(base): return hits if writable_by(base, uid, gids): hits.append(base) if not recursive: return hits for r, ds, fs in os.walk(base): for x in ds + fs: p = os.path.join(r, x) if not os.path.islink(p) and writable_by(p, uid, gids): hits.append(p) return hits # ---------- 各項檢查 ---------- def read_version(root): src = open(os.path.join(root, 'wp-includes/version.php'), encoding='utf-8').read() ver = src.split("$wp_version = '")[1].split("'")[0] loc = src.split("$wp_local_package = '")[1].split("'")[0] if "$wp_local_package = '" in src else 'en_US' return ver, loc def check_core(rep, root): rep.section('核心檔案完整性') try: ver, loc = read_version(root) except (OSError, IndexError): rep.add(BAD, '讀不到 wp-includes/version.php', '確認根目錄路徑是否正確') return None url = f'https://api.wordpress.org/core/checksums/1.0/?version={ver}&locale={loc}' try: sums = json.load(urllib.request.urlopen(url, timeout=30))['checksums'] except Exception as e: # noqa: BLE001 rep.add(WARN, '取不到官方檢查碼', f'{url}({e})') return None if not isinstance(sums, dict): rep.add(WARN, '官方沒有這個版本/語系的檢查碼', f'WordPress {ver} ({loc})') return None core = {f: h for f, h in sums.items() if not f.startswith('wp-content/')} bad, missing = [], [] for f, h in core.items(): p = os.path.join(root, f) if not os.path.exists(p): missing.append(f) elif hashlib.md5(open(p, 'rb').read()).hexdigest() != h: bad.append(f) extra = [] for d in ('wp-admin', 'wp-includes'): for r, _, fs in os.walk(os.path.join(root, d)): for x in fs: rel = os.path.relpath(os.path.join(r, x), root) if rel not in core: extra.append(rel) rep.add(INFO, f'WordPress {ver} ({loc})', f'官方檢查碼 {len(core)} 個核心檔案') rep.add(BAD if bad else OK, '核心檔案內容', f'不符 {len(bad)} 個' if bad else '全部相符', '用官方安裝檔覆蓋這些檔案,並查清楚是怎麼被改的' if bad else '', bad) rep.add(BAD if extra else OK, 'wp-admin、wp-includes 多出的檔案', f'{len(extra)} 個' if extra else '沒有', '官方沒有這些檔案,常見於後門;確認後刪除' if extra else '', extra) real_missing = [m for m in missing if m not in ('readme.html', 'license.txt', 'wp-config-sample.php')] rep.add(WARN if real_missing else OK, '缺少的核心檔案', f'{len(missing)} 個' + ('(readme.html 等說明檔不影響運作)' if missing and not real_missing else ''), '用官方安裝檔補回' if real_missing else '', missing) return core def check_root(rep, root, core): rep.section('根目錄') known = set(core or {}) | ROOT_ALLOW unknown = sorted(f for f in os.listdir(root) if os.path.isfile(os.path.join(root, f)) and f not in known) php = [f for f in unknown if f.lower().endswith(SCAN_EXT)] other = [f for f in unknown if f not in php] if core is None: rep.add(INFO, '沒有官方清單,略過根目錄比對') return rep.add(BAD if php else OK, '根目錄多出的 PHP 檔', f'{len(php)} 個' if php else '沒有', '打開確認內容;不是自己放的就先移出網站目錄再調查' if php else '', php) rep.add(INFO if other else OK, '根目錄其他非官方檔案', f'{len(other)} 個' if other else '沒有', '確認是自己放的(例如網站驗證檔)' if other else '', other) def check_perms(rep, root, web_user): rep.section(f'寫入權限(以 {web_user} 身分判斷)') try: uid, gids = web_identity(web_user) except KeyError: rep.add(WARN, f'找不到帳號 {web_user}', '用 --web-user 指定 PHP 的執行身分') return me = pwd.getpwuid(os.getuid()).pw_name q = lambda p: os.path.relpath(p, root) if p != root else '.' targets = [ ('根目錄(只看資料夾本身與根目錄的檔案)', root, False), ('wp-content(只看資料夾本身與第一層檔案)', os.path.join(root, 'wp-content'), False), ('wp-admin', os.path.join(root, 'wp-admin'), True), ('wp-includes', os.path.join(root, 'wp-includes'), True), ('wp-content/themes', os.path.join(root, 'wp-content/themes'), True), ('wp-content/plugins', os.path.join(root, 'wp-content/plugins'), True), ('wp-content/mu-plugins', os.path.join(root, 'wp-content/mu-plugins'), True), ] for name, path, rec in targets: if not os.path.exists(path): continue hits = walk_writable(path, uid, gids, rec) if not rec: hits += [os.path.join(path, f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and writable_by(os.path.join(path, f), uid, gids)] foreign = [] for r, ds, fs in (os.walk(path) if rec else [(path, [], [])]): for x in ds + fs: p = os.path.join(r, x) if os.lstat(p).st_uid == uid: foreign.append(q(p)) if hits: fix = [] if foreign: fix.append(f'有 {len(foreign)} 個檔案的擁有者是 {web_user},先改回:' f'sudo chown -R {me}:{web_user} {q(path)}') if rec: fix.append(f'chmod -R g-w,o-w {q(path)}') else: fix.append(f'chmod g-w,o-w {q(path)} && find {q(path)} -maxdepth 1 -type f -exec chmod g-w,o-w {{}} +') rep.add(WARN, name, f'PHP 可寫入 {len(hits)} 處,被塞檔或改檔時擋不住', '\n'.join(fix), [q(h) for h in hits]) else: rep.add(OK, name, 'PHP 不能寫入') up = os.path.join(root, 'wp-content/uploads') if os.path.isdir(up): rep.add(OK if writable_by(up, uid, gids) else WARN, 'wp-content/uploads', 'PHP 可寫入(上傳圖片需要)' if writable_by(up, uid, gids) else 'PHP 不能寫入,上傳圖片會失敗') cfg = os.path.join(root, 'wp-config.php') if os.path.exists(cfg): st = os.lstat(cfg) if writable_by(cfg, uid, gids): rep.add(BAD, 'wp-config.php 可被 PHP 改寫', owner_of(cfg), f'sudo chown {me}:{web_user} wp-config.php && chmod 640 wp-config.php') else: rep.add(OK, 'wp-config.php 不能被 PHP 改寫', owner_of(cfg)) if st.st_mode & stat.S_IROTH: rep.add(BAD, 'wp-config.php 其他帳號讀得到', '資料庫密碼與加密金鑰會外洩給主機上的其他帳號', 'chmod 640 wp-config.php') else: rep.add(OK, 'wp-config.php 其他帳號讀不到', owner_of(cfg)) def check_config(rep, root): rep.section('wp-config.php 設定') cfg = os.path.join(root, 'wp-config.php') try: src = open(cfg, encoding='utf-8', errors='replace').read() except OSError as e: rep.add(WARN, '讀不到 wp-config.php', str(e)) return code = re.sub(r'/\*.*?\*/|//[^\n]*|#[^\n]*', '', src, flags=re.S) def defined_true(name): return re.search(rf"define\s*\(\s*['\"]{name}['\"]\s*,\s*(true|1)\s*\)", code, re.I) if defined_true('DISALLOW_FILE_MODS'): rep.add(OK, '後台安裝與編輯外掛、佈景主題', '已關閉(DISALLOW_FILE_MODS)') elif defined_true('DISALLOW_FILE_EDIT'): rep.add(OK, '後台檔案編輯器', '已關閉(DISALLOW_FILE_EDIT)') else: rep.add(WARN, '後台檔案編輯器', '開著;管理員密碼外洩時可以直接從後台改 PHP', "在 wp-config.php 的「That's all, stop editing」之前加入:\n" "define( 'DISALLOW_FILE_EDIT', true );") if defined_true('WP_DEBUG_DISPLAY') or (defined_true('WP_DEBUG') and not re.search( r"define\s*\(\s*['\"]WP_DEBUG_DISPLAY['\"]\s*,\s*(false|0)\s*\)", code, re.I)): rep.add(WARN, '除錯訊息', 'WP_DEBUG 開著且可能顯示在頁面上,會洩漏路徑與程式資訊', "正式站設 define( 'WP_DEBUG', false ); 或 define( 'WP_DEBUG_DISPLAY', false );") else: rep.add(OK, '除錯訊息', '不會顯示在頁面上') def check_uploads(rep, root): rep.section('上傳資料夾') up = os.path.join(root, 'wp-content/uploads') if not os.path.isdir(up): rep.add(INFO, '沒有 wp-content/uploads') return php = [] for r, _, fs in os.walk(up): for x in fs: if x.lower().endswith(SCAN_EXT): php.append(os.path.relpath(os.path.join(r, x), root)) rep.add(BAD if php else OK, '上傳資料夾裡的 PHP 檔', f'{len(php)} 個' if php else '沒有', '上傳資料夾不該有 PHP;確認後刪除,並確認 nginx 已禁止在這裡執行 PHP' if php else '', php) def check_backdoor(rep, root): rep.section('wp-content 後門線索(需人工確認)') pats = [(re.compile(p, re.I), d) for p, d in BACKDOOR] base = os.path.join(root, 'wp-content') hits = [] scanned = 0 for r, ds, fs in os.walk(base): ds[:] = [d for d in ds if d not in ('node_modules', '.git', 'cache')] for x in fs: if not x.lower().endswith(SCAN_EXT): continue p = os.path.join(r, x) try: if os.path.getsize(p) > 5_000_000: continue src = open(p, encoding='utf-8', errors='replace').read() except OSError: continue scanned += 1 for rx, desc in pats: m = rx.search(src) if m: line = src.count('\n', 0, m.start()) + 1 hits.append(f'{os.path.relpath(p, root)}:{line} {desc}') if hits: rep.add(WARN, '可疑寫法', f'掃描 {scanned} 個 PHP 檔,{len(hits)} 處符合', '逐一打開確認;正常外掛也可能用到其中幾種(例如上傳功能)', hits) else: rep.add(OK, '可疑寫法', f'掃描 {scanned} 個 PHP 檔,沒有符合的寫法') def check_url(rep, url): rep.section(f'外部讀取測試({url})') url = url.rstrip('/') tests = [ ('/.git/HEAD', '.git 資料夾', lambda c, b: c == 200 and b.startswith(b'ref:')), ('/.env', '.env', lambda c, b: c == 200 and b'=' in b[:200]), ('/wp-config.php.bak', 'wp-config 備份檔', lambda c, b: c == 200 and b'DB_' in b), ('/wp-config.php', 'wp-config.php 原始碼', lambda c, b: c == 200 and b'DB_PASSWORD' in b), ('/xmlrpc.php', 'xmlrpc.php', lambda c, b: c == 405 or (c == 200 and b'XML-RPC' in b)), ('/wp-json/wp/v2/users', '使用者清單', lambda c, b: c == 200 and b'"slug"' in b), ('/wp-content/debug.log', 'debug.log', lambda c, b: c == 200 and len(b) > 0), ] for path, name, leaked in tests: req = urllib.request.Request(url + path, headers={'User-Agent': 'wp-security-check'}) try: with urllib.request.urlopen(req, timeout=15) as r: code, body = r.status, r.read(4096) except urllib.error.HTTPError as e: code, body = e.code, e.read(4096) if e.fp else b'' except Exception as e: # noqa: BLE001 rep.add(WARN, name, f'{path} 連不上({e})') continue if leaked(code, body): level = WARN if path in ('/xmlrpc.php', '/wp-json/wp/v2/users') else BAD rep.add(level, name, f'{path} 讀得到(HTTP {code})', '在 nginx 擋掉,或用 DA2 安全外掛關閉') else: rep.add(OK, name, f'{path} 讀不到(HTTP {code})') def main(): ap = argparse.ArgumentParser(description='WordPress 主機端安全檢查(只看不改)') ap.add_argument('root', help='WordPress 根目錄') ap.add_argument('--web-user', default='www-data', help='PHP 的執行身分(預設 www-data)') ap.add_argument('--url', help='網站公開網址;有給才做外部讀取測試') ap.add_argument('--skip-core', action='store_true', help='不比對核心檔案(離線時用)') ap.add_argument('--json', action='store_true', help='輸出 JSON') a = ap.parse_args() root = os.path.abspath(a.root) rep = Report() core = None if a.skip_core else check_core(rep, root) check_root(rep, root, core) check_perms(rep, root, a.web_user) check_config(rep, root) check_uploads(rep, root) check_backdoor(rep, root) if a.url: check_url(rep, a.url) if a.json: print(json.dumps({'root': root, 'counts': rep.counts(), 'sections': rep.sections}, ensure_ascii=False, indent=2)) else: print(f'WordPress 安全檢查:{root}') rep.print() sys.exit(rep.worst()) if __name__ == '__main__': main() ```把權限鎖起來
把屬於
www-data的檔案改回自己的帳號(需要 sudo):sudo chown :www-data wp-config.php sudo find wp-content/plugins -user www-data -exec chown :www-data {} +拿掉群組的寫入權。
uploads和upgrade不動,上傳圖片需要寫入:chmod g-w,o-w . wp-content && find . wp-content -maxdepth 1 -type f -exec chmod g-w,o-w {} + chmod -R g-w,o-w wp-admin wp-includes wp-content/themes wp-content/plugins在
wp-config.php關掉後台檔案編輯器:define( 'DISALLOW_FILE_EDIT', true );再跑一次檢查程式。
擁有者還是自己的帳號,所以用自己的帳號 rsync 部署佈景主題照常可以覆寫,不需要 sudo。但要注意一點:rsync -a 會連權限一起複製,我的原始檔是 664,部署一次群組又能寫入了。部署指令要加上 --chmod:
rsync -a --delete --chmod=D755,F644 my-theme/ /var/www/example/wp-content/themes/my-theme/
鎖好之後的檢查結果
我放了一個臨時的 PHP 檔,讓網站自己試著在每個資料夾寫入檔案。結果只有 uploads 寫得進去,根目錄、wp-content、wp-admin、wp-includes、佈景主題和外掛都寫不進去,wp-config.php 也改不了。首頁、文章和後台照常打開,後台的檔案編輯器則直接顯示錯誤頁。
再跑一次檢查程式,注意從 7 項變成 0 項。
常見問題
鎖起來之後,後台更新會怎樣?
後台的更新 WordPress、安裝外掛、安裝佈景主題就不能用了:一般會改成要求填 FTP 帳密;wp-config.php 設了 FS_METHOD 為 direct 的話(我的網站就是),則直接顯示更新失敗。這是正常的。更新時改在主機上用自己的帳號覆蓋檔案,再比對一次官方檢查碼。
上傳圖片、寫文章會受影響嗎?
不會。文章、設定、留言存在資料庫,圖片存在 uploads,這兩個都沒有鎖。
安全外掛還需要嗎?
需要,但分工不同。外掛負責擋攻擊和日常提醒,主機上的檢查程式負責確認權限有沒有被改回去、網站有沒有被入侵。
參考來源
- WordPress.org 核心檢查碼 API,
https://api.wordpress.org/core/checksums/1.0/(檢查程式比對核心檔案用),查閱 2026-12-02 - WordPress 7.1.5 原始碼:
wp-admin/includes/file.php(get_filesystem_method())、wp-admin/includes/update-core.php - 本站實驗:
wp-security-check.py鎖定前後的檢查結果、鎖定指令與 rsync--chmod部署,2026-12-02
這是〈WordPress 安全〉的最後一篇看整個系列 →