Instalando e Configurando o Samba4 em Master/Slave utilizando Bind9 DLZ e com replicação do Sysvol no CentOS 6

E ai galera, eu vou abordar a instalação do Samba 4 trabalhando como PDC e tando o seu BDC vamos utilizar como backend de DNS o Bind9 DLZ e como na documentação do samba é aconselhado efetuar a replicação do Sysvol pois o samba 4 ainda não da suporte vamos implementar isso tambem e como não pode faltar vamos configurar a questão do nosso backup e restore.

OBS: Eu vou utilizar a versão 4.1.3 do samba que é a última estável no dia: 18/12/2013 a última versão que est a no repositório git ta dando alguns problemas e como precisamos de algo que fique trabalhando sem parar vamos utilizar a estável.

OBS: O Samba 4 não funciona com o bind em chroot está nas documentações oficiais.

O que vou utilizar:

  • CentOS 6.4
    • IP: 192.168.0.25/24
    • nome: nodo1
    • domínio: douglas.lan
  • CentOS 6.4
    • IP: 192.168.0.26/26
    • nome: nodo2
    • domínio: douglas.lan

Prepare os dois CentOS com o seguinte script http://wiki.douglasqsantos.com.br/doku.php/confinicialcentos6_en para que não falte nenhum pacote ou configuração.

Configuração do MASTER

Vamos atualizar os repositórios e vamos fazer um upgrade do sistema

yum check-update && yum update -y

Agora vamos instalar as dependências para podemos compilar o samba

yum install  openldap-devel pam-devel git gcc make wget  libacl-devel libblkid-devel gnutls-devel readline-devel python-devel cups-devel \
libaio-devel quota-devel ctdb-devel krb5-devel krb5-workstation acl setroubleshoot-server setroubleshoot-plugins policycoreutils-python \
libsemanage-python setools-libs-python setools-libs popt-devel libpcap-devel libidn-devel libxml2-devel libacl-devel libsepol-devel libattr-devel \
keyutils-libs-devel cyrus-sasl-devel cups-devel bind-utils bind-sdb bind-devel bind-libs bind avahi-devel mingw32-iconv gamin \
libcap-devel rpc2-devel glusterfs-devel python-dns -y

Agora vamos ajustar o fstab para que ele de suporte a acl,user_xattr e barrier eu vou habilitar isso na partição / se você tiver várias partições é bom habilitar em todas que você queira habilitar os compartilhamentos.

vim /etc/fstab
[...]
/dev/mapper/VolGroup-lv_root /                       ext4    defaults,acl,user_xattr,barrier=1        1 1

Agora vamos remontar a raiz

mount -o remount /

Agora vamos listar os atributos da raiz

mount | egrep acl
/dev/mapper/VolGroup-lv_root on / type ext4 (rw,acl,user_xattr,barrier=1)

Agora os atributos já estão carregados.

Agora vamos obter o samba vamos acessar o diretório que vai armazenar os fontes

cd /usr/src

Agora vamos obter os fontes

wget -c http://ftp.samba.org/pub/samba/stable/samba-4.1.3.tar.gz

Agora vamos desempacotar o samba

tar -xzvf samba-4.1.3.tar.gz

Agora vamos acessar o diretório dos fontes

cd samba-4.1.3

Agora vamos criar a configuração para o samba

./configure --enable-debug --enable-selftest

Agora vamos mandar compilar o samba este processo demora um pouco

make

Agora vamos mandar instalar o samba

make install

Agora vamos acertar a PATH do usuário root no caso dele estar utilizando o shell Bash

echo "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/local/samba/sbin:/usr/local/samba/bin" >> /root/.bashrc

Agora precisamos importar a nova PATH

source /root/.bashrc

Agora vamos acertar a PATH do usuário root no caso dele estar utilizando o shell zsh

echo "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/local/samba/sbin:/usr/local/samba/bin" >> /root/.zshrc

Agora precisamos importar a nova PATH

source /root/.zshrc

Agora vamos ajustar o resolv.conf ele vai utilizar o nome do nosso domínio e o ip do pdc.

vim /etc/resolv.conf
domain douglas.lan
search douglas.lan
nameserver 192.168.0.25

Agora vamos ajustar a interface de rede para utilizar o nosso novo DNS

vim /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"
BOOTPROTO="static"
BROADCAST="192.168.0.255"
DNS1="192.168.0.25"
GATEWAY="192.168.0.1"
IPADDR="192.168.0.25"
NETMASK="255.255.255.0"
NM_CONTROLLED="yes"
ONBOOT="yes"
TYPE="Ethernet"

Agora vamos configurar o Bind

vim /etc/named.conf
//named.conf

options {
  listen-on port 53 { 127.0.0.1; 192.168.0.0/24; };
  listen-on-v6 port 53 { ::1; };
  directory   "/var/named";
  dump-file   "/var/named/data/cache_dump.db";
  statistics-file "/var/named/data/named_stats.txt";
  memstatistics-file "/var/named/data/named_mem_stats.txt";
  allow-query     { 192.168.0.0/24; localhost; };
  recursion yes;
  forwarders { 8.8.8.8; 8.8.4.4; };

  dnssec-enable yes;
  dnssec-validation yes;
  dnssec-lookaside auto;

  /* Path to ISC DLV key */
  bindkeys-file "/etc/named.iscdlv.key";

  managed-keys-directory "/var/named/dynamic";

 /* keytab para samba4 */
  tkey-gssapi-keytab "/usr/local/samba/private/dns.keytab";

};

logging {
  channel default_debug {
          file "data/named.run";
          severity dynamic;
  };
};

zone "." IN {
  type hint;
  file "named.ca";
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
/*Arquivo de configuração do samba4 que informa a localização do bind_dlz */
include "/usr/local/samba/private/named.conf";

Agora vamos provisionar o nosso domínio

Para saber quais opções podem ser utilizadas podemos listar da seguinte forma

samba-tool domain provision -h

Agora vamos provisionar o nosso domínio

samba-tool domain provision --domain=DOUGLAS --adminpass=sen@134* \
--dns-backend=BIND9_DLZ --server-role=dc \
--function-level=2008_R2 --use-xattr=yes \
--use-rfc2307 --realm=douglas.lan

A saída do comando acima vai ser algo como

Looking up IPv4 addresses
Looking up IPv6 addresses
No IPv6 address will be assigned
Setting up share.ldb
Setting up secrets.ldb
Setting up the registry
Setting up the privileges database
Setting up idmap db
Setting up SAM db
Setting up sam.ldb partitions and settings
Setting up sam.ldb rootDSE
Pre-loading the Samba 4 and AD schema
Adding DomainDN: DC=douglas,DC=lan
Adding configuration container
Setting up sam.ldb schema
Setting up sam.ldb configuration data
Setting up display specifiers
Modifying display specifiers
Adding users container
Modifying users container
Adding computers container
Modifying computers container
Setting up sam.ldb data
Setting up well known security principals
Setting up sam.ldb users and groups
Setting up self join
Adding DNS accounts
Creating CN=MicrosoftDNS,CN=System,DC=douglas,DC=lan
Creating DomainDnsZones and ForestDnsZones partitions
Populating DomainDnsZones and ForestDnsZones partitions
See /usr/local/samba/private/named.conf for an example configuration include file for BIND
and /usr/local/samba/private/named.txt for further documentation required for secure DNS updates
Setting up sam.ldb rootDSE marking as synchronized
Fixing provision GUIDs
A Kerberos configuration suitable for Samba 4 has been generated at /usr/local/samba/private/krb5.conf
Setting up fake yp server settings
Once the above files are installed, your Samba4 server will be ready to use
Server Role:           active directory domain controller
Hostname:              nodo1
NetBIOS Domain:        DOUGLAS
DNS Domain:            douglas.lan
DOMAIN SID:            S-1-5-21-2011945809-1847694634-1467046014

Agora vamos inserir o named na incialização do sistema

chkconfig --add named 
chkconfig named on

Agora vamos criar o script de inicialização

vim /etc/init.d/samba
#!/bin/sh
#
# chkconfig: - 91 35
# description: Starts and stops the Samba smbd daemon \
#        used to provide SMB network services.
#
# pidfile: /var/run/samba/smbd.pid
# config:  /etc/samba/smb.conf


# Source function library.
if [ -f /etc/init.d/functions ] ; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
  . /etc/rc.d/init.d/functions
else
  exit 1
fi

# Avoid using root's TMPDIR
unset TMPDIR

# Source networking configuration.
. /etc/sysconfig/network

if [ -f /etc/sysconfig/samba ]; then
   . /etc/sysconfig/samba
fi

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 1

# Check that smb.conf exists.
[ -f /usr/local/samba/etc/smb.conf ] || exit 6

RETVAL=0


start() {
        KIND="SMB"
  echo -n $"Starting $KIND services: "
  /usr/local/samba/sbin/samba
  RETVAL=$?
  echo
  [ $RETVAL -eq 0 ] && touch /usr/local/samba/var/lock/smb || \
     RETVAL=1
  return $RETVAL
}

stop() {
        KIND="SMB"
  echo -n $"Shutting down $KIND services: "
  killproc smbd
  RETVAL=$?
  echo
  [ $RETVAL -eq 0 ] && rm -f /usr/local/samba/var/lock/smb
  return $RETVAL
}

restart() {
  stop
  start
}

reload() {
        echo -n $"Reloading smb.conf file: "
  killproc smbd -HUP
  RETVAL=$?
  echo
  return $RETVAL
}

rhstatus() {
  status -l smb smbd
  return $?
}


# Allow status as non-root.
if [ "$1" = status ]; then
       rhstatus
       exit $?
fi

# Check that we can write to it... so non-root users stop here
[ -w /usr/local/samba/etc/smb.conf ] || exit 4



case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  restart)
    restart
  ;;
  reload)
    reload
  ;;
  status)
    rhstatus
  ;;
  condrestart)
    [ -f /var/lock/subsys/smb ] && restart || :
  ;;
  *)
  echo $"Usage: $0 {start|stop|restart|reload|status|condrestart}"
  exit 2
esac

exit $?

Agora vamos dar permissão para o nosso script e vamos inserir ele na incialização

chmod +x /etc/init.d/samba
chkconfig --add samba
chkconfig samba on

Agora vamos inicializar o named e o samba

/etc/init.d/named start
/etc/init.d/samba start

Agora vamos consultar o daemon do samba

ps aux | egrep samba
root      4184  6.2  8.2 528976 41260 ?        Ss   12:08   0:00 /usr/local/samba/sbin/samba
root      4187  0.0  5.7 528976 28648 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4188  0.0  5.8 528976 29500 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4189  0.1  6.1 533128 31100 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4190  0.0  5.6 528976 28608 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4191  6.6  8.6 579936 43304 ?        Ss   12:08   0:00 /usr/local/samba/sbin/smbd --option=server role check:inhibit=yes --foreground
root      4192 11.3  6.1 528976 30768 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4193  0.0  5.8 528976 29204 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4194  0.0  6.1 528976 30716 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4195  0.3  5.9 528976 30096 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4196  0.1  6.0 532436 30568 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4197  0.0  5.7 528976 28748 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4198  0.0  5.9 528976 29712 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4199  0.1  5.8 528976 29632 ?        S    12:08   0:00 /usr/local/samba/sbin/samba
root      4203  0.0  5.7 579420 29052 ?        S    12:08   0:00 /usr/local/samba/sbin/smbd --option=server role check:inhibit=yes --foreground

Como pode ser visto ele está rodando ok.

Agora vamos listar a versão do nosso samba

smbclient --version
Version 4.1.3

Agora vamos mandar listar os compartilhamentos

smbclient -L localhost -U%
Domain=[DOUGLAS] OS=[Unix] Server=[Samba 4.1.3]

  Sharename       Type      Comment
  ---------       ----      -------
  netlogon        Disk      
  sysvol          Disk      
  IPC$            IPC       IPC Service (Samba 4.1.3)
Domain=[DOUGLAS] OS=[Unix] Server=[Samba 4.1.3]

  Server               Comment
  ---------            -------

  Workgroup            Master
  ---------            -------

Agora vamos mandar listar o netlogon com o usuário administrator

smbclient //localhost/netlogon -UAdministrator%'sen@134*' -c 'ls'
Domain=[DOUGLAS] OS=[Unix] Server=[Samba 4.1.3]
  .                                   D        0  Mon Aug 26 12:02:01 2013
  ..                                  D        0  Mon Aug 26 12:02:14 2013

    34426 blocks of size 262144. 24007 blocks available

Agora vamos mandar listar a configuração do nosso samba

testparm
Load smb config files from /usr/local/samba/etc/smb.conf
rlimit_max: increasing rlimit_max (4096) to minimum Windows limit (16384)
Processing section "[netlogon]"
Processing section "[sysvol]"
Loaded services file OK.
Server role: ROLE_ACTIVE_DIRECTORY_DC
Press enter to see a dump of your service definitions

[global]
  workgroup = DOUGLAS
  realm = douglas.lan
  netbios name = NODO1
  server role = active directory domain controller
  passdb backend = samba_dsdb
  server services = s3fs, rpc, nbt, wrepl, ldap, cldap, kdc, drepl, winbind, ntp_signd, kcc, dnsupdate
  rpc_server:tcpip = no
  rpc_daemon:spoolssd = embedded
  rpc_server:spoolss = embedded
  rpc_server:winreg = embedded
  rpc_server:ntsvcs = embedded
  rpc_server:eventlog = embedded
  rpc_server:srvsvc = embedded
  rpc_server:svcctl = embedded
  rpc_server:default = external
  idmap_ldb:use rfc2307 = yes
  idmap config * : backend = tdb
  map archive = No
  map readonly = no
  store dos attributes = Yes
  vfs objects = dfs_samba4, acl_xattr

