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

Add support for custom CIL rules #145

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions udica/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,13 @@ def get_args():
required=False,
default=None,
)
parser.add_argument(
"--custom-rules",
type=str,
help="Path to a CIL file with custom rules",
dest="CustomRules",
required=False,
)
parser.add_argument(
"-d",
"--ansible",
Expand Down
47 changes: 47 additions & 0 deletions udica/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from os import chdir, getcwd, remove
from os.path import exists
import tarfile
import re

import selinux
import semanage
Expand Down Expand Up @@ -105,6 +106,39 @@ def list_ports(port_number, port_proto):
return ctype


def validate_cil_template(cil_path):
"""Ensures that the file is correctly balanced with respect to parentheses."""
try:
with open(cil_path, 'r') as cil_file:
lines = cil_file.readlines()

if not lines:
print("Error: CIL file is empty.")
return False

# Check for balanced parentheses
open_parens = 0
for idx, line in enumerate(lines):
line = line.strip()
open_parens += line.count('(')
open_parens -= line.count(')')
if open_parens < 0:
print(f"Error: Unbalanced parentheses detected in the custom CIL file at line {idx + 1}.")
return False

if open_parens != 0:
print("Error: Unbalanced parentheses in the CIL file.")
return False

return True

except FileNotFoundError:
print(f"Error: CIL file {cil_path} not found.")
return False
except Exception as e:
print(f"Unexpected error while validating CIL file: {e}")
return False

def create_policy(
opts, capabilities, devices, mounts, ports, append_rules, inspect_format
):
Expand Down Expand Up @@ -168,6 +202,19 @@ def create_policy(
+ perms.socket[item["protocol"]]
+ " ( name_bind ))) \n"
)

# Validate and include custom template if provided
if opts.get("CustomRules"):
if validate_cil_template(opts["CustomRules"]):
with open(opts["CustomRules"], "r") as template_file:
custom_template = template_file.read()
policy.write("\n; Start of custom CIL template\n")
policy.write(custom_template)
policy.write("\n; End of custom CIL template\n")
else:
print("Invalid custom template. Aborting policy creation.")
policy.close()
return

# devices
# Not applicable for CRI-O container engine
Expand Down