NAT-rules-fixed-IPv4-provider/configure_NAT_from_RULES
2024-02-14 18:19:40 +00:00

81 lines
2.6 KiB
Bash
Executable file

#!/bin/bash
add_NAT_forwarding() {
if [ "$#" -ne 6 ]; then
echo "Usage: $0 <interface_source> <tcp_or_udp> <original_destination_ip> <original_destination_port> <forward_to_ip> <forward_to_port>"
exit 1
fi
interface_source="$1"
tcp_or_udp="$2"
original_destination_ip="$3"
original_destination_port="$4"
forward_to_ip="$5"
forward_to_port="$6"
firewall-cmd --add-rich-rule "rule family=\"ipv4\" destination address=\"$original_destination_ip\" forward-port port=\"$original_destination_port\" protocol=\"$tcp_or_udp\" to-addr=\"$forward_to_ip\" to-port=\"$forward_to_port\"" --permanent > /dev/null
echo "+ [$interface_source][$tcp_or_udp] $original_destination_ip:$original_destination_port --> $forward_to_ip:$forward_to_port"
}
remove_NAT_forwarding() {
if [ "$#" -ne 6 ]; then
echo "Usage: $0 <interface_source> <tcp_or_udp> <original_destination_ip> <original_destination_port> <forward_to_ip> <forward_to_port>"
exit 1
fi
interface_source="$1"
tcp_or_udp="$2"
original_destination_ip="$3"
original_destination_port="$4"
forward_to_ip="$5"
forward_to_port="$6"
firewall-cmd --remove-rich-rule "rule family=\"ipv4\" destination address=\"$original_destination_ip\" forward-port port=\"$original_destination_port\" protocol=\"$tcp_or_udp\" to-addr=\"$forward_to_ip\" to-port=\"$forward_to_port\"" --permanent > /dev/null
echo "- [$interface_source][$tcp_or_udp] $original_destination_ip:$original_destination_port --> $forward_to_ip:$forward_to_port"
}
# Actual script
if [ `id -u` -ne 0 ]; then
echo "This scripts only runs as root."
exit 2
fi
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <up/down>"
exit 1
fi
action="$1"
for rule in "${RULES[@]}"; do
protocol="tcp"
if [[ "$rule" == */udp ]]; then
protocol="udp"
rule="${rule%/udp}" # Remove "/udp" from the end of the string
fi
IFS=":" read -ra parts <<< "$rule"
port_origin="${parts[0]}"
forward_port="${parts[1]}"
# Appeler la fonction appropriée en fonction de l'action spécifiée
case "$action" in
"up")
add_NAT_forwarding "$INTERFACE_SOURCE" "$protocol" "$ORIGINAL_DESTINATION_IP" "$port_origin" "$FORWARD_TO_IP" "$forward_port"
;;
"down")
remove_NAT_forwarding "$INTERFACE_SOURCE" "$protocol" "$ORIGINAL_DESTINATION_IP" "$port_origin" "$FORWARD_TO_IP" "$forward_port"
;;
*)
echo "Invalid action. Use 'up' or 'down'."
exit 1
;;
esac
done
firewall-cmd --reload > /dev/null
echo -e "\nDone! Don't forget to add/remove the rules in the security list."