Brady
A moan, a groan, my life story and how me, a technically minded person just can't seem to fit in with anybody.

PHP – Get users SID from Active Directory via LDAP (objectsid)

Have you ever needed to read an AD users SID so you can use it as the unique identifier it is?

Well I did but when I read out objectsid from AD for a user I found a load of weird symbols. It turned out that the data outputted was binary data. So after some digging around to see how to translate the binary data to a human readable SID like S-1-5-21-823795046-756116320-56781596-16683 I got to work to write a PHP script that could do just that.

This is what I came up with:

[PHP]$suffix =”@sub.mydomain.co.uk”;
$base_dn = “dc=sub,dc=mydomain,dc=co,dc=uk”;
$server = “127.0.0.1″;

$USERNAME = “username”;
$PASSWORD = “password”;

$USERNAMETOSEARCH = “user to get sid”;

$ds = ldap_connect($server);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
$r = ldap_bind($ds, $USERNAME.$suffix, $PASSWORD);
$sr = ldap_search($ds, $base_dn, “(samaccountname=”.$USERNAMETOSEARCH.”)”);
$entries = ldap_get_entries($ds, $sr);

// All SID’s begin with S-
$sid = “S-”;
// Convert Bin to Hex and split into byte chunks
$sidinhex = str_split(bin2hex($entries[0]['objectsid'][0]), 2);
// Byte 0 = Revision Level
$sid = $sid.hexdec($sidinhex[0]).”-”;
// Byte 1-7 = 48 Bit Authority
$sid = $sid.hexdec($sidinhex[6].$sidinhex[5].$sidinhex[4].$sidinhex[3].$sidinhex[2].$sidinhex[1]);
// Byte 8 count of sub authorities – Get number of sub-authorities
$subauths = hexdec($sidinhex[7]);
//Loop through Sub Authorities
for($i = 0; $i < $subauths; $i++) { $start = 8 + (4 * $i); // X amount of 32Bit (4 Byte) Sub Authorities $sid = $sid.”-”.hexdec($sidinhex[$start+3].$sidinhex[$start+2].$sidinhex[$start+1].$sidinhex[$start]); } echo $sid;[/PHP] Now this is written in PHP but I’m sure this code can be pretty much be translated to any other language.