I was trying to learn how setuid
works.
So I made a dummy program which just prints the current user:
#include<bits/stdc++.h>
using namespace std;
int main(){
cout << system("id -a") << "\n";
cout << system("whoami") << "\n";
}
I compiled and created the executable my-binary
under the user anmol
:
-rwxrwxr-x 1 anmol anmol 9972 Feb 1 16:54 my-binary
Then, I set the setuid
option using chmod +s
:
-rwsrwsr-x 1 anmol anmol 9972 Feb 1 16:54 my-binary
If I execute it normally, I get the following output:
uid=1000(anmol) gid=1000(anmol) groups=1000(anmol),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),116(lpadmin),122(sambashare)
anmol
Now, if I change to another user using su user2
, and then execute it, I get:
uid=1001(user2) gid=1001(user2) groups=1001(user2)
user2
And when I execute it using sudo ./my-binary
, I get:
uid=1001(root) gid=1001(root) groups=1001(root)
root
As far as I understand, no matter how I run it, should I not get the 1st output everytime?
I checked other similar questions over here and some suggested me to check if the filesystem is mounted using nosuid
option, so I executed mount | /dev/sda1
and got the output:
/dev/sda1 on / type ext4 (rw,relatime,errors=remount-ro,data=ordered)
Which means that this option is not enabled.
Any hints on why am I not getting the expected output?
#include<bits/stdc++.h>
?!? That's a bad idea. Don't do that. – Andrew Henle Feb 04 '20 at 10:48