Files
251123-biz-ul-dx/netflow/iptables.sh
Wang Sen Di ade50d9812 -
2025-12-16 09:49:35 +08:00

76 lines
2.2 KiB
Bash

#!/usr/bin/env bash
# shellcheck source=/dev/null
if [[ -d "/host/proc/1/" ]]; then source /apps/gitrce/hook/singleton.sh "$0"; fi
__get_mount_paths_cgroup_id() {
docker ps -q --no-trunc | while read -r cid; do
_path=$(docker inspect "$cid" --format '{{range .Mounts}}{{.Source}}{{"\n"}}{{end}}' 2>/dev/null)
if grep -q "$CACHE/$FILE_PATH_START" <<<"$_path"; then
_cmd="find /sys/fs/cgroup/ -type d -name $cid | grep net_cls 2>/dev/null"
_cgroup_path=$(nsenter --mount=/host/proc/1/ns/mnt --net=/host/proc/1/ns/net sh -c "$_cmd")
_cmd_classid="cat $_cgroup_path/net_cls.classid 2>/dev/null"
_cgroup_id=$(nsenter --mount=/host/proc/1/ns/mnt --net=/host/proc/1/ns/net sh -c "$_cmd_classid")
echo "$_cgroup_id"
fi
done
}
# __get_mount_paths_cgroup_id
__get_in_cgroup_ids() {
awk '$0 != 0 && $0 != 1' /sys/fs/cgroup/net_cls,net_prio/*/net_cls.classid
}
__main() {
:
update-alternatives --set iptables /usr/sbin/iptables-legacy 2>/dev/null
update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy 2>/dev/null
readarray -t _cgroup_ids < <(__get_mount_paths_cgroup_id)
if [[ ${#_cgroup_ids[@]} -eq 0 ]]; then
readarray -t _cgroup_ids < <(__get_in_cgroup_ids)
fi
_owner_id=51000
_chain="output_netflow_owner_${_owner_id}"
for cmd in iptables ip6tables; do
$cmd -t mangle -N "$_chain" 2>/dev/null || true
if ! $cmd -t mangle -C OUTPUT -m mark ! --mark 0x0 -j "$_chain" 2>/dev/null; then
$cmd -t mangle -A OUTPUT -m mark ! --mark 0x0 -j "$_chain"
fi
if ! $cmd -t mangle -C FORWARD -m mark ! --mark 0x0 -j "$_chain" 2>/dev/null; then
$cmd -t mangle -A FORWARD -m mark ! --mark 0x0 -j "$_chain"
fi
if ! $cmd -t mangle -C "$_chain" -j RETURN 2>/dev/null; then
$cmd -t mangle -A "$_chain" -j RETURN
fi
$cmd -t mangle -L OUTPUT -v -n -x
done
for cgid in "${_cgroup_ids[@]}"; do
for cmd in iptables ip6tables; do
$cmd -t mangle -N "$_chain" 2>/dev/null || true
if ! $cmd -t mangle -C OUTPUT -o '!lo' -m cgroup --cgroup "$cgid" -j "$_chain" 2>/dev/null; then
$cmd -t mangle -A OUTPUT -o '!lo' -m cgroup --cgroup "$cgid" -j "$_chain"
fi
if ! $cmd -t mangle -C "$_chain" -j RETURN 2>/dev/null; then
$cmd -t mangle -A "$_chain" -j RETURN
fi
done
done
}
__main
__help() {
cat >/dev/null <<-'EOF'
EOF
}