setuid permissions in Linux

setuid stands for Set User  ID on Execution.

What is User ID(UID)?

UID is a number used to uniquely identify the user on the system, and to determine which system resources the user can access.

When you create a file, the ownership of the file will be based on the user id and group id of the user created the file.

When you run a process, the process will be running with the user id and group id of the user starting the process. It means, if user1 created an executable file, the owner and group of file will be the user1, but when we run the executable with other user, the uid of the process will be the other user not the user created the executable.

getuid()  returns the User Id of the calling process.


In the above screenshot, I created hello.c with the user 'jamal', so the owner and group is 'jamal'. But when running the generated executable/process we get the uid of the user who started the executable/process.

If you set the setuid bit on the executable, the executable will not run with the privileges of the user who launched it, but with the privileges of the owner instead.

geteuid() will returns the effective user id of the calling process.
Let's see what is the output in case of setuid bit not set.


You can see the UID and EUID are same in both the users.

Now let's add SUID Permission to 'hello' executable

How to set setuid permission of a file?

chmod u+s myfile




You can see when I run the hello executable with setuid permission, the EUID is the same as owner of the executable and not the calling process.

setuid() function will set user identity.

Let's see a use case of setuid bit. I created a server socket program and bind to HTTP (80) port.


When I run this with normal user, it fails with permission denied. As root is required to bind ports less than 1024. How can we run this program without sudo. Answer is setuid.



After, we set the setuid bit, we can run the server with the root permissions and bind the ports less than 1024.

Note: You should avoid using setuid permissions as it is insecure, we will discuss in upcoming posts the way to avoid setuid and still achieve the above result.


How to find files with setuid set in Linux?

find . -perm /4000


Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig