【问题标题】:unsuccessfully call external shell script as non-root user以非 root 用户身份调用外部 shell 脚本失败
【发布时间】:2012-05-16 22:33:56
【问题描述】:

我希望 A 用户以 B 用户的身份做一些工作。如果 B 是 root 就可以,但非 root 用户失败。以下是基本代码:

root.c:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    setuid( 0 );
    system( "/tmp/script_of_root.sh" );

    return 0;
}

script_of_root.sh:

#!/bin/sh
echo $RANDOM >> /tmp/file_of_root

回放

$ cd /tmp
$ cc root.c -o root
$ su -
# chown root.root /tmp/root
# chmod 4755 /tmp/root
# exit
$ ./root

执行“./root”后,文件“/tmp/file_of_root”将被更新。但是,如果我将相同的东西应用于非 root 用户,它就不起作用。代码:

foobar.c:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    setuid( 1001 );    // uid of user "foobar"
    system( "/tmp/script_of_foobar.sh" );

    return 0;
}

script_of_foobar.sh:

#!/bin/sh
echo $RANDOM >> /tmp/file_of_foobar

回放

$ cd /tmp
$ cc foobar.c -o foobar
$ su -
# chown foobar.users /tmp/foobar
# chmod 4755 /tmp/foobar
# exit
$ ./foobar

如果我以其他普通用户的身份运行“./foobar”(而不是“foobar”本身),就会出错:

/tmp/script_of_foobar.sh: line 2: file_of_foobar: Permission denied

我完全糊涂了。为什么第二种情况不起作用?

最好的问候。

【问题讨论】:

  • 如果结果不为零,您能否检查setuid(1001)perror() 调用的返回值?
  • /tmp的权限是什么? foobar 用户是否对/tmp 有写权限?

标签: c linux shell permissions


【解决方案1】:

foobar.c 中的 setuid 调用只有在您是 root 或您的有效 UID 为 1001 时才会成功。

所以。如果您不是 root,setuid(1001) 将失败,并且您将没有必要的权限来覆盖“foobar”拥有的文件。

【讨论】:

  • 试试 seteuid(1001)。你已经在二进制文件上设置了 setuid 位,但为了确保你没有搞砸,我建议你 printf ("%d\n", geteuid ());就在你调用 system() 之前。
【解决方案2】:

从输出看来,您的非 root 用户能够执行 script_of_foobar.sh,但无法写入 /tmp/file_of_foobar。 /tmp 上的权限是否可能关闭?我认为应该设置为 1777。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多