權限位圖總覽
特殊位 | 用戶 | 組群 | 其他
s s t r w x r w x r w x
- SUID (Set UID):僅對檔案生效,執行時以檔案擁有者身分運行。
- SGID (Set GID):對目錄生效,目錄下新建檔案自動屬於目錄所屬群組。
- Sticky Bit:對目錄生效,只有檔案擁有者、目錄擁有者、root 可刪除檔案。
字母表示規則
| 位置 | 原有 x 權限 | 無 x 權限 | 含義 |
| SUID (user x) | s | S | 小寫=有執行權,大寫=無執行權(無效設定) |
| SGID (group x) | s | S | 同上 |
| Sticky (other x) | t | T | 同上 |
指令設定法 (符號模式)
# SUID
chmod u+s filename
chmod u-s filename # 移除
# SGID
chmod g+s dirname
# Sticky
chmod o+t dirname
數字模式 (八進位)
4 = SUID
2 = SGID
1 = Sticky
chmod 4755 file # rwsr-xr-x (SUID)
chmod 2755 dir # rwxr-sr-x (SGID)
chmod 1777 dir # rwxrwxrwt (Sticky,如 /tmp)
chmod 6755 file # rwsr-sr-x (SUID+SGID)
經典實戰案例
案例 1:SUID - 讓一般用戶執行 ping (需 root 權限開啟 ICMP socket)
ls -l /bin/ping
# -rwsr-xr-x 1 root root ... /bin/ping (有 s 位)
# 移除 SUID 後一般用戶無法 ping
chmod u-s /bin/ping
su - user
ping www.google.com
# ping: icmp open socket: Operation not permitted
案例 2:SGID - 專案共享目錄,新檔自動歸屬專案群組
groupadd devteam
mkdir /project
chgrp devteam /project
chmod 2775 /project # SGID + 群組寫入
# 所有 devteam 成員在 /project 建立的檔案,群組皆為 devteam
案例 3:Sticky Bit - 公開上傳目錄,防止誤刪他人檔案
mkdir /shared
chmod 1777 /shared # 所有人可寫、可建檔,但只能刪自己檔案
# 類似 /tmp 目錄預設權限
注意事項
chmod 不檢查語意合法性,可對非執行檔設 SUID,但無實際作用。
- Shell 腳本設 SUID 在現代 Linux 多被忽略(安全機制),二進制程式才生效。
- Sticky Bit 僅對目錄有效,對檔案設定無意義。