#!/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" 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("

400 Bad Request

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("

403 Forbidden

Access denied.

") exit() # Check existence if not os.path.isfile(requested_path): print("Status: 404 Not Found\n") print(f"

404 Not Found

{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""" {html.escape(filename)}

{html.escape(filename)}

{html_content} """) EOF echo "==> Making script executable..." sudo chmod +x "$SCRIPT_PATH" echo "==> Creating example markdown files..." sudo tee "$MD_DIR/index.md" > /dev/null << EOF # Welcome This is the **root index** page. EOF sudo tee "$MD_DIR/docs/tutorial.md" > /dev/null << EOF # Tutorial Page This is a **nested Markdown file** inside `docs/`. EOF echo "==> Creating Apache virtual host config..." sudo tee "$APACHE_CONF" > /dev/null << EOF ServerAdmin webmaster@localhost DocumentRoot $WEBROOT Options +ExecCGI AddHandler cgi-script .py Require all granted Alias /markdown/ $WEBROOT/ EOF echo "==> Enabling site and restarting Apache..." sudo a2ensite markdown sudo systemctl reload apache2 echo "" echo "✅ Setup Complete!" echo "Open in your browser:" echo " Root file: http://localhost/cgi-bin/render.py?file=index.md" echo " Nested file: http://localhost/cgi-bin/render.py?file=docs/tutorial.md"