| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | @@ -186,7 +186,9 @@ func templateArgs(ctx context.Context, bootScripts bool, instDir, name string, i |
| 6 | return nil, err |
| 7 | } |
| 8 | args.SlirpGateway = usernet.GatewayIP(subnet) |
| 9 | - if *instConfig.VMType == limatype.VZ { |
| 10 | + // QEMU too has its own gvisor netstack (startUsernet), whose gateway |
| 11 | + // answers DNS. |
| 12 | + if *instConfig.VMType == limatype.VZ || *instConfig.VMType == limatype.QEMU { |
| 13 | args.SlirpDNS = usernet.GatewayIP(subnet) |
| 14 | } else { |
| 15 | args.SlirpDNS = usernet.DNSIP(subnet) |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | @@ -47,6 +47,9 @@ type Config struct { |
| 21 | SSHLocalPort int |
| 22 | SSHAddress string |
| 23 | VirtioGA bool |
| 24 | + // UsernetQEMUSock is the QEMU socket of the instance's own gvisor |
| 25 | + // netstack, used instead of slirp when set (see startUsernet). |
| 26 | + UsernetQEMUSock string |
| 27 | } |
| 28 | |
| 29 | // minimumQemuVersion returns hardMin and softMin. |
| 30 | @@ -802,10 +805,21 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er |
| 31 | // Network |
| 32 | // Configure default usernetwork with limayaml.MACAddress(driver.Instance.Dir) for eth0 interface |
| 33 | firstUsernetIndex := limayaml.FirstUsernetIndex(y) |
| 34 | - if firstUsernetIndex == -1 { |
| 35 | + switch { |
| 36 | + case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "" && runtime.GOOS == "windows": |
| 37 | + // No file descriptor passing there (fd_connect): QEMU connects to the |
| 38 | + // socket itself, which QEMU 7.2 or later can on Windows. The same |
| 39 | + // stream as the socket netdev's. |
| 40 | + if !strings.Contains(string(features.NetdevHelp), "stream") { |
| 41 | + return "", nil, errors.New("QEMU 7.2 or later is needed (its stream netdev)") |
| 42 | + } |
| 43 | + args = append(args, "-netdev", fmt.Sprintf("stream,id=net0,server=off,addr.type=unix,addr.path=%s", cfg.UsernetQEMUSock)) |
| 44 | + case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "": |
| 45 | + args = append(args, "-netdev", fmt.Sprintf("socket,id=net0,fd={{ fd_connect %q }}", cfg.UsernetQEMUSock)) |
| 46 | + case firstUsernetIndex == -1: |
| 47 | args = append(args, "-netdev", fmt.Sprintf("user,id=net0,net=%s,dhcpstart=%s,hostfwd=tcp:%s:%d-:22", |
| 48 | networks.SlirpNetwork, networks.SlirpIPAddress, cfg.SSHAddress, cfg.SSHLocalPort)) |
| 49 | - } else { |
| 50 | + default: |
| 51 | qemuSock, err := usernet.Sock(y.Networks[firstUsernetIndex].Lima, usernet.QEMUSock) |
| 52 | if err != nil { |
| 53 | return "", nil, err |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | @@ -41,6 +41,7 @@ import ( |
| 59 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 60 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 61 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 62 | + "github.com/lima-vm/lima/v2/pkg/networks" |
| 63 | "github.com/lima-vm/lima/v2/pkg/networks/usernet" |
| 64 | "github.com/lima-vm/lima/v2/pkg/osutil" |
| 65 | "github.com/lima-vm/lima/v2/pkg/reflectutil" |
| 66 | @@ -60,6 +61,46 @@ type LimaQemuDriver struct { |
| 67 | |
| 68 | swtpmCmd *exec.Cmd |
| 69 | swtpmWaitCh chan error |
| 70 | + |
| 71 | + // The instance's own gvisor netstack (startUsernet), as with vz. |
| 72 | + usernetClient *usernet.Client |
| 73 | + usernetStop context.CancelFunc |
| 74 | +} |
| 75 | + |
| 76 | +// startUsernet starts the instance's own gvisor netstack, as vz does: one |
| 77 | +// network per instance, in the hostagent, where usernet.Outbound applies. |
| 78 | +func startUsernet(ctx context.Context, inst *limatype.Instance) (client *usernet.Client, qemuSock string, stop context.CancelFunc, err error) { |
| 79 | + endpointSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock) |
| 80 | + if err != nil { |
| 81 | + return nil, "", nil, err |
| 82 | + } |
| 83 | + qemuSock, err = usernet.SockWithDirectory(inst.Dir, "", usernet.QEMUSock) |
| 84 | + if err != nil { |
| 85 | + return nil, "", nil, err |
| 86 | + } |
| 87 | + os.RemoveAll(endpointSock) |
| 88 | + os.RemoveAll(qemuSock) |
| 89 | + ctx, stop = context.WithCancel(ctx) |
| 90 | + err = usernet.StartGVisorNetstack(ctx, &usernet.GVisorNetstackOpts{ |
| 91 | + MTU: 1500, |
| 92 | + Endpoint: endpointSock, |
| 93 | + QemuSocket: qemuSock, |
| 94 | + Async: true, |
| 95 | + DefaultLeases: map[string]string{ |
| 96 | + networks.SlirpIPAddress: limayaml.MACAddress(inst.Dir), |
| 97 | + }, |
| 98 | + Subnet: networks.SlirpNetwork, |
| 99 | + }) |
| 100 | + if err != nil { |
| 101 | + stop() |
| 102 | + return nil, "", nil, err |
| 103 | + } |
| 104 | + subnetIP, _, err := net.ParseCIDR(networks.SlirpNetwork) |
| 105 | + if err != nil { |
| 106 | + stop() |
| 107 | + return nil, "", nil, err |
| 108 | + } |
| 109 | + return usernet.NewClient(endpointSock, subnetIP), qemuSock, stop, nil |
| 110 | } |
| 111 | |
| 112 | var _ driver.Driver = (*LimaQemuDriver)(nil) |
| 113 | @@ -324,6 +365,18 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { |
| 114 | SSHAddress: l.Instance.SSHAddress, |
| 115 | VirtioGA: l.virtioPort != "", |
| 116 | } |
| 117 | + if limayaml.FirstUsernetIndex(l.Instance.Config) == -1 { |
| 118 | + client, sock, stop, err := startUsernet(ctx, l.Instance) |
| 119 | + if err != nil { |
| 120 | + return nil, err |
| 121 | + } |
| 122 | + l.usernetClient, l.usernetStop, qCfg.UsernetQEMUSock = client, stop, sock |
| 123 | + defer func() { |
| 124 | + if l.qCmd == nil { |
| 125 | + stop() |
| 126 | + } |
| 127 | + }() |
| 128 | + } |
| 129 | qExe, qArgs, err := Cmdline(ctx, qCfg) |
| 130 | if err != nil { |
| 131 | return nil, err |
| 132 | @@ -443,12 +496,19 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { |
| 133 | go func() { |
| 134 | defer close(l.qWaitCh) |
| 135 | defer cancel() |
| 136 | - l.qWaitCh <- qCmd.Wait() |
| 137 | + err := qCmd.Wait() |
| 138 | + if l.usernetStop != nil { |
| 139 | + l.usernetStop() |
| 140 | + } |
| 141 | + l.qWaitCh <- err |
| 142 | }() |
| 143 | l.vhostCmds = vhostCmds |
| 144 | go func() { |
| 145 | + client := l.usernetClient |
| 146 | if usernetIndex := limayaml.FirstUsernetIndex(l.Instance.Config); usernetIndex != -1 { |
| 147 | - client := usernet.NewClientByName(l.Instance.Config.Networks[usernetIndex].Lima) |
| 148 | + client = usernet.NewClientByName(l.Instance.Config.Networks[usernetIndex].Lima) |
| 149 | + } |
| 150 | + if client != nil { |
| 151 | err := client.ConfigureDriver(ctx, l.Instance, l.SSHLocalPort) |
| 152 | if err != nil { |
| 153 | l.qWaitCh <- err |
| 154 | @@ -716,8 +776,11 @@ func (l *LimaQemuDriver) killSwtpm() error { |
| 155 | func (l *LimaQemuDriver) shutdownQEMU(ctx context.Context, timeout time.Duration, qCmd *exec.Cmd, qWaitCh <-chan error) error { |
| 156 | // "power button" refers to ACPI on the most archs, except RISC-V |
| 157 | logrus.Info("Shutting down QEMU with the power button") |
| 158 | + client := l.usernetClient |
| 159 | if usernetIndex := limayaml.FirstUsernetIndex(l.Instance.Config); usernetIndex != -1 { |
| 160 | - client := usernet.NewClientByName(l.Instance.Config.Networks[usernetIndex].Lima) |
| 161 | + client = usernet.NewClientByName(l.Instance.Config.Networks[usernetIndex].Lima) |
| 162 | + } |
| 163 | + if client != nil { |
| 164 | err := client.UnExposeSSH(l.SSHLocalPort) |
| 165 | if err != nil { |
| 166 | logrus.Warnf("Failed to remove SSH binding for port %d", l.SSHLocalPort) |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | @@ -29,6 +29,15 @@ const ( |
| 172 | UDP Network = "udp" |
| 173 | ) |
| 174 | |
| 175 | +// Names, when set by the program running the hostagent, decides the names the |
| 176 | +// guest may resolve: another gets NXDOMAIN, and is never asked upstream. |
| 177 | +// Answered is told of the addresses given for each name (without the final |
| 178 | +// dot), so that a policy can let the guest reach those only. |
| 179 | +var ( |
| 180 | + Names func(name string) bool |
| 181 | + Answered func(name string, ips []net.IP) |
| 182 | +) |
| 183 | + |
| 184 | type HandlerOptions struct { |
| 185 | IPv6 bool |
| 186 | StaticHosts map[string]string |
| 187 | @@ -150,6 +159,11 @@ func (h *Handler) handleQuery(ctx context.Context, w dns.ResponseWriter, req *dn |
| 188 | reply.SetReply(req) |
| 189 | logrus.Tracef("handleQuery received DNS query: %v", req) |
| 190 | for _, q := range req.Question { |
| 191 | + if Names != nil && !Names(strings.TrimSuffix(q.Name, ".")) { |
| 192 | + reply.SetRcode(req, dns.RcodeNameError) |
| 193 | + handled = true |
| 194 | + continue |
| 195 | + } |
| 196 | hdr := dns.RR_Header{ |
| 197 | Name: q.Name, |
| 198 | Rrtype: q.Qtype, |
| 199 | @@ -181,6 +195,9 @@ func (h *Handler) handleQuery(ctx context.Context, w dns.ResponseWriter, req *dn |
| 200 | continue |
| 201 | } |
| 202 | } |
| 203 | + if Answered != nil { |
| 204 | + Answered(strings.TrimSuffix(q.Name, "."), addrs) |
| 205 | + } |
| 206 | for _, ip := range addrs { |
| 207 | var a dns.RR |
| 208 | ipv6 := ip.To4() == nil |
| 209 | |
| 210 | new file mode 100644 |
| 211 | |
| 212 | |
| 213 | |
| 214 | @@ -0,0 +1,43 @@ |
| 215 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 216 | +// SPDX-License-Identifier: Apache-2.0 |
| 217 | + |
| 218 | +package dns |
| 219 | + |
| 220 | +import ( |
| 221 | + "net" |
| 222 | + "runtime" |
| 223 | + "testing" |
| 224 | + |
| 225 | + "github.com/miekg/dns" |
| 226 | + "gotest.tools/v3/assert" |
| 227 | +) |
| 228 | + |
| 229 | +// A name Names refuses gets NXDOMAIN, without a lookup; one it allows is |
| 230 | +// answered, and Answered told of its addresses. |
| 231 | +func TestNamesAnswered(t *testing.T) { |
| 232 | + if runtime.GOOS == "windows" { |
| 233 | + t.Skip() |
| 234 | + } |
| 235 | + h, err := NewHandler(HandlerOptions{StaticHosts: map[string]string{"ok.test": "192.0.2.1", "no.test": "192.0.2.2"}}) |
| 236 | + assert.NilError(t, err) |
| 237 | + told := map[string][]net.IP{} |
| 238 | + Names = func(name string) bool { return name == "ok.test" } |
| 239 | + Answered = func(name string, ips []net.IP) { told[name] = ips } |
| 240 | + t.Cleanup(func() { Names, Answered = nil, nil }) |
| 241 | + |
| 242 | + w := new(TestResponseWriter) |
| 243 | + req := new(dns.Msg) |
| 244 | + req.SetQuestion("no.test.", dns.TypeA) |
| 245 | + h.ServeDNS(w, req) |
| 246 | + assert.Equal(t, dnsResult.Rcode, dns.RcodeNameError) |
| 247 | + assert.Equal(t, len(dnsResult.Answer), 0) |
| 248 | + |
| 249 | + req = new(dns.Msg) |
| 250 | + req.SetQuestion("ok.test.", dns.TypeA) |
| 251 | + h.ServeDNS(w, req) |
| 252 | + assert.Equal(t, dnsResult.Rcode, dns.RcodeSuccess) |
| 253 | + assert.Equal(t, len(dnsResult.Answer), 1) |
| 254 | + assert.Equal(t, told["ok.test"][0].String(), "192.0.2.1") |
| 255 | + _, asked := told["no.test"] |
| 256 | + assert.Assert(t, !asked) |
| 257 | +} |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | @@ -44,6 +44,7 @@ import ( |
| 263 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 264 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 265 | "github.com/lima-vm/lima/v2/pkg/networks" |
| 266 | + "github.com/lima-vm/lima/v2/pkg/networks/usernet" |
| 267 | "github.com/lima-vm/lima/v2/pkg/osutil" |
| 268 | "github.com/lima-vm/lima/v2/pkg/portfwd" |
| 269 | "github.com/lima-vm/lima/v2/pkg/sshutil" |
| 270 | @@ -419,6 +420,10 @@ func (a *HostAgent) Run(ctx context.Context) error { |
| 271 | hosts["host.lima.internal"] = networks.SlirpGateway |
| 272 | name := hostname.FromInstName(a.instName) // TODO: support customization |
| 273 | hosts[name] = networks.SlirpIPAddress |
| 274 | + // The guest reaches this server on the host's loopback, past any |
| 275 | + // usernet.Outbound policy. |
| 276 | + usernet.AllowHostService("udp", a.udpDNSLocalPort) |
| 277 | + usernet.AllowHostService("tcp", a.tcpDNSLocalPort) |
| 278 | srvOpts := dns.ServerOptions{ |
| 279 | UDPPort: a.udpDNSLocalPort, |
| 280 | TCPPort: a.tcpDNSLocalPort, |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | @@ -10,10 +10,12 @@ import ( |
| 286 | "fmt" |
| 287 | "net" |
| 288 | "net/http" |
| 289 | + "net/netip" |
| 290 | "os" |
| 291 | "runtime" |
| 292 | "strconv" |
| 293 | "strings" |
| 294 | + "sync" |
| 295 | "time" |
| 296 | |
| 297 | "github.com/balajiv113/fd" |
| 298 | @@ -42,6 +44,42 @@ var opts *GVisorNetstackOpts |
| 299 | |
| 300 | const gatewayMacAddr = "5a:94:ef:e4:0c:dd" |
| 301 | |
| 302 | +// Outbound, when set by the program running the hostagent, decides what the |
| 303 | +// guests of the per-instance netstacks may reach (types.Configuration.Outbound). |
| 304 | +// The host services the guest needs (AllowHostService) are reached past it. |
| 305 | +var Outbound types.Outbound |
| 306 | + |
| 307 | +// Names and Answered, when set by the program running the hostagent, are |
| 308 | +// applied by the gateway's DNS server of the per-instance netstacks to every |
| 309 | +// query it gets (types.Configuration.DNSNames and DNSAnswered). |
| 310 | +var ( |
| 311 | + Names func(name string) bool |
| 312 | + Answered func(name string, ips []net.IP) |
| 313 | +) |
| 314 | + |
| 315 | +type hostService struct { |
| 316 | + network string |
| 317 | + port uint16 |
| 318 | +} |
| 319 | + |
| 320 | +// hostServices are the ports of 127.0.0.1 the guest may always reach. |
| 321 | +var hostServices sync.Map |
| 322 | + |
| 323 | +// AllowHostService lets the guest reach port of 127.0.0.1 over network ("tcp" |
| 324 | +// or "udp") past Outbound: the hostagent's DNS server. |
| 325 | +func AllowHostService(network string, port int) { |
| 326 | + hostServices.Store(hostService{network, uint16(port)}, true) |
| 327 | +} |
| 328 | + |
| 329 | +func outbound(network string, dst netip.AddrPort) bool { |
| 330 | + if dst.Addr().Unmap() == netip.AddrFrom4([4]byte{127, 0, 0, 1}) { |
| 331 | + if _, ok := hostServices.Load(hostService{network, dst.Port()}); ok { |
| 332 | + return true |
| 333 | + } |
| 334 | + } |
| 335 | + return Outbound.Allows(network, dst) |
| 336 | +} |
| 337 | + |
| 338 | func StartGVisorNetstack(ctx context.Context, gVisorOpts *GVisorNetstackOpts) error { |
| 339 | opts = gVisorOpts |
| 340 | |
| 341 | @@ -81,6 +119,9 @@ func StartGVisorNetstack(ctx context.Context, gVisorOpts *GVisorNetstackOpts) er |
| 342 | gatewayIP: "127.0.0.1", |
| 343 | }, |
| 344 | GatewayVirtualIPs: []string{gatewayIP}, |
| 345 | + Outbound: outbound, |
| 346 | + DNSNames: Names, |
| 347 | + DNSAnswered: Answered, |
| 348 | } |
| 349 | |
| 350 | groupErrs, ctx := errgroup.WithContext(ctx) |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | @@ -5,6 +5,7 @@ package usernet |
| 356 | |
| 357 | import ( |
| 358 | "bufio" |
| 359 | + "net/netip" |
| 360 | "os" |
| 361 | "path" |
| 362 | "testing" |
| 363 | @@ -46,3 +47,26 @@ func createResolveFile(t *testing.T, file, content string) { |
| 364 | err = writer.Flush() |
| 365 | assert.NilError(t, err) |
| 366 | } |
| 367 | + |
| 368 | +// A host service is reached on 127.0.0.1, over its network and port only. |
| 369 | +func TestOutboundHostServices(t *testing.T) { |
| 370 | + saved := Outbound |
| 371 | + Outbound = func(string, netip.AddrPort) bool { return false } |
| 372 | + t.Cleanup(func() { Outbound = saved }) |
| 373 | + AllowHostService("udp", 54321) |
| 374 | + t.Cleanup(func() { hostServices.Delete(hostService{"udp", 54321}) }) |
| 375 | + |
| 376 | + for _, tc := range []struct { |
| 377 | + network, dst string |
| 378 | + want bool |
| 379 | + }{ |
| 380 | + {"udp", "127.0.0.1:54321", true}, |
| 381 | + {"udp", "[::ffff:127.0.0.1]:54321", true}, |
| 382 | + {"tcp", "127.0.0.1:54321", false}, |
| 383 | + {"udp", "127.0.0.1:54322", false}, |
| 384 | + {"udp", "127.0.0.2:54321", false}, |
| 385 | + {"udp", "[::1]:54321", false}, |
| 386 | + } { |
| 387 | + assert.Equal(t, outbound(tc.network, netip.MustParseAddrPort(tc.dst)), tc.want, "%s %s", tc.network, tc.dst) |
| 388 | + } |
| 389 | +} |