2

How can I log into an LDAP server with a Kerberos username and password without making any changes to the configuration of the computer that the Python script is running on? The ldap3 documentation assumes that Kerberos has already been set up by editing /etc/krb5.conf and running kinit.

Alex Henrie
  • 744
  • 1
  • 6
  • 17

2 Answers2

1

You can use the environment variable KRB5_CONFIG to specify a temporary config file and the acquire_cred_with_password function to construct a credentials object to pass to the LDAP connection. Use the following example:

import gssapi
import os
from ldap3 import *
from tempfile import NamedTemporaryFile

controller = 'mydomaincontroller'
realm = 'MYDOMAIN.COM'
username = 'myuser'
password = 'mypassword'

conf = f'''
[libdefaults]
    default_realm = {realm}

[realms]
    {realm} = {{
        kdc = {controller}.{realm}
        admin_server = {controller}.{realm}
        default_domain = {realm}
    }}
'''
print(conf)

with NamedTemporaryFile() as f:
    f.write(conf.encode())
    f.flush()

    os.environ['KRB5_CONFIG'] = f.name

    user = gssapi.Name(base=username, name_type=gssapi.NameType.user)
    creds = gssapi.raw.acquire_cred_with_password(user, password.encode()).creds

    server = Server(f'{controller}.{realm}')
    conn = Connection(server, authentication=SASL, sasl_mechanism=KERBEROS,
                      sasl_credentials=(None, None, creds))
    conn.bind()

print(conn)
print(conn.extend.standard.who_am_i())

Note that the relam must be all uppercase, and the realm and the domain are the same in this example. mydomaincontroller.mydomain.com must be defined in DNS or in /etc/hosts.

The documentation for the sasl_credentials argument is in the ldap3 source code.

Alex Henrie
  • 744
  • 1
  • 6
  • 17
0

Ask your realm administrator to add proper DNS SRV records pointing at your KDCs:

_kerberos._tcp  SRV  10  0  88  kdc1
_kerberos._tcp  SRV  10  0  88  kdc2

This will let krb5 clients automatically find KDCs without manual client-side configuration. (All Active Directory domains have such records; it's not a new feature at all.)

In place of configuring default_realm, specify the realm as part of the "username" (i.e. the full Kerberos principal in user@REALM format).

user1686
  • 13,155
  • 2
  • 35
  • 54