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

Authentification centralisée avec 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 26% complete.
Outdated translations are marked like this.


Ce guide introduit les bases de LDAP et montre comment configurer OpenLDAP pour des besoin d'authentification dans un groupe d'ordinateurs.


Getting started with OpenLDAP

Qu'est-ce que LDAP ?

LDAP signifie Lightweight Directory Access Protocol (Protocole Allégé pour accès à des annuaires). Basé sur X.500 il couvre la plupart de ses fonctions primaires, mais ne possède pas ses fonctions les plus ésotériques. Maintenant, qu'est-ce que ce X.500 et pourquoi LDAP existe-t-il ?

X.500 est un modèle pour les services d'annuaires dans de concept OSI. Il comprend des définitions d'espaces de noms et les protocoles pour interroger et mettre à jour l'annuaire. Néanmoins, X.500 s'est avérer être surdimensionné dans maintes situations. C'est là qu'entre en scène LDAP. Comme X.500 il procure un modèle données/espace de noms pour l'annuaire et un protocole. Cependant, LDAP est conçu pour tourner directement au-dessus de la pile TCP/IP. Considérez LDAP comme une version allégée de X:500.

Je n'ai pas saisi. Qu'est-ce qu'un annuaire ?

Un annuaire est une base de données spécialisée conçue pour des interrogations fréquentes mais avec des mises à jour moins fréquentes. Au contraire des bases de données générales, il ne comprend pas de prise en charge des transactions ou de fonctionnalités de retour en arrière. Les annuaires sont facilement répliqués pour en augmenter la disponibilité et la fiabilité. Lorsque les annuaires sont répliqués, des incohérences temporaires sont autorisées jusqu'à ce qu'elles soient synchronisées à la fin.

Comment l'information est-elle structurée ?

Toutes les informations dans un annuaire sont organisées de manière hiérarchisée. Même plus, si vous voulez entrer des données dans un annuaire, cet annuaire doit savoir comment ranger ces informations dans un arbre. Jetons un coup d'œil à une société imaginaire et un arbre similaire à Internet :

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

Comme vous n'entrez pas les données dans la base de données de cette façon ascii-artistique, chacun des nœuds d'un tel arbre doit être défini. Pour nommer de tels nœuds, LDAP utilise un schéma de nommage. La plupart des distributions LDAP (y compris OpenLDAP) contiennent déjà un certain nombre de schémas prédéfinis (et largement approuvés), tels que l'inetOrgPerson, un schéma fréquemment utilisé pour définir les utilisateurs que des machines Unix/Linux peuvent utiliser, appelés posixAccount (comptes posix). Notez qu'il existe des interfaces graphiques basées sur le web pour faciliter la gestion de LDAP : reportez-vous à Working with OpenLDAP pour une liste non exhaustive.

Les utilisateurs intéressés sont encouragés à lire le guide d'administration de OpenLDAP .

So... what can it be used for?

LDAP peut être utilisé pour différentes choses. Ce document est centré sur la gestion centralisée d'utilisateurs, en conservant tous les comptes utilisateur dans un emplacement LDAP unique (ce qui ne veut pas dire qu'il est hébergé sur un serveur unique, LDAP prenant en charge une haute disponibilité et la redondance), bien que d'autres objectifs peuvent être atteints en utilisant LDAP également.

  • Infrastructure de clés publiques
  • Calendrier partagé
  • Carnet d'adresses partagé
  • Espace de stockage pour DHCP, DNS, ...
  • Directives de configuration des classes système (conserver la trace de la configuration de plusieurs serveurs)
  • Authentification centralisée (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)

Commençez par installer OpenLDAP. Assurez-vous que les options de la variable USE, "berkdb, crypt, gnutls, ipv6, sasl, ssl, syslog, -minimal" et "tcpd" sont utilisées.

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 has a main user called "rootdn" (Root Distinguished Name), which is hardcoded in the application. Unlike the classic Unix root user, the rootdn user still needs to be assigned with proper permissions. The rootdn user may be used only in the context of the configuration, but it can also be used in the directory definition. In that case a user can authenticate himself as rootdn with either the configuration used password and the tree (directory-based) password.

User passwords (regardless if it is for rootdn users or others) for verification purposes can be stored as cleartext or hashed. Multiple different hash algorithms are available, but usage of weak algorythms (up to MD5) is not recommended. SHA is currently considered sufficiently cryptographically secure.

In the below command, a hashed value is created for a given password; the result of this command can be used in the slapd.conf configuration file, or in the internal directory definition of a user:

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

Jouez sur le niveau de déverminage (le -d 1 ci-dessus) pour plus d'informations. Si tout se passe bien, vous verrez config file testing succeeded. Si une erreur s'est produite, slaptest indiquera le numéro de ligne (du fichier slapd.conf ) à laquelle elle s'applique.

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

Running this command will transfer and translate the configuration. After that you are expected to update the configuration using specially prepared ldif files. And only if you aren't enough familiar with them, you can first edit slapd.conf and after that re-translate the slapd.conf into slapd.d/. Don't forget to check the directory's permissions.

Pour plus d'instruction, reportez-vous aux commentaires en ligne des fichiers générés.

La ligne ci-dessous activera la méthode de configuration slapd.d/.

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

Pour finir, créez la structure /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

Maintenir l'annuaire

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.

Some examples of updates on the OLC-style configuration are mentioned below.

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

To change the log level used by the OpenLDAP instance:

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

In order to apply the changes, run the following command:

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.

