python-ldap creating a group returns "already exists" (in an empty OU and non existent sAMAccountName)

Question:

I set my ldap vars:

ldap_server = "ldaps://server:636"
ldap_username = "sec-admin@server"
ldap_pw = "<pw>"
dn = 'OU=ou1,OU=ou2,OU=ou3,OU=ou4,DC=dc1,DC=dc2,DC=dc3,DC=com'

and successfully connect to the server:

import sys
import ldap
import ldap.modlist as modlist

try:
  ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
  l = ldap.initialize(ldap_server)
  l.set_option(ldap.OPT_REFERRALS, 0)
  l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
  l.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
  l.set_option(ldap.OPT_X_TLS_DEMAND, True)
  l.set_option(ldap.OPT_DEBUG_LEVEL, 255)
  l.simple_bind_s(ldap_username, ldap_pw)
except ldap.LDAPError as e:
  print(e)

and able to search:

search_scope = ldap.SCOPE_SUBTREE
retrieve_attributes = None
search_filter = "(objectClass=group)"
try:
  l_search = l.search(dn, search_scope, search_filter, retrieve_attributes)
  result_status, result_data = l.result(l_search, 0)
  print("-----------------------------------")
  print(result_data)
  print("-----------------------------------")
except ldap.LDAPError as e:
  print(e)

which returns:

-----------------------------------
[]
-----------------------------------

but if I try to add a security group:

# creating a group
attr = {}
attr['objectClass']    = [b'group', b'top']
attr['groupType']      = b'-2147483646'
attr['cn']             = b'blah-blah-1'
attr['name']           = b'blah-blah-1'
attr['sAMAccountName'] = b'blah-blah-1'

ldif = modlist.addModlist(attr)
print(ldif)
l.add_s(dn, ldif)

I get an error:

[('objectClass', [b'group', b'top']), ('groupType', b'-2147483646'), 
 ('cn', b'blah-blah-1'), ('name', b'blah-blah-1'), 
 ('sAMAccountName', b'blah-blah-1')]

dap.ALREADY_EXISTS: {'msgtype': 105, 'msgid': 3, 'result': 68, 
'desc': 'Already exists', 'ctrls': [], 
'info': '00002071: UpdErr: DSID-030503CF, problem 6005 (ENTRY_EXISTS), data 0n'}

What do I do wrong?

Asked By: arthur

||

Answers:

If the script posted here is complete, then you’re using a duplicate DN – you’re trying to create the group object using the DN of its parent OU (which of course already exists).

The DN passed to "Add" operations must be the DN of the new object, not of its parent, as some object types (maybe not in AD schema, but commonly in other LDAP systems) can choose from several different naming attributes so the DN is not automatically determined.

Answered By: user1686