Comprehensive Code Analysis: ExampleContainers
Table of Contents
1. Overview and Purpose
2. Architecture and Structure
3. Key Components Analysis
4. Technical Implementation Details
5. External Dependencies and Integrations
6. Code Quality Assessment
7. Usage and Interface
8. Notable Features and Highlights
1. Overview and Purpose
Programming Languages Used
Go (Golang) - Primary language for service containers
Python - Alternative implementation for service containers
JavaScript (JXA - JavaScript for Automation) - Agent payload implementation for macOS
JSON - Configuration and data exchange format
Overall Purpose and Functionality
ExampleContainers is a demonstration framework for the Mythic Command & Control (C2) platform . It serves as a reference implementation showing how to create
modular C2 services including:
Payload Types: Malware agents that execute on target systems
C2 Profiles : Communication protocols between agents and the C2 server
Supporting Services: Logging, webhooks, translation, authentication, and event processing
Problem Solved
This codebase addresses the need for:
Modular C2 framework development
Cross-platform agent deployment (Linux, macOS, Windows)
Flexible communication protocols (HTTP, WebSocket)
Scalable service architecture with container support
Educational reference for security researchers and red teamers
Application Type
Distributed cybersecurity framework consisting of:
Container-based microservices
Agent-based remote access tools
C2 infrastructure components
Development/testing framework for security tooling
2. Architecture and Structure
High-Level Architecture
The system follows a microservices architecture with the following layers:
┌─────────────────────────────────────────────────────────────┐
│ Mythic Core Server │
├─────────────────────────────────────────────────────────────┤
│ RabbitMQ / gRPC │
├─────────────────────────────────────────────────────────────┤
│ Go Services Container │ Python Services Container │
│ ├─ Basic Agent │ ├─ Basic Python Agent │
│ ├─ HTTP C2 Profile │ ├─ WebSocket C2 Profile │
│ ├─ Logger Service │ ├─ Logger Service │
│ ├─ Webhook Service │ ├─ Webhook Service │
│ ├─ Translation Service │ ├─ Translation Service │
│ ├─ Auth Service │ └─ Event Processing │
│ └─ Event Processing │ │
├─────────────────────────────────────────────────────────────┤
│ Target Systems │
│ (Deployed Agent Payloads) │
└─────────────────────────────────────────────────────────────┘
File/Module Organization
ExampleContainers/
├── [Link] # Container configuration
├── Payload_Type/
│ ├── go_services/ # Go-based service implementations
│ │ ├── [Link] # Service orchestrator
│ │ ├── basic_agent/ # Go payload type implementation
│ │ ├── http/ # HTTP C2 profile
│ │ ├── my_logger/ # Logging service
│ │ ├── my_webhooks/ # Webhook notifications
│ │ ├── my_auth/ # Authentication service
│ │ ├── my_event_processor/ # Event handling
│ │ └── no_actual_translation/ # Translation service stub
│ └── python_services/ # Python-based service implementations
│ ├── [Link] # Service orchestrator
│ ├── basic_python_agent/ # Python payload type (JXA)
│ ├── websocket/ # WebSocket C2 profile
│ ├── translator/ # Translation service
│ ├── my_logger/ # Logging service
│ └── mywebhook/ # Webhook service
├── C2_Profiles/ # C2 profile definitions (empty - examples in services)
├── documentation-c2/ # C2 documentation (placeholder)
└── documentation-payload/ # Payload documentation (placeholder)
Design Patterns Used
1. Factory Pattern: Service initialization and registration
2. Strategy Pattern: Multiple C2 communication protocols
3. Observer Pattern : Event processing and logging
4. Builder Pattern: Payload construction with parameters
5. Plugin Architecture: Modular service loading
Data Flow and Control Flow
1. Service Registration: Services register with Mythic core via RabbitMQ/gRPC
2. Payload Building : Agents are compiled with specific configurations
3. C2 Communication : Agents communicate through configured profiles
4. Task Processing : Commands flow from Mythic → Agent → Response
5. Event Processing: Actions trigger logging, webhooks, and notifications
3. Key Components Analysis
A. Go Services Container ( [Link] )
Purpose: Orchestrates all Go-based Mythic services in a single container
Key Function:
func main() {
// Initialize all services
[Link]()
[Link]()
[Link]()
my_webhooks.Initialize()
my_logger.Initialize()
my_event_processor.Initialize()
my_auth.Initialize()
// Start service listeners
[Link]([][Link]{
MythicContainer.MythicServiceC2,
[Link],
[Link],
[Link],
[Link],
[Link],
[Link],
})
}
Dependencies: MythicContainer library, individual service modules Output: Running service container that communicates with Mythic core
B. Basic Agent Payload Builder ( basic_agent/agentfunctions/[Link] )
Purpose: Compiles Go-based agents with custom configurations
Key Features :
Cross-platform compilation (Linux, macOS, Windows)
Multiple architectures (AMD64, ARM64)
Build modes: executable, shared library, C archive
Optional obfuscation with Garble
Configurable C2 parameters
Build Process:
1. Parse build parameters and C2 configuration
2. Generate Go build command with link flags
3. Set cross-compilation environment variables
4. Execute build with optional obfuscation
5. Return compiled payload binary
C. HTTP C2 Profile ( http/c2functions/[Link] )
Purpose: Implements HTTP-based command and control communication
Key Components:
Configuration Validation: Ensures SSL/port compatibility
Redirector Rules: Generates mod_rewrite rules for traffic forwarding
OPSEC Checks: Validates configuration for operational security
Parameter Management : Handles callbacks, encryption, headers
Parameters:
Callback host/port configuration
HTTP headers customization
AES encryption settings
Proxy support
Jitter and timing controls
D. Python Services Container ( [Link] )
Purpose: Orchestrates Python-based Mythic services
import mythic_container
import basic_python_agent
import [Link].c2_functions.websocket
from [Link] import *
from my_logger import logger
mythic_container.mythic_service.start_and_run_forever()
Architecture: Import-based service registration with automatic class discovery
E. Basic Python Agent ( basic_python_agent/agent_functions/[Link] )
Purpose: Builds JavaScript for Automation (JXA) payloads for macOS
Key Features :
JXA-based agent for macOS systems
Dynamic command integration
C2 profile templating
Base64 encoding and configuration stamping
Build Process:
1. Gather command implementation files
2. Load base JXA template
3. Inject UUID and commands
4. Configure C2 profile parameters
5. Return JavaScript payload
F. WebSocket C2 Profile ( websocket/mythic/c2_functions/[Link] )
Purpose: WebSocket-based C2 communication protocol
Configuration Parameters:
WebSocket callback host (ws:// or [Link]
User-Agent strings
AES encryption settings
Callback intervals and jitter
Domain fronting support
4. Technical Implementation Details
Data Structures
Go Services
[Link]: Payload configuration and metadata
[Link]: Build-time configuration options
c2structs.C2Profile : C2 communication profile definition
[Link]: Webhook service configuration
Python Services
PayloadType: Base class for payload implementations
C2Profile: Base class for C2 protocol implementations
C2ProfileParameter: Configuration parameter definitions
Algorithms and Logic
Payload Building Algorithm
1. Parameter Validation : Verify build parameters and C2 settings
2. Cross-Compilation Setup: Configure GOOS, GOARCH, CC variables
3. Linker Flag Generation: Create ldflags with configuration values
4. Optional Obfuscation : Apply Garble if enabled
5. Binary Generation: Execute go build command
6. File Handling : Read and return compiled binary
C2 Communication Flow
1. Key Exchange (if enabled): RSA + AES hybrid encryption setup
2. Agent Check-in: Initial registration with system information
3. Task Polling: Periodic requests for new commands
4. Command Execution: Process and execute received tasks
5. Response Transmission : Send results back to C2 server
Error Handling
Build Failures: Comprehensive stderr capture and reporting
Communication Errors: Retry logic with exponential backoff
Validation Errors : Parameter verification and user feedback
Service Failures: Graceful degradation and logging
Security Considerations
Encryption
AES-256 with HMAC: Message authentication and confidentiality
RSA Key Exchange : Secure session key establishment
Base64 Encoding : Data transport encoding
OPSEC Features
Configurable User-Agents : Blend with normal traffic
Custom Headers : HTTP header customization
Jitter: Randomized communication timing
Kill Dates: Automatic agent termination
Proxy Support: Traffic routing through proxies
Validation
Parameter Verification: Regex-based input validation
SSL/Port Compatibility: Configuration consistency checks
Certificate Validation : SSL certificate handling
Performance Considerations
Chunked Transfers: Large file upload/download optimization
Compression: Optional payload compression
Connection Pooling: Efficient HTTP connection reuse
Asynchronous Processing: Non-blocking service operations
5. External Dependencies and Integrations
Go Dependencies ( [Link] )
require (
[Link]/MythicMeta/MythicContainer v1.4.23 // Core Mythic integration
[Link]/Khan/genqlient v0.8.0 // GraphQL client generation
[Link]/crewjam/saml v0.4.14 // SAML authentication
[Link]/mitchellh/mapstructure v1.5.0 // Struct mapping utilities
)
Python Dependencies
mythic_container: Core Python integration library
asyncio: Asynchronous programming support
pathlib: Path manipulation utilities
External Services Integration
Mythic Core Server
RabbitMQ: Message queue for service communication
gRPC: Direct communication for translation services
GraphQL: API queries and mutations
PostgreSQL: Database backend (implicit)
Build Tools
Go Compiler: Cross-platform binary generation
Garble: Go code obfuscation tool
GCC Cross-Compilers:
o64-clang (macOS targeting)
x86_64-w64-mingw32-gcc (Windows targeting)
aarch64-linux-gnu-gcc (ARM64 Linux targeting)
Third-Party Services
Slack Webhooks: Notification integration
SAML Providers : Authentication integration
HTTP Proxies: Traffic routing
Configuration Requirements
Environment Variables: Service connection parameters
Docker Compose: Container orchestration
SSL Certificates: HTTPS communication
Network Configuration: Port bindings and firewall rules
6. Code Quality Assessment
Readability
Strengths:
Clear function and variable naming conventions
Consistent indentation and formatting
Logical code organization with separate modules
Comprehensive inline comments in complex sections
Areas for Improvement:
Some functions are quite long (e.g., HTTP C2 builder functions)
Magic numbers could be replaced with named constants
Complex conditional logic could benefit from decomposition
Maintainability
Strengths:
Modular Design: Clear separation of concerns
Plugin Architecture: Easy to add new services
Configuration-Driven : Externalized settings
Error Handling : Comprehensive error reporting
Areas for Improvement:
Some code duplication between Go and Python implementations
Hard-coded paths in several places
Limited automated testing visible in codebase
Best Practices Adherence
Go Code:
Proper error handling with explicit returns
Use of Go modules for dependency management
Structured logging integration
Interface-based design patterns
Python Code:
Class-based inheritance patterns
Async/await usage where appropriate
Proper import organization
Type hints in function signatures
JavaScript Code:
Error handling with try-catch blocks
Object-oriented design patterns
Consistent code formatting
⚠️ Some global variables and magic numbers
Potential Improvements
1. Add Unit Tests: Comprehensive test coverage for all services
2. Configuration Validation: More robust parameter validation
3. Documentation: API documentation and usage examples
4. Logging Standards: Consistent logging levels and formats
5. Error Recovery : More graceful failure handling
6. Code Deduplication: Shared utility functions
7. Usage and Interface
How to Run/Execute
Go Services
cd ExampleContainers/Payload_Type/go_services
go mod download && go mod tidy
go build -o mythic_go_services .
make run_custom # With environment variables set in Makefile
Python Services
cd ExampleContainers/Payload_Type/python_services
python [Link]
Docker Deployment
The services are designed to run within Docker containers as part of the Mythic ecosystem.
Environment Variables
DEBUG_LEVEL="trace"
RABBITMQ_HOST="[Link]"
RABBITMQ_PASSWORD="[password]"
MYTHIC_SERVER_HOST="[Link]"
MYTHIC_SERVER_GRPC_PORT="17444"
WEBHOOK_DEFAULT_URL="[webhook_url]"
Configuration Options
Build Parameters
mode: default , c-archive , c-shared
architecture: AMD_x64 , ARM_x64
proxy_bypass : Boolean flag
garble: Enable obfuscation
C2 Parameters
callback_host: Target C2 server URL
callback_port: Communication port
headers: Custom HTTP headers
AESPSK: Encryption configuration
jitter: Communication randomization percentage
Input/Output Formats
Payload Build Response
{
"PayloadUUID": "uuid-string",
"Success": true,
"Payload": "base64-encoded-binary",
"BuildMessage": "Success message",
"BuildStdOut": "compilation output",
"BuildStdErr": "error output"
}
Agent Communication
{
"action": "get_tasking",
"tasking_size": 1,
"tasks": [
{
"id": "task-id",
"command": "ls",
"parameters": {"path": "/tmp"}
}
]
}
8. Notable Features and Highlights
Clever Implementations
1. Cross-Platform Build System
The Go payload builder demonstrates sophisticated cross-compilation:
goarch := "amd64"
if architecture == "ARM_x64" {
goarch = "arm64"
}
command := [Link]("CGO_ENABLED=1 GOOS=%s GOARCH=%s ", targetOs, goarch)
if targetOs == "darwin" {
command += "CC=o64-clang CXX=o64-clang++ "
} else if targetOs == "windows" {
command += "CC=x86_64-w64-mingw32-gcc "
}
2. Hybrid Encryption in JXA Agent
The JavaScript agent implements sophisticated RSA+AES hybrid encryption:
RSA for initial key exchange
AES-256-CBC for bulk data encryption
HMAC-SHA256 for message authentication
Automatic key negotiation on first connection
3. Dynamic Service Registration
Both Go and Python implementations use elegant service registration patterns:
// Go approach
[Link]("basicAgent").AddPayloadDefinition(payloadDefinition)
[Link]("basicAgent").AddBuildFunction(build)
# Python approach - automatic class discovery
mythic_container.mythic_service.start_and_run_forever()
Complex Business Logic
1. SSL/Port Validation Logic
The HTTP C2 profile includes sophisticated validation for SSL/port combinations:
if [Link](parameterHost, "https") && ![Link] {
message := [Link]("C2 Profile container is configured to NOT use SSL on port %d, but the callback host for the agent is using https,
message += "This means there should be the following connectivity for success:\n"
message += [Link]("Agent via SSL to %s on port %d, then redirection to C2 Profile container WITHOUT SSL on port %d", parameterHost,
[Link] = message
[Link] = false
return response
}
2. Mod_Rewrite Rule Generation
Automatic generation of Apache mod_rewrite rules for traffic redirection:
htaccessTemplate := `
RewriteEngine On
RewriteCond %%{REQUEST_METHOD} ^(GET|POST) [NC]
RewriteCond %%{REQUEST_URI} ^({%s})$
RewriteCond %%{HTTP_USER_AGENT} "{%s}"
%s
RewriteRule ^.*$ {redirect}/? [L,R=302]
`
Interesting Technical Choices
1. JXA for macOS Agents
Using JavaScript for Automation provides:
Native macOS API access
Bypasses traditional binary detection
Leverages existing JavaScript obfuscation techniques
Enables living-off-the-land tactics
2. Container-Based Architecture
Microservices approach enables:
Independent service scaling
Language diversity (Go + Python)
Fault isolation
Easy deployment and updates
3. Dual Communication Protocols
Supporting both RabbitMQ and gRPC:
RabbitMQ for asynchronous messaging
gRPC for synchronous translation services
Optimal protocol selection per use case
Unique Aspects
1. Educational Framework Design
The codebase serves as both functional software and educational resource:
Clear separation between examples and production code
Comprehensive parameter documentation
OPSEC guidance built into validation functions
2. OPSEC-Aware Implementation
Security considerations built into the design:
Kill date functionality
Traffic jitter and randomization
User-Agent and header customization
Proxy support for traffic routing
3. Multi-Language Agent Support
Demonstrates platform-specific optimization:
Go agents for cross-platform compatibility
JXA agents for macOS-specific capabilities
WebSocket vs HTTP protocol options
Conclusion
ExampleContainers represents a well-architected demonstration of modern C2 framework design. The codebase successfully balances educational value with
functional implementation, providing clear examples of:
Microservices Architecture: Clean separation of concerns
Cross-Platform Compatibility: Sophisticated build systems
Security-First Design : Built-in OPSEC considerations
Extensible Framework : Plugin-based architecture
Production-Ready Features : Encryption, error handling, logging
The code quality is generally high with good documentation, error handling, and modular design. Areas for improvement include increased test coverage, reduced
code duplication, and enhanced configuration validation.
This framework serves as an excellent reference for security researchers, red team operators, and developers interested in understanding modern C2 architecture and
implementation patterns.