1

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
6
  • 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
    Commented Jan 19, 2020 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. Commented Jan 20, 2020 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. Commented Jan 20, 2020 at 6:32
  • 1
    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
    Commented Jan 20, 2020 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? Commented Jan 21, 2020 at 17:26

1 Answer 1

2

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.

4
  • 1
    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. Commented Jan 21, 2020 at 20:56
  • Can you authenticate with -D "$USERNAME" or in your environment does it really need to be -D "$DN"? Commented Jan 21, 2020 at 20:56
  • @roaima -D "$USERNAME" does not work. It returns 34 with "invalid DN". I use Debian 10. Commented Jan 22, 2020 at 6:00
  • Ok that's fine. I use AD-based LDAP, which is different. Commented Jan 22, 2020 at 7:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .