Reputation: 4173
I have a user level application that needs to enable/disable a device by writing to it's device file(which requires root privileges).
Here's the current implementation of my interface:
bool DeviceInterface::EnableDevice( bool isEnabled )
{
bool isSuccessful = false;
//enable device
if(isEnabled)
{
isSuccessful = (system("enableDevice.sh 1") == 0)? true : false;
}
//disable device
else
{
isSuccessful = (system("enableDevice.sh 0") == 0)? true : false;
}
return isSuccessful ;
}
My script "enableDevice.sh" simply looks like this, and runs just fine when ran as root:
echo $1 > /sys/devices/device_file
This fails as it requires root privileges to be able to write to a device file. I'm totally new to "pipes", "fork" and "exec". Can anybody help me how I could pass "0" or "1" to a script to enable and disable the device?
Upvotes: 0
Views: 177
Reputation: 143
In order for 'enableDevice.sh' to do this, it needs to be running as root. You could mark it suid (chmod u+S enableDevice.sh) and chown it to root. Note that you'll need to be root to do the chown (on any reasonable unix system).
Of course you could always open up write permissions for your (well, the programs') group or for everyone, i.e. chmod g+w,o+w /sys/devices/device_file
I REALLY wouldn't recommend you do this. if I called that script with '\"bunch of nothing at all > /dev/sda' it'd overwrite the (likely) root of your system drive.
A better idea would be to have the script check what "$1" is, and then echo 0 or 1 to the device, or do nothing if it's neither. i.e. don't trust user data, especially in suid scripts!
case "$1" in
enable) VALUE=1 ;;
disable) VALUE=0 ;;
*) exit ;;
esac
echo $VALUE > /sys/devices/device_file
Better still, have a deamon which you've run as root hanging around watching a named pipe which does (effectively) the above, depending on what it gets in the pipe.
Upvotes: 1
Reputation: 335
Run chmod on enableDevice.sh as follows ( being root) :-
#chmod 4755 enableDevice.sh
It's called setting the setuid bit. With this non-root users will be able to run this script and it will run with the owner's ( who in our case : root) privileges. And thus your program will work. Do read about setuid. EDIT : Also, before chmod, make the owner and group of enableDevice.sh as root. Then only it will work.
Upvotes: 1