如何限制特定可执行文件的互联网访问,同时保留局域网权限
Great question—this is a super common scenario when you want to lock down an app's external connectivity without breaking local network functionality. Let's build on the options you've already explored and deliver simple, actionable solutions:
1. Tweaked AppArmor Profile (Your Closest Match, Now With LAN Access)
Since you mentioned AppArmor was almost there, here's how to modify a profile to explicitly allow your local subnet while blocking all other outgoing internet traffic:
Step 1: Create/Edit the AppArmor Profile
Open a profile for your app (replace /path/to/your/app.exe with the actual path):
sudo nano /etc/apparmor.d/local/usr.bin.your-app-name
Step 2: Add LAN Allow + Internet Block Rules
Paste these lines (adjust 192.168.1.0/24 to match your local subnet—use ip addr to find your LAN range):
# Allow full LAN access (TCP/UDP) network inet tcp dst 192.168.1.0/24, network inet udp dst 192.168.1.0/24, # Block all other outgoing internet traffic network inet tcp deny, network inet udp deny,
Step 3: Load the Profile & Enforce It
sudo apparmor_parser -r /etc/apparmor.d/usr.bin.your-app-name sudo aa-enforce /path/to/your/app.exe
Pro tip: Use aa-complain instead of aa-enforce first if you want to test the rules without blocking anything immediately.
2. Improved unshare -n Method (Isolated Network Namespace)
The basic unshare -n cuts off all network access, but we can add LAN connectivity manually to the isolated namespace. Here's an automated script to simplify this:
Automated Script
Create a small bash script (save as run-app-lan-only.sh):
#!/bin/bash # Configure these variables to match your setup LAN_SUBNET="192.168.1.0/24" NETWORK_INTERFACE="eth0" # Or wlan0 for Wi-Fi APP_PATH="/path/to/your/app.exe" # Launch app in isolated namespace with LAN access only unshare -n bash -c " ip link set $NETWORK_INTERFACE up # Re-add your local IP to the namespace ip addr add $(ip addr show $NETWORK_INTERFACE | grep 'inet ' | awk '{print $2}') dev $NETWORK_INTERFACE # Add route for LAN subnet ip route add $LAN_SUBNET dev $NETWORK_INTERFACE # Run your app $APP_PATH "
Make it executable and run:
chmod +x run-app-lan-only.sh sudo ./run-app-lan-only.sh
3. Simple IPTables Rule (Quickest One-Off Solution)
If you want a no-fuss, temporary fix (or persistent if you save the rules), use IPTables' owner module to target the app directly:
# Allow LAN traffic for the app sudo iptables -A OUTPUT -m owner --exe-path /path/to/your/app.exe -d 192.168.1.0/24 -j ACCEPT # Block all other outgoing traffic for the app sudo iptables -A OUTPUT -m owner --exe-path /path/to/your/app.exe ! -d 192.168.1.0/24 -j DROP
Note for Wine Users
If your .exe runs via Wine, replace --exe-path with --pid-owner targeting the Wine process, or stick with the AppArmor method—it’s more reliable for Wine-managed apps.
内容的提问来源于stack exchange,提问作者Ignatiamus

