What is nslcd linux

5. Настройка аутентификации пользователей через OpenLDAP на клиенте

Где работаем: ldap-client

Перейдём к настройке клиентской рабочей станции. Для начала установим необходимые пакеты:

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

  • URI сервера LDAP: ldap://ldap-srv.example.com ;
  • База поиска сервера LDAP: dc=example,dc=com ;
  • Имена настраиваемых служб: group , netgroup , passwd , shadow .

Прежде чем делать запросы к LDAP-серверу, проверим параметры клиента в /etc/ldap/ldap.conf:

Конечно, для того, чтобы всё заработало, сертификат нашего Certificate Authority (rootca.crt) и CRL-файл (rootca.crl) должны быть на месте.

Проверим работоспособность простым запросом. Результат опустим (Вы должны увидеть всё DIT):

Поправим конфигурацию нашей локальной службы имён LDAP в файле /etc/nslcd.conf. Измените значение директивы bindpw на пароль записи cn=nssproxy,ou=users,dc=example,dc=com , который мы задавали ранее:

Краткое описание использованных директив:

  • С помощью директивы base мы сообщаем демону nslcd, где в DIT искать ту или иную информацию;
  • bind_timelimit ограничивает время на установление соединения с сервером пятью секундами;
  • timelimit устанавливает максимальное время ожидания ответа от сервера в 10 секунд;
  • idle_timelimit заставит nslcd разорвать соединение с сервером, если в течении минуты в соединении не было никакой активности;
  • ssl заставляет клиента использовать TLS при подключении к серверу;
  • tls_reqcert и tls_cacertfile подобны директивам TLS_REQCERT и TLS_CACERT в конфигурации /etc/ldap/ldap.conf (необходимость проверки сертификата сервера и путь к корневому сертификату для выполнения проверки);
  • nss_initgroups_ignoreusers описывает пользователей системы, поиск которых не нужно производить в 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:

Часть файла до пустой строки — конфигурация по-умолчанию. Далее — добавленное нами. Обратите внимание на строку с директивой AllowGroups . С помощью неё мы ограничиваем список групп пользователей, которые могут быть аутентифицированы через ssh. За информацией по остальным директивам обратитесь к документации.

Проверим работу с использованием какой-нибудь третьей машины. Например, выполним на нашем 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 на клиенте

Источник

LDAP Authentication and Authorization

Cumulus Linux uses Pluggable Authentication Modules (PAM) and Name Service Switch (NSS) for user authentication. NSS enables PAM to use LDAP to provide user authentication, group mapping, and information for other services on the system.

  • NSS specifies the order of the information sources that are used to resolve names for each service. Using NSS with authentication and authorization provides the order and location for user lookup and group mapping on the system.
  • PAM handles the interaction between the user and the system, providing login handling, session setup, authentication of users, and authorization of user actions.
Читайте также:  Parallel desktops mac os �� �������� ����

There are three common ways to configure LDAP authentication on Linux: you can use libnss-ldap , libnss-ldapd , or libnss-sss . This chapter describes libnss-ldapd only. From internal testing, this library worked best with Cumulus Linux and is the easiest to configure, automate, and troubleshoot.

Install libnss-ldapd

The libldap-2.4-2 and libldap-common LDAP packages are already installed on the Cumulus Linux image; however you need to install these additional packages to use LDAP authentication:

To install the additional packages, run the following command:

You can also install these packages even if the switch is not connected to the internet, as they are contained in the cumulus-local-apt-archive repository that is embedded in the Cumulus Linux image.

Follow the interactive prompts to specify the LDAP URI, search base distinguished name (DN), and services that must have LDAP lookups enabled. You need to select at least the passwd , group , and shadow services (press space to select a service). When done, click OK. This creates a very basic LDAP configuration using anonymous bind and initiates user search under the base DN specified.

After the dialog closes, the install process prints information similar to the following:

After the installation is complete, the name service caching daemon ( nslcd ) runs. This service handles all the LDAP protocol interactions and caches information returned from the LDAP server. ldap is appended in the /etc/nsswitch.conf file, as is the secondary information source for passwd, group, and shadow. The local files ( /etc/passwd , /etc/groups and /etc/shadow ) are used first, as specified by the compat source.

Keep compat as the first source in NSS for passwd, group, and shadow. This prevents you from getting locked out of the system.

Entering incorrect information during the installation process might produce configuration errors. You can correct the information after installation by editing certain configuration files.

  • Edit the /etc/nslcd.conf file to update the LDAP URI and search base DN (see Update the nslcd.conf File, below).
  • Edit the /etc/nssswitch.conf file to update the service selections.

Be sure to restart netd after editing the files.

Instead of running the installer and following the interactive prompts, as described above, you can pre-seed the installer parameters using debconf-utils .

Run apt-get install debconf-utils and create the pre-seeded parameters using debconf-set-selections . Provide the appropriate answers.

to check the settings. Here is an example of how to pre-seed answers to the installer questions using debconf-set-selections :

Update the nslcd.conf File

After installation, update the main configuration file ( /etc/nslcd.conf ) to accommodate the expected LDAP server settings.

This section documents some of the more important options that relate to security and how queries are handled. For details on all the available configuration options, read the nslcd.conf man page.

After first editing the /etc/nslcd.conf file and/or enabling LDAP in the /etc/nsswitch.conf file, you must restart netd with the sudo systemctl restart netd command. If you disable LDAP, you need to restart the netd service.

Connection

The LDAP client starts a session by connecting to the LDAP server on TCP and UDP port 389 or on port 636 for LDAPS. Depending on the configuration, this connection might be unauthenticated (anonymous bind); otherwise, the client must provide a bind user and password. The variables used to define the connection to the LDAP server are the URI and bind credentials.

The URI is mandatory and specifies the LDAP server location using the FQDN or IP address. The URI also designates whether to use ldap:// for clear text transport, or ldaps:// for SSL/TLS encrypted transport. You can also specify an alternate port in the URI. In production environments, the LDAPS protocol is recommended so that all communications are secure.

After the connection to the server is complete, the BIND operation authenticates the session. The BIND credentials are optional, and if not specified, an anonymous bind is assumed. This is typically not allowed in most production environments. Configure authenticated (Simple) BIND by specifying the user ( binddn ) and password ( bindpw ) in the configuration. Another option is to use SASL (Simple Authentication and Security Layer) BIND, which provides authentication services using other mechanisms, like Kerberos. Contact your LDAP server administrator for this information as it depends on the configuration of the LDAP server and the credentials that are created for the client device.

Читайте также:  Хакерское по для линукс

Search Function

When an LDAP client requests information about a resource, it must connect and bind to the server. Then, it performs one or more resource queries depending on the lookup. All search queries sent to the LDAP server are created using the configured search base, filter, and the desired entry (uid=myuser) being searched. If the LDAP directory is large, this search might take a significant amount of time. It is a good idea to define a more specific search base for the common maps (passwd and group).

Search Filters

It is also common to use search filters to specify criteria used when searching for objects within the directory. This is used to limit the search scope when authenticating users. The default filters applied are:

Attribute Mapping

The map configuration allows you to override the attributes pushed from LDAP. To override an attribute for a given map, specify the attribute name and the new value. This is useful to ensure that the shell is bash and the home directory is /home/cumulus :

In LDAP, the map refers to one of the supported maps specified in the manpage for nslcd.conf (such as passwd or group).

Create Home Directory on Login

If you want to use unique home directories, run the sudo pam-auth-update command and select Create home directory on login in the PAM configuration dialog (press the space bar to select the option). Select OK, then press Enter to save the update and close the dialog.

The home directory for any user that logs in (using LDAP or not) is created and populated with the standard dotfiles from /etc/skel if it does not already exist.

When nslcd starts, you might see an error message similar to the following (where 5816 is the nslcd PID):

You can safely ignore this message. The libdb package and resulting log messages from nslcd do not cause any issues when you use LDAP as a client for login and authentication.

Example Configuration

Here is an example configuration using Cumulus Linux.

Configure LDAP Authorization

Linux uses the sudo command to allow non-administrator users (such as the default cumulus user account) to perform privileged operations. To control the users authorized to use sudo, the /etc/sudoers file and files located in the /etc/sudoers.d/ directory define a series of rules. Typically, the rules are based on groups, but can also be defined for specific users. You can add sudo rules using the group names from LDAP. For example, if a group of users are associated with the group netadmin, you can add a rule to give those users sudo privileges. Refer to the sudoers manual ( man sudoers ) for a complete usage description. The following shows an example in the /etc/sudoers file:

Active Directory Configuration

