CommandGPT: Using ChatGPT for C2 and Post-Exploitation

Jonas Bauters (Solution Lead · NVISO)

BruCON 0x0F · Day 2

Overview

In an era where the cybersecurity community often expresses skepticism about the practical application of Artificial Intelligence beyond marketing hype, Jonas Bauters of NVISO challenges this notion with his presentation, "CommandGPT: Using ChatGPT for C2 and Post-Exploitation." Bauters dives into the fascinating, and somewhat unsettling, prospect of leveraging Large Language Models (LLMs) like OpenAI's GPT for dynamic command and control (C2) operations. While acknowledging the prevailing sentiment that "we don't need another C2 and AI in cyber is mostly BS," Bauters embarks on a compelling exploration of how an LLM can be integrated into offensive security frameworks, moving beyond mere assistance to active code generation and execution.

Watch on YouTube

Visual summary for CommandGPT: Using ChatGPT for C2 and Post-Exploitation by Jonas Bauters
Visual summary for CommandGPT: Using ChatGPT for C2 and Post-Exploitation by Jonas Bauters

Key moments

  1. 5:28 Introducing CommandGPT: A C2 using AI
  2. 6:47 C# implant and runtime code compilation
  3. 16:30 Video demo: Ransomware-like emulation (keyboard, encryption)
  4. 20:00 Drawbacks: Temporary files and security detections
  5. 25:20 Improved architecture using a builder system
  6. 32:00 Future potential: Purple teaming and threat intelligence
  7. 37:00 Q&A: Risks of running unknown AI-generated code

CommandGPT: Using ChatGPT for C2 and Post-Exploitation

Speakers: Jonas Bauters, Solution Lead, NVISO

Conference: BruCON

YouTube: https://www.youtube.com/watch?v=Sv0QODx5-oM

Overview

In an era where the cybersecurity community often expresses skepticism about the practical application of Artificial Intelligence beyond marketing hype, Jonas Bauters of NVISO challenges this notion with his presentation, "CommandGPT: Using ChatGPT for C2 and Post-Exploitation." Bauters dives into the fascinating, and somewhat unsettling, prospect of leveraging Large Language Models (LLMs) like OpenAI's GPT for dynamic command and control (C2) operations. While acknowledging the prevailing sentiment that "we don't need another C2 and AI in cyber is mostly BS," Bauters embarks on a compelling exploration of how an LLM can be integrated into offensive security frameworks, moving beyond mere assistance to active code generation and execution.

This talk details the creation of a proof-of-concept implant, dubbed CommandGPT, which dynamically generates and executes post-exploitation modules at runtime by interacting with the OpenAI API. Bauters openly discusses the technical hurdles, practical limitations, and significant defensive implications of such an approach. While not advocating for its immediate operational deployment in red team engagements due to inherent risks and detection challenges, the research highlights a potent future trajectory for both legitimate red team automation and, more concerningly, for malicious actors seeking to automate and diversify their attack capabilities. The presentation serves as a critical wake-up call, demonstrating that the integration of AI into offensive toolsets is not a distant fantasy but a tangible, albeit nascent, reality.

Background

▶ Watch: Introducing CommandGPT: A C2 using AI (5:28)

The utility of Large Language Models (LLMs) like GPT in offensive security has been a topic of growing interest, extending far beyond simple query-response interactions. Bauters begins by outlining several general offensive applications where LLMs have already proven beneficial. For penetration testing, GPT can assist in crafting specific commands, such as those for SQL injection, or guiding the execution of various tools. The speaker references "Pentest GPT," a tool that automates aspects of penetration testing by providing a workflow against systems like Hack The Box, suggesting commands, analyzing output, and identifying potential vulnerabilities based on open ports or CVEs.

Beyond direct technical assistance, LLMs excel in social engineering and phishing, capable of generating convincing email content, even if initially resistant to overtly malicious requests (which can often be bypassed by framing them as "business emails"). They can also streamline mundane tasks like report writing, generating comprehensive finding descriptions, risk ratings, and recommendations, as demonstrated with an LLMNR relaying finding. Furthermore, LLMs can perform basic source code analysis, identifying potential vulnerabilities or compilation issues within given code snippets.

Taking this a step further, Bauters explores the use of LLMs in malware development. He illustrates how GPT can generate code for tasks like process injection in C++, providing a starting point for fine-tuning. This concept isn't entirely new; Bauters cites prior work that inspired CommandGPT. Black Mamba, developed by Jeff Sims, is a Python-based implant focused on keylogging. It generates specific keylogging code by asking GPT with a highly crafted prompt, executes it, and sends output via Teams. The key aspect here is the "very specifically crafted prompt" to control code generation. Another example is Chaty Katy by CyberArk, also open-source and Python-based, focusing on keylogging, encryption, and persistence. However, Bauters noted difficulties in getting it to work and the lack of provided specific prompts, limiting its direct utility. These existing projects, despite their limitations, laid the groundwork for Bauters' central question: could an LLM be used to create a dynamic command and control framework? The goal was to assess its feasibility, functionality, and potential downsides.

Key Findings

▶ Watch: Video demo: Ransomware-like emulation (keyboard, encryption) (16:30)

The core finding of Jonas Bauters' research is the successful demonstration that Large Language Models can indeed be leveraged to create a dynamic command and control (C2) framework, capable of generating and executing post-exploitation modules at runtime. This proof-of-concept, dubbed CommandGPT, represents a significant step towards automating and diversifying offensive operations through AI.

Initially, Bauters envisioned an ideal architecture where the operator and implant would interact directly with the LLM through a shared conversation ID, allowing for a truly stateless, conversation-driven C2. However, a critical limitation was discovered: conversation IDs cannot be used to reference subsequent requests or maintain state across different interactions. This meant that each new request would require the entire conversation history to be provided as context, rendering the ideal architecture impractical for a lean C2.

To overcome this, Bauters pivoted to a more traditional C2 architecture, integrating the LLM as a dynamic module generator within an existing framework. He built upon his colleague Weba Williams' C2, W2C2, which provided a robust foundation and a user interface. In this revised model, the operator interacts with a Team Server, which then relays commands to the implant running on the target. The implant, rather than executing pre-defined modules, reaches out to OpenAI's API (specifically, an Azure-hosted instance) with the operator's request. GPT then generates the appropriate C# code module, which the implant receives, compiles at runtime using .NET's CompileAssemblyFromSource functionality, executes, and finally sends the output back through the Team Server to the operator.

This approach effectively replaces a multitude of static, pre-programmed C2 modules with a single, dynamic "GPT" module. The implant's ability to generate and execute code on the fly based on natural language commands is the central innovation. While Bauters emphasizes that CommandGPT is not intended to replace established C2 frameworks like Cobalt Strike, nor is it open-sourced to prevent immediate malicious adoption, it unequivocally demonstrates the technical feasibility of using LLMs for real-time, adaptive post-exploitation. The project highlights both the immense potential for automation and the inherent challenges in controlling and securing such an AI-driven offensive capability.

Technical Deep Dive

▶ Watch: Drawbacks: Temporary files and security detections (20:00)

The technical implementation of CommandGPT hinges on several key components and design decisions, primarily driven by the need for dynamic code generation and execution.

The implant itself was developed in C#, a deliberate choice by Bauters. C# was selected for its relative simplicity, making it accessible even for a "simple red team manager," and crucially, for its built-in capabilities to execute code at runtime. This latter requirement is paramount, as the core functionality involves requesting a C# module from GPT and then compiling and running it within the implant process.

The implant's interaction with the LLM is facilitated through OpenAI's API. Bauters utilized an Azure-hosted OpenAI environment, leveraging the Balgo.OpenAI SDK for communication. The initial implementation began with the Completion API, which is a legacy interface. This API presented a significant challenge: prompt engineering. Bauters discovered that omitting a crucial period (.) at the end of a command would cause the API to "complete" the sentence, adding unsolicited text (e.g., "and display their Associated process IDs"), rendering the generated code unusable. Explicitly ending prompts with a . was critical for the Completion API to interpret the sentence as complete and return only the requested code.

Later in the development, Bauters transitioned to the more recent and recommended Chat Completion API, which supports models like GPT 3.5. This API offers several advantages, including larger token sizes, potentially lower cost per request, and enhanced capabilities. Crucially, it enables full-on conversations by applying different roles: a system role (e.g., "You are now a helpful coding assistant"), a user role for the operator's request, and an assistant role for GPT's response, from which the generated code is extracted. This structured conversation model proved more robust than the single-prompt approach of the Completion API.

The cornerstone of the implant's dynamic execution is the .NET feature CompileAssemblyFromSource. This capability allows the implant to receive C# source code as a string, compile it into an assembly in memory, and then execute that assembly reflectively within the running application. To ensure consistent execution, the prompt for GPT was specifically crafted to generate code with a fixed structure: a namespace named GPT, a class named Program, and an empty Main method. This consistent structure enables the implant to reliably load and invoke the generated module.

Integration into the C2 framework meant replacing numerous pre-programmed post-exploitation modules with a single GPT command. This command takes the natural language instruction from the operator, forwards it to the LLM, and then handles the compilation and execution of the returned code.

However, this dynamic approach introduced several technical challenges:

  • Dependencies: Modules generated by GPT often require references to specific .NET assemblies. Bauters initially had to discover these through trial and error, then hardcode them into the compiler parameters. An improvement involved parsing the using statements in the generated source code to dynamically add the required references. This works well for default .NET libraries but becomes problematic for external libraries that would need to be installed via NuGet on the target system, which is generally not feasible.
  • Code Quality and Errors: GPT-generated code was not always perfect, leading to two main types of errors: compiler errors (preventing CompileAssemblyFromSource from succeeding) and reflection errors (preventing successful execution after compilation). Initial error handling was rudimentary, simply retrying the same request. An improved error handling mechanism was implemented where the implant would send the previously generated source code along with the specific error message back to GPT within the conversation context. This allowed GPT to "learn" from its mistakes and often correct the code, as demonstrated by an example where a missing dependency declaration for a scheduled task was identified and rectified by GPT.

This detailed technical approach showcases the sophisticated interplay between LLM capabilities, .NET runtime features, and robust error handling necessary to make CommandGPT a functional proof-of-concept.

Demo / Proof of Concept

▶ Watch: Future potential: Purple teaming and threat intelligence (32:00)

Jonas Bauters provided a compelling demonstration of CommandGPT's capabilities through a series of videos, showcasing how natural language commands could drive post-exploitation activities typically associated with ransomware. The goal was to illustrate the potential for AI-driven threat emulation.

The demonstration began with basic reconnaissance and system checks:

  1. Keyboard Layout Check: The operator issued the command "show the systems keyboard set settings." This is a common check performed by ransomware to determine if the target system is located in Eastern European or Russian regions, often leading to abortion of execution if true. In the demo, the system was identified as "United States," indicating a "good to go" for ransomware.
  2. Process Monitoring: A command was given to "check the running processes and if calculator is running it prints danger." While "calculator" isn't a high-risk process, this demonstrated the ability to dynamically check for specific processes (e.g., EDR solutions like Defender or CrowdStrike) and trigger conditional actions, such as sleeping for a longer period.
  3. File Enumeration: The implant enumerated folders on the user's desktop, revealing a folder named "important," which was then targeted for further action.

The core of the ransomware emulation then followed:

  1. File Encryption: The operator instructed CommandGPT to "encrypt all of the files in there with we're keeping it simple in exor with key just a." The demonstration showed a file named confidential.dxt within the "important" folder. Upon execution, the file extension was changed to .RS (a common ransomware extension). However, a critical flaw in the GPT-generated code was highlighted: it only encrypted the first character of the file. This was due to a logical error in the generated XOR loop, which checked the key length (a is one character) and only performed the encryption if the index was below that length. Bauters acknowledged this limitation but affirmed that the system had successfully encrypted folders in other tests. This specific example underscored the challenges of relying on dynamically generated code.
  2. Ransom Note Creation: As a final step, CommandGPT was asked to "download the contents from paste bin and then store it on the desktop as ransom.txt." The demo showed the creation of ransom.txt on the desktop, containing what Bauters identified as an example LockBit ransomware note.

This sequence of actions, from reconnaissance and conditional checks to file encryption and ransom note deployment, effectively showcased CommandGPT's potential to automate an entire, albeit simplified, ransomware attack chain purely through natural language instructions. Despite the minor flaw in the encryption module, the demonstration clearly illustrated the proof-of-concept's ability to generate and execute relevant post-exploitation code dynamically.

Defensive Implications

▶ Watch: Q&A: Risks of running unknown AI-generated code (37:00)

The CommandGPT proof-of-concept unveils several critical defensive implications that blue teams and security professionals must consider as LLM-driven offensive tools become more sophisticated. The dynamic nature of code generation introduces new detection challenges, but also presents unique opportunities for defenders.

  1. Temporary Files and Static Detections:
  • The CompileAssemblyFromSource method, while powerful for runtime compilation, often results in the creation of temporary files (DLLs or EXEs) on the target system, even when configured for in-memory generation. These files are typically stored in temporary directories.
  • If the generated code performs inherently malicious actions (e.g., process injection), these temporary files can be statically detected by endpoint detection and response (EDR) solutions like Windows Defender. Bauters demonstrated this with a process injection module, which was immediately flagged.
  • Attempts to have GPT encrypt the source code before delivery were unsuccessful. Even if self-encrypted, the code must be decrypted before compilation and execution, making it vulnerable to static analysis at that point.
  • Defenders should monitor temporary directories for executable files and analyze their contents for known malicious signatures or behaviors.
  1. Compilation After Delivery (MITRE ATT&CK T1500):
  • A significant detection opportunity arises from the act of compiling code on the target system. CommandGPT explicitly calls csc.exe (the C# compiler) during its operation.
  • This activity directly maps to the MITRE ATT&CK technique T1500: Compile After Delivery.
  • Defenders should implement robust detections for csc.exe execution, especially when initiated by unusual parent processes or in conjunction with other suspicious activities. The talk highlighted that temporary source code (.cs files) and the command-line parameters used for compilation are often visible, providing rich telemetry for detection.
  1. Network Traffic to LLM Endpoints:
  • The implant's direct communication with OpenAI or Azure OpenAI API endpoints presents a unique network signature.
  • Defenders should monitor network traffic for connections to known LLM service providers. While these services are legitimate, their presence emanating from internal systems, especially those hosting sensitive data or not typically expected to access external AI services, could indicate compromise or unusual activity. This "trusted connection" is a double-edged sword: it bypasses traditional C2 infrastructure but creates a distinct network footprint.
  1. Dependencies and Missing Libraries:
  • The reliance on target system libraries for compilation can also be a detection point. If GPT generates code requiring specific, non-standard libraries (e.g., NuGet packages), the compilation will fail unless those dependencies are present.
  • While not a direct detection, repeated compilation failures due to missing dependencies could indicate an attempted dynamic execution.

Proposed Defensive Architecture / Mitigation Strategy:

Bauters suggests an improved architecture for red teams (and by extension, a strategy for defenders to anticipate) that addresses some of these detection challenges:

  • Intermediate Building System: Instead of the implant directly contacting GPT, the Team Server (or a dedicated proxy) would request the module from GPT. This module would then be sent to a separate, controlled building system.
  • Decoupled Compilation: On this builder system, red teams would have complete control. They could compile the assembly, install necessary dependencies, retry compilation until the code is robust, and even encrypt the compiled assembly before delivery.
  • Encrypted Delivery to Implant: The encrypted, pre-compiled assembly would then be delivered to the implant. The implant would decrypt and execute it reflectively.
  • Defensive Advantage: This approach decouples compilation from the target system, eliminating csc.exe execution and temporary file creation on the victim machine. It shifts these detectable actions to a controlled environment.
  • Defensive Counter-Consideration: While this reduces direct on-target detections related to compilation, it effectively reverts to a more traditional C2 channel for module delivery. Defenders would then focus on detecting the encrypted payload delivery and the reflective execution techniques, which are already common in advanced C2 frameworks. The unique network signature to OpenAI is also lost on the implant, though it would still be present on the Team Server/builder.

Ultimately, CommandGPT underscores that while LLMs offer new avenues for offensive operations, they also introduce new artifacts and behaviors that, when understood, can be leveraged for effective detection.

Key Takeaways

  • LLMs Enable Dynamic C2 Module Generation: The CommandGPT proof-of-concept definitively shows that large language models like GPT can be integrated into C2 frameworks to dynamically generate and execute post-exploitation modules in C# at runtime based on natural language commands.
  • Significant Technical Hurdles Exist: Challenges include effective prompt engineering (e.g., using the . for the Completion API), managing API limitations (e.g., lack of persistent conversation IDs), handling dependencies, and ensuring the quality and reliability of generated code through robust error handling.
  • Clear Detection Opportunities for Defenders: The current implementation of CommandGPT leaves distinct forensic artifacts, including temporary files (DLLs/EXEs) on the target, the explicit execution of csc.exe (Compile After Delivery - MITRE T1500), and direct network connections to OpenAI/Azure API endpoints.
  • Malicious Actors Will Adapt and Automate: While red teams face ethical constraints in deploying such tools in production, malicious actors (e.g., ransomware groups) are unburdened by these and are likely to rapidly adopt, refine, and specialize LLMs (e.g., FraudGPT, WormGPT) for automated, evasive post-exploitation, custom-training models for specific evasion techniques or TTPs.
  • Promising Future for Purple Teaming and Automation: The most valuable immediate application for legitimate security operations might be in "purple mode," where LLMs ingest threat intelligence reports and automatically generate natural language emulation plans. These plans can then be executed by CommandGPT-like tools on dedicated test systems, facilitating more abstract, technique-level detection validation.
  • Running Unknown Code in Production is Risky: Red teamers should exercise extreme caution and generally avoid running dynamically generated, unvalidated code from an LLM directly in a customer's production environment due to unpredictability and potential for unintended side effects or even backdoor inclusions.

About the Speaker(s)

Jonas Bauters is a Solution Lead for Benelux at NVISO, a European cybersecurity firm originally founded in Belgium. In his role, he focuses on Adversarial Risk Emulation and Simulation (ARS), which encompasses a range of offensive security services. Bauters is part of a dedicated team of approximately 13 red team operators, working alongside his German counterpart. Their work primarily involves target-driven testing, including red teaming, purple teaming, cyber engagements, and scenario-based penetration testing for clients with varying levels of security maturity. His expertise lies in understanding and emulating sophisticated adversary tactics to improve organizational defenses.

Reviews

→ Top-rated talks at BruCON 0x0F

All talks from BruCON 0x0F