Централизованная аутентификация с использованием OpenLDAP

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Centralized authentication using OpenLDAP and the translation is 48% complete.
Outdated translations are marked like this.
The information in this article is probably outdated. You can help the Gentoo community by verifying and updating this article.

Данное руководство знакомит с основами LDAP и описывает, как можно настроить OpenLDAP для осуществления аутентификации в рамках группы компьютеров.

Предупреждение
The current state does not yield a working configuration. See Talk:Centralized_authentication_using_OpenLDAP for details. Work is in progress.

Введение в 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). Каталоги легко дублируются для улучшения доступности и надежности. При дублировании каталогов допускаются временные противоречия при условии, что позже они будут синхронизированы.

Как осуществляется структурирование информации?

Вся информация в каталоге структурирована иерархически. Более того, для того, чтобы внести данные в каталог, каталог должен знать, как хранить эти данные в дереве. Рассмотрим вымышленную компанию и дерево, подобное Интернет:

КОД Организационная структура для GenFic, вымышленное сообщество Gentoo (Fictional Gentoo community)
dc:         org
             |
dc:        genfic         ## (Организация)
          /      \
ou:    Люди    серверы    ## (Организационные единицы)
      /    \     ..
uid: ..   John            ## (Специфические данные OU)

Поскольку данные не записываются в базу в подобной манере ascii-art, каждый элемент этого дерева должен быть определен. Для названий элементов LDAP использует схему наименований. Большая часть дистрибутивов LDAP (включая OpenLDAP) включает в себя определенное количество предопределенных (и одобренных) схем, таких как inetOrgPerson, или часто используемая схема для определения пользователей, которую могут использовать Unix/Linux-системы, которая называется posixAccount. Существуют утилиты графического интерфейса, основанные на веб, для упрощения управления LDAP: раздел Работа с OpenLDAP содержит неполный список таких утилит.

Заинтересованным пользователям рекомендуется прочитать OpenLDAP Admin Guide.

Для чего же его можно использовать?

LDAP можно использовать для разнообразных нужд. В этой статье описывается централизованное управление пользователями, хранение всех учетных записей пользователей в одном местонахождении LDAP (что не означает, что оно находится на одном сервере — LDAP поддерживает высокую доступность (high availability) и резервирование (redundancy)), однако LDAP может использоваться и в других целях.

  • инфраструктура открытых ключей
  • общий календарь
  • общая адресная книга
  • хранилище для DHCP, DNS, ...
  • System Class Configuration Directives (отслеживание нескольких конфигураций сервера)
  • централизованная аутентификация (PosixAccount)
  • ...

Настройка сервера OpenLDAP

Общие примечания

Это руководство использует домен genfic.org в качестве примера. Естественно, вам нужно будет изменить это название. Однако убедитесь, что верхний элемент является официальным доменом верхнего уровня (net, com, cc, be, ...).

USE flags for net-nds/openldap LDAP suite of application and development tools

argon2 Enable password hashing algorithm from app-crypt/argon2
autoca Automatic Certificate Authority overlay
berkdb Add support for sys-libs/db (Berkeley DB for MySQL)
cleartext Enable use of cleartext passwords
crypt Add support for encryption -- using mcrypt or gpg where applicable
cxx Build support for C++ (bindings, extra libraries, code generation, ...)
debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
experimental Enable experimental backend options
gnutls Prefer net-libs/gnutls as SSL/TLS provider (ineffective with USE=-ssl)
iodbc Add support for iODBC library
ipv6 Add support for IP version 6
kerberos Add kerberos support
kinit Enable support for kerberos init
minimal Build libraries & userspace tools only. Does not install any server code
odbc Enable ODBC and SQL backend options
overlays Enable contributed OpenLDAP overlays
pbkdf2 Enable support for pbkdf2 passwords
perl Add optional support/bindings for the Perl language
samba Add support for SAMBA (Windows File and Printer sharing)
sasl Add support for the Simple Authentication and Security Layer
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
sha2 Enable support for pw-sha2 password hashes
smbkrb5passwd Enable overlay for syncing ldap, unix and lanman passwords
ssl Add support for SSL/TLS connections (Secure Socket Layer / Transport Layer Security)
static-libs Build static versions of dynamic libraries as well
syslog Enable support for syslog
systemd Enable use of systemd-specific libraries and features like socket activation or session tracking
tcpd Add support for TCP wrappers
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)

Сначала установим OpenLDAP. Убедитесь в том, что USE-флаги syslog, -minimal (отключено) и tcpd установлены.

root #emerge --ask net-nds/openldap

OpenLDAP поддерживает два механизма аутентификации:

  1. стандартный пользователь/пароль (в терминологии LDAP пользователь подразумевает binddn), называемый SIMPLE
  2. запросы проксирования авторизации SASL (Simple Authentication and Security Layer, смотрите RFC4422)

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. This is only limited to the host the server runs on.

У OpenLDAP есть основной пользователь, "rootdn" (Root Distinguished Name), встроенный в приложение. В отличие от традиционного пользователя root Unix, пользователю rootdn необходимо предоставить соответствующие права доступа. Пользователя rootdn можно использовать только в контексте конфигурации, однако его также можно использовать в определении каталога. В этом случае пользователь может аутентифицироваться как rootdn либо с помощью пароля конфигурации, либо с помощью пароля дерева (основанного на каталоге).

В целях верификации, пароли пользователей (как пользователей rootdn, так и других) можно хранить в виде простого текста, либо в хешированном (hashed) виде. Доступно несколько хеш-алгоритмов, но не рекомендуется использовать слабые алгоритмы (вплоть до MD5). На данный момент, SHA считается достаточно безопасным с точки зрения криптографии.

В нижеприведенной команде хешированное значение создается для данного пароля; результат этой команды можно использовать в файле конфигурации slapd.conf либо во внутреннем определении пользователя в каталоге:

root #slappasswd
New password: my-password
Re-enter new password: my-password
{SSHA}EzP6I82DZRnW+ou6lyiXHGxSpSOw2XO4

Устаревшая конфигурация (через slapd.conf)

Предупреждение
Do not use this anymore in 2021. It is also not the foundation to be transformed to LDIF with OpenLDAP tools. It will not be translated correctly.

Теперь отредактируйте конфигурацию сервера LDAP в файле /etc/openldap/slapd.conf. Предоставленный файл slapd.conf, взят из оригинального архива исходного кода OpenLDAP. Ниже приведен пример файла конфигурации, которым его можно заменить.

ФАЙЛ /etc/openldap/slapd.conf
include	/etc/openldap/schema/core.schema
include /etc/openldap/schema/cosine.schema
include /etc/openldap/schema/inetorgperson.schema
include /etc/openldap/schema/nis.schema
include	/etc/openldap/schema/misc.schema
 
pidfile  /var/run/openldap/slapd.pid
argsfile /var/run/openldap/slapd.args
 
## ## ServerID, используемый в случае дублирования
serverID 0 
loglevel 0
 
## ## Раздел Certificate/SSL
TLSCipherSuite normal
TLSCACertificateFile /etc/openldap/ssl/ldap.crt
TLSCertificateFile /etc/openldap/ssl/ldap.pem
TLSCertificateKeyFile /etc/openldap/ssl/ldap.key
TLSVerifyClient never
 
## ## Управление доступом
access to dn.base="" by * read
access to dn.base="cn=Subschema" by * read
access to *
  by self write
  by users read
  by anonymous read
 
## ## Определение базы данных
database mdb
suffix "dc=genfic,dc=org"
checkpoint 32 30
maxsize 10485760
#Заметка: важно установить как можно большее значение, насколько это возможно,
#(относительно ожидаемого роста фактических данных с течением времени)
#так как увеличение размера позже может оказаться нецелесообразным, когда система уже находится под большой нагрузкой.
 
rootdn "cn=Manager,dc=genfic,dc=org"
## ## rootpwd, сгенерированный ранее с помощью команды slappasswd
rootpw "{SSHA}EzP6I82DZRnW+ou6lyiXHGxSpSOw2XO4" 
directory "/var/lib/openldap-data"
index objectClass eq
 
## ## Синхронизация (с другим сервером LDAP)
syncrepl rid=001
  provider=ldap://ldap2.genfic.org
  type=refreshAndPersist
  retry="5 5 300 +"
  searchbase="dc=genfic,dc=org"
  attrs="*,+"
  bindmethod="simple"
  binddn="cn=ldapreader,dc=genfic,dc=org"
  credentials="ldapsyncpass"
 
index entryCSN eq
index entryUUID eq
 
mirrormode TRUE
 
overlay syncprov
syncprov-checkpoint 100 10
Заметка
Don't forget, the second node must use different value of rid and proper address in provider ldapuri.

Для более подробного анализа файла конфигурации рекомендуем изучить OpenLDAP Administrator's Guide, хотя man 5 slapd.conf будет достаточно.

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

user $slaptest -v -d 1 -f /etc/openldap/slapd.conf

Измените уровень отладки ("-d 1" выше), чтобы получить больше информации. Если все в порядке, будет отображено сообщение config file testing succeeded. В случае ошибки, slaptest выведет номер строки в файле slapd.conf, содержащей ошибку.

By default slapd writes the log events to the local4 syslog facility.

Предупреждение
Обратите внимание, что, начиная с версии 2.4.23, OpenLDAP перешел с традиционных файлов конфигурации (slapd.conf) на OLC (OnLineConfiguration, также известный по структуре cn=config), в качестве метода конфигурации, используемого по умолчанию. Одно из преимуществ использования OLC в том, что динамический backend (cn=config) не требует перезапуска сервера после обновления конфигурации. Существующие пользователи могут перейти на новый метод конфигурации, запустив команду slaptest одновременно с параметрами -f и -F. По традиции, OLC хранится в ldif backend (что сохраняет преимущества удобочитаемости для человека) в каталоге /etc/openldap/slapd.d. В Gentoo преобразование конфигурации пока не требуется, однако поддержка на данный момент документированного подхода в будущем будет убрана.

Миграция с slapd.conf на OLC

Предупреждение
The following section is totally unusable and will be improved soon. Instead follow any decent basic LDIF based setup guide tosetup the objectClass: olcGlobal setup objectClass: moduleList, back_mdb.so or back_bdb.la, depending on USE setup objectClass: olcSchemaConfig, nis.ldif and such database config for tree, incl. reader role, denying anonymous reads and so on create a base DN/ objectclass=organization, without it tools like phpldapadmin will not work at all setup organizational units to group objectClass further, sane substructure with Person, Group import relevant Gentoo groups, e.g. wheel, audio, usb, desktop users with these will be rather limited use a tool, even only temporarily, to create one or two more users

Чтобы иметь возможность изменения конфигурации сервера OpenLDAP, необходимо определить как минимум доступ для записи write (или, как правило, для управления manage) в cn=config.

В нижеследующем примере показано, как можно предоставить доступ для управления к OLC (база данных cn=config) для системного администратора (пользователя root), добавив соответствующие строки в конец файла slapd.conf:

ФАЙЛ /etc/openldap/slapd.confПредоставление прав управления пользователю Linux root в cn=config
database config
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

Затем, мы вызываем утилиту slaptest с параметрами -f и -F чтобы сконвертировать файл slapd.conf в каталог конфигураций (slapd.d).

root #mkdir /etc/openldap/slapd.d
root #slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d
root #chown -R ldap /etc/openldap/slapd.d

Запуск этой команды переместит и преобразует конфигурацию. После этого предполагается обновление конфигурации с помощью специально подготовленных файлов ldif. Лишь в том случае, если вы с ними не знакомы, следует редактировать slapd.conf и повторно преобразовать его в slapd.d/. Не забудьте проверить права доступа каталога.

Для дополнительных инструкций прочитайте in-line комментарии сгенерированных файлов.

Нижеприведенная строка включает метод конфигурации slapd.d/.

ФАЙЛ /etc/conf.d/slapd
OPTS="-F /etc/openldap/slapd.d -h 'ldaps:// ldap:// ldapi://%2fvar%2frun%2fopenldap%2fslapd.sock'"

Наконец, создайте структуру /var/lib/openldap-data:

root #mkdir -p /var/lib/openldap-data
root #chown -R ldap:ldap /var/lib/openldap-data
root #chmod -R 0700 /var/lib/openldap-data

Initial setup with OLC

An initial configuration is shipped as a standard LDAP database dump, available as slapd.ldif or config.ldif.

Предупреждение
To include additional schemas, flat schema files should be converted into ldif format. Custom scheme must also be converted into ldif format. See openldap.ldif for more detailed description.
Предупреждение
{{{1}}}

This initial configuration can be loaded (and only loaded, unlike ordinary LDAP databases) by the slapadd utility:

root #slapadd -d -1 -F /etc/openldap/slapd.d -n 0 -l /etc/openldap/config.ldif

When using a root account, be sure to correct ownership of the files created by root, as described below in migrate section.

Предупреждение
The default configuration does not provide permissions to change the server's configuration to anybody.

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:

ФАЙЛ config-access.ldif
# {0}config, config
dn: olcDatabase={0}config,cn=config
objectClass: olcDatabaseConfig
olcDatabase: {0}config
olcAccess: {0}to *  by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage  by * none
olcAddContentAcl: TRUE
olcLastMod: TRUE
olcMaxDerefDepth: 15
olcReadOnly: FALSE
olcRootDN: cn=config
olcSyncUseSubentry: FALSE
olcMonitoring: FALSE

Для более подробной информации смотрите man 5 slapd-config.

Предупреждение
This database configuration must be added between dn: olcDatabase=frontend,cn=config and dn: olcDatabase=mdb,cn=config, because each part requires the previous to exist and creates a default one if not.

When using OLC, never manually edit the configuration files. The directory files can be used to check the consistency of the configuration through:

root #slaptest -v -d 1 -F /etc/openldap/slapd.d

Обслуживание каталога

После завершения конфигурации запустите slapd:

root #service slapd start

Большинство пользователей также захотят запускать демон OpenLDAP автоматически:

root #rc-update add slapd

Теперь можно использовать сервер каталога для аутентификации пользователей в 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 eselect repository.

Server management with OLC

Заметка
One of the benefits of using OLC-style configuration is that the LDAP server does not require a restart to apply configuration changes.

Ниже приводится несколько примеров обновления конфигурации в стиле OLC.

Например, чтобы изменить местонахождение каталога конфигурации OLC (необходимо после миграции с конфигурационного файла на каталог конфигураций):

ФАЙЛ fix-configs.ldif
dn: cn=config
changetype: modify
delete: olcConfigFile
dn: cn=config
changetype: modify
replace: olcConfigDir
olcConfigDir: /etc/openldap/slapd.d

