xref: /aosp_15_r20/external/crosvm/tools/examples/setup_network (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
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
6# Set up networking on the host using a TAP device. This probably works on
7# many ubuntu or debian machines, but highly depends on the existing network
8# configuration.
9
10setup_network() {
11    # ANCHOR: setup_tap
12    sudo ip tuntap add mode tap user "$USER" vnet_hdr crosvm_tap
13    sudo ip addr add 192.168.10.1/24 dev crosvm_tap
14    sudo ip link set crosvm_tap up
15    # ANCHOR_END: setup_tap
16
17    # ANCHOR: setup_routing
18    sudo sysctl net.ipv4.ip_forward=1
19    # Network interface used to connect to the internet.
20    HOST_DEV=$(ip route get 8.8.8.8 | awk -- '{printf $5}')
21    sudo iptables -t nat -A POSTROUTING -o "${HOST_DEV}" -j MASQUERADE
22    sudo iptables -A FORWARD -i "${HOST_DEV}" -o crosvm_tap -m state --state RELATED,ESTABLISHED -j ACCEPT
23    sudo iptables -A FORWARD -i crosvm_tap -o "${HOST_DEV}" -j ACCEPT
24    # ANCHOR_END: setup_routing
25}
26
27echo "This will set up a tap device 'crosvm_tap'."
28echo
29echo "It will run the following commands:"
30echo
31type setup_network | sed '1,3d;$d'
32echo
33read -p "Continue [y/N]? " -r
34if [[ ! $REPLY =~ ^[Yy]$ ]]; then
35    exit 0
36fi
37
38set -ex
39setup_network
40