Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Check for Root User.

| Comments

If we check out the GNU/Linux source code, it's clear that the UID for user with root privilages is set to 0

It's important to note that superuser account always have UID/GID set to 0/0 as we noted from the above links to the source, but the superuser account name need not be root always. [root -> uid 0, but uid -> 0 need not be root.]

So the basic idea of checking if the user is root aka a user with super privilages is to check for the UID/GID.

Let's have a look at how the same is done in few langauges of my choice ;):

In bash:

1
  isRoot=$(($UID == 0))

In nodejs:

1
var isRoot = process.getuid && process.getuid() === 0;

In ruby:

1
isRoot = Process.uid.zero?

In python:

1
2
import os
isRoot = os.geteuid() == 0

In perl:

1
$isRoot = $< == 0;

In haskell:

1
2
import System.Posix.User
let isRoot = fmap (== 0) getRealUserID

In all of the above isRoot will hold a boolean value true if the user is has root privilages or else false.

Hope this was informative! ;)

The other school thought

There are other set of people who prefer to do a try and check method i.e try to some specific root privilage action and check if it succeeded.

There might be many such operations to check, lets stick to a simple example of checking if / is writable?

Let's see how would that look:

Bash:

1
[[ -w / ]] && isRoot=true || isRoot=false

node:

1
2
3
4
5
6
try {
  fs.openSync("/usr/bin/ls","w"); // Workaround.
  isRoot=true;
} catch(e) {
  isRoot=false;
}

ruby:

1
2
3
#is writable by the real user id of this process.?

isRoot = File.writable_real?("/")

python:

1
2
import os
isRoot = os.access('/', os.W_OK)

perl:

1
$isRoot = (-w "/" ? true: false);

haskell:

1
2
3
4
import System.Directory
getPermissions "/"

let isRoot = writeable it

Comments