Files
Reims-Go/internal/guesttools/management_test.go
T
root 403e2aeac0 fix(network): secure Npcap channels and enable bidirectional host access
Require AF_UNIX for bridge and management channels and reject legacy TCP restore paths before opening resources. Add per-adapter host delivery, Npcap receive injection, and checksum and segmentation handling for Ethernet and WLAN IPv4/IPv6 traffic.

Validation: full CI, targeted packetbridge/app tests, two live macOS VMs over Ethernet and WLAN, and Windows Firewall allow/block/default-deny checks with SMB 3.02 negotiation. Authenticated SMB file access and physical-display suspend/resume remain unverified.
2026-12-02 16:28:46 +08:00

302 lines
8.7 KiB
Go

package guesttools
import (
"bytes"
"context"
"encoding/binary"
"errors"
"io"
"net"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/testutil/socketdir"
)
func TestManagementRejectsLegacyBeforeOpeningOrReplacingEndpoints(t *testing.T) {
dir := socketdir.New(t)
out, in := filepath.Join(dir, "out.sock"), filepath.Join(dir, "in.sock")
srv := NewTransportServer(nil)
t.Cleanup(func() { _ = srv.Close(context.Background()) })
cfg := VMConfig{VMName: "test", VMDir: dir, QEMUPath: "unused", ManagementOutSock: out, ManagementInSock: in}
if _, err := srv.EnsureManagementNetwork(cfg); err != nil {
t.Fatal(err)
}
existing := srv.management[vmRegistryKey(cfg.DriverID, cfg.VMName)]
for _, tc := range []struct {
outSock, inSock string
outPort, inPort int
}{
{"", "", 12001, 12002},
{out, in, 0, 12002},
{out, "", 0, 0},
{"", in, 0, 0},
} {
bad := cfg
bad.ManagementOutSock, bad.ManagementInSock = tc.outSock, tc.inSock
bad.ManagementOutPort, bad.ManagementInPort = tc.outPort, tc.inPort
for _, open := range []func() error{
func() error { _, err := srv.EnsureManagementNetwork(bad); return err },
func() error {
_, err := newManagementRelay(tc.outSock, tc.inSock, tc.outPort, tc.inPort, dir, "unused", nil)
return err
},
} {
err := open()
coded, ok := err.(*i18n.CodedError)
if !ok || coded.Code != "E_NETWORK_LEGACY_TRANSPORT" {
t.Fatalf("旧通道未被前置检查拒绝: %v", err)
}
if srv.management[vmRegistryKey(cfg.DriverID, cfg.VMName)] != existing {
t.Fatal("非法配置替换了现有中继")
}
for _, path := range []string{out, in} {
if _, err := os.Stat(path); err != nil {
t.Fatalf("非法配置破坏了已有端点: %v", err)
}
}
}
}
}
func buildTestDHCPFrame(opts []byte) []byte {
dhcpLen := 240 + len(opts)
udpLen := 8 + dhcpLen
ipLen := 20 + udpLen
frame := make([]byte, 14+ipLen)
copy(frame[0:6], []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff})
copy(frame[6:12], []byte{0x52, 0x54, 0x00, 0x12, 0x34, 0x56})
binary.BigEndian.PutUint16(frame[12:14], 0x0800)
ip := frame[14:]
ip[0] = 0x45
binary.BigEndian.PutUint16(ip[2:4], uint16(ipLen))
ip[8] = 64
ip[9] = 17 // UDP
copy(ip[12:16], []byte{10, 0, 2, 2})
copy(ip[16:20], []byte{10, 0, 2, 15})
udp := ip[20:]
binary.BigEndian.PutUint16(udp[0:2], 67)
binary.BigEndian.PutUint16(udp[2:4], 68)
binary.BigEndian.PutUint16(udp[4:6], uint16(udpLen))
binary.BigEndian.PutUint16(udp[6:8], 0x1234) // non-zero sentinel to verify zeroing
dhcp := udp[8:]
dhcp[0] = 2 // BOOTREPLY
dhcp[1] = 1
dhcp[2] = 6
copy(dhcp[16:20], []byte{10, 0, 2, 15})
copy(dhcp[236:240], []byte{99, 130, 83, 99})
copy(dhcp[240:], opts)
return frame
}
func parseDHCPOptionCodes(frame []byte) []byte {
opts := frame[14+20+8+240:]
var codes []byte
for i := 0; i < len(opts); {
code := opts[i]
if code == 0 {
i++
continue
}
if code == 255 {
break
}
if i+1 >= len(opts) {
break
}
l := int(opts[i+1])
codes = append(codes, code)
i += 2 + l
}
return codes
}
func writeTestStreamFrame(w io.Writer, frame []byte) error {
var hdr [4]byte
binary.BigEndian.PutUint32(hdr[:], uint32(len(frame)))
if _, err := w.Write(hdr[:]); err != nil {
return err
}
_, err := w.Write(frame)
return err
}
func TestStripManagementRoutes(t *testing.T) {
opts := []byte{
53, 1, 5, // DHCP ACK (keep)
1, 4, 255, 255, 255, 0, // Subnet mask (keep)
3, 4, 10, 0, 2, 2, // Router (strip)
6, 4, 10, 0, 2, 3, // DNS (strip)
15, 4, 't', 'e', 's', 't', // Domain name (strip)
51, 4, 0, 0, 14, 16, // Lease time (keep)
54, 4, 10, 0, 2, 2, // Server ID (keep)
119, 3, 1, 'a', 0, // Domain search (strip)
121, 5, 0, 10, 0, 2, 2, // Classless route (strip)
249, 5, 0, 10, 0, 2, 2, // MS classless route (strip)
252, 4, 'h', 't', 't', 'p', // WPAD (strip)
255, // End
}
frame := buildTestDHCPFrame(opts)
orig := append([]byte(nil), frame...)
stripManagementRoutes(frame)
if bytes.Equal(frame, orig) {
t.Fatal("expected DHCP route/DNS options to be stripped")
}
got := parseDHCPOptionCodes(frame)
want := []byte{53, 1, 51, 54}
if !bytes.Equal(got, want) {
t.Fatalf("remaining DHCP options = %v, want %v", got, want)
}
// IPv4 UDP checksum must be zeroed after modifying DHCP payload in place.
udp := frame[14+20:]
if binary.BigEndian.Uint16(udp[6:8]) != 0 {
t.Fatalf("expected UDP checksum zeroed, got 0x%04x", binary.BigEndian.Uint16(udp[6:8]))
}
// Non-DHCP / short frames pass through unmodified.
short := []byte{1, 2, 3, 4}
shortCopy := append([]byte(nil), short...)
stripManagementRoutes(shortCopy)
if !bytes.Equal(shortCopy, short) {
t.Fatal("short frame should pass through unchanged")
}
}
func TestManagementRelayUnixAuth(t *testing.T) {
dir := socketdir.New(t)
outSock := filepath.Join(dir, "o.sock")
inSock := filepath.Join(dir, "i.sock")
if len(outSock) > 100 {
t.Fatalf("unexpectedly long temp socket path: %d bytes (%s)", len(outSock), outSock)
}
var allowPeer atomic.Bool
auth := func(_ context.Context, _ net.Conn, _, _ string) error {
if !allowPeer.Load() {
return errors.New("rogue peer denied")
}
return nil
}
relay, err := newManagementRelay(outSock, inSock, 0, 0, dir, `C:\dummy\qemu.exe`, auth)
if err != nil {
t.Fatalf("newManagementRelay: %v", err)
}
defer relay.close()
// 1. Rogue peer on outSock must be rejected and closed without delivering frames.
allowPeer.Store(false)
rogue, err := net.DialTimeout("unix", outSock, time.Second)
if err != nil {
t.Fatalf("dial rogue out: %v", err)
}
_ = writeTestStreamFrame(rogue, []byte("rogue-frame-should-not-pass"))
_ = rogue.SetReadDeadline(time.Now().Add(2 * time.Second))
buf := make([]byte, 1)
if _, rerr := rogue.Read(buf); rerr == nil {
t.Fatal("expected rogue peer connection to be closed by auth")
}
_ = rogue.Close()
// 2. Authorized outSock connects BEFORE inSock and sends a DHCP frame (early frame buffering).
allowPeer.Store(true)
outConn, err := net.DialTimeout("unix", outSock, time.Second)
if err != nil {
t.Fatalf("dial authorized out: %v", err)
}
defer outConn.Close()
dhcpFrame := buildTestDHCPFrame([]byte{
53, 1, 2, // DHCP OFFER
1, 4, 255, 255, 255, 0,
3, 4, 10, 0, 2, 2, // Router (must be stripped)
6, 4, 10, 0, 2, 3, // DNS (must be stripped)
255,
})
if err := writeTestStreamFrame(outConn, dhcpFrame); err != nil {
t.Fatalf("write early DHCP frame: %v", err)
}
time.Sleep(80 * time.Millisecond)
// 3. Rogue attempt on inSock while unauthorized must NOT steal the buffered frame.
allowPeer.Store(false)
rogueIn, err := net.DialTimeout("unix", inSock, time.Second)
if err != nil {
t.Fatalf("dial rogue in: %v", err)
}
_ = rogueIn.SetReadDeadline(time.Now().Add(2 * time.Second))
if _, rerr := io.ReadFull(rogueIn, make([]byte, 4)); rerr == nil {
t.Fatal("rogue inSock peer must not receive buffered frame")
}
_ = rogueIn.Close()
// 4. Authorized inSock connects and receives the buffered, route-stripped DHCP frame.
allowPeer.Store(true)
inConn, err := net.DialTimeout("unix", inSock, time.Second)
if err != nil {
t.Fatalf("dial authorized in: %v", err)
}
defer inConn.Close()
_ = inConn.SetReadDeadline(time.Now().Add(2 * time.Second))
var hdr [4]byte
if _, err := io.ReadFull(inConn, hdr[:]); err != nil {
t.Fatalf("read buffered frame header: %v", err)
}
n := binary.BigEndian.Uint32(hdr[:])
got := make([]byte, n)
if _, err := io.ReadFull(inConn, got); err != nil {
t.Fatalf("read buffered frame body: %v", err)
}
codes := parseDHCPOptionCodes(got)
if !bytes.Equal(codes, []byte{53, 1}) {
t.Fatalf("forwarded DHCP options = %v, want [53 1] (router/DNS stripped)", codes)
}
}
func TestManagementClosePreservesReplacementSockets(t *testing.T) {
dir := socketdir.New(t)
outSock, inSock := filepath.Join(dir, "o.sock"), filepath.Join(dir, "i.sock")
r, err := newManagementRelay(outSock, inSock, 0, 0, dir, "unused-qemu", nil)
if err != nil {
t.Fatal(err)
}
// 保留一个退出中的任务,确保新监听创建在旧监听已关闭、旧 close 尚未返回之间。
r.wg.Add(1)
closed := make(chan struct{})
go func() { r.close(); close(closed) }()
<-r.ctx.Done()
r.mu.Lock()
r.mu.Unlock()
var replacements []net.Listener
for _, path := range []string{outSock, inSock} {
listener, err := net.Listen("unix", path)
if err != nil {
r.wg.Done()
<-closed
for _, previous := range replacements {
previous.Close()
}
t.Fatal(err)
}
replacements = append(replacements, listener)
defer listener.Close()
}
r.wg.Done()
<-closed
for _, path := range []string{outSock, inSock} {
conn, err := net.DialTimeout("unix", path, time.Second)
if err != nil {
t.Fatalf("旧中继关闭删除了新中继端点: %v", err)
}
conn.Close()
}
}