Centralized authentication using OpenLDAP/es

Esta guía presenta las cuestiones básicas de LDAP y le muestra cómo configurar OpenLDAP para realizar tareas de autenticación entre un grupo de computadoras.

¿Qué es LDAP?
LDAP significa Lightweight Directory Access Protocol (Protocolo Ligero de Acceso a Directorio). Está basado en X.500 el cual define la mayoría de sus funciones y carece de algunas funciones esotéricas que tiene X.500. Ahora bien, ¿Qué es X.500 y porqué existe LDAP?

X.500 es un modelo de Servicio de Directorio basado en el concepto OSI (Interconexión de sistemas Abiertos). Contiene definiciones de espacios de nombres y protocolos para consultar y actualizar el directorio. Sin embargo, se ha encontrado en muchos casos que X.500 es demasiado estricto. Mejor entrar en LDAP. Al igual que X.500, proporciona un modelo de datos y espacio de nombres para el directorio y el protocolo. No obstante, LDAP está diseñado para correr directamente sobre la pila TCP/IP. Podemos considerar a LDAP como una versión ligera de X.500.

No lo pillo. ¿Qué es un directorio?
Un directorio es una base de datos especializada diseñada para consultas frecuentes y actualizaciones no tan frecuentes. Al contrario que las bases de datos generalistas, no ofrecen soporte para transacciones o funcionalidad de vuelta atrás (roll-back). Los directorios se replican fácilmente para incrementar disponibilidad y fiabilidad. Cuando se replican los directorios, se permiten inconsistencias temporales siempre que acaben sincronizándose.

¿Cómo se estructura la información?
Toda la información dentro de un directorio está estructurada jerárquicamente. Aún más, si intenta introducir datos en un directorio, éste debe conocer la forma de almacenar estos datos en un árbol. Eche un vistazo a una compañía ficticia y a su organigrama:

Estructura organizativa de GenFic, una empresa Gentoo ficticia

Puesto que no puede alimentar la base de datos con este tipo de arte ascii, se debe definir cada nodo de este árbol. Para nombrar estos nodos, LDAP usa un sistema de definición de nombres. La mayor parte de distribuciones de LDAP (incluyendo OpenLDAP) ya contienen un buen número de esquemas predefinidos (y normalmente aprobados), como el inetOrgPerson o un esquema llamado posixAccount utilizado frecuentemente para definir usuarios que los equipos Unix o Linux pueden utilizar. Observe que existen herramientas basadas en GUI para que facilitar la gestión de LDAP. Eche un vistazo a Trabajar con OpenLDAP para una lista exhaustiva.

Se recomienda a los usuarios interesado leer la Guía de Administración de OpenLDAP.

Y bien.. ¿Para qué se utiliza?
Se puede usar LDAP para diferentes propósitos. En este documento se trata la administración centralizada de usuarios, manteniendo todas las cuentas de usuario en una única ubicación LDAP (lo que no significa que esté albergada en un único servidor, puesto que LDAP ofrece soporte a alta disponibilidad y redundancia). Sin embargo, se puede utilizar LDAP para otros fines.


 * Infraestructura de Clave Pública (PKI)


 * Calendario compartido


 * Libreta de direcciones compartida


 * Almacenamiento para DHCP, DNS, ...


 * Directivas de configuración de clases del sistema (manteniendo el seguimiento de varias configuraciones del servidor)


 * Autenticación centralizada (PosixAccount)



Configuración del servidor OpenLDAP
En esta guía utilizamos como ejemplo el dominio genfic.com. Por supuesto, deberá cambiarlo. Sin embargo, asegúrese de que el nodo superior es un dominio oficial de primer nivel (net, com, cc, be, ...).

En primer lugar haga emerge de OpenLDAP. Asegúrese que se usan los ajustes USE berkdb, crypt, gnutls, ipv6, sasl, ssl, syslog y tcpd.

OpenLDAP tiene un usuario principal llamado "rootdn" (Root Distinguished Name o Nombre Distinguido de Root) el cual está definido dentro de la aplicación. Al contrario que el usuario root clásico de Unix, al usuario rootdn se le deben asignar los permisos adecuados. El usuario rootdn solo se puede utilizar en el contexto de la configuración y también en la definición del directorio. En este caso un usuario puede autenticarse a si mismo como rootdn con la contraseña usada en la configuración y la contraseña (basada en el directorio) del árbol.

La contraseñas de usuario (independientemente si son para usuarios rootdn u otros) para propósitos de verificación se pueden almacenar como testo en claro o aplicando un hash. Se dispone de varios algoritmos hash, sin embargo no se recomienda el uso de algoritmos débiles (hasta MD5). Actualmente en criptografía se considera que SHA es suficientemente seguro.

En la orden de abajo, se crea un valor hash para una contraseña dada, el resultado de esta orden se puede utilizar en el fichero de configuración o bien en la definición del directorio interno de un usuario:

Ahora edite la configuración LDAP del servidor en. El fichero que se muestra es de los fuentes originales de openLDAP. Abajo se muestra un fichero ejemplo de configuración que se puede utilizar para reemplazarlo de modo que las cosas comiencen a funcionar.

/etc/openldap/slapd.conf

Para un análisis más detallado del fichero de configuración, le sugerimos que acceda a la guía del administrador de OpenLDAP.

Verifying the configuration
Después de configurar el fichero, puede comprobarlo con la siguiente orden.

Or, if you decide to use OLC:

Vary the debug level (the "-d 1" above) for more info. If all goes well you will see config file testing succeeded. If there's an error,  will list the line number to which it applies (of the  file).

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

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

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

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 and after that re-translate the  into. Don't forget to check the directory's permissions.

For more instructions read the in-line comments of the generated files.

The below line will enable the configuration method.

/etc/conf.d/slapd

Para terminar, cree la estructura :

Start slapd:

If it does not start then increase the loglevel variable in to 4 or more, and look in  for more information.

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

For instance, to change the location of the OLC configuration directory:

fix-configs.ldif

To change the log level used by the OpenLDAP instance:

loglevel.ldif

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

Configuring the OpenLDAP Client tools
Edit the LDAP Client configuration file. This file is read by ldapsearch and other ldap command line tools.

You can test the running server with the following command:

If you receive an error, try adding  to increase the verbosity and solve the issue you have.

Client Configuration for Centralised Authentication
There are numerous methods/tools that can be used for remote authentication. Some distributions also have their own easy to use configuration tool. Below there are some in no particular order. It is possible to combine local users and centrally authorized accounts at the same time. This is important because, for instance, if the LDAP server cannot be accessed one can still login as root.


 * SSSD (Single Sign-on Services Daemon). Its primary function is to provide access to identity and authentication remote resource through a common framework that can provide caching and offline support to the system. It provides PAM and NSS modules, and in the future will support D-Bus interfaces for extended user information. It also provides a better database to store local users as well as extended user data.


 * Use  to login to the LDAP server and authenticate. Passwords are not sent over the network in clear text.


 * NSLCD (Name Service Look up Daemon). Similar to SSSD, but older.


 * NSS (Name Service Switch) using the traditional  module to fetch password hashes over the network. To permit users to update their password this has to be combined with the   method.

The first two are demonstrated below with the minimum necessary configuration options to get working.

Client PAM configuration SSSD Method
Here is the more direct method. The three files that are required to be edited are mentioned below.

Add sss to the end as shown below to enable the lookup to be handed to the sssd system service. Once you have finished editing start the sssd daemon.

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

Now try logging in from another box.

Client PAM configuration the pam_ldap Module Method
First, we will configure PAM to allow LDAP authorization. Install so that PAM supports LDAP authorization, and  so that your system can cope with LDAP servers for additional information (used by ).

The last file is the most critical open a few extra root windows as a backup before editing this. The lines in bold have been added to enable remote authentication.

/etc/pam.d/system-auth

Ahora cambie para que contenga:

/etc/ldap.conf

Next, copy over the (OpenLDAP) file from the server to the client so the clients are aware of the LDAP environment:

Finally, configure your clients so that they check the LDAP for system accounts:

/etc/nsswitch.conf

If you noticed one of the lines you pasted into your was commented out (the   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 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, put the pass in there for 10 seconds while changing the users password and remove it when done.

Migrate existing data to ldap
Configuring OpenLDAP for centralized administration and management of common Linux/Unix items isn't easy, but thanks to some tools and scripts available on the Internet, migrating a system from a single-system administrative point-of-view towards an OpenLDAP-based, centralized managed system isn't hard either.

Go to http://www.padl.com/OSS/MigrationTools.html and fetch the scripts there. You'll need the migration tools and the script.

Next, extract the tools and copy the script inside the extracted location:

The next step now is to migrate the information of your system to OpenLDAP. The script will do this for you, after you have provided it with the information regarding your LDAP structure and environment.

At the time of writing, the tools require the following input:

The tool will also ask you which accounts and settings you want to migrate.

High availability
To setup replication of changes across multiple LDAP systems. Replication within OpenLDAP is, in this guide, set up using a specific replication account which has read rights on the primary LDAP server and which pulls in changes from the primary LDAP server to the secondary.

This setup is then mirrored, allowing the secondary LDAP server to act as a primary. Thanks to OpenLDAP's internal structure, changes are not re-applied if they are already in the LDAP structure.

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

Next, create the synchronisation account. We will create an LDIF file (the format used as data input for LDAP servers) and add it to each LDAP server:

OpenLDAP permissions
If we take a look at you'll see that you can specify the ACLs (permissions if you like) of what data users can read and/or write:

/etc/openldap/slapd.conf

This gives you access to everything a user should be able to change. If it's your information, then you got write access to it; if it's another user their information then you can read it; anonymous people can send a login/pass to get logged in. There are four levels, ranking them from lowest to greatest:.

The next ACL is a bit more secure as it blocks normal users to read other people their shadowed password:

/etc/openldap/slapd.conf

This example gives root and John access to read/write/search for everything in the the tree below. This also lets users change their own 's. As for the ending statement everyone else just has a search ability meaning they can fill in a search filter, but can't read the search results. Now you can have multiple acls but the rule of the thumb is it processes from bottom up, so your toplevel should be the most restrictive ones.

Maintaining the directory
You can start using the directory to authenticate users in apache/proftpd/qmail/samba. You can manage it with LAM (Ldap Account Manager), phpldapadmin, diradm, jxplorer, or lat, which provide easy management interfaces.

Agradecimientos
Nos gustaría dar las gracias a Matt Heler por dejarnos su máquina para realizar esta guía. También queremos agradecer a los tíos simpáticos en #ldap @ irc.freenode.net