Skip to content

Instantly share code, notes, and snippets.

@Micrified
Created March 12, 2022 09:05
Show Gist options
  • Save Micrified/b586967b60dc807c7d9d3aaaf0d15144 to your computer and use it in GitHub Desktop.
Save Micrified/b586967b60dc807c7d9d3aaaf0d15144 to your computer and use it in GitHub Desktop.
Describes UNIX setuid

SetUID

The setuid feature enables an executable to be run with the effective UID of the file owner. For example, a binary owned by root (passwd) can be run by any user (so they can change their password). Normally, simply giving group-level execution rights isn’t enough. Because while you might be able to run passwd, it will still fail when it tries to modify files not owned by the invoking user.

With setuid, the running process will appear to be running as the file-owner (hence the term effective UID). This ensures that the program can indeed modify files also belonging to the owner. The best-case use for this (and probably most common) is for root, when it wants to make binaries and services available to users like the change-password facility that also must make file-system changes to root owned files.


Command

chmod 4<permissions> <filename> (the 4 prefix means to apply setuid)

E.G: chmod 4644 passwd


Demo

Consider a file owned by root, named names.txt. It appears on the filesystem as such:

-rw-r--r-- 1 root wheel ... root.txt

You can see root owns this file. Others cannot modify it.

Suppose there is a program to modify it, called append-names.c:

#include <stdio.h>
#include <stdlib.h>
int main (int argc, const char *argv[]) {
  if (argc != 2) return -1;
  FILE *f = fopen("names.txt", "a");
  if (NULL == f) return -1;
  fprintf(f, "%s\n", argv[1]);
  return 0;
}

The program (when compiled to append-names) by default has permisssions:

-rwxr-xr-x 1 root wheel ... append-names"

Users can execute this, but it will fail at fopen (due to permissions). To allow the users to run it, the root user can set the setuid bit:

chmod 4755 append-names

Here, the 4 that prefixes the permissions means to apply setuid. Now, when you look at permissions:

-rwsr-xr-x 1 rooot wheel ... append-names

You see the "x" indicator under owner-permissions has changed to "s". This indicates setuid is active. A non-root user may now execute this binary, and also successfully modify the names.txt file as a side-effect.


Notes

  • Scripts CANNOT run with setuid. They are an exception due to security concerns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment