mb-admin/scripts/pma-gateway/create_pma_gateway.sh

87 lines
2.4 KiB
Bash

#!/bin/bash
# ==============================================================================
# Script: create_pma_gateway.sh
# Purpose: Create a time-limited gateway URL for phpMyAdmin on Virtuozzo LLSMP.
# Usage: create_pma_gateway.sh --validity=30 [--slug=myalias]
# Outputs: Prints the generated URL.
# ==============================================================================
set -euo pipefail
SLUG=""
VALIDITY=30 # minutes
for arg in "$@"; do
case $arg in
--slug=*) SLUG="${arg#*=}" ;;
--validity=*) VALIDITY="${arg#*=}" ;;
*) echo "Unknown argument $arg"; exit 1 ;;
esac
done
if [[ -z "$SLUG" ]]; then
SLUG=$(openssl rand -hex 4) # 8-char random
fi
# Determine environment public host (no node prefix)
if [[ -n "${JELASTIC_ENV_DOMAIN:-}" ]]; then
ENV_HOST="$JELASTIC_ENV_DOMAIN"
else
ENV_HOST=$(hostname -f)
ENV_HOST=${ENV_HOST#node*-} # strip nodeXXXX-
fi
PMADB_DIR="/usr/share/phpMyAdmin"
GATEWAY_FILE="$PMADB_DIR/access-db-$SLUG.php"
SECRET_FILE="/var/lib/jelastic/keys/mbadmin_secret"
sudo mkdir -p "$(dirname $SECRET_FILE)"
if [[ ! -f "$SECRET_FILE" ]]; then
sudo sh -c "openssl rand -hex 32 > $SECRET_FILE"
sudo chmod 600 "$SECRET_FILE"
fi
SECRET=$(sudo cat "$SECRET_FILE")
now=$(date +%s)
expires=$((now + VALIDITY*60))
# token = base64("$SLUG:$expires") . '.' . HMAC_SHA256(secret, data)
data="$SLUG:$expires"
base=$(printf "%s" "$data" | base64 -w0)
mac=$(printf "%s" "$data" | openssl dgst -sha256 -hmac "$SECRET" | cut -d' ' -f2)
token="$base.$mac"
sudo tee "$GATEWAY_FILE" >/dev/null <<PHP
<?php
// auto-generated gateway, valid until $expires
ini_set('session.cookie_httponly', 1);
function fail() { header('HTTP/1.1 403 Forbidden'); echo 'Access denied'; exit; }
if (!isset(
_PHPMYADMIN_PMA_GATEWAY_TOKEN')){fail();}
$token =
_PHPMYADMIN_PMA_GATEWAY_TOKEN;
if (!strpos($token,'.')){fail();}
list(
base, $sig) = explode('.', $token, 2);
$data = base64_decode($base, true);
if ($data === false){fail();}
list(
slug, $exp) = explode(':', $data, 2);
if (time()>intval($exp)){fail();}
$secret = trim(file_get_contents('$SECRET_FILE'));
if (hash_equals($sig, hash_hmac('sha256', $data, $secret)) === false){fail();}
// set auth cookie then redirect
setcookie('pma_token', $sig, intval($exp), '/', '', true, true);
header('Location: /');
exit;
?>
PHP
sudo chmod 640 "$GATEWAY_FILE"
URL="https://$ENV_HOST:8443/access-db-$SLUG.php?token=$token"
echo "$URL"