Red Team Notes
  • What is ired.team notes?
  • Pinned
    • Pentesting Cheatsheets
      • SQL Injection & XSS Playground
    • Active Directory & Kerberos Abuse
      • From Domain Admin to Enterprise Admin
      • Kerberoasting
      • Kerberos: Golden Tickets
      • Kerberos: Silver Tickets
      • AS-REP Roasting
      • Kerberoasting: Requesting RC4 Encrypted TGS when AES is Enabled
      • Kerberos Unconstrained Delegation
      • Kerberos Constrained Delegation
      • Kerberos Resource-based Constrained Delegation: Computer Object Takeover
      • Domain Compromise via DC Print Server and Kerberos Delegation
      • DCShadow - Becoming a Rogue Domain Controller
      • DCSync: Dump Password Hashes from Domain Controller
      • PowerView: Active Directory Enumeration
      • Abusing Active Directory ACLs/ACEs
      • Privileged Accounts and Token Privileges
      • From DnsAdmins to SYSTEM to Domain Compromise
      • Pass the Hash with Machine$ Accounts
      • BloodHound with Kali Linux: 101
      • Backdooring AdminSDHolder for Persistence
      • Active Directory Enumeration with AD Module without RSAT or Admin Privileges
      • Enumerating AD Object Permissions with dsacls
      • Active Directory Password Spraying
      • Active Directory Lab with Hyper-V and PowerShell
      • ADCS + PetitPotam NTLM Relay: Obtaining krbtgt Hash with Domain Controller Machine Certificate
      • From Misconfigured Certificate Template to Domain Admin
      • Shadow Credentials
      • Abusing Trust Account$: Accessing Resources on a Trusted Domain from a Trusting Domain
  • offensive security
    • Red Team Infrastructure
      • HTTP Forwarders / Relays
      • SMTP Forwarders / Relays
      • Phishing with Modlishka Reverse HTTP Proxy
      • Automating Red Team Infrastructure with Terraform
      • Cobalt Strike 101
      • Powershell Empire 101
      • Spiderfoot 101 with Kali using Docker
    • Initial Access
      • Password Spraying Outlook Web Access: Remote Shell
      • Phishing with MS Office
        • Phishing: XLM / Macro 4.0
        • T1173: Phishing - DDE
        • T1137: Phishing - Office Macros
        • Phishing: OLE + LNK
        • Phishing: Embedded Internet Explorer
        • Phishing: .SLK Excel
        • Phishing: Replacing Embedded Video with Bogus Payload
        • Inject Macros from a Remote Dotm Template
        • Bypassing Parent Child / Ancestry Detections
        • Phishing: Embedded HTML Forms
      • Phishing with GoPhish and DigitalOcean
      • Forced Authentication
      • NetNTLMv2 hash stealing using Outlook
    • Code Execution
      • regsvr32
      • MSHTA
      • Control Panel Item
      • Executing Code as a Control Panel Item through an Exported Cplapplet Function
      • Code Execution through Control Panel Add-ins
      • CMSTP
      • InstallUtil
      • Using MSBuild to Execute Shellcode in C#
      • Forfiles Indirect Command Execution
      • Application Whitelisting Bypass with WMIC and XSL
      • Powershell Without Powershell.exe
      • Powershell Constrained Language Mode Bypass
      • Forcing Iexplore.exe to Load a Malicious DLL via COM Abuse
      • pubprn.vbs Signed Script Code Execution
    • Code & Process Injection
      • CreateRemoteThread Shellcode Injection
      • DLL Injection
      • Reflective DLL Injection
      • Shellcode Reflective DLL Injection
      • Process Doppelganging
      • Loading and Executing Shellcode From PE Resources
      • Process Hollowing and Portable Executable Relocations
      • APC Queue Code Injection
      • Early Bird APC Queue Code Injection
      • Shellcode Execution in a Local Process with QueueUserAPC and NtTestAlert
      • Shellcode Execution through Fibers
      • Shellcode Execution via CreateThreadpoolWait
      • Local Shellcode Execution without Windows APIs
      • Injecting to Remote Process via Thread Hijacking
      • SetWindowHookEx Code Injection
      • Finding Kernel32 Base and Function Addresses in Shellcode
      • Executing Shellcode with Inline Assembly in C/C++
      • Writing Custom Shellcode Encoders and Decoders
      • Backdooring PE Files with Shellcode
      • NtCreateSection + NtMapViewOfSection Code Injection
      • AddressOfEntryPoint Code Injection without VirtualAllocEx RWX
      • Module Stomping for Shellcode Injection
      • PE Injection: Executing PEs inside Remote Processes
      • API Monitoring and Hooking for Offensive Tooling
      • Windows API Hooking
      • Import Adress Table (IAT) Hooking
      • DLL Injection via a Custom .NET Garbage Collector
      • Writing and Compiling Shellcode in C
      • Injecting .NET Assembly to an Unmanaged Process
      • Binary Exploitation
        • 32-bit Stack-based Buffer Overflow
        • 64-bit Stack-based Buffer Overflow
        • Return-to-libc / ret2libc
        • ROP Chaining: Return Oriented Programming
        • SEH Based Buffer Overflow
        • Format String Bug
    • Defense Evasion
      • AV Bypass with Metasploit Templates and Custom Binaries
      • Evading Windows Defender with 1 Byte Change
      • Bypassing Windows Defender: One TCP Socket Away From Meterpreter and Beacon Sessions
      • Bypassing Cylance and other AVs/EDRs by Unhooking Windows APIs
      • Windows API Hashing in Malware
      • Detecting Hooked Syscalls
      • Calling Syscalls Directly from Visual Studio to Bypass AVs/EDRs
      • Retrieving ntdll Syscall Stubs from Disk at Run-time
      • Full DLL Unhooking with C++
      • Enumerating RWX Protected Memory Regions for Code Injection
      • Disabling Windows Event Logs by Suspending EventLog Service Threads
      • Obfuscated Powershell Invocations
      • Masquerading Processes in Userland via _PEB
      • Commandline Obfusaction
      • File Smuggling with HTML and JavaScript
      • Timestomping
      • Alternate Data Streams
      • Hidden Files
      • Encode/Decode Data with Certutil
      • Downloading Files with Certutil
      • Packed Binaries
      • Unloading Sysmon Driver
      • Bypassing IDS Signatures with Simple Reverse Shells
      • Preventing 3rd Party DLLs from Injecting into your Malware
      • ProcessDynamicCodePolicy: Arbitrary Code Guard (ACG)
      • Parent Process ID (PPID) Spoofing
      • Executing C# Assemblies from Jscript and wscript with DotNetToJscript
    • Enumeration and Discovery
      • Windows Event IDs and Others for Situational Awareness
      • Enumerating COM Objects and their Methods
      • Enumerating Users without net, Services without sc and Scheduled Tasks without schtasks
      • Enumerating Windows Domains with rpcclient through SocksProxy == Bypassing Command Line Logging
      • Dump Global Address List (GAL) from OWA
      • Application Window Discovery
      • Account Discovery & Enumeration
      • Using COM to Enumerate Hostname, Username, Domain, Network Drives
      • Detecting Sysmon on the Victim Host
    • Privilege Escalation
      • Primary Access Token Manipulation
      • Windows NamedPipes 101 + Privilege Escalation
      • DLL Hijacking
      • WebShells
      • Image File Execution Options Injection
      • Unquoted Service Paths
      • Pass The Hash: Privilege Escalation with Invoke-WMIExec
      • Environment Variable $Path Interception
      • Weak Service Permissions
    • Credential Access & Dumping
      • Dumping Credentials from Lsass Process Memory with Mimikatz
      • Dumping Lsass Without Mimikatz
      • Dumping Lsass without Mimikatz with MiniDumpWriteDump
      • Dumping Hashes from SAM via Registry
      • Dumping SAM via esentutl.exe
      • Dumping LSA Secrets
      • Dumping and Cracking mscash - Cached Domain Credentials
      • Dumping Domain Controller Hashes Locally and Remotely
      • Dumping Domain Controller Hashes via wmic and Vssadmin Shadow Copy
      • Network vs Interactive Logons
      • Reading DPAPI Encrypted Secrets with Mimikatz and C++
      • Credentials in Registry
      • Password Filter
      • Forcing WDigest to Store Credentials in Plaintext
      • Dumping Delegated Default Kerberos and NTLM Credentials w/o Touching Lsass
      • Intercepting Logon Credentials via Custom Security Support Provider and Authentication Packages
      • Pulling Web Application Passwords by Hooking HTML Input Fields
      • Intercepting Logon Credentials by Hooking msv1_0!SpAcceptCredentials
      • Credentials Collection via CredUIPromptForCredentials
    • Lateral Movement
      • WinRM for Lateral Movement
      • WinRS for Lateral Movement
      • WMI for Lateral Movement
      • RDP Hijacking for Lateral Movement with tscon
      • Shared Webroot
      • Lateral Movement via DCOM
      • WMI + MSI Lateral Movement
      • Lateral Movement via Service Configuration Manager
      • Lateral Movement via SMB Relaying
      • WMI + NewScheduledTaskAction Lateral Movement
      • WMI + PowerShell Desired State Configuration Lateral Movement
      • Simple TCP Relaying with NetCat
      • Empire Shells with NetNLTMv2 Relaying
      • Lateral Movement with Psexec
      • From Beacon to Interactive RDP Session
      • SSH Tunnelling / Port Forwarding
      • Lateral Movement via WMI Event Subscription
      • Lateral Movement via DLL Hijacking
      • Lateral Movement over headless RDP with SharpRDP
      • Man-in-the-Browser via Chrome Extension
      • ShadowMove: Lateral Movement by Duplicating Existing Sockets
    • Persistence
      • DLL Proxying for Persistence
      • Schtask
      • Service Execution
      • Sticky Keys
      • Create Account
      • AddMonitor()
      • NetSh Helper DLL
      • Abusing Windows Managent Instrumentation
        • WMI as a Data Storage
      • Windows Logon Helper
      • Hijacking Default File Extension
      • Persisting in svchost.exe with a Service DLL
      • Modifying .lnk Shortcuts
      • Screensaver Hijack
      • Application Shimming
      • BITS Jobs
      • COM Hijacking
      • SIP & Trust Provider Hijacking
      • Hijacking Time Providers
      • Installing Root Certificate
      • Powershell Profile Persistence
      • RID Hijacking
      • Word Library Add-Ins
      • Office Templates
    • Exfiltration
      • Powershell Payload Delivery via DNS using Invoke-PowerCloud
  • reversing, forensics & misc
    • Internals
      • Configuring Kernel Debugging Environment with kdnet and WinDBG Preview
      • Compiling a Simple Kernel Driver, DbgPrint, DbgView
      • Loading Windows Kernel Driver for Debugging
      • Subscribing to Process Creation, Thread Creation and Image Load Notifications from a Kernel Driver
      • Listing Open Handles and Finding Kernel Object Addresses
      • Sending Commands From Your Userland Program to Your Kernel Driver using IOCTL
      • Windows Kernel Drivers 101
      • Windows x64 Calling Convention: Stack Frame
      • Linux x64 Calling Convention: Stack Frame
      • System Service Descriptor Table - SSDT
      • Interrupt Descriptor Table - IDT
      • Token Abuse for Privilege Escalation in Kernel
      • Manipulating ActiveProcessLinks to Hide Processes in Userland
      • ETW: Event Tracing for Windows 101
      • Exploring Injected Threads
      • Parsing PE File Headers with C++
      • Instrumenting Windows APIs with Frida
      • Exploring Process Environment Block
      • Writing a Custom Bootloader
    • Cloud
      • AWS Accounts, Users, Groups, Roles, Policies
    • Neo4j
    • Dump Virtual Box Memory
    • AES Encryption Using Crypto++ .lib in Visual Studio C++
    • Reversing Password Checking Routine
