HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows...

52
HOWTO / KNOW HOW PUESTA EN MARCHA DE UN SERVIDOR LDAP CON CERTIFICACIÓN TLS Y CONFIGURACIÓN DE CLIENTES LINUX Y WINDOWS PARA AUTENTIFICARSE CONTRA ÉL

Transcript of HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows...

Page 1: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HOWTO / KNOW HOW

PUESTA EN MARCHA DE UN SERVIDOR LDAP CON CERTIFICACIÓN TLS Y CONFIGURACIÓN DE CLIENTES LINUX Y WINDOWS PARA AUTENTIFICARSE CONTRA ÉL

Page 2: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

Nombre E-mail Fecha Realizado [email protected] 01 de abril de 2008 Revisado Descripción HowTo y Conceptos para levantar un servidor LDAP y autenticar clientes Linux/Windows contra él

Versión: v.0.0 Páginas totales: 52

Nombre de Archivo: Servidor ldap linux y clientes linux y windows.doc

DISCLAIMER: La información que aquí aparece puede no ser 100% correcta. He intentado hacerlo lo mejor posible, pero puede que haya cometido errores, principalmente por falta de conocimientos. Cualquier comentario, crítica, pregunta o corrección será muy bien recibida en [email protected]

Page 3: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

3

AUTENTIFICACIÓN LINUX/WINDOWS CONTRA SAMBA/LDAP LINUX

1 abril 2008

Índice 1. Introducción 4 2. Instalación y configuración del servidor LDAP 6

2.1 Instalación de LAM (Ldap Account Manager). 9 2.2. Añadir usuarios y grupos al servidor. 11 2.3. Probando el servidor 14

2.3.3 Posibles problemas 19 3. Instalación y configuración del cliente Linux. 21

3.1 Instalación del software. 21 3.2 Indicar el servidor al que conectarse. 21 3.3 Resolución de nombres del sistema 22 3.4 Haciendo login. 25

4. Introducción de TLS 28 4.1 Creando la entidad certificadora (CA) 28 4.2 Creando certificados de las máquinas 29 4.3 Asegurando el servidor 32 4.4 Haciendo un cliente confiable 33 4.5 Posibles problemas 38

4.5.1 TLS Already started 38 4.5.2 I have no name! 38 4.5.3 Handshake failure 39

5. Autentificación de una máquina Windows 40 5.1 Configuración en el servidor. 40

5.1.1 Instalando el software 40 5.1.2 Añadir el esquema Samba a LDAP 40 5.1.3. Configurar Samba 41 5.1.3 Configurar y utilizar las smbldap-tools 42

5.2 Configuración del cliente Windows 48 5.2.1 Comprobar que podemos acceder al servidor con “test” 48 5.2.2 Unirse al dominio “JOME”. 49

6. Links y referencias usados 52

Page 4: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

1. Introducción Este tutorial se hizo con dos ordenadores que están dentro de una LAN privada (formada conectando dos PCs en un router de telefónica) como la que cualquiera puede tener en su casa. CLIENTE

Debian 4.0 (Etch) Hostname: Enano IPAddress: dhcp

SERVIDOR

Xubuntu 7.10 (Gutsy Gibbon)

Hostname: xxxx IPAddress: 192.168.1.30

CLIENTE

Windows 2000 Professional SP4

Hostname: Enano IPAddress: dhcp

El ordenador cliente dispone de un arranque dual que le permite entrar tanto en una Debian como en un Windows 2000 Professional. Se va a instalar un servidor LDAP en xxxx, y allí se creará un usuario de nombre test y password test (usuario que solamente existirá en la base de datos de Ldap) y se va a explicar el proceso necesario para poder iniciar sesión con este usuario en el ordenador cliente (ya sea bajo Linux o bajo Windows). Este usuario pertenecerá al grupo test, grupo que también existirá únicamente en la base de datos Ldap. Para aclarar conceptos hay que entender antes de nada que Ldap no autentifica nada de por sí; es únicamente una base de datos especialmente rápida en las lecturas, lo que pasa es que, como veremos más adelante, se le puede decir “el

Page 5: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

5

nombre de los usuarios lo coges de la tabla llamada ‘tal’, el nombre de los grupos de la tabla llamada ‘cual’…” pero tiene muchas más utilidades; por ejemplo, puede usarse para almacenar direcciones de correo (agenda) en la que no se utiliza para autentificación ni mucho menos. Para cuestiones de autentificación existen otros métodos, como NIS (o NIS+) y que, de hecho, para la autentificación Linux ↔ Linux son mucho más sencillos de configurar, pero son incompatibles con Windows. También quiero aclarar que no se pretende migrar todos los usuarios del servidor a LDAP: solamente uno.

Page 6: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

6

2. Instalación y configuración del servidor LDAP Primero, instalación de los paquetes necesarios: ~$ sudo apt-get install slapd ldap-utils

Es posible que pregunte algunas cosas, como una contraseña del administrador del servidor. En sistemas basados en Debian, siempre es posible pedir la re-configuración de ese y otros parámetros con: ~$ dpkg-reconfigure slapd

Desea omitir la configuracion de ldap : no Introduzca el nombre de dominio DNS : nombre.del.dominio1 Instrodusca el nombre de su organizacion : nombre.del.dominio Contraseña del administrador : LDAPpassword Verificacion de la contraseña : LDAPpassword Motor de base de datos a utilizar : BDB Desea que se borre la base de datos cuando purge el paquete slapd : NO Desea mover la base de datos antigua : SI Permitir el protocolo LDAPV2 : si

En este caso, el nombre del dominio es jome Después, hay que buscar y configurar el fichero slapd.conf. En Ubuntu 7.10 este fichero se encuentra en /etc/ldap/slapd.conf. En distribuciones que utilicen otras versiones del servidor LDAP, como Fedora, puede encontrarse bajo /etc/openldap/. Si la re-configuración con dpkg-reconfigure ha sido correcta, en el fichero /etc/ldap/slapd.conf ya se habrán escrito algunos datos básicos. En negrita aparece lo más relevante a la hora de para comprobar que la configuración es correcta. # Allow LDAPv2 binds allow bind_v2 # This is the main slapd configuration file. See slapd.conf(5) for more # info on the configuration options. ####################################################################### # Global Directives: # Features to permit #allow bind_v2 # Schema and objectClass definitions include /etc/ldap/schema/core.schema include /etc/ldap/schema/cosine.schema include /etc/ldap/schema/nis.schema include /etc/ldap/schema/inetorgperson.schema # Where the pid file is put. The init.d script # will not stop the server if you change this. pidfile /var/run/slapd/slapd.pid # List of arguments that were passed to the server argsfile /var/run/slapd/slapd.args # Read slapd.conf(5) for possible values loglevel 0

1 El nombre del dominio puede ser, por ejemplo, linux.debian.es

Page 7: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

7

# Where the dynamically loaded modules are stored modulepath /usr/lib/ldap moduleload back_bdb # The maximum number of entries that is returned for a search operation sizelimit 500 # The tool-threads parameter sets the actual amount of cpu's that is used # for indexing. tool-threads 1 ####################################################################### # Specific Backend Directives for bdb: # Backend specific directives apply to this backend until another # 'backend' directive occurs backend bdb checkpoint 512 30 ####################################################################### # Specific Backend Directives for 'other': # Backend specific directives apply to this backend until another # 'backend' directive occurs #backend <other> ####################################################################### # Specific Directives for database #1, of type bdb: # Database specific directives apply to this databasse until another # 'database' directive occurs database bdb # The base of your directory in database #1 suffix "dc=jome" # rootdn directive for specifying a superuser on the database. This is needed # for syncrepl. rootdn "cn=Admin,dc=jome" # Where the database file are physically stored for database #1 directory "/var/lib/ldap" # For the Debian package we use 2MB as default but be sure to update this # value if you have plenty of RAM dbconfig set_cachesize 0 2097152 0 # Sven Hartge reported that he had to set this value incredibly high # to get slapd running at all. See http://bugs.debian.org/303057 # for more information. # Number of objects that can be locked at the same time. dbconfig set_lk_max_objects 1500 # Number of locks (both requested and granted) dbconfig set_lk_max_locks 1500 # Number of lockers dbconfig set_lk_max_lockers 1500 # Indexing options for database #1 index objectClass eq # Save the time that the entry gets modified, for database #1 lastmod on # Where to store the replica logs for database #1 # replogfile /var/lib/ldap/replog # The userPassword by default can be changed # by the entry owning it if they are authenticated. # Others should not be able to see it, except the # admin entry below # These access lines apply to database #1 only access to attrs=userPassword,shadowLastChange by dn="cn=admin,dc=jome" write by anonymous auth by self write by * none # Ensure read access to the base for things like # supportedSASLMechanisms. Without this you may # have problems with SASL not knowing what # mechanisms are available and the like.

Page 8: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

8

# Note that this is covered by the 'access to *' # ACL below too but if you change that as people # are wont to do you'll still need this if you # want SASL (and possible other things) to work # happily. access to dn.base="" by * read # The admin dn has full write access, everyone else # can read everything. access to * by dn="cn=admin,dc=jome" write by * read # For Netscape Roaming support, each user gets a roaming # profile for which they have write access to #access to dn=".*,ou=Roaming,o=morsnet" # by dn="cn=admin,dc=jome" write # by dnattr=owner write # # # ####################################################################### # Specific Directives for database #2, of type 'other' (can be bdb too): # Database specific directives apply to this databasse until another # 'database' directive occurs #database <other> # The base of your directory for database #2 #suffix "dc=debian,dc=org"

En este momento el demonio slapd se habrá puesto en marcha. En estas primeras etapas se puede comprobar si es así haciendo una búsqueda simple. # ldapsearch -x -b dc=jome

Que debería proporcionar una salida vacía. # extended LDIF # # LDAPv3 # base <dc=tured,dc=com> with scope subtree # filter: (objectclass=*) # requesting: ALL # # search result search: 2 result: 34 Invalid DN syntax text: invalid DN # numResponses: 1

Si no funciona, o se quiere más información se puede lanzar el servidor en una consola en modo foreground (no como demonio) con mucha salida de depurado. ~$killall slapd (para matar los demonios que haya corriendo) ~$slapd –d 1

Esto iniciará el servidor en la máquina identificada como localhost, y puede que en la búsqueda haya que decírselo explícitamente: ~$ldapsearch –x –h localhost –b dc=jome

También existe la función slapcat, que muestra el contenido del servidor en formato LDIF. Una herramienta para chequear este fichero y estudie su sintaxis, proporcionando incluso avisos de seguridad es el comando slaptest (~#slaptest –v)

Page 9: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

9

2.1 Instalación de LAM (Ldap Account Manager). La forma más rápida de gestionar un servidor y ver su contenido es utilizar una herramienta web de gestión, como LAM2. Es un paquete que existe ya en Ubuntu, con lo cual, instalarlo es fácil: ~$apt-get install ldap-account-mannager

Al ser una herramienta web de gestión depende, entre otros, de Apache y Php. Una vez funcionando, puede utilizarse tecleando en la barra de cualquier navegador http://dirección_del_servidor/lam. Por ejemplo, si el servidor está en 192.168.1.30:

Puede que no esté bien configurado por defecto: es decir, que el servidor o el nombre del usuario administrador no sean los correctos. En ese caso, hay que acudir al link “LAM configuration” que aparece en la parte superior derecha de la página: Al hacer clic en él, se abrirá una nueva página en la que podremos controlar configuración en general o configuración de datos del servidor:

Al intentar hacer cambios pide passwords. ¡Cuidado! No hay que escribir aquí el del servidor LDAP, sino los de la aplicación LAM. Puede tener varios passwords distintos: Uno de es necesario para añadir, borrar y renombrar perfiles de 2 Pagina web del proyecto: http://lam.sourceforge.net/

Page 10: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

10

configuración globales y se almacena en /etc/ldap-account-manager/config.cfg. El otro es el password de un perfil de conexión concreto (puede que utilicemos la misma instancia de LAM para supervisar varios servidores).Se puede establecer en “Edit server profiles” como se detalla a continuación Entrando en “Edit server profiles” aparece lo que se debe ajustar:

Los campos más importantes son los que aparecen arriba del todo (Preferencias del servidor) y al final (Preferencias de seguridad).El nombre del servidor es importante. Depende de cómo se arranque el demonio slapd. Es lo que se le indica con el parámetro –h si se arranca en consola, o lo que se establezca en las opciones por defecto que aparecen en /etc/default/slapd (lo veremos más adelante, en la página 13).

Page 11: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

11

2.2. Añadir usuarios y grupos al servidor.

Ahora el servidor está vacío. Si se accede utilizando LAM, y se hace clic sobre el link , se observa que solo existe la entrada del administrador del servidor

(técnicamente, cn=Admin, dc=jome)

Se deben crear, en la base de datos de LDAP, las entradas que se corresponderán con los usuarios, los grupos y los hosts. Para entender esto, obsérvese las primeras líneas de /etc/nsswitch.conf. Allí aparecen: passwd group shadow

Se desea que (en los clientes que se autentificarán contra nuestro servidor) esas entradas también se vayan a resolver con LDAP y que un usuario que solo exista en el servidor LDAP pueda iniciar sesión. Para ello, hay que añadir unas tablas en la base de datos de LDAP:

• People: para almacenar los usuarios (y el shadow) • Groups: para almacenar los grupos • Hosts: para almacenar información sobre las máquinas (será útil, como veremos

más adelante, para Samba) Como se verá a lo largo del documento, no tienen necesariamente que llamarse así. Estos campos (o tablas) pueden crearse muy fácilmente con la herramienta LAM. Si no se quiere (o no se puede) utilizar, deben añadirse por consola en formato ldif3. Para añadir estos grupos, crear un fichero (donde sea, puede ser incluso en /tmp) que contenga lo siguiente: dn: ou=Groups,dc=jome objectClass: top objectClass: organizationalUnit ou: Group dn: ou=People,dc=jome objectClass: top objectClass: organizationalUnit ou: People dn: ou=Hosts,dc=jome objectClass: top objectClass: organizationalUnit ou: Hosts

3 Más información sobre Ldif: http://www.bdat.net/documentos/cursos/ar01s88.html

Page 12: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

12

El nombre del fichero no es relevante. Suponiendo que en este caso fuese OUs.ldif, habría que hacer lo siguiente para introducir su información el servidor: root@xxxx:/tmp# ldapadd -x -D 'cn=Admin,dc=jome' -W -f OUs.ldif Enter LDAP Password: LDAPpassword adding new entry "ou=People,dc=jome"

adding new entry "ou=Groups,dc=jome"

adding new entry "ou=Hosts,dc=jome"

Gráficamente se puede ver lo ocurrido: En LAM, hacer clic sobre el link “Refrescar” y ahí aparecen:

Ahora hay que añadir un grupo y un usuario de test. Se puede hacer gráficamente con LAM o con una entrada Ldif. Veámoslo más detalladamente con este último método. De momento, el usuario será una cuenta normal (para eso tiene que ser una objectClass: posixAccount). El usuario tendrá un password, que será “test”. Éste puede almacenarse en texto plano (con lo cual, el campo userPassword del usuario no tiene más que ser: userPassword: test) o encriptado. Siempre es más seguro una encriptación md5. Para ver qué hash Md5 se corresponde con la cadena “test”, ejecutar: root@xxxx:~# slappasswd –h {MD5} –s test {MD5}CY9rzUYh03PK3k6DJie09g==

Para añadir el usuario y el grupo, poner en un fichero .ldif lo siguiente: # Fichero /tmp/user_group.ldif # Testing Group# dn: cn=test,ou=Group,dc=jome objectClass: top objectClass: posixGroup cn: test gidNumber: 2000 # # New Tester user # dn: uid=test,ou=People,dc=jome objectClass: top objectClass: account objectClass: posixAccount uid: test cn: Test User userPassword: {MD5}CY9rzUYh03PK3k6DJie09g== gecos: Test User uidNumber: 2000 gidNumber: 2000 homeDirectory: /home/test loginShell: /bin/bash

Y añadirlo con ldapadd como se ha visto en la página 12.

Page 13: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

13

Con LAM puede verse gráficamente lo ocurrido:

Ya prácticamente está configurado el servidor. Ahora se deben indicar las opciones de arranque por defecto. Eso se hace en el fichero /etc/default/slapd. # Default location of the slapd.conf file SLAPD_CONF="/etc/ldap/slapd.conf" # System account to run the slapd server under. If empty the server # will run as root. SLAPD_USER="openldap" # System group to run the slapd server under. If empty the server will # run in the primary group of its user. SLAPD_GROUP="openldap" # Path to the pid file of the slapd server. If not set the init.d script # will try to figure it out from $SLAPD_CONF (/etc/ldap/slapd.conf) SLAPD_PIDFILE= # Configure if the slurpd daemon should be started. Possible values: # - yes: Always start slurpd # - no: Never start slurpd # - auto: Start slurpd if a replica option is found in slapd.conf (default) SLURPD_START=auto # slapd normally serves ldap only on all TCP-ports 389. slapd can also # service requests on TCP-port 636 (ldaps) and requests via unix # sockets. # Example usage: SLAPD_SERVICES="ldap://xxxx:389/ ldaps://xxxx:636/ ldapi:///" # Additional options to pass to slapd and slurpd SLAPD_OPTIONS="" SLURPD_OPTIONS=""

Son importantes los servicios que se arrancarán (línea en negrita). Si desde el exterior se accede al servidor LDAP de la máquina “xxxx”, hay que arrancarlo así. Es decir (suponiendo que la IP de la máquina xxxx fuese la 192.168.1.30) no es lo mismo arrancar con ldap://192.168.1.30:389/ que con ldap://xxxx:389/.

Page 14: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

14

2.3. Probando el servidor Con lo explicado hasta ahora, ya se debería disponer de un servidor LDAP en el que aparece un usuario llamado test que pertenece a un grupo llamado test. Esto es fácilmente comprobable:

2.3.1 Configurar las bases de datos del sistema. Con nuestro sistema, ya debería ser suficiente para que. Para utilizar LDAP como fuente de usuarios y grupos (y, por tanto, que el usuario test sea considerado un usuario del sistema) hay que modificar el fichero /etc/nsswitch.conf y dejarlo así:

# /etc/nsswitch.conf # # Example configuration of GNU Name Service Switch functionality. # If you have the `glibc-doc-reference' and `info' packages installed, try: # `info libc "Name Service Switch"' for information about this file. passwd: files ldap #compat group: files ldap #compat shadow: files ldap #compat hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4 networks: files protocols: db files services: db files ethers: db files rpc: db files netgroup: nis

Para buscar los passwd, group y shadow el sistema acudirá primero a los ficheros locales y luego al servidor LDAP. Inicialmente están únicamente en compat, que es que acuda a mirar a ficheros locales (la diferencia con files es que compat permite la compatibilidad con formatos de fichero antiguos)

2.3.2 Identificar las bases de datos del sistema con las OUs de LDAP Ahora hay que indicar qué OUs almacenan qué datos del sistema. Indicarle al sistema que los usuarios los tiene que ir a buscar a la OU:People, los grupos a la OU:Groups… y en qué servidores se encuentran dichas OUs. En Ubuntu eso se hace en el fichero /etc/ldap.conf. Versiones anteriores de LDAP (como la usada en Debian Etch) dividen este fichero en dos que son prácticamente redundantes. Ahora están unidos. Una posibilidad es: ###DEBCONF### ## ## Configuration of this file will be managed by debconf as long as the ## first line of the file says '###DEBCONF###' ## ## You should use dpkg-reconfigure to configure this file via debconf ## # # @(#)$Id: ldap.conf,v 1.38 2006/05/15 08:13:31 lukeh Exp $ # # This is the configuration file for the LDAP nameservice # switch library and the LDAP PAM module. # # PADL Software # http://www.padl.com # # Your LDAP server. Must be resolvable without using LDAP. # Multiple hosts may be specified, each separated by a

Page 15: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

15

# space. How long nss_ldap takes to failover depends on # whether your LDAP client library supports configurable # network or connect timeouts (see bind_timelimit). host xxxx # The distinguished name of the search base. base dc=jome # Another way to specify your LDAP server is to provide an # uri with the server name. This allows to use # Unix Domain Sockets to connect to a local LDAP Server. uri ldap://xxxx:389/ #uri ldaps://127.0.0.1/ #uri ldapi://%2fvar%2frun%2fldapi_sock/ # Note: %2f encodes the '/' used as directory separator # The LDAP version to use (defaults to 3 # if supported by client library) ldap_version 3 # The distinguished name to bind to the server with. # Optional: default is to bind anonymously. #binddn cn=proxyuser,dc=padl,dc=com # The credentials to bind with. # Optional: default is no credential. #bindpw secret # The distinguished name to bind to the server with # if the effective user ID is root. Password is # stored in /etc/ldap.secret (mode 600) rootbinddn cn=Admin,dc=jome # The port. # Optional: default is 389. #port 389 #port 636 #Puerto seguro # The search scope. #scope sub #scope one #scope base # Search timelimit #timelimit 30 # Bind/connect timelimit #bind_timelimit 30 # Reconnect policy: hard (default) will retry connecting to # the software with exponential backoff, soft will fail # immediately. #bind_policy hard # Idle timelimit; client will close connections # (nss_ldap only) if the server has not been contacted # for the number of seconds specified below. #idle_timelimit 3600 # Filter to AND with uid=%s #pam_filter objectclass=account # The user ID attribute (defaults to uid) #pam_login_attribute uid # Search the root DSE for the password policy (works # with Netscape Directory Server) #pam_lookup_policy yes # Check the 'host' attribute for access control # Default is no; if set to yes, and user has no # value for the host attribute, and pam_ldap is # configured for account management (authorization) # then the user will not be allowed to login. #pam_check_host_attr yes # Check the 'authorizedService' attribute for access # control # Default is no; if set to yes, and the user has no # value for the authorizedService attribute, and

Page 16: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

16

# pam_ldap is configured for account management # (authorization) then the user will not be allowed # to login. #pam_check_service_attr yes # Group to enforce membership of #pam_groupdn cn=PAM,ou=Groups,dc=padl,dc=com # Group member attribute #pam_member_attribute uniquemember # Specify a minium or maximum UID number allowed #pam_min_uid 1000 #pam_max_uid 0 # Template login attribute, default template user # (can be overriden by value of former attribute # in user's entry) #pam_login_attribute userPrincipalName #pam_template_login_attribute uid #pam_template_login nobody # HEADS UP: the pam_crypt, pam_nds_passwd, # and pam_ad_passwd options are no # longer supported. # # Do not hash the password at all; presume # the directory server will do it, if # necessary. This is the default. #pam_password # Hash password locally; required for University of # Michigan LDAP server, and works with Netscape # Directory Server if you're using the UNIX-Crypt # hash mechanism and not using the NT Synchronization # service. #pam_password crypt # Remove old password first, then update in # cleartext. Necessary for use with Novell # Directory Services (NDS) #pam_password clear_remove_old #pam_password nds # RACF is an alias for the above. For use with # IBM RACF #pam_password racf # Update Active Directory password, by # creating Unicode password and updating # unicodePwd attribute. #pam_password ad # Use the OpenLDAP password change # extended operation to update the password. #pam_password exop # Redirect users to a URL or somesuch on password # changes. #pam_password_prohibit_message Please visit http://internal to change your password. # RFC2307bis naming contexts # Syntax: # nss_base_XXX base?scope?filter # where scope is {base,one,sub} # and filter is a filter to be &'d with the # default filter. # You can omit the suffix eg: # nss_base_passwd ou=People, # to append the default base DN but this # may incur a small performance impact. nss_base_passwd ou=People,dc=jome?one nss_base_shadow ou=People,dc=jome?one nss_base_group ou=Groups,dc=jome?one nss_base_hosts ou=Hosts,dc=jome?one #nss_base_services ou=Services,dc=padl,dc=com?one #nss_base_networks ou=Networks,dc=padl,dc=com?one #nss_base_protocols ou=Protocols,dc=padl,dc=com?one #nss_base_rpc ou=Rpc,dc=padl,dc=com?one #nss_base_ethers ou=Ethers,dc=padl,dc=com?one

Page 17: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

17

#nss_base_netmasks ou=Networks,dc=padl,dc=com?ne #nss_base_bootparams ou=Ethers,dc=padl,dc=com?one #nss_base_aliases ou=Aliases,dc=padl,dc=com?one #nss_base_netgroup ou=Netgroup,dc=padl,dc=com?one # attribute/objectclass mapping # Syntax: #nss_map_attribute rfc2307attribute mapped_attribute #nss_map_objectclass rfc2307objectclass mapped_objectclass # configure --enable-nds is no longer supported. # NDS mappings #nss_map_attribute uniqueMember member # Services for UNIX 3.5 mappings #nss_map_objectclass posixAccount User #nss_map_objectclass shadowAccount User #nss_map_attribute uid msSFU30Name #nss_map_attribute uniqueMember msSFU30PosixMember #nss_map_attribute userPassword msSFU30Password #nss_map_attribute homeDirectory msSFU30HomeDirectory #nss_map_attribute homeDirectory msSFUHomeDirectory #nss_map_objectclass posixGroup Group #pam_login_attribute msSFU30Name #pam_filter objectclass=User #pam_password ad # configure --enable-mssfu-schema is no longer supported. # Services for UNIX 2.0 mappings #nss_map_objectclass posixAccount User #nss_map_objectclass shadowAccount user #nss_map_attribute uid msSFUName #nss_map_attribute uniqueMember posixMember #nss_map_attribute userPassword msSFUPassword #nss_map_attribute homeDirectory msSFUHomeDirectory #nss_map_attribute shadowLastChange pwdLastSet #nss_map_objectclass posixGroup Group #nss_map_attribute cn msSFUName #pam_login_attribute msSFUName #pam_filter objectclass=User #pam_password ad # RFC 2307 (AD) mappings #nss_map_objectclass posixAccount user #nss_map_objectclass shadowAccount user #nss_map_attribute uid sAMAccountName #nss_map_attribute homeDirectory unixHomeDirectory #nss_map_attribute shadowLastChange pwdLastSet #nss_map_objectclass posixGroup group #nss_map_attribute uniqueMember member #pam_login_attribute sAMAccountName #pam_filter objectclass=User #pam_password ad # configure --enable-authpassword is no longer supported # AuthPassword mappings #nss_map_attribute userPassword authPassword # AIX SecureWay mappings #nss_map_objectclass posixAccount aixAccount #nss_base_passwd ou=aixaccount,?one #nss_map_attribute uid userName #nss_map_attribute gidNumber gid #nss_map_attribute uidNumber uid #nss_map_attribute userPassword passwordChar #nss_map_objectclass posixGroup aixAccessGroup #nss_base_group ou=aixgroup,?one #nss_map_attribute cn groupName #nss_map_attribute uniqueMember member #pam_login_attribute userName #pam_filter objectclass=aixAccount #pam_password clear # Netscape SDK LDAPS #ssl on #ssl off # Netscape SDK SSL options #sslpath /etc/ssl/certs #sslpath /var/lib/ldap/certs/Client

Page 18: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

18

# OpenLDAP SSL mechanism # start_tls mechanism uses the normal LDAP port, LDAPS typically 636 #ssl start_tls #ssl on # OpenLDAP SSL options # Require and verify server certificate (yes/no) # Default is to use libldap's default behavior, which can be configured in # /etc/openldap/ldap.conf using the TLS_REQCERT setting. The default for # OpenLDAP 2.0 and earlier is "no", for 2.1 and later is "yes". #tls_checkpeer yes # CA certificates for server certificate verification # At least one of these are required if tls_checkpeer is "yes" #tls_cacertfile /etc/ssl/ca.cert #tls_cacertfile /var/lib/ldap/certs/cacert.pem #tls_cacertdir /var/lib/ldap/certs # Seed the PRNG if /dev/urandom is not provided #tls_randfile /var/run/egd-pool # SSL cipher suite # See man ciphers for syntax tls_ciphers TLSv1 # Client certificate and key # Use these, if your server requires client authentication. #tls_cert /var/lib/ldap/certs/Client/ldap.client.pem #tls_key /var/lib/ldap/certs/Client/ldap.client.key.pem # Disable SASL security layers. This is needed for AD. #sasl_secprops maxssf=0 # Override the default Kerberos ticket cache location. #krb5_ccname FILE:/etc/.ldapcache # SASL mechanism for PAM authentication - use is experimental # at present and does not support password policy control #pam_sasl_mech DIGEST-MD5

Ahora, ejecutando getent passwd debería aparecer el usuario test: root@xxxx: getent passwd root:x:0:0:Admin:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh dhcp:x:100:101::/nonexistent:/bin/false syslog:x:101:102::/home/syslog:/bin/false klog:x:102:103::/home/klog:/bin/false hplip:x:103:7:HPLIP system user,,,:/var/run/hplip:/bin/false avahi-autoipd:x:104:112:Avahi autoip daemon,,,:/var/lib/avahi-autoipd:/bin/false messagebus:x:105:113::/var/run/dbus:/bin/false avahi:x:106:114:Avahi mDNS daemon,,,:/var/run/avahi-daemon:/bin/false gdm:x:107:116:Gnome Display Manager:/var/lib/gdm:/bin/false haldaemon:x:108:117:Hardware abstraction layer,,,:/home/haldaemon:/bin/false hector:x:1000:1000:Hector Blanco,,,:/home/hector:/bin/bash openldap:x:109:120:OpenLDAP Server Account,,,:/var/lib/ldap:/bin/false sshd:x:110:65534::/var/run/sshd:/usr/sbin/nologin test:*:2000:2000:Test User:/home/test:/bin/bash

Page 19: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

19

Efectivamente, aparece al final. Puede observarse que en campo correspondiente al password aparece un *. Eso es porque este usuario no es shadow. Para que lo sea, hay que añadir un nuevo atributo a nuestro usuario en LDAP: hay que añadirle la objectClass: shadowAccount. En nuestro caso, estos fueron sus campos:

objectClass shadowAccount shadowExpire -1 shadowFlag 0 shadowInactive -1 shadowLastChange 11700 shadowMax 999999 shadowMin 0 shadowWarning 7

Ahora ya sí: root@xxxx: getent passwd root:x:0:0:Admin:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh [. . .] openldap:x:109:120:OpenLDAP Server Account,,,:/var/lib/ldap:/bin/false sshd:x:110:65534::/var/run/sshd:/usr/sbin/nologin test:x:2000:2000:Test User:/home/test:/bin/bash

Ahora debería ser posible crear un fichero cualquiera y establecer como propietario al usuario test del grupo test (con el comando chown test:test <fichero>)

2.3.3 Posibles problemas Parece que existe un bug4 en Ubuntu de manera que si el servidor LDAP no está funcionando, y ya se ha configurado /etc/nsswitch.conf para que la resolución de bases de datos se haga con LDAP (es decir, está con passwd files ldap), el Kernel log daemon se cuelga, bloqueando el proceso de arranque (en la consola aparece Login: pero no llega a arrancar el Gdm y el sistema no responde). Yo modifiqué ligeramente el script de arranque de slapd para intentar evitar que esto ocurriese. Lo primero es crear dos copias de /etc/nsswitch.conf en un directorio aparte (en mi caso /etc/ldap/MisChastillas): una de ellas con la resolución a través de LDAP y otra con la resolución en compat (como está inicialmente),de manera que si el arranque de LDAP no es correcto (slapd no ha creado un fichero de Pid) se cree un enlace simbólico desde /etc/nsswitch.conf al fichero que contiene la resolución clásica con compat, mientras que si está correctamente arrancado, el enlace simbólico se hace hacia el fichero con la resolución por LDAP. Por otra parte, esta modificación cuando slapd se detiene, deja /etc/nsswitch.conf apuntando a la versión que resuelve sin LDAP. /etc/ldap/MisChastillas/nsswitch.conf.conLdap /etc/ldap/MisChastillas/nsswitch.conf.Sin.Ldap # /etc/nsswitch.conf # # Example configuration of GNU Name Service Switch functionality. # If you have the glibc-doc-reference' and `info' packages # installed, try: info libc "Name Service Switch"' for # information about this file. passwd: files ldap group: files ldap shadow: files ldap hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4

# /etc/nsswitch.conf # # Example configuration of GNU Name Service Switch functionality. # If you have the glibc-doc-reference' and `info' packages # installed, try: info libc "Name Service Switch"' for information # about this file. passwd: compat group: compat shadow: compat hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4

4 Información sobre el bug: https://bugs.launchpad.net/ubuntu/+source/openldap2/+bug/150006 http://www.openldap.org/lists/openldap-technical/200802/msg00038.html

Page 20: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

20

networks: files protocols: db files services: db files ethers: db files rpc: db files netgroup: nis

networks: files protocols: db files services: db files ethers: db files rpc: db files netgroup: nis

A continuación, modificar los métodos start() y stop() del script de inicio de LDAP (/etc/init.d/slapd). En la versión que nos ocupa, estos métodos se encontraban entre las líneas 179 y 210 de dicho fichero, y quedaron así: # Start the OpenLDAP daemons start() { echo -n "Starting OpenLDAP:" trap 'report_failure' 0 start_slapd start_slurpd trap "-" 0 rm /etc/nsswitch.conf if [ -f "$SLAPD_PIDFILE" ]; then echo -n "\nSlapdRunning (PID found): Moviendo fichero Nsswitch" ln -s /etc/ldap/MisChastillas/nsswitch.conf.ConLdap /etc/nsswitch.conf else echo -n "\nError rasing SLAPD" ln -s /etc/ldap/MisChastillas/nsswitch.conf.SinLdap /etc/nsswitch.conf fi echo . } # Stop the OpenLDAP daemons stop() { echo -n "Stopping OpenLDAP:" trap 'report_failure' 0 stop_slurpd stop_slapd rm /etc/nsswitch.conf ln -s /etc/ldap/MisChastillas/nsswitch.conf.SinLdap /etc/nsswitch.conf trap "-" 0 echo . }

Page 21: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

21

3. Instalación y configuración del cliente Linux. 3.1 Instalación del software. Es probable que ya esté instalado, pero por si acaso: ~#apt-get install libldap2

Desde luego sí serán necesarios: ~#apt-get install libnss-ldap libpam-ldap nscd

El primero (libnss-ldap) es para la resolución de nombres (es decir, para que al hacer getent passwd en el cliente aparezca también el usuario “test” que está en el servidor LDAP. El segundo (libpam-ldap) es para poder utilizar servicios que requieran autentificación con los datos de passwords, usuarios… que existen en el servidor LDAP (para poder iniciar sesión con el usuario “test”, por ejemplo). El tercero es un cacheador de nombres para que la resolución se pueda hacer desde cualquier usuario.

3.2 Indicar el servidor al que conectarse. Lo primero es decirle al sistema qué servidor debe utilizar para consultas al servidor. Eso se hace en el fichero /etc/ldap/ldap.conf. En este caso, y de momento, se utiliza una conexión sin encriptar (al puerto 389). El servidor está iniciado con ldap://xxxx:389, así que desde la máquina cliente se debe poder saber a qué IP corresponde ese hostname, es decir que un ping xxxx devuelva una respuesta satisfactoria. Si este nombre no aparece en los DNS del sistema (que será lo más probable), la forma más fácil es retocar el fichero /etc/hosts y añadir la siguiente línea: 192.168.1.30 xxxx.Jome xxxx

Por claridad, es recomendable ponerlo justo antes de la sección de IPv6. Con esto, se puede modificar /etc/ldap/ldap.conf indicando cual va a ser el servidor por defecto (para eso vale el fichero ldap.conf: para indicar opciones de LDAP por defecto a todo el sistema). El fichero /etc/ldap/ldap.conf puede quedar así: # $OpenLDAP: pkg/ldap/libraries/libldap/ldap.conf,v 1.9 2000/09/04 19:57: # # LDAP Defaults # # See ldap.conf(5) for details # This file should be world readable but not world writable. #BASE dc=example, dc=com BASE dc=jome URI ldap://xxxx:389 #URI ldap://ldap.example.com ldap://ldap-master.example.com:666

Page 22: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

22

3.3 Resolución de nombres del sistema Al igual que se había explicado en el caso del servidor, (página 14) hay que modificar la forma de resolver los nombres en el sistema, indicando que se debe usar LDAP. Para ello, modificar las entradas passwd, shadow y hosts de /etc/nsswitch.conf para que quede: passwd: files ldap group: files ldap shadow: files ldap

A continuación, y como se hacía también en el caso del servidor (página 14), hay que indicar con qué entradas de LDAP deben corresponderse las entradas de las bases de datos locales. Como se ha adelantado en el punto 3.1, eso se hace con el fichero /etc/libnss-ldap.conf (a diferencia de Ubuntu, en el que se hacía en /etc/ldap.conf). Es muy probable que al instalar el paquete libnss-ldap, se hayan hecho una serie de preguntas como cual es el servidor LDAP (que es xxxx), qué usuario tiene permisos de administración (cn=admin,dc=jome), la versión de LDAP a usar (3)…, preguntas que ya habrán dado pie a una cierta auto-configuración de este fichero libnss-ldap.conf, de manera que lo único que haya que cambiar sean las entradas en las que se le dice al sistema con qué tablas de la base de datos LDAP debe hacer corresponder a las bases de datos del sistema. Debe quedar una cosa parecida a esto (NOTA: Se han eliminado bloques completos de comentarios para que ocupe menos. En los puntos en los que se ha eliminado información, aparece: [ . . .]) ###DEBCONF### # the configuration of this file will be done by debconf as long as the # first line of the file says '###DEBCONF###' # # Your LDAP server. Must be resolvable without using LDAP. # Multiple hosts may be specified, each separated by a # space. How long nss_ldap takes to failover depends on # whether your LDAP client library supports configurable # network or connect timeouts (see bind_timelimit). #host 127.0.0.1 # The distinguished name of the search base. base dc=jome # Another way to specify your LDAP server is to provide an uri ldap://xxxx/ # Unix Domain Sockets to connect to a local LDAP Server. #uri ldap://127.0.0.1/ #uri ldaps://127.0.0.1/ #uri ldapi://%2fvar%2frun%2fldapi_sock/ # Note: %2f encodes the '/' used as directory separator # The LDAP version to use (defaults to 3 # if supported by client library) ldap_version 3 # The distinguished name to bind to the server with. # Optional: default is to bind anonymously. # Please do not put double quotes around it as they # would be included literally. #binddn cn=proxyuser,dc=padl,dc=com

Page 23: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

23

# The credentials to bind with. # Optional: default is no credential. #bindpw secret # The distinguished name to bind to the server with # if the effective user ID is root. Password is # stored in /etc/libnss-ldap.secret (mode 600) # Use 'echo -n "mypassword" > /etc/libnss-ldap.secret' instead # of an editor to create the file. rootbinddn cn=Admin,dc=jome # The port. # Optional: default is 389. #port 389 # The search scope. #scope sub #scope one #scope base # Search timelimit #timelimit 30

[ . . . ]

# Remove old password first, then update in # cleartext. Necessary for use with Novell # Directory Services (NDS) #pam_password nds # RACF is an alias for the above. For use with # IBM RACF #pam_password racf # Update Active Directory password, by # creating Unicode password and updating # unicodePwd attribute. #pam_password ad # Use the OpenLDAP password change # extended operation to update the password. #pam_password exop # Redirect users to a URL or somesuch on password # changes. #pam_password_prohibit_message Please visit http://internal to change your password # Use backlinks for answering initgroups() #nss_initgroups backlink # Enable support for RFC2307bis (distinguished names in group # members) #nss_schema rfc2307bis # RFC2307bis naming contexts # Syntax: # nss_base_XXX base?scope?filter # where scope is {base,one,sub} # and filter is a filter to be &'d with the # default filter. # You can omit the suffix eg: # nss_base_passwd ou=People, # to append the default base DN but this # may incur a small performance impact. nss_base_passwd ou=People,dc=jome?one nss_base_shadow ou=People,dc=jome?one nss_base_group ou=Groups,dc=jome?one nss_base_hosts ou=Hosts,dc=jome?one #nss_base_services ou=Services,dc=padl,dc=com?one #nss_base_networks ou=Networks,dc=padl,dc=com?one

Page 24: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

24

#nss_base_protocols ou=Protocols,dc=padl,dc=com?one #nss_base_rpc ou=Rpc,dc=padl,dc=com?one #nss_base_ethers ou=Ethers,dc=padl,dc=com?one #nss_base_netmasks ou=Networks,dc=padl,dc=com?ne #nss_base_bootparams ou=Ethers,dc=padl,dc=com?one #nss_base_aliases ou=Aliases,dc=padl,dc=com?one #nss_base_netgroup ou=Netgroup,dc=padl,dc=com?one # attribute/objectclass mapping # Syntax: #nss_map_attribute rfc2307attribute mapped_attribute #nss_map_objectclass rfc2307objectclass mapped_objectclass

[ . . . ]

# CA certificates for server certificate verification # At least one of these are required if tls_checkpeer is "yes" #tls_cacertfile /etc/ssl/ca.cert #tls_cacertdir /etc/ssl/certs # Seed the PRNG if /dev/urandom is not provided #tls_randfile /var/run/egd-pool # SSL cipher suite # See man ciphers for syntax #tls_ciphers TLSv1 # Client certificate and key # Use these, if your server requires client authentication. #tls_cert #tls_key # Disable SASL security layers. This is needed for AD. #sasl_secprops maxssf=0 # Override the default Kerberos ticket cache location. #krb5_ccname FILE:/etc/.ldapcache

Efectivamente, con esto ya se “ve” el usuario “test”: Enano:/tmp# getent passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh Debian-exim:x:100:102::/var/spool/exim4:/bin/false statd:x:101:65534::/var/lib/nfs:/bin/false identd:x:102:65534::/var/run/identd:/bin/false hector:x:1000:1000:hector,,,:/home/hector:/bin/bash test:x:2000:2000:Test User:/home/test:/bin/bash

Y se pueden tener ficheros cuyo dueño sea “test”: Enano:/tmp# touch prueba

Enano:/tmp# chown test:test prueba

Page 25: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

25

Enano:/tmp# ls -l total 3 -rw-r--r-- 1 test test 0 2008-04-12 23:53 prueba

Si el servidor LDAP se cayese, quedarían el Uid y el Gid preservados: Enano:/tmp# ls -l total 3 -rw-r--r-- 1 2000 2000 0 2008-04-12 23:53 prueba

Hay que decir que el password para el usuario administrador de LDAP (cn=admin, dc=jome) debe estar almacenado en texto claro en /etc/libnss-ldap.secret. Por eso, ese fichero únicamente debe ser legible por root: Enano:/etc# ls –l /etc/libnss-ldap.secret -rw------- 1 root root 8 2008-01-12 23:47 /etc/libnss-ldap.secret

Esto debería ser suficiente para entrar en sesión con test. De momento, la única manera de hacerlo es pasar desde el usuario root al usuario test, porque cuando root quiere convertirse en un usuario “normal”, no se le pide password. Enano:~#su test test@Enano:/root$

3.4 Haciendo login. Ahora solo nos queda que el usuario test pueda loguearse. Para ello, hay que retocar el fichero /etc/pam_ldap.conf. De forma resumida (sin comentarios) porque es prácticamente igual que /etc/libnss-ldap.conf), debe quedar: ###DEBCONF### base dc=jome uri ldap://xxxx/ ldap_version 3 rootbinddn cn=Admin,dc=jome pam_password md5 # RFC2307bis naming contexts # Syntax: # nss_base_XXX base?scope?filter # where scope is {base,one,sub} # and filter is a filter to be &'d with the # default filter. # You can omit the suffix eg: # nss_base_passwd ou=People, # to append the default base DN but this # may incur a small performance impact. nss_base_passwd ou=People,dc=jome?one nss_base_shadow ou=People,dc=jome?one nss_base_group ou=Groups,dc=jome?one nss_base_hosts ou=Hosts,dc=jome?one #nss_base_services ou=Services,dc=padl,dc=com?one #nss_base_networks ou=Networks,dc=padl,dc=com?one #nss_base_protocols ou=Protocols,dc=padl,dc=com?one

Page 26: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

26

Luego hay que modificar también los ficheros de pilas PAM (que se encuentran en /etc/pam.d/) Conviene entender que, en Linux, cuando un usuario intenta ejecutar algún servicio que requiere validación, el sistema acude a los archivos de /etc/pam.d/ y mira con qué modulo PAM debe intentar autentificar el servicio en cuestión (más información en http://www.linuxjournal.com/article/2120). Hay unos ficheros comunes que comienzan por common- que se van “importando” conforme se necesitan en las pilas PAM de los servicios que requieren autentificación. Esos son los que hay que modificar5 (aunque no es necesario modificar common-session). • common-account (Qué hacer para a la hora de mapear cuentas del sistema) account sufficient pam_ldap.so account required pam_unix.so

• common-auth (Qué hacer cuando se quiera autentificar un usuario) auth sufficient pam_ldap.so auth required pam_unix.so use_first_pass nullok_secure

• common-password (Qué hacer cuando se quieran cambiar contraseñas) password sufficient pam_ldap.so md5 password required pam_unix.so nullok obscure min4 max8 md5

Así ya debería poderse entrar en el sistema con el usuario test, e incluso cambiar su password con el comando “estándar” passwd. Se puede observar que, efectivamente, al modificar el pasword se modifica en LDAP. test@Enano:/$passwd Enter login(LDAP) password:test New password: testar Re-enter new password:testar LDAP password information changed for test passwd: contraseña actualizada correctamente

Eso sí: como en realidad su directorio home no existe, el sistema lo reenviará al directorio raíz / (al loguearnos aparecerá un mensaje del estilo No directory, logging in with HOME=/) Una buena manera de comprobar que la configuración PAM funciona correctamente es utilizando el comando pamtest que proporciona el paquete libpam-dotfile. Hace pruebas contra los módulos PAM (se explica al final de http://informatica.iescuravalera.es/iflica/gtfinal/libro/x4915.html) Una vez instalado (con ~# apt-get install libpam-dotfile) podrá chequearse si un determinado usuario consigue autentificarse en un determinado servicio. Por ejemplo, para saber si el usuario test puede cambiar su contraseña, se ejecutaría: Enano:~# pamtest passwd test Trying to authenticate <test> for service <passwd>. Password: test

5 Utilizado: http://help.ubuntu.com/community/LDAPClientAuthentication

Page 27: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

27

Authentication successful. Sin embargo, al intentar hacer login con un usuario inexistente: Enano:~# pamtest login pepe Trying to authenticate <pepe> for service <login>. Password: pepe Failed to authenticate: User not known to the underlying authentication module

Page 28: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

28

4. Introducción de TLS Para hacer esto se ha seguido la guía encontrada en http://www.openldap.org/pub/ksoper/OpenLDAP_TLS.html (puntos 4.2 en adelante y 5) Si no se dispone de una entidad certificadora externa, hay que crear una propia. Esto será suficiente para una red local.

4.1 Creando la entidad certificadora (CA) Esto puede requerir la instalación de herramientas SSL (paquete openssl) Primero hay que elegir un lugar para almacenar la entidad certificadora. En este caso se eligió /var/lib/ldap/certs. Mucho cuidado:. Si se reconfigura el servidor slapd (~$dpkg-reconfigure slapd) este directorio se borrará. root@xxxx:/var/lib/ldap/certs# mkdir myCA root@xxxx:/var/lib/ldap/certs# cd myCA/ root@xxxx:/var/lib/ldap/certs/myCA# /usr/lib/ssl/misc/CA.sh -newca

CA certificate filename (or enter to create) Making CA certificate ... Generating a 1024 bit RSA private key ......................++++++ ....++++++ writing new private key to './demoCA/private/./cakey.pem' Enter PEM pass phrase: rootCA Verifying - Enter PEM pass phrase: rootCA ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:es State or Province Name (full name) [Some-State]:Aragon Locality Name (eg, city) []:Zaragoza Organization Name (eg, company) [Internet Widgits Pty Ltd]:certificadora de mi casa Organizational Unit Name (eg, section) []:ninguna Common Name (eg, YOUR name) []:name Email Address []:[email protected] Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:challenge An optional company name []:ninguno Using configuration from /usr/lib/ssl/openssl.cnf Enter pass phrase for ./demoCA/private/./cakey.pem: rootCA Check that the request matches the signature Signature ok Certificate Details: Serial Number: 0 (0x0) Validity Not Before: Apr 10 13:59:03 2008 GMT Not After : Apr 10 13:59:03 2011 GMT Subject: countryName = es

Page 29: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

29

stateOrProvinceName = Aragon organizationName = certificadora de mi casa organizationalUnitName = ninguna commonName = name emailAddress = [email protected] X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: C8:9D:23:B6:F6:CF:25:CA:07:31:50:C7:75:22:B7:B6:8F:D2:5B:F2 X509v3 Authority Key Identifier: keyid:C8:9D:23:B6:F6:CF:25:CA:07:31:50:C7:75:22:B7:B6:8F:D2:5B:F2 Certificate is to be certified until Apr 10 13:59:03 2011 GMT (1095 days) Write out database with 1 new entries Data Base Updated

Esto debería crear un directorio llamado demoCA con todos los datos necesarios de la entidad certificadora (incluyendo su propio certificado, cacert.pem) root@xxxx:/var/lib/ldap/certs/myCA# ls -l demoCA/ total 40 -rw-r--r-- 1 root root 3313 2008-04-10 15:59 cacert.pem -rw-r--r-- 1 root root 802 2008-04-10 15:58 careq.pem drwxr-xr-x 2 root root 4096 2008-04-10 15:56 certs drwxr-xr-x 2 root root 4096 2008-04-10 15:56 crl -rw-r--r-- 1 root root 133 2008-04-10 15:59 index.txt -rw-r--r-- 1 root root 21 2008-04-10 15:59 index.txt.attr -rw-r--r-- 1 root root 0 2008-04-10 15:56 index.txt.old drwxr-xr-x 2 root root 4096 2008-04-10 15:59 newcerts drwxr-xr-x 2 root root 4096 2008-04-10 15:56 private -rw-r--r-- 1 root root 3 2008-04-10 15:59 serial -rw-r--r-- 1 root root 3 2008-04-10 15:56 serial.old

4.2 Creando certificados de las máquinas Ahora hay que crear el certificado del servidor y de los clientes para que la CA lo firme. Técnicamente es una clave RSA, pero es preferible no llamarla “key” porque está sin firmar. La “key” será este certificado firmado por la CA. Cuidado: aquí es importante que el “Common name” que preguntará durante el proceso sea el hostname de la máquina que se va a certificar con este certificado. En el caso del servidor, xxxx, y en el del cliente, Enano. Si no es así, el certificado no será válido. El proceso para el servidor y para los clientes es igual, pero cambiando el “Common name”. Como ejemplo, se detalla lo hecho para obtener un certificado para el servidor: root@xxxx:/var/lib/ldap/certs# openssl req -newkey rsa:1024 -nodes -keyout newreq.pem -out newreq.pem Generating a 1024 bit RSA private key .............................++++++ .++++++ writing new private key to 'newreq.pem' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN.

Page 30: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

30

There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:es State or Province Name (full name) [Some-State]:Aragon Locality Name (eg, city) []:Zaragoza Organization Name (eg, company) [Internet Widgits Pty Ltd]:jome Organizational Unit Name (eg, section) []:ninguna

Common Name (eg, YOUR name) []:xxxx Email Address []: [email protected] Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:challenge An optional company name []:ninguno

Efectivamente, el “request” se ha creado root@xxxx:/var/lib/ldap/certs# ls myCA newreq.pem

Ahora, que lo firme la entidad certificadora. Para que ésta lo “vea”, tiene que estar dentro del directorio myCA/ root@xxxx:/var/lib/ldap/certs# mv newreq.pem myCA/

root@xxxx:/var/lib/ldap/certs# cd myCA/ root@xxxx:/var/lib/ldap/certs/myCA# /usr/lib/ssl/misc/CA.sh -sign Using configuration from /usr/lib/ssl/openssl.cnf Enter pass phrase for ./demoCA/private/cakey.pem: rootCA

La que se haya puesto al crear la CA

Check that the request matches the signature Signature ok Certificate Details: Serial Number: 1 (0x1) Validity Not Before: Apr 10 14:23:12 2008 GMT Not After : Apr 10 14:23:12 2009 GMT Subject: countryName = es stateOrProvinceName = Aragon localityName = Zaragoza organizationName = jome organizationalUnitName = ninguna commonName = xxxx emailAddress = [email protected] X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 28:F0:5F:D8:7E:33:93:67:ED:21:7A:E3:4B:5E:0A:53:AF:70:4B:74 X509v3 Authority Key Identifier: keyid:C8:9D:23:B6:F6:CF:25:CA:07:31:50:C7:75:22:B7:B6:8F:D2:5B:F2 Certificate is to be certified until Apr 10 14:23:12 2009 GMT (365 days) Sign the certificate? [y/n]:y 1 out of 1 certificate requests certified, commit? [y/n]y Write out database with 1 new entries Data Base Updated Certificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption

Page 31: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

31

Issuer: C=es, ST=Aragon, O=certificadora de mi casa, OU=ninguna, CN=name/[email protected] Validity Not Before: Apr 10 14:23:12 2008 GMT Not After : Apr 10 14:23:12 2009 GMT Subject: C=es, ST=Aragon, L=Zaragoza, O=jome, OU=ninguna, CN=xxxx/[email protected] Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:e8:31:47:ad:7c:ce:1d:41:84:7e:44:f9:11:52: ff:a7:f0:33:fd:c1:ae:c3:9b:01:0b:b7:9b:2d:fa: 22:cb:15:e2:a7:57:a1:f1:02:8a:c7:8e:2a:c2:c6: 21:a0:70:ea:ff:35:0b:2c:23:c8:f7:9d:9f:4f:d2: 1f:a1:7d:b1:f7:7c:2d:f2:0f:9f:58:af:6e:ea:5c: 38:71:9e:d3:dd:f6:22:77:c7:7c:16:b2:52:8f:4c: 14:c1:2a:cb:8a:0f:e9:0c:75:d0:35:40:57:01:50: 8b:8f:3e:ce:75:ff:77:28:9a:37:6a:28:61:94:dc: 57:1a:4d:b9:c1:d9:73:3f:9d Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 28:F0:5F:D8:7E:33:93:67:ED:21:7A:E3:4B:5E:0A:53:AF:70:4B:74 X509v3 Authority Key Identifier: keyid:C8:9D:23:B6:F6:CF:25:CA:07:31:50:C7:75:22:B7:B6:8F:D2:5B:F2 Signature Algorithm: sha1WithRSAEncryption 3a:59:d7:e0:b1:11:5a:83:37:51:24:98:8a:a2:e5:58:b1:b3: f7:a0:4f:3f:3a:6e:c9:f9:b6:e9:75:9d:a3:f9:41:a7:5d:43: 7e:33:90:a2:88:a4:d8:57:da:fa:04:d3:f7:f4:97:2c:c1:c5: 2e:6e:bb:a6:b3:0a:9a:db:ff:8d:77:63:17:89:ea:b1:ff:f0: 43:9f:1e:c9:52:41:84:39:07:23:43:52:1c:98:5a:a6:8c:24: 00:9b:e0:11:b7:78:9e:74:59:2b:9d:a0:3d:c4:c8:75:f4:ed: a3:2a:df:68:01:20:9b:7f:4f:51:68:b6:aa:fe:b8:e2:f8:94: e9:1f -----BEGIN CERTIFICATE----- MIIDEjCCA<. . .> <. . .>/rji+JTpHw== -----END CERTIFICATE----- Signed certificate is in newcert.pem

Efectivamente, ahí aparece: root@xxxx:/var/lib/ldap/certs/myCA# ls demoCA newcert.pem newreq.pem

Ahora solo queda mover los datos necesarios (la CA, key del servidor y key del servidor firmada) a sus directorios (pueden ser cualquiera). root@xxxx: mkdir /var/lib/ldap/certs/Server root@xxxx:/var/lib/ldap/certs/myCA# cp demoCA/cacert.pem /var/lib/ldap/certs/cacert.pem root@xxxx:/var/lib/ldap/certs/myCA# mv newcert.pem /var/lib/ldap/certs/Server/server_crt.pem root@xxxx:/var/lib/ldap/certs/myCA# mv newreq.pem /var/lib/ldap/certs/Server/server_key.pem root@xxxx:/var/lib/ldap/certs/myCA# chmod 400 /var/lib/ldap/certs/Server/server_key.pem

Cuidado: Ahora el demonio que arranque LDAP tiene que tener permisos para leer estos certificados (si no, no arrancará). Tal y como está hecho hasta ahora, solo el usuario root tiene acceso (de solo lectura a la server_key.pem). Viendo /etc/default/slapd se observa una opción que dice: SLAPD_USER=”openldap” con lo cual, no podrá arrancar. Hay que cambiar al dueño de server_key.pem: root@xxxx: chown openldap /var/lib/ldap/certs/Server/server_key.pem

Page 32: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

32

La entidad certificadora recién creada puede usarse para crear los certificados de los clientes. Será como lo hecho para crear un certificado para el servidor y que la CA lo firme, pero cambiando el Common Name por el de los clientes. Por ejemplo, un cliente será la máquina “Enano”. Pues los pasos a seguir para crear un certificado para “Enano” son, de manera muy resumida: root@xxxx:/var/lib/ldap/certs# openssl req -newkey rsa:1024 -nodes -keyout newreq.pem -out newreq.pem

(Decirle que el Common name es “Enano”) root@xxxx:/var/lib/ldap/certs/myCA# /usr/lib/ssl/misc/CA.sh -sign

Esto proporcionará, al igual que antes, dos certificados (newreq.pem y newcert.pem). Estos certificados, y el de la entidad certificadora (cacert.pm) hay que llevarlos a la máquina “Enano”

4.3 Asegurando el servidor Para que el servidor arranque LDAP con TLS, añadir al final de /etc/ldap/slapd.conf lo siguiente: TLSCipherSuite HIGH:MEDIUM+SSLv2 TLSACertificateFile /var/lib/ldap/certs/cacert.pem TLSCertificateFile /var/lib/ldap/certs/Server/server_crt.pem TLSCertificateKeyFile /var/lib/ldap/certs/Server/server_key.pem TLSVerifyClient hard

Es importante saber los niveles de verificación del cliente. Pueden ser never | allow | try | demand,hard6.Lo ideal es hard.. Con esto, se debería poder arrancar el servidor siempre en modo seguro. Es decir, se puede editar /etc/default/slapd y hacer: SLAPD_SERVICES=”ldaps://xxxx:636 ldapi:///”

Reiniciar el servidor y ver que los cambios han quedado correctamente reflejados: root@xxxx:/home/hector# /etc/init.d/slapd restart Stopping OpenLDAP: slapd. Starting OpenLDAP: slapd root@xxxx:/home/hector# ps aux|grep slapd openldap 6999 0.0 0.1 15084 2700 ? Ssl 15:42 0:00 /usr/sbin/slapd -h ldaps://xxxx:636/ ldapi:/// -g openldap -u openldap -f /etc/ldap/slapd.conf root 7004 0.0 0.0 2988 772 pts/0 S+ 15:42 0:00 grep slapd

Se puede ver que el único puerto en el que LDAP está escuchando es el puerto seguro: root@xxxx:/home/hector# netstat -l -p -tcp Conexiones activas de Internet (solo servidores) Protocolo Recv-Q Send-Q Dirección Local Dirección Externa Estado PID/Program name tcp 0 0 *:kshell *:* ESCUCHAR 5982/inetd tcp 0 0 *:kerberos-adm *:* ESCUCHAR 5982/inetd tcp 0 0 *:pop3 *:* ESCUCHAR 5982/inetd tcp 0 0 *:www *:* ESCUCHAR 6241/apache2 tcp 0 0 *:ftp *:* ESCUCHAR 5982/inetd tcp 0 0 localhost:ipp *:* ESCUCHAR 5870/cupsd tcp 0 0 *:telnet *:* ESCUCHAR 5982/inetd

6 Más información en: http://www.openldap.org/pub/ksoper/OpenLDAP_TLS.html#5.1

Page 33: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

33

tcp 0 0 xxxx:kerberos *:* ESCUCHAR 5944/kdc tcp 0 0 localhost:kerberos *:* ESCUCHAR 5944/kdc tcp 0 0 xxxx:ldaps *:* ESCUCHAR 6999/slapd tcp 0 0 *:kx *:* ESCUCHAR 5982/inetd tcp6 0 0 *:ssh *:* ESCUCHAR 5836/sshd tcp6 0 0 ip6-localhost:ipp *:* ESCUCHAR 5870/cupsd tcp6 0 0 ip6-localhost:kerberos *:* ESCUCHAR 5944/kdc

4.4 Haciendo un cliente confiable En /etc/ldap/ldap.conf se permite indicar la ruta a la entidad certificadora (con la directiva TLS_CACERT) y si se debe intentar validar el certificado proporcionado por el servidor (con TLS_REQCERT). La opción más restrictiva y segura es hard (al igual que lo que ocurría con las opciones del aseguramiento del servidor, explicadas en la página 32) Así, un fichero /etc/ldap/ldap.conf viable podría ser: # $OpenLDAP: pkg/ldap/libraries/libldap/ldap.conf,v 1.9 2000/09/04 kurt Exp $ # # LDAP Defaults # # See ldap.conf(5) for details # This file should be world readable but not world writable. #BASE dc=example, dc=com BASE dc=jome URI ldaps://xxxx:636 #URI ldap://ldap.example.com ldap://ldap-master.example.com:666 TLS_CACERT /var/lib/ldap/certs/cacert.pem TLS_REQCERT hard

Por otro lado, hay que indicarle la ruta a los certificados. Esto no puede indicarse en fichero /etc/ldap/ldap.conf (que contiene opciones genéricas) y hay que crear, en cada directorio $HOME de los usuarios que se vayan a conectar al servidor un fichero llamado .ldaprc (o ldaprc, sin el punto) con esa información. Está bien explicado en http://www.openldap.org/pub/ksoper/OpenLDAP_TLS.html#5.2.1 Un fichero /root/.ldaprc válido sería: #/root/.ldaprc TLS_CERT /var/lib/ldap/certs/client_crt.pem TLS_KEY /var/lib/ldap/certs/client_key.pem

Aquí hay que tener cuidado con dos cosas:

1. Los contenidos de este fichero tienen prioridad sobre las opciones genéricas establecidas en /etc/ldap/ldap.conf (con lo cual, si hubiésemos puesto en .ldaprc que TLS_REQCERT never, no se intentaría chequear la validez del servidor).

2. El usuario al que pertenezca este fichero tiene que tener permisos para leer los certificados. Normalmente la client_key tendrá permisos a 400, es decir, solo root lo puede leer. En este caso, no hay problema, porque es root el usuario de este .ldaprc, pero podría ser que no.

Page 34: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

34

El siguiente paso es modificar los ficheros /etc/libnss-ldap.conf y /etc/pam_ldap.conf (si el cliente es Debian, como en el presente caso) o /etc/ldap.conf si el cliente fuese Ubuntu (como ocurre en el servidor, que actúa como cliente conectándose a sí mismo). Como para cualquiera de los casos, la configuración es igual, solamente se va a detallar el utilizado en xxxx (que, al ser una Ubuntu, se tratará del fichero /etc/ldap.conf). El lector será los suficientemente inteligente como para darse cuenta de que hay cosas, como las rutas a los certificados (opciones tls_cert y tls_key), que varían en función de la máquina en la que estén los ficheros. ###DEBCONF### ## ## Configuration of this file will be managed by debconf as long as the ## first line of the file says '###DEBCONF###' ## ## You should use dpkg-reconfigure to configure this file via debconf ## # # @(#)$Id: ldap.conf,v 1.38 2006/05/15 08:13:31 lukeh Exp $ # # This is the configuration file for the LDAP nameservice # switch library and the LDAP PAM module. # # PADL Software # http://www.padl.com # # Your LDAP server. Must be resolvable without using LDAP. # Multiple hosts may be specified, each separated by a # space. How long nss_ldap takes to failover depends on # whether your LDAP client library supports configurable # network or connect timeouts (see bind_timelimit). #host xxxx # The distinguished name of the search base. base dc=jome # Another way to specify your LDAP server is to provide an # uri with the server name. This allows to use # Unix Domain Sockets to connect to a local LDAP Server. #uri ldap://127.0.0.1/ #uri ldaps://127.0.0.1/ #uri ldapi://%2fvar%2frun%2fldapi_sock/ # Note: %2f encodes the '/' used as directory separator uri ldaps://xxxx:636 # The LDAP version to use (defaults to 3 # if supported by client library) ldap_version 3 # The distinguished name to bind to the server with. # Optional: default is to bind anonymously. #binddn cn=proxyuser,dc=padl,dc=com # The credentials to bind with. # Optional: default is no credential. #bindpw secret # The distinguished name to bind to the server with # if the effective user ID is root. Password is # stored in /etc/ldap.secret (mode 600) rootbinddn cn=Admin,dc=jome # The port. # Optional: default is 389. #port 636 # The search scope. #scope sub #scope one #scope base

Page 35: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

35

# Search timelimit #timelimit 30 # Bind/connect timelimit #bind_timelimit 30 # Reconnect policy: hard (default) will retry connecting to # the software with exponential backoff, soft will fail # immediately. #bind_policy hard # Idle timelimit; client will close connections # (nss_ldap only) if the server has not been contacted # for the number of seconds specified below. #idle_timelimit 3600 # Filter to AND with uid=%s #pam_filter objectclass=account # The user ID attribute (defaults to uid) #pam_login_attribute uid # Search the root DSE for the password policy (works # with Netscape Directory Server) #pam_lookup_policy yes # Check the 'host' attribute for access control # Default is no; if set to yes, and user has no # value for the host attribute, and pam_ldap is # configured for account management (authorization) # then the user will not be allowed to login. #pam_check_host_attr yes # Check the 'authorizedService' attribute for access # control # Default is no; if set to yes, and the user has no # value for the authorizedService attribute, and # pam_ldap is configured for account management # (authorization) then the user will not be allowed # to login. #pam_check_service_attr yes # Group to enforce membership of #pam_groupdn cn=PAM,ou=Groups,dc=padl,dc=com # Group member attribute #pam_member_attribute uniquemember # Specify a minium or maximum UID number allowed #pam_min_uid 1000 #pam_max_uid 0 # Template login attribute, default template user # (can be overriden by value of former attribute # in user's entry) #pam_login_attribute userPrincipalName #pam_template_login_attribute uid #pam_template_login nobody # HEADS UP: the pam_crypt, pam_nds_passwd, # and pam_ad_passwd options are no # longer supported. # # Do not hash the password at all; presume # the directory server will do it, if # necessary. This is the default. #pam_password md5 # Hash password locally; required for University of # Michigan LDAP server, and works with Netscape # Directory Server if you're using the UNIX-Crypt # hash mechanism and not using the NT Synchronization # service. #pam_password crypt # Remove old password first, then update in # cleartext. Necessary for use with Novell # Directory Services (NDS) #pam_password clear_remove_old #pam_password nds

Page 36: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

36

# RACF is an alias for the above. For use with # IBM RACF #pam_password racf # Update Active Directory password, by # creating Unicode password and updating # unicodePwd attribute. #pam_password ad # Use the OpenLDAP password change # extended operation to update the password. #pam_password exop # Redirect users to a URL or somesuch on password # changes. #pam_password_prohibit_message Please visit http://internal to change your password. # RFC2307bis naming contexts # Syntax: # nss_base_XXX base?scope?filter # where scope is {base,one,sub} # and filter is a filter to be &'d with the # default filter. # You can omit the suffix eg: # nss_base_passwd ou=People, # to append the default base DN but this # may incur a small performance impact. nss_base_passwd ou=People,dc=jome?one nss_base_shadow ou=People,dc=jome?one nss_base_group ou=Groups,dc=jome?one nss_base_hosts ou=Hosts,dc=jome? #nss_base_services ou=Services,dc=padl,dc=com?one #nss_base_networks ou=Networks,dc=padl,dc=com?one #nss_base_protocols ou=Protocols,dc=padl,dc=com?one #nss_base_rpc ou=Rpc,dc=padl,dc=com?one #nss_base_ethers ou=Ethers,dc=padl,dc=com?one #nss_base_netmasks ou=Networks,dc=padl,dc=com?ne #nss_base_bootparams ou=Ethers,dc=padl,dc=com?one #nss_base_aliases ou=Aliases,dc=padl,dc=com?one #nss_base_netgroup ou=Netgroup,dc=padl,dc=com?one # attribute/objectclass mapping # Syntax: #nss_map_attribute rfc2307attribute mapped_attribute #nss_map_objectclass rfc2307objectclass mapped_objectclass # configure --enable-nds is no longer supported. # NDS mappings #nss_map_attribute uniqueMember member # Services for UNIX 3.5 mappings #nss_map_objectclass posixAccount User #nss_map_objectclass shadowAccount User #nss_map_attribute uid msSFU30Name #nss_map_attribute uniqueMember msSFU30PosixMember #nss_map_attribute userPassword msSFU30Password #nss_map_attribute homeDirectory msSFU30HomeDirectory #nss_map_attribute homeDirectory msSFUHomeDirectory #nss_map_objectclass posixGroup Group #pam_login_attribute msSFU30Name #pam_filter objectclass=User #pam_password ad # configure --enable-mssfu-schema is no longer supported. # Services for UNIX 2.0 mappings #nss_map_objectclass posixAccount User #nss_map_objectclass shadowAccount user #nss_map_attribute uid msSFUName #nss_map_attribute uniqueMember posixMember #nss_map_attribute userPassword msSFUPassword #nss_map_attribute homeDirectory msSFUHomeDirectory #nss_map_attribute shadowLastChange pwdLastSet #nss_map_objectclass posixGroup Group #nss_map_attribute cn msSFUName #pam_login_attribute msSFUName #pam_filter objectclass=User #pam_password ad # RFC 2307 (AD) mappings

Page 37: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

37

#nss_map_objectclass posixAccount user #nss_map_objectclass shadowAccount user #nss_map_attribute uid sAMAccountName #nss_map_attribute homeDirectory unixHomeDirectory #nss_map_attribute shadowLastChange pwdLastSet #nss_map_objectclass posixGroup group #nss_map_attribute uniqueMember member #pam_login_attribute sAMAccountName #pam_filter objectclass=User #pam_password ad # configure --enable-authpassword is no longer supported # AuthPassword mappings #nss_map_attribute userPassword authPassword # AIX SecureWay mappings #nss_map_objectclass posixAccount aixAccount #nss_base_passwd ou=aixaccount,?one #nss_map_attribute uid userName #nss_map_attribute gidNumber gid #nss_map_attribute uidNumber uid #nss_map_attribute userPassword passwordChar #nss_map_objectclass posixGroup aixAccessGroup #nss_base_group ou=aixgroup,?one #nss_map_attribute cn groupName #nss_map_attribute uniqueMember member #pam_login_attribute userName #pam_filter objectclass=aixAccount #pam_password clear #pam_password md5 # Netscape SDK LDAPS #ssl on # Netscape SDK SSL options #sslpath /etc/ssl/certs #sslpath /var/lib/ldap/certs/Client # OpenLDAP SSL mechanism # start_tls mechanism uses the normal LDAP port, LDAPS typically 636 ssl start_tls # OpenLDAP SSL options # Require and verify server certificate (yes/no) # Default is to use libldap's default behavior, which can be configured in # /etc/openldap/ldap.conf using the TLS_REQCERT setting. The default for # OpenLDAP 2.0 and earlier is "no", for 2.1 and later is "yes". tls_checkpeer yes # CA certificates for server certificate verification # At least one of these are required if tls_checkpeer is "yes" tls_cacertfile /var/lib/ldap/certs/cacert.pem #tls_cacertdir /var/lib/ldap/certs # Seed the PRNG if /dev/urandom is not provided #tls_randfile /var/run/egd-pool # SSL cipher suite # See man ciphers for syntax tls_ciphers TLSv1 # Client certificate and key # Use these, if your server requires client authentication. tls_cert /var/lib/ldap/certs/Server/server_crt.pem tls_key /var/lib/ldap/certs/Server/server_key. #NOTA: En caso de ser el cliente seran las client_crt y client_key # Disable SASL security layers. This is needed for AD. #sasl_secprops maxssf=0 # Override the default Kerberos ticket cache location. #krb5_ccname FILE:/etc/.ldapcache # SASL mechanism for PAM authentication - use is experimental # at present and does not support password policy control #pam_sasl_mech DIGEST-MD5

Page 38: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

38

4.5 Posibles problemas A continuación se detallan algunos problemas que se encontraron a lo largo del proceso, así como sus posibles soluciones.

4.5.1 TLS Already started En alguna versión de LDAP, al poner la URI como ldaps://xxxx:636, el sistema ya sabe que debe cifrar la conexión, con lo cual, la opción ssl start_tls resulta redundante y puede que el sistema no responda. Si pensamos que el fichero /etc/libnss-ldap.conf es correcto, pero hacemos un getent passwd y no aparecen los usuarios LDAP (en el presente caso, no aparece el usuario “test”) se puede intentar averiguar si el problema es que el TLS ya está arrancado. Para ello, lo primero que se debe hacer es una búsqueda “manual” con TLS activado (-ZZ): Enano:~# ldapsearch –x –ZZ Ldap_start_tls: Operations error (1) additional info; TLS already started

La mejor solución en este caso es aprovechar la capacidad que TLS tiene de iniciar una sesión sin encriptar y luego negociar una encriptación: es decir dejar al servidor corriendo en un puerto inseguro (ldap://xxxx:389) y que luego se negocie una conexión encriptada. Para ello, mantener la configuración como se ha explicado hasta el momento pero a la hora de indicar la URI del servidor ésta se deja como ldap://xxxx:389 Recordemos que la URI aparece en el fichero /etc/default/slapd del servidor y en los ficheros de configuración de LDAP como cliente (es decir en /etc/ldap/ldap.conf, /etc/ldap.conf, o /etc/libnss-ldap.conf y /etc/pam_ldap.conf). De hecho, es como se explica en el tutorial que se ha seguido (http://www.openldap.org/pub/ksoper/OpenLDAP_TLS.html#5.2)

4.5.2 I have no name! Si el nivel de verificación en el servidor es muy alto (en /etc/ldap/slapd.conf la opción TLSVerifyClient es demand o hard) y no está instalado el demonio nscd en el cliente (como se explica en la página 21) es posible que no se pueda resolver el nombre de un usuario dado un UID. Esto ocurrirá con los usuarios que no tengan en sus directorios $HOME un fichero .ldaprc que apunte correctamente a los certificados del cliente. Al loguearnos puede aparecer este curioso problema: Enano login: test Password: test Last login: Mon Apr 14 01:36:20 2008 on tty2 Linux Enano 2.6.18-6-486 #1 SunFeb1022:06:33 UTC 2008 i586 The programs included with Debian GNU/Linux system are free software; The exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. No directory, logging in with HOME=/ I have no name!@Enano:/$

Es decir, que no es capaz de resolver el usuario que se corresponde con Uid=2000. De hecho, esto es lo que ocurre al hacer un whoami: I have no name!@Enano:/$ whoami whoami: cannot find name for user ID 2000

Page 39: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

39

4.5.3 Handshake failure Este es un fallo bastante común al ejecutar una búsqueda contra un servidor que requiere que los clientes estén certificados correctamente. Al ejecutar una búsqueda con ldapsearch obtenemos: test@Enano:/$ ldapsearch -x -ZZ ldap_start_tls: Can't contact LDAP server (-1) additional info: error:14094410:SSL routines:SSL3_READ_BYTES:/ sslv3 alert handshake failure

Eso es porque el cliente no está proporcionando los certificados correctamente. De hecho, al ejecutar el servidor en foreground y salida verbosa, aparece lo siguiente: root@xxxx:/home/hector# slapd -h "ldaps://xxxx:636" -d 1 @(#) $OpenLDAP: slapd 2.3.35 (Mar 5 2008 15:11:54) $ buildd@terranova:/build/buildd/openldap2.3-2.3.35/debian/build/servers/slapd daemon_init: listen on ldaps://xxxx:636

[. . . ] < Mucha salida de debug > [. . . ]

bdb_db_open: dbenv_open(/var/lib/ldap) slapd starting >>> slap_listener(ldaps://xxxx:636) connection_get(11): got connid=0 connection_read(11): checking for input on id=0 TLS trace: SSL_accept:before/accept initialization TLS trace: SSL_accept:SSLv3 read client hello A TLS trace: SSL_accept:SSLv3 write server hello A TLS trace: SSL_accept:SSLv3 write certificate A TLS trace: SSL_accept:SSLv3 write certificate request A TLS trace: SSL_accept:SSLv3 flush data TLS trace: SSL_accept:error in SSLv3 read client certificate A TLS trace: SSL_accept:error in SSLv3 read client certificate A connection_get(11): got connid=0 connection_read(11): checking for input on id=0 TLS trace: SSL3 alert write:fatal:handshake failure TLS trace: SSL_accept:error in SSLv3 read client certificate B TLS: can't accept. TLS: error:140890C7:SSL routines:SSL3_GET_CLIENT_CERTIFICATE:peer did not return a certificate s3_srvr.c:2476 connection_read(11): TLS accept failure error=-1 id=0, closing connection_closing: readying conn=0 sd=11 for close connection_close: conn=0 sd=11

Chequear que existe el fichero $HOME/.ldaprc y que en su contenido se han establecido correctamente TLS_CERT y TLS_KEY apuntando a los certificados del cliente.

Page 40: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

40

5. Autentificación de una máquina Windows Windows necesita Samba para funcionar y que los usuarios cumplan una serie de requisitos Samba, se necesitan una serie de campos extra para que Windows reconozca los usuarios de LDAP como usuarios Windows.

5.1 Configuración en el servidor. Para esta sección se ha utilizado el siguiente tutorial: http://download.gna.org/smbldap-tools/docs/samba-ldap-howto/

5.1.1 Instalando el software Instalar los siguientes paquetes (se detalla también la versión).

Paquete Versión samba 3.0.26a-1 samba-common 3.0.26a-1 smbclient 3.0.26a-1 smbldap-tools 0.9.5

Es muy importante utilizar la versión 0.9.57 de smblap-tools o posterior, ya que existen problemas graves a la hora de crear máquinas Samba en el servidor LDAP con versiones anteriores (no crea los campos Samba necesarios).

5.1.2 Añadir el esquema Samba a LDAP En el fichero /etc/ldap/slapd.conf, añadir el esquema samba.schema. En las primeras líneas aparecen los esquemas que se incluyen. Añadir /etc/ldap/schema/samba.schema de forma que quede así: # Allow LDAPv2 binds allow bind_v2 # This is the main slapd configuration file. See slapd.conf(5) for more # info on the configuration options. ####################################################################### # Global Directives: # Features to permit #allow bind_v2 # Schema and objectClass definitions include /etc/ldap/schema/core.schema include /etc/ldap/schema/cosine.schema include /etc/ldap/schema/nis.schema include /etc/ldap/schema/inetorgperson.schema include /etc/ldap/schema/samba.schema # Where the pid file is put. The init.d script # will not stop the server if you change this. pidfile /var/run/slapd/slapd.pid [ . . . ]

7 Descargable en: http://www.iallanis.info/smbldap-tools/development_release/smbldap-tools-0.9.5.tgz

Page 41: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

41

5.1.3. Configurar Samba Dejar el fichero de configuración /etc/samba/smb.conf así: [global] #Configuracion basica

workgroup = JOME security = user

netbios name = xxxx server string = xxxx PDC server Version %v encrypt passwords = yes enable privileges=yes #Configuració para ser el PDC maestro preferred master = yes local master = yes domain master = yes domain logons = yes

#Configuracion de logs log level = 4

debug level=3 syslog = 3 log file = /var/log/samba/samba.log max log size = 1000

#Configuracion LDAP

ldap admin dn = cn=Admin,dc=jome ldap delete dn = yes passdb backend = ldapsam:ldap://xxxx/

ldap user suffix = ou=People ldap group suffix = ou=Groups ldap machine suffix = ou=Hosts ldap passwd sync = Yes ldap suffix =dc=jome

ldap passwd sync = yes ldap ssl = start_tls #Configuracion programas varios

add machine script =/usr/local/sbin/smbldap-useradd -W ‘%u’ add user script = /usr/sbin/smbldap-useradd -a -m '%u'

delete user script = /usr/sbin/smbldap-userdel -r %u add group script = /usr/sbin/smbldap-groupadd -p '%g' delete group script = /usr/sbin/smbldap-groupdel '%g' add user to group script = /usr/sbin/smbldap-groupmod -m '%u' '%g' delete user from group script = /usr/sbin/smbldap-groupmod -x '%u' '%g' set primary group script = /usr/sbin/smbldap-usermod -g '%g' '%u' passwd program = /usr/sbin/smbldap-passwd '%u' printing = cups printcap name = CUPS

[netlogon]

comment = Network Logon Service path = /var/lib/samba/netlogon guest ok = Yes writeable = No browseable = No valid users=root @smbusers locking = No

[profiles]

comment = Profile Share path = /var/lib/samba/profiles read only = No

[print$]

comment = Printer Drivers path = /var/lib/samba/drivers browseable = yes guest ok = no read only = yes write list = Administrator

Page 42: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

42

Samba debe conocer el password del usuario administrador especificado en este fichero (en la línea ldap admin dn = cn=Admin,dc=jome). Se le proporciona ejecutando: ~# smbpasswd –w password_del_admin_LDAP Setting stored password for “cn=Admin,dc=jome” in secrets.tdb

(El password se almacenará en /var/lib/samba/secrets.tdb) Para comprobar que el fichero de configuración no contiene errores, ejecutar el comando testparm.

5.1.3 Configurar y utilizar las smbldap-tools 1. Descargarlas: root@xxxx:/usr/src/# wget http://www.iallanis.info/smbldap-tools/development_release/smbldap-tools-0.9.5.tgz

2. Descomprimir: root@xxxx:/usr/src/# tar -xfz smbldap-tools-0.9.5.tgz

3. Seguir las instrucciones que se encontrarán en smbldap-tools-

0.9.5/INSTALL, que dicen que hay que copiar los scripts a /usr/local/sbin o ejecutar:

root@xxxx:/usr/src/smbldap-tools-0.9.5# make install /usr/bin/install -m0755 smbldap-* smbldap_tools.pm /usr/sbin /usr/bin/install -m0644 smbldap.conf /etc//smbldap-tools/ /usr/bin/install -m0600 smbldap_bind.conf /etc//smbldap-tool Deberían quedar almacenadas en el directorio: /usr/sbin/ 4. Ejecutar ~# net getlocalsid y guardar el número que salga (es necesario en

el siguiente paso) root@xxxx:~# net getlocalsid SID for domain XXXX is: S-1-5-21-2710697030-1106397243-3057445555

5. Editar el fichero de configuración /etc/smbldap-tools/smbldap.conf para que quede con los valores correctos:

# $Source: $ # $Id: smbldap.conf,v 1.18 2005/05/27 14:28:47 jtournier Exp $ # # smbldap-tools.conf : Q & D configuration file for smbldap-tools # This code was developped by IDEALX (http://IDEALX.org/) and # contributors (their names can be found in the CONTRIBUTORS file). # # Copyright (C) 2001-2002 IDEALX # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software

Page 43: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

43

# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, # USA. # Purpose : # . be the configuration file for all smbldap-tools scripts ############################################################################## # # General Configuration # ############################################################################## # Put your own SID. To obtain this number do: "net getlocalsid". # If not defined, parameter is taking from "net getlocalsid" return SID="S-1-5-21-2710697030-1106397243-3057445555" # Domain name the Samba server is in charged. # If not defined, parameter is taking from smb.conf configuration file # Ex: sambaDomain="IDEALX-NT" sambaDomain="JOME" ############################################################################## # # LDAP Configuration # ############################################################################## # Notes: to use to dual ldap servers backend for Samba, you must patch # Samba with the dual-head patch from IDEALX. If not using this patch # just use the same server for slaveLDAP and masterLDAP. # Those two servers declarations can also be used when you have # . one master LDAP server where all writing operations must be done # . one slave LDAP server where all reading operations must be done # (typically a replication directory) # Slave LDAP server # Ex: slaveLDAP=127.0.0.1 # If not defined, parameter is set to "127.0.0.1" slaveLDAP="xxxx" # Slave LDAP port # If not defined, parameter is set to "389" slavePort="389" # Master LDAP server: needed for write operations # Ex: masterLDAP=127.0.0.1 # If not defined, parameter is set to "127.0.0.1" masterLDAP="xxxx" # Master LDAP port # If not defined, parameter is set to "389" masterPort="389" # Use TLS for LDAP # If set to 1, this option will use start_tls for connection # (you should also used the port 389) # If not defined, parameter is set to "1" ldapTLS="1" # How to verify the server's certificate (none, optional or require) # see "man Net::LDAP" in start_tls section for more details verify="require" # CA certificate # see "man Net::LDAP" in start_tls section for more details cafile="/var/lib/ldap/certs/cacert.pem" # certificate to use to connect to the ldap server # see "man Net::LDAP" in start_tls section for more details clientcert="/var/lib/ldap/certs/Server/server_crt.pem" # key certificate to use to connect to the ldap server # see "man Net::LDAP" in start_tls section for more details clientkey="/var/lib/ldap/certs/Server/server_key.pem" # LDAP Suffix # Ex: suffix=dc=IDEALX,dc=ORG suffix="dc=jome" # Where are stored Users

Page 44: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

44

# Ex: usersdn="ou=Users,dc=IDEALX,dc=ORG" # Warning: if 'suffix' is not set here, you must set the full dn for usersdn usersdn="ou=People,${suffix}" # Where are stored Computers # Ex: computersdn="ou=Computers,dc=IDEALX,dc=ORG" # Warning: if 'suffix' is not set here, you must set the full dn for computersdn computersdn="ou=Hosts,${suffix}" # Where are stored Groups # Ex: groupsdn="ou=Groups,dc=IDEALX,dc=ORG" # Warning: if 'suffix' is not set here, you must set the full dn for groupsdn groupsdn="ou=Groups,${suffix}" # Where are stored Idmap entries (used if samba is a domain member server) # Ex: groupsdn="ou=Idmap,dc=IDEALX,dc=ORG" # Warning: if 'suffix' is not set here, you must set the full dn for idmapdn # idmapdn="ou=Idmap,${suffix}" # Where to store next uidNumber and gidNumber available for new users and groups # If not defined, entries are stored in sambaDomainName object. # Ex: sambaUnixIdPooldn="sambaDomainName=${sambaDomain},${suffix}" # Ex: sambaUnixIdPooldn="cn=NextFreeUnixId,${suffix}" sambaUnixIdPooldn="sambaDomainName=${sambaDomain},${suffix}" # Default scope Used scope="sub" # Unix password encryption (CRYPT, MD5, SMD5, SSHA, SHA, CLEARTEXT) hash_encrypt="MD5" # if hash_encrypt is set to CRYPT, you may set a salt format. # default is "%s", but many systems will generate MD5 hashed # passwords if you use "$1$%.8s". This parameter is optional! crypt_salt_format="%s" ############################################################################## # # Unix Accounts Configuration # ############################################################################## # Login defs # Default Login Shell # Ex: userLoginShell="/bin/bash" userLoginShell="/bin/bash" # Home directory # Ex: userHome="/home/%U" userHome="/home/%U" # Default mode used for user homeDirectory userHomeDirectoryMode="700" # Gecos userGecos="System User" # Default User (POSIX and Samba) GID defaultUserGid="513" # Default Computer (Samba) GID defaultComputerGid="515" # Skel dir skeletonDir="/etc/skel" # Default password validation time (time in days) Comment the next line if # you don't want password to be enable for defaultMaxPasswordAge days (be # careful to the sambaPwdMustChange attribute's value) defaultMaxPasswordAge="45" ############################################################################## # # SAMBA Configuration # ############################################################################## # The UNC path to home drives location (%U username substitution) # Just set it to a null string if you want to use the smb.conf 'logon home' # directive and/or disable roaming profiles

Page 45: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

45

# Ex: userSmbHome="\\PDC-SMB3\%U" userSmbHome="\\PDC-SRV\%U" # The UNC path to profiles locations (%U username substitution) # Just set it to a null string if you want to use the smb.conf 'logon path' # directive and/or disable roaming profiles # Ex: userProfile="\\PDC-SMB3\profiles\%U" userProfile="\\PDC-SRV\profiles\%U" # The default Home Drive Letter mapping # (will be automatically mapped at logon time if home directory exist) # Ex: userHomeDrive="H:" userHomeDrive="H:" # The default user netlogon script name (%U username substitution) # if not used, will be automatically username.cmd # make sure script file is edited under dos # Ex: userScript="startup.cmd" # make sure script file is edited under dos userScript="logon.bat" # Domain appended to the users "mail"-attribute # when smbldap-useradd -M is used # Ex: mailDomain="idealx.com" mailDomain="jome" ############################################################################## # # SMBLDAP-TOOLS Configuration (default are ok for a RedHat) # ############################################################################## # Allows not to use smbpasswd (if with_smbpasswd == 0 in smbldap_conf.pm) but # prefer Crypt::SmbHash library with_smbpasswd="0" smbpasswd="/usr/bin/smbpasswd" # Allows not to use slappasswd (if with_slappasswd == 0 in smbldap_conf.pm) # but prefer Crypt:: libraries with_slappasswd="0" slappasswd="/usr/sbin/slappasswd" # comment out the following line to get rid of the default banner # no_banner="1"

6. Editar el fichero de configuración /etc/smbldap-tools/smbldap_bind.conf

para que las smbldap-tools se puedan conectar como administrador (“cn=admin., dc=jome”) al servidor LDAP.

############################ # Credential Configuration # ############################ # Notes: you can specify two differents configuration if you use a # master ldap for writing access and a slave ldap server for reading access # By default, we will use the same DN (so it will work for standard Samba # release) slaveDN="cn=Admin,dc=jome" slavePw="password_del_administrador_del_servidor_Ldap" masterDN="cn=Admin,dc=jome" masterPw="password_del_administrador_del_servidor_Ldap"

Aquí las contraseñas no pueden ponerse cifradas, así que este fichero tiene que ser legible (y editable) únicamente por root. (Ejecutar: chmod 600 /etc/smbldap-tools/smbldap_bind.conf). 7. Añadir grupos Samba y algunos usuarios necesarios con el script smbldap-

populate: root@xxxx:/etc/smbldap-tools# smbldap-populate Populating LDAP directory for domain JOME (S-1-5-21-2710697030-1106397243-3057445555) (using builtin directory structure) entry dc=jome already exist.

Page 46: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

46

entry ou=People,dc=jome already exist. entry ou=Groups,dc=jome already exist. entry ou=Hosts,dc=jome already exist. adding new entry: uid=root,ou=People,dc=jome adding new entry: uid=nobody,ou=People,dc=jome adding new entry: cn=Domain Admins,ou=Groups,dc=jome adding new entry: cn=Domain Users,ou=Groups,dc=jome adding new entry: cn=Domain Guests,ou=Groups,dc=jome adding new entry: cn=Domain Computers,ou=Groups,dc=jome adding new entry: cn=Administrators,ou=Groups,dc=jome adding new entry: cn=Account Operators,ou=Groups,dc=jome adding new entry: cn=Print Operators,ou=Groups,dc=jome adding new entry: cn=Backup Operators,ou=Groups,dc=jome adding new entry: cn=Replicators,ou=Groups,dc=jome adding new entry: sambaDomainName=JOME,dc=jome Please provide a password for the domain root: Changing UNIX and samba passwords for root New password: clave_de_root_para_samba Retype new password: clave_de_root_para_samba

Cuidado: Este “root” no es el del sistema. Es un usuario auxiliar que se ha añadido al servidor LDAP y que servirá para, desde Windows, acceder a las cuentas de máquinas (máquinas Windows) sin necesidad de utilizar al root del sistema. Se puede ver que entre sus OUs aparece que es una sambaSamAccount y múltiples campos Samba: root@xxxx:/mnt# ldapsearch -H "ldap://xxxx:389" -x -D "cn=Admin,dc=jome" \ -w password_del_Admin_LDAP uid=root # root, People, jome dn: uid=root,ou=People,dc=jome cn: root sn: root objectClass: top objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: sambaSamAccount objectClass: posixAccount objectClass: shadowAccount gidNumber: 0 uid: root uidNumber: 0 homeDirectory: /home/root sambaLogonTime: 0 sambaLogoffTime: 2147483647 sambaKickoffTime: 2147483647 sambaPwdCanChange: 0 sambaHomePath: \\PDC-SRV\root sambaHomeDrive: H: sambaProfilePath: \\PDC-SRV\profiles\root sambaPrimaryGroupSID: S-1-5-21-2710697030-1106397243-3057445555-512 sambaSID: S-1-5-21-2710697030-1106397243-3057445555-500 loginShell: /bin/false gecos: Netbios Domain Administrator sambaLMPassword: 157D69E4420D91787584248B8D2C9F9E sambaAcctFlags: [U] sambaNTPassword: 1BD788147CD18F08197106040F68B844 sambaPwdLastSet: 1208193287 sambaPwdMustChange: 1212081287 userPassword:: e01ENX1RZFJCZllNcUNEd1pCdkdscTZ6a0NnPT0= shadowLastChange: 13983 shadowMax: 45

Para poder utilizar este usuario como “falso root” (como dice en el tutorial: http://download.gna.org/smbldap-tools/docs/samba-ldap-howto/#htoc67 ) hay que darle privilegios:

Page 47: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

47

root@xxxx:/home/hector# smbldap-usermod -G +512 root User "root" already member of the group "512".

root@xxxx:/home/hector# net -U root%rutsamba rpc rights grant \ 'JOME\Domain Admins' SeMachineAccountPrivilege Successfully granted rights.

8. Hacer que el usuario test sea un usuario válido para Windows. Viendo los campos del usuario test, se observa que no tiene campos Samba, con lo cual, Windows no lo aceptará al intentar loguerase con él. Hay que hacer que los tenga. Lo primero es hacer que el grupo “test” al que pertenece nuestro usuario sea reconocido como grupo Samba. Para eso: root@xxxx:/# smbldap-groupmod –a test

A continuación, aprovechar los scripts de smbldap-tools para añadir los campos Samba a “test” (lo más importante es la opción –P, para dotarle de un password Samba). root@xxxx:/home/hector# smbldap-usermod -P --givenName "test" -a -A "1" -B "1" \ -Z "cn=Test,displayName=Test User" test Use of uninitialized value in string at /usr/sbin/smbldap-usermod line 306. Use of uninitialized value in string eq at /usr/sbin/smbldap-usermod line 307. Use of uninitialized value in string eq at /usr/sbin/smbldap-usermod line 307. Use of uninitialized value in string eq at /usr/sbin/smbldap-usermod line 307. Use of uninitialized value in concatenation (.) or string at /usr/sbin/smbldap-usermod line 307. Changing UNIX and samba passwords for test New password: test Retype new password:test

9. Añadir la máquina “enano” a los hosts. root@xxxx:/# smbldap-useradd -W enano

Esto debería proporcionar una cuenta de máquina en el servidor LDAP (nota: para seguir la nomenclatura de Windows, el nombre que recibe es enano$. root@xxxx:/home/hector# ldapsearch -H "ldap://xxxx:389" -x -D "cn=Admin,dc=jome" \ -w rutldap uid=enano$ # enano$, Hosts, jome dn: uid=enano$,ou=Hosts,dc=jome cn: enano$ uid: enano$ uidNumber: 1002 gidNumber: 515 homeDirectory: /dev/null loginShell: /bin/false description: Computer gecos: Computer objectClass: posixAccount objectClass: account objectClass: sambaSamAccount sambaLogonTime: 0 sambaLogoffTime: 2147483647 sambaKickoffTime: 2147483647 sambaPwdCanChange: 0 sambaPwdMustChange: 2147483647 sambaPwdLastSet: 1208202135 sambaAcctFlags: [W ] sambaSID: S-1-5-21-2710697030-1106397243-3057445555-3004 sambaPrimaryGroupSID: S-1-5-21-2710697030-1106397243-3057445555-515 displayName: enano$ sambaDomainName: JOME sambaNTPassword: FB950D358A0164C0D1D936A21389A505

Page 48: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

48

En teoría, los scripts de smbldap-tools son capaces de crear automáticamente estas cuentas cuando una máquina se intenta unir al dominio, pero en la práctica están dando muchos problemas.

5.2 Configuración del cliente Windows En este punto se detallarán los pasos seguidos para que la máquina Windows pueda loguearse con nuestro usuario “test”.

5.2.1 Comprobar que podemos acceder al servidor con “test” Ir a “Mis sitios de red” y buscar el equipo “xxxx” o ver toda la red, hasta conseguir ver a “xxxx”

Una vez encontrado, hacer doble clic sobre él. Se nos pedirá un nombre de usuario y contraseña para acceder a los recursos. Se puede comprobar que no todos los usuarios pueden acceder. Sin embargo, entrando con “test” (password test) sí conseguimos acceder a los recursos compartidos:

Page 49: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

49

5.2.2 Unirse al dominio “JOME”. En estos momentos el cliente está conectado al servidor XXXX. Ahora no se puede unir al dominio. Si se intentara, se obtendría un error como este:

Antes de nada hay que desconectarse de xxxx. Para ello, ejecutar (en una consola o en Inicio Ejecutar) el comando net use \\xxxx /delete. Hacer doble clic sobre “Mi PC” y seleccionar “Propiedades” en el menú que se desplegará. Ir a la segunda pestaña, “Identificación de red”. Seleccionar en el radio button “Dominio” en lugar de “Grupo de trabajo” que probablemente será el que está seleccionado:

Escribir JOME:

Page 50: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

50

Y aceptar. Pedirá el nombre de un usuario (y su contraseña) que tenga permisos para crear entidades en el dominio:

Este es el momento de introducir el password del “falso root” que se creó en el punto 7 de la página 45. Si todo va bien, tendremos esto:

Reiniciar el sistema. Debería pedir que se presione “Alt + Ctrl + Supr” para iniciar sesión. Al hacerlo, saldrá una pantalla parecida a la que hay bajo estas líneas:

Page 51: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

51

En el combo, podemos elegir si queremos entrar con cuentas de usuarios locales o del dominio. Si elegimos el dominio JOME, deberíamos poder entrar con el usuario “Test” de password “test”. Eso si, como los profiles no están bien definidos y los directorios “home” tampoco, saldrán un par de mensajes de error, pero entrará en sesión correctamente.

Page 52: HowTo Servidor Ldap Linux (Ubuntu) Con TLS y Samba - Configuracion Clientes Linux (Debian) y Windows 2000

HowTo Servidor LDAP y clientes Linux/Windows

52

6. Links y referencias usados Guía rápida para levantar un servidor LDAP (sin TLS): http://bulma.net/body.phtml?nIdNoticia=1991 Guía más detallada que la anterior para levantar un servidor LDAP (sin TLS) http://bulma.net/body.phtml?nIdNoticia=1343&nIdPage=3 Guía del administrador OpenLdap 2. 4. http://www.openldap.org/doc/admin24/ OpenLdap con TLS (como crear certificados, asegurar el servidor…) http://www.openldap.org/pub/ksoper/OpenLDAP_TLS.html Tutorial rápido de LDAP y Samba en Ubuntu 7.10. http://www.howtoforge.com/openldap-samba-domain-controller-ubuntu7.10 Tutorial rápido de LDAP y Samba. http://www.fatofthelan.com/articles/articles.php?pid=24 Buen tutorial Ldap + Samba (aunque habla de alguna herramienta que yo no he encontrado) http://www.debianperu.org/node/358 Tutorial Ldap + Samba (muy buena la parte de Samba) http://dns.bdat.net/documentos/validacion_ldap/book1.html Tutorial sobre integración de sistemas Windows – Linux (completísimo: siver tanto para servidores Linux / clientes Windows como para servidores Windows / clientes Linux) http://fferrer.dsic.upv.es/cursos/Integracion/html/index.html Explicaciones sobre PAM: http://www.freebsd.org/doc/en_US.ISO8859-1/articles/pam/pam-config.html Tutorial rápido de Samba como P.D.C http://dns.bdat.net/documentos/samba/validacion_winbind/t1.html Tutorial rápido de Samba como P.D.C. (se puede usar para referencias de comandos y así) http://www.linuxparatodos.net/portal/staticpages/index.php?page=13-como-samba Guía oficial de referencia Samba http://us1.samba.org/samba/docs/man/Samba-HOWTO-Collection/index.html Guía oficial de las SmbLdapTools: http://download.gna.org/smbldap-tools/docs/samba-ldap-howto/