Introduction to privilege dropping in C

Jan S
2 min readSep 26, 2016

--

I recently wanted to create a server application. And since I’m interested in all kinds of security and exploitation mitigation techniques I’m going to write a little introduction into privilege dropping when using the C programming language.

The concept of privilege dropping is easy. An application, in this case a server, gets started and wants to open a lower range port e.g. 187. On UNIX and unix-like systems ports below 1025 are restricted and an administrator has to approve the use of those ports. Thats the reason the server gets root permissions and is able to open up its needed port(s). After the initial start phase and after the ports have been successfully opened the program drops its privileges to a user who does not have root access on the machine (the less, the better).

The reason for dropping privileges is pretty obvious: security.

Lets assume you run your application as root. Lets now assume your application has a bug with security implications. Now an attacker could probably exploit this bug. Since the application is running with all the permissions it could possibly get, the overtime to safe your company/life is mostly written in stone. I will not get into much detail about what could be wrong with the application, that is something I may write about in another post.

Implementing privilege dropping (privdrop) is fairly easy. Basically the program needs to figure out if its running as root ( uid == 0) with getuid() and then set the uid and gid to an unprivileged user.

For example:

//are we root?
if (getuid == 0) {
if (setgid(gid) == -1)
//error
if (setuid(uid) == -1)
//error
}

Be sure to first set the gid and then the uid! Otherwise a regain of root privs would be possible.

Securecoding has a very good example how to implement privdrop.

The first programm I know of that used privdrop is OpenSSH. A lot of daemons in the OpenBSD base system drop their privileges when the first setup steps are done. (Look at the drop_privs() function.)

Ftp-proxy is another very good example. The developers took it one step further and even chrooted the process. They also used setresgid() and setresuid() which is a non-standard C function, but is available on Linux and BSDs.

I used C as the programming language of my choice in this post, but the privilege dropping is not bound to C. As long as you are able to call the needed functionality you are able to drop the rights. You do not have an excuse to run the server as root all the time!

--

--