[netlogon]
  path = /usr/local/samba/var/locks/sysvol/douglas.lan/scripts
  read only = No

[sysvol]
  path = /usr/local/samba/var/locks/sysvol
  read only = No

Agora vamos ajustar o limits.conf para não aparecer os avisos no samba

vim /etc/security/limits.conf
#colocar no final do arquivo
root hard nofile 131072
root soft nofile 65536
mioutente hard nofile 32768
mioutente soft nofile 16384

Agora vamos testar a resolução de nome

nslookup douglas.lan
Server:   192.168.0.25
Address:  192.168.0.25#53

Name: douglas.lan
Address: 192.168.0.25

Agora vamos ajustar a configuração do kerberos

Vamos fazer backup do arquivo de configuração

mv /etc/krb5.conf /etc/krb5.conf.old

Vamos criar um link para o sistema reconhecer o arquivo de configuração do samba como default

ln -sf /usr/local/samba/private/krb5.conf /etc/krb5.conf

Agora vamos ajustar a configuração do krb5.conf

vim /etc/krb5.conf
[logging]
     default = FILE:/var/log/krb5libs.log
     kdc = FILE:/var/log/krb5kdc.log
     admin_server = FILE:/var/log/kadmind.log

[libdefaults]
     default_realm = DOUGLAS.LAN
     dns_lookup_realm = true
     dns_lookup_kdc = true
     ticket_lifetime = 24h
     forwardable = yes

[appdefaults]
     pam = {
          debug = false
          ticket_lifetime = 36000
          renew_lifetime = 36000
          forwardable = true
          krb4_convert = false
     }

Agora vamos criar um link para o keytab do kerberos

ln -s /usr/local/samba/private/dns.keytab /etc/krb5.keytab 

Agora vamos ajustar a configuração do samba para que ele consiga mapear via winbind

vim /usr/local/samba/etc/smb.conf
[global]
  workgroup = DOUGLAS
  realm = douglas.lan
  netbios name = NODO1
  server role = active directory domain controller
  passdb backend = samba_dsdb
  server services = s3fs, rpc, nbt, wrepl, ldap, cldap, kdc, drepl, winbind, ntp_signd, kcc, dnsupdate
  rpc_server:tcpip = no
  rpc_daemon:spoolssd = embedded
  rpc_server:spoolss = embedded
  rpc_server:winreg = embedded
  rpc_server:ntsvcs = embedded
  rpc_server:eventlog = embedded
  rpc_server:srvsvc = embedded
  rpc_server:svcctl = embedded
  rpc_server:default = external
  #IDMAP
  idmap_ldb:use rfc2307 = yes
  idmap config * : backend = tdb
  idmap config *:range = 70001-80000
  idmap config DOUGLAS:backend = ad
  idmap config DOUGLAS:schema_mode = rfc2307
  idmap config DOUGLAS:range = 500-40000
  #WINBIND
  winbind nss info = rfc2307
  winbind trusted domains only = no
  winbind use default domain = yes
  winbind enum users  = yes
  winbind enum groups = yes
  map archive = No
  map readonly = no
  store dos attributes = Yes
  vfs objects = dfs_samba4, acl_xattr
  #o template shell é necessário para logar com a autenticação via winbind
  template shell = /bin/bash
  #DESABILITANDO AS IMPRESSORAS
  printcap name = /dev/null
  load printers = no
  disable spoolss = yes
  printing = bsd
  ### LOGS
  log file = /var/log/samba/smbd.log
  max log size = 50
  log level = 2
  vfs objects = recycle full_audit
  ### LIXEIRA
  recycle:repository = Lixeira
  recycle:exclude = *.tmp *.TMP *.temp *.TEMP ~*
  recycle:keeptree = yes
  full_audit:success = rmdir mkdir open write rename unlink
  full_audit:failure = rmdir mkdir open write rename unlink
  full_audit:prefix = %U|%I|%m|%S
  full_audit:failure = none
  full_audit:facility = local5
  full_audit:priority = notice
  veto files = /*.mp3/*.wav/*.exe/*.cmd/*.adm/*.inf/*.ini/*.pif
  delete veto files = yes
  dos filemode = yes
        

[netlogon]
  path = /usr/local/samba/var/locks/sysvol/douglas.lan/scripts
  read only = No

[sysvol]
  path = /usr/local/samba/var/locks/sysvol
  read only = No

Agora vamos criar o diretório para armazenar os logs

mkdir -p /var/log/samba

Agora precisamos ajustar as bibliotecas do winbind para os sistemas de 32bits precisamos fazer da seguinte forma

ln -s /usr/local/samba/lib/libnss_winbind.so /lib
ln -s /lib/libnss_winbind.so /lib/libnss_winbind.so.2
ldconfig

Para os sistemas de 64bits precisamos fazer da seguinte forma

ln -s /usr/local/samba/lib/libnss_winbind.so /lib64
ln -s /lib64/libnss_winbind.so /lib64/libnss_winbind.so.2
ldconfig

Agora vamos ajustar o nsswitch.conf

vim /etc/nsswitch.conf
[...]
passwd: files winbind
[...]
group:  files winbind

Agora vamos inicializar um ticket para o administrator

kinit administrator
Password for administrator@DOUGLAS.LAN: 
Warning: Your password will expire in 41 days on Mon Oct  7 12:02:11 2013

Agora vamos listar o nosso ticket

klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: administrator@DOUGLAS.LAN

Valid starting     Expires            Service principal
08/26/13 12:22:19  08/26/13 22:22:19  krbtgt/DOUGLAS.LAN@DOUGLAS.LAN
  renew until 08/27/13 12:22:16

O nosso kerberos está ok.

Vamos instalar o ntp

yum install ntp -y

Agora vamos fazer um backup do arquivo de configuração default do ntp.conf

cp /etc/ntp.conf /etc/ntp.conf.old

Agora vamos configurar o ntp

vim /etc/ntp.conf
server 127.127.1.0
fudge  127.127.1.0 stratum 10
server a.ntp.br iburst prefer
server 0.pool.ntp.org  iburst prefer
server 1.pool.ntp.org  iburst prefer
driftfile /var/lib/ntp/ntp.drift
logfile /var/log/ntp
ntpsigndsocket /usr/local/samba/var/lib/ntp_signd/
restrict default kod nomodify notrap nopeer mssntp
restrict 127.0.0.1
restrict a.ntp.br mask 255.255.255.255 nomodify notrap nopeer noquery
restrict 0.pool.ntp.org mask 255.255.255.255 nomodify notrap nopeer noquery
restrict 1.pool.ntp.org mask 255.255.255.255 nomodify notrap nopeer noquery

Agora vamos iniciar ele

/etc/init.d/ntpd start

Agora vamos consultar o seu sincronismo

ntpq -p 127.0.0.1
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 LOCAL(0)        .LOCL.          10 l    -   64    1    0.000    0.000   0.000
 a.ntp.br        .INIT.          16 u    -   64    0    0.000    0.000   0.000
 a.st1.ntp.br    .INIT.          16 u    -   64    0    0.000    0.000   0.000
 roma.coe.ufrj.b .INIT.          16 u    -   64    0    0.000    0.000   0.000

Agora vamos inserir o ntp na incialização

chkconfig --add ntpd
chkconfig ntpd on

Agora vamos atualizar o nosso ntp

ntpdate -u a.ntp.br

Agora vamos ajustar o grupo do arquivo ntp_signd

chgrp ntp /usr/local/samba/var/lib/ntp_signd

O nosso samba já está ok.

Agora podemos obter os RSAT(Admin pack) em:

Agora vamos testar o winbind

wbinfo -t
checking the trust secret for domain DOUGLAS via RPC calls succeeded

Agora vamos listar os grupos

wbinfo -g
Enterprise Read-Only Domain Controllers
Domain Admins
Domain Users
Domain Guests
Domain Computers
Domain Controllers
Schema Admins
Enterprise Admins
Group Policy Creator Owners
Read-Only Domain Controllers
DnsUpdateProxy

Agora vamos listar os usuários

wbinfo -u
Administrator
Guest
krbtgt
dns-nodo1

Agora vamos testar o update de dns no samba

samba_dnsupdate --verbose
IPs: ['192.168.0.25']
Looking for DNS entry A douglas.lan 192.168.0.25 as douglas.lan.
Looking for DNS entry A nodo1.douglas.lan 192.168.0.25 as nodo1.douglas.lan.
Looking for DNS entry A gc._msdcs.douglas.lan 192.168.0.25 as gc._msdcs.douglas.lan.
Looking for DNS entry CNAME eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4._msdcs.douglas.lan nodo1.douglas.lan as eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4._msdcs.douglas.lan.
Looking for DNS entry SRV _kpasswd._tcp.douglas.lan nodo1.douglas.lan 464 as _kpasswd._tcp.douglas.lan.
Checking 0 100 464 nodo1.douglas.lan. against SRV _kpasswd._tcp.douglas.lan nodo1.douglas.lan 464
Looking for DNS entry SRV _kpasswd._udp.douglas.lan nodo1.douglas.lan 464 as _kpasswd._udp.douglas.lan.
Checking 0 100 464 nodo1.douglas.lan. against SRV _kpasswd._udp.douglas.lan nodo1.douglas.lan 464
Looking for DNS entry SRV _kerberos._tcp.douglas.lan nodo1.douglas.lan 88 as _kerberos._tcp.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._tcp.douglas.lan nodo1.douglas.lan 88
Looking for DNS entry SRV _kerberos._tcp.dc._msdcs.douglas.lan nodo1.douglas.lan 88 as _kerberos._tcp.dc._msdcs.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._tcp.dc._msdcs.douglas.lan nodo1.douglas.lan 88
Looking for DNS entry SRV _kerberos._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 88 as _kerberos._tcp.default-first-site-name._sites.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 88
Looking for DNS entry SRV _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo1.douglas.lan 88 as _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo1.douglas.lan 88
Looking for DNS entry SRV _kerberos._udp.douglas.lan nodo1.douglas.lan 88 as _kerberos._udp.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._udp.douglas.lan nodo1.douglas.lan 88
Looking for DNS entry SRV _ldap._tcp.douglas.lan nodo1.douglas.lan 389 as _ldap._tcp.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.douglas.lan nodo1.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.dc._msdcs.douglas.lan nodo1.douglas.lan 389 as _ldap._tcp.dc._msdcs.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.dc._msdcs.douglas.lan nodo1.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.gc._msdcs.douglas.lan nodo1.douglas.lan 3268 as _ldap._tcp.gc._msdcs.douglas.lan.
Checking 0 100 3268 nodo1.douglas.lan. against SRV _ldap._tcp.gc._msdcs.douglas.lan nodo1.douglas.lan 3268
Looking for DNS entry SRV _ldap._tcp.pdc._msdcs.douglas.lan nodo1.douglas.lan 389 as _ldap._tcp.pdc._msdcs.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.pdc._msdcs.douglas.lan nodo1.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 389 as _ldap._tcp.default-first-site-name._sites.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo1.douglas.lan 389 as _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo1.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan nodo1.douglas.lan 3268 as _ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan.
Checking 0 100 3268 nodo1.douglas.lan. against SRV _ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan nodo1.douglas.lan 3268
Looking for DNS entry SRV _ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan nodo1.douglas.lan 389 as _ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan nodo1.douglas.lan 389
Looking for DNS entry SRV _gc._tcp.douglas.lan nodo1.douglas.lan 3268 as _gc._tcp.douglas.lan.
Checking 0 100 3268 nodo1.douglas.lan. against SRV _gc._tcp.douglas.lan nodo1.douglas.lan 3268
Looking for DNS entry SRV _gc._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 3268 as _gc._tcp.default-first-site-name._sites.douglas.lan.
Checking 0 100 3268 nodo1.douglas.lan. against SRV _gc._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 3268
No DNS updates needed

Agora vamos mandar atualizar todos os registros

samba_dnsupdate --verbose --all-names
IPs: ['192.168.0.25']
Calling nsupdate for A douglas.lan 192.168.0.25
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
douglas.lan.    900 IN  A 192.168.0.25

Calling nsupdate for A nodo1.douglas.lan 192.168.0.25
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
nodo1.douglas.lan.  900 IN  A 192.168.0.25

Calling nsupdate for A gc._msdcs.douglas.lan 192.168.0.25
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
gc._msdcs.douglas.lan.  900 IN  A 192.168.0.25

Calling nsupdate for CNAME eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4._msdcs.douglas.lan nodo1.douglas.lan
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4._msdcs.douglas.lan. 900 IN CNAME nodo1.douglas.lan.

Calling nsupdate for SRV _kpasswd._tcp.douglas.lan nodo1.douglas.lan 464
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kpasswd._tcp.douglas.lan. 900  IN  SRV 0 100 464 nodo1.douglas.lan.

Calling nsupdate for SRV _kpasswd._udp.douglas.lan nodo1.douglas.lan 464
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kpasswd._udp.douglas.lan. 900  IN  SRV 0 100 464 nodo1.douglas.lan.

Calling nsupdate for SRV _kerberos._tcp.douglas.lan nodo1.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._tcp.douglas.lan. 900 IN  SRV 0 100 88 nodo1.douglas.lan.

Calling nsupdate for SRV _kerberos._tcp.dc._msdcs.douglas.lan nodo1.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._tcp.dc._msdcs.douglas.lan. 900 IN SRV 0 100 88 nodo1.douglas.lan.

Calling nsupdate for SRV _kerberos._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._tcp.default-first-site-name._sites.douglas.lan. 900 IN SRV 0 100 88 nodo1.douglas.lan.

Calling nsupdate for SRV _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo1.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan. 900 IN SRV0 100 88 nodo1.douglas.lan.

Calling nsupdate for SRV _kerberos._udp.douglas.lan nodo1.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._udp.douglas.lan. 900 IN  SRV 0 100 88 nodo1.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.douglas.lan nodo1.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.douglas.lan. 900 IN  SRV 0 100 389 nodo1.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.dc._msdcs.douglas.lan nodo1.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.dc._msdcs.douglas.lan. 900 IN SRV  0 100 389 nodo1.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.gc._msdcs.douglas.lan nodo1.douglas.lan 3268
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.gc._msdcs.douglas.lan. 900 IN SRV  0 100 3268 nodo1.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.pdc._msdcs.douglas.lan nodo1.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.pdc._msdcs.douglas.lan. 900 IN SRV 0 100 389 nodo1.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.default-first-site-name._sites.douglas.lan. 900 IN SRV 0 100 389 nodo1.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo1.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan. 900 IN SRV 0 100 389 nodo1.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan nodo1.douglas.lan 3268
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan. 900 IN SRV 0 100 3268 nodo1.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan nodo1.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan. 900IN SRV 0 100 389 nodo1.douglas.lan.

Calling nsupdate for SRV _gc._tcp.douglas.lan nodo1.douglas.lan 3268
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_gc._tcp.douglas.lan. 900 IN  SRV 0 100 3268 nodo1.douglas.lan.

Calling nsupdate for SRV _gc._tcp.default-first-site-name._sites.douglas.lan nodo1.douglas.lan 3268
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_gc._tcp.default-first-site-name._sites.douglas.lan. 900 IN SRV 0 100 3268 nodo1.douglas.lan.

Agora vamos efetuar uma consulta de dns para registros de serviços

Vamos consultar o serviço do ldap

host -t SRV _ldap._tcp.douglas.lan.
_ldap._tcp.douglas.lan has SRV record 0 100 389 nodo1.douglas.lan.

Vamos consultar o serviço do kerberos

host -t SRV _kerberos._udp.douglas.lan.
_kerberos._udp.douglas.lan has SRV record 0 100 88 nodo1.douglas.lan.

Agora vamos consultar o registro do tipo A do nosso server

host -t A nodo1.douglas.lan
nodo1.douglas.lan has address 192.168.0.25

Agora vamos listar a keytab do kerberos

klist -k
Keytab name: FILE:/etc/krb5.keytab
KVNO Principal
---- --------------------------------------------------------------------------
   1 DNS/nodo1.douglas.lan@DOUGLAS.LAN
   1 dns-nodo1@DOUGLAS.LAN
   1 DNS/nodo1.douglas.lan@DOUGLAS.LAN
   1 dns-nodo1@DOUGLAS.LAN
   1 DNS/nodo1.douglas.lan@DOUGLAS.LAN
   1 dns-nodo1@DOUGLAS.LAN
   1 DNS/nodo1.douglas.lan@DOUGLAS.LAN
   1 dns-nodo1@DOUGLAS.LAN
   1 DNS/nodo1.douglas.lan@DOUGLAS.LAN
   1 dns-nodo1@DOUGLAS.LAN

Agora vamos consultar os tickets ativos

klist -e
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: administrator@DOUGLAS.LAN

Valid starting     Expires            Service principal
08/26/13 12:22:19  08/26/13 22:22:19  krbtgt/DOUGLAS.LAN@DOUGLAS.LAN
  renew until 08/27/13 12:22:16, Etype (skey, tkt): aes256-cts-hmac-sha1-96, aes256-cts-hmac-sha1-96 

Ajustando a PAM

Agora vamos a configuração da PAM, com isso vamos poder autenticar os usuários do domínio no Linux eu vou deixar habilitado somente o grupo do root e o ti-admin que terá que ser criado no AD para autenticar no Linux e obter um shell.

Vamos criar um link para a biblioteca de autenticação do winbind que foi compilada para sistemas 64bits

ln -sf /usr/local/samba/lib/security/pam_winbind.so  /lib64/security/pam_winbind.so

Vamos criar um link para a biblioteca de autenticação do winbind que foi compilada para sistemas 32bits

ln -sf /usr/local/samba/lib/security/pam_winbind.so  /lib/security/pam_winbind.so

Vamos alterar o system-auth para que quando o usuário for logar no sistema seja criado o diretório home dele com o conteúdo do diretório /etc/skel

vim /etc/pam.d/system-auth
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=3 type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0027

Agora vamos ajustar o login

vim /etc/pam.d/login
#%PAM-1.0 
auth       sufficient    pam_winbind.so
auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
auth       include      system-auth
 
account    sufficient     pam_succeed_if.so user ingroup root
account    required    pam_winbind.so
account    required     pam_nologin.so
account    include      system-auth
#Grupos que vão poder efetuar login no servidor
account    requisite    pam_succeed_if.so user ingroup ti-admin
 
password   include      system-auth
# pam_selinux.so close should be the first session rule 
 
session    required     pam_selinux.so close
session    required     pam_mkhomedir.so        skel=/etc/skel umask=0027
session    include      system-auth
session    required     pam_loginuid.so
session    optional     pam_console.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context 
session    required     pam_selinux.so open
session    optional     pam_keyinit.so force revoke

Agora vamos ajustar o ssh

vim /etc/pam.d/sshd
#%PAM-1.0 
auth       sufficient    pam_winbind.so
auth       include      system-auth
 
account    sufficient   pam_succeed_if.so user ingroup root
account    required     pam_winbind.so
account    required     pam_nologin.so
account    include      system-auth
#Grupos que vão poder logar via ssh
account    requisite    pam_succeed_if.so user ingroup ti-admin
 
password   include      system-auth
 
session    required     pam_mkhomedir.so        skel=/etc/skel umask=0027
session    optional     pam_keyinit.so force revoke
session    include      system-auth
session    required     pam_loginuid.so

Depois de criar o grupo e o usuário no sistema precisamos consultar eles via winbind para confirmarmos que o usuário e o grupo estão sendo mapeados.

Vamos consultar os usuários

wbinfo -u
Administrator
Guest
krbtgt
dns-nodo1
douglas.santos

Agora vamos consultar os grupos

wbinfo -g
Enterprise Read-Only Domain Controllers
Domain Admins
Domain Users
Domain Guests
Domain Computers
Domain Controllers
Schema Admins
Enterprise Admins
Group Policy Creator Owners
Read-Only Domain Controllers
DnsUpdateProxy
ti-admin

Agora vamos reiniciar o servidor

reboot

Agora depois que logou novamente vamos consultar a conexão do winbind

wbinfo -t
checking the trust secret for domain DOUGLAS via RPC calls succeeded

Eu já estou com o meu usuário douglas.santos e ele pertence ao grupo ti-admin agora vamos testar a conexão via ssh

ssh douglas.santos@192.168.0.25
douglas.santos@192.168.0.25's password: 
Creating directory '/home/DOUGLAS/douglas.santos'.
Last login: Mon Aug 26 13:05:38 2013 from 192.168.0.130
[13:10:02] DOUGLAS\douglas.santos@nodo1 [~] $

Agora se conferirmos os logs do secure vamos ter algo como

tail -f /var/log/secure
Aug 26 13:10:02 nodo1 sshd[1266]: pam_winbind(sshd:auth): getting password (0x00000000)
Aug 26 13:10:02 nodo1 sshd[1266]: pam_winbind(sshd:auth): user 'douglas.santos' granted access
Aug 26 13:10:02 nodo1 sshd[1266]: pam_succeed_if(sshd:account): requirement "user ingroup root" not met by user "DOUGLAS\douglas.santos"
Aug 26 13:10:02 nodo1 sshd[1266]: pam_winbind(sshd:account): user 'DOUGLAS\douglas.santos' granted access
Aug 26 13:10:02 nodo1 sshd[1266]: pam_succeed_if(sshd:account): requirement "user ingroup ti-admin" was met by user "DOUGLAS\douglas.santos"
Aug 26 13:10:02 nodo1 sshd[1266]: Accepted password for douglas.santos from 192.168.0.130 port 59514 ssh2
Aug 26 13:10:02 nodo1 sshd[1266]: pam_unix(sshd:session): session opened for user DOUGLAS\douglas.santos by (uid=0)

Como podemos notar a nossa autenticação está ok.

Backup e Restore do Samba 4

O script de backup do samba não é instalado quando rodamos o make install com isso precisamos copiar ele para o diretório onde ficam os binários.

Vou considerar que o os fontes do samba estão em /usr/src/samba-4.1.3

Vamos copiar os arquivos.

cp /usr/src/samba-4.1.3/source4/scripting/bin/samba_backup /usr/sbin

Agora vamos ajustar as permissões do arquivo de backup

chown root:root /usr/sbin/samba_backup
chmod 750 /usr/sbin/samba_backup

Agora precisamos ajustar as seguintes váriaveis no script

vim /usr/sbin/samba_backup
[...]
FROMWHERE=/usr/local/samba
WHERE=/usr/local/backups
[...]
DAYS=90

Temos:

  • FROMWHERE → aonde está instalado o nosso samba
  • WHERE → aonde desejamos armazenar o backup
  • DAYS → Quantidade de dias que vamos querer manter o nosso backup

Agora vamos criar o diretório que vai armazenar os arquivos do samba

mkdir /usr/local/backups

Agora vamos ajustar as permissões

chmod 750 /usr/local/backups

Agora podemos rodar o script

/usr/sbin/samba_backup

Vamos ter alguns arquivos como abaixo

ls -l /usr/local/backups
total 12148
-rw-r--r-- 1 root root      819 Ago 26 13:18 etc.260813.tar.bz2
-rw-r--r-- 1 root root 12428120 Ago 26 13:18 samba4_private.260813.tar.bz2
-rw-r--r-- 1 root root      510 Ago 26 13:18 sysvol.260813.tar.bz2

Se o script for executado sem erros, vamos ter 3 arquivos após o termino:

  • etc.{Timestamp}.tar.bz2
  • samba4_private.{Timestamp}.tar.bz2
  • sysvol.{Timestamp}.tar.bz2

Nós podemos deixar o script de backup no crontab. Exemplo vamos deixar um backup diário as 2 da manhã.

crontab -e
0 2 * * *       /usr/sbin/samba_backup

Já temos a nossa rotina de Backup pronta.

Restore

OBS:

  • O backup e o restore tem que ser da mesma versão do Samba ou seja de 4.1.3 para 4.1.3
  • O Restore deve ser feito em uma máquina com o mesmo nome e ip da máquina que foi efetuado o backup.
  • É recomendado sempre restaurar o backup no mesmo SO que foi feito o backup pois da merda (Já testei e algumas coisas não funcionam)
  • Sempre após um restore é importante testar todo o samba antes de colocar em produção novamente.
  • Se o sistema todo foi corrompido você precisa primeiro configurar um Samba novamente para depois restaurar o backup considerando o que já foi mencionado.

Agora o samba não pode estar rodando para podermos remover os arquivo para resturar o backup

Vamos parar o samba

/etc/init.d/samba stop
Shutting down SMB services:                                [  OK  ]

Vamos remover os arquivos e diretório necessários

rm -rf /usr/local/samba/etc
rm -rf /usr/local/samba/private
rm -rf /usr/local/samba/var/locks/sysvol

Agora vamos efetuar o restore dos arquivos

cd /usr/local/backups
tar -jxf etc.260813.tar.bz2 -C /usr/local/samba
tar -jxf samba4_private.260813.tar.bz2 -C /usr/local/samba 
tar -jxf sysvol.260813.tar.bz2 -C /usr/local/samba

Agora precisamos renomear os aquivos *.ldb.bak no diretório private para *.ldb

find /usr/local/samba/private/ -type f -name '*.ldb.bak' -print0 | while read -d $'\0' f ; do mv "$f" "${f%.bak}" ; done

Agora vamos restaurar as acls do sysvol

samba-tool ntacl sysvolreset

Agora caso esteja utilizando o o BIND_DLZ como backend precisamos corrigir os hardlinks para o banco de dados do DNS

samba_upgradedns --dns-backend=BIND9_DLZ

Agora vamos iniciar o samba

/etc/init.d/samba start
Starting SMB services: 

Agora vamos listar os nossos usuários

wbinfo -u
Administrator
Guest
krbtgt
dns-nodo1
douglas.santos

Agora vamos listar os nossos grupos

wbinfo -g
Enterprise Read-Only Domain Controllers
Domain Admins
Domain Users
Domain Guests
Domain Computers
Domain Controllers
Schema Admins
Enterprise Admins
Group Policy Creator Owners
Read-Only Domain Controllers
DnsUpdateProxy
ti-admin

Tudo ok como estava antes do backup.

Criando compartilhamentos

A criação de compartilhamentos no Samba ficou mais simples pelo meu ponto de vista, podemos fazer o gerenciamento das permissões dos compartilhamentos via Windows.

OBS: Você precisa ser dono do diretório ou pertencer ao grupo dono do diretório para poder visualizar ou manipular as permissões.

Vamos habilitar os administradores do domínio a gerenciarem os compartilhamentos via Windows

net rpc rights grant 'DOUGLAS\Domain Admins' SeDiskOperatorPrivilege -U administrator
Enter administrator's password:
Successfully granted rights.

Se acabar precisando dar todas as permissões existentes para um deternimado grupo por exemplo para DOUGLAS\Domain Admins' podemos fazer da seguinte forma

net rpc rights grant  'DOUGLAS\Domain Admins' SeMachineAccountPrivilege SeTakeOwnershipPrivilege SeBackupPrivilege SeRestorePrivilege SeRemoteShutdownPrivilege SePrintOperatorPrivilege SeAddUsersPrivilege SeDiskOperatorPrivilege SeSecurityPrivilege SeSystemtimePrivilege SeShutdownPrivilege SeDebugPrivilege SeSystemEnvironmentPrivilege SeSystemProfilePrivilege SeProfileSingleProcessPrivilege SeIncreaseBasePriorityPrivilege SeLoadDriverPrivilege SeCreatePagefilePrivilege SeIncreaseQuotaPrivilege SeChangeNotifyPrivilege SeUndockPrivilege SeManageVolumePrivilege SeImpersonatePrivilege SeCreateGlobalPrivilege SeEnableDelegationPrivilege -U administrator
Enter administrator's password:
Successfully granted rights.

Agora vamos criar um novo compartilhamento

vim /usr/local/samba/etc/smb.conf
[...]
[Demo]
     path = /srv/samba/Demo/
     read only = no

Agora vamos criar o diretório

mkdir -p /srv/samba/Demo/

Agora vamos recarregar as configurações do samba

smbcontrol all reload-config

Agora no Windows com um usuário do grupo Domain Adminis eu vou usar o Administrator

  • Abra menu iniciar executar e digite: compmgmt.msc
  • Click com o botão direito em gerenciamento do computador e conectar a outro computador
  • Agora informe o nome do servidor samba ou o seu endereço ip
  • Agora navegue até ferramentas do sistema/Pastas compartilhadas/compartilhamentos agora selecione o nosso novo compartilhamento

  • Click com o botão direito no compartilhamento e selecione Propriedades
  • Agora na guia permissões de compartilhamento. Aqui você pode configurar quem vai ter acesso ao compartilhamento

  • Selecione agora a guia segurança em editar podemos alterar as permissões do sistema de arquivo.

  • Agora é so selecionar ok e fechar a janela.

Perfil móvel

Agora vamos configurar o perfil móvel.

Vamos criar o diretório que vai armazenar os profiles

mkdir -p /srv/samba/Profiles/

Agora vamos adicionar mais um compartilhamento no samba

vim /usr/local/samba/etc/smb.conf
[...]
[Profiles]
     path = /srv/samba/Profiles/
     read only = no

Agora vamos recarregar o samba

smbcontrol all reload-config

Agora vamos logar em uma máquina Windows com um usuário administrador

  • Menu Iniciar/Executar digite: \\nodo1

Vamos ter algo como abaixo

  • Click com o botão direito no compartilhamento e escolha Propriedades e selecione a guia Segurança
  • Click em avançadas e selecione Alterar Permissões.
  • Deixe somente:
    • Administrator
    • Proprietário criador
  • Agora adicione Domain Users

Agora deixe as permissões como a tabela abaixo:

Nome Permissão Aplicato a
Administrator Controle Total Esta pasta, subpastas e arquivos
Domain Users Percorrer pastas/executar arquivos, Listas pastas/ler dados, Criar pastas/acrescentar dados Esta pasta somente
PROPRIETÁRIO CRIADOR Controle Total Subpastas e Arquivos Somente

Permissão dos domains Users vai ser algo como abaixo

Depois disso:

  • Ok
  • OK
  • Sim
  • Ok
  • OK

Agora vamos ajustar o perfil remoto.

  • Menu Iniciar/Ferramentas Administrativas/Usuários e Computadores do Active Directory
  • Selecione o usuário que deseja configurar o perfil móvel
  • Click com o botão direito selecione propriedades
  • Agora selecione perfil
  • Agora em caminho do perfil informe: \\nodo1.douglas.lan\Profiles\%username%
  • Agora selecione Ok
  • Agora já pode logar com o seu usuário e testar o perfil os dados do perfil vão ficar armazenados em:
    • /srv/samba/Profiles/

Depois de logar e efetuar o logout com o usuário douglas.santos vamos ter algo como abaixo

ls -l /srv/samba/Profiles
total 8
drwxrwx---+ 14 DOUGLAS\douglas.santos users 4096 Ago 26 17:04 douglas.santos.V2/

Script de Logon

O script de logon pode ser adicionado em /usr/local/samba/var/locks/sysvol/douglas.lan/scripts

Vamos criar um script simples para mapear o compartilhamento demo

vim /usr/local/samba/var/locks/sysvol/douglas.lan/scripts/sharedemo.bat
net use x: \\nodo1.douglas.lan\Demo

Agora vamos ajustar as permissões dele

chmod +x /usr/local/samba/var/locks/sysvol/douglas.lan/scripts/sharedemo.bat

Agora vamos converter ele para o formato Microsoft

unix2dos /usr/local/samba/var/locks/sysvol/douglas.lan/scripts/sharedemo.bat
  • Menu Iniciar/Ferramentas Administrativas/Usuários e Computadores do Active Directory
  • Selecione o usuário que deseja configurar o perfil móvel
  • Click com o botão direito selecione propriedades
  • Agora selecione perfil
  • Em script de logon informe: sharedemo.bat

Agora vamos efetuar logon com o nosso usuário douglas.santos

Vamos ter algo como o abaixo

Configuração do SLAVE

Vamos atualizar os repositórios e vamos fazer um upgrade do sistema

yum check-update && yum update -y

Agora vamos instalar as dependências para podemos compilar o samba

yum install  openldap-devel pam-devel git gcc make wget  libacl-devel libblkid-devel gnutls-devel readline-devel python-devel cups-devel \
libaio-devel quota-devel ctdb-devel krb5-devel krb5-workstation acl setroubleshoot-server setroubleshoot-plugins policycoreutils-python \
libsemanage-python setools-libs-python setools-libs popt-devel libpcap-devel libidn-devel libxml2-devel libacl-devel libsepol-devel libattr-devel \
keyutils-libs-devel cyrus-sasl-devel cups-devel bind-utils bind-sdb bind-devel bind-libs bind avahi-devel mingw32-iconv gamin \
libcap-devel rpc2-devel glusterfs-devel python-dns -y

Agora vamos ajustar o fstab para que ele de suporte a acl,user_xattr e barrier eu vou habilitar isso na partição / se você tiver várias partições é bom habilitar em todas que você queira habilitar os compartilhamentos.

vim /etc/fstab
[...]
/dev/mapper/VolGroup-lv_root /                       ext4    defaults,acl,user_xattr,barrier=1        1 1

Agora vamos remontar a raiz

mount -o remount /

Agora vamos listar os atributos da raiz

mount | egrep acl
/dev/mapper/VolGroup-lv_root on / type ext4 (rw,acl,user_xattr,barrier=1)

Agora os atributos já estão carregados.

Agora vamos obter o samba vamos acessar o diretório que vai armazenar os fontes

cd /usr/src

Agora vamos obter os fontes

wget -c http://ftp.samba.org/pub/samba/stable/samba-4.1.3.tar.gz

Agora vamos desempacotar o samba

tar -xzvf samba-4.1.3.tar.gz

Agora vamos acessar o diretório dos fontes

cd samba-4.1.3

Agora vamos criar a configuração para o samba

./configure --enable-debug --enable-selftest

Agora vamos mandar compilar o samba este processo demora um pouco

make

Agora vamos mandar instalar o samba

make install

Agora vamos acertar a PATH do usuário root no caso dele estar utilizando o shell Bash

echo "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/local/samba/sbin:/usr/local/samba/bin" >> /root/.bashrc

Agora precisamos importar a nova PATH

source /root/.bashrc

Agora vamos acertar a PATH do usuário root no caso dele estar utilizando o shell zsh

echo "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/local/samba/sbin:/usr/local/samba/bin" >> /root/.zshrc

Agora precisamos importar a nova PATH

source /root/.zshrc

Agora vamos ajustar o resolv.conf ele vai utilizar o nome do nosso domínio e o ip do pdc.

vim /etc/resolv.conf
domain douglas.lan
search douglas.lan
nameserver 192.168.0.25

Agora vamos ajustar a interface de rede para utilizar o nosso novo DNS

vim /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"
BOOTPROTO="static"
BROADCAST="192.168.0.255"
DNS1="192.168.0.26"
GATEWAY="192.168.0.1"
IPADDR="192.168.0.25"
NETMASK="255.255.255.0"
NM_CONTROLLED="yes"
ONBOOT="yes"
TYPE="Ethernet"

Agora vamos configurar o Bind

vim /etc/named.conf
//named.conf

options {
  listen-on port 53 { 127.0.0.1; 192.168.0.0/24; };
  listen-on-v6 port 53 { ::1; };
  directory   "/var/named";
  dump-file   "/var/named/data/cache_dump.db";
  statistics-file "/var/named/data/named_stats.txt";
  memstatistics-file "/var/named/data/named_mem_stats.txt";
  allow-query     { 192.168.0.0/24; localhost; };
  recursion yes;
  forwarders { 8.8.8.8; 8.8.4.4; };

  dnssec-enable yes;
  dnssec-validation yes;
  dnssec-lookaside auto;

  /* Path to ISC DLV key */
  bindkeys-file "/etc/named.iscdlv.key";

  managed-keys-directory "/var/named/dynamic";

 /* keytab para samba4 */
  tkey-gssapi-keytab "/usr/local/samba/private/dns.keytab";

};

logging {
  channel default_debug {
          file "data/named.run";
          severity dynamic;
  };
};

zone "." IN {
  type hint;
  file "named.ca";
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
/*Arquivo de configuração do samba4 que informa a localização do bind_dlz */
include "/usr/local/samba/private/named.conf";

Agora vamos ajustar a configuração do krb5.conf

vim /etc/krb5.conf
[logging]
     default = FILE:/var/log/krb5libs.log
     kdc = FILE:/var/log/krb5kdc.log
     admin_server = FILE:/var/log/kadmind.log

[libdefaults]
     default_realm = DOUGLAS.LAN
     dns_lookup_realm = true
     dns_lookup_kdc = true
     ticket_lifetime = 24h
     forwardable = yes

[appdefaults]
     pam = {
          debug = false
          ticket_lifetime = 36000
          renew_lifetime = 36000
          forwardable = true
          krb4_convert = false
     }

Vamos abrir um ticket no kerberos para verificarmos a nossa configuração

kinit administrator
Password for administrator@DOUGLAS.LAN: 
Warning: Your password will expire in 41 days on Mon Oct  7 12:02:11 2013

Agora vamos inserir o nosso servidor como bdc

Agora vamos provisionar o nosso domínio

samba-tool domain join douglas.lan DC -U administrator --realm=douglas.lan --dns-backend=BIND9_DLZ 
Finding a writeable DC for domain 'douglas.lan'
Found DC nodo1.douglas.lan
Password for [DOUGLAS\administrator]:
workgroup is DOUGLAS
realm is douglas.lan
checking sAMAccountName
Deleted CN=NODO2,OU=Domain Controllers,DC=douglas,DC=lan
Deleted CN=NTDS Settings,CN=NODO2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=douglas,DC=lan
Deleted CN=NODO2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=douglas,DC=lan
Adding CN=NODO2,OU=Domain Controllers,DC=douglas,DC=lan
Adding CN=NODO2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=douglas,DC=lan
Adding CN=NTDS Settings,CN=NODO2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=douglas,DC=lan
Adding SPNs to CN=NODO2,OU=Domain Controllers,DC=douglas,DC=lan
Setting account password for NODO2$
Enabling account
Calling bare provision
No IPv6 address will be assigned
Provision OK for domain DN DC=douglas,DC=lan
Starting replication
Schema-DN[CN=Schema,CN=Configuration,DC=douglas,DC=lan] objects[402/1550] linked_values[0/0]
Schema-DN[CN=Schema,CN=Configuration,DC=douglas,DC=lan] objects[804/1550] linked_values[0/0]
Schema-DN[CN=Schema,CN=Configuration,DC=douglas,DC=lan] objects[1206/1550] linked_values[0/0]
Schema-DN[CN=Schema,CN=Configuration,DC=douglas,DC=lan] objects[1550/1550] linked_values[0/0]
Analyze and apply schema objects
Partition[CN=Configuration,DC=douglas,DC=lan] objects[402/1625] linked_values[0/0]
Partition[CN=Configuration,DC=douglas,DC=lan] objects[804/1625] linked_values[0/0]
Partition[CN=Configuration,DC=douglas,DC=lan] objects[1206/1625] linked_values[0/0]
Partition[CN=Configuration,DC=douglas,DC=lan] objects[1608/1625] linked_values[0/0]
Partition[CN=Configuration,DC=douglas,DC=lan] objects[1625/1625] linked_values[28/0]
Replicating critical objects from the base DN of the domain
Partition[DC=douglas,DC=lan] objects[98/98] linked_values[25/0]
Partition[DC=douglas,DC=lan] objects[375/277] linked_values[26/0]
Done with always replicated NC (base, config, schema)
Replicating DC=DomainDnsZones,DC=douglas,DC=lan
Partition[DC=DomainDnsZones,DC=douglas,DC=lan] objects[40/40] linked_values[0/0]
Replicating DC=ForestDnsZones,DC=douglas,DC=lan
Partition[DC=ForestDnsZones,DC=douglas,DC=lan] objects[18/18] linked_values[0/0]
Partition[DC=ForestDnsZones,DC=douglas,DC=lan] objects[36/18] linked_values[0/0]
Committing SAM database
Sending DsReplicateUpdateRefs for all the replicated partitions
Setting isSynchronized and dsServiceName
Setting up secrets database
Joined domain DOUGLAS (SID S-1-5-21-2011945809-1847694634-1467046014) as a DC

Agora vamos inserir o named na incialização do sistema

chkconfig --add named 
chkconfig named on

Agora vamos criar o script de inicialização

vim /etc/init.d/samba
#!/bin/sh
#
# chkconfig: - 91 35
# description: Starts and stops the Samba smbd daemon \
#        used to provide SMB network services.
#
# pidfile: /var/run/samba/smbd.pid
# config:  /etc/samba/smb.conf


# Source function library.
if [ -f /etc/init.d/functions ] ; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
  . /etc/rc.d/init.d/functions
else
  exit 1
fi

# Avoid using root's TMPDIR
unset TMPDIR

# Source networking configuration.
. /etc/sysconfig/network

if [ -f /etc/sysconfig/samba ]; then
   . /etc/sysconfig/samba
fi

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 1

# Check that smb.conf exists.
[ -f /usr/local/samba/etc/smb.conf ] || exit 6

RETVAL=0


start() {
        KIND="SMB"
  echo -n $"Starting $KIND services: "
  /usr/local/samba/sbin/samba
  RETVAL=$?
  echo
  [ $RETVAL -eq 0 ] && touch /usr/local/samba/var/lock/smb || \
     RETVAL=1
  return $RETVAL
}

stop() {
        KIND="SMB"
  echo -n $"Shutting down $KIND services: "
  killproc smbd
  RETVAL=$?
  echo
  [ $RETVAL -eq 0 ] && rm -f /usr/local/samba/var/lock/smb
  return $RETVAL
}

restart() {
  stop
  start
}

reload() {
        echo -n $"Reloading smb.conf file: "
  killproc smbd -HUP
  RETVAL=$?
  echo
  return $RETVAL
}

rhstatus() {
  status -l smb smbd
  return $?
}


# Allow status as non-root.
if [ "$1" = status ]; then
       rhstatus
       exit $?
fi

# Check that we can write to it... so non-root users stop here
[ -w /usr/local/samba/etc/smb.conf ] || exit 4



case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  restart)
    restart
  ;;
  reload)
    reload
  ;;
  status)
    rhstatus
  ;;
  condrestart)
    [ -f /var/lock/subsys/smb ] && restart || :
  ;;
  *)
  echo $"Usage: $0 {start|stop|restart|reload|status|condrestart}"
  exit 2
