-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPowershell Notes .txt
1675 lines (1096 loc) · 46.6 KB
/
Powershell Notes .txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
------------------------------------------------------------------------------
Pentester Academy : Powershell
------------------------------
Ques : What is Powershell ?
Ans : Powershell is an automation platform and scripting language for windows and
windows seerver that allows you to simplify the management of your system
NOTE : As a Pentester we are suppose to have a good knowledge about powershell
Course Contents :
=================
1. Introduction to Powershell
2. Basics of Powershell
3. Scripting
4. Advance Scripting Concept
5. Modules
6. Job
7. Powershell with .NET
8. Using Window API with powershell
9. Powershell and WMI
10. Working with COM object
11. Interacting with Registry
12. Recon and Scanning
13. Exploitation
- BruteForce
- Client Side Attack
- Using Existing exploitation Technique
- Porting exploit to powershell
- Human interface Device
14. Powershell and Metasploit
- Running Powershell Script
- using powershell in metasploit exploits
15. Post Exploitation
- Information gathering and exfilteration
- Backdoors
- privilege Escalation
- Getting system secrets
- Pass the hash
- powershell remoting
- WMI and WSMAN for remote command execution
- Web shells
- Achieving Persistence
16. Using powershell with othere security tools
17. Defence against Powershell attacks
-------------------------------------------------------------------------------
Ques : What is Powershell for us ?
Ans : - A Powershell and Scripting llanguage is already present on the most general
Target in a pen-test
- Less Dependence on Metasploit and *nix based Scripting
Ques : Why Powershell ?
Ans :
- Provide access to almost everything on a window platform which could
be useful for us as attackers
- Easy to learn and really powerfull
- Based on .Net framework and is tightly integerated with windows
- Trusted by the countermeasures and system administrator
---------------------------------------------------------------------------------
Some Command
> cd \
> dir
> ls
> ps
> Get-Help | more : so that it fits to screen
> Get-Help * | more
> Get-Help *process | more
> Get-Process
> Get-Help *alias*
> Get-Alias
> Get-Help Get-Help -Examples
> Get-Help Get-Help -Online
---------------------------------------------------------------------------------
Exploring and Using Cmdlets
> Get-Help Get-Command | more
> Get-Command -CommandType cmdlet : list only the cmdlet
> Get-Help Get-command -Parameter * : list the prarameter in cmdlet
> Get-Command -CommandType Cmdlet -Name *process* : list all the cmdlet having process in their name
> Get-Command -CommandType Cmdlet | Measure-Object : count the objects
> Get-Service
> Get-Process
Cmdlet in Powershell follow a verb Noun Naming Convention
> Get-Command -Verb stop
> Get-Command -Verb Start
> Get-Help start-Process -examples | more
> Start-Process [name]
> Stop-Process -id [pid]
---------------------------------------------------------------------------------
Output Formatting and Output Manipulation
Powershell has Cmdlets which could be used for
- Output Formatiing
> Get-Command -CommandType Cmdlet -Name *Format*
- Output Manipulation
> Get-Command -CommandType Cmdlet -Name out*
---------------------------------------------------------------------------------
> Get-ChildItem or ls
> Get-ChildItem | Format-Table Name : list only names
> Get-ChildItem | Format-Table * : list all the property
> Get-ChildItem | Format-List | more : List the property of objects
> Get-Process | Out-GridView
> Get-Content [file_name] : To get Content of the file
---------------------------------------------------------------------------------
Operators
Arithematic ( +, -, *, /, % )
Assignment ( =, +=, -=, /=, %= )
Comparison ( -eq, -ne, -gt, -lt, -le, -ge, -match, -nomatch, -replace, -like, -notlike, -in, -notin, -contains, -notcontains )
Redirection (> , >> , 2> , 2>&1)
> Declaring Variable using '$'
> "Hello World" -match "Hello" : True/False
> "Hello " -replace "l" : Heo
> "Hello" -replce "l","y" : heyyo
---------------------------------------------------------------------------------
Advanced Operator
Logical ( -and, -not, -or, -xor )
Split and Join ( -split, -Join )
Type Operator ( -is, -as, -isnot )
> "String as given " -split "option"
> "Hello " , "World" -join "-" : Hello -World
> 3 -is "int" : True
> 3 -is "float" : False
---------------------------------------------------------------------------------
Types in Powershell
- Dynamic Types : Not Strictly Typed
- Type Adaption : Provide Access to Alternate object system like WMI, COM , ADSI etc
- The Basis of powershell is .NET
> $value = "String " + 1
> $value.GetValue()
Variable Types
String : Single Quoted vs Double Quoted
Here String
Double Quote Expands the function
single Variable treat function as string
Multiline String :
$value = @" dndsjfnoifn "@
Type Converison : Type Conversion in powershell is done with the help of [] operator
[int]$variable
Arrays : Commands in Powershell return an arrays of objects - [object[]]
more than one type of element could be stored
> $array = 1,2,3,4,5
> $array.length() : length of the array
> $array[index]
> $empty_array = @()
---------------------------------------------------------------------------------
Conditional Statements
if, elseif , else
support usaage of command and cmdlets and pipeline in the condition part
if - Condition
> if(1 -gt 0) { statement } else { Statement }
> if((get-process).count -gt 2){Statement } else{statement}
---------------------------------------------------------------------------------
Switch Statements
Support Parameter like (-Exact , -Wildcard - Regex ) For condition matching
Ability to process file using the -file operator
switch -regex -file C:\test\WindowsUpdate.log{'Validating'{$_}}
example :
> switch (1) {1 {"One"} 2 {"Two "} 3 {Three}}
> switch (1) {1 {"One"} 2 {"Two "} 3 {Three} default {statement}}
> switch -wildcard ('abc') { a* {'A'} *b* {'B'} }
---------------------------------------------------------------------------------
Loop Statements :
While(){}
do{}while()
do{]untile()
for(;;){}
foreach( in ){} :
$procs = Get-Process
foreach ($proc in $procs ){echo $proc}
Loop Cmdlets :
1. ForEach-Object
Get-Process | ForEach-Object{$_.name}
2. Where-Object
Get-ChildItem | Where-Object {$_.Name -match "txt"}
> Get-ExecutionPolicy
> Set-ExecutionPolicy bypass : to bypass the execution policy
---------------------------------------------------------------------------------
Functions Part 1
Simple Ussage
parameter of a powershell Functions
- $args
- Declaring Parameters
- Positional and named parameters
> function add {1 + 3}
> add
> function paramas { $args }
> function paramadd {$args[0] + $args[1]}
> function product($num1, $num2) {$num1 * $num2}
> calling : product -num1 10 -num2 19
> calling : product 1 2
Functions Part 2
Dynamic Number of Parameter
Type Declaration of the parameter
Default values
> function varparams ($a, $b){
$a
$b
}
Handle Variable number of input :
> funcition variable_params ($a , $b ){
$a
$b
$args
}
Declaring Types of the Variable
> function typeVariable ([int]$a, [int]$b){ Statements }
Variable having Default Values
> function default_variable ( $a = 32, $b ){ statement }
Functions Part 3
Switch Parameters
Returning Values
Scope of Variable and Functions
Switch Parameters
function switchable ($a,$b,[switch]$flip){
$a
$b
if($flip){$a - $b}
}
> switchable 1 2 -flip
> switchable 1 2
Returning Values
$output = switchable 1 2
Scope of Variable and Functions
> $var1 = 33 : Global Variable
> function var($var1 = 22){ : local Variable
> $var1
> }
Powershell doesnot function overloading
> ls function: = to display all the fucntions
---------------------------------------------------------------------------------
Advanced Function in Powershell
- param Statement
- Param attributes
- Mandatory
- ParameterSetname
- Position
- ValueFroPipeline
- Parameter Validation
- AllowEmptyString
- AllowNull
- AllowEmptyCollection
- ValidateLength
- ValidatePattern
- ValidateSet
function addvancedFucntion
{
param (
[parameter (mandatory=$True, Position = 1, ValueFromPipeline=$True)] $a,
[parameter ( position = 0)] $b
)
Write-Output " a is $a "
Write-Output " b is $b "
}
> 12 | addvancedFucntion -b 13
AllowNull : Allows NUll value where value is mandatory
function addvancedFucntion
{
param (
[parameter (mandatory=$True, Position = 1, ValueFromPipeline=$True, AllowNull())] $a,
[parameter ( position = 0)] $b
)
Write-Output " a is $a "
Write-Output " b is $b "
}
ValidateSet:
function addvancedFucntion
{
param (
[parameter (mandatory=$True, Position = 1, ValueFromPipeline=$True, ValidateSet(1,2,3))] $a,
[parameter ( position = 0)] $b
)
Write-Output " a is $a "
Write-Output " b is $b "
}
---------------------------------------------------------------------------------
Powershell Scripting
- Dot Sourcing
- CmdletBinding
- Verbose Output
- Parameter Check
- SupportShouldProcess { -Whatif and -Confirm }
[CmdletBinding()] : Provide ability to verbose output
function Show-Advanced{
[CmdletBinding()] : This attribute allows the script to behave as a precompiled cmdlet
param(
[parameter()]$filePath
)
Remove-Item $filePath
}
Verbose Outputing
function Show-Advanced{
[CmdletBinding()]
param(
[parameter()]$filePath
)
Write-Verbose "Deleting $filePath"
Remove-Item $filePath
}
> . .\file.ps1
> Show-Advanced -filePath [] -Verbose
SupportShouldProcess
- gives Whatif functionality
function Show-Advanced{
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[parameter()]$filePath
)
Write-Verbose "Deleting $filePath"
Remove-Item $filePath
}
> . .\file.ps1
> Show-Advanced -filePath [] -Verbose -Whatif
- gives confirm support
> Show-Advanced -filePath [] -Verbose -confirm
gives a dialog for confirm
---------------------------------------------------------------------------------
Modules
- Writing Script Module
- Controlling Visibility
- To Create a module just change the extension from .ps1 to .psm1
- To import a module : Import-Module .\module.ps1
- To Check : Get-Command -CommandType Function
- To Remove Module : Remove-Module [Module_name]
if you want to hide a function which you dont want to show to users use
Export-ModuleMember -Function [function_name]
---------------------------------------------------------------------------------
ManiFest Modules
- Creating a Manifest
> New-ModuleManifest .\[name_of_the_manifest].psd1
- Check any Manifest
> Test-ModuleManifest .\[Name_of_the_manifest].psd1
- Using a Manifest Module
---------------------------------------------------------------------------------
Remoting Part - 1
Running cmdlets on remote Computer
- exploring cmdlet with -ComputerName parameter
- using cmdlet on the single remote computer
- using cmdlet on multiple remote computer
> get-help *remote*
> Get-Command -CommandType Cmdlet | Get-Member
> Get-Command -CommandType Cmdlet -ParameterName computername
> Get-Command -CommandType Cmdlet | Where-Object {$_.Parameters.Keys -contains 'ComputerName'}
> Get-Command -CommandType Cmdlet | Where-Object {$_.Parameters.Keys -contains 'ComputerName' -and $_.Parameters.Keys -contains 'credential' -and $_.Parameters.Keys -notcontains 'Session'}
does not contains session which means it support the poweshell remotely
These are the command we use :
Cmdlet Get-HotFix : This command takes too much time
Cmdlet Get-PSSession
Cmdlet Get-WmiObject
Cmdlet Invoke-WmiMethod
Cmdlet Register-WmiEvent
Cmdlet Remove-WmiObject
Cmdlet Restart-Computer
Cmdlet Set-WmiInstance
Cmdlet Stop-Computer
Cmdlet Test-Connection
1. Get-Hotfix
> Get-HotFix -ComputerName AnshPC -Credential barat\domainuser
2. Test-Connection
> foreach($pc in ('localhost','googl.com')){Test-Connection $pc}
---------------------------------------------------------------------------------
Remoting Part - 2
Based on WSMAN protocol and uses Winrm
- need port 5985(HTTP) 5986(HTTPS)
- Alternate Port Possible
Using PowerShell Remoting
- Trusted Domain
- Work Group
(WSMan:\localhost\client\trustedhost)
Running Cmdlet which supports remoting
> Set-Item WSMan:\localhost\client\trustedhosts -Value *
---------------------------------------------------------------------------------
Remoting One to One
Interacting Session - PSsession
- Runs in a new Process
- Is StateFul
Using PSsession
- Initiating
- INteracting
- Closing
> powershell -version 2
> help *session*
> New-PSSession -ComputerName [Name] -Credential [ Credentials] : Start a new process
> Get-PSSession
> Get-PSSession -ComputerName [Name eg. domainpc]
> $PSVersionTable : get Version of Powershell
> Enter-PSSession -id [ id ]
> Enter-PSSession -Name [ Name_of_Session ]
> $env:COMPUTERNAME = > Display Computer name
> Remove-PSSession [session id]
---------------------------------------------------------------------------------
Remoting One to Many
Invoke-Command
- Running Command
- Running Scripts
- Running Modules
"Fan-Out" Or "One-to-Many"
> Invoke-Command -ScriptBlock {Command1, Command2, Command3} -ComputerName [Name] -Credentials [eg. bharat\domainuser]
> Invoke-Command -FilePath [Path] -ComputerName [Name] -Credentials [bharat\domainuser]
above command is used to run powershell script on othere computer
NOTE : We cannot run modules directly for that we have to do the following steps
1. Import the module- locally
> Import-Module .\file_name.psm1
2. Now to run any function from the module ussage is as follows
> Invoke-Command -ScriptBlock ${function:Get-Information} -ComputerNane [] -Credentials []
---------------------------------------------------------------------------------
Advanced Powershell Remoting
- Using Invoke-Command state fuly across session
- Implicit Remoting
NOTE * in Invoke-Command Command are ran independently without having any state
# Explicit Remoting
This Can be Solve with the help of using PSSession
> New-PSSession -ComputerName [] -Credentials []
> $sess = Get-PSSession
> Invoke-Command -ScriptBlock {$procs = Get-Process} -Session $sess
> Invoke-Command -ScripBlock {$procs} -Session $sess
Note : This Method alloes us to run command in statefull manner
# Implicit Remoting
Powershell allows us to create Proxy funtions for implicit Remoting
# Explicit Remoting
> Get-PSSession
> Invoke-Command -ScriptBlock {function Get-sysinfo {Whoami; $env:COMPUTERNAME}} -Session $sess
> Invoke-Command -ScriptBlock {Get-sysinfo} -Session $sess
# Implicit Remoting
# Import-PSSession : This allows us to create proxy functions from a PSSession
> Import-PSSession -CommandName Get-sysInfo -Session $sess
> Get-Sysinfo : now we can use it as local Function
We can export into module from command
> Export-PSSession -ModuleName domainmodule -CommanName Get-Sysinfo -session $sess
---------------------------------------------------------------------------------
Jobs in Powershell
Jobs in powershell are a way to execute commands and Scripts etc in Background
# jobs :
- Start
- Receive Output
- Remove
- Remote Jobs
Local Jobs
> Start-Job -ScriptBlock {commands} : Start the Job
> Get-job -Id [id]
> Get-job | Receive-Job : Receive the output
> Get-job | Remove-Job : Stop the JOb
> Get-job -FilePath [path_to_script]
We can also use multiple jobs using foreach loop
Remote Jobs
One way of running Commands and Scripts remotely is to use Cmdlets which support the AsJob Parameter
Invoke-Command Uses Asjobs thorughly
> Invoke-Command -ScriptBlock{ps} -Computername [] -credentials [] : This is Dry Run
> Invoke-Command -ScriptBlock { Start-Job -ScriptBlock {ps}} -ComputerName [] -Credential [] : This run as a JOb
But We know that Invoke-Command is State less to resolve this issue we use PSSession
> $sess = New-PSSession -ComputerName [] -Credentials []
> Invoke-Command -ScriptBlock { Start-Job -ScriptBlock {ps}} -Session $sess
---------------------------------------------------------------------------------
.NET Classes
# First One is Using Assembly Name
Using .NET - Exploring .NET Classes
Explore Assemblies :
[AppDomain]::currentDomain.GetAssemblies()
> [AppDomain]::currentDomain.GetAssemblies() | ForEach-Object {$_.GetTypes()} | Where-Object {$_.IsPublic -eq 'True'}
Public Classes
> $classes = [AppDomain]::currentDomain.GetAssemblies() | ForEach-Object {$_.GetTypes()} | Where-Object {$_.IsPublic -eq 'True'}
> $ProcClass = $classes | Where-Object {$_.Name -eq "Process"}
Get-Member : it is used to list the methods and Properties of an object
> $ProcClass | Get-Member
> $ProcClass | Get-Member -MemberType Method : This list only methods
Get-Member By Default Doesnot Show Static and Intrinsic member
for that we have to print it using -Static
> $ProcClass | Get-Member -MemberType Method -Static
> $ProcClass::GetCurrentProcess()
> $procClass.FullName
> [System.Diagnostics.Process]::GetCurrentProcess()
> $ProcClass | Get-Member | Format-List
Using .NET - Add Type
=> Add type is used whenever you want to extend the functionality of Powershell with the help of .NET
=> The Add-Type cmdlet lets you define a Microsoft . NET Core class in your PowerShell session
Adding of Class
> Add-Type -AssemblyName System.Windows.Forms
Class has been loaded to check
> [System.Windows.Forms.SendKeys]
> [System.Windows.Forms.SendKeys] | Get-Member -Static
=> List Devices in Powershell Without WMIC
> Add-Type -AssemblyName System.ServiceProcess
> [System.ServiceProcess.ServiceController]
> [System.ServiceProcess.ServiceController]::GetServices() | Where-Object {$_.Status -eq "Running"} : Getting all the running Services
Second Method - Using New-Object
--------
Use Add-Type with -FromSource
New-Object
$Dotnetcode = @"
public class SysCommands{
public static void lookup (string DomainName){
System.Diagnostics.Process.Start("nslookup.exe",DomainName);
}
public void netcmd (string cmd){
string cmdString = "/k net.exe " + cmd;
System.Diagnostics.Process.Start("cmd.exe",cmdString);
}
}
"@
Add-Type -TypeDefinition $Dotnetcode
[SysCommands]::lookup("google.com")
# Creating a onject of SysCommads CLass
$obj = New-Object SysCommands This is the main part
$obj.netcmd("user")
Third Type - Using .NET Type
---------------------------
use Add-Type with -FromPath
-Compiling DLLs/ConsoleApps
-Using Dlls
Objects can be pass through using -passthru
> $obj = Add-Type -Path .\syscommands.dll -PassThru
> $obj.GetMethod() | Where-Object {$_.Name -eq "netcmd"}
$Dotnetcode = @"
public class SysCommands2{
public static void lookup (string DomainName){
System.Diagnostics.Process.Start("nslookup.exe",DomainName);
}
public void netcmd (string cmd){
string cmdString = "/k net.exe " + cmd;
System.Diagnostics.Process.Start("cmd.exe",cmdString);
}
public static void Main(){
string cmdString = "/k net.exe " + "user";
System.Diagnostics.Process.Start("cmd.exe",cmdString);
}
}
"@
#Add-Type -TypeDefinition $Dotnetcode -OutputType Library -OutputAssembly C:\Users\AnshPC\Desktop\syscommands.dll
Add-Type -TypeDefinition $Dotnetcode -OutputType ConsoleApplication -OutputAssembly C:\Users\AnshPC\Desktop\Syscommands.exe
<#[SysCommands2]::lookup("google.com")
# Creating a onject of SysCommads CLass
$obj = New-Object SysCommands2
$obj.netcmd("user")#>
Fourth Type : .NET
------------------
- use Add-Type with -MemberDefinition
- Making Window Api Calls
- Getting Signature (pinvoke.net recommended)
- Make the method Declaration public
- Use the modification signature in Add-Type -MemberDefinition
---------------------------------------------------------------------------------
WMI : Window Management Instrumentation
=> WMI is used to access management information across platforms in an enterprise
Cmdlets
Exploring Namespaces
> Get-Wmiobject -Namespace "root" -class "__Namespace" | select name
# WMI contain Namespaces which are the collection of classes to Hold object of different types
> Get-Wmiobject -Namespace "root" -class "__Namespace" | select name
# Exploring Classes
> Get-WmiObject -Namespace "roo/cimv2" -List
> Get-WmiObject -Namespace "root/cimv2"-List | Where-Object {$_.Name -match "Process"}
# Exploring Methods
> Get-WmiObject -class Win32_process -List | Select-Object -ExpandProperty Methods
WMI Using Cmdlets
- Using Get-WmiObject ( local and remote )
- Filter
- Get-WmiObject -Class Win32_process -Filter {Name ="Powershell.exe"}
- Where-Object
- Get-WmiObject -Class Win32_process | Where-Object {$_.Name -eq "powershell.exe"}
- Query {accepts query in format similar to SQL Query}
- Get-WmiObject -Query {Select * From Win32_Process Where Name = "Powershell.exe "}
- Remove Wmi Object
Remote :
> Get-WmiObject -Class [eg. Win32_process] -ComputerName [] -Credential []
WMI - Using Cmdlets
- Invoke-WmiMethod ( local and remote )
- Running executables
- Running Powershell commands and Scripts
> Invoke-WmiMethod -Class Win32_process -Name Create -ArgumentList "notepad.exe"
> Invoke-WmiMethod -Class Win32_process -Name Create -ArgumentList "cmd.exe"
To run it Remotely
> Invoke-WmiMethod -Class Win32_process -Name Create -ArgumentList "notepad.exe" -ComputerName [] -Credential []
> Invoke-WmiMethod -Class Win32_process -Name Create -ArgumentList "powershell.exe -noexit -c dir"
> Invoke-WmiMethod -Class Win32_process -Name Create -ArgumentList "powershell.exe -noexit -c dir" -ComputerName [] -Credentials []
---------------------------------------------------------------------------------
COM Object in Powershell
COM Object are Interfaces to various windows application
Exploring COM Objects
> Get-ChildItem REGISTRY::HKEY_CLASSES_ROOT\CLSID\ -Include PROGID -Recurse | ForEach {$_.GetValue("") } | Where-Object {$_ -match "<appname>"}
> Get-ChildItem REGISTRY::HKEY_CLASSES_ROOT\CLSID\ -Include PROGID -Recurse | ForEach {$_.GetValue("") } | Where-Object {$_ -match "wscript"}
> $wscript = New-Object -ComObject WScript.Shell.1
> $wscript | Get-Member
> $wscript.CurrentDirectory
> $wscript.SpecialFolders
> $wscript.Popup("Hello")
> $wscript.Exec("notepad.exe")
---------------------------------------------------------------------------------
Reading Windows Registry
- Registry Provider
- Reading Registry
- Get-Items
- Get-ChildItem
- Get-ChildItemProperty
- Accessing all registry hives
Ques : What is Windows Registry
Ans : The Windows Registry is a database which is maintained by Windows and is loaded into your computer’s memory when your system starts. This Registry holds all the information that Windows needs to communicate with your computer hardware, behave according to each user’s settings, and also maintains an on-going update of itself as these settings change.
Windows will write this updated data back to your drive during the shut-down process. This is one very good reason to let Windows shut down your PC and for you not to simply push the power button.
Powershell provide a PSProvider for the windows Registry
> Get-PSProvider -PSProvider Registry
Reading Registry Using Commands :
Using Get-Item
> Get-Item 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\'
> Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\'
> Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\' | Foramt-List *
> Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\'
> Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\' -Recurse
To Access all the Registry use :
> Set-Location Registry::
> ls
Editing Windows Registry
- Cmdlets
- New-Item
- New-ItemProperty
- Set-Item
- Set-ItemProperty
- Rename-Item
- Rename-ItemProperty
> New-Item -Path HKCU:\PFPT
> New-Item -Path HKCU:\PFPT\NewSubDir
> New-ItemProperty -Path HKCU:\PFPT -Name Reg2 -PropertyType String -Value 2
> Rename-Item HKCU:\PFPT -newname PFPTNew
> Rename-ItemProperty HKCU:\PFPTNew -Name reg2 -NewName reg1
Attaching sticky key to debugger so that it is execute whenever shift key is press for 5 times
Create a registry key
> New-Item 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe'
> New-ItemProperty 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe' -Name Debugger -PropertyType String -Value cmd.exe
Windows Registry on Remote Computer
Three Ways to Access Window Registry Remotely
1. Powershell Remoting
2. WMI : https://github.com/darkoperator/Posh-SecMod/blob/master/Registry/Registry.ps1
3. .NET
Powershell Remoting
Using PSSession
> Enter-PSSession -ComputerName [] -Credential []
> Get-Item 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion'
> Exit
Using Invoke Command
> Invoke-Command -ScriptBlock{HKLM:\Software} -ComputerName [] -credential []
Using Wmic
> $RemoteReg = Get-WmiObject -List "StdRegProv" -ComputerName [] -credential []
> $RemoteReg | Select-Object -ExpandProperty method
> $RemoteReg.GetStringValue(identifier, "Software\Microsoft\Windows NT\CurrentVersion","Productname")
These identifier an be easily taken from internet
Using .NET Method : Cannot Pass Alternate Credentials
> [Microsoft.Win32.RegistryKey].getMethod()
---------------------------------------------------------------------------------
Pentesting Methodology
Tools Required for Offensive Powershell
1 - Nishang : https://github.com/samratashok/nishang
2 - PowerSploit : https://github.com/mattifestation/powersploit
3 - PowerTools : https://github.com/Veil-FrameWork/powertools
4 - Posh-SecMod : https://github.com/darkoperator/Posh-SecMod/
Recon and Scanning Part 1
- Host-Discovery
- Port-Scan
- other Recon method
commands :
To get to know about all the commands use :
> Get-Command -Module nishang
1. Host Discovery in Nishang
> Import-Module .\nishang\
> Port-Scan -StartAddress [ip] -EndAddress [ip] -ResolveHost
2. HostDiscovery scanning using powersploit
> Import-Module .\PowerSploit\PowerSploit.psd1\
> Invoke-PortScan -Hosts google.com -PingOnly
3. Posh-SecMod
> Import-Module .\Posh-SecMod\Posh-SecMod.psd1
> Invoke-ARPScan -CIDR [ip eg. 192.168.0.0/24]