# apparmor.d - Full set of apparmor profiles
# Copyright (C) 2015-2020 Mikhail Morfikov
# Copyright (C) 2021-2024 Alexandre Pujol <alexandre@pujol.io>
# SPDX-License-Identifier: GPL-2.0-only

abi <abi/3.0>,

include <tunables/global>

@{exec_path} = @{bin}/vnstat
profile vnstat @{exec_path} {
  include <abstractions/base>
  include <abstractions/consoles>

  # The following rules are needed when adding a new interface to the vnstat database. Usually this
  # action is performed as root, but the vnstatd daemon is run as vnstat (user/group), and all the
  # database files under /var/lib/vnstat/ are owned by vnstat:vnstat. Because of the above, the
  # dac_override CAP is needed to allow writing files in that dir.
  #
  # If this CAP was denied, then the following error is printed when adding new interfaces:
  #
  #  Error: Exec step failed (8: attempt to write a readonly database): "insert into interface
  #  (name, active, created, updated, rxcounter, txcounter, rxtotal, txtotal) values ('eth0', 1,
  #  datetime('now', 'localtime'), datetime('now', 'localtime'), 0, 0, 0, 0)"
  #  Error: Adding interface "ifb0" to database failed.
  #
  capability dac_override,
  #
  # Also the vnstat.db file has to have the write permission:
  /var/lib/vnstat/vnstat.db w,
  /var/lib/vnstat/vnstat.db-journal rw,
  #
  # This is needed to change the owner:group to vnstat:vnstat of the database file.
  capability chown,

  @{exec_path} mr,

  # Many apps/users can query vnstat database, so don't use owner here.
  /var/lib/vnstat/ r,
  /var/lib/vnstat/vnstat.db rk,

  /etc/vnstat.conf r,

  @{sys}/class/net/ r,

  @{sys}/devices/@{pci}/net/*/statistics/{tx,rx}_{bytes,packets} r,
  @{sys}/devices/virtual/net/*/statistics/{tx,rx}_{bytes,packets} r,

  @{sys}/devices/@{pci}/net/*/speed r,
  @{sys}/devices/virtual/net/*/speed r,

  @{PROC}/@{pid}/net/dev r,

  # file_inherit
  deny @{PROC}/@{pid}/stat r,
  deny @{PROC}/@{pid}/net/tcp{,6} r,
  deny @{PROC}/@{pid}/net/if_inet6 r,
  deny @{PROC}/@{pid}/cmdline r,
  deny @{PROC}/@{pid}/io r,
  deny @{PROC}/@{pid}/net/route r,
  deny @{PROC}/uptime r,
  deny @{PROC}/diskstats r,
  deny @{PROC}/loadavg r,
  deny @{sys}/devices/**/hwmon/**/temp*_input r,
  owner /dev/tty@{int} rw,
  deny network inet dgram,
  deny network inet6 dgram,

  include if exists <local/vnstat>
}
