LDAP-based authentication for Samba

Install and configure Samba as a primary domain controller with LDAP on Linux

This tutorial demonstrates how to install and configure Samba as a primary domain controller with a secure LDAP-based authentication mechanism. It also describes how to configure the LDAP server, OpenLDAP, for PAM-based authentication and how to secure the link between Samba and OpenLDAP with Transport Layer Security (TLS). The completed system boasts a secure file- and print-sharing setup, in addition to a robust LDAP server that could be used for purposes beyond those required by Samba. Additionally, Windows® clients are able to logon to your Samba server which acts as a primary domain controller and have shared drives automatically mounted for them based on their group membership.

Keith Robertson (keithrob@us.ibm.com), Advisory software engineer, IBM

Keith Robertson is an Advisory Software Engineer at IBM in Research Triangle Park, NC. He is pursuing a master's degree in computer networking at North Carolina State University in Raleigh, NC. His background includes experience with networking technologies and software-development techniques. He has a working knowledge of low-level telecom networking protocols (such as SIP and MEGACO) and IP networking management protocols (such as SNMP and ICMP). He is also skilled at C/C++ and the Java programming language. You can contact Keith at keithrob@us.ibm.com.



31 January 2006

Before you start

About this tutorial

In this tutorial -- about how to install and configure Samba as a primary domain controller with a secure LDAP-based authentication mechanism -- I'll:

  • Introduce LDAP, show how it integrates with Samba, and discuss security concerns
  • Go through the steps of configuring LDAP, including installing OpenLDAP and the IDEALX LDAP Samba toolkit; configuring OpenLDAP necessities, the slapd.conf file, the /etc/ldap.conf file, and the Pluggable Authentication Modules (PAM); and explain how to start OpenLDAP
  • Next, show you how to configure Samba, including installing and starting Samba and the Logon Profile Generator; creating the required directories and the shared drives; configuring the smb.conf file and setting the LDAP database-access password; populating the database; adding the PAM and other users and adding Windows workstations to the domain; and debugging the Samba installation in case it didn't work
  • Finally, cover security issues and talk about how to enable security for this system, including enabling the Transport Layer Security for OpenLDAP, PAM, and Samba and how to test the security of your system

The completed system boasts a secure file- and print-sharing setup, in addition to a robust LDAP server that could be used for purposes beyond those required by Samba. Additionally, Microsoft Windows clients are able to logon to your Samba server which acts as a primary domain controller and have shared drives automatically mounted for them based on their group membership.

This tutorial is best suited for readers with moderate UNIX or Linux familiarity and experience with basic IP networking concepts. The author used Fedora Core 3 as the Linux distribution, but other Linux distributions or UNIX variants, such as AIX, Solaris, or HP-UX, would also work for the setup described in the tutorial. All applications and utilities used in this tutorial are open source and are available from either your Linux vendor or the application vendor's homepage.

Prerequisites

The Linux distribution is Fedora Core 3; however, there is no reason why the setup described here would not work on other Linux distributions or UNIX variants such as AIX, Solaris, or HP-UX. The software is free and obtained in a number of ways. I recommend that you get a precompiled version (such as an RPM) from your Linux vendor's ftp mirror.

Here is a list of software used in this tutorial. There is no need to get the list beforehand as the tutorial describes how to download and install them.

  • OpenSSL.
  • OpenLDAP.
  • Samba.
  • Perl module Crypt::SmbHash.
  • Perl module Digest::SHA1.
  • Perl module IO::Socket::SSL.
  • Perl module Net::SSLeay.
  • IDEALX Samba LDAP tools.

Note: This tutorial identifies the specific versions of the various software components tested. You might have success with earlier versions of the software, but I cannot guarantee that they will work. In general, software that is newer than the versions described in this tutorial should work.

Tutorial network layout

The network described in this tutorial is intended to be small so that you can easily duplicate the examples on a home or lab network. For this setup, I used a typical home broadband router with a built-in firewall. The following diagram depicts the physical network layout.

Figure 1. Tutorial network configuration
Tutorial network configuration

This Microsoft Windows network contains three classes of users -- marketing, engineering, and management. Engineering and marketing each have a shared drive where users from each group may place files for others in that same group to see; however, members from one group cannot see files on the other group's shared drive. For example, a marketing employee may not view a file on the engineering drive. Management also has a shared drive that is visible only to managers. In addition, we give managers special privileges so that they can see files from both engineering and marketing.


Introducing LDAP

Now I'll introduce LDAP, show how it integrates with Samba, and discuss security concerns.

A brief introduction to LDAP

LDAP is a popular mechanism for authentication and as a repository for storing personally identifiable information. It has several advantages over traditional flat-file-based authentication mechanisms, for example /etc/passwd. One of these advantages is that LDAP can be used to produce the Holy Grail of password management, a single sign-on. Single sign-on is available because software applications can authenticate remotely against a common LDAP-based user repository across a TCP/IP network. The LDAP method of authentication is in direct contrast to flat-file-based authentication schemes that are typically tied to a single machine and do not distribute well.

LDAP manages data in what is termed a directory information tree. This tree helps to organize data through categorization. Many LDAP servers use SQL databases to store their information because they are a natural fit. As with a traditional SQL database, LDAP uses schemas to define where data should be located and how data should be formatted. The use of schemas and the similarities with traditional SQL databases are key advantages of LDAP because they contribute greatly to its extensibility.

Integrating Samba with LDAP

There are three main integration points between Samba and an LDAP server:

  • The first is the inclusion of Samba's schema into the LDAP server.
  • The second is configuring Samba to authenticate through the LDAP server.

Authentication takes place with the help of Linux's PAM utility (Pluggable Authentication Modules). The PAM utility abstracts the process of authentication away from software applications running on Linux so that they do not have to understand the complexities of a particular authentication mechanism. As such, PAM gives software applications an enormous degree of flexibility because a software application can call one API for authentication and PAM decides if it should use flat file, LDAP, or some other mechanism for authentication.

  • The third integration point involves a set of tools that aid in the management of Samba's LDAP directory information tree. This toolkit is produced by a third-party; however, it is covered under the GNU Public License.

Security

A key strength of LDAP is its ability to be used as an authentication mechanism for software applications that could be scattered across a network. A side effect of this strength is that passwords may flow across the network during the authentication phase and, as a result, could be intercepted. Fortunately, LDAP supports both SSL (Secure Sockets Layer) and TLS.

In this tutorial, the LDAP server is running on the same physical server as Samba; thus, there isn't much need for encryption. However, I will demonstrate how to encrypt the channel between LDAP and Samba because it is relatively simple and necessary for the reader who hosts Samba and LDAP on different machines.

This tutorial proceeds in two phases. The first phase details how to configure Samba and LDAP in an unsecured mode. Once the first phase is complete, encryption is enabled to secure the channel between Samba and the LDAP server. I am proceeding in a two-phase approach because in general, it is usually easier to install, configure, and diagnose problems in an unsecured mode.


Configuring LDAP

Step 1: Installing OpenLDAP

To install OpenLDAP:

  1. Check to see if your distribution has OpenLDAP installed. Issue the following command at a terminal: rpm -qa | grep ldap. If you do not get a response of openldap-2.2.13 or greater, then you should either upgrade or install anew (which is described next).
  2. If you don't have OpenLDAP version 2.2.13 or greater, go to your distribution's mirror and download a binary package. In my case, I went to Fedora's mirror list and downloaded openldap-2.2.13-2.i386.rpm. Then I issued the following command: rpm -Uvh openldap-2.2.13-2.i386.rpm.

Step 2: Installing IDEALX's LDAP Toolkit for Samba

A toolkit from IDEALX is required to automate many of the important interactions between Samba and your LDAP server. Included in the toolkit from IDEALX are scripts that Samba automatically call to add users, modify users, add machines, etc. The scripts are written in Perl and can also be used from the command line.

To install the IDEALX toolkit:

  1. Go to IDEALX's homepage and download version .0.9.1 or later of the toolkit (smbldap-tools-.0.9.1.tgz).
  2. In a temporary directory, unpack the toolkit with the following command: tar -zxf smbldap-tools-0.9.1.tgz.
  3. We create a directory for the IDEALX scripts to live in. At the command prompt type: mkdir -p /var/lib/samba/sbin. Then type: chmod -R 755 /var/lib/samba.
  4. Change into the directory created by the tar command. Type: cd smbldap-tools-0.9.1.
  5. Copy the required scripts from the temporary directory to the permanent directory with the following command: cp smbldap* configure.pl /var/lib/samba/sbin.
  6. Set the correct ownership and permissions by changing into the /var/lib/samba/sbin directory and issuing the following commands in order:
    1. chmod 750 *
    2. chmod 640 smbldap_bind.conf smbldap.conf smbldap_tools.pm
  7. You can now safely remove the temporary directory.

The IDEALX toolkit requires some additional Perl modules that may not be installed on your system. This section demonstrates how to download and install them.

  1. The first thing you need to do is to download all of the requisite Perl modules from CPAN.org. Go to CPAN.org and type the following search strings into the search box.
    • Search for Perl module: Crypt::SmbHash
    • Search for Perl module: Digest::SHA1
    • Search for Perl module: IO::Socket::SSL
    • Search for Perl module: Net::SSLeay
    Hopefully, you will be able to navigate from the results of each search directly to each module's homepage. On each of the four module's homepage you will find a link to download the associated Perl module.
  2. The next step is to un-tar and un-zip the downloaded Perl modules. Issue the following command in the directory where you saved the four downloaded modules: tar -zxvf *.gz.
  3. The final step is to build and install each of the four modules. Change into each of the newly created directories and issue the following commands as root.
    1. perl Makefile.PL
    2. make install

Step 3: Configure the schemas, directories, and keys needed by OpenLDAP

If you installed from an RPM and your Linux distribution is Fedora, then you should have a directory called /etc/openldap. In this directory is OpenLDAP's primary configuration file, slapd.conf. Before we begin editing this file, we perform some preliminary setup actions.

OpenLDAP needs to be made aware of Samba's LDAP schema. To do this we copy Samba's schema into /etc/openldap/schema.

  1. Find Samba's schema. It should be located in the directory that Samba was installed in. To find it type: locate samba.schema.
  2. Copy it into /etc/openldap/schema.
  3. Set the correct permissions. Type: chmod 644 /etc/openldap/schema/samba.schema.

Create the directory for our LDAP database. In this tutorial, we give this directory the same name as our domain name.

  1. Type: mkdir -p /var/lib/ldap/somedomain.com.
  2. Set the correct permissions: chmod 700 /var/lib/ldap/somedomain.com.
  3. Set the correct ownership. Fedora users should already have the user LDAP defined in /etc/passwd. If you are installing on a different distribution you may need to create that user. Type: chown ldap:ldap /var/lib/ldap/somedomain.com.

Finally, we create the encryption keys that OpenLDAP uses for TLS. To do this you need OpenSSL. The vast majority of Linux distributions ship with OpenSSL; however, if you do not have it installed, get a copy from your vendor or http://www.openssl.org/.

This tutorial assumes that the user will not be using a commercial certificate authority (CA) such as Verisign, Thawte, etc. As such, we will need to become our own CA and sign the certificates used by our LDAP server. The steps below demonstrate how to become a CA and sign certificates.

  1. If you haven't already done so, edit openssl.cnf to match your particular needs. Find the openssl.cnf file and type: locate openssl.cnf.
  2. In the same directory as openssl.cnf issue the following commands as root.
    Listing 1. Step to become CA
    mkdir -p CA/certs CA/crl CA/newcerts  CA/private
    chmod 700 CA/private
    touch CA/index.txt
    echo 01 > CA/serial
  3. Open openssl.cnf in your favorite editor and change the following parameters to match your particular situation.
    Listing 2. Step to become CA
    # The dir parameter is important because it tells
    # openssl where to find all necessary files used to
    # generate keys.
    dir                             = ./
    # default_days defines the length of time your key is valid for.
    default_days                    = 3650
    # default_bits is an indicator of the strength of your key.  I elected
    # 1024 but you can choose more or less.
    default_bits                    = 1024
    # The following parameters should be modified to fit your
    # organization.
    countryName_default             = US
    stateOrProvinceName_default     = North Carolina
    localityName_default            = Raleigh
    0.organizationName_default      = somedomain.com
  4. Create your CA certificate and key pair with the following command: openssl req -nodes -config openssl.cnf -new -x509 -keyout CA/private/cakey.pem -out CA/cacert.pem -days 3650.
  5. Create the key pair for OpenLDAP with the following commands:
    1. openssl req -config openssl.cnf -nodes -new -keyout /etc/openldap/slapd-key.pem -out slapd.csr
    2. openssl ca -config openssl.cnf -out /etc/openldap/slapd-cert.pem -in slapd.csr
    3. chown root:ldap /etc/openldap/slapd-key.pem
    4. chmod 640 /etc/openldap/slapd-key.pem
    5. chmod 644 /etc/openldap/slapd-cert.pem
  6. Copy your CA's certificate to the openldap configuration directory so that various applications can access it.
    1. cp CA/cacert.pem /etc/openldap/
    2. chmod 644 /etc/openldap/cacert.pem

Step 4: Configure slapd.conf

The executable supplied by OpenLDAP that corresponds to an actual LDAP server is called slapd. The slapd daemon reads all of its configuration information from slapd.conf. In this section, I provide a sample slapd.conf that is annotated with comments. You must change all sections a denoted by a "# MODIFY" comment to fit your particular situation.

Before we begin editing, generate a password hash for the rootdn. This is the password that you must use to make changes to your LDAP server's directory information tree.

Note: Choose a password that is different from your Linux server's root password.

  1. From the command line type: slappasswd -h {SSHA} -s <your password here>.
  2. Save the output from this command, as you will need it next. It could look like: {SSHA}kCuJt72QLJ2O06nFUvdre97sHT0AxlH/.

If you installed a binary version of OpenLDAP on Fedora, slapd.conf it should exist as /etc/openldap/slapd.conf. Modify it to suit your particular situation.

The contents of /etc/openldap/slapd.conf looks like this:

Listing 3. Contents of slapd.conf
#
# 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/cosine.schema
include     /etc/openldap/schema/inetorgperson.schema
include     /etc/openldap/schema/nis.schema
include     /etc/openldap/schema/samba.schema

# -1 is all messages 296 is a good compromise for most debugging
#loglevel    -1
pidfile     /var/run/slapd.pid
argsfile    /var/run/slapd.args

# The following three lines are related to security.  Leave them commented out now.
# We uncomment them and enable security *after* we have successfully tested Samba with
# LDAP in an unsecured configuration.  Debugging is infinitely easier without encryption
# enabled.
#TLSCipherSuite          HIGH
#TLSCertificateFile      /etc/openldap/slapd-cert.pem
#TLSCertificateKeyFile   /etc/openldap/slapd-key.pem

database    bdb
# MODIFY
# Modify suffix and rootdn to match your domain name.
suffix      "dc=somedomain,dc=com"
rootdn      "cn=Manager,dc=somedomain,dc=com"

# MODIFY
# Use the following to generate:
#  slappasswd -h {SSHA} -s <your password here>
rootpw      {SSHA}kCuJt72QLJ2O06nFUvdre97sHT0AxlH/

# MODIFY
# The database directory MUST exist prior to running slapd AND
# should only be accessible by the slapd and slap tools.
# Mode 700 recommended with an owner of ldap and a group of ldap
directory   /var/lib/ldap/somedomain.com

# Indices to maintain for this database
index objectClass           eq
index cn                    pres,sub,eq
index sn                    pres,sub,eq
index uid                   pres,sub,eq
index displayName           pres,sub,eq
index uidNumber             eq
index gidNumber             eq
index memberUID             eq
index sambaSID              eq
index sambaPrimaryGroupSID  eq
index sambaDomainName       eq
index default               sub

# Access Control Entries
# Note these ACEs are duplicated from the IDEALX smbldap usermanual with one exception
# users can authenticate and change their password access to attrs=userPassword,
sambaNTPassword,sambaLMPassword,sambaPwdLastSet,sambaPwdMustChange
      by dn="uid=samba,ou=Users,dc=somedomain,dc=com" write
      by self write
      by anonymous auth
      by * none
# some attributes need to be readable anonymously so that 'id user' can answer correctly
access to attrs=objectClass,entry,gecos,homeDirectory,uid,uidNumber,gidNumber,cn,
memberUid
      by dn="uid=samba,ou=Users,dc=somedomain,dc=com" write
      by * read
# somme attributes can be writable by users themselves
access to attrs=description,telephoneNumber
      by dn="uid=samba,ou=Users,dc=somedomain,dc=com" write
      by self write
      by * read
# some attributes need to be writable for samba (this ACE modified from original to allow
some unix commands to work) access to attrs=cn,sambaLMPassword,sambaNTPassword,
sambaPwdLastSet,sambaLogonTime,sambaLogoffTime,sambaKickoffTime,sambaPwdCanChange,
sambaPwdMustChange,sambaAcctFlags,displayName,sambaHomePath,sambaHomeDrive,
sambaLogonScript,sambaProfilePath,description,sambaUserWorkstations,sambaPrimaryGroupSID,
sambaDomainName,sambaSID,sambaGroupType,sambaNextRid,sambaNextGroupRid,sambaNextUserRid,
sambaAlgorithmicRidBase,sambaLogonScript,loginShell
      by dn="uid=samba,ou=Users,dc=somedomain,dc=com" write
      by self read
      by * none
# samba need to be able to create the samba domain account
access to dn.base="dc=somedomain,dc=com"
      by dn="uid=samba,ou=Users,dc=somedomain,dc=com" write
      by * none
