What keeps me from abusing setuid(0) and programs with setuid bit set?

Just learning about the privilege escalation method provided by setuid. Correct me if I am wrong but what it does is change the uid of the current process to whatever uid I set. Right ?

So what stops me from writing my own C program and calling setuid(0) within it and gaining root privileges ?

Also my next question will be lets question will be about programs which have the setuid bit set.

If a program has the setuid bit set and the owner as root then can't I just exec that program in to my process and use to wreak havoc ? Its the same problem of gaining root privileges ?

I have seen a lot of documentation online on what these systems do, but none on how these systems are restricted. Hence I am asking the question here.

Yes, if you have the rights to set the uid bit in the first place which you won't.

If you could set the uid bit on your program you are only allowing it to run as you (which it would anyway). You cannot set your new executable to be owned by root.

Yes, it will run with the privileges of the owner BUT only until that executable ends (and you won't be able to break out of it). After that, it reverts to your rights.

The purpose of setuid is as follows. Take the /etc/passwd file which holds user account information. No ordinary user can be allowed to edit or delete that file, but wait a minute, an ordinary user needs to be allowed to change their own password which is stored (encrypted) in that file. So, simply, the command to change password can be run as root to achieve the password change but only until that command ends. Other than that, the ordinary user has no rights to the passwd file.

I suppose if you have access to become the super-user (usually root, but some sites have multiple UID=0 accounts) then you are trusted. If you then choose to abuse that trust by creating a setuid executable file owned by the super-user then you are sharing that trust. If you leave the file available to be updated by others, then you are sharing the trust for what trust you are sharing.

It is usually frowned upon with most people preferring to use sudo instead. Rules can be written to allow people to assume other identities whilst running executables. It's all down to who you trust.

Can you tell us a bit more about what you need it to do?

Robin