esac

exit $?

Agora vamos dar permissão para o nosso script e vamos inserir ele na incialização

chmod +x /etc/init.d/samba
chkconfig --add samba
chkconfig samba on

Agora vamos inicializar o named e o samba

/etc/init.d/named start
/etc/init.d/samba start

Agora vamos consultar o daemon do samba

ps aux | egrep samba
root      1268  7.0  8.2 525140 41276 ?        Ss   18:50   0:00 /usr/local/samba/sbin/samba
root      1271  0.0  5.7 525140 28648 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1272  0.0  5.8 525140 29500 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1273  0.1  6.2 529292 31152 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1274  0.0  5.6 525140 28608 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1275  8.8  6.1 525140 30768 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1276  0.0  5.8 525140 29204 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1277  7.0  8.6 576100 43440 ?        Ss   18:50   0:00 /usr/local/samba/sbin/smbd --option=server role check:inhibit=yes --foreground
root      1278  0.0  6.1 525140 30716 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1279  0.5  6.2 529292 31316 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1280  0.1  5.9 527652 29864 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1281  0.0  5.7 525140 28748 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1282  0.0  5.9 525140 29712 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1283  0.0  5.9 525140 29708 ?        S    18:50   0:00 /usr/local/samba/sbin/samba
root      1291  0.0  5.7 575584 29052 ?        S    18:50   0:00 /usr/local/samba/sbin/smbd --option=server role check:inhibit=yes --foreground

Como pode ser visto ele está rodando ok.

Agora vamos listar a versão do nosso samba

smbclient --version
Version 4.1.3

Agora vamos mandar listar os compartilhamentos

smbclient -L localhost -U%
Domain=[DOUGLAS] OS=[Unix] Server=[Samba 4.1.3]

  Sharename       Type      Comment
  ---------       ----      -------
  netlogon        Disk      
  sysvol          Disk      
  IPC$            IPC       IPC Service (Samba 4.1.3)
Domain=[DOUGLAS] OS=[Unix] Server=[Samba 4.1.3]

  Server               Comment
  ---------            -------

  Workgroup            Master
  ---------            -------

Agora vamos mandar listar o netlogon com o usuário administrator

smbclient //localhost/netlogon -UAdministrator%'sen@134*' -c 'ls'
Domain=[DOUGLAS] OS=[Unix] Server=[Samba 4.1.3]
  .                                   D        0  Mon Aug 26 18:35:20 2013
  ..                                  D        0  Mon Aug 26 18:35:20 2013

    34426 blocks of size 262144. 23857 blocks available

Agora vamos mandar listar a configuração do nosso samba

testparm
Load smb config files from /usr/local/samba/etc/smb.conf
rlimit_max: increasing rlimit_max (4096) to minimum Windows limit (16384)
Processing section "[netlogon]"
Processing section "[sysvol]"
Loaded services file OK.
Server role: ROLE_ACTIVE_DIRECTORY_DC
Press enter to see a dump of your service definitions

[global]
  workgroup = DOUGLAS
  realm = douglas.lan
  server role = active directory domain controller
  passdb backend = samba_dsdb
  server services = s3fs, rpc, nbt, wrepl, ldap, cldap, kdc, drepl, winbind, ntp_signd, kcc, dnsupdate
  rpc_server:tcpip = no
  rpc_daemon:spoolssd = embedded
  rpc_server:spoolss = embedded
  rpc_server:winreg = embedded
  rpc_server:ntsvcs = embedded
  rpc_server:eventlog = embedded
  rpc_server:srvsvc = embedded
  rpc_server:svcctl = embedded
  rpc_server:default = external
  idmap config * : backend = tdb
  map archive = No
  map readonly = no
  store dos attributes = Yes
  vfs objects = dfs_samba4, acl_xattr

[netlogon]
  path = /usr/local/samba/var/locks/sysvol/douglas.lan/scripts
  read only = No

[sysvol]
  path = /usr/local/samba/var/locks/sysvol
  read only = No

Agora vamos ajustar o limits.conf para não aparecer os avisos no samba

vim /etc/security/limits.conf
#colocar no final do arquivo
root hard nofile 131072
root soft nofile 65536
mioutente hard nofile 32768
mioutente soft nofile 16384

Agora vamos testar a resolução de nome

nslookup douglas.lan
Server:   192.168.0.25
Address:  192.168.0.25#53

Name: douglas.lan
Address: 192.168.0.25
Name: douglas.lan
Address: 192.168.0.26

Agora vamos ajustar a configuração do kerberos

Vamos fazer backup do arquivo de configuração

mv /etc/krb5.conf /etc/krb5.conf.old

Vamos criar um link para o sistema reconhecer o arquivo de configuração do samba como default

ln -sf /usr/local/samba/private/krb5.conf /etc/krb5.conf

Agora vamos ajustar a configuração do krb5.conf

vim /etc/krb5.conf
[logging]
     default = FILE:/var/log/krb5libs.log
     kdc = FILE:/var/log/krb5kdc.log
     admin_server = FILE:/var/log/kadmind.log

[libdefaults]
     default_realm = DOUGLAS.LAN
     dns_lookup_realm = true
     dns_lookup_kdc = true
     ticket_lifetime = 24h
     forwardable = yes

[appdefaults]
     pam = {
          debug = false
          ticket_lifetime = 36000
          renew_lifetime = 36000
          forwardable = true
          krb4_convert = false
     }

Agora vamos criar um link para o keytab do kerberos

ln -s /usr/local/samba/private/dns.keytab /etc/krb5.keytab 

Agora vamos ajustar a configuração do samba para que ele consiga mapear via winbind

vim /usr/local/samba/etc/smb.conf
[global]
  workgroup = DOUGLAS
  realm = douglas.lan
  netbios name = NODO2
  server role = active directory domain controller
  passdb backend = samba_dsdb
  server services = s3fs, rpc, nbt, wrepl, ldap, cldap, kdc, drepl, winbind, ntp_signd, kcc, dnsupdate
  rpc_server:tcpip = no
  rpc_daemon:spoolssd = embedded
  rpc_server:spoolss = embedded
  rpc_server:winreg = embedded
  rpc_server:ntsvcs = embedded
  rpc_server:eventlog = embedded
  rpc_server:srvsvc = embedded
  rpc_server:svcctl = embedded
  rpc_server:default = external
  #IDMAP
  idmap_ldb:use rfc2307 = yes
  idmap config * : backend = tdb
  idmap config *:range = 70001-80000
  idmap config DOUGLAS:backend = ad
  idmap config DOUGLAS:schema_mode = rfc2307
  idmap config DOUGLAS:range = 500-40000
  #WINBIND
  winbind nss info = rfc2307
  winbind trusted domains only = no
  winbind use default domain = yes
  winbind enum users  = yes
  winbind enum groups = yes
  map archive = No
  map readonly = no
  store dos attributes = Yes
  vfs objects = dfs_samba4, acl_xattr
  #o template shell é necessário para logar com a autenticação via winbind
  template shell = /bin/bash
  #DESABILITANDO AS IMPRESSORAS
  printcap name = /dev/null
  load printers = no
  disable spoolss = yes
  printing = bsd
  ### LOGS
  log file = /var/log/samba/smbd.log
  max log size = 50
  log level = 2
  vfs objects = recycle full_audit
  ### LIXEIRA
  recycle:repository = Lixeira
  recycle:exclude = *.tmp *.TMP *.temp *.TEMP ~*
  recycle:keeptree = yes
  full_audit:success = rmdir mkdir open write rename unlink
  full_audit:failure = rmdir mkdir open write rename unlink
  full_audit:prefix = %U|%I|%m|%S
  full_audit:failure = none
  full_audit:facility = local5
  full_audit:priority = notice
  veto files = /*.mp3/*.wav/*.exe/*.cmd/*.adm/*.inf/*.ini/*.pif
  delete veto files = yes
  dos filemode = yes


[netlogon]
  path = /usr/local/samba/var/locks/sysvol/douglas.lan/scripts
  read only = No

[sysvol]
  path = /usr/local/samba/var/locks/sysvol
  read only = No

Agora vamos criar o diretório para armazenar os logs

mkdir -p /var/log/samba

Agora precisamos ajustar as bibliotecas do winbind para os sistemas de 32bits precisamos fazer da seguinte forma

ln -s /usr/local/samba/lib/libnss_winbind.so /lib
ln -s /lib/libnss_winbind.so /lib/libnss_winbind.so.2
ldconfig

Para os sistemas de 64bits precisamos fazer da seguinte forma

ln -s /usr/local/samba/lib/libnss_winbind.so /lib64
ln -s /lib64/libnss_winbind.so /lib64/libnss_winbind.so.2
ldconfig

Agora vamos ajustar o nsswitch.conf

vim /etc/nsswitch.conf
[...]
passwd: files winbind
[...]
group:  files winbind

Agora vamos inicializar um ticket para o administrator

kinit administrator
Password for administrator@DOUGLAS.LAN: 
Warning: Your password will expire in 41 days on Mon Oct  7 12:02:11 2013

Agora vamos listar o nosso ticket

klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: administrator@DOUGLAS.LAN

Valid starting     Expires            Service principal
08/26/13 18:54:21  08/27/13 04:54:21  krbtgt/DOUGLAS.LAN@DOUGLAS.LAN
  renew until 08/27/13 18:54:17

O nosso kerberos está ok.

Vamos instalar o ntp

yum install ntp -y

Agora vamos fazer um backup do arquivo de configuração default do ntp.conf

cp /etc/ntp.conf /etc/ntp.conf.old

Agora vamos configurar o ntp

vim /etc/ntp.conf
server 127.127.1.0
fudge  127.127.1.0 stratum 10
server a.ntp.br iburst prefer
server 0.pool.ntp.org  iburst prefer
server 1.pool.ntp.org  iburst prefer
driftfile /var/lib/ntp/ntp.drift
logfile /var/log/ntp
ntpsigndsocket /usr/local/samba/var/lib/ntp_signd/
restrict default kod nomodify notrap nopeer mssntp
restrict 127.0.0.1
restrict a.ntp.br mask 255.255.255.255 nomodify notrap nopeer noquery
restrict 0.pool.ntp.org mask 255.255.255.255 nomodify notrap nopeer noquery
restrict 1.pool.ntp.org mask 255.255.255.255 nomodify notrap nopeer noquery

Agora vamos iniciar ele

/etc/init.d/ntpd start

Agora vamos consultar o seu sincronismo

ntpq -p 127.0.0.1
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 LOCAL(0)        .LOCL.          10 l    -   64    1    0.000    0.000   0.000
 a.ntp.br        .INIT.          16 u    -   64    0    0.000    0.000   0.000
 a.st1.ntp.br    .INIT.          16 u    -   64    0    0.000    0.000   0.000
 roma.coe.ufrj.b .INIT.          16 u    -   64    0    0.000    0.000   0.000

Agora vamos inserir o ntp na incialização

chkconfig --add ntpd
chkconfig ntpd on

Agora vamos atualizar o nosso ntp

ntpdate -u a.ntp.br

Agora vamos ajustar o grupo do arquivo ntp_signd

chgrp ntp /usr/local/samba/var/lib/ntp_signd

O nosso samba já está ok.

Agora podemos obter os RSAT(Admin pack) em:

Agora vamos testar o winbind

wbinfo -t
checking the trust secret for domain DOUGLAS via RPC calls succeeded

Agora vamos listar os grupos

wbinfo -g
Enterprise Read-Only Domain Controllers
Domain Admins
Domain Users
Domain Guests
Domain Computers
Domain Controllers
Schema Admins
Enterprise Admins
Group Policy Creator Owners
Read-Only Domain Controllers
DnsUpdateProxy
ti-admin

Agora vamos listar os usuários

wbinfo -u
Administrator
Guest
krbtgt
dns-nodo1
douglas.santos

Agora vamos testar o update de dns no samba

samba_dnsupdate --verbose
IPs: ['192.168.0.26']
Skipping PDC entry (SRV _ldap._tcp.pdc._msdcs.${DNSDOMAIN}                   ${HOSTNAME} 389) as we are not a PDC
Skipping PDC entry (SRV _ldap._tcp.pdc._msdcs.${DNSFOREST}                   ${HOSTNAME} 389) as we are not a PDC
Looking for DNS entry A douglas.lan 192.168.0.26 as douglas.lan.
Looking for DNS entry A nodo2.douglas.lan 192.168.0.26 as nodo2.douglas.lan.
Looking for DNS entry A gc._msdcs.douglas.lan 192.168.0.26 as gc._msdcs.douglas.lan.
Looking for DNS entry CNAME ccc206ae-bc66-4a4e-a282-06aa4613cadd._msdcs.douglas.lan nodo2.douglas.lan as ccc206ae-bc66-4a4e-a282-06aa4613cadd._msdcs.douglas.lan.
Looking for DNS entry SRV _kpasswd._tcp.douglas.lan nodo2.douglas.lan 464 as _kpasswd._tcp.douglas.lan.
Checking 0 100 464 nodo2.douglas.lan. against SRV _kpasswd._tcp.douglas.lan nodo2.douglas.lan 464
Looking for DNS entry SRV _kpasswd._udp.douglas.lan nodo2.douglas.lan 464 as _kpasswd._udp.douglas.lan.
Checking 0 100 464 nodo1.douglas.lan. against SRV _kpasswd._udp.douglas.lan nodo2.douglas.lan 464
Checking 0 100 464 nodo2.douglas.lan. against SRV _kpasswd._udp.douglas.lan nodo2.douglas.lan 464
Looking for DNS entry SRV _kerberos._tcp.douglas.lan nodo2.douglas.lan 88 as _kerberos._tcp.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._tcp.douglas.lan nodo2.douglas.lan 88
Checking 0 100 88 nodo2.douglas.lan. against SRV _kerberos._tcp.douglas.lan nodo2.douglas.lan 88
Looking for DNS entry SRV _kerberos._tcp.dc._msdcs.douglas.lan nodo2.douglas.lan 88 as _kerberos._tcp.dc._msdcs.douglas.lan.
Checking 0 100 88 nodo2.douglas.lan. against SRV _kerberos._tcp.dc._msdcs.douglas.lan nodo2.douglas.lan 88
Looking for DNS entry SRV _kerberos._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 88 as _kerberos._tcp.default-first-site-name._sites.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 88
Checking 0 100 88 nodo2.douglas.lan. against SRV _kerberos._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 88
Looking for DNS entry SRV _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo2.douglas.lan 88 as _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo2.douglas.lan 88
Checking 0 100 88 nodo2.douglas.lan. against SRV _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo2.douglas.lan 88
Looking for DNS entry SRV _kerberos._udp.douglas.lan nodo2.douglas.lan 88 as _kerberos._udp.douglas.lan.
Checking 0 100 88 nodo1.douglas.lan. against SRV _kerberos._udp.douglas.lan nodo2.douglas.lan 88
Checking 0 100 88 nodo2.douglas.lan. against SRV _kerberos._udp.douglas.lan nodo2.douglas.lan 88
Looking for DNS entry SRV _ldap._tcp.douglas.lan nodo2.douglas.lan 389 as _ldap._tcp.douglas.lan.
Checking 0 100 389 nodo2.douglas.lan. against SRV _ldap._tcp.douglas.lan nodo2.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.dc._msdcs.douglas.lan nodo2.douglas.lan 389 as _ldap._tcp.dc._msdcs.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.dc._msdcs.douglas.lan nodo2.douglas.lan 389
Checking 0 100 389 nodo2.douglas.lan. against SRV _ldap._tcp.dc._msdcs.douglas.lan nodo2.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.gc._msdcs.douglas.lan nodo2.douglas.lan 3268 as _ldap._tcp.gc._msdcs.douglas.lan.
Checking 0 100 3268 nodo2.douglas.lan. against SRV _ldap._tcp.gc._msdcs.douglas.lan nodo2.douglas.lan 3268
Looking for DNS entry SRV _ldap._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 389 as _ldap._tcp.default-first-site-name._sites.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 389
Checking 0 100 389 nodo2.douglas.lan. against SRV _ldap._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo2.douglas.lan 389 as _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan.
Checking 0 100 389 nodo1.douglas.lan. against SRV _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo2.douglas.lan 389
Checking 0 100 389 nodo2.douglas.lan. against SRV _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo2.douglas.lan 389
Looking for DNS entry SRV _ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan nodo2.douglas.lan 3268 as _ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan.
Checking 0 100 3268 nodo2.douglas.lan. against SRV _ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan nodo2.douglas.lan 3268
Looking for DNS entry SRV _ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan nodo2.douglas.lan 389 as _ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan.
Checking 0 100 389 nodo2.douglas.lan. against SRV _ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan nodo2.douglas.lan 389
Looking for DNS entry SRV _gc._tcp.douglas.lan nodo2.douglas.lan 3268 as _gc._tcp.douglas.lan.
Checking 0 100 3268 nodo2.douglas.lan. against SRV _gc._tcp.douglas.lan nodo2.douglas.lan 3268
Looking for DNS entry SRV _gc._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 3268 as _gc._tcp.default-first-site-name._sites.douglas.lan.
Checking 0 100 3268 nodo1.douglas.lan. against SRV _gc._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 3268
Checking 0 100 3268 nodo2.douglas.lan. against SRV _gc._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 3268
No DNS updates needed

Agora vamos mandar atualizar todos os registros

samba_dnsupdate --verbose --all-names
IPs: ['192.168.0.26']
Skipping PDC entry (SRV _ldap._tcp.pdc._msdcs.${DNSDOMAIN}                   ${HOSTNAME} 389) as we are not a PDC
Skipping PDC entry (SRV _ldap._tcp.pdc._msdcs.${DNSFOREST}                   ${HOSTNAME} 389) as we are not a PDC

Calling nsupdate for A douglas.lan 192.168.0.26
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
douglas.lan.    900 IN  A 192.168.0.26

Calling nsupdate for A nodo2.douglas.lan 192.168.0.26
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
nodo2.douglas.lan.  900 IN  A 192.168.0.26

Calling nsupdate for A gc._msdcs.douglas.lan 192.168.0.26
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
gc._msdcs.douglas.lan.  900 IN  A 192.168.0.26

Calling nsupdate for CNAME ccc206ae-bc66-4a4e-a282-06aa4613cadd._msdcs.douglas.lan nodo2.douglas.lan
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
ccc206ae-bc66-4a4e-a282-06aa4613cadd._msdcs.douglas.lan. 900 IN CNAME nodo2.douglas.lan.

Calling nsupdate for SRV _kpasswd._tcp.douglas.lan nodo2.douglas.lan 464
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kpasswd._tcp.douglas.lan. 900  IN  SRV 0 100 464 nodo2.douglas.lan.

Calling nsupdate for SRV _kpasswd._udp.douglas.lan nodo2.douglas.lan 464
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kpasswd._udp.douglas.lan. 900  IN  SRV 0 100 464 nodo2.douglas.lan.

Calling nsupdate for SRV _kerberos._tcp.douglas.lan nodo2.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._tcp.douglas.lan. 900 IN  SRV 0 100 88 nodo2.douglas.lan.

Calling nsupdate for SRV _kerberos._tcp.dc._msdcs.douglas.lan nodo2.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._tcp.dc._msdcs.douglas.lan. 900 IN SRV 0 100 88 nodo2.douglas.lan.

Calling nsupdate for SRV _kerberos._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._tcp.default-first-site-name._sites.douglas.lan. 900 IN SRV 0 100 88 nodo2.douglas.lan.

Calling nsupdate for SRV _kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo2.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan. 900 IN SRV0 100 88 nodo2.douglas.lan.

Calling nsupdate for SRV _kerberos._udp.douglas.lan nodo2.douglas.lan 88
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_kerberos._udp.douglas.lan. 900 IN  SRV 0 100 88 nodo2.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.douglas.lan nodo2.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.douglas.lan. 900 IN  SRV 0 100 389 nodo2.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.dc._msdcs.douglas.lan nodo2.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.dc._msdcs.douglas.lan. 900 IN SRV  0 100 389 nodo2.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.gc._msdcs.douglas.lan nodo2.douglas.lan 3268
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.gc._msdcs.douglas.lan. 900 IN SRV  0 100 3268 nodo2.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.default-first-site-name._sites.douglas.lan. 900 IN SRV 0 100 389 nodo2.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan nodo2.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.default-first-site-name._sites.dc._msdcs.douglas.lan. 900 IN SRV 0 100 389 nodo2.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan nodo2.douglas.lan 3268
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.default-first-site-name._sites.gc._msdcs.douglas.lan. 900 IN SRV 0 100 3268 nodo2.douglas.lan.

Calling nsupdate for SRV _ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan nodo2.douglas.lan 389
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_ldap._tcp.15cf6198-7655-4ba1-9563-2682bf9b6483.domains._msdcs.douglas.lan. 900IN SRV 0 100 389 nodo2.douglas.lan.

Calling nsupdate for SRV _gc._tcp.douglas.lan nodo2.douglas.lan 3268
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_gc._tcp.douglas.lan. 900 IN  SRV 0 100 3268 nodo2.douglas.lan.

Calling nsupdate for SRV _gc._tcp.default-first-site-name._sites.douglas.lan nodo2.douglas.lan 3268
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
_gc._tcp.default-first-site-name._sites.douglas.lan. 900 IN SRV 0 100 3268 nodo2.douglas.lan.

Agora vamos efetuar uma consulta de dns para registros de serviços

Vamos consultar o serviço do ldap

host -t SRV _ldap._tcp.douglas.lan.
_ldap._tcp.douglas.lan has SRV record 0 100 389 nodo2.douglas.lan.
_ldap._tcp.douglas.lan has SRV record 0 100 389 nodo1.douglas.lan.

Vamos consultar o serviço do kerberos

host -t SRV _kerberos._udp.douglas.lan.
_kerberos._udp.douglas.lan has SRV record 0 100 88 nodo1.douglas.lan.
_kerberos._udp.douglas.lan has SRV record 0 100 88 nodo2.douglas.lan.

Agora vamos consultar o registro do tipo A do nosso server

host -t A nodo2.douglas.lan
nodo2.douglas.lan has address 192.168.0.26

Agora vamos listar a keytab do kerberos

klist -k
Keytab name: FILE:/etc/krb5.keytab
KVNO Principal
---- --------------------------------------------------------------------------
   1 DNS/nodo2.douglas.lan@DOUGLAS.LAN
   1 dns-nodo2@DOUGLAS.LAN
   1 DNS/nodo2.douglas.lan@DOUGLAS.LAN
   1 dns-nodo2@DOUGLAS.LAN
   1 DNS/nodo2.douglas.lan@DOUGLAS.LAN
   1 dns-nodo2@DOUGLAS.LAN
   1 DNS/nodo2.douglas.lan@DOUGLAS.LAN
   1 dns-nodo2@DOUGLAS.LAN
   1 DNS/nodo2.douglas.lan@DOUGLAS.LAN
   1 dns-nodo2@DOUGLAS.LAN

Agora vamos consultar os tickets ativos

klist -e
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: administrator@DOUGLAS.LAN

Valid starting     Expires            Service principal
08/26/13 18:54:21  08/27/13 04:54:21  krbtgt/DOUGLAS.LAN@DOUGLAS.LAN
  renew until 08/27/13 18:54:17, Etype (skey, tkt): aes256-cts-hmac-sha1-96, aes256-cts-hmac-sha1-96 

Agora vamos consultar se os nossos dois servidores estão no sysvol

ldbsearch -H /usr/local/samba/private/sam.ldb '(invocationid=*)' --cross-ncs objectguid
# record 1
dn: CN=NTDS Settings,CN=NODO1,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=douglas,DC=lan
objectGUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4

# record 2
dn: CN=NTDS Settings,CN=NODO2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=douglas,DC=lan
objectGUID: ccc206ae-bc66-4a4e-a282-06aa4613cadd

# returned 2 records
# 2 entries
# 0 referrals

Agora vamos consultar a replicação

samba-tool drs showrepl
Default-First-Site-Name\NODO2
DSA Options: 0x00000001
DSA object GUID: ccc206ae-bc66-4a4e-a282-06aa4613cadd
DSA invocationId: 08233b5e-5d9f-469f-b350-641b18278b60

==== INBOUND NEIGHBORS ====

CN=Schema,CN=Configuration,DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ Mon Aug 26 19:01:06 2013 BRT was successful
    0 consecutive failure(s).
    Last success @ Mon Aug 26 19:01:06 2013 BRT

DC=DomainDnsZones,DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ Mon Aug 26 19:01:06 2013 BRT was successful
    0 consecutive failure(s).
    Last success @ Mon Aug 26 19:01:06 2013 BRT

CN=Configuration,DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ Mon Aug 26 19:01:06 2013 BRT was successful
    0 consecutive failure(s).
    Last success @ Mon Aug 26 19:01:06 2013 BRT

DC=ForestDnsZones,DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ Mon Aug 26 19:01:06 2013 BRT was successful
    0 consecutive failure(s).
    Last success @ Mon Aug 26 19:01:06 2013 BRT

DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ Mon Aug 26 19:01:07 2013 BRT was successful
    0 consecutive failure(s).
    Last success @ Mon Aug 26 19:01:07 2013 BRT

==== OUTBOUND NEIGHBORS ====

CN=Schema,CN=Configuration,DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ NTTIME(0) was successful
    0 consecutive failure(s).
    Last success @ NTTIME(0)

DC=DomainDnsZones,DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ NTTIME(0) was successful
    0 consecutive failure(s).
    Last success @ NTTIME(0)

CN=Configuration,DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ NTTIME(0) was successful
    0 consecutive failure(s).
    Last success @ NTTIME(0)

DC=ForestDnsZones,DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ NTTIME(0) was successful
    0 consecutive failure(s).
    Last success @ NTTIME(0)

DC=douglas,DC=lan
  Default-First-Site-Name\NODO1 via RPC
    DSA object GUID: eae04ba1-3ca2-4ec6-b08c-4962ca4f04b4
    Last attempt @ NTTIME(0) was successful
    0 consecutive failure(s).
    Last success @ NTTIME(0)

==== KCC CONNECTION OBJECTS ====

Connection --
  Connection name: d6fcfc72-89b0-4f4c-88c2-bf887510b6af
  Enabled        : TRUE
  Server DNS name : nodo1.douglas.lan
  Server DN name  : CN=NTDS Settings,CN=NODO1,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=douglas,DC=lan
    TransportType: RPC
    options: 0x00000001
Warning: No NC replicated for Connection!

A nossa replicação está ok

Ajustando a PAM no SLAVE

Agora vamos a configuração da PAM, com isso vamos poder autenticar os usuários do domínio no Linux eu vou deixar habilitado somente o grupo do root e o ti-admin que terá que ser criado no AD para autenticar no Linux e obter um shell.

Vamos criar um link para a biblioteca de autenticação do winbind que foi compilada para sistemas 64bits

ln -sf /usr/local/samba/lib/security/pam_winbind.so  /lib64/security/pam_winbind.so

Vamos criar um link para a biblioteca de autenticação do winbind que foi compilada para sistemas 32bits

ln -sf /usr/local/samba/lib/security/pam_winbind.so  /lib/security/pam_winbind.so

Vamos alterar o system-auth para que quando o usuário for logar no sistema seja criado o diretório home dele com o conteúdo do diretório /etc/skel

vim /etc/pam.d/system-auth
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=3 type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0027

Agora vamos ajustar o login

vim /etc/pam.d/login
#%PAM-1.0 
auth       sufficient    pam_winbind.so
auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
auth       include      system-auth
 
account    sufficient     pam_succeed_if.so user ingroup root
account    required    pam_winbind.so
account    required     pam_nologin.so
account    include      system-auth
#Grupos que vão poder efetuar login no servidor
account    requisite    pam_succeed_if.so user ingroup ti-admin
 
password   include      system-auth
# pam_selinux.so close should be the first session rule 
 
session    required     pam_selinux.so close
session    required     pam_mkhomedir.so        skel=/etc/skel umask=0027
session    include      system-auth
session    required     pam_loginuid.so
session    optional     pam_console.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context 
session    required     pam_selinux.so open
session    optional     pam_keyinit.so force revoke

Agora vamos ajustar o ssh

vim /etc/pam.d/sshd
#%PAM-1.0 
auth       sufficient    pam_winbind.so
auth       include      system-auth
 
account    sufficient   pam_succeed_if.so user ingroup root
account    required     pam_winbind.so
account    required     pam_nologin.so
account    include      system-auth
#Grupos que vão poder logar via ssh
account    requisite    pam_succeed_if.so user ingroup ti-admin
 
password   include      system-auth
 
session    required     pam_mkhomedir.so        skel=/etc/skel umask=0027
session    optional     pam_keyinit.so force revoke
session    include      system-auth
session    required     pam_loginuid.so

Como esse servidor é uma replica do pdc devemos já ter os usuários e grupos somente vamos consultar eles

Vamos consultar os usuários

wbinfo -u
Administrator
Guest
krbtgt
dns-nodo1
douglas.santos

Agora vamos consultar os grupos

wbinfo -g
Enterprise Read-Only Domain Controllers
Domain Admins
Domain Users
Domain Guests
Domain Computers
Domain Controllers
Schema Admins
Enterprise Admins
Group Policy Creator Owners
Read-Only Domain Controllers
DnsUpdateProxy
ti-admin

Agora vamos reiniciar o servidor

reboot

Agora depois que logou novamente vamos consultar a conexão do winbind

wbinfo -t
checking the trust secret for domain DOUGLAS via RPC calls succeeded

Eu já estou com o meu usuário douglas.santos e ele pertence ao grupo ti-admin agora vamos testar a conexão via ssh

ssh douglas.santos@192.168.0.26
douglas.santos@192.168.0.26's password: 
Creating directory '/home/DOUGLAS/douglas.santos'.
[19:08:04] DOUGLAS\douglas.santos@nodo2 [~] $ 

Agora se conferirmos os logs do secure vamos ter algo como

tail -f /var/log/secure
Aug 26 19:08:03 nodo2 sshd[1222]: pam_winbind(sshd:auth): getting password (0x00000000)
Aug 26 19:08:03 nodo2 sshd[1222]: pam_winbind(sshd:auth): user 'douglas.santos' granted access
Aug 26 19:08:03 nodo2 sshd[1222]: pam_succeed_if(sshd:account): requirement "user ingroup root" not met by user "DOUGLAS\douglas.santos"
Aug 26 19:08:04 nodo2 sshd[1222]: pam_winbind(sshd:account): user 'DOUGLAS\douglas.santos' granted access
Aug 26 19:08:04 nodo2 sshd[1222]: pam_succeed_if(sshd:account): requirement "user ingroup ti-admin" was met by user "DOUGLAS\douglas.santos"
Aug 26 19:08:04 nodo2 sshd[1222]: Accepted password for douglas.santos from 192.168.0.130 port 48754 ssh2
Aug 26 19:08:04 nodo2 sshd[1222]: pam_unix(sshd:session): session opened for user DOUGLAS\douglas.santos by (uid=0)

Como podemos notar a nossa autenticação está ok.

Replicação do Sysvol

Aqui eu vou abordar como é recomendado pela equipe do samba pra efetuar a replicação do sysvol que por enquanto não é automática.

No servidor Master no meu caso o nodo1 vamos instalar o rsync e o xinetd

yum install xinetd rsync -y

Agora vamos colocar o xinetd na incialização do sistema

chkconfig --add xinetd
chkconfig xinetd on

Agora vamos acertar a configuração do rsync para o xinetd

vim /etc/xinetd.d/rsync
# default: off
# description: The rsync server is a good addition to an ftp server, as it \
# allows crc checksumming etc.
service rsync
{
  disable = no
  only_from   = 192.168.0.0/24
  socket_type     = stream
  wait            = no
  user            = root
  server          = /usr/bin/rsync
  server_args     = --daemon
  log_on_failure  += USERID
}

Agora vamos criar o nosso arquivo de configuração do rsync.conf que vai conter o compartilhamento do sysvol

vim /etc/rsyncd.conf
[SysVol]
path = /usr/local/samba/var/locks/sysvol/
comment = Samba Sysvol Share
uid = root
gid = root
read only = yes
auth users = sysvol-replication
secrets file = /usr/local/samba/etc/rsyncd.secret

Note que ali vamos utilizar um usuário e uma senha agora vamos criar o arquivo contendo a senha

vim /usr/local/samba/etc/rsyncd.secret
sysvol-replication:pa$$w0rd

Agora vamos ajustar as permissões do arquivo senão o rsync não vai liberar o compartilhamento

chmod 440 /usr/local/samba/etc/rsyncd.secret

Agora vamos reiniciar o xinetd

/etc/init.d/xinetd restart

Vamos consultar o tamanho do sysvol do servidor master

du -sh /usr/local/samba/var/locks/sysvol
100K  /usr/local/samba/var/locks/sysvol

Agora vamos consultar o tamanho do sysvol do servidor slave

du -sh /usr/local/samba/var/locks/sysvol
12K /usr/local/samba/var/locks/sysvol

Note que temos uma diferença grande.

Agora vamos configurar o servidor slave

Vamos instalar o rsync

yum install rsync -y

Agora vamos criar o arquivo contendo a senha para acessar o servidor master

vim /usr/local/samba/etc/rsync-sysvol.secret
pa$$w0rd

Agora vamos acertar as permissões do arquivo de senha

chmod 440 /usr/local/samba/etc/rsync-sysvol.secret

Agora vamos fazer testar o sincronismo do sysvol

rsync --dry-run -XAavz --delete-after --password-file=/usr/local/samba/etc/rsync-sysvol.secret rsync://sysvol-replication@192.168.0.25/SysVol/ /usr/local/samba/var/locks/sysvol/
receiving file list ... done
./
douglas.lan/
douglas.lan/Policies/
douglas.lan/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/
douglas.lan/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/GPT.INI
douglas.lan/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/MACHINE/
douglas.lan/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/USER/
douglas.lan/Policies/{6AC1786C-016F-11D2-945F-00C04FB984F9}/
douglas.lan/Policies/{6AC1786C-016F-11D2-945F-00C04FB984F9}/GPT.INI
douglas.lan/Policies/{6AC1786C-016F-11D2-945F-00C04FB984F9}/MACHINE/
douglas.lan/Policies/{6AC1786C-016F-11D2-945F-00C04FB984F9}/USER/
douglas.lan/scripts/
douglas.lan/scripts/sharedemo.bat

sent 109 bytes  received 876 bytes  656.67 bytes/sec
total size is 77  speedup is 0.08 (DRY RUN)

Note que não tivemos erro nenhum com isso podemos omitir agora a opção --dry-run

Agora vamos fazer a replicação

rsync -XAavz --delete-after --password-file=/usr/local/samba/etc/rsync-sysvol.secret rsync://sysvol-replication@192.168.0.25/SysVol/ /usr/local/samba/var/locks/sysvol/
receiving file list ... done
./
douglas.lan/
douglas.lan/Policies/
douglas.lan/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/
douglas.lan/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/GPT.INI
douglas.lan/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/MACHINE/
douglas.lan/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/USER/
douglas.lan/Policies/{6AC1786C-016F-11D2-945F-00C04FB984F9}/
douglas.lan/Policies/{6AC1786C-016F-11D2-945F-00C04FB984F9}/GPT.INI
douglas.lan/Policies/{6AC1786C-016F-11D2-945F-00C04FB984F9}/MACHINE/
douglas.lan/Policies/{6AC1786C-016F-11D2-945F-00C04FB984F9}/USER/
douglas.lan/scripts/
douglas.lan/scripts/sharedemo.bat

sent 173 bytes  received 2308 bytes  4962.00 bytes/sec
total size is 77  speedup is 0.03

Agora vamos consultar o tamanho do sysvol do servidor master

du -sh /usr/local/samba/var/locks/sysvol 
100K  /usr/local/samba/var/locks/sysvol

Agora vamos consultar o tamanho do sysvol do servidor slave

du -sh /usr/local/samba/var/locks/sysvol
100K  /usr/local/samba/var/locks/sysvol

Agora vamos deixar uma rotina no crontab do servidor slave para sempre efetuar o sincronismo

crontab -e
*/5 * * * *  rsync -XAavz --delete-after --password-file=/usr/local/samba/etc/rsync-sysvol.secret rsync://sysvol-replication@192.168.0.25/SysVol/ /usr/local/samba/var/locks/sysvol

Esse sincronismo pode ser feito para todos os DCs menos para o PDC.

Configurando um Cliente CentOS para autenticar no Samba 4

Prepare os dois CentOS com o seguinte script http://wiki.douglasqsantos.com.br/doku.php/confinicialcentos6_en para que não falte nenhum pacote ou configuração.

Vamos instalar as dependências para ele poder fazer parte do domínio samba 4

yum install samba samba-winbind samba-winbind-devel samba-client samba-common \
 pam_krb5 cifs-utils samba-winbind-krb5-locator samba-doc krb5-workstation -y

Agora vamos inserir os serviços na incialização do sistema

chkconfig --add nmb
chkconfig --add smb
chkconfig --add winbind

Agora vamos ativar eles

chkconfig nmb on
chkconfig smb on
chkconfig winbind on

Agora vamos ajustar o resolv.conf do cliente

vim /etc/resolv.conf
domain douglas.lan
search douglas.lan
nameserver 192.168.0.25
nameserver 192.168.0.26

Agora vamos ajustar a interface de rede

vim /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"
BOOTPROTO="static"
BROADCAST="192.168.0.255"
DNS1="192.168.0.25"
DNS2="192.168.0.26"
GATEWAY="192.168.0.1"
IPADDR="192.168.0.27"
NETMASK="255.255.255.0"
NM_CONTROLLED="yes"
ONBOOT="yes"
TYPE="Ethernet"

