Search for "Enabled" users in net-ldap for Ruby

Neil Hoff picture Neil Hoff · Jan 3, 2013 · Viewed 17k times · Source

I am using the net-ldap gem to search active directory.
I can search for users by using filter:

filter = Net::LDAP::Filter.eq("sAMAccountName", "neil*")
filter2 = ~Net::LDAP::Filter.eq("objectclass", "computer")

joined_filter = Net::LDAP::Filter.join(filter, filter2)

ldap.search(:base => treebase, :filter => joined_filter) do |entry|
   puts entry.sAMAccountName
end

This gives me all the users whose sAMAccountName starts with neil and is not a computer account.

How do I add a filter that only searches enabled accounts?

Answer

Daro picture Daro · Jan 4, 2013

You can use the ruleOID LDAP_MATCHING_RULE_BIT_AND rule to check UserAccountControl.

I use this filter to find users that are enabled:

(&(objectCategory=organizationalPerson)(objectClass=User)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))

userAccountControl:1.2.840.113556.1.4.803 will have Bit 2 set if the account is disabled.

The value of ruleOID can be one of the following:

•1.2.840.113556.1.4.803 - This is the LDAP_MATCHING_RULE_BIT_AND rule. The matching rule is true only if all bits from the property match the value. This rule is like the bitwise AND operator.

•1.2.840.113556.1.4.804 - This is the LDAP_MATCHING_RULE_BIT_OR rule. The matching rule is true if any bits from the property match the value. This rule is like the bitwise OR operator.

An example is when you want to query Active Directory for user class objects that are disabled. The attribute that holds this information is the userAccountControl attribute. This attribute is composed of a combination of different flags. The flag for setting the object that you want to disable is UF_ACCOUNTDISABLE, which has a value of 0x02 (2 decimal). The bitwise comparison filter that specifies userAccountControl with the UF_ACCOUNTDISABLED bit set would resemble this: (UserAccountControl:1.2.840.113556.1.4.803:=2)