setup_network 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/bin/bash
  2. # Copyright 2022 The ChromiumOS Authors
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. # Set up networking on the host using a TAP device. This probably works on
  6. # many ubuntu or debian machines, but highly depends on the existing network
  7. # configuration.
  8. setup_network() {
  9. # ANCHOR: setup_tap
  10. sudo ip tuntap add mode tap user "$USER" vnet_hdr crosvm_tap
  11. sudo ip addr add 192.168.10.1/24 dev crosvm_tap
  12. sudo ip link set crosvm_tap up
  13. # ANCHOR_END: setup_tap
  14. # ANCHOR: setup_routing
  15. sudo sysctl net.ipv4.ip_forward=1
  16. # Network interface used to connect to the internet.
  17. HOST_DEV=$(ip route get 8.8.8.8 | awk -- '{printf $5}')
  18. sudo iptables -t nat -A POSTROUTING -o "${HOST_DEV}" -j MASQUERADE
  19. sudo iptables -A FORWARD -i "${HOST_DEV}" -o crosvm_tap -m state --state RELATED,ESTABLISHED -j ACCEPT
  20. sudo iptables -A FORWARD -i crosvm_tap -o "${HOST_DEV}" -j ACCEPT
  21. # ANCHOR_END: setup_routing
  22. }
  23. echo "This will set up a tap device 'crosvm_tap'."
  24. echo
  25. echo "It will run the following commands:"
  26. echo
  27. type setup_network | sed '1,3d;$d'
  28. echo
  29. read -p "Continue [y/N]? " -r
  30. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  31. exit 0
  32. fi
  33. set -ex
  34. setup_network