This is Gentoo's testing wiki. It is a non-operational environment and its textual content is outdated.

Please visit our production wiki at https://wiki.gentoo.org

使用OpenLDAP集中式认证

From Gentoo Wiki (test)
Jump to:navigation Jump to:search
This page is a translated version of the page Centralized authentication using OpenLDAP and the translation is 34% complete.
Outdated translations are marked like this.


这篇指南介绍了LDAP的基础知识以及向你展示如何安装针对一组计算机认证目的的OpenLDAP。


Getting started with OpenLDAP

什么是LDAP?

LDAP代表着轻量组目录访问协议。基于X.500它包含了它的绝大部分主要功能,但是缺少X.500的更加深奥的功能。现在什么是这个X.500以及为什么会有一个LDAP?

X.500是一个OSI概念中的目录服务模型。它包含了命名空间定义和目录查询和更新协议。然而,X.500在很多场景中都太大了。进入LDAP。像X.500它为目录和协议提供一个数据/命名空间模型。不过,LDAP是为直接通过TCP/IP栈进行而设计。可以看出LDAP是X.500的一个瘦身版本。

我不理解。什么是目录?

目录是为频繁查询但不频繁更新而设计的一个特殊的数据库。不像其它常规数据库,它们不包含事件支持或回滚功能。目录很容易复用以提供可用性和可靠性。当目录被复用,允许临时的不一致直到得到最终同步。

信息结构是什么样?

目录中的所有信息都是垂直结构。更多的是,如果你想输入向目录中输入数据,目录必须知道如何在树中储存这个数据。让我们看看一个虚构的公司和一个像互联网的树。

CODE Organisational structure for GenFic, a Fictional Gentoo community
dc:         org
             |
dc:        genfic         ## (Organisation)
          /      \
ou:   People   servers    ## (Organisational Units)
      /    \     ..
uid: ..   John            ## (OU-specific data)

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

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

So... what can it be used for?

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

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

OpenLDAP server setup

Common notes

The domain genfic.org is an example in this guide. You will of course want to change this. However, make sure that the top node is an official top level domain (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.

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)

Now edit the LDAP Server configuration in /etc/openldap/slapd.conf. The provided slapd.conf is from the original OpenLDAP source. Below is a sample configuration file one can use to replace it with to get things started.

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 mdb
suffix "dc=genfic,dc=org"
checkpoint 32 30
maxsize 10485760
#Note: It is important to set this to as large a value as possible,
#(relative to anticipated growth of the actual data over time)
#since growing the size later may not be practical when the system is under heavy load.
 
rootdn "cn=Manager,dc=genfic,dc=org"
## ## 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=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
Note
Don't forget, that on second node you must use different value of rid and proper address in provider ldapuri.

For a more detailed analysis of the configuration file, we suggest that you work through the OpenLDAP Administrator's Guide, although man 5 slapd.conf may be enough.

If it does not start, the first thing you must do is to check the config file. You can do it with the following command.

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.

Warning
Note that since version 2.4.23, OpenLDAP default finally moved from traditional flat config files (slapd.conf) to OLC (OnLineConfiguration, also known through its cn=config structure) as default configuration method. One of benefits of using OLC is that the dynamic backend (cn=config) doesn't require restart of server after updating the configuration. Existing users can migrate to the new configuration method by invoking slaptest setting both -f and -F options. Traditionally OLC is stored in ldif backend (which keep benefits of human-readability) in the /etc/openldap/slapd.d directory. In Gentoo it is not required to convert the configuration yet, but support for the currently documented approach will be removed in the future.

Migration from slapd.conf to OLC

If you want to be able to change OpenLDAP server's configuration, you must define at least write (or normally manage) access to cn=config.

The example below shows how to grant manage access on OLC (cn=config database) to the system administrator (root user) by adding the proper lines at the end of the slapd.conf file:

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, we 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 /etc/openldap/slapd.d
root #chown -R ldap /etc/openldap/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 -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.

Warning
If you need to include additional schemas, you also should use not flat schema files, but converted into ldif format. If you use a custom scheme, you also will need to convert it into ldif format, see openldap.ldif for more detailed description.

It 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

If you use root account to do it, you must correct ownership of created files, as described below in migrate section.

Warning
The default configuration does not provide permissions to change the server's configuration to anybody.

If you need the right to change the configuration database, you must provide the proper permissions. 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.

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

维护目录

Start slapd now that the configuration steps have been completed:

root #service slapd start

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

root #rc-update add slapd

