检查用户是否是root用C? [英] Check if user is root in C?

查看:404
本文介绍了检查用户是否是root用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何,如果用户是root我核实?

How can I verify if the user is root?

推荐答案

通常这是一个错误的测试,如果用户是root。 POSIX甚至不需要root用户,但它留下来的执行情况,确定权限的工作。 code,如:

Usually it's a mistake to test if the user is root. POSIX does not even require a root user, but leaves it to the implementation to determine how permissions work. Code such as:

if (i_am_root) do_privileged_op(); else print_error();

真的会惹恼用户提供先进的特权模式,使根是没有必要进行必要的特权操作。我记得在CD刻录在Linux上的初期,我不得不砍遍 cdrecord的源删除所有无用的检查,看是否有人作为root运行,当它的工作只是罚款与读取权限的/ dev / SGA

will really annoy users with advanced privilege models where root is not necessary to perform the necessary privileged operations. I remember back in the early days of cd burning on Linux, I had to hack all over the cdrecord source to remove all the useless checks to see if it was running as root, when it worked just fine with permission to read /dev/sga.

相反,你应该总是尝试您需要的,如果它未通知用户执行,并检查 EPERM 或类似的特权操作他们有足够的权限(也许应重试以root身份运行)。

Instead, you should always attempt the privileged operation you need to perform, and check for EPERM or similar if it fails to notify the user that they have insufficient privileges (and perhaps should retry running as root).

的一种情况是非常有用的检查根如果你的程序被调用SUID根正在检查。一个合理的考验将是:

The one case where it's useful to check for root is checking if your program was invoked "suid-root". A reasonable test would be:

uid_t uid=getuid(), euid=geteuid();
if (uid<0 || uid!=euid) {
    /* We might have elevated privileges beyond that of the user who invoked
     * the program, due to suid bit. Be very careful about trusting any data! */
} else {
    /* Anything goes. */
}

请注意,我允许的可能性(牵强,但最好是偏执狂),要么调用来获得UID / EUID可能会失败,并在故障情况下,我们应该承担我们suid和恶意用户已经在某种程度上造成了系统调用试图隐藏我们的suid失败。

Note that I allowed for the possibility (far-fetched, but best to be paranoid) that either of the calls to get uid/euid could fail, and that in the failure case we should assume we're suid and a malicious user has somehow caused the syscalls to fail in an attempt to hide that we're suid.

这篇关于检查用户是否是root用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