Skip to content
Jennifer Programming Language

ldap - LDAP v3 client and directory server

Import with import "ldap.j" as ldap;. An LDAP v3 client and a lightweight, in-memory directory server (RFC 4511). The wire messages are ASN.1 BER, built and parsed with the asn1 library; the transport is net TCP, with LDAPS / StartTLS through net's TLS. SASL SCRAM binds reuse the sasl module; the mutable server directory is backed by the kv store. Needs the default jennifer binary (net).

jennifer
import "ldap.j" as ldap;
import "transport.j" as transport;
use io;

def c as ldap.Conn init ldap.connect("localhost:389", transport.Security.Starttls);
ldap.bind($c, "cn=admin,dc=example,dc=org", "secret");
def hits as list of ldap.Entry init ldap.search($c,
    "ou=people,dc=example,dc=org", ldap.SCOPE_SUB,
    ldap.parseFilter("(uid=alice)"), ["cn", "mail"]);
for (def e in $hits) {
    io.printf("%s -> %s\n", $e.dn, ldap.firstValue($e, "mail"));
}
ldap.unbind($c);

Runnable: examples/modules/ldap_demo.j.

Values

Entries, attributes, and results come back as small structs:

jennifer
export def struct Conn { handle as net.Conn, timeoutMs as int,
    security as transport.Security, allowInsecureAuth as bool };
export def struct Attribute { name as string, values as list of string };
export def struct Entry { dn as string, attributes as list of Attribute };
export def struct Result { code as int, matchedDn as string, message as string };

An Entry is a DN plus multi-valued attributes. Read an attribute with ldap.values(entry, name) (a list of string, case-insensitive name) or ldap.firstValue(entry, name) (the first value, or ""). A Result carries the LDAP result code - ldap.SUCCESS (0) on success, ldap.INVALID_CREDENTIALS (49) on a failed bind.

Client

Connecting

ldap.connect(address, security) opens a connection; security is a transport.Security value:

jennifer
import "ldap.j" as ldap;
import "transport.j" as transport;

def a as ldap.Conn init ldap.connect("dir.example.org:389", transport.Security.None);      # plaintext
def b as ldap.Conn init ldap.connect("dir.example.org:636", transport.Security.Tls);       # LDAPS
def c as ldap.Conn init ldap.connect("dir.example.org:389", transport.Security.Starttls);  # StartTLS

transport.Security.Starttls connects in plaintext and upgrades in-band via the StartTLS extended operation (or call ldap.startTls(conn) yourself and use the Conn it returns, whose security is then Starttls). ldap.close closes without an unbind; ldap.unbind sends an unbind request and closes. Each read and write times out after Conn.timeoutMs (5000 ms by default).

Both TLS modes verify the server certificate against the system roots and the host name. For a directory with a private CA or a self-signed certificate, pass a net.TLSOptions to ldap.connectWith(address, security, tls) (or ldap.startTlsWith(conn, tls)): caCert is a PEM certificate to trust in place of the system roots (the server is still authenticated), skipVerify accepts any certificate (insecure: no server authentication, for testing only). A zero net.TLSOptions is plain connect.

jennifer
use fs;
use net;

def t as net.TLSOptions;
$t.caCert = fs.readBytes("/etc/ssl/corp-ca.pem");
def d as ldap.Conn init ldap.connectWith("dir.corp.example:636", transport.Security.Tls, $t);

A password is never sent over a plaintext (transport.Security.None) connection by default: a simple bind with a password, and a passwordModify carrying one, throw an LdapError (code 0) before anything is sent. Use Tls or Starttls, or, for a trusted link such as loopback, opt in on the connection with $c.allowInsecureAuth = true;. An anonymous bind and a SASL SCRAM bind (which never sends the password) are not affected.

Binding

jennifer
def r as ldap.Result init ldap.bind($c, "cn=admin,dc=example,dc=org", "secret");
if ($r.code == ldap.SUCCESS) { io.printf("bound\n"); }

