Searching Active Directory With ldapsearch

Searching Active Directory With ldapsearch

I spent another 30 minutes today digging through bookmarks and Stack Overflow posts in order to re-learn how to use ldapsearch from Linux to validate that internal access to my AD domain was working for the purposes of app authentication. To keep from having to re-learn this (for the 5th or 6th time) again the next time I need it, and for those learning it for the first time, I figured a blog post was in order.

What follows are the steps to search Active Directory from a Linux terminal using ldapsearch:

  1. (Debian-based) Install the ldap-utils package: apt-get install ldap-utils
  2. (Optional) If you're configuring permanent access to your domain for authentication, user lookup, or something else, you should create a user account specifically for this purpose. A dedicated user account also makes it easier to track access via event logging. This user account does not need any special access - membership in the Domain Users group is sufficient.
  3. For the purposes of this article, we'll assume the following:
    • The dedicated user account for searching your domain is called "ldap_user" and is located in the built-in Users Organizational Unit (OU).
    • You have a custom OU called "My Users" that contains the user accounts you're searching for.
    • The UID of the specific user you're searching for is "matt".
  4. Given those assumptions, our command will be:
    ldapsearch -x -D "CN=ldap_user,OU=Users,DC=example,DC=com" \ -W -H ldap://dc.example.com -b "OU=My Users,DC=example,DC=com" \ -s sub "uid=matt"

Breaking down the parameters to ldapsearch:
-x - Use simple authentication instead of SASL
-D - Full directory path to the bind user, "ldap_user"
-W - Prompt for the bind user's password.
-H - URL of the LDAP server (non-SSL for simplicity); use "ldaps://" for SSL.
-b - The search base - our "My Users" OU.
-s - The search scope; in this case, "sub" for recursive.
"uid=matt" - Our search filter, looking for a user with the UID attribute "matt".

If successful, the search will return results similar to the following:

# extended LDIF
#
# LDAPv3
# base <OU=My Users,DC=example,DC=com> with scope subtree
# filter: uid=matt
# requesting: ALL
#

# Matt, My Users, example.com
dn: CN=Matt,OU=My Users,DC=example,DC=com
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: user
cn: Matt 
sn: 
c: US
l: Lake St. Louis
st: MO
...

One other note - for the purposes of this article, I used simple authentication and a plain-text connection to the directory. In the real world, you would want to require SASL authentication and LDAPS. You can find more information about designing, implementing, securing, and maintaining Active Directory over in the members area.

Happy Searching!