Tom's FreeBSD blog

July 21, 2010

Finding a user’s primary group in AD

Filed under: Active Directory — tmclaugh @ 1:30 pm

Active Directory is at its heart LDAP and Kerberos on steroids.

2 Comments »

  1. Thanks for posting the algorithm. Here is a PHP implementation (note that PHP pack/unpack do not support 64-bit int, so this uses bcmath):

    function sid2str($sid)
    {
    $srl = ord($sid[0]);
    $number_sub_id = ord($sid[1]);
    $x = substr($sid,2,6);
    $h = unpack(‘N’,”\x0\x0″.substr($x,0,2));
    $l = unpack(‘N’,substr($x,2,6));
    $iav = bcadd(bcmul($h[1],bcpow(2,32)),$l[1]);
    for ($i=0; $i<$number_sub_id; $i++)
    {
    $sub_id = unpack('V', substr($sid, 8+4*$i, 4));
    $sub_ids[] = $sub_id[1];
    }
    return sprintf('S-%d-%d-%s', $srl, $iav, implode('-',$sub_ids));
    }

    function get_primary_group($server, $admin, $passwd, $base, $username)
    {
    global $server, $admin, $passwd, $connect, $r;
    $connect = ldap_connect($server);
    ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
    $bind = ldap_bind($connect, $admin, $passwd) or exit('bind');

    $r = ldap_search($connect, $base, "sAMAccountName=$username", array('primaryGroupID')) or exit('ldap_search');
    $data = ldap_get_entries($connect, $r);
    $pri_grp_rid = $data[0]['primarygroupid'][0];
    print("pri_grp_rid = ${pri_grp_rid}\n");
    $r = ldap_read($connect, $base, '(objectclass=*)', array('objectSid')) or exit('ldap_search');
    $data = ldap_get_entries($connect, $r);
    $domain_sid = $data[0]['objectsid'][0];

    $domain_sid_s = sid2str($domain_sid);
    print("domain_sid_s = ${domain_sid_s}\n");

    $r = ldap_search($connect, $base, "objectSid=${domain_sid_s}-${pri_grp_rid}", array('cn')) or exit('ldap_search');
    $data = ldap_get_entries($connect, $r);
    print("cn = {$data[0]['cn'][0]}\n");
    }

    Comment by Chris — October 5, 2010 @ 8:14 am

  2. Related.. Trackback…

    [...]the time to read or visit the content or sites we have linked to below the[...]…

    Trackback by Buy Guaranteed Facebook Fans — December 2, 2011 @ 3:56 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress