Skip to content

Instantly share code, notes, and snippets.

@PhilipSchmid
Last active April 29, 2020 11:30
Show Gist options
  • Save PhilipSchmid/55e40dba4e323e9236a1101a7d0d6abb to your computer and use it in GitHub Desktop.
Save PhilipSchmid/55e40dba4e323e9236a1101a7d0d6abb to your computer and use it in GitHub Desktop.
Automatically add Linux NIC to namespace at system boot (e.g. used for Ethernet USB dongles with dynamic identifier)

Linux NIC to namespace (persisted via systemd service)

Save the file nic-isolation.service to /etc/systemd/system/nic-isolation.service.

Afterwards reload the systemd daemon and enable & start the "service":

sudo systemctl daemon-reload
sudo systemctl enable nic-isolation.service
sudo systemctl start nic-isolation.service

TODO: Improve the security level by enabling some systemd security features: https://www.redhat.com/sysadmin/mastering-systemd

[Unit]
Description=Isolate USB NIC to separate namespace
After=syslog.target network.target
[Service]
Type=oneshot
PermissionsStartOnly=true
PIDFile=/var/run/nic-isolation.pid
ExecStartPre=-/bin/bash -c "/bin/systemctl set-environment USB_NIC=$(basename -a /sys/class/net/* | grep enx.*)"
ExecStart=-/bin/ip netns add isolation
ExecStart=-/bin/ip link set ${USB_NIC} netns isolation
ExecStart=-/bin/ip netns exec isolation ip link set lo up
ExecStart=-/bin/ip netns exec isolation ip link set ${USB_NIC} up
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment