Investigating PowerShell Attacks



Similar documents
Investigating PowerShell Attacks

WHITE PAPER. INVESTIGATING POWERSHELL ATTACKS Black Hat USA Authors: Ryan Kazanciyan, Matt Hastings SECURITY REIMAGINED

Who DIT It? Detecting and Mitigating Privilege Escalation Attacks on the Active Directory Data Store

Abusing Windows Management Instrumentation (WMI) to Build a Persistent, Asynchronous, and Fileless Backdoor. Matt Graeber

Exploiting Transparent User Identification Systems

Click Studios. Passwordstate. Password Discovery, Reset and Validation. Requirements

Microsoft Windows PowerShell v2 For Administrators

DRIVE-BY DOWNLOAD WHAT IS DRIVE-BY DOWNLOAD? A Typical Attack Scenario

RSA Security Analytics

WolfTech Active Directory: Diagnostic Tools

How To - Implement Single Sign On Authentication with Active Directory

Abusing Windows Management Instrumentation (WMI) to Build a Persistent, Asyncronous, and Fileless Backdoor

ILTA HANDS ON Securing Windows 7

How To - Implement Clientless Single Sign On Authentication with Active Directory

User Identification (User-ID) Tips and Best Practices

SECURITY BEST PRACTICES FOR CISCO PERSONAL ASSISTANT (1.4X)

OPAS Prerequisites. Prepared By: This document contains the prerequisites and requirements for setting up OPAS.

Server Manager Performance Monitor. Server Manager Diagnostics Page. . Information. . Audit Success. . Audit Failure

NETWRIX ACCOUNT LOCKOUT EXAMINER

Course Description. Course Audience. Course Outline. Course Page - Page 1 of 12

MS 6419 Configuring, Managing and Maintaining Windows Server 2008-based Servers

PowerShell Remoting Configuration

Ipswitch Client Installation Guide

Symantec Enterprise Security Manager Baseline Policy Manual for CIS Benchmark. For Windows Server 2008 (Domain Member Servers and Domain Controllers)

Windows 7, Enterprise Desktop Support Technician

Windows 7, Enterprise Desktop Support Technician Course 50331: 5 days; Instructor-led

Windows Server 2008 R2: Server Management and PowerShell V2

A Roadmap for Securing IIS 5.0

PROJECTIONS SUITE. Database Setup Utility (and Prerequisites) Installation and General Instructions. v0.9 draft prepared by David Weinstein

How To - Implement Clientless Single Sign On Authentication in Single Active Directory Domain Controller Environment

User Migration Tool. Note. Staging Guide for Cisco Unified ICM/Contact Center Enterprise & Hosted Release 9.0(1) 1

Symantec Enterprise Security Manager Baseline Policy Manual for CIS Benchmark

Acronis Backup & Recovery 10 Server for Windows. Installation Guide

Web. Security Options Comparison

Requirements & Install. Module 2 Single Engine Installation

RSA SecurID Ready Implementation Guide

"Charting the Course to Your Success!" MOC D Windows 7 Enterprise Desktop Support Technician Course Summary

Ad Hoc Transfer Plug-in for Outlook Installation Guide

Jetico Central Manager. Administrator Guide

Windows PowerShell Fundamentals

Windows PowerShell Cookbook

MCTS Guide to Microsoft Windows 7. Chapter 7 Windows 7 Security Features

RSA Security Analytics

MS-50255: Managing, Maintaining, and Securing Your Networks Through Group Policy. Course Objectives. Required Exam(s) Price.

6419: Configuring, Managing, and Maintaining Server 2008

411-Administering Windows Server 2012

SSL VPN. Virtual Appliance Installation Guide. Virtual Private Networks

Use Enterprise SSO as the Credential Server for Protected Sites

5nine Virtual Firewall 2.1 for Microsoft Hyper-V

Managing Windows Environments with Group Policy

Pass-the-Hash II: Admin s Revenge. Skip Duckwall & Chris Campbell

Remote Desktop Reporter Agent Deployment Guide

Setting Up Scan to SMB on TaskALFA series MFP s.

OneStop Reporting 3.7 Installation Guide. Updated:

Active Directory Installation on Windows Server 2012

Acronis Backup & Recovery 11

User-ID Best Practices

Configuring Managing and Maintaining Windows Server 2008 Servers (6419B)

Receiver Updater for Windows 4.0 and 3.x

Disaster Recovery System Administration Guide for Cisco Unified Contact Center Express Release 8.0(2)

Manage Traps in a VDI Environment. Traps Administrator s Guide. Version 3.3. Copyright Palo Alto Networks

Active Directory Integration

