python-ldap creating a group - python

I'm trying to create a security group in AD from a python script with python-ldap.
I'm able to bind my user which has sufficient rights to perform such an operation (confirmed by creating the group from ADExplorer gui client) and search the domain, but when it comes to adding the new group it fails with:
ldap.INSUFFICIENT_ACCESS: {'info': '00000005: SecErr: DSID-03152492, problem 4003 (INSUFF_ACCESS_RIGHTS), data 0\n', 'desc': 'Insufficient access'}
This is the script:
import ldap
import ldap.modlist as modlist
server = 'hidden'
user_dn = 'hidden'
user_pw = 'hidden'
fs_dn = 'ou=fssecuritygroups,ou=tkogroups,ou=tokyo,dc=unit,dc=xyz,dc=intra'
l = ldap.initialize("ldaps://"+server)
l.bind_s(user_dn, user_pw)
groupname = 'mytestfs'
attr = {}
attr['objectClass'] = ['group','top']
attr['groupType'] = '-2147483646'
attr['cn'] = groupname
attr['name'] = groupname
attr['sAMAccountName'] = groupname
ldif = modlist.addModlist(attr)
print(l.add_s(fs_dn,ldif))

I got the same error when I try to add a new object under a dn where I am not allowed to add.
E.g. I have access rights to the ldap-server (binding works), I'm allowed to add group-objects under ou=germany,ou=groups,dc=ACME - but I'm not allowed to add a group-object under ou=groups,dc=ACME.
Maybe you checkout the constraints of the ldap or the like.

Related

Python3 LDAP query to get name and email of a specific group

I would like to get the users' name and email of a specific group when querying an LDAP server using ldap3 Python library.
I have been trying the following command, but I am not getting also the email address.
c.search(search_base=LDAP_BASE,search_filter=("(&(objectclass=group)(cn=test-group))"),attributes=["*"])
Any idea how to get have this filter to retrieve the desired data?
This query is not retrieving also the email address.
Thank you.
If everyone needs the same query, here is the answer:
# Firstly find out the DN associated with LDAP group
c.search(base_dn, '(sAMAccountName="test-group")',
search_scope=SUBTREE, attributes=['distinguishedName', 'member'])
dn_json = json.loads(c.response_to_json())
distinguished_name = dn_json["entries"][0]["attributes"]["distinguishedName"]
# Retrieve data based on DN
c.search(base_dn, '(&(objectclass=user)(memberOf={}))'.format(distinguished_name),
attributes=["givenName", "sn", "mail"])
user_data = json.loads(c.response_to_json())
for index in range(len(user_data["entries"])):
first_name = user_data["entries"][index]["attributes"]["givenName"]
surname = user_data["entries"][index]["attributes"]["sn"]
mail = user_data["entries"][index]["attributes"]["mail"]

Query for user in AD using python

I am trying to write a python script to validate if a username exists in a particular domain or not .
To query :
username -- > anandabhis
domain name --> example.com
Output : Successfully verified .
For this I have used python-ldap module to connect to LDAP server . But I am unable to proceed further even after reading lots of documentations.
import ldap
def test_login(self):
domain = 'EXAMPLE'
server = 'ldap-001.example.com'
admin_username = 'admin'
admin_password = 'secret-password'
connection = ldap.initialize('ldap://{0}'.format(server))
connection.protocol_version = 3
connection.set_option(ldap.OPT_REFERRALS, 0)
connection.simple_bind_s('{0}\{1}'.format(domain, admin_username), admin_password)
search_username = 'anandabhis'
A simple search for the sAMAccountName of the user should allow you to get the attributes of the user.
user_filter = '(sAMAccountName={})'.format(search_username)
base_dn = 'DC={},DC=com'.format(domain)
result = connection.search_s(base_dn, ldap.SCOPE_SUBTREE, user_filter)
print result

Adding AD group with python-ldap

