Linux 檔案系統的權限機制包含基礎的 rwx 權限位、特殊權限位(SUID/SGID/Sticky Bit)以及較少被注意的隱藏屬性(chattr/lsattr)。本文將從 umask 預設權限計算、chattr 隱藏屬性配置、特殊權限位實戰三個維度,完整剖析 Linux 權限體系。

666 (rw-rw-rw-) —— 預設無執行權限777 (rwxrwxrwx) —— 需執行權限才能 cd 進入umask 為「拿掉」的權限位,最終權限 = 最大權限 - umask# 預設 umask 0022
[root@www ~]# umask
0022
[root@www ~]# touch test1; mkdir test2
[root@www ~]# ll
-rw-r--r-- 1 root root 0 ... test1 # 666-022=644
drwxr-xr-x 2 root root 4096 ... test2 # 777-022=755
# 修改 umask 0002(保留群組寫入)
[root@www ~]# umask 0002
[root@www ~]# touch test3; mkdir test4
[root@www ~]# ll
-rw-rw-r-- 1 root root 0 ... test3 # 666-002=664
drwxrwxr-x 2 root root 4096 ... test4 # 777-002=775
022,限制他人寫入002,允許同群組協作/etc/profile 或 ~/.bashrc 永久設定這些屬性位於 inode 層面,ls -l 看不見,需用 lsattr 查看,chattr 修改,且多數需 root 權限。
| 屬性 | 效果 | 適用對象 | 權限需求 |
|---|---|---|---|
| i | 不可刪除、改名、建立連結、寫入/新增資料 | 檔案/目錄 | root |
| a | 僅能追加資料(append only) | 檔案 | root |
| S | 同步寫入磁碟(如同 sync 掛載選項) | 檔案 | root |
| A | 不更新 atime(存取時間),減少 I/O | 檔案/目錄 | 一般用戶 |
| c | 自動壓縮儲存,讀取自動解壓 | 檔案 | root |
| d | dump 備份時略過 | 檔案/目錄 | root |
| s | 刪除時徹底清空磁碟區塊,不可復原 | 檔案 | root |
| u | 刪除時保留資料區塊,可嘗試救援 | 檔案 | root |
| j | ext3/4 系統下,資料先寫入 journal | 檔案 | root |
# 設定 i 屬性(防刪除)
[root@www tmp]# touch attrtest
[root@www tmp]# chattr +i attrtest
[root@www tmp]# rm attrtest
rm: cannot remove 'attrtest': Operation not permitted
# 移除屬性
[root@www tmp]# chattr -i attrtest
# 查看屬性
[root@www tmp]# lsattr attrtest
----ia---j--- attrtest # i=不可異動, a=僅追加, j=journal
-a:顯示隱藏檔屬性-d:目錄本身屬性(不列出內容)-R:遞迴顯示子目錄x 權限passwd、su、ping)x 位變為 s(如 -rwsr-xr-x)| 對象 | 效果 |
|---|---|
| 二進位執行檔 | 執行期間獲得檔案所屬群組權限 |
| 目錄 | 1. 使用者需 rx 進入2. 新建檔案/目錄自動繼承該目錄的群組 3. 適用於團隊共享目錄 |