Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support for the fs_context function #75

Merged
merged 19 commits into from
Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions data/error_policies/fs_context.cas
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
resource foo {
fs_context(bob, "ext3", xattr);
fs_context(this, "sockfs", fs_type);
fs_context(this, "sockfs", foo);
fs_context(this, "proc", zap);

fs_context(this, "sysfs", genfscon, "/zap", [bar]);
fs_context(this, "sysfs", genfscon, "/zap", [file bar]);
fs_context(this, "fs1", xattr, "/zap", [file dir]);
fs_context(this, "fs2", task, "/zap");

// Policies must include at least one av rule
allow(domain, foo, file, [read]);
}
23 changes: 23 additions & 0 deletions data/error_policies/fs_context_dup.cas
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
resource foo {
fs_context(foo, "ext3", xattr);
fs_context(foo, "ext3", task);
fs_context(foo, "ext3", trans);

fs_context(this, "sysfs", genfscon, "/zap", [dir]);
fs_context(this, "sysfs", genfscon, "/zap", [file]);
fs_context(this, "sysfs", genfscon, "/zap", [any]);
fs_context(this, "sysfs", genfscon, "/zap");

fs_context(this, "test", genfscon, "/zap/baa", [file]);

// Policies must include at least one av rule
allow(domain, foo, file, [read]);
}

resource bar {
fs_context(this, "test", genfscon, "/zap/baa", [file]);
}

resource xyz {
fs_context(this, "test", genfscon, "/zap/baa", [file]);
}
153 changes: 153 additions & 0 deletions data/expected_cil/fs_context.cil

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions data/policies/fs_context.cas
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
resource foo {
dburgener marked this conversation as resolved.
Show resolved Hide resolved
fs_context(foo, "ext3", xattr);
fs_context(this, "sockfs", task);
fs_context(this, "tmpfs", trans);
fs_context(this, "tmpfs", trans);

fs_context(this, "proc", genfscon, "/");
fs_context(this, "proc", genfscon, "/");
fs_context(this, "cgroup", genfscon);
// TODO re-add when secilc check is in place
// fs_context(this, "sysfs", genfscon, "/zap", [dir]);

// Policies must include at least one av rule
allow(domain, foo, file, [read]);
}

// TODO re-add when secilc check is in place
// resource bar {
// fs_context(this, "sysfs", genfscon, "/zap/baa", [file]);
//}
185 changes: 126 additions & 59 deletions doc/TE.md

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ pub enum BuiltIns {
AvRule,
FileContext,
ResourceTransition,
FileSystemContext,
DomainTransition,
}

Expand Down Expand Up @@ -429,6 +430,9 @@ impl FuncCall {
if self.name == constants::RESOURCE_TRANS_FUNCTION_NAME {
return Some(BuiltIns::ResourceTransition);
}
if self.name == constants::FS_CONTEXT_FUNCTION_NAME {
return Some(BuiltIns::FileSystemContext);
}
if self.name == constants::DOMTRANS_FUNCTION_NAME {
return Some(BuiltIns::DomainTransition);
}
Expand Down
154 changes: 148 additions & 6 deletions src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,23 @@ use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::convert::TryFrom;
use std::ops::Range;

use crate::ast::{
Argument, CascadeString, Declaration, Expression, FuncCall, LetBinding, Machine, Module,
PolicyFile, Statement,
};
use crate::constants;
use crate::context::{BlockType, Context as BlockContext};
use crate::error::{CascadeErrors, ErrorItem, InternalError};
use crate::error::{
add_or_create_compile_error, CascadeErrors, CompileError, ErrorItem, InternalError,
};
use crate::internal_rep::{
argument_to_typeinfo, argument_to_typeinfo_vec, generate_sid_rules, type_slice_to_variant,
validate_derive_args, Annotated, AnnotationInfo, ArgForValidation, Associated, BoundTypeInfo,
ClassList, Context, FunctionArgument, FunctionInfo, FunctionMap, MachineMap, ModuleMap, Sid,
TypeInfo, TypeMap, ValidatedCall, ValidatedMachine, ValidatedModule, ValidatedStatement,
ClassList, Context, FSContextType, FileSystemContextRule, FunctionArgument, FunctionInfo,
FunctionMap, MachineMap, ModuleMap, Sid, TypeInfo, TypeMap, ValidatedCall, ValidatedMachine,
ValidatedModule, ValidatedStatement,
};

use codespan_reporting::files::SimpleFile;
Expand Down Expand Up @@ -49,7 +53,7 @@ pub fn generate_sexp(
// TODO: The rest of compilation
let cil_types = type_list_to_sexp(type_decl_list, type_map);
let headers = generate_cil_headers(classlist, *machine_configurations);
let cil_rules = rules_list_to_sexp(policy_rules);
let cil_rules = rules_list_to_sexp(policy_rules)?;
let cil_macros = func_map_to_sexp(func_map)?;
let sid_statements =
generate_sid_rules(generate_sids("kernel_sid", "security_sid", "unlabeled_sid"));
Expand Down Expand Up @@ -217,6 +221,19 @@ pub fn get_built_in_types_map() -> Result<TypeMap, CascadeErrors> {
if let Some(i) = built_in_types.get_mut(constants::SELF) {
i.inherits = vec![CascadeString::from(constants::RESOURCE)];
}
// Add xattr, task, trans, and genfscon as children of fs_type
if let Some(i) = built_in_types.get_mut("xattr") {
i.inherits = vec![CascadeString::from(constants::FS_TYPE)];
}
if let Some(i) = built_in_types.get_mut("task") {
i.inherits = vec![CascadeString::from(constants::FS_TYPE)];
}
if let Some(i) = built_in_types.get_mut("trans") {
i.inherits = vec![CascadeString::from(constants::FS_TYPE)];
}
if let Some(i) = built_in_types.get_mut("genfscon") {
i.inherits = vec![CascadeString::from(constants::FS_TYPE)];
}

Ok(built_in_types)
}
Expand Down Expand Up @@ -329,6 +346,128 @@ pub fn build_func_map<'a>(
Ok(decl_map)
}

// Helper function to deal with the case where we need to either create a
// new error or add to an existing one, but specifically for this issue
// we need to create a new error and immediately add to it.
#[allow(clippy::too_many_arguments)]
fn new_error_helper(
error: Option<CompileError>,
msg: &str,
file_a: &SimpleFile<String, String>,
file_b: &SimpleFile<String, String>,
range_a: Range<usize>,
range_b: Range<usize>,
help_a: &str,
help_b: &str,
) -> CompileError {
let mut ret;
// error is not None so we have already found something, so we just
// need to add a new error message
if let Some(unwrapped_error) = error {
ret = unwrapped_error.add_additional_message(file_a, range_a, help_a);
} else {
// error is none so we need to make a new one
ret = CompileError::new(msg, file_b, range_b, help_b);
ret = ret.add_additional_message(file_a, range_a, help_a);
}

ret
}

pub fn validate_fs_context_duplicates(
dburgener marked this conversation as resolved.
Show resolved Hide resolved
fsc_rules: BTreeMap<String, BTreeSet<&FileSystemContextRule>>,
) -> Result<(), CascadeErrors> {
let mut errors = CascadeErrors::new();

'key_loop: for v in fsc_rules.values() {
// We only have 1 or 0 elements, thus we cannot have a semi duplicate
if v.len() <= 1 {
continue;
}
let mut error: Option<CompileError> = None;
for rule in v {
match rule.fscontext_type {
// If we ever see a duplicate of xattr task or trans we know something is wrong
FSContextType::XAttr | FSContextType::Task | FSContextType::Trans => {
error = Some(add_or_create_compile_error(error,
"Duplicate filesystem context.",
&rule.file,
rule.fs_name.get_range().ok_or_else(||CascadeErrors::from(InternalError::new()))?,
&format!("Found multiple different filesystem type declarations for filesystem: {}", rule.fs_name)));
}
FSContextType::GenFSCon => {
// genfscon gets more complicated. We can have similar rules as long as the paths are different.
// If we find a genfscon with the same path, they must have the same context and object type.
if let Some(path) = &rule.path {
// Look through the rules again
for inner_rule in v {
// Only check path if it was provided as part of the rule
if let Some(inner_path) = &inner_rule.path {
// If our paths match, check if our contexts match
if path == inner_path && rule.context != inner_rule.context {
dburgener marked this conversation as resolved.
Show resolved Hide resolved
error = Some(new_error_helper(error,
"Duplicate genfscon contexts",
&inner_rule.file,
&rule.file,
inner_rule.context_range.clone(),
rule.context_range.clone(),
&format!("Found duplicate genfscon rules for filesystem {} with differing contexts: {}", inner_rule.fs_name, inner_rule.context),
&format!("Found duplicate genfscon rules for filesystem {} with differing contexts: {}", rule.fs_name, rule.context)));
// Our paths are the same but our file types differ. We must also have a file type.
} else if path == inner_path
&& rule.file_type != inner_rule.file_type
&& rule.file_type.is_some()
{
error = Some(new_error_helper(error,
"Duplicate genfscon file types",
&inner_rule.file,
&rule.file,
inner_rule.file_type_range.clone(),
rule.file_type_range.clone(),
&format!("Found duplicate genfscon rules for filesystem {} with differing file types", inner_rule.fs_name),
&format!("Found duplicate genfscon rules for filesystem {} with differing file types", rule.fs_name)));
}
}
}
// If we have found an error we don't want to look through
// the inner loop again because it will cause duplicate errors
// in the "other" matching directions.
// So an error for A -> B and B -> A
if let Some(unwraped_error) = error {
errors.add_error(unwraped_error);
continue 'key_loop;
}
}
}
}
}
if let Some(unwraped_error) = error {
errors.add_error(unwraped_error);
}
}
errors.into_result(())
}

pub fn validate_rules(statements: &BTreeSet<ValidatedStatement>) -> Result<(), CascadeErrors> {
let mut errors = CascadeErrors::new();

let mut fsc_rules: BTreeMap<String, BTreeSet<&FileSystemContextRule>> = BTreeMap::new();
for statement in statements {
// Add all file system context rules to a new map to check for semi duplicates later
if let ValidatedStatement::FscRule(fs) = statement {
fsc_rules
.entry(fs.fs_name.to_string())
.or_default()
.insert(fs);
}
}

if let Err(call_errors) = validate_fs_context_duplicates(fsc_rules) {
errors.append(call_errors);
}
errors.into_result(())
}

// Mutate hash map to set the validated body
pub fn validate_functions<'a>(
mut functions: FunctionMap<'a>,
Expand Down Expand Up @@ -809,6 +948,8 @@ pub fn get_reduced_infos<'a>(
// Get the policy rules
let new_policy_rules = get_policy_rules(policies, &new_type_map, classlist, &new_func_map)?;

validate_rules(&new_policy_rules)?;

// generate_sexp(...) is called at this step because new_func_map and new_policy_rules,
// which are needed for the generate_sexp call, cannot be returned from this function.
// This is because they reference the local variable, new_func_map_copy, which cannot be
Expand Down Expand Up @@ -1594,11 +1735,12 @@ fn get_rules_vec_for_type(ti: &TypeInfo, s: sexp::Sexp, type_map: &TypeMap) -> V
ret
}

fn rules_list_to_sexp<'a, T>(rules: T) -> Vec<sexp::Sexp>
fn rules_list_to_sexp<'a, T>(rules: T) -> Result<Vec<sexp::Sexp>, ErrorItem>
where
T: IntoIterator<Item = ValidatedStatement<'a>>,
{
rules.into_iter().map(|r| Sexp::from(&r)).collect()
let ret: Result<Vec<_>, _> = rules.into_iter().map(|r| Sexp::try_from(&r)).collect();
ret
}

fn generate_sids<'a>(
Expand Down
5 changes: 4 additions & 1 deletion src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub const AUDITALLOW_FUNCTION_NAME: &str = "auditallow";
pub const NEVERALLOW_FUNCTION_NAME: &str = "neverallow";
pub const FILE_CONTEXT_FUNCTION_NAME: &str = "file_context";
pub const RESOURCE_TRANS_FUNCTION_NAME: &str = "resource_transition";
pub const FS_CONTEXT_FUNCTION_NAME: &str = "fs_context";
pub const DOMTRANS_FUNCTION_NAME: &str = "domain_transition";
pub const SYSTEM_TYPE: &str = "machine_type";
pub const MONOLITHIC: &str = "monolithic";
Expand All @@ -24,9 +25,11 @@ pub const PERM: &str = "perm";
pub const CLASS: &str = "obj_class";
pub const MODULE: &str = "module";
pub const SELF: &str = "self";
pub const FS_TYPE: &str = "fs_type";

pub const BUILT_IN_TYPES: &[&str] = &[
DOMAIN, RESOURCE, MODULE, "path", "string", CLASS, PERM, "context", SELF, "*",
DOMAIN, RESOURCE, MODULE, "path", "string", CLASS, PERM, "context", SELF, FS_TYPE, "xattr",
"task", "trans", "genfscon", "*",
];

pub const SYSTEM_CONFIG_DEFAULTS: &[(&str, &str)] =
Expand Down
14 changes: 14 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,20 @@ impl CompileError {
}
}

pub fn add_or_create_compile_error(
error: Option<CompileError>,
msg: &str,
file: &SimpleFile<String, String>,
range: Range<usize>,
help: &str,
) -> CompileError {
if let Some(unwrapped_error) = error {
unwrapped_error.add_additional_message(file, range, help)
} else {
CompileError::new(msg, file, range, help)
}
}

#[derive(Error, Clone, Debug)]
#[error("{backtrace:?}")]
pub struct InternalError {
Expand Down
Loading