萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux ACL 權限控制完整教學:突破傳統 rwx 限制

前言:為什麼需要 ACL?

Windows 的檔案屬性(唯讀、隱藏)雖直觀,但 Linux 的權限機制更細緻彈性。傳統 rwx 僅能針對「擁有者、群組、其他人」三類主體設定權限,無法針對特定使用者個別授權。ACL(Access Control List) 彌補此缺口,允許對單一檔案/目錄設定多組使用者或群組的獨立權限,甚至限制 root 的存取,實現更精細的存取控制。

步驟一:確認核心與檔案系統支援 ACL

並非所有核心預設啟用 ACL,需檢查目前核心配置:

# grep -i acl /boot/config-$(uname -r)

若輸出包含 CONFIG_EXT4_FS_ACL=y(或 ext3/xfs 相關選項),即表示支援。若無,需重編核心或安裝支援 ACL 的核心套件(參考 ACL 官網)。

步驟二:掛載時啟用 ACL 選項

掛載分區時加入 acl 參數:

# mount -t ext4 -o acl /dev/sda1 /fs1

寫入 /etc/fstab 永久生效:

/dev/sda1  /fs1  ext4  defaults,acl  0  2

步驟三:實戰 ACL 權限設定

以下以三個測試帳號(test1、test2、test3)示範核心操作。

建立測試環境

# useradd test1; useradd test2; useradd test3
# echo "password" | passwd --stdin test1  # 同步設定密碼
# mount -t ext4 -o acl /dev/sda1 /fs1

案例一:基礎權限拒絕存取

以 test1 建立檔案並移除群組與他人權限:

$ su - test1
$ cd /fs1
$ echo "Create by test1" > test1.txt
$ chmod go-rwx test1.txt
$ ls -l test1.txt
-rw------- 1 test1 test1 17 Jul 14 22:11 test1.txt

此時 test2 嘗試讀取會被拒絕:

$ su - test2
$ cat /fs1/test1.txt
cat: /fs1/test1.txt: Permission denied

案例二:使用 setfacl 授權特定使用者

回到 test1,授予 test2 讀寫權限:

$ su - test1
$ setfacl -m u:test2:rw /fs1/test1.txt

觀察權限變化:

$ ls -l /fs1/test1.txt
-rw-rw-r--+ 1 test1 test1 17 Jul 14 22:11 test1.txt

檔名後的 + 標誌表示啟用 ACL。用 getfacl 查看完整規則:

$ getfacl /fs1/test1.txt
# file: test1.txt
# owner: test1
# group: test1
user::rw-
user:test2:rw-        # 新增的 ACL 項目
group::r--
mask::rw-
other::r--

驗證 test2 現可讀寫:

$ su - test2
$ cat /fs1/test1.txt
Create by test1
$ echo "Modify by test2" >> /fs1/test1.txt
$ cat /fs1/test1.txt
Create by test1
Modify by test2

案例三:未授權使用者仍被拒絕

$ su - test3
$ cat /fs1/test1.txt
cat: /fs1/test1.txt: Permission denied

除 root 外,test3 無法存取,確認 ACL 精準生效。

常用 ACL 指令速查

  • setfacl -m u:使用者:權限 檔案:新增/修改使用者 ACL
  • setfacl -m g:群組:權限 檔案:新增/修改群組 ACL
  • setfacl -x u:使用者 檔案:移除指定使用者 ACL
  • setfacl -b 檔案:移除所有 ACL 規則
  • getfacl 檔案:顯示完整 ACL 設定
  • ls -l 顯示 + 即表示有 ACL 屬性

結語

ACL 讓 Linux 權限管理從「三組固定權限」進化為「任意粒度的存取控制」,特別適合多使用者協作、專案目錄隔離、Web 伺服器虛擬主機等場景。掌握 setfacl/getfacl 兩大核心指令,即可靈活駕馭企業級權限需求。

copyright © 萬盛學電腦網 all rights reserved