I am implementing char driver ( Linux) and there are certain IOCTL commands are there in my driver which needs to be only executed by ADMIN.
My question is how can I check user permission under my ioctl command implementation and restrict unprivileged user from accessing IOCTL.
You can use
bool capable(int cap)
function, which returns true if user has capability requested. Possible values of cap are listed in kernel sources atinclude/uapi/linux/capability.h
(macros started with CAP_).As you can see, there are many admin-like capabilities. Choose one which seems fit better for you task. Or just take CAP_SYS_ADMIN.
Restrict by Write Permission
You can restrict certain ioctl commands if the device is opened read-only. To implement this, given the first parameter to the
ioctl
function,struct file *file
, test iffile->f_mode
hasFMODE_WRITE
bit set.Set the permissions so that only a particular user or group has write permissions for the device. This could be useful in a scenario where certain users should be able to control a device, by opening it in read-write mode, while other users can only read the device and get status by opening it in read-only mode.
A user might also choose to
open()
the device with modeO_RDONLY
, if the user only wants to read the device while ensuring he doesn't modify it.Restrict by Capabilities
You could restrict certain ioctl commands to only be permitted if the user has a specified capability (
CAP_SYS_ADMIN
is likely suitable).