# Linux Selinux Policy Writing

> Use when writing a custom SELinux policy module for a confined service that the targeted policy does not cover, on systems you administer. Covers generating a type enforcement module from AVC denials with audit2allow, writing .te, .fc, and .if files by hand, compiling with checkmodule and semodule_package, labeling files with file contexts, testing in a permissive domain, and promoting a tested module to enforcing. Defensive policy authoring that keeps enforcement on instead of disabling it.

- Skill: `mizazhaider-ceh/linux-selinux-policy-writing` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/linux-selinux-policy-writing`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/linux-selinux-policy-writing/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/linux-selinux-policy-writing

---


The targeted policy covers common services, but a custom application
with its own data directories, ports, and helper binaries will hit
denials the shipped policy never anticipated. Writing a policy module
is the correct response, and it is a skill worth doing carefully:
a sloppy module can grant a confined service far more than it needs,
quietly undoing the containment SELinux exists to provide. This
sub-skill covers the full authoring loop: draft from denials, write
clean type enforcement by hand, label files, test in a permissive
domain, and only then enforce. The parent skill covers SELinux
operations generally; this file is the module-authoring reference.

## Quick Workflow

1. Run the service through its full workload in permissive domain mode
   and collect every AVC denial it produces.
2. Draft a module from the denials, then read every generated rule and
   delete anything the service does not legitimately need.
3. Give the service its own dedicated types for its data and
   configuration instead of granting access to generic types.
4. Write file contexts for the service's paths and label them.
5. Compile, install, and test in enforcing mode with the real
   workload, checking for new denials after each change.
6. Ship the module through configuration management with the service,
   so rebuilds do not silently drop the policy.
7. Review modules on every major policy update: a new targeted policy
   release may already cover the service, making a custom module
   redundant or conflicting.

## 1. Drafting from denials with audit2allow

Start from real denials, not from guesses. Put the domain in
permissive mode (not the whole system), exercise the service fully,
then generate a draft module. The draft is raw material: it encodes
exactly what was attempted, including any access the service should
not have, so the next step is always manual review.

```bash
semanage permissive -a myapp_t
# exercise the service through its full workload, then:
ausearch -m avc -ts today --raw | audit2allow -M myapp
cat myapp.te
semanage permissive -d myapp_t
```

A generated module for a service that reads its own config and writes
its own log typically looks small. If the draft is large, that is
information: either the workload exercised paths the service should
not touch, or the service needs dedicated types (section 2) instead of
broad grants to generic types. A draft granting access to `etc_t`,
`shadow_t`, or `user_home_t` deserves a hard stop and a conversation
with the service owner before it is installed anywhere.

## 2. Writing type enforcement by hand

Hand-written type enforcement is clearer and narrower than generated
output. Declare a domain type for the process, types for its data and
configuration, an entrypoint for its executable, and the exact allow
rules it needs. The pattern below is the template for most custom
services: a domain, a config type, a data type, a log type, and rules
that connect only those pieces.

```
policy_module(myapp, 1.0.0)

type myapp_t;
type myapp_exec_t;
type myapp_conf_t;
type myapp_data_t;
type myapp_log_t;

init_daemon_domain(myapp_t, myapp_exec_t)

