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를 활용한 중앙 인증
이 안내서는 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 스택을 통해 바로 동작하도록 설계했습니다. X.500에서 군더더기를 뺀 결과물로서 LDAP를 이해하십시오.
잘 모르겠는데요. 디렉터리가 뭔가요?
디렉터리는 빈번한 요청에 드물게 업데이트를 수행하도록 설계하여 특화된 데이터베이스입니다. 일반 데이터베이스와는 달리 트랜잭션 지원 기능이나 롤백 기능이 없습니다. 디렉터리는 가용성과 신뢰성을 개선하기 위해 쉽게 복제할 수 있습니다. 디렉터리를 복제하면, 디렉터리를 동기화 한 만큼 일시적인 비일관성도 허용됩니다.
정보가 어떻게 구성되어 있죠?
모든 디렉터리 내부 정보는 계층 구조로 되어 있습니다. 게다가 디렉터리에 데이터를 입력하면 트리에 데이터를 어떻게 저장하는지 알아야 합니다. 그러면 허구속의 회사와 인터넷과 비슷한 트리를 보도록 하겠습니다:
dc: org | dc: genfic ## (Organisation) / \ ou: People servers ## (Organisational Units) / \ .. uid: .. John ## (OU-specific data)
아스키 아트 유사 방식으로 데이터베이스에 데이터를 넣지 않았기 때문에 각 트리의 모든 노드를 반드시 정의해야 합니다. LDAP에서는 이 노드에 이름을 부여하려 작명 스킴을 사용합니다. 대부분의 LDAP 구성(OpenLDAP 포함)에서는 이미 설정한(그리고 일반적으로 승인하는) inetOrgPerson 같은 스키마와 유닉스/리눅스 머신에서 사용할 수 있도록 사용자를 정의하는 지주 사용하는 posixAccount 스키마가 있습니다. LDAP를 문제 없이 관리할 수 있게 하는 GUI 웹 기반 도구가 있음을 참고하십시오. 대략적인 목록은 Working with OpenLDAP을 보십시오
흥미를 가진 사용자라면 OpenLDAP 관리자 안내서를 보십시오.
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
+cleartext
|
Enable use of cleartext passwords |
+syslog
|
Enable support for syslog |
argon2
|
Enable password hashing algorithm from app-crypt/argon2 |
autoca
|
Automatic Certificate Authority overlay |
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 |
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) |
verify-sig
|
Verify upstream signatures on distfiles |
먼저 OpenLDAP를 이머지하겠습니다. berkdb, crypt, gnutls, ipv6, sasl, ssl, syslog,-minimal, tcpd USE 플래그를 사용했는지 확인하십시오.
root #
emerge --ask openldap
OpenLDAP supports two authentication mechanisms:
- standard user-password (in LDAP terms user means binddn) named SIMPLE
- 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(루트 식별 이름) 입니다. 기존의 유닉스 루트 사용자와는 달리, rootdn 사용자는 적당한 권한 할당이 필요합니다. rootdn 사용자는 설정 환경에서만 활용할 수 있지만 디렉터리 정의 범위에서도 사용할 수 있습니다. 이 경우 해당 사용자는 환경 설정에 넣은 암호과 트리(디렉터리 기반) 암호를 사용하여 rootdn으로 자신을 인증 할 수 있습니다.
검증 목적의(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.
/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
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
더 많은 내용을 확인하려면 디버그 레벨("-d 1" 이상)을 바꿔보십시오. 모든 동작이 잘 된다면 "config file testing succeedded"가 보입니다.
오류가 있다면, slaptest
에서 (slapd.conf 파일에서) 오류가 난 부분의 줄 번호를 표시합니다
By default slapd writes the log events to the local4 syslog facility.
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:
/etc/openldap/slapd.conf
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
이 명령을 실행하면 설정을 보내고 변환합니다. 이 과정이 끝나면 각각 마련된 ldif 파일을 사용하여 설정을 업데이트함니다. 그리고 이 방식에 충분히 익숙하지 않다면, 우선 slapd.conf를 편집하고, 그 다음에 slapd.conf 파일을 slapd.d/ 형식에 맞춰 재작성할 수 있습니다. 디렉터리 권한 확인을 잊지 마십시오.
더 많은 내용은 만들어진 파일의 자체 주석을 참고하십시오.
아래 줄은 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.
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.
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:
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
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):
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 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
:
/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 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:
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.
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:
/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:
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
To delete an ACL:
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의 내부 구조에 감사해야 할 일은 LDAP 구조상 바뀐 내용이 또 있다 할지라도 중복 적용하지 않습니다.
For normal operation of OpenLDAP cluster upstream recommends to use the same version on all nodes.
Setting up replication
복제를 설정하려면, 우선, 먼저 위에서 진행한 바와 같이 두번째 OpenLDAP 서버를 설정해야 합니다. 그러나 설정 파일에 대해서는 다음을 주의하십시오.
- 동기화 복제 제공자는 다른 시스템을 가리킵니다
- 각각의 OpenLDAP의 서버 ID는 다릅니다
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
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:
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 # 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, you need to add replication's definition.
On node 1:
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:
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.
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:
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 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:
/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:
/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
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:
/etc/sysctl.conf
## For LDAP: net.core.somaxconn = 256
And, possibly, some other application-specific parameters.
Configuring the OpenLDAP client tools
LDAP 클라이언트 설정 파일을 편집하십시오. 이 파일은 ldapsearch 및 다른 ldap 명령행 도구에서 읽어들입니다.
/etc/openldap/ldap.conf
Add the followingBASE 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
를 추가하고, 처한 문제를 해결해보십시오.
Client configuration for centralized authentication
원격 인증에 사용할 수 있는 방식과 도구는 많이 있습니다. 어떤 배포판에서는 사용하기 쉬운 자체 도구도 있습니다. 아래에는 특별한 순서는 없습니다. 로컬 사용자와 중앙 인증 계정을 통시에 합칠 수 있습니다. LDAP 서버가 루트 계정으로 여전히 로그인할 수 있는 위치에 접근할 수 없는 경우 등의 이유로 이러한 점은 중요합니다.
- SSSD (Single Sign-on Services Daemon). 시스템에 캐싱, 오프라인 지원 기능을 제공할 수 있는 일반 프레임워크를 통해 원격 자원을 식별하고 인증하여 접근하는 기능을 제공하는 근본 기능을 수행합니다. PAM과 NSS 모듈을 제공하며, 나중에는 확장 사용자 정보에 대해 D-Bus 인터페이스를 지원할 예정입니다. 확장 사용자 데이터로 로컬 사용자를 저장하기 위해 더 나은 데이터베이스를 제공하기도 합니다.
- LDAP 서버에 로그인하고 인증하기 위해
pam_ldap
를 사용합니다. 암호는 네트워크 상에 분명한 텍스트로 전송하지 않습니다.
- NSLCD (Name Service Look up Daemon). SSSD와 유사하지만 오래됐습니다.
- 기존
pam_unix
모듈을 사용하는 NSS(Name Service Switch)로 네트워크로 암호 해시를 가져옵니다. 사용자가 암호를 새로 바꿀 수 있게 하려면,pam_ldap
방식과 결합합니다.
아랫 부분에 시연한 처음 두 부분은, 동작하게 하는 최소한의 필요 설정 옵션입니다.
SSSD 방식의 클라이언트 PAM 설정
더 직접적인 방식이 있습니다. 아래에 필요한 세가지 파일을 편집한 상태로 보여드리겠습니다.
/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
sssd 시스템 서비스의 역할로서의 검색을 활성화 하려면 하부에 보이는대로 마지막 부분에 sss를 추가하십시오. 편집을 끝내고 나면 sssd 데몬을 시작하십시오.
/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_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.
Client PAM configuration the pam_ldap module method
먼저 LDAP 인증을 할 수 있게 PAM을 설정하겠습니다. PAM이 LDAP 인증을 지원하게 sys-auth/pam_ldap를 설치하고, (nsswitch.conf가 활용하는) 추가 정보에 대해 여러분의 시스템이 LDAP 서버에 대응할 수 있도록 sys-auth/nss_ldap를 설치하십시오.
root #
emerge --ask pam_ldap nss_ldap
마지막 파일은 상당히 중요합니다. 이 파일을 편집하기 전의 백업본으로 몇가지 추가 루트 터미널 창을 여십시오. #
으로 끝나는 줄은 원격 인증을 활성화하려 추가했습니다.
/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를 바꾸십시오:
/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를 검사하도록 하십시오:
/etc/nsswitch.conf
passwd: files ldap group: files ldap shadow: files ldap
/etc/ldap.conf에 붙여넣은 줄 중 하나를(rootbinddn
줄) 주석처리했음을 알아챘다면: 슈퍼유저 권한으로 사용자의 암호를 바꾸려 하지 않는 한 이럴 필요가 없습니다. 이 경우 /etc/ldap.secret에 있는 그대로의 텍스트로 루트 암호를 적어넣어야 합니다. 이는 위험한 조치이며 파일 접근 권한을 chmod 명령을 통해 600 값으로 설정해야 합니다. 여러분이 할 일은 파일을 빈채로 두는 것이며, LDAP와 /etc/passwd에서 누군가의 암호를 바꾸려 할 경우, 사용자의 암호를 10초 이내로 넣어두었다가 과정 처리가 끝나면 제거하십시오.
Convert file userbase to LDAP
집중화 관리 및 일반 Linux/Unix 요소 관리를 위한 OpenLDAP 설정은 쉽지 않지만, 단일 시스템 관리 관점의 시스템을 OpenLDAP 기반 집중화 관리 시스템을 덜 까다롭게 하는 몇가지 도구와 스크립트가 인터넷에 둥둥 떠다닌다는 점은 감사해야 할 일입니다. :-P
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로 옮깁니다. LDAP 구조와 환경에 대한 정보를 제공한 후 make_master.sh 스크립트로 이 과정을 진행하십시오.
작성하는 도중에, 도구에서 다음 입력사항을 요구합니다:
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
|
또한 도구에서 옮길 계정과 설정이 어떤건지 물어봅니다.
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.