/etc/apparmor.d/
и содержат список правил контроля доступа к ресурсам, которые может использовать каждая программа. Профили собираются и загружаются в ядро командой apparmor_parser
. Каждый профиль может быть загружен либо в режиме исполнения, либо в режиме регистрации жалоб. Режим исполнения обеспечивает соблюдение политики и сообщает о попытках нарушения, в то время как режиме регистрации жалоб не форсирует политику, но регистрирует системные вызовы, которые были отклонены.
apt install apparmor apparmor-profiles apparmor-profiles-extra apparmor-utils
with root privileges.
aa-status
быстро это подтвердит:
#
aa-status
apparmor module is loaded. 40 profiles are loaded. 18 profiles are in enforce mode. /usr/bin/man [..] 22 profiles are in complain mode. [..] dnsmasq [..] 0 profiles are in kill mode. 0 profiles are in unconfined mode. 1 processes have profiles defined. 1 processes are in enforce mode. /usr/sbin/dhclient (473) /{,usr/}sbin/dhclient 0 processes are in complain mode. 0 processes are unconfined but have a profile defined. 0 processes are in mixed mode. 0 processes are in kill mode.
aa-enforce
и aa-complain
, давая в качестве параметра либо путь исполняемого файла, либо путь к файлу политики. Кроме того, профиль может быть полностью отключен aa-disable
или переведён в режим аудита (в т.ч. для регистрации принятых системных вызовов) командой aa-audit
.
#
aa-enforce /usr/bin/pidgin
Setting /usr/bin/pidgin to enforce mode.
#
aa-complain /usr/sbin/dnsmasq
Setting /usr/sbin/dnsmasq to complain mode.
aa-unconfined
для перечисления программ, которые не имеют связанного профиля и выставляют открытый сетевой сокет. С опцией --paranoid
вы получаете все незавершенные процессы, которые имеют по крайней мере одно активное сетевое соединение.
#
aa-unconfined
473 /usr/sbin/dhclient confined by '/{,usr/}sbin/dhclient (enforce)' 521 /usr/sbin/sshd (sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups) not confined 1206 /usr/sbin/squid not confined 9931 /usr/bin/containerd not confined 11171 /usr/sbin/exim4 not confined
/sbin/dhclient
(существует профиль, поставляемый с apparmor-profiles, чтобы вы могли сравнить свои результаты с официальным. Для этого мы будем использовать a-genprof dhclient
. Он пригласит вас использовать приложение в другом окне чтобы, по завершении вернуться к a-genprof
для сканирования событий AppArmor в системных журналах и конвертирования их в правила доступа. Для каждого зарегистрированного события он будет делать одно или несколько правил, которые вы можете либо одобрить, либо дополнительно отредактировать несколькими способами:
#
aa-genprof dhclient
Updating AppArmor profiles in /etc/apparmor.d. Writing updated profile for /usr/sbin/dhclient. Setting /usr/sbin/dhclient to complain mode. Before you begin, you may wish to check if a profile already exists for the application you wish to confine. See the following wiki page for more information: https://gitlab.com/apparmor/apparmor/wikis/Profiles Profiling: /usr/sbin/dhclient Please start the application to be profiled in another window and exercise its functionality now. Once completed, select the "Scan" option below in order to scan the system logs for AppArmor events. For each AppArmor event, you will be given the opportunity to choose whether the access should be allowed or denied. [(S)can system log for AppArmor events] / (F)inish
S
Reading log entries from /var/log/syslog. Profile: /usr/sbin/dhclientExecute: /usr/sbin/dhclient-script Severity: unknown (I)nherit / (C)hild / (P)rofile / (N)amed / (U)nconfined / (X) ix On / (D)eny / Abo(r)t / (F)inish
P
Should AppArmor sanitise the environment when switching profiles? Sanitising environment is more secure, but some applications depend on the presence of LD_PRELOAD or LD_LIBRARY_PATH. [(Y)es] / (N)oY
Writing updated profile for /usr/sbin/dhclient-script. WARNING: Ignoring exec event in /usr/sbin/dhclient//null-/usr/sbin/dhclient-script//null-/usr/bin/systemctl, nested profiles are not supported yet. Complain-mode changes: Profile: /usr/sbin/dhclientCapability: net_raw Severity: 8 [1 - capability net_raw,] (A)llow / [(D)eny] / (I)gnore / Audi(t) / Abo(r)t / (F)inish
A
Adding capability net_raw, to profile. Profile: /usr/sbin/dhclient Capability: net_bind_service Severity: 8 [1 - include <abstractions/nis>] 2 - capability net_bind_service, (A)llow / [(D)eny] / (I)gnore / Audi(t) / Abo(r)t / (F)inishA
Adding include <abstractions/nis> to profile. Profile: /usr/sbin/dhclientPath: /etc/dhcp/dhclient.conf New Mode: owner r Severity: unknown [1 - owner /etc/dhcp/dhclient.conf r,] (A)llow / [(D)eny] / (I)gnore / (G)lob / Glob with (E)xtension / (N)ew / Audi(t) / (O)wner permissions off / Abo(r)t / (F)inish
A
Adding owner /etc/dhcp/dhclient.conf r, to profile. Profile: /usr/sbin/dhclientPath: /var/lib/dhcp/dhclient.leases New Mode: owner rw Severity: unknown [1 - owner /var/lib/dhcp/dhclient.leases rw,] (A)llow / [(D)eny] / (I)gnore / (G)lob / Glob with (E)xtension / (N)ew / Audi(t) / (O)wner permissions off / Abo(r)t / (F)inish
A
Adding owner /var/lib/dhcp/dhclient.leases rw, to profile. [..] Profile: /usr/sbin/dhclient-scriptPath: /usr/bin/dash New Mode: owner r Severity: unknown [1 - include <abstractions/gvfs-open>] 2 - include <abstractions/ubuntu-browsers.d/plugins-common> 3 - include <abstractions/xdg-open> 4 - owner /usr/bin/dash r, (A)llow / [(D)eny] / (I)gnore / (G)lob / Glob with (E)xtension / (N)ew / Audi(t) / (O)wner permissions off / Abo(r)t / (F)inish
2
Profile: /usr/sbin/dhclient-script Path: /usr/bin/dash New Mode: owner r Severity: unknown 1 - include <abstractions/gvfs-open> [2 - include <abstractions/ubuntu-browsers.d/plugins-common>] 3 - include <abstractions/xdg-open> 4 - owner /usr/bin/dash r, (A)llow / [(D)eny] / (I)gnore / (G)lob / Glob with (E)xtension / (N)ew / Audi(t) / (O)wner permissions off / Abo(r)t / (F)inishA
Adding include <abstractions/ubuntu-browsers.d/plugins-common> to profile. [..] Enforce-mode changes: = Changed Local Profiles = The following local profiles were changed. Would you like to save them? [1 - /usr/sbin/dhclient] 2 - /usr/sbin/dhclient-script (S)ave Changes / Save Selec(t)ed Profile / [(V)iew Changes] / View Changes b/w (C)lean profiles / Abo(r)tS
Writing updated profile for /usr/sbin/dhclient. Writing updated profile for /usr/sbin/dhclient-script. Profiling: /usr/sbin/dhclient Please start the application to be profiled in another window and exercise its functionality now. Once completed, select the "Scan" option below in order to scan the system logs for AppArmor events. For each AppArmor event, you will be given the opportunity to choose whether the access should be allowed or denied. [(S)can system log for AppArmor events] / (F)inishF
Setting /usr/sbin/dhclient to enforce mode. Setting /usr/sbin/dhclient-script to enforce mode. Reloaded AppArmor profiles in enforce mode. Please consider contributing your new profile! See the following wiki page for more information: https://gitlab.com/apparmor/apparmor/wikis/Profiles Finished generating profile for /usr/sbin/dhclient.
Первым обнаруженным событием является выполнение другой программы. В этом случае у вас есть несколько вариантов: вы можете запустить программу с профилем родительского процесса (выбор “Inherit”), вы можете запустить её с собственным выделенным профилем (“Profile” и выбор “Named”, отличающийся только возможностью использовать произвольное имя профиля), вы можете запустить её с подпрофилем родительского процесса (выбор “Child”), вы можете запустить её без какого-либо профиля (выбор “Unconfined”) или вы можете решить не запускать её вообще (выбор “Deny”).
Обратите внимание, что когда вы решите запустить её с выделенным профилем, который ещё не существует, инструмент создаст недостающий профиль для вас и будет вносить предложения по правилу для этого профиля в том же запуске.
| |
На уровне ядра специальные полномочия корневого пользователя были разделены на “capabilities” (возможности). Когда системный вызов требует определённой возможности, AppArmor будет проверять, позволяет ли профиль программе использовать эту возможность.
| |
Here the program seeks read permissions for its configuration file /etc/dhcp/dhclient.conf .
| |
Here the program seeks read and write permissions to write the lease into /var/lib/dhcp/dhclient.leases .
| |
Notice that this access request is not part of the dhclient profile but of the new profile that we created when we allowed /usr/sbin/dhclient-script to run with its own profile.
aa-genprof detected that this permission was also granted by multiple “abstractions” and offers them as alternative choices. An abstraction provides a reusable set of access rules grouping together multiple resources that are commonly used together. In this specific case, we opted for selection “2” to first select the “#include <abstractions/ubuntu-browsers.d/plugins-common>” choice and then “A” to allow it.
После прохождения всех зарегистрированных событий программа предлагает сохранить все профили, которые были созданы во время запуска. В этом случае у нас есть два профиля, которые мы сохраняем одновременно выбором опции “Save” (но вы также можете сохранить их в индивидуальном порядке), прежде чем покинуть программу с “Finish”.
|
aa-genprof
на самом деле является только умной обёрткой вокруг aa-logprof
: она создаёт пустой профиль, загружает его в режиме регистрации жалоб, а затем запускает aa-logprof
, инструмент для обновления профиля на основе зарегистрированных нарушений профиля. Таким образом, позднее вы сможете повторно запустить этот инструмент, чтобы улучшить профиль, который вы только что создали.
/etc/apparmor.d/usr.sbin.dhclient
близкий к профилю, предоставляемому apparmor-profiles в /usr/share/apparmor/extra-profiles/sbin.dhclient
.
/etc/apparmor.d/usr.sbin.dhclient-script
может быть похож на /usr/share/apparmor/extra-profiles/sbin.dhclient
, предоставляемый в apparmor-profiles.