Agora vamos ajustar o horário do servidor pois como vamos trabalhar com winbind e kerberos não podemos ter diferença de horario

ntpdate -u a.ntp.br

Agora vamos ajustar o kerberos

vim /etc/krb5.conf
[libdefaults]
default_realm = DOUGLAS.LAN
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
[realms]
DOUGLAS.LAN = {
kdc = 192.168.0.25
kdc = 192.168.0.26
admin_server = 192.168.0.25:749
default_server = 192.168.0.25
}
[domain_realm]
.douglas.lan=DOUGLAS.LAN
douglas.lan=DOUGLAS.LAN
[login]
krb4_convert = true
krb4_get_tickets = false
[kdc]
profile = /etc/krb5kdc/kdc.conf
[appdefaults]
pam = {
debug = false
ticket_lifetime = 36000
renew_lifetime = 36000
forwardable = true
krb4_convert = false
}
[logging]
default = file:/var/log/krb5libs.log
kdc = file:/var/log/krb5kdc.log
admin_server = file:/var/log/kadmind.log

Agora vamos acertar o limits.conf

vim /etc/security/limits.conf
[...]
#colocar no final do arquivo
root hard nofile 131072
root soft nofile 65536
mioutente hard nofile 32768
mioutente soft nofile 16384

Agora vamos ajustar o smb.conf

vim /etc/samba/smb.conf
[global]
        workgroup = DOUGLAS
        security = ADS
        realm = DOUGLAS.LAN
        netbios name = CENTOS
        encrypt passwords = yes
        idmap config * : backend = tdb
        idmap config * : range = 10000-30000
        idmap config DOUGLAS:backend = ad
        idmap config DOUGLAS:schema_mode = rfc2307
        auth methods = winbind
        winbind nss info = rfc2307
        winbind trusted domains only = no
        winbind use default domain = yes
        winbind enum users  = yes
        winbind enum groups = yes
        template shell = /bin/bash

Agora vamos ajustar o nsswitch.conf

vim /etc/nsswitch.conf
[...]
passwd:     files winbind
shadow:     files
group:        files winbind

Vamos iniciar os serviços

/etc/init.d/nmb start
/etc/init.d/smb start
/etc/init.d/winbind start

Agora vamos ajustar a PAM

Vamos ajustar para que quando o usuário faça login seja criado o seu diretório home

vim /etc/pam.d/system-auth
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=3 type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0027

Agora vamos ajustar o login utilizando o winbind aqui eu liberei somente o grupo root e o ti-admin para efetuar login em máquinas Linux

vim /etc/pam.d/login
#%PAM-1.0 
auth       sufficient    pam_winbind.so
auth [user_unknown=ignore success=ok ignore=ignore default=bad] pam_securetty.so
auth       include      system-auth
 
 
account    sufficient     pam_succeed_if.so user ingroup root
account    required    pam_winbind.so
account    required     pam_nologin.so
account    include      system-auth
#Grupos que vão poder efetuar login no servidor
account    requisite    pam_succeed_if.so user ingroup ti-admin
 
password   include      system-auth
# pam_selinux.so close should be the first session rule 
 
session    required     pam_selinux.so close
session    required     pam_mkhomedir.so        skel=/etc/skel umask=0027
session    include      system-auth
session    required     pam_loginuid.so
session    optional     pam_console.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context 
session    required     pam_selinux.so open
session    optional     pam_keyinit.so force revoke

Agora vamos ajustar o acesso via ssh utilizando o winbind aqui eu liberei somente o grupo root e o ti-admin para efetuar login em máquinas Linux

vim /etc/pam.d/sshd
#%PAM-1.0 
auth       sufficient    pam_winbind.so
auth       include      system-auth
 
account    sufficient   pam_succeed_if.so user ingroup root
account    required     pam_winbind.so
account    required     pam_nologin.so
account    include      system-auth
#Grupos que vão poder logar via ssh
account    requisite    pam_succeed_if.so user ingroup ti-admin
 
password   include      system-auth
 
session    required     pam_mkhomedir.so        skel=/etc/skel umask=0027
session    optional     pam_keyinit.so force revoke
session    include      system-auth
session    required     pam_loginuid.so

Agora vamos verificar se estamos conseguindo criar um ticker do kerberos

kinit administrator
Password for administrator@DOUGLAS.LAN: 
Warning: Your password will expire in 41 days on Mon Oct  7 12:02:11 2013

Agora vamos listar o nosso ticket

klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: administrator@DOUGLAS.LAN

Valid starting     Expires            Service principal
08/27/13 10:02:54  08/27/13 20:02:54  krbtgt/DOUGLAS.LAN@DOUGLAS.LAN
  renew until 08/28/13 10:02:51

Agora vamos fazer o join no domínio

net ads join douglas.lan -U administrator

Esse erro de DNS ainda estou tentando arrumar.

Agora vamos reiniciar os serviços

/etc/init.d/nmb restart
/etc/init.d/smb restart
/etc/init.d/winbind restart

Agora vamos testar a conexão com o winbind

wbinfo -t
checking the trust secret for domain DOUGLAS via RPC calls succeeded

Agora vamos listar os usuários do domínio

wbinfo -u
douglas.santos
administrator
dns-nodo1
krbtgt
guest

Vamos listar os grupos

wbinfo -g
allowed rodc password replication group
enterprise read-only domain controllers
denied rodc password replication group
ti-admin
read-only domain controllers
group policy creator owners
ras and ias servers
domain controllers
enterprise admins
domain computers
cert publishers
dnsupdateproxy
domain admins
domain guests
schema admins
domain users
dnsadmins

Agora vamos testar o acesso via ssh para esse cliente

ssh douglas.santos@192.168.0.27
douglas.santos@192.168.0.27's password: 
Creating directory '/home/DOUGLAS/douglas.santos'.
[10:40:01] douglas.santos@centos [~] $ 

Agora vamos ver os logs de acesso do centos

tail -f /var/log/secure
Aug 27 10:38:55 centos sshd[13906]: pam_winbind(sshd:auth): getting password (0x00000000)
Aug 27 10:38:56 centos sshd[13906]: pam_winbind(sshd:auth): user 'douglas.santos' granted access
Aug 27 10:39:32 centos sshd[13906]: pam_succeed_if(sshd:account): requirement "user ingroup root" not met by user "douglas.santos"
Aug 27 10:39:32 centos sshd[13906]: pam_winbind(sshd:account): user 'douglas.santos' granted access
Aug 27 10:39:35 centos sshd[13906]: pam_succeed_if(sshd:account): requirement "user ingroup ti-admin" was met by user "douglas.santos"
Aug 27 10:39:35 centos sshd[13906]: Accepted password for douglas.santos from 192.168.0.130 port 46470 ssh2
Aug 27 10:39:50 centos sshd[13906]: pam_unix(sshd:session): session opened for user douglas.santos by (uid=0)

O cliente está configurado com sucesso :D

Configurando um Cliente Debian Wheezy para autenticar no Samba 4

Prepare o seu sistema com o seguinte script http://wiki.douglasqsantos.com.br/doku.php/confinicialwheezy_en para que não falte nenhum pacote ou configuração.

Vamos atualizar os repositórios e fazer um upgrade do sistema

aptitude update && aptitude dist-upgrade -y

Agora vamos ajustar as variáveis de ambiente do Debian

export DEBIAN_PRIORITY=critical
export DEBIAN_FRONTEND=noninteractive

Agora vamos instalar as dependências

aptitude install samba samba-common smbclient winbind krb5-config libpam-krb5 cifs-utils  krb5-user -y

Agora vamos voltar as variáveis de ambiente do Debian

unset DEBIAN_PRIORITY
unset DEBIAN_FRONTEND

Agora vamos ajustar o resolv.conf

vim /etc/resolv.conf
domain douglas.lan
search douglas.lan
nameserver 192.168.0.25
nameserver 192.168.0.26

Agora vamos ajustar o horário do nosso servidor

ntpdate -u a.ntp.br

Agora vamos ajustar o arquivo de configuração do kerberos

vim /etc/krb5.conf
[libdefaults]
default_realm = DOUGLAS.LAN
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
[realms]
DOUGLAS.LAN = {
kdc = 192.168.0.25
kdc = 192.168.0.26
admin_server = 192.168.0.25:749
default_server = 192.168.0.25
}
[domain_realm]
.douglas.lan=DOUGLAS.LAN
douglas.lan=DOUGLAS.LAN
[login]
krb4_convert = true
krb4_get_tickets = false
[kdc]
profile = /etc/krb5kdc/kdc.conf
[appdefaults]
pam = {
debug = false
ticket_lifetime = 36000
renew_lifetime = 36000
forwardable = true
krb4_convert = false
}
[logging]
default = file:/var/log/krb5libs.log
kdc = file:/var/log/krb5kdc.log
admin_server = file:/var/log/kadmind.log

Agora vamos ajustar o limits.conf

vim /etc/security/limits.conf
[...]
#colocar no final do arquivo
root hard nofile 131072
root soft nofile 65536
mioutente hard nofile 32768
mioutente soft nofile 16384

Agora vamos ajustar o smb.conf

vim /etc/samba/smb.conf
[global]
        workgroup = DOUGLAS
        security = ADS
        realm = DOUGLAS.LAN
        netbios name = DEBIAN
        encrypt passwords = yes
        idmap config * : backend = tdb
        idmap config * : range = 10000-30000
        idmap config DOUGLAS:backend = ad
        idmap config DOUGLAS:schema_mode = rfc2307
        auth methods = winbind
        winbind nss info = rfc2307
        winbind trusted domains only = no
        winbind use default domain = yes
        winbind enum users  = yes
        winbind enum groups = yes
        template shell = /bin/bash

Agora vamos ajustar o nsswitch.conf

vim /etc/nsswitch.conf
[...]
passwd:         compat winbind
group:            compat winbind

Agora vamos reiniciar os serviços

/etc/init.d/samba restart
/etc/init.d/winbind restart

Agora vamos fazer o join no domínio

net ads join douglas.lan -U administrator

Agora vamos reiniciar os serviços

/etc/init.d/samba restart
/etc/init.d/winbind restart

Agora vamos ajustar a PAM

Vamos ajustar a autenticação

vim /etc/pam.d/common-password
password        sufficient                      pam_unix.so
password        requisite                       pam_krb5.so minimum_uid=1000
password        [success=2 default=ignore]      pam_unix.so obscure use_authtok try_first_pass sha512
password        [success=1 default=ignore]      pam_winbind.so use_authtok try_first_pass
password        requisite                       pam_deny.so
password        required                        pam_permit.so

Vamos ajustar o controle de sessão do usuário para criar o diretório home quando ele efetuar o login

vim /etc/pam.d/common-session
session [default=1]                     pam_permit.so
session requisite                       pam_deny.so
session required                        pam_permit.so
session required                        pam_unix.so 
session optional                        pam_winbind.so 
session optional                        pam_mkhomedir.so skel=/etc/skel umask=0027

Agora vamos testar a conexão com o winbind

wbinfo -t
checking the trust secret for domain DOUGLAS via RPC calls succeeded

Agora vamos listar os usuários do domínio

wbinfo -u
douglas.santos
administrator
dns-nodo1
krbtgt
guest

Vamos listar os grupos

wbinfo -g
allowed rodc password replication group
enterprise read-only domain controllers
denied rodc password replication group
ti-admin
read-only domain controllers
group policy creator owners
ras and ias servers
domain controllers
enterprise admins
domain computers
cert publishers
dnsupdateproxy
domain admins
domain guests
schema admins
domain users
dnsadmins

Agora vamos testar o acesso via ssh para esse cliente

ssh douglas.santos@192.168.0.52
douglas.santos@192.168.0.52's password: 
Creating directory '/home/DOUGLAS/douglas.santos'.
Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.46-1 x86_64

The programs included with the 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.
[10:35:45] douglas.santos@debian [~] $ 

Nos logs de autenticação vamos ter algo como abaixo

tail -f /var/log/auth.log
Aug 27 10:35:44 debian sshd[4852]: pam_krb5(sshd:auth): user douglas.santos authenticated as douglas.santos@DOUGLAS.LAN
Aug 27 10:35:44 debian sshd[4852]: Accepted password for douglas.santos from 192.168.0.130 port 51197 ssh2
Aug 27 10:35:44 debian sshd[4852]: pam_unix(sshd:session): session opened for user douglas.santos by (uid=0)

O cliente esta autenticando com sucesso :D

Referências