how to setuid for a file in linux

SetUID stands for set user id on execution. The Linux systems allow for elevated or escalated privileges when executing files. This is a special type of permission that can be set on the file in addition to the usual set of file permissions.

When the setuid is set on an executable file, the users can execute that file with the same permissions or privileges as the owner of the file.

An example of such a file is the passwd file. The passwd executable file is owned by the root. When an user wants to change or set their password, they will need to run the passwd command. But only the super user or root have the necessary permissions to modify passwords and associated files.

But because the setuid permissions are set on the passwd executable file, the user will run the script as the super user. This will allow the script and thus the user to modify the password successfully. This escalated privilege exist only for the duration that the file is run and only for the process executing the file.

how to view the setuid permission on the file

Checking if the file has setUID set on it is simple enough. You can use the ls command that you use to list the files. You can use the ls command with -l option or the stat command. Usually you will see an x in the user-executable bit position when the setuid is not set, but for file which has setUID permissions, you will see an s in the field.

bash$ ls -li

how to set the setuid on a file

You can set the setUID of a file using the chmod command just as you change the permissions of a file. There are two different ways you can set the permission: using the octal format method or the user friendly human readable format.

In the octal format, the magic number you have to remember is 4. If you prepend 4 to the usual set of permission bits, then the file will have the setuid bit set:

$ chmod 4755

In the human readable format, you will use the character s to specify that the setuid be set for the user on the file.

$ chmod u+s

how to remove setuid permission of a file

It should be pretty obvious as to how you can remove or unset the setuid bit. In the otcal format you can prepend 0 instead of 4 to unset the permission.

$ chmod 0755

In the human readable format, you will use -s instead of +s ….

$ chmod u-s

In the normal order of business, it is very unlikely that you will need to setuid of a file. The most common use case is when you have a multiple user machine and you want the users to execute something at the admin level.