I am trying to create group within AD with no success, below is my code:
import ldap
import ldap.modlist as modlist
LDAPserver = 'hidden'
LDAPlogin = 'hidden'
LDAPpassword = 'hidden'
l = ldap.initialize('ldap://' + LDAPserver)
l.simple_bind_s(LDAPlogin, LDAPpassword)
dn = 'OU=someunit,OU=someunit,OU=someunit,OU=someunit,DC=my-company,DC=local'
attrs = {}
attrs['objectclass'] = ['top','Group']
attrs['cn'] = 'group name to be created'
attrs['description'] = 'Test Group'
ldif = modlist.addModlist(attrs)
l.add_s(dn,ldif)
l.unbind_s()
Following snippet gives me an error:
ldap.INSUFFICIENT_ACCESS: {'info': '00000005: SecErr: DSID-031521D0, problem 4003
(INSUFF_ACCESS_RIGHTS), data 0\n', 'desc': 'Insufficient access'}
However, using same credentials I can create group with some UI tools like LDAP Admin
so I suppose that I have proper permissions to create groups, but still no success with python-ldap.
I can also query existing groups and fetch its members via script.
I believe that the problem is in my attributes, maybe Active Directory need some different values to be inserted into attrs variable. AD is running under Win Server 2012 R2.
Any help would be appreciated :)
The dn should actually be CN=<groupname> + base_dn, so in your case something like
dn = 'CN=groupname,OU=someunit,OU=someunit,OU=someunit,OU=someunit,DC=my-company,DC=local'
Please try to replace LDAPlogin to a full bind dn value such as
"cn=hidden,dc=example,dc=com"

How do I connect dbus and policykit to my function in python?

I am making a python application that has a method needing root privileges. From https://www.freedesktop.org/software/polkit/docs/0.105/polkit-apps.html, I found Example 2. Accessing the Authority via D-Bus which is the python version of the code below, I executed it and I thought I'd be able to get root privileges after entering my password but I'm still getting "permission denied" on my app. This is the function I'm trying to connect
import dbus
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
authority = dbus.Interface(proxy, dbus_interface='org.freedesktop.PolicyKit1.Authority')
system_bus_name = bus.get_unique_name()
subject = ('system-bus-name', {'name' : system_bus_name})
action_id = 'org.freedesktop.policykit.exec'
details = {}
flags = 1 # AllowUserInteraction flag
cancellation_id = '' # No cancellation id
result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)
print result
In the python code you quoted, does result indicate success or failure? If it fails, you need to narrow down the error by first of all finding out what the return values of bus, proxy, authority and system_bus_name are. If it succeeds, you need to check how you are using the result.

Unable to authenticate ,enable the user in active Directory ,the user account created by using python ldap

Here i'm attached the python files to create user and authenticating user in windows active Directory 2008 r2
create.py
import ldap
import ldap.modlist as modlist
name='testing3'
password='p#ssw0rd'
l = ldap.initialize('ldap://##2.168.3#.##')
l.simple_bind_s('Administrator#example.local', 'p#ssw0rd1')
dn="cn="+name+",ou=oli,dc=example,dc=local"
attrs = {}
attrs['objectclass'] = ['Top','person','organizationalPerson','user']
attrs['cn'] = name
attrs['displayName'] = name
attrs['name'] = name
attrs['givenName'] = name
attrs['mail'] = name
attrs['ou'] = "Users"
#attrs['pwdLastSet'] = "-1"
attrs['userPrincipalName'] = name + "#naanal.local
attrs['userAccountControl'] = '514'
attrs['sAMAccountName'] = name
attrs['userPassword'] = password
ldif = modlist.addModlist(attrs)
l.add_s(dn,ldif)
l.unbind_s()
Using this program create user in the Active directory but unable to create the enabled user account. i can user the userAccountcontrol=''512` but it not working .userAccountcontrol='514' its working but user account was disabled.
using ldap modify change the userAccountcontrol getting error "when i'm try to enable the user account getting error "{'info': '0000052D: SvcErr: DSID-031A120C, problem 5003 (WILL_NOT_PERFORM), data 0\n', 'desc': 'Server is unwilling to perform'}""
Authe.py
import ldap
username='shan'
password='p#ssw0rd'
LDAP_SERVER = 'ldap://###.##.##.##'
LDAP_USERNAME = '%s#example.local' % username
LDAP_PASSWORD = password
base_dn = 'DC=example,DC=example'
ldap_filter = 'userPrincipalName=%s#example.local' % username
attrs = ['memberOf']
try:
ldap_client = ldap.initialize(LDAP_SERVER)
ldap_client.set_option(ldap.OPT_REFERRALS,0)
ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
print 'successfull'
except ldap.INVALID_CREDENTIALS:
ldap_client.unbind()
print 'Wrong username ili password'
except ldap.SERVER_DOWN:
print 'AD server not awailable'
create the user account using create.py .then enable the user account manually in the active directory.after i'm try to authenticate the created user account not detected.but manually created account detected by using authe.py file
i'm using Ubuntu 14.04 64 bit
There are two problems with your code:
Active Directory stores the password in the unicodePwd attribute and not userPassword. See this link for more details. This article also explains how the value for unicodePwd must be encoded (UTF-16)
The other problem (this is also explained in the referenced article) is that you must connect over a secure connection to Active Directory whenever you are making changes to the password attribute (including creating a user). The URL starting with ldap:// makes me believe that your connection is not secure.
I hope this helps.

Categories

Resources