使用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 23% 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来完成一组计算机之间的认证。

Warning
The current state does not yield a working configuration. See Talk:Centralized_authentication_using_OpenLDAP for details. Work is in progress.

LDAP是什么?

LDAP是指“Lightweight Directory Access Protocol(轻量目录访问协议)”,它是基于X.500协议的,包括了X.500的大部分功能,但是精减掉了那些过于艰深的东西。那么什么是X.500,而为什么还要有LDAP出现呢?

X.500是OSI标准体系中的目录服务模型,它包含了命名空间的定义以及查询与更新目录的协议,但是X.500在很多场景下被认为有些“用力过猛”。而LDAP,虽然像X.500一样也为目录提供了数据/命名空间的模型与协议,但它被设计为运行在TCP/IP网络协议栈上(译者注:TCP/IP协议栈是IETF标准化组织定义的,而之前讲的OSI标准体系是区别于IETF的另外一套标准化组织,其实OSI体系更古老,更资深也更复杂,我们现在的互联网是基于TCP/IP的通信协议栈的,而OSI里面是有对应于TCP/IP的通信协议栈的,但由于设备厂家支持较少,最终没有流行起来。IETF与OSI有矛盾但也有合作,互相借鉴很多有价值的东西),所以我们可以把LDAP当成是“减肥”了的X.500。

我还是不理解,什么是目录?

目录是一个特殊的数据库,它的数据经常被查询,但是不经常更新。不像普通的数据库,目录不包括对事件(transaction)的支持也不包括回滚特性。目录是很容易被复制的,以便增加它的可用性和可靠性。当目录被复制时,临时的数据不一致情况是允许出现的,只要最终这些数据得到同步即可。

信息是怎样被组织的?

目录中所有的信息被分层次组织在一起。另外,如果您想在目录中添加数据,目录必须要知道如何在树状结构中添加您的这些数据。我们用一个虚构的公司来举例说明一下,如下面的像Internet一样的树状结构:

CODE GenFic公司的组织架构, 它是一个虚拟的Gentoo公司
dc:         com
             |
dc:        genfic         ## (公司)
          /      \
ou:   People   servers    ## (公司部门)
      /    \     ..
uid: ..   John            ## (部门里的数据)

因为您不能像上图一样使用ascii图形码向一个数据库中输入数据,所以这样一个树形结构中的每一个节点都要被定义。为了定义这样一个节点,LDAP使用“命名方案(Naming Scheme)”。大多数的LDAP发行版(包括OpenLDAP)已经包括了一揽子预定义(以及共同认可)的命名方案,如“inetOrgPerson”,或者“posixAccount”,“posixAccount”用来定义一个用户(user)的Unix/Linux相关属性,它是非常常用的。值得一提的是您可以考虑采用图形化的基于web的工具来管理LDAP,这样能轻松很多。参见实际使用OpenLDAP

感兴趣的用户推荐阅读 OpenLDAP Admin Guide

那么,LDAP能够干什么呢?

LDAP可以用来做许多不同的事情呢。这篇文档聚焦于如何集中管理用户,把所有用户的信息保存在统一的LDAP目录里(统一并不意味着只有一台服务器,LDAP是支持高可用性与高冗余性的),另外还有其它一些目标也可以通过LDAP来实现。

  • 公钥基础设施
  • 共享日历
  • 共享地址簿
  • 存储DHCP,DNS,......
  • 系统级的配置管理(跟踪多台服务器的配置)
  • 集中认证 (PosixAccount)
  • ...

OpenLDAP服务器配置

Common notes

域名“genfic.com”是这份指南中的一个例子,您当然想改变它,但是请确保其顶级节点是官方的合法域名,如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)

我们首先要emerge OpenLDAP。请确保如下USE标记被使用:berkdb, crypt, gnutls, ipv6, sasl, ssl, syslog, -minimal

root #emerge --ask openldap

OpenLDAP supports two authentication mechanisms:

  1. Standard user-password (in LDAP terms user means binddn) named SIMPLE.
  2. Proxying authentication requests to SASL (Simple Authentication and Security Layer, see RFC4422 for details).

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)”,这个用户已经在应用中被写死,不可更改。但是与Unix中的root用户不同,rootdn仍然需要被指定适当的权限。rootdn用户可能仅在配置的上下文中被使用,也可能被用于目录的定义,相应地,rootdn用户可以使用配置文件里的密码和目录树中的密码来认证他们自己。(译者注:这里不太好理解,我的个人理解是:openldap的服务器采用/etc/slapd.conf来做配置,里面有一个rootdn条目,这里面指定的dn,例如cn=Manager,dc=genfic,dc=com就是ldap里面最牛的管理员,它可以在LDAP里面干任何事儿,另外openldap运行起来之后,它会维护一个用户信息数据库,这个数据库里面是可以没有cn=Manager,dc=genfic,dc=com这个dn的,当没有这个dn时,这个叫Manager的用户就是只可以管理ldap目录及其内容,但不能用这个用户在ldap客户端上登录,也不能保存关于Manager的个人信息,如电话、地址等,因为ldap没有存储这些信息的地方。但是您也可以在数据库中自己加上这个用户的相应节点,这时这个用户就可以像其它用户一样享受在客户端登录,保存个人信息等“福利”了。)

为了验证目的的用户密码(不管是rootdn的还是其它用户的)都可以被存储为明文或者哈希过的。很多哈希算法都是可用的,但是使用太弱(比MD5更弱)的加密算法是不被推荐的。SHA当前被认为是足够安全的算法。

下面的命令创建了一个给定口令的哈希值,命令的输出结果可以被用在slapd.conf 配置文件中,或者目录中某一个用户的口令属性中。

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

Legacy configuration (flat config slapd.conf)

Warning
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原包里来的,下面是一个范例配置,您可以用它替换掉系统中原来的文件来开始您的工作。

FILE /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 used in case of replication
serverID 0 
loglevel 0
 
## ## Certificate/SSL Section
TLSCipherSuite normal
TLSCACertificateFile /etc/openldap/ssl/ldap.crt
TLSCertificateFile /etc/openldap/ssl/ldap.pem
TLSCertificateKeyFile /etc/openldap/ssl/ldap.key
TLSVerifyClient never
 
## ## Access Controls
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 definition
database hdb
suffix "dc=genfic,dc=com"
checkpoint 32 30
rootdn "cn=Manager,dc=genfic,dc=com"
## ## rootpwd generated earlier via slappasswd command
rootpw "{SSHA}EzP6I82DZRnW+ou6lyiXHGxSpSOw2XO4" 
directory "/var/lib/openldap-data"
index objectClass eq
 
## ## Synchronisation (pull from other LDAP server)
syncrepl rid=000
  provider=ldap://ldap2.genfic.com
  type=refreshAndPersist
  retry="5 5 300 +"
  searchbase="dc=genfic,dc=com"
  attrs="*,+"
  bindmethod="simple"
  binddn="cn=ldapreader,dc=genfic,dc=com"
  credentials="ldapsyncpass"
 
index entryCSN eq
index entryUUID eq
 
mirrormode TRUE
 
overlay syncprov
syncprov-checkpoint 100 10
Note
Don't forget, the second node must use different value of rid and proper address in provider ldapuri.

要想深入了解配置文件的含义,我们建议您研读OpenLDAP Administrator's Guide。

在定制化slapd.conf 配置文件之后,您可以使用下面的命令检查验证其是否配置无误:

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

改变debug级别(上面的"-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风格的配置文件,并且将是缺省的配置方法。使用OLC风格的配置文件的一大好处是当配置需要被更改时,这一动态的后台配置(cn=config)不需要重启服务就可以生效。老用户可以通过设置了-f和-F参数的命令slaptest 将现有配置迁移到新的OLC风格的配置。传统的OLC是以ldif格式(这样可以保证可读性)保存在/etc/openldap/slapd.d 目录中的。Gentoo用户目前还不一定需要进行这一配置文件的转换,但是未来老的方法将可能不被支持。

Migration from slapd.conf to OLC

Warning
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服务器的配置,您必须至少要对cn=config赋予写权限(或者管理权限 )。

下面的例子展示了如何在OLC(“cn=config”数据库)中向系统管理员赋予管理权限 ,我们需要在 slapd.conf 的末尾添加一行配置:

FILE /etc/openldap/slapd.confGranting root Linux account manage rights to cn=config
database config
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none

Then, invoke the slaptest utility with the -f and -F options to convert the slapd.conf file into a configuration directory (slapd.d).

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

上面的命令将会转换并翻译配置文件(slapd.conf->OLC),您可能曾经想过用准备好的ldif文件来完成OLC配置文件的升级,不过假如您对此不那么熟悉,你就可以像我们这样先编辑 slapd.conf ,然后用slaptest命令将其翻译为OLC配置文件(最终保存于 slapd.d/中),最后不要忘记检查这个目录的权限是否可以被ldap系统用户访问。

您可以从产生的文件的注释中获取更多的指导。

下面这一行配置用于使能slapd.d/(OLC)配置方法。

FILE /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 ldap:ldap /var/lib/openldap-data
root #chmod 700 /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.

Warning
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.
Warning
{{{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.

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

FILE 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

See man 5 slapd-config for more details.

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

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

维护目录

启动slapd服务:

root #/etc/init.d/slapd start

Most users will also want the OpenLDAP daemon to start automatically:

root #rc-update add slapd

您可以在apache/proftpd/qmail/samba中开始用目录来认证用户了。您可以用LAM (Ldap Account Manager),phpldapadmin,diradm,jxplorer或者lat来管理您的目录,它们都提供了方便的接口来实施管理。

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

Note
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配置文件的存放路径:

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

改变OpenLDAP服务的日志级别:

FILE loglevel.ldif
dn: cn=config
changetype: modify
replace: olcLogLevel
olcLogLevel: stats sync

为了确认这些改变,可以运行下面的命令:

root #ldapmodify -Y EXTERNAL -H ldapi:/// -f loglevel.ldif
Warning
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 logging

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:

FILE /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:

FILE /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.

Access management (ACLs)

The authorizations and access control mechanism used in OpenLDAP is described in the slapd.access manual page. Its base syntax is as follows:

CODE ACL syntax in OpenLDAP
access to <what> [ by <who> [ <access> ] [ <control> ] ]+

The following table shows the access levels available in 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.

Warning
Remember that the rootdn user can read and write everything.

Config file

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.

For example:

FILE /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
…


Config directory

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.

For example:

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

FILE 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

To delete an ACL:

FILE delete_acl.ldif
dn: olcDatabase={-1}frontend,cn=config
changetype: modify
delete: olcAccess
olcAccess: {1}

复制

高可靠性

设置在多个LDAP服务器之间同步信息。在这份指导中,复制功能会使用一个特别的复制帐号 ( ldapreader ) ,它具有对主LDAP服务器上的读权限 ,然后它会把改变的信息从主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的内部架构,此时已经被复制过的变更的信息不会再被重新复制回来。

Warning
For normal operation of OpenLDAP cluster upstream recommends to use the same version on all nodes.

设置复制

为了设置复制,首先要设置备用OpenLDAP服务器,它的大部分配置跟前面的配置相同,但是要注意的区别是:

  • sync replication provider 要指向另外一台机器。
  • 每一台OpenLDAP服务器的serverID 是不同的。
Note
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
user $cat ldapreader.ldif
dn: cn=ldapreader,dc=genfic,dc=com
userPassword: {SSHA}XvbdAv6rdskp9HgFaFL9YhGkJH3HSkiM
objectClass: organizationalRole
objectClass: simpleSecurityObject
cn: ldapreader
description: LDAP reader used for synchronization
user $ldapadd -x -W -D "cn=Manager,dc=genfic,dc=com" -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:

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

FILE 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
Warning
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:

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

FILE 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.

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

FILE 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
Warning
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:

FILE /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:

FILE /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:

FILE /etc/security/limits.conf
ldap           soft    nofile          4096
ldap           hard    nofile          8192

And restart daemon.

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

FILE /etc/sysctl.conf
## For LDAP:
net.core.somaxconn = 256

And, possibly, some other application-specific parameters.

配置OpenLDAP的客户端工具

编辑LDAP客户端的配置文件。这个文件会被ldapsearch和其它ldap命令行工具读取。

FILE /etc/openldap/ldap.confAdd the following
BASE         dc=genfic, dc=com
URI          ldap://ldap.genfic.com:389/ ldap://ldap1.genfic.com:389/ ldap://ldap2.genfic.com:389/
TLS_REQCERT  allow
TIMELIMIT    2

您可以用下面的命令测试运行中的服务器。

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

如果您收到错误信息,您可以用 -d 255这个参数来增加debug级别,以便获取更详细的信息用于解决问题。

集中化认证的客户端配置

有很多方法/工具可以被用来做远程认证。一些发行版也提供了它们自己的很好用的配置工具。下面列出一些,排名不分先后。把本地用户认证与集中认证同时结合在一起是可行的。这一点非常重要,因为万一LDAP服务器不可用,至少您还可以通过root用户进行本地登录。

  • SSSD (Single Sign-on Services Daemon). 它主要的功能是为远程身份认证提供一个通用的框架,提供缓存与不在线的支持。它提供PAM与NSS模块,将来还会为扩展用户信息支持D-Bus接口。它也提供了一个更好的数据库来存储本地用户和扩展用户的数据。
  • 使用 pam_ldap 登录到LDAP服务器并认证。口令不会在网络上以明文的方式发送。
  • NSLCD (Name Service Look up Daemon)。与SSSD类似,但更古老。
  • NSS (Name Service Switch) 使用传统的 pam_unix 模块从网络上获取哈希口令。如果要允许用户变更他们的口令,还需要结合pam_ldap方法一起使用。

下面我们会用最少的必要配置来演示前两个方法使之工作。

客户端 PAM 配置 SSSD 的方法

Warning
Untested as of 2021

操作方法很简单,只有三个文件需要被编辑,如下:

FILE /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=com
ldap_tls_reqcert = never
# primary and backup ldap servers below [first server and],[second server]
ldap_uri = ldap://X.X.X.X,ldap://X.X.X.X


按照如下文件所示增加“sss”到每一行的末尾,这样就可以将(对用户信息的)查询工作转交给sssd系统服务,你完成对这个文件的编辑后,就可以将sssd的后台服务启动起来了。

FILE /etc/nsswitch.conf提供对SSSD支持的nsswitch.conf 文件范例
passwd:     files sss
shadow:     files sss
group:      files sss
  
netgroup:   files sss
automount:  files sss
sudoers:    files sss

最后一个文件是非常关键的。请在编辑它之前先打开另外一个终端窗口以便失败时退回(译者注:我因为开始一点也不懂pam的这个配置文件的原理,也没有重视这一条要求,当时就编辑错了,导致还得用引导盘引导系统后用root用户重新编辑这个文件,直至系统恢复)。文件中在行尾标注了 #的行即是用于使能远程认证。注意使用pam_mkhomedir.so 来支持在用户登录时创建主目录(如果是首次在某一客户端登录的话)。

FILE /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                                                        #

好了,现在就可以试着从另外一个终端进行登录了。

Note
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)所用。

Note
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用户登录终端作好准备。行尾标有 # 的表示使能远程认证。

FILE /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:

FILE /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
Warning
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
Note
{{{1}}}
Warning
Make sure that /etc/nslcd.conf is owned by nslcd and only readable by nslcd through chmod 400.
FILE /etc/ldap.conf
## #host 127.0.0.1
## #base dc=padl,dc=com
 
base dc=genfic,dc=com
## #rootbinddn uid=root,ou=People,dc=genfic,dc=com
bind_policy soft
bind_timelimit 2
ldap_version 3
nss_base_group ou=Group,dc=genfic,dc=com
nss_base_hosts ou=Hosts,dc=genfic,dc=com
nss_base_passwd ou=People,dc=genfic,dc=com
nss_base_shadow ou=People,dc=genfic,dc=com
pam_filter objectclass=posixAccount
pam_login_attribute uid
pam_member_attribute memberuid
pam_password exop
scope one
timelimit 2
uri ldap://ldap.genfic.com/ ldap://ldap1.genfic.com ldap://ldap2.genfic.com
  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

为集中认证和管理Linux/Unix信息配置OpenLDAP不是个轻松的活儿,但是拜互联网上的工具们和脚本们所赐,从分立的系统管理到基于OpenLDAP的集中系统管理的迁移工作也不是那么难。

-{R可以得到这些脚本。您可能需要迁移工具和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 LDAP目录树的根 dc=genfic,dc=com
Mail domain e-mail地址所用域名 genfic.com
Mail host 邮件服务器系统的FQDN smtp.genfic.com
LDAP Root DN LDAP系统管理员的DN cn=Manager,dc=genfic,dc=com
LDAP Root Password 系统管理员的帐号密码 slappasswd command

这个工具也会问您想要迁移哪些帐号和设置。

Warning
您不需要改变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 @ irc.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.