Convert String SID
Whilst working on a script to query Active Directory, I needed to be able to search by a SID. Unfortunately the SID I had was in the standard string format, which you cannot search with. So it needs to be converted, I wrote this script in PHP which will convert the standard string SID into a format that allows you to search LDAP.
Lets just jump in, no comments here but basically I split the SID at the hyphens and repack.
function convertSID($SIDstr) { $SIDbits = split('-',$SIDstr); $conSID = ''; array_shift($SIDbits); $conSID .= sprintf('%02d',dechex(array_shift($SIDbits))); $dashes = substr_count($SIDstr,'-'); $dashes = $dashes - 2; $conSID .= sprintf('%02d',dechex($dashes)); $conSID .= sprintf('%012d',sprintf('%X',array_shift($SIDbits))); $tmp = unpack("H*",(pack('I*',array_shift($SIDbits)))); $conSID .= $tmp[1]; $tmp = unpack("H*",(pack('I*',array_shift($SIDbits)))); $conSID .= $tmp[1]; $tmp = unpack("H*",(pack('I*',array_shift($SIDbits)))); $conSID .= $tmp[1]; $tmp = unpack("H*",(pack('I*',array_shift($SIDbits)))); $conSID .= $tmp[1]; $tmp = unpack("H*",(pack('I*',array_shift($SIDbits)))); $conSID .= $tmp[1]; return "\\".str_replace("\r\n","\\",rtrim(chunk_split($conSID,2))); } # Put in a proper SID here $before="S-1-5-21-1234567890-123456789-123456789-1234"; $after = convertSID($before); echo "BEFORE: $before\nAFTER: $after\n"; $ds = ldap_connect("LDAP_HOST"); ldap_bind($ds,"LDAP_USER","LDAP_PASS"); $dn = "ou=Users,dc=example,dc=com"; $sr = ldap_search($ds,$dn,"objectSid=$after",array('displayname')); $e = ldap_get_entries($ds,$sr); var_dump($e);
Based on code originally published here.