Cette configuration est ensuite réfléchie, autorisant le serveur LDAP secondaire à fonctionner comme serveur primaire. Grâce à la structure interne d'OpenLDAP, les changements ne sont pas ré-appliqués s'ils sont déjà dans la structure LDAP.

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

Setting up replication

To setup replication, first setup a second OpenLDAP server, similarly as above. However take care that, in the configuration file:

  • The sync replication provider is pointing to the other system
  • The serverID of each OpenLDAP system is different
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

Créez ensuite le compte de synchronisation. Créez un fichier LDIF (le format utilisé en tant que données d'entrée pour les serveurs LDAP) et ajoutez le à chaque serveur 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

Éditez les fichiers de configuration du client LDAP. Ce fichier est lu par ldapsearch et les autres outils en ligne de commande de 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

Nous pouvons tester le serveur en service à l'aide de la commande suivante :

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

Si vous obtenez une erreur, essayez d'ajouter -d 255 pour augmenter la verbosité et résoudre votre problème.

Client configuration for centralized authentication

Il existe de nombreuses méthodes ou de nombreux outils à utiliser pour une authentification à distance. Quelques distributions disposent également de leur propre outil convivial de configuration. Ci-dessous, nous en présentons quelques uns sans ordre particulier. Il est possible des combiner des comptes d'utilisateurs locaux et des comptes autorisés de manière centralisée en même temps. Ceci est important parce que, par exemple, si le serveur LDAP n'est pas accessible, on peut toujours se connecter en tant qu'utilisateur root.

  • SSSD (Single Sign-on Services Daemon). Son premier rôle est de fournir un accès à une identité et à une ressources distante d'authentification à travers une structure commune qui assure la mise en cache et une assistance hors ligne au système. IL fournit des modules PAM et NSS, et dans le futur prendra en charge les interfaces D-Bus pour une information utilisateur étendue. Il procure aussi une base de données meilleure pour stocker les utilisateurs locaux et des données utilisateur étendues.
  • Utilise pam_ldap pour se connecter au serveur LDAP et s'authentifier. Les mots de passe ne sont pas envoyés en clair sur le réseau.
  • NSLCD (Name Service Look up Daemon ou démon de service de recherche de nom). Similaire à SSSD, mais plus ancien.
  • NSS (Name Service Switch ou commutateur de service ). Il utilise le module pam_unix traditionnel pour aller chercher les hachages des mots de passe sur le réseau. Pour permettre aux utilisateurs de mettre leur mot de passe à jour, ceci doit être combiné avec la méthode pam_ldap.

Les deux premiers sont démontrés ci-après avec les options minimales de configuration pour que ça fonctionne.

Configuration PAM du client par la méthode SSSD

Voici une méthode plus directe. Les trois fichiers à éditer sont indiqués ci-dessous :

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


Ajoutez sss à la fin comme indiqué ci-dessous pour activer la recherche par le service système sssd. Une fois que vous avez terminé l'édition, démarrez le démon 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

The last file is the most critical. Open an extra root terminal as a fallback before editing this. The lines that end with # have been added to enable remote authentication. Note the use of pam_mkhomedir.so to support creating the user home directories.

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                                                        #

Maintenant essayez de vous connecter depuis une autre machine.

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

Tout d'abord, vous allez configurer PAM pour permettre l,autorisation LDAP. Installezsys-auth/pam_ldap afin que PAM prenne en charge l'autorisation LDAP, et sys-auth/nss_ldap afin que votre système puisse coopérer avec les serveurs LDAP pour une information additionnelle (utilisée par nsswitch.conf ).

root #emerge --ask pam_ldap nss_ldap

The last file is the most critical. Open a few extra root terminals as a backup before editing this. The lines that end with # have been added to enable remote authentication.

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                                                                   #

Maintenant changez /etc/ldap.conf pour lire :

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

Ensuite copiez le fichier ldap.conf (de OpenLDAP) du serveur vers le client afin que le clients soient conscients de l'environnement LDAP :

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

Pour terminer, configurez les clients afin qu'ils interrogent LDAP sur les comptes du système :

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

If you noticed one of the lines you pasted into your /etc/ldap.conf was commented out (the rootbinddn line): you don't need it unless you want to change a user's password as superuser. In this case you need to echo the root password to /etc/ldap.secret in plaintext. This is DANGEROUS and should be chmoded to 600. What you might want to do is keep that file blank and when you need to change someone's password that's both in the LDAP and /etc/passwd, put the pass in there for 10 seconds while changing the users password and remove it when done.

Convert file userbase to LDAP

Configurer OpenLDAP pour une administration centralisée et la gestion d'items Linux/Unix communs n'est pas chose facile, mais grâce à quelques outils et scripts disponibles sur Internet, migrer un système conçu pour être administré en tant que système unique vers un système à gestion centralisée basé sur LDAP n'est pas difficile.

Rendez-vous sur http://www.padl.com/OSS/MigrationTools.html et recherchez-y les scripts. Vous avez besoin des outils de migration et du script make_master.sh.

Ensuite, extrayez les outils et copiez le script make_master.sh dans l'emplacement d'extraction :

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

L'étape suivante est maintenant de migrer les informations de votre système vers OpenLDAP. Le script make_master.sh le fera pour vous, après que vous lui ayez fourni l'information concernant votre structure LDAP et votre environnement.

Au moment de l'écriture, les outils ont besoin des entrées suivantes :

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

L'outil vous demandera aussi quels comptes et quelles configurations vous voulez migrer.

Attention !
Il n'est pas nécessaire de changer pam.d/system-auth

Remerciements

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.