Skip to content
Snippets Groups Projects
Commit e62b1da0 authored by Recolic's avatar Recolic :house_with_garden:
Browse files

.

parent 3c5392ca
No related branches found
No related tags found
No related merge requests found
......@@ -9,8 +9,14 @@
#
# GPT-4o
# GPT-4o v2, allows multiple replacement
#!/bin/bash
set -euo pipefail
HOST="$1"
REMOTE_FILE="$2"
SAFE_CMD_REGEX1='^genpasswd[A-Za-z0-9_@\. -]*$'
SAFE_CMD_REGEX2='^rsec[A-Za-z0-9_@ -]*$'
if [[ -z "$HOST" || -z "$REMOTE_FILE" ]]; then
echo "Usage: $0 <host> <remote_file>"
......@@ -18,26 +24,42 @@ if [[ -z "$HOST" || -z "$REMOTE_FILE" ]]; then
exit 1
fi
# Step 1: fetch file content
# Create temp file for caching and cleanup later
tmp_file=$(mktemp)
trap 'rm -f "$tmp_file"' EXIT
# Step 1: SSH to remote and fetch file
if [ "$HOST" = "." ]; then
CONTENT=$(cat "$REMOTE_FILE") || exit 1
cp "$REMOTE_FILE" "$tmp_file"
else
CONTENT=$(ssh "$HOST" cat "$REMOTE_FILE") || exit 1
scp "$HOST:$REMOTE_FILE" "$tmp_file" > /dev/null
fi
# Step 2: find the placeholder
PLACEHOLDER_LINE=$(echo "$CONTENT" | grep -m1 '__RSEC_PLACEHOLDER(') || exit 0
CMD=$(echo "$PLACEHOLDER_LINE" | sed -n 's/.*__RSEC_PLACEHOLDER(\(.*\)).*/\1/p') || exit 0
# Step 2: Replace all __RSEC_PLACEHOLDER(...) instances
# Extract all unique placeholders
placeholders=$(grep -oP '__RSEC_PLACEHOLDER\(\K[^)]+' "$tmp_file" | sort -u)
# Step 3: validate command
SAFE_CMD_REGEX1='^genpasswd[A-Za-z0-9_@\. -]*$'
SAFE_CMD_REGEX2='^rsec[A-Za-z0-9_@ -]*$'
if [[ "$CMD" =~ $SAFE_CMD_REGEX1 ]] || [[ "$CMD" =~ $SAFE_CMD_REGEX2 ]]; then
OUTPUT=$(bash -c "$CMD" 2>/dev/null) || exit $?
ssh "$HOST" sed -i "'s|__RSEC_PLACEHOLDER([^)]*)|$OUTPUT|g'" "$REMOTE_FILE"
# Step 2: Replace all __RSEC_PLACEHOLDER(...) instances
grep -oP '__RSEC_PLACEHOLDER\(\K[^)]+' "$tmp_file" | sort -u | while read -r CMD; do
echo "rsec_populate: EXEC $CMD"
if [[ "$CMD" =~ $SAFE_CMD_REGEX1 ]] || [[ "$CMD" =~ $SAFE_CMD_REGEX2 ]]; then
output=$(bash -c "$CMD")
else
echo "Rejected unsafe command: $CMD"
exit 1
fi
# Escape output for sed
safe_output=$(printf '%s\n' "$output" | sed -e 's/[\/&]/\\&/g')
sed -i "s|__RSEC_PLACEHOLDER(${CMD})|$safe_output|g" "$tmp_file"
done
# Step 3: Upload back to remote
if [ "$HOST" = "." ]; then
cp "$tmp_file" "$REMOTE_FILE"
else
echo "Rejected to execute unsafe command '$CMD'"
exit 1
scp "$tmp_file" "$HOST:$REMOTE_FILE" > /dev/null
fi
# Step 4: Cleanup handled by trap
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment