Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Active Directory user password in Python 3.x

I am trying to make a Python script that will open an LDAP connection to a server running AD, take a search entry (in this case a name), search for that entry and change that users password to a randomly generated password (as well as set the option to change password on logon) and then send them an automated secure email containing the new temporary password.

So far I have been able to connect to the server, and search for a single DN which returns. The temporary password is being generated, and an email is being sent (although the password is not hashed, and the email is not secure yet). However, I cannot find any information on where to go from here.

I have found Change windows user password with python however I see that this does not play well with AD, and the other LDAP in Python documentation I have been finding seems to be outdated from 2.x and no longer works. The documentation for ldap3 (https://media.readthedocs.org/pdf/ldap3/stable/ldap3.pdf) also doesnt seem to really mention anything for it, and exhaustive Googling has been fruitless. I am new to this kind of programming having only low level or academic knowledge previously, so this has been a bit frustrating but Python is my strongest language.

----------------EDITED CODE TO CURRENT STATUS-----------------------

#Takes input for name which will be used for search criterion
zid = input("ZID: ")
zid = str(zid).lower()
print(zid)

#Binds session to the server and opens a connection
try:
    server = ldap3.Server('ldap://<IP_Address>', get_info=all)
    conn = ldap3.Connection(server, '%[email protected]' %zid, password = "<something>", auto_bind=True) 
    print("Successfully bound to server.\n")
except:
    print("Unsucessful initialization of <IP_Address>")
    try:
        server = ldap3.Server('ldap://<IP_Address>', get_info=all)
        conn = ldap3.Connection(server, '%[email protected]' %zid, password = "<something>", auto_bind=True) 
        print("Successfully bound to server.\n")
    except:
        print("Unsucessful initialization of <IP_Address>")
        try:
            server = ldap3.Server('ldap://<IP_Address>', get_info=all)
            conn = ldap3.Connection(server, '%[email protected]', password = "<something>", auto_bind=True) %zid 
            print("Successfully bound to server.\n")
        except:
            print("Unsucessful initialization of <IP_Address>")
            sys.exit(0)

#Searches and prints LDAP entries
try:
    base_dn = 'DC=<something>,DC=<something>,DC=<something>,DC=<something>,DC=com'
    zid_filter = '(sAMAccountName=%s)' %zid
    conn.search(base_dn, zid_filter, attributes=['mail'])

    #i.e. "DN: CN=<First Last>,OU=<something>, DC= <something>
    user_dn = str(conn.entries)

    #i.e. "CN=<First Last>"
    front = user_dn.find('C')
    back = user_dn.find(',')
    user_cn = user_dn[front:back]

    #i.e. "<First Last>"
    display_name = user_cn[3:]

    #i.e. "first.last@<something>.com"
    raw_email = str(conn.entries)
    front = raw_email.find('mail: ')
    back = raw_email.find('@<something>.com')
    user_email = raw_email[front + 6:back] + '@<something>.com'
except:
    print("Could not search entries")

#Generates random 12 digit alpha-numeric password
try:
    new_password = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(12))
    print(new_password)
    print("New password successfully generated")
except:
    print("New password could not be generated")


#Set and replace AD Password
try:
    conn.extend.microsoft.modify_password(user_dn, None, new_password)
    print ("Active Directory password was set successfully!")
except:
    print('Error setting AD password')
    sys.exit(0)

Any suggestions on how to get/set the user password and hash the password for security purposes during this whole ordeal? For the email I imagine I can force it to use HTTPS and that would be sufficient, but the connection to the server passing the new_password to I would like to secure.

like image 942
woundjuice Avatar asked Mar 12 '23 23:03

woundjuice


2 Answers

ldap3 contains a specific method for changing AD password, just add the following after you generated a new password:

dn = conn.entries[0].entry_get_dn() # supposing you got back a single entry conn.extend.microsoft.modify_password(dn, None, new_password)

This should properly encode the password and store it in AD.

like image 160
cannatag Avatar answered Mar 24 '23 11:03

cannatag


This code is working with Windows 2012 R2 AD:

First, install latest ldap3:

sudo pip3 install ldap

#!/usr/bin/python3

import ldap3

SERVER='127.0.0.1'
BASEDN="DC=domain,DC=com"
USER="[email protected]"
CURREENTPWD="current_password"
NEWPWD="new_password"

SEARCHFILTER='(&(userPrincipalName='+USER+')(objectClass=person))'

USER_DN=""
USER_CN=""

ldap_server = ldap3.Server(SERVER, get_info=ldap3.ALL)
conn = ldap3.Connection(ldap_server, USER, CURREENTPWD, auto_bind=True)
conn.start_tls()
print(conn)

conn.search(search_base = BASEDN,
         search_filter = SEARCHFILTER,
         search_scope = ldap3.SUBTREE,
         attributes = ['cn', 'givenName', 'userPrincipalName'],
         paged_size = 5)

for entry in conn.response:
    if entry.get("dn") and entry.get("attributes"):
        if entry.get("attributes").get("userPrincipalName"):
            if entry.get("attributes").get("userPrincipalName") == USER:
                USER_DN=entry.get("dn")
                USER_CN=entry.get("attributes").get("cn")

print("Found user:", USER_CN)

if USER_DN:
    print(USER_DN)
    print(ldap3.extend.microsoft.modifyPassword.ad_modify_password(conn, USER_DN, NEWPWD, CURREENTPWD,  controls=None))
else:
    print("User DN is missing!")
like image 22
Tamas Tobi Avatar answered Mar 24 '23 12:03

Tamas Tobi