Active Directory (AD) is a fully featured LDAP-based NIS server create by Microsoft. It offers unique features that classic OpenLDAP servers do not have. AD can be more complicated to configure on the client and each version works a little differently with Linux-based LDAP clients. Some more advanced configuration examples, from testing LDAP clients on Cumulus Linux with Active Directory (AD/LDAP), are available in our knowledge base.

LDAP Verification Tools

Typically, password and group information is retrieved from LDAP and cached by the LDAP client daemon. To test the LDAP interaction, you can use these command-line tools to trigger an LDAP query from the device. This helps to create the best filters and verify the information sent back from the LDAP server.

Identify a User with the id Command

The id command performs a username lookup by following the lookup information sources in NSS for the passwd service. This simply returns the user ID, group ID and the group list retrieved from the information source. In the following example, the user cumulus is locally defined in /etc/passwd , and myuser is on LDAP. The NSS configuration has the passwd map configured with the sources compat ldap :

getent

The getent command retrieves all records found with NSS for a given map. It can also retrieve a specific entry under that map. You can perform tests with the passwd , group , shadow , or any other map configured in the /etc/nsswitch.conf file. The output from this command is formatted according to the map requested. For the passwd service, the structure of the output is the same as the entries in /etc/passwd . The group map outputs the same structure as /etc/group .

Читайте также:  Драйвера m2npv vm windows

In this example, looking up a specific user in the passwd map, the user cumulus is locally defined in /etc/passwd , and myuser is only in LDAP.

In the next example, looking up a specific group in the group service, the group cumulus is locally defined in /etc/groups , and netadmin is on LDAP.

Running the command getent passwd or getent group without a specific request returns all local and LDAP entries for the passwd and group maps.

The ldapsearch command performs LDAP operations directly on the LDAP server. This does not interact with NSS. This command helps display what the LDAP daemon process is receiving back from the server. The command has many options. The simplest option uses anonymous bind to the host and specifies the search DN and the attribute to look up.

To use NCLU, a user must be in either the netshow or netedit NCLU group in the LDAP database. You can either:

  • Add a user or one of their groups to the /etc/netd.conf file manually.
  • Add a user to the local /etc/group file as a member of the netshow or netedit groups.

In the following example, a user that is not in the netshow or netedit NCLU group in the LDAP database runs the NCLU net show version command, which produces an error:

To add user to the netshow or netedit NCLU group in the LDAP database, either edit the /etc/group file manually or use the sudo adduser USERNAME netshow command, then restart netd . For example, to add the user bill to the netshow group:

Now, the user can run the NCLU net show commands successfully:

LDAP Browsers

There are several GUI LDAP clients available that help you work with LDAP servers. These are free tools that show the structure of the LDAP database graphically.

Troubleshooting

nslcd Debug Mode

When setting up LDAP authentication for the first time, turn off the nslcd service using the systemctl stop nslcd.service command (or the systemctl stop nslcd@mgmt.service if you are running the service in a management VRF) and run it in debug mode. Debug mode works whether you are using LDAP over SSL (port 636) or an unencrypted LDAP connection (port 389).

After you enable debug mode, run the following command to test LDAP queries:

If LDAP is configured correctly, the following messages appear after you run the getent command:

In the output above,

indicates that the entire directory structure is queried.

You can query a specific user with the following command:

You can replace myuser with any username on the switch. The following debug output indicates that user myuser exists:

Common Problems

SSL/TLS

  • The FQDN of the LDAP server URI does not match the FQDN in the CA-signed server certificate exactly.
  • nslcd cannot read the SSL certificate and reports a Permission denied error in the debug during server connection negotiation. Check the permission on each directory in the path of the root SSL certificate. Ensure that it is readable by the nslcd user.

If the nscd cache daemon is also enabled and you make some changes to the user from LDAP, you can clear the cache using the following commands:

The nscd package works with nslcd to cache name entries returned from the LDAP server. This might cause authentication failures. To work around these issues, disable nscd , restart the nslcd service, then retry authentication:

If you are running the nslcd service in a management VRF, you need to run the systemctl restart nslcd@mgmt.service command instead of the systemctl restart nslcd.service command. For example:

The search filter returns incorrect results. Check for typos in the search filter. Use ldapsearch to test your filter.

Optionally, configure the basic LDAP connection and search parameters in /etc/ldap/ldap.conf .

When a local username also exists in the LDAP database, the order of the information sources in /etc/nsswitch can be updated to query LDAP before the local user database. This is generally not recommended. For example, the configuration below ensures that LDAP is queried before the local database.

Источник

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