HIGH zip slipflaskbasic auth

Zip Slip in Flask with Basic Auth

Zip Slip in Flask with Basic Auth — how this specific combination creates or exposes the vulnerability

Zip Slip is a path traversal vulnerability that occurs when an application constructs file paths from user-supplied input without proper validation. In Flask, this typically arises when extracting files from archives (for example, a ZIP) and using the provided filename directly to build the destination path. When Basic Auth protects the endpoint, developers may assume authentication alone limits who can trigger file extraction, but the authentication layer only verifies identity—it does not sanitize or restrict the content of user-supplied data. An authenticated user can still supply malicious archive contents with crafted filenames such as ../../etc/passwd or absolute paths, causing the server to write files outside the intended directory. Because the scan tests unauthenticated attack surfaces, middleBrick can still detect path traversal indicators in endpoints that accept file uploads or archive extraction, even when Basic Auth is present. The presence of authentication may reduce opportunistic exploitation but does not eliminate the risk; the vulnerability resides in the path-handling logic, not the auth mechanism. Real-world attack patterns include using crafted ZIP archives with deeply nested or specially named entries to traverse directories, potentially leading to unauthorized file reads or writes. This combination illustrates that authentication and input validation are independent controls; failing to validate paths means the endpoint remains exploitable regardless of the auth method.

Basic Auth-Specific Remediation in Flask — concrete code fixes

To remediate Zip Slip in Flask while using Basic Auth, you must validate and sanitize file paths independently of authentication. Always resolve extracted paths against a configured base directory and ensure the result remains within that directory. The following example shows a Flask route with HTTP Basic Auth that safely extracts a ZIP file using zipfile and pathlib:

import zipfile
from pathlib import Path
from flask import Flask, request, abort
from werkzeug.security import check_password_hash

app = Flask(__name__)

# Simple user store (in production, use a secure backend)
USERS = {"admin": "pbkdf2:sha256:260000$..."}  # pre-hashed password

def verify_auth(username, password):
    if username not in USERS:
        return False
    return check_password_hash(USERS[username], password)

@app.route('/upload', methods=['POST'])
def upload_archive():
    auth = request.authorization
    if not auth or not verify_auth(auth.username, auth.password):
        abort(401, description='Authentication required')

    if 'file' not in request.files:
        abort(400, description='No file provided')

    file = request.files['file']
    if file.filename == '':
        abort(400, description='Empty filename')

    base = Path(app.config.get('EXTRACT_DIR', '/safe/extraction/dir')).resolve()
    try:
        with zipfile.ZipFile(file.stream) as z:
            for member in z.infolist():
                member_path = Path(member.filename).resolve()
                # Ensure the resolved path stays within base
                if not member_path.is_relative_to(base):
                    abort(400, description='Invalid file path in archive')
                z.extract(member, path=base)
    except zipfile.BadZipFile:
        abort(400, description='Invalid ZIP file')
    return 'Extraction successful', 200

if __name__ == '__main__':
    app.run()

Key remediation steps include:

  • Use pathlib.Path and resolve() to eliminate .. and symlink components.
  • Check that each extracted path is relative to a defined base directory using is_relative_to (or manual prefix checks on older Python versions).
  • Avoid concatenating user input directly into paths; prefer joining with Path objects.
  • Limit extraction behavior to trusted archives; consider using extractall with strict path checks rather than iterating when possible.

middleBrick can detect indicators of path traversal in endpoints that handle file extraction, even when Basic Auth is in use. By scanning with authenticated scenarios (via manual credentials) and unauthenticated probes, the tool surfaces risky patterns in path handling and provides prioritized findings with remediation guidance mapped to frameworks such as OWASP API Top 10.

Frequently Asked Questions

Does Basic Auth prevent Zip Slip if usernames and passwords are protected?
No. Basic Auth only verifies identity; it does not validate or sanitize file paths. Zip Slip depends on how the server constructs filesystem paths from archive entries, so authentication does not mitigate traversal.
How can middleBrick help detect Zip Slip in Flask APIs protected by Basic Auth?
middleBrick tests the unauthenticated attack surface by default, but you can provide credentials to include authenticated scans. It analyzes request handling and response patterns to identify path traversal indicators, regardless of whether Basic Auth is used, and reports findings with remediation guidance.