Reputation: 138
Don't tell me this is a duplicate because I have already read questions like how to execute a command as root but I just can't make it work for me.
This is my C program whoami.c
:
#include <stdio.h>
#include <stdlib.h>
int main() {
system("whoami");
}
And this is exactly what I did:
user@ubuntu:~/Desktop/test$ ls
whoami.c
user@ubuntu:~/Desktop/test$ gcc whoami.c
user@ubuntu:~/Desktop/test$ sudo chown root:root a.out
[sudo] password for user:
user@ubuntu:~/Desktop/test$ sudo chmod 4711 a.out
user@ubuntu:~/Desktop/test$ ls -l
total 24
-rws--x--x 1 root root 16816 Nov 13 13:03 a.out
-rw-rw-r-- 1 user user 75 Nov 13 13:03 whoami.c
user@ubuntu:~/Desktop/test$ ./a.out
user
user@ubuntu:~/Desktop/test$ sudo ./a.out
root
user@ubuntu:~/Desktop/test$
I thought that the s
in the execution bit means that no matter who starts this program, it will ever run as root so my question is why is this not working?
And if doing this is not possible how can I let any user run a specific program as root?
Upvotes: 1
Views: 2329
Reputation: 138
This worked for me: add setuid(geteuid());
before running de command.
To use setuid()
and geteuid()
you need to import unistd.h
Working program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
setuid(geteuid());
system("whoami");
}
If you set up SUID with the same commands of the question you get always root
as output no matter which user run this program.
Instead of whoami
you can use any other command, also if it require root privileges.
I saw this setup in a YouTube video
Upvotes: 3