Scaling API-first – The story of a global engineering organization
Powering up on power shell avengercon - 2018
1. Powering up on PowerShell
Fernando Tomlinson (@Wired_Pulse)
2. Powering up on PowerShell
Fernando Tomlinson (@Wired_Pulse)
Wireless:
SSID: PoSh or PoSH-5g
Pass: powershell
PoSh-Hunter:
HTTP://192.168.0.100
In the VM:
1. Type “resmon”
2. Checkmark “wlms.exe”
3. Right-click & Suspend
3. Get-ADUser –Filter {Name -eq ”Fernando Tomlinson”}
• 17 years of forensics, incident response, and information
technology experience with the Department of Defense
• Adjunct Digital Forensics Professor at a local college
• PowerShell enthusiast; developing and coding in PowerShell for
4 years
• Co-developer of Under the Wire (UnderTheWire.tech)
• Developer of PoSh Hunter (Posh-Hunter.com)
• Other sites:
• cyberfibers.com
• github.com/wiredpulse
PS C: >
6. • The demos used in this presentation can be found
at the below link
https://drive.google.com/file/d/1eNGTq5V7HqMCl
dqcjDiHR_HFmySShfzF/view?usp=sharing
Demos
7. Agenda
• Overview
• Moving around
• Hashing
• Data Storage
• Custom Event Logs
• WinRM Logging
• Port Scanning
• Persistence through Profiles
• Questions
8. What is this PowerShell?
• Introduced in 2006
• Implemented as an engine that can be embedded in a GUI
or used directly as a CLI
• Interactive command shell (like CMD)
• Scripting language (simplified C#)
• Remote management framework
• Built on top of .NET Framework
• Piping of full objects, not text
• Functionality provided by commands:
• Cmdlets (pronounced “command-lets”)
• Functions
• Scripts
• Native commands
9. How does it Work?
Cmdlets Scripts Functions Output
Host Interface
Runspace Interface
HostPS C: > _
What you see…
11. Elevator Speech about PowerShell
• Installed by default as part of OS
• Can access and manage most OS components
• Can access registry, files, WMI, change settings etc.
• Antivirus struggles (but has gotten better) with detection
• Can reflectively inject code
• Doesn’t touch disk most of the time
• Leaves barely any forensics evidence
• Encrypted network traffic
• Provide remote shell capability
• Full .NET Framework access
• Win32 API and native code access
12.
13.
14. Versions
PowerShell v2 PowerShell v3 PowerShell v4 PowerShell v5
Windows 7 Default
Server 2008R2 Default
Windows 8 Default
Windows 8.1 Default
Server 2012 Default
Server 2012R2 Default
Windows 10 Default
Server 2016 Default
Server 2019 Default
• A decent amount of organizations are still running Windows 7 with v2 installed!
• Above OS versions can all be upgraded to v5
– Requires Windows management framework
– Requires .NET framework 4.5
• PowerShell v5.1 (Windows specific) and PowerShell Core 6.2 (Cross-platform)
15.
16. • Get-Help – Help docs on cmdlets and examples
• Get-Command – Lists all commands installed including
cmdlets, aliases, functions, filters, scripts, and apps
• Get-Host – Lists version of PowerShell
• Get-PSDrives - Alias, Variables, Functions, HKCU, HKLM
• Set-Location – Changes present working directory
• Get-ChildItem – Directory listing
• Get-Content – Reads the contents of a file
• Get-ItemProperty – Metadata/ Registry Values
• Flow Control – If, For, Foreach, While
Quick Primer (Jimmy Johns)
17.
18. • National Software Reference Library
• https://www.nist.gov/software-quality-
group/national-software-reference-library-nsrl
• Identifying known bad or unknown hashes
• Could be streamlined with whitelisting
• Disk hashing == resource intense
• Recommend running processes or
tailored approach
Hashes
20. Storing Data
• Data -> Bytes -> Base64 -> Storage
• Fileless approach
• Anywhere that allows to be written to
• Registry
• Active Directory
• Event Logs
• Alternate Data Streams
• There when we need it
• Less likely to be found
21. Active Directory
• Over 50 properties to use
• Has size limitations
• Requires applicable rights to alter
• Readable by Domain Users
22. • Regedit allows the registry to be viewed like the
file system
• Keys are folders
• Values are files
• PowerShell views it the same way
Keys (Folders) Values (Files)
22
Value Data (Properties)
Registry
24. Choices, choices…
• Get-WinEvent
• Classic logs and Event Tracing for Windows (ETW)
• Search local or remote event logs
• Filtering performed at the remote server, not locally
• Can query archived log files off-line (*.evtx files)
• Supports the XPath query language:
• Very flexible and precise query syntax
• Build your XPath query in Event Viewer
• Lots of XPath tutorials on the Internet
• Get-EventLog
• Classic logs only
• Search local or remote event logs
• Filtering performed locally
24
25. • Custom logging
• Create your own custom logs
• Could be used to log activity that otherwise had no
way of being logged
Eventlogs
You said the data wasn’t
logging!
26. Formatting event log message field and Developing
custom eventlogs and messages.
Walkthrough
27. • Protocol is Web Services – Management (WS-MAN),
using HTTP (by default) or HTTPS
• Implemented by the Windows Remote Management
(WinRM) service
• Enabled by default on Windows Server 2012 and newer;
available on any computer running PowerShell 2.0 or
newer
• Must be enabled on any computer that will receive
incoming connections
Windows Remote Management (WinRM)
28.
29. The Enable-PSRemoting cmdlet performs the following operations:
• Runs the Set-WSManQuickConfig cmdlet, which performs the following tasks:
• Starts the WinRM service
• Sets the startup type on the WinRM service to Automatic
• Creates a listener to accept requests on any IP address
• Enables a firewall exception for WS-Management communications
• Registers the Microsoft.PowerShell and Microsoft.PowerShell.Workflow session
configurations, if it they are not already registered
• Registers the Microsoft.PowerShell32 session configuration on 64-bit computers,
if it is not already registered
• Enables all session configurations
• Changes the security descriptor of all session configurations to allow remote
access
• Restarts the WinRM service to make the preceding changes effective.
Enabling Remoting… what does it do?
29
30. • Channel-level encryption provided only with HTTPS
connections
• Application-level encryption provided with all
connections
• Credentials transmitted in clear-text only
with the Basic authentication protocol
when HTTPS is not in use
Security
31. • Operational
• On by default
• Analytics and Debug
• Off by default and provide very little
(Not so useful) logging
32.
33. • Get-PSSession
• Only returns information about the connections
you have
• Get-WSManInstance
• Returns information about all connections to the system
• IP, ID, user, idle time, and more
Getting visibility
35. Port Scanning
• Get-NetConnection
• V5+
• Full connect scan w/ auto close
• Auto pings target
• Net.Sockets.Client
• V2+ (.net 3.5+)
• Full connect scan w/o auto close
37. • Search Order
1. Aliases
2. Functions
3. Cmdlets
4. Native commands
Command Execution Search Order
38. • Each host application defines the script files it will load and the order in
which it loads them
• The console and ISE host applications share certain profile scripts
(CurrentUserAllHosts & AllUsersAllHosts) and define other scripts that are
unique to each (AllUsersCurrentHost & CurrentUserCurrentHost)
• Six total: two shared (Console and ISE), two for Console, and two for ISE
• List Profiles:
• Even though a path is listed, profiles aren’t created by default
Profile Scripts
41. • ABC (Always Be Coding)
• ISE -> Get-Command -> Get-Help -> <tab>
• Interactive challenged-based learning
• Under the Wire (http://UnderTheWire.tech)
• Posh-Hunter (https://Posh-Hunter.com)
How can YOU learn more PowerShell?
Hinweis der Redaktion
- Local instance of Posh-Hunter.com
- Over 90 challenges
Demos and a cheatsheet are on the site
# Sysinternals
gci hkcu:\software\sysinternals
- Previously called monad
- cmdlets == compiled dotnet
- functions == reusable chunks of code
PowerShell sits directly on the Microsoft .NET Framework
System.Management.Automation.dll is the dll enabling all the magic
Run PowerShell via hosting application
A runspace is created via the .NET framework for our specific application
Within the runspace, we can run cmdlets, scripts, and or functions
Our output is then passed to the hosting applications interface
Which brings us to what we see
https://www.thewindowsclub.com/difference-powershell-powershell-core
Microsoft Windows 7 SP1 and Windows Server 2008 R2 were the first versions of the operating system to include PowerShell (version 2.0) installed by default
Versions of PowerShell have been included in every subsequent release of Windows, through PowerShell 5.0 on Windows Server 2016 and on Windows 10.
https://redmondmag.com/articles/2017/07/17/windows-powershell-6.0-and-powershell-core.aspx
https://4sysops.com/wiki/differences-between-powershell-versions/
Query local or remote systems
Output of the queries can then be filtered, searched, consolidated and perhaps saved to a CSV file or HTML report
Filtering with get-winevent is performed at the target computer, not locally, which is much faster than downloading an entire (possibly multi-gigabyte) log and filtering it locally afterwards. We want to push the query filtering work out to the remote computer whenever possible.
- XPath Queries
Queries with get-winevent can be defined using a simple hashtable, an XPath query, or an XML definition of one or more XPath queries performed simultaneously. The Xpath query syntax is complex, but we can use the graphical Event Viewer application to build these queries for us. Once Event Viewer constructs the XML for the query, that XML string can simply be pasted into our scripts.
DEMO:
# To see a list of all local event logs:
get-winevent -listlog *
# To see a list of logs that begin with "s" on the remote computer named "server47":
get-winevent -listlog s* -computername "server47"
# To see the details of just the Security log:
get-winevent -listlog security | format-list *
# To show the last 20 events from the System log:
get-winevent -logname system -maxevents 20
# To get the last 20 events from each of the three classic logs:
$events = get-winevent -logname system -maxevents 20
$events += get-winevent -logname application -maxevents 20
$events += get-winevent -logname security -maxevents 20
$events | sort-object -property TimeCreated |
format-table TimeCreated,ID,Level,Message –auto
- A hash table is an array of paired items in the form " <property> = <value>" , with each pairing separated from the other pairs with a semicolon. One way to filter query results is
to give the target computer a hash table of filters, such that only the events which match the properties and values in the filters will be returned. Here is an example.
# To only show events with ID number 4624 from the Security log:
get-winevent -filterhashtable @fLogName="Security"; ID=4624}
- Note: You cannot use wildcards in -FilterHashTable query values, with the exceptions of log names and provider names. Sorry. How would you know which properties can be used in a hash table filter? Unfortunately, not every property of an event entry displayed by get-member can be used in a hash table filter (unlike filtering with where-object). The help for get-winevent gives the ugly details, but these are the properties you will most likely wish to use in filters (they are not case sensitive):
• LogName
• ProviderName
• ID
• Level
• StartTime
• EndTime
- The "StartTime" and "EndTime" properties will take datetime objects, like those created by the get-date cmdlet. Here is an example.
# To only show Security log events between five and three days ago:
$Day5Ago = (get-date).AddDays(-5)
$Day3Ago = (get-date).AddDays(-3)
get-winevent -filterhashtable @{LogName="Security"; StartTime=$Day5Ago; EndTime=$Day3Ago}
# To only show Warning events from the Application log:
get-winevent -FilterHashtable @{LogName="Application"; Leve1=3}
# To only show 10 recent Critical, Error and Warning events from the System log on a remote computer named "server47.testing.local":
get-winevent -FilterHashtable @{liogName="SYstem"; Level=@(1,2,3)) -MaxEvents 10 -ComputerName "server47.testing.local"
# To list the last 10 user accounts created (notice the "+=" in the second command):
$events = get-winevent –FilterHashtable @fLogName="Security"; ID=47201 –ErrorAction SilentlyContinue
$events += get-winevent –FilterHashtable @fLogName="Security"; ID=6241 –ErrorAction SilentlyContinue
$events | select-object -last 10
- SilentlyContinue is used to suppress the output of nothing being returned
- Other EventLog cmdlets:
Clear-EventLog
Write-EventLog
Limit-EventLog
Show-EventLog
New-EventLog
Remove-EventLog
# To clear the System and Application logs on a remote computer named Server57:
Clear-eventlog –log system,application –computername Server57
The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs, and the event logs that are generated by the Windows Event Log technology introduced in Windows Vista. It also gets events in log files generated by Event Tracing for Windows (ETW).
Enable-remoting –force suppresses the user prompts.
Session configurations are specifying what is actually above to the user. You can restrict cmdlets and commands
(for example, to a nondomain computer on TrustedHosts list)
When you execute a command without a full path to it, PowerShell searches for that command's name by trying to match it to one of these types of items, in this order:
If two commands of the same type with the same name exist, such as two functions both named ”tasklist", whichever was added most recently is what is executed because the earlier one was replaced.
https://www.computerperformance.co.uk/powershell/functions/
DEMO:
# Add a ping alias
PS:\> ping # Returns the correct menu for ping
PS:\> new-alias ping notepad
PS:\> ping # spawns notepad
PS:\> c:\windows\system32\ping.exe # Works as it should
Change “CurrentUser” profile path
https://stackoverflow.com/questions/5095509/is-it-possible-to-change-the-default-value-of-profile-to-a-new-value
- If you are accessing the $profile variable from within the Windows PowerShell console, the AllUsersCurrentHost and the CurrentUserCurrentHost note properties refer to the Windows PowerShell console. If you access the $profile variable from within the Windows PowerShell ISE, the AllUsersCurrentHost and the CurrentUserCurrentHost note properties refer to the Windows PowerShell ISE profiles.
CurrentUserCurrentHost = user logged in, the PowerShell host they are using (Console or ISE)
Profiles are loaded in the order shown. So the most authoritative one is the user’s AllUsersAllHosts profile (microsoft.powershell[ise]_profile.ps1)
AllUsersAllHosts
AllUsersCurrentHost
CurrentUserAllHost
CurrentUserCurrentHost
DEMO:
# Test to see if profile script exists
if (!(Test-Path -Path $PROFILE )) { New-Item -Type File -Path $PROFILE}