修正忘れ
This commit is contained in:
parent
8cdccae6bf
commit
5115961094
3 changed files with 20 additions and 647 deletions
36
README.md
36
README.md
|
|
@ -1,37 +1,41 @@
|
|||
|
||||
このプロジェクトは、iptablesのルールを編集するためのスクリプトです。以下が使用方法とライセンス情報です。
|
||||
このプロジェクトは、nftablesのルールを編集するためのスクリプトです。以下が使用方法とライセンス情報です。
|
||||
|
||||
---
|
||||
|
||||
### 概要
|
||||
このツールは、`iptables`のルールを編集する際のスクリプトであり、一時ファイルを作成し、エディタでルールを編集する処理を含みます。
|
||||
このツールは、`nftables`のルールを編集する際のスクリプトです。
|
||||
|
||||
---
|
||||
|
||||
### 使用方法
|
||||
1. **ルールの編集**
|
||||
**ルールの編集**
|
||||
```bash
|
||||
ipf 11434:10.1.1.2:11434 # Forward local port 11434 to 10.1.1.2:11434
|
||||
ipf -L # List all rules with numbers
|
||||
ipf -d 1 # Delete rule number 1
|
||||
ipf -d 1 -q # Delete rule number 1 (quiet mode)
|
||||
ipf -v # Show current iptables rules by iptables-save
|
||||
ipf -e # Edit all rules in editor and restore
|
||||
```
|
||||
ipf -e で一時ファイルが作成され、エディタ(例: `nano`)でルールを編集できます。編集が完了した後、一時ファイルは自動的に削除されます [1]。
|
||||
Usage: ipfn [OPTIONS] [RULES]
|
||||
|
||||
2. **バージョン情報の表示**
|
||||
```bash
|
||||
ipf --version # Show version information
|
||||
Rules Format:
|
||||
80:10.10.100.5:8080 Full (LocalPort:TargetIP:TargetPort)
|
||||
80:8080 IP defaults to 127.0.0.1
|
||||
11434 Map same port to 127.0.0.1
|
||||
|
||||
Options:
|
||||
-l, -L List all rules
|
||||
-d HANDLE/:PORT/all Delete specific rules or '*' for all
|
||||
-R Reset: Clear ALL rules immediately
|
||||
-q Quiet mode (No output, Auto-yes)
|
||||
-t [HANDLE] Test connectivity
|
||||
-f Enable IP forward & Bridge tuning / Skip test
|
||||
-v Verbose (raw nftables output)
|
||||
-h Show this help
|
||||
```
|
||||
これにより、ソフトウェアのバージョンとライセンス情報が表示されます [1]。
|
||||
|
||||
|
||||
---
|
||||
|
||||
### ライセンス
|
||||
MIT License に基づくライセンスです。
|
||||
**権利者**: krasherjoe
|
||||
**日付**: 2025-10-26
|
||||
**日付**: 2026-01-22
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
395
ipf1.0.4
395
ipf1.0.4
|
|
@ -1,395 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# sudo権限で実行されているか確認し、そうでなければsudoで再実行
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
exec sudo "$0" "$@"
|
||||
fi
|
||||
|
||||
# グローバル変数
|
||||
RULES_FILE="/tmp/iptables_forward_rules"
|
||||
QUIET=false
|
||||
PROTO="tcp" # デフォルトプロトコル
|
||||
|
||||
# コンテナ環境検出関数
|
||||
is_container() {
|
||||
# systemd-detect-virt を使用してコンテナ環境を検出
|
||||
if command -v systemd-detect-virt &> /dev/null; then
|
||||
if systemd-detect-virt --quiet | grep -qE "container|vm"; then
|
||||
return 0 # コンテナまたは仮想マシン環境
|
||||
fi
|
||||
fi
|
||||
|
||||
# lxc-checkconfig を使用して LXC コンテナを検出 (systemd-detect-virt がない場合)
|
||||
if command -v lxc-checkconfig &> /dev/null; then
|
||||
if lxc-checkconfig 2>&1 | grep -q "Running in an LXC container"; then
|
||||
return 0 # LXC コンテナ環境
|
||||
fi
|
||||
fi
|
||||
|
||||
# その他 (LXD など) のコンテナ環境検出方法を追加可能
|
||||
|
||||
return 1 # コンテナ環境ではない
|
||||
}
|
||||
|
||||
|
||||
# ヘルプ表示
|
||||
show_help() {
|
||||
cat << EOF
|
||||
Usage: ipf [OPTIONS] [PORT:IP:PORT | -L | -d RULE_NUMBER]
|
||||
|
||||
Examples:
|
||||
ipf 11434:10.1.1.2:11434 # Forward local port 11434 to 10.1.1.2:11434
|
||||
ipf -L # List all rules with numbers
|
||||
ipf -d 1 # Delete rule number 1
|
||||
ipf -d 1 -q # Delete rule number 1 (quiet mode)
|
||||
ipf -v # Show current iptables rules by iptables-save
|
||||
ipf -e # Edit all rules in editor and restore
|
||||
ipf -f # Enable IP forwarding
|
||||
ipf -t 1 # Test rule number 1
|
||||
ipf -t 11434:10.10.1.2:11434 # Test rule by specification
|
||||
ipf -p udp 11434:10.1.1.2:11434 # Forward using UDP
|
||||
|
||||
Options:
|
||||
-h, --help Show this help message
|
||||
-L, -l List all rules
|
||||
-d NUM Delete rule by number
|
||||
-q Quiet mode (no output)
|
||||
-v Show current iptables rules (via iptables-save)
|
||||
-e Edit all rules in editor and restore
|
||||
-f Enable IP forwarding and localnet routing
|
||||
-t ARG Test connectivity for rule number or PORT:IP:PORT
|
||||
-p PROTO Specify protocol (tcp|udp) for the following rule
|
||||
--version Show version information
|
||||
|
||||
NOTE:
|
||||
All port forwarding is performed using DNAT only. No MASQUERADE (SNAT) is applied,
|
||||
so the original source IP of the client is preserved. This ensures that
|
||||
fail2ban logs the correct client IP on the destination server.
|
||||
EOF
|
||||
}
|
||||
|
||||
# バージョン情報を表示
|
||||
show_version() {
|
||||
cat << EOF
|
||||
ipf ver.1.0.4
|
||||
Date: 2025-10-26
|
||||
Created by: qwen3/gpt-oss/gemini-2.5-pro and krasherjoe
|
||||
|
||||
---
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 krasherjoe
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
---
|
||||
|
||||
** WARNING / 注意 **
|
||||
This script operates with administrative privileges (sudo) to modify your system's
|
||||
firewall (iptables) rules. Incorrect use, especially with the -e (edit) option,
|
||||
can disrupt your network connectivity or overwrite existing security rules.
|
||||
Please use with caution and understand the changes you are making.
|
||||
|
||||
このスクリプトは管理者権限(sudo)で動作し、システムのファイアウォール(iptables)ルールを
|
||||
直接変更します。特に -e (編集) オプションの誤った使用は、ネットワーク接続を中断させたり、
|
||||
既存のセキュリティルールを上書きする危険性があります。
|
||||
コンテナ環境ではMASQUERADEを使用するため、クライアントの元のIPアドレスが隠蔽されます。
|
||||
これにより、fail2banなどのツールが不正な行為者を正しく識別し、ブロックできなくなる可能性があります。
|
||||
セキュリティへの影響を考慮してください。
|
||||
内容をよく理解した上で、注意して使用してください。
|
||||
EOF
|
||||
}
|
||||
|
||||
# エラーメッセージを表示
|
||||
error() {
|
||||
echo "Error: $*" >&2
|
||||
logger -p user.err "ipf: $*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# ルールの保存
|
||||
save_rules() {
|
||||
iptables-save > "$RULES_FILE"
|
||||
}
|
||||
|
||||
# ルールの読み込み
|
||||
load_rules() {
|
||||
if [[ -f "$RULES_FILE" ]]; then
|
||||
iptables-restore < "$RULES_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
# ルール番号と内容をリスト表示
|
||||
list_rules() {
|
||||
local i=1
|
||||
echo "Forwarding rules:"
|
||||
iptables -t nat -L PREROUTING -n -v --line-numbers | grep -E '^[0-9]+' | while read -r line; do
|
||||
echo "$i: $line"
|
||||
((i++))
|
||||
done
|
||||
}
|
||||
|
||||
# ルールを削除
|
||||
delete_rule() {
|
||||
local num=$1
|
||||
if ! [[ "$num" =~ ^[0-9]+$ ]]; then
|
||||
error "Invalid rule number: $num"
|
||||
fi
|
||||
|
||||
# ユーザーへの表示用に整形されたルール行を取得
|
||||
local rule_line_verbose=$(iptables -t nat -L PREROUTING --line-numbers | grep -E "^$num\s+" | head -n 1)
|
||||
if [[ -z "$rule_line_verbose" ]]; then
|
||||
error "No rule found with number: $num"
|
||||
fi
|
||||
|
||||
# パース用に-nオプションを付けたルール行を取得
|
||||
local rule_line_numeric=$(iptables -t nat -L PREROUTING -n --line-numbers | grep -E "^\s*$num\s+" | head -n 1)
|
||||
if [[ -z "$rule_line_numeric" ]]; then
|
||||
error "Could not find numeric rule for number: $num" # Should not happen
|
||||
fi
|
||||
|
||||
# ルールから詳細を抽出 (sedを使い、より堅牢に)
|
||||
local line_details=$(echo "$rule_line_numeric" | sed -n 's/.*\(tcp\|udp\).*dpt:\([0-9]*\).*to:\([0-9.]*\):\([0-9]*\).*/\1 \2 \3 \4/p')
|
||||
if [[ -z "$line_details" ]]; then
|
||||
error "Could not parse rule details from line: $rule_line_numeric"
|
||||
fi
|
||||
read -r proto local_port target_ip target_port <<< "$line_details"
|
||||
|
||||
# 1. PREROUTING ルールを番号で削除
|
||||
if ! iptables -t nat -D PREROUTING "$num"; then
|
||||
error "Failed to delete PREROUTING rule $num"
|
||||
fi
|
||||
|
||||
# 2. 対応する OUTPUT ルールをすべて削除
|
||||
while iptables -t nat -D OUTPUT -p "$proto" -m "$proto" --dport "$local_port" -j DNAT --to-destination "$target_ip:$target_port" >/dev/null 2>&1; do :; done
|
||||
|
||||
# 3. 対応する FORWARD ルールをすべて削除
|
||||
while iptables -D FORWARD -p "$proto" -m "$proto" -d "$target_ip" --dport "$target_port" -j ACCEPT >/dev/null 2>&1; do :; done
|
||||
|
||||
# 4. 確立済み通信を許可するルールを削除 (存在確認後に削除)
|
||||
if iptables -C FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT 2>/dev/null; then
|
||||
iptables -D FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT >/dev/null 2>&1
|
||||
fi
|
||||
|
||||
if ! $QUIET; then
|
||||
echo "Deleted rule $num: $rule_line_verbose"
|
||||
fi
|
||||
}
|
||||
|
||||
# ポートフォワーディングルールを追加
|
||||
add_rule() {
|
||||
# IPフォワーディングが有効かチェック
|
||||
if [[ $(sysctl -n net.ipv4.ip_forward) -ne 1 ]]; then
|
||||
error "IP forwarding is disabled. Please enable it by running: ipf -f"
|
||||
fi
|
||||
|
||||
local container_env=$(is_container)
|
||||
if [[ $container_env -eq 0 ]]; then
|
||||
echo -e "\e[33mDetected container environment. MASQUERADE is enabled, which hides the original client IP address. This will prevent tools like fail2ban from correctly identifying and blocking malicious actors. Consider the security implications.\e[0m" # コンテナ環境であることを示すメッセージ
|
||||
fi
|
||||
|
||||
# 確立済みの通信は許可する (戻りのパケットのため)
|
||||
iptables -I FORWARD 1 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
|
||||
|
||||
local port_ip_port=$1
|
||||
local local_port=$(echo "$port_ip_port" | cut -d':' -f1)
|
||||
local target_ip=$(echo "$port_ip_port" | cut -d':' -f2)
|
||||
local target_port=$(echo "$port_ip_port" | cut -d':' -f3)
|
||||
|
||||
# IPアドレス検証
|
||||
if ! [[ "$target_ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
|
||||
error "Invalid IP address: $target_ip"
|
||||
fi
|
||||
|
||||
# ポート番号検証
|
||||
if ! [[ "$local_port" =~ ^[0-9]+$ ]] || ! [[ "$target_port" =~ ^[0-9]+$ ]]; then
|
||||
error "Invalid port number"
|
||||
fi
|
||||
if (( local_port < 1 || local_port > 65535 || target_port < 1 || target_port > 65535 )); then
|
||||
error "Port number out of range (1-65535)"
|
||||
fi
|
||||
|
||||
# iptablesでルールを追加
|
||||
# 外部からのパケットを対象
|
||||
iptables -t nat -A PREROUTING -p "$PROTO" -m "$PROTO" --dport "$local_port" -j DNAT --to-destination "$target_ip:$target_port"
|
||||
# ローカルで生成されたパケットを対象
|
||||
iptables -t nat -A OUTPUT -p "$PROTO" -m "$PROTO" --dport "$local_port" -j DNAT --to-destination "$target_ip:$target_port"
|
||||
|
||||
if [[ $container_env -eq 0 ]]; then
|
||||
# コンテナ環境ではMASQUERADEを使用
|
||||
iptables -t nat -A POSTROUTING -p "$PROTO" -m "$PROTO" -d "$target_ip" --dport "$target_port" -j MASQUERADE
|
||||
fi
|
||||
|
||||
# 転送されるパケットを許可する
|
||||
iptables -A FORWARD -p "$PROTO" -m "$PROTO" -d "$target_ip" --dport "$target_port" -j ACCEPT
|
||||
|
||||
if ! $QUIET; then
|
||||
echo "Rule added: port $local_port -> $target_ip:$target_port (proto=$PROTO)"
|
||||
fi
|
||||
}
|
||||
|
||||
# ルールを編集して復元
|
||||
edit_rules() {
|
||||
local temp_file
|
||||
temp_file=$(mktemp -t iptables.rules.XXXXXX) || error "Failed to create temporary file"
|
||||
chmod 0600 "$temp_file"
|
||||
trap 'rm -f "$temp_file"' EXIT
|
||||
|
||||
# 現在のルールを一時ファイルに保存
|
||||
iptables-save > "$temp_file"
|
||||
|
||||
# エディタを決定
|
||||
local editor=${EDITOR:-nano}
|
||||
if ! command -v "$editor" > /dev/null; then
|
||||
editor=vi
|
||||
fi
|
||||
|
||||
# nanoで編集
|
||||
if ! "$editor" "$temp_file"; then
|
||||
error "Editor closed without saving or an error occurred."
|
||||
fi
|
||||
|
||||
# 編集後の内容でリストア
|
||||
if iptables-restore < "$temp_file"; then
|
||||
echo "iptables rules restored successfully from your edits."
|
||||
echo "--- Displaying new rules ---"
|
||||
iptables-save
|
||||
else
|
||||
error "Failed to restore iptables rules. Please check for syntax errors in your edits."
|
||||
fi
|
||||
}
|
||||
|
||||
# 疎通確認用関数
|
||||
test_rule() {
|
||||
local arg=$1
|
||||
local local_port target_ip target_port
|
||||
|
||||
if [[ "$arg" =~ ^[0-9]+$ ]]; then
|
||||
# rule number → ルール行を取得
|
||||
local line=$(iptables -t nat -L PREROUTING -n --line-numbers | grep "^$arg ")
|
||||
if [[ -z "$line" ]]; then
|
||||
error "No rule found with number: $arg"
|
||||
fi
|
||||
local_port=$(echo "$line" | awk '{print $8}'|cut -d ':' -f2)
|
||||
target_ip=$(echo "$line" | awk -F: '{print $1}')
|
||||
target_port=$(echo "$line" | awk -F: '{print $2}')
|
||||
else
|
||||
# 文字列形式
|
||||
local_port=$(echo "$arg" | cut -d':' -f1)
|
||||
target_ip=$(echo "$arg" | cut -d':' -f2)
|
||||
target_port=$(echo "$arg" | cut -d':' -f3)
|
||||
fi
|
||||
|
||||
echo "Testing connectivity to local port \"$(tput setaf 3)nc -z -w 5 127.0.0.1 $local_port$(tput sgr0)\""
|
||||
if nc -z -w 5 127.0.0.1 "$local_port" 2>/dev/null; then
|
||||
echo "$(tput setaf 6)Connection successful.$(tput sgr0)"
|
||||
else
|
||||
echo "$(tput setaf 1)Connection failed.$(tput sgr0)"
|
||||
fi
|
||||
}
|
||||
|
||||
# メイン処理
|
||||
main() {
|
||||
# オプション解析
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-h|--help)
|
||||
show_help
|
||||
exit 0
|
||||
;;
|
||||
-L|-l)
|
||||
list_rules
|
||||
exit 0
|
||||
;;
|
||||
-v)
|
||||
iptables-save | grep -v '^#' | less -R
|
||||
exit 0
|
||||
;;
|
||||
-e)
|
||||
edit_rules
|
||||
exit 0
|
||||
;;
|
||||
-f)
|
||||
if sysctl -w net.ipv4.ip_forward=1 > /dev/null && \
|
||||
sysctl -w net.ipv4.conf.all.route_localnet=1 > /dev/null && \
|
||||
sysctl -w net.ipv4.conf.default.route_localnet=1 > /dev/null; then
|
||||
echo "IP forwarding and localnet routing enabled."
|
||||
else
|
||||
error "Failed to enable kernel parameters."
|
||||
fi
|
||||
exit 0
|
||||
;;
|
||||
--version)
|
||||
show_version
|
||||
exit 0
|
||||
;;
|
||||
-d)
|
||||
if [[ $# -lt 2 ]]; then
|
||||
error "Missing rule number for -d option"
|
||||
fi
|
||||
delete_rule "$2"
|
||||
exit 0
|
||||
;;
|
||||
-t)
|
||||
if [[ $# -lt 2 ]]; then
|
||||
error "Missing argument for -t option"
|
||||
fi
|
||||
test_rule "$2"
|
||||
exit 0
|
||||
;;
|
||||
-q)
|
||||
QUIET=true
|
||||
shift
|
||||
;;
|
||||
-p)
|
||||
if [[ $# -lt 2 ]]; then
|
||||
error "Missing protocol after -p"
|
||||
fi
|
||||
if [[ "$2" != "tcp" && "$2" != "udp" ]]; then
|
||||
error "Unsupported protocol: $2"
|
||||
fi
|
||||
PROTO="$2"
|
||||
shift 2
|
||||
;;
|
||||
-*)
|
||||
error "Unknown option: $1"
|
||||
;;
|
||||
*)
|
||||
break
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# 引数が残っていれば、ルール追加処理
|
||||
if [[ $# -eq 0 ]]; then
|
||||
show_help
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local arg=$1
|
||||
|
||||
# ルール追加処理
|
||||
if [[ "$arg" =~ ^[0-9]+:[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+$ ]]; then
|
||||
add_rule "$arg"
|
||||
else
|
||||
error "Invalid format. Expected: PORT:IP:PORT or -L or -d RULE_NUMBER"
|
||||
fi
|
||||
}
|
||||
|
||||
# 実行
|
||||
main "$@"
|
||||
236
ipfn1.0
236
ipfn1.0
|
|
@ -1,236 +0,0 @@
|
|||
#!/bin/bash
|
||||
# Name: ipfn
|
||||
# Version: 1.2.4
|
||||
# Date: 2026-01-22
|
||||
# Description: Enhanced for VM/LXD/Docker with bridge-nf tuning and robust forwarding.
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
exec sudo "$0" "$@"
|
||||
fi
|
||||
|
||||
TABLE_NAME="ipf_wrapper"
|
||||
PROTO="tcp"
|
||||
FORCE_FLAG=false
|
||||
SKIP_TEST=false
|
||||
QUIET_MODE=false
|
||||
|
||||
# --- 1. Utility & Core Setup ---
|
||||
|
||||
msg() { [[ "$QUIET_MODE" == false ]] && echo -e "$@"; }
|
||||
|
||||
init_nft() {
|
||||
nft add table inet ${TABLE_NAME} 2>/dev/null
|
||||
# NAT Chains
|
||||
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
|
||||
# Filter Chain (For VM/CT Forwarding)
|
||||
nft add chain inet ${TABLE_NAME} forward { type filter hook forward priority 0 \; policy accept \; } 2>/dev/null
|
||||
}
|
||||
|
||||
enable_forwarding() {
|
||||
msg "Optimizing kernel parameters for VM/LXD/Docker..."
|
||||
sysctl -w net.ipv4.ip_forward=1 >/dev/null
|
||||
sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null
|
||||
sysctl -w net.ipv4.conf.all.route_localnet=1 >/dev/null
|
||||
# ブリッジパケットをNetfilterに渡す設定 (存在する場合のみ)
|
||||
sysctl -w net.bridge.bridge-nf-call-iptables=1 2>/dev/null
|
||||
sysctl -w net.bridge.bridge-nf-call-ip6tables=1 2>/dev/null
|
||||
msg "\e[32mForwarding and Bridge-NF enabled.\e[0m"
|
||||
}
|
||||
|
||||
show_help() {
|
||||
echo "Usage: ipfn [OPTIONS] [RULES]"
|
||||
echo ""
|
||||
echo "Rules Format:"
|
||||
echo " 80:10.10.100.5:8080 Full (LocalPort:TargetIP:TargetPort)"
|
||||
echo " 80:8080 IP defaults to 127.0.0.1"
|
||||
echo " 11434 Map same port to 127.0.0.1"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " -l, -L List all rules"
|
||||
echo " -d HANDLE/:PORT/all Delete specific rules or '*' for all"
|
||||
echo " -R Reset: Clear ALL rules immediately"
|
||||
echo " -q Quiet mode (No output, Auto-yes)"
|
||||
echo " -t [HANDLE] Test connectivity"
|
||||
echo " -f Enable IP forward & Bridge tuning / Skip test"
|
||||
echo " -v Verbose (raw nftables output)"
|
||||
echo " -h Show this help"
|
||||
}
|
||||
|
||||
list_rules() {
|
||||
[[ "$QUIET_MODE" == true ]] && return
|
||||
local highlight_uuid=$1
|
||||
init_nft
|
||||
msg "Forwarding Rules (ipfn):"
|
||||
printf "%-10s %-6s %-20s %-20s %-10s\n" "HANDLE" "PROTO" "LOCAL" "TARGET" "UUID"
|
||||
echo "-----------------------------------------------------------------------------------"
|
||||
nft -a list chain inet ${TABLE_NAME} prerouting | grep "dnat" | while read -r line; do
|
||||
handle=$(echo "$line" | grep -o 'handle [0-9]*' | awk '{print $2}')
|
||||
proto=$(echo "$line" | grep -q "udp" && echo "udp" || echo "tcp")
|
||||
target=$(echo "$line" | grep -oE '([0-9.]+|\[[0-9a-fA-F:]+\]):[0-9]+' | head -n 1)
|
||||
lport=$(echo "$line" | grep -o 'dport [0-9]*' | awk '{print $2}')
|
||||
full_uuid=$(echo "$line" | grep -o 'ipf-id:[a-z0-9-]*' | cut -d':' -f2)
|
||||
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
|
||||
printf "%-10s %-6s %-20s %-20s %-10s\n" "$handle" "$proto" ":$lport" "$target" "${full_uuid:0:8}"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
test_rule_by_port() {
|
||||
[[ "$QUIET_MODE" == true ]] && return
|
||||
local lp=$1
|
||||
echo -n "Testing connectivity to :$lp... "
|
||||
if nc -z -v -w 2 127.0.0.1 "$lp" 2>&1 | grep -iqE "succeeded|connected|open"; then
|
||||
echo -e "\e[32mOK\e[0m"
|
||||
else
|
||||
echo -e "\e[31mFAILED\e[0m"
|
||||
fi
|
||||
}
|
||||
|
||||
# --- 2. Deletion Logic ---
|
||||
|
||||
validate_rule_handle() {
|
||||
nft -a list chain inet ${TABLE_NAME} prerouting | grep "handle $1" | grep -q "dnat"
|
||||
}
|
||||
|
||||
all_clear() {
|
||||
if [[ "$FORCE_FLAG" == false ]]; then
|
||||
msg "\e[33mWarning: This will delete ALL forwarding rules.\e[0m"
|
||||
read -p "Are you sure? (y/N): " confirm
|
||||
[[ ! "$confirm" =~ ^[yY]$ ]] && exit 0
|
||||
fi
|
||||
nft delete table inet ${TABLE_NAME} 2>/dev/null
|
||||
init_nft
|
||||
msg "All rules cleared successfully."
|
||||
exit 0
|
||||
}
|
||||
|
||||
parse_delete_targets() {
|
||||
local input=$1
|
||||
local -a final_handles=()
|
||||
[[ "$input" == "*" || "$input" == "all" ]] && all_clear
|
||||
IFS=',' read -r -a parts <<< "$input"
|
||||
for part in "${parts[@]}"; do
|
||||
if [[ "$part" =~ ^:([0-9]+)$ ]]; then
|
||||
local target_port="${BASH_REMATCH[1]}"
|
||||
local found_h=$(nft -a list chain inet ${TABLE_NAME} prerouting | grep "dport $target_port" | grep -o 'handle [0-9]*' | awk '{print $2}')
|
||||
for h in $found_h; do final_handles+=("$h"); done
|
||||
elif [[ "$part" =~ ^([0-9]+)-([0-9]+)$ ]]; then
|
||||
for ((i=${BASH_REMATCH[1]}; i<=${BASH_REMATCH[2]}; i++)); do
|
||||
validate_rule_handle "$i" && final_handles+=("$i")
|
||||
done
|
||||
else
|
||||
validate_rule_handle "$part" && final_handles+=("$part")
|
||||
fi
|
||||
done
|
||||
echo "${final_handles[@]}"
|
||||
}
|
||||
|
||||
# --- 3. Adding Logic ---
|
||||
|
||||
add_rule() {
|
||||
init_nft
|
||||
local raw_input=$1
|
||||
local lp tip tp
|
||||
|
||||
if [[ "$raw_input" =~ ^([0-9]+):([0-9\.]+):([0-9]+)$ ]]; then
|
||||
lp=${BASH_REMATCH[1]}; tip=${BASH_REMATCH[2]}; tp=${BASH_REMATCH[3]}
|
||||
elif [[ "$raw_input" =~ ^([0-9]+):([0-9]+)$ ]]; then
|
||||
lp=${BASH_REMATCH[1]}; tip="127.0.0.1"; tp=${BASH_REMATCH[2]}
|
||||
elif [[ "$raw_input" =~ ^([0-9]+)$ ]]; then
|
||||
lp=${BASH_REMATCH[1]}; tip="127.0.0.1"; tp=${BASH_REMATCH[1]}
|
||||
else
|
||||
msg "\e[31mError: Invalid rule format '$raw_input'\e[0m"; exit 1
|
||||
fi
|
||||
|
||||
local raw_uuid=$(cat /proc/sys/kernel/random/uuid)
|
||||
local uuid="ipf-id:$raw_uuid"
|
||||
local family="ip"; [[ "$tip" =~ : ]] && family="ip6"
|
||||
|
||||
# DNAT
|
||||
nft add rule inet ${TABLE_NAME} prerouting "$PROTO" dport "$lp" dnat $family to "$tip:$tp" comment "\"$uuid\""
|
||||
nft add rule inet ${TABLE_NAME} output "$PROTO" dport "$lp" dnat $family to "$tip:$tp" comment "\"$uuid\""
|
||||
|
||||
# FORWARD (VM/CT対応)
|
||||
nft add rule inet ${TABLE_NAME} forward $family daddr "$tip" "$PROTO" dport "$tp" ct state new,established,related accept comment "\"$uuid\""
|
||||
nft add rule inet ${TABLE_NAME} forward $family saddr "$tip" "$PROTO" sport "$tp" ct state established,related accept comment "\"$uuid\""
|
||||
nft add rule inet ${TABLE_NAME} forward iifname "lo" accept comment "\"$uuid\""
|
||||
|
||||
# POSTROUTING (MASQUERADE: 戻りパケットの保証)
|
||||
nft add rule inet ${TABLE_NAME} postrouting $family daddr "$tip" "$PROTO" dport "$tp" masquerade comment "\"$uuid\""
|
||||
|
||||
list_rules "$raw_uuid"
|
||||
[[ "$SKIP_TEST" == false ]] && { echo ""; test_rule_by_port "$lp"; }
|
||||
}
|
||||
|
||||
# --- 4. Main Parsing ---
|
||||
|
||||
for arg in "$@"; do
|
||||
[[ "$arg" =~ q ]] && QUIET_MODE=true && FORCE_FLAG=true && SKIP_TEST=true
|
||||
[[ "$arg" =~ f ]] && FORCE_FLAG=true && SKIP_TEST=true
|
||||
[[ "$arg" == "-R" ]] && RESET_MODE=true
|
||||
done
|
||||
|
||||
if [[ "$RESET_MODE" == true ]]; then all_clear; fi
|
||||
|
||||
if [[ $# -eq 0 ]]; then list_rules; exit 0; fi
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-h|--help) show_help; exit 0 ;;
|
||||
-v|--verbose) nft list table inet ${TABLE_NAME}; exit 0 ;;
|
||||
-L|-l) list_rules; exit 0 ;;
|
||||
-f)
|
||||
enable_forwarding
|
||||
[[ $# -eq 1 ]] && exit 0 ;;
|
||||
-t*)
|
||||
h_str="${1#-t}"
|
||||
if [[ -z "$h_str" && ( "$2" =~ ^[0-9,-]+$ ) ]]; then h_str="$2"; shift; fi
|
||||
if [[ -z "$h_str" ]]; then
|
||||
count=$(nft list chain inet ${TABLE_NAME} prerouting | grep -c "dnat")
|
||||
if [ "$count" -eq 1 ]; then
|
||||
h_str=$(nft -a list chain inet ${TABLE_NAME} prerouting | grep "handle" | awk '{print $NF}')
|
||||
else
|
||||
msg "Error: Multiple rules exist. Specify a handle."; exit 1
|
||||
fi
|
||||
fi
|
||||
lp=$(nft -a list chain inet ${TABLE_NAME} prerouting | grep "handle $h_str" | grep -o 'dport [0-9]*' | awk '{print $2}')
|
||||
[[ -n "$lp" ]] && test_rule_by_port "$lp" || msg "Error: Handle $h_str not found."
|
||||
exit 0 ;;
|
||||
-*[d]*)
|
||||
h_str=$(echo "$1" | sed -E 's/^-q?d?f?//')
|
||||
[[ -z "$h_str" ]] && { h_str="$2"; shift; }
|
||||
handles=($(parse_delete_targets "$h_str"))
|
||||
[[ ${#handles[@]} -eq 0 ]] && { msg "No valid targets."; exit 1; }
|
||||
if [[ "$FORCE_FLAG" == false ]]; then
|
||||
msg "Review rules to delete (Top-level only):"
|
||||
for h in "${handles[@]}"; do
|
||||
nft -a list chain inet ${TABLE_NAME} prerouting | grep "handle $h" | sed 's/^/ /'
|
||||
done
|
||||
read -p "Delete these rules and their sub-rules? (y/N): " confirm
|
||||
[[ ! "$confirm" =~ ^[yY]$ ]] && exit 0
|
||||
fi
|
||||
for h in "${handles[@]}"; do
|
||||
ri=$(nft -a list chain inet ${TABLE_NAME} prerouting | grep "handle $h")
|
||||
[[ -z "$ri" ]] && continue
|
||||
uuid=$(echo "$ri" | grep -o 'ipf-id:[a-z0-9-]*' | head -n 1)
|
||||
for c in prerouting output forward postrouting; do
|
||||
nft -a list chain inet ${TABLE_NAME} "$c" | 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
|
||||
done
|
||||
msg "Deleted associated with handle $h"
|
||||
done
|
||||
list_rules; exit 0 ;;
|
||||
*)
|
||||
if [[ "$1" =~ ^[0-9] ]]; then
|
||||
add_rule "$1"; exit 0
|
||||
else
|
||||
msg "\e[31mError: Unknown option '$1'\e[0m\n"; show_help; exit 1
|
||||
fi ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
Loading…
Reference in a new issue