#!/bin/bash set -e # Variables WEBROOT="/var/www/html/markdown" CGI_DIR="$WEBROOT/cgi-bin" MD_DIR="$WEBROOT/md" APACHE_CONF="/etc/apache2/sites-available/markdown.conf" SCRIPT_NAME="render.py" SCRIPT_PATH="$CGI_DIR/$SCRIPT_NAME" UPLOAD_USER="anon" echo "==> Installing dependencies..." sudo apt update sudo apt install -y apache2 python3 python3-markdown echo "==> Enabling CGI module..." sudo a2enmod cgi echo "==> Creating directory structure..." sudo mkdir -p "$CGI_DIR" sudo mkdir -p "$MD_DIR/docs" echo "==> Writing secure CGI Python script with nested directory support..." sudo tee "$SCRIPT_PATH" > /dev/null << 'EOF' #!/usr/bin/env python3 import cgi import os import markdown import html print("Content-Type: text/html\n") form = cgi.FieldStorage() filename = form.getvalue("file", "index.md") # Reject malicious input if not filename or ".." in filename or filename.startswith("/"): print("Status: 400 Bad Request\n") print("
Invalid filename.
") exit() # Resolve safe absolute path basedir = os.path.abspath("../md") requested_path = os.path.normpath(os.path.join(basedir, filename)) if not requested_path.startswith(basedir): print("Status: 403 Forbidden\n") print("Access denied.
") exit() # Check existence if not os.path.isfile(requested_path): print("Status: 404 Not Found\n") print(f"{html.escape(filename)} not found.
") exit() # Read and convert with open(requested_path, 'r') as f: md_text = f.read() html_content = markdown.markdown(md_text) print(f"""