Чтобы изменить уровень журнала, используемого процессом OpenLDAP:

ФАЙЛ loglevel.ldif
dn: cn=config
changetype: modify
replace: olcLogLevel
olcLogLevel: stats stats2 sync

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

root #ldapmodify -Y EXTERNAL -H ldapi:/// -f loglevel.ldif
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
modifying entry "cn=config"
Предупреждение
On restart, the init script performs a check of the updated configuration. The ldapmodify command used above blocks only fatal errors. To get info about non-fatal errors using OLC:
root #slaptest -F /etc/openldap/slapd.d
58b7d4c2 olcThreads: value #0: warning, threads=64 larger than twice the default (2*16=32); YMMV.
config file testing succeeded

Журналирование в OpenLDAP

OpenLDAP 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:

root #grep conn=1 /var/log/slapd.log
Mar  9 12:26:47 ldap1 slapd[95182]: conn=1 fd=14 ACCEPT from IP=192.168.100.9:55655 (IP=192.168.1.1:389)
Mar  9 12:26:47 ldap1 slapd[95182]: conn=1 op=0 BIND dn="" method=128
Mar  9 12:26:47 ldap1 slapd[95182]: conn=1 op=0 RESULT tag=97 err=0 text=
Mar  9 12:26:47 ldap1 slapd[95182]: conn=1 op=1 SRCH base="ou=People,dc=genfic,dc=org" scope=1 deref=0 filter="(&(objectClass=posixAccount)(uidNumber=1001))"
Mar  9 12:26:47 ldap1 slapd[95182]: conn=1 op=1 SRCH attr=uid userPassword uidNumber gidNumber cn homeDirectory loginShell gecos description objectClass shadowLastChange shadowMax shadowExpire
Mar  9 12:26:47 ldap1 slapd[95182]: conn=1 op=1 ENTRY dn="uid=larry,ou=People,dc=genfic,dc=org"
Mar  9 12:26:47 ldap1 slapd[95182]: conn=1 op=1 SEARCH RESULT tag=101 err=0 nentries=1 text=

Most common errors in server log are err=49:

ФАЙЛ /var/log/slapd.log
Aug 10 12:47:27 ldap-2 slapd[32920]: conn=1004 op=0 RESULT tag=97 err=49 text=

Which means «invalid credentials» (i.e. wrong password).

And err=32:

ФАЙЛ /var/log/slapd.log
Aug 10 14:15:35 ldap-2 slapd[32966]: conn=1085 op=1 SEARCH RESULT tag=101 err=32 nentries=0 text=

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, описан в man-странице slaps.access. Основной синтаксис выглядит следующим образом:

КОД ACL syntax in OpenLDAP
access to <what> [ by <who> [ <access> ] [ <control> ] ]+

Таблица ниже показывает уровни доступа доступные в OpenLDAP:

Access level Privileges Description
none 0 no access
disclose d needed for information disclosure on error
auth dx needed to authenticate (bind)
compare cdx needed to compare
search scdx needed to apply search filters
read rscdx needed to read search results
write wrscdx needed to modify/rename
manage mwrscdx needed to manage

For details about the exact privilege settings, see the manual pages and official OpenLDAP documentation.

Предупреждение
Запомните, что пользователь rootdn может читать и записывать везде.

Конфигурационный файл

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.

Например:

ФАЙЛ /etc/openldap/slapd.conf
…
access to attrs=userPassword
         by dn="cn=ldapreader,dc=genfic,dc=org" read
         by self read
         by anonymous auth
         by * none
  
access to dn.base="cn=Subschema" by users read
access to dn.base="" by * read
…


Конфигурационный каталог

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.

Например:

ФАЙЛ add_acl.ldif
dn: olcDatabase={-1}frontend,cn=config
changetype: modify
add: olcAccess
olcAccess: {0}to dn.base="cn=subschema" by users read
olcAccess: {1}to dn.base="" by * read

The following example inserts a new ACL on top, making the existing olcAccess entries to shift by one:

ФАЙЛ insert_acl.ldif
dn: olcDatabase={-1}frontend,cn=config
changetype: modify
add: olcAccess
olcAccess: {0}to attrs=userPassword
  by dn="cn=ldapreader,dc=genfic,dc=org" read
  by self read
  by anonymous auth
  by * none

Чтобы удалить ACL:

ФАЙЛ delete_acl.ldif
dn: olcDatabase={-1}frontend,cn=config
changetype: modify
delete: olcAccess
olcAccess: {1}

Дублирование

Высокая доступность

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

Настройка дублирования

Для того, чтобы настроить дублирование, сначала настройте второй сервер OpenLDAP подобно тому, как описано выше. Однако обратите внимание на то, что в файле конфигурации:

  • sync replication provider указывает на другую систему
  • У каждой системы OpenLDAP свой serverID
Заметка
Using a mirrored installation means that the OpenLDAP service should be configured like a single server installation, so the serverID value on each of the nodes must be the same. Instances are identified by rid values, which must be unique.
Synchronisation account

