blob: 59c4b59fcee79e4a73473af5f68e24fca86d2060 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
Lorenz Brun52f7f292020-06-24 16:42:02 +02002// SPDX-License-Identifier: Apache-2.0
Lorenz Brun52f7f292020-06-24 16:42:02 +02003
4// nanoswitch is a virtualized switch/router combo intended for testing.
Serge Bazanski216fe7b2021-05-21 18:36:16 +02005// It uses the first interface as an external interface to connect to the host
6// and pass traffic in and out. All other interfaces are switched together and
7// served by a built-in DHCP server. Traffic from that network to the
8// SLIRP/external network is SNATed as the host-side SLIRP ignores routed
9// packets.
Serge Bazanskibe742842022-04-04 13:18:50 +020010//
11// It also has built-in userspace proxying support for accessing the first
12// node's services, as well as a SOCKS proxy to access all nodes within the
13// network.
Lorenz Brun52f7f292020-06-24 16:42:02 +020014package main
15
16import (
17 "bytes"
18 "context"
19 "fmt"
20 "io"
Lorenz Brun52f7f292020-06-24 16:42:02 +020021 "net"
22 "os"
23 "time"
24
25 "github.com/google/nftables"
26 "github.com/google/nftables/expr"
27 "github.com/insomniacslk/dhcp/dhcpv4"
28 "github.com/insomniacslk/dhcp/dhcpv4/server4"
29 "github.com/vishvananda/netlink"
Lorenz Brun52f7f292020-06-24 16:42:02 +020030
Serge Bazanski31370b02021-01-07 16:31:14 +010031 common "source.monogon.dev/metropolis/node"
32 "source.monogon.dev/metropolis/node/core/network/dhcp4c"
33 dhcpcb "source.monogon.dev/metropolis/node/core/network/dhcp4c/callback"
Tim Windelschmidt4f586b52025-04-02 15:04:10 +020034 "source.monogon.dev/osbase/bringup"
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020035 "source.monogon.dev/osbase/supervisor"
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +010036 "source.monogon.dev/osbase/test/qemu"
Lorenz Brun52f7f292020-06-24 16:42:02 +020037)
38
39var switchIP = net.IP{10, 1, 0, 1}
40var switchSubnetMask = net.CIDRMask(24, 32)
41
Serge Bazanski216fe7b2021-05-21 18:36:16 +020042// defaultLeaseOptions sets the lease options needed to properly configure
43// connectivity to nanoswitch.
Lorenz Brun52f7f292020-06-24 16:42:02 +020044func defaultLeaseOptions(reply *dhcpv4.DHCPv4) {
45 reply.GatewayIPAddr = switchIP
Serge Bazanski216fe7b2021-05-21 18:36:16 +020046 // SLIRP fake DNS server.
47 reply.UpdateOption(dhcpv4.OptDNS(net.IPv4(10, 42, 0, 3)))
Lorenz Brun52f7f292020-06-24 16:42:02 +020048 reply.UpdateOption(dhcpv4.OptRouter(switchIP))
Serge Bazanski216fe7b2021-05-21 18:36:16 +020049 // Make sure we exercise our DHCP client in E2E tests.
50 reply.UpdateOption(dhcpv4.OptIPAddressLeaseTime(30 * time.Second))
Lorenz Brun52f7f292020-06-24 16:42:02 +020051 reply.UpdateOption(dhcpv4.OptSubnetMask(switchSubnetMask))
52}
53
Serge Bazanski216fe7b2021-05-21 18:36:16 +020054// runDHCPServer runs an extremely minimal DHCP server with most options
55// hardcoded, a wrapping bump allocator for the IPs, 30 second lease timeout
56// and no support for DHCP collision detection.
Lorenz Brun52f7f292020-06-24 16:42:02 +020057func runDHCPServer(link netlink.Link) supervisor.Runnable {
Serge Bazanski3e5e5802022-06-21 13:46:31 +020058 currentIP := net.IP{10, 1, 0, 2}
Lorenz Brun52f7f292020-06-24 16:42:02 +020059
Serge Bazanskid279dc02022-05-06 12:17:42 +020060 // Map from stringified MAC address to IP address, allowing handing out the
61 // same IP to a given MAC on re-discovery.
62 leases := make(map[string]net.IP)
63
Lorenz Brun52f7f292020-06-24 16:42:02 +020064 return func(ctx context.Context) error {
65 laddr := net.UDPAddr{
66 IP: net.IPv4(0, 0, 0, 0),
67 Port: 67,
68 }
69 server, err := server4.NewServer(link.Attrs().Name, &laddr, func(conn net.PacketConn, peer net.Addr, m *dhcpv4.DHCPv4) {
70 if m == nil {
71 return
72 }
73 reply, err := dhcpv4.NewReplyFromRequest(m)
74 if err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +010075 supervisor.Logger(ctx).Warningf("Failed to generate DHCP reply: %v", err)
Lorenz Brun52f7f292020-06-24 16:42:02 +020076 return
77 }
78 reply.UpdateOption(dhcpv4.OptServerIdentifier(switchIP))
79 reply.ServerIPAddr = switchIP
80
81 switch m.MessageType() {
82 case dhcpv4.MessageTypeDiscover:
83 reply.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeOffer))
84 defaultLeaseOptions(reply)
Serge Bazanskid279dc02022-05-06 12:17:42 +020085 hwaddr := m.ClientHWAddr.String()
86 // Either hand out already allocated address from leases, or allocate new.
87 if ip, ok := leases[hwaddr]; ok {
88 reply.YourIPAddr = ip
89 } else {
Serge Bazanski3e5e5802022-06-21 13:46:31 +020090 leases[hwaddr] = net.ParseIP(currentIP.String())
91 reply.YourIPAddr = leases[hwaddr]
Serge Bazanskid279dc02022-05-06 12:17:42 +020092 currentIP[3]++ // Works only because it's a /24
93 }
94 supervisor.Logger(ctx).Infof("Replying with DHCP IP %s to %s", reply.YourIPAddr.String(), hwaddr)
Lorenz Brun52f7f292020-06-24 16:42:02 +020095 case dhcpv4.MessageTypeRequest:
96 reply.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeAck))
97 defaultLeaseOptions(reply)
Lorenz Brundbac6cc2020-11-30 10:57:26 +010098 if m.RequestedIPAddress() != nil {
99 reply.YourIPAddr = m.RequestedIPAddress()
100 } else {
101 reply.YourIPAddr = m.ClientIPAddr
102 }
Lorenz Brun52f7f292020-06-24 16:42:02 +0200103 case dhcpv4.MessageTypeRelease, dhcpv4.MessageTypeDecline:
104 supervisor.Logger(ctx).Info("Ignoring Release/Decline")
105 }
106 if _, err := conn.WriteTo(reply.ToBytes(), peer); err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +0100107 supervisor.Logger(ctx).Warningf("Cannot reply to client: %v", err)
Lorenz Brun52f7f292020-06-24 16:42:02 +0200108 }
109 })
110 if err != nil {
111 return err
112 }
113 supervisor.Signal(ctx, supervisor.SignalHealthy)
114 go func() {
115 <-ctx.Done()
116 server.Close()
117 }()
118 return server.Serve()
119 }
120}
121
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200122// userspaceProxy listens on port and proxies all TCP connections to the same
123// port on targetIP
Serge Bazanski52304a82021-10-29 16:56:18 +0200124func userspaceProxy(targetIP net.IP, port common.Port) supervisor.Runnable {
Lorenz Brun52f7f292020-06-24 16:42:02 +0200125 return func(ctx context.Context) error {
126 logger := supervisor.Logger(ctx)
127 tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(0, 0, 0, 0), Port: int(port)})
128 if err != nil {
129 return err
130 }
131 supervisor.Signal(ctx, supervisor.SignalHealthy)
132 go func() {
133 <-ctx.Done()
134 tcpListener.Close()
135 }()
136 for {
137 conn, err := tcpListener.AcceptTCP()
138 if err != nil {
139 if ctx.Err() != nil {
140 return ctx.Err()
141 }
142 return err
143 }
144 go func(conn *net.TCPConn) {
145 defer conn.Close()
146 upstreamConn, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: targetIP, Port: int(port)})
147 if err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +0100148 logger.Infof("Userspace proxy failed to connect to upstream: %v", err)
Lorenz Brun52f7f292020-06-24 16:42:02 +0200149 return
150 }
151 defer upstreamConn.Close()
152 go io.Copy(upstreamConn, conn)
153 io.Copy(conn, upstreamConn)
154 }(conn)
155 }
156
157 }
158}
159
160// addNetworkRoutes sets up routing from DHCP
161func addNetworkRoutes(link netlink.Link, addr net.IPNet, gw net.IP) error {
162 if err := netlink.AddrReplace(link, &netlink.Addr{IPNet: &addr}); err != nil {
163 return fmt.Errorf("failed to add DHCP address to network interface \"%v\": %w", link.Attrs().Name, err)
164 }
165
166 if gw.IsUnspecified() {
167 return nil
168 }
169
170 route := &netlink.Route{
171 Dst: &net.IPNet{IP: net.IPv4(0, 0, 0, 0), Mask: net.IPv4Mask(0, 0, 0, 0)},
172 Gw: gw,
173 Scope: netlink.SCOPE_UNIVERSE,
174 }
175 if err := netlink.RouteAdd(route); err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200176 return fmt.Errorf("could not add default route: netlink.RouteAdd(%+v): %w", route, err)
Lorenz Brun52f7f292020-06-24 16:42:02 +0200177 }
178 return nil
179}
180
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200181// nfifname converts an interface name into 16 bytes padded with zeroes (for
182// nftables)
Lorenz Brun52f7f292020-06-24 16:42:02 +0200183func nfifname(n string) []byte {
184 b := make([]byte, 16)
Tim Windelschmidt5e460a92024-04-11 01:33:09 +0200185 copy(b, n+"\x00")
Lorenz Brun52f7f292020-06-24 16:42:02 +0200186 return b
187}
188
189func main() {
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200190 bringup.Runnable(root).Run()
191}
192
193func root(ctx context.Context) (err error) {
194 logger := supervisor.Logger(ctx)
195 logger.Info("Starting NanoSwitch, a tiny TOR switch emulator")
196
197 c := &nftables.Conn{}
198
199 links, err := netlink.LinkList()
Lorenz Brundf952412020-12-21 14:59:36 +0100200 if err != nil {
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200201 logger.Fatalf("Failed to list links: %v", err)
Lorenz Brundf952412020-12-21 14:59:36 +0100202 }
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200203 var externalLink netlink.Link
204 var vmLinks []netlink.Link
205 for _, link := range links {
206 attrs := link.Attrs()
207 if link.Type() == "device" && len(attrs.HardwareAddr) > 0 {
208 if attrs.Flags&net.FlagUp != net.FlagUp {
209 netlink.LinkSetUp(link) // Attempt to take up all ethernet links
Lorenz Brun52f7f292020-06-24 16:42:02 +0200210 }
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200211 if bytes.Equal(attrs.HardwareAddr, qemu.HostInterfaceMAC) {
212 externalLink = link
213 } else {
214 vmLinks = append(vmLinks, link)
Lorenz Brun52f7f292020-06-24 16:42:02 +0200215 }
216 }
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200217 }
218 vmBridgeLink := &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: "vmbridge", Flags: net.FlagUp}}
219 if err := netlink.LinkAdd(vmBridgeLink); err != nil {
220 logger.Fatalf("Failed to create vmbridge: %v", err)
221 }
222 for _, link := range vmLinks {
223 if err := netlink.LinkSetMaster(link, vmBridgeLink); err != nil {
224 logger.Fatalf("Failed to add VM interface to bridge: %v", err)
225 }
226 logger.Infof("Assigned interface %s to bridge", link.Attrs().Name)
227 }
228 if err := netlink.AddrReplace(vmBridgeLink, &netlink.Addr{IPNet: &net.IPNet{IP: switchIP, Mask: switchSubnetMask}}); err != nil {
229 logger.Fatalf("Failed to assign static IP to vmbridge: %v", err)
230 }
231 if externalLink != nil {
232 nat := c.AddTable(&nftables.Table{
233 Family: nftables.TableFamilyIPv4,
234 Name: "nat",
235 })
Lorenz Brun52f7f292020-06-24 16:42:02 +0200236
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200237 postrouting := c.AddChain(&nftables.Chain{
238 Name: "postrouting",
239 Hooknum: nftables.ChainHookPostrouting,
240 Priority: nftables.ChainPriorityNATSource,
241 Table: nat,
242 Type: nftables.ChainTypeNAT,
243 })
Lorenz Brun52f7f292020-06-24 16:42:02 +0200244
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200245 // Masquerade/SNAT all traffic going out of the external interface
246 c.AddRule(&nftables.Rule{
247 Table: nat,
248 Chain: postrouting,
249 Exprs: []expr.Any{
250 &expr.Meta{Key: expr.MetaKeyOIFNAME, Register: 1},
251 &expr.Cmp{
252 Op: expr.CmpOpEq,
253 Register: 1,
254 Data: nfifname(externalLink.Attrs().Name),
Lorenz Brun52f7f292020-06-24 16:42:02 +0200255 },
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200256 &expr.Masq{},
257 },
258 })
Lorenz Brun52f7f292020-06-24 16:42:02 +0200259
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200260 if err := c.Flush(); err != nil {
261 panic(err)
Lorenz Brun52f7f292020-06-24 16:42:02 +0200262 }
Tim Windelschmidt4f586b52025-04-02 15:04:10 +0200263
264 netIface := &net.Interface{
265 Name: externalLink.Attrs().Name,
266 MTU: externalLink.Attrs().MTU,
267 Index: externalLink.Attrs().Index,
268 Flags: externalLink.Attrs().Flags,
269 HardwareAddr: externalLink.Attrs().HardwareAddr,
270 }
271 dhcpClient, err := dhcp4c.NewClient(netIface)
272 if err != nil {
273 logger.Fatalf("Failed to create DHCP client: %v", err)
274 }
275 dhcpClient.RequestedOptions = []dhcpv4.OptionCode{dhcpv4.OptionRouter}
276 dhcpClient.LeaseCallback = dhcpcb.Compose(dhcpcb.ManageIP(externalLink), dhcpcb.ManageRoutes(externalLink))
277 supervisor.Run(ctx, "dhcp-client", dhcpClient.Run)
278 if err := os.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1\n"), 0644); err != nil {
279 logger.Fatalf("Failed to write ip forwards: %v", err)
280 }
281 } else {
282 logger.Info("No upstream interface detected")
283 }
284 supervisor.Run(ctx, "dhcp-server", runDHCPServer(vmBridgeLink))
285 supervisor.Run(ctx, "proxy-cur1", userspaceProxy(net.IPv4(10, 1, 0, 2), common.CuratorServicePort))
286 supervisor.Run(ctx, "proxy-dbg1", userspaceProxy(net.IPv4(10, 1, 0, 2), common.DebugServicePort))
287 supervisor.Run(ctx, "proxy-k8s-api1", userspaceProxy(net.IPv4(10, 1, 0, 2), common.KubernetesAPIPort))
288 supervisor.Run(ctx, "proxy-k8s-api-wrapped1", userspaceProxy(net.IPv4(10, 1, 0, 2), common.KubernetesAPIWrappedPort))
289 supervisor.Run(ctx, "socks", runSOCKSProxy)
290 supervisor.Signal(ctx, supervisor.SignalHealthy)
291 supervisor.Signal(ctx, supervisor.SignalDone)
292 return nil
Lorenz Brun52f7f292020-06-24 16:42:02 +0200293}