Sepolicy android что это

Содержание
  1. Exploring Android’s SELinux Kernel Policy Introduction Since Android 4.3, SELinux is part of the Security Enhancements for Android and contributes to the Android security model by enforcing mandatory access control over all processes and by confining privileged processes besides Linux’s native discretionary access control. This article focuses on Android’s SELinux kernel policy. I explain in detail how SELinux statements are transformed into a binary file. I dissect briefly its file format and, I introduce a proof-of-concept tool I wrote, sedump, to get back SELinux equivalent statements from a binary file extracted from an Android ROM for instance. Building Android sepolicy The journey begins with understanding how Android’s SELinux kernel policy is generated. Source files required to build Android’s sepolicy can be downloaded either from the Android Source Tree (external/sepolicy) or from the Security Enhancements (SE) for Android repositories (external-sepolicy). Like any other Android project, rules to build output files are described inside a make file named Android.mk. Let us dissect that file, especially rules to build the sepolicy target: When run, the sepolicy target outputs two files, sepolicy and sepolicy.dontaudit, into the $( intermediates ) folder defined by the Android build system. These two files are generated with checkpolicy by providing respectively $( sepolicy_policy.conf ) and $( sepolicy_policy.conf ) .dontaudit as input. The sepolicy_policy.conf target outputs two files, $( intermediates ) /policy.conf and $( intermediates ) /policy.conf.dontaudit . The general-purpose macro processor M4 expands files listed in the $( sepolicy_build_files ) variable in order to generate policy.conf and its stripped off version policy.conf.dontaudit. $( sepolicy_build_files ) simply lists all source files required to build the Android SELinux kernel policy: Let us precise that this file list can be overriden with board specific files while executing $( call build_policy, $( sepolicy_build_files )) . This is an expected behaviour in Android build system when defining BOARD_SEPOLICY_* variables. All the brick put back together, one can generate easily a sepolicy file outside of Android build system. checkpolicy is not an android-specific tool, thus one provided with the setools package in your default Linux distribution should be enough: checkpolicy accepts numerous options. The -M option is a flag to indicate that the compiled policy should embed multi-level security statements and the -c specifies the policy version. Understanding the SELinux Kernel Policy File Format Let us dig the subject deeper by understanding how the SELinux textual statements are transformed into a binary kernel policy. Unfortunately for us, the SELinux kernel policy file format is not documented, probably because it is a complex format which depends heavily on the policy version. The main entry point for checkpolicy is located in checkpolicy.c. In a few words, a SELinux policy is represented in memory by a policydb_t data structure. It is zeroed and initialized by the policydb_init() method, and its members are set while parsing SELinux statements using LEX and YACC (policy_scan.l and policy_parse.y) in read_source_policy(). Once fully parsed, checkpolicy outputs the resulting SELinux kernel policy binary to the path specified in the command line. The method policydb_write() is in charge of writing a policydb_t on the disk. I deliberately skip the parsing of the SELinux statement and I assume that the policy has been loaded and the policydb_t data structure is ready to be written on the disk. The following listing handles writing the binary policy on the disk: policydb_write () expects two arguments: a reference to a policydb_t data structure and a reference to a struct policy_file . The later is an abstration layer for possible input or output formats (memory-mapped memory or basic I/O). The struct policy_file is defined as follows in libsepol: Let us focus now on policydb_write () (defined in libsepol/src/write.c) to understand the format of the binary policy. SELinux policies can be defined via a SELinux kernel policy or a SELinux module policy: as we are only interested in SELinux kernel policies, one can focus only on code path satisfying p -> policy_type == POLICY_KERN in the source code. policydb_write () begins an SELinux kernel policy binary with a magic number that holds the type of policy. It writes then information related to policy compatibility: the length of a standardized string identifier and the string identifier itself («SE Linux» or «XenFlask» or «SELinux Module»), the policy version number, the configuration (e.g, MLS policy or not), the symbol array and object context array sizes. To illustrate the file format, I wrote an incomplete 010Editor template that parses the SELinux kernel policy header. Using Python format parser (pfp), one can dissect an sepolicy header with the above mentionned template. As expected, we manage to retrieve the same piece of information as file: The SELinux kernel policy header is followed by two serialized ebitmap_t (libsepol/ebitmap.c): on that stores polcap statements and another one for permissive statements. To output these bitmaps, the template has been updated with the following: In AOSP, policycap statements are defined in policy_capabilities. There are two policy capability defined, network_peer_controls and open_perms , which is consistent with the above displayed bitmap and the meaning of each bit defined in libsepol/polcaps.c. Furthermore, no permissive type is defined in the AOSP SELinux configuration which likely explain the empty bitmap for permissive. Unfortunately, the remaining SELinux kernel policy is a bit tedious to explain as there are many data structures involved and to serialize: policydb_write () outputs identifiers declarations (common, types, attributes, etc.) and the defined access vector rules (allow, deny, dontaudit, etc. rules.). Let us detail the serialization of common permission sets. Common permission sets are stored in the policydb_t data structure in the symtable [ 0 ]. table field. It is a hash table with the common permission set identifier as key and a reference to a common_datum_t as value. The latter is a structure with a datum_t (i.e., index) and an hash table listing the permission associated with the common identifier. All these structures are defined in libsepol/sepol/policydb/policydb.h. In libsepol, hashtab_t hash tables are all serialized in the same way. The serialized structure contains a nprim member, keys and values of the hash table and additionnally nelem , representing the number of elements stored in the hash table. These members can be found in the serialized symtable [ 0 ]. table and common_datum_t . As for strings identifiers, they are simply serialized with the string itself and its length. Here is an updated template to parse the common permission group: As the process is slightly the same for the other statements, I will leave to the curious reader the decoding of the remaining binary as an exercise. Dumping sepolicy back to policy.conf So far, I assumed that one had the source code to build the sepolicy file. Unfortunately, real life is far from being that easy and all you have, when analyzing an Android system, is a binary SELinux kernel policy file. Furthermore, this policy file is rarely the one from AOSP as manufacturers may add (and they generally do!) a new set of rules to reduce the attack surface on the services they added. In order to audit SELinux statements, most of the time, one have to extract information from the binary policy file using setools3 utilities (apol, sesearch, seinfo, sediff, etc.) for instance. That work is particularly tedious as these tools output only a fragment of the sepolicy file at a time and one may have to juggle with multiple tools to get an information of the binary file. To my surprise and to my knowledge, no tool exists to extract a compilable policy.conf file from a sepolicy binary [1]. However, as we have just seen in the previous section, the SELinux kernel policy is simply a serialized version of a policydb_t structure, built from parsing the policy.conf file. Moreover, checkpolicy is able produce a semantically equivalent binary kernel policy (see -b option) from a compiled kernel policy. Thus, it should be possible to deserialize an sepolicy binary and get back a policy.conf file equivalent to the original one. I quickly wrote a proof-of-concept tool called sedump few weeks ago, using setools4’s python bindings. As setools4 is still in alpha version and may conflict with setools3, I recommend to run it inside a docker container: So far, it has been tested with sepolicy binaries built from AOSP and sepolicy binaries extracted from Samsung stock ROMs. Currently, binary policies with conditional access vectors are not working, I am still working on the problem. Outside the docker container, one can test that the policy.conf file is semantically equivalent to the original one, by compiling it and running a diffing tool like sediff: [1] dispol currently only displays access vector and conditional access vector rules. Conclusion Security Enhancements for Android, and more generally SELinux, is a really complex subject. In this article, I covered only a tiny part of this solution, which has been an integral part of the Android security model since Android 4.3. We have dissected, first, Android’s build system to understand how was generated the SELinux kernel policy binary for Android. The whole build process is not that different from SELinux for desktops, it heavily uses m4 and checkpolicy to respectively expand and build a monolithic policy from a set of SELinux statements. As regular versions of m4 and checkpolicy are used, one can build a sepolicy out of Android source tree easily. Then, I dug further in the policy compilation process by analyzing the source code of checkpolicy. We introduced data structures used to store these statements in memory and I presented briefly the file format of an SELinux kernel policy. The sepolicy binary is simply a serialized version of a policydb_t structure, built from parsing the policy.conf file. Finally, I introduced a proof-of-concept tool, sedump, to decompile or deserialize a sepolicy binary into a text file policy.conf, and, to my surprise, no such tool exists. Once decompiled, one can audit the SELinux policy the hard way, modify it and compile it to get a new policy file if needed. Please note that sedump is still in alpha-version: do not hesitate to give us feedbacks or report failing test cases to us via github. A known limitation is binary policies with conditional access vectors, if/else statement may not be correctly rendered. There is a lot of work to do before thinking about merging it into setools4’s mainline. Источник Временное отключение или изменение SELinux на Android Я разработчик root -app для Android. К сожалению, теперь на некоторых устройствах / ПЗУ есть SELinux в принудительном режиме -mode и предотвращает некоторые действия моего приложения. Поскольку это корневое приложение, пользователи предоставляют мне root-доступ! Теперь SELinux блокирует некоторые из моих действий, и мне нужно найти решение для этого. Я пытался временно отключить SELinux Я играю с идеей редактировать файл sepolicy во время выполнения, чтобы разрешить заблокированные команды и запускать перезагрузку, но я не уверен, что и как это может работать, и это не очень хорошая идея. У кого есть еще несколько советов или ресурсов для меня? Вы можете использовать supolicy из приложения SuperSU, см. Ссылку для подробного описания, когда и как это можно назвать. Узнайте, почему что-то блокируется SELinux, проверяя сообщения аудита, например dmesg | grep «audit» dmesg | grep «audit» Создайте правило allow . , позволяющее заблокировать операцию. Они аналогичны (идентичны?), Чтобы «разрешать» правила в файлах SELinux * .te. Запустите supolicy —live «allow . » в корневой оболочке и проверьте, supolicy —live «allow . » ли операция. Если нет, расширьте правило (ы) разрешения. Вы можете указать несколько правил «разрешить» в одном вызове supolicy . Обратите внимание, что supolicy – дорогостоящая операция, поэтому обязательно вызывайте ее только один раз. Если вы не хотите зависеть от SuperSU от Chainfire, вы можете попробовать sepolicy-inject . Я сам этого не испытывал. Я пытался отключить SELinux на Android 4.3 некоторое время, и это то, к чему я пришел. На Samsung S4 Android 4.3 setenforce 0 переключится в Permissive режим. На Samsung Note 3 Android 4.3 setenforce 0 не изменит статус SELinux. Я пробовал Nexus 4 Android 4.3, но по умолчанию это Permissive режим Если у вас есть root-доступ, запустите su 0 setenforce 0 чтобы перейти в Permissive режим: Вы можете скачать приложение selinux mod changer. Это не в игровом магазине, поэтому вы можете загрузить его из хрома или любого другого браузера по вашему выбору. Приложение просто нуждается в корневом разрешении, поэтому попробуйте. Измените файл build.prop в системной папке в самом первом каталоге, используя поиск текстового редактора «selinux» Если вы видите что-то вроде enable_selinux = 1 , измените его на 0, если это нужно отключить, наоборот, изменения будут применены после перезагрузки или загрузки. В моем случае они уже отключили его, но это было в строке комментариев Строка, начинающаяся с #, – это комментарий, который ничего не изменит. Аналогичным образом вы можете включить / выключить учетную запись нескольких пользователей, обновления системы. Мой производитель устройств отключил обновления системы. Источник Быстрое создания SELinux-модулей с помощью утилиты sepolicy В пакет policycoreutils-devel входит python-утилита sepolicy, которая сильно облегчает написание модуля. В этой статье мы рассмотрим процесс создания модуля для nmap с помощью этой утилиты. TL; DR В предыдущих статьях мы детально рассматривали создание policy module и связанные с этим вопросы. Сейчас же я расскажу о том, как значительно облегчить себе жизнь с man 8 sepolicy Постановка задачи Задачи, которые мы решим в статье: Написать модуль для nmap. Разрешить пользователям проводить сканы. Ограничить любые деструктивные действия. Создание заготовки У sepolicy есть режим генерации базовых модулей, вызываемый командой sepolicy generate (или sepolgen). Давайте создадим шаблон нашего модуля: Разберем аргументы командной строки: -n — имя модуля. —application — тип/приложение. /usr/bin/nmap — путь к исполняемому файлу. -u staff_u -u user_u — список пользователей, которые могут использовать это приложение. Так как путь /usr/bin/nmap уже описан как traceroute_exec_t, сборка модуля as is вызовет конфликт. Поэтому удаляем файл nmap.fc перед сборкой модуля, а после сборки — делаем chcon. Отладка Сейчас модуль работает в permissive-режиме, т. е. политики проверяются, но реальной блокировки не происходит. Это можно понять по строке permissive nmap_t в файле nmap.te. Теперь запустим nmap с различными опциями для формирования достаточного количества логов. Предварительно рекомендую выполнить команду semodule -DB для отключения dontaudit-правил (правила, которые не дают писать в лог те или иные запреты). Заодно видим, что out.log создался с контекстом user_home_dir_t — нужно создать новый тип (nmap_result_log_t) и дать необходимые права доступа. Финализация Итак, нам нужно сделать следующее: Разрешить необходимые доступы к сети. Разрешить писать логи. Сделать новый тип для логов. Сделать правило перехода типов для логов. Дать права пользователям и приложению на правку этих логов. Правим модуль и получаем следующий код: И проверяем в enforcing-режиме: Что еще может sepolicy? Показать списки макросов интерфейсов Отслеживать возможные переходы типов Отслеживать «общие» типы для обмена данными А также генерировать документацию, показывать состояние booleans и прочие полезные вещи. Очень хорошая утилита, на самом деле. Вместо заключения SELinux не так страшен, как его малюют. Пользуйтесь вспомогательными утилитами, и написание полиси станет для вас легким и приятным делом. Если вы хотите узнать больше — приходите на PHDays 18, где я буду вести четырехчасовой семинар по настройке SELinux-окружения. Источник
  2. Introduction
  3. Building Android sepolicy
  4. Understanding the SELinux Kernel Policy File Format
  5. Dumping sepolicy back to policy.conf
  6. Conclusion
  7. Временное отключение или изменение SELinux на Android
  8. Быстрое создания SELinux-модулей с помощью утилиты sepolicy
  9. Постановка задачи
  10. Создание заготовки
  11. Отладка
  12. Финализация
  13. Что еще может sepolicy?
  14. Вместо заключения
Читайте также:  Рекавери меню как выйти андроид

Exploring Android’s SELinux Kernel Policy

Introduction

Since Android 4.3, SELinux is part of the Security Enhancements for Android and contributes to the Android security model by enforcing mandatory access control over all processes and by confining privileged processes besides Linux’s native discretionary access control.

This article focuses on Android’s SELinux kernel policy. I explain in detail how SELinux statements are transformed into a binary file. I dissect briefly its file format and, I introduce a proof-of-concept tool I wrote, sedump, to get back SELinux equivalent statements from a binary file extracted from an Android ROM for instance.

Building Android sepolicy

The journey begins with understanding how Android’s SELinux kernel policy is generated. Source files required to build Android’s sepolicy can be downloaded either from the Android Source Tree (external/sepolicy) or from the Security Enhancements (SE) for Android repositories (external-sepolicy).

Like any other Android project, rules to build output files are described inside a make file named Android.mk. Let us dissect that file, especially rules to build the sepolicy target:

When run, the sepolicy target outputs two files, sepolicy and sepolicy.dontaudit, into the $( intermediates ) folder defined by the Android build system. These two files are generated with checkpolicy by providing respectively $( sepolicy_policy.conf ) and $( sepolicy_policy.conf ) .dontaudit as input.

The sepolicy_policy.conf target outputs two files, $( intermediates ) /policy.conf and $( intermediates ) /policy.conf.dontaudit . The general-purpose macro processor M4 expands files listed in the $( sepolicy_build_files ) variable in order to generate policy.conf and its stripped off version policy.conf.dontaudit. $( sepolicy_build_files ) simply lists all source files required to build the Android SELinux kernel policy:

Let us precise that this file list can be overriden with board specific files while executing $( call build_policy, $( sepolicy_build_files )) . This is an expected behaviour in Android build system when defining BOARD_SEPOLICY_* variables.

All the brick put back together, one can generate easily a sepolicy file outside of Android build system. checkpolicy is not an android-specific tool, thus one provided with the setools package in your default Linux distribution should be enough:

checkpolicy accepts numerous options. The -M option is a flag to indicate that the compiled policy should embed multi-level security statements and the -c specifies the policy version.

Understanding the SELinux Kernel Policy File Format

Let us dig the subject deeper by understanding how the SELinux textual statements are transformed into a binary kernel policy. Unfortunately for us, the SELinux kernel policy file format is not documented, probably because it is a complex format which depends heavily on the policy version.

The main entry point for checkpolicy is located in checkpolicy.c. In a few words, a SELinux policy is represented in memory by a policydb_t data structure. It is zeroed and initialized by the policydb_init() method, and its members are set while parsing SELinux statements using LEX and YACC (policy_scan.l and policy_parse.y) in read_source_policy(). Once fully parsed, checkpolicy outputs the resulting SELinux kernel policy binary to the path specified in the command line. The method policydb_write() is in charge of writing a policydb_t on the disk.

I deliberately skip the parsing of the SELinux statement and I assume that the policy has been loaded and the policydb_t data structure is ready to be written on the disk. The following listing handles writing the binary policy on the disk:

policydb_write () expects two arguments: a reference to a policydb_t data structure and a reference to a struct policy_file . The later is an abstration layer for possible input or output formats (memory-mapped memory or basic I/O). The struct policy_file is defined as follows in libsepol:

Let us focus now on policydb_write () (defined in libsepol/src/write.c) to understand the format of the binary policy. SELinux policies can be defined via a SELinux kernel policy or a SELinux module policy: as we are only interested in SELinux kernel policies, one can focus only on code path satisfying p -> policy_type == POLICY_KERN in the source code.

policydb_write () begins an SELinux kernel policy binary with a magic number that holds the type of policy. It writes then information related to policy compatibility: the length of a standardized string identifier and the string identifier itself («SE Linux» or «XenFlask» or «SELinux Module»), the policy version number, the configuration (e.g, MLS policy or not), the symbol array and object context array sizes. To illustrate the file format, I wrote an incomplete 010Editor template that parses the SELinux kernel policy header.

Using Python format parser (pfp), one can dissect an sepolicy header with the above mentionned template. As expected, we manage to retrieve the same piece of information as file:

The SELinux kernel policy header is followed by two serialized ebitmap_t (libsepol/ebitmap.c): on that stores polcap statements and another one for permissive statements. To output these bitmaps, the template has been updated with the following:

In AOSP, policycap statements are defined in policy_capabilities. There are two policy capability defined, network_peer_controls and open_perms , which is consistent with the above displayed bitmap and the meaning of each bit defined in libsepol/polcaps.c. Furthermore, no permissive type is defined in the AOSP SELinux configuration which likely explain the empty bitmap for permissive.

Unfortunately, the remaining SELinux kernel policy is a bit tedious to explain as there are many data structures involved and to serialize: policydb_write () outputs identifiers declarations (common, types, attributes, etc.) and the defined access vector rules (allow, deny, dontaudit, etc. rules.). Let us detail the serialization of common permission sets.

Common permission sets are stored in the policydb_t data structure in the symtable [ 0 ]. table field. It is a hash table with the common permission set identifier as key and a reference to a common_datum_t as value. The latter is a structure with a datum_t (i.e., index) and an hash table listing the permission associated with the common identifier. All these structures are defined in libsepol/sepol/policydb/policydb.h.

In libsepol, hashtab_t hash tables are all serialized in the same way. The serialized structure contains a nprim member, keys and values of the hash table and additionnally nelem , representing the number of elements stored in the hash table. These members can be found in the serialized symtable [ 0 ]. table and common_datum_t . As for strings identifiers, they are simply serialized with the string itself and its length. Here is an updated template to parse the common permission group:

As the process is slightly the same for the other statements, I will leave to the curious reader the decoding of the remaining binary as an exercise.

Dumping sepolicy back to policy.conf

So far, I assumed that one had the source code to build the sepolicy file. Unfortunately, real life is far from being that easy and all you have, when analyzing an Android system, is a binary SELinux kernel policy file. Furthermore, this policy file is rarely the one from AOSP as manufacturers may add (and they generally do!) a new set of rules to reduce the attack surface on the services they added.

In order to audit SELinux statements, most of the time, one have to extract information from the binary policy file using setools3 utilities (apol, sesearch, seinfo, sediff, etc.) for instance. That work is particularly tedious as these tools output only a fragment of the sepolicy file at a time and one may have to juggle with multiple tools to get an information of the binary file.

To my surprise and to my knowledge, no tool exists to extract a compilable policy.conf file from a sepolicy binary [1]. However, as we have just seen in the previous section, the SELinux kernel policy is simply a serialized version of a policydb_t structure, built from parsing the policy.conf file. Moreover, checkpolicy is able produce a semantically equivalent binary kernel policy (see -b option) from a compiled kernel policy. Thus, it should be possible to deserialize an sepolicy binary and get back a policy.conf file equivalent to the original one.

I quickly wrote a proof-of-concept tool called sedump few weeks ago, using setools4’s python bindings. As setools4 is still in alpha version and may conflict with setools3, I recommend to run it inside a docker container:

So far, it has been tested with sepolicy binaries built from AOSP and sepolicy binaries extracted from Samsung stock ROMs. Currently, binary policies with conditional access vectors are not working, I am still working on the problem.

Outside the docker container, one can test that the policy.conf file is semantically equivalent to the original one, by compiling it and running a diffing tool like sediff:

[1] dispol currently only displays access vector and conditional access vector rules.

Conclusion

Security Enhancements for Android, and more generally SELinux, is a really complex subject. In this article, I covered only a tiny part of this solution, which has been an integral part of the Android security model since Android 4.3.

We have dissected, first, Android’s build system to understand how was generated the SELinux kernel policy binary for Android. The whole build process is not that different from SELinux for desktops, it heavily uses m4 and checkpolicy to respectively expand and build a monolithic policy from a set of SELinux statements. As regular versions of m4 and checkpolicy are used, one can build a sepolicy out of Android source tree easily.

Then, I dug further in the policy compilation process by analyzing the source code of checkpolicy. We introduced data structures used to store these statements in memory and I presented briefly the file format of an SELinux kernel policy. The sepolicy binary is simply a serialized version of a policydb_t structure, built from parsing the policy.conf file.

Finally, I introduced a proof-of-concept tool, sedump, to decompile or deserialize a sepolicy binary into a text file policy.conf, and, to my surprise, no such tool exists. Once decompiled, one can audit the SELinux policy the hard way, modify it and compile it to get a new policy file if needed.

Please note that sedump is still in alpha-version: do not hesitate to give us feedbacks or report failing test cases to us via github. A known limitation is binary policies with conditional access vectors, if/else statement may not be correctly rendered. There is a lot of work to do before thinking about merging it into setools4’s mainline.

Источник

Временное отключение или изменение SELinux на Android

Я разработчик root -app для Android.

К сожалению, теперь на некоторых устройствах / ПЗУ есть SELinux в принудительном режиме -mode и предотвращает некоторые действия моего приложения.

Поскольку это корневое приложение, пользователи предоставляют мне root-доступ!

Теперь SELinux блокирует некоторые из моих действий, и мне нужно найти решение для этого.

Я пытался временно отключить SELinux

Я играю с идеей редактировать файл sepolicy во время выполнения, чтобы разрешить заблокированные команды и запускать перезагрузку, но я не уверен, что и как это может работать, и это не очень хорошая идея.

У кого есть еще несколько советов или ресурсов для меня?

Вы можете использовать supolicy из приложения SuperSU, см. Ссылку для подробного описания, когда и как это можно назвать.

  • Узнайте, почему что-то блокируется SELinux, проверяя сообщения аудита, например dmesg | grep «audit» dmesg | grep «audit»
  • Создайте правило allow . , позволяющее заблокировать операцию. Они аналогичны (идентичны?), Чтобы «разрешать» правила в файлах SELinux * .te.
  • Запустите supolicy —live «allow . » в корневой оболочке и проверьте, supolicy —live «allow . » ли операция. Если нет, расширьте правило (ы) разрешения. Вы можете указать несколько правил «разрешить» в одном вызове supolicy .

Обратите внимание, что supolicy – дорогостоящая операция, поэтому обязательно вызывайте ее только один раз.

Если вы не хотите зависеть от SuperSU от Chainfire, вы можете попробовать sepolicy-inject . Я сам этого не испытывал.

Я пытался отключить SELinux на Android 4.3 некоторое время, и это то, к чему я пришел.

На Samsung S4 Android 4.3 setenforce 0 переключится в Permissive режим.

На Samsung Note 3 Android 4.3 setenforce 0 не изменит статус SELinux.

Я пробовал Nexus 4 Android 4.3, но по умолчанию это Permissive режим

Если у вас есть root-доступ, запустите su 0 setenforce 0 чтобы перейти в Permissive режим:

Вы можете скачать приложение selinux mod changer. Это не в игровом магазине, поэтому вы можете загрузить его из хрома или любого другого браузера по вашему выбору. Приложение просто нуждается в корневом разрешении, поэтому попробуйте.

Измените файл build.prop в системной папке в самом первом каталоге, используя поиск текстового редактора «selinux»
Если вы видите что-то вроде enable_selinux = 1 , измените его на 0, если это нужно отключить, наоборот, изменения будут применены после перезагрузки или загрузки.

В моем случае они уже отключили его, но это было в строке комментариев

Строка, начинающаяся с #, – это комментарий, который ничего не изменит. Аналогичным образом вы можете включить / выключить учетную запись нескольких пользователей, обновления системы.

Мой производитель устройств отключил обновления системы.

Источник

Быстрое создания SELinux-модулей с помощью утилиты sepolicy

В пакет policycoreutils-devel входит python-утилита sepolicy, которая сильно облегчает написание модуля. В этой статье мы рассмотрим процесс создания модуля для nmap с помощью этой утилиты.

TL; DR

В предыдущих статьях мы детально рассматривали создание policy module и связанные с этим вопросы. Сейчас же я расскажу о том, как значительно облегчить себе жизнь с man 8 sepolicy

Постановка задачи

Задачи, которые мы решим в статье:

  • Написать модуль для nmap.
  • Разрешить пользователям проводить сканы.
  • Ограничить любые деструктивные действия.

Создание заготовки

У sepolicy есть режим генерации базовых модулей, вызываемый командой sepolicy generate (или sepolgen). Давайте создадим шаблон нашего модуля:

Разберем аргументы командной строки:

  • -n — имя модуля.
  • —application — тип/приложение.
  • /usr/bin/nmap — путь к исполняемому файлу.
  • -u staff_u -u user_u — список пользователей, которые могут использовать это приложение.

Так как путь /usr/bin/nmap уже описан как traceroute_exec_t, сборка модуля as is вызовет конфликт. Поэтому удаляем файл nmap.fc перед сборкой модуля, а после сборки — делаем chcon.

Отладка

Сейчас модуль работает в permissive-режиме, т. е. политики проверяются, но реальной блокировки не происходит. Это можно понять по строке permissive nmap_t в файле nmap.te.

Теперь запустим nmap с различными опциями для формирования достаточного количества логов. Предварительно рекомендую выполнить команду semodule -DB для отключения dontaudit-правил (правила, которые не дают писать в лог те или иные запреты).

Заодно видим, что out.log создался с контекстом user_home_dir_t — нужно создать новый тип (nmap_result_log_t) и дать необходимые права доступа.

Финализация

Итак, нам нужно сделать следующее:

  • Разрешить необходимые доступы к сети.
  • Разрешить писать логи.
  • Сделать новый тип для логов.
  • Сделать правило перехода типов для логов.
  • Дать права пользователям и приложению на правку этих логов.

Правим модуль и получаем следующий код:

И проверяем в enforcing-режиме:

Что еще может sepolicy?

Показать списки макросов интерфейсов

Отслеживать возможные переходы типов

Отслеживать «общие» типы для обмена данными

А также генерировать документацию, показывать состояние booleans и прочие полезные вещи. Очень хорошая утилита, на самом деле.

Вместо заключения

SELinux не так страшен, как его малюют. Пользуйтесь вспомогательными утилитами, и написание полиси станет для вас легким и приятным делом.

Если вы хотите узнать больше — приходите на PHDays 18, где я буду вести четырехчасовой семинар по настройке SELinux-окружения.

Источник

Оцените статью