Autenticazione con LDAP per Samba: differenze tra le versioni
(→Autore) |
m (→Autore) |
(5 versioni intermedie di uno stesso utente non sono mostrate) | |
(Nessuna differenza)
|
Versione attuale delle 11:10, 3 ott 2008
Indice
Introduzione
Come installare e configurare samba come controllore di dominio di primo livello (PDC).
Questa guida descrive come installare e configurare Samba come PDC autenticando gli utenti con LDAP. Il sistema imposta un potente e sicuro file/print server oltre ad un robusto Directory Server.
Inoltre il server samba fa anche da logon server per i client Windows® che con l'aiuto dei “logons script” accedono automaticamente ai propri dischi condivisi in base al gruppo di appartenenza.
Prima di cominciare
Questa guida descrive il setup di un PDC con OpenLdap e Samba:
- come installare e configurare ldap (installando e configurando OpenLDAP, gli script IDEALX per samba, i file slapd.conf e /etc/ldap.conf, Pluggable Authentication Modules (PAM) e infine avvio di OpenLDAP);
- come installare e configurare samba (installazione e avvio di samba, creazione delle cartelle e dei dischi condivisi, configurazione del file smb.conf e impostazione del database delle password LDAP, inizializzazione del database e integrazione di PAM, aggiunta di utenti e workstation windows® nella Directory;
- come abilitare e testare la sicurezza del sistema (TLS per OpenLDAP, PAM e Samba).
Prerequisiti
Sono necessari una buona conoscenza dei sistemi UNIX®/LINUX® dal punto di vista della shell (riga di comando) e nozioni anche di base di networking e di programmazione in python o perl (per la creazione degli logon script, qui è stato usato python).
La distribuzione di riferimento è una Fedora Core 5, però la procedura qui descritta funziona su tutte le altre distribuzioni (es. Slackware®) e le varianti UNIX® come AIX e HP-UX.
È raccomandato procurarsi una versione precompilata dei pacchetti per la propria distribuzione (es .rpm per Red Hat® e derivati oppure .tgz per Slackware® e derivati).
I seguenti pacchetti sono necessari:
- OpenSSL;
- OpenLDAP;
- Samba;
- Modulo Perl Crypt::SmbHash;
- Module Perl Digest::SHA1;
- Modulo Perl IO::Socket::SSL;
- Modulo Perl Net::SSLeay.
Schema della rete
La semplicità della rete in esame la rende facilmente adattabile ad una piccola rete domestica. E' stato usato un router a banda larga con firewall integrato.
+------------+ | PC LINUX | | con Server | | Samba | +------+-----+ +----------+ __________ | | ROUTER | | | -----+------+------+-------+ + +---- >> --- >>| INTERNET | | | | FIREWALL | |__________| +----+----+ +----+----+ +----------+ | WINDOWS | | WINDOWS | | CLIENT | | CLIENT | +---------+ +---------+
Questa picola rete ha tre gruppi: finanze, ricerca e amministrazione.
Gli utenti dei gruppi finanze e ricerca hanno dei dischi condivisi in cui salvare i propri file; i membri dei due gruppi hanno solo accesso alle condivisioni del proprio gruppo.
Gli utenti del gruppo amministrazione hanno dei dischi accessibili solo dgli amministratori, hanno però dei privileggi che consentono loro di accedere alle condivisioni sia di finanze sia di ricerca.
Introduzione a LDAP
LDAP : Lightweight Directory Access Protocol, è un protollo per far comunicare più computer con un Directory Server (rfc 1777 e 2251); è stato progettato per permettere un accesso leggero ad alberi derivati da Directory X.500 OSI Directory Access Protocol (DAP).
I dati sono organizzati in una struttura gerarchica (con supporto nativo della replicazione) e non di tabelle come nei DBMS relazionali, quali oracle oppure postgresql.
Una Directory è una collezione gerarchica di oggetti e di attributi associati agli ogetti stessi.
Esempio di Directory:
_ (_) dc=vicenza, dc=linux, dc=it | | +---------+---------+ | | | | | | _ _ _ (_) (_) (_) ou=soci, dc=vicenza, dc=linux, dc=it | | +---------+---------+ | | | | | | _ _ _ (_) (_) (_) cn=ottavio, ou=soci, dc=vicenza, dc=linux, dc=it
Integrazione LDAP - SAMBA
Esistono tre principali punti d'integrazione di Samba in un server LDAP:
- il primo è l'inclusione dello schema samba nel server LDAP;
- il secondo è la configurazione di samba per autenticare via il server LDAP, grazie all'utility PAM che crea uno strato di astrazione nel processo di autenticazione, nascondendone la complessità (decidendo ad esempio se usare un file, LDAP, oppure un altro meccanismo di autenticazione);
- il terzo consiste nel usare un insieme di strumenti: i così detti “ IDEALX LDAP toolkit per Samba”, noti anche come gli "smbldap-tools", prodotti da terzi, ma rilasciati sotto licenza GPL.
Configurazione di LDAP
Installazione di OpenLDAP
Per installare OpenLDAP verificare che nella propria distribuzione non sia già installato, con i seguenti comandi (per fedora):
rpm -qa | grep ldap
se non si ottiene un risultato simile a openladp-2.3.24 o superiore sarà necessario scaricarlo su uno dei mirror e installarlo con il comando:
rpm -ivh openladp-2.3.24-2.i386.rpm
oppure usando YUM (il sistema di aggiornamento online di fedora, qui non ne parleremo).
Questo è un esempio di output che ottengo sulla mia Slackware:
root@chrix:~# ls /var/log/packages/ | grep -i ldap nss_ldap-244-i486-1wsa openldap-2.3.24-i486-2kjz
in caso contrario è possibile scaricare il pacchetto precompilato su uno dei repository di Slackware oppure installarlo direttamente con swaret o altri strumenti di aggiornamento online.
Installazione degli smbldap-tools
Essi sono richiesti per automatizzare la maggior parte delle interazioni tra samba e il server LDAP, contengono ad esempio script che samba richiama automaticamente per aggiungere/rimuovere utenti e/o gruppi, agiungere computer... Sono scritti in perl e quindi eseguibili da shell. Di solito sono già inclusi in vari distribuzioni col pacchetto samba, questo è l'output che ottengo sulla mia Slackware:
root@chrix:~# cd /usr/share/doc/samba-3.0.21c/examples/LDAP/smbldap-tools-0.9.1 root@chrix:~# ls CONTRIBUTORS INSTALL doc/ smbldap-groupshow smbldap-userdel smbldap_bind.conf COPYING Makefile smb.conf smbldap-passwd smbldap-userinfo smbldap_tools.pm ChangeLog README smbldap-groupadd smbldap-populate smbldap-usermod FILES TODO smbldap-groupdel smbldap-tools.spec smbldap-usershow INFRA configure.pl smbldap-groupmod smbldap-useradd smbldap.conf
per installare gli IDEALX scripts:
- andare sul sito e scaricare la versione 0.9.1 o superiore (smbldaptool-0.9.1.tar.gz);
- scompattare l'archivio in una cartella temporanea col comando:
tar -xvzf smbldap-tool-0.9.1.tar.gz
- creare una cartella per gli script quindi impostare i permessi giusti:
mkdir -p /var/lib/samba/sbin chmod -R 755 /var/lib/samba/
- entrare nella cartella scompattata e copiare gli script nella cartella precedentemente creata, all'invito di comandi scrivere:
cd smbldap-tool-0.9.1 cp smbldap* configure.pl /var/lib/samba/sbin
- impostare i permessi corretti nella cartella /var/lib/samba/sbin, impartendo i seguenti comandi:
chmod 755 * chmod 640 smbldap_bind.conf smbldap.conf smbldap_tools.pm
- infine rimuovere la cartella temporanea in cui è stato scompattato l'archivio.
Il toolkit IDEALX richiede moduli perl aggiuntivi che di default non sono sempre installati nel sistema.
- Andare sul sito e scaricare i seguenti moduli perl (è disponibile un motore di ricerca interno):
- Crypt::SmbHash;
- Digest::SHA1;
- IO::Socket::SSL;
- Net::SSLeay.
- Scompattare tutti gli archivi appena scaricati usando questo comando:
for archivio in *; do tar -xvzf $archivio; done
- Compilare ed installare ( da root) ognuno dei quattro moduli, entrando ogni volta nella rispettiva cartella con i comandi:
perl Makefile.PL make test make install
Configurazione degli schema, delle chiavi ssl e delle cartelle usate da OpenLDAP
Chi usa un pacchetto precompilato ( rpm o tgz ) avrà la cartella /etc/openldap contenente il file di configurazione slapd.conf, prima di editare quel file è necessario copiare il file samba.schema nella cartella /etc/openldap/schema se non già presente! E impostare i permessi corretti:
chmod 644 /etc/openldap/schema/samba.schema
Potete usare locate oppure find per trovarlo, sulla mia Slackaware usando locate:
root@chrix:~# cd /etc/openldap root@chrix:~# locate samba.schema /etc/samba/samba.schema.oc.IBM-ds /etc/samba/samba.schema.at.IBM-ds /etc/samba/samba.schema /etc/openldap/schema/samba.schema /usr/doc/samba-3.0.21c/examples/LDAP/samba.schema.oc.IBM-ds /usr/doc/samba-3.0.21c/examples/LDAP/samba.schema.at.IBM-ds /usr/doc/samba-3.0.21c/examples/LDAP/samba.schema
Ora creare una cartella per il database di LDAP
mkdir -p /var/lib/ldap/miodominio.com chmod 700 /var/lib/ldap/miodominio.com chown ldap:ldap /var/lib/ldap/miodominio.com
In Fedora l'utente ldap viene creato all'installazione di OpenLDAP, in altre distribuzioni bisogna spesso crearlo a mano!
Infine creare le chiavi che OpenLDAP usa per la criptazione dei dati, per fare ciò è necessario il pacchetto OpenSSL già incluso nella maggior parte delle distribuzioni; altrimenti potete scaricarlo dal sito.
Questo howto descrive come autofirmare i propri cerficati (cioè essere una Certificate Authority: CA).
- Con il comando locate openssl.cnf individuare il file openssl.cnf ed editarlo a secondo la vostra configurazione, ad esempio cambiare il paese in IT, il nome dell'orgarnizazione in miodominio.com ( di default si trova in /etc/ssl/openssl.cnf );
- Nella stessa cartella di openssl.cnf digittare i seguenti comandi:
mkdir -p CA/certs CA/crl CA/newcerts CA/private chmod 700 CA/private touch CA/index.txt echo 01 > CA/serial
- Creare il certificato della CA e la chiave con il comando:
openssl req -nodes -config openssl.cnf -new -x509 -keyout CA/private/cakey.pem -out CA/cacert.pem -days 3650
- Creare la chiave per OpenLDAP con questi comandi:
openssl req -config openssl.cnf -nodes -new -keyout /etc/openldap/slapd-key.pem -out slapd.csr openssl ca -config openssl.cnf -out /etc/openldap/slapd-cert.pem -in slapd.csr
- Impostare i permessi corretti:
chown root:ldap /etc/openldap/slapd-key.pem chmod 640 /etc/openldap/slapd-key.pem chmod 644 /etc/openldap/slapd-cert.pem
- Copiare il certificato CA nella cartella di configurazione in modo vari apllicazioni possano accedervi:
cp CA/cacert.pem /etc/openldap chmod 644 /etc/openldap/cacert.pem
- Configurare il file slapd.conf. Il demone di OpenLDAP si chiama slapd, e legge le configurazioni dal file slapd.conf, prima di editare quel file bisogna generare l'impronta della password per l'admin rootdn (root distinguished name), per fare ciò usare l'utility slappasswd come segue:
slappasswd -h {SSHA} -s password_desiderata
Salvare l'output di quel comando in un file ad esempio utilizzando le redirezioni “>”, perché verrà usato in seguito.
Con la mia Slackware ottengo:
root@chrix:/etc/openldap# slappasswd -h {SSHA} -s slacky123 {SSHA}edkSLDngACZohmpeSlzsz7/P8u3Hr4jD root@chrix:/etc/openldap#
esempio di file /etc/openldap/slapd.conf da modificare in funzione della propria configurazione:
# # See slapd.conf(5) for details on configuration options. # This file should NOT be world readable. #include /etc/openldap/schema/core.schema include /etc/openldap/schema/samba.schema # Define global ACLs to disable default read access. # Do not enable referrals until AFTER you have a working directory # service AND an understanding of referrals. #referral ldap://root.openldap.org pidfile /var/run/slapd.pid argsfile /var/run/slapd.args # Load dynamic backend modules: # modulepath /usr/libexec/openldap # moduleload back_bdb.la # moduleload back_ldap.la # moduleload back_ldbm.la # moduleload back_passwd.la # moduleload back_shell.la # Sample security restrictions # Require integrity protection (prevent hijacking) # Require 112-bit (3DES or better) encryption for updates # Require 63-bit encryption for simple bind # security ssf=1 update_ssf=112 simple_bind=64 # Sample access control policy: # Root DSE: allow anyone to read it # Subschema (sub)entry DSE: allow anyone to read it # Other DSEs: # Allow self write access # Allow authenticated users read access # Allow anonymous users to authenticate # Directives needed to implement policy: # access to dn.base="" by * read # access to dn.base="cn=Subschema" by * read # access to * # by self write # by users read # by anonymous auth # # if no access controls are present, the default policy # allows anyone and everyone to read anything but restricts # updates to rootdn. (e.g., "access to * by * read") # # rootdn can always read and write EVERYTHING! ####################################################################### # BDB database definitions ####################################################################### database bdb suffix "dc=chrix,dc=lan" rootdn "cn=Manager,dc=chrix,dc=lan" # Cleartext passwords, especially for the rootdn, should # be avoid. See slappasswd(8) and slapd.conf(5) for details. # Use of strong authentication encouraged. # qui la password con slappasswd rootpw {SSHA}edkSLDngACZohmpeSlzsz7/P8u3Hr4jD # The database directory MUST exist prior to running slapd AND # should only be accessible by the slapd and slap tools. # Mode 700 recommended. directory /var/openldap-data # Indices to maintain index objectClass eq
Configurare /etc/ldap.conf
il file /etc/ldap.conf è usato dai client LDAP sul computer locale quali PAM che è l'interfaccia usata da samba per l'autenticazione via il server LDAP, il file ldap.conf da usare è quello impostato per funzionare con PAM, per sapere quale configurazione usare impartire i seguenti comandi:
strings /lib/libnss_ldap.so.2 | grep conf
il valore ritornato dovrebbe essere:
/etc/ldap.conf
Esempio di file /etc/ldap.conf da modificare in funzione della propria configurazione:
#$Id: ldap.conf,v 2.43 2005/05/25 00:05:08 lukeh Exp $ # # This is the configuration file for the LDAP nameservice # switch library and the LDAP PAM module. # # PADL Software # http://www.padl.com # # Your LDAP server. Must be resolvable without using LDAP. # Multiple hosts may be specified, each separated by a # space. How long nss_ldap takes to failover depends on # whether your LDAP client library supports configurable # network or connect timeouts (see bind_timelimit). host 127.0.0.1 # The distinguished name of the search base. base dc=chrix,dc=lan # Another way to specify your LDAP server is to provide an # uri with the server name. This allows to use # Unix Domain Sockets to connect to a local LDAP Server. #uri ldap://127.0.0.1/ uri ldaps://127.0.0.1/ #uri ldapi://%2fvar%2frun%2fldapi_sock/ # Note: %2f encodes the '/' used as directory separator # The LDAP version to use (defaults to 3 # if supported by client library) #ldap_version 3 # The distinguished name to bind to the server with. # Optional: default is to bind anonymously. binddn cn=Manager,dc=chrix,dc=lan # The credentials to bind with. # Optional: default is no credential. bindpw {SSHA}gk/Q2Imacloss8Kobm6MvQF3MrHVZNnJ # The distinguished name to bind to the server with # if the effective user ID is root. Password is # stored in /etc/ldap.secret (mode 600) rootbinddn cn=manager,dc=chrix,dc=lan # The port. # Optional: default is 389. port 389 # The search scope. #scope sub #scope one #scope base # Search timelimit #timelimit 30 # Bind/connect timelimit #bind_timelimit 30 # Reconnect policy: # hard_open: reconnect to DSA with exponential backoff if # opening connection failed # hard_init: reconnect to DSA with exponential backoff if # initializing connection failed # hard: alias for hard_open # soft: return immediately on server failure #bind_policy hard # Idle timelimit; client will close connections # (nss_ldap only) if the server has not been contacted # for the number of seconds specified below. #idle_timelimit 3600 # Pagesize: when configured with --enable-paged-results allow # to set the pagesize to a custom value #pagesize 1000 # Filter to AND with uid=%s pam_filter objectclass=account # The user ID attribute (defaults to uid) pam_login_attribute uid # Search the root DSE for the password policy (works # with Netscape Directory Server) #pam_lookup_policy yes # Check the 'host' attribute for access control # Default is no; if set to yes, and user has no # value for the host attribute, and pam_ldap is # configured for account management (authorization) # then the user will not be allowed to login. #pam_check_host_attr yes # Check the 'authorizedService' attribute for access # control # Default is no; if set to yes, and the user has no # value for the authorizedService attribute, and # pam_ldap is configured for account management # (authorization) then the user will not be allowed # to login. #pam_check_service_attr yes # Group to enforce membership of #pam_groupdn cn=PAM,ou=Groups,dc=padl,dc=com # Group member attribute #pam_member_attribute uniquemember # Specify a minium or maximum UID number allowed #pam_min_uid 0 #pam_max_uid 0 # Template login attribute, default template user # (can be overriden by value of former attribute # in user's entry) #pam_login_attribute userPrincipalName #pam_template_login_attribute uid #pam_template_login nobody # HEADS UP: the pam_crypt, pam_nds_passwd, # and pam_ad_passwd options are no # longer supported. # # If you are using XAD, you can set pam_password # to racf, ad, or exop. Make sure that you have # SSL enabled. # Do not hash the password at all; presume # the directory server will do it, if # necessary. This is the default. #pam_password clear # Hash password locally; required for University of # Michigan LDAP server, and works with Netscape # Directory Server if you're using the UNIX-Crypt # hash mechanism and not using the NT Synchronization # service. pam_password crypt # Remove old password first, then update in # cleartext. Necessary for use with Novell # Directory Services (NDS) #pam_password nds # RACF is an alias for the above. For use with # IBM RACF #pam_password racf # Update Active Directory password, by # creating Unicode password and updating # unicodePwd attribute. pam_password ad # Use the OpenLDAP password change # extended operation to update the password. #pam_password exop # Redirect users to a URL or somesuch on password # changes. #pam_password_prohibit_message Please visit http://internal to change your password. # RFC2307bis naming contexts # Syntax: # nss_base_XXX base?scope?filter # where scope is {base,one,sub} # and filter is a filter to be &'d with the # default filter. # You can omit the suffix eg: # nss_base_passwd ou=People, # to append the default base DN but this # may incur a small performance impact. nss_base_passwd ou=Users,dc=chrix,dc=lan?one nss_base_passwd ou=Computers,dc=chrix,dc=lan?one nss_base_shadow ou=Users,dc=chrix,dc=lan?one nss_base_group ou=Groups,dc=chrix,dc=lan?one #nss_base_hosts ou=Hosts,dc=padl,dc=com?one #nss_base_services ou=Services,dc=padl,dc=com?one #nss_base_networks ou=Networks,dc=padl,dc=com?one #nss_base_protocols ou=Protocols,dc=padl,dc=com?one #nss_base_rpc ou=Rpc,dc=padl,dc=com?one #nss_base_ethers ou=Ethers,dc=padl,dc=com?one #nss_base_netmasks ou=Networks,dc=padl,dc=com?ne #nss_base_bootparams ou=Ethers,dc=padl,dc=com?one #nss_base_aliases ou=Aliases,dc=padl,dc=com?one #nss_base_netgroup ou=Netgroup,dc=padl,dc=com?one # attribute/objectclass mapping # Syntax: #nss_map_attribute rfc2307attribute mapped_attribute #nss_map_objectclass rfc2307objectclassmapped_objectclass # configure --enable-nds is no longer supported. # NDS mappings #nss_map_attribute uniqueMember member # Services for UNIX 3.5 mappings #nss_map_objectclass posixAccount User #nss_map_objectclass shadowAccount User #nss_map_attribute uid msSFU30Name #nss_map_attribute uniqueMember msSFU30PosixMember #nss_map_attribute userPassword msSFU30Password #nss_map_attribute homeDirectory msSFU30HomeDirectory #nss_map_attribute homeDirectory msSFUHomeDirectory #nss_map_objectclass posixGroup Group #pam_login_attribute msSFU30Name #pam_filter objectclass=User #pam_password ad # configure --enable-mssfu-schema is no longer supported. # Services for UNIX 2.0 mappings #nss_map_objectclass posixAccount User #nss_map_objectclass shadowAccount user #nss_map_attribute uid msSFUName #nss_map_attribute uniqueMember posixMember #nss_map_attribute userPassword msSFUPassword #nss_map_attribute homeDirectory msSFUHomeDirectory #nss_map_attribute shadowLastChange pwdLastSet #nss_map_objectclass posixGroup Group #nss_map_attribute cn msSFUName #pam_login_attribute msSFUName #pam_filter objectclass=User #pam_password ad # RFC 2307 (AD) mappings #nss_map_objectclass posixAccount user #nss_map_objectclass shadowAccount user #nss_map_attribute uid sAMAccountName #nss_map_attribute homeDirectory unixHomeDirectory #nss_map_attribute shadowLastChange pwdLastSet #nss_map_objectclass posixGroup group #nss_map_attribute uniqueMember member #pam_login_attribute sAMAccountName #pam_filter objectclass=User #pam_password ad # configure --enable-authpassword is no longer supported # AuthPassword mappings #nss_map_attribute userPassword authPassword # AIX SecureWay mappings #nss_map_objectclass posixAccount aixAccount #nss_base_passwd ou=aixaccount,?one #nss_map_attribute uid userName #nss_map_attribute gidNumber gid #nss_map_attribute uidNumber uid #nss_map_attribute userPassword passwordChar #nss_map_objectclass posixGroup aixAccessGroup #nss_base_group ou=aixgroup,?one #nss_map_attribute cn groupName #nss_map_attribute uniqueMember member #pam_login_attribute userName #pam_filter objectclass=aixAccount pam_password md5 # For pre-RFC2307bis automount schema #nss_map_objectclass automountMap nisMap #nss_map_attribute automountMapName nisMapName #nss_map_objectclass automount nisObject #nss_map_attribute automountKey cn #nss_map_attribute automountInformation nisMapEntry # Netscape SDK LDAPS #ssl on # Netscape SDK SSL options #sslpath /etc/ssl/certs/cert7.db # OpenLDAP SSL mechanism # start_tls mechanism uses the normal LDAP port, LDAPS typically 636 #ssl start_tls ssl off # OpenLDAP SSL options # Require and verify server certificate (yes/no) # Default is to use libldap's default behavior, which can be configured in # /etc/openldap/ldap.conf using the TLS_REQCERT setting. The default for # OpenLDAP 2.0 and earlier is "no", for 2.1 and later is "yes". #tls_checkpeer yes # CA certificates for server certificate verification # At least one of these are required if tls_checkpeer is "yes" #tls_cacertfile /etc/ssl/ca.cert #tls_cacertdir /etc/ssl/certs # Seed the PRNG if /dev/urandom is not provided #tls_randfile /var/run/egd-pool # SSL cipher suite # See man ciphers for syntax #tls_ciphers TLSv1 # Client certificate and key # Use these, if your server requires client authentication. #tls_cert #tls_key # Disable SASL security layers. This is needed for AD. #sasl_secprops maxssf=0 # Override the default Kerberos ticket cache location. #krb5_ccname FILE:/etc/.ldapcache
Configurare PAM
La Fedora core include un tool a riga di comando per la configurazione di PAM chiamato authconfig, gli utenti di altre distribuzioni possono usare il tool webmin, esiste un modulo perl per la configurazione di PAM. oppure quelli più esperti possono editare a mano il file di configurazione. Da shell digitare (per fedora core):
authconfig
e selezionare Use LDAP, Use MD5 Passwords, Use shadow Passwords e Use LDAP Authentication nelle impostazioni di LDAP, abilitare TLS, alla voce Server mettere l'indirizzo 127.0.0.1, e infine nella voce Base DN mettere i valori relativi alla vostra configurazione ad esempio: dc=miodominio,dc=com (sostituite “miodominio” e “com” con i valori che desiderate!)
Per Slackware:
spostarsi nella cartella /etc/pam.d
creare il file common-auth se già non esiste, e aggiungerci le seguenti righe:
#Autencicazione pam per ldap auth required pam_env.so auth sufficient pam_unix.so likeauth nullok shadow auth sufficient pam_ldap.so use_first_pass auth required pam_deny.so #Account account requisite pam_unix.so account sufficient pam_localuser.so account required pam_ldap.so #Password password required pam_cracklib.so retry=3 password sufficient pam_unix.so nullok use_authtok shadow md5 password sufficient pam_ldap.so use_authtok use_first_pass password required pam_deny.so #Session session required pam_limits.so session required pam_unix.so session required pam_mkhomedir.so skel=/etc/skel/ umask=0066 session optional pam_ldap.so
ora configuare /etc/nsswitch.conf, perché possa usare ldap per autenticare gli utenti
passwd: files ldap group: files ldap shadow: files ldap
Avviare OpenLDAP
su Fedora:
/etc/init.d/ldap start
su Slackware:
/etc/rc.d/rc.ldap start
Configurazione di Samba
Se non è già presente nel sistema, è possibile scaricarlo dal sito oppure prelevare la versione precompilata per la propria distribuzione nei repository.
Esempio di file /etc/samba/smb.conf completo da modificare a seconda della vostra configurazione (ad esempio cambiare il percorso da /opt/IDEALX a /var/lib/samba/... )
# Global parameters [global] workgroup = TUX-NET netbios name = PDC-SRV security = user enable privileges = yes server string = Samba Server %v encrypt passwords = Yes min passwd length = 3 unix password sync = Yes passwd program = /var/lib/samba/sbin/smbldap-passwd -u %u passwd chat = "Changing password for*\nNew password*" %n\n "*Retype new password*" %n\n" log level = 0 syslog = 0 log file = /var/log/samba/log.%m max log size = 100000 time server = Yes socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192 mangling method = hash2 Dos charset = 850 Unix charset = ISO8859-1 logon drive = H: logon home = logon path = domain logons = Yes domain master = Yes os level = 65 preferred master = Yes wins support = yes passdb backend = ldapsam:ldap://127.0.0.1/ ldap admin dn = cn=Manager,dc=chrix,dc=lan ldap suffix = dc=chrix,dc=lan ldap group suffix = ou=Groups ldap user suffix = ou=Users ldap machine suffix = ou=Computers add user script = /var/lib/samba/sbin/smbldap-useradd -m "%u" delete user script = /var/lib/samba/sbin/smbldap-userdel "%u" add machine script = /var/lib/samba/sbin/smbldap-useradd -t 0 -w "%u" add group script = /var/lib/samba/sbin/smbldap-groupadd -p "%g" delete group script = /var/lib/samba/sbin/smbldap-groupdel "%g" add user to group script = /var/lib/samba/sbin/smbldap-groupmod -m "%u" "%g" delete user from group script = /var/lib/samba/sbin/smbldap-groupmod -x "%u" "%g" set primary group script = /var/lib/samba/sbin/smbldap-usermod -g '%g' '%u' # printers configuration printer admin = @"Print Operators" load printers = Yes create mask = 0640 directory mask = 0750 nt acl support = No printing = cups printcap name = cups deadtime = 10 guest account = nobody map to guest = Bad User dont descend = /proc,/dev,/etc,/lib,/lost+found,/initrd show add printer wizard = yes ; to maintain capital letters in shortcuts in any of the profile folders: preserve case = yes short preserve case = yes case sensitive = no [netlogon] path = /home/netlogon/ browseable = No read only = yes #lo script logon.py permette di montare automaticamente i dischi all'accesso verrà discusso più avanti root preexec = /home/netlogon/logon.py %U %I [finanze] path = /home/finanze read only = no create mask = 0770 directory mask = 0770 browsable = no [ricerca] path = /home/ricerca read only = no create mask = 0770 directory mask = 0770 browsable = no [amministrazione] path = /home/amministrazione force group = amministrazione read only = no create mask = 0770 directory mask = 0770 browsable = no [profiles] path = /home/profiles read only = no create mask = 0600 directory mask = 0700 browseable = No guest ok = Yes profile acls = yes csc policy = disable # next line is a great way to secure the profiles #force user = %U # next line allows administrator to access all profiles #valid users = %U "Domain Admins" [printers] comment = Network Printers printer admin = @"Print Operators" guest ok = yes printable = yes path = /home/spool/ browseable = No read only = Yes printable = Yes print command = /usr/bin/lpr -P%p -r %s lpq command = /usr/bin/lpq -P%p lprm command = /usr/bin/lprm -P%p %j [print$] path = /home/printers guest ok = No browseable = Yes read only = Yes valid users = @"Print Operators" write list = @"Print Operators" create mask = 0664 directory mask = 0775
Impostare la password per l'accesso al database LDAP
smbpasswd -w la_vostra_password
Dovreste avere una risposta simile a questa:
setting stored password for “cn=Manager,dc=chrix,dc=lan” in secrets.tdb
Esempio di script scritto in python per montare automaticamente le home degli utenti/gruppi dopo all'accesso al dominio, da modificare a seconda della vostra configurazione!
#!/usr/bin/env python """ ntlogon.py written by Timothy (rhacer) Grant Copyright 1999 - 2002 by Timothy Grant is distributed under the terms of the GNU Public License. The format for the configuration file is as follows: While there is some room for confusion, we attempt to process things in order of specificity: Global first, Group second, User third, OS Type forth. This order can be debated forever, but it seems to make the most sense. # Everything in the Global section applies to all users logging on to the # network [Global] @ECHO "Welcome to our network!!!" NET TIME \\\\servername /SET /YES NET USE F: \\\\servername\\globalshare /YES # Map the private user area in the global section so we don't have to # create individual user entries for each user! NET USE U: \\\\servername\\%U /YES # Group entries, User entries and OS entries each start with the # keyword followed by a dash followed by--appropriately enough the Group # name, the User name, or the OS name. [Group-admin] @ECHO "Welcome administrators!" NET USE G: \\\\servername\\adminshare1 /YES NET USE I: \\\\servername\\adminshare2 /YES [Group-peons] @ECHO "Be grateful we let you use computers!" NET USE G: \\\\servername\\peonshare1 /YES [Group-hackers] @ECHO "What can I do for you today great one?" NET USE G: \\\\servername\\hackershare1 /YES NET USE I: \\\\servername\\adminshare2 /YES [User-fred] @ECHO "Hello there Fred!" NET USE F: \\\\servername\\fredsspecialshare /YES [OS-WfWg] @ECHO "Time to upgrade it?" # End configuration file usage: ntlogon [-g | --group=groupname] [-u | --user=username] [-o | --os=osname] [-m | --machine=netbiosname] [-f | --templatefile=filename] [-d | --dir=netlogon directory] [-v | --version] [-h | --help] [--pause] [--debug] """ # #" This quote mark is an artifact of the inability of my editor to # correctly colour code anything after the triple-quoted docstring. # if your editor does not have this flaw, feel free to remove it. import sys import getopt import re import string import os version = "ntlogon.py v0.8" def buildScript(buf, sections, group, user, ostype, machine, debug, pause): """ buildScript() Takes the contents of the template file and builds a DOS batch file to be executed as an NT logon script. It does this by determining which sections of the configuration file should be included and creating a list object that contains each line contained in each included section. The list object is then returned to the calling routine. All comments (#) are removed. A REM is inserted to show which section of the configuration file each line comes from. We leave blanklines as they are sometimes useful for debugging We also replace all of the Samba macros (e.g., %U, %G, %a, %m) with their expanded versions which have been passed to us by smbd """ hdrstring = script = [] # # These are the Samba macros that we currently know about. # any user defined macros will also be added to this dictionary. # We do not store the % sign as part of the macro name. # The replace routine will prepend the % sign to all possible # replacements. # macros = { 'U': user, 'G': group, 'a': ostype, 'm': machine } # # Process each section defined in the list sections # for s in sections: # print 'searching for: ' + s idx = 0 while idx < len(buf): ln = buf[idx] # # We need to set up a regex for each possible section we # know about. This is slightly complicated due to the fact # that section headers contain user defined text. # if s == 'Global': hdrstring = '\[ *' + s + ' *\]' elif s == 'Group': hdrstring = '\[ *' + s + ' *- *' + group + ' *\]' elif s == 'User': hdrstring = '\[ *' + s + ' *- *' + user + ' *\]' elif s == 'OS': hdrstring = '\[ *' + s + ' *- *' + ostype + ' *\]' elif s == 'Machine': hdrstring = '\[ *' + s + ' *- *' + machine + ' *\]' # # See if we have found a section header # if re.search(r'(?i)' + hdrstring, ln): idx = idx + 1 # increment the counter to move to the next line. x = re.match(r'([^#\r\n]*)', ln) # Determine the section # name and strip out CR/LF # and comment information if debug: print 'rem ' + x.group(1) + ' commands' else: # create the rem at the beginning of each section of the # logon script. script.append('rem ' + x.group(1) + ' commands') # # process each line until we have found another section # header # while not re.search(r'.*\[.*\].*', buf[idx]): # # strip comments and line endings # x = re.match(r'([^#\r\n]*)', buf[idx]) if string.strip(x.group(1)) != : # if there is still content after stripping comments and # line endings then this is a line to process line = x.group(1) # # Check to see if this is a macro definition line # vardef = re.match(r'(.*)=(.*)', line) if vardef: varname = string.strip(vardef.group(1)) # Strip leading and varsub = string.strip(vardef.group(2)) # and trailing spaces if varname == : print "Error: No substition name specified line: %d" % idx sys.exit(1) if varsub == : print "Error: No substitution text provided line: %d" % idx sys.exit(1) if macros.has_key(varname): print "Warning: macro %s redefined line: %d" % (varname, idx) macros[varname] = varsub idx = idx + 1 continue # # Replace all the macros that we currently # know about. # # Iterate over the dictionary that contains all known # macro substitutions. # # We test for a macro name by prepending % to each dictionary # key. # for varname in macros.keys(): line = re.sub(r'%' + varname + r'(\W)', macros[varname] + r'\1', line) if debug: print line if pause: print 'pause' else: script.append(line) idx = idx + 1 if idx == len(buf): break # if we have reached the end of the file # stop processing. idx = idx + 1 # increment the line counter if debug: print else: script.append() return script
# End buildScript() def run(): """ run() everything starts here. The main routine reads the command line arguments, opens and reads the configuration file. """ configfile = '/etc/ntlogon.conf' # Default configuration file group = # Default group user = # Default user ostype = # Default os machine = # Default machine type outfile = 'logon.bat' # Default batch file name # this file name WILL take on the form # username.bat if a username is specified debug = 0 # Default debugging mode pause = 0 # Default pause mode outdir = '/usr/local/samba/netlogon/' # Default netlogon directory sections = ['Global', 'Machine', 'OS', 'Group', 'User'] # Currently supported # configuration file # sections options, args = getopt.getopt(sys.argv[1:], 'd:f:g:ho:u:m:v', ['templatefile=', 'group=', 'help', 'os=', 'user=', 'machine=', 'dir=', 'version', 'pause', 'debug']) # # Process the command line arguments # for i in options: # template file to process if (i[0] == '-f') or (i[0] == '--templatefile'): configfile = i[1] # print 'configfile = ' + configfile # define the group to be used elif (i[0] == '-g') or (i[0] == '--group'): group = i[1] # print 'group = ' + group # define the os type elif (i[0] == '-o') or (i[0] == '--os'): ostype = i[1] # print 'os = ' + os # define the user elif (i[0] == '-u') or (i[0] == '--user'): user = i[1] outfile = user + '.bat' # Setup the output file name # print 'user = ' + user # define the machine elif (i[0] == '-m') or (i[0] == '--machine'): machine = i[1] # define the netlogon directory elif (i[0] == '-d') or (i[0] == '--dir'): outdir = i[1] # print 'outdir = ' + outdir # if we are asked to turn on debug info, do so. elif (i[0] == '--debug'): debug = 1 # print 'debug = ' + debug # if we are asked to turn on the automatic pause functionality, do so elif (i[0] == '--pause'): pause = 1 # print 'pause = ' + pause # if we are asked for the version number, print it. elif (i[0] == '-v') or (i[0] == '--version'): print version sys.exit(0) # if we are asked for help print the docstring. elif (i[0] == '-h') or (i[0] == '--help'): print __doc__ sys.exit(0) # # open the configuration file # try: iFile = open(configfile, 'r') except IOError: print 'Unable to open configuration file: ' + configfile sys.exit(1) # # open the output file # if not debug: try: oFile = open(outdir + outfile, 'w') except IOError: print 'Unable to open logon script file: ' + outdir + outfile sys.exit(1) buf = iFile.readlines() # read in the entire configuration file # # call the script building routine # script = buildScript(buf, sections, group, user, ostype, machine, debug, pause) # # write out the script file # if not debug: for ln in script: oFile.write(ln + '\r\n') if pause: if string.strip(ln) != : # Because whitespace oFile.write('pause' + '\r\n') # is a useful tool, we # don't put pauses after # an empty line. # End run() # # immediate-mode commands, for drag-and-drop or execfile() execution if __name__ == '__main__': run() else: print "Module ntlogon.py imported." print "To run, type: ntlogon.run()" print "To reload after changes to the source, type: reload(ntlogon)" # # End NTLogon.py #
Avviare Samba
su Fedora:
/etc/init.d/samba start
su Slackware:
/etc/rc.d/rc.samba start
Inizializzazione del database di LDAP
Eseguire lo script configure.PL in /var/lib/samba/sbin ( o comunque dove avete scelto di salvarlo) poi popolare il database di ldap eseguendo lo script smbldap-populate per creare l'amminstratore del dominio, alcuni gruppi e vari altri elementi.
Creare i dischi condivisi e gli utenti per l'amministrazione di quelle condivisioni:
cd /var/lib/samba/sbin ./smbldap-groupadd ricerca ./smbldap-groupadd finanze ./smbldap-groupadd amministrazione ./smbldap-useradd -s /sbin/nologin -m -g ricerca ricerca ./smbldap-useradd -s /sbin/nologin -m -g finanze finanze ./smbldap-useradd -s /sbin/nologin -m -g amministrazione amministrazione
Aggiungere l'utente samba alla Directory con:
smbldap-useradd -s /bin/false -d /dev/null -P samba.
Impostare la password quando richiesta, nel file ldap.conf modificare il campo binddn con
uid=samba,ou=Users,dc=miodominio,dc=com e bindpw con la password di prima,
(cambaiate i parametri a seconda della vostra configurazione! io ho dc=chrix,dc=lan)
Dopo aver aggiunto alcuni utenti al sistema, potete aggiungere una workstation windows xp professional o windows 2000 al dominio.
Per semplicità potete usare un tool grafico come phpLdapAdmin per amministrare la Directory, Da shell, per aggiungere l'utente pippo al gruppo ricerca, la sintassi è la seguente:
smbldap-useradd -a -G “Domain Users”, ricerca pippo smbldap-passwd pippo
Ora godetevi il vostro nuovo Directory Server! Soluzione meno costosa di RHEL... (Red Hat Enterprise Linux)
Autore
è garantito il permesso di copiare e/o modifiacre questo documento secondo i termini della licenza per documentazione libera GNU v.1.1 o successiva pubblicata dalla Free Software Foundation.
autore: Chrix