0

I am writing a bash script that needs ldap authenticate to do the next steps. However, I have not found a tool that can auth ldap and return whether the username and password are true. Is there a existing program that can help me do this?

The script is like

read USERNAME
read -s PASSWD
LDAP_AUTH_RESULT="$(<ldapauth> <USERNAME> <PASSWD/prompt-passwd>)"
if [[ $LDAP_AUTH_RESULT == "$SUCCESS_FLAG" ]]; then
<things to do>
fi
  • If all you're doing for your authentication is to see if the username/password is valid in AD, you can use ldapsearch and see what the return code is. A result of 0 means a successfull connection. Are you saying that once authenticated, the commands need to run as the authenticated user? – cutrightjm Jan 19 at 5:38
  • @cutrightjm I only need to verify whether the username and password are correct. The following commands will be run by the original user. – Steven Yang Jan 20 at 6:29
  • I used ldapsearch -x -s sub "uid=<username> -W" to try to authenticate, but it seems that it is requiring the password of LDAP admin, instead of the specified user's. – Steven Yang Jan 20 at 6:32
  • Try this syntax, substituting everything after CN= to your account's AD CN. ldapsearch -d -1 -x -H ldaps://dc1.domain.co.uk -D "CN=username,OU=ou-to-use,DC=domain,DC=com" – cutrightjm Jan 20 at 14:35
  • @cutrightjm This command works, thanks. But on our ldap server, CN is full name such as "CN=John Smith" (and "uid=john"). Is it possible to specify the username with uid? – Steven Yang Jan 21 at 17:26
1

Thanks to @cutrightjm for your hints in the comment. Current I am using such script

#!/bin/bash

printf "Enter LDAP Username:"
read USERNAME
DN=$(ldapsearch -x -H ldaps://ldap.example.com -s sub "uid=${USERNAME}" | grep 'dn: ' | sed 's/dn: //g')
ldapsearch -H ldaps://ldap.example.com -D "${DN}" -W > /dev/null
EXITCODE=$?
if [[ ${EXITCODE} -eq 0 ]]; then
    echo "Auth success"
else
    echo "Auth failed"
    exit ${EXITCODE}
fi

It is tested to work, but I am not sure whether there are any security issues.

| improve this answer | |
  • Minor improvement... printf ; read can be read -p "Enter LDAP Username: " USERNAME, and your grep | sed can be replaced with sed -n 's/^dn: //p'. I'd recommend from a style perspective that all variables should be lowercase rather than uppercase. – roaima Jan 21 at 20:56
  • Can you authenticate with -D "$USERNAME" or in your environment does it really need to be -D "$DN"? – roaima Jan 21 at 20:56
  • @roaima -D "$USERNAME" does not work. It returns 34 with "invalid DN". I use Debian 10. – Steven Yang Jan 22 at 6:00
  • Ok that's fine. I use AD-based LDAP, which is different. – roaima Jan 22 at 7:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.