qwen2.5-coder:14bに指摘され修正

This commit is contained in:
joe 2026-01-22 21:48:10 +09:00
parent 28da4e2709
commit 822f61a966

279
ipf
View file

@ -1,74 +1,115 @@
#!/bin/bash #!/bin/bash
# Name: ipf # Name: ipf
# Version: 1.5.9 # Version: 1.6.1
# Date: 2026-01-22 # Date: 2026-01-22
# Description: Full feature set. Includes conflict prevention, fixed -t parsing, and -f logic. # Description: Fully-featured nftables wrapper.
# Refinement: Incorporated Qwen2.5-Coder's feedback with human-readable robustness.
# Root check # -----------------------------------------------------------------------------
# 1. Root & Environment Check
# -----------------------------------------------------------------------------
if [ "$(id -u)" -ne 0 ]; then if [ "$(id -u)" -ne 0 ]; then
exec sudo "$0" "$@" exec sudo "$0" "$@"
fi fi
# Global Variables # Global Configurations
TABLE_NAME="ipf" TABLE_NAME="ipf"
VERSION="1.5.9" VERSION="1.6.1"
PROTO="tcp" PROTO="tcp"
FORCE_FLAG=false FORCE_FLAG=false
SKIP_TEST=false SKIP_TEST=false
QUIET_MODE=false QUIET_MODE=false
RESET_MODE=false RESET_MODE=false
# --- 1. Core Functions --- # -----------------------------------------------------------------------------
# 2. Messaging & System Functions
# -----------------------------------------------------------------------------
msg() { msg() {
[[ "$QUIET_MODE" == false ]] && echo -e "$@" [[ "$QUIET_MODE" == false ]] && echo -e "$@"
} }
err() {
# Even in quiet mode, critical errors should be visible but without color codes if requested
if [[ "$QUIET_MODE" == false ]]; then
echo -e "\e[31m$@\e[0m" >&2
else
echo "$@" >&2
fi
}
enable_forwarding() { enable_forwarding() {
msg "\e[34m[System]\e[0m Enabling IP forwarding and localnet routing..." msg "\e[34m[System]\e[0m Enabling IP forwarding..."
sysctl -w net.ipv4.ip_forward=1 >/dev/null
# Enable route_localnet for all interfaces to allow forwarding to 127.0.0.1 # Qwen's point: Check sysctl success
if ! sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1; then
err "Critical: Could not enable net.ipv4.ip_forward. Please check your system permissions."
fi
# Enable route_localnet for all interfaces (essential for DNAT to 127.0.0.1)
for dev in /proc/sys/net/ipv4/conf/*/route_localnet; do for dev in /proc/sys/net/ipv4/conf/*/route_localnet; do
echo 1 > "$dev" 2>/dev/null if [[ -f "$dev" ]]; then
echo 1 > "$dev" 2>/dev/null
fi
done done
} }
init_nft() { init_nft() {
# Create table if it doesn't exist
nft add table inet "${TABLE_NAME}" 2>/dev/null nft add table inet "${TABLE_NAME}" 2>/dev/null
nft add chain inet "${TABLE_NAME}" prerouting { type nat hook prerouting priority -100 \; } 2>/dev/null
nft add chain inet "${TABLE_NAME}" output { type nat hook output priority -100 \; } 2>/dev/null # Qwen's point: Reliable chain initialization
nft add chain inet "${TABLE_NAME}" postrouting { type nat hook postrouting priority 100 \; } 2>/dev/null # Prerouting (NAT)
nft add chain inet "${TABLE_NAME}" forward { type filter hook forward priority 0 \; policy accept \; } 2>/dev/null nft add chain inet "${TABLE_NAME}" prerouting "{ type nat hook prerouting priority -100 ; policy accept ; }" 2>/dev/null
# Output (NAT for local traffic)
nft add chain inet "${TABLE_NAME}" output "{ type nat hook output priority -100 ; policy accept ; }" 2>/dev/null
# Postrouting (Masquerade)
nft add chain inet "${TABLE_NAME}" postrouting "{ type nat hook postrouting priority 100 ; policy accept ; }" 2>/dev/null
# Forward (Filter)
nft add chain inet "${TABLE_NAME}" forward "{ type filter hook forward priority 0 ; policy accept ; }" 2>/dev/null
} }
# -----------------------------------------------------------------------------
# 3. Data & Packet Processing
# -----------------------------------------------------------------------------
get_total_packets() { get_total_packets() {
local uuid=$1 local uuid=$1
local total=0 # Optimized: One-pass sum of packets for all rules with this UUID
local counts=$(nft list table inet "${TABLE_NAME}" 2>/dev/null | grep "$uuid" | grep -o 'packets [0-9]*' | awk '{print $2}') # We use awk to ensure we always return a number, even if no rules match.
for c in $counts; do local total=$(nft list table inet "${TABLE_NAME}" 2>/dev/null | grep "$uuid" | grep -o 'packets [0-9]*' | awk '{sum+=$2} END {print sum+0}')
total=$((total + c))
done
echo "$total" echo "$total"
} }
test_connection() { test_connection() {
# Crucial: Argument order for nc (options first, then target) local target_ip=$1
nc -z -w 1 "$1" "$2" >/dev/null 2>&1 local target_port=$2
# Ensure standard NC argument order: [options] [host] [port]
nc -z -w 1 "$target_ip" "$target_port" >/dev/null 2>&1
return $? return $?
} }
# -----------------------------------------------------------------------------
# 4. Rule Management Functions
# -----------------------------------------------------------------------------
delete_by_handle() { delete_by_handle() {
local h=$1 local h=$1
# Find UUID associated with this handle local uuid=""
local uuid=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "handle $h" | grep -o 'ipf-id:[a-z0-9-]*')
# Qwen's point: Search UUID across ALL chains, not just prerouting
local search_chains=("prerouting" "output" "forward" "postrouting")
for sc in "${search_chains[@]}"; do
uuid=$(nft -a list chain inet "${TABLE_NAME}" "$sc" 2>/dev/null | grep "handle $h" | grep -o 'ipf-id:[a-z0-9-]*' | head -n 1)
[[ -n "$uuid" ]] && break
done
if [[ -z "$uuid" ]]; then if [[ -z "$uuid" ]]; then
return 1 return 1
fi fi
# Delete rules in all chains that share this UUID # Delete all rules associated with this UUID in all relevant chains
local chains=("prerouting" "output" "forward" "postrouting") for c in "${search_chains[@]}"; do
for c in "${chains[@]}"; do
nft -a list chain inet "${TABLE_NAME}" "$c" 2>/dev/null | grep "$uuid" | grep -o 'handle [0-9]*' | awk '{print $2}' | while read -r rh; do nft -a list chain inet "${TABLE_NAME}" "$c" 2>/dev/null | grep "$uuid" | grep -o 'handle [0-9]*' | awk '{print $2}' | while read -r rh; do
nft delete rule inet "${TABLE_NAME}" "$c" handle "$rh" nft delete rule inet "${TABLE_NAME}" "$c" handle "$rh"
done done
@ -81,7 +122,7 @@ test_strict_handle() {
local info=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "handle $h") local info=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "handle $h")
if [[ -z "$info" ]]; then if [[ -z "$info" ]]; then
echo -e "Handle $h \e[31mNOT FOUND\e[0m" err "Handle $h not found in table '${TABLE_NAME}'"
return return
fi fi
@ -96,17 +137,17 @@ test_strict_handle() {
local count_before=$(get_total_packets "$uuid") local count_before=$(get_total_packets "$uuid")
if test_connection "$tip" "$tp"; then if test_connection "$tip" "$tp"; then
# Actual trigger test via localhost # Try to trigger the rule via localhost
nc -z -w 1 127.0.0.1 "$lp" >/dev/null 2>&1 nc -z -w 1 127.0.0.1 "$lp" >/dev/null 2>&1
sleep 0.1 sleep 0.1
local count_after=$(get_total_packets "$uuid") local count_after=$(get_total_packets "$uuid")
if (( count_after > count_before )); then if (( count_after > count_before )); then
echo -e "\e[32mPASSED\e[0m" echo -e "\e[32mPASSED\e[0m"
else else
echo -e "\e[33mSKIPPED (Check other rules)\e[0m" echo -e "\e[33mSKIPPED (Traffic not hitting rule)\e[0m"
fi fi
else else
echo -e "\e[31mOFFLINE (Target Down)\e[0m" echo -e "\e[31mOFFLINE (Target Unreachable)\e[0m"
fi fi
} }
@ -114,7 +155,8 @@ list_rules() {
[[ "$QUIET_MODE" == true ]] && return [[ "$QUIET_MODE" == true ]] && return
local highlight_uuid=$1 local highlight_uuid=$1
init_nft init_nft
msg "Forwarding Rules (ipf):"
msg "Forwarding Rules (Table: ${TABLE_NAME}):"
printf "%-10s %-6s %-20s %-20s %-10s\n" "HANDLE" "PROTO" "LOCAL" "TARGET" "UUID" printf "%-10s %-6s %-20s %-20s %-10s\n" "HANDLE" "PROTO" "LOCAL" "TARGET" "UUID"
echo "-----------------------------------------------------------------------------------" echo "-----------------------------------------------------------------------------------"
@ -138,7 +180,7 @@ add_rule() {
init_nft init_nft
[[ "$FORCE_FLAG" == true ]] && enable_forwarding [[ "$FORCE_FLAG" == true ]] && enable_forwarding
# Parsing # Syntax Parsing (LPORT:TIP:TPORT / LPORT:TPORT / LPORT)
if [[ "$raw" =~ ^([0-9]+):([0-9\.]+):([0-9]+)$ ]]; then if [[ "$raw" =~ ^([0-9]+):([0-9\.]+):([0-9]+)$ ]]; then
lp=${BASH_REMATCH[1]}; tip=${BASH_REMATCH[2]}; tp=${BASH_REMATCH[3]} lp=${BASH_REMATCH[1]}; tip=${BASH_REMATCH[2]}; tp=${BASH_REMATCH[3]}
elif [[ "$raw" =~ ^([0-9]+):([0-9]+)$ ]]; then elif [[ "$raw" =~ ^([0-9]+):([0-9]+)$ ]]; then
@ -146,73 +188,64 @@ add_rule() {
elif [[ "$raw" =~ ^([0-9]+)$ ]]; then elif [[ "$raw" =~ ^([0-9]+)$ ]]; then
lp=${BASH_REMATCH[1]}; tip="127.0.0.1"; tp=${BASH_REMATCH[1]} lp=${BASH_REMATCH[1]}; tip="127.0.0.1"; tp=${BASH_REMATCH[1]}
else else
msg "\e[31mError: Invalid rule format '$raw'\e[0m" err "Error: Invalid rule format '$raw'"
return 1 return 1
fi fi
# --- Conflict Management --- # --- Conflict Management ---
# Delete any existing rules using the same local port to prevent shadowing # Find and overwrite existing rules for the same local port
local existing_h=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "dport $lp" | grep -o 'handle [0-9]*' | awk '{print $2}') local existing_rules=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "dport $lp" | grep -o 'handle [0-9]*' | awk '{print $2}')
for eh in $existing_h; do for eh in $existing_rules; do
msg "\e[33mOverwriting existing rule on port :$lp (Handle $eh)...\e[0m"
delete_by_handle "$eh" delete_by_handle "$eh"
done done
# UUID Generation # Generate Unique ID for the rule set
local u_raw=$(cat /proc/sys/kernel/random/uuid) local u_raw=$(cat /proc/sys/kernel/random/uuid)
local u="ipf-id:$u_raw" local u="ipf-id:$u_raw"
local fam="ip" local fam="ip"
[[ "$tip" =~ : ]] && fam="ip6" [[ "$tip" =~ : ]] && fam="ip6"
# Rule Insertion (using insert to stay at the top) # 1. PREROUTING: Redirect incoming external packets
nft insert rule inet "${TABLE_NAME}" prerouting "$PROTO" dport "$lp" counter dnat $fam to "$tip:$tp" comment "\"$u\"" nft insert rule inet "${TABLE_NAME}" prerouting "$PROTO" dport "$lp" counter dnat $fam to "$tip:$tp" comment "\"$u\""
# 2. OUTPUT: Redirect locally generated packets
nft insert rule inet "${TABLE_NAME}" output "$PROTO" dport "$lp" counter dnat $fam to "$tip:$tp" comment "\"$u\"" nft insert rule inet "${TABLE_NAME}" output "$PROTO" dport "$lp" counter dnat $fam to "$tip:$tp" comment "\"$u\""
# 3. FORWARD: Allow traffic to the target
nft insert rule inet "${TABLE_NAME}" forward $fam daddr "$tip" "$PROTO" dport "$tp" ct state new,established,related accept comment "\"$u\"" nft insert rule inet "${TABLE_NAME}" forward $fam daddr "$tip" "$PROTO" dport "$tp" ct state new,established,related accept comment "\"$u\""
# 4. FORWARD: Allow return traffic from the target
nft insert rule inet "${TABLE_NAME}" forward $fam saddr "$tip" "$PROTO" sport "$tp" ct state established,related accept comment "\"$u\"" nft insert rule inet "${TABLE_NAME}" forward $fam saddr "$tip" "$PROTO" sport "$tp" ct state established,related accept comment "\"$u\""
# 5. FORWARD: Loopback interface allowance
nft insert rule inet "${TABLE_NAME}" forward iifname "lo" accept comment "\"$u\"" nft insert rule inet "${TABLE_NAME}" forward iifname "lo" accept comment "\"$u\""
# 6. POSTROUTING: Source NAT to ensure target sees local IP
nft insert rule inet "${TABLE_NAME}" postrouting $fam daddr "$tip" "$PROTO" dport "$tp" masquerade comment "\"$u\"" nft insert rule inet "${TABLE_NAME}" postrouting $fam daddr "$tip" "$PROTO" dport "$tp" masquerade comment "\"$u\""
list_rules "$u_raw" list_rules "$u_raw"
# Auto-test unless forced
if [[ "$SKIP_TEST" == false && "$FORCE_FLAG" == false ]]; then if [[ "$SKIP_TEST" == false && "$FORCE_FLAG" == false ]]; then
local new_h=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "$u_raw" | grep -o 'handle [0-9]*' | awk '{print $2}') local nh=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "$u_raw" | grep -o 'handle [0-9]*' | awk '{print $2}')
echo "" echo ""
test_strict_handle "$new_h" test_strict_handle "$nh"
fi fi
} }
all_clear() { all_clear() {
if [[ "$FORCE_FLAG" == false ]]; then if [[ "$FORCE_FLAG" == false ]]; then
echo -e "\e[33mWarning: This will delete ALL ipf rules.\e[0m" echo -e "\e[33mWarning: This will delete ALL rules in table '${TABLE_NAME}'.\e[0m"
read -p "Are you sure? (y/N): " confirm read -p "Confirm removal? (y/N): " confirm
[[ ! "$confirm" =~ ^[yY]$ ]] && exit 0 [[ ! "$confirm" =~ ^[yY]$ ]] && exit 0
fi fi
nft delete table inet "${TABLE_NAME}" 2>/dev/null nft delete table inet "${TABLE_NAME}" 2>/dev/null
init_nft init_nft
msg "All ipf rules cleared." msg "Table '${TABLE_NAME}' has been reset."
list_rules list_rules
exit 0 exit 0
} }
show_help() { # -----------------------------------------------------------------------------
echo "ipf version ${VERSION}" # 5. Argument Parsing (Main Loop)
echo "Usage: ipf [OPTIONS] [RULE]" # -----------------------------------------------------------------------------
echo ""
echo "Options:"
echo " -f Kernel: Enable forwarding & route_localnet"
echo " Global: Acts as 'Force' (Skips confirmation & tests)"
echo " -l, -L List all forwarding rules"
echo " -d HANDLE/:PORT/all Delete rule (Add -f to skip confirmation)"
echo " -R Reset: Clear ALL rules (Add -f to skip confirmation)"
echo " -t [TARGET] Test connectivity (Handle, :Port, or IP:Port)"
echo " -y Same as -f (Force/Yes)"
echo " -q Quiet mode (implies -f)"
echo " -v, --version Show version"
echo " -h, --help Show this help message"
}
# --- 2. Flag Pre-processing ---
# Pre-parse flags for Global behavior
for arg in "$@"; do for arg in "$@"; do
if [[ "$arg" =~ q ]]; then QUIET_MODE=true; FORCE_FLAG=true; SKIP_TEST=true; fi if [[ "$arg" =~ q ]]; then QUIET_MODE=true; FORCE_FLAG=true; SKIP_TEST=true; fi
if [[ "$arg" =~ f ]]; then FORCE_FLAG=true; SKIP_TEST=true; fi if [[ "$arg" =~ f ]]; then FORCE_FLAG=true; SKIP_TEST=true; fi
@ -223,98 +256,70 @@ done
if [[ "$RESET_MODE" == true ]]; then all_clear; fi if [[ "$RESET_MODE" == true ]]; then all_clear; fi
if [[ $# -eq 0 ]]; then list_rules; exit 0; fi if [[ $# -eq 0 ]]; then list_rules; exit 0; fi
# --- 3. Main Loop ---
while [[ $# -gt 0 ]]; do while [[ $# -gt 0 ]]; do
case "$1" in case "$1" in
-h|--help) show_help; exit 0 ;; -h|--help)
-l|-L) list_rules; exit 0 ;; echo "ipf version ${VERSION}"
-v|--version) echo "ipf version ${VERSION}"; exit 0 ;; echo "Usage: ipf [OPTIONS] [RULE]"
echo "Example: ipf 80:192.168.1.10:8080"
exit 0 ;;
-v|--version)
echo "ipf version ${VERSION}"; exit 0 ;;
-l|-L)
list_rules; exit 0 ;;
-f|-y|-q) -f|-y|-q)
[[ "$1" == "-f" ]] && enable_forwarding [[ "$1" == "-f" ]] && enable_forwarding
shift shift; [[ $# -eq 0 ]] && exit 0; continue ;;
[[ $# -eq 0 ]] && exit 0
continue
;;
-*[d]*) -*[d]*)
# Handle combined flags like -fd or -qd # Support combined flags and comma-separated handles
h_str=$(echo "$1" | sed -E 's/^-q?d?f?y?//') target="${1#-d}"
if [[ -z "$h_str" ]]; then [[ -z "$target" ]] && { target="$2"; shift; }
h_str="$2" [[ "$target" == "all" ]] && all_clear
shift
fi
if [[ "$h_str" == "all" || "$h_str" == "*" ]]; then IFS=',' read -r -a parts <<< "$target"
all_clear for p in "${parts[@]}"; do
fi if [[ "$p" =~ ^:([0-9]+)$ ]]; then
# Delete by local port
# Collect handles to delete port="${BASH_REMATCH[1]}"
handles=() for h in $(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "dport $port" | grep -o 'handle [0-9]*' | awk '{print $2}'); do
IFS=',' read -r -a parts <<< "$h_str" delete_by_handle "$h"
for part in "${parts[@]}"; do
if [[ "$part" =~ ^:([0-9]+)$ ]]; then
p="${BASH_REMATCH[1]}"
# Find all handles for this local port
for h in $(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "dport $p" | grep -o 'handle [0-9]*' | awk '{print $2}'); do
handles+=("$h")
done done
else else
handles+=("$part") # Delete by handle
if ! delete_by_handle "$p"; then
err "Error: Handle $p not found."
fi
fi fi
done done
list_rules; exit 0 ;;
for h in "${handles[@]}"; do
if delete_by_handle "$h"; then
msg "Deleted handle $h"
else
msg "\e[31mError: Handle $h not found\e[0m"
fi
done
list_rules
exit 0
;;
-t*) -t*)
h_str="${1#-t}" # Support combined or separated test target
if [[ -z "$h_str" ]]; then target="${1#-t}"
h_str="$2" [[ -z "$target" ]] && { target="$2"; shift; }
shift
fi
# Pattern matching for different test types if [[ "$target" =~ ^([0-9\.]+):([0-9]+)$ ]]; then
if [[ "$h_str" =~ ^([0-9\.]+):([0-9]+)$ ]]; then # External Target IP:PORT test
# IP:PORT test ip=${BASH_REMATCH[1]}; port=${BASH_REMATCH[2]}
tip=${BASH_REMATCH[1]}; tp=${BASH_REMATCH[2]} echo -n "Checking Target $ip:$port... "
echo -n "Checking Target $tip:$tp... " test_connection "$ip" "$port" && echo -e "\e[32mUP\e[0m" || echo -e "\e[31mDOWN\e[0m"
test_connection "$tip" "$tp" && echo -e "\e[32mUP\e[0m" || echo -e "\e[31mDOWN\e[0m" elif [[ "$target" =~ ^:([0-9]+)$ ]]; then
elif [[ "$h_str" =~ ^:([0-9]+)$ ]]; then # Local port test
# :PORT test (local) port="${BASH_REMATCH[1]}"
p="${BASH_REMATCH[1]}" echo -n "Checking Local :$port... "
echo -n "Checking Local :$p... " nc -z -w 1 127.0.0.1 "$port" >/dev/null 2>&1 && echo -e "\e[32mOK\e[0m" || echo -e "\e[31mOFFLINE\e[0m"
nc -z -w 1 127.0.0.1 "$p" >/dev/null 2>&1 && echo -e "\e[32mOK\e[0m" || echo -e "\e[31mOFFLINE\e[0m" elif [[ "$target" =~ ^[0-9]+$ ]]; then
elif [[ "$h_str" =~ ^[0-9]+$ ]]; then # Internal rule test by handle
# Handle test test_strict_handle "$target"
test_strict_handle "$h_str"
else else
# Default: test the first rule found # Default to testing first available rule
top_h=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "dnat" | head -n 1 | grep -o 'handle [0-9]*' | awk '{print $2}') top_h=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "dnat" | head -n 1 | grep -o 'handle [0-9]*' | awk '{print $2}')
if [[ -n "$top_h" ]]; then [[ -n "$top_h" ]] && test_strict_handle "$top_h" || err "Error: No valid target to test."
test_strict_handle "$top_h"
else
msg "\e[31mError: No valid test target found for '$h_str'\e[0m"
fi
fi fi
exit 0 exit 0 ;;
;;
[0-9]*) [0-9]*)
# Positional argument as a rule add_rule "$1"; exit 0 ;;
add_rule "$1"
exit 0
;;
*) *)
msg "\e[31mError: Unknown option '$1'\e[0m" err "Unknown option '$1'. Use --help for usage."; exit 1 ;;
show_help
exit 1
;;
esac esac
shift shift
done done