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

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

281
ipf
View file

@ -1,74 +1,115 @@
#!/bin/bash
# Name: ipf
# Version: 1.5.9
# Version: 1.6.1
# 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
exec sudo "$0" "$@"
fi
# Global Variables
# Global Configurations
TABLE_NAME="ipf"
VERSION="1.5.9"
VERSION="1.6.1"
PROTO="tcp"
FORCE_FLAG=false
SKIP_TEST=false
QUIET_MODE=false
RESET_MODE=false
# --- 1. Core Functions ---
# -----------------------------------------------------------------------------
# 2. Messaging & System Functions
# -----------------------------------------------------------------------------
msg() {
[[ "$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() {
msg "\e[34m[System]\e[0m Enabling IP forwarding and localnet routing..."
sysctl -w net.ipv4.ip_forward=1 >/dev/null
# Enable route_localnet for all interfaces to allow forwarding to 127.0.0.1
msg "\e[34m[System]\e[0m Enabling IP forwarding..."
# 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
echo 1 > "$dev" 2>/dev/null
if [[ -f "$dev" ]]; then
echo 1 > "$dev" 2>/dev/null
fi
done
}
init_nft() {
# Create table if it doesn't exist
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
nft add chain inet "${TABLE_NAME}" postrouting { type nat hook postrouting priority 100 \; } 2>/dev/null
nft add chain inet "${TABLE_NAME}" forward { type filter hook forward priority 0 \; policy accept \; } 2>/dev/null
# Qwen's point: Reliable chain initialization
# Prerouting (NAT)
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() {
local uuid=$1
local total=0
local counts=$(nft list table inet "${TABLE_NAME}" 2>/dev/null | grep "$uuid" | grep -o 'packets [0-9]*' | awk '{print $2}')
for c in $counts; do
total=$((total + c))
done
# Optimized: One-pass sum of packets for all rules with this UUID
# We use awk to ensure we always return a number, even if no rules match.
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}')
echo "$total"
}
test_connection() {
# Crucial: Argument order for nc (options first, then target)
nc -z -w 1 "$1" "$2" >/dev/null 2>&1
local target_ip=$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 $?
}
# -----------------------------------------------------------------------------
# 4. Rule Management Functions
# -----------------------------------------------------------------------------
delete_by_handle() {
local h=$1
# Find UUID associated with this handle
local uuid=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "handle $h" | grep -o 'ipf-id:[a-z0-9-]*')
local uuid=""
# 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
return 1
fi
# Delete rules in all chains that share this UUID
local chains=("prerouting" "output" "forward" "postrouting")
for c in "${chains[@]}"; do
# Delete all rules associated with this UUID in all relevant chains
for c in "${search_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 delete rule inet "${TABLE_NAME}" "$c" handle "$rh"
done
@ -81,7 +122,7 @@ test_strict_handle() {
local info=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "handle $h")
if [[ -z "$info" ]]; then
echo -e "Handle $h \e[31mNOT FOUND\e[0m"
err "Handle $h not found in table '${TABLE_NAME}'"
return
fi
@ -96,17 +137,17 @@ test_strict_handle() {
local count_before=$(get_total_packets "$uuid")
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
sleep 0.1
local count_after=$(get_total_packets "$uuid")
if (( count_after > count_before )); then
echo -e "\e[32mPASSED\e[0m"
else
echo -e "\e[33mSKIPPED (Check other rules)\e[0m"
echo -e "\e[33mSKIPPED (Traffic not hitting rule)\e[0m"
fi
else
echo -e "\e[31mOFFLINE (Target Down)\e[0m"
echo -e "\e[31mOFFLINE (Target Unreachable)\e[0m"
fi
}
@ -114,7 +155,8 @@ list_rules() {
[[ "$QUIET_MODE" == true ]] && return
local highlight_uuid=$1
init_nft
msg "Forwarding Rules (ipf):"
msg "Forwarding Rules (Table: ${TABLE_NAME}):"
printf "%-10s %-6s %-20s %-20s %-10s\n" "HANDLE" "PROTO" "LOCAL" "TARGET" "UUID"
echo "-----------------------------------------------------------------------------------"
@ -138,7 +180,7 @@ add_rule() {
init_nft
[[ "$FORCE_FLAG" == true ]] && enable_forwarding
# Parsing
# Syntax Parsing (LPORT:TIP:TPORT / LPORT:TPORT / LPORT)
if [[ "$raw" =~ ^([0-9]+):([0-9\.]+):([0-9]+)$ ]]; then
lp=${BASH_REMATCH[1]}; tip=${BASH_REMATCH[2]}; tp=${BASH_REMATCH[3]}
elif [[ "$raw" =~ ^([0-9]+):([0-9]+)$ ]]; then
@ -146,73 +188,64 @@ add_rule() {
elif [[ "$raw" =~ ^([0-9]+)$ ]]; then
lp=${BASH_REMATCH[1]}; tip="127.0.0.1"; tp=${BASH_REMATCH[1]}
else
msg "\e[31mError: Invalid rule format '$raw'\e[0m"
err "Error: Invalid rule format '$raw'"
return 1
fi
# --- Conflict Management ---
# Delete any existing rules using the same local port to prevent shadowing
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}')
for eh in $existing_h; do
# Find and overwrite existing rules for the same local port
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_rules; do
msg "\e[33mOverwriting existing rule on port :$lp (Handle $eh)...\e[0m"
delete_by_handle "$eh"
done
# UUID Generation
# Generate Unique ID for the rule set
local u_raw=$(cat /proc/sys/kernel/random/uuid)
local u="ipf-id:$u_raw"
local fam="ip"
[[ "$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\""
# 2. OUTPUT: Redirect locally generated packets
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\""
# 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\""
# 5. FORWARD: Loopback interface allowance
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\""
list_rules "$u_raw"
# Auto-test unless forced
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 ""
test_strict_handle "$new_h"
test_strict_handle "$nh"
fi
}
all_clear() {
if [[ "$FORCE_FLAG" == false ]]; then
echo -e "\e[33mWarning: This will delete ALL ipf rules.\e[0m"
read -p "Are you sure? (y/N): " confirm
echo -e "\e[33mWarning: This will delete ALL rules in table '${TABLE_NAME}'.\e[0m"
read -p "Confirm removal? (y/N): " confirm
[[ ! "$confirm" =~ ^[yY]$ ]] && exit 0
fi
nft delete table inet "${TABLE_NAME}" 2>/dev/null
init_nft
msg "All ipf rules cleared."
msg "Table '${TABLE_NAME}' has been reset."
list_rules
exit 0
}
show_help() {
echo "ipf version ${VERSION}"
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 ---
# -----------------------------------------------------------------------------
# 5. Argument Parsing (Main Loop)
# -----------------------------------------------------------------------------
# Pre-parse flags for Global behavior
for arg in "$@"; do
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
@ -223,98 +256,70 @@ done
if [[ "$RESET_MODE" == true ]]; then all_clear; fi
if [[ $# -eq 0 ]]; then list_rules; exit 0; fi
# --- 3. Main Loop ---
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help) show_help; exit 0 ;;
-l|-L) list_rules; exit 0 ;;
-v|--version) echo "ipf version ${VERSION}"; exit 0 ;;
-f|-y|-q)
-h|--help)
echo "ipf version ${VERSION}"
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)
[[ "$1" == "-f" ]] && enable_forwarding
shift
[[ $# -eq 0 ]] && exit 0
continue
;;
shift; [[ $# -eq 0 ]] && exit 0; continue ;;
-*[d]*)
# Handle combined flags like -fd or -qd
h_str=$(echo "$1" | sed -E 's/^-q?d?f?y?//')
if [[ -z "$h_str" ]]; then
h_str="$2"
shift
fi
# Support combined flags and comma-separated handles
target="${1#-d}"
[[ -z "$target" ]] && { target="$2"; shift; }
[[ "$target" == "all" ]] && all_clear
if [[ "$h_str" == "all" || "$h_str" == "*" ]]; then
all_clear
fi
# Collect handles to delete
handles=()
IFS=',' read -r -a parts <<< "$h_str"
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")
IFS=',' read -r -a parts <<< "$target"
for p in "${parts[@]}"; do
if [[ "$p" =~ ^:([0-9]+)$ ]]; then
# Delete by local port
port="${BASH_REMATCH[1]}"
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
delete_by_handle "$h"
done
else
handles+=("$part")
# Delete by handle
if ! delete_by_handle "$p"; then
err "Error: Handle $p not found."
fi
fi
done
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
;;
list_rules; exit 0 ;;
-t*)
h_str="${1#-t}"
if [[ -z "$h_str" ]]; then
h_str="$2"
shift
fi
# Support combined or separated test target
target="${1#-t}"
[[ -z "$target" ]] && { target="$2"; shift; }
# Pattern matching for different test types
if [[ "$h_str" =~ ^([0-9\.]+):([0-9]+)$ ]]; then
# IP:PORT test
tip=${BASH_REMATCH[1]}; tp=${BASH_REMATCH[2]}
echo -n "Checking Target $tip:$tp... "
test_connection "$tip" "$tp" && echo -e "\e[32mUP\e[0m" || echo -e "\e[31mDOWN\e[0m"
elif [[ "$h_str" =~ ^:([0-9]+)$ ]]; then
# :PORT test (local)
p="${BASH_REMATCH[1]}"
echo -n "Checking Local :$p... "
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 [[ "$h_str" =~ ^[0-9]+$ ]]; then
# Handle test
test_strict_handle "$h_str"
if [[ "$target" =~ ^([0-9\.]+):([0-9]+)$ ]]; then
# External Target IP:PORT test
ip=${BASH_REMATCH[1]}; port=${BASH_REMATCH[2]}
echo -n "Checking Target $ip:$port... "
test_connection "$ip" "$port" && echo -e "\e[32mUP\e[0m" || echo -e "\e[31mDOWN\e[0m"
elif [[ "$target" =~ ^:([0-9]+)$ ]]; then
# Local port test
port="${BASH_REMATCH[1]}"
echo -n "Checking Local :$port... "
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"
elif [[ "$target" =~ ^[0-9]+$ ]]; then
# Internal rule test by handle
test_strict_handle "$target"
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}')
if [[ -n "$top_h" ]]; then
test_strict_handle "$top_h"
else
msg "\e[31mError: No valid test target found for '$h_str'\e[0m"
fi
[[ -n "$top_h" ]] && test_strict_handle "$top_h" || err "Error: No valid target to test."
fi
exit 0
;;
exit 0 ;;
[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"
show_help
exit 1
;;
err "Unknown option '$1'. Use --help for usage."; exit 1 ;;
esac
shift
done