LDAP and Active Directory on Linux: How NSS, PAM and SSSD Work Together

12 Min Read • Published on Nov 25, 2026
Tutorial contents
In this page

Most companies keep their users and groups in a directory. A Linux server that wants to let alice log in must answer two questions:

  1. Who is alice? Her UID, home directory, shell and groups.
  2. Is that really her? Check her password, Kerberos ticket or key.

On Linux, NSS answers the first, PAM the second, and SSSD is the daemon that talks to the directory for both.

About the examples
The lab for this tutorial had no directory server, so the commands and output on this page are typical, illustrative output (names such as ldap.example.com are placeholders), not captured runs. The commands and file formats are the real ones. Run them against a test server before you trust them.

LDAP in 10 minutes

LDAP (Lightweight Directory Access Protocol) is a protocol for reading and searching a directory: a tree of entries, optimised for many reads and few writes.

The tree (DIT)

dc=example,dc=com                          <- the base (the domain)
├── ou=People
│   ├── uid=alice,ou=People,dc=example,dc=com
│   └── uid=bob,ou=People,dc=example,dc=com
└── ou=Groups
    └── cn=admins,ou=Groups,dc=example,dc=com
TermMeaning
EntryOne object: a user, group, computer
DN (distinguished name)The entry’s full unique path, read right to left: uid=alice,ou=People,dc=example,dc=com
RDNIts own name inside the parent (uid=alice)
AttributeA name/value pair: mail: alice@example.com. Can have several values
objectClassWhich attributes an entry must or may have (inetOrgPerson, posixAccount)
SchemaThe definition of all classes and attributes
Base DNWhere a search starts
BindLDAP’s word for “log in” (authenticate)

An entry (LDIF)

LDIF is the text format for entries:

dn: uid=alice,ou=People,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: posixAccount
uid: alice
cn: Alice Smith
mail: alice@example.com
uidNumber: 10001
gidNumber: 10001
homeDirectory: /home/alice
loginShell: /bin/bash

posixAccount is the “Unix” part: it carries the UID, GID, home and shell that Linux needs. Directories that lack these attributes cannot supply Linux identities without extra mapping (see AD).

Searching

A search has a base, a scope, a filter and the attributes to return:

$ ldapsearch -H ldaps://ldap.example.com -D "uid=svc-sssd,ou=Services,dc=example,dc=com" -W \
    -b "ou=People,dc=example,dc=com" -s sub "(uid=alice)" uid uidNumber mail memberOf
OptionMeaning
-HServer URL
-D / -WBind DN and “prompt for the password”
-bBase DN
-sScope: base (just that entry), one (children), sub (whole subtree)
Filter(uid=alice), (&(objectClass=posixAccount)(uid=a*)), (|(mail=a*)(mail=b*)), (!(disabled=TRUE))

Filter syntax is prefix notation: operator first, in parentheses.

Security of the connection

OptionPortNotes
Plain LDAP389Cleartext passwords. Never use for binds
StartTLS389Upgrades the connection to TLS (-ZZ in tools)
LDAPS636TLS from the first byte
Anonymous and simple binds
A “simple bind” sends the password to the server. Without TLS, it is readable by anyone on the network. Require TLS, and disable anonymous binds.

This is where PKI comes in. The directory server needs a certificate (with the server’s DNS name in the SAN), and every client needs the issuing CA in its trust store. Test it the way you test any TLS service:

$ openssl s_client -connect ldap.example.com:636 -servername ldap.example.com \
    -CAfile root.crt </dev/null 2>&1 | grep -E "Verif|Protocol"
$ openssl s_client -starttls ldap -connect ldap.example.com:389 -CAfile root.crt </dev/null

“Can’t contact LDAP server” is very often a certificate problem: wrong name in the SAN, missing intermediate, expired certificate, or the client does not trust the CA.

Active Directory

Active Directory (AD) is Microsoft’s directory. It is not “just LDAP”: it is an LDAP directory + Kerberos + DNS (+ SMB file services and Group Policy), run on domain controllers (DCs).

PieceRole
LDAP (389, 636)Directory queries and changes
Kerberos (88)Authentication with tickets, no password on the wire
DNSClients find DCs through _ldap._tcp.example.com and _kerberos._tcp.example.com SRV records. If DNS is wrong, nothing works
Global Catalog (3268, 3269)A partial, forest-wide copy of the directory for searches across domains
SMB / RPCFile shares, domain join, Group Policy

Common AD terms:

TermMeaning
Domain, forestA domain is a unit of administration; a forest is a set of trusting domains
sAMAccountNameThe short legacy login (alice)
userPrincipalName (UPN)alice@example.com, the modern login
objectSidThe user’s immutable SID, the real identity. Names can change, SIDs do not
memberOfThe groups a user belongs to (including through nesting, with an extra query)
Computer accountEvery domain-joined machine has an account and a secret
OUOrganizational Unit: a folder for users, computers, and for applying policy

AD and POSIX identities

Linux needs a numeric UID and GID. AD has two ways to provide them:

  1. POSIX attributes in AD (uidNumber, gidNumber, unixHomeDirectory, loginShell), filled in by admins. SSSD setting: ldap_id_mapping = False.
  2. Algorithmic ID mapping (the SSSD default for AD): SSSD calculates the UID from the user’s SID. Each machine produces the same numbers because the algorithm is deterministic, with no AD changes needed.

Never mix the two on the same fleet. Changing it later changes every user’s UID, and every file’s owner on disk looks wrong.

The Linux side: three cooperating layers

                         ┌───────────────────────────┐
  ssh alice@server  ───► │ sshd                      │
                         └──────┬──────────┬─────────┘
                    "who is     │          │  "is the password / ticket right?"
                     alice?"    ▼          ▼
                         ┌────────┐   ┌────────┐
                         │  NSS   │   │  PAM   │
                         └───┬────┘   └───┬────┘
                             │  both call the SSSD modules
                             ▼            ▼
                         ┌───────────────────────────┐
                         │ sssd  (daemon + cache)    │
                         └──────┬──────────┬─────────┘
                       LDAP(S)  │          │ Kerberos
                                ▼          ▼
                         ┌───────────────────────────┐
                         │ AD / LDAP directory       │
                         └───────────────────────────┘

NSS: the Name Service Switch (identity)

Programs such as ls, id and chown call C library functions (getpwnam, getgrnam) to turn names into numbers and back. NSS decides where the library looks, in /etc/nsswitch.conf:

passwd:     files sss
group:      files sss
shadow:     files sss
sudoers:    files sss

Read left to right: first the local files, then SSSD. Query NSS exactly as programs do, with getent (it is the first thing to try):

$ getent passwd alice
alice:*:10001:10001:Alice Smith:/home/alice:/bin/bash
$ getent group admins
admins:*:20001:alice,bob
$ id alice
uid=10001(alice) gid=10001(alice) groups=10001(alice),20001(admins)

If getent passwd alice finds nothing, nothing else will work. Fix identity first.

Tip
ldapsearch returning the user does not prove NSS works. Always test with getent/id, because they take the same path the system takes.

PAM: Pluggable Authentication Modules (authentication)

PAM is the framework that programs (sshd, login, sudo, su, screen lockers) call to decide can this person in? Each service has a stack of modules in /etc/pam.d/, in four groups:

GroupQuestion
authIs the user who they say they are? (password, Kerberos, OTP)
accountIs the account allowed now? (expired, locked, host restrictions)
passwordChange the password
sessionSet up and tear down the session (create the home directory, log)

A typical line, and what the control flags mean:

auth    sufficient   pam_sss.so forward_pass
auth    required     pam_unix.so try_first_pass
FlagMeaning
requiredMust succeed; failure is reported at the end
requisiteMust succeed; fail immediately otherwise
sufficientIf it succeeds (and nothing required failed), stop with success
optionalOnly matters if it is the only one

pam_sss.so hands the request to SSSD, and pam_mkhomedir.so or pam_oddjob_mkhomedir.so creates the home directory at first login. Do not edit these files by hand; use the distribution’s tools:

$ sudo authselect select sssd with-mkhomedir with-sudo     # RHEL, Fedora
$ sudo pam-auth-update --enable mkhomedir                   # Debian, Ubuntu
A broken PAM stack can lock everyone out
Always keep a root session open in another terminal while changing PAM, and test with a new login before closing it.

SSSD: the System Security Services Daemon

SSSD is a daemon that sits between NSS/PAM and the directory. It:

  • talks LDAP and Kerberos for you, with TLS, connection reuse and failover between several servers (found from DNS SRV records);
  • caches users, groups and (hashed) credentials, so logins keep working when the network or DC is down, and it is fast;
  • handles the Kerberos ticket and password change;
  • supplies other services: sudo rules, SSH public keys, autofs.

It is organised as providers inside a domain:

ProviderJob
id_providerUsers and groups (NSS)
auth_providerPassword / Kerberos check (PAM auth)
access_providerWho may log in (PAM account)
chpass_providerPassword change

Joining an AD domain (the easy way)

realmd (realm) wraps the steps: it discovers the domain via DNS, creates the computer account in AD, writes the machine’s Kerberos keytab /etc/krb5.keytab, and generates sssd.conf.

$ realm discover example.com
example.com
  type: kerberos
  realm-name: EXAMPLE.COM
  domain-name: example.com
  configured: no
  server-software: active-directory
  client-software: sssd
$ sudo realm join --user=Administrator example.com
$ realm list
$ id alice@example.com
uid=1282001103(alice@example.com) gid=1282000513(domain users@example.com) groups=...

The very large UID is the algorithmic SID mapping from earlier. Requirements before you join: the machine can resolve the domain’s DNS records, its clock is within 5 minutes of the DC (Kerberos), and ports 88, 389/636, 445 and 464 are reachable.

A result of realm join is roughly this /etc/sssd/sssd.conf (mode 0600, owned by root, or SSSD refuses to start):

[sssd]
domains = example.com
services = nss, pam, ssh, sudo

[domain/example.com]
id_provider = ad
auth_provider = ad
access_provider = ad
ad_domain = example.com
krb5_realm = EXAMPLE.COM
realmd_tags = manages-system joined-with-adcli
cache_credentials = True
use_fully_qualified_names = False
fallback_homedir = /home/%u
default_shell = /bin/bash
ldap_id_mapping = True

Plain LDAP (no AD)

For OpenLDAP, 389 Directory Server or FreeIPA, use the generic provider. Never leave out TLS:

[sssd]
domains = example
services = nss, pam, ssh, sudo

[domain/example]
id_provider = ldap
auth_provider = ldap
ldap_uri = ldaps://ldap1.example.com, ldaps://ldap2.example.com
ldap_search_base = dc=example,dc=com
ldap_default_bind_dn = uid=svc-sssd,ou=Services,dc=example,dc=com
ldap_default_authtok = <service-account-password>
ldap_tls_reqcert = demand
ldap_tls_cacert = /etc/pki/tls/certs/example-root-ca.pem
cache_credentials = True
  • ldap_tls_reqcert = demand means: verify the server certificate. The tempting never turns TLS into encryption without identity, so anyone can impersonate the server. Do not use it, even “just to test”.
  • ldap_tls_cacert is the root or intermediate CA that issued the directory’s certificate: this is why PKI knowledge matters for directory work.
  • The bind password is a secret: 0600, and use a low-privilege read-only account. Prefer FreeIPA, AD with Kerberos (keytab) or a client certificate where you can.

After editing, restart and clear the cache:

$ sudo systemctl restart sssd
$ sudo sss_cache -E          # or: sssctl cache-expire -E

Kerberos in two minutes

Instead of sending a password to every service, you log in once to the KDC (the DC) and get a ticket-granting ticket (TGT). The TGT is then exchanged for a service ticket per service (SSH, NFS, a web app). Tickets have a lifetime (usually 10 hours). Machines prove themselves with the keytab.

$ kinit alice@EXAMPLE.COM
Password for alice@EXAMPLE.COM:
$ klist
Ticket cache: KCM:1000
Default principal: alice@EXAMPLE.COM

Valid starting     Expires            Service principal
11/25/26 09:00:01  11/25/26 19:00:01  krbtgt/EXAMPLE.COM@EXAMPLE.COM
$ sudo klist -k /etc/krb5.keytab     # the machine's own keys

With Kerberos single sign-on to SSH, set GSSAPIAuthentication yes on both client and server; you then log in without typing a password.

Putting it together: what happens at ssh alice@server

  1. sshd asks NSS (getpwnam("alice")). NSS asks SSSD, which checks its cache, or searches LDAP / AD, and returns UID, home and shell.
  2. sshd runs the PAM auth stack. pam_sss passes the password to SSSD, which does a Kerberos or LDAP bind against the directory.
  3. PAM account runs: access_provider rules, expired or locked accounts, allowed hosts.
  4. PAM session runs: pam_mkhomedir creates /home/alice if missing.
  5. sudo later asks NSS and SSSD for groups (%admins) to decide on privilege.

Authorization: who may log in, who may sudo

Authentication (“is it her?”) is not authorization (“may she be here?”). A default SSSD setup lets any valid directory user log in to every machine. Restrict it:

# Only these groups may log in to this host
access_provider = simple
simple_allow_groups = linux-admins, linux-users

For AD you can also use access_provider = ad with ad_access_filter = (memberOf=CN=linux-users,OU=Groups,DC=example,DC=com), or host-based rules (FreeIPA HBAC, AD GPO). For sudo, use group rules (%linux-admins ALL=(ALL) ALL in /etc/sudoers.d/) or store rules in the directory with the sudo service.

Nested groups are common in AD. memberOf does not show indirect membership by default. AD can compute it with the matching rule 1.2.840.113556.1.4.1941:

(memberOf:1.2.840.113556.1.4.1941:=CN=linux-users,OU=Groups,DC=example,DC=com)

SSH keys and SSH certificates with a directory

ApproachHowComment
Keys in the directoryAuthorizedKeysCommand /usr/bin/sss_ssh_authorizedkeys, with the public key stored in sshPublicKey or AD altSecurityIdentitiesCentralised, but keys never expire
SSH certificatesThe server trusts one CA; principals come from group membershipSSH certificates: short-lived, no per-user server config
Kerberos (GSSAPI)Single sign-on with AD ticketsGreat inside the AD network, awkward outside it

A good combined design: the directory (or your IdP, via SCIM and OIDC) remains the source of truth for who is in which group; the CA turns that into short-lived SSH or X.509 certificates; SSSD only supplies the Unix identity and group IDs on the server. That is the model behind role-based access with short-lived SSH certificates.

Troubleshooting

Work from the bottom up: network → DNS → time → TLS → directory → SSSD → NSS → PAM → sshd.

SymptomCheck
getent passwd alice emptysssctl domain-status example.com; systemctl status sssd; nsswitch.conf has sss
Works, then not after a changeStale cache: sss_cache -E
Permission denied after the correct passwordaccess_provider, group filters, account expired, pam_sss in account
Can log in only once, offlinecache_credentials and offline_credentials_expiration
Slow loginsDNS timeouts, an unreachable DC, huge nested group lookups (try ignore_group_members)
Clock skew too greatNTP/chrony: Kerberos fails past ±5 minutes
Can't contact LDAP serverFirewall, DNS, TLS: run openssl s_client as above and ldapsearch -ZZ
Wrong or changed UIDsMixed ID-mapping settings, or two domains mapped to the same range

Tools you will use constantly:

$ sssctl domain-list
$ sssctl domain-status example.com
$ sssctl user-checks alice          # shows NSS, PAM and cache views in one go
$ sudo sssctl config-check          # validates sssd.conf
$ id alice; getent group admins
$ ldapsearch -H ldaps://ldap.example.com -x -b "" -s base namingContexts   # tests TLS & reach
$ dig -t SRV _ldap._tcp.example.com
$ kinit alice && klist
$ sudo journalctl -u sssd -f

For deeper detail, set debug_level = 6 in the relevant [domain/...], [nss] and [pam] sections, restart SSSD and read /var/log/sssd/*.log. Turn it back down afterwards: debug logs can contain sensitive data.

Security checklist

  • TLS everywhere for LDAP, with verified certificates. Never ldap_tls_reqcert = never.
  • On AD, require LDAP signing and channel binding (the default on current Windows Server), which protect against relay attacks.
  • A read-only service account with the smallest search scope, and a long random password stored with 0600. Prefer keytabs and certificates.
  • Disable anonymous binds; restrict which attributes are readable.
  • Limit who can log in to which hosts. Do not rely on “everyone in the directory”.
  • Keep time in sync and DNS correct; most AD “mystery failures” are one of these.
  • Monitor and expire: the directory’s TLS certificate (a common surprise outage), the machine account password, and the keytab.
  • Treat the DCs and the directory as tier-0 assets: whoever controls them controls every login. Their CA keys and certificates deserve the same protection as any other.
  • Active Directory Certificate Services (AD CS) is Microsoft’s built-in enterprise CA. Misconfigured certificate templates are a well-known path to domain takeover. Review who can enroll, and which templates allow requesters to supply their own subject name.
  • Log authentications centrally (journald, auditd, and the DC’s security log).

About BastionXP

BastionXP is a cloud-native private PKI CA and device identity management platform that eliminates passwords and shared secrets by issuing hardware-attested certificates to mobile devices and laptops. Secure access to your Wi-Fi, VPN, and SaaS applications in your enterprise network. Replace legacy SCEP with automated ACME Device Attestation. No shared secrets. Zero credential theft. Learn more about BastionXP →

Start Your Free Trial Now

Try BastionXP for free with no commitments. No credit card required.