KBench / tools /factory /shared /restrict-network.sh
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
0f775e2 verified
Raw
History Blame Contribute Delete
2.57 kB
#!/bin/bash
# Outbound firewall (anti-cheat): allow ONLY DNS, loopback, docker-internal networks, and the LLM API
# endpoints the agent needs. Everything else is dropped — in particular pypi, github, and huggingface,
# so the agent cannot `pip install vllm` / `pip install sglang` / clone the reference moe_align kernel and
# copy it. torch + triton are already in the image, and mini-swe-agent is pre-installed (harbor's patched
# installer skips the network install when it is already present), so no package index is needed at run time.
#
# Runs as the container ENTRYPOINT before the CMD. iptables rules are network-namespace-wide, so they also
# apply to the agent's `docker exec` commands. Requires cap_add: NET_ADMIN.
set -uo pipefail
# LLM API endpoints the agent may reach. Extend at launch via ALLOWED_HOSTS=host1,host2 (no scheme).
API_HOSTS=(
api.fireworks.ai
openrouter.ai openrouter.io
api.openai.com api.anthropic.com generativelanguage.googleapis.com
api.together.xyz integrate.api.nvidia.com api.moonshot.cn api.kimi.com
)
# Auto-allow hosts from any *_BASE_URL / *_ENDPOINT env var (ANTHROPIC_BASE_URL, OPENAI_BASE_URL, …).
CUSTOM=()
while IFS='=' read -r n v; do
case "$n" in
*_BASE_URL|*_URL|*_ENDPOINT)
[ -n "$v" ] && CUSTOM+=("$(echo "$v" | sed 's|.*://||; s|[:/].*||')") ;;
esac
done < <(env)
if [ -n "${ALLOWED_HOSTS:-}" ]; then IFS=',' read -ra E <<< "$ALLOWED_HOSTS"; CUSTOM+=("${E[@]}"); fi
ALL_HOSTS=("${API_HOSTS[@]}" ${CUSTOM[@]+"${CUSTOM[@]}"})
if iptables -L OUTPUT -n >/dev/null 2>&1; then
echo "restrict-network: applying outbound allowlist firewall..."
iptables -F OUTPUT 2>/dev/null || true
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
iptables -A OUTPUT -d 127.0.0.11 -j ACCEPT
for h in "${ALL_HOSTS[@]}"; do
for ip in $(getent ahosts "$h" 2>/dev/null | awk '{print $1}' | sort -u); do
iptables -A OUTPUT -d "$ip" -j ACCEPT
done
done
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
echo "restrict-network: outbound locked to DNS + LLM endpoints; pypi/github/HF blocked."
else
echo "restrict-network: WARNING — iptables unavailable (need cap_add NET_ADMIN); NOT firewalled." >&2
fi
exec "$@"