1.6.3 1.6.1に回帰した系?

This commit is contained in:
joe 2026-01-23 11:10:40 +09:00
parent 822f61a966
commit 69b25cdb59

169
ipf
View file

@ -1,9 +1,9 @@
#!/bin/bash
# Name: ipf
# Version: 1.6.1
# Date: 2026-01-22
# Description: Fully-featured nftables wrapper.
# Refinement: Incorporated Qwen2.5-Coder's feedback with human-readable robustness.
# Version: 1.6.3
# Date: 2026-01-23
# Description: Restored the rich UI (asterisk, highlighting) from 1.6.1
# while maintaining robust logic and AI-refined backends.
# -----------------------------------------------------------------------------
# 1. Root & Environment Check
@ -14,7 +14,7 @@ fi
# Global Configurations
TABLE_NAME="ipf"
VERSION="1.6.1"
VERSION="1.6.3"
PROTO="tcp"
FORCE_FLAG=false
SKIP_TEST=false
@ -22,7 +22,7 @@ QUIET_MODE=false
RESET_MODE=false
# -----------------------------------------------------------------------------
# 2. Messaging & System Functions
# 2. Messaging & System Functions (Rich UI)
# -----------------------------------------------------------------------------
msg() {
@ -30,7 +30,6 @@ msg() {
}
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
@ -41,12 +40,11 @@ err() {
enable_forwarding() {
msg "\e[34m[System]\e[0m Enabling IP forwarding..."
# Qwen's point: Check sysctl success
# Check sysctl success (Robustness)
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."
err "Critical: Could not enable net.ipv4.ip_forward. Please check 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
if [[ -f "$dev" ]]; then
echo 1 > "$dev" 2>/dev/null
@ -55,49 +53,40 @@ enable_forwarding() {
}
init_nft() {
# Create table if it doesn't exist
nft add table inet "${TABLE_NAME}" 2>/dev/null
# Qwen's point: Reliable chain initialization
# Prerouting (NAT)
# Precise chain initialization with correct priorities
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
# 3. Data & Counter Processing
# -----------------------------------------------------------------------------
get_total_packets() {
local uuid=$1
# 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.
# Optimized sum logic: one-pass via awk
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() {
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
nc -z -w 1 "$1" "$2" >/dev/null 2>&1
return $?
}
# -----------------------------------------------------------------------------
# 4. Rule Management Functions
# 4. Rule Management Functions (UUID-Driven)
# -----------------------------------------------------------------------------
delete_by_handle() {
local h=$1
local uuid=""
# Qwen's point: Search UUID across ALL chains, not just prerouting
# Search UUID across all relevant chains (Robustness)
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)
@ -108,7 +97,7 @@ delete_by_handle() {
return 1
fi
# Delete all rules associated with this UUID in all relevant chains
# Atomic-like deletion across all chains for this ID
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"
@ -137,17 +126,16 @@ test_strict_handle() {
local count_before=$(get_total_packets "$uuid")
if test_connection "$tip" "$tp"; then
# 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 (Traffic not hitting rule)\e[0m"
echo -e "\e[33mSKIPPED (Check shadowing)\e[0m"
fi
else
echo -e "\e[31mOFFLINE (Target Unreachable)\e[0m"
echo -e "\e[31mOFFLINE (Target Down)\e[0m"
fi
}
@ -167,6 +155,7 @@ list_rules() {
local lport=$(echo "$line" | grep -o 'dport [0-9]*' | awk '{print $2}')
local full_uuid=$(echo "$line" | grep -o 'ipf-id:[a-z0-9-]*' | cut -d':' -f2)
# UI: Highlight and Asterisk for the newly added rule
if [[ -n "$highlight_uuid" && "$full_uuid" == "$highlight_uuid" ]]; then
printf "\e[1;36m*%-9s %-6s %-20s %-20s %-10s\e[0m\n" "$handle" "$proto" ":$lport" "$target" "${full_uuid:0:8}"
else
@ -180,7 +169,7 @@ add_rule() {
init_nft
[[ "$FORCE_FLAG" == true ]] && enable_forwarding
# Syntax Parsing (LPORT:TIP:TPORT / LPORT:TPORT / LPORT)
# 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
@ -188,43 +177,34 @@ add_rule() {
elif [[ "$raw" =~ ^([0-9]+)$ ]]; then
lp=${BASH_REMATCH[1]}; tip="127.0.0.1"; tp=${BASH_REMATCH[1]}
else
err "Error: Invalid rule format '$raw'"
return 1
err "Error: Invalid rule format '$raw'"; return 1
fi
# --- Conflict Management ---
# 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"
# Conflict Management: Overwrite existing port rules
local conflicts=$(nft -a list chain inet "${TABLE_NAME}" prerouting 2>/dev/null | grep "dport $lp" | grep -o 'handle [0-9]*' | awk '{print $2}')
for ch in $conflicts; do
msg "\e[33mOverwriting existing rule on port :$lp (Handle $ch)...\e[0m"
delete_by_handle "$ch"
done
# Generate Unique ID for the rule set
# UUID Generation
local u_raw=$(cat /proc/sys/kernel/random/uuid)
local u="ipf-id:$u_raw"
local fam="ip"
[[ "$tip" =~ : ]] && fam="ip6"
local fam="ip"; [[ "$tip" =~ : ]] && fam="ip6"
# 1. PREROUTING: Redirect incoming external packets
# Rule Block (NAT, Filter, Masquerade)
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"
if [[ "$SKIP_TEST" == false && "$FORCE_FLAG" == false ]]; then
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 "$nh"
echo ""; test_strict_handle "$nh"
fi
}
@ -237,20 +217,40 @@ all_clear() {
nft delete table inet "${TABLE_NAME}" 2>/dev/null
init_nft
msg "Table '${TABLE_NAME}' has been reset."
list_rules
exit 0
list_rules; exit 0
}
show_help() {
echo "ipf version ${VERSION}"
echo "Usage: ipf [OPTIONS] [RULE]"
echo ""
echo "Example Rules:"
echo " 80:10.0.0.1:8080 Forward local :80 to 10.0.0.1:8080"
echo " 8080:80 Forward local :8080 to localhost :80"
echo " 2222 Forward local :2222 to localhost :2222"
echo ""
echo "Options:"
echo " -f Kernel: Enable forwarding & route_localnet"
echo " Global: Force mode (Skip confirmation/tests)"
echo " -l, -L List all forwarding rules"
echo " -d HANDLE/:PORT/all Delete specific rule(s)"
echo " -t [TARGET] Test connectivity (Handle, :Port, or IP:Port)"
echo " -R Reset: Clear ALL rules in the table"
echo " -v, --version Show version"
echo " -h, --help Show this help message"
}
# -----------------------------------------------------------------------------
# 5. Argument Parsing (Main Loop)
# 5. Main Loop (Parsing)
# -----------------------------------------------------------------------------
# Pre-parse flags for Global behavior
# Global Flag Pre-processing
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
if [[ "$arg" =~ y ]]; then FORCE_FLAG=true; SKIP_TEST=true; fi
[[ "$arg" == "-R" ]] && RESET_MODE=true
case "$arg" in
-q*) QUIET_MODE=true; FORCE_FLAG=true; SKIP_TEST=true ;;
-f*|-y*) FORCE_FLAG=true; SKIP_TEST=true ;;
-R) RESET_MODE=true ;;
esac
done
if [[ "$RESET_MODE" == true ]]; then all_clear; fi
@ -258,68 +258,37 @@ if [[ $# -eq 0 ]]; then list_rules; exit 0; fi
while [[ $# -gt 0 ]]; do
case "$1" in
-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 ;;
-h|--help) show_help; 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 ;;
-*[d]*)
# Support combined flags and comma-separated handles
target="${1#-d}"
[[ -z "$target" ]] && { target="$2"; shift; }
target="${1#-d}"; [[ -z "$target" ]] && { target="$2"; shift; }
[[ "$target" == "all" ]] && all_clear
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
# Delete by handle
if ! delete_by_handle "$p"; then
err "Error: Handle $p not found."
fi
delete_by_handle "$p" || err "Error: Handle $p not found."
fi
done
list_rules; exit 0 ;;
-t*)
# Support combined or separated test target
target="${1#-t}"
[[ -z "$target" ]] && { target="$2"; shift; }
target="${1#-t}"; [[ -z "$target" ]] && { target="$2"; shift; }
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"
echo -n "Target $target... "; test_connection "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" && 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"
echo -n "Local $target... "; nc -z -w 1 127.0.0.1 "${BASH_REMATCH[1]}" >/dev/null 2>&1 && echo -e "\e[32mOK\e[0m" || echo -e "\e[31mOFFLINE\e[0m"
else
# 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}')
[[ -n "$top_h" ]] && test_strict_handle "$top_h" || err "Error: No valid target to test."
test_strict_handle "$target"
fi
exit 0 ;;
[0-9]*)
add_rule "$1"; exit 0 ;;
*)
err "Unknown option '$1'. Use --help for usage."; exit 1 ;;
[0-9]*) add_rule "$1"; exit 0 ;;
*) err "Unknown option '$1'. Use -h for help."; exit 1 ;;
esac
shift
done