0.网址
博客地址
该博客基于linux 5.10.17,含有三个lsm demo,难度为递进顺序,作者展示了其如何逐步完成一个有实际使用价值的简单的lsm demo。
1.Whitelist demo
hook函数
由于是第一个demo,所以只用到了一个hook函数bprm_check_security,该函数在exec()时被调用,返回值为0时允许执行二进制文件,返回值为负时会拒绝此次调用。
原理
不加载未知的二进制文件,未知这里被定义为无扩展属性security.whitelisted,即只允许存在扩展属性security.whitelisted的二进制文件被exec() 。
代码
为了防止该模块对os的正常运行(实际使用中会导致无法进入图形界面,将返回值全部设0,仅通过输出观察调用是否合法)
int whitlist_bprm_check_security(struct linux_binprm *bprm)
{
struct task_struct *task=current;
kuid_t uid=task->cred->uid;
//The target we are checking
struct dentry *dentry=bprm->file->f_path.dentry;
struct inode *inode=d_backing_inode(dentry);
//size of the attribute,if any.
int size=0;
//Root can access everything.
if(uid.val==0)
return 0;
//If there is an attribute,allow the access.
//Otherwise, deny it.
size=__vfs_getxattr(dentry,inode,"security.whitelisted",NULL,0);
if(size>0){
printk("whitelist LSM check of %s allowing access for UID %d [ERRO:%d]\n",bprm->filename,uid.val,size);
return 0;
}
printk( "whitelist LSM check of %s denying access for UID %d [ERRO:%d]\n",bprm->filename,uid.val,size);
//return -EPERM;
return 0;
}
运行结果
测试时要配合setfattr等使用,将grep和tail setfattr -n security.whitelisted -v 1 XXX(grep / tail)后,运行以下指令,发现调用三次whitelist LSM,只有一次被阻止(无扩展属性的dmesg) 。