Digot
Digot

Reputation: 207

PHP ActiveDirectory through LDAP - How to find the name of a users primary group?

So I want to retrieve the group name of a users primary group.

I already know how to retrieve the primaryGroupID but I haven't found a field in the group class, that holds such an id.

Thats how I retrieve the primaryGroupID:

$filter = "(sAMAccountName=" . $username . ")";
$attr = array ( "primaryGroupID", "sAMAccountName" );
$result = ldap_search( $ldap, "DC=ad,DC=test,DC=local", $filter, $attr ) or exit( "Unable to search LDAP server" . ldap_error( $ldap ) );
$entries = ldap_get_entries( $ldap, $result );

Thanks in advance!

Upvotes: 1

Views: 740

Answers (1)

ChadSikorra
ChadSikorra

Reputation: 2869

The primaryGroupID is actually the RID of the group you need to get. Basically what you need to do to determine the actual group is the following:

  1. Obtain the objectSid and primaryGroupID attributes from the user.
  2. Convert the objectSid of the user to its string form.
  3. Replace the last set of digits in the string SID with the primaryGroupID
  4. Search for a group with an objectSid equal to the SID from the last step.

This is a pretty tedious task for something that pretty much never changes. But here's how I currently decode the objectSid from LDAP:

https://github.com/ldaptools/ldaptools/blob/master/src/LdapTools/AttributeConverter/ConvertWindowsSid.php

Just pass the value to the fromLdap($value) function. Then with the string version of the SID get the SID of the group like so:

$groupSid = preg_replace('/\d+$/', $primaryGroupId, $userSid);

Now using the above $groupSid you can search for a group with an objectSid equal to that.

Upvotes: 2

Related Questions