ansible become что это

Become (Privilege Escalation)¶

Ansible can use existing privilege escalation systems to allow a user to execute tasks as another.

Become¶

Directives¶

These can be set from play to task level, but are overridden by connection variables as they can be host specific.

For example, to manage a system service (which requires root privileges) when connected as a non- root user (this takes advantage of the fact that the default value of become_user is root ):

To run a command as the apache user:

To do something as the nobody user when the shell is nologin:

Connection variables¶

Each allows you to set an option per group and/or host, these are normally defined in inventory but can be used as normal variables.

ansible_become equivalent of the become directive, decides if privilege escalation is used or not. ansible_become_method allows to set privilege escalation method ansible_become_user allows to set the user you become through privilege escalation, does not imply ansible_become: True ansible_become_pass allows you to set the privilege escalation password

Command line options¶

For those using old playbooks will not need to be changed, even though they are deprecated, sudo and su directives, variables and options will continue to work. It is recommended to move to become as they may be retired at one point. You cannot mix directives on the same object (become and sudo) though, Ansible will complain if you try to.

Become will default to using the old sudo/su configs and variables if they exist, but will override them if you specify any of the new ones.

Limitations¶

Although privilege escalation is mostly intuitive, there are a few limitations on how it works. Users should be aware of these to avoid surprises.

Becoming an Unprivileged User¶

Ansible 2.0.x and below has a limitation with regards to becoming an unprivileged user that can be a security risk if users are not aware of it. Ansible modules are executed on the remote machine by first substituting the parameters into the module file, then copying the file to the remote machine, and finally executing it there.

In Ansible 2.1, this window is further narrowed: If the connection is made as a privileged user (root), then Ansible 2.1 and above will use chown to set the file’s owner to the unprivileged user being switched to. This means both the user making the connection and the user being switched to via become must be unprivileged in order to trigger this problem.

If any of the parameters passed to the module are sensitive in nature, then those pieces of data are located in a world readable module file for the duration of the Ansible module execution. Once the module is done executing, Ansible will delete the temporary file. If you trust the client machines then there’s no problem here. If you do not trust the client machines then this is a potential danger.

Ways to resolve this include:

Although the Solaris ZFS filesystem has filesystem ACLs, the ACLs are not POSIX.1e filesystem acls (they are NFSv4 ACLs instead). Ansible cannot use these ACLs to manage its temp file permissions so you may have to resort to allow_world_readable_tmpfiles if the remote machines use ZFS.

Changed in version 2.1.

In addition to the additional means of doing this securely, Ansible 2.1 also makes it harder to unknowingly do this insecurely. Whereas in Ansible 2.0.x and below, Ansible will silently allow the insecure behaviour if it was unable to find another way to share the files with the unprivileged user, in Ansible 2.1 and above Ansible defaults to issuing an error if it can’t do this securely. If you can’t make any of the changes above to resolve the problem, and you decide that the machine you’re running on is secure enough for the modules you want to run there to be world readable, you can turn on allow_world_readable_tmpfiles in the ansible.cfg file. Setting allow_world_readable_tmpfiles will change this from an error into a warning and allow the task to run as it did prior to 2.1.

Connection Plugin Support¶

Privilege escalation methods must also be supported by the connection plugin used. Most connection plugins will warn if they do not support become. Some will just ignore it as they always run as root (jail, chroot, etc).

Only one method may be enabled per host¶

Can’t limit escalation to certain commands¶

Privilege escalation permissions have to be general. Ansible does not always use a specific command to do something but runs modules (code) from a temporary file name which changes every time. If you have ‘/sbin/service’ or ‘/bin/chmod’ as the allowed commands this will fail with ansible as those paths won’t match with the temporary file that ansible creates to run the module.

Читайте также:  74947191 trw для чего

Mailing List Questions? Help? Ideas? Stop by the list on Google Groups irc.freenode.net #ansible IRC chat channel

Copyright © 2017 Red Hat, Inc.
Last updated on Dec 01, 2020.

Ansible docs are generated from GitHub sources using Sphinx using a theme provided by Read the Docs.

Источник

Become (Privilege Escalation)¶

Ansible can use existing privilege escalation systems to allow a user to execute tasks as another.

Become¶

Directives¶

These can be set from play to task level, but are overridden by connection variables as they can be host specific.

For example, to manage a system service (which requires root privileges) when connected as a non- root user (this takes advantage of the fact that the default value of become_user is root ):

To run a command as the apache user:

To do something as the nobody user when the shell is nologin:

Connection variables¶

Each allows you to set an option per group and/or host, these are normally defined in inventory but can be used as normal variables.

ansible_become equivalent of the become directive, decides if privilege escalation is used or not. ansible_become_method allows to set privilege escalation method ansible_become_user allows to set the user you become through privilege escalation, does not imply ansible_become: True ansible_become_pass allows you to set the privilege escalation password

Command line options¶

For those using old playbooks will not need to be changed, even though they are deprecated, sudo and su directives, variables and options will continue to work. It is recommended to move to become as they may be retired at one point. You cannot mix directives on the same object (become and sudo) though, Ansible will complain if you try to.

Become will default to using the old sudo/su configs and variables if they exist, but will override them if you specify any of the new ones.

Limitations¶

Although privilege escalation is mostly intuitive, there are a few limitations on how it works. Users should be aware of these to avoid surprises.

Becoming an Unprivileged User¶

Ansible 2.0.x and below has a limitation with regards to becoming an unprivileged user that can be a security risk if users are not aware of it. Ansible modules are executed on the remote machine by first substituting the parameters into the module file, then copying the file to the remote machine, and finally executing it there.

In Ansible 2.1, this window is further narrowed: If the connection is made as a privileged user (root), then Ansible 2.1 and above will use chown to set the file’s owner to the unprivileged user being switched to. This means both the user making the connection and the user being switched to via become must be unprivileged in order to trigger this problem.

If any of the parameters passed to the module are sensitive in nature, then those pieces of data are located in a world readable module file for the duration of the Ansible module execution. Once the module is done executing, Ansible will delete the temporary file. If you trust the client machines then there’s no problem here. If you do not trust the client machines then this is a potential danger.

Ways to resolve this include:

Although the Solaris ZFS filesystem has filesystem ACLs, the ACLs are not POSIX.1e filesystem acls (they are NFSv4 ACLs instead). Ansible cannot use these ACLs to manage its temp file permissions so you may have to resort to allow_world_readable_tmpfiles if the remote machines use ZFS.

Changed in version 2.1.

In addition to the additional means of doing this securely, Ansible 2.1 also makes it harder to unknowingly do this insecurely. Whereas in Ansible 2.0.x and below, Ansible will silently allow the insecure behaviour if it was unable to find another way to share the files with the unprivileged user, in Ansible 2.1 and above Ansible defaults to issuing an error if it can’t do this securely. If you can’t make any of the changes above to resolve the problem, and you decide that the machine you’re running on is secure enough for the modules you want to run there to be world readable, you can turn on allow_world_readable_tmpfiles in the ansible.cfg file. Setting allow_world_readable_tmpfiles will change this from an error into a warning and allow the task to run as it did prior to 2.1.

Читайте также:  что прикладывать к жалобе по делу об административном правонарушении

Connection Plugin Support¶

Privilege escalation methods must also be supported by the connection plugin used. Most connection plugins will warn if they do not support become. Some will just ignore it as they always run as root (jail, chroot, etc).

Only one method may be enabled per host¶

Can’t limit escalation to certain commands¶

Privilege escalation permissions have to be general. Ansible does not always use a specific command to do something but runs modules (code) from a temporary file name which changes every time. If you have ‘/sbin/service’ or ‘/bin/chmod’ as the allowed commands this will fail with ansible as those paths won’t match with the temporary file that ansible creates to run the module.

Mailing List Questions? Help? Ideas? Stop by the list on Google Groups irc.freenode.net #ansible IRC chat channel

Copyright © 2017 Red Hat, Inc.
Last updated on Dec 01, 2020.

Ansible docs are generated from GitHub sources using Sphinx using a theme provided by Read the Docs.

Источник

Понимание эскалации привилегий:стать

Using become

Стать директивами

Стать переменными подключения

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

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

Станьте опциями командной строки

