Часть первая. apparmor

Содержание:

Configuration

Auditing and generating profiles

To create new profiles the Audit framework should be running. This is because Arch Linux adopted systemd and doesn’t do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.

Understanding profiles

Profiles are human readable text files residing under describing how binaries should be treated when executed. A basic profile looks similar to this:

/etc/apparmor.d/usr.bin.test
#include <tunables/global>

profile test /usr/lib/test/test_binary {
    #include <abstractions/base>

    # Main libraries and plugins
    /usr/share/TEST/** r,
    /usr/lib/TEST/** rm,

    # Configuration files and logs
    @{HOME}/.config/ r,
    @{HOME}/.config/TEST/** rw,
}

Most common use cases are covered by the following statements:

  • — read: read data
  • — write: create, delete, write to a file and extend it
  • — memory map executable: memory map a file executable

Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).

Installation

Kernel

When , it is required to at least set the following options:

CONFIG_SECURITY_APPARMOR=y
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1
CONFIG_DEFAULT_SECURITY_APPARMOR=y
CONFIG_AUDIT=y

For those new or altered variables to not get overridden, place them at the bottom of the config file or adjust the previous invocations accordingly.

Instead of setting and , you can also set kernel boot parameters: .

Userspace Tools

Note: Since AppArmor builds and installs a kernel module it must be rebuilt against the current kernel on each update

The userspace tools and libraries to control AppArmor are supplied by the AUR package.

The package is a split package which consists of following sub-packages:

  • apparmor (meta package)
  • apparmor-libapparmor
  • apparmor-utils
  • apparmor-parser
  • apparmor-profiles
  • apparmor-pam
  • apparmor-vim

To load all AppArmor profiles on startup, enable .

Testing

After a reboot you can test if AppArmor is really enabled using this command as root:

# cat /sys/module/apparmor/parameters/enabled
Y

(Y=enabled, N=disabled, no such file = module not in kernel)

Install all AppArmor Profiles[edit]

Installationedit

The easiest method is to install all available AppArmor profiles. This can result in a few profiles being enforced for software that is not installed, but this will not have any adverse impacts.

At time of writing it is not required to change Whonix APT repository.

Install .

1. Update the package lists.

sudo apt-get update

sudo apt-get update

2. Upgrade the system.

sudo apt-get dist-upgrade

sudo apt-get dist-upgrade

3. Install the package.

sudo apt-get install apparmor-profiles apparmor-profiles-extra apparmor-profiles-kicksecure

sudo apt-get install apparmor-profiles apparmor-profiles-extra apparmor-profiles-kicksecure

The procedure of installing is complete.

Enablingedit

Some profiles in the and packages are not enforced by default because the Debian maintainers do not believe they are mature enough.

To see which profiles are in complain mode (not actually providing protection) and which are in enforce mode (providing actual protection), run.

sudo aa-status

sudo aa-status

To enable a profile which is currently in complain mode you need to find it in folder .

ls /etc/apparmor.d

ls /etc/apparmor.d

And then enable. For example.

(The following example is already enforced by default if installed as per above.)

sudo aa-enforce /etc/apparmor.d/home.tor-browser.firefox

sudo aa-enforce /etc/apparmor.d/home.tor-browser.firefox

It might not be advisable or useful to enable all available AppArmor profiles.

Next see the contents of folder to see what other AppArmor profiles are available.

ls /usr/share/apparmor/extra-profiles

ls /usr/share/apparmor/extra-profiles

If you are using any of these applications, copy the profile over to folder . Example.

sudo cp /usr/share/apparmor/extra-profiles/bin.netstat /etc/apparmor.d

sudo cp /usr/share/apparmor/extra-profiles/bin.netstat /etc/apparmor.d

And then enable it. Example.

sudo aa-enforce /etc/apparmor.d/bin.netstat

sudo aa-enforce /etc/apparmor.d/bin.netstat

Профили

Профили AppArmor — это простые текстовые файлы, которые расположены в . Файлы профиля называются соответственно полному пути до исполняемого файла, которым они управляют, с заменой символа «/» на «.». Например — это профиль AppArmor для команды .

Профили AppArmor имеют два режима выполнения:

  1. Жалоб/Обучения (Complaining/Learning): нарушения профиля разрешаются и сохраняются в журнале. Полезно для тестирования и разработки новых профилей.
  2. Принудительный/Ограниченный (Enforced/Confined): принуждает следовать политике профиля, при этом также записывает нарушения в журнал.

Существует два основных типа правил, используемых в профиле:

  1. Записи путей (Path entries): которые описывают к каким файлам приложение имеет доступ в файловой системе.
  2. Записи разрешений (Capability entries): определяют какие права ограничиваемый процесс имеет право использовать.

В качестве примера можно рассмотреть /etc/apparmor.d/bin.ping:

 1  #include <tunables/global>
 2  /bin/ping flags=(complain) {
 3    #include <abstractions/base>
 4    #include <abstractions/consoles>
 5    #include <abstractions/nameservice>
 6 
 7    capability net_raw,
 8    capability setuid,
 9    network inet raw,
10  
11    /bin/ping mixr,
12    /etc/modules.conf r,
13 }
  1. #include <tunables/global>: включает операторы из других файлов. Это позволяет операторам, относящимся к нескольким приложениям находится в одном общем файле.
  2. /bin/ping flags=(complain): путь к программе, управляемой профилем, также устанавливающий режим обучения.
  3. capability net_raw,: разрешает приложению доступ к возможностям CAP_NET_RAW Posix.1e.
  4. /bin/ping mixr,: разрешает приложению доступ на чтение и выполнение файла.

После редактирования профиля он должен быть перезагружен.

Создание профиля

  1. Разработка плана тестирования. План тестирования стоит разделить на маленькие тестовые блоки. Каждый тестовый блок должен иметь краткое описание и перечень шагов выполнения. Некоторые стандартные тестовые блоки:
    1. Запуск программы.
    2. Остановка программы.
    3. Перезагрузка программы.
    4. Тестирование всех команд, поддерживаемых сценарием инициализации.
  2. Создание нового профиля: Используйте aa-genprof для создания нового профиля. Команда в терминале:
    $ sudo aa-genprof executable 
  3. Чтобы получить ваш новый профиль в составе пакета apparmor-profiles, зарегистрируйте проблему в Launchpad для пакета AppArmor.
    1. Включите ваш план тестирования и тестовые блоки.
    2. Присоедините ваш новый профиль к зарегистрированной проблеме.

Обновление профилей

Когда программа ведет себя неправильно, проанализируйте сообщения, отправленные в файлы журналов. Программа aa-logprof может быть использована для сканирования файлов журнала AppArmor для проверки сообщений, их рассмотрения (анализа) и обновления профилей. Команда в терминале:

$ sudo aa-logprof 

AppArmor руководствуется принципом «запрещено все, что не разрешено», поэтому, когда в профиле нет никакого соответствующего правила, действие не разрешается.

Contribute to upstream AppArmor profiles

This documentation focuses on contributing to profiles that live in the upstream apparmor-profiles repository, but the procedure is quite similar for the other repositories.

If you want to contribute to existing/upstream AppArmor profiles, you need to:

  • Generate and update your profiles: see

  • Test your profiles: see AppArmor/Debug

  • create an account on GitLab.com

  • upload a SSH key to be able to push your changes.
  • install the Git version control system: sudo apt install git

  • Fork the upstream project: https://gitlab.com/apparmor/apparmor-profiles/forks/new

  • git clone your brand new fork.

  • Create a topic branch git checkout -b BRANCHNAME origin/master

  • , and test it

  • Once done, you can commit the changes to your local repository: git add -p && git commit

  • Push the changes to your remote repository on a dedicated branch: git push -u origin BRANCHNAME

  • Then you will see a link that proposes you send a merge request through the web interface.

Installation

AppArmor is available in all .

To enable AppArmor as default security model on every boot, set the following kernel parameters:

apparmor=1 lsm=lockdown,yama,apparmor

Note: The kernel parameter sets the initialization order of Linux security modules. The kernel’s configured value can be found with and the current value with .

  • can be omitted from as it will always get included automatically.

Install for userspace tools and libraries to control AppArmor. To load all AppArmor profiles on startup, enable .

Custom kernel

When , it is required to set at least the following options:

CONFIG_SECURITY_APPARMOR=y
CONFIG_AUDIT=y

To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:

CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1
CONFIG_DEFAULT_SECURITY_APPARMOR=y

4: Создание профиля AppArmor для Nginx

Установите apparmor-utils – набор утилит для управления AppArmor.

Команда aa-autodep создаст пустой профиль в каталоге /etc/apparmor.d.

Затем используйте следующую команду, чтобы включить режим complain.

Перезапустите Nginx.

Откройте в браузере:

После этого в логе Nginx появятся записи о посещении данного сайта.

Вернитесь в терминал. Используйте утилиту AppArmor, чтобы просмотреть логи Nginx и одобрить или отклонить перечисленные там действия.

Эта команда сканирует лог-файлы и обновляет профиль Nginx. AppArmor несколько раз предложит разрешить или отклонить функцию. Если на данный момент сервер не подвержен атаке, можно просто нажать А на все запросы программы (поскольку все предложенные функции важны для работы Nginx). Чтобы сохранить изменения, нажмите S.

Итак, чтобы включить AppArmor для нового приложения:

  • Создайте пустой профиль приложения.
  • Откройте приложение и выполните несколько обычных действий, чтобы в логах появились записи.
  • Запустите утилиту AppArmor, которая проверит логи и одобрит (или отклонит) перечисленные в них действия приложения.

AppArmor Denials and Complain Mode

AppArmor denials are logged to (or for non-DBus policy violations if auditd is installed). The kernel will rate limit AppArmor denials which can cause problems while profiling. You can avoid this by installing auditd or by adjusting rate limiting in the kernel:

Another way to to view AppArmor denials is by using the aa-notify tool. aa-notify is a very simple program that will report any new AppArmor denials by consulting (or if auditd is installed). For example,

will show any AppArmor denials within the last day.

We are going to take the easy route to develop this profile and use the tool to evaluate the log entries that AppArmor makes in complain mode, so let’s set the AppArmor profile for certspotter to complain mode for this policy so that we can see what is happening.

Now let’s try running certspotter again:

It immediately starts generating AppArmor entries in the logs that look like this:

because we haven’t yet created the profile rules to allow it to access the network.

Что защищать?

Но это еще не все возможности, которые любезно предоставляет AppArmor. Одна из самых сложных проблем – это определение тех утилит, сервисов и программ, которые требуют защиты. Здесь на помощь приходит утилита unconfined из набора средств AppArmor. Не секрет, что наибольший риск несут те программы, которые доступны потенциальным злоумышленникам через сеть. Утилита unconfined предоставит список работающих программ, которые имеют открытые TCP и UDP-порты, а также укажет на наличие/отсутствие профилей для этих программ:

$ unconfined
2494 /usr/sbin/avahi-daemon не ограничен
3266 /usr/sbin/cupsd не ограничен
5490 /usr/sbin/hpiod не ограничен
5493 /usr/bin/python2.5 не ограничен
6391 /usr/sbin/mysqld не ограничен
6621 /usr/lib/postfix/master ограничен
6725 /usr/sbin/dovecot не ограничен
6870 /usr/sbin/apache2 не ограничен

Таким образом, вы всегда сможете создать свой «черный список» программ, отвечающих на запросы из сети, и соответствующим образом их защитить.

Qubes Users Note[edit]

Qubes-Whonix users require some extra steps to set up AppArmor. Non-Qubes-Whonix users can skip this section.

If you are interested, click on Expand on the right.

The following steps should be completed in dom0 for both and TemplateVMs. After these settings have been applied to the Whonix templates, the (ProxyVM) and (AppVM) will inherit the AppArmor kernel settings.

It is unnecessary to recreate the and TemplateBasedVMs to benefit from the new kernel parameters. It is also important for users to verify AppArmor is active in the and VMs after making these changes.

Whonix-Gateway edit

1. Open a dom0 terminal.

→ →

2. List the current kernel parameters.

qvm-prefs -g whonix-gw-15 kernelopts

qvm-prefs -g whonix-gw-15 kernelopts

Qubes R4 and later releases will show.

nopat

3. Keep the existing kernel parameters and add ‘apparmor=1 security=apparmor’.

For example.

qvm-prefs -s whonix-gw-15 kernelopts "nopat apparmor=1 security=apparmor"

qvm-prefs -s whonix-gw-15 kernelopts «nopat apparmor=1 security=apparmor»

qvm-prefs -s sys-whonix kernelopts "nopat apparmor=1 security=apparmor"

qvm-prefs -s sys-whonix kernelopts «nopat apparmor=1 security=apparmor»

4. List the current kernel parameters again (hit the up arrow key twice; it is unnecessary to type the command again).

qvm-prefs -g whonix-gw-15 kernelopts

qvm-prefs -g whonix-gw-15 kernelopts

The output should show AppArmor is part of the new kernel parameters. For example.

nopat apparmor=1 security=apparmor

5. Start the ProxyVM and confirm AppArmor is now active.

sudo aa-status --enabled ; echo $?

sudo aa-status —enabled ; echo $?

The output should show.

Whonix-Workstation edit

1. Open a dom0 terminal.

→ →

2. List the current kernel parameters.

qvm-prefs -g whonix-ws-15 kernelopts

qvm-prefs -g whonix-ws-15 kernelopts

Qubes R4 and later releases will show.

nopat

3. Keep the existing kernel parameters and add ‘apparmor=1 security=apparmor’.

For example.

qvm-prefs -s whonix-ws-15 kernelopts "nopat apparmor=1 security=apparmor"

qvm-prefs -s whonix-ws-15 kernelopts «nopat apparmor=1 security=apparmor»

qvm-prefs -s anon-whonix kernelopts "nopat apparmor=1 security=apparmor"

qvm-prefs -s anon-whonix kernelopts «nopat apparmor=1 security=apparmor»

4. List the current kernel parameters again (hit the up arrow key twice; it is unnecessary to type the command again).

qvm-prefs -g whonix-ws-15 kernelopts

qvm-prefs -g whonix-ws-15 kernelopts

The output should show AppArmor is part of the new kernel parameters. For example.

nopat apparmor=1 security=apparmor

5. Start the AppVM and confirm AppArmor is now active.

sudo aa-status --enabled ; echo $?

sudo aa-status —enabled ; echo $?

The output should show.

5: Редактирование профиля AppArmor для Nginx

Профиль для Nginx был сгенерирован автоматически, потом он требует дополнительного редактирования. Откройте файл /etc/apparmor.d/usr.sbin.nginx:

Изменения, которые нужно внести:

Добавьте строку (обязательно со знаком диеза):

  • Добавьте строки capability setgid и capability setuid.
  • В строке /data/www/safe/ задайте весь каталог (при помощи символа *).
  • Добавьте строку (обязательно с запятой в конце):

Чтобы Nginx получил право на запись в логе ошибок, установите w в строке /var/log/nginx/error.log.

Строка apache2-common позволяет Nginx слушать разные порты. Строки capability позволяют запускать новые процессы. Правило deny блокирует доступ к каталогу /data/www/unsafe/.

В результате профиль будет выглядеть так:

Ваш профиль может выглядеть немного иначе, так как он создаётся на основе лог-файла. Вы можете самостоятельно изучить параметры и обновить индивидуальные настройки профиля, а можете просто скопировать этот файл, подогнав его под свою серверную среду. Настройки AppArmor могут случайно заблокировать доступ к безопасным каталогам, потому будьте готовы к устранению неполадок.

Чтобы включить профиль AppArmor для Nginx, используйте:

Рекомендуется перезапустить все профили и Nginx, чтобы обновит настройки.

В случае возникновения ошибки на любом этапе настройки проверьте конфигурационный файл и /var/log/syslog.

Проверьте состояние AppArmor:

Процесс Nginx должен быть в исполнении.

Снова откройте браузер и посетите страницу:

На экране должна появиться страница из каталога safe. Затем посетите:

Сервер должен вернуть ошибку 403 Forbidden.

More Profiles[edit]

It is possible to utilize profiles by other vendors, but this is unsupported by Whonix developers. As a reminder, it is not necessary to install AppArmor profiles for any applications that are unlikely to be used (such as dovecot). Additional options include:

  • Debian has packages that can be .
  • Ubuntu also provides profiles . It is not easy to download these as a package to be installed in Debian. Further, the profiles may or may not differ from (or complement) profiles listed earlier.

Footnotesedit

  1. https://wiki.debian.org/AppArmor

  2. http://wiki.apparmor.net/index.php/Main_Page

  3. Non-Qubes-Whonix means all Whonix platforms except Qubes-Whonix . This includes Whonix KVM, Whonix VirtualBox and Whonix Physical Isolation.

  4. While Debian enabled AppArmor by default since Debian , Fedora does not. This matters since Qubes, which is Fedora based, by default uses dom0, not VM kernel. Therefore this is still required even though Whonix is based on a recent enough Debian version.

  5. Since Qubes R3.0, TemplateBasedVMs inherit the kernelopts setting of their TemplateVM .
  6. https://packages.debian.org/buster/apparmor-profiles

  7. Tor Browser is installed by ; the latter is a default Whonix application.

  8. Otherwise essential profile formatting might break or unwanted content (such as line numbers) might be copied inadvertently, leading to a non-functional profile.

  9. In Whonix 13.

  10. This issue was fixed in the Whonix 14 release.

  11. To install it, run: .

  12. https://forums.whonix.org/t/whonix-14-debian-stretch-apparmor-related-changes/3563

Whonix is Supported by Evolution Host DDoS
Protected VPS. Stay private and get your VPS with Bitcoin or Monero.

Search engines: YaCy | Qwant | ecosia | MetaGer | peekier | Whonix Wiki

Follow:

Donate:

Share:
|

Please consider a recurring donation !


This is a wiki. Want to improve this page? Help is welcome and volunteer contributions are happily considered! Read, understand and agree to , then Edit! Edits are held for moderation. Policy of Whonix Website and Whonix Chat and Policy On Nonfreedom Software applies.

Copyright (C) 2012 — 2020 ENCRYPTED SUPPORT LP. Whonix is a trademark. Whonix is a licensee of the Open Invention Network . Unless otherwise noted, the content of this page is copyrighted and licensed under the same Freedom Software as Whonix itself. (Why?)

Whonix is a derivative of and not affiliated with Debian . Debian is a registered trademark owned by Software in the Public Interest, Inc .

Whonix is produced independently from the Tor anonymity software and carries no guarantee from The Tor Project about quality, suitability or anything else.

By using our website, you acknowledge that you have read, understood and agreed to our Privacy Policy, Cookie Policy, Terms of Service, and E-Sign Consent. Whonix is provided by ENCRYPTED SUPPORT LP. See Imprint, Contact.

TOMOYO Linux

Проект TOMOYO Linux
начат в 2003 году японской компанией NTT DATA CORPORATION как легкая реализация
MAC для Linuх-ядра. Через два года лицензию изменили на GNU GPL и выложили код
на SF.net. Некоторое время проект предоставлял патчи и готовые сборки ядер для
разных дистрибутивов. Но начиная с версии ядра 2.6.30, код TOMOYO Linux
включен в основную ветку разработки, что уже само по себе — Событие для любого
подобного проекта.

В настоящее время существует две версии TOMOYO Linux. Первая версия
использует оригинальные хуки, она доступна только в виде патчей и может
использоваться в ядрах 2.4 и 2.6. Вторая (которая уже в ядре) адаптирована под
LSM, но по функциональным возможностям уступает версии 1.х: нет поддержки
сетевых функций, обработки атрибутов, POSIX-возможностей (на сайте представлена
сравнительная таблица). В настоящее время соответствующие пакеты имеются в
репозиториях многих дистрибутивов, но фактически поддержка заявлена пока только
в Mandriva. К слову, в этом дистрибутиве предлагается и графический интерфейс
Tomoyo GUI, позволяющий запустить и настроить политики приложений. Доступность в
репозиториях пакетов для большинства дистрибутивов позволяет буквально в
считанные минуты перевести ОС на новую систему безопасности. Например, Ubuntu
10.04:

Если ядро собирается самостоятельно, активируй параметр «Enable different
security models» и «TOMOYO Linux Support» в секции Security options.

При беглом взгляде TOMOYO очень похож на AppArmor. Обе системы
контролируют путь (pathname based), а правила имеют сходный синтаксис. Но есть и
отличия. Так, в TOMOYO можно указать поведение программы в зависимости от
того, как она запущена. Например, оболочка, запущенная через SSH, может иметь
больше ограничений, чем запущенная с локальной системы. Предусмотрена проверка
дополнительных параметров, с которыми включена программа, а также привилегий (UID/GUD).
Приложения в терминологии TOMOYO называются доменами (domains).
Конфигурационные файлы TOMOYO находятся в каталоге /etc/tomoyo, после
запуска системы настройки имеют свое отражение в /proc/tomoyo, где их можно
редактировать на лету. Параметры работы TOMOYO хранятся в /etc/tomoyo/profile.conf
и доступны в /proc/tomoyo/profile. Именно здесь определяются режимы работы
TOMOYO — disable, permissive, enforsing и learning (обучаясь, система сама
строит правила). Есть и другие файлы:

  • manager.conf (/proc/tomoyo/manager) — программы, которые могут изменить
    политику в /proc/tomoyo;
  • exception_policy.conf (/proc/tomoyo/exception_policy) — исключения для
    политик домена;
  • domain_policy.conf (/proc/tomoyo/domain_policy) — политики домена;
  • meminfo.conf (/proc/tomoyo/meminfo) — настройка использования памяти и
    квот.

После установки пакета ccs-tools необходимо провести инициализацию TOMOYO,
выполнив скрипт /usr/lib/ccs/tomoyo_init_police.sh, который и создаст нужные
конфиги. Далее потребуется перезагрузка системы. Затем можно запускать редактор
политик:

BoF agenda and discussion

These items would be nice to have for hardy:

Integration with the desktop

Package the gnome applet.

A GUI for managing AppArmor profiles:

  • enable and disable profiles.
  • set their enforcing mode.
  • list audit messages related to AppArmor.

system-config-selinux should be considered when designing the GUI.

Packaging helpers

Adding a new script to debhelper to automate packaging apparmor profiles:

  • updating the postinst script to reload apparmor.
  • copy the apparmor profile to the right place.

Adding support to cdbs.

Profiles storage improvments

Improve profile directory layout to support repository, distro and local profiles.

Don’t store the flag in the profiles itself. Variables in policy, profile dependency issues.

Adding profiles to:

  • gdm.
  • mousemu.

Introduction

AppArmor is a Mandatory Access Control (MAC) system which is a kernel (LSM) enhancement to confine programs to a limited set of resources. AppArmor’s security model is to bind access control attributes to programs rather than to users. AppArmor confinement is provided via profiles loaded into the kernel, typically on boot. AppArmor profiles can be in one of two modes: enforcement and complain. Profiles loaded in enforcement mode will result in enforcement of the policy defined in the profile as well as reporting policy violation attempts (either via syslog or auditd). Profiles in complain mode will not enforce policy but instead report policy violation attempts.

AppArmor differs from some other MAC systems on Linux: it is path-based, it allows mixing of enforcement and complain mode profiles, it uses include files to ease development, and it has a far lower barrier to entry than other popular MAC systems.

AppArmor is an established technology first seen in Immunix and later integrated into Ubuntu, Novell/SUSE, and Mandriva. Core AppArmor functionality is in the mainline Linux kernel from 2.6.36 onwards; work is ongoing by AppArmor, Ubuntu and other developers to merge additional AppArmor functionality into the mainline kernel.

Example profile

From /etc/apparmor.d/usr.sbin.tcpdump on Ubuntu 9.04:

#include <tunables/global>

/usr/sbin/tcpdump {
  #include <abstractions/base>
  #include <abstractions/nameservice>
  #include <abstractions/user-tmp>

  capability net_raw,
  capability setuid,
  capability setgid,
  capability dac_override,
  network raw,
  network packet,

  # for -D
  capability sys_module,
  @{PROC}/bus/usb/ r,
  @{PROC}/bus/usb/** r,

  # for -F and -w
  audit deny @{HOME}/.* mrwkl,
  audit deny @{HOME}/.*/ rw,
  audit deny @{HOME}/.*/** mrwkl,
  audit deny @{HOME}/bin/ rw,
  audit deny @{HOME}/bin/** mrwkl,
  @{HOME}/ r,
  @{HOME}/** rw,

  /usr/sbin/tcpdump r,
}

The above profile for tcpdump demonstrates several properties of AppArmor:

  • profiles are simple text files
  • comments are supported in the profile
  • absolute paths as well as file globbing can be used when specifying file access
  • various access controls for files are present. From the profile we see ‘r’ (read), ‘w’ (write), ‘m’ (memory map as executable), ‘k’ (file locking), and ‘l’ (creation hard links). There are others not demonstrated in this profile, including (but not limited to) ‘ix’ (execute and inherit this profile), ‘Px’ (execute under another profile, after cleaning the environment), and ‘Ux’ (execute unconfined, after cleaning the environment)
  • access controls for capabilities are present
  • access controls for networking are present
  • specificity in rule matching, ie the most specific rule matches (eg access to @{HOME}/bin/bad.sh is denied with auditing due to ‘audit deny @{HOME}/bin/** mrwkl,‘ even though general access to @{HOME} is permitted with ‘@{HOME}/** rw,‘)

  • include files are supported to ease development and simplify profiles (ie #include <abstractions/base>, #include <abstractions/nameservice>, #include <abstractions/user-tmp>)

  • variables can be defined and manipulated outside the profile (#include <tunables/global> with @{PROC} and @{HOME})

  • AppArmor profiles are easy to read and audit

Please see below for full details on updating and developing profiles as well as instructions using AppArmor.

Inspect the current state

AppArmor profiles can be set to different modes:

  • complain mode: violations to the policy will only be logged

  • enforce mode: operations that violate the policy will be blocked.

Note that deny rules in profiles are enforced/blocked even in complain mode.

Find out if AppArmor is enabled (returns Y if true):

$ cat /sys/module/apparmor/parameters/enabled

List all loaded AppArmor profiles for applications and processes and detail their status (enforced, complain, unconfined):

$ sudo aa-status

List running executables which are currently confined by an AppArmor profile:

$ ps auxZ | grep -v '^unconfined'

List of processes with tcp or udp ports that do not have AppArmor profiles loaded:

$ sudo aa-unconfined
$ sudo aa-unconfined --paranoid
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *