Skip to main content
C ProgrammingRaspberry Pi

Using a Simple C Program to Explain the Linux SUID Permission

By January 6, 2014October 9th, 2016No Comments

Effective and Real Permissions

SUID PermissionsSome programs in Linux use the Set UID or SUID permission. One notable program using this is the user password command: /usr/bin/passwd. When the program runs it will execute with the permissions of the file’s owner and not the current user. When we examine the runtime environment of the program we will find that we maintain  REAL UID and an EFFECTIVE UID. The REAL UID being the UID of the user and the EFFECTIVE UID  represents the user’s whose rights we use. Using these values in a simple C program that we can use to demonstrate the use of the SUID permission. This may be of interest to you a someone learning to write C code or an administrator wanting to more about permissions.

Simple C Program

Starting off we will be creating very a simple C in our favoured IDE or text editor. We will use the vim editor in the demonstration.

#include <stdio.h>
#include <unistd.h>
 int main () {
  int real = getuid();
  int euid = geteuid();
  printf("The REAL UID =: %d\n", real);
  printf("The EFFECTIVE UID =: %d\n", euid);
}

The code really is as simple as it looks, using just the 2 header files and the main function. Within the function main we populate two variables. Firstly real and then the euid. The functions getuid() and geteuid() come from the unistd header. Finally, we print the contents of the variables with the next two lines, one variable per line. Once created we can compile the code with using the command the gcc.

gcc -o setuid setuid.c

The compiler will assign standard permissions of rwx rx rx or 755 to the file. We can run it and we will see that the Real and Effective UID are the same.

SUID Permission inLinux

There are programs that standard users need to run with elevated permissions, these include programs like the mount command and passwd program. The program can be owned by root or another account; most often root. When the program runs it will execute with the permissions of the owner of the file rather than the current user. This becomes the EFFECTIVE UID to the running process. In this way standard users can change their own password with /usr/bin/passwd even though the file they write to would not be accessible to their own UID.

Setting this on our file we need to change to the root account and first set the ownership and then permissions of the file:

sudo chown root setuid
sudo chmod 4755 setuid

SUID Permission

Remember the setuid is the name of our program file. The leading 4 in the permission block implements the SUID permission. As a standard user now when we run the program even the REAL UID is still our own UID the EFFECTIVE UID will be 0f the UID of root, the files’ owner.