allow myapp_t myapp_conf_t:file { getattr open read };
allow myapp_t myapp_data_t:dir { getattr search open read write add_name remove_name };
allow myapp_t myapp_data_t:file { getattr open read write create unlink };
allow myapp_t myapp_log_t:file { getattr open read write append create };
allow myapp_t self:tcp_socket { create connect };
```

Key discipline: never grant a domain access to a generic type such as
`etc_t` or `var_t` when a dedicated type exists, never use `unconfined`
as a shortcut for a service domain, and keep the rule set to the
least privilege the workload demonstrably needs. If a rule's purpose
is not obvious from the service's documented behavior, add a comment
explaining it, so the next reviewer can judge whether it still belongs.

## 3. File contexts and labeling

A type enforcement module without file contexts is inert: the files
must actually carry the new types. Write a `.fc` file mapping paths to
types, install it with the module, and apply it with `restorecon`.
Use regular expressions carefully: a pattern that is too broad labels
files that belong to other services, and a pattern that is too narrow
leaves the service's files mislabeled and denied.

```
/etc/myapp(/.*)?        gen_context(system_u:object_r:myapp_conf_t,s0)
/var/lib/myapp(/.*)?    gen_context(system_u:object_r:myapp_data_t,s0)
/var/log/myapp(/.*)?    gen_context(system_u:object_r:myapp_log_t,s0)
/usr/sbin/myapp         --  gen_context(system_u:object_r:myapp_exec_t,s0)
```

```bash
semanage fcontext -a -t myapp_conf_t "/etc/myapp(/.*)?"
semanage fcontext -a -t myapp_data_t "/var/lib/myapp(/.*)?"
restorecon -Rv /etc/myapp /var/lib/myapp
ls -Z /etc/myapp/myapp.conf /var/lib/myapp/
```

Verify with `ls -Z` after labeling: the config file should show
`myapp_conf_t` and the data directory `myapp_data_t`. If a file still
shows a generic type after `restorecon`, the context pattern did not
match the path (check for a missing trailing pattern or a conflicting
earlier rule), or the module's file context list was not installed.

## 4. Compiling, installing, and testing

Compile the module with `checkmodule` and package it with
`semodule_package`, or use the `make -f /usr/share/selinux/devel/Makefile`
helper where the distribution provides it. Install with `semodule -i`,
then test in enforcing mode with the full workload while watching for
new denials. A module that passes a smoke test but fails under real
load (background jobs, log rotation, backup reads) is not finished.

```bash
checkmodule -M -m -o myapp.mod myapp.te
semodule_package -o myapp.pp -m myapp.mod -f myapp.fc
semodule -i myapp.pp
semodule -l | grep myapp
ausearch -m avc -ts recent --interpret | grep myapp | head -20
```

If a denial appears after installation, the loop is: read the denial,
decide whether the access is legitimate, add the narrowest rule or
fix the label, rebuild, reinstall, and retest. Keep the `.te` source
in version control next to the service definition, not just the
compiled `.pp` on the host, or the next rebuild will lose the policy
and the service will break in enforcing mode.

## 5. Interfaces and reuse

When several services share a pattern (for example, several daemons
that read a shared config directory), define an interface in a `.if`
file so each service's module calls the interface instead of copying
raw allow rules. Interfaces keep policy DRY and make audits possible:
a reviewer reads the interface once and understands every caller.

```
## <summary>Read myapp shared configuration</summary>
## <param name="domain"><summary>Domain allowed to read the config</summary></param>
interface(`myapp_read_conf',`
    gen_require(`
        type myapp_conf_t;
    ')
    allow $1 myapp_conf_t:file { getattr open read };
    allow $1 myapp_conf_t:dir { getattr search open };
')
```

Call it from a consumer module with `myapp_read_conf(myapp_t)`. The
`gen_require` block declares the types the interface needs, so the
module compiles even when the interface's types are defined elsewhere.
Prefer interfaces for shared patterns and direct rules for
service-specific access; an interface for a one-off rule adds
indirection without reuse value.

## Edge cases

- A module compiled against one policy version may fail to load after
  a major targeted policy upgrade if types it references changed, so
  rebuild and retest custom modules as part of every OS upgrade.
- Permissive domain mode (`semanage permissive -a`) logs denials for
  one domain while the rest of the system stays enforcing, which is
  strictly safer than global permissive mode during module testing.
- `audit2allow` without review is the most common source of overbroad
  custom policy, since it grants whatever was attempted, including
  probes from a misbehaving or compromised process.
- File context patterns are matched in order, and a more specific
  earlier rule wins, so test labeling on a copy of the directory tree
  before applying a new pattern to production paths.
- Services started before the module is installed run under the old
  domain until restarted, so restart the service after installing a
  module and confirm the new domain with `ps -Z`.
- Dontaudit rules can hide denials that matter during testing, so
  when a service fails silently with no AVC messages, temporarily
  disable dontaudit rules with `semodule --disable_dontaudit` and
  retest before concluding the problem is not SELinux.
- Modules must be removed cleanly (`semodule -r myapp`) when a service
  is retired, or stale types and contexts linger and confuse future
  audits of the host.

## Key references

- SELinux Project policy writing guide: https://selinuxproject.org/
- Red Hat SELinux policy module guide: https://www.redhat.com/en/topics/linux/what-is-selinux
- NSA SELinux documentation: https://www.nsa.gov/Research/SELinux/
- audit2allow manual: https://linux.die.net/man/1/audit2allow
- MITRE ATT&CK M1026 Privileged Account Management (least privilege): https://attack.mitre.org/mitigations/M1026/

