Mastering Linux Security and Hardening
上QQ阅读APP看书,第一时间看更新

Preventing abuse via user's shell scripts

So, what if a user has written a shell script that requires sudo privileges? To answer that, let's have Frank create the frank_script.sh shell script that looks like this:

#!/bin/bash

echo "This script belongs to Frank the Cat."

Okay, he wouldn't need sudo privileges for that, but let's pretend that he does. After he sets the executable permission and runs it with sudo, the output will look like this:

 frank@packtpub1:~$ sudo ./frank_script.sh
[sudo] password for frank:
Sorry, user frank is not allowed to execute './frank_script.sh' as root on packtpub1.tds.
frank@packtpub1:~$

So, naturally frustrated, Frank requested that I create a sudo rule so that he can run the script. So, I open visudo and add this rule for Frank:

frank ALL=(ALL) /home/frank/frank_script.sh

Now when Frank runs the script with sudo, it works:

 frank@packtpub1:~$ sudo ./frank_script.sh
[sudo] password for frank:
This script belongs to Frank the Cat.
frank@packtpub1:~$

But since this file is in Frank's own home directory and he is its owner, he can edit it any way he wants. So, being the sneaky type, he adds the sudo -i line to the end of the script so that it now looks like this:

#!/bin/bash

echo "This script belongs to Frank the Cat."
sudo -i

Be prepared for a shock as you watch what happens next:

 frank@packtpub1:~$ sudo ./frank_script.sh
This script belongs to Frank the Cat.
root@packtpub1:~#

As you can see, Frank is now logged in as the root user.

What sudo -i does is to log a person in to the root user's shell, the same way that sudo su - does. If Frank were to do sudo -i from his own command prompt, it would fail because Frank doesn't have the privilege to do that. But he does have the sudo privilege to run his own shell script. By leaving the shell script in his own home directory, Frank can put root-level commands into it. By running the script with sudo, the root-level commands in the script will execute with root-level privileges.

To remedy this, I'll use my awesome powers of sudo to move Frank's script to the /usr/local/sbin directory and change the ownership to the root user so that Frank won't be able to edit it. And of course, before I do that, I'll make sure to delete that sudo -i line from it:

 donnie@packtpub1:~$ sudo -i
root@packtpub1:~# cd /home/frank
root@packtpub1:/home/frank# mv frank_script.sh /usr/local/sbin
root@packtpub1:/home/frank# chown root: /usr/local/sbin/frank_script.sh
root@packtpub1:/home/frank# exit
logout
donnie@packtpub1:~$

Finally, I'll open visudo and change his rule to reflect the new location of the script. The new rule looks like this:

frank ALL=(ALL) /usr/local/sbin/frank_script.sh

Frank can still run the script, but he can't edit it:

 frank@packtpub1:~$ sudo frank_script.sh
This script belongs to Frank the Cat.
frank@packtpub1:~$