This script must be run as root linux

Allow bash script to be run as root, but not sudo

I’m new here and new to bash/linux. My teacher gave me an assignment to allow a script to be run only when you’re «really» root and not when you’re using sudo. After two hours of searching and trying I’m beginning to think he’s trolling me. Allowing only root is easy, but how do I exclude users that run it with sudo? This is what I have:

if [[ $EUID -ne 0 ]]; then echo "You must be root to run this script." exit fi 

Take away sudo all and enumerate only the commands a user should be allowed to run as root, excluding your script from that list.

How would you stop the sudo user from removing the restriction from the script once you have put it in place? There is no difference between the root user logged in from a console and the root user accessing the system via sudo . The foolproof solution woud be to simply uninstall sudo .

I think that any answer has to consider the possibility that the lecturer is ignoring (or hasn’t thought of) the possibility of running sudo su and intends that the solution prevents the script from starting to run rather than aborting if it doesn’t like its execution environment. As such I agree with @mikem and would highlight man sudoers -> SECURITY NOTES since some of their caveats aren’t relevant if the script can’t be edited or renamed.

I can see a couple of possibilities here. 1. Your teacher is an idiot who didn’t/doesn’t realize how hard it would be, or how fragile his/her pet «solution» really is. 2. Your teacher is using this as an example to demonstrate the inadequacy of the students attempted solutions. 3. Your teacher is a jerk who decided to throw a neophyte to the wolves just for fun (you mention the trolling possibility in your question). In any case, I question the motives behind such an assignment.

Nothing about sudo requires it to give you root access; that’s just the default behavior everyone is familiar with. sudo can be configured to allow you to do only very specific things, including not gain root access at all.

8 Answers 8

The only way I could think of is to check one of the SUDO_* environment variables set by sudo:

#!/usr/bin/env sh if [ "$(id -u)" -eq 0 ] then if [ -n "$SUDO_USER" ] then printf "This script has to run as root (not sudo)\n" >&2 exit 1 fi printf "OK, script run as root (not sudo)\n" else printf "This script has to run as root\n" >&2 exit 1 fi 

Notice that of course this solution is not future proof as you cannot stop anyone from setting a variable before running the script:

$ su Password: # SUDO_USER=whatever ./root.sh This script has to run as root (not sudo) # ./root.sh OK, script run as root (not sudo) 

+1, but this can still be tricked by something like sudo bash -c ‘unset SUDO_USER=; my_command;’ . I would not rely on it.

Читайте также:  Telegram клиент для linux

It might not be good for actual work, but it will probably get my assignment done, which is what matters at the moment. Thank you very much!

The paranoids among us would begin with env | grep -E ‘SUDO|PPID|PID , and validate each via /usr/bin/ps and other command line tools. One could check each of env | sort , if one wished.

Care! If user run sudo su — , variables SUDO_* doesn’t exist anymore! See unix.stackexchange.com/a/626764/27653

Care, if user run screen ,. detach then re-attach, you can’t see anything more than a root login shell!! See last paragraph at: unix.stackexchange.com/a/626764/27653

Another option would be to check if the grandparent process name is «sudo»:

#!/bin/sh if [ "$(id -u)" -eq 0 ] then if [ $(ps -o comm= -p $(ps -o ppid= -p $$)) = "sudo" ] then echo Running under sudo else echo Running as root and not via sudo fi else echo Not running as root fi 

This fails when run under «sudo su» or «sudo bash». I think you need to check multiple levels of processes.

Granted; you could extend this to loop over the PPID process tree, but I thought I’d cover the most common usage of ./script or sudo ./script , to point out the core idea of checking for «sudo» as being the parent process or not.

This answer attempts to address the question «how do I exclude users that run it with sudo?» in the straightforward interpretation, not as an exhaustive security measure. I don’t know what the professor was aiming for, but maybe parent processes were on the syllabus and they thought this would be an instructive exercise. Any simple measure can be fooled, as we’ve seen so far with the straightforward SUDO_USER environment variable and these process checks.

The information about which user logged in is available in /proc/self/loginuid . EDIT due to comments: That file does not seem to exist on all systems. I tested and it is available on Centos 6, Fedora 32, Fedora 33 and Ubuntu 20.04, all in standard x86_64 setups. If we login as our user and than use sudo or su to become root, this will not change /proc/self/loginuid and it will be some non-zero value. If we directly log in as root, then cat /proc/self/loginuid will return 0 . Note that this file can NOT be modified, even root cannot do this. EDIT due to Stéphane Chazelas’ comment: Root can overwrite this file using echo 0 > /proc/self/loginuid . However, this can be prevented by setting auditctl —loginuid-immutable .

The script to check for real root (if auditctl —loginuid-immutable is set) could look like

#!/bin/bash loginuid=$(cat /proc/self/loginuid) echo $loginuid if [[ $loginuid -ne 0 ]]; then echo "You did not log in as root." exit fi 

I believe this requires CONFIG_AUDIT=y , on Linux, but on such a system this is the right answer (though I imagine the actual goal was to read the manual and find SUDO_USER).

Читайте также:  Linux посмотреть разрядность системы

sudo sh -c ‘echo 0 > /proc/self/loginuid && cat /proc/self/loginuid’ outputs 0 for me on Ubuntu 20.04 with a 5.4.0-58-generic Linux kernel

Источник

Linux

Проверяем от которого пользователя запущен скрипт, если не root выводим сообщение и выходим с ошибкой:

# Check the script is being run by root if [ "$(id -u)" != "0" ]; then echo "This script must be run as root" exit 1 fi
Или запрещаем запуск скрипта от root'а: 
# Check the script is not being run by root if [ "$(id -u)" == "0" ]; then echo "This script must not be run as root" exit 1 fi 

Источник

I am getting an error that I should not run script as root

«root@Lenovo:~/ardupilot. » — «Please do not run this script as root». What exactly is your question? The script already told you why it refused to run.

2 Answers 2

Look, you are signed in as the root user:

Type sudo su YOURUSERNAME it will be changed to

I would suggest creating a new user with just enough permissions to get the job done, then run this script with that user. The way this account is made will depend on which distribution of Linux is being used here, along with the types of permissions necessary to run the script, but there should be options for this in the Settings menu and terminal, respectively.

Running scripts directly from Root is a security hazard. Since Root doesn’t have any restrictions, if the account happened to get infected with malware and hacked, the entire system would be compromised. I have reason to believe the whole point of the error is to prevent exactly this.

You must log in to answer this question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

Ubuntu and the circle of friends logo are trade marks of Canonical Limited and are used under licence.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Bash Scripting: Require script to be run as root (or with sudo)

I’m trying to write a bash script (in Ubuntu) that will backup a directory using tar. How can I do a check in the script so that it can only be run as root (or with sudo)? For instance, if a user runs the script, it should say that this script must be run with sudo privileges, and then quit. If the script is executed as root, it will continue past the check. I know there has to be an easy solution, I just haven’t been able to find it by googling.

Recently, I’ve seen things like systemd elevate privileges automatically with user password entered. I’d be interested in an answer that can not only alert the user they don’t have the needed permissions, but offer to elevate it for them instead of forcing a restart.

Читайте также:  Hp 2014 драйвер linux

came here looking for something like that. I’m building up a script which has sudo usage in the middle of it. would be nice to get it right from the start, but none of the solutions presented here so far have worked (both id -u and sudo id -u come out as «1000» instead of 0)

7 Answers 7

To pull the effective uid use this command:

If the result is ‘0’ then the script is either running as root, or using sudo. You can run the check by doing something like:

if [[ $(/usr/bin/id -u) -ne 0 ]]; then echo "Not running as root" exit fi 

I’d recommend fully-qualifying the path to id (e.g., /usr/bin/id). Otherwise a devious user could write their own script/binary that always returns 0 and then put it in a location that exists earlier in the executing users’ path.

I agree with theother. it’s a bash script. Qualifying the ‘id’ bin won’t stop anyone who is seriously intent on getting around the check anyway. Better to leave it unqualified for portability.

I assume you know that by changing the ownership to root

and setting the permissions to 700

you will accomplish the same thing — without the suggestion to run as sudo.

But I will post this answer for completeness.

The bash variable $EUID shows the effective UID the script is running at, if you want to make sure the script runs as root, check wether $EUID contains the value 0 or not:

if [[ $EUID -ne 0 ]]; then echo "$0 is not running as root. Try using sudo." exit 2 fi 

This is better than the solution with /usr/bin/id (for bash scripts!) because it doesn’t require an external command.

Instead of just exiting, could prompt the user for sudo login by replacing the echo line with sudo «$0» «$@» , and replace exit 2 with exit $? .

You can use whoami command as well.

if [ ! "`whoami`" = "root" ] then echo "\nPlease run script as root." exit 1 fi 

Actually the uid 0 is the special user account with full privilege. «root» is simply the most common label/name mapped to that UID. It doesn’t have to be ‘root’ and an attacker may try to exploit this.

What is your objective here, to inform the user that they should run the script as root or as some kind of security precaution?

If you just want to inform the user than any of the uid suggestions are fine, but they’re as useful as tyres on a horse as a security precaution — there’s nothing to stop a user from copying the script, taking out the if statement, and running it anyway.

If this is a security issue then the script should be set to 700, owned by root:root, so that it is not readable or executable by any other user.

Источник

Оцените статью
Adblock
detector