AMSI Memory Patching Refrain
Much has been written about the Antimalware Scan Interface (AMSI) over the years in the cyber security industry. From a penetration testing perspective, AMSI is viewed as an impediment that needs to be overcome during offensive operations. Putting this aside for a moment, let’s start with defining exactly what AMSI is first. What is AMSI? AMSI is Microsoft’s signature and behavioral analysis response to in-memory script object and .NET assembly execution threats. AMSI provides object scanning coverage for: The architecture of AMSI is divided into two parts: the AMSI client implemented in the amsi.dll file, and the AMSI provider, which is Windows defender providing the signature matching and behavioral analysis components. The AMSI client DLL has two functions that are called upon for scanning objects, AmsiScanString() and AmsiScanBuffer(). Ultimately, the string scanning function ends up just using the AmsiScanBuffer() function anyway, which means that all data flows through the AmsiScanBuffer() function in the DLL when scanning objects. There are two output indications from using this function. The first is the function return value itself, and the second is the result parameter. The buffer scanning function writes into a result parameter buffer one of three values: The function return value is either going to be S_OK, which is a zero or some HRESULT (refer to MSDN for details) error code. A notable error code that can be returned, which we will address later in this blog is E_INVALIDARG, hexadecimal 0x80070057. How do we know if AMSI is enabled on a system? The easiest test and one that I personally love is to use PowerShell and just test a known evil string in a script or statement. The screenshot below shows my favorite test. There are many possibilities to effectively bypass AMSI functionality, which include: Our focus in this blog is memory patching within the amsi.dll itself. Since the implementation of amsi.dll will change over time, the reader should note that this blog is based on research performed using the Windows installation as detailed in this table. Memory (Machine Code) Patching As already mentioned, the critical path with AMSI is the flow of data through the AmsiScanBuffer() function. What memory patching really represents is direct machine code patching once the amsi.dll is loaded. Using direct Win32 API calls, it is a simple recipe to: Wait just a second though. If we do this, won’t we get caught by defenses? The answer to this question is maybe, because it depends on what defenses are installed on that system. In the context of installed EDR, there are ways you could get caught. There are methods to squelch telemetry feeds for EDRs, which include things like overwriting ntdll.dll hooks and patching ETW telemetry. There are also ways to perform direct or indirect system calls when leveraging ntdll.dll functions for memory protection and writing functions. For the purposes of this blog post, we are just going to focus on the in-memory AMSI patch itself in an x64 Windows architecture context. In the Intel/AMD 64-bit processor, the RAX register is used to contain the return value for any function. When a function returns, it is executing the assembly instruction of “RET”, which is hexadecimal 0xc3. The most obvious machine code patch in this case would be to search for the beginning of the AmsiScanBuffer() function and just write a single byte 0xc3 to that location. This seems very intuitive and might work, but there is one problem. When the function is called, we have no idea what the value of the RAX register is. A likely case is that RAX contains some other random value, and we just don’t know what the behavior will be of the PowerShell or other calling process that used the scan function. Why? Because some uses of amsi.dll might completely ignore the return code and purely focus on the “result” parameter (buffer) and some might take a return value other than the expected/defined codes as a real problem. The coolest thing, however, at this juncture is that we have options! If we are patching at the very beginning of the function, we are in the context of the function prologue, which is focused on setting up the stack for this function variable/memory use, and then usually validating parameters. In other words, there are a lot of machine code opcodes between the start of the function and the subsequent function call into where the real signature or behavioral matching occurs. This implies that all we need to really care about here is the RAX (return code) value itself. Here are some common HRESULT (return values) that we might consider putting into RAX before using our RET instruction. Now we are getting into writing assembler code, albeit relatively simple assembler code. One of my favorite tools when I am researching a memory opcode patching technique is an online assembler by Taylor Hornby here at this URL: https://defuse.ca/online-x86-assembler.htm Using this really nice tool, we can enter the two assembler instructions we are interested in, MOV RAX, 0 and RET, putting a zero in the RAX register and returning from the function, and have it assemble the exact byte sequence of opcodes we need. If we are moving any value that is less than 32-bits a register, we also have the option to use different opcodes based on the bit-length of the register, giving us additional variability on opcode use. As we use smaller register opcodes, the arguments become progressively smaller, meaning we reduce the size of the byte patch. The more flexible variations we have to use for a machine code patch, the more likely we will be able to evade a signature match. For example: For reference below is a diagram of the x64 processor architecture reminding us of the register layout. The next thing you might wonder is how to test one of these bypass methods? All you need here is a process that loads amsi.dll and the use of a debugger, which can modify memory. In my case, to test bypasses,
Exploiting PHP Foundational Vulnerabilities
PHP (Hypertext Preprocessor) is a widely used open-source server-side scripting language designed for web development. It has over the years gained widespread acceptance for its ease of use and programming/scripting abilities and is notably the scripting language that implements the popular WordPress application. WordPress is the most popular content management system (CMS) in the world powering approximately 42% of worldwide websites, and nearly 60% of websites that use a CMS. On October 21st, 2026, the PHP project reported the following two CVEs and released a patch for the vulnerabilities. These CVEs are related in that they both involve memory use from the heap in PHP worker processes. Background Exploitability of these CVEs is non-trivial with some pre-conditions to be met and multiple possibilities/avenues of potential attack. In this blog, we will focus purely on CVE-2026-109618 to see if we can get a single HTTP POST exploitation vector. We must first have an application configuration and components that allows for the upload of multipart form data. Within PHP, there was a feature released in version 5.4.0 that introduced a configuration switch called “session.upload_progress”. In the implementation, the switch defaults to being enabled. Below is a snippet from the PHP manual: This feature processes multipart form data in a function called php_session_rfc1867_callback() in the PHP session handling API. All the HTTP POST request data in the session API is processed before any application code runs. The callback handler function: Therefore, this callback function in the PHP code is an excellent candidate to allow a threat actor to trigger an out-of-memory condition and potentially gain remote code execution. Lab Setup To explore these vulnerabilities, we need a reliable lab setup. A docker container is the easiest way to get up and running with Apache mod_php. As you might imagine, Docker Hub publishes a number of images for the community already. Having said that, I learned through the process of banging my head against a brick wall repeatedly that the PHP project to their credit had recompiled PHP with the fixes and back ported into older versions of the docker containers. Bravo, but it was unexpected and frustrating for me while getting the lab up and running! The following setup information formed the basis of my lab: Initial Attack Path (Low Hanging Fruit) There is another defect that allows for a reasonably easy initial attack path and that is the multipart form handler code in PHP that accepts the session cookie from the form data without checking the session.use_only_cookies setting. This gives us session fixation, which means that we will know the session identifier, and will directly map to the stale session file we leave on the server. Notably the “name” parameter sent in the post request is stored directly in the temporary session state file. The session state file that is written when the OOM condition is triggered will not be deleted leaving the attacked supplied data in the “name” parameter within the file contents. Below is an example using my probing script of injecting data into this field and then looking at the file on the target docker container. All we need from there is some form of local file inclusion in the PHP of the application and we get command injection ability by writing PHP code into the filename variable we post. For example, we could write the following text into the filename field that remains on disk in the stale session state files: Then if any other PHP script includes this state file, we have an execution of the command. However, this path depends on a local file inclusion vulnerability in the application. I dropped a simple vulnerable PHP script onto the web server with a direct file inclusion to verify this. Higher Complexity Attack Path An interesting observation is that the multipart form upload code in the session handling API will potentially trigger the out of memory condition before any application code runs. More specifically, the Zend engine (zend_bailout() function in zend.c of the php source code) will be executed when the Zend HashTable structure is only partially initialized. The last line of code in zend_bailout() is the LONGJMP() macro that ultimately just executes a longjmp() to transfer program execution control into the shutdown and exit function for this request. Since all this code is written in C, any time we are about to shut down a process, developers are obligated to cleanup memory. This is commonly referred to as a destructor function, and in the C language, context must be manually implemented. Without getting too far in the weeds, the bottom line is that the Zend HashTable structure, when initialized for an HTTP request, contains memory pointers for object destruction functions. If we can somehow influence the value of one of these memory pointers, we will be able to control execution. From a high level, these are the parts and sequence of the exploit: What POP4 represents here is a return-oriented programming (ROP) gadget we are using as a springboard to get the right things put into the right registers before our system call. The astute reader is going to recognize that to make all this work, we need some static memory addresses. This is the point in the blog where I tell you that I did all this work in a docker container after switching Address Space Layout Randomization (ASLR) off, and hard coded the memory addresses of both LIBC, and the loaded LIBPHP object. ASLR is a great defense mechanism; however, during the course of an exploit POC development there are already complexities of understanding the exact nature of the vulnerability, in this case the memory layout of the heap, and we need to break the development steps down into manageable steps minimizing complexity at each step. Once we have achieved success with a defensive mechanism like ASLR disabled, we can move forward with further development with defenses re-enabled steadily growing the exploit capability. ASLR Enabled Attack Path It is possible to adapt this attack path for different vulnerable versions of PHP and for a normal implementation where ASLR is not disabled. In the case where ASLR
Automating AI Hacking with Tree of Attack
Introduction Tree of Attacks with Pruning (TAP) uses an LLM to iteratively generate and refine candidate attack prompts through tree-of-thoughts reasoning. The process continues until a prompt successfully jailbreaks the target model. A key component of TAP is its pruning mechanism: before a candidate prompt is sent to the target, TAP evaluates its likelihood of success and discards prompts that are unlikely to produce a jailbreak. By combining tree-of-thoughts exploration with pruning, TAP can efficiently navigate a large search space while reducing the number of queries made to the target model. This technique automates the process of generating and refining attacks against LLMs through systematic exploration and evaluation. In this article, we’ll examine how TAP works, how its probing process is structured, and how one AI system can be used to automatically generate and evaluate attacks against another AI system with minimal human intervention. Additionally, we are excited to introduce parley-ng, an improved version of the original parley with extra features which will be disclosed in this blog post as well as a proof of concept (PoC) that generates ready-to-use prompts allowing users to manually test Special Token Injection and Response Prefill against LLMs in controlled environments. Why Tree of Attack Building on the PAIR algorithm (Prompt Automatic Iterative Refinement), TAP demonstrates a high success rate in generating jailbreak prompts against state-of-the-art LLMs. In experiments, TAP successfully generated jailbreaks for more than 80% of the tested prompts while requiring fewer than 20 queries per attack. This represents a substantial improvement over the previous state-of-the-art black-box approaches for automated jailbreak generation. How Tree of Attack Works? There are three different LLM roles utilized in this process: The program then repeatedly does: Attacker │ generate several prompts │ ┌──────────┼──────────┐ ▼ ▼ ▼ Prompt A Prompt B Prompt C │ │ │ ▼ ▼ ▼ Target Target Target │ │ │ Response Response Response │ │ │ └──────────┼──────────┘ ▼ keep the best candidates (the rest are pruned) │ ▼ repeat the process So rather than trying one prompt, the program generates a tree of possible prompts and keeps the most promising branch for each depth level, while pruning the others. The PAIR algorithm paper (Prompt Automatic Iterative Refinement) is used to leverage the AI model refining Jailbreaks. This means that the attacker AI is provided with the previous prompt, previous response, and an improvement strategy. Tree of Attack begins first with the attacker AI being tasked to refine/mutate/modify prompts in order to come up with new strategies. To archieve this independently, the attacker AI is first provided with a collection of strategies to bypass safety measures. These collections include sensitive words obfuscation, roleplaying scenarios, reward offering, etc. The evaluator AI learns how AI behaves in different scenarios and come up with new strategies on the next prompts. Then, the attacker AI is provided with an adversarial prompts dataset curated collection of malicious or tricky inputs. This is the prompt foundation, and together with the strategies, it comes up with a new obfuscated prompt. The prompts are sent to the targeted LLM, while the evaluator AI rates each of the responses. The response with the highest score is used to branch out. This process is repeated in a loop, until the goal is finally reached. Attack Visualization When using parley, visualizing the attack can be hard to interpret. This makes it hard for the operator to understand how the prompt has evolved and what worked best. So we came up with an additional feature of generating an interactive HTML report after a scan has finished, where you can see how the original prompt got evolved in (multiple) stages until the goal was achieved. Each of the prompts, responses, and strategies are shown on the right side when a node is clicked. Additionally, the user can highlight the solution, which greys out all the partial, pruned, or refused prompts. The node with the highest score is kept for the following branches. Special Token Injection PAIR algorithm that parley uses is good enough for most of the jailbreak cases; however, improvements can be made. We are not going to focus on obfuscation (encoding, hyphens, etc.), since the mix combinations of these techniques can exponentially increase the attack vectors, which defeat our initial goal on being efficient. One approach to increase the attack effectiveness without exponentially increasing the complexity is to leverage the use of Special Token Injection. Special token injection is a security attack in which an adversary embeds hidden or control tokens within a chat input to manipulate how an AI model interprets the message. The goal is to make the model treat user-supplied content as though it were a privileged system instruction or part of the assistant’s own response, potentially bypassing the intended instruction hierarchy. Major LLM families rely on reserved special tokens to define conversation roles and regulate the flow of interactions. OpenAI’s ChatML format uses <|im_start|> and <|im_end|> to mark message boundaries and role assignments. Meta’s Llama uses [INST] and [/INST]. Mistral, DeepSeek, and Qwen each have their own delimiters. Each architecture uses their own format, meaning that you need to first understand the architecture of the chat-based LLM you are targeting before attacking it. For open-weight models, the answer is already there, but if you are dealing with an black-box model, you can ask for it. Once the model (and its architecture) is recognized, you can find the exact special tokens and formatting logic directly in the model’s tokenizer configuration or chat template metadata. One approach is by searching the model in Hugging Face Model Page. Every model page includes a tokenizer_config.json file in its “Files and versions” tab, which contains the chat template. You can use the following Ungated Hugging Face tokenizer configurations for the other architectures: Let’s take Llama architecture as an example. (Note: Other LLMs uses different chat templates and special tokens). You can access the official model by going straight to its Hugging Face model page -> Files and Versions -> special_tokens_map.json. Alternatively (and also the
UEFI Vulnerability Analysis using AI Part 4: Building the Application
Much of the AI-based vulnerability research work that has been done up to now centers on user-mode application and OS code, with some recent work done on kernel internals. Very little has been published on AI research into boot firmware, which is somewhat surprising, given that platform initialization is at the very root-of-trust. In this article, Part 4 of the series, I’ve begun enhancing the DeepSeek-r1 open-source, open-weight model on my NVIDIA DGX Spark with a Knowledge Base of specialized data, for powerful inference on UEFI code. In Part 1 of this series, I set a baseline for UEFI vulnerability discovery by unleashing the ChatGPT frontier model (at that time, ChatGPT 5.1; we’re now at ChatGPT 5.5) on a Tianocore EDKII open-source build for an Intel Whiskey Lake design (the AAEON UP Xtreme board). ChatGPT correctly diagnosed the vulnerabilities in OpenSSL in a 2021 firmware build, and found that the majority of these issues were corrected in the 2025 version. However, it could only consume a tiny portion of the build firmware’s source code at one time, in part due to the limited context available to ChatGPT for my chat (128K tokens); this rendered detection of more obscure code weaknesses impossible. In Part 2, I embarked on a journey to move the firmware analysis over to the NVIDIA DGX Spark, to take advantage of the power of local, open and private LLMs for this research. Unfortunately, using currently available tools (such as Open WebUI, LMStudio, repomix, docling, etc.), I couldn’t get close to the effectiveness I needed, and I discovered that the frontier models themselves had not been trained on some of the lower-level internals of UEFI, such as are contained within the Intel Software Developers Manual (SDM). Back in December of last year, they didn’t even know what a Model-Specific Register (MSR) was! Even today, if you ask for a description of MSR C80H (a debug MSR, without any further context), Gemini 3.5 Flash will tell you: Depending on the context, MSR C80H typically refers to an Intel Processor architectural register, though it can also refer to a hardware model in rf-engineering. Here are the details for both: 1. Intel Computing: IA32_DEBUG_INTERFACE MSR In x86 architecture (specifically Intel processors), an MSR is a Model-Specific Register. The address C80H (or 0xC80) corresponds to the IA32_DEBUG_INTERFACE register. Purpose: It controls and reports the status of Silicon Debug features (such as JTAG-based probing, Intel DCI, and hardware debugging tools). Key Bit Functionality: Bit 0 (Enable): Allows software or hardware probes to enable the debug interface. Bit 31 (Debug_Has_Occurred): A status bit that asserts if a debug event or probe has successfully interacted with the processor. Usage: It is primarily utilized by low-level firmware (like UEFI/BIOS), operating system kernels, and security researchers looking into hardware vulnerability analysis or debugging hardware execution. 2. RF & Microwave Hardware: MEC C80H Coaxial Termination If you are looking at RF/microwave component specifications, C80H is a model number manufactured by Microwave Engineering Corporation (M.E.C.). Description: A high-power coaxial dummy load (termination). Frequency Range: 2.0 to 18.0 GHz. Power Handling: Up to 500 W of continuous average power (with a 10 kW peak pulse limit). Cooling: It features passive radiating fins for heat dissipation (unlike the “C80F” model, which uses an integrated fan). Which of these two definitions matches the project or context you are working on? Not to be too picky, but this is wrong/incomplete! It also completely missed describing Bit 30, the lock bit, which is crucial to the enabling of silicon debug prior to the first SMI assertion. Here’s what the actual raw data looks like from the SDM: Intel SDM contents for IA32_DEBUG_INTERFACE MSR And context is everything, isn’t it? The LLM needs to know if you’re asking about Intel registers or RF hardware. Even a frontier model needs proper prompting and context for deep research. And these are the top-of-the-line frontier models. As part of my further experimentation, I downloaded and ran two best-in-class open-source models onto my DGX Spark, nemotron-3-Super:120b-a12b-q4_K_M and DeepSeek-r1:70b, and posed the same question. Here’s what you get: Nemotron and DeepSeek running in series within Open WebUI It can be seen from the above image that you can issue the same prompt to both Nemotron and DeepSeek simultaneously using Open WebUI, and they run in series without running out of memory; neat, huh? Unfortunately, the results are garbage. Nemotron interpreting MSR as “Minimum Safe Radius” and DeepSeek saying “Microsoft Research” shows you how challenging it is to train models. Give them a little more context with the prompt “From the Intel Software Developers Manual (SDM), Volume 4, what is the description for Model-Specific Register (MSR) C80H?”, and you get: Nemotron and DeepSeek balking at MSR C80H IA32_DEBUG_CTRL They both understood the reference to the SDM and now understood what an MSR was, but neither Nemotron nor DeepSeek could find the actual MSR C80H and describe it! Given a more explicit prompt, “Were you trained on the Intel SDM?”, Nemotron responded: Nemotron 3 Super Deep Firmware Analysis Thought for 21 seconds No, I was not specifically trained on the Intel Software Developer’s Manual (SDM) as a primary or exclusive data source. Here’s a clear breakdown of my training context and capabilities regarding technical documentation like the SDM: 1. My Training Data Scope: I am a large language model created by NVIDIA, trained on a vast, diverse dataset of publicly available text, code, and technical documentation up to my knowledge cutoff (July 2024). This dataset includes sources like books, articles, forums (e.g., Stack Overflow), open-source code repositories, and technical websites — but it does not guarantee inclusion of every specific document, such as the full Intel SDM. While the Intel SDM is publicly available and likely represented in part within my training data (as it’s a widely referenced technical resource), I was not trained exclusively or primarily on it. My knowledge of x86 architecture, instruction sets, or system programming comes from a broad synthesis of many sources. 2. What This Means
Introduction to Tokenizers in LLMs
Introduction Have you ever wondered how a Large Language Model (LLM) like ChatGPT actually reads and understands text? The answer begins with something called a tokenizer. A tokenizer is the very first step in the language processing pipeline. Before an AI model can understand a sentence, answer a question, or generate text, it must first break the input into smaller pieces called tokens. These tokens are the units the model uses to process language internally. What is a Token and Tiktoken? A token can be many different things. Sometimes it is a complete word, such as “football.” In other cases, it can be only a part of a word. For example, the word “extraordinary” might be split into smaller pieces like “extra”, “ordin”, and “ary.” Tokens can also include punctuation marks, spaces, symbols, emojis, or even URLs. After the text is divided into tokens, each token is assigned a unique numeric ID from the tokenizer’s vocabulary. In simple terms, tokenization is the bridge between human language and machine understanding, making it one of the most important concepts in modern AI and Large Language Models. So, we are using tiktoken, an open-source library developed by OpenAI, to understand how text is converted into tokens. It uses the same tokenization method as OpenAI’s models, allowing us to see exactly how words, punctuation, and symbols are split before being processed by an LLM. This makes it a useful tool for learning how tokenization works and for estimating token usage in real-world applications. tiktoken was introduced to provide a reliable and consistent way for developers to work with the tokenization schemes used by models such as GPT-3.5 and GPT-4, helping bridge the gap between raw text and the numerical representations that LLMs The code above demonstrates how the cl100k_base tokenizer converts the text “I love playing football%” into a sequence of token IDs that a Large Language Model can understand and process. Each word, symbol, or character is broken into tokens, and every token is mapped to a unique numeric value from the tokenizer’s vocabulary. The `tokens` list represents these numeric IDs, while enc.decode(tokens) performs the reverse operation by converting the token IDs back into the original text. In simple terms, this example shows the complete flow of how LLMs handle text internally: Text → Tokens → Token IDs → Text. For example, a sentence like “I love playing football!” may be transformed into a sequence of token IDs such as [40, 3021, 5737, 9141, 4]. While humans see readable text, the model only works with these numerical representations internally. Each token ID corresponds to a specific word, subword, or symbol stored in the tokenizer’s vocabulary. Since transformer models can only process numerical data, these token IDs are converted into vectors of numbers called embeddings. The model performs all of its computations on these vectors and produces another vector as output. During text generation, this output is used to predict the most likely next token, which is then converted back into human-readable text by the tokenizer. For example, in this tokenizer, the exclamation mark “!” is assigned the token ID 0 based on its position within the tokenizer’s vocabulary. Every word, symbol, or character is mapped to a unique numeric ID that the model uses internally during processing. The enc.decode(tokens) function performs the reverse operation by converting those token IDs back into human-readable text. This demonstrates the complete workflow used inside Large Language Models: Text → Tokens → Token IDs → Text. If you want to experiment with tokenization yourself, you can also use the tokenizer visualizer available at https://tiktokenizer.vercel.app/?model=cl100k_base, which allows you to see how text is split into tokens and mapped to IDs in real time. Modern Tokenization and Workflow in LLMs Modern Large Language Models (LLMs) cannot process raw text directly because neural networks only work with numerical data. Tokenizers solve this problem by breaking text into smaller units called tokens and assigning each token a unique numeric ID. Modern tokenizers commonly use subword-based techniques such as Byte Pair Encoding (BPE), WordPiece, and SentencePiece. These methods allow models to efficiently handle rare words, multiple languages, misspellings, and previously unseen terms without requiring an extremely large vocabulary. As a result, the model can generalize more effectively while keeping the vocabulary size manageable. The overall text processing pipeline inside an LLM can be simplified as: Raw Text → Tokenization → Token IDs → Embedding Vectors → Neural Network → Output Token IDs → Text Tokens to Embeddings After text is converted into tokens, the LLM still cannot work with just token IDs because numbers like 40, 3021, 5737, 9141 don’t carry meaning by themselves. To understand language, the model needs a way to represent each token in a format that captures semantic relationships, meaning, context, similarity, and grammar. This is achieved through embeddings. To make tokens meaningful, the model converts each token ID into an embedding vector. An embedding is a continuous high-dimensional vector representation of a token that helps the model capture semantic relationships, patterns, and similarities between words. Instead of representing a token as a single number, embeddings transform it into a dense vector of floating-point values. These vectors allow the model to learn relationships between words, grammar, and language structure during training. For example, words with similar meanings often end up with embedding vectors that are mathematically close to each other in vector space. This is one of the key reasons embeddings are fundamental to how Large Language Models understand and generate human language. The code first tokenizes the input text using the cl100k_base tokenizer, converting each word and symbol into numeric token IDs. Since neural networks cannot process token IDs directly, the code then simulates an embedding layer by creating a random embedding table containing 100,000 rows one for each possible token in the vocabulary and 8 columns representing the embedding dimensions. Each token ID is used to retrieve its corresponding embedding vector, allowing the model to represent tokens as meaningful numerical features instead of simple integer values.
Harnessing the Power of Cobalt Strike Profiles for EDR Evasion – Part 3
This blog post is a continuation of the previous entry “Harnessing the Power of Cobalt Strike Profiles for EDR Evasion“ and its follow-up, Part 2. Following the release of Cobalt Strike 4.13 by Fortra, we immediately began exploring the newly introduced capabilities and evaluating their impact on operational security. Through testing and experimentation, we developed an updated set of Malleable C2 profiles designed to further strengthen detection evasion techniques. Every feature introduced in this blog is already implemented in the CS 4.13 malleable profiles within our GitHub repository. Drip Loading Although this capability was introduced in Cobalt Strike 4.12, it remains highly relevant due to its potential impact on detection evasion and therefore deserves to be mentioned in this post. One approach EDRs can take to detect process injections is through correlating different events for common injection primitives. Instead of allocating a large chunk of memory as most shellcode loaders do, the Drip Loading technique allocates multiple smaller chunks of memory until the entire payload is reserved. Additionally, the dripload_delay and rdll_dripload_delay, are extremely useful options, which introduces delay between each allocation chunk. This further enhances the evasion capability by breaking event correlation that EDRs usually rely on for identifying common injection primitives. This feature is available for the reflective loader options and can be configured via the new Malleable C2 settings as seen below: stage { set allocator “VirtualAlloc”; # The only compatible allocator with DripLoading set rdll_use_driploading “true”; set rdll_dripload_delay “100”; //adds a further delay ifdesired } Similarly, drip loading can be configured for process injection via the new Malleable C2 options for the process-inject block as shown below: process-inject { set allocator “VirtualAlloc”; # The only compatible allocator with DripLoading set use_driploading “true”; set dripload_delay “100”; //adds a further delay if desired } The only compatible allocation method for Drip Loading is VirtualAlloc, every other allocation method will result in a fail during profile check: Since we have now switched to VirtualAlloc for the allocation primitive, we can enhance it by using indirect syscalls, making it the new final configuration set: stage { set allocator “VirtualAlloc”; # The only compatible allocator with DripLoading set rdll_use_driploading “true”; set rdll_dripload_delay “200”; set rdll_use_syscalls “true”; # NtVirtualAlloc instead of VirtualAlloc set syscall_method “indirect”; } process-inject { set allocator “VirtualAlloc”; # The only compatible allocator with DripLoading set use_driploading “true”; set dripload_delay “100”; //adds a further delay if desired } Through memory analysis, we have observed that the payload is spread across 64 KB memory regions, whose permissions are constantly changed to RW and RX through each beacon iteration cycle: OPSEC Note: Although this blog demonstrates Drip Loading using the VirtualAlloc allocation primitive and indirect syscalls for simplicity and ease of setup, our preferred configuration is to pair Drip Loading with the default Cobalt Strike Sleep Mask (updated in version 4.13). The latest Sleep Mask implementation now performs return address spoofing for all proxied BeaconGate calls, including VirtualAlloc. As a result, it effectively mitigates the primary drawback typically associated with using VirtualAlloc, while retaining the operational benefits of Drip Loading. In our assessment, this combination represents the most effective Drip Loading configuration currently available. While this setup requires some additional configuration, the process is relatively straightforward. We previously covered BeaconGate and its initial setup in detail in Part 2 of this blog series, which can be used as a starting point for implementing this configuration. Check-in Delay It can be a good idea to introduce delays where possible, as this breaks detections that rely on event timing correlation heuristics. Beacon now supports the checkin_delay Malleable C2 option. This will delay Beacon’s initial check-in to break event correlation detection heuristics on reflective loading and the immediate metadata exchange. checkin_delay will result in a delay of the beacon showing up in the client GUI since the metadata is delayed as well. Deprecated Features After implementing the new features into our profile, we immediately encountered validation errors during the C2Lint process. The reported issues were related to the following directives within the stage block: stage { set rdll_loader “PrependLoader”; set name “ActivationManager.dll”; } The warning regarding rdll_loader was expected. As previously announced in Fortra’s Cobalt Strike 4.11 release blog, Beacon now utilizes the Prepend Loader by default. With the Stomp Loader scheduled for deprecation, there is no longer a need to explicitly select between the two loader implementations. Simply removing the rdll_loader directive was sufficient to resolve that validation error. The name directive also triggered a linting error. Removing this option makes the profile valid again; the reason is that the “name” refers to the name of the exported function used by the Beacon to call into a stomped reflective loader. All the stomp architecture was removed (i.e., there’s no longer an exported function), so the option is irrelevant in 4.13. Detection Testing Results White Knight Labs evaluated the profile against six of the most popular Endpoint Detection and Response (EDR) solutions. Testing was conducted using the finalized Malleable C2 profile in combination with an open-source shellcode loader. Across all tested EDR products, no detections were observed. In addition, White Knight Labs scanned the in-memory process using a collection of recent and widely adopted YARA rules. None of the rules produced a match, indicating that the generated memory artifacts did not trigger the tested signatures. Conclusion With the release of Cobalt Strike 4.13, several subtle but impactful changes have been introduced that further enhance the flexibility and stealth of Beacon operations. Throughout this post, we explored how modern features such as Drip Loading, the updated Sleep Mask implementation, and BeaconGate integration can be combined to reduce behavioral indicators against event-correlation and memory-based detection techniques. All of the improvements discussed in this article have been already added in Cobalt Strike 4.13 profiles, which are available in our GitHub repository for further testing and research. Resources https://download.cobaltstrike.com/releasenotes.txthttps://www.cobaltstrike.com/blog/cobalt-strike-413-lost-in-translation
Backdooring Electron Applications
In increasingly restrictive corporate environments, deploying and maintaining C2 implants on Windows systems presents unique challenges. Signed execution policies, strict network controls, advanced segmentation, and continuous software behavior monitoring severely limit traditional loading and communication techniques. This blog explores how to adapt implant development and operational strategies to survive under these conditions. It covers topics such as executing under signature requirements, covert communication within networks under deep inspection, and approaches to maintaining persistence without violating environmental constraints. Imagine you gain access to a Windows environment configured in a highly restrictive way, which prevents you from loading unsigned implants by enforcing Windows Defender Application Control (WDAC) policies. What would you do in that case? If PowerShell is not blocked, you can execute your scripts, keeping in mind that AMSI will analyze them and determine whether the code is malicious or not. If all else fails, we can use an alternative called Loki C2. It’s a C2 that backcodes applications built with Electron. But what exactly is an Electron application? You’re probably familiar with applications like Teams, Notion, or Discord. Well, they’re built in Node.js using a framework called Electron (basically HTML, CSS, and JavaScript). Using this C2 server is very simple, you just need to download the server (.exe) and configure it using an Azure account, as communication will take place through a Blob. Firstly, the client binary will require two parameters: the SAS Token and the Blob URL. This will generates a folder with the implant’s contents, ready for use. I personally recommend obfuscating the implant’s contents using any JavaScript obfuscator you know to avoid IOCs. It also generates the Meta Container parameter, which we then copy entirely to the server: With everything configured, we must choose whether we want to back-store an existing application (e.g., Teams) or download a new application already implanted. In this case, we opted for the second option. Research has been conducted and discovered that the Mailspring application is vulnerable to this technique. Therefore, the application was downloaded, and the contents of the resources/app folder were deleted. That content was replaced by our implant which will be pasted inside resources/app. Now all that remains is to download the application onto the victim’s device and establish the connection. As shown in the image, the connection has been successfully established on a computer with MDE installed. Final Considerations This technique can be very powerful in some environments because it uses a signed application and communication is established through an Azure domain, which allows execution and connection in very restrictive environments. Various tests have been conducted with most of the top EDRs, and in many of them, the implant works even without obfuscation. Others report certain alerts that can be avoided by obfuscating the implant. Another important point is the option of backloading an application like Teams instead of downloading a new one. Be careful, if this isn’t done precisely, the application can become corrupted and stop working. One more thing that has worked for me is modifying the C2 code and recompiling it, altering the order of the functions and commenting out some that are not needed.
UEFI Vulnerability Analysis Using AI Part 3: Scaling Understanding, Not Just Context
In the prior two blogs within this UEFI Vulnerability Analysis using AI series, I described my research on analyzing enormous codebases, starting with UEFI firmware. The first two articles dealt with extending the open-source Large Language Model (LLM) token context window (effectively, what the LLM can hold in memory all at one time). In this article, the use of Knowledge Graphs to improve AI reasoning powers is investigated on the NVIDIA DGX Spark. In Part 1, I used the ChatGPT frontier model to analyze the OpenSSL module within an older version of the open-source Tianocore EDKII UEFI build. ChatGPT did a very good job of detecting the vulnerabilities in this older (August 2021) release. But it chokes on doing anything much larger than the OpenSSL module, which is a tiny fraction of the total UEFI image—due mostly to token context window and file upload size limits. You can see the challenge visually below: Caption: Relative size of the OpenSSL module to the entire UEFI codebase In Part 2, subtitled Breaking the Token Barrier, I described my first attempts to use a private LLM on my DGX Spark to analyze larger portions of the UEFI source code base for vulnerabilities. Here, I discovered obstacles: So, in this article, I’ve taken a “side-trip” to address the limitations of RAG and improve the inference reasoning power of my models. I’ll do this by using Knowledge Graph (KG) technology. So, you may ask, what is KG technology, and why use it as opposed to plain old text vector databases? That’s a very good question. Standard text databases treat data as rows and columns (in as many dimensions as is needed), whereas KGs organize facts into a network of interconnected entities, and are built using “triples”, which are: Viewing data in KG form addresses subtle “blind spots” found in LLMs: specifically, grounding facts and reducing hallucinations, and adding insight through meaningful relationships. Vector databases only know if two pieces of text are mathematically close to each other in a vector space; whereas KGs allow for deterministic logic, knowing how Node A relates to Node B (i.e., the CEO of “X” is located in “Y”). Confusing? A picture is worth a thousand words, so let’s begin with the end in mind. Below is a short video that captures a simple KG implementation: Caption: Video of Knowledge Graph for SourcePoint User Guide As a trial run, I decided to apply KG to ASSET InterTech’s SourcePoint JTAG-based debugger’s User Guide. This document, much like the Intel SDM, contains specialized information that does not appear to be “baked in” to any generally available LLM currently on the web. Applying superior reasoning powers to the esoteric data within these documents will aid in the accuracy and quality of the large codebase analysis. On the DGX Spark, NVIDIA provides a convenient set of Playbooks that help engineers explore and learn about many AI technologies that make up the NVIDIA stack. One of the playbooks is entitled Text to Knowledge Graph (named txt2kg hereinafter). Here’s the overview: Caption: Text to Knowledge Graph Playbook Instructions Author’s Note: You might miss it, but the overview section has in the fine print, “Future Enhancements: Vector embeddings and GraphRAG capabilities are planned enhancements.” So, we’ll need to wait a bit until all of the power of Knowledge Graphs for inference can be demonstrated. A set of instructions is provided, and they look fairly simple: Caption: Instructions for txt2kg And NVIDIA has a couple of videos that demonstrate the use of the txt2kg: Turn Text Into a Knowledge Graph with 70B LLM on DGX Spark I’m not a big fan of this one, although it’s short (about two minutes long), so you might as well watch it. It purports to demonstrate txt2kg on a 70B LLM (llama3.1:70b-instruct-q4_K_M) but there’s so much it doesn’t show, or “blurs” out to obfuscate what might be going on under the hood. DGX Spark Live: Process Text for GraphRAG With Up to 120B LLM This is worth a watch as well, and it’s longer (about 40 minutes). The only frustrating thing about it is that it purports to run on a 120B LLM (gpt-oss:120b), which is pretty large for the Spark, so we’ll see. There’s also a couple of useful articles to read in the NVIDIA Forums that proved invaluable: Unfortunately, there’s a lot more that needs to be done beyond what’s covered in the above, and there are many pitfalls; I’ll describe some of my own experiences below, in the hope to save readers some time. But first, it was necessary to divide up the SourcePoint User Guide into many separate constituent markdown (.md) files. txt2kg isn’t designed to swallow one monolithic PDF (in this case, 700+ pages worth, and 4MB in size). And it works with text (.md, .csv, .txt, and .json) only; a lot of the images that are in the SourcePoint User Guide can’t be consumed, and just clog up the works if you attempt to go further. As it turns out, these images aren’t really needed to put together a good KG for this document. So, first, we’ll use the Docling application (readers may remember my first attempt to use this in Part 2 of this series, Breaking the Token Barrier), to change the PDF to a single markdown file. As a separate note: from the Part 2 blog in this series, I found that the Intel SDM was not structured well for easy processing. The tables, in particular, don’t lend themselves to easy conversion to txt or md files. It’s a side project (Maybe hire an intern? Or use Copilot, Claude, etc.?) to put this into a form that Docling can easily convert without losing much of the value of the content. The specific Docling command to run on the SourcePoint PDF is: docling –to md SourcePoint.pdf –image-import-mode placeholder The “–image-import-mode placeholder” removes all images. And then, it’s necessary to chop up this monolithic markdown file into individual .md files for the separate sections within
The New Chapter of Egress Communication with Cobalt Strike User-Defined C2
Introduction For years, External C2 has been regarded as one of the most effective ways to bypass EDR and XDR solutions thanks to its ability to support custom-built egress channels. It allows red teams to design their own communication mechanisms, avoiding the static signatures that defenders traditionally monitor and detect. However, several limitations became apparent as External C2 matured: User-Defined C2: The New External C2 User-Defined C2 (UDC2) was introduced as the evolution of External C2, specifically designed to address many of these shortcomings. UDC2 is significantly lighter and only requires the development of a Beacon Object File (BOF) rather than a full standalone client. The new workflow can be summarized as follows: Beacon leverages the UDC2 BOF to transmit encrypted frames over the custom C2 channel implemented in the BOF. Using your C2 protocol, the BOF communicates frame data with the UDC2 server, which relays it to the UDC2 listener on your Cobalt Strike team server via a direct TCP link. The following image describes the architecture difference between User-Defined and External C2: As illustrated in the diagram, while from a development perspective the attacker infrastructure remains (almost) the same, the difference is in the client itself. Previously with External C2, the whole client must be developed. Meaning that the client will request the SMB beacon, inject it in the client itself and communicate with it through named pipe to relay the beacon task and later parse its output before sending it back to the Teamserver via the egress channel. With UDC2, only the BOF is required to develop, which will proxy the beacon functions, so its traffic gets redirected to the custom communication channel. Since the Beacon remains untouched, we can make use of Artifact Kit, Sleep Mask, UDRL and all the other evasion features Cobalt Strike offers. User-Defined C2: The Advantages With UDC2: However, the primary limitation is that development is constrained to C, since Beacon Object Files (BOFs) must be written in C. The additional BOF can also have evasive characteristics, particularly when leveraging APIs or libraries associated with commonly used services such as Slack, Microsoft platforms, AWS, Mattermost, Discord, etc. When aligned with legitimate tools and communication patterns already present in the target environment, the BOF’s traffic is more likely to blend in. However, extended or high-volume tasking – such as relaying large amounts of traffic – may generate abnormal spikes (for example, an unusually high rate of Slack messages per minute), which could appear suspicious to monitoring solutions or EDR platforms. Increasing Beacon sleep intervals can help reduce this visibility, though this approach may be less suitable for proxychains traffic, where speed is required to avoid connection timeout. Demo: Slack Egress Channel Since Fortra has open sourced a project demonstrating UDC2 via ICMP echo requests and replies, we decided to experiment with the new capability – this time using Slack instead. To achieve this, we set up a Slack workspace and created a bot with permissions to send and read messages. Our design uses two separate channels: one for client-to-server communication and another for server-to-client responses. This separation helps prevent any potential communication collisions. The initial development of the Slack transport began with a simple goal: leverage the WinInet API to perform HTTPS POST and GET requests against the Slack Web API. In the early “Proof of Concept” phase, the logic was simple—data was formatted using standard library functions like sprintf, and buffers were declared as fixed-size arrays on the stack (e.g., char response[8192]). While this worked in a standard executable environment, it was fundamentally incompatible with the constraints of a Beacon Object File (BOF). To solve this, we had to systematically “de-stack” the entire implementation. Every large buffer—the raw HTTP response, the extracted JSON value from Slack API, and the intermediate Base64 decoded binary—was migrated to the process heap. The official’s example has already implemented a safeHeapAlloc wrapper around Kernel32$HeapAlloc. Instead of: char resp[16384]; // Triggers __chkstkWe moved to: void* respPtr = NULL; safeHeapAlloc(&respPtr, 16384); // BOF compatible The same logic must be applied for data send logic. From the server-side, we created the following Python3 code to read and send data via Slack API: The final result is a default Beacon sending data through Slack API and the third-party server relaying it to Cobalt Strike’s Team Server, resulting in a Slack egress client/server communication: Conclusion In summary, while External C2 paved the way for flexible and stealthy command-and-control customization, its architectural and operational shortcomings eventually limited its practicality. User-Defined C2 represents a more mature evolution, delivering lighter integration, improved OPSEC, and reduced development overhead by leveraging BOFs instead of standalone clients. Although it does introduce constraints, most notably its dependency on C, it offers a far more streamlined and maintainable approach to building custom egress channels, ultimately empowering red teams with a cleaner, safer, and more scalable alternative. All codes and scripts referenced throughout this post, as well as the final project are available on our GitHub repository. References
UEFI Vulnerability Analysis using AI Part 2: Breaking the Token Barrier
In my Part 1 article on this topic, I used the ChatGPT frontier model to perform something that was previously unthinkable: an accurate machine analysis of OpenSSL vulnerabilities in the open-source EDKII build for an Intel CPU. This article documents the research to extend the LLM context memory beyond that of just the OpenSSL code: in fact, to analyze the entire UEFI firmware codebase simultaneously. Imagine the subtle bugs and vulnerabilities that might be found, if the entire UEFI codebase could be kept in memory and inferenced at one time. An LLM’s context window is the ultimate determinant of how much memory a given session holds: that is, how much can the model keep “in memory” before it starts to forget earlier context. Think of it in terms of the human brain: theoretically, we can remember everything from the current moment back to early childhood. Things might get fuzzy the further back we go; but at least in principle, if we took for example a Calculus course in college, we can probably do some simple derivatives even today in our head. More complex derivatives might take a few moments of self-study, but we’d be up to speed quickly. This is an analogy at best, and I’m probably mixing my AI “training” and “inference” metaphors a little to make the point. But machines work similarly to the human brain: in some respects, the LLM context window represents an LLM’s memory of the information that has been fed to it, up to a point. This is ultimately dependent on the amount, in classical AI implementations, of the amount of VRAM that is available to the GPUs involved in the inference stage. But it is possible to work around that, as we’ll see. In the earlier article, UEFI Vulnerability Analysis Using AI: Part 1, I did some basic analysis using ChatGPT of the CryptoPkg module within the Tianocore EDKII source tree, and it performed admirably. And when questioned, ChatGPT admitted: My current context window is about 128k tokens (roughly 400–500 pages of text). That’s the maximum amount of text I can keep “in working memory” at once when analyzing a file or conversation. Given the above constraint, and the fact that the CryptoPkg module itself is 65MB in size, with 18,668 files/folders therein, it’s a given that ChatGPT was doing some magic behind the scenes, or worse, silently disposing of earlier tokens and “forgetting” them as part of the analysis. This was not what I wanted. The goal is a transparent, clear use of an “open-source” downloadable LLM on my DGX Spark that I could tune specifically for the purposes of vulnerability detection in a huge codebase, striving for as much accuracy as possible; recognizing that there would be tradeoffs between reasoning power (LLM parameters), codebase size (token context window), system performance, and other factors. So continued the journey to develop this solution, make as many mistakes as I could, trip over as many obstacles as possible, and fall into as many pits as I could find. Such is the fast-track hands-on way of becoming an AI developer! On the DGX Spark, front-and-center in the Getting Started section that pops up when you first boot up the system is the Playbook for using the Open WebUI application with Ollama: It was extremely easy to set up, and I’ve had a lot of experience with Ollama, so I decided to start this way – only to regret it, as you’ll see shortly. But first, it was necessary to choose an Ollama model that would be well-suited to this purpose, with a large context window, and that would run comfortably on the DGX Spark. After some research, here’s a summary of what I found a few weeks ago: Here’s the top LLM for local large-codebase analysis (with tags, params, context, disk size, quant, and rough VRAM needs). 1️⃣ DeepSeek-R1-Distill-Llama-70B Why #1: best open-weight reasoning model right now, with 128K context and strong performance on code + general logic. Great for “understand this whole subsystem + design” type work. Ollama tag (typical): deepseek-r1:70b → currently deepseek-r1:70b-llama-distill-q4_K_M under the hood Ollama+2Ollama+2 Parameters: ~70.6B Context window: 128K tokens (Ollama tag lists 128K context window) Ollama Quantization (Ollama default): Q4_K_M (there’s also a q8_0 tag at ~75GB if you want higher fidelity) Ollama Size on disk (Ollama q4_K_M): ~43GB Ollama+1 VRAM you should plan for (quantized): For smooth use at 32K–64K context with everything on GPU: ~48–60GB With offloading (some layers on CPU/host RAM): workable on 24–32GB, but slower. Best use: Cross-file reasoning, understanding protocols/architectures, finding subtle bugs, mixing code + docs + logs. You can always let R1 “think aloud” then truncate the chain-of-thought if you don’t need verbosity. Sounds easy, right? Well, it wasn’t. In the interest of time, I won’t belabor all I went through, but I found that Retrieval-Augmented Generation (RAG) did not work reliably with Open WebUI, among other things. And the simplistic interface did not seem to have all the bells and whistles I would need to truly fine-tune a local LLM to do codebase analysis. So, after punting on Open WebUI, after some research, I decided to move to LM Studio – this promised to be a low-code way of achieving the goal. If you haven’t any experience with LM Studio yet, I’d highly recommend watching the YouTube video Correctly Install LM Studio on Linux Ubuntu and Host LLMs Using GUI, it will definitely save you time. Here’s a short list of things you need to do on the Spark to set it up: Download the .AppImage installation file from www.lmstudio.ai/download?os=linux. At the time of this writing, it’s LM-Studio-0.3.33-1-arm64.AppImage. Create an LMStudio folder in your home directory. Copy the .AppImage file from the Downloads folder into the LMStudio folder. Open a Terminal session, and navigate to the LMStudio folder with cd ~/LMStudio. Type chmod u+x LM-Studio-0.3.33-1-arm64.AppImage. Navigate to the newly created squashfs-root folder: cd squashfs-root Type in: sudo chown root:root chrome-sandbox sudo chmod 4755 chrome-sandbox Now you can directly invoke ./lmstudio