It is now possible to use the directory server to authenticate users in apache/proftpd/qmail/samba.

The directory server can be managed with tools such as net-nds/phpldapadmin, app-admin/diradm and net-nds/jxplorer from the Gentoo ebuild repository, or app-misc/ldapexplorertool from the poly-c overlay available through Layman or eselect repository.

Server management with OLC

Note
One of the benefits of using OLC-style configuration is that you don't need to restart the LDAP server to apply configuration changes.

一些OLC风格的配置文件升级范例可以参见下文。

For instance, to change the location of the OLC configuration directory (needed after switching from a config file to config directory style):

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 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"
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 you try to do something wrong, or there is a mistake in your ACLs set.

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
add|delete} 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}

Replication

High availability

A common high availability setup with OpenLDAP is to use replication of changes across multiple LDAP systems.

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.

Setting up replication

为了设置复制,首先要设置备用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
FILE ldapreader.ldif
dn: cn=ldapreader,dc=genfic,dc=org
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=org" -f ldapreader.ldif
Password: ## enter the administrative password
Enabling syncprov overlay

Overlay can be linked statically and dynamically. When it is built dynamivally, you'll need to load module. For now in Gentoo it's usually built statically. To enshure 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

Included static overlays:
    syncprov
Included static backends:
    config
    ldif
    bdb
    hdb
Load syncprov module (optional)

If you need to load syncprov module, you should 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

# 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, you need to add replication's definition.

On node 1:

FILE add-replication-node1.ldif
dn: cn=config
changetype: modify
add: olcServerID
olcServerID: 1

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 +"

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

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 +"

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 your database will not fit into default limits. So, you will need to encrease 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 limitates LDAP server performance.

Sympthoms

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)

Encreasing OS limits

First, you should 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 encrease, 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 net.core.somaxconn parameter. In runtime you could update it by:

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.

Configuring the OpenLDAP client tools

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

FILE /etc/openldap/ldap.confAdd the following
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这个参数来增加debug级别,以便获取更详细的信息用于解决问题。

Client configuration for centralized authentication

有很多方法/工具可以被用来做远程认证。一些发行版也提供了它们自己的很好用的配置工具。下面列出一些,排名不分先后。把本地用户认证与集中认证同时结合在一起是可行的。这一点非常重要,因为万一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方法

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

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=org
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.confExample nsswitch.conf with SSSD support
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-authEnable pam_sss support
#%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.

Client PAM configuration the pam_ldap module method

首先我们要配置PAM来允许LDAP认证。安装 sys-auth/pam_ldap程序包以便让PAM支持LDAP授权,然后是 sys-auth/nss_ldap以支持您的系统从LDAP服务器获取额外信息为 (nsswitch.conf)所用。

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                                                                   #

改变 /etc/ldap.conf为只读权限。

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

下一步,把(OpenLDAP) ldap.conf 文件从服务器拷贝到客户端,这样客户端就可以理解LDAP环境了。

root #scp ldap-server:/etc/openldap/ldap.conf /etc/openldap

最后,在客户端进行配置以便它会为系统帐号查询LDAP。

FILE /etc/nsswitch.conf
passwd:         files ldap
group:          files ldap
shadow:         files ldap

如果您注意到在/etc/ldap.conf 有一行被注释掉了 (rootbinddn),这意味着您在这个客户端上不需要以超级用户(LDAP的超级用户)身份变更其它用户的密码。如果您真的想这么做,您还需要在/etc/ldap.secret中以明文方式把超级用户的密码写入其中。这是很危险的做法,所以您还应该把这个文件的权限设为600。比较好的做法是,平时将/etc/ldap.secret文件留空,当您需要变更某个用户(LDAP或 /etc/passwd)的密码时,把超级用户的密码填在那里,完成任务后,再把密码清空。

Convert file userbase to LDAP

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

http://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架构和环境的相关信息。

截止到我们写文档的时候,这个工具需要下面的输入信息:

Input Description Example
LDAP BaseDN The base location (root) of your tree dc=genfic,dc=org
Mail domain Domain used in e-mail addresses genfic.org
Mail host FQDN of your mail server infrastructure smtp.genfic.org
LDAP Root DN Administrative account information for your LDAP structure cn=Manager,dc=genfic,dc=org
LDAP Root Password Password for the administrative account, cfr earlier slappasswd command

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

Warning
您不需要改变pam.d/system-auth

知识

We would like to thank Matt Heler for lending us his box for the purpose of this guide. Thanks also go to the cool guys in #ldap on 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, Joshua Saddler (nightmorph)
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.