LDAP – Get Object by objectGUID Using ldapsearch

ldaplinux

If I have the objectGUID attribute as returned by the ldapsearch command, how can I search the whole directory for an object with that objectGUID?

For example, if I search a user getting its objectGUID, I get the following:

$ ldapsearch -x -D $MyDn -W -h $Host -b "dc=x,dc=y" "(mail=something)" objectGUID

# 7f435ae312a0d8197605, p, Externals, x.y
dn: CN=7f435ae312a0d8197605,OU=p,DC=x,DC=y
objectGUID:: b+bSezFkKkWDmbIZiyE5rg==

Starting from the value b+bSezFkKkWDmbIZiyE5rg==, how can I create a query string to get that object?

Best Answer

This script worked for me; I'm posting it here in case it might help someone else

#!/bin/bash

# specify as first parameter the object ID as received by an LDAP query; it's base-64 encoded.
OBJECT_ID="${1}"

# we decode it, we hex-dump it and store it in an array to
# re-order it in the format expected by LDAP
BASE64_DECODED=$(echo $OBJECT_ID | base64 -d -i)
G=($(echo ${BASE64_DECODED} | hexdump -e '1/1 " %02X"'))
    OBJECTGUID="${G[3]}${G[2]}${G[1]}${G[0]}-${G[5]}${G[4]}-${G[7]}${G[6]}-${G[8]}${G[9]}-${G[10]}${G[11]}${G[12]}${G[13]}${G[14]}${G[15]}"

BIND_DN="CN=..."

# Note that we use the GUID as the search base
SEARCH_BASE="<GUID=${OBJECTGUID}>"

# we query for any object (the important point here is the search base)
QUERY="(cn=*)"

ATTRIBUTES="objectGUID userPrincipalName sAMAccountName"

ldapsearch -x -D "${BIND_DN}" -W -h x.y.com -b "${SEARCH_BASE}" "${QUERY}" ${ATTRIBUTES}