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?
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!
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.