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 🙂

Share