| 1 | package virtualnetwork |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/binary" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "math" |
| 10 | "net" |
| 11 | |
| 12 | "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 13 | log "github.com/sirupsen/logrus" |
| 14 | "gvisor.dev/gvisor/pkg/tcpip/header" |
| 15 | ) |
| 16 | |
| 17 | func (n *VirtualNetwork) AcceptVpnKit(conn net.Conn) error { |
| 18 | if err := vpnkitHandshake(conn, n.configuration); err != nil { |
| 19 | log.Error(err) |
| 20 | } |
| 21 | _ = n.networkSwitch.Accept(context.Background(), conn, types.HyperKitProtocol) |
| 22 | return nil |
| 23 | } |
| 24 | |
| 25 | func vpnkitHandshake(conn net.Conn, configuration *types.Configuration) error { |
| 26 | |
| 27 | msgInit := make([]byte, 49) |
| 28 | if _, err := io.ReadFull(conn, msgInit); err != nil { |
| 29 | return err |
| 30 | } |
| 31 | if _, err := conn.Write(msgInit); err != nil { |
| 32 | return err |
| 33 | } |
| 34 | |
| 35 | |
| 36 | msgCommand := make([]byte, 41) |
| 37 | if _, err := io.ReadFull(conn, msgCommand); err != nil { |
| 38 | return err |
| 39 | } |
| 40 | vpnkitUUID := string(msgCommand[1:37]) |
| 41 | log.Debugf("UUID sent by Hyperkit: %s", vpnkitUUID) |
| 42 | |
| 43 | |
| 44 | resp := make([]byte, 258) |
| 45 | resp[0] = 0x01 |
| 46 | |
| 47 | if configuration.MTU < 0 || configuration.MTU > math.MaxUint16 { |
| 48 | return fmt.Errorf("invalid MTU: %d", configuration.MTU) |
| 49 | } |
| 50 | mtu := uint16(configuration.MTU) |
| 51 | binary.LittleEndian.PutUint16(resp[1:3], mtu) |
| 52 | binary.LittleEndian.PutUint16(resp[3:5], mtu+header.EthernetMinimumSize) |
| 53 | |
| 54 | mac, err := macAddr(configuration, vpnkitUUID) |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | log.Debugf("Sending mac address: %s", mac.String()) |
| 59 | |
| 60 | copy(resp[5:11], mac) |
| 61 | |
| 62 | _, err = conn.Write(resp) |
| 63 | return err |
| 64 | } |
| 65 | |
| 66 | func macAddr(configuration *types.Configuration, vpnkitUUID string) (net.HardwareAddr, error) { |
| 67 | macStr, ok := configuration.VpnKitUUIDMacAddresses[vpnkitUUID] |
| 68 | if !ok { |
| 69 | return randomMac() |
| 70 | } |
| 71 | return net.ParseMAC(macStr) |
| 72 | } |
| 73 | |
| 74 | func randomMac() (net.HardwareAddr, error) { |
| 75 | buf := make([]byte, 6) |
| 76 | _, err := rand.Read(buf) |
| 77 | if err != nil { |
| 78 | return nil, err |
| 79 | } |
| 80 | |
| 81 | |
| 82 | buf[0] |= 2 |
| 83 | |
| 84 | |
| 85 | buf[0] &= ^byte(1) |
| 86 | |
| 87 | return buf, nil |
| 88 | } |