Настройка PAM в Linux
Библиотеки PAM или Pluggable Authentication Modules — это набор компонентов, предоставляющих программный интерфейс для авторизации пользователей в Linux. Возможно вы уже сталкивались с PAM, когда хотели запустить какую либо графическую программу от имени суперпользователя без использования sudo. Но применение этих библиотек намного шире. Они используются утилитой login и менеджером входа gdm при входе в системе, утилитой ssh при удалённом подключении по SSH, а также другими службами где нужна аутентификация.
Этот механизм появился примерно в 1997 году и с тех пор дошёл до нашего времени практически неизменным. Конечно, были дописаны новые модули, но суть работы осталась такая же как изначально. В этой статье мы рассмотрим как выполняется настройка PAM в Linux.
Как работает PAM в Linux?
Основа безопасности Linux — это аутентификация пользователей и их права. Если бы не было библиотек PAM, то разработчику каждой программы пришлось бы реализовать самому проверку логина и пароля пользователя, а также его прав, может ли он получить доступ к тому или иному ресурсу или нет. Чтобы этого не делать был создан набор библиотек, который поддерживает различные способы аутентификации. Для различных служб нужны разные способы аутентификации, это может быть логин и пароль Unix, открытый ключ, Fingerprint ключа или что-то ещё, и всё это поддерживается в PAM. Давайте рассмотрим как работает PAM на примере авторизации в текстовой консоли Linux с помощью утилиты login:
- Утилита login запрашивает у пользователя логин и пароль, а затем делает запрос к libpam, чтобы выяснить действительно ли это тот пользователь, за которого он пытается себя выдать. Для проверки локального логина и пароля используется модуль pam_unix, затем результат возвращается в программу.
- Затем утилита спрашивает у libpam может ли этот пользователь подключаться. Библиотека использует тот же модуль, чтобы определить не истёк ли пароль пользователя. Другие модули могут проверять права доступа основанные на имени хоста или времени.
- Если пароль пользователя истёк он не сможет войти в систему, либо ему предложат сменить пароль прямо сейчас.
- Если всё хорошо, то процесс входа продолжается, и модуль pam_unix записывает временную метку входа в файл /var/log/wtmp, затем запускается командная оболочка.
- Если на каком-либо этапе входа возникла ошибка, сообщение о ней записывается в файл журнала /var/log/secure.
- При выходе с системе тот же модуль unix_pam записывает временную метку в файл /var/log/wtmp.
Теперь рассмотрим как выполняется настройка PAM Linux.
Как настроить PAM в Linux
Все конфигурационные файлы PAM для различных приложений находятся в папке /etc/pam.d. Давайте посмотрим на конфигурационный файл для утилиты sudo:
Каждая строчка файла состоит из нескольких полей:
тип обязательность модуль параметры
- Первое поле — тип, определяет какой тип запроса к PAM надо выполнить. Существует четыре различных типа запроса auth (проверка данных входа, например, логина и пароля), account (проверка не истёк ли пароль пользователя), password (обновление пароля), и session (обслуживание сессии, например, логгирование и монтирование папок).
- Второе поле определяет как нужно интерпретировать результат, возвращённый модулем PAM. Доступно тоже несколько возможных вариантов: required (тест должен быть обязательно пройден, но следующие строки тоже будут проверяться), requisite (аналогично required, только если тест не проходит, то следующие строки уже не проверяются), sufficient (противоположно requisite, если тест проходит, то следующие строки уже не проверяются), optional (проваленные тесты игнорируются).
- Третье и четвертое поле — это название библиотеки модуля и её параметры. Всё это надо выполнить для выполнения теста авторизации или действия.
Кроме того, существуют директивы include, которые включают строки из других файлов так, как будто они были написаны в этом файле. Файл настройки sudo кажется совсем коротким, но в него включаются другие файлы. Давайте посмотрим ещё на файл /etc/pam.d/common-auth:
Здесь можно видеть более расширенный синтаксис параметра обязательности. Он позволяет лучше понять как всё это работает. Давайте его рассмотрим:
[значение1 = действие1 значение2 = действие2 …]
Модули PAM могут возвращать около 30-ти значений и они зависят от выбранного типа (account/auth/session. ), вот они все: success, open_err, symbol_err, service_err, system_err, buf_err, perm_denied, auth_err, cred_insufficient, authinfo_unavail, user_unknown, maxtries, new_authtok_reqd, acct_expired, session_err, cred_unavail, cred_expired, cred_err, no_module_data, conv_err, authtok_err, authtok_recover_err, authtok_lock_busy, authtok_disable_aging, try_again, ignore, abort, authtok_expired, module_unknown, bad_item, conv_again, incomplete и default. Последнее, default, означает все поля, которые явно не заданы.
В качестве действия могут быть указанны такие значения:
- ignore — не влияет на общий код возврата в приложение;
- bad — расценивать это значение как свидетельство сбоя модуля;
- die — аналогично bad, только сразу возвращать управление в приложение;
- ok — значение должно влиять на общий возвращаемый результат, переопределяет общий результат если он раньше был успешен, но не отменяет сбой;
- done — аналогично ok, только управление сразу возвращается приложению.
Таким образом, те четыре варианта обязательности, которые мы рассматривали выше можно описать вот так:
- required: [success=ok new_authtok_reqd=ok ignore=ignore default=bad]
- requisite: [success=ok new_authtok_reqd=ok ignore=ignore default=die]
- sufficient: [success=done new_authtok_reqd=done default=ignore]
- optional: [success=ok new_authtok_reqd=ok default=ignore]
- success — модуль вернул состояние успешно, поскольку значение ok, это состояние будет учтено если ни один предыдущий модуль не дал сбоя;
- new_authtok_reqd — модуль сообщает, что пароль пользователя желательно обновить;
- ignore — модуль просит игнорировать его результат, игнорируем;
- default — все остальные возвращаемые значение расцениваем как сбой.
Обратите внимание. что модуль возвращает только одно определенное значение и уже к нему применяется действие.
Чтобы закрепить всё это на практике давайте рассмотрим как запретить авторизацию от имени пользователя losst на компьютере с помощью PAM. Для этого можно воспользоваться модулем /lib/security/pam_listfile.so. Он позволяет ограничить доступ для пользователей на основе файла со списком. Откройте файл /etc/pam.d/sshd и добавьте туда такую строчку:
sudo vi /etc/pam.d/sshd
auth required pam_listfile.so \
onerr=succeed item=user sense=deny file=/etc/denyusers
Здесь мы используем тип запроса auth, обязательность required и указанный выше модуль. Вот его опции и их значения:
- onerr=succeed — если возникает ошибка, доступ разрешить;
- item=user — указывает, что в файле конфигурации находятся логины пользователей;
- sense=deny — действие, если логин пользователя найден в файле;
- file=/etc/denyusers — файл с логинами пользователей, для которых надо запретить доступ.
Теперь в файл /etc/denyusers добавьте имя пользователя losst, естественно, такой пользователь должен существовать в системе. Затем попробуйте перейти в любую консоль и авторизоваться от его имени. У вас ничего не выйдет, а в логе /var/log/security или /var/log/auth.log будет сообщение об ошибке:
А если эту строчку закомментировать, то всё снова заработает.
Выводы
В этой статье мы рассмотрели как настроить PAM Linux, как видите, это очень гибкая система, но будьте осторожны. Любая неверная настройка может отнять у вас доступ к собственной системе!
Источник
An introduction to Pluggable Authentication Modules (PAM) in Linux
Pluggable Authentication Modules (PAM) have been around since 1997. I was taught that PAM originated from Sun’s Solaris, and it does appear that the first enterprise use and popularization occurred there. However, according to a 1997 article I found, the first full implementation was the Linux-PAM deployment. The article is still available from Linux Journal. The basic premise and implementation have not changed since then. There are some new keywords and many new modules, but overall the process is the same as 20 years ago.
More Linux resources
As the A in PAM indicates, PAM is about authentication. In most cases, when you log in to a system via a console or from across the network with SSH or Cockpit, PAM is involved. It doesn’t matter if the user accounts are held locally or in a centralized location. For as much as it is used, it not common to manipulate the PAM configuration files directly. Other utilities do it for you. Many changes are made at installation, such as when installing the sssd RPM or using the ipa-client-install utility. The most common additional configurations can be handled by authconfig (RHEL7 and older) or authselect (RHEL8), or even through the Cockpit web interface. Most administrators do not learn about PAM configuration files until they get involved in advanced authentication and security topics.
What do we gain with PAM?
PAM separates the standard and specialized tasks of authentication from applications. Programs such as login , gdm , sshd , ftpd , and many more all want to know that a user is who they say they are, yet there are many ways to do that. A user can provide a user name and password credential which can be stored locally or remotely with LDAP or Kerberos. A user can also provide a fingerprint or a certificate as a credential. It would be painful to ask each application developer to rewrite the authentication checks for each new method. A call to PAM libraries leaves the checks to authentication experts. PAM is pluggable in that we can have different applications run different tests and modular in that we can add new methods with new libraries.
Let’s look at the high-level steps taken when a locally-defined user logs into a text-based console:
- The login application prompts for a user name and password, then makes a libpam authentication call to ask, «Is this user who they say they are?» The pam_unix module is responsible for checking the local account authentication. Other modules may also be checked, and ultimately the result is passed back to the login process.
- The login process next asks, «Is this user allowed to connect?», then makes an account call to libpam . The pam_unix module checks for things like whether the password has expired. Other modules might check host or time-based access control lists. An overall response is handed back to the process.
- If the password has expired, the application responds. Some applications simply fail to log in the user. The login process prompts the user for a new password.
- To get the password verified and written to the correct location, the login process makes a password call to libpam . The pam_unix module writes to the local shadow file. Other modules may also be called to verify the password strength.
- If the login process is continuing at this point, it is ready to create the session. A session call to libpam results in the pam_unix module writing a login timestamp to the wtmp file. Other modules enable X11 authentication or SELinux user contexts.
- On logout, when the session is closed, another session call can be made to libpam . This is when the pam_unix module writes the logout timestamp to the wtmp file.
There are many components to PAM
If you make a change to authentication using a program such as authconfig or authselect and want to see what changed, here are some of the places to look:
/usr/lib64/security
A collection of PAM libraries that perform various checks. Most of these modules have man pages to explain the use case and options available.
/etc/pam.d
A collection of configuration files for applications that call libpam . These files define which modules are checked, with what options, in which order, and how to handle the result. These files may be added to the system when an application is installed and are frequently edited by other utilities.
Since there are several checks done by all applications, these files may also have include statements to call other configuration files in this directory. Most shared modules are found in the system-auth file for local authentication and the password-auth file for applications listening for remote connections.
/etc/security
A collection of additional configuration files for specific modules. Some modules, such as pam_access and pam_time , allow additional granularity for checks. When an application configuration file calls these modules, the checks are completed using the additional information from its corresponding supplemental configuration files. Other modules, like pam_pwquality , make it easier for other utilities to modify the configuration by placing all the options in a separate file instead of on the module line in the application configuration file.
/var/log/secure
Most security and authentication errors are reported to this log file. Permissions are configured on this file to restrict access.
man pam
This man page describes the overall process, including the types of calls and a list of files involved.
man pam.conf
This man page describes the overall format and defines keywords and fields for the pam.d configuration files.
man -k pam_
This search of man pages lists pages available for modules installed.
Wrap up
PAM allows for a much more robust authentication environment than per-application services could provide. It has been in Linux for many, many years, and is involved with nearly all user identification processes.
In the next article, I will walk through the format of the /etc/pam.d configuration files.
Источник