Investigating PowerShell Attacks PRESENTED BY: © Mandiant, A FireEye Company. All rights reserved. Investigating PowerShell Attacks Defcon 2014 (Pre-Conference Draft) Ryan Kazanciyan, Matt Hastings © Mandiant, A FireEye Company. All rights reserved. Background Case Study 2 Attacker Client Victim VPN WinRM, SMB, NetBIOS Victim workstations, servers � Fortune 100 organization � Compromised for > 3 years � Active Directory � Authenticated access to corporate VPN � Command-and-control via � Scheduled tasks � Local execution of PowerShell scripts � PowerShell Remoting © Mandiant, A FireEye Company. All rights reserved. It  can  do  almost  anything… Why PowerShell? 3 Execute commands Reflectively load / inject code Download files from the internet Enumerate files Interact with the registry Interact with services Examine processes Retrieve event logs Access .NET framework Interface with Win32 API © Mandiant, A FireEye Company. All rights reserved. � PowerSploit � Reconnaissance � Code execution � DLL injection � Credential harvesting � Reverse engineering � Nishang � Posh-SecMod � Veil-PowerView � Metasploit � More  to  come… PowerShell Attack Tools 4 © Mandiant, A FireEye Company. All rights reserved. PowerShell Malware in the Wild 5 © Mandiant, A FireEye Company. All rights reserved. Investigation Methodology 6 evil.ps1 Local PowerShell script backdoor.ps1 Persistent PowerShell Registry File System Event Logs Memory Network Traffic Sources of Evidence WinRM PowerShell Remoting © Mandiant, A FireEye Company. All rights reserved. � Has admin (local or domain) on target system � Has network access to needed ports on target system � Can use other remote command execution methods to: � Enable execution of unsigned PS scripts � Enable PS remoting Attacker Assumptions 7 © Mandiant, A FireEye Company. All rights reserved. Version Reference 8 2.0 3.0 4.0 Default Default (R2)Default Default Default (SP1) Default (R2 SP1) Requires WMF 3.0 Update Requires WMF 3.0 Update Requires WMF 4.0 Update Requires WMF 4.0 Update Requires WMF 4.0 Update Memory Analysis © Mandiant, A FireEye Company. All rights reserved. � Scenario: Attacker interacts with target host through PowerShell remoting � What’s  left  in  memory  on  the  accessed  system? � How can you find it? � How long does it persist? Memory Analysis 10 © Mandiant, A FireEye Company. All rights reserved. WinRM Process Hierarchy 11 Invoke-Command {c:\evil.exe} Client wsmprovhost.exe svchost.exe (DcomLaunch) evil.exe wsmprovhost.exe Get-ChildItem C:\ svchost.exe (WinRM) Remote Host Invoke-Command {Get-ChildItem C:\} Kernel Invoke-Mimikatz.ps1 © Mandiant, A FireEye Company. All rights reserved. Remnants in Memory 12 wsmprovhost.exe svchost.exe (DcomLaunch) evil.exe wsmprovhost.exe Get-ChildItem C:\ svchost.exe (WinRM) Terminate at end of session Remnants of C2 persist in memory Kernel Cmd history Cmd history © Mandiant, A FireEye Company. All rights reserved. Example: In-Memory Remnants 13 SOAP in WinRM service memory, after interactive PsSession with command: echo teststring_pssession > c:\testoutput_possession.txt © Mandiant, A FireEye Company. All rights reserved. Example: In-Memory Remnants 14 WinRM service memory - Invoke-Mimikatz.ps1 executed remotely on target host © Mandiant, A FireEye Company. All rights reserved. � XML / SOAP strings /wsman.xsd prompt""/rsp:Comma nd>AAAAAAAAAFkAAAAAAAAAAAMAAAa jAgAAAAYQAgC2Yc+EDBrbTLq08PrufN+rij8VmjyqZEaG AKwYZTnxB++7vzxPYmogUmVmSWQ9IjAiPjxNUz48T2JqI E49IlBvd2VyU2hlbGwiIFJlZklkPSIxIj48TVM+PE9iai BOPSJDbWRzIiBSZWZJZD0iMiI+PFROIFJlZklkPSIwIj4 8VD5TeXN0ZW0uQ29sbG . . . © Mandiant, A FireEye Company. All rights reserved. wsmprovhost.exe • Best source of intact evidence • Only lasts until PS session exits svchost.exe for WinRM • Fragments of evidence • Retention depends on # of remoting sessions • May last until reboot Kernel pool • Fragments of evidence • Brief lifespan, depends on system utilization Pagefile • Fragments of evidence • Brief lifespan, depends on system utilization • May last beyond reboot How Long Will Evidence Remain? 16 © Mandiant, A FireEye Company. All rights reserved. � Timing is everything � Challenging to recover evidence � Many variables � System uptime � Memory utilization � Volume of WinRM activity Memory Analysis Summary 17 Event Logs © Mandiant, A FireEye Company. All rights reserved. � Scenario: Attacker interacts with target host through � Local PowerShell execution � PowerShell remoting � Which event logs capture activity? � Level of logging detail? � Differences between PowerShell 2.0 and 3.0? Event Logs 19 © Mandiant, A FireEye Company. All rights reserved. � Application Logs � Windows PowerShell.evtx � Microsoft-Windows- PowerShell/Operational.evtx � Microsoft-Windows- WinRM/Operational.evtx � Analytic Logs � Microsoft-Windows- PowerShell/Analytic.etl � Microsoft-Windows- WinRM/Analytic.etl PowerShell Event Logs 20 © Mandiant, A FireEye Company. All rights reserved. � What you do get � Start & stop times of activity � Loaded providers � User account context � What  you  don’t  get � Detailed history of executed commands � Console input / output � Analytic logs help (somewhat) � Disabled by default � High volume of events � Encoding & fragmentation PowerShell 2.0 Event Logging 21 © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 22 PowerShell EID 400: Engine state is changed from None to Available. EID 403: Engine state is changed from Available to Stopped. Start & stop times of PowerShell session © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 23 PowerShell Operational** EID 40961: PowerShell console is starting up EID 4100: Error Message = File C:\temp\test.ps1 cannot be loaded because running scripts is disabled on this system ** Events exclusive to PowerShell 3.0 or greater Start time of PowerShell session Error provides path to PowerShell script © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 24 PowerShell Analytic** EID 7937: Command test.ps1 is Started. EID 7937: Command Write-Output is Started. EID 7937: Command dropper.exe is Started ** Events exclusive to PowerShell 3.0 or greater What executed? (arguments not logged) © Mandiant, A FireEye Company. All rights reserved. Remoting (Accessed Host) 25 PowerShell EID 600: Provider WSMan is Started. EID 400: Engine state is changed from None to Available. Start time of PowerShell session Indicates use of PowerShell remoting © Mandiant, A FireEye Company. All rights reserved. Remoting (Accessed Host) 26 WinRM Operational EID 81: Processing client request for operation CreateShell EID 169: User CORP\MattH authenticated successfully using NTLM EID 134: Sending response for operation DeleteShell Who connected via remoting Timeframe of remoting activity © Mandiant, A FireEye Company. All rights reserved. Remoting (Accessed Host) 27 PowerShell Analytic EID 32850: Request 7873936. Creating a server remote session. UserName: CORP\JohnD EID 32867: Received remoting fragment […]  Payload  Length:  752  Payload  Data: 0x020000000200010064D64FA51E7C784 18483DC[…]   EID 32868: Sent remoting fragment […]   Payload Length: 202 Payload Data: 0xEFBBBF3C4F626A2052656649643D22 30223E3[…]   Who connected via remoting Encoded contents of remoting I/O © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Encoded I/O 28 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Decoded Input 29 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Decoded Output 30 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. � Set global profile to log console command activity %windir%\system32\WindowsPowerShell\v1.0\ profile.ps1 � Use Start-Transcript cmdlet � Records all session input / output to text file � Overwrite default prompt function � Intercept commands and add to event log � Only works for local PowerShell execution � Can run PowerShell without loading profiles Other Logging Solutions for PS 2.0 31 © Mandiant, A FireEye Company. All rights reserved. � AppLocker – Script rules Other Logging Solutions for PS 2.0 32 © Mandiant, A FireEye Company. All rights reserved. PowerShell 3.0: Module Logging 33 Computer Configuration  →   Administrative Templates  →   Windows  Components  →   Windows  PowerShell  → Turn on Module Logging Solves (almost) all our logging problems! © Mandiant, A FireEye Company. All rights reserved. Module Logging Examples 34 ParameterBinding(Get-ChildItem): name="Filter"; value="*.txt" ParameterBinding(Get-ChildItem): name="Recurse"; value="True" ParameterBinding(Get-ChildItem): name="Path"; value="c:\temp" ParameterBinding(Select-String): name="Pattern"; value="password" ParameterBinding(Select-String): name="InputObject"; value="creds.txt" ... Command Name = Get-ChildItem User = CORP\MHastings ParameterBinding(Out-Default): name="InputObject"; value="C:\temp\creds.txt:2:password: secret" ParameterBinding(Out-Default): name="InputObject"; value="C:\temp\creds.txt:5:password: test" Microsoft-Windows-PowerShell/Operational (EID 4103) Get-ChildItem c:\temp -Filter *.txt -Recurse | Select-String password Logged upon command execution Logged upon command output © Mandiant, A FireEye Company. All rights reserved. Module Logging Examples 35 Invoke-Mimikatz.ps1 via remoting Detailed  “per- command”   logging © Mandiant, A FireEye Company. All rights reserved. Module Logging Examples 36 Invoke-Mimikatz.ps1 via remoting Mimikatz output in event log Persistence © Mandiant, A FireEye Company. All rights reserved. � Scenario: Attacker configures system to load malicious PS upon startup / logon � Why persist? � Backdoors � Keyloggers � What are common PS persistence mechanisms? � How to find them? PowerShell Persistence 38 © Mandiant, A FireEye Company. All rights reserved. � Registry  “autorun”  keys � Scheduled tasks � User  “startup”  folders � Easy to detect � Autorun review � Registry timeline analysis � File system timeline analysis � Event log review Common Techniques 39 At1.job At1.job At1.job © Mandiant, A FireEye Company. All rights reserved. Persistence via WMI 40 Set-WmiInstance Namespace:  “root\subscription” EventFilter Filter name, event query CommandLineEventConsumer Consumer name, path to powershell.exe FilterToConsumerBinding Filter name, consumer name Set-WmiInstance Set-WmiInstance Use WMI to automatically launch PowerShell upon a common event © Mandiant, A FireEye Company. All rights reserved. � Query that causes the consumer to trigger Event Filters 41 SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325 Run within minutes of startup SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Hour = 12 AND TargetInstance.Minute = 00 GROUP WITHIN 60 Run at 12:00 © Mandiant, A FireEye Company. All rights reserved. � Launch  “PowerShell.exe”  when  triggered  by  filter � Where does the evil PS code load from? Event Consumers 42 sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64 String('7L0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyq BymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ/ff/z9cZmQBbPbOStrJniGAqsgfP3 58Hz8ivlsXbb795bpdrdv0o2/nZVml363qcvbR/xMAAP//'),[IO.Compression.Co mpressionMode]::Decompress)),[Text.Encoding]::ASCII)).ReadToEnd() Stored in user or system-wide  “profile.ps1” Set-WmiInstance -Namespace "root\subscription" -Class 'CommandLineEventConsumer' -Arguments @{ name='TotallyLegitWMI';CommandLineTemplate="$($Env:SystemRoot)\Syst em32\WindowsPowerShell\v1.0\powershell.exe - NonInteractive";RunInteractively='false'} Added to Consumer Command-Line Arguments (length  limit,  code  must  be  base64’d) © Mandiant, A FireEye Company. All rights reserved. Enumerating WMI Objects with PowerShell 43 � Get-WMIObject –Namespace root\Subscription -Class __EventFilter � Get-WMIObject -Namespace root\Subscription -Class __EventConsumer � Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding © Mandiant, A FireEye Company. All rights reserved. PS WMI Evidence: File System 44 WBEM repository files changed (common) sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStr eam][Convert]::FromBase64String('7L0HYBxJl iUmL23Ke39K9UrX4HShCIBgEyTYkEA... Global or per-user “profile.ps1”  changed   (if used to store code) Strings in “objects.data” © Mandiant, A FireEye Company. All rights reserved. PS WMI Evidence: Registry 45 Key Value Data HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\ ESS\//./root/CIMV2\Win32ClockProvider [N/A] [N/A] Key Last Modified 06/04/14 01:30:03 UTC Created only when setting a time-based WMI filter (many other types of triggers may be used) © Mandiant, A FireEye Company. All rights reserved. � SysInternals AutoRuns (v12) � Memory: WMI filter & consumer names � svchost.exe (WinMgmt service) � WmiPrvse.exe � Event logs: WMI Trace � Too noisy PS WMI Evidence: Other Sources 46 Conclusions © Mandiant, A FireEye Company. All rights reserved. � Refer to whitepaper � Prefetch file  for  “PowerShell.exe” � Local execution only � Scripts in Accessed File list � Registry � PowerShell  “ExecutionPolicy”  setting � Network traffic analysis (WinRM) � Port 5985 (HTTP) / port 5986 (HTTPS) � Payload always encrypted � Identify anomalous netflows Other Sources of Evidence 48 © Mandiant, A FireEye Company. All rights reserved. � Upgrade to PS 3.0 and enable Module Logging if possible � Baseline legitimate usage in environment � ExecutionPolicy setting � Remoting enabled � Script naming conventions, paths � Which users � Source systems � Destination systems � Recognize artifacts of anomalous usage Lessons Learned 49 © Mandiant, A FireEye Company. All rights reserved. � Matt Graeber � Joseph Bialek � Chris Campbell � Lee Holmes � David Wyatt � David Kennedy � Josh Kelley � All the other PowerShell authors, hackers, and researchers! Acknowledgements 50 © Mandiant, A FireEye Company. All rights reserved. ryan.kazanciyan@mandiant.com @ryankaz42 matt.hastings@mandiant.com @HastingsVT Questions? 51 mailto:ryan.kazanciyan@mandiant.com mailto:matt.hastings@mandiant.com