-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipforward.sh
executable file
·76 lines (68 loc) · 1.82 KB
/
ipforward.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/bin/bash
# Script for forwarding IP with nftables
#
# Author: alozo (github.com/alozoBack)
# Usage info
function show_help {
echo "Usage: $0 [-t] [-u] [-d destination] [-o origin] [-p port]"
echo " -t Use TCP protocol"
echo " -u Use UDP protocol"
echo " -d destination Destination IP"
echo " -o origin Origin IP"
echo " -p port Port to forward"
}
# Initialize variables
protocol=""
origin=""
dest=""
port=""
# Parse command line arguments using getopts
while getopts "tud:o:p:h" opt; do
case ${opt} in
t )
protocol="tcp"
;;
u )
protocol="udp"
;;
d )
dest=$OPTARG
;;
o )
origin=$OPTARG
;;
p )
port=$OPTARG
;;
h )
show_help
exit 0
;;
\? )
show_help
exit 1
;;
esac
done
# Check if all required arguments are provided
if [ -z "$protocol" ] || [ -z "$origin" ] || [ -z "$dest" ] || [ -z "$port" ]; then
echo "Error: Missing required arguments."
show_help
exit 1
fi
# Make sure nftables table and chains exist
nft add table ip nat
nft add chain ip nat prerouting { type nat hook prerouting priority 0 \; }
nft add chain ip nat postrouting { type nat hook postrouting priority 100 \; }
# Apply nftables rules based on protocol
if [ "$protocol" == "tcp" ]; then
nft add rule ip nat prerouting ip daddr $origin tcp dport $port dnat to $dest:$port
nft add rule ip nat postrouting ip saddr $dest oifname eth0 masquerade
elif [ "$protocol" == "udp" ]; then
nft add rule ip nat prerouting ip daddr $origin udp dport $port dnat to $dest:$port
nft add rule ip nat postrouting ip saddr $dest oifname eth0 masquerade
else
echo "Invalid protocol selected."
exit 1
fi
echo "Forwarding rule added: $origin -> $dest on port $port using $protocol"