Skip to content

Instantly share code, notes, and snippets.

@calum-github
Last active July 23, 2020 23:35
Show Gist options
  • Save calum-github/02ba06d50eb61945a0baa712be59fcae to your computer and use it in GitHub Desktop.
Save calum-github/02ba06d50eb61945a0baa712be59fcae to your computer and use it in GitHub Desktop.
AD Plugin UID calculation from ObjectGUID
#!/bin/bash
#
# Author: Calum Hunter
# Date: 28/11/2016
# Version: 1.0
# Purpose: To generate a Mac UID from the objectGUID attribute
# (GeneratedUID) in AD.
# This uses the same method that the Apple
# AD Plugin uses
#
## Start by loading up our ldap query variables
SVC_ACCOUNT_NAME="Username"
SVC_ACCOUNT_PASS="Password"
DOMAIN="my.domain"
LDAP_SERVER="dc.my.domain:389"
SEARCH_BASE="CN=John\, Smith,OU=Users,DC=MY,DC=DOMAIN"
DECODE_BASE64(){
# This function takes the encoded output from ldapsearch and decodes it
# It then needs to be "hex-dumped" in order to get it into regular text
# So that we can work with it
OBJECT_ID="$1"
BASE64_DECODED=$(echo $OBJECT_ID | base64 -D)
G=($(echo ${BASE64_DECODED} | hexdump -e '16/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]}"
}
# Search LDAP for our user account
RESULT=$(ldapsearch -LLL -H ldap://$LDAP_SERVER -o ldif-wrap=no -x -D ${SVC_ACCOUNT_NAME}@$DOMAIN -w ${SVC_ACCOUNT_PASS} -b "${SEARCH_BASE}" \
-s sub -a always "(objectClass=user)" "objectGUID")
# Get our user DN and objectGUID from the result above.
USER_DN=$(echo "$RESULT" | grep "dn:")
USER_GUID_BASE64=$(echo "$RESULT" | awk -F "::" '/objectGUID/ {print $2}')
# Get our GeneratedUID from LDAPSEARCH by decoding and hex dumping it
DECODE_BASE64 "$USER_GUID_BASE64"
# Now lets get the first 32 bits of our GUID
GUID_32=${OBJECTGUID:0:8}
# Now convert this to decimal
GUID_32_DEC=$(echo "ibase=16; $GUID_32" | bc)
# Check if this is greater than the largest decimal figure allowed for a mac UID (32Bit Integer)
if [ $GUID_32_DEC -gt 2147483647 ]; then
# Get the first character of our 32bit GUID
FIRST_CHAR=${GUID_32:0:1}
# Use the below table to replace the first character with number it represents. ie: A=2
case $FIRST_CHAR in
A)
NUMBER=2 ;;
B)
NUMBER=3 ;;
C)
NUMBER=4 ;;
D)
NUMBER=5 ;;
E)
NUMBER=6 ;;
F)
NUMBER=7 ;;
9)
NUMBER=1 ;;
8)
NUMBER=0 ;;
*)
esac
# Now lets replace the first character with our new number
A=$(echo $GUID_32 | cut -c2-)
NEW_32_GUID="${NUMBER}${A}"
GUID_32_DEC=$(echo "ibase=16; $NEW_32_GUID" | bc)
fi
# Echo our output
echo "User: $(echo $USER_DN | awk -F "dn:" '{print $2}')"
echo "ObjectGUID: $OBJECTGUID"
echo "Mac UID: $GUID_32_DEC"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment