LSM在内核中很多地方已经插入了hook函数,并且在security.c函数中声明了security_ops结构,要实现你自己的安全模块,只需要定义你自己的struct security_operations,并且用register_security注册即可,下面举个简单例子:
test.c代码如下:
/*
* Test Linux Security Module
*
* Author: penghuan <penghuanmail@126.com>
*
* Copyright (C) 2010 UbuntuKylin, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation.
*
*/
#include <linux/security.h>
#include <linux/sysctl.h>
#include <linux/ptrace.h>
#include <linux/prctl.h>
#include <linux/ratelimit.h>
#include <linux/workqueue.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/dcache.h>
#include <linux/path.h>
int test_file_permission(struct file *file, int mask)
{
char *name = file->f_path.dentry->d_name.name;
if(!strcmp(name, "test.txt"))
{
file->f_flags |= O_RDONLY;
printk("you can have your control code here!\n");
}
return 0;
}
static struct security_operations test_security_ops = {
.name = "test",
.file_permission = test_file_permission,
};
static __init int test_init(void)
{
printk("enter test init!\n");
printk(KERN_INFO "Test: becoming......\n")
if (register_security(&test_security_ops))
panic("Test: kernel registration failed.\n");
return 0;
}
security_initcall(test_init);
将该文件以模块的形式放到security/下编译进内核,启用新的内核后,当你操作文件test.txt时,通过dmesg命令就能再终端看到”you can have your control code here!“输出
所以一般的做法是:定义你自己的struct security_operations,实现你自己的hook函数,具体有哪些hook函数可以查询include/linux/security.h文件,然后调用register_security来用你的test_security_ops初始化全局的security_ops指针