User Permission check on ioctl command

2019-06-20 23:02发布

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.

2条回答
forever°为你锁心
2楼-- · 2019-06-20 23:38

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 at include/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.

查看更多
趁早两清
3楼-- · 2019-06-20 23:44

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 if file->f_mode has FMODE_WRITE bit set.

if (!(file->f_mode & FMODE_WRITE))
        return -EACCES;

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 mode O_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).

if (!capable(CAP_SYS_ADMIN))
        return -EACCES;
查看更多
登录 后发表回答