真实用户id、有效用户id、保存的设置用户id的区别以及联系(setuid、seteuid)

文章转载自:https://blog.csdn.net/taiyang1987912/article/details/40651623

 

在使用 setuid() 函数时会遇到 3 个关于 ID 的概念:
real user ID -- 真实用户 ID
effective user ID -- 有效用户 ID
saved set-user-ID -- 保存了的设置用户 ID。

真实用户 ID (real user ID) 就是通常所说的 UID,在 /etc/passwd 中能看到它的身影,如:

beyes:x: 1000:1000:beyes,206,26563288,63230688:/home/beyes:/bin/bash

它用来标识系统中各个不同的用户。普通用户无法改变这个 ID 值。

有效用户 ID (effective) 表明,在运行一个程序时,你是以哪种有效身份运行它的。一般而言,有效用户ID 等于 真实用户 ID。这两个 ID 值可以用 geteuid() 和 getuid() 函数获取。

#include <sys/types.h>

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>


int main(void)

{

printf ("The real user ID is: %d\n", getuid());

printf ("The effective user ID is :%d\n", geteuid());

return (0);

}

编译程序后,查看生成的可执行文件权限:

 

$ls -l getuid.exe
-rwxr-xr-x 1 beyes beyes 4775 Jun  9 15:38 getuid.exe

普通用户运行

$ ./getuid.exe
The real user ID is: 1000
The effective user ID is :1000

root 用户运行

# ./getuid.exe
The real user ID is: 0
The effective user ID is :0

这就是所说的一般情况:实际用户ID == 有效用户 ID

下面看不一致的情况
使用 chmod 改变该程序的有效权限位(suid):

$ chmod u+s getuid.exe
$ ls -l getuid.exe
-rwsr-xr-x 1 beyes beyes 4775 Jun  9 15:38 getuid.exe


再使用普通用户运行:

$ ./getuid.exe
The real user ID is: 1000
The effective user ID is :1000

切换到 root 用户运行:

# ./getuid.exe
The real user ID is: 0
The effective user ID is :1000

从 root 运行输出来看,有效用户 ID 的值为 1000 。也就是说,root 运行这个程序时,是没有 root 的权限的,它只有 beyes 这个普通用户(实际用户 ID 为 1000)的权限。关于设置有效权限位可以参考:http://www.groad.net/bbs/read.php?tid-367.html

下面用一个实例来验证 root 运行此程序时只有 beyes 这个普通用户的权限,按下面步骤来进行:

1. 现在 /root 目录下创建一个普通的文本文件 rootfile.txt :

# echo "hello world" > /root/rootfile.txt
# ls -l /root/rootfile.txt
-rw-r--r-- 1 root root 12 Jun  9 15:48 /root/rootfile.txt


2. 修改上面的程序代码为:

#include <sys/types.h>

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>


int main(void)

{

    const char *file = "/root/rootfile.txt";


    printf ("The real user ID is: %d\n", getuid());

    printf ("The effective user ID is :%d\n", geteuid());


    if (!unlink (file))

        printf ("Ok, I am root, and I can delete the file which in /root directory.\n");

    else

        perror ("unlink error");


    return (0);

}

在上面的代码中所要做的事情很简单,就是要尝试删除 /root/rootfile.txt 这个文件。使用普通用户来编译该程序。

现在先使用普通用户来运行该程序:

$ ./getuid.exe
The real user ID is: 1000
The effective user ID is :1000
unlink error: Permission denied

很自然,普通用户没有权限删除 /root 下的文件。

下面使用 root 来运行该程序:

# ./getuid.exe
The real user ID is: 0
The effective user ID is :0
Ok, I am root, and I can delete the file which in /root directory.

也很正常,root 有权限删除它目录下的文件。

现在为这个程序添加有效权限位,注意这里是用普通用户运行的 chmod 命令:

beyes@debian:~$ chmod u+s getuid.exe
beyes@debian:~$ ls -l getuid.exe
-rwsr-xr-x 1 beyes beyes 5211 Jun 10 10:45 getuid.exe

再次分别以 普通用户 和 root 用户运行上面的程序:

普通用户:

$ ./getuid.exe
The real user ID is: 1000
The effective user ID is :1000
unlink error: Permission denied

还是一样,普通用户并没有权限删除 /root 下的文件。

root 用户:

# ./getuid.exe
The real user ID is: 0
The effective user ID is :1000
unlink error: Permission denied

由输出可见,root 用户也没法删除该文件!同时我们看到,此时的 有效用户 ID 值为 1000,所以我们知道,这个程序所赋予操作文件的权限不但要检查实际用户ID,更重要的是要考虑 有效用户ID ;如果 有效用户 没有权限删除,那么换成 root 用户它也相当于被降权了,当然这个降权仅限于在这个程序的空间中。



下面通过 setuid() 和 seteuid() 这两个函数来考察一下 saved set-user-ID (保存的设置用户ID)这个概念。

在使用 setuid() 时会遇到如下情况:
1. 若进程有 root 权限,则函数将实际用户 ID、有效用户 ID 设置为参数 uid  。见如下代码:

 

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>


void show_ids(void)

{

    printf ("real uid: %d\n", getuid());

    printf ("effective uid: %d\n", geteuid());

}


int main(int argc, char *argv[])

{


    int uid;

    show_ids();

    uid = atoi(argv[1]);


    if (setuid (uid) < 0)

        perror ("setuid error");


    show_ids();


    return (0);

}

下面使用 root 用户来运行上面的程序:

 

# ./setuid.exe 1001
real uid: 0
effective uid: 0
real uid: 1001
effective uid: 1001

由此可见,在 root 下,实际用户 ID 和有效用户 ID 均被设为 setuid() 的参数 uid 的值。

2. 若进程不具有 root 权限,那么普通用户使用 setuid() 时参数 uid 只能是自己的,没有权限设置别的数值,否则返回失败:
使用普通用户来运行:

$ ./setuid.exe 1001
real uid: 1000
effective uid: 1000
setuid error: Operation not permitted
real uid: 1000
effective uid: 1000

由以上可以看出,只有超级用户进程才能更改实际用户 ID 。所以一个非特权用户进程不能通过 setuid 或 seteuid 得到特权用户权限。

这里考虑 su 这个程序,su 可以将普通用户切换到 root 用户。这是因为,su 被设置了 有效权限位:

# ll /bin/su
-rwsr-xr-x 1 root root 29152 Feb 16 04:50 /bin/su

如上面所做实验描述的一样,普通用户在运行 su 时,它也就拥有了 root 的权限。

对于调用了 setuid() 函数的程序要格外小心,当进程的有效用户 ID 即 euid 是 root 用户时(设置了有效权限位),如果调用了 setuid() ,那么它会与它相关的所有 ID (real user ID, effective user ID,saved set-user-ID) 都变成它参数里所设的 ID,这样该进程就变成了普通用户进程,也就再也恢复不了 root 权限了。看下面代码:

 

 

 
#include <stdio.h>

#include <stdlib.h>


void show_ids (void)

{

    printf ("The real user ID is: %d\n", getuid());

    printf ("The effective user ID is :%d\n", geteuid());

}


int main(void)

{

    const char *file = "/root/rootfile3.txt";  

        setuid (0)

    show_ids();

    if (!unlink (file)) {

        printf ("Ok, I am root, and I can delete the file which in /root directory.\n");

    system ("echo hello world > /root/rootfile3.txt");

    printf ("Now, drop the root privileges.\n");
    
    if (setuid (1000) < 0) {

        perror ("setuid");

    exit (EXIT_FAILURE);

    }

    show_ids();

    if (unlink (file) < 0) {

        printf ("Ok, we have no privilege to delete rootfile.txt.\n");

    }

    printf ("try to regain root power again...\n");

    if (seteuid (0)) {

        perror ("seteuid");

    show_ids();

    exit (EXIT_FAILURE);

    }

}
 

我们使用 root 编译上面的程序,并运行 chmod u+s 给程序添加 suid 位,然后以普通用户来运行它:

# ./getuid3 The real user ID is: 0The effective user ID is :0Ok, I am root, and I can delete the file which in /root directory.Now, drop the root privileges.The real user ID is: 1000The effective user ID is :1000Ok, we have no privilege to delete rootfile.txt.try to regain root power again... seteuid: Operation not permittedThe real user ID is: 1000The effective user ID is :1000

由输出可见,在运行 setuid (1000) 函数时,我们还是具有 root 权限的,所以该函数会设置成功。正是因为有了 root 权限,所以 3 个 ID (真实用户ID,已保存用户ID,有效用户ID)都会被设置为 1000。所以在运行完 setuid(1000) 后,进程已经被降权为普通用户,此时想再  seteuid (0) 提高权限已经不可能。这里需要提到一点,对于 show_ids() 函数里,我们无法获取 保存的设置用户ID(saved set-user-ID),这是因为没有这种 API 。但是我们知道这个约定:当用户是 root 时,使用 setuid() 来修改 uid,这 3 个 ID 是会被同时都修改的。但是有没有办法,先使进程降权后在某些时候再恢复 root 权力呢?办法是使用 seteuid() 而不是 setuid() 。那 setuid() 和 seteuid() 有什么不同么?在 seteuid() 的 man 手册里提到:

seteuid() sets the effective user ID of the calling process.  Unprivileged user processes may only set the effective user ID to the real user ID, the effec‐tive user ID or the saved set-user-ID.

setedui() 用来设置调用进程的有效用户 ID。普通用户进程只能将 有效用户ID 设置为 实际用户ID,有效用户ID,保存的设置用户ID。这里比较重要的是,seteuid() 中的参数可以被设置为 保存的设置用户 ID 。保存的设置用户 ID 是这样的一种概念:它是从 exec 复制有效用户 ID 而得来的。具体的说,当我们从一个 shell 里执行一个外部命令时(这里就当做是执行上面的 getuid3 这个),如果该程序设置了用户ID位(有效权限位),那么在 exec 根据文件的用户ID设置了进程的有效用户 ID 后,就会将这个副本保存起来。简单的说,saved set-user-ID 保存了 有效用户ID 的值。比如对于 getuid3 这个程序,saved set-user-ID 保存的值就是 0 。据此,我们修改上面的 getuid3 程序代码为:

#include <sys/types.h>

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>


void show_ids (void)

{

    printf ("The real user ID is: %d\n", getuid());

    printf ("The effective user ID is :%d\n", geteuid());

}


int main(void)

{

    const char *file = "/root/rootfile3.txt";


    show_ids();

    if (!unlink (file)) {

        printf ("Ok, I am root, and I can delete the file which in /root directory.\n");

        system ("echo hello world > /root/rootfile3.txt");

        printf ("Now, drop the root privileges.\n");

        if (seteuid (1000) < 0) {

            perror ("setuid");

            exit (EXIT_FAILURE);

        }

        show_ids();

        if (unlink (file) < 0) {

            printf ("Ok, we have no privilege to delete rootfile3.txt.\n");

           }

    printf ("try to regain root power again...\n");

    if (seteuid (0)) {

        perror ("seteuid");

        show_ids();

        exit (EXIT_FAILURE);

        }

    }

    show_ids();


    printf ("try to delete rootfile3.txt again\n");

    if (!unlink(file)) {

        printf ("Ok, regain root power successful!\n");

        system ("echo hello world > /root/rootfile3.txt");

        return (0);

        }


    return (0);

}

在上面的代码中,我们将原来的 setuid(1000) 替换为 seteuid(1000); 。并且在此后,再次尝试删除 /root/rootfile3.txt 这个文件。下面在普通用户下运行该程序:

beyes@debian:~/C/syscall/getuid$ ./getuid3
The real user ID is: 1000
The effective user ID is :0
Ok, I am root, and I can delete the file which in /root directory.
Now, drop the root privileges.
The real user ID is: 1000
The effective user ID is :1000
Ok, we have no privilege to delete rootfile3.txt.
try to regain root power again...
The real user ID is: 1000
The effective user ID is :0
try to delete rootfile.txt again
Ok, regain root power successful!

此时我们看到整个过程:
先是普通用户执行了具有 root 有效权限位设置的程序,它成功的删除了 /root 下面的一个文本文件;然后使用 system() 系统调用恢复了该文件,目的是方便下面继续实验。接着,它使用 seteuid() 函数时该进程降权为普通用户权限进程。此后,正是因为有了 saved set-user-ID 的保存,所以当再次使用 seteuid() 恢复 进程的 root 权限时可以恢复成功!

所以再次看到,setuid() 会改变 saved set-user-ID 的值而不能恢复权限;而 seteuid() 不会改变 saved set-user-ID 这个值,所以它能够恢复。

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Git-2.21.0-64 for windows Git 2.23 Release Notes ====================== Updates since v2.22 ------------------- Backward compatibility note * The "--base" option of "format-patch" computed the patch-ids for prerequisite patches in an unstable way, which has been updated to compute in a way that is compatible with "git patch-id --stable". * The "git log" command by default behaves as if the --mailmap option was given. UI, Workflows & Features * The "git fast-export/import" pair has been taught to handle commits with log messages in encoding other than UTF-8 better. * In recent versions of Git, per-worktree refs are exposed in refs/worktrees/<wtname>/ hierarchy, which means that worktree names must be a valid refname component. The code now sanitizes the names given to worktrees, to make sure these refs are well-formed. * "git merge" learned "--quit" option that cleans up the in-progress merge while leaving the working tree and the index still in a mess. * "git format-patch" learns a configuration to set the default for its --notes=<ref> option. * The code to show args with potential typo that cannot be interpreted as a commit-ish has been improved. * "git clone --recurse-submodules" learned to set up the submodules to ignore commit object names recorded in the superproject gitlink and instead use the commits that happen to be at the tip of the remote-tracking branches from the get-go, by passing the new "--remote-submodules" option. * The pattern "git diff/grep" use to extract funcname and words boundary for Matlab has been extend to cover Octave, which is more or less equivalent. * "git help git" was hard to discover (well, at least for some people). * The pattern "git diff/grep" use to extract funcname and words boundary for Rust has been added. * "git status" can be told a non-standard default value for the "--[no-]ahead-behind" option with a new configuration variable status.aheadBehind. * "git fetch" and "git pull" reports when a fetch results in non-fast-forward updates to let the user notice unusual situation. The commands learned "--no-show-forced-updates" option to disable this safety feature. * Two new commands "git switch" and "git restore" are introduced to split "checking out a branch to work on advancing its history" and "checking out paths out of the index and/or a tree-ish to work on advancing the current history" out of the single "git checkout" command. * "git branch --list" learned to always output the detached HEAD as the first item (when the HEAD is detached, of course), regardless of the locale. * The conditional inclusion mechanism learned to base the choice on the branch the HEAD currently is on. * "git rev-list --objects" learned the "--no-object-names" option to squelch the path to the object that is used as a grouping hint for pack-objects. * A new tag.gpgSign configuration variable turns "git tag -a" into "git tag -s". * "git multi-pack-index" learned expire and repack subcommands. * "git blame" learned to "ignore" commits in the history, whose effects (as well as their presence) get ignored. * "git cherry-pick/revert" learned a new "--skip" action. * The tips of refs from the alternate object store can be used as starting point for reachability computation now. * Extra blank lines in "git status" output have been reduced. * The commits in a repository can be described by multiple commit-graph files now, which allows the commit-graph files to be updated incrementally. * "git range-diff" output has been tweaked for easier identification of which part of what file the patch shown is about. Performance, Internal Implementation, Development Support etc. * Update supporting parts of "git rebase" to remove code that should no longer be used. * Developer support to emulate unsatisfied prerequisites in tests to ensure that the remainder of the tests still succeeds when tests with prerequisites are skipped. * "git update-server-info" learned not to rewrite the file with the same contents. * The way of specifying the path to find dynamic libraries at runtime has been simplified. The old default to pass -R/path/to/dir has been replaced with the new default to pass -Wl,-rpath,/path/to/dir, which is the more recent GCC uses. Those who need to build with an old GCC can still use "CC_LD_DYNPATH=-R" * Prepare use of reachability index in topological walker that works on a range (A..B). * A new tutorial targeting specifically aspiring git-core developers has been added. * Auto-detect how to tell HP-UX aCC where to use dynamically linked libraries from at runtime. * "git mergetool" and its tests now spawn fewer subprocesses. * Dev support update to help tracing out tests. * Support to build with MSVC has been updated. * "git fetch" that grabs from a group of remotes learned to run the auto-gc only once at the very end. * A handful of Windows build patches have been upstreamed. * The code to read state files used by the sequencer machinery for "git status" has been made more robust against a corrupt or stale state files. * "git for-each-ref" with multiple patterns have been optimized. * The tree-walk API learned to pass an in-core repository instance throughout more codepaths. * When one step in multi step cherry-pick or revert is reset or committed, the command line prompt script failed to notice the current status, which has been improved. * Many GIT_TEST_* environment variables control various aspects of how our tests are run, but a few followed "non-empty is true, empty or unset is false" while others followed the usual "there are a few ways to spell true, like yes, on, etc., and also ways to spell false, like no, off, etc." convention. * Adjust the dir-iterator API and apply it to the local clone optimization codepath. * We have been trying out a few language features outside c89; the coding guidelines document did not talk about them and instead had a blanket ban against them. * A test helper has been introduced to optimize preparation of test repositories with many simple commits, and a handful of test scripts have been updated to use it. Fixes since v2.22 ----------------- * A relative pathname given to "git init --template=<path> <repo>" ought to be relative to the directory "git init" gets invoked in, but it instead was made relative to the repository, which has been corrected. * "git worktree add" used to fail when another worktree connected to the same repository was corrupt, which has been corrected. * The ownership rule for the file descriptor to fast-import remote backend was mixed up, leading to an unrelated file descriptor getting closed, which has been fixed. * A "merge -c" instruction during "git rebase --rebase-merges" should give the user a chance to edit the log message, even when there is otherwise no need to create a new merge and replace the existing one (i.e. fast-forward instead), but did not. Which has been corrected. * Code cleanup and futureproof. * More parameter validation. * "git update-server-info" used to leave stale packfiles in its output, which has been corrected. * The server side support for "git fetch" used to show incorrect value for the HEAD symbolic ref when the namespace feature is in use, which has been corrected. * "git am -i --resolved" segfaulted after trying to see a commit as if it were a tree, which has been corrected. * "git bundle verify" needs to see if prerequisite objects exist in the receiving repository, but the command did not check if we are in a repository upfront, which has been corrected. * "git merge --squash" is designed to update the working tree and the index without creating the commit, and this cannot be countermanded by adding the "--commit" option; the command now refuses to work when both options are given. * The data collected by fsmonitor was not properly written back to the on-disk index file, breaking t7519 tests occasionally, which has been corrected. * Update to Unicode 12.1 width table. * The command line to invoke a "git cat-file" command from inside "git p4" was not properly quoted to protect a caret and running a broken command on Windows, which has been corrected. * "git request-pull" learned to warn when the ref we ask them to pull from in the local repository and in the published repository are different. * When creating a partial clone, the object filtering criteria is recorded for the origin of the clone, but this incorrectly used a hardcoded name "origin" to name that remote; it has been corrected to honor the "--origin <name>" option. * "git fetch" into a lazy clone forgot to fetch base objects that are necessary to complete delta in a thin packfile, which has been corrected. * The filter_data used in the list-objects-filter (which manages a lazily sparse clone repository) did not use the dynamic array API correctly---'nr' is supposed to point at one past the last element of the array in use. This has been corrected. * The description about slashes in gitignore patterns (used to indicate things like "anchored to this level only" and "only matches directories") has been revamped. * The URL decoding code has been updated to avoid going past the end of the string while parsing %-<hex>-<hex> sequence. * The list of for-each like macros used by clang-format has been updated. * "git branch --list" learned to show branches that are checked out in other worktrees connected to the same repository prefixed with '+', similar to the way the currently checked out branch is shown with '*' in front. (merge 6e9381469e nb/branch-show-other-worktrees-head later to maint). * Code restructuring during 2.20 period broke fetching tags via "import" based transports. * The commit-graph file is now part of the "files that the runtime may keep open file descriptors on, all of which would need to be closed when done with the object store", and the file descriptor to an existing commit-graph file now is closed before "gc" finalizes a new instance to replace it. * "git checkout -p" needs to selectively apply a patch in reverse, which did not work well. * Code clean-up to avoid signed integer wraparounds during binary search. * "git interpret-trailers" always treated '#' as the comment character, regardless of core.commentChar setting, which has been corrected. * "git stash show 23" used to work, but no more after getting rewritten in C; this regression has been corrected. * "git rebase --abort" used to leave refs/rewritten/ when concluding "git rebase -r", which has been corrected. * An incorrect list of options was cached after command line completion failed (e.g. trying to complete a command that requires a repository outside one), which has been corrected. * The code to parse scaled numbers out of configuration files has been made more robust and also easier to follow. * The codepath to compute delta islands used to spew progress output without giving the callers any way to squelch it, which has been fixed. * Protocol capabilities that go over wire should never be translated, but it was incorrectly marked for translation, which has been corrected. The output of protocol capabilities for debugging has been tweaked a bit. * Use "Erase in Line" CSI sequence that is already used in the editor support to clear cruft in the progress output. * "git submodule foreach" did not protect command line options passed to the command to be run in each submodule correctly, when the "--recursive" option was in use. * The configuration variable rebase.rescheduleFailedExec should be effective only while running an interactive rebase and should not affect anything when running a non-interactive one, which was not the case. This has been corrected. * The "git clone" documentation refers to command line options in its description in the short form; they have been replaced with long forms to make them more recognisable. * Generation of pack bitmaps are now disabled when .keep files exist, as these are mutually exclusive features. (merge 7328482253 ew/repack-with-bitmaps-by-default later to maint). * "git rm" to resolve a conflicted path leaked an internal message "needs merge" before actually removing the path, which was confusing. This has been corrected. * "git stash --keep-index" did not work correctly on paths that have been removed, which has been fixed. (merge b932f6a5e8 tg/stash-keep-index-with-removed-paths later to maint). * Window 7 update ;-) * A codepath that reads from GPG for signed object verification read past the end of allocated buffer, which has been fixed. * "git clean" silently skipped a path when it cannot lstat() it; now it gives a warning. * "git push --atomic" that goes over the transport-helper (namely, the smart http transport) failed to prevent refs to be pushed when it can locally tell that one of the ref update will fail without having to consult the other end, which has been corrected. * The internal diff machinery can be made to read out of bounds while looking for --function-context line in a corner case, which has been corrected. (merge b777f3fd61 jk/xdiff-clamp-funcname-context-index later to maint). * Other code cleanup, docfix, build fix, etc. (merge fbec05c210 cc/test-oidmap later to maint). (merge 7a06fb038c jk/no-system-includes-in-dot-c later to maint). (merge 81ed2b405c cb/xdiff-no-system-includes-in-dot-c later to maint). (merge d61e6ce1dd sg/fsck-config-in-doc later to maint).

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值