Powered by GitBook
On this page
  • Context
  • Credits
  • Infrastructure Overview
  • Configuring Infrastructure
  • Service Providers
  • File Structure
  • Variables
  • C2
  • C2 Redirector
  • Testing C2 and C2 Redirector
  • Phishing
  • Phishing Redirector
  • Testing Phishing Redirector
  • Payload Redirector
  • Outputs
  • Download & Try
  • References
  1. offensive security
  2. Red Team Infrastructure

Automating Red Team Infrastructure with Terraform

PreviousPhishing with Modlishka Reverse HTTP ProxyNextCobalt Strike 101

Last updated 6 years ago

Context

The purpose of this lab was to get my hands dirty while building a simple, resilient and easily disposable red team infrastructure. Additionally, I wanted to play around with the the concept of Infrastructure as a Code, so I chose to tinker with a tool I have been hearing about for some time now - Terraform.

Credits

Automated red teaming infrastructure is not a new concept - quite the opposite - I drew my inspiration from the great work of he explained his process of building an automated red team environment. He based it off of the great by and - which is exactly the resource I used when labbing about the below:

...as well as this exercise.

Infrastructure Overview

Below is a high level diagram showing the infrastructure that I built for this lab - it can be and usually is much more built out, but the principle remains the same - redirectors are placed in front of each server to make the infrastructure more resilient to discovery that enables operators to quickly replace the burned servers with new ones:

  • There are 6 servers in total

  • 3 servers (phishing, payload and c2) are considered the long term servers - we do not want our friendly blue teams to discover those

  • 3 redirectors (smtp relay, payload redirector and c2 redirector) - these are the servers that sit in front of our long term servers and act as proxies. It is assumed that these servers will be detected and burned during an engagement. This is where the automation piece of Terraform comes in - since the our environment's state is defined in Terraform configuration files, we can rebuild those burned servers in almost no time and the operation can continue without bigger interruptions.