365 Services. 1.1 Configuring Access Manager Prerequisite Adding the Office 365 Metadata. docsys (en) 2 August 2012

Module 3: Resolve Software Failure This module explains how to fix problems with applications that have problems after being installed.

DC Agent Troubleshooting

Partie Serveur Lab : Implement Group Policy. Create, Edit and Link GPOs. Lab : Explore Group Policy Settings and Features

Walton Centre. Document History Date Version Author Changes 01/10/ A Cobain L Wyatt 31/03/ L Wyatt Update to procedure

6WRUP:DWFK. Policies for Dedicated SQL Servers Group

Why You Need to Detect More Than PtH. Matt Hathaway, Senior Product Manager, Rapid7 Jeff Myers, Lead Software Engineer, Rapid7

Configuring, Managing and Maintaining Windows Server 2008-based Servers

ArcGIS Server Security Threats & Best Practices David Cordes Michael Young

SOA Software API Gateway Appliance 7.1.x Administration Guide

Random Password Manager Enterprise Edition

LAE 5.1. Windows Server Installation Guide. Version 1.0

Microsoft Corporation. Status: Preliminary documentation

Introduction to the Mobile Access Gateway

Hacker s Perspective on your Windows Infrastructure: Windows 10 Mandatory Check List

6425C - Windows Server 2008 R2 Active Directory Domain Services

Using Microsoft Windows Authentication for Microsoft SQL Server Connections in Data Archive

Using Logon Agent for Transparent User Identification

Course 6419B: Configuring, Managing and Maintaining Windows Server 2008-based Servers

Terminal Services Tools and Settings - Terminal Services: %PRODUCT%

Red vs. Blue: Modern Active Directory Attacks, Detection, & Protection

HYPERION SYSTEM 9 N-TIER INSTALLATION GUIDE MASTER DATA MANAGEMENT RELEASE 9.2

McAfee One Time Password

IBM WebSphere Application Server Version 7.0

Enterprise. Insights. Active Directory Integration: Installation and Setup Guide. v1.0.5

TARGETPROCESS INSTALLATION GUIDE

Deploying Microsoft Operations Manager with the BIG-IP system and icontrol

Network Detective. HIPAA Compliance Module RapidFire Tools, Inc. All rights reserved V

Preparing for GO!Enterprise MDM On-Demand Service

Deploying RSA ClearTrust with the FirePass controller

SQL Server Solutions GETTING STARTED WITH. SQL Safe Backup

Good Morning Wireless! SSID: MSFTOPEN No Username or Password Required

Click Studios. Passwordstate. Installation Instructions

DSCompromised: A Windows DSC Attack Framework

Administration Guide. BlackBerry Resource Kit for BlackBerry Enterprise Service 10. Version 10.2

Red vs. Blue: Modern Active Directory Attacks, Detection, & Protection

Transcription:

Investigating PowerShell Attacks Matt Hastings October 7, 2014 Background Case Study 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 2

Why PowerShell? It can do almost anything Execute commands Download files from the internet Reflectively load / inject code Interface with Win32 API Enumerate files Interact with the registry Interact with services Examine processes Retrieve event logs Access.NET framework 3 PowerShell Attack Tools PowerSploit Reconnaissance Code execution DLL injection Credential harvesting Reverse engineering Nishang Posh-SecMod Veil-PowerView Metasploit More to come 4

PowerShell Malware in the Wild 5 Investigation Methodology WinRM PowerShell Remoting evil.ps1 Local PowerShell script backdoor.ps1 Persistent PowerShell Registry File System Event Logs Memory Network Traffic Sources of Evidence 6

Attacker Assumptions 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 7 Version Reference 2.0 3.0 4.0 Default (SP1) Default (R2 SP1) Requires WMF 3.0 Update Requires WMF 3.0 Update Default Requires WMF 4.0 Update Requires WMF 4.0 Update Requires WMF 4.0 Update Default Default Default (R2) 8

MEMORY ANALYSIS 9 Memory Analysis 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? 10

WinRM Process Hierarchy Invoke-Command {c:\evil.exe} svchost.exe (DcomLaunch) Client Invoke-Command {Get-ChildItem C:\} Invoke-Mimikatz.ps1 -DumpCreds ComputerName victim" wsmprovhost.exe evil.exe wsmprovhost.exe {PS code} Victim 11 Remnants in Memory svchost.exe (DcomLaunch) Terminate at end of session wsmprovhost.exe wsmprovhost.exe evil.exe Cmd history Cmd history {PS code} Remnants of WinRM SOAP persist svchost.exe (WinRM) Kernel 12

How Long Will Evidence Remain? wsmprovhost.exe svchost.exe (WinRM) Kernel Memory Pagefile Evidence Best source of command history, output Fragments of remoting I/O Fragments of remoting I/O Fragments of remoting I/O Retention Single remoting session Varies with # of remoting sessions Varies with memory utilization Varies with memory utilization Max Lifetime End of remoting session Reboot Reboot Varies may persist beyond reboot 13 Example Simple Command echo teststring_pssession > c:\testoutput_possession.txt SOAP remnants in WinRM memory after receiving command 14

Example Remote Invoke-Mimikatz WinRM service memory on target host after Invoke-Mimikatz.ps1 executed remotely 15 Example Encoded Command Invoke-Command -Computername 192.168.114.133 -Cred win-jacr88jtqv5\administrator {echo testingencodedstring > c:\out.txt}" powershell.exe enc SQBuAHYAbwBrAGUALQBDAG8AbQBtAGEAbgBkACAALQBDAG8AbQBwAHUAdABlAHIAbgBhAG0AZQAgADEAOQ AyAC4AMQA2ADgALgAxADEANAAuADEAMwAzACAALQBDAHIAZQBkACAAdwBpAG4ALQBqAGEAYwByADgAOABq AHQAcQB2ADUAXABhAGQAbQBpAG4AaQBzAHQAcgBhAHQAbwByACAAewBlAGMAaABvACAAdABAHMAdABpAG4 AZwBFAG4AYwBvAGQAZQBkAFMAdAByAGkAbgBnACAAPgAgAGMAOgBcAG8AdQB0AC4AdAB4AHQAfQA= WinRM service memory on target host 16

What to Look For? WSMan & MS PSRP Syntax /wsman.xsd <rsp:command> <rsp:commandline> <rsp:arguments> <S N="Cmd > Known attacker filenames View context around hits Yes, this is painful <rsp:commandresponse><rsp:commandid>""xmlns:r sp="http://schemas.microsoft.com/wbem/wsman/1 /windows/shell"""c80927b1-c741-4e99-9f97- CBA80F23E595</a:MessageID><w:Locale xml:lang="en-us" s:mustunderstand="false" /><p:datalocale xml:lang="en-us" s:mustunderstand="false" /><p:sessionid"/w:operationtimeout></s:header ><s:body><rsp:commandline xmlns:rsp="http://schemas.microsoft.com/wbem/ wsman/1/windows/shell" CommandId="9A153F8A- AA3C-4664-8600- AC186539F107"><rsp:Command>prompt""/rsp:Comma nd><rsp:arguments>aaaaaaaaafkaaaaaaaaaaamaaaa jagaaaayqagc2yc+edbrbtlq08prufn+rij8vmjyqzeag AKwYZTnxB++7vzxPYmogUmVmSWQ9IjAiPjxNUz48T2JqI E49IlBvd2VyU2hlbGwiIFJlZklkPSIxIj48TVM+PE9iai BOPSJDbWRzIiBSZWZJZD0iMiI+PFROIFJlZklkPSIwIj4 8VD5TeXN0ZW0uQ29sbG... 17 Memory Analysis Summary Timing is everything Challenging to recover evidence Many variables System uptime Memory utilization Volume of WinRM activity 18

EVENT LOGS 19 Event Logs Scenario: Attacker interacts with target host through local PowerShell script execution or PowerShell remoting Which event logs capture activity? Level of logging detail? Differences between PowerShell 2.0 and 3.0? 20

PowerShell Event Logs 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 21 Local PowerShell Execution PowerShell EID 400: Engine state is changed from None to Available. HostName=ConsoleHost EID 403: Engine state is changed from Available to Stopped. HostName=ConsoleHost Start & stop times of PowerShell session 22

Local PowerShell Execution EID 40961: PowerShell console is starting up Start time of PowerShell session PowerShell Operational** 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 Error provides path to PowerShell script 23 Local PowerShell Execution PowerShell Analytic** EID 7937: Command test.ps1 is Started. EID 7937: Command Write-Output is Started. EID 7937: Command dropper.exe is Started ** Log disabled by default. Events exclusive to PowerShell 3.0 or greater Executed cmdlets, scripts, or commands (no arguments) 24

Remoting PowerShell EID 6: Creating WSMan Session. The connection string is: 192.168.1.1/wsman?PSVersion=2.0 Start of remoting session (client host) PowerShell EID 400: Engine state is changed from None to Available. HostName=ServerRemoteHost EID 403: Engine state is changed from Available to Stopped. HostName=ServerRemoteHost Start & stop of remoting session (accessed host) 25 Remoting (Accessed Host) EID 169: User CORP\MattH authenticated successfully using NTLM Who connected via remoting WinRM Operational EID 81: Processing client request for operation CreateShell EID 134: Sending response for operation DeleteShell Timeframe of remoting activity 26

