Skip to content
Advertisement

Why does SetSUID not work for shell script?

I am trying to create a executor program for regular users on linux with SUID bit set so whatever commands, passed to the program as parameters, get executed with root permission. However when I try to implement this as a bash script, this does not work, where it works when implemented in C. I want to know what I am doing wrong for the shell script. The codes are below

Shell Script:

#! /bin/bash
if [ $# -lt 1 ]; then
echo "Usage: $0 <Command String>"
exit 1
fi
$@
#Also tried this, same result
#exec $@

Execution:

root#: chmod 755 exec.sh 
root#: chmod u+s exec.sh
root#: ll exec.sh
-rwsr-xr-x 1 root root 75 Sep 19 16:55 exec.sh

regular_user$: ./exec.sh whoami
regular_user

C Program:

#include <stdlib.h>
#include <stdio.h>
int main ( int argc, char *argv[] )
{
if ( argc < 2 ) {
    printf( "Usage: %s <Command String>n", argv[0] );
    return 1;
}
else
{
    argv[argc]=NULL;
    //setuid(0);  //Works without these
    //setgid(0);
    int exit=execvp(argv[1], argv+1);
    return exit;
}
}

Execution:

root#: gcc exec.c -o exec.obj
root#: chmod 755 exec.obj
root#: chmod u+s exec.obj
root#: ll exec.obj
-rwsr-xr-x 1 root root 6979 Sep 19 17:03 exec.obj

regular_user$: ./exec.obj whoami
root

Both files have identical permissions

-rwsr-xr-x 1 root root 75 Sep 19 16:55 exec.sh
-rwsr-xr-x 1 root root 6979 Sep 19 17:03 exec.obj

Advertisement

Answer

It is documented in execve(2) :

Linux ignores the set-user-ID and set-group-ID bits on scripts.

IIRC, setuid scripts would be a significant security hole

See this question

You could configure sudo to avoid asking a password – see sudoers(5) (or use super)

You could also write a simple C program wrapping your shell script, and make it setuid.

Advertisement