Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Get SID from Linux ldapsearch in Active Directory

With the help of a fantastic post on ServerFault, here is a way to find a user's SID in string format from an ldapsearch against Active Directory.

#!/bin/sh
# Filename: get_sid.sh
# Author: YasithaB
# Startdate: 2018-02-14 15:58
# Title: Script that Converts Sid from AD Ldap Hexadecimal into String
# Purpose: Help convert sid to usable value
# History:
#    2018-02-15 Modified to work with kornshell
# Usage:
#    ldapsearch -b 'dc=prod,dc=example,dc=com' -s 'sub' -x -D 'CN=My Username,OU=Domain Users,DC=prod,DC=example,DC=com' -W -H 'ldaps://adds2.prod.example.com:636' '(cn=Target Username)' objectSid | grep -E '^objectSid:' | awk '{print $2}' | ./get_sid.sh --stdin
# Reference:
#    https://serverfault.com/questions/851864/get-sid-by-its-objectsid-using-ldapsearch/852338#852338
# Improve:
# Document: Below this line
# Base-64 encoded objectSid
test -z "${OBJECT_ID}" && OBJECT_ID="AQUAAAAAAAUVAAAAPWW1S5rojK4mDAiG5BAAAA=="
case "${1}" in
   "--stdin" ) read OBJECT_ID ;;
   "") : ;;
   *) OBJECT_ID="${1}" ;;
esac
# Decode it, hex-dump it and store it in an array
H="$( printf '%s' $OBJECT_ID | base64 -d -i | hexdump -v -e '1/1 "%02X"' )"
# SID Structure: https://technet.microsoft.com/en-us/library/cc962011.aspx
# LESA = Little Endian Sub Authority
# BESA = Big Endian Sub Authority
# LERID = Little Endian Relative ID
# BERID = Big Endian Relative ID
BESA2=${H:16:8}
BESA3=${H:24:8}
BESA4=${H:32:8}
BESA5=${H:40:8}
BERID=${H:48:10}
LESA1=${H:4:12}
LESA2=${BESA2:6:2}${BESA2:4:2}${BESA2:2:2}${BESA2:0:2}
LESA3=${BESA3:6:2}${BESA3:4:2}${BESA3:2:2}${BESA3:0:2}
LESA4=${BESA4:6:2}${BESA4:4:2}${BESA4:2:2}${BESA4:0:2}
LESA5=${BESA5:6:2}${BESA5:4:2}${BESA5:2:2}${BESA5:0:2}
LERID=${BERID:6:2}${BERID:4:2}${BERID:2:2}${BERID:0:2}
SID="S-1-$((16#$LESA1))-$((16#$LESA2))-$((16#$LESA3))-$((16#$LESA4))-$((16#$LESA5))-$((16#$LERID))"
echo "${SID}"

Comments