forked from byt3bl33d3r/CrackMapExec
/
cme_db.py
312 lines (234 loc) · 11.6 KB
/
cme_db.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
import cmd
import sqlite3
import sys
import os
import requests
import argparse
from requests import ConnectionError
from ConfigParser import ConfigParser
from core.database import CMEDatabase
from core.helpers import validate_ntlm
#The following disables the InsecureRequests warning and the 'Starting new HTTPS connection' log message
requests.packages.urllib3.disable_warnings()
class CMEDatabaseNavigator(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = 'cmedb > '
try:
# set the database connection to autocommit w/ isolation level
conn = sqlite3.connect('data/cme.db', check_same_thread=False)
conn.text_factory = str
conn.isolation_level = None
self.db = CMEDatabase(conn)
except Exception as e:
print "[-] Could not connect to database: {}".format(e)
sys.exit(1)
try:
self.config = ConfigParser()
self.config.read('cme.conf')
except Exception as e:
print "[-] Error reading cme.conf: {}".format(e)
def display_creds(self, creds):
print "\nCredentials:\n"
print " CredID Admin On CredType Domain UserName Password"
print " ------ -------- -------- ------ -------- --------"
for cred in creds:
# (id, credtype, domain, username, password, host, notes, sid)
credID = cred[0]
credType = cred[1]
domain = cred[2]
username = cred[3]
password = cred[4]
links = self.db.get_links(credID=credID)
print u" {}{}{}{}{}{}".format('{:<8}'.format(credID),
'{:<13}'.format(str(len(links)) + ' Host(s)'),
'{:<12}'.format(credType),
u'{:<17}'.format(domain.decode('utf-8')),
u'{:<21}'.format(username.decode('utf-8')),
u'{:<17}'.format(password.decode('utf-8')))
print ""
def display_hosts(self, hosts):
print "\nHosts:\n"
print " HostID Admins IP Hostname Domain OS"
print " ------ ------ -- -------- ------ --"
for host in hosts:
# (id, ip, hostname, domain, os)
hostID = host[0]
ip = host[1]
hostname = host[2]
domain = host[3]
os = host[4]
links = self.db.get_links(hostID=hostID)
print u" {}{}{}{}{}{}".format('{:<8}'.format(hostID),
'{:<15}'.format(str(len(links)) + ' Cred(s)'),
'{:<17}'.format(ip),
u'{:<25}'.format(hostname.decode('utf-8')),
u'{:<17}'.format(domain.decode('utf-8')),
'{:<17}'.format(os))
print ""
def do_exit(self, line):
sys.exit(0)
def do_import(self, line):
if not line:
return
if line == 'empire':
headers = {'Content-Type': 'application/json'}
#Pull the username and password from the config file
payload = {'username': self.config.get('Empire', 'username'),
'password': self.config.get('Empire', 'password')}
#Pull the host and port from the config file
base_url = 'https://{}:{}'.format(self.config.get('Empire', 'api_host'), self.config.get('Empire', 'api_port'))
try:
r = requests.post(base_url + '/api/admin/login', json=payload, headers=headers, verify=False)
if r.status_code == 200:
token = r.json()['token']
url_params = {'token': token}
r = requests.get(base_url + '/api/creds', headers=headers, params=url_params, verify=False)
creds = r.json()
for cred in creds['creds']:
if cred['credtype'] == 'token' or cred['credtype'] == 'krbtgt' or cred['username'].endswith('$'):
continue
self.db.add_credential(cred['credtype'], cred['domain'], cred['username'], cred['password'])
print "[+] Empire credential import successful"
else:
print "[-] Error authenticating to Empire's RESTful API server!"
except ConnectionError as e:
print "[-] Unable to connect to Empire's RESTful API server: {}".format(e)
def complete_import(self, text, line, begidx, endidx):
"Tab-complete 'import' commands."
commands = ["empire"]
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
return [s[offs:] for s in commands if s.startswith(mline)]
def do_hosts(self, line):
filterTerm = line.strip()
if filterTerm == "":
hosts = self.db.get_hosts()
self.display_hosts(hosts)
else:
hosts = self.db.get_hosts(filterTerm=filterTerm)
print "\nHost(s):\n"
print " HostID IP Hostname Domain OS"
print " ------ -- -------- ------ --"
hostIDList = []
for host in hosts:
hostID = host[0]
hostIDList.append(hostID)
ip = host[1]
hostname = host[2]
domain = host[3]
os = host[4]
print u" {}{}{}{}{}".format('{:<8}'.format(hostID),
'{:<17}'.format(ip),
u'{:<25}'.format(hostname.decode('utf-8')),
u'{:<17}'.format(domain.decode('utf-8')),
'{:<17}'.format(os))
print ""
print "\nCredential(s) with Admin Access:\n"
print " CredID CredType Domain UserName Password"
print " ------ -------- ------ -------- --------"
for hostID in hostIDList:
links = self.db.get_links(hostID=hostID)
for link in links:
linkID, credID, hostID = link
creds = self.db.get_credentials(filterTerm=credID)
for cred in creds:
credID = cred[0]
credType = cred[1]
domain = cred[2]
username = cred[3]
password = cred[4]
print u" {}{}{}{}{}".format('{:<8}'.format(credID),
'{:<12}'.format(credType),
u'{:<17}'.format(domain.decode('utf-8')),
u'{:<21}'.format(username.decode('utf-8')),
u'{:<17}'.format(password.decode('utf-8')))
print ""
def do_creds(self, line):
filterTerm = line.strip()
if filterTerm == "":
creds = self.db.get_credentials()
self.display_creds(creds)
elif filterTerm.split()[0].lower() == "add":
# add format: "domain username password <notes> <credType> <sid>
args = filterTerm.split()[1:]
if len(args) == 3:
domain, username, password = args
if validate_ntlm(password):
self.db.add_credential("hash", domain, username, password)
else:
self.db.add_credential("plaintext", domain, username, password)
else:
print "[!] Format is 'add domain username password"
return
elif filterTerm.split()[0].lower() == "remove":
args = filterTerm.split()[1:]
if len(args) != 1 :
print "[!] Format is 'remove <credID>'"
return
else:
self.db.remove_credentials(args)
self.db.remove_links(credIDs=args)
elif filterTerm.split()[0].lower() == "plaintext":
creds = self.db.get_credentials(credtype="plaintext")
self.display_creds(creds)
elif filterTerm.split()[0].lower() == "hash":
creds = self.db.get_credentials(credtype="hash")
self.display_creds(creds)
else:
creds = self.db.get_credentials(filterTerm=filterTerm)
print "\nCredential(s):\n"
print " CredID CredType Domain UserName Password"
print " ------ -------- ------ -------- --------"
credIDList = []
for cred in creds:
credID = cred[0]
credIDList.append(credID)
credType = cred[1]
domain = cred[2]
username = cred[3]
password = cred[4]
print u" {}{}{}{}{}".format('{:<8}'.format(credID),
'{:<12}'.format(credType),
u'{:<17}'.format(domain.decode('utf-8')),
u'{:<21}'.format(username.decode('utf-8')),
u'{:<17}'.format(password.decode('utf-8')))
print ""
print "\nAdmin Access to Host(s):\n"
print " HostID IP Hostname Domain OS"
print " ------ -- -------- ------ --"
for credID in credIDList:
links = self.db.get_links(credID=credID)
for link in links:
linkID, credID, hostID = link
hosts = self.db.get_hosts(hostID)
for host in hosts:
hostID = host[0]
ip = host[1]
hostname = host[2]
domain = host[3]
os = host[4]
print u" {}{}{}{}{}".format('{:<8}'.format(hostID),
'{:<17}'.format(ip),
u'{:<25}'.format(hostname.decode('utf-8')),
u'{:<17}'.format(domain.decode('utf-8')),
'{:<17}'.format(os))
print ""
def complete_creds(self, text, line, begidx, endidx):
"Tab-complete 'creds' commands."
commands = [ "add", "remove", "hash", "plaintext"]
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
return [s[offs:] for s in commands if s.startswith(mline)]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("path", nargs='?', type=str, default='data/cme.db', help="path to CME database (default: data/cme.db)")
args = parser.parse_args()
if not os.path.exists(args.path):
print 'Path to CME database invalid'
sys.exit(1)
try:
cmedbnav = CMEDatabaseNavigator()
cmedbnav.cmdloop()
except KeyboardInterrupt:
pass