Install in seconds
Install this skill
Copy the command and run it in your terminal. You can review the source before installing.
terminal
git clone https://github.com/utkusen/sast-skills

Works with Git. The repository opens in your current directory.

πŸ›
Quality

Insecure File Upload Detection

by utkusen

Detect insecure file upload vulnerabilities in codebases using a three-phase approach: discovery, batched verification, and merge. Use when auditing code for unrestricted upload, extension bypass, or RCE via file upload.

1.2K stars60 forksAdded 2026/07/20
ai-securityclaudeclaude-codesast

Documentation

README

Insecure File Upload Detection

You are performing a focused security assessment to find insecure file upload vulnerabilities in a codebase. This skill uses a three-phase approach with subagents: discovery (find all places where uploaded files are received and stored), batched verify (check bypass vectors in parallel batches of up to 3 upload sites each), and merge (consolidate batch reports into one results file).

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


What is an Insecure File Upload

Insecure file upload occurs when an application accepts files from users without properly validating or restricting what can be uploaded, allowing an attacker to upload executable or malicious files. The most critical outcome is Remote Code Execution (RCE): an attacker uploads a web shell (e.g., a .php file) and the server executes it when accessed via a direct URL.

The core pattern: a user-supplied file reaches a storage location without adequate extension validation, and the stored file is accessible or executable.

What Insecure File Upload IS

  • Accepting any file type with no extension or content check: file.save(upload_path) with no validation
  • Content-Type-only validation: checking Content-Type: image/png without verifying the actual extension or file content β€” trivially bypassed by setting the header manually
  • Extension blocklist with gaps: .php is blocked but .php3, .php4, .php5, .phtml, .phar, .shtml are not
  • Case-insensitive bypass: blocking .php but allowing .PHP, .Php, .pHp
  • Double extension bypass: shell.php.jpg β€” code extracts the last .jpg and considers it safe, but the server (Apache) serves it as PHP
  • Path traversal in filenames: ../../webroot/shell.php stored via an unsanitized filename
  • Incomplete filename sanitization: only stripping ../ but not encoded variants %2e%2e%2f
  • Serving uploaded files from a web-executable directory without disabling execution

What Insecure File Upload is NOT

Do not flag these as file upload vulnerabilities:

  • Stored XSS via SVG: uploading an SVG with embedded <script> that is reflected back β€” that's XSS, not an upload execution issue
  • SSRF via file content: uploading an XML or SVG that triggers an outbound request β€” that's XXE/SSRF, not a file upload execution issue
  • DoS via large files: missing file size limits β€” a separate availability issue
  • IDOR on download: accessing another user's uploaded file without authorization β€” that's IDOR
  • Secure uploads: files stored outside the web root, or served through a controlled download endpoint that sets Content-Disposition: attachment, or stored in an object storage bucket with no public execution capability

Patterns That Prevent Insecure File Upload

When you see these patterns together, the code is likely not vulnerable:

1. Allowlist of safe extensions (most important)

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf'}
ext = filename.rsplit('.', 1)[-1].lower()
if ext not in ALLOWED_EXTENSIONS:
    abort(400)

2. Magic byte / file content validation (defense in depth)

import magic
mime = magic.from_buffer(file.read(2048), mime=True)
ALLOWED_MIMES = {'image/png', 'image/jpeg', 'image/gif'}
if mime not in ALLOWED_MIMES:
    abort(400)

3. Filename sanitization using a trusted library

from werkzeug.utils import secure_filename
filename = secure_filename(file.filename)  # strips path separators and dangerous chars

4. Storing uploads outside the web root

/var/uploads/  ← not served by the web server
/var/www/html/ ← web root (do NOT store uploads here)

5. Serving uploads through a controlled endpoint with Content-Disposition

@app.route('/download/<filename>')
def download(filename):
    return send_from_directory(UPLOAD_FOLDER, filename,
                               as_attachment=True)  # forces download, prevents execution

6. Renaming the file to a server-generated UUID

import uuid
stored_name = str(uuid.uuid4()) + '.jpg'  # extension is server-controlled, not user-controlled

Vulnerable vs. Secure Examples

Python β€” Flask

# VULNERABLE: no extension check, file stored in web-accessible directory
@app.route('/upload', methods=['POST'])
def upload():
    f = request.files['file']
    f.save(os.path.join('static/uploads', f.filename))
    return 'uploaded'

# VULNERABLE: content-type only check (trivially bypassed with curl -H)
@app.route('/upload', methods=['POST'])
def upload():
    f = request.files['file']
    if f.content_type not in ['image/png', 'image/jpeg']:
        abort(400)
    f.save(os.path.join('static/uploads', f.filename))
    return 'uploaded'

# VULNERABLE: blocklist β€” .phtml/.phar/.php5 not covered
BLOCKED = {'.php', '.sh', '.exe'}
@app.route('/upload', methods=['POST'])
def upload():
    f = request.files['file']
    ext = os.path.splitext(f.filename)[1].lower()
    if ext in BLOCKED:
        abort(400)
    f.save(os.path.join('static/uploads', f.filename))
    return 'uploaded'

# SECURE: allowlist + sanitized filename + outside web root
ALLOWED = {'png', 'jpg', 'jpeg', 'gif'}
UPLOAD_FOLDER = '/var/uploads'  # outside web root

@app.route('/upload', methods=['POST'])
def upload():
    f = request.files['file']
    filename = secure_filename(f.filename)
    ext = filename.rsplit('.', 1)[-1].lower()
    if ext not in ALLOWED:
        abort(400)
    f.save(os.path.join(UPLOAD_FOLDER, filename))
    return 'uploaded'

Python β€” Django

# VULNERABLE: no validation on FileField
class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ['upload']

# VULNERABLE: manual save with no extension check
def upload(request):
    f = request.FILES['file']
    with open(f'media/uploads/{f.name}', 'wb+') as dest:
        for chunk in f.chunks():
            dest.write(chunk)

# SECURE: custom validator on FileField
def validate_file_extension(value):
    ext = os.path.splitext(value.name)[1].lower()
    if ext not in ['.png', '.jpg', '.jpeg', '.gif']:
        raise ValidationError('Unsupported file extension.')

class DocumentForm(forms.ModelForm):
    upload = forms.FileField(validators=[validate_file_extension])

Node.js β€” Multer (Express)

// VULNERABLE: no file filter, stored in public directory
const upload = multer({ dest: 'public/uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
    res.send('uploaded');
});

// VULNERABLE: MIME type filter only (can be faked)
const upload = multer({
    dest: 'uploads/',
    fileFilter: (req, file, cb) => {
        if (!file.mimetype.startsWith('image/')) return cb(null, false);
        cb(null, true);
    }
});

// SECURE: allowlist of extensions + storage outside web root
const ALLOWED_EXT = ['.jpg', '.jpeg', '.png', '.gif'];
const storage = multer.diskStorage({
    destination: '/var/uploads',  // not served by Express
    filename: (req, file, cb) => {
        const ext = path.extname(file.originalname).toLowerCase();
        cb(null, `${uuidv4()}${ext}`);
    }
});
const upload = multer({
    storage,
    fileFilter: (req, file, cb) => {
        const ext = path.extname(file.originalname).toLowerCase();
        cb(null, ALLOWED_EXT.includes(ext));
    }
});

PHP

// VULNERABLE: no extension check, stored in web root
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);

// VULNERABLE: checking only content type header
if ($_FILES['file']['type'] !== 'image/jpeg') {
    die('Invalid file type');
}
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);

// VULNERABLE: blocklist missing phtml/phar
$ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
$blocked = ['php', 'sh', 'py'];
if (in_array($ext, $blocked)) die('Blocked');
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);

// SECURE: allowlist + rename to UUID + outside web root
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) die('Invalid extension');
$stored = '/var/uploads/' . bin2hex(random_bytes(16)) . '.' . $ext;
move_uploaded_file($_FILES['file']['tmp_name'], $stored);

Java β€” Spring Boot (MultipartFile)

// VULNERABLE: no validation, stored in web-accessible path
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
    Path path = Paths.get("src/main/resources/static/uploads/" + file.getOriginalFilename());
    Files.write(path, file.getBytes());
    return "uploaded";
}

// VULNERABLE: content type header only
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
    if (!file.getContentType().startsWith("image/")) throw new BadRequestException();
    Files.write(Paths.get("uploads/" + file.getOriginalFilename()), file.getBytes());
    return "uploaded";
}

// SECURE: allowlist + UUID rename + path outside web root
private static final Set<String> ALLOWED = Set.of("jpg", "jpeg", "png", "gif");

@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
    String original = StringUtils.cleanPath(file.getOriginalFilename());
    String ext = FilenameUtils.getExtension(original).toLowerCase();
    if (!ALLOWED.contains(ext)) throw new BadRequestException("Invalid extension");
    String stored = UUID.randomUUID() + "." + ext;
    Files.write(Paths.get("/var/uploads/" + stored), file.getBytes());
    return "uploaded";
}

Go

// VULNERABLE: no extension check, stored in static directory
func uploadHandler(w http.ResponseWriter, r *http.Request) {
    file, header, _ := r.FormFile("file")
    defer file.Close()
    dst, _ := os.Create("static/uploads/" + header.Filename)
    defer dst.Close()
    io.Copy(dst, file)
}

// SECURE: allowlist extension + UUID rename + outside web root
var allowed = map[string]bool{"jpg": true, "jpeg": true, "png": true, "gif": true}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    file, header, _ := r.FormFile("file")
    defer file.Close()
    ext := strings.ToLower(filepath.Ext(header.Filename))
    if ext == "" || !allowed[ext[1:]] {
        http.Error(w, "invalid extension", http.StatusBadRequest)
        return
    }
    stored := "/var/uploads/" + uuid.New().String() + ext
    dst, _ := os.Create(stored)
    defer dst.Close()
    io.Copy(dst, file)
}

Ruby on Rails

# VULNERABLE: no content type or extension validation
def upload
  file = params[:file]
  File.open(Rails.root.join('public', 'uploads', file.original_filename), 'wb') do |f|
    f.write(file.read)
  end
end

# SECURE: ActiveStorage with content type allowlist (Rails 6+)
has_one_attached :avatar
validates :avatar, content_type: ['image/png', 'image/jpg', 'image/jpeg']
# Note: still validate extension too β€” content_type is user-supplied in some configurations

# SECURE: CarrierWave with extension and content type allowlist
class AvatarUploader < CarrierWave::Uploader::Base
  def extension_allowlist
    %w[jpg jpeg png gif]
  end

  def content_type_allowlist
    /image\//
  end
end

C# β€” ASP.NET Core

// VULNERABLE: no extension check, stored in wwwroot
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file) {
    var path = Path.Combine("wwwroot/uploads", file.FileName);
    using var stream = new FileStream(path, FileMode.Create);
    await file.CopyToAsync(stream);
    return Ok();
}

// SECURE: allowlist + GUID rename + outside web root
private static readonly HashSet<string> _allowed = new() { ".jpg", ".jpeg", ".png", ".gif" };

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file) {
    var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
    if (!_allowed.Contains(ext)) return BadRequest("Invalid extension");
    var stored = Path.Combine("/var/uploads", $"{Guid.NewGuid()}{ext}");
    using var stream = new FileStream(stored, FileMode.Create);
    await file.CopyToAsync(stream);
    return Ok();
}

Execution

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

Phase 1: Find All File Upload Sites

Launch a subagent with the following instructions:

Goal: Find every location in the codebase where files uploaded by users are received and stored. Write results to sast/fileupload-recon.md.

Context: You will be given the project's architecture summary. Use it to understand the framework, file storage patterns, and whether uploads go to local disk, cloud storage, or a CDN.

What to search for β€” file upload handling patterns:

Look for any code that receives a file from an HTTP request and writes or stores it. Do not yet evaluate whether validation is present β€” just find all the sites.

  1. Python / Django:
    • request.FILES access
    • InMemoryUploadedFile, TemporaryUploadedFile
    • default_storage.save(...), FileSystemStorage().save(...)
    • Model FileField / ImageField form submissions
    • shutil.copyfileobj(f, dest) or manual .write(f.read()) on uploaded data
  2. Python / Flask:
    • request.files.get(...) or request.files[...]
    • file.save(...) calls on a FileStorage object
    • werkzeug FileStorage handling
  3. Node.js:
    • multer middleware: upload.single(...), upload.array(...), upload.fields(...)
    • busboy, formidable, multiparty form parsing
    • express-fileupload: req.files
    • fs.writeFile / fs.createWriteStream / pipe() called with a request stream
  4. PHP:
    • $_FILES access
    • move_uploaded_file(...) calls
    • copy($_FILES[...]['tmp_name'], ...)
  5. Java / Spring:
    • MultipartFile parameters in controller methods: @RequestParam MultipartFile
    • CommonsMultipartFile, StandardMultipartFile
    • Part.write(...) (Servlet API)
    • file.transferTo(...), Files.write(path, file.getBytes())
  6. Go:
    • r.FormFile(...) or r.MultipartForm.File
    • io.Copy(dst, file) where file comes from a multipart form
    • os.Create(...) called with a filename derived from header.Filename
  7. Ruby / Rails:
    • params[:file] with .read, .original_filename, .tempfile
    • File.open(..., 'wb') called with uploaded data
    • has_one_attached / has_many_attached (ActiveStorage)
    • CarrierWave mount_uploader, Shrine include Shrine::Attachment
  8. C# / ASP.NET:
    • IFormFile parameters: file.CopyToAsync(...), file.OpenReadStream()
    • HttpPostedFileBase.SaveAs(...)
    • Request.Files[...]

Output format β€” write to sast/fileupload-recon.md:

# File Upload Recon: [Project Name]

## Summary
Found [N] file upload sites.

## Upload Sites

### 1. [Descriptive name β€” e.g., "Avatar upload endpoint"]
- **File**: `path/to/file.ext` (lines X-Y)
- **Endpoint / function**: [route or function name]
- **Framework / method**: [e.g., Flask request.files / multer / move_uploaded_file]
- **Storage destination**: [path, variable, or storage abstraction β€” e.g., "static/uploads/" or "S3 via boto3" or "unknown"]
- **Validation observed** (preliminary, Phase 2 will analyze in depth): [list any extension checks, content-type checks, or "none visible"]
- **Code snippet**:

[the upload receive and save code]


[Repeat for each site]

After Phase 1: Check for Candidates Before Proceeding

After Phase 1 completes, read sast/fileupload-recon.md. If the recon found zero upload sites (the summary reports "Found 0" or the "Upload Sites" section is empty or absent), skip Phase 2 and Phase 3 entirely. Instead, write the following content to sast/fileupload-results.md and stop:

# File Upload Analysis Results

No file upload sites found.

Only proceed to Phase 2 if Phase 1 found at least one upload site.

Phase 2: Check for Extension Bypass Vulnerabilities (Batched)

After Phase 1 completes, read sast/fileupload-recon.md and split the upload sites into batches of up to 3 sites each. Launch one subagent per batch in parallel. Each subagent analyzes only its assigned sites and writes results to its own batch file.

Batching procedure (you, the orchestrator, do this β€” not a subagent):

  1. Read sast/fileupload-recon.md and count the numbered site sections (### 1., ### 2., etc.).
  2. Divide them into batches of up to 3. For example, 8 sites β†’ 3 batches (1-3, 4-6, 7-8).
  3. For each batch, extract the full text of those site sections from the recon file.
  4. Launch all batch subagents in parallel, passing each one only its assigned sites.
  5. Each subagent writes to sast/fileupload-batch-N.md where N is the 1-based batch number.
  6. Identify the project's primary language/framework from sast/architecture.md and select only the matching examples from the "Vulnerable vs. Secure Examples" section above. For example, if the project uses Node.js with Multer, include only the "Node.js β€” Multer (Express)" examples. Include these selected examples in each subagent's instructions where indicated by [TECH-STACK EXAMPLES] below.

Give each batch subagent the following instructions (substitute the batch-specific values):

Goal: For each assigned file upload site below, determine whether an attacker can upload a malicious file (e.g., a PHP web shell, a JSP shell, a Python script) by manipulating the filename, extension, or Content-Type header. Write results to sast/fileupload-batch-[N].md.

Your assigned upload sites (from the recon phase):

[Paste the full text of the assigned site sections here, preserving the original numbering]

Context: You will be given the project's architecture summary. Use it to understand the framework, storage paths, and how uploads are served.

Reference β€” what insecure file upload is and is not:

Focus on execution or dangerous file types reaching storage without adequate controls. Do not flag stored XSS via SVG, SSRF via uploaded XML, DoS via size limits, or IDOR on download as file-upload execution issues (other skills cover those).

Patterns that reduce risk β€” if you see a strong combination (allowlist, sanitization, non-web-root storage, UUID rename), the site is likely Not Vulnerable unless bypass still applies.

Vulnerable vs. Secure examples for this project's tech stack:

[TECH-STACK EXAMPLES]

For each upload site, evaluate the following bypass vectors:

  1. No extension check: No validation of any kind on the filename or extension. Any file is accepted. Immediately flag as Vulnerable.

  2. Content-Type / MIME header only: Validation reads Content-Type or mimetype from the request headers but does not inspect the actual filename extension or file bytes. Attackers can set Content-Type: image/png while uploading shell.php. Flag as Vulnerable.

  3. Blocklist-based validation: An explicit list of forbidden extensions. Check whether the blocklist is exhaustive for the server's technology:

    • PHP servers: Are .php3, .php4, .php5, .php7, .phtml, .phar, .shtml also blocked? If any are missing, flag as Vulnerable.
    • Java servers: Are .jsp, .jspx, .jsw, .jsv, .jspf also blocked?
    • ASP.NET servers: Are .asp, .aspx, .ashx, .asmx, .cer, .asa also blocked?
    • Node.js: Is .js execution possible via the server config? Check if .js files in the upload dir can be required/executed.
    • Any blocklist is inherently

More from utkusen

Other Claude Code skills by this author in the directory.

πŸ”
1w ago

SAST Analysis

Performs reconnaissance and architecture mapping as the first phase of a security assessment. Analyzes tech stack, entry points, data flows, and trust boundaries to prepare for vulnerability detection.
AI Engineering
+1%1.2K60
πŸ”Ž
1w ago

Business Logic Vulnerability Detection

Detects business logic vulnerabilities such as price manipulation, workflow bypass, race conditions, and reward abuse using a three-phase threat modeling approach. Use for security audits requiring logic flaw analysis.
Quality
+1%1.2K60
πŸ”
1w ago

Insecure File Upload Detection

Detects insecure file upload vulnerabilities in a codebase through a three-phase approach: discovery of upload endpoints, batched verification of bypass vectors, and consolidation of findings. Use when auditing for file upload, unrestricted upload, or extension bypass bugs.
Quality
+1%1.2K60
πŸ”
1w ago

GraphQL Injection Detection

Detects GraphQL injection vulnerabilities in codebases through a phased static analysis: recon for unsafe document assembly, batched verification of user-input traces, and merging results. Use when auditing GraphQL APIs for injection risks.
Quality
+1%1.2K60
πŸ”‘
1w ago

Hardcoded Secrets Detection

Detect hardcoded API keys, tokens, passwords, and other sensitive data in publicly accessible code such as frontend JavaScript, mobile apps, and HTML templates. Uses a three-phase approach with batch verification.
Quality
+1%1.2K60
πŸ”Ž
1w ago

IDOR Detection

Detects IDOR vulnerabilities by analyzing endpoints for missing ownership or authorization checks. Uses a three-phase parallel subagent approach for efficient verification. Requires a prior SAST run (sast/architecture.md).
Quality
+1%1.2K60