-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfind_expiring_users_in_ad.py
More file actions
192 lines (159 loc) · 7.94 KB
/
Copy pathfind_expiring_users_in_ad.py
File metadata and controls
192 lines (159 loc) · 7.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/python3
#filename: find_expiring_users.py
#description: use python to query get_secrets and get password from AWS secrets. Then query AD to find out what accounts are expiring.
# Use this code snippet in your app.
# If you need more information about configurations or implementing the sample code, visit the AWS docs:
# https://aws.amazon.com/developers/getting-started/python/
import boto3
import base64
from botocore.exceptions import ClientError
def get_secret():
secret_name = "arn:aws:secretsmanager:us-east-1:663434348:secret:test-admin-XHB1"
region_name = "us-east-1"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
# In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
# See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
# We rethrow the exception by default.
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
if e.response['Error']['Code'] == 'DecryptionFailureException':
# Secrets Manager can't decrypt the protected secret text using the provided KMS key.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InternalServiceErrorException':
# An error occurred on the server side.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidParameterException':
# You provided an invalid value for a parameter.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidRequestException':
# You provided a parameter value that is not valid for the current state of the resource.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'ResourceNotFoundException':
# We can't find the resource that you asked for.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
#print(secret) # debug pass <- We use this one
secret = secret.split(':')[1].replace("}"[-1],"").replace("\"","") #clean up string
#print("final:'" + secret + "'")
#for key,value in secret.items():
# print(key, '->', value )
# return (value)
return secret #return password
else:
decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
print(secret) # Debug password
# Your code goes here.
# Math to convert MS time to Unix time
# AD's date format is 100 nanosecond intervals since Jan 1 1601 in GMT.
# To convert to seconds, divide by 10000000.
# To convert to UNIX, convert to positive seconds and subtract 1164473600 to be seconds since Jan 1 1970 (epoch).
def convert_time(ad_time):
# A value of 0 or 0x7FFFFFFFFFFFFFFF (9223372036854775807) indicates that the account never expires.
# FIXME: Better handling of account-expires!
if ad_time == "9223372036854775807":
ad_time = "0"
ad_seconds = (int(ad_time) / 10000000)
#return ((int(ad_seconds) + 11644473600) if int(ad_seconds) != 0 else 0)
return ((int(ad_seconds) - 11644473600) if int(ad_seconds) != 0 else 0)
mysecret=get_secret()
##############
#MAIN area
#query ldap using ldap3
##############
import re
import datetime
import ldap3
from ldap3 import Server, Connection, SAFE_SYNC, SUBTREE
server= Server('domaincontroller.example.net')
print("ldapserver",server)
user=('CN=LDAP Linux,OU=Service Accounts,OU=Non-Expiring Password Users,OU=Special Policies,DC=example,DC=net')
conn=Connection(server,user,mysecret, client_strategy=SAFE_SYNC, auto_bind=True)
# paged search wrapped in a generator
total_entries = 0
entry_generator = conn.extend.standard.paged_search(search_base = 'DC=example,DC=net',
search_filter = '(objectClass=user)',
search_scope = SUBTREE,
attributes = ['UserPrincipalName', 'Name', 'mail', 'msDS-UserPasswordExpiryTimeComputed' ],
paged_size = 5,
generator=False)
# for entry in entry_generator:
# total_entries += 1
# #print(entry)
# #parsing dict
# for key,value in entry.items():
# if ( key == 'dn' ):
# if re.search(r'(?i)OU=Users', value) or re.search(r'(?i)OU=Administrators', value) :
# print ("----------------------------------------")
# dn=value
# else:
# dn=''
# if ( key == 'attributes' and dn != '') :
# print("dn:", dn)
# print("name:",value['name'])
# print("key:",value['UserPrincipalName'])
# if ( len(value['mail']) > 2 ):
# print("email:", value['mail'])
# else:
# print("email: empty email for -> ",dn)
# mytime = value['msDS-UserPasswordExpiryTimeComputed']
# epoch_time=convert_time(mytime)
# print("expiration epoch:",epoch_time)
# print("expiration:",datetime.datetime.fromtimestamp(epoch_time))
# now_seconds=datetime.datetime.today().timestamp()
# days_remaining=( (epoch_time - now_seconds) / ( 60 * 60 * 24) )
# print("remaining:", days_remaining)
total_expiring = 0
for entry in entry_generator:
total_entries += 1
#print(entry)
#parsing dict
for key,value in entry.items():
if ( key == 'dn' ):
if re.search(r'(?i)OU=Users', value) or re.search(r'(?i)OU=Administrators', value) :
dn=value
else:
dn=''
if ( key == 'attributes' and dn != '') :
mytime = value['msDS-UserPasswordExpiryTimeComputed']
epoch_time=convert_time(mytime)
#print("expiration epoch:",epoch_time)
#print("expiration:",datetime.datetime.fromtimestamp(epoch_time))
now_seconds=datetime.datetime.today().timestamp()
seconds_remaining = epoch_time - now_seconds
days_remaining=( (seconds_remaining ) / ( 60 * 60 * 24) ) # days left
if ( days_remaining < 10 and days_remaining > -20 ):
print ("----------------------------------------")
total_expiring += 1
print("dn:", dn)
print("name:",value['name'])
print("key:",value['UserPrincipalName'])
if ( len(value['mail']) > 2 ):
print("email:", value['mail'])
else:
print("email: empty email for -> ",dn)
print("remaining days:", days_remaining) # days remaining
print("remaining seconds:", seconds_remaining ) #seconds remaining
#convert to end time in human readable format
myend=datetime.datetime.fromtimestamp(seconds_remaining+now_seconds).strftime("%A, %B %d, %Y %I:%M:%S")
print("final date:", myend )
print('Total expring:', total_expiring)
#print('Total entries retrieved:', total_entries)
#print("connection info")
#print (conn.search)