-3

I am running my service as a user (given the correct permissions and added to appropriate groups), but if I want, I can also run it as root. How can I disable this system-wide and not for a single application?

Fisnik Hajredini
  • 73
  • 1
  • 1
  • 5
  • In which programming language? – Toby Speight Oct 17 '19 at 12:45
  • We can't *prevent* root running a program, but we can add code to rectify the situation as soon as we reach user code. The easiest way in C is to call one of the `setuid()` family of calls to change to (e.g.) the "nobody" user. If the process isn't sufficiently privileged, the `setuid` will fail (we can ignore the error return from it), but if it's run as root, it will no longer be doing so. – Toby Speight Oct 17 '19 at 12:55
  • Is there any setting to set this globally on the system instead of programming it on the application itself? – Fisnik Hajredini Oct 17 '19 at 13:32
  • That would be a [sf] or [unix.se] question (but I think the answer is no). – Toby Speight Oct 17 '19 at 15:45

1 Answers1

2

Assuming its written in bash. you can do something like this:

if [[ $EUID -eq 0 ]]; then
  echo "Cant run this as root" 1>&2
  exit 1
fi

Another way to detect which user is running the script is

id -u
$UID

Im currently in my Mac Box and logged as root in a terminal this is the output

  ~# id -u
0
~# echo $UID
0
~# echo $EUID
0
~#
~#

So you are basically saying if my check on the user id is 0 then its root. So just print a message and exit

jstuartmilne
  • 4,398
  • 1
  • 20
  • 30