Sleepless Strings - Template Injection in Insomnia
Marcio Almeida (Co-founder and Technical Director · Tanto Security), Justin Steven (Head of Research · Tanto Security)
BSides Canberra VIII (2025) · Day 3 · Main Track
Overview
In "Sleepless Strings: Template Injection in Insomnia," Marcio Almeida and Justin Steven of Tanto Security unveil a critical client-side template injection vulnerability within Insomnia, a popular API development client by Kong Inc. The talk meticulously details their journey from an accidental discovery during a penetration test to developing sophisticated remote code execution (RCE) exploits, and the subsequent cat-and-mouse game with the vendor as they attempted to patch the underlying issue. This presentation is a compelling case study on the often-underestimated risks of client-side vulnerabilities, the complexities of vulnerability disclosure, and the challenges of mitigating fundamental design flaws.

Key moments
- 0:40 Understanding template engines and their power
- 7:50 Accidental discovery of template injection in Insomnia
- 13:40 Initial exploit: code execution via malicious collection file
- 18:40 Remote code execution via poisoned HTTP cookies
- 26:10 Vendor's first patch and immediate bypass demonstration
- 34:50 Bypassing cookie sanitization with template 'sandwich' trick
- 37:50 Node integration disabled: limiting code execution impact
- 50:00 Advice for vendors on improving vulnerability disclosure
Sleepless Strings - Template Injection in Insomnia
Speakers: Marcio Almeida (Co-founder and Technical Director, Tanto Security); Justin Steven (Head of Research, Tanto Security)
Conference: BSides Canberra
YouTube: https://www.youtube.com/watch?v=7bMTu3yCZVc
Overview
In "Sleepless Strings: Template Injection in Insomnia," Marcio Almeida and Justin Steven of Tanto Security unveil a critical client-side template injection vulnerability within Insomnia, a popular API development client by Kong Inc. The talk meticulously details their journey from an accidental discovery during a penetration test to developing sophisticated remote code execution (RCE) exploits, and the subsequent cat-and-mouse game with the vendor as they attempted to patch the underlying issue. This presentation is a compelling case study on the often-underestimated risks of client-side vulnerabilities, the complexities of vulnerability disclosure, and the challenges of mitigating fundamental design flaws.
The core of the issue lies in Insomnia's default behavior of evaluating user-controlled input as Nunjucks templates, a powerful templating engine. While template engines are designed to safely interpolate data, they become a significant security risk when an attacker can control the template itself. Almeida and Steven demonstrate how this design decision, initially overlooked, could lead to arbitrary JavaScript execution and ultimately RCE on a user's machine, simply by importing a malicious API collection or, more alarmingly, by receiving a crafted HTTP cookie.
This talk is highly significant for developers, security researchers, and API users alike. It highlights that even trusted desktop applications built with frameworks like Electron (which bundle Node.js) can harbor severe vulnerabilities if core security principles are not adhered to. The speakers' persistent efforts in bypassing multiple vendor patches underscore the brittle nature of mitigation strategies that fail to address the root cause, offering invaluable lessons on secure development practices and the critical importance of comprehensive vulnerability handling.
Background
▶ Watch: Understanding template engines and their power (0:40)
The concept of template injection originates from the misuse of templating engines, which are software components designed to combine a static template with dynamic data to produce a final document. Common examples include rendering HTML pages with user-specific content. The standard secure practice dictates that only untrustworthy data should be fed into the parameters side of the engine, while the template itself remains controlled by the developer. Many engines even offer automatic HTML encoding for parameters to prevent Cross-Site Scripting (XSS).
However, a critical vulnerability arises when an attacker can control the template content. This class of vulnerability, popularized as Server-Side Template Injection (SSTI) by James Kettle of PortSwigger in 2015, allows attackers to inject malicious code directly into the template, which is then executed by the powerful templating engine. The complexity and power of engines like Jinja2, Twig, or, in this case, Nunjucks, mean that controlling the template often grants arbitrary code execution or access to underlying system functions. While SSTI typically refers to server-side exploitation, Almeida and Steven reveal a similar paradigm on the client-side.
Insomnia, developed by Kong Inc., is a desktop API client built with Electron (which integrates Node.js), serving as a popular alternative to tools like Postman. It allows developers and penetration testers to create, test, and manage API requests. A key feature for penetration testers, as highlighted by Marcio Almeida, is its "local scratchpad" functionality, which prevents sensitive API collections (potentially containing credentials for development or even production environments) from being synchronized to a cloud environment. This local storage, while beneficial for privacy, becomes a critical attack vector when combined with template injection.
The genesis of the discovery was during an API penetration test. Almeida encountered an API endpoint that returned partially built HTML in its JSON response, prompting him to test for XSS and template injection. He sent the classic template injection payload {{7*7}} through Insomnia, expecting it to be passed through to the target API. To his surprise, the API responded with 49. Further investigation revealed that Insomnia itself was evaluating the payload before sending it, treating the input as a template. This unexpected behavior stemmed from Insomnia's use of Nunjucks for evaluating environment variables and other dynamic content. The Nunjucks documentation explicitly warns: "Nunjucks does not sandbox execution. It's not safe to run user-defined templates or inject user-defined content into a template definition." This stark warning directly contradicted Insomnia's default functionality, setting the stage for the vulnerability.
Key Findings
▶ Watch: Initial exploit: code execution via malicious collection file (13:40)
The central finding was a client-side template injection vulnerability in Insomnia, specifically allowing arbitrary code execution due to the application's default evaluation of user-controlled input as Nunjucks templates. This was initially discovered by Marcio Almeida during a routine penetration test.
The key discoveries and their evolution include:
- Initial Payload & Impact: The
{{7*7}}payload confirmed that Insomnia's internal environment variable processing (and other fields) used a Nunjucks templating engine. Further research quickly led to a simple Nunjucks payload capable of achieving arbitrary JavaScript execution, such as{{(self.constructor.constructor("alert('Code Execution!')"))()}}. - Import Collection as a Vector: The most straightforward exploitation vector identified was through importing a malicious API collection file. An attacker could craft an Insomnia collection (e.g., a
.jsonfile) containing the Nunjucks RCE payload. If a user imported this file and then navigated to a request containing the payload, the code would execute on their machine. This provided a plausible pretext for phishing developers or security testers. - Remote Code Execution via Cookies: Justin Steven and Marcio Almeida significantly escalated the threat by discovering a remote, zero-click RCE vector using HTTP cookies. Insomnia's behavior of storing and evaluating cookies as templates meant that an attacker could set a malicious cookie (e.g., via a crafted HTTP response from a server). Upon the next request sent by Insomnia, the application would attempt to evaluate this cookie as a template, triggering RCE without direct user interaction beyond sending a request to a malicious or compromised server. This transformed the vulnerability from a high-interaction file-import scenario to a stealthier, more potent remote attack.
- Vendor Response & Patch Bypasses: The vendor, Kong Inc., initially dismissed the report as a duplicate of a publicly known GitHub issue from 2020. However, upon understanding the remote cookie vector, they re-prioritized it as a critical CVSS 9.3 issue. This led to a series of iterative patches and subsequent bypasses:
- Blocking
require: Insomnia attempted to block therequirekeyword, which is commonly used in Node.js to load modules (likechild_processfor RCE). This was bypassed by encoding/obfuscating the string or usingmodule.require. - Removing
range,cycler,joiner: The original RCE chains often leveraged global Nunjucks functions likerange.constructor.constructor. Insomnia removedrangeandcycler, but the researchers quickly foundjoiner.constructor.constructorachieved the same goal. Whenjoinerwas also removed, they discovered many other JavaScript objects ("".constructor.constructor,"".toString.constructor) could be used as an "eval sync" to access theFunctionconstructor. - Cookie Sanitization Bypass: Insomnia attempted to sanitize cookies by stripping
{{and}}characters. This was bypassed using a "sandwich trick" (e.g.,{{{{payload}}}}where the inner braces protect the outer ones from immediate sanitization) and later via double interpolation with Nunjucks comment tags ({# #}), which were not sanitized. - Disabling Node Integration: In a significant move, Insomnia v11.4.0 disabled Node.js integration within the Nunjucks sandbox. This prevented direct use of Node.js APIs like
require('child_process')for RCE. However, the researchers demonstrated that JavaScript execution was still possible, allowing for internal network requests, file reading (via new internal APIs or../traversal on allowed paths), and exfiltration of sensitive environment variables (API keys, credentials) stored within Insomnia.
- Persistent Remote JavaScript Implant: Even with Node integration disabled, the remote cookie RCE allowed for a persistent JavaScript implant within Insomnia. This implant could hook the templating engine, observe all user requests, exfiltrate sensitive data (like credentials from environment variables), and even establish a C2-like communication channel by polling an attacker's server for further JavaScript commands to execute.
The vendor's initial oversight and the subsequent reactive patching efforts underscore the challenges of mitigating a fundamental design flaw where user-controlled input is treated as executable code.
Technical Deep Dive
▶ Watch: Vendor's first patch and immediate bypass demonstration (26:10)
The technical core of this vulnerability lies in Insomnia's use of Nunjucks as its templating engine for dynamic content, including environment variables, request bodies, and, crucially, HTTP cookies. Nunjucks, being a powerful JavaScript templating engine, allows for complex logic, including filters, macros, and access to global JavaScript objects.
The initial discovery involved the simple Nunjucks payload {{7*7}}. When evaluated by Nunjucks, this performs the arithmetic operation and returns 49. The key insight was that if Nunjucks was evaluating simple arithmetic, it could also evaluate more complex JavaScript.
The primary method for achieving arbitrary JavaScript execution in a Nunjucks environment involves leveraging JavaScript's object model to gain access to the Function constructor. A common pattern, similar to those found in Jinja2 SSTI for Python, is to find an object that exposes its constructor property. The constructor of a function is Function. Once you have the Function constructor, you can use it to create and execute arbitrary JavaScript code from a string.
Initially, the researchers used a payload similar to:
{{(self.constructor.constructor("alert('Code Execution!')"))()}}
Here, self refers to the Nunjucks context. In many JavaScript environments, self (or this in a global context) can be used to access global objects. The constructor of an object provides access to the function that created it. The constructor of a function is the Function object itself. Therefore, self.constructor.constructor effectively gives access to the Function constructor. By calling Function("arbitrary_js_code")() you can execute any JavaScript string.
When Insomnia attempted to block specific global Nunjucks functions like range, cycler, and joiner (e.g., {{range.constructor.constructor("...")()}}), the researchers demonstrated that many other JavaScript objects could serve the same purpose. For instance:
{{ "".constructor.constructor("alert('bypassed!')")() }}(String object){{ "".toString.constructor("alert('bypassed!')")() }}(String prototype method)
These payloads derive the Function constructor from fundamental JavaScript types, proving difficult to block without fundamentally altering the JavaScript environment.
For Remote Code Execution (RCE), the JavaScript execution needs to break out of the browser-like sandbox into the underlying Node.js environment. Electron applications, by default, often have nodeIntegration enabled, meaning the JavaScript context has access to Node.js modules. The classic Node.js RCE payload involves using require('child_process') to spawn system commands:
{{(self.constructor.constructor("require('child_process').execSync('calc.exe')"))()}}
This would pop a calculator on a Windows system.
Insomnia's initial attempts to mitigate this focused on sanitization and blocking specific keywords:
- Blocking
require: Version 11 shipped with a fix to block the string "require". This was bypassed using various obfuscation techniques (e.g., string concatenation, Nunjucks filters, or even Nunjucks' own templating features to dynamically construct the string). The most effective bypass wasmodule.require, which accesses therequirefunction through themoduleglobal object, often bypassing simple string checks. - Cookie Sanitization: To counter the remote cookie RCE, Insomnia implemented a sanitizer that stripped
{{and}}from cookie values. This was defeated in two ways:
- The "Sandwich Trick":
{{{{payload}}}}– The sanitizer would process from left to right. It might remove the outer{{, leaving{{payload}}, which would then be evaluated. If it removed the right}}first, it would leave{{payload{{, which would then be processed again. The key was that the replacement chain happened one by one, allowing for a nested structure to survive. - Double Interpolation with Comment Tags: Nunjucks comment tags
{# #}were not stripped by the cookie sanitizer. This allowed for a payload like{{ "{#" + "a" + "#}" + "{{" + "payload" + "}}" }}. After the first round of templating (by Nunjucks itself), the comment tags would be evaluated, leaving{{payload}}, which would then be subject to a second round of interpolation, thus bypassing the sanitizer that only looked for raw{{and}}. This highlights the dangers of sanitization that isn't robust and multi-pass.
The most significant mitigation from Insomnia came in versions 11.40 and later: disabling Node.js integration within the Nunjucks rendering sandbox. This isolated the template execution environment, preventing direct access to Node.js APIs like child_process. While this effectively stopped direct RCE via require, it did not stop arbitrary JavaScript execution within the sandbox. The researchers demonstrated that even in this restricted environment, an attacker could:
- Make arbitrary HTTP requests to the local network or external servers.
- Read local files using internal Insomnia APIs or by leveraging the
filetag with path traversal (../) if a user had allowed any path. - Exfiltrate environment variables: Insomnia's "Manage Environments" feature, which stores API keys and credentials, exposes these values to the Nunjucks sandbox. Arbitrary JavaScript could read these sensitive values and exfiltrate them.
- Install a persistent JavaScript implant: By hooking the
onmessagehandler (the entry point into the sandbox), an attacker could observe and manipulate all subsequent template rendering requests, effectively creating a persistent C2-like mechanism within the Insomnia client. This implant could continuously exfiltrate data, poll for new commands, and monitor user activity within the application.
This detailed technical progression illustrates a fundamental security principle: fixing symptoms (like blocking keywords or sanitizing specific inputs) is often less effective than addressing the root cause (evaluating untrusted input as code).
Demo / Proof of Concept
▶ Watch: Bypassing cookie sanitization with template 'sandwich' trick (34:50)
The talk showcased several compelling demonstrations and proof-of-concept (PoC) scenarios, evolving from simple observation to sophisticated remote exploitation:
- **Initial Discovery (
{{7*7}}):** Marcio Almeida recounted the accidental discovery during a penetration test. He initially sent{{7*7}}as an SSTI payload to a target API via Insomnia. When the API responded with49, he first celebrated an SSTI on the target. However, upon reviewing the request in Burp Suite, he found that Insomnia had already replaced his payload with49. Sending the same payload directly via Burp Suite to the target API resulted in the literal{{7*7}}string being returned, confirming that Insomnia itself was the vulnerable component. He then observed that the environment variable fields within Insomnia were evaluating these Nunjucks templates.
- Code Execution with
alert(): The next PoC involved a simple JavaScript payload to demonstrate arbitrary code execution. Almeida used a slightly modified version of theFunctionconstructor payload, such as{{(self.constructor.constructor("alert('Code Execution!')"))()}}, which would cause a JavaScriptalertbox to pop up on the user's screen when the template was evaluated. This visually confirmed the ability to execute arbitrary JavaScript.
- Importing a Malicious Collection: The first practical exploitation vector involved crafting an Insomnia collection file (
.json) containing the malicious Nunjucks payload. The demonstration showed a user importing this file into their Insomnia scratchpad. Merely navigating to the request within the imported collection that contained the payload would trigger thealert()pop-up, proving code execution on the victim's machine. This highlighted the risk of sharing or downloading untrusted Insomnia collection files.
- Remote Code Execution via Cookies: This was the most impactful demonstration.
- Poisoning the Cookie Jar: The researchers set up a simple Python web server that, when queried, would respond with a
Set-Cookieheader containing the malicious Nunjucks RCE payload (e.g.,Set-Cookie: evilcookie={{(self.constructor.constructor("alert('RCE via cookie!')"))()}}). - Triggering Execution: The demo showed an Insomnia user sending a request to this malicious server. Insomnia would receive and store the crafted cookie. Crucially, upon sending any subsequent request (even to a legitimate, unrelated endpoint), Insomnia would attempt to evaluate all cookies in its cookie jar before sending them. This evaluation process would trigger the RCE payload, causing the
alert()pop-up. This "first request poisons, second request executes" mechanism demonstrated a truly remote, low-interaction attack. - Exfiltrating Data with Cookies: A further refinement showed how cookies could be used as a covert command-and-control (C2) channel. A Python script on the attacker's server would execute a command (e.g.,
whoami), encode the output, and embed it into aSet-Cookieheader. The victim's Insomnia client would receive, execute, and then exfiltrate this output in the subsequent request's cookie header back to the attacker's server, providing a way to retrieve command results.
- Persistent JavaScript Implant: The final, most advanced PoC demonstrated the ability to install a persistent JavaScript implant within Insomnia, even after Node.js integration was disabled. The attacker's server would deliver a JavaScript payload via a cookie that:
- Hooks the
onmessagehandler of the Nunjucks sandbox to observe all template rendering. - Reads sensitive environment variables (API keys, credentials) from Insomnia's configuration.
- Makes background HTTP requests to exfiltrate this data and poll the attacker's server for new commands.
- This "sleepless strings" implant could continuously monitor and exfiltrate data from the user's Insomnia client until the application was restarted, illustrating a comprehensive compromise.
These demonstrations collectively painted a clear picture of the escalating severity and sophistication of the exploitation techniques, from a local file import to a persistent, remote, and highly stealthy implant.
Defensive Implications
▶ Watch: Advice for vendors on improving vulnerability disclosure (50:00)
The "Sleepless Strings" vulnerability offers crucial lessons for developers and security professionals regarding the secure use of templating engines and the defense of client-side applications. The speakers strongly advocate for PortSwigger's four-step "grief handling process" for template injection:
- Don't pass untrusted data into the template side: This is the golden rule. If an application's functionality requires dynamic templates, re-evaluate the design. In Insomnia's case, treating user-controlled content (like cookies or environment variables) as templates inherently violates this principle.
- Use less sophisticated engines: If untrusted template control is unavoidable, opt for simpler templating engines (e.g., Mustache) that have limited logic and are less prone to RCE. Nunjucks, like Jinja2, is highly powerful and thus inherently riskier.
- Sandbox the template renderer: If a powerful engine is necessary, implement robust sandboxing. However, the talk repeatedly demonstrated that sandboxing is "inherently difficult and prone to bypasses," as seen with Insomnia's attempts to block
require, specific globals, and sanitize input. This approach often leads to an arms race between developers and attackers. - Accept arbitrary code execution and containerize: The most extreme measure is to assume RCE is inevitable and run the template rendering in an isolated environment (e.g., a Docker container or a dedicated web worker with strict isolation). Insomnia's move to disable Node.js integration within the sandbox was a step in this direction, limiting the RCE to JavaScript execution within a browser-like context.
Specific recommendations for defenders based on Insomnia's experience:
- Prioritize Root Cause Fixes: Insomnia's initial attempts to block keywords (
require) or sanitize input (cookies) proved brittle and easily bypassed. These are mitigation strategies, not fixes. The root cause was the implicit trust placed on user-controlled input being evaluated as a Nunjucks template. A true fix would involve either not using Nunjucks for such inputs or strictly sandboxing it from the ground up to prevent access to sensitive JavaScript features. - Be Wary of Sanitization: The cookie sanitization bypasses (sandwich trick, double interpolation) vividly illustrate that sanitization is incredibly difficult to get right. It requires anticipating all possible attacker permutations and edge cases, which is a monumental and often impossible task.
- Early Design Decisions Matter: Choosing a powerful templating engine like Nunjucks for user-controlled inputs introduces significant risk. Had a simpler, less powerful engine been chosen initially, or had the principle of not evaluating untrusted input as templates been followed, this entire class of vulnerability might have been avoided. Changing this later is challenging due to user dependency on existing syntax.
- Implement Strong Isolation for Client-Side Apps: For Electron apps, disabling
nodeIntegrationis a critical step to prevent direct RCE. However, as shown, even withnodeIntegrationoff, the ability to execute arbitrary JavaScript allows for significant compromise, including internal network scanning, file exfiltration (via internal APIs), and credential theft from environment variables. Further isolation, potentially using multiple web workers with strict Content Security Policies (CSPs) and inter-process communication (IPC) validation, is necessary. - User-Controlled Paths and Data: Features like Insomnia's
filetag, which allows users to bless certain paths for file reading, must be implemented with extreme caution. The../path traversal bypass demonstrated how even seemingly safe allowlists can be circumvented. Similarly, any user-controlled data that is processed by a templating engine (e.g., environment variables, request parameters, headers, cookies) should be treated as untrusted. - Improve Vulnerability Disclosure Processes: The communication challenges highlighted in the talk (initial dismissal, lack of transparent plans, delayed gift card) underscore the need for vendors to foster better relationships with researchers. Transparent communication, engaging technical staff, and clear timelines can significantly improve the remediation process and build trust.
Ultimately, the talk serves as a stark reminder that security must be integrated into design from the outset, rather than bolted on as an afterthought through brittle mitigations.
Key Takeaways
- Client-Side Template Injection is a Critical Threat: The talk demonstrates that template injection vulnerabilities are not confined to server-side applications. Client-side applications, especially those built with frameworks like Electron, can suffer from severe template injection issues leading to arbitrary code execution and data exfiltration.
- Untrusted Input + Powerful Template Engine = RCE: Treating user-controlled input (such as HTTP cookies or environment variables) as templates, especially with powerful engines like Nunjucks, is a fundamental design flaw that inevitably leads to security vulnerabilities.
- Sanitization is Brittle and Often Ineffective: Relying on string sanitization or keyword blocking to prevent template injection is a weak defense. Attackers can almost always bypass these mitigations through encoding, obfuscation, or leveraging engine-specific features like double interpolation.
- Root Cause Remediation is Paramount: Patching symptoms rather than addressing the root cause leads to an endless cycle of bypasses and re-patches. Developers should prioritize re-architecting features that misuse templating engines rather than implementing reactive, brittle fixes.
- Even "Sandbox" Bypass Leads to Significant Compromise: While disabling Node.js integration prevents direct RCE via
child_process, arbitrary JavaScript execution within an Electron sandbox still allows for internal network reconnaissance, file exfiltration, credential theft (from environment variables), and persistent implants. - Vulnerability Disclosure Remains Challenging: The experience with Kong Inc. highlights the difficulties in vulnerability disclosure, including initial dismissal, communication breakdowns, and the complexities of coordinating patches and public disclosure. Both vendors and researchers can improve by fostering more transparent and patient communication.
About the Speaker(s)
Marcio Almeida is a Co-founder and Technical Director at Tanto Security. He is a seasoned security professional with expertise in penetration testing and vulnerability research, as demonstrated by his discovery and detailed analysis of the Insomnia template injection vulnerability. His practical experience in API penetration testing directly led to the initial finding presented in this talk.
Justin Steven is the Head of Research at Tanto Security. He collaborates with Marcio Almeida on advanced vulnerability research and exploit development. Justin played a key role in escalating the Insomnia vulnerability from a local file import to a remote, cookie-based code execution, and in bypassing subsequent vendor patches. His contributions emphasize a deep understanding of web security and client-side exploitation techniques.