ldap.bind performs a simple bind and returns the Result; it does not throw on a bad password, so check .code. An empty DN and password is an anonymous bind. A non-empty DN with an empty password is refused before anything is sent (an LdapError, kind "ldap", code 0): RFC 4513 section 5.1.2 makes it an unauthenticated bind, which many servers answer with success without checking anything, so a login form with an empty password field would look logged in. ldap.bindSasl(conn, algo, user, password) performs a SASL SCRAM bind (algo "sha1" or "sha256"), verifying the server signature.

Searching and filters

ldap.search(conn, baseDn, scope, filter, attributes) returns the matching entries; an empty attributes list requests all user attributes. scope is one of ldap.SCOPE_BASE, ldap.SCOPE_ONE, or ldap.SCOPE_SUB.

Build the filter from an RFC 4515 string with ldap.parseFilter, or from the constructors:

jennifer
import "ldap.j" as ldap;
use asn1;

def f1 as asn1.Value init ldap.parseFilter("(&(objectClass=person)(uid=alice))");
def f2 as asn1.Value init ldap.allOf([ldap.equals("objectClass", "person"), ldap.present("mail")]);

A value spliced into a filter string from untrusted input must be escaped with ldap.escapeFilterValue (\, *, (, ) and NUL become \5c, \2a, \28, \29, \00), or (uid= + *)(objectClass=* turns one lookup into a search of everything. The constructors take raw values and need no escaping. parseFilter decodes \XX escapes (a \2a is a literal star, not a wildcard) and refuses groups nested more than 64 deep. The string must be exactly one filter: text after it ((uid=a)x), an unescaped ( in a value or an item without an attribute is an LdapError.

jennifer
def name as string init "ada";   # untrusted input, e.g. a login form field
def f3 as asn1.Value init ldap.parseFilter("(uid=" + ldap.escapeFilterValue($name) + ")");
ConstructorFilter
ldap.equals(attr, value)(attr=value)
ldap.present(attr)(attr=*)
ldap.greaterOrEqual(attr, value)(attr>=value)
ldap.lessOrEqual(attr, value)(attr<=value)
ldap.approx(attr, value)(attr~=value)
ldap.substrings(attr, initial, anyParts, final)(attr=initial*any*final)
ldap.allOf(filters)(&(...)(...))
ldap.anyOf(filters)`(
ldap.negate(filter)(!(...))

ldap.searchPaged(conn, baseDn, scope, filter, attributes, pageSize) pulls large result sets a page at a time via the simple-paged-results control.

The replies of one search (every page of a searchPaged) are capped at transport.MAX_RECEIVED_BYTES (64 MiB) in total, and each message at 16 MiB; past either the search throws kind "limit".

Attribute values come back as strings. A binary value (one that is not valid UTF-8 - Active Directory objectGUID / objectSid, userCertificate, jpegPhoto) is returned base64-encoded (the LDIF convention) rather than throwing; decode it with encoding.fromText("base64", value).

Writing

The write operations return a Result (check .code against ldap.SUCCESS):

jennifer
ldap.add($c, "uid=jdoe,ou=people,dc=example,dc=org", {
    "objectClass": ["inetOrgPerson"], "uid": ["jdoe"], "cn": ["J Doe"], "mail": ["jdoe@example.org"]
});
ldap.modify($c, "uid=jdoe,ou=people,dc=example,dc=org", [
    ldap.change(ldap.MOD_REPLACE, "mail", ["j.doe@example.org"]),
    ldap.change(ldap.MOD_ADD, "description", ["created via ldap"])
]);
ldap.modifyDn($c, "uid=jdoe,ou=people,dc=example,dc=org", "uid=jd", true, "");   # rename (newSuperior "" keeps the parent)
ldap.passwordModify($c, "uid=jd,ou=people,dc=example,dc=org", "oldpw", "newpw"); # RFC 3062
ldap.delete($c, "uid=jd,ou=people,dc=example,dc=org");

ldap.change(operation, name, values) builds one modify change; operation is ldap.MOD_ADD, ldap.MOD_DELETE, or ldap.MOD_REPLACE (an empty value list on MOD_DELETE removes the whole attribute). ldap.passwordModify uses the RFC 3062 extended operation - pass userDn "" for the currently-bound user, oldPassword "" for an administrative reset, and newPassword "" to have the server generate one (do it over TLS). These operations require a directory server that accepts writes; the built-in server is read-only over LDAP.

Active Directory notes

The client works against Active Directory over LDAPS or StartTLS with a simple bind (user@domain, DOMAIN\user, or a full DN). AD caps a result set at 1000 rows, so use ldap.searchPaged for large searches (it sends AD's required paged control). Bind to a specific domain controller, or the Global Catalog on port 3268, to avoid referrals. AD's native SASL is Kerberos (GSSAPI), which this module does not implement - use simple bind over TLS. Change a password with ldap.passwordModify over TLS (AD requires an encrypted connection for it).

Server

The server answers simple bind and search for an in-memory directory. It is read-only over the LDAP protocol: add, modify, delete, modifyDN and compare get their response with result code 53 (unwillingToPerform) and the session goes on; but your own code can mutate the directory: it is a shared kv-backed store, so a web interface or a database sync can update it while the server runs and the change is visible immediately. There is no schema enforcement and no ACLs.

Building a directory

jennifer
def dir as ldap.Directory init ldap.directory([
    ldap.entry("uid=alice,ou=people,dc=example,dc=org", {
        "objectClass": ["inetOrgPerson", "person"],
        "uid": ["alice"], "cn": ["Alice A"], "mail": ["alice@example.org"],
        "userPassword": [ldap.password("ssha", "secret")]
    }),
    ldap.group("cn=admins,ou=groups,dc=example,dc=org", ["uid=alice,ou=people,dc=example,dc=org"])
]);

ldap.directory is in-memory. For a directory that persists across restarts, use ldap.openDirectory(path) instead: it is backed by a kv.openFile store, so every edit is written to disk. A new file starts empty; seed it on first run by checking ldap.listEntries and ldap.addEntry-ing when it is empty.

ldap.entry(dn, attrs) builds an entry from a map of string to list of string; ldap.group(dn, members) builds a groupOfNames (its cn is taken from the DN's RDN). ldap.password(scheme, plain) hashes a password into a userPassword value; an unknown scheme is an LdapError. scheme is:

schemestored formnotes
"plain"cleartexttesting only
"sha" / "ssha"{SHA} / {SSHA}SHA-1 (salted with 8 random bytes); fast hash, interop only
"sha256" / "ssha256"{SHA256} / {SSHA256}SHA-256 (salted with 8 random bytes); still a fast hash
"pbkdf2"{PBKDF2-SHA256}$iterations$salt$hashrecommended - a slow KDF (PBKDF2 through crypto.deriveKey, 100000 iterations)
"pbkdf2-sha512"{PBKDF2-SHA512}$...slow KDF over SHA-512

The {SHA} / {SSHA} names follow the OpenLDAP / RFC 2307 convention for interop, but they are fast hashes - weak for password storage even when salted. Prefer "pbkdf2" unless you need to interoperate with a directory that expects {SSHA}. The server's bind check accepts every scheme.

The server never returns userPassword in search results, even when it is requested by name, and never matches it in a filter: every filter item on it ((userPassword=...), a substring, =*, ordering, by name or OID 2.5.4.35) evaluates to Undefined (RFC 4511 4.5.1.7), so a search cannot be used to guess the stored value one character at a time.

Mutating a live directory

jennifer
ldap.addEntry($dir, ldap.entry("uid=bob,ou=people,dc=example,dc=org", {"uid": ["bob"]}));  # insert / replace by DN
ldap.modifyEntry($dir, $entry);                                                   # replace by DN
ldap.setAttribute($dir, "uid=bob,ou=people,dc=example,dc=org", "mail", ["bob@example.org"]);
ldap.deleteEntry($dir, "uid=bob,ou=people,dc=example,dc=org");
def e as ldap.Entry init ldap.getEntry($dir, "uid=bob,ou=people,dc=example,dc=org");
def all as list of ldap.Entry init ldap.listEntries($dir);
def ok as bool init ldap.hasEntry($dir, "uid=bob,ou=people,dc=example,dc=org");

The directory can be built from a database at startup and kept in sync by your own admin tooling while the server serves auth requests from it. The edits are serialised by a lock that every copy of the Directory value shares, so tasks may edit it concurrently without losing writes. Open a file-backed directory once and share that value: a second openDirectory of the same path has its own lock.

Serving

jennifer
def dir as ldap.Directory init ldap.directory([]);   # or entries, as above
ldap.serve($dir, ":389");   # blocks, one spawn per connection

For a stoppable server, drive the listener yourself: ldap.listen(address) -> net.Listener, ldap.serveOn(dir, listener) runs the accept loop until the listener is closed (close it from another task to stop).

Configuring Authelia against this server

Authelia can use the Jennifer LDAP server as its authentication backend. Build a directory with an admin bind account, a people subtree, and a groups subtree:

jennifer
import "ldap.j" as ldap;

def dir as ldap.Directory init ldap.directory([
    ldap.entry("cn=admin,dc=example,dc=org", {
        "objectClass": ["person"], "cn": ["admin"],
        "userPassword": [ldap.password("ssha", "adminpassword")]
    }),
    ldap.entry("uid=alice,ou=people,dc=example,dc=org", {
        "objectClass": ["inetOrgPerson"], "uid": ["alice"],
        "cn": ["Alice A"], "displayName": ["Alice A"], "mail": ["alice@example.org"],
        "userPassword": [ldap.password("ssha", "alicepassword")]
    }),
    ldap.group("cn=admins,ou=groups,dc=example,dc=org", ["uid=alice,ou=people,dc=example,dc=org"])
]);
ldap.serve($dir, ":389");

Then point Authelia's authentication_backend.ldap at it:

yaml
authentication_backend:
  ldap:
    address: 'ldap://127.0.0.1:389'
    implementation: 'custom'
    base_dn: 'dc=example,dc=org'
    additional_users_dn: 'ou=people'
    additional_groups_dn: 'ou=groups'
    users_filter: '(&({username_attribute}={input})(objectClass=inetOrgPerson))'
    username_attribute: 'uid'
    display_name_attribute: 'displayName'
    mail_attribute: 'mail'
    groups_filter: '(&(member={dn})(objectClass=groupOfNames))'
    group_name_attribute: 'cn'
    user: 'cn=admin,dc=example,dc=org'
    password: 'adminpassword'

Authelia binds as the user account, searches users_filter under additional_users_dn for the login name, binds again as the found user DN to check the password, then searches groups_filter for the user's groups - all of which this server answers. Put TLS in front (transport.Security.Tls on a 636 listener, or a reverse proxy) before exposing it beyond localhost. The same setup works for any LDAP-authenticating application; Authelia is one example.

PAM authentication

A Jennifer program can also be a system authentication helper for Linux PAM via pam_exec.so, which passes the username in the PAM_USER environment variable and (with expose_authtok) the password on stdin, then reads the helper's exit code (0 = allow). examples/modules/pam_auth.j is a ready-made helper that binds against this directory to authenticate; point a /etc/pam.d/<service> auth line at it (auth sufficient pam_exec.so expose_authtok quiet /path/to/pam_auth.j). It fails closed: a missing user, an empty password, or an unreachable server denies. Its checkCredentials can be repointed at a kvstore or a PBKDF2-hash file instead of LDAP.

Errors

Client and server failures throw an ldap.LdapError (kind "ldap"): a malformed reply, a refused StartTLS, a failed SASL bind or search, a password over plaintext without allowInsecureAuth. A socket failure stays a net.NetError (kind "net"), and the generic kinds pass through as they are: "timeout", "closed", "cancelled", and "limit" for a message over 16 MiB or a search over 64 MiB.

LdapError fieldMeaning
kindalways "ldap"
messageldap: and what failed, with the result code and diagnostic when the server sent them
codethe server's LDAP result code (32 noSuchObject, 50 insufficientAccessRights, ...); 0 when the failure is not a server result
matchedDnthe matched DN of the server's result, "" when none
diagnosticthe server's diagnostic message, "" when none

LDAP-level result codes on a bind (such as a bad password) are returned in the Result, not thrown.

Academy talks

TalkWhat it shows
Network toolbox: SNMP, NTP, LDAP and IP addressessearching users and groups and checking passwords with bind over TLS

API reference

Every exported function, struct and constant of ldap, with its signature, generated from the module's doc comments: the ldap API reference.