# samba need to be able to create new users account
access to dn="ou=Users,dc=somedomain,dc=com"
      by dn="uid=samba,ou=Users,dc=somedomain,dc=com" write
      by * none
# samba need to be able to create new groups account
access to dn="ou=Groups,dc=somedomain,dc=com"
      by dn="uid=samba,ou=Users,dc=somedomain,dc=com" write
      by * none
# samba need to be able to create new computers account
access to dn="ou=Computers,dc=somedomain,dc=com"
      by dn="uid=samba,ou=Users,dc=somedomain,dc=com" write
      by * none
# this can be omitted but we leave it: there could be other branch
# in the directory
access to *
      by self read
      by * none

Step 5: Configure /etc/ldap.conf

The /etc/ldap.conf file is used by LDAP clients on the local system. These clients include PAM, the interface through which Samba authenticates with the LDAP server.

Sometimes there are multiple instances of ldap.conf on your system. Locate the one that PAM has been configured to use. To do this type: strings /lib/libnss_ldap.so.2 | grep conf. Usually, the returned value is /etc/ldap.conf.

Edit ldap.conf in your favorite editor and insert the following text. Modify the sections denoted with a "# MODIFY" comment.

The contents of /etc/ldap.conf look like this:

Listing 4. Contents of /etc/ldap.conf
## IMPORTANT
## The /etc/ldap.conf file is used by PAM.   There is another ldap.conf file in
## /etc/openldap.
## The file, /etc/openldap/ldap.conf, is used by ldap tools, such as ldapsearch.
## If you intend to use those tools you will need to add a TLS_CACERT directive to that
## file also.

# Your LDAP server. Must be resolvable without using LDAP.
# Multiple hosts may be specified, each separated by a
# space.
host 127.0.0.1

# MODIFY
# The distinguished name of the search base.
base dc=somedomain,dc=com

# MODIFY
# The distinguished name to bind to the server with.
# We will use the root dn until we can create a lesser privileged user.
binddn cn=Manager,dc=somedomain,dc=com
bindpw < use the password you created for Manager in "Step 4: Configure slapd.conf">

# MODIFY
# Note: "ou=Users" and "ou=Groups" should match what
# you entered in smb.conf for "ldap group suffix"
# and "ldap user suffix"
nss_base_passwd		ou=Users,dc=somedomain,dc=com?one
nss_base_passwd		ou=Computers,dc=somedomain,dc=com?one
nss_base_shadow		ou=Users,dc=somedomain,dc=com?one
nss_base_group		ou=Groups,dc=somedomain,dc=com?one

ssl no
pam_password md5
# We need to tell PAM where the certificate used to authenticate the LDAP
# server (i.e. is the LDAP server the one we think it is).
tls_cacertfile /etc/openldap/cacert.pem

# If you experience difficulty authenticating after enabling TLS, try uncommenting
# the next line.  You will know that you are having problems if you
# issue "getent group" and do not see any of the MS Windows groups
# that have been created in your LDAP database.
# tls_checkpeer no

Step 6: Configure PAM

Configuring PAM can be tricky. As such, I prefer to use the utility provided by my Linux vendor to do all of the dirty work for me. Fedora provides a command line utility called authconfig that knows how to modify all of PAM's configuration files. Other Linux vendors have similar configuration utilities, so consult the documentation if you're not using Fedora.

  1. Launch authconfig from the command line. Type: authconfig.
  2. Edit the first screen as shown.
    Figure 2. authconfig screen 1
    authconfig screen 1
  3. Edit the second screen as shown.
    Figure 3. authconfig screen 2
    authconfig screen 2

Step 7: Start OpenLDAP

Now it is time to start our LDAP server. Fedora users who installed from a binary RPM should be able to execute the following command: /etc/init.d/ldap start.


Configuring Samba

Now let's turn our attention to Samba -- installation, creating directories, and configuration.

Step 1: Installing Samba

To install Samba:

  1. Check to see if your distribution already has Samba installed. Issue the following command at a terminal: rpm -qa | grep samba. If you do not get a response of samba-3.0.14 or greater, then you should either upgrade or install anew (which is described next).
  2. If you do not have Samba version 3.0.14 or greater, go to Samba's homepage and download a binary package for your particular Linux distribution. The Samba suite is divided into four separate RPMs, all of which are extremely useful and I recommend you install them all. However, if you are a minimalist, you should install the samba and samba-common packages only. Download the samba RPMs that you want and install them with the following command: rpm -Uvh samba*.

Step 2: Create the requisite directories

We need to create some directories that Samba uses for runtime data.

  1. mkdir -p /var/lib/samba/netlogon/scripts/ /var/lib/samba/printing/
  2. chmod -R 755 /var/lib/samba/netlogon /var/lib/samba/printing

Step 3: Configure smb.conf

If you installed a binary version of Samba on Fedora, you should have a configuration directory called /etc/samba. This directory contains various files that are used by Samba's two daemons (smbd and nmbd). Samba's primary configuration file, smb.conf, is located in this directory. We change this file to reflect our Microsoft Windows network and we add hooks to make Samba aware of the LDAP backend. The file is shown below with comments.

Change all sections a denoted by a "# MODIFY" comment to fit your particular situation. Also, all of the directives in this configuration file are described in the Samba manual. You can view it by typing man smb.conf.

The contents of /etc/samba/smb.conf look like this:

Listing 5. Contents of /etc/samba/smb.conf
# Global parameters
[# Global parameters
[global]
        # MODIFY
        workgroup = BIGTIME
        # MODIFY
        netbios name =  linus
        # MODIFY
        server string = Linus Samba Server
        passdb backend = ldapsam:ldap://127.0.0.1/
        # By default run with minimal logging.  However, if you need to debug
        # 5 is a fairly verbose logging level.
        #log level = 5
        log file = /var/log/samba/log.%m
        max log size = 50
        time server = Yes
        add user script = /var/lib/samba/sbin/smbldap-useradd -a '%u'
        delete user script = /var/lib/samba/sbin/smbldap-userdel '%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'
        add machine script = /var/lib/samba/sbin/smbldap-useradd -w '%u'
        # Personally, I do not like roaming profiles because they take up too
        # much space on my server.  As such, I disable roaming profiles by
        # setting the following two variables to null
        logon path =
        logon home =
        logon drive = H:
        domain logons = Yes
        preferred master = Yes
        domain master = Yes
        wins support = Yes
        # MODIFY
        ldap admin dn = cn=Manager,dc=somedomain,dc=com
        ldap group suffix = ou=Groups
        ldap idmap suffix = ou=Idmap
        ldap machine suffix = ou=Computers
        ldap passwd sync = Yes
        # MODIFY
        ldap suffix = dc=somedomain,dc=com
        ldap user suffix = ou=Users
        idmap backend = ldap:ldap://127.0.0.1
        idmap uid = 10000-20000
        idmap gid = 10000-20000


# The next three blocks define the shared drives that we will be exposing.  They are all
# nearly identical.  The important thing to note is that all files on these drives are
# readable and writeable by any user in that group.
[netlogon]
        path = /var/lib/samba/netlogon/scripts
        browseable = No
        root preexec = /var/lib/samba/netlogon/scripts/logon.pl %U %I

# MODIFY
[marketing]
        comment = Marketing material
        path = /home/marketing
        # Any files written to this drive will have this user group. Since this is a
        # *shared* drive all users should have permission to read/write/remove any file.
        # If you do not agree you will probably want to remove the "force group" line
        force group = marketing
        read only = No
        create mask = 0770
        directory mask = 0770
        browseable = No

# MODIFY
[engineering]
        comment = Common material
        path = /home/engineering
        path = /home/marketing
        # Any files written to this drive will have this user group. Since this is a
        # *shared* drive all users should have permission to read/write/remove any file.
        # If you do not agree you will probably want to remove the "force group" line
        force group = engineering
        read only = No
        create mask = 0770
        directory mask = 0770
        browseable = No

# MODIFY
[management]
        comment = Management Data
        path = /home/management
        path = /home/marketing
        # Any files written to this drive will have this user group. Since this is a
        # *shared* drive all users should have permission to read/write/remove any file.
        # If you do not agree you will probably want to remove the "force group" line
        force group = management
        read only = No
        create mask = 0770
        directory mask = 0770

Step 4: Set Samba's password for accessing the LDAP database

Samba needs to know the rootdn's password so that is can both read and write to its schema within the LDAP server. Execute the following command to give Samba this password. You should use the same password as in Step 4: Configure slapd.conf: smbpasswd -w <your password here>.

Samba should respond as follows: Setting stored password for "cn=Manager,dc=somedomain,dc=com" in secrets.tdb.

Step 5: Install the Logon Profile Generator

Our Samba server is configured to be a Microsoft Windows domain controller and as such, it can control what actions a Windows client takes when it logs on to our domain. These actions can include things like retrieving a stored roaming profile, mounting drives, and synchronizing with a time server.

Our Samba server does not be store roaming profiles because these can take up quite a bit of space; however, we force each Microsoft Windows client that logs in to our domain to mount drives and synchronize with a time server.

In this step we create a Perl script that generates a Windows batch file that is executed each time a user logs in to the BIGTIME domain. The batch file causes the user's Windows machine to automatically mount the drives that their security profile grants them access to. This action is useful for large organizations with many common drives and a diverse security policy. The location and execution of this batch script are defined by two parameters in the netlogon section of smb.conf, they are path and root preexec.

The Perl script is shown following. Perform these actions to install the Perl logon script:

  1. cd /var/lib/samba/netlogon/scripts
  2. Create a file called logon.pl and fill it with the contents shown below.
  3. chmod 755 /var/lib/samba/netlogon/logon.pl

Following is the Perl logon script.

The contents of /var/lib/samba/netlogon/logon.pl looks like:

Listing 6. Contents of Perl logon script
#!/usr/bin/perl
use strict;
# Set the permissions on any file we create to 640 (i.e. -rw-r--r--)
umask(022);

my $NETLOGON_DIR = "/var/lib/samba/netlogon/scripts";
my $LOG_DIR = "/var/log/samba";
my $SERVERNAME = "linus";
## You will need to modify this hash to match your mountpoints.
my %MOUNTPOINTS = (
                "engineering" => "NET USE W: \\\\$SERVERNAME\\engineering \/YES\r\n",
                "marketing" => "NET USE W: \\\\$SERVERNAME\\marketing \/YES\r\n",
                "management" => "NET USE W: \\\\$SERVERNAME\\management \/YES\r\n"
                );

## Make sure that there is a user name and that it contains a valid
## user name string (i.e. no invalid chars).
if ($#ARGV != 1 ||
    $ARGV[0] =~ /[^a-zA-Z0-9-_]/) {
    exit(1);
}

# Make sure that the user exists and log attempts with invalid IDs
my $uid = getpwnam($ARGV[0]);
if ($uid == /[^0-9]/){
    my $now = localtime;
    open LOG, ">>$LOG_DIR/log.netlogon";
    print LOG "$now";
    print LOG " - Error: Unknown user $ARGV[0] logged into $SERVERNAME from $ARGV[1]\n";
    close LOG;
    exit(1);
}
# Log the logon attempt
my $now = localtime;
open LOG, ">>$LOG_DIR/log.netlogon";
print LOG "$now";
print LOG " - User $ARGV[0] logged into $SERVERNAME from $ARGV[1]\n";
close LOG;


## Create a custom logon batch file.
open FH, ">$NETLOGON_DIR/$ARGV[0].cmd";

# Turn echo off
print FH "\@ECHO OFF\r\n";

# Synchronize time between Windows client and Linux server.
print FH "NET TIME \\\\$SERVERNAME \/SET \/YES\r\n";

foreach my $key (keys(%MOUNTPOINTS)) {
    if (isMember($ARGV[0], $key)) {
       # Put mount points in file
       print FH "$MOUNTPOINTS{$key}";
    }
}
close FH;


# Checks to see if the given user is a member of
# the given group.
# Returns 1 if true and 0 otherwise.
sub isMember{
    my ($user, $group) = @_;
    my ($name, $passwd, $gid, $members) = getgrnam($group);
    my @members = split /\s+/, $members;

    for(@members){
       if ($user eq $_) {
          return 1;
       }
    }
    return 0;
}

Step 6: Start Samba

Now it is time to start our Samba server. Fedora users who installed from a binary RPM should be able to execute the following command: /etc/init.d/samba start.

Step 7: Populate the LDAP database

Now it is time to populate the LDAP database with our Samba schema and some initial values. For this task use the handy IDEALX scripts. We begin by executing a configuration script, /var/lib/samba/sbin/configure.pl. The configuration script creates two files, smbldap_bind.conf and smbldap.conf, which contain important environment variables used by all of the scripts in the IDEALX toolkit.

  1. First type: cd /var/lib/samba/sbin/.
  2. Edit smbldap_tools.pm and make the following changes to the variables smbldap_conf and smbldap_bind_conf.
    • my $smbldap_conf="/var/lib/samba/sbin/smbldap.conf";
    • my $smbldap_bind_conf="/var/lib/samba/sbin/smbldap_bind.conf";
  3. Next, launch the configuration utility by typing: ./configure.pl
  4. You will now be prompted with a series of questions and I have provided a sample listing. In general, you should be able to simply press the return key to the queries; however, here are some important things to know.
    • The password hash is case sensitive and should match the hash algorithm you specified in ldap.conf's pam_password variable (see Step 5: Configure /etc/ldap.conf).
    • In this tutorial there is no LDAP slave server, so we will use the same information as the master server.
    • The bind password requested by this script is the same password you used for the rootdn in Step 4: Configure slapd.conf.

The output from the configure.pl script looks like:

Listing 7. Output from the Perl configure script
[root@linus sbin]# ./configure.pl
If you need to change this, enter the full directory path, then press enter to continue.
Smbldap-tools Configuration Directory Path [/etc/opt/IDEALX/smbldap-tools/] >
 /var/lib/samba/sbin
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Let's start configuring the smbldap-tools scripts ...

. workgroup name: name of the domain Samba act as a PDC
  workgroup name [BIGTIME] >
. netbios name: netbios name of the samba controler
  netbios name [linus] >
. logon drive: local path to which the home directory will be connected (for NT
  Workstations). Ex: 'H:'
  logon drive [H:] >
. logon home: home directory location (for Win95/98 or NT Workstation).
  (use %U as username) Ex:'\\linus\%U'
  logon home (press the "." character if you don't want homeDirectory) [\\linus\%U]
  > .
. logon path: directory where roaming profiles are stored. Ex:'\\linus\profiles\%U'
  logon path (press the "." character if you don't want roaming profile)
  [\\linus\profiles\%U] > .
. home directory prefix (use %U as username) [/home/%U] >
. default users' homeDirectory mode [700] >
. default user netlogon script (use %U as username) [%U.cmd] > ""
  default password validation time (time in days) [45] >
. ldap suffix [dc=somedomain,dc=com] >
. ldap group suffix [ou=Groups] >
. ldap user suffix [ou=Users] >
. ldap machine suffix [ou=Computers] >
. Idmap suffix [ou=Idmap] >
. sambaUnixIdPooldn: object where you want to store the next uidNumber
  and gidNumber available for new users and groups
  sambaUnixIdPooldn object (relative to ${suffix}) [sambaDomainName=BIGTIME] >
. ldap master server: IP adress or DNS name of the master (writable) ldap server
  ldap master server [127.0.0.1] >
. ldap master port [389] >
. ldap master bind dn [cn=Manager,dc=somedomain,dc=com] >
. ldap master bind password [] >
. ldap slave server: IP adress or DNS name of the slave ldap server: can also be the
  master one
  ldap slave server [127.0.0.1] >
. ldap slave port [389] >
. ldap slave bind dn [cn=Manager,dc=somedomain,dc=com] >
. ldap slave bind password [] >
. ldap tls support (1/0) [0] > 1
. How to verify the server's certificate (none, optional or require) [require] >
. CA certificate file [/var/lib/samba/sbin//ca.pem] > /etc/openldap/cacerts/cacert.pem
. certificate to use to connect to the ldap server
  [/var/lib/samba/sbin//smbldap-tools.pem] >
. key certificate to use to connect to the ldap server
  [/var/lib/samba/sbin//smbldap-tools.key] >
. SID for domain BIGTIME: SID of the domain (can be obtained with
  'net getlocalsid linus')
  SID for domain BIGTIME [S-1-5-21-1030832020-2822878261-2997333186] >
. unix password encryption: encryption used for unix passwords
  unix password encryption (CRYPT, MD5, SMD5, SSHA, SHA) [SSHA] > MD5
. default user gidNumber [513] >
. default computer gidNumber [515] >
. default login shell [/bin/bash] >
. default skeleton directory [/etc/skel] >
. default domain name to append to mail adress [] > somedomain.com
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
backup old configuration files:
  /var/lib/samba/sbin/smbldap.conf->/var/lib/samba/sbin/smbldap.conf.old
  /var/lib/samba/sbin/smbldap_bind.conf->/var/lib/samba/sbin/smbldap_bind.conf.old
writing new configuration file:
  /var/lib/samba/sbin/smbldap.conf done.
  /var/lib/samba/sbin/smbldap_bind.conf done.
  1. For those of you who do not want password expiration enabled, I will demonstrate how to disable it. Edit smbldap.conf and comment out the following line: defaultMaxPasswordAge="45".
  2. Execute the following three commands to set the proper permissions and ownership:
    1. chown root:root smbldap.conf smbldap_bind.conf
    2. chmod 644 smbldap.conf
    3. chmod 600 smbldap_bind.conf
  3. Now it is time to initialize our Samba schema in the LDAP database. We will execute the IDEALX script, smbldap-populate, which will create a domain administrator, some necessary groups, and various other important schema elements. When you execute this script you may notice warnings about uninitialized variables. If you do not want to see these warnings you can edit all of the IDEALX scripts and replace all instances of "#!/usr/bin/perl -w" with "#!/usr/bin/perl". The following code is sample output from smbldap-populate. (Note: smbldap-populate may prompt you for a password for the domain administrator which is by default is named root. You should give this user a password that is different from the one used for the rootdn in Step 4: Configure slapd.conf and that is different from you Linux machine's root user.
Listing 8. Executing the IDEALX script, smbldap-populate
[root@linus sbin]# ./smbldap-populate
Populating LDAP directory for domain BIGTIME (S-1-5-21-1030832020-2822878261-2997333186)
(using builtin directory structure)

LDAP config host: 127.0.0.1
port: 389
version: 3
timeout: 60
adding new entry: dc=somedomain,dc=com
adding new entry: ou=Users,dc=somedomain,dc=com
adding new entry: ou=Groups,dc=somedomain,dc=com
adding new entry: ou=Computers,dc=somedomain,dc=com
adding new entry: uid=root,ou=Users,dc=somedomain,dc=com
adding new entry: uid=nobody,ou=Users,dc=somedomain,dc=com
adding new entry: cn=Domain Admins,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=Domain Users,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=Domain Guests,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=Domain Computers,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=Administrators,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=Account Operators,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=Print Operators,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=Backup Operators,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=Replicators,ou=Groups,dc=somedomain,dc=com
adding new entry: cn=NextFreeUnixId,dc=somedomain,dc=com

Please provide a password for the domain root:
LDAP config host: 127.0.0.1
port: 389
version: 3
timeout: 60
Changing password for root
New password :
Retype new password :

Step 8: Create the shared drives

To create a shared drive for each of our three user groups (engineering, marketing, and management) we use the smbldap-useradd utility. This utility will create a directory in /home that serves as a shared drive. We will also create an associated UNIX user group that we use later to grant ordinary users permissions to the shared drive. Execute the following commands as root:

Listing 9. Creating UNIX group for permissions to shared drive
cd /var/lib/samba/sbin
./smbldap-groupadd engineering
./smbldap-groupadd marketing
./smbldap-groupadd management
./smbldap-useradd -s /sbin/nologin -m -g engineering engineering
./smbldap-useradd -s /sbin/nologin -m -g marketing marketing
./smbldap-useradd -s /sbin/nologin -m -g management management

Note: The option "-s /sbin/nologin" is a security measure used to prevent someone from logging into your Linux box with one of the three IDs.

Step 9a: Add the PAM user

For security reasons, we will force PAM to connect to our LDAP server with a DN that is not root (like cn=Manager,dc=somedomain,dc=com). A quick scan of the ldap.conf file we created in Step 5: Configure /etc/ldap.conf will show that PAM will attempt to connect to the LDAP with a dn of cn=Manager,dc=somedomain,dc=com. We will create a lesser privledged user (uid=samba,ou=Users,dc=somedomain,dc=com) in this step.

Issue the following command to create the user samba: smbldap-useradd -s /bin/false -d /dev/null -P samba. When prompted for a password, give a unique password. When finished, update the binddn with uid=samba,ou=Users,dc=somedomain,dc=com and bindpw paramater in ldap.conf with the password you just gave.

Step 9b: Add some users

The next step is to add some users and assign each a security profile. This list identifies users and their assigned group:

  • Marketing group: catbert
  • Management group: boss
  • Engineering group: dilbert, wally

Next, we create the users on our Linux system. This requires a two-step process for each user:

  1. Create the user ID on the system.
  2. Set the Samba password.

By default the smbldap-useradd script will attempt to create a home directory on your Linux system for each user, we will disable this with the -a option. Issue the following commands as root:

Listing 10. Disabling the -a option
cd /var/lib/samba/sbin
./smbldap-useradd -a -G "Domain Users",engineering dilbert
./smbldap-passwd dilbert
./smbldap-useradd -a -G "Domain Users",engineering wally
./smbldap-passwd wally
./smbldap-useradd -a -G "Domain Users",marketing catbert
./smbldap-passwd catbert
./smbldap-useradd -a -G "Domain Users",marketing,management,engineering boss
./smbldap-passwd boss

Step 10: Add Microsoft Windows workstations to your domain

For this step, visit each workstation you plan to grant access. (The following steps are for Microsoft Windows XP Professional, but they can be applied to other Microsoft Windows variants.)

Log on to each Windows workstation as administrator and perform the following actions:

  1. Go to the Control Panel and select System.
  2. Select the Computer Name tab.
  3. Click the button to rename this computer or join a domain.
  4. A new window should appear. In this window, click the radio button for domain and enter BIGTIME as the domain. Click OK.
  5. When prompted for a user ID and password, use root as the user ID and the password you gave in Step 7: Populate the LDAP database. You are prompted to reboot the workstation.
  6. After rebooting, you will notice that the domain BIGTIME has been added to the Log on to: selection box. Before we can log on as one of the domain members we created in Step 9a: Add the PAM user, we should decide where they fit in this workstation's local security hierarchy. In this tutorial, we will add all Domain Users in the BIGTIME domain to the Power Users local group on this workstation. Follow these steps:
    1. From the logon screen, select the option for (this computer) from the Log on to: selection box.
    2. Now log on as a user with administrative privileges for this workstation.
    3. After logging in, select Start.
    4. Select Control Panel.
    5. Select Administrative Tools.
    6. Select Computer Management.
    7. Navigate to Local Users and Groups.
    8. Click on Groups.
    9. Click on Power Users.
    10. Click the Add button and make sure the box From this Location contains BIGTIME.
    11. Click the Advanced button.
    12. Click Find Now.
    13. You will be prompted for the domain administrator's id and password. Enter root and the password from Step 7: Populate the LDAP database.
    14. Select Domain Users and click OK until you are returned to the Computer Management window.
  7. Next, enter any of the users you configured (boss, wally, catbert, or dilbert) and log on to that workstation.
  8. The workstation should automatically mount the drives that the user is allowed to access based on their security profile.
  9. Repeat steps 1-6 on every workstation in your network.

Step 11: Quick review

You should now have a fully functioning Samba server acting as a MS Windows Primary Domain Controller if everything went smoothly. If everything did not go smoothly, you should stop and debug before we complicate matters by enabling encryption in the next section. I have listed some diagnostic tests that you can run to assist with debugging.

  • Execute testparm /etc/samba/smb.conf. This will check your Samba server's configuration file for errors.
  • A good test is to ensure that your Linux box can resolve the group IDs of the Windows users you created in Step 9a: Add the PAM user (wally, dilbert, etc.). Execute groups wally. If you do not see engineering and Domain Users, you should verify that your modifications to ldap.conf are spelled correctly and match exactly with those in smb.conf and slapd.conf.
  • Examine your LDAP database with JXplorer. JXplorer is a graphical LDAP database browser and it can assist you with understanding how Samba interacts with the database. For example, if you were successful adding computers, groups, or users, you should see them in your LDAP server's directory information tree.
  • Look for problems in the logs. Examine the Samba's logs in /var/log/samba and OpenLDAP's logs in /var/log/slapd.

Enabling security

Wrapping this tutorial up by looking at security issues, I'll show you how to enable the Transport Layer Security for OpenLDAP, PAM, and Samba, and how to test the configuration.

Step 1: Enable TLS for OpenLDAP

In this step, we will instruct our LDAP server to use the security certificates we generated in Step 3: Configure the schemas, directories, and keys needed by OpenLDAP. Simply open /etc/openldap/slapd.conf and uncomment the following three lines:

Listing 11. Enabling TLS for OpenLDAP
TLSCipherSuite          HIGH
TLSCertificateFile      /etc/openldap/slapd-cert.pem
TLSCertificateKeyFile   /etc/openldap/slapd-key.pem

Step 2: Enable TLS for PAM

Now we need to instruct PAM to communicate with the LDAP server over an encrypted connection. Fedora users can launch authconfig and let the tool do all of the dirty work. Alternatively, you can simply edit /etc/ldap.conf and add the following line ssl start_tls.

Some people may experience difficulty getting PAM to communicate with their LDAP server after enabing TLS. If you are unable to see the Windows groups you created in your LDAP database with getent group, try adding the following line at the end of your ldap.conf file: tls_checkpeer no.

This is a screen shot depicting the TLS being enabled through authconfig.

Figure 4. LDAP Authentication over TLS in authconfig
LDAP Authentication over TLS in authconfig

Here is a listing of ldap.conf with TLS enabled.

Listing 12. ldap.conf with TLS enabled
## IMPORTANT
## The /etc/ldap.conf file is used by PAM.   There is another ldap.conf file in
## /etc/openldap.
## The file, /etc/openldap/ldap.conf, is used by ldap tools, such as ldapsearch.
## If you intend to use those tools you will need to add a TLS_CACERT directive to that
## file also.

# Your LDAP server. Must be resolvable without using LDAP.
# Multiple hosts may be specified, each separated by a
# space.
host 127.0.0.1

# MODIFY
# The distinguished name of the search base.
base dc=somedomain,dc=com

# MODIFY
# The distinguished name to bind to the server with.
# We will not be using the root dn.  Instead we will create
# lesser privileged user.
binddn uid=samba,ou=Users,dc=somedomain,dc=com
bindpw <your password here>

# MODIFY
# Note: "ou=Users" and "ou=Groups" should match what
# you entered in smb.conf for "ldap group suffix"
# and "ldap user suffix"
nss_base_passwd		ou=Users,dc=somedomain,dc=com?one
nss_base_passwd		ou=Computers,dc=somedomain,dc=com?one
nss_base_shadow		ou=Users,dc=somedomain,dc=com?one
nss_base_group		ou=Groups,dc=somedomain,dc=com?one

ssl start_tls
pam_password md5
# We need to tell PAM where the certificate used to authenticate the LDAP
# server (i.e. is the LDAP server the one we think it is).
tls_cacertfile /etc/openldap/cacert.pem

# If you experience difficulty authenticating after enabling TLS, try uncommenting
# the next line.  You will know that you are having problems if you
# issue "getent group" and do not see any of the MS Windows groups
# that have been created in your LDAP database.
tls_checkpeer no

Step 3: Enable TLS for Samba

Finally, we will enable Samba to communicate with the LDAP server over TLS. To accomplish this, we need to configure the IDEALX scripts to use TLS when communicating with the LDAP server. Make the following modifications to /var/lib/samba/sbin/smbldap.conf.

Listing 13. Getting Samba to talk to LDAP server via TLS
# Set this variable to 1 to enable TLS
ldapTLS="1"
# Require that the client (i.e. samba) verify the authenticity of the LDAP server
verify="require"
# You should have already created this certificate during the LDAP configuration phase.
cafile="/etc/openldap/slapd-cert.pem"

You may have noticed that there are other options in the smbldap.conf file for authentication, clientcert and client key. These two options are there for the truly paranoid and would allow the LDAP server to authenticate the client.

Step 4: Test the configuration

Now it is time to test the secured configuration; however, we should restart our LDAP server and our Samba server. Execute:

Listing 14. To test, restart LDAP and Samba servers
/etc/init.d/ldap restart
/etc/init.d/smb restart

To test a TLS security between Samba and LDAP try the following:

  1. Execute /var/lib/samba/sbin/smbldap-usershow dilbert. This should cause the IDEALX scripts to communicate with the LDAP server over a TLS connection and return all of the information the LDAP server has about the user dilbert.
  2. Next, try to log in to the BIGTIME domain from a Windows workstation.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Linux on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Linux
ArticleID=132928
ArticleTitle=LDAP-based authentication for Samba
publish-date=01312006