SkillAgentSearch skills...

sast-pathtraversal

Detect path traversal vulnerabilities in a codebase using a three-phase approach: recon (find file-loading sinks with dynamic paths), batched verify (trace user input and mitigations in parallel subagents, 3 sinks each), and merge (consolidate batch results).

Install / Use

npx skills add utkusen/sast-skills --skill sast-pathtraversal

Installs into whichever agent you are using.

About this skill
📄

SKILL.md

Installable skill definition

Quality Score

89/100

Category

Security

Supported Platforms

Universal

Our assessment of sast-pathtraversal

sast-pathtraversal scores 89/100 on our quality scale, 492nd of 971 Security skills we index.

Its SKILL.md is 27 KB long, well organised into 36 sections with 17 code examples: a thorough specification that gives an agent plenty to work with.

With 1,321 GitHub stars, it is one of the more widely adopted skills in the catalogue.

Substance
30/30
Structure
20/20
Description
15/15
Adoption
13/20
Freshness
11/15

Maintenance, license and trust

  • The repository was last updated about 6 months ago. That is recent enough to be usable, but agent tooling moves fast, so check the instructions against your agent's current version.
  • It is released under the MIT license, a permissive license that allows use, modification and commercial use with attribution.
  • Its trust signals score 98/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.

sast-pathtraversal compared with similar skills

All 4 of these similar skills score higher than sast-pathtraversal; compare them before choosing.

SkillScoreStarsUpdatedFormat
sast-pathtraversal (this skill)by utkusen891.3k6mo agoSKILL.md
algorithmic-artby anthropics100177.9k8d agoSKILL.md
pptxby anthropics100177.9k8d agoSKILL.md
designby nextlevelbuilder100130.2k9d agoSKILL.md
ui-ux-pro-maxby nextlevelbuilder100130.2k9d agoSKILL.md

Frequently asked questions

How do I install sast-pathtraversal?
Run npx skills add utkusen/sast-skills --skill sast-pathtraversal. The install tabs above show the steps for each supported agent.
Which AI agents does sast-pathtraversal work with?
It is written for Universal, as a SKILL.md file. Other agents that read the same format can often use it too.
Is sast-pathtraversal safe to use?
It is MIT-licensed and scores 98/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
Is sast-pathtraversal still maintained?
The repository was last updated about 6 months ago. That is recent enough to be usable, but agent tooling moves fast, so check the instructions against your agent's current version.

name: sast-pathtraversal description: >- Detect path traversal vulnerabilities in a codebase using a three-phase approach: recon (find file-loading sinks with dynamic paths), batched verify (trace user input and mitigations in parallel subagents, 3 sinks each), and merge (consolidate batch results). Requires sast/architecture.md (run sast-analysis first). Outputs findings to sast/pathtraversal-results.md. Use when asked to find path traversal, directory traversal, or file disclosure bugs.

Path Traversal Detection

You are performing a focused security assessment to find path traversal vulnerabilities in a codebase. This skill uses a three-phase approach with subagents: recon (find file-loading sinks with dynamic paths), batched verify (trace user input and check mitigations in parallel batches of 3), and merge (consolidate batch results into one report).

Prerequisites: sast/architecture.md must exist. Run the analysis skill first if it doesn't.


What is Path Traversal

Path traversal (also called directory traversal) occurs when user-supplied input is incorporated into a file path that is then used to read, write, or serve files from the filesystem — without properly constraining the resulting path to an intended base directory. An attacker can supply sequences like ../ or encoded variants (%2e%2e%2f, ..%2f, %2e%2e/) to escape the intended directory and access arbitrary files such as /etc/passwd, application source code, credentials, or private keys.

The core pattern: unvalidated user input reaches a filesystem operation and the resolved path is not verified to remain within the intended base directory.

What Path Traversal IS

  • Serving a user-requested filename directly from a base directory without canonicalizing and checking the resulting path: open(os.path.join(BASE_DIR, user_filename))
  • Constructing a file path from a URL parameter and passing it to a file-read function: fs.readFile(path.join(__dirname, req.query.file), ...)
  • Template rendering or include directives driven by user input: include($_GET['page'] . '.php')
  • Archive extraction (ZipFile, tarfile, zipslip) where entry names are used as output paths without stripping ../ components
  • Using send_file() / send_from_directory() / res.sendFile() with an unsanitized user-controlled path
  • Reading a file whose path is derived from a user-controlled database value that was stored without sanitization

What Path Traversal is NOT

Do not flag these as path traversal:

  • SSRF: Fetching a remote URL from user input — that is Server-Side Request Forgery, a separate class
  • RCE via file write: Writing attacker-controlled content to an arbitrary path — related but a different impact class (flag as RCE or File Upload)
  • Static file serving: Serving files from a path that is entirely hardcoded with no user influence
  • Safe path joins followed by realpath + prefix check: The code computes realpath() and verifies it starts with the intended base directory
  • basename() before join: Using only the filename component strips traversal sequences (though note this prevents directory selection, not just traversal)

Patterns That Prevent Path Traversal

When you see these mitigations applied before the file operation, the code is likely not vulnerable:

1. realpath / resolve followed by a base-directory prefix check (most robust fix)

# Python
import os
BASE = '/var/www/files'
safe_path = os.path.realpath(os.path.join(BASE, user_input))
if not safe_path.startswith(BASE + os.sep):
    raise PermissionError("Path escape detected")
with open(safe_path) as f:
    ...
// Node.js
const BASE = path.resolve('/var/www/files');
const resolved = path.resolve(BASE, req.query.file);
if (!resolved.startsWith(BASE + path.sep)) {
    return res.status(403).send('Forbidden');
}
fs.readFile(resolved, ...);
// Java
Path base = Paths.get("/var/www/files").toRealPath();
Path resolved = base.resolve(userInput).normalize();
if (!resolved.startsWith(base)) {
    throw new SecurityException("Path escape");
}
Files.readAllBytes(resolved);

2. basename() / path.basename() to strip directory components

# Python — strips all directory parts, only the filename remains
filename = os.path.basename(user_input)
with open(os.path.join(BASE, filename)) as f:
    ...
// PHP
$filename = basename($_GET['file']);
readfile('/var/www/uploads/' . $filename);

3. Allowlist of permitted filenames or extensions

ALLOWED = {'report.pdf', 'manual.txt', 'logo.png'}
if user_input not in ALLOWED:
    abort(400)
with open(os.path.join(BASE, user_input)) as f:
    ...

4. Framework-provided safe file serving

# Flask — send_from_directory validates the path stays within the directory
return send_from_directory('/var/www/files', filename)

# Django — FileResponse with a path that was never user-controlled

Vulnerable vs. Secure Examples

Python — Flask

# VULNERABLE: user-controlled filename joined without realpath check
@app.route('/download')
def download():
    filename = request.args.get('file')
    filepath = os.path.join('/var/www/files', filename)
    return send_file(filepath)

# SECURE: resolve and verify the path stays within the base directory
@app.route('/download')
def download():
    filename = request.args.get('file')
    base = os.path.realpath('/var/www/files')
    filepath = os.path.realpath(os.path.join(base, filename))
    if not filepath.startswith(base + os.sep):
        abort(403)
    return send_file(filepath)

Python — FastAPI

# VULNERABLE: path parameter used directly in file read
@app.get('/file/{name}')
async def get_file(name: str):
    return FileResponse(f'/app/static/{name}')

# SECURE: basename strips traversal sequences
@app.get('/file/{name}')
async def get_file(name: str):
    safe_name = os.path.basename(name)
    return FileResponse(os.path.join('/app/static', safe_name))

Node.js — Express

// VULNERABLE: req.query.file used directly in readFile
app.get('/file', (req, res) => {
  const filePath = path.join(__dirname, 'uploads', req.query.file);
  fs.readFile(filePath, (err, data) => res.send(data));
});

// SECURE: resolve and check prefix
app.get('/file', (req, res) => {
  const base = path.resolve(__dirname, 'uploads');
  const filePath = path.resolve(base, req.query.file);
  if (!filePath.startsWith(base + path.sep)) {
    return res.status(403).send('Forbidden');
  }
  fs.readFile(filePath, (err, data) => res.send(data));
});

PHP

// VULNERABLE: direct inclusion of user input
<?php
$page = $_GET['page'];
include($page . '.php');

// VULNERABLE: readfile with unsanitized path
$file = $_GET['file'];
readfile('/var/www/uploads/' . $file);

// SECURE: basename strips directory components
$file = basename($_GET['file']);
readfile('/var/www/uploads/' . $file);

// SECURE: realpath + prefix check
$base = realpath('/var/www/uploads');
$path = realpath($base . '/' . $_GET['file']);
if ($path === false || strpos($path, $base . DIRECTORY_SEPARATOR) !== 0) {
    http_response_code(403);
    exit;
}
readfile($path);

Ruby on Rails

# VULNERABLE: params[:file] used directly in file read
def show
  file_path = Rails.root.join('public', 'reports', params[:file])
  send_file file_path
end

# SECURE: basename only
def show
  safe_name = File.basename(params[:file])
  send_file Rails.root.join('public', 'reports', safe_name)
end

Java — Spring

// VULNERABLE: path variable used directly to read file
@GetMapping("/file/{name}")
public ResponseEntity<Resource> getFile(@PathVariable String name) throws IOException {
    Path filePath = Paths.get("/var/www/files").resolve(name);
    Resource resource = new UrlResource(filePath.toUri());
    return ResponseEntity.ok(resource);
}

// SECURE: normalize and check prefix
@GetMapping("/file/{name}")
public ResponseEntity<Resource> getFile(@PathVariable String name) throws IOException {
    Path base = Paths.get("/var/www/files").toRealPath();
    Path resolved = base.resolve(name).normalize();
    if (!resolved.startsWith(base)) {
        return ResponseEntity.status(403).build();
    }
    Resource resource = new UrlResource(resolved.toUri());
    return ResponseEntity.ok(resource);
}

Go

// VULNERABLE: query param joined directly to base directory
func fileHandler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("file")
    http.ServeFile(w, r, filepath.Join("/var/www/files", name))
}

// SECURE: filepath.Clean + prefix check
func fileHandler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("file")
    base := "/var/www/files"
    clean := filepath.Join(base, filepath.Clean("/"+name))
    if !strings.HasPrefix(clean, base+string(os.PathSeparator)) {
        http.Error(w, "Forbidden", http.StatusForbidden)
        return
    }
    http.ServeFile(w, r, clean)
}

Archive Extraction (ZipSlip)

# VULNERABLE: ZipSlip — zip entry names can contain ../
import zipfile
with zipfile.ZipFile(user_zip) as zf:
    zf.extractall('/var/www/uploads')

# SECURE: validate each entry path stays within the target directory
import zipfile, os
base = os.path.realpath('/var/www/uploads')
with zipfile.ZipFile(user_zip) as zf:
    for member in zf.namelist():
        target = os.path.realpath(os.path.join(base, member))
        if not target.startswith(base + os.sep):
            raise ValueError(f"ZipSlip detected: {member}")
    zf.extractall(base)

Execution

This skill runs in three phases using subagents. Pass the contents of sast/architecture.md to all subagents as context.

Phase 1: Find File-Loading Sinks With Dynamic Paths

Launch a subagent with the following instructions:

Goal: Find every location in the codebase where a file is opened, read, served, or extracted using a dynamically constructed path — meaning the path (or a component of it) is stored in a variable rather than being a fully hardcoded string. Write results to sast/pathtraversal-recon.md.

Context: You will be given the project's architecture summary. Use it to understand the tech stack, web framework, file-serving patterns, and any file upload or download features.

What to search for — file-loading sinks with dynamic path components:

Flag any call to a file-reading/serving function where the path argument contains a variable (regardless of where the variable comes from). You are not tracing user input in this phase — that is Phase 2's job. Just find all dynamic file access patterns.

  1. Direct file open / read calls with a variable path:
    • Python: open(var), open(os.path.join(..., var)), pathlib.Path(var).read_text(), pathlib.Path(var).read_bytes()
    • Node.js: fs.readFile(var, ...), fs.readFileSync(var), fs.createReadStream(var)
    • PHP: file_get_contents(var), fopen(var, ...), readfile(var), include(var), require(var), include_once(var), require_once(var)
    • Ruby: File.read(var), File.open(var), IO.read(var), IO.binread(var)
    • Java: new FileInputStream(var), new File(var), Files.readAllBytes(Paths.get(var)), Files.newInputStream(path)
    • Go: os.Open(var), os.ReadFile(var), ioutil.ReadFile(var), os.OpenFile(var, ...)
    • C#: File.ReadAllText(var), File.ReadAllBytes(var), new FileStream(var, ...), System.IO.File.Open(var, ...)
  2. Framework file-serving calls with a variable path:
    • Flask: send_file(var), send_from_directory(base, var)
    • FastAPI / Starlette: FileResponse(var)
    • Django: FileResponse(open(var, 'rb')), StreamingHttpResponse over an opened file
    • Express: res.sendFile(var), res.download(var), express.static with dynamic root
    • S

Truncated for display — read the full file on GitHub.

Related Skills

View on GitHub
GitHub Stars1.3k
CategorySecurity
Updated5mo ago
Forks65

Trust signals

98/100

From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.

1 info