# AppArmor profile for the MspCoreX RMM server agent (headless, root).
# Intent: bound the dangerous surface (mounts, ptrace of other tasks, raw
# block devices) and document the mspcorex writable tree — NOT to tightly
# sandbox a root daemon whose job is to run apt/dpkg/usermod and open PTYs.
# Package tools transition to unconfined (Ux) so auto-update is never broken.
#
# Validate (parse-only, no enforcement): apparmor_parser -Q <this file>
# Ship in complain mode first (operator promotes to enforce after AVC-clean).

#include <tunables/global>

/opt/mspcorex/agent-server/bin/mspcorex-agent-server flags=(attach_disconnected,complain) {
  #include <abstractions/base>
  #include <abstractions/nameservice>
  #include <abstractions/ssl_certs>

  # The agent runs as root and supervises the host; capabilities are bounded by
  # the systemd CapabilityBoundingSet, not duplicated here. Allow the set the
  # unit grants (no CAP_SYS_PTRACE — dropped in L7).
  capability net_admin,
  capability sys_admin,
  capability dac_read_search,
  capability dac_override,
  capability chown,
  capability fowner,
  capability setuid,
  capability setgid,
  capability kill,

  # Own binaries + writable trees.
  /opt/mspcorex/agent-server/bin/** ix,
  /opt/mspcorex/agent-server/previous/** ix,
  /etc/opt/mspcorex/agent-server/** rwk,
  /var/opt/mspcorex/agent-server/** rwk,
  /run/mspcorex/ rw,
  /run/mspcorex/** rwk,

  # Broad read for monitoring (proc/sys/etc) — a root RMM agent inventories the host.
  @{PROC}/ r,
  @{PROC}/** r,
  /sys/** r,
  # cgroup v2 delegation for remote-terminal slices (mkdir under /sys/fs/cgroup).
  /sys/fs/cgroup/** rw,
  /etc/** r,
  /etc/shadow r,

  # PTY allocation for remote terminal.
  /dev/pts/ r,
  /dev/pts/* rw,
  /dev/ptmx rw,
  /dev/null rw,
  # No `ptrace` rule: the L7 cap audit found no ptrace(2)/process_vm_*//proc/<pid>/mem
  # consumer in any crate (process_dispatch.rs reads /proc/<pid>/stat+cmdline only),
  # and CAP_SYS_PTRACE was dropped from the unit. Keep the AppArmor surface in sync.

  # Package + admin tooling runs UNCONFINED — these are the OS's tools; confining
  # them here would break auto-update / local-user ops.
  /usr/bin/apt Ux,
  /usr/bin/apt-get Ux,
  /usr/bin/dpkg Ux,
  /usr/sbin/usermod Ux,
  /usr/sbin/gpasswd Ux,
  /usr/sbin/chpasswd Ux,
  /usr/bin/chage Ux,
  /bin/systemctl Ux,
  /usr/bin/systemctl Ux,
  /bin/sh Ux,
  /bin/bash Ux,
  /usr/bin/systemd-run Ux,
}