Remoting (Accessed Host) EID 32850: Request 7873936. Creating a server remote session. UserName: CORP\JohnD Who connected via remoting PowerShell Analytic EID 32867: Received remoting fragment [ ] Payload Length: 752 Payload Data: 0x020000000200010064D64FA51E7C784 18483DC[ ] EID 32868: Sent remoting fragment [ ] Payload Length: 202 Payload Data: 0xEFBBBF3C4F626A2052656649643D22 30223E3[ ] Encoded contents of remoting I/O 27 PS Analytic Log: Encoded I/O Invoke-Command {Get-ChildItem C:\} 28

PS Analytic Log: Decoded Input Invoke-Command {Get-ChildItem C:\} 29 PS Analytic Log: Decoded Output Invoke-Command {Get-ChildItem C:\} 30

Logging via PowerShell Profiles %windir%\system32\windowspowershell\v1.0\profile.ps1 Add code to global profile Loads with each local PS session Start-Transcript cmdlet Overwrite default prompt function Limitations Will not log remoting activity Can launch PowerShell without loading profiles 31 Logging via AppLocker Set Audit or Enforce script rules Captures user, script path 32

PowerShell 3.0: Module Logging Solves (almost) all our logging problems! Computer Configuration Administrative Templates Windows Components Windows PowerShell Turn on Module Logging 33 Module Logging Example: File Listing Get-ChildItem c:\temp -Filter *.txt -Recurse Select-String password Microsoft-Windows-PowerShell/Operational (EID 4103) 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 Logged upon command execution 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" Logged upon command output 34

Module Logging Example: Invoke- Mimikatz Invoke-Mimikatz.ps1 via remoting Detailed percommand logging 35 Module Logging Example: Invoke- Mimikatz Mimikatz output in event log 36

PERSISTENCE 37 PowerShell Persistence Scenario: Attacker configures system to load malicious PowerShell code upon startup or user logon What are common PowerShell persistence mechanisms? How to find them? 38

Common Techniques Registry autorun keys Scheduled tasks User startup folders Easy to detect Autorun review Registry timeline analysis File system timeline analysis Event log review At1.job At1.job At1.job 39 Persistence via WMI Use WMI to automatically launch PowerShell upon a common event Namespace: root\subscription Set-WmiInstance EventFilter Filter name, event query Set-WmiInstance CommandLineEventConsumer Consumer name, path to powershell.exe Set-WmiInstance FilterToConsumerBinding Filter name, consumer name 40

Event Filters Query that causes the consumer to trigger 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 41 Event Consumers Launch PowerShell.exe when triggered by filter Where does the evil PS code load from? 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) 42

Enumerating WMI Objects with PowerShell Get-WMIObject Namespace root\subscription -Class EventFilter Get-WMIObject -Namespace root\subscription -Class EventConsumer Get-WMIObject -Namespace root\subscription -Class FilterToConsumerBinding 43 PS WMI Evidence: File System WBEM repository files changed (common) Strings in objects.data Global or per-user profile.ps1 changed (if used to store code) sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStr eam][convert]::frombase64string('7l0hybxjl iuml23ke39k9urx4hshcibgeytykea... 44

PS WMI Evidence: Registry Key Value Data HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\ ESS\//./root/CIMV2\Win32ClockProvider Key Last Modified 06/04/14 01:30:03 UTC [N/A] [N/A] Created only when setting a time-based WMI filter (many other types of triggers may be used) 45 PS WMI Evidence: Other Sources SysInternals AutoRuns v12 Memory: WMI filter & consumer names svchost.exe (WinMgmt service) WmiPrvse.exe Event logs: WMI Trace 46

CONCLUSIONS 47 Other Sources of Evidence Refer to whitepaper Prefetch for PowerShell.exe Local execution only Scripts in Accessed File list Registry ExecutionPolicy setting Network traffic analysis (WinRM) 5985 (HTTP) / 5986 (HTTPS) Payload always encrypted Identify anomalous netflows SysInternals Sysmon Command argument auditing Local execution only POWERSHELL.EXE-59FC8F3D.pf 48

Lessons Learned Upgrade and enable Module Logging if possible Baseline legitimate PowerShell usage ExecutionPolicy setting Script naming conventions, paths Remoting enabled? Which users? Common source / destination systems Recognize artifacts of anomalous usage 49 Acknowledgements Matt Graeber Joseph Bialek Chris Campbell Lee Holmes David Wyatt David Kennedy Josh Kelley All the other PowerShell authors, hackers, and researchers! 50

Questions? ryan.kazanciyan@mandiant.com @ryankaz42 matt.hastings@mandiant.com @HastingsVT 51