diff --git a/netflow/iptables.sh b/netflow/iptables.sh index ec119d4..f1e3bd8 100644 --- a/netflow/iptables.sh +++ b/netflow/iptables.sh @@ -3,11 +3,35 @@ 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}" @@ -28,6 +52,18 @@ __main() { $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