Restructure the native module

Consolidate all code into the src folder
This commit is contained in:
topjohnwu
2022-07-23 13:51:56 -07:00
parent c7c9fb9576
commit b9e89a1a2d
198 changed files with 52 additions and 45 deletions
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "magiskpolicy"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["staticlib", "rlib"]
path = "lib.rs"
[dependencies]
base = { path = "../base" }
+105
View File
@@ -0,0 +1,105 @@
#include <base.hpp>
#include "policy.hpp"
#if 0
// Print out all rules going through public API for debugging
template <typename ...Args>
static void dprint(const char *action, Args ...args) {
std::string s(action);
for (int i = 0; i < sizeof...(args); ++i) s += " %s";
s += "\n";
LOGD(s.data(), (args ? args : "*")...);
}
#else
#define dprint(...)
#endif
bool sepolicy::allow(const char *s, const char *t, const char *c, const char *p) {
dprint(__FUNCTION__, s, t, c, p);
return impl->add_rule(s, t, c, p, AVTAB_ALLOWED, false);
}
bool sepolicy::deny(const char *s, const char *t, const char *c, const char *p) {
dprint(__FUNCTION__, s, t, c, p);
return impl->add_rule(s, t, c, p, AVTAB_ALLOWED, true);
}
bool sepolicy::auditallow(const char *s, const char *t, const char *c, const char *p) {
dprint(__FUNCTION__, s, t, c, p);
return impl->add_rule(s, t, c, p, AVTAB_AUDITALLOW, false);
}
bool sepolicy::dontaudit(const char *s, const char *t, const char *c, const char *p) {
dprint(__FUNCTION__, s, t, c, p);
return impl->add_rule(s, t, c, p, AVTAB_AUDITDENY, true);
}
bool sepolicy::allowxperm(const char *s, const char *t, const char *c, const char *range) {
dprint(__FUNCTION__, s, t, c, "ioctl", range);
return impl->add_xperm_rule(s, t, c, range, AVTAB_XPERMS_ALLOWED, false);
}
bool sepolicy::auditallowxperm(const char *s, const char *t, const char *c, const char *range) {
dprint(__FUNCTION__, s, t, c, "ioctl", range);
return impl->add_xperm_rule(s, t, c, range, AVTAB_XPERMS_AUDITALLOW, false);
}
bool sepolicy::dontauditxperm(const char *s, const char *t, const char *c, const char *range) {
dprint(__FUNCTION__, s, t, c, "ioctl", range);
return impl->add_xperm_rule(s, t, c, range, AVTAB_XPERMS_DONTAUDIT, false);
}
bool sepolicy::type_change(const char *s, const char *t, const char *c, const char *d) {
dprint(__FUNCTION__, s, t, c, d);
return impl->add_type_rule(s, t, c, d, AVTAB_CHANGE);
}
bool sepolicy::type_member(const char *s, const char *t, const char *c, const char *d) {
dprint(__FUNCTION__, s, t, c, d);
return impl->add_type_rule(s, t, c, d, AVTAB_MEMBER);
}
bool sepolicy::type_transition(const char *s, const char *t, const char *c, const char *d, const char *o) {
if (o) {
dprint(__FUNCTION__, s, t, c, d, o);
return impl->add_filename_trans(s, t, c, d, o);
} else {
dprint(__FUNCTION__, s, t, c, d);
return impl->add_type_rule(s, t, c, d, AVTAB_TRANSITION);
}
}
bool sepolicy::permissive(const char *s) {
dprint(__FUNCTION__, s);
return impl->set_type_state(s, true);
}
bool sepolicy::enforce(const char *s) {
dprint(__FUNCTION__, s);
return impl->set_type_state(s, false);
}
bool sepolicy::type(const char *name, const char *attr) {
dprint(__FUNCTION__, name, attr);
return impl->add_type(name, TYPE_TYPE) && impl->add_typeattribute(name, attr);
}
bool sepolicy::attribute(const char *name) {
dprint(__FUNCTION__, name);
return impl->add_type(name, TYPE_ATTRIB);
}
bool sepolicy::typeattribute(const char *type, const char *attr) {
dprint(__FUNCTION__, type, attr);
return impl->add_typeattribute(type, attr);
}
bool sepolicy::genfscon(const char *fs_name, const char *path, const char *ctx) {
dprint(__FUNCTION__, fs_name, path, ctx);
return impl->add_genfscon(fs_name, path, ctx);
}
bool sepolicy::exists(const char *type) {
return hashtab_search(impl->db->p_types.table, type) != nullptr;
}
+60
View File
@@ -0,0 +1,60 @@
#pragma once
#include <stdlib.h>
#include <selinux.hpp>
#include <string>
#define ALL nullptr
struct sepolicy {
using c_str = const char *;
// Public static factory functions
static sepolicy *from_data(char *data, size_t len);
static sepolicy *from_file(c_str file);
static sepolicy *from_split();
static sepolicy *compile_split();
// External APIs
bool to_file(c_str file);
void parse_statement(c_str stmt);
void load_rules(const std::string &rules);
void load_rule_file(c_str file);
// Operation on types
bool type(c_str name, c_str attr);
bool attribute(c_str name);
bool permissive(c_str type);
bool enforce(c_str type);
bool typeattribute(c_str type, c_str attr);
bool exists(c_str type);
// Access vector rules
bool allow(c_str src, c_str tgt, c_str cls, c_str perm);
bool deny(c_str src, c_str tgt, c_str cls, c_str perm);
bool auditallow(c_str src, c_str tgt, c_str cls, c_str perm);
bool dontaudit(c_str src, c_str tgt, c_str cls, c_str perm);
// Extended permissions access vector rules
bool allowxperm(c_str src, c_str tgt, c_str cls, c_str range);
bool auditallowxperm(c_str src, c_str tgt, c_str cls, c_str range);
bool dontauditxperm(c_str src, c_str tgt, c_str cls, c_str range);
// Type rules
bool type_transition(c_str src, c_str tgt, c_str cls, c_str def, c_str obj = nullptr);
bool type_change(c_str src, c_str tgt, c_str cls, c_str def);
bool type_member(c_str src, c_str tgt, c_str cls, c_str def);
// File system labeling
bool genfscon(c_str fs_name, c_str path, c_str ctx);
// Magisk
void magisk_rules();
// Deprecate
bool create(c_str name) { return type(name, "domain"); }
protected:
// Prevent anyone from accidentally creating an instance
sepolicy() = default;
};
+1
View File
@@ -0,0 +1 @@
pub use base;
+121
View File
@@ -0,0 +1,121 @@
#include <base.hpp>
#include <vector>
#include "policy.hpp"
using namespace std;
[[noreturn]] static void usage(char *arg0) {
fprintf(stderr,
R"EOF(MagiskPolicy - SELinux Policy Patch Tool
Usage: %s [--options...] [policy statements...]
Options:
--help show help message for policy statements
--load FILE load monolithic sepolicy from FILE
--load-split load from precompiled sepolicy or compile
split cil policies
--compile-split compile split cil policies
--save FILE dump monolithic sepolicy to FILE
--live immediately load sepolicy into the kernel
--magisk apply built-in Magisk sepolicy rules
--apply FILE apply rules from FILE, read and parsed
line by line as policy statements
(multiple --apply are allowed)
If neither --load, --load-split, nor --compile-split is specified,
it will load from current live policies (/sys/fs/selinux/policy)
)EOF", arg0);
exit(1);
}
int main(int argc, char *argv[]) {
cmdline_logging();
const char *out_file = nullptr;
vector<string_view> rule_files;
sepolicy *sepol = nullptr;
bool magisk = false;
bool live = false;
if (argc < 2) usage(argv[0]);
int i = 1;
for (; i < argc; ++i) {
// Parse options
if (argv[i][0] == '-' && argv[i][1] == '-') {
auto option = argv[i] + 2;
if (option == "live"sv)
live = true;
else if (option == "magisk"sv)
magisk = true;
else if (option == "load"sv) {
if (argv[i + 1] == nullptr)
usage(argv[0]);
sepol = sepolicy::from_file(argv[i + 1]);
if (!sepol) {
fprintf(stderr, "Cannot load policy from %s\n", argv[i + 1]);
return 1;
}
++i;
} else if (option == "load-split"sv) {
sepol = sepolicy::from_split();
if (!sepol) {
fprintf(stderr, "Cannot load split cil\n");
return 1;
}
} else if (option == "compile-split"sv) {
sepol = sepolicy::compile_split();
if (!sepol) {
fprintf(stderr, "Cannot compile split cil\n");
return 1;
}
} else if (option == "save"sv) {
if (argv[i + 1] == nullptr)
usage(argv[0]);
out_file = argv[i + 1];
++i;
} else if (option == "apply"sv) {
if (argv[i + 1] == nullptr)
usage(argv[0]);
rule_files.emplace_back(argv[i + 1]);
++i;
} else if (option == "help"sv) {
statement_help();
} else {
usage(argv[0]);
}
} else {
break;
}
}
// Use current policy if nothing is loaded
if (sepol == nullptr && !(sepol = sepolicy::from_file(SELINUX_POLICY))) {
fprintf(stderr, "Cannot load policy from " SELINUX_POLICY "\n");
return 1;
}
if (magisk)
sepol->magisk_rules();
if (!rule_files.empty())
for (const auto &rule_file : rule_files)
sepol->load_rule_file(rule_file.data());
for (; i < argc; ++i)
sepol->parse_statement(argv[i]);
if (live && !sepol->to_file(SELINUX_LOAD)) {
fprintf(stderr, "Cannot apply policy\n");
return 1;
}
if (out_file && !sepol->to_file(out_file)) {
fprintf(stderr, "Cannot dump policy to %s\n", out_file);
return 1;
}
delete sepol;
return 0;
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
// Internal APIs, do not use directly
#include <sepol/policydb/policydb.h>
#include <sepolicy.hpp>
struct sepol_impl : public sepolicy {
avtab_ptr_t get_avtab_node(avtab_key_t *key, avtab_extended_perms_t *xperms);
bool add_rule(const char *s, const char *t, const char *c, const char *p, int effect, bool invert);
void add_rule(type_datum_t *src, type_datum_t *tgt, class_datum_t *cls, perm_datum_t *perm, int effect, bool invert);
void add_xperm_rule(type_datum_t *src, type_datum_t *tgt,
class_datum_t *cls, uint16_t low, uint16_t high, int effect, bool invert);
bool add_xperm_rule(const char *s, const char *t, const char *c, const char *range, int effect, bool invert);
bool add_type_rule(const char *s, const char *t, const char *c, const char *d, int effect);
bool add_filename_trans(const char *s, const char *t, const char *c, const char *d, const char *o);
bool add_genfscon(const char *fs_name, const char *path, const char *context);
bool add_type(const char *type_name, uint32_t flavor);
bool set_type_state(const char *type_name, bool permissive);
void add_typeattribute(type_datum_t *type, type_datum_t *attr);
bool add_typeattribute(const char *type, const char *attr);
void strip_dontaudit();
sepol_impl(policydb *db) : db(db) {}
~sepol_impl();
policydb *db;
};
#define impl reinterpret_cast<sepol_impl *>(this)
void statement_help();
+262
View File
@@ -0,0 +1,262 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cil/cil.h>
#include <base.hpp>
#include <stream.hpp>
#include "policy.hpp"
#define SHALEN 64
static bool cmp_sha256(const char *a, const char *b) {
char id_a[SHALEN] = {0};
char id_b[SHALEN] = {0};
if (int fd = xopen(a, O_RDONLY | O_CLOEXEC); fd >= 0) {
xread(fd, id_a, SHALEN);
close(fd);
} else {
return false;
}
if (int fd = xopen(b, O_RDONLY | O_CLOEXEC); fd >= 0) {
xread(fd, id_b, SHALEN);
close(fd);
} else {
return false;
}
LOGD("%s=[%.*s]\n", a, SHALEN, id_a);
LOGD("%s=[%.*s]\n", b, SHALEN, id_b);
return memcmp(id_a, id_b, SHALEN) == 0;
}
static bool check_precompiled(const char *precompiled) {
bool ok = false;
const char *actual_sha;
char compiled_sha[128];
actual_sha = PLAT_POLICY_DIR "plat_and_mapping_sepolicy.cil.sha256";
if (access(actual_sha, R_OK) == 0) {
ok = true;
sprintf(compiled_sha, "%s.plat_and_mapping.sha256", precompiled);
if (!cmp_sha256(actual_sha, compiled_sha))
return false;
}
actual_sha = PLAT_POLICY_DIR "plat_sepolicy_and_mapping.sha256";
if (access(actual_sha, R_OK) == 0) {
ok = true;
sprintf(compiled_sha, "%s.plat_sepolicy_and_mapping.sha256", precompiled);
if (!cmp_sha256(actual_sha, compiled_sha))
return false;
}
actual_sha = PROD_POLICY_DIR "product_sepolicy_and_mapping.sha256";
if (access(actual_sha, R_OK) == 0) {
ok = true;
sprintf(compiled_sha, "%s.product_sepolicy_and_mapping.sha256", precompiled);
if (!cmp_sha256(actual_sha, compiled_sha) != 0)
return false;
}
actual_sha = SYSEXT_POLICY_DIR "system_ext_sepolicy_and_mapping.sha256";
if (access(actual_sha, R_OK) == 0) {
ok = true;
sprintf(compiled_sha, "%s.system_ext_sepolicy_and_mapping.sha256", precompiled);
if (!cmp_sha256(actual_sha, compiled_sha) != 0)
return false;
}
return ok;
}
static void load_cil(struct cil_db *db, const char *file) {
auto d = mmap_data(file);
cil_add_file(db, (char *) file, (char *) d.buf, d.sz);
LOGD("cil_add [%s]\n", file);
}
sepolicy *sepolicy::from_data(char *data, size_t len) {
LOGD("Load policy from data\n");
policy_file_t pf;
policy_file_init(&pf);
pf.data = data;
pf.len = len;
pf.type = PF_USE_MEMORY;
auto db = static_cast<policydb_t *>(xmalloc(sizeof(policydb_t)));
if (policydb_init(db) || policydb_read(db, &pf, 0)) {
LOGE("Fail to load policy from data\n");
free(db);
return nullptr;
}
auto sepol = new sepol_impl(db);
return sepol;
}
sepolicy *sepolicy::from_file(const char *file) {
LOGD("Load policy from: %s\n", file);
policy_file_t pf;
policy_file_init(&pf);
auto fp = xopen_file(file, "re");
pf.fp = fp.get();
pf.type = PF_USE_STDIO;
auto db = static_cast<policydb_t *>(xmalloc(sizeof(policydb_t)));
if (policydb_init(db) || policydb_read(db, &pf, 0)) {
LOGE("Fail to load policy from %s\n", file);
free(db);
return nullptr;
}
auto sepol = new sepol_impl(db);
return sepol;
}
sepolicy *sepolicy::compile_split() {
char path[128], plat_ver[10];
cil_db_t *db = nullptr;
sepol_policydb_t *pdb = nullptr;
FILE *f;
int policy_ver;
const char *cil_file;
#if MAGISK_DEBUG
cil_set_log_level(CIL_INFO);
#endif
cil_set_log_handler(+[](int lvl, const char *msg) {
if (lvl == CIL_ERR) {
LOGE("cil: %s", msg);
} else if (lvl == CIL_WARN) {
LOGW("cil: %s", msg);
} else if (lvl == CIL_INFO) {
LOGI("cil: %s", msg);
} else {
LOGD("cil: %s", msg);
}
});
cil_db_init(&db);
run_finally fin([db_ptr = &db]{ cil_db_destroy(db_ptr); });
cil_set_mls(db, 1);
cil_set_multiple_decls(db, 1);
cil_set_disable_neverallow(db, 1);
cil_set_target_platform(db, SEPOL_TARGET_SELINUX);
cil_set_attrs_expand_generated(db, 1);
f = xfopen(SELINUX_VERSION, "re");
fscanf(f, "%d", &policy_ver);
fclose(f);
cil_set_policy_version(db, policy_ver);
// Get mapping version
f = xfopen(VEND_POLICY_DIR "plat_sepolicy_vers.txt", "re");
fscanf(f, "%s", plat_ver);
fclose(f);
// plat
load_cil(db, SPLIT_PLAT_CIL);
sprintf(path, PLAT_POLICY_DIR "mapping/%s.cil", plat_ver);
load_cil(db, path);
sprintf(path, PLAT_POLICY_DIR "mapping/%s.compat.cil", plat_ver);
if (access(path, R_OK) == 0)
load_cil(db, path);
// system_ext
sprintf(path, SYSEXT_POLICY_DIR "mapping/%s.cil", plat_ver);
if (access(path, R_OK) == 0)
load_cil(db, path);
sprintf(path, SYSEXT_POLICY_DIR "mapping/%s.compat.cil", plat_ver);
if (access(path, R_OK) == 0)
load_cil(db, path);
cil_file = SYSEXT_POLICY_DIR "system_ext_sepolicy.cil";
if (access(cil_file, R_OK) == 0)
load_cil(db, cil_file);
// product
sprintf(path, PROD_POLICY_DIR "mapping/%s.cil", plat_ver);
if (access(path, R_OK) == 0)
load_cil(db, path);
cil_file = PROD_POLICY_DIR "product_sepolicy.cil";
if (access(cil_file, R_OK) == 0)
load_cil(db, cil_file);
// vendor
cil_file = VEND_POLICY_DIR "nonplat_sepolicy.cil";
if (access(cil_file, R_OK) == 0)
load_cil(db, cil_file);
cil_file = VEND_POLICY_DIR "plat_pub_versioned.cil";
if (access(cil_file, R_OK) == 0)
load_cil(db, cil_file);
cil_file = VEND_POLICY_DIR "vendor_sepolicy.cil";
if (access(cil_file, R_OK) == 0)
load_cil(db, cil_file);
// odm
cil_file = ODM_POLICY_DIR "odm_sepolicy.cil";
if (access(cil_file, R_OK) == 0)
load_cil(db, cil_file);
if (cil_compile(db))
return nullptr;
if (cil_build_policydb(db, &pdb))
return nullptr;
auto sepol = new sepol_impl(&pdb->p);
return sepol;
}
sepolicy *sepolicy::from_split() {
const char *odm_pre = ODM_POLICY_DIR "precompiled_sepolicy";
const char *vend_pre = VEND_POLICY_DIR "precompiled_sepolicy";
if (access(odm_pre, R_OK) == 0 && check_precompiled(odm_pre))
return sepolicy::from_file(odm_pre);
else if (access(vend_pre, R_OK) == 0 && check_precompiled(vend_pre))
return sepolicy::from_file(vend_pre);
else
return sepolicy::compile_split();
}
sepol_impl::~sepol_impl() {
policydb_destroy(db);
free(db);
}
bool sepolicy::to_file(const char *file) {
uint8_t *data;
size_t len;
// No partial writes are allowed to /sys/fs/selinux/load, thus the reason why we
// first dump everything into memory, then directly call write system call
auto fp = make_stream_fp<byte_stream>(data, len);
run_finally fin([=]{ free(data); });
policy_file_t pf;
policy_file_init(&pf);
pf.type = PF_USE_STDIO;
pf.fp = fp.get();
if (policydb_write(impl->db, &pf)) {
LOGE("Fail to create policy image\n");
return false;
}
int fd = xopen(file, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0)
return false;
xwrite(fd, data, len);
close(fd);
return true;
}
+199
View File
@@ -0,0 +1,199 @@
#include <base.hpp>
#include "policy.hpp"
using namespace std;
void sepolicy::magisk_rules() {
// Temp suppress warnings
set_log_level_state(LogLevel::Warn, false);
// This indicates API 26+
bool new_rules = exists("untrusted_app_25");
// Prevent anything to change sepolicy except ourselves
deny(ALL, "kernel", "security", "load_policy");
type(SEPOL_PROC_DOMAIN, "domain");
permissive(SEPOL_PROC_DOMAIN); /* Just in case something is missing */
typeattribute(SEPOL_PROC_DOMAIN, "mlstrustedsubject");
typeattribute(SEPOL_PROC_DOMAIN, "netdomain");
typeattribute(SEPOL_PROC_DOMAIN, "bluetoothdomain");
type(SEPOL_FILE_TYPE, "file_type");
typeattribute(SEPOL_FILE_TYPE, "mlstrustedobject");
// Make our root domain unconstrained
allow(SEPOL_PROC_DOMAIN, ALL, ALL, ALL);
// Allow us to do any ioctl
if (impl->db->policyvers >= POLICYDB_VERSION_XPERMS_IOCTL) {
allowxperm(SEPOL_PROC_DOMAIN, ALL, "blk_file", ALL);
allowxperm(SEPOL_PROC_DOMAIN, ALL, "fifo_file", ALL);
allowxperm(SEPOL_PROC_DOMAIN, ALL, "chr_file", ALL);
}
// Create unconstrained file type
allow(ALL, SEPOL_FILE_TYPE, "file", ALL);
allow(ALL, SEPOL_FILE_TYPE, "dir", ALL);
allow(ALL, SEPOL_FILE_TYPE, "fifo_file", ALL);
allow(ALL, SEPOL_FILE_TYPE, "chr_file", ALL);
allow(ALL, SEPOL_FILE_TYPE, "lnk_file", ALL);
allow(ALL, SEPOL_FILE_TYPE, "sock_file", ALL);
if (new_rules) {
// Make client type literally untrusted_app
type(SEPOL_CLIENT_DOMAIN, "domain");
typeattribute(SEPOL_CLIENT_DOMAIN, "coredomain");
typeattribute(SEPOL_CLIENT_DOMAIN, "appdomain");
typeattribute(SEPOL_CLIENT_DOMAIN, "untrusted_app_all");
typeattribute(SEPOL_CLIENT_DOMAIN, "netdomain");
typeattribute(SEPOL_CLIENT_DOMAIN, "bluetoothdomain");
type(SEPOL_EXEC_TYPE, "file_type");
typeattribute(SEPOL_EXEC_TYPE, "exec_type");
// Basic su client needs
allow(SEPOL_CLIENT_DOMAIN, SEPOL_EXEC_TYPE, "file", ALL);
allow(SEPOL_CLIENT_DOMAIN, SEPOL_CLIENT_DOMAIN, ALL, ALL);
const char *pts[]{"devpts", "untrusted_app_devpts", "untrusted_app_25_devpts"};
for (auto type : pts) {
allow(SEPOL_CLIENT_DOMAIN, type, "chr_file", "getattr");
allow(SEPOL_CLIENT_DOMAIN, type, "chr_file", "read");
allow(SEPOL_CLIENT_DOMAIN, type, "chr_file", "write");
allow(SEPOL_CLIENT_DOMAIN, type, "chr_file", "ioctl");
}
// Allow these processes to access MagiskSU
vector<const char *> clients{ "init", "shell", "update_engine", "appdomain" };
for (auto type : clients) {
if (!exists(type))
continue;
// exec magisk
allow(type, SEPOL_EXEC_TYPE, "file", "read");
allow(type, SEPOL_EXEC_TYPE, "file", "open");
allow(type, SEPOL_EXEC_TYPE, "file", "getattr");
allow(type, SEPOL_EXEC_TYPE, "file", "execute");
allow(SEPOL_CLIENT_DOMAIN, type, "process", "sigchld");
// Auto transit to client domain
allow(type, SEPOL_CLIENT_DOMAIN, "process", "transition");
dontaudit(type, SEPOL_CLIENT_DOMAIN, "process", "siginh");
dontaudit(type, SEPOL_CLIENT_DOMAIN, "process", "rlimitinh");
dontaudit(type, SEPOL_CLIENT_DOMAIN, "process", "noatsecure");
// Kill client process
allow(type, SEPOL_CLIENT_DOMAIN, "process", "signal");
}
// type transition require actual types, not attributes
const char *app_types[]{
"system_app", "priv_app", "platform_app", "untrusted_app", "untrusted_app_25",
"untrusted_app_27", "untrusted_app_29", "untrusted_app_30"};
clients.pop_back();
clients.insert(clients.end(), app_types, app_types + std::size(app_types));
for (auto type : clients) {
// Auto transit to client domain
type_transition(type, SEPOL_EXEC_TYPE, "process", SEPOL_CLIENT_DOMAIN);
}
// Allow system_server to manage magisk_client
allow("system_server", SEPOL_CLIENT_DOMAIN, "process", "getpgid");
allow("system_server", SEPOL_CLIENT_DOMAIN, "process", "sigkill");
// Don't allow pesky processes to monitor audit deny logs when poking magisk daemon socket
dontaudit(ALL, SEPOL_PROC_DOMAIN, "unix_stream_socket", ALL);
// Only allow client processes and zygote to connect to magisk daemon socket
allow(SEPOL_CLIENT_DOMAIN, SEPOL_PROC_DOMAIN, "unix_stream_socket", ALL);
allow("zygote", SEPOL_PROC_DOMAIN, "unix_stream_socket", ALL);
} else {
// Fallback to poking holes in sandbox as Android 4.3 to 7.1 set PR_SET_NO_NEW_PRIVS
// Allow these processes to access MagiskSU
const char *clients[] { "init", "shell", "appdomain", "zygote" };
for (auto type : clients) {
if (!exists(type))
continue;
allow(type, SEPOL_PROC_DOMAIN, "unix_stream_socket", "connectto");
allow(type, SEPOL_PROC_DOMAIN, "unix_stream_socket", "getopt");
}
}
// Let everyone access tmpfs files (for SAR sbin overlay)
allow(ALL, "tmpfs", "file", ALL);
// Allow magiskinit daemon to handle mock selinuxfs
allow("kernel", "tmpfs", "fifo_file", "write");
// For relabelling files
allow("rootfs", "labeledfs", "filesystem", "associate");
allow(SEPOL_FILE_TYPE, "pipefs", "filesystem", "associate");
allow(SEPOL_FILE_TYPE, "devpts", "filesystem", "associate");
// Let init transit to SEPOL_PROC_DOMAIN
allow("kernel", "kernel", "process", "setcurrent");
allow("kernel", SEPOL_PROC_DOMAIN, "process", "dyntransition");
// Let init run stuffs
allow("kernel", SEPOL_PROC_DOMAIN, "fd", "use");
allow("init", SEPOL_PROC_DOMAIN, "process", ALL);
allow("init", "tmpfs", "file", "getattr");
allow("init", "tmpfs", "file", "execute");
// suRights
allow("servicemanager", SEPOL_PROC_DOMAIN, "dir", "search");
allow("servicemanager", SEPOL_PROC_DOMAIN, "dir", "read");
allow("servicemanager", SEPOL_PROC_DOMAIN, "file", "open");
allow("servicemanager", SEPOL_PROC_DOMAIN, "file", "read");
allow("servicemanager", SEPOL_PROC_DOMAIN, "process", "getattr");
allow(ALL, SEPOL_PROC_DOMAIN, "process", "sigchld");
// allowLog
allow("logd", SEPOL_PROC_DOMAIN, "dir", "search");
allow("logd", SEPOL_PROC_DOMAIN, "file", "read");
allow("logd", SEPOL_PROC_DOMAIN, "file", "open");
allow("logd", SEPOL_PROC_DOMAIN, "file", "getattr");
// dumpsys
allow(ALL, SEPOL_PROC_DOMAIN, "fd", "use");
allow(ALL, SEPOL_PROC_DOMAIN, "fifo_file", "write");
allow(ALL, SEPOL_PROC_DOMAIN, "fifo_file", "read");
allow(ALL, SEPOL_PROC_DOMAIN, "fifo_file", "open");
allow(ALL, SEPOL_PROC_DOMAIN, "fifo_file", "getattr");
// bootctl
allow("hwservicemanager", SEPOL_PROC_DOMAIN, "dir", "search");
allow("hwservicemanager", SEPOL_PROC_DOMAIN, "file", "read");
allow("hwservicemanager", SEPOL_PROC_DOMAIN, "file", "open");
allow("hwservicemanager", SEPOL_PROC_DOMAIN, "process", "getattr");
// For mounting loop devices, mirrors, tmpfs
allow("kernel", ALL, "file", "read");
allow("kernel", ALL, "file", "write");
// Allow all binder transactions
allow(ALL, SEPOL_PROC_DOMAIN, "binder", ALL);
// For changing file context
allow("rootfs", "tmpfs", "filesystem", "associate");
// Zygisk rules
allow("zygote", "zygote", "capability", "sys_resource"); // prctl PR_SET_MM
allow("zygote", "zygote", "process", "execmem");
allow("zygote", "fs_type", "filesystem", "unmount");
allow("system_server", "system_server", "process", "execmem");
// Shut llkd up
dontaudit("llkd", SEPOL_PROC_DOMAIN, "process", "ptrace");
dontaudit("llkd", SEPOL_CLIENT_DOMAIN, "process", "ptrace");
// Allow update_engine/addon.d-v2 to run permissive on all ROMs
permissive("update_engine");
#if 0
// Remove all dontaudit in debug mode
impl->strip_dontaudit();
#endif
set_log_level_state(LogLevel::Warn, true);
}
+609
View File
@@ -0,0 +1,609 @@
#include <base.hpp>
#include "policy.hpp"
// Invert is adding rules for auditdeny; in other cases, invert is removing rules
#define strip_av(effect, invert) ((effect == AVTAB_AUDITDENY) == !invert)
// libsepol internal APIs
__BEGIN_DECLS
int policydb_index_decls(sepol_handle_t * handle, policydb_t * p);
int avtab_hash(struct avtab_key *keyp, uint32_t mask);
int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p, unsigned char alwaysexpand);
int context_from_string(
sepol_handle_t * handle,
const policydb_t * policydb,
context_struct_t ** cptr,
const char *con_str, size_t con_str_len);
__END_DECLS
template <typename T>
struct auto_cast_wrapper
{
auto_cast_wrapper(T *ptr) : ptr(ptr) {}
template <typename U>
operator U*() const { return static_cast<U*>(ptr); }
private:
T *ptr;
};
template <typename T>
static auto_cast_wrapper<T> auto_cast(T *p) {
return auto_cast_wrapper<T>(p);
}
static auto hashtab_find(hashtab_t h, const_hashtab_key_t key) {
return auto_cast(hashtab_search(h, key));
}
template <class Node, class Func>
static void hash_for_each(Node **node_ptr, int n_slot, const Func &fn) {
for (int i = 0; i < n_slot; ++i) {
for (Node *cur = node_ptr[i]; cur; cur = cur->next) {
fn(cur);
}
}
}
template <class Func>
static void hashtab_for_each(hashtab_t htab, const Func &fn) {
hash_for_each(htab->htable, htab->size, fn);
}
template <class Func>
static void avtab_for_each(avtab_t *avtab, const Func &fn) {
hash_for_each(avtab->htable, avtab->nslot, fn);
}
template <class Func>
static void for_each_attr(hashtab_t htab, const Func &fn) {
hashtab_for_each(htab, [&](hashtab_ptr_t node) {
auto type = static_cast<type_datum_t *>(node->datum);
if (type->flavor == TYPE_ATTRIB)
fn(type);
});
}
static int avtab_remove_node(avtab_t *h, avtab_ptr_t node) {
if (!h || !h->htable)
return SEPOL_ENOMEM;
int hvalue = avtab_hash(&node->key, h->mask);
avtab_ptr_t prev, cur;
for (prev = nullptr, cur = h->htable[hvalue]; cur; prev = cur, cur = cur->next) {
if (cur == node)
break;
}
if (cur == nullptr)
return SEPOL_ENOENT;
// Detach from hash table
if (prev)
prev->next = node->next;
else
h->htable[hvalue] = node->next;
h->nel--;
// Free memory
if (node->key.specified & AVTAB_XPERMS)
free(node->datum.xperms);
free(node);
return 0;
}
static bool is_redundant(avtab_ptr_t node) {
switch (node->key.specified) {
case AVTAB_AUDITDENY:
return node->datum.data == ~0U;
case AVTAB_XPERMS:
return node->datum.xperms == nullptr;
default:
return node->datum.data == 0U;
}
}
avtab_ptr_t sepol_impl::get_avtab_node(avtab_key_t *key, avtab_extended_perms_t *xperms) {
avtab_ptr_t node;
/* AVTAB_XPERMS entries are not necessarily unique */
if (key->specified & AVTAB_XPERMS) {
bool match = false;
node = avtab_search_node(&db->te_avtab, key);
while (node) {
if ((node->datum.xperms->specified == xperms->specified) &&
(node->datum.xperms->driver == xperms->driver)) {
match = true;
break;
}
node = avtab_search_node_next(node, key->specified);
}
if (!match)
node = nullptr;
} else {
node = avtab_search_node(&db->te_avtab, key);
}
if (!node) {
avtab_datum_t avdatum{};
/*
* AUDITDENY, aka DONTAUDIT, are &= assigned, versus |= for
* others. Initialize the data accordingly.
*/
avdatum.data = key->specified == AVTAB_AUDITDENY ? ~0U : 0U;
/* this is used to get the node - insertion is actually unique */
node = avtab_insert_nonunique(&db->te_avtab, key, &avdatum);
}
return node;
}
void sepol_impl::add_rule(type_datum_t *src, type_datum_t *tgt, class_datum_t *cls, perm_datum_t *perm, int effect, bool invert) {
if (src == nullptr) {
if (strip_av(effect, invert)) {
// Stripping av, have to go through all types for correct results
hashtab_for_each(db->p_types.table, [&](hashtab_ptr_t node) {
add_rule(auto_cast(node->datum), tgt, cls, perm, effect, invert);
});
} else {
// If we are not stripping av, go through all attributes instead of types for optimization
for_each_attr(db->p_types.table, [&](type_datum_t *type) {
add_rule(type, tgt, cls, perm, effect, invert);
});
}
} else if (tgt == nullptr) {
if (strip_av(effect, invert)) {
hashtab_for_each(db->p_types.table, [&](hashtab_ptr_t node) {
add_rule(src, auto_cast(node->datum), cls, perm, effect, invert);
});
} else {
for_each_attr(db->p_types.table, [&](type_datum_t *type) {
add_rule(src, type, cls, perm, effect, invert);
});
}
} else if (cls == nullptr) {
hashtab_for_each(db->p_classes.table, [&](hashtab_ptr_t node) {
add_rule(src, tgt, auto_cast(node->datum), perm, effect, invert);
});
} else {
avtab_key_t key;
key.source_type = src->s.value;
key.target_type = tgt->s.value;
key.target_class = cls->s.value;
key.specified = effect;
avtab_ptr_t node = get_avtab_node(&key, nullptr);
if (invert) {
if (perm)
node->datum.data &= ~(1U << (perm->s.value - 1));
else
node->datum.data = 0U;
} else {
if (perm)
node->datum.data |= 1U << (perm->s.value - 1);
else
node->datum.data = ~0U;
}
if (is_redundant(node))
avtab_remove_node(&db->te_avtab, node);
}
}
bool sepol_impl::add_rule(const char *s, const char *t, const char *c, const char *p, int effect, bool invert) {
type_datum_t *src = nullptr, *tgt = nullptr;
class_datum_t *cls = nullptr;
perm_datum_t *perm = nullptr;
if (s) {
src = hashtab_find(db->p_types.table, s);
if (src == nullptr) {
LOGW("source type %s does not exist\n", s);
return false;
}
}
if (t) {
tgt = hashtab_find(db->p_types.table, t);
if (tgt == nullptr) {
LOGW("target type %s does not exist\n", t);
return false;
}
}
if (c) {
cls = hashtab_find(db->p_classes.table, c);
if (cls == nullptr) {
LOGW("class %s does not exist\n", c);
return false;
}
}
if (p) {
if (c == nullptr) {
LOGW("No class is specified, cannot add perm [%s] \n", p);
return false;
}
perm = hashtab_find(cls->permissions.table, p);
if (perm == nullptr && cls->comdatum != nullptr) {
perm = hashtab_find(cls->comdatum->permissions.table, p);
}
if (perm == nullptr) {
LOGW("perm %s does not exist in class %s\n", p, c);
return false;
}
}
add_rule(src, tgt, cls, perm, effect, invert);
return true;
}
#define ioctl_driver(x) (x>>8 & 0xFF)
#define ioctl_func(x) (x & 0xFF)
void sepol_impl::add_xperm_rule(type_datum_t *src, type_datum_t *tgt,
class_datum_t *cls, uint16_t low, uint16_t high, int effect, bool invert) {
if (src == nullptr) {
for_each_attr(db->p_types.table, [&](type_datum_t *type) {
add_xperm_rule(type, tgt, cls, low, high, effect, invert);
});
} else if (tgt == nullptr) {
for_each_attr(db->p_types.table, [&](type_datum_t *type) {
add_xperm_rule(src, type, cls, low, high, effect, invert);
});
} else if (cls == nullptr) {
hashtab_for_each(db->p_classes.table, [&](hashtab_ptr_t node) {
add_xperm_rule(src, tgt, auto_cast(node->datum), low, high, effect, invert);
});
} else {
avtab_key_t key;
key.source_type = src->s.value;
key.target_type = tgt->s.value;
key.target_class = cls->s.value;
key.specified = effect;
avtab_datum_t *datum;
avtab_extended_perms_t xperms;
memset(&xperms, 0, sizeof(xperms));
if (ioctl_driver(low) != ioctl_driver(high)) {
xperms.specified = AVTAB_XPERMS_IOCTLDRIVER;
xperms.driver = 0;
} else {
xperms.specified = AVTAB_XPERMS_IOCTLFUNCTION;
xperms.driver = ioctl_driver(low);
}
if (xperms.specified == AVTAB_XPERMS_IOCTLDRIVER) {
for (int i = ioctl_driver(low); i <= ioctl_driver(high); ++i) {
if (invert)
xperm_clear(i, xperms.perms);
else
xperm_set(i, xperms.perms);
}
} else {
for (int i = ioctl_func(low); i <= ioctl_func(high); ++i) {
if (invert)
xperm_clear(i, xperms.perms);
else
xperm_set(i, xperms.perms);
}
}
datum = &get_avtab_node(&key, &xperms)->datum;
if (datum->xperms == nullptr)
datum->xperms = auto_cast(xmalloc(sizeof(xperms)));
memcpy(datum->xperms, &xperms, sizeof(xperms));
}
}
bool sepol_impl::add_xperm_rule(const char *s, const char *t, const char *c, const char *range, int effect, bool invert) {
type_datum_t *src = nullptr, *tgt = nullptr;
class_datum_t *cls = nullptr;
if (s) {
src = hashtab_find(db->p_types.table, s);
if (src == nullptr) {
LOGW("source type %s does not exist\n", s);
return false;
}
}
if (t) {
tgt = hashtab_find(db->p_types.table, t);
if (tgt == nullptr) {
LOGW("target type %s does not exist\n", t);
return false;
}
}
if (c) {
cls = hashtab_find(db->p_classes.table, c);
if (cls == nullptr) {
LOGW("class %s does not exist\n", c);
return false;
}
}
uint16_t low, high;
if (range) {
if (strchr(range, '-')){
sscanf(range, "%hx-%hx", &low, &high);
} else {
sscanf(range, "%hx", &low);
high = low;
}
} else {
low = 0;
high = 0xFFFF;
}
add_xperm_rule(src, tgt, cls, low, high, effect, invert);
return true;
}
bool sepol_impl::add_type_rule(const char *s, const char *t, const char *c, const char *d, int effect) {
type_datum_t *src, *tgt, *def;
class_datum_t *cls;
src = hashtab_find(db->p_types.table, s);
if (src == nullptr) {
LOGW("source type %s does not exist\n", s);
return false;
}
tgt = hashtab_find(db->p_types.table, t);
if (tgt == nullptr) {
LOGW("target type %s does not exist\n", t);
return false;
}
cls = hashtab_find(db->p_classes.table, c);
if (cls == nullptr) {
LOGW("class %s does not exist\n", c);
return false;
}
def = hashtab_find(db->p_types.table, d);
if (def == nullptr) {
LOGW("default type %s does not exist\n", d);
return false;
}
avtab_key_t key;
key.source_type = src->s.value;
key.target_type = tgt->s.value;
key.target_class = cls->s.value;
key.specified = effect;
avtab_ptr_t node = get_avtab_node(&key, nullptr);
node->datum.data = def->s.value;
return true;
}
bool sepol_impl::add_filename_trans(const char *s, const char *t, const char *c, const char *d, const char *o) {
type_datum_t *src, *tgt, *def;
class_datum_t *cls;
src = hashtab_find(db->p_types.table, s);
if (src == nullptr) {
LOGW("source type %s does not exist\n", s);
return false;
}
tgt = hashtab_find(db->p_types.table, t);
if (tgt == nullptr) {
LOGW("target type %s does not exist\n", t);
return false;
}
cls = hashtab_find(db->p_classes.table, c);
if (cls == nullptr) {
LOGW("class %s does not exist\n", c);
return false;
}
def = hashtab_find(db->p_types.table, d);
if (def == nullptr) {
LOGW("default type %s does not exist\n", d);
return false;
}
filename_trans_key_t key;
key.ttype = tgt->s.value;
key.tclass = cls->s.value;
key.name = (char *) o;
filename_trans_datum_t *last = nullptr;
filename_trans_datum_t *trans = hashtab_find(db->filename_trans, (hashtab_key_t) &key);
while (trans) {
if (ebitmap_get_bit(&trans->stypes, src->s.value - 1)) {
// Duplicate, overwrite existing data and return
trans->otype = def->s.value;
return true;
}
if (trans->otype == def->s.value)
break;
last = trans;
trans = trans->next;
}
if (trans == nullptr) {
trans = auto_cast(xcalloc(sizeof(*trans), 1));
filename_trans_key_t *new_key = auto_cast(malloc(sizeof(*new_key)));
*new_key = key;
new_key->name = strdup(key.name);
trans->next = last;
trans->otype = def->s.value;
hashtab_insert(db->filename_trans, (hashtab_key_t) new_key, trans);
}
db->filename_trans_count++;
return ebitmap_set_bit(&trans->stypes, src->s.value - 1, 1) == 0;
}
bool sepol_impl::add_genfscon(const char *fs_name, const char *path, const char *context) {
// First try to create context
context_struct_t *ctx;
if (context_from_string(nullptr, db, &ctx, context, strlen(context))) {
LOGW("Failed to create context from string [%s]\n", context);
return false;
}
// Allocate genfs context
ocontext_t *newc = auto_cast(xcalloc(sizeof(*newc), 1));
newc->u.name = strdup(path);
memcpy(&newc->context[0], ctx, sizeof(*ctx));
free(ctx);
// Find or allocate genfs
genfs_t *last_gen = nullptr;
genfs_t *newfs = nullptr;
for (genfs_t *node = db->genfs; node; node = node->next) {
if (strcmp(node->fstype, fs_name) == 0) {
newfs = node;
break;
}
last_gen = node;
}
if (newfs == nullptr) {
newfs = auto_cast(xcalloc(sizeof(*newfs), 1));
newfs->fstype = strdup(fs_name);
// Insert
if (last_gen)
last_gen->next = newfs;
else
db->genfs = newfs;
}
// Insert or replace genfs context
ocontext_t *last_ctx = nullptr;
for (ocontext_t *node = newfs->head; node; node = node->next) {
if (strcmp(node->u.name, path) == 0) {
// Unlink
if (last_ctx)
last_ctx->next = node->next;
else
newfs->head = nullptr;
// Destroy old node
free(node->u.name);
context_destroy(&node->context[0]);
free(node);
break;
}
last_ctx = node;
}
// Insert
if (last_ctx)
last_ctx->next = newc;
else
newfs->head = newc;
return true;
}
bool sepol_impl::add_type(const char *type_name, uint32_t flavor) {
type_datum_t *type = hashtab_find(db->p_types.table, type_name);
if (type) {
LOGW("Type %s already exists\n", type_name);
return true;
}
type = auto_cast(xmalloc(sizeof(type_datum_t)));
type_datum_init(type);
type->primary = 1;
type->flavor = flavor;
uint32_t value = 0;
if (symtab_insert(db, SYM_TYPES, strdup(type_name), type, SCOPE_DECL, 1, &value))
return false;
type->s.value = value;
ebitmap_set_bit(&db->global->branch_list->declared.p_types_scope, value - 1, 1);
auto new_size = sizeof(ebitmap_t) * db->p_types.nprim;
db->type_attr_map = auto_cast(xrealloc(db->type_attr_map, new_size));
db->attr_type_map = auto_cast(xrealloc(db->attr_type_map, new_size));
ebitmap_init(&db->type_attr_map[value - 1]);
ebitmap_init(&db->attr_type_map[value - 1]);
ebitmap_set_bit(&db->type_attr_map[value - 1], value - 1, 1);
// Re-index stuffs
if (policydb_index_decls(nullptr, db) ||
policydb_index_classes(db) || policydb_index_others(nullptr, db, 0))
return false;
// Add the type to all roles
for (int i = 0; i < db->p_roles.nprim; ++i) {
// Not sure all those three calls are needed
ebitmap_set_bit(&db->role_val_to_struct[i]->types.negset, value - 1, 0);
ebitmap_set_bit(&db->role_val_to_struct[i]->types.types, value - 1, 1);
type_set_expand(&db->role_val_to_struct[i]->types, &db->role_val_to_struct[i]->cache, db, 0);
}
return true;
}
bool sepol_impl::set_type_state(const char *type_name, bool permissive) {
type_datum_t *type;
if (type_name == nullptr) {
hashtab_for_each(db->p_types.table, [&](hashtab_ptr_t node) {
type = auto_cast(node->datum);
if (ebitmap_set_bit(&db->permissive_map, type->s.value, permissive))
LOGW("Could not set bit in permissive map\n");
});
} else {
type = hashtab_find(db->p_types.table, type_name);
if (type == nullptr) {
LOGW("type %s does not exist\n", type_name);
return false;
}
if (ebitmap_set_bit(&db->permissive_map, type->s.value, permissive)) {
LOGW("Could not set bit in permissive map\n");
return false;
}
}
return true;
}
void sepol_impl::add_typeattribute(type_datum_t *type, type_datum_t *attr) {
ebitmap_set_bit(&db->type_attr_map[type->s.value - 1], attr->s.value - 1, 1);
ebitmap_set_bit(&db->attr_type_map[attr->s.value - 1], type->s.value - 1, 1);
hashtab_for_each(db->p_classes.table, [&](hashtab_ptr_t node){
auto cls = static_cast<class_datum_t *>(node->datum);
for (constraint_node_t *n = cls->constraints; n ; n = n->next) {
for (constraint_expr_t *e = n->expr; e; e = e->next) {
if (e->expr_type == CEXPR_NAMES &&
ebitmap_get_bit(&e->type_names->types, attr->s.value - 1)) {
ebitmap_set_bit(&e->names, type->s.value - 1, 1);
}
}
}
});
}
bool sepol_impl::add_typeattribute(const char *type, const char *attr) {
type_datum_t *type_d = hashtab_find(db->p_types.table, type);
if (type_d == nullptr) {
LOGW("type %s does not exist\n", type);
return false;
} else if (type_d->flavor == TYPE_ATTRIB) {
LOGW("type %s is an attribute\n", attr);
return false;
}
type_datum *attr_d = hashtab_find(db->p_types.table, attr);
if (attr_d == nullptr) {
LOGW("attribute %s does not exist\n", type);
return false;
} else if (attr_d->flavor != TYPE_ATTRIB) {
LOGW("type %s is not an attribute \n", attr);
return false;
}
add_typeattribute(type_d, attr_d);
return true;
}
void sepol_impl::strip_dontaudit() {
avtab_for_each(&db->te_avtab, [=](avtab_ptr_t node) {
if (node->key.specified == AVTAB_AUDITDENY || node->key.specified == AVTAB_XPERMS_DONTAUDIT)
avtab_remove_node(&db->te_avtab, node);
});
}
+352
View File
@@ -0,0 +1,352 @@
#include <cstring>
#include <vector>
#include <string>
#include <base.hpp>
#include "policy.hpp"
using namespace std;
static const char *type_msg_1 =
R"EOF("allow *source_type *target_type *class *perm_set"
"deny *source_type *target_type *class *perm_set"
"auditallow *source_type *target_type *class *perm_set"
"dontaudit *source_type *target_type *class *perm_set"
)EOF";
static const char *type_msg_2 =
R"EOF("allowxperm *source_type *target_type *class operation xperm_set"
"auditallowxperm *source_type *target_type *class operation xperm_set"
"dontauditxperm *source_type *target_type *class operation xperm_set"
- The only supported operation is 'ioctl'
- xperm_set format is either 'low-high', 'value', or '*'.
'*' will be treated as '0x0000-0xFFFF'.
All values should be written in hexadecimal.
)EOF";
static const char *type_msg_3 =
R"EOF("permissive ^type"
"enforce ^type"
)EOF";
static const char *type_msg_4 =
R"EOF("typeattribute ^type ^attribute"
)EOF";
static const char *type_msg_5 =
R"EOF("type type_name ^(attribute)"
- Argument 'attribute' is optional, default to 'domain'
)EOF";
static const char *type_msg_6 =
R"EOF("attribute attribute_name"
)EOF";
static const char *type_msg_7 =
R"EOF("type_transition source_type target_type class default_type (object_name)"
- Argument 'object_name' is optional
)EOF";
static const char *type_msg_8 =
R"EOF("type_change source_type target_type class default_type"
"type_member source_type target_type class default_type"
)EOF";
static const char *type_msg_9 =
R"EOF("genfscon fs_name partial_path fs_context"
)EOF";
void statement_help() {
fprintf(stderr,
R"EOF(One policy statement should be treated as one parameter;
this means each policy statement should be enclosed in quotes.
Multiple policy statements can be provided in a single command.
Statements has a format of "<rule_name> [args...]".
Arguments labeled with (^) can accept one or more entries. Multiple
entries consist of a space separated list enclosed in braces ({}).
Arguments labeled with (*) are the same as (^), but additionally
support the match-all operator (*).
Example: "allow { s1 s2 } { t1 t2 } class *"
Will be expanded to:
allow s1 t1 class { all-permissions-of-class }
allow s1 t2 class { all-permissions-of-class }
allow s2 t1 class { all-permissions-of-class }
allow s2 t2 class { all-permissions-of-class }
Supported policy statements:
%s
%s
%s
%s
%s
%s
%s
%s
%s
)EOF", type_msg_1, type_msg_2, type_msg_3, type_msg_4,
type_msg_5, type_msg_6, type_msg_7, type_msg_8, type_msg_9);
exit(0);
}
using parsed_tokens = vector<vector<const char *>>;
static bool tokenize_string(char *stmt, parsed_tokens &arr) {
// cur is the pointer to where the top level is parsing
char *cur = stmt;
for (char *tok; (tok = strtok_r(nullptr, " ", &cur)) != nullptr;) {
vector<const char *> token;
if (tok[0] == '{') {
// cur could point to somewhere in the braces, restore the string
if (cur)
cur[-1] = ' ';
++tok;
char *end = strchr(tok, '}');
if (end == nullptr) {
// Bracket not closed, syntax error
return false;
}
*end = '\0';
for (char *sub_tok; (sub_tok = strtok_r(nullptr, " ", &tok)) != nullptr;)
token.push_back(sub_tok);
cur = end + 1;
} else if (tok[0] == '*') {
token.push_back(nullptr);
} else {
token.push_back(tok);
}
arr.push_back(std::move(token));
}
return true;
}
// Check array size and all args listed in 'ones' have size = 1 (no multiple entries)
template <int size, int ...ones>
static bool check_tokens(parsed_tokens &arr) {
if (arr.size() != size)
return false;
initializer_list<int> list{ones...};
for (int i : list)
if (arr[i].size() != 1)
return false;
return true;
}
template <int size, int ...ones>
static bool tokenize_and_check(char *stmt, parsed_tokens &arr) {
return tokenize_string(stmt, arr) && check_tokens<size, ones...>(arr);
}
template <typename Func, typename ...Args>
static void run_and_check(const Func &fn, const char *action, Args ...args) {
if (!fn(args...)) {
string s = "Error in: %s";
for (int i = 0; i < sizeof...(args); ++i) s += " %s";
s += "\n";
LOGW(s.data(), action, (args ? args : "*")...);
}
}
#define run_fn(...) run_and_check(fn, action, __VA_ARGS__)
// Pattern 1: allow { source } { target } { class } { permission }
template <typename Func>
static bool parse_pattern_1(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
if (!tokenize_and_check<4>(stmt, arr))
return false;
for (auto src : arr[0])
for (auto tgt : arr[1])
for (auto cls : arr[2])
for (auto perm : arr[3])
run_fn(src, tgt, cls, perm);
return true;
}
// Pattern 2: allowxperm { source } { target } { class } ioctl range
template <typename Func>
static bool parse_pattern_2(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
if (!tokenize_and_check<5, 3, 4>(stmt, arr) || arr[3][0] != "ioctl"sv)
return false;
auto range = arr[4][0];
for (auto src : arr[0])
for (auto tgt : arr[1])
for (auto cls : arr[2])
run_fn(src, tgt, cls, range);
return true;
}
// Pattern 3: permissive { type }
template <typename Func>
static bool parse_pattern_3(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
if (!tokenize_and_check<1>(stmt, arr))
return false;
for (auto type : arr[0])
run_fn(type);
return true;
}
// Pattern 4: typeattribute { type } { attribute }
template <typename Func>
static bool parse_pattern_4(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
if (!tokenize_and_check<2>(stmt, arr))
return false;
for (auto type : arr[0])
for (auto attr : arr[1])
run_fn(type, attr);
return true;
}
// Pattern 5: type name { attribute }
template <typename Func>
static bool parse_pattern_5(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
string tmp_str;
if (!tokenize_string(stmt, arr))
return false;
if (arr.size() == 1) {
arr.emplace_back(initializer_list<const char*>{ "domain" });
}
if (!check_tokens<2, 0>(arr))
return false;
for (auto attr : arr[1])
run_fn(arr[0][0], attr);
return true;
}
// Pattern 6: attribute name
template <typename Func>
static bool parse_pattern_6(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
if (!tokenize_and_check<1, 0>(stmt, arr))
return false;
run_fn(arr[0][1]);
return true;
}
// Pattern 7: type_transition source target class default (filename)
template <typename Func>
static bool parse_pattern_7(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
if (!tokenize_string(stmt, arr))
return false;
if (arr.size() == 4)
arr.emplace_back(initializer_list<const char*>{nullptr});
if (!check_tokens<5, 0, 1, 2, 3, 4>(arr))
return false;
run_fn(arr[0][0], arr[1][0], arr[2][0], arr[3][0], arr[4][0]);
return true;
}
// Pattern 8: type_change source target class default
template <typename Func>
static bool parse_pattern_8(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
if (!tokenize_and_check<4, 0, 1, 2, 3>(stmt, arr))
return false;
run_fn(arr[0][0], arr[1][0], arr[2][0], arr[3][0]);
return true;
}
// Pattern 9: genfscon name path context
template <typename Func>
static bool parse_pattern_9(const Func &fn, const char *action, char *stmt) {
parsed_tokens arr;
if (!tokenize_and_check<3, 0, 1, 2>(stmt, arr))
return false;
run_fn(arr[0][0], arr[1][0], arr[2][0]);
return true;
}
#define add_action_func(name, type, fn) \
else if (strcmp(name, action) == 0) { \
auto __fn = [=](auto && ...args){ return (fn)(args...); };\
if (!parse_pattern_##type(__fn, name, remain)) \
LOGW("Syntax error in '%s'\n\n%s\n", stmt, type_msg_##type); \
}
#define add_action(act, type) add_action_func(#act, type, act)
void sepolicy::parse_statement(const char *stmt) {
// strtok modify strings, create a copy
string cpy(stmt);
char *remain;
char *action = strtok_r(cpy.data(), " ", &remain);
if (remain == nullptr) {
LOGW("Syntax error in '%s'\n\n", stmt);
return;
}
if (0) {}
add_action(allow, 1)
add_action(deny, 1)
add_action(auditallow, 1)
add_action(dontaudit, 1)
add_action(allowxperm, 2)
add_action(auditallowxperm, 2)
add_action(dontauditxperm, 2)
add_action(permissive, 3)
add_action(enforce, 3)
add_action(typeattribute, 4)
add_action(type, 5)
add_action(attribute, 6)
add_action(type_transition, 7)
add_action(type_change, 8)
add_action(type_member, 8)
add_action(genfscon, 9)
// Backwards compatible syntax
add_action(create, 3)
add_action_func("attradd", 4, typeattribute)
add_action_func("name_transition", 7, type_transition)
else { LOGW("Unknown action: '%s'\n\n", action); }
}
void sepolicy::load_rule_file(const char *file) {
file_readline(true, file, [&](string_view line) -> bool {
if (line.empty() || line[0] == '#')
return true;
parse_statement(line.data());
return true;
});
}
void sepolicy::load_rules(const string &rules) {
struct cookie {
const string &s;
size_t pos;
};
cookie c{rules, 0};
FILE *fp = funopen(&c, /* read */ [](void *v, char *buf, int sz) -> int {
auto c = reinterpret_cast<cookie*>(v);
if (c->pos == c->s.length())
return 0;
size_t end = std::min(c->pos + sz, c->s.length());
int len = end - c->pos;
memcpy(buf, c->s.data() + c->pos, len);
c->pos = end;
return len;
}, /* write */ [](auto, auto, auto) -> int {
return 0;
}, /* seek */ [](auto, auto, auto) -> fpos_t {
return 0;
}, /* close */ [](auto) -> int {
return 0;
});
file_readline(true, fp, [&](string_view line) -> bool {
if (line.empty() || line[0] == '#')
return true;
parse_statement(line.data());
return true;
});
}