SBM Labs

Cyber Security Collaboration Project

Gathering information about Active Directory users
19 Jul 2014

Let's write python script in order to do simple audit of Active Directory users. We will send ldap request and save results to the file.

AD users have two similar attributes - lastLogon and lastLogonTimestamp. The first one is not replicated between DC servers and contains timestamp of last logon on the specific Domain Controller. Attribute lastLogonTimestamp is replicated between DC servers and updated as follows:

1. Get value ms-DS-Logon-Time-Sync-Interval from AD. By default it is 14.
2. User authenticates in AD.
3. Get value from user's attribute lastLogontimeStamp.
4. X = (ms-DS-Logon-Time-Sync-Interval - (random percent of 5)).
5. Y = (current date - lastLogontimeStamp).
6. If X ≤ Y then the value of attribute lastLognTimeStamp is updated and replicated between DC servers.
7. If X > Y then the value of attribute lastLognTimeStamp is not updated.

You can find python script below.

We get sAMAccountName and lastLogonTimestamp of AD users using this script.


import ldap, getpass

print " "
print "**********************"
print "****** AD Audit ******"
print "**********************"
print " "

ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, raw_input("Input path to CA certificate: "))
conn = ldap.initialize('ldaps://' + raw_input("Input LDAP server FQDN: "))
conn.simple_bind_s(raw_input("Input username: ") + '@' + raw_input("Input domain: "), getpass.getpass("Input password: "))

basedn=raw_input("Input Base DN: ")




from datetime import datetime, timedelta
def convert_ad_timestamp(timestamp):
    epoch_start = datetime(year=1601,month=1,day=1)
    seconds_since_epoch = timestamp/10**7
    return epoch_start + timedelta(seconds=seconds_since_epoch)

f = open(raw_input("Input filename: "),'a')

for entry in results:
    if 'lastLogonTimestamp' in entry[1]:
        f.write(entry[1]['sAMAccountName'][0]+' '+convert_ad_timestamp(int(entry[1]['lastLogonTimestamp'][0])).strftime("%d-%m-%y %H:%M")+'\n')



You can write python script to file. For example, After it you should do this file as executable.

$ chmod +x

Recursive search of Active Directory users
How to check DNS server for zone transfer?