-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautomation-ADGetUser.yml
328 lines (307 loc) · 12.8 KB
/
automation-ADGetUser.yml
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
commonfields:
id: ADGetUser
version: -1
name: ADGetUser
script: |-
import re
UserAccountControlFlags = {
'SCRIPT': 0x0001,
'ACCOUNTDISABLE': 0x0002,
'HOMEDIR_REQUIRED': 0x0008,
'LOCKOUT': 0x0010,
'PASSWD_NOTREQD': 0x0020,
'PASSWD_CANT_CHANGE': 0x0040,
'ENCRYPTED_TEXT_PWD_ALLOWED': 0x0080,
'TEMP_DUPLICATE_ACCOUNT': 0x0100,
'NORMAL_ACCOUNT': 0x0200,
'INTERDOMAIN_TRUST_ACCOUNT': 0x0800,
'WORKSTATION_TRUST_ACCOUNT': 0x1000,
'SERVER_TRUST_ACCOUNT': 0x2000,
'DONT_EXPIRE_PASSWORD': 0x10000,
'MNS_LOGON_ACCOUNT': 0x20000,
'SMARTCARD_REQUIRED': 0x40000,
'TRUSTED_FOR_DELEGATION': 0x80000,
'NOT_DELEGATED': 0x100000,
'USE_DES_KEY_ONLY': 0x200000,
'DONT_REQ_PREAUTH': 0x400000,
'PASSWORD_EXPIRED': 0x800000,
'TRUSTED_TO_AUTH_FOR_DELEGATION': 0x1000000,
'PARTIAL_SECRETS_ACCOUNT': 0x04000000
}
limit = 20
if demisto.get(demisto.args(), 'limit'):
limit = demisto.args()['limit']
def escapeSpecialCharacters(s):
return re.sub(r'([\()])', lambda r : '\\' + r.group(), s)
def createAccountEntities(t,attrs):
accounts = []
for l in t:
account = {}
account['Type'] = 'AD'
account['ID'] = demisto.get(l,'dn')
account['Email'] = {'Address':demisto.get(l,'mail')}
account['Username'] = demisto.get(l,'samAccountName')
account['DisplayName'] = demisto.get(l,'displayName')
account['Manager'] = demisto.get(l,'manager')
account['Groups'] = demisto.get(l,'memberOf').split('<br>') if demisto.get(l,'memberOf') else ''
for attr in set(argToList(attrs)) - set(['dn','mail','name','displayName','memberOf']):
account[attr.title()] = demisto.get(l,attr)
accounts.append(account)
return accounts
def prettifyDateTimeADFields(resAD):
try:
for m in resAD:
if isError(m):
continue
m['ContentsFormat'] = formats['table']
for f in [ 'lastlogon' , 'lastlogoff' , 'pwdLastSet' , 'badPasswordTime' , 'lastLogonTimestamp' ]:
if f not in m['Contents'][0]:
continue
if m['Contents'][0][f] == "0":
m['Contents'][0][f] = "N/A"
else:
try:
m['Contents'][0][f] = FormatADTimestamp( m['Contents'][0][f] )
except:
pass # Could not prettify timestamp - return as is
for f in [ 'whenChanged' , 'whenCreated' ]:
try:
m['Contents'][0][f] = PrettifyCompactedTimestamp( m['Contents'][0][f] )
except:
pass # Could not prettify timestamp - return as is
return resAD
except Exception as ex:
return { 'Type' : entryTypes['error'], 'ContentsFormat' : formats['text'], 'Contents' : 'Error occurred while parsing output from ad command. Exception info: ' + str(ex) + '\nInvalid output:\n' + str( resAD ) }
def translateUserAccountControl(resAD, userAccountControlOut):
try:
for m in resAD:
if isError(m) or not demisto.get(m, 'Contents') or not isinstance(m['Contents'], list):
continue
if 'UserAccountControl' not in m['Contents'][0] or m['Contents'][0]['UserAccountControl'] == "":
continue
if userAccountControlOut:
accountControlFlags = []
for flag, mask in UserAccountControlFlags.iteritems():
if int(m['Contents'][0]['UserAccountControl'],10) & mask != 0:
accountControlFlags.append(flag)
m['Contents'][0]['UserAccountControl'] = ', '.join(accountControlFlags)
else:
m['Contents'][0]['ACCOUNTDISABLE'] = int(m['Contents'][0]['UserAccountControl'],10) & 2 != 0
return resAD
except Exception as ex:
return { 'Type' : entryTypes['error'], 'ContentsFormat' : formats['text'], 'Contents' : 'Error occurred while parsing output from ad command. Exception info: ' + str(ex) + '\nInvalid output:\n' + str( resAD ) }
def listAll(attrs, using, userAccountControlOut):
args = {}
args['filter'] = "(objectClass=User)"
args['attributes'] = attrs
args['size-limit'] = limit
args['using-brand'] = 'activedir'
if using:
args['using'] = using
resAD = getADSearchResp(args)
if isError(resAD[0]) or isinstance(demisto.get(resAD[0],'Contents'), str) or isinstance(demisto.get(resAD[0],'Contents'), unicode):
return resAD
else:
resAD = prettifyDateTimeADFields(resAD)
resAD = translateUserAccountControl(resAD, userAccountControlOut)
return resAD
def getGroups(userDN):
queryValue = escapeSpecialCharacters(userDN)
group_attrs = 'name'
filterstr = r"(&(member{0}=".format(':1.2.840.113556.1.4.1941:') + queryValue + ")(objectcategory=group))"
args = {
'filter' : filterstr,
'attributes' : group_attrs,
'size-limit' : limit,
'using-brand' : 'activedir'
}
group_resp = getADSearchResp(args)
if isError(group_resp[0]):
return group_resp
try:
data = demisto.get(group_resp[0],'Contents')
data = data if isinstance(data, list) else [data]
memberOf = ",".join([demisto.get(k,'dn') for k in data])
return memberOf
except Exception as e:
return ""
def queryBuilder(queryType,queryValue,attrs,nested,using, userAccountControlOut):
args = {}
args['size-limit'] = limit
args['using-brand'] = 'activedir'
if using:
args['using'] = using
filterstr = r"(&(objectClass=User)({0}={1}))".format(queryType, queryValue)
args['filter'] = filterstr
args['attributes'] = attrs
resp = getADSearchResp(args)
if isError(resp) or isinstance(demisto.get(resp[0],'Contents'), str) or isinstance(demisto.get(resp[0],'Contents'), unicode):
return resp
if nested:
for index,user in enumerate(resp[0]['Contents']):
memberOf = getGroups(user["dn"])
if memberOf:
resp[0]['Contents'][index]['memberOf'] = memberOf
resp = prettifyDateTimeADFields(resp)
resp = translateUserAccountControl(resp, userAccountControlOut)
return resp
def getADSearchResp(args):
try:
return demisto.executeCommand( 'ad-search', args )
except Exception as e:
if 'Unsupported Command' in str(e):
return_error('No instances of "Active Directory Query" are configured.\nIf you are trying to run "ADGetUser" with "Active Directory Query V2", please use the aquivilant command "ad-get-user" instead.')
raise e
attrs = 'dn,name,displayName,memberOf,mail,samAccountName,manager,UserAccountControl,ACCOUNTDISABLE,provider'
queryValue, queryType = "",""
headers = argToList(demisto.get(demisto.args(), 'headers'))
userAccountControlOut = False
nestedSearch = True if demisto.get(demisto.args(), 'nestedSearch') == 'true' else False
if demisto.get(demisto.args(), 'attributes'):
attrs += "," + demisto.args()['attributes']
if demisto.get(demisto.args(), 'userAccountControlOut'):
userAccountControlOut = demisto.args()['userAccountControlOut'] == 'true'
if demisto.get(demisto.args(), 'dn'):
queryValue = demisto.args()['dn']
queryType = "distinguishedName"
elif demisto.get(demisto.args(), 'name'):
queryValue = demisto.args()['name']
queryType = "name"
elif demisto.get(demisto.args(), 'username'):
queryValue = demisto.args()['username']
queryType = "samAccountName"
elif demisto.get(demisto.args(), 'email'):
queryValue = demisto.args()['email']
queryType = "mail"
elif demisto.get(demisto.args(), 'customFieldType'):
if not demisto.get(demisto.args(), 'customFieldData'):
demisto.results({ 'Type' : entryTypes['error'], 'ContentsFormat' : formats['text'], '' : 'To do custom search, both "customFieldType" and "customFieldData" should be provided' })
else:
queryValue = demisto.args()['customFieldData']
queryType = demisto.args()['customFieldType']
resp = None
if queryValue and queryType:
resp = queryBuilder(queryType,escapeSpecialCharacters(queryValue),attrs,nestedSearch,demisto.get(demisto.args(),'using'), userAccountControlOut)
else:
resp = listAll(attrs, demisto.get(demisto.args(),'using'), userAccountControlOut)
if isError(resp):
demisto.results(resp)
else:
found = False
for response in resp:
context = {}
data = demisto.get(response,'Contents')
if isinstance(data, str) or isinstance(data, unicode) :
if data == 'No results':
continue
found = True
md = data
else:
data = data if isinstance(data, list) else [data]
found = True
md = tableToMarkdown("Active Directory User", data, headers)
context['Account(val.Email && val.Email === obj.Email || val.ID && val.ID === obj.ID || val.Username && val.Username === obj.Username)'] = createAccountEntities(data,attrs)
if len(data) > 0 and demisto.get(data[0], 'name'):
context['DBotScore'] = {'Indicator': data[0]['samAccountName'], 'Type': 'username', 'Vendor': 'AD', 'Score': 0, 'isTypedIndicator': True}
demisto.results({'Type' : entryTypes['note'],
'Contents': data,
'ContentsFormat' : formats['json'],
'HumanReadable': md,
'ReadableContentsFormat' : formats['markdown'],
'EntryContext' : context})
if not found:
demisto.results({'Type' : entryTypes['note'],
'Contents': resp,
'ContentsFormat' : formats['json'],
'HumanReadable': 'No results found for user',
'ReadableContentsFormat' : formats['markdown'],
'EntryContext' : {}})
type: python
tags:
- active directory
- enhancement
- username
comment: |-
Use Active Directory to retrieve detailed information about a user account. The user can be specified by name, email or as an Active Directory Distinguished Name (DN).
If no filter is provided, the result will show all users.
enabled: true
system: true
args:
- name: dn
default: true
description: Active Directory Distinguished Name for the desired user
- name: name
description: Name of the desired user
- name: attributes
description: Include these AD attributes of the resulting objects in addition to
the default ones
- name: customFieldType
description: Search user by this custom field type
- name: customFieldData
description: Search user by this custom field data (relevant only if `customFieldType`
is provided)
- name: headers
description: The columns headers to show by order
- name: nestedSearch
auto: PREDEFINED
predefined:
- "true"
- "false"
description: ' Enter ''true'' to allow nested groups search as well'
- name: username
description: samAccountName of the desire user
- name: limit
description: Maximum number of objects to return (default is 20)
- name: email
description: mail attribute of desire user
- name: userAccountControlOut
auto: PREDEFINED
predefined:
- "true"
- "false"
description: Include verbose translation for UserAccountControl flags
- name: using
description: Select instance name
outputs:
- contextPath: Account
description: Active Directory Account
- contextPath: Account.Type
description: Type of the Account entity
type: string
- contextPath: Account.ID
description: The unique Account DN (Distinguished Name)
type: string
- contextPath: Account.Username
description: The Account username
type: string
- contextPath: Account.Email
description: The email object associated with the Account
- contextPath: Account.Groups
description: The groups the Account is part of
type: string
- contextPath: Account.DisplayName
description: The Account display name
type: string
- contextPath: Account.Manager
description: The Account's manager
type: string
- contextPath: Account.Email.Address
description: The email address object associated with the Account
type: string
- contextPath: DBotScore.Indicator
description: The indicator value
type: string
- contextPath: DBotScore.Type
description: The indicator's type
type: string
- contextPath: DBotScore.Vendor
description: The indicator's vendor
type: string
- contextPath: DBotScore.Score
description: The indicator's score
type: number
scripttarget: 0
dependson:
must:
- activedir|||ad-search
runonce: false