Далее создайте синхронизационную учетную запись. Создадим файл LDIF (формат, используемый для ввода данных на серверах LDAP) и добавим его на каждом сервере LDAP:

user $slappasswd -s myreaderpassword
 {SSHA}XvbdAv6rdskp9HgFaFL9YhGkJH3HSkiM
ФАЙЛ ldapreader.ldif
'"`UNIQ--pre-00000027-QINU`"'
user $ldapadd -x -W -D "cn=Manager,dc=genfic,dc=org" -f ldapreader.ldif
Password: ## enter the administrative password
Enabling syncprov overlay

Overlay 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:

root #/usr/lib64/openldap/slapd -VVV
@(#) $OpenLDAP: slapd 2.4.44 (Feb 28 2017 10:07:46) $
	@larry:/var/tmp/portage/net-nds/openldap-2.4.44/work/openldap-2.4.44-abi_x86_64.amd64/servers/slapd
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
Included static overlays:
    syncprov
Included static backends:
    config
    ldif
    bdb
    hdb
Load syncprov module (optional)

To load syncprov module, use the following ldif file:

ФАЙЛ syncprov-module-load.ldif
#Load the syncprov module.
dn: cn=module{0},cn=config
changetype: modify
add: olcModuleLoad
olcModuleLoad: syncprov
Setting up replication for database

Next step, mandatory for everybody, is to setup replication for database (must be done on both nodes):

ФАЙЛ syncprov-add-overlay.ldif
# syncrepl Provider for primary db
dn: olcOverlay=syncprov,olcDatabase={1}mdb,cn=config
changetype: add
objectClass: olcOverlayConfig
objectClass: olcSyncProvConfig
olcOverlay: syncprov
olcSpNoPresent: TRUE
olcSpCheckpoint: 100 10
olcSpSessionlog: 100
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Add indexes for replica to the frontend db.
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: entryCSN eq
-
add: olcDbIndex
olcDbIndex: entryUUID eq
Предупреждение
One of poorly-documented feature of ldif-backend is that it doesn't permit file deletion. So, you can add overlay, but cannot remove it.
Final configuration

Finally, add replication's definition.

On node 1:

ФАЙЛ add-replication-node1.ldif
dn: cn=config
changetype: modify
add: olcServerID
olcServerID: 1
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcSyncrepl
olcSyncrepl: 
  rid=001 
  provider=ldap://ldap-2.genfic.org 
  binddn="cn=ldapreader,dc=genfic,dc=org" 
  bindmethod=simple 
  credentials="secret" 
  searchbase="dc=genfic,dc=org" 
  type=refreshAndPersist 
  timeout=0 
  network-timeout=0 
  retry="60 +"
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcMirrorMode
olcMirrorMode: TRUE

secret traditionally means the password string.

On node 2:

ФАЙЛ add-replication-node2.ldif
add-replication-node2.ldif 
dn: cn=config
changetype: modify
add: olcServerID
olcServerID: 1
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcSyncrepl
olcSyncrepl:
  rid=002
  provider=ldap://ldap-1.genfic.org
  binddn="cn=ldapreader,dc=genfic,dc=org"
  bindmethod=simple
  credentials="secret"
  searchbase="dc=genfic,dc=org"
  type=refreshAndPersist
  timeout=0
  network-timeout=0
  retry="60 +"
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcMirrorMode
olcMirrorMode: TRUE

The only difference is in server's ident (rid) and provider uri.

Заметка
You need to load ldap database only on one node of cluster and should not load on another. The database will be replicated automatically after adding quoted definition.

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:

root #tail -f /var/log/slapd.log
May 14 15:39:29 ldap2 slapd[1749]: olcMirrorMode: value #0: <olcMirrorMode> database is not a shadow
May 14 15:39:29 ldap2 slapd[1749]: config error processing olcDatabase={1}mdb,cn=config: <olcMirrorMode> database is not a shadow
May 14 15:39:29 ldap2 slapd[1749]: slapd stopped.
May 14 15:39:29 ldap2 slapd[1749]: connections_destroy: nothing to destroy.

Almost certainly the database will not fit into default limits. So, you will need to increase ldapreader's limits. For example:

ФАЙЛ add_replicator-limits.ldif
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcLimits
olcLimits: dn.exact="cn=ldapreader,dc=genfic,dc=org" time.soft=unlimited time.hard=unlimited size.soft=unlimited size.hard=unlimited
Предупреждение
Database file note: replicated database size may be significantly different with origin. In my case about 300 megabytes ldif-dump is loaded into almost 900 megabytes mdb-data file and replicated in 1.5 gigabyte mdb-data file.

Performance tuning

Default daemon settings significantly limits LDAP server performance.

Symptoms

When server load fits system limit client applications fails with different kind of timeout errors.

In server log this produces error messages like following:

ФАЙЛ /var/log/slapd.log
May 17 15:56:11 ldap2 slapd[13834]: fd=76 DENIED from unknown (192.168.210.101)
May 17 15:56:11 ldap2 slapd[13834]: warning: cannot open /etc/hosts.allow: Too many open files
May 17 15:56:11 ldap2 slapd[13834]: warning: cannot open /etc/hosts.deny: Too many open files
May 17 15:56:11 ldap2 slapd[13834]: fd=237 DENIED from unknown (192.168.77.130)
May 17 15:56:11 ldap2 slapd[13834]: warning: cannot open /etc/hosts.allow: Too many open files
May 17 15:56:11 ldap2 slapd[13834]: daemon: accept(8) failed errno=24 (Too many open files)

Increasing OS limits

First, read ldap system user limits:

root #su ldap -c 'ulimit -aHS' -s '/bin/bash'
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 6981
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 6981
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

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:

ФАЙЛ /usr/src/linux-4.9.95-gentoo/Documentation/sysctl/fs.txt
nr_open:
This denotes the maximum number of file-handles a process can 
allocate. Default value is 1024*1024 (1048576) which should be
enough for most machines. Actual limit depends on RLIMIT_NOFILE
resource limit.


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:

ФАЙЛ /etc/security/limits.conf
ldap           soft    nofile          4096
ldap           hard    nofile          8192

And restart daemon.

Предупреждение
For some unknown reasons, upstart init system together with systemd by design ignores system PAM settings i.e. /etc/security/limits.conf file. Users of systemd init in Gentoo please contact me to verify the solution.

The next limitation is sysctl's net.core.somaxconn parameter.

During run time, this value can be updated via:

root #sysctl -w net.core.somaxconn=256
net.core.somaxconn = 256

After verifying new value do not forget to fix it:

ФАЙЛ /etc/sysctl.conf
## For LDAP:
net.core.somaxconn = 256

And, possibly, some other application-specific parameters.

Настройка клиентских утилит OpenLDAP

Отредактируйте файл конфигурации клиента LDAP. Этот файл читается командой ldapsearch и другими ldap-утилитами командной строки.

ФАЙЛ /etc/openldap/ldap.confДобавьте следующее
BASE         dc=genfic, dc=org
URI          ldap://ldap.genfic.org:389/ ldap://ldap-1.genfic.org:389/ ldap://ldap-2.genfic.org:389/
TLS_REQCERT  allow
TIMELIMIT    2

Запущенный сервер можно протестировать с помощью следующей команды:

user $ldapsearch -x -D "cn=Manager,dc=genfic,dc=org" -W

В случае возникновения ошибки, попробуйте добавить -d 255 для увеличения детализации вывода.

Настройка клиента для централизованной аутентификации

Существует целый ряд методов/утилит для осуществления удаленной аутентификации. Некоторые дистрибутивы также предоставляют свои собственные конфигурационные утилиты, легкие в использовании. Ниже приводится ряд утилит в произвольном порядке. Существует возможность одновременного сочетания локальных пользователей и центрально авторизованных учетных записей. Это важно, поскольку, например, если LDAP сервер недоступен, по-прежнему можно войти в систему в качестве пользователя root.

  • SSSD (Single Sign-on Services Daemon). Его основная функция — обеспечение доступа к identity и аутентификационного удаленного ресурса посредством общей структуры, которая способна предоставлять кеширование и оффлайн поддержку для системы. Он предоставляет модули PAM и NSS, и в будущем будет поддерживать интерфейсы D-Bus для расширенной пользовательской информации. Он также предоставляет лучшую базу данных для хранения локальных пользователей, а также расширенных пользовательских данных.
  • Используйте pam_ldap для входа на сервер LDAP и аутентификации. Пароли не посылаются по сети в виде простого текста.
  • NSLCD (Name Service Look up Daemon). Схож с SSSD, но старше его.
  • NSS (Name Service Switch) с использованием традиционного модуля pam_unix для загрузки хешей паролей по сети. Чтобы разрешить пользователям обновлять пароли, этот метод нужно использовать совместно с методом pam_ldap.

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

Настройка клиента PAM метод SSSD

Предупреждение
Untested as of 2021

Здесь представлен более краткий метод. Ниже приводятся три файла, которые необходимо отредактировать.

ФАЙЛ /etc/sssd/sssd.conf
[sssd]
config_file_version = 2
services = nss, pam
domains = genfic
debug_level = 5
  
[nss]
filter_users = root,ldap,named,avahi,haldaemon,dbus,radiusd,news,nscd
  
[domain/genfic]
id_provider = ldap
auth_provider = ldap
ldap_search_base = dc=genfic,dc=org
ldap_tls_reqcert = never
# основной и резервный серверы ldap [первый сервер и],[второй сервер]
ldap_uri = ldap://X.X.X.X,ldap://X.X.X.X


Добавьте sss в конце как показано ниже, чтобы включить передачу поиска имени системному сервису sssd. После завершения редактирования запустите демон sssd.

ФАЙЛ /etc/nsswitch.confПример файла nsswitch.conf с поддержкой SSSD
passwd:     files sss
shadow:     files sss
group:      files sss
  
netgroup:   files sss
automount:  files sss
sudoers:    files sss

Последний файл является наиболее важным. Откройте дополнительный root-терминал перед тем, как его редактировать. Строки, заканчивающиеся символом #, добавлены для включения удаленной аутентификации. Обратите внимание на использование pam_mkhomedir.so для поддержки создания домашних каталогов пользователей.

ФАЙЛ /etc/pam.d/system-authВключение поддержки pam_sss
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        sufficient    pam_sss.so use_first_pass                                         #
auth        required      pam_deny.so
  
account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so                         #
account     required      pam_permit.so
  
password    requisite     pam_cracklib.so try_first_pass retry=3
password    sufficient    pam_unix.so md5 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok                                            #
password    required      pam_deny.so
  
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0077
session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so                                                        #

Теперь попробуйте войти в систему с другого компьютера.

Заметка
SSSD method could be used not only for LDAP-authentication, but also to use AD-authentication.

Настройка клиента PAM метод модуль pam_ldap

Before starting any change to the client side authentication configuration, make sure that the LDAP server can be reached and presents the correct information. The following steps assume a user Bert Ram was created in the LDAP with login name bertram. Exchange accordingly with a user from the LDAP instance. Use the manager role with caution. But at least check with the LDAP read user role and a user that will logon to the client(s) to be configured:

# Uses the manager role, prompts for Manager's password
# if you can't use the manager role change -D to reader role
ldapsearch -x uid=bertram -H ldaps://ldap.genfic.org -b "dc=genfic,dc=org" -D cn=Manager,dc=genfic,dc=org -W
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Make a member query for the initgroups with the user that will login
# tests also this user's password
ldapsearch -x '({{|}}(&(objectClass=posixAccount)(uid=bertram))({{&}}(objectClass=posixGroup)(memberUid=bertram)))'  -H ldaps://ldap.genfic.org -b "dc=genfic,dc=org" -D "cn=Bert Ram,dc=genfic,dc=org" -W

Сначала настроим PAM таким образом, чтобы разрешить авторизацию LDAP. Установите sys-auth/pam_ldap, чтобы PAM поддерживал авторизацию LDAP, и sys-auth/nss_ldap, чтобы система могла справиться с серверами LDAP для дополнительной информации (используется файлом nsswitch.conf).

Заметка
sys-auth/pam_ldap in combination with sys-auth/nss_ldap is an alternative. It requires a globally readable /etc/ldap.conf which is questionable with recent OpenLDAP setups that prohibit anonymous binds. A readable plain text password is as good as anonymous binds. Also code did not change for a long time and some links are dead. Nevertheless it still works. Also ldap.conf on cliet systems may collide with other services.
root #emerge --ask pam_ldap nss_ldap

Последний файл является наиболее важным. Откройте несколько дополнительных root-терминалов перед тем, как его редактировать. Строки, заканчивающиеся символом #, добавлены для включения удаленной аутентификации.

ФАЙЛ /etc/pam.d/system-auth
#%PAM-1.0
 
auth       required     pam_env.so
auth       sufficient   pam_unix.so try_first_pass likeauth nullok
auth       sufficient   pam_ldap.so use_first_pass                                                    #
auth       required     pam_deny.so
 
account    sufficient   pam_ldap.so                                                                   #
account    required     pam_unix.so
 
password   required     pam_cracklib.so difok=2 minlen=8 dcredit=2 ocredit=2 try_first_pass retry=3
password   sufficient   pam_unix.so try_first_pass use_authtok nullok md5 shadow
password   sufficient   pam_ldap.so use_authtok use_first_pass                                        #
password   required     pam_deny.so
 
session    required     pam_limits.so
session    required     pam_unix.so
session    optional     pam_ldap.so                                                                   #
  1. anything before pam_unix left out

account required pam_unix.so

  1. ...after pam_unix again, before pam_permit.so

account sufficient pam_ldap.so minimum_uid=1000 account required pam_permit.so

  1. anything before pam_unix left out

password sufficient pam_unix.so nullok md5 shadow use_authtok

  1. ...after pam_unix again, before pam_deny.so

password sufficient pam_ldap.so minimum_uid=1000 try_first_pass password required pam_deny.so

  1. anything before pam_unix left out

session required pam_unix.so session optional pam_ldap.so minimum_uid=1000

}}

