資訊人筆記

Work hard, Have fun, Make history!

使用者工具

網站工具


operating_system:nix_suid_sgid_in_unix

[*nix] SUID & SGID in UNIX

0x00 前言

UNIX系統中許多地方都會涉及 suid 和 sgid,在學習時還有 euid、egid 和原本 real uid、gid 和 sticky bit 幾個名詞

本篇記錄這幾個名詞之間的關聯與系統權限的觀念


0x01檔案權限

在 UNIX 底下使用 ls -l 指令可以看見類似以下的表示法

-rwxr-xr-x

我們也可以使用 chmod 指令改變檔案權限

這邊細節請見參考資料

而除了 owner、group、other 各自的 read、write、excute 的執行權限外,最前面一位表示文件種類

在 UNIX 中有著將一切視為檔案的概念,最前面一位包含了

  • - : 表示regular file
  • d : 表示資料夾
  • l : 表示link
  • p : 表示name pipe
  • s : 表示socket
  • c : 表示character special file
  • b : 表示block special file

而一般 suid、sgid 只對 regular file 和 directory 有意義

若檔案有配置 suid 則會顯示在檔案權限的可執行位上

  • -rwsr-xr-x : 表示有 setuid,且 owner 有配執行權 (4755)
  • -rwSr- -r- - : 表示有 setuid,但 owner 沒有配執行權 (4644)
  • -rwxr-sr-x : 表示有 setgid,且 group 有配執行權 (2755)
  • -rw-r-Sr- - : 表示有 setgid,但 group 沒有配執行權 (2644)

0x02 EUID、EGID、SUID、SGID概念

一般所謂的 real uid、real gid 是指我們登入時的 uid、gid

suid、sgid 指的是 setuid、setgid,這是可以設置在文件權限上的

uid, gid 會在user登入時會參照 /etc/passwd 中的設定賦予

而 euid 和 egid 指的是 effective 的意思,kernel 是依照 euid 和 egid 來決定 process 對 resource 的訪問權限

假設一個 process 在沒有 setuid、setgid 的情況下

euid=uid
egid=gid

若 process 在有 setuid、setgid 的情況下

euid=process owner uid
egid=process owner gid

suid 的權限高於 sgid,若僅設 suid、而 euid 和 egid 權限衝突下,以 euid 優先

所以在UNIX系統中我們使用 passwd 更改自己密碼時,user 本身不需要 root 權限

但 passwd 這隻程式會去修改 /etc/master.passwd 和 /etc/passwd 檔案中 user 的密碼資料

/etc/master.passwd和/etc/passwd都是只有root可寫入

這是因為 /usr/bin/passwd 這個檔案有 setuid

-r-sr-xr-x 2 root wheel 8392 Mar 22 23:50 /usr/bin/passwd

這邊可以看到最後三碼是 r-x,所以一般 user 都可以直接執行

而在 2~4 碼可以看到 r-s 這表示在執行時程式的 euid 會被設為 file owner 也就是 root

因此一般 user 執行 passwd 時,程式本身就能拿到root權限而去修改 /etc/passwd 中的資料了


0x03 Sticky bit

除了 suid、sgid 外,在權限配置上還有個會出現的就是 sticky bit

sticky bit 對 regular file 而言有以下兩個功能

  • Cache the executable in swap area after execution
  • Increase performance of loading the executable

對 directory 的效用則為

在該資料夾內的檔案僅可被以下人員 delete 或 rename

  • 該 file owner
  • sticky bit directory 的 owner
  • superuser

常見的 sticky bit directory 如 /tmp

  • drwxrwxrwt : 有sticky bit 且 other 有配執行權
  • drwxrwxrwT : 有sticky bit 但 other 沒有配執行權

0x04 參考資料

operating_system/nix_suid_sgid_in_unix.txt · 上一次變更: 127.0.0.1