Buscar este blog

miércoles, 8 de mayo de 2013

Añadir equipo GNU/Linux a Active Directory


En esta pequeña receta les enseñaré a añadir a un usuario con una máquina GNU/Linux a iniciar sesión en un Active Directory o PDC, para que de esa forma una vez que iniciamos sesión en nuestro sistema, automáticamente el sistema inciará sesión también en el contralador de dominio Active Directory.
Para ello utlizaremos el conjunto de aplicaciones Samba, autenticación KerberosWinbind y algún que otro paquete más.
Este post aplica para Ubuntu y sus derivados.
Partiremos de un sistema recien instalado el cual necesitamos agregar a un dominio ya creado  con una cuenta de usuario ya creada. Esta cuenta creada en el PDC debe ser la misma que la que utilizaremos para entrar en nuestro Ubuntu.
Una vez instalado el sistema con su sistema gráfico y todo, pasaremos modificar la configuración para que cada vez que entremos a nuestro sistema nuevo, automaticamente inicie la sesión en el PDC a la vez que entramos en nuestro sistema. Para ello utilizaremos nuestro gestos de inicio de sesión, en mi caso GDM.
Para ello, como he dicho antes supondremos que ya tenemos la cuenta del cliente creada, en el ejemplo tomaremos como dominio de prueba el nombre DOMINIO.LOCAL, con la ip 192.168.1.1, el nombre del controlador de dominio sera en nuestro ejemplo pdc.edages.local y como usuario juanmi
Comencemos instalando unos cuantos paquetes:
# apt-get install samba smbclient winbind krb5-user krb5-config ntpdate
Una vez realizado comenzaremos a modificar la configuración de samba, para ello haremos una copia del archivo original y crearemos uno nuevo:
# mv /etc/samba/smb.conf /etc/samba/smb.conf.ORIGINAL
Editaremos el nuevo archivo:
# sudo nano /etc/samba/smb.conf
Y pondremos el siguiente contenido, cambiándolo según sea cada caso, respeten las MAYUSCULAS.
[global]
workgroup = DOMINIO
realm = DOMINIO.LOCAL
security = ADS
password server = 192.168.1.1
log level = 1
syslog = 0
printcap name = cups
domain master = No
wins server = 192.168.1.1
idmap uid = 10000-29999
idmap gid = 10000-29999
winbind separator =
winbind use default domain = Yes
winbind enum users = Yes
winbind enum groups = Yes
winbind use default domain = Yes
netbios name = juanmi
template homedir = /home/%D/%U
template shell = /bin/bash
client use spnego = yes
domain master = no
server string = Juanmi
encrypt passwords = true
dos charset = 850
unix charset = iso-8859-15
[homes]
comment = Home Directories
valid users = %S
browseable = No
read only = No
inherit acls = Yes
[profiles]
comment = Network Profiles Service
path = %H
read only = No
store dos attributes = Yes
create mask = 0600
directory mask = 0700
[printers]
comment = All Printers
path = /var/spool/samba
create mask = 0700
printable = Yes
browseable = Yes
[print$]
comment = Printer Drivers
path = /var/lib/samba/printers
[Comparto]
comment = Comparto en Juanmi
path = /home/juanmi/Desktop/Comparto
read only = No
inherit acls = Yes
public = no
browseable = yes
create mask= 664
force create mode = 664
directory mask = 775
force directory mode = 775
[Musica]
comment = Musica
path = /home/juanmi/Desktop/Musica
read only = No
inherit acls = Yes
Crearemos el directorio para alojar las home de cada usuario del dominio:
# mkdir /home/DOMINIO
Continuaremos ahora configurando más archivos. Ahora sigue /etc/krb5.conf
# sudo nano /etc/krb5.conf
y pongamos el siguiente contenido, cambiándolo de nuevo con las opciones necesarias:
[libdefaults]
krb4_config = /etc/krb.conf
krb4_realms = /etc/krb.realms
kdc_timesync = 1
ccache_type = 4
forwardable = true
proxiable = true
v4_instance_resolve = false
v4_name_convert = {
host = {
rcmd = host
ftp = ftp
}
plain = {
something = something-else
}
}
fcc-mit-ticketflags = true
clockskew = 300
# The following krb5.conf variables are only for MIT Kerberos.
# The following encryption type specification will be used by MIT Kerberos
# if uncommented.  In general, the defaults in the MIT Kerberos code are
# correct and overriding these specifications only serves to disable new
# encryption types as they are added, creating interoperability problems.
#       default_tgs_enctypes = aes256-cts arcfour-hmac-md5 des3-hmac-sha1 des-cbc-crc des-cbc-md5
#       default_tkt_enctypes = aes256-cts arcfour-hmac-md5 des3-hmac-sha1 des-cbc-crc des-cbc-md5
#       permitted_enctypes = aes256-cts arcfour-hmac-md5 des3-hmac-sha1 des-cbc-crc des-cbc-md5
# The following libdefaults parameters are only for Heimdal Kerberos.
[realms]
DOMINIO.LOCAL = {
kdc = 192.168.1.1
default_domain = dominio.local
admin_server = 192.168.1.1
        }
dominio.local = {
kdc = 
192.168.1.1
                default_domain = dominio.local
admin_server = 1
92.168.1.1
        }
dominio = {
kdc = 
192.168.1.1
                default_domain = dominio
admin_server = 
192.168.1.1
        }
[logging]
kdc = FILE:/var/log/krb5/krb5kdc.log
admin_server = FILE:/var/log/krb5/kadmind.log
default = SYSLOG:NOTICE:DAEMON
[domain_realm]
.dominio = dominio
.dominio.local = DOMINIO.LOCAL
[appdefaults]
pam = {
ticket_lifetime = 1d
renew_lifetime = 1d
forwardable = true
proxiable = false
retain_after_close = false
minimum_uid = 0
try_first_pass = true
}


Editaremos ahora todos los archivos para que cuando iniciemos utilicen los datos introducidos para que inicie la sesión contra el Active Directory:
# cd /etc/pam.d/
# nano common-account
Y lo dejaremos así:
 #
# /etc/pam.d/common-account – authorization settings common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of the authorization modules that define
# the central access policy for use on the system.  The default is to
# only deny service to users whose accounts are expired in /etc/shadow.
#
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules.  See
# pam-auth-update(8) for details.
#
# here are the per-package modules (the “Primary” block)
account sufficient      pam_winbind.so
account [success=1 new_authtok_reqd=done default=ignore]        pam_unix.so
# here’s the fallback if no module succeeds
account requisite                       pam_deny.so
# prime the stack with a positive return value if there isn’t one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
account required                        pam_permit.so
# and here are more per-package modules (the “Additional” block)
# end of pam-auth-update config
Ahora
# nano common-auth
Y lo dejaremos así:
#
# /etc/pam.d/common-auth – authentication settings common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of the authentication modules that define
# the central authentication scheme for use on the system
# (e.g., /etc/shadow, LDAP, Kerberos, etc.).  The default is to use the
# traditional Unix authentication mechanisms.
#
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules.  See
# pam-auth-update(8) for details.
# here are the per-package modules (the “Primary” block)
auth    sufficient      pam_winbind.so
auth    [success=1 default=ignore]      pam_unix.so nullok_secure try_first_pass
# here’s the fallback if no module succeeds
auth    requisite                       pam_deny.so
# prime the stack with a positive return value if there isn’t one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
auth    required                        pam_permit.so
# and here are more per-package modules (the “Additional” block)
# end of pam-auth-update config
Ahora
# nano common-session
Y lo dejaremos así:
#
# /etc/pam.d/common-session – session-related modules common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of modules that define tasks to be performed
# at the start and end of sessions of *any* kind (both interactive and
# non-interactive).
#
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules.  See
# pam-auth-update(8) for details.
# here are the per-package modules (the “Primary” block)
session [default=1]                     pam_permit.so
# here’s the fallback if no module succeeds
session requisite                       pam_deny.so
# prime the stack with a positive return value if there isn’t one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
session required                        pam_permit.so
# and here are more per-package modules (the “Additional” block)
session sufficient      pam_winbind.so
session required        pam_unix.so
session optional                        pam_ck_connector.so nox11
# end of pam-auth-update config
Ahora
# nano common-password
Y lo dejaremos así:
#
# /etc/pam.d/common-password – password-related modules common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of modules that define the services to be
# used to change user passwords.  The default is pam_unix.
# Explanation of pam_unix options:
#
# The “md5″ option enables MD5 passwords.  Without this option, the
# default is Unix crypt.
#
# The “obscure” option replaces the old `OBSCURE_CHECKS_ENAB’ option in
# login.defs.
#
# See the pam_unix manpage for other options.
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules.  See
# pam-auth-update(8) for details.
# here are the per-package modules (the “Primary” block)
password        sufficient      pam_winbind.so
password        [success=1 default=ignore]      pam_unix.so obscure use_authtok try_first_pass md5
# here’s the fallback if no module succeeds
password        requisite                       pam_deny.so
# prime the stack with a positive return value if there isn’t one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
password        required                        pam_permit.so
# and here are more per-package modules (the “Additional” block)
password        optional        pam_gnome_keyring.so
# end of pam-auth-update config
Y por último  editaremos la configuración de nuestro gestor de sesiones, en mi caso GDM, como dije más arriba:
# nano gdm
Y lo dejaremos así:
 #%PAM-1.0
auth required /lib/security/pam_securetty.so
auth sufficient /lib/security/pam_winbind.so
auth sufficient /lib/security/pam_unix.so use_first_pass envfile=/etc/default/locale
auth required /lib/security/pam_nologin.so
account sufficient /lib/security/pam_winbind.so
session required /lib/security/pam_mkhomedir.so skel=/etc/skel
umask=0022
auth requisite pam_nologin.so
auth    required        pam_env.so readenv=1
auth    required   ­;     pam_env.so readenv=1 envfile=/etc/default/locale
;@include common-auth
;@include common-account
session required pam_limits.so
;@include common-session
session optional /lib/security/pam_console.so
;@include common-password
Ahora debemos editar el archivo  /etc/nsswitch.conf para decirle que utilice tambien winbind:
# nano /etc/nsswitch.conf
y lo dejaremos como aparece aquí:
#/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 winbind
group:          files winbind
shadow:         files winbind
hosts:          files dns winbind
networks:       files
protocols:      db files
services:       db files
ethers:         db files
rpc:            db files
netgroup:       nis
Perfecto. Ya tenemos todo configurado. Ahora ajustaremos la hora del sistema para que no nos falle con el servidor, el cual asumimos que lo tenemos en hora:
# ntpdate hora.rediris.es
Crearemos los tickets Kerberos con el siguiente comando, necesitaremos el password del administrador del dominio:
# kinit administrador@DOMINIO.LOCAL
Solo si da problemas al recibir los tickets Kerberos volveremos a intentarlo con el nombre del dominio en minusculas:
# kinit administrador@dominio.local
Reiniciemos Samba y Windbind y comprobemos la configuración:
# /etc/init.d/samba restart
# /etc/init.d/winbind restart
# testparm
Uniremos la máquina al dominio con el siguiente comando:
# net ads join -S 192.168.1.1  -U administrador
Si les diese algún problema, prueben con el nombre del servidor Active Directory, en nuestro ejemplo PDC:
# net ads join -S pdc.dominio.local  -U administrador
Ahora solo nos queda comprobar que hemos hecho todo bien:
# net rpc testjoin
Si todo es correcto, nos mostrará un mensaje como este:
Join to ‘DOMINIO’ is OK
Ahora lo siguiente:
# net ads info­
Nos mostrará:
LDAP server: 192.168.1.1
LDAP server name: pdc.dominio.local
Realm: DOMINIO.LOCAL
Bind Path: dc=DOMINIO,dc=LOCAL
LDAP port: 389
Server time: jue, 2 jul 2009 14:36:04 CEST
KDC server: 192.168.1.1
Server time offset: 0
Ahora:
# net rpc info -U juanmi
Enter juanmi’s password:
Domain Name: DOMINIO
Domain SID: S-1-5-21-224523388-1220989662-682023330
Sequence number: 7529
Num users: 169
Num domain groups: 0
Num local groups: 12
# wbinfo -u
Nos dará los usuarios del dominio
# wbinfo -g
Nos dará los grupos del dominio
# getent passwd
Nos dará más información de los usuarios del dominio
# getent group
Nos dará más información de los grupos del dominio
Ahora solo nos queda reiniciar el equipo y comprobar que una vez metido el usuario y la contraseña en GDM podemos volver a lanzar los comandos de comprobación de arriba:
 # net rpc testjoin
# net ads info
# net rpc info -U juanmi
# wbinfo -u
# wbinfo -g
# getent passwd
# getent group
Ya podrán entrar en nuestro equipo los usuarios del dominio sin que se les pida password.

Happy Hacking!!!

3 comentarios:

  1. Estoy tratando de aplicar este aporte pero necesito ayuda. Después de instalar los paquetes y hacer las configuraciones mencionadas, al ejecutar # ntpdate hora.rediris.es me dice: no server suitable for synchronization found. Después intenté ejecutar el kinit y tampoco funcionó. Lo ejecuté como dice en la guía y también sustituyendo dominio.local por el nombre real de mi dominio pero nada y hasta aquí me he quedado esperando de su ayuda.

    Saludos.

    ResponderEliminar
    Respuestas
    1. El comando ntpdate realiza la sincronización con el servidor de horario mundial. El equipo debe tener salida a internet, tal vez por eso te dice que no encuentra ningún servidor para hacer la sincronización de hora.

      Kinit debe ser con el usuario administrador del servidor de dominio, es decir, la cuenta con la que unes los equipos al dominio.

      Puedes saltarte el paso del ntpdate. En cuanto a la unión del dominio, supongamos que tu servidor se llama midominio, primero debes verificar que efectivamente puedes verlo con un ping o que te responde al nombre del servidor.

      Eliminar
  2. El equipo tiene salida a internet de echo el comentario anterior lo hice conectado desde ahí. El kinit lo use también con el usuario que mencionas que en mi caso es root. Suponiendo que mi dominio es empresazac, el kinit lo ejecute como root@empresazac y tampoco tuve éxito. Ahora, en la guía pone de ejemplo DOMINIO.LOCAL como el nombre del dominio, estoy suponiendo que en los scripts debo sustituir DOMINIO.LOCAL por mi dominio que en este caso sería empresazac ¿es correcto?

    Respondiendo a lo del ping, este me responde cuando le pongo la ip del servidor pero no me responde con el nombre.

    ResponderEliminar

Tus comentarios son muy importantes. Gracias por tomarte tu tiempo.

Happy Hacking!!!