Connecting to and 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 ![]()
Tags: Auth::SASL, Authen::Krb5::Easy, GSSAPI, Kerberos, keytab, KRB5CCNAME, LDAP, Net::LDAP
April 2nd, 2008 at 11:24 am
Thanks, that is a great help. Works like a charm.
November 13th, 2008 at 3:08 pm
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.