Nslcd linux что это
5. Настройка аутентификации пользователей через OpenLDAP на клиенте
Где работаем: ldap-client
Перейдём к настройке клиентской рабочей станции. Для начала установим необходимые пакеты:
Прежде чем делать запросы к LDAP-серверу, проверим параметры клиента в /etc/ldap/ldap.conf:
Конечно, для того, чтобы всё заработало, сертификат нашего Certificate Authority (rootca.crt) и CRL-файл (rootca.crl) должны быть на месте.
Проверим работоспособность простым запросом. Результат опустим (Вы должны увидеть всё DIT):
Краткое описание использованных директив:
Поменяем права доступа к nslcd.conf, потому что теперь в нём хранится информация для аутентификации:
Проверим содержимое /etc/nsswitch.conf:
Убедимся в том, что демон nslcd запускается при старте системы и перезапустим его:
Убедимся, что в системе ldap-client НЕТ учётной записи с именем nssproxy. Следующая команда должна выполняться без результата:
Убедимся так же, что кэширующий демон службы имён загружается при старте системы и перезапустим его:
Сделаем пару запросов к LDAP-серверу, используя настроенную нами систему:
Для того, чтобы проверить доступность информации о пароле потребуется выполнить getent от имени пользователя root:
Не беспокойтесь, хэш пароля мы видеть не должны.
Отлично, всё работает! Вышеприведённые результаты команд означают, что система ldap-client может осуществлять поиск по данным пользователей и групп в нашем каталоге OpenLDAP.
Создадим домашний каталог нашего тестового пользователя и установим для него права доступа:
Запустим в отдельном терминале вывод журнала аутентификации:
В другом терминале выполним:
Мы должны получить приглашение командной строки пользователя test.user.
Теперь попробуем зайти на машину ldap-client по сети с использованием ssh под учётной записью test.user.
Демон ssh в конфигурации по-умолчанию должен работать с поддержкой PAM (и, соответственно, поддерживать аутентификацию через LDAP). Но на всякий случай приведём рабочую конфигурацию /etc/ssh/sshd_config:
Проверим работу с использованием какой-нибудь третьей машины. Например, выполним на нашем DNS-сервере (dns-srv):
Вывод последней команды сокращён. Если появляется приглашение командной строки, значит всё в порядке!
Где работаем: ldap-srv
Давайте заглянем в /var/log/slapd.log на нашем сервере. Мы можем обнаружить там следующие строки:
С помощью следующей команды мы можем убедиться, что в нашем каталоге пока нет никаких индексов:
Это значит, что в нашей базе данных надо создать индексы для атрибутов из журнала /var/log/slapd.log. Поэтому создадим ещё один LDIF-файл 5-posixAccount.indexes.ldif и запишем в него:
Зачем мелочиться? Укажем по-больше индексируемых атрибутов. И загрузим конфигурацию в наш каталог:
Проверим результат изменений:
Отлично! Теперь в журнале /var/log/slapd.log не должно быть ошибок.
OpenLDAP и Ubuntu на практике > Настройка аутентификации пользователей через OpenLDAP на клиенте
За пределами nss_ldap, или Еще о методах авторизации
Архив номеров / 2015 / Выпуск №4 (149) / За пределами nss_ldap, или Еще о методах авторизации
В пакет входят пара библиотек libnss_ldap.so, конфигурационный файл nslcd.conf, стартовый скрипт nclsd и немного документации и мануалов. Во FreeBSD программа устанавливается из портов, из net/nss-pam-ldapd. Устанавливается примерно то же самое, минус документация – только файл образца конфигурации. Конфигурационный файл напоминает файл от nss_ldap и рассматриваться будет в том же порядке, что и ldap.conf, – то есть описываться будут только параметры, которые были настроены, потому что всего в нем параметров очень много. Желающие могут прочитать man nslcd.conf [5]. Статью целиком читайте в журнале «Системный администратор», №4 за 2015 г. на страницах 04-08. PDF-версию данного номера можно приобрести в нашем магазине. DescriptionThe file T contains the configuration information for running nslcd (see nslcd(8)). The file contains options, one on each line, defining the way NSS lookups are mapped onto LDAP lookups. OptionsRuntime OptionsGeneral Connection OptionsWhen using the ldapi scheme, %2f should be used to escape slashes (e.g. ldapi://%2fvar%2frun%2fslapd%2fldapi/), although most of the time this should not be needed. This option may be specified multiple times. Normally, only the first server will be used with the following servers as fall-back (see T below). If LDAP lookups are used for host name resolution, any host names should be specified as an IP address or name that can be resolved without using LDAP. T VERSION Specifies the version of the LDAP protocol to use. The default is to use the maximum version supported by the LDAP library. T DN Specifies the distinguished name with which to bind to the directory server for lookups. The default is to bind anonymously. T PASSWORD Specifies the clear text credentials with which to bind. This option is only applicable when used with T above. If you set this option you should consider changing the permissions of the T file to only grant access to the root user. T DN Specifies the distinguished name to use when the root user tries to modify a user’s password using the PAM module. The PAM module prompts the user for the admin password instead of the user’s password. Kerberos Authentication OptionsSearch/Mapping OptionsA global search base may be specified or a MAP-specific one. If no MAP-specific search bases are defined the global ones are used. If, instead of a DN, the value DOMAIN is specified, the host’s DNS domain is used to construct a search base. If the NEWATTRIBUTE is presented in quotes («) it is treated as an expression which will be evaluated to build up the actual value used. See the section on attribute mapping expressions below for more details. Timing/Reconnect OptionsNote that the reconnect logic as described above is the mechanism that is used between nslcd and the LDAP server. The mechanism between the NSS client library and nslcd is simpler with a fixed compiled-in time out of a 10 seconds for writing to nslcd and a time out of 60 seconds for reading answers. nslcd itself has a read time out of 0.5 seconds and a write time out of 60 seconds. Ssl/Tls OptionsOther OptionsThis is useful for LDAP servers that contain a lot of entries (e.g. more than 500) and limit the number of entries that are returned with one request. For OpenLDAP servers you may need to set T for allowing more entries to be returned over multiple pages. T user1,user2. This option prevents group membership lookups through LDAP for the specified users. This can be useful in case of unavailability of the LDAP server. This option may be specified multiple times. The regular expression should be specified as a POSIX extended regular expression. The expression itself needs to be separated by slash (/) characters and the ‘i’ flag may be appended at the end to indicate that the match should be case-insensitive. The default value is T For example, to check that the user has a proper authorizedService value if the attribute is present: T The default behaviour is not to do this extra search and always grant access. Supported MapsAttribute Mapping ExpressionsThe expressions are a subset of the double quoted string expressions in the Bourne (POSIX) shell. Instead of variable substitution, attribute lookups are done on the current entry and the attribute value is substituted. The following expressions are supported: T (or T for short) will substitute the value of the attribute T (use default) will substitbute the value of the attribute or, if the attribute is not set or empty substitute the word T (use alternative) will substitbute word if attribute is set, otherwise substitute the empty string The nslcd daemon checks the expressions to figure out which attributes to fetch from LDAP. Some examples to demonstrate how these expressions may be used in attribute mapping: T use the T attribute, using the value 0 as default T use the T attribute to build a T value if that attribute is missing T if the T attribute is set, return 100, otherwise leave value empty Arthur de JongOpen Source / Free Software developer Use an LDAP server for identity and authentication management on unix systems. nslcd.conf(5) manual pagenslcd.conf — configuration file for LDAP nameservice daemon DescriptionThe file nslcd.conf contains the configuration information for running nslcd (see nslcd (8) ). The file contains options, one on each line, defining the way NSS lookups and PAM actions are mapped to LDAP lookups. OptionsRuntime optionsThis specifies the user id with which the daemon should be run. This can be a numerical id or a symbolic value. If no uid is specified no attempt to change the user will be made. Note that you should use values that don’t need LDAP to resolve. This specifies the group id with which the daemon should be run. This can be a numerical id or a symbolic value. If no gid is specified no attempt to change the group will be made. Note that you should use values that don’t need LDAP to resolve. General connection optionsWhen using the ldapi scheme, %2f should be used to escape slashes (e.g. ldapi://%2fvar%2frun%2fslapd%2fldapi/ ), although most of the time this should not be needed. This option may be specified multiple times and/or with more URIs on the line, separated by spaces. Normally, only the first server will be used with the following servers as fall-back (see bind_timelimit below). Specifies the distinguished name with which to bind to the directory server for lookups. The default is to bind anonymously. Specifies the credentials with which to bind. This option is only applicable when used with binddn above. If you set this option you should consider changing the permissions of the nslcd.conf file to only grant access to the root user. Specifies the distinguished name to use when the root user tries to modify a user’s password using the PAM module. Note that currently this DN needs to exist as a real entry in the LDAP directory. Specifies the credentials with which to bind if the root user tries to change a user’s password. This option is only applicable when used with rootpwmoddn above. If this option is not specified the PAM module prompts the user for this password. If you set this option you should consider changing the permissions of the nslcd.conf file to only grant access to the root user. SASL authentication optionsSpecifies the authentication identity to be used when performing SASL authentication. Kerberos authentication optionsSet the name for the GSS-API Kerberos credentials cache. Search/mapping optionsA global search base may be specified or a MAP-specific one. If no MAP-specific search bases are defined the global ones are used. If this value is not defined an attempt is made to look it up in the configured LDAP server. If the LDAP server is unavailable during start-up nslcd will not start. scope [ MAP ] sub[ tree ]|one[ level ]|base|children Specifies the search scope (subtree, onelevel, base or children). The default scope is subtree; base scope is almost never useful for name service lookups; children scope is not supported on all servers. Specifies the policy for dereferencing aliases. The default policy is to never dereference aliases. Specifies whether automatic referral chasing should be enabled. The default behaviour is to chase referrals. map MAP ATTRIBUTE NEWATTRIBUTE If the NEWATTRIBUTE is presented in quotes («) it is treated as an expression which will be evaluated to build up the actual value used. See the section on attribute mapping expressions below for more details. The uidNumber and gidNumber attributes in the passwd and group maps may be mapped to the objectSid followed by the domain SID to derive numeric user and group ids from the SID (e.g. objectSid:S-1-5-21-3623811015-3361044348-30300820 ). By default all userPassword attributes are mapped to the unmatchable password («*») to avoid accidentally leaking password information. Timing/reconnect optionsSpecifies the time limit (in seconds) to use when connecting to the directory server. This is distinct from the time limit specified in timelimit and affects the set-up of the connection only. Note that not all LDAP client libraries have support for setting the connection time out. The default bind_timelimit is 10 seconds. Specifies the period of inactivity (in seconds) after which the connection to the LDAP server will be closed. The default is not to time out connections. Централизованная аутентификация с использованием OpenLDAPДанное руководство знакомит с основами LDAP и описывает, как можно настроить OpenLDAP для осуществления аутентификации в рамках группы компьютеров. ContentsВведение в OpenLDAPЧто такое LDAP?LDAP означает Легковесный протокол доступа к каталогу (Lightweight Directory Access Protocol). Основанный на X.500, он включает в себя большую часть его основных функций, за исключением более редких, которые есть у X.500. Что же такое X.500 и зачем нужен LDAP? X.500 является моделью для сервисов каталога (Directory Services) в концепции OSI. Он содержит определения пространства имен (namespace) и протоколы для запросов и обновления каталога. Однако, существует немало случаев, когда полноценная функциональность X.500 не требуется. Встречайте LDAP. Как и X.500, он обеспечивает модель данные/пространство имен для каталога и протокола. Однако LDAP разработан для прямой работы через стек TCP/IP. Можно считать LDAP сокращенной версией X.500. Что такое каталог (directory)?Каталог — это специализированная база данных, созданная для частых запросов, но нечастых обновлений. В отличие от обычных баз данных, каталог не поддерживает транзакции (transaction) или функциональности отката (roll-back). Каталоги легко дублируются для улучшения доступности и надежности. При дублировании каталогов допускаются временные противоречия при условии, что позже они будут синхронизированы. Как осуществляется структурирование информации?Вся информация в каталоге структурирована иерархически. Более того, для того, чтобы внести данные в каталог, каталог должен знать, как хранить эти данные в дереве. Рассмотрим вымышленную компанию и дерево, подобное Интернет: Поскольку данные не записываются в базу в подобной манере ascii-art, каждый элемент этого дерева должен быть определен. Для названий элементов LDAP использует схему наименований. Большая часть дистрибутивов LDAP (включая OpenLDAP) включает в себя определенное количество предопределенных (и одобренных) схем, таких как inetOrgPerson, или часто используемая схема для определения пользователей, которую могут использовать Unix/Linux-системы, которая называется posixAccount. Существуют утилиты графического интерфейса, основанные на веб, для упрощения управления LDAP: раздел Работа с OpenLDAP содержит неполный список таких утилит. Заинтересованным пользователям рекомендуется прочитать OpenLDAP Admin Guide. Для чего же его можно использовать?LDAP можно использовать для разнообразных нужд. В этой статье описывается централизованное управление пользователями, хранение всех учетных записей пользователей в одном местонахождении LDAP (что не означает, что оно находится на одном сервере — LDAP поддерживает высокую доступность (high availability) и резервирование (redundancy)), однако LDAP может использоваться и в других целях. Настройка сервера OpenLDAPОбщие примечанияUSE flags for net-nds/openldap LDAP suite of application and development toolsOpenLDAP поддерживает два механизма аутентификации: Although the OpenLDAP default is to use SASL, the initial version of this article used only password-based authentication. With the OLC add-on the article starts to describe the use of the simplest SASL mechanism called EXTERNAL, which relies on the system authentication. У OpenLDAP есть основной пользователь, «rootdn» (Root Distinguished Name), встроенный в приложение. В отличие от традиционного пользователя root Unix, пользователю rootdn необходимо предоставить соответствующие права доступа. Пользователя rootdn можно использовать только в контексте конфигурации, однако его также можно использовать в определении каталога. В этом случае пользователь может аутентифицироваться как rootdn либо с помощью пароля конфигурации, либо с помощью пароля дерева (основанного на каталоге). В целях верификации, пароли пользователей (как пользователей rootdn, так и других) можно хранить в виде простого текста, либо в хешированном (hashed) виде. Доступно несколько хеш-алгоритмов, но не рекомендуется использовать слабые алгоритмы (вплоть до MD5). На данный момент, SHA считается достаточно безопасным с точки зрения криптографии. В нижеприведенной команде хешированное значение создается для данного пароля; результат этой команды можно использовать в файле конфигурации slapd.conf либо во внутреннем определении пользователя в каталоге: Устаревшая конфигурация (через slapd.conf)Для более подробного анализа файла конфигурации рекомендуем изучить OpenLDAP Administrator’s Guide, хотя man 5 slapd.conf будет достаточно. Если не запускается, первое, что вы должны сделать, это проверить файл конфигурации. Это можно сделать с помощью следующей команды. By default slapd writes the log events to the local4 syslog facility. Миграция с slapd.conf на OLCВ нижеследующем примере показано, как можно предоставить доступ для управления к OLC (база данных cn=config) для системного администратора (пользователя root), добавив соответствующие строки в конец файла slapd.conf : Для дополнительных инструкций прочитайте in-line комментарии сгенерированных файлов. Наконец, создайте структуру /var/lib/openldap-data : Initial setup with OLCThis initial configuration can be loaded (and only loaded, unlike ordinary LDAP databases) by the slapadd utility: When using a root account, be sure to correct ownership of the files created by root, as described below in migrate section. For the right to change the configuration database, proper permissions must be provided. The next example shows how these privileges are granted to the root system user: When using OLC, never manually edit the configuration files. The directory files can be used to check the consistency of the configuration through: Обслуживание каталогаПосле завершения конфигурации запустите slapd : Большинство пользователей также захотят запускать демон OpenLDAP автоматически: Теперь можно использовать сервер каталога для аутентификации пользователей в apache/proftpd/qmail/samba. The directory server can be managed with tools such as net-nds/phpldapadmin, app-admin/diradm and net-nds/jxplorer from the Gentoo ebuild repository, or app-misc/ldapexplorertool from the poly-c overlay available through Layman or eselect repository. Server management with OLCНиже приводится несколько примеров обновления конфигурации в стиле OLC. Например, чтобы изменить местонахождение каталога конфигурации OLC (необходимо после миграции с конфигурационного файла на каталог конфигураций): Чтобы изменить уровень журнала, используемого процессом OpenLDAP: Чтобы применить изменения, запустите следующую команду: Журналирование в OpenLDAPOpenLDAP produces numerous log events, which might not be obvious to interpret, but are necessary for debugging purposes. As OpenLDAP by default writes the log events into the system log, it is advisable to reconfigure the system logger to direct OpenLDAP log events into a dedicated log file. It is advisable to use the stats stats2 log level in OpenLDAP standalone server and stats stats2 sync in OpenLDAP cluster. In such case query results logs session-related information such as the following: Most common errors in server log are err=49 : Which means «invalid credentials» (i.e. wrong password). Which means «No such object». Usually this error appears when binddn (user) has no permissions on requested object. So either try to do something wrong, or there is a mistake in the set ACLs. Управление доступом (ACL)Таблица ниже показывает уровни доступа доступные в OpenLDAP:
For details about the exact privilege settings, see the manual pages and official OpenLDAP documentation. Конфигурационный файлACLs are parsed in the order they are set in the configuration, and are applied based on the specificity (meaning that, when an ACL rule is considered, the remainder of ACL rules is no longer checked). As such, more specific definitions should go first, before more generic ones are listed. For more information, see Access Control Evaluation. Конфигурационный каталогACLs are parsed in the order they are set in the configuration, and are applied based on the specificity (meaning that, when an ACL rule is considered, the remainder of ACL rules is no longer checked). As such, more specific definitions should go first, before more generic ones are listed. This order, when using OLC, is handled through the olcAccess directives. The following example inserts a new ACL on top, making the existing olcAccess entries to shift by one: ДублированиеВысокая доступностьНастройка дублирования изменений на нескольких системах LDAP. В данном руководстве дублирование в OpenLDAP настраивается с помощью специальной учетной записи ( ldapreader ), у которой есть права чтения на основном сервере LDAP и которая загружает изменения с основного сервера на вспомогательный. Replication within OpenLDAP is, in this guide, set up using a specific replication account ( ldapreader ) which has read rights on the primary LDAP server and which pulls in changes from the primary LDAP server to the secondary. Далее эта настройка дублируется, что позволяет вспомогательному серверу LDAP выполнять роль основного. Благодаря внутренней структуре OpenLDAP, если изменения уже присутствуют в структуре LDAP, повторно они не применяются. Настройка дублированияДля того, чтобы настроить дублирование, сначала настройте второй сервер OpenLDAP подобно тому, как описано выше. Однако обратите внимание на то, что в файле конфигурации: Synchronisation accountДалее создайте синхронизационную учетную запись. Создадим файл LDIF (формат, используемый для ввода данных на серверах LDAP) и добавим его на каждом сервере LDAP: Enabling syncprov overlayOverlay can be linked statically and dynamically. When it is built dynamically, you’ll need to load module. For now in Gentoo it’s usually built statically. To ensure type: Load syncprov module (optional)To load syncprov module, use the following ldif file: Setting up replication for databaseNext step, mandatory for everybody, is to setup replication for database (must be done on both nodes): Final configurationFinally, add replication’s definition. secret traditionally means the password string. The only difference is in server’s ident (rid) and provider uri. If LDAP master (mirror node with initially loaded database) is unavailable (slapd daemon not started, or 389/tcp port is blocked by a packet filter) slapd daemon on secondary node fails to start with the following error message: Almost certainly the database will not fit into default limits. So, you will need to increase ldapreader ‘s limits. For example: Performance tuningDefault daemon settings significantly limits LDAP server performance. SymptomsWhen server load fits system limit client applications fails with different kind of timeout errors. In server log this produces error messages like following: Increasing OS limitsFirst, read ldap system user limits: The first parameter, you need to increase, is the open files limit. Maximum available value is described in Documentation/sysctl/fs.txt file of kernel documentation: PAM system limits are stored in /etc/security/limits.conf file or, optionally, in /etc/security/limits.d/ directory. Daemons, started with sys-apps/openrc init system use these parameters (see sys-apps/openrc: start-stop-daemon should use system-services PAM stack for details), so you need just to put in the file: And restart daemon. The next limitation is sysctl ‘s net.core.somaxconn parameter. During run time, this value can be updated via: After verifying new value do not forget to fix it: And, possibly, some other application-specific parameters. Настройка клиентских утилит OpenLDAPОтредактируйте файл конфигурации клиента LDAP. Этот файл читается командой ldapsearch и другими ldap-утилитами командной строки. Запущенный сервер можно протестировать с помощью следующей команды: Настройка клиента для централизованной аутентификацииСуществует целый ряд методов/утилит для осуществления удаленной аутентификации. Некоторые дистрибутивы также предоставляют свои собственные конфигурационные утилиты, легкие в использовании. Ниже приводится ряд утилит в произвольном порядке. Существует возможность одновременного сочетания локальных пользователей и центрально авторизованных учетных записей. Это важно, поскольку, например, если LDAP сервер недоступен, по-прежнему можно войти в систему в качестве пользователя root. Первые два варианта демонстрируются ниже, с минимальным необходимым количеством параметров конфигурации. Настройка клиента PAM метод SSSDЗдесь представлен более краткий метод. Ниже приводятся три файла, которые необходимо отредактировать. Добавьте sss в конце как показано ниже, чтобы включить передачу поиска имени системному сервису sssd. После завершения редактирования запустите демон sssd. Теперь попробуйте войти в систему с другого компьютера. Настройка клиента PAM метод модуль pam_ldapСначала настроим PAM таким образом, чтобы разрешить авторизацию LDAP. Установите sys-auth/pam_ldap, чтобы PAM поддерживал авторизацию LDAP, и sys-auth/nss_ldap, чтобы система могла справиться с серверами LDAP для дополнительной информации (используется файлом nsswitch.conf ). Теперь отредактируйте /etc/ldap.conf следующим образом: Далее скопируйте файл (OpenLDAP) ldap.conf с сервера на клиент, чтобы клиенты знали об окружении LDAP: Наконец, настройте клиентов таким образом, чтобы они проверяли LDAP на наличие системных учетных записей: Перенесение существующих данных на LDAPНастройка OpenLDAP для централизованного администрирования и управления привычными объектами Linux/Unix непроста, но, благодаря некоторым утилитам и сценариям, доступным в Интернете, задача перенесения системы с администрирования одной системы на центрально управляемую систему на основе OpenLDAP не так уж сложна. Затем распакуйте утилиты и скопируйте сценарий make_master.sh в распакованное местонахождение: На момент написания, утилитам требуется следующий ввод:
Утилита также запросит, какие учетные записи и настройки следует перенести. TroubleshootingEmerge errors after conversion to LDAPIf for any reasons local user accounts (i.e. /etc/passwd /etc/shadow) or groups (i.e. /etc/group) are deleted after converting the file userbase to LDAP, errors may be encountered relating to missing user (or group) while emerging certain packages. Example of error while emerging www-servers/apache due to missing «apache» local user account:
|