Configuring Infrastructure

Service Providers

My test red team infrasture is built by leveraging the following services and providers:

  • DigitalOcean Droplets for all the servers and redirectors

  • DigitalOcean DNS management for the smtp relay (phishing redirector) - mostly because we need the ability to set a PTR DNS record for our smtp relay in order to reduce chances of our phishing email being classified as spam by target users' mail gateways

  • CloudFlare DNS management for controlling DNS records for any other domains that point to our long-term servers

File Structure

My red team infrastructure is defined by terraform state configuration files that are currently organized in the following way:

I think the file names are self explanatory, but below gives additional info on some of the config files:

  • Configs folder - all the config files that were too big or inconvenient to modify during Droplet creation with Terraform's provisioners. It includes configs for payload redirector (apache: .htaccess, apache2.conf), smtp redirector (postfix: header_checks - for stripping out email headers of the originating smtp server, master.cf - general postfix config for TLS and opendkim, opendkim.conf - configuring DKIM integration with postfix)

  • providers - required to build the infrastructure such as DigitalOcean and CloudFlare in my case

  • variables - stores API keys and similar data used across different terraform state files

  • sshkeys - stores ssh keys that our servers and redirectors will accept logons from

  • dns - defines DNS records and specify how our servers and redirectors can be accessed

  • firewalls - define access rules - who can access which server

  • outputs - a file that prints out key IP addresses and domain names of the built infrastructure

Other key points on a couple of the files are outlined below.

Variables

Variables.tf stores things like API tokens, domain names for redirectors and c2s, operator IPs that are used in firewall rules (i.e only allow incoming connections to team server or GoPhish from an operator owned IP):

Additionally, variables.tf contains link to a password protected Cobalt Strike zip archive and the password itself:

C2

For this lab, I chose Cobalt Strike as my C2 server.

Below is the remote-exec Terraform provisioner for C2 server that downloads CS zip, unzips it with a given CS password and creates a cron job to make sure the C2 server is started once the server boots up:

C2 Redirector

I use a socat to simply redirect all incoming traffic on port 80 and 443 to the main HTTP C2 server running Cobalt Strike team server:

Testing C2 and C2 Redirector

It's easy to test if your C2 and its redirectors work as expected.

Note below - a couple of FQDNs that were printed out by Terraform when outputs.tf file was executed: static.redteam.me and ads.redteam.me both pointing to 159.203.122.243 - this is the C2 redirector IP - any traffic on port 80 and 443 will be redirected to the main C2 server, which is hosted on 68.183.150.191 as shown in the second image below:

Below gif shows the test in action and the steps are as follows:

  1. Cobalt Strike is launched and connected to the main C2 server hosted on 68.183.150.191 - it can be reached via css.ired.team

  2. a new listener on port 443 is created on the C2 host 68.183.150.191

  3. beacon hostsname are set to two subdomains on the C2 redirector - static.redteam.me and ads.redteam.me

  4. stageless beacon is generated and executed on the target system via SMB

  5. beacon calls back to *.redteam.me which redirects traffic to the C2 teamserver on 68.183.150.191 and we see a CS session popup:

Below is a screengrab of the tcpdump on C2 server which shows that the redirector IP (organge, 159.203.122.243) has initiated the connection to the C2 (blue, 68.183.150.191):

Phishing

My phishing server is running GoPhish framework, which I labbed about here:

The GoPhish is set to listen on port 3333 which I expose to the internet, but only allow access for the operator using DigitalOcean firewalls:

Again - var.operator-ip is set in variables.tf

Phishing Redirector

This was the most time consuming piece to set up. It is a known fact that setting up SMTP servers usually is a huge pain. Automating the red team infrastructure is worth purely because of the fact that you will not ever need to rebuild the SMTP server from scratch once it gets burned during the engagement.

The pain for this piece originated from setting up the smtp relay, since there were a number of moving parts to it:

  • setting up SPF records

  • setting up DKIM

  • setting up encryption

  • configuring postfix as a relay

  • sanitizing email headers to obfuscate the originating email server (the phishing server)

Testing Phishing Redirector

Once the infrastucture has been stood up, phishing redirector's (smtp relay) DNS zone should have the spf, dkim and dmarc records, similarly to those seen here:

Once DNS records are done, we can send a quick test email to gmail from the actual phishing server through the relay server and see if spf, dkim and dmarc checks PASS, which we can see below they did in our case, suggesting phishing/smtp relay is setup correctly:

attacker@kali
telnet redteam.me 25
helo redteam.me
mail from: olasenor@redteam.me
rcpt to: mantvydo@gmail.com
data
to: Mantvydas Baranauskas <mantvydo@gmail.com>
from: Ola Senor <olasenor@redteam.me>
subject: daily report

Hey Mantvydas,
As you were requesting last week - attaching as promised the documents needed to keep the project going forward.
.

Payload Redirector

Payload redirector server is built on apache2 mod_rewrite and proxy modules. Mod_rewrite module allows us to write fine-grained URL rewriting rules and proxy victim's HTTP requests to appropriate payloads as the operator deems appropriate.

.htaccess

Below is an .htaccess file that instructs apache, or to be precise mod_rewrite module, on when, where and how (i.e proxy or redirect) to rewrite incoming HTTP requests:

.htaccess
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|ipad|iphone|ipod|opera mobile|palmos|webos" [NC]
RewriteRule ^.*$ http://payloadURLForMobiles/login [P]
RewriteRule ^.*$ http://payloadURLForOtherClients/%{REQUEST_URI} [P]

Breakdown of the file:

  • Line 2 essentially says: hey, apache, if you see an incoming http request with a user agent that contains any of the words "android, blackberry, ..." etc, move to line 3

  • Line 3 instructs apache to proxy ([P]) the http request to http://payloadURLForMobiles/login. If condition in line 2 fails, move to line 4

  • If condition in line 2 fails, the http request gets proxied to http://payloadURLForOtherClients/%{REQUEST_URI} where REQUEST_URI is the part of the http request that was appended after the domain name - i.e someDomain.com/?thisIsTheRequestUri=true

Below screenshot should illustrate the above concept:

  1. green highlight - we used curl (and its default UA), which according to the .htaccess file, should have redirected us to payloadURLForOtherClients - which we see it attempted to, but of course failed since it's a test and a non-resolvable host is specified

  2. pink - we curl'ed the payload redirector again, but this time with a forged UA, masquerading the http request as if it was coming from an iphone - we can see that apache correctly attempted to proxy the request through to the payloadURLForMobiles host:

Outputs

Outputs.tf contains key server DNS names and their IP addresses for operator's reference:

Also, note the last highlighted bit - an instruction for an operator to execute a ./finalize.sh command from the working directory. It will install LetsEncrypt certificates on the smtp relay server and also print out the DKIM DNS TXT record that needs to be added to the DigitalOcean's DNS records for the smtp relay domain:

The DNS record mail._domainkey placeholder with a dummy value "I am DKIM, but change with the DKIM from finalize.sh" is created (dns.tr file) for ones convenience - that value needs to be replaced with the above highlighted DKIM value provided by the finalize.sh script.

Ideally, this step would be automated during the droplet bootstrapping, but I was not yet able to do that due to some Terraform bugs I encountered.

Below shows (top to bottom):

  • terraform config that sets up a new DNS TXT record placeholder for DKIM

  • terraform creating the DNS TXT record based on the above config from dns.tf

  • the actual result - DNS TXT record placeholder for redteam.me domain

Download & Try

If you would like to test this setup, feel free to grab the config files here:

References

Note however, you could build your servers using Amazon AWS or other popular VPS provider as long as it is supported by . Same applies to the DNS management piece. I used DigitalOcean and CloudFlare because I already had accounts and I like them ¯\_(ツ)_/¯

Terraform
Phishing with GoPhish and DigitalOcean
@_RastaMouse
where
wiki
Steve Borosh
Jeff Dimmock
Red Team Infrastructure
LogoGitHub - mantvydasb/Red-Team-Infrastructure-Automation: Disposable and resilient red team infrastructure with TerraformGitHub
LogoStrengthen Your Phishing with Apache mod_rewrite and Mobile User Redirectionbluescreenofjeff.com - a blog about penetration testing and red teaming
LogoInfrastructure as Code (Terraform + Ansible)Rasta Mouse
LogoHow To Install and Configure DKIM with Postfix on Debian Wheezy | DigitalOceanDigitalOcean
https://developers.digitalocean.com/documentation/changelog/api-v2/new-size-slugs-for-droplet-plan-changes/developers.digitalocean.com
3KB
daily report.eml
Daily report.eml
URL to a password protected Cobalt Strike zip
variables.tf showing my fake and misspelled password
C2 redirector IPs
C2 teamserver IPs
Cobalt Strike C2 & C2 redirector test
Successful C2 traffic redirection