Tag Archives: perl

Switch to another UID/GID, with Perl

Originally I wanted to start by describing Linux' setuid()-like functions, which change the user-id of a running process (and more). Some reading made me realize that this area is too big (but interesting!) for a simple post, and also that I still don't master it..

So I'll focus only a single, simple task: switching from root to regular user permissions: when a daemon is being run by root (i.e. init scripts), for security reasons we want them to "transform" to a regular user right asap. In the kernel level we want to do something like setuid or setresuid (set all the user identifiers: Real, Effective and Saved) to a specific, different UID.

However, we don't talk about the kernel, but about a much higher scripting language.. So let's begin with basics: according to perlvar manpage, $> (or $EUID if using 'use English') represents the Effective User ID (Effective is the User ID which matters permission-wise). "print $>" perl command would simply print the EUID.

Now for the surprise.. "$>=44" perl command simply sets the EUID! Oh, the simplicity 🙂

GID can be set in a similar manner, but can't be set after the the uid is switched (we need the initial root permission for the GID switch).

Enough talking, let the code begin:

#!/usr/bin/perl -w
use strict;
ues English;
$EGID=22;
$EUID=22;
sleep 50; # Sleep so we can have time to run "ps axo pid,uid,euid,gid,egid" :)