In /etc/nsswitch.conf each line for passwd, group, shadow and initgroups needs to be prepended with ldap:

ФАЙЛ /etc/nsswitch.conf
# Many explanations in comments before...
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
passwd:         db files ldap
group:          db files ldap
shadow:         db files ldap
initgroups:     db [SUCCESS=continue] files ldap
gshadow:        files
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# more statements afterwards
Предупреждение
If initgroups lacks ldap as source users logging in with LDAP credentials will have only their primary group. All other groups like wheel, audio, video and so on will be missing.

Теперь отредактируйте /etc/ldap.conf следующим образом:

  • URI to contact LDAP server, use TLS/ ldaps:// by any means, otherwise passwords are transferred unencrypted
  • Base (general) to lookup DNs
  • Bind-DN (and secret) since anonymous binds are bad
  • Base per group, passwd and/ or shadow in case your LDAP tree deviates from defaults (as mentioned in the file's comments)
  • optional client certificates if you use mutual TLS
  • mapping for group membership to memberUid if you use primary group with additional groups expressed by membership
Заметка
{{{1}}}
Предупреждение
Make sure that /etc/nslcd.conf is owned by nslcd and only readable by nslcd through chmod 400.
ФАЙЛ /etc/ldap.conf
#host 127.0.0.1
#base dc=padl,dc=com
 
base dc=genfic,dc=org
#rootbinddn uid=root,ou=People,dc=genfic,dc=org
bind_policy soft
bind_timelimit 2
ldap_version 3
nss_base_group ou=Group,dc=genfic,dc=org
nss_base_hosts ou=Hosts,dc=genfic,dc=org
nss_base_passwd ou=People,dc=genfic,dc=org
nss_base_shadow ou=People,dc=genfic,dc=org
pam_filter objectclass=posixAccount
pam_login_attribute uid
pam_member_attribute memberuid
pam_password exop
scope one
timelimit 2
uri ldap://ldap.genfic.org/ ldap://ldap1.genfic.org ldap://ldap2.genfic.org
  1. The user and group nslcd should run as.

uid nslcd gid nslcd

uri ldaps://ldap.genfic.org/

base dc=genfic,dc=org

  1. a plain assumption for a user with only read permission on the LDAP

binddn userid=ldapreader,dc=genfic,dc=org bindpw a plain text secret

  1. Reduce timeout from 30s to something sane otherwise login waits at least
  2. until timeout

bind_timelimit 2

  1. There are many other mappings for different schemas. Assuming you use
  2. posixAccount as schema member can be mapped to memberUid to add
  3. initgroups correctly

map group member memberUid }}

