Created
May 21, 2025 14:56
-
-
Save joshfinley/2f2112f458a447404a0083c73fd72362 to your computer and use it in GitHub Desktop.
Use ldapsearch to get the domain SID and convert to readable format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Usage: ./get_domain_sid.sh <BASE_DN> [LDAP_HOST] [BIND_DN] [BIND_PW] | |
# | |
# Examples: | |
# ./get_domain_sid.sh "DC=example,DC=com" ldap.example.com "cn=admin,dc=example,dc=com" "password" | |
# ./get_domain_sid.sh "DC=example,DC=com" ldap.example.com | |
# ./get_domain_sid.sh "DC=example,DC=com" | |
BASEDN="$1" | |
LDAPHOST="${2:-localhost}" | |
BINDDN="$3" | |
BINDPW="$4" | |
if [ -z "$BASEDN" ]; then | |
echo "Usage: $0 <BASE_DN> [LDAP_HOST] [BIND_DN] [BIND_PW]" | |
exit 1 | |
fi | |
# Run ldapsearch | |
if [ -n "$BINDDN" ] && [ -n "$BINDPW" ]; then | |
BASE64SID=$(ldapsearch -x -LLL -H "ldap://$LDAPHOST" -D "$BINDDN" -w "$BINDPW" -b "$BASEDN" "(objectClass=domain)" objectSid | grep '^objectSid::' | awk '{print $2}') | |
else | |
BASE64SID=$(ldapsearch -x -LLL -H "ldap://$LDAPHOST" -b "$BASEDN" "(objectClass=domain)" objectSid | grep '^objectSid::' | awk '{print $2}') | |
fi | |
if [ -z "$BASE64SID" ]; then | |
echo "Failed to retrieve objectSid." | |
exit 1 | |
fi | |
# Convert base64 to hex | |
HEX=$(echo "$BASE64SID" | base64 -d | xxd -p | tr 'a-f' 'A-F') | |
# Parse SID | |
REV=$(echo "$HEX" | cut -c3-4) | |
IDAUTH=$(echo "$HEX" | cut -c5-16) | |
IDAUTH_DEC=$((16#${IDAUTH})) | |
SUBCOUNT=$((16#$REV)) | |
SUBAUTHS_HEX=$(echo "$HEX" | cut -c17-) | |
SID="S-1-${IDAUTH_DEC}" | |
for ((i=0; i<$SUBCOUNT; i++)); do | |
PART=$(echo "$SUBAUTHS_HEX" | cut -c$((i*8+1))-$((i*8+8))) | |
REV_PART=$(echo "$PART" | sed 's/../& /g' | awk '{print $4$3$2$1}') | |
SID="$SID-$((16#$REV_PART))" | |
done | |
echo "$SID" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment