Connecting to an LDAP server using Kerberos authentication in Perl

Connecting to an LDAP server using Kerberos authentication in Perl

It took me a while to figure this code out, and there seemed to be a lack of complete examples on the web to do exactly this, so I thought I’d document it.

I needed to connect to an LDAP server using a Kerberos principal for authentication from within a Perl script. This meant that it needed to do it without any external input, so it couldn’t rely on a password being entered or someone doing a kinit first.

The code is fairly simple. It basically gets the right credentials using a pre-initialised keytab and then sets up the relevant objects and uses them to bind to an LDAP server.

#!/usr/local/bin/perl -w    

# How to connect to an LDAP server using GSSAPI Kerberos auth.    

use strict;    

use Net::LDAP;
use Authen::SASL qw(Perl);
# This module makes doing the kinit much easier
use Authen::Krb5::Easy qw(kinit kdestroy kerror);    

# Location of the keytab which contains testuser's key
# exported in kadmin by: ktadd -k /tmp/test.keytab testuser
my $keytab = '/tmp/test.keytab';
# Where to store the credentials
my $ccache = '/tmp/test.ccache';    

$ENV{KRB5CCNAME} = $ccache;    

# Get credentials for testuser
kinit($keytab, 'testuser@CS.UKC.AC.UK') || die kerror();    

# Set up a SASL object
my $sasl = Authen::SASL->new(mechanism => 'GSSAPI') || die "$@";    

# Set up an LDAP connection
my $ldap = Net::LDAP->new('ldap.cs.kent.ac.uk') || die "$@";    

# Finally bind to LDAP using our SASL object
my $mesg = $ldap->bind(sasl => $sasl);    

# This should say "0 (Success)" if it worked
print "Message is ". $mesg->code ." (". $mesg->error .").\n";    

# Clear up the credentials
kdestroy();

Hopefully this will help someone else out. Comments welcome 🙂

(Visited 5,088 times, 1 visits today)
Share

7 Comments

  1. Joseph Riad

    First off, I would really like to thank you for this writeup. It’s a real life saver and it helped me tremendously.

    Just one note though. I couldn’t make it work with
    use Authen::SASL qw(Perl);

    It worked with
    use Authen::SASL qw(XS);
    though.

  2. ARI

    i just dont get what these lines means:
    # Location of the keytab which contains testuser’s key
    # exported in kadmin by: ktadd -k /tmp/test.keytab testuser
    my $keytab = ‘/tmp/test.keytab’;
    # Where to store the credentials
    my $ccache = ‘/tmp/test.ccache’;
    do i need to make those file or not?

  3. Oliver Gorwits

    You can also use the k5start command line tool to prime the Kerberos ticket cache and keep it refreshed. This is useful if your Perl code is a daemon, so you want to always make sure the cache has tickets to use in it.

    Well done on a nice succinct HOWTO on this dark art 🙂

    p.e. k5start is usually in an OS package called kstart.

Leave a Reply

Your email address will not be published. Required fields are marked *