запросить пароль эскалации привилегий;не подразумевает,что «станет» будет использоваться.Обратите внимание,что этот пароль будет использоваться для всех хостов.

выполнять операции с «Стань» (пароль не подразумевается)

Метод повышения привилегий для использования (по умолчанию=sudo),допустимые варианты:[sudo | su | pbrun | pfexec | doas | dzdo | ksu | runas | machinectl ]

Риски и ограничения становления

Хотя эскалация привилегий в основном интуитивно понятна,есть несколько ограничений на то,как она работает.Пользователи должны знать об этом,чтобы избежать сюрпризов.

Риски стать непривилегированным пользователем

Допустимые модули выполняются на удаленной машине,сначала подставляя параметры в файл модуля,затем копируя файл на удаленную машину и,наконец,выполняя его на ней.

Новое в Ansible 2.11, на этом этапе Ansible попробует chmod + a, который является специфичным для macOS способом установки списков ACL для файлов.

После завершения выполнения модуля Ansible удаляет временный файл.

Существует несколько способов полностью избежать вышеописанного логического потока:

Изменено в версии 2.1.

Изменено в версии 2.10.

Не поддерживается всеми соединительными плагинами

Методы повышения привилегий также должны поддерживаться используемым соединительным штекером.Большинство подключаемых модулей предупреждают о том,что они не поддерживаются.Некоторые просто игнорируют его,так как они всегда запускаются как root (jail,chroot и т.д.).

На каждый хост может быть включен только один метод

Эскалация привилегий должна быть общей

Вы не можете ограничить разрешения на повышение привилегий для определенных команд. Ansible не всегда использует определенную команду для выполнения каких-либо действий, а запускает модули (код) из временного файла, имя которого меняется каждый раз. Если у вас есть ‘/ sbin / service’ или ‘/ bin / chmod’ в качестве разрешенных команд, это не сработает с ansible, поскольку эти пути не будут совпадать с временным файлом, который Ansible создает для запуска модуля. Если у вас есть правила безопасности, которые ограничивают вашу среду sudo / pbrun / doas запуском только определенных путей команд, используйте Ansible из специальной учетной записи, которая не имеет этого ограничения, или используйте Red Hat Ansible Tower для управления косвенным доступом к учетным данным SSH.

Может не иметь доступа к переменным окружения,заполненным pamd_systemd

Станьте и сетевая автоматизация

Установка режима активации для всех задач

group_vars/eos.yml

Пароли для включения режима

авторизация и auth_pass

Стать и Windows

Административные права

Чтобы определить тип токена,который смог получить Ansible,запустите следующую задачу:

Вывод будет выглядеть так,как показано ниже:

Местные сервисные счета

Станьте без установки пароля

Использование become без пароля достигается одним из двух различных способов:

Поскольку нет никаких гарантий, что существующий токен будет существовать для пользователя при запуске Ansible, существует большое изменение, когда процесс становления будет иметь доступ только к локальным ресурсам. Используйте make с паролем, если задача требует доступа к сетевым ресурсам

Учетные записи без пароля

В качестве общей лучшей практики в области безопасности,вы должны избегать разрешения учетных записей без паролей.

Станьте флажками для Windows

Эти флаги должны быть установлены только в том случае,если они становятся обычной учетной записью пользователя,а не локальной учетной записью службы,как LocalSystem.

Ограничения становятся на Windows

Вопросы? Помочь? Идеи? Остановитесь на списке в Google Groups

Источник

Ansible не так прост

Конечно, это неправильно. Я давно присматривался к chef и Puppet, которые, как я думал, решат все мои проблемы. Но я смотрел на конфиги знакомых проектов и откладывал. Это же нужно изучать, разбираться с ruby, бороться с многочисленными, по отзывам, косяками и ограничениями. Две недели назад статья Георгия amarao стала животворящим пинком. Даже не сама статья, а перечисление систем управления конфигурацией. После чтения комментариев и лёгкого гугления решил: возьму Ansible. Потому что питон, и на проблемы никто не жалуется.

Читайте также:  Беспроводная антенна на авто

Что ж, тогда я первым буду.

Сначала я нарыл кучу документации и учебников по Ansible, начиная с бесполезного видеоролика Quick Start на официальном сайте. Их, конечно, много, сделаны для разных задач и написаны разными людьми, но объединяет их одно: учебники делали для людей, которые уже понимают Ansible. Для людей со сферическим сервером в вакууме, которым достаточно подсказать, что бывают роли, модули и таски. Но я пришёл с clean slate и собрал все грабли, какие нашёл. Надеюсь, эта заметка поможет вам их обойти.

От систем управления конфигурациями я ждал чудес, вроде автоматически обновляемых приложений из git. Но оказалось, что Ansible — это лишь способ сохранить последовательность действий при настройке нового сервера. Вы сможете сделать в Ansible только то, что умеете делать из консоли самостоятельно. Чудес нет.

Начало. Vagrant

Задача: не делаю новый хост, потому что хочу сохранить ip. То есть, очищу дроплет через контрольную панель, затем инициализирую с помощью Ansible. План: написать playbook и отладить его на Vagrant.

И первый сюрприз: в коробке Ubuntu 16.04 нет python по умолчанию! Дикость для федоры, где пакетный менеджер написан на питоне. Ansible, как я узнал, загружает свои модули на сервер и выполняет их там. Идём на StackOverflow, находим волшебный таск (точнее, десять вариаций одного таска и непонятно, как лучше):

Суперпользователь, become!

Развернём базу данных

StackOverflow снова в помощь: оказывается, есть три выхода. Один из них — сделать ansible.cfg и прописать внутрь pipelining=True (а для решения какой-то другой возникшей проблемы я временно ставил pipelining=False ). Второй выход — буквально, «не делайте так». И третий самый простой: ставите пакет acl и всё волшебным образом работает. Вернее, не работает другим способом: «sudo: a password is required». Ну что за дела, откуда здесь вообще пароли, я же с ключом захожу?

Чтобы отвлечься, открыл текстовый редактор и начал писать эти заметки. К этому моменту я разбираюсь с Ansible вот уже неделю по полтора-два часа, а ещё даже базу данных в постгресе не создал. В учебниках это всё выглядит так просто… Посчитал вкладки, связанные с Ansible в фаерфоксе: 48 штук. Сорок восемь. Примерно одна шестая от общего числа.

После того, как я разобрался с пользователями, написание ролей пошло как по маслу. Уже готова одна роль из шести, шестьдесят тасков. Но начать сложнее, чем кажется по учебникам.

Полезные штуки

Во время написания playbook-ов находишь или нагугливаешь много полезных мелочей. Какие-то описаны в документации, какие-то — в статьях (поищите «Ansible» на хабре). Вот несколько из них.

Перед изменением таблиц PostgreSQL удобно проверять их состояние с помощью pg_tables. Например:

В одной из статей нашёл совет не переизобретать велосипед, а искать подходящие роли в каталоге Ansible Galaxy. Действительно, php-fpm и postfix ставили тысячи людей до вас, и часто найдётся хорошо написанная роль с удобными значениями по умолчанию.

И в requirements.yml пишете строчки для каждой роли из Galaxy:

Источник

📜 Как настроить управляемые узлы Ansible и запустить специальные команды – часть 3

Настройка SSH-аутентификации без пароля на управляемые узлы

Напомним, что в нашем последнем разделе управление удаленными узлами с помощью Ansible требует настройки SSH-аутентификации без пароля между узлом управления Ansible и управляемыми узлами.

Это включает в себя генерацию пары ключей (пара открытых и закрытых ключей SSH) на узле Ansible Control и копирование открытого ключа на все удаленные хосты.

Это будет решающим шагом вперед и сделает вашу работу намного проще.

Настройте повышение привилегий на управляемых узлах

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

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

Чтобы достичь этого, вам нужно вызвать определенные директивы в playbook для запуска задач от имени привилегированного пользователя на удаленных хостах.

Ansible позволяет вам «стать» другим пользователем на управляемом узле, отличном от того, который в данный момент вошел в систему.

become

Директива become:yes повышает ваши привилегии и позволяет вам выполнять задачи, требующие привилегий root, такие как установка и обновление пакетов и перезагрузка системы.

Источник

Автомобильный онлайн портал