This is just a note and needs distinction between systemd and OpenRC, start nslcd:

root #/etc/init.d/nslcd start

If the daemon started successfully, change to one of the console terminals. Return to the graphical session by pressing Ctrl+Alt+F7. Switch to one of the 6 login consoles by pressing Ctrl+Alt+F1..F6. At the login prompt, try user bertram.

Перенесение существующих данных на LDAP

Настройка OpenLDAP для централизованного администрирования и управления привычными объектами Linux/Unix непроста, но, благодаря некоторым утилитам и сценариям, доступным в Интернете, задача перенесения системы с администрирования одной системы на центрально управляемую систему на основе OpenLDAP не так уж сложна.

Загрузите сценарии с https://www.padl.com/OSS/MigrationTools.html. Вам понадобятся утилиты перенесения и сценарий make_master.sh.

Затем распакуйте утилиты и скопируйте сценарий make_master.sh в распакованное местонахождение:

root #mktemp -d
/tmp/tmp.zchomocO3Q
root #cd /tmp/tmp.zchomocO3Q
root #tar xvzf /path/to/MigrationTools.tgz
root #mv /path/to/make_master.sh MigrationTools-47
root #cd MigrationTools-47

Следующий шаг — перенести информацию с системы на OpenLDAP. Это осуществляется с помощью сценария make_master.sh, после предоставления ему информации о структуре и окружении LDAP.

На момент написания, утилитам требуется следующий ввод:

Ввод Описание Пример
LDAP BaseDN Базовое местонахождение (root) дерева dc=genfic,dc=org
Почтовый домен Домен, используемый для адресов электронной почты genfic.org
Почтовый хост FQDN инфраструктуры почтового сервера smtp.genfic.org
LDAP Root DN Информация об административной учетной записи структуры LDAP cn=Manager,dc=genfic,dc=org
Пароль пользователя Root LDAP Пароль для административной учетной записи, cfr ранее команда slappasswd

Утилита также запросит, какие учетные записи и настройки следует перенести.

Предупреждение
Вносить изменения в pam.d/system-auth не требуется

Troubleshooting

Emerge errors after conversion to LDAP

If 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:

Installing build system files
make[1]: Leaving directory '/var/tmp/portage/www-servers/apache-2.4.41/work/httpd-2.4.41'               [ ok ]
chown: invalid user: ?apache:apache?
* ERROR: www-servers/apache-2.4.41::gentoo failed (install phase):
*   fowners failed

In such cases, a workaround involves emerging the package using FEATURES=-network-sandbox. Doing so has potential security consequences so system users should remain in local files.

Благодарности

Мы хотели бы поблагодарить Matt Heler за то, что он одолжил нам свой компьютер в целях написания данного руководства. Также спасибо замечательным ребятам на канале #ldap (webchat) в сети Freenode.net


This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: Benjamin Coles, Sven Vermeulen (SwifT) , Brandon Hale, Benny Chuang, jokey,
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article's associated history page.