diff --git a/scripts/pma-gateway/create_pma_gateway.sh b/scripts/pma-gateway/create_pma_gateway.sh index 374d9ca..60a52b1 100644 --- a/scripts/pma-gateway/create_pma_gateway.sh +++ b/scripts/pma-gateway/create_pma_gateway.sh @@ -148,31 +148,38 @@ if [ -f "$VHOST_CONFIG" ]; then # If rules are not already in place, add them. if ! sudo grep -qF "$MARKER" "$VHOST_CONFIG"; then - # Remove any existing rewrite block to ensure a clean state. - sudo sed -i '/\s*/,/<\/rewrite>/d' "$VHOST_CONFIG" + # Ensure xmlstarlet is installed, as it's the safest way to edit XML. + if ! command -v xmlstarlet &> /dev/null; then + echo "xmlstarlet not found. Installing for safe XML editing..." >&2 + if ! sudo dnf install -y xmlstarlet; then + echo "FATAL: Failed to install xmlstarlet. Cannot safely modify vhost." >&2 + exit 1 + fi + fi - # Define the new rewrite block using a temporary file to avoid escaping issues. - REWRITE_TMP=$(mktemp) - cat > "$REWRITE_TMP" <<'EOF' - - 1 - 0 - - # PMA Gateway Security Rules - # Allow access to the gateway scripts themselves - RewriteCond %{REQUEST_URI} ^/access-db-.*\.php$ - RewriteRule .* - [L] - # For all other requests, block if the security cookie is not present - RewriteCond %{HTTP_COOKIE} !pma_access_granted - RewriteRule .* - [F,L] - - + # Define the new rules content. Note the lack of indentation. + # xmlstarlet will handle the formatting. + NEW_RULES_CONTENT=$(cat <<'EOF' +# PMA Gateway Security Rules +# Allow access to the gateway scripts themselves +RewriteCond %{REQUEST_URI} ^/access-db-.*\.php$ +RewriteRule .* - [L] +# For all other requests, block if the security cookie is not present +RewriteCond %{HTTP_COOKIE} !pma_access_granted +RewriteRule .* - [F,L] EOF +) - # Use awk to insert the new block before the tag for robustness - sudo awk -v r="$(cat $REWRITE_TMP)" '{if (/\s*/) print r} {print}' "$VHOST_CONFIG" | sudo tee "$VHOST_CONFIG" > /dev/null + # Use xmlstarlet to atomically update the rewrite block in-place. + # This is far safer than sed/awk for structured XML. + if ! sudo xmlstarlet ed -L \ + -u "//virtualHostConfig/rewrite/enable" -v "1" \ + -u "//virtualHostConfig/rewrite/rules" -v "$NEW_RULES_CONTENT" \ + "$VHOST_CONFIG"; then + echo "FATAL: xmlstarlet failed to update $VHOST_CONFIG." >&2 + exit 1 + fi - rm -f "$REWRITE_TMP" NEEDS_RESTART=1 fi else