2024-08-05 19:06:48 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
|
|
|
|
// Package vnet simulates a virtual Internet containing a set of networks with various
|
|
|
|
// NAT behaviors. You can then plug VMs into the virtual internet at different points
|
|
|
|
// to test Tailscale working end-to-end in various network conditions.
|
|
|
|
//
|
|
|
|
// See https://github.com/tailscale/tailscale/issues/13038
|
|
|
|
package vnet
|
|
|
|
|
|
|
|
// TODO:
|
|
|
|
// - [ ] tests for NAT tables
|
|
|
|
|
|
|
|
import (
|
2024-08-10 20:46:47 +00:00
|
|
|
"bytes"
|
2024-08-05 19:06:48 +00:00
|
|
|
"context"
|
2024-08-07 00:33:45 +00:00
|
|
|
"crypto/tls"
|
2024-08-05 19:06:48 +00:00
|
|
|
"encoding/binary"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-08-27 05:21:14 +00:00
|
|
|
"iter"
|
2024-08-05 19:06:48 +00:00
|
|
|
"log"
|
2024-08-27 05:21:14 +00:00
|
|
|
"maps"
|
2024-08-08 04:43:25 +00:00
|
|
|
"math/rand/v2"
|
2024-08-05 19:06:48 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2024-08-07 00:33:45 +00:00
|
|
|
"net/http/httptest"
|
2024-08-05 19:06:48 +00:00
|
|
|
"net/netip"
|
|
|
|
"os/exec"
|
|
|
|
"strconv"
|
|
|
|
"sync"
|
2024-08-09 03:11:50 +00:00
|
|
|
"sync/atomic"
|
2024-08-05 19:06:48 +00:00
|
|
|
"time"
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
"github.com/gaissmai/bart"
|
2024-08-05 19:06:48 +00:00
|
|
|
"github.com/google/gopacket"
|
|
|
|
"github.com/google/gopacket/layers"
|
|
|
|
"go4.org/mem"
|
|
|
|
"gvisor.dev/gvisor/pkg/buffer"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/header"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/link/channel"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/network/arp"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
|
2024-08-14 04:09:53 +00:00
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
|
2024-08-05 19:06:48 +00:00
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
|
|
|
|
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
|
|
|
|
"gvisor.dev/gvisor/pkg/waiter"
|
2024-08-08 04:31:50 +00:00
|
|
|
"tailscale.com/client/tailscale"
|
2024-08-07 00:33:45 +00:00
|
|
|
"tailscale.com/derp"
|
|
|
|
"tailscale.com/derp/derphttp"
|
|
|
|
"tailscale.com/net/netutil"
|
2024-08-05 19:06:48 +00:00
|
|
|
"tailscale.com/net/stun"
|
|
|
|
"tailscale.com/syncs"
|
|
|
|
"tailscale.com/tailcfg"
|
2024-08-07 00:33:45 +00:00
|
|
|
"tailscale.com/tstest/integration/testcontrol"
|
|
|
|
"tailscale.com/types/key"
|
|
|
|
"tailscale.com/types/logger"
|
2024-08-05 19:06:48 +00:00
|
|
|
"tailscale.com/util/mak"
|
2024-08-09 03:11:50 +00:00
|
|
|
"tailscale.com/util/must"
|
2024-08-05 19:06:48 +00:00
|
|
|
"tailscale.com/util/set"
|
2024-08-10 20:46:47 +00:00
|
|
|
"tailscale.com/util/zstdframe"
|
2024-08-05 19:06:48 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const nicID = 1
|
2024-08-23 18:43:12 +00:00
|
|
|
|
|
|
|
const (
|
|
|
|
stunPort = 3478
|
|
|
|
pcpPort = 5351
|
|
|
|
ssdpPort = 1900
|
|
|
|
)
|
2024-08-05 19:06:48 +00:00
|
|
|
|
|
|
|
func (s *Server) PopulateDERPMapIPs() error {
|
|
|
|
out, err := exec.Command("tailscale", "debug", "derp-map").Output()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("tailscale debug derp-map: %v", err)
|
|
|
|
}
|
|
|
|
var dm tailcfg.DERPMap
|
|
|
|
if err := json.Unmarshal(out, &dm); err != nil {
|
|
|
|
return fmt.Errorf("unmarshal DERPMap: %v", err)
|
|
|
|
}
|
|
|
|
for _, r := range dm.Regions {
|
|
|
|
for _, n := range r.Nodes {
|
|
|
|
if n.IPv4 != "" {
|
|
|
|
s.derpIPs.Add(netip.MustParseAddr(n.IPv4))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) InitNAT(natType NAT) error {
|
|
|
|
ctor, ok := natTypes[natType]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("unknown NAT type %q", natType)
|
|
|
|
}
|
|
|
|
t, err := ctor(n)
|
|
|
|
if err != nil {
|
2024-08-14 04:09:53 +00:00
|
|
|
return fmt.Errorf("error creating NAT type %q for network %v: %w", natType, n.wanIP4, err)
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
n.setNATTable(t)
|
|
|
|
n.natStyle.Store(natType)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) setNATTable(nt NATTable) {
|
|
|
|
n.natMu.Lock()
|
|
|
|
defer n.natMu.Unlock()
|
|
|
|
n.natTable = nt
|
|
|
|
}
|
|
|
|
|
|
|
|
// SoleLANIP implements [IPPool].
|
|
|
|
func (n *network) SoleLANIP() (netip.Addr, bool) {
|
2024-08-26 03:50:22 +00:00
|
|
|
if len(n.nodesByIP4) != 1 {
|
2024-08-05 19:06:48 +00:00
|
|
|
return netip.Addr{}, false
|
|
|
|
}
|
2024-08-26 03:50:22 +00:00
|
|
|
for ip := range n.nodesByIP4 {
|
2024-08-05 19:06:48 +00:00
|
|
|
return ip, true
|
|
|
|
}
|
|
|
|
return netip.Addr{}, false
|
|
|
|
}
|
|
|
|
|
|
|
|
// WANIP implements [IPPool].
|
2024-08-14 04:09:53 +00:00
|
|
|
func (n *network) WANIP() netip.Addr { return n.wanIP4 }
|
2024-08-05 19:06:48 +00:00
|
|
|
|
|
|
|
func (n *network) initStack() error {
|
|
|
|
n.ns = stack.New(stack.Options{
|
|
|
|
NetworkProtocols: []stack.NetworkProtocolFactory{
|
|
|
|
ipv4.NewProtocol,
|
2024-08-14 04:09:53 +00:00
|
|
|
ipv6.NewProtocol,
|
2024-08-05 19:06:48 +00:00
|
|
|
arp.NewProtocol,
|
|
|
|
},
|
|
|
|
TransportProtocols: []stack.TransportProtocolFactory{
|
|
|
|
tcp.NewProtocol,
|
|
|
|
icmp.NewProtocol4,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
sackEnabledOpt := tcpip.TCPSACKEnabled(true) // TCP SACK is disabled by default
|
|
|
|
tcpipErr := n.ns.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt)
|
|
|
|
if tcpipErr != nil {
|
|
|
|
return fmt.Errorf("SetTransportProtocolOption SACK: %v", tcpipErr)
|
|
|
|
}
|
|
|
|
n.linkEP = channel.New(512, 1500, tcpip.LinkAddress(n.mac.HWAddr()))
|
|
|
|
if tcpipProblem := n.ns.CreateNIC(nicID, n.linkEP); tcpipProblem != nil {
|
|
|
|
return fmt.Errorf("CreateNIC: %v", tcpipProblem)
|
|
|
|
}
|
|
|
|
n.ns.SetPromiscuousMode(nicID, true)
|
|
|
|
n.ns.SetSpoofing(nicID, true)
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
var routes []tcpip.Route
|
2024-08-05 19:06:48 +00:00
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
if n.v4 {
|
|
|
|
prefix := tcpip.AddrFrom4Slice(n.lanIP4.Addr().AsSlice()).WithPrefix()
|
|
|
|
prefix.PrefixLen = n.lanIP4.Bits()
|
|
|
|
if tcpProb := n.ns.AddProtocolAddress(nicID, tcpip.ProtocolAddress{
|
|
|
|
Protocol: ipv4.ProtocolNumber,
|
|
|
|
AddressWithPrefix: prefix,
|
|
|
|
}, stack.AddressProperties{}); tcpProb != nil {
|
|
|
|
return errors.New(tcpProb.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
ipv4Subnet, err := tcpip.NewSubnet(tcpip.AddrFromSlice(make([]byte, 4)), tcpip.MaskFromBytes(make([]byte, 4)))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not create IPv4 subnet: %v", err)
|
|
|
|
}
|
|
|
|
routes = append(routes, tcpip.Route{
|
2024-08-05 19:06:48 +00:00
|
|
|
Destination: ipv4Subnet,
|
|
|
|
NIC: nicID,
|
2024-08-14 04:09:53 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
if n.v6 {
|
|
|
|
prefix := tcpip.AddrFrom16(n.wanIP6.Addr().As16()).WithPrefix()
|
|
|
|
prefix.PrefixLen = n.wanIP6.Bits()
|
|
|
|
if tcpProb := n.ns.AddProtocolAddress(nicID, tcpip.ProtocolAddress{
|
|
|
|
Protocol: ipv6.ProtocolNumber,
|
|
|
|
AddressWithPrefix: prefix,
|
|
|
|
}, stack.AddressProperties{}); tcpProb != nil {
|
|
|
|
return errors.New(tcpProb.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
ipv6Subnet, err := tcpip.NewSubnet(tcpip.AddrFromSlice(make([]byte, 16)), tcpip.MaskFromBytes(make([]byte, 16)))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not create IPv6 subnet: %v", err)
|
|
|
|
}
|
|
|
|
routes = append(routes, tcpip.Route{
|
|
|
|
Destination: ipv6Subnet,
|
|
|
|
NIC: nicID,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
n.ns.SetRouteTable(routes)
|
2024-08-05 19:06:48 +00:00
|
|
|
|
|
|
|
const tcpReceiveBufferSize = 0 // default
|
|
|
|
const maxInFlightConnectionAttempts = 8192
|
|
|
|
tcpFwd := tcp.NewForwarder(n.ns, tcpReceiveBufferSize, maxInFlightConnectionAttempts, n.acceptTCP)
|
|
|
|
n.ns.SetTransportProtocolHandler(tcp.ProtocolNumber, func(tei stack.TransportEndpointID, pb *stack.PacketBuffer) (handled bool) {
|
|
|
|
return tcpFwd.HandlePacket(tei, pb)
|
|
|
|
})
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
pkt := n.linkEP.ReadContext(n.s.shutdownCtx)
|
|
|
|
if pkt == nil {
|
|
|
|
if n.s.shutdownCtx.Err() != nil {
|
|
|
|
// Return without logging.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
n.handleIPPacketFromGvisor(pkt.ToView().AsSlice())
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
func (n *network) handleIPPacketFromGvisor(ipRaw []byte) {
|
|
|
|
if len(ipRaw) == 0 {
|
|
|
|
panic("empty packet from gvisor")
|
|
|
|
}
|
|
|
|
var goPkt gopacket.Packet
|
|
|
|
ipVer := ipRaw[0] >> 4 // 4 or 6
|
|
|
|
switch ipVer {
|
|
|
|
case 4:
|
|
|
|
goPkt = gopacket.NewPacket(
|
|
|
|
ipRaw,
|
|
|
|
layers.LayerTypeIPv4, gopacket.Lazy)
|
|
|
|
case 6:
|
|
|
|
goPkt = gopacket.NewPacket(
|
|
|
|
ipRaw,
|
|
|
|
layers.LayerTypeIPv6, gopacket.Lazy)
|
|
|
|
default:
|
2024-08-25 01:04:58 +00:00
|
|
|
panic(fmt.Sprintf("unexpected IP packet version %v", ipVer))
|
2024-08-14 04:09:53 +00:00
|
|
|
}
|
|
|
|
flow, ok := flow(goPkt)
|
|
|
|
if !ok {
|
|
|
|
panic("unexpected gvisor packet")
|
|
|
|
}
|
2024-08-26 03:50:22 +00:00
|
|
|
node, ok := n.nodeByIP(flow.dst)
|
2024-08-14 04:09:53 +00:00
|
|
|
if !ok {
|
|
|
|
n.logf("no node for netstack dest IP %v", flow.dst)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
eth := &layers.Ethernet{
|
2024-08-31 02:23:49 +00:00
|
|
|
SrcMAC: n.mac.HWAddr(),
|
|
|
|
DstMAC: node.mac.HWAddr(),
|
2024-08-14 04:09:53 +00:00
|
|
|
}
|
|
|
|
sls := []gopacket.SerializableLayer{
|
|
|
|
eth,
|
|
|
|
}
|
|
|
|
for _, layer := range goPkt.Layers() {
|
|
|
|
sl, ok := layer.(gopacket.SerializableLayer)
|
|
|
|
if !ok {
|
|
|
|
log.Fatalf("layer %s is not serializable", layer.LayerType().String())
|
|
|
|
}
|
|
|
|
sls = append(sls, sl)
|
|
|
|
}
|
|
|
|
|
2024-08-31 02:23:49 +00:00
|
|
|
resPkt, err := mkPacket(sls...)
|
|
|
|
if err != nil {
|
2024-08-14 04:09:53 +00:00
|
|
|
n.logf("gvisor: serialize error: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if nw, ok := n.writers.Load(node.mac); ok {
|
2024-08-31 02:23:49 +00:00
|
|
|
nw.write(resPkt)
|
2024-08-14 04:09:53 +00:00
|
|
|
} else {
|
|
|
|
n.logf("gvisor write: no writeFunc for %v", node.mac)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
func netaddrIPFromNetstackIP(s tcpip.Address) netip.Addr {
|
|
|
|
switch s.Len() {
|
|
|
|
case 4:
|
|
|
|
return netip.AddrFrom4(s.As4())
|
|
|
|
case 16:
|
|
|
|
return netip.AddrFrom16(s.As16()).Unmap()
|
|
|
|
}
|
|
|
|
return netip.Addr{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func stringifyTEI(tei stack.TransportEndpointID) string {
|
|
|
|
localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
|
|
|
|
remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
|
|
|
|
return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) acceptTCP(r *tcp.ForwarderRequest) {
|
|
|
|
reqDetails := r.ID()
|
|
|
|
|
|
|
|
clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
|
|
|
|
destIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
|
2024-08-07 00:33:45 +00:00
|
|
|
destPort := reqDetails.LocalPort
|
2024-08-05 19:06:48 +00:00
|
|
|
if !clientRemoteIP.IsValid() {
|
|
|
|
r.Complete(true) // sends a RST
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
log.Printf("vnet-AcceptTCP: %v", stringifyTEI(reqDetails))
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
var wq waiter.Queue
|
|
|
|
ep, err := r.CreateEndpoint(&wq)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
|
|
|
|
r.Complete(true) // sends a RST
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ep.SocketOptions().SetKeepAlive(true)
|
|
|
|
|
2024-08-07 00:33:45 +00:00
|
|
|
if destPort == 123 {
|
2024-08-05 19:06:48 +00:00
|
|
|
r.Complete(false)
|
|
|
|
tc := gonet.NewTCPConn(&wq, ep)
|
|
|
|
io.WriteString(tc, "Hello from Go\nGoodbye.\n")
|
|
|
|
tc.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-23 19:49:51 +00:00
|
|
|
if destPort == 8008 && fakeTestAgent.Match(destIP) {
|
2024-08-26 03:50:22 +00:00
|
|
|
node, ok := n.nodeByIP(clientRemoteIP)
|
2024-08-26 03:43:20 +00:00
|
|
|
if !ok {
|
|
|
|
n.logf("unknown client IP %v trying to connect to test driver", clientRemoteIP)
|
|
|
|
r.Complete(true)
|
|
|
|
return
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
r.Complete(false)
|
|
|
|
tc := gonet.NewTCPConn(&wq, ep)
|
|
|
|
ac := &agentConn{node, tc}
|
|
|
|
n.s.addIdleAgentConn(ac)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-23 19:49:51 +00:00
|
|
|
if destPort == 80 && fakeControl.Match(destIP) {
|
2024-08-07 00:33:45 +00:00
|
|
|
r.Complete(false)
|
|
|
|
tc := gonet.NewTCPConn(&wq, ep)
|
|
|
|
hs := &http.Server{Handler: n.s.control}
|
|
|
|
go hs.Serve(netutil.NewOneConnListener(tc, nil))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-23 19:49:51 +00:00
|
|
|
if fakeDERP1.Match(destIP) || fakeDERP2.Match(destIP) {
|
|
|
|
if destPort == 443 {
|
|
|
|
ds := n.s.derps[0]
|
|
|
|
if fakeDERP2.Match(destIP) {
|
|
|
|
ds = n.s.derps[1]
|
|
|
|
}
|
2024-08-07 00:33:45 +00:00
|
|
|
|
2024-08-23 19:49:51 +00:00
|
|
|
r.Complete(false)
|
|
|
|
tc := gonet.NewTCPConn(&wq, ep)
|
|
|
|
tlsConn := tls.Server(tc, ds.tlsConfig)
|
|
|
|
hs := &http.Server{Handler: ds.handler}
|
|
|
|
go hs.Serve(netutil.NewOneConnListener(tlsConn, nil))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if destPort == 80 {
|
|
|
|
r.Complete(false)
|
|
|
|
tc := gonet.NewTCPConn(&wq, ep)
|
|
|
|
hs := &http.Server{Handler: n.s.derps[0].handler}
|
|
|
|
go hs.Serve(netutil.NewOneConnListener(tc, nil))
|
|
|
|
return
|
|
|
|
}
|
2024-08-07 00:33:45 +00:00
|
|
|
}
|
2024-08-23 19:49:51 +00:00
|
|
|
if destPort == 443 && fakeLogCatcher.Match(destIP) {
|
2024-08-10 20:46:47 +00:00
|
|
|
r.Complete(false)
|
|
|
|
tc := gonet.NewTCPConn(&wq, ep)
|
|
|
|
go n.serveLogCatcherConn(clientRemoteIP, tc)
|
|
|
|
return
|
|
|
|
}
|
2024-08-07 00:33:45 +00:00
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
var targetDial string
|
|
|
|
if n.s.derpIPs.Contains(destIP) {
|
2024-08-07 00:33:45 +00:00
|
|
|
targetDial = destIP.String() + ":" + strconv.Itoa(int(destPort))
|
2024-08-23 19:49:51 +00:00
|
|
|
} else if fakeProxyControlplane.Match(destIP) {
|
2024-08-07 00:33:45 +00:00
|
|
|
targetDial = "controlplane.tailscale.com:" + strconv.Itoa(int(destPort))
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
if targetDial != "" {
|
|
|
|
c, err := net.Dial("tcp", targetDial)
|
|
|
|
if err != nil {
|
|
|
|
r.Complete(true)
|
|
|
|
log.Printf("Dial controlplane: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
tc := gonet.NewTCPConn(&wq, ep)
|
|
|
|
defer tc.Close()
|
|
|
|
r.Complete(false)
|
|
|
|
errc := make(chan error, 2)
|
|
|
|
go func() { _, err := io.Copy(tc, c); errc <- err }()
|
|
|
|
go func() { _, err := io.Copy(c, tc); errc <- err }()
|
|
|
|
<-errc
|
|
|
|
} else {
|
|
|
|
r.Complete(true) // sends a RST
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-10 20:46:47 +00:00
|
|
|
// serveLogCatchConn serves a TCP connection to "log.tailscale.io", speaking the
|
|
|
|
// logtail/logcatcher protocol.
|
|
|
|
//
|
|
|
|
// We terminate TLS with an arbitrary cert; the client is configured to not
|
|
|
|
// validate TLS certs for this hostname when running under these integration
|
|
|
|
// tests.
|
|
|
|
func (n *network) serveLogCatcherConn(clientRemoteIP netip.Addr, c net.Conn) {
|
|
|
|
tlsConfig := n.s.derps[0].tlsConfig // self-signed (stealing DERP's); test client configure to not check
|
|
|
|
tlsConn := tls.Server(c, tlsConfig)
|
|
|
|
var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
all, _ := io.ReadAll(r.Body)
|
|
|
|
if r.Header.Get("Content-Encoding") == "zstd" {
|
|
|
|
var err error
|
|
|
|
all, err = zstdframe.AppendDecode(nil, all)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("LOGS DECODE ERROR zstd decode: %v", err)
|
|
|
|
http.Error(w, "zstd decode error", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
var logs []struct {
|
|
|
|
Logtail struct {
|
|
|
|
Client_Time time.Time
|
|
|
|
}
|
|
|
|
Text string
|
|
|
|
}
|
|
|
|
if err := json.Unmarshal(all, &logs); err != nil {
|
|
|
|
log.Printf("Logs decode error: %v", err)
|
|
|
|
return
|
|
|
|
}
|
2024-08-26 03:50:22 +00:00
|
|
|
node := n.nodesByIP4[clientRemoteIP]
|
2024-08-10 20:46:47 +00:00
|
|
|
if node != nil {
|
|
|
|
node.logMu.Lock()
|
|
|
|
defer node.logMu.Unlock()
|
2024-08-13 04:39:28 +00:00
|
|
|
node.logCatcherWrites++
|
2024-08-10 20:46:47 +00:00
|
|
|
for _, lg := range logs {
|
|
|
|
tStr := lg.Logtail.Client_Time.Round(time.Millisecond).Format(time.RFC3339Nano)
|
|
|
|
fmt.Fprintf(&node.logBuf, "[%v] %s\n", tStr, lg.Text)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
hs := &http.Server{Handler: handler}
|
|
|
|
hs.Serve(netutil.NewOneConnListener(tlsConn, nil))
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
type EthernetPacket struct {
|
|
|
|
le *layers.Ethernet
|
|
|
|
gp gopacket.Packet
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ep EthernetPacket) SrcMAC() MAC {
|
|
|
|
return MAC(ep.le.SrcMAC)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ep EthernetPacket) DstMAC() MAC {
|
|
|
|
return MAC(ep.le.DstMAC)
|
|
|
|
}
|
|
|
|
|
|
|
|
type MAC [6]byte
|
|
|
|
|
|
|
|
func (m MAC) IsBroadcast() bool {
|
|
|
|
return m == MAC{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
|
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
// IsIPv6Multicast reports whether m is an IPv6 multicast MAC address,
|
|
|
|
// typically one containing a solicited-node multicast address.
|
|
|
|
func (m MAC) IsIPv6Multicast() bool {
|
|
|
|
return m[0] == 0x33 && m[1] == 0x33
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
func macOf(hwa net.HardwareAddr) (_ MAC, ok bool) {
|
|
|
|
if len(hwa) != 6 {
|
|
|
|
return MAC{}, false
|
|
|
|
}
|
|
|
|
return MAC(hwa), true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m MAC) HWAddr() net.HardwareAddr {
|
|
|
|
return net.HardwareAddr(m[:])
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m MAC) String() string {
|
|
|
|
return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2], m[3], m[4], m[5])
|
|
|
|
}
|
|
|
|
|
2024-08-08 04:43:25 +00:00
|
|
|
type portMapping struct {
|
|
|
|
dst netip.AddrPort // LAN IP:port
|
|
|
|
expiry time.Time
|
|
|
|
}
|
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
// writerFunc is a function that writes an Ethernet frame to a connected client.
|
|
|
|
//
|
|
|
|
// ethFrame is the Ethernet frame to write.
|
|
|
|
//
|
|
|
|
// interfaceIndexID is the interface ID for the pcap file.
|
|
|
|
type writerFunc func(dst vmClient, ethFrame []byte, interfaceIndexID int)
|
2024-08-22 13:36:24 +00:00
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
// networkWriter are the arguments to a writerFunc and the writerFunc.
|
2024-08-22 13:36:24 +00:00
|
|
|
type networkWriter struct {
|
2024-08-27 05:21:14 +00:00
|
|
|
writer writerFunc // Function to write packets to the network
|
|
|
|
c vmClient
|
|
|
|
interfaceID int // The interface ID of the src node (for writing pcaps)
|
2024-08-22 13:36:24 +00:00
|
|
|
}
|
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
func (nw networkWriter) write(b []byte) {
|
|
|
|
nw.writer(nw.c, b, nw.interfaceID)
|
2024-08-22 13:36:24 +00:00
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
type network struct {
|
2024-08-09 04:29:09 +00:00
|
|
|
s *Server
|
2024-08-14 04:09:53 +00:00
|
|
|
num int // 1-based
|
|
|
|
mac MAC // of router
|
2024-08-09 04:29:09 +00:00
|
|
|
portmap bool
|
|
|
|
lanInterfaceID int
|
|
|
|
wanInterfaceID int
|
2024-08-14 04:09:53 +00:00
|
|
|
v4 bool // network supports IPv4
|
|
|
|
v6 bool // network support IPv6
|
|
|
|
wanIP6 netip.Prefix // router's WAN IPv6, if any, as a /64.
|
|
|
|
wanIP4 netip.Addr // router's LAN IPv4, if any
|
|
|
|
lanIP4 netip.Prefix // router's LAN IP + CIDR (e.g. 192.168.2.1/24)
|
2024-09-03 22:00:18 +00:00
|
|
|
breakWAN4 bool // break WAN IPv4 connectivity
|
2024-08-26 03:50:22 +00:00
|
|
|
nodesByIP4 map[netip.Addr]*node // by LAN IPv4
|
2024-08-14 04:09:53 +00:00
|
|
|
nodesByMAC map[MAC]*node
|
2024-08-09 04:29:09 +00:00
|
|
|
logf func(format string, args ...any)
|
2024-08-05 19:06:48 +00:00
|
|
|
|
|
|
|
ns *stack.Stack
|
|
|
|
linkEP *channel.Endpoint
|
|
|
|
|
2024-08-08 19:10:00 +00:00
|
|
|
natStyle syncs.AtomicValue[NAT]
|
|
|
|
natMu sync.Mutex // held while using + changing natTable
|
|
|
|
natTable NATTable
|
|
|
|
portMap map[netip.AddrPort]portMapping // WAN ip:port -> LAN ip:port
|
|
|
|
portMapFlow map[portmapFlowKey]netip.AddrPort // (lanAP, peerWANAP) -> portmapped wanAP
|
2024-08-05 19:06:48 +00:00
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
macMu sync.Mutex
|
|
|
|
macOfIPv6 map[netip.Addr]MAC // IPv6 source IP -> MAC
|
|
|
|
|
2024-08-22 13:36:24 +00:00
|
|
|
// writers is a map of MAC -> networkWriters to write packets to that MAC.
|
2024-08-05 19:06:48 +00:00
|
|
|
// It contains entries for connected nodes only.
|
2024-08-22 13:36:24 +00:00
|
|
|
writers syncs.Map[MAC, networkWriter] // MAC -> to networkWriter for that MAC
|
|
|
|
}
|
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
// registerWriter registers a client address with a MAC address.
|
|
|
|
func (n *network) registerWriter(mac MAC, c vmClient) {
|
|
|
|
nw := networkWriter{
|
|
|
|
writer: n.s.writeEthernetFrameToVM,
|
|
|
|
c: c,
|
|
|
|
}
|
|
|
|
if node, ok := n.s.nodeByMAC[mac]; ok {
|
|
|
|
nw.interfaceID = node.interfaceID
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-27 05:21:14 +00:00
|
|
|
n.writers.Store(mac, nw)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) unregisterWriter(mac MAC) {
|
|
|
|
n.writers.Delete(mac)
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
2024-08-28 04:38:42 +00:00
|
|
|
// RegisteredWritersForTest returns the number of registered connections (VM
|
|
|
|
// guests with a known MAC to whom a packet can be sent) there are to the
|
|
|
|
// server. It exists for testing.
|
|
|
|
func (s *Server) RegisteredWritersForTest() int {
|
|
|
|
num := 0
|
|
|
|
for n := range s.networks {
|
|
|
|
num += n.writers.Len()
|
|
|
|
}
|
|
|
|
return num
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
func (n *network) MACOfIP(ip netip.Addr) (_ MAC, ok bool) {
|
2024-08-14 04:09:53 +00:00
|
|
|
if n.lanIP4.Addr() == ip {
|
2024-08-05 19:06:48 +00:00
|
|
|
return n.mac, true
|
|
|
|
}
|
2024-08-26 03:50:22 +00:00
|
|
|
if n, ok := n.nodesByIP4[ip]; ok {
|
2024-08-05 19:06:48 +00:00
|
|
|
return n.mac, true
|
|
|
|
}
|
|
|
|
return MAC{}, false
|
|
|
|
}
|
|
|
|
|
|
|
|
type node struct {
|
2024-08-13 04:39:28 +00:00
|
|
|
mac MAC
|
2024-08-13 15:20:43 +00:00
|
|
|
num int // 1-based node number
|
2024-08-13 04:39:28 +00:00
|
|
|
interfaceID int
|
|
|
|
net *network
|
|
|
|
lanIP netip.Addr // must be in net.lanIP prefix + unique in net
|
|
|
|
verboseSyslog bool
|
2024-08-10 20:46:47 +00:00
|
|
|
|
|
|
|
// logMu guards logBuf.
|
|
|
|
// TODO(bradfitz): conditionally write these out to separate files at the end?
|
|
|
|
// Currently they only hold logcatcher logs.
|
2024-08-13 04:39:28 +00:00
|
|
|
logMu sync.Mutex
|
|
|
|
logBuf bytes.Buffer
|
|
|
|
logCatcherWrites int
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
2024-08-13 15:20:43 +00:00
|
|
|
// String returns the string "nodeN" where N is the 1-based node number.
|
|
|
|
func (n *node) String() string {
|
|
|
|
return fmt.Sprintf("node%d", n.num)
|
|
|
|
}
|
|
|
|
|
2024-08-07 00:33:45 +00:00
|
|
|
type derpServer struct {
|
|
|
|
srv *derp.Server
|
|
|
|
handler http.Handler
|
|
|
|
tlsConfig *tls.Config
|
|
|
|
}
|
|
|
|
|
|
|
|
func newDERPServer() *derpServer {
|
|
|
|
// Just to get a self-signed TLS cert:
|
|
|
|
ts := httptest.NewTLSServer(nil)
|
|
|
|
ts.Close()
|
|
|
|
|
|
|
|
ds := &derpServer{
|
|
|
|
srv: derp.NewServer(key.NewNode(), logger.Discard),
|
|
|
|
tlsConfig: ts.TLS, // self-signed; test client configure to not check
|
|
|
|
}
|
|
|
|
var mux http.ServeMux
|
|
|
|
mux.Handle("/derp", derphttp.Handler(ds.srv))
|
|
|
|
mux.HandleFunc("/generate_204", derphttp.ServeNoContent)
|
|
|
|
|
|
|
|
ds.handler = &mux
|
|
|
|
return ds
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
type Server struct {
|
|
|
|
shutdownCtx context.Context
|
|
|
|
shutdownCancel context.CancelFunc
|
2024-08-09 03:11:50 +00:00
|
|
|
shuttingDown atomic.Bool
|
|
|
|
wg sync.WaitGroup
|
2024-08-07 00:33:45 +00:00
|
|
|
blendReality bool
|
2024-08-05 19:06:48 +00:00
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
optLogf func(format string, args ...any) // or nil to use log.Printf
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
derpIPs set.Set[netip.Addr]
|
|
|
|
|
|
|
|
nodes []*node
|
|
|
|
nodeByMAC map[MAC]*node
|
|
|
|
networks set.Set[*network]
|
2024-08-14 04:09:53 +00:00
|
|
|
networkByWAN *bart.Table[*network]
|
2024-08-05 19:06:48 +00:00
|
|
|
|
2024-08-09 03:11:50 +00:00
|
|
|
control *testcontrol.Server
|
|
|
|
derps []*derpServer
|
|
|
|
pcapWriter *pcapWriter
|
2024-08-07 00:33:45 +00:00
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
// writeMu serializes all writes to VM clients.
|
|
|
|
writeMu sync.Mutex
|
|
|
|
scratch []byte
|
|
|
|
|
2024-08-07 00:33:45 +00:00
|
|
|
mu sync.Mutex
|
|
|
|
agentConnWaiter map[*node]chan<- struct{} // signaled after added to set
|
|
|
|
agentConns set.Set[*agentConn] // not keyed by node; should be small/cheap enough to scan all
|
|
|
|
agentDialer map[*node]DialFunc
|
|
|
|
}
|
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
func (s *Server) logf(format string, args ...any) {
|
|
|
|
if s.optLogf != nil {
|
|
|
|
s.optLogf(format, args...)
|
|
|
|
} else {
|
|
|
|
log.Printf(format, args...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) SetLoggerForTest(logf func(format string, args ...any)) {
|
|
|
|
s.optLogf = logf
|
|
|
|
}
|
|
|
|
|
2024-08-07 00:33:45 +00:00
|
|
|
type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)
|
|
|
|
|
|
|
|
var derpMap = &tailcfg.DERPMap{
|
|
|
|
Regions: map[int]*tailcfg.DERPRegion{
|
|
|
|
1: {
|
|
|
|
RegionID: 1,
|
|
|
|
RegionCode: "atlantis",
|
|
|
|
RegionName: "Atlantis",
|
|
|
|
Nodes: []*tailcfg.DERPNode{
|
|
|
|
{
|
|
|
|
Name: "1a",
|
|
|
|
RegionID: 1,
|
|
|
|
HostName: "derp1.tailscale",
|
2024-08-23 19:49:51 +00:00
|
|
|
IPv4: fakeDERP1.v4.String(),
|
|
|
|
IPv6: fakeDERP1.v6.String(),
|
2024-08-07 00:33:45 +00:00
|
|
|
InsecureForTests: true,
|
|
|
|
CanPort80: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
2: {
|
|
|
|
RegionID: 2,
|
|
|
|
RegionCode: "northpole",
|
|
|
|
RegionName: "North Pole",
|
|
|
|
Nodes: []*tailcfg.DERPNode{
|
|
|
|
{
|
|
|
|
Name: "2a",
|
|
|
|
RegionID: 2,
|
|
|
|
HostName: "derp2.tailscale",
|
2024-08-23 19:49:51 +00:00
|
|
|
IPv4: fakeDERP2.v4.String(),
|
|
|
|
IPv6: fakeDERP2.v6.String(),
|
2024-08-07 00:33:45 +00:00
|
|
|
InsecureForTests: true,
|
|
|
|
CanPort80: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func New(c *Config) (*Server, error) {
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
s := &Server{
|
|
|
|
shutdownCtx: ctx,
|
|
|
|
shutdownCancel: cancel,
|
|
|
|
|
2024-08-07 00:33:45 +00:00
|
|
|
control: &testcontrol.Server{
|
|
|
|
DERPMap: derpMap,
|
|
|
|
ExplicitBaseURL: "http://control.tailscale",
|
|
|
|
},
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
blendReality: c.blendReality,
|
|
|
|
derpIPs: set.Of[netip.Addr](),
|
2024-08-05 19:06:48 +00:00
|
|
|
|
|
|
|
nodeByMAC: map[MAC]*node{},
|
2024-08-14 04:09:53 +00:00
|
|
|
networkByWAN: &bart.Table[*network]{},
|
2024-08-05 19:06:48 +00:00
|
|
|
networks: set.Of[*network](),
|
|
|
|
}
|
2024-08-07 00:33:45 +00:00
|
|
|
for range 2 {
|
|
|
|
s.derps = append(s.derps, newDERPServer())
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
if err := s.initFromConfig(c); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for n := range s.networks {
|
|
|
|
if err := n.initStack(); err != nil {
|
|
|
|
return nil, fmt.Errorf("newServer: initStack: %v", err)
|
|
|
|
}
|
|
|
|
}
|
2024-08-07 00:33:45 +00:00
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
2024-08-07 00:33:45 +00:00
|
|
|
func (s *Server) Close() {
|
2024-08-09 03:11:50 +00:00
|
|
|
if shutdown := s.shuttingDown.Swap(true); !shutdown {
|
|
|
|
s.shutdownCancel()
|
2024-08-09 04:29:09 +00:00
|
|
|
s.pcapWriter.Close()
|
2024-08-09 03:11:50 +00:00
|
|
|
}
|
|
|
|
s.wg.Wait()
|
2024-08-07 00:33:45 +00:00
|
|
|
}
|
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
// MACs returns the MAC addresses of the configured nodes.
|
|
|
|
func (s *Server) MACs() iter.Seq[MAC] {
|
|
|
|
return maps.Keys(s.nodeByMAC)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) RegisterSinkForTest(mac MAC, fn func(eth []byte)) {
|
|
|
|
n, ok := s.nodeByMAC[mac]
|
|
|
|
if !ok {
|
|
|
|
log.Fatalf("RegisterSinkForTest: unknown MAC %v", mac)
|
|
|
|
}
|
|
|
|
n.net.writers.Store(mac, networkWriter{
|
|
|
|
writer: func(_ vmClient, eth []byte, _ int) {
|
|
|
|
fn(eth)
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
func (s *Server) HWAddr(mac MAC) net.HardwareAddr {
|
|
|
|
// TODO: cache
|
|
|
|
return net.HardwareAddr(mac[:])
|
|
|
|
}
|
|
|
|
|
|
|
|
type Protocol int
|
|
|
|
|
|
|
|
const (
|
|
|
|
ProtocolQEMU = Protocol(iota + 1)
|
2024-08-22 13:36:24 +00:00
|
|
|
ProtocolUnixDGRAM // for macOS Virtualization.Framework and VZFileHandleNetworkDeviceAttachment
|
2024-08-05 19:06:48 +00:00
|
|
|
)
|
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
func (s *Server) writeEthernetFrameToVM(c vmClient, ethPkt []byte, interfaceID int) {
|
|
|
|
s.writeMu.Lock()
|
|
|
|
defer s.writeMu.Unlock()
|
|
|
|
|
|
|
|
if ethPkt == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
switch c.proto() {
|
|
|
|
case ProtocolQEMU:
|
|
|
|
s.scratch = binary.BigEndian.AppendUint32(s.scratch[:0], uint32(len(ethPkt)))
|
|
|
|
s.scratch = append(s.scratch, ethPkt...)
|
|
|
|
if _, err := c.uc.Write(s.scratch); err != nil {
|
2024-08-28 04:38:42 +00:00
|
|
|
s.logf("Write pkt: %v", err)
|
2024-08-27 05:21:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
case ProtocolUnixDGRAM:
|
|
|
|
if _, err := c.uc.WriteToUnix(ethPkt, c.raddr); err != nil {
|
2024-08-28 04:38:42 +00:00
|
|
|
s.logf("Write pkt : %v", err)
|
2024-08-27 05:21:14 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
must.Do(s.pcapWriter.WritePacket(gopacket.CaptureInfo{
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
CaptureLength: len(ethPkt),
|
|
|
|
Length: len(ethPkt),
|
|
|
|
InterfaceIndex: interfaceID,
|
|
|
|
}, ethPkt))
|
|
|
|
}
|
|
|
|
|
|
|
|
// vmClient is a comparable value representing a connection from a VM, either a
|
|
|
|
// QEMU-style client (with streams over a Unix socket) or a datagram based
|
|
|
|
// client (such as macOS Virtualization.framework clients).
|
|
|
|
type vmClient struct {
|
|
|
|
uc *net.UnixConn
|
|
|
|
raddr *net.UnixAddr // nil for QEMU-style clients using streams; else datagram source
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c vmClient) proto() Protocol {
|
|
|
|
if c.raddr == nil {
|
|
|
|
return ProtocolQEMU
|
|
|
|
}
|
|
|
|
return ProtocolUnixDGRAM
|
|
|
|
}
|
|
|
|
|
2024-08-28 15:06:17 +00:00
|
|
|
func parseEthernet(pkt []byte) (dst, src MAC, ethType layers.EthernetType, payload []byte, ok bool) {
|
|
|
|
// headerLen is the length of an Ethernet header:
|
|
|
|
// 6 bytes of destination MAC, 6 bytes of source MAC, 2 bytes of EtherType.
|
|
|
|
const headerLen = 14
|
|
|
|
if len(pkt) < headerLen {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
dst = MAC(pkt[0:6])
|
|
|
|
src = MAC(pkt[6:12])
|
|
|
|
ethType = layers.EthernetType(binary.BigEndian.Uint16(pkt[12:14]))
|
|
|
|
payload = pkt[headerLen:]
|
|
|
|
ok = true
|
|
|
|
return
|
|
|
|
}
|
2024-08-27 05:21:14 +00:00
|
|
|
|
2024-08-22 13:36:24 +00:00
|
|
|
// Handles a single connection from a QEMU-style client or muxd connections for dgram mode
|
2024-08-05 19:06:48 +00:00
|
|
|
func (s *Server) ServeUnixConn(uc *net.UnixConn, proto Protocol) {
|
2024-08-09 03:11:50 +00:00
|
|
|
if s.shuttingDown.Load() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
s.wg.Add(1)
|
|
|
|
defer s.wg.Done()
|
|
|
|
context.AfterFunc(s.shutdownCtx, func() {
|
|
|
|
uc.SetDeadline(time.Now())
|
|
|
|
})
|
2024-08-28 04:38:42 +00:00
|
|
|
s.logf("Got conn %T %p", uc, uc)
|
2024-08-05 19:06:48 +00:00
|
|
|
defer uc.Close()
|
|
|
|
|
|
|
|
buf := make([]byte, 16<<10)
|
2024-08-27 05:21:14 +00:00
|
|
|
didReg := map[MAC]bool{}
|
2024-08-05 19:06:48 +00:00
|
|
|
for {
|
|
|
|
var packetRaw []byte
|
2024-08-22 13:36:24 +00:00
|
|
|
var raddr *net.UnixAddr
|
|
|
|
|
|
|
|
switch proto {
|
|
|
|
case ProtocolUnixDGRAM:
|
|
|
|
n, addr, err := uc.ReadFromUnix(buf)
|
|
|
|
raddr = addr
|
2024-08-05 19:06:48 +00:00
|
|
|
if err != nil {
|
2024-08-28 04:38:42 +00:00
|
|
|
if s.shutdownCtx.Err() != nil {
|
|
|
|
// Return without logging.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
s.logf("ReadFromUnix: %#v", err)
|
2024-08-05 19:06:48 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
packetRaw = buf[:n]
|
2024-08-22 13:36:24 +00:00
|
|
|
case ProtocolQEMU:
|
2024-08-05 19:06:48 +00:00
|
|
|
if _, err := io.ReadFull(uc, buf[:4]); err != nil {
|
2024-08-08 19:47:54 +00:00
|
|
|
if s.shutdownCtx.Err() != nil {
|
|
|
|
// Return without logging.
|
|
|
|
return
|
|
|
|
}
|
2024-08-28 04:38:42 +00:00
|
|
|
s.logf("ReadFull header: %v", err)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
n := binary.BigEndian.Uint32(buf[:4])
|
|
|
|
|
|
|
|
if _, err := io.ReadFull(uc, buf[4:4+n]); err != nil {
|
2024-08-08 19:47:54 +00:00
|
|
|
if s.shutdownCtx.Err() != nil {
|
|
|
|
// Return without logging.
|
|
|
|
return
|
|
|
|
}
|
2024-08-28 04:38:42 +00:00
|
|
|
s.logf("ReadFull pkt: %v", err)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
packetRaw = buf[4 : 4+n] // raw ethernet frame
|
|
|
|
}
|
2024-08-27 05:21:14 +00:00
|
|
|
c := vmClient{uc, raddr}
|
2024-08-05 19:06:48 +00:00
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
// For the first packet from a MAC, register a writerFunc to write to the VM.
|
2024-08-28 15:06:17 +00:00
|
|
|
_, srcMAC, _, _, ok := parseEthernet(packetRaw)
|
|
|
|
if !ok {
|
2024-08-05 19:06:48 +00:00
|
|
|
continue
|
|
|
|
}
|
2024-08-22 13:36:24 +00:00
|
|
|
srcNode, ok := s.nodeByMAC[srcMAC]
|
|
|
|
if !ok {
|
2024-08-28 04:38:42 +00:00
|
|
|
s.logf("[conn %p] got frame from unknown MAC %v", c.uc, srcMAC)
|
2024-08-22 13:36:24 +00:00
|
|
|
continue
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-27 05:21:14 +00:00
|
|
|
if !didReg[srcMAC] {
|
|
|
|
didReg[srcMAC] = true
|
2024-08-28 04:38:42 +00:00
|
|
|
s.logf("[conn %p] Registering writer for MAC %v, node %v", c.uc, srcMAC, srcNode.lanIP)
|
2024-08-27 05:21:14 +00:00
|
|
|
srcNode.net.registerWriter(srcMAC, c)
|
|
|
|
defer srcNode.net.unregisterWriter(srcMAC)
|
|
|
|
}
|
2024-08-22 13:36:24 +00:00
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
if err := s.handleEthernetFrameFromVM(packetRaw); err != nil {
|
|
|
|
srcNode.net.logf("handleEthernetFrameFromVM: [conn %p], %v", c.uc, err)
|
2024-08-22 13:36:24 +00:00
|
|
|
}
|
2024-08-27 05:21:14 +00:00
|
|
|
}
|
|
|
|
}
|
2024-08-22 13:36:24 +00:00
|
|
|
|
2024-08-27 05:21:14 +00:00
|
|
|
func (s *Server) handleEthernetFrameFromVM(packetRaw []byte) error {
|
|
|
|
packet := gopacket.NewPacket(packetRaw, layers.LayerTypeEthernet, gopacket.Lazy)
|
|
|
|
le, ok := packet.LinkLayer().(*layers.Ethernet)
|
|
|
|
if !ok || len(le.SrcMAC) != 6 || len(le.DstMAC) != 6 {
|
|
|
|
return fmt.Errorf("ignoring non-Ethernet packet: % 02x", packetRaw)
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-27 05:21:14 +00:00
|
|
|
ep := EthernetPacket{le, packet}
|
|
|
|
|
|
|
|
srcMAC := ep.SrcMAC()
|
|
|
|
srcNode, ok := s.nodeByMAC[srcMAC]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("got frame from unknown MAC %v", srcMAC)
|
|
|
|
}
|
|
|
|
|
|
|
|
must.Do(s.pcapWriter.WritePacket(gopacket.CaptureInfo{
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
CaptureLength: len(packetRaw),
|
|
|
|
Length: len(packetRaw),
|
|
|
|
InterfaceIndex: srcNode.interfaceID,
|
|
|
|
}, packetRaw))
|
|
|
|
srcNode.net.HandleEthernetPacket(ep)
|
|
|
|
return nil
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) routeUDPPacket(up UDPPacket) {
|
|
|
|
// Find which network owns this based on the destination IP
|
|
|
|
// and all the known networks' wan IPs.
|
|
|
|
|
|
|
|
// But certain things (like STUN) we do in-process.
|
|
|
|
if up.Dst.Port() == stunPort {
|
|
|
|
// TODO(bradfitz): fake latency; time.AfterFunc the response
|
|
|
|
if res, ok := makeSTUNReply(up); ok {
|
2024-08-07 00:33:45 +00:00
|
|
|
//log.Printf("STUN reply: %+v", res)
|
2024-08-05 19:06:48 +00:00
|
|
|
s.routeUDPPacket(res)
|
2024-08-07 00:33:45 +00:00
|
|
|
} else {
|
|
|
|
log.Printf("weird: STUN packet not handled")
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-13 15:20:43 +00:00
|
|
|
dstIP := up.Dst.Addr()
|
2024-08-14 04:09:53 +00:00
|
|
|
netw, ok := s.networkByWAN.Lookup(dstIP)
|
2024-08-05 19:06:48 +00:00
|
|
|
if !ok {
|
2024-08-13 15:20:43 +00:00
|
|
|
if dstIP.IsPrivate() {
|
|
|
|
// Not worth spamming logs. RFC 1918 space doesn't route.
|
|
|
|
return
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
log.Printf("no network to route UDP packet for %v", up.Dst)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
netw.HandleUDPPacket(up)
|
|
|
|
}
|
|
|
|
|
|
|
|
// writeEth writes a raw Ethernet frame to all (0, 1, or multiple) connected
|
|
|
|
// clients on the network.
|
|
|
|
//
|
|
|
|
// This only delivers to client devices and not the virtual router/gateway
|
|
|
|
// device.
|
2024-08-14 04:09:53 +00:00
|
|
|
//
|
|
|
|
// It reports whether a packet was written to any clients.
|
|
|
|
func (n *network) writeEth(res []byte) bool {
|
2024-08-28 15:06:17 +00:00
|
|
|
dstMAC, srcMAC, etherType, _, ok := parseEthernet(res)
|
|
|
|
if !ok {
|
2024-08-14 04:09:53 +00:00
|
|
|
return false
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-28 15:06:17 +00:00
|
|
|
|
|
|
|
if dstMAC.IsBroadcast() || (n.v6 && etherType == layers.EthernetTypeIPv6 && dstMAC == macAllNodes) {
|
2024-08-14 04:09:53 +00:00
|
|
|
num := 0
|
2024-08-22 13:36:24 +00:00
|
|
|
n.writers.Range(func(mac MAC, nw networkWriter) bool {
|
2024-08-27 05:21:14 +00:00
|
|
|
if mac != srcMAC {
|
|
|
|
num++
|
|
|
|
nw.write(res)
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
return true
|
|
|
|
})
|
2024-08-14 04:09:53 +00:00
|
|
|
return num > 0
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
if srcMAC == dstMAC {
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("dropping write of packet from %v to itself", srcMAC)
|
2024-08-14 04:09:53 +00:00
|
|
|
return false
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-22 13:36:24 +00:00
|
|
|
if nw, ok := n.writers.Load(dstMAC); ok {
|
|
|
|
nw.write(res)
|
2024-08-14 04:09:53 +00:00
|
|
|
return true
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
|
|
|
|
const debugMiss = false
|
|
|
|
if debugMiss {
|
|
|
|
gp := gopacket.NewPacket(res, layers.LayerTypeEthernet, gopacket.Lazy)
|
|
|
|
n.logf("no writeFunc for dst %v from src %v; pkt=%v", dstMAC, srcMAC, gp)
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
var (
|
2024-08-28 15:06:17 +00:00
|
|
|
macAllNodes = MAC{0: 0x33, 1: 0x33, 5: 0x01}
|
2024-08-14 04:09:53 +00:00
|
|
|
macAllRouters = MAC{0: 0x33, 1: 0x33, 5: 0x02}
|
2024-08-27 05:21:14 +00:00
|
|
|
macBroadcast = MAC{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
testingEthertype layers.EthernetType = 0x1234
|
2024-08-14 04:09:53 +00:00
|
|
|
)
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
func (n *network) HandleEthernetPacket(ep EthernetPacket) {
|
|
|
|
packet := ep.gp
|
|
|
|
dstMAC := ep.DstMAC()
|
2024-08-28 15:06:17 +00:00
|
|
|
isBroadcast := dstMAC.IsBroadcast() || (n.v6 && ep.le.EthernetType == layers.EthernetTypeIPv6 && dstMAC == macAllNodes)
|
2024-08-14 04:09:53 +00:00
|
|
|
isV6SpecialMAC := dstMAC[0] == 0x33 && dstMAC[1] == 0x33
|
|
|
|
|
|
|
|
// forRouter is whether the packet is destined for the router itself
|
|
|
|
// or if it's a special thing (like V6 NDP) that the router should handle.
|
|
|
|
forRouter := dstMAC == n.mac || isBroadcast || isV6SpecialMAC
|
|
|
|
|
|
|
|
const debug = false
|
|
|
|
if debug {
|
2024-08-28 15:06:17 +00:00
|
|
|
n.logf("HandleEthernetPacket: %v => %v; type %v, bcast=%v, forRouter=%v", ep.SrcMAC(), ep.DstMAC(), ep.le.EthernetType, isBroadcast, forRouter)
|
2024-08-14 04:09:53 +00:00
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
|
|
|
|
switch ep.le.EthernetType {
|
|
|
|
default:
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("Dropping non-IP packet: %v", ep.le.EthernetType)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
2024-08-27 05:21:14 +00:00
|
|
|
case 0x1234:
|
|
|
|
// Permitted for testing. Not a real ethertype.
|
2024-08-05 19:06:48 +00:00
|
|
|
case layers.EthernetTypeARP:
|
|
|
|
res, err := n.createARPResponse(packet)
|
|
|
|
if err != nil {
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("createARPResponse: %v", err)
|
2024-08-05 19:06:48 +00:00
|
|
|
} else {
|
|
|
|
n.writeEth(res)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
case layers.EthernetTypeIPv6:
|
2024-08-14 04:09:53 +00:00
|
|
|
if !n.v6 {
|
|
|
|
n.logf("dropping IPv6 packet on v4-only network")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if dstMAC == macAllRouters {
|
|
|
|
if rs, ok := ep.gp.Layer(layers.LayerTypeICMPv6RouterSolicitation).(*layers.ICMPv6RouterSolicitation); ok {
|
|
|
|
n.handleIPv6RouterSolicitation(ep, rs)
|
|
|
|
} else {
|
|
|
|
n.logf("unexpected IPv6 packet to all-routers: %v", ep.gp)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
isMcast := dstMAC.IsIPv6Multicast()
|
|
|
|
if isMcast || dstMAC == n.mac {
|
|
|
|
if ns, ok := ep.gp.Layer(layers.LayerTypeICMPv6NeighborSolicitation).(*layers.ICMPv6NeighborSolicitation); ok {
|
|
|
|
n.handleIPv6NeighborSolicitation(ep, ns)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if ep.gp.Layer(layers.LayerTypeMLDv2MulticastListenerReport) != nil {
|
|
|
|
// We don't care about these (yet?) and Linux spams a bunch
|
|
|
|
// a bunch of them out, so explicitly ignore them to prevent
|
|
|
|
// log spam when verbose logging is enabled.
|
|
|
|
return
|
|
|
|
}
|
2024-08-28 15:06:17 +00:00
|
|
|
if isMcast && !isBroadcast {
|
2024-08-14 04:09:53 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(bradfitz): handle packets to e.g. [fe80::50cc:ccff:fecc:cc01]:43619
|
|
|
|
// and don't fall through to the router below.
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
case layers.EthernetTypeIPv4:
|
|
|
|
// Below
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send ethernet broadcasts and unicast ethernet frames to peers
|
|
|
|
// on the same network. This is all LAN traffic that isn't meant
|
|
|
|
// for the router/gw itself:
|
2024-08-14 04:09:53 +00:00
|
|
|
if isBroadcast || !forRouter {
|
|
|
|
n.writeEth(ep.gp.Data())
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
|
|
|
|
if forRouter {
|
2024-08-14 04:09:53 +00:00
|
|
|
n.HandleEthernetPacketForRouter(ep)
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// HandleUDPPacket handles a UDP packet arriving from the internet,
|
|
|
|
// addressed to the router's WAN IP. It is then NATed back to a
|
|
|
|
// LAN IP here and wrapped in an ethernet layer and delivered
|
|
|
|
// to the network.
|
|
|
|
func (n *network) HandleUDPPacket(p UDPPacket) {
|
2024-08-09 04:29:09 +00:00
|
|
|
buf, err := n.serializedUDPPacket(p.Src, p.Dst, p.Payload, nil)
|
|
|
|
if err != nil {
|
|
|
|
n.logf("serializing UDP packet: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n.s.pcapWriter.WritePacket(gopacket.CaptureInfo{
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
CaptureLength: len(buf),
|
|
|
|
Length: len(buf),
|
|
|
|
InterfaceIndex: n.wanInterfaceID,
|
|
|
|
}, buf)
|
2024-09-03 22:00:18 +00:00
|
|
|
if p.Dst.Addr().Is4() && n.breakWAN4 {
|
|
|
|
// Blackhole the packet.
|
|
|
|
return
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
dst := n.doNATIn(p.Src, p.Dst)
|
|
|
|
if !dst.IsValid() {
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("Warning: NAT dropped packet; no mapping for %v=>%v", p.Src, p.Dst)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
p.Dst = dst
|
2024-08-09 04:29:09 +00:00
|
|
|
buf, err = n.serializedUDPPacket(p.Src, p.Dst, p.Payload, nil)
|
|
|
|
if err != nil {
|
|
|
|
n.logf("serializing UDP packet: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n.s.pcapWriter.WritePacket(gopacket.CaptureInfo{
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
CaptureLength: len(buf),
|
|
|
|
Length: len(buf),
|
|
|
|
InterfaceIndex: n.lanInterfaceID,
|
|
|
|
}, buf)
|
2024-08-05 19:06:48 +00:00
|
|
|
n.WriteUDPPacketNoNAT(p)
|
|
|
|
}
|
|
|
|
|
2024-08-26 03:50:22 +00:00
|
|
|
func (n *network) nodeByIP(ip netip.Addr) (node *node, ok bool) {
|
|
|
|
if ip.Is4() {
|
|
|
|
node, ok = n.nodesByIP4[ip]
|
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
if !ok && ip.Is6() {
|
|
|
|
var mac MAC
|
|
|
|
n.macMu.Lock()
|
|
|
|
mac, ok = n.macOfIPv6[ip]
|
|
|
|
n.macMu.Unlock()
|
|
|
|
if !ok {
|
2024-08-26 03:50:22 +00:00
|
|
|
log.Printf("warning: no known MAC for IPv6 %v", ip)
|
2024-08-14 04:09:53 +00:00
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
node, ok = n.nodesByMAC[mac]
|
|
|
|
if !ok {
|
2024-08-26 03:50:22 +00:00
|
|
|
log.Printf("warning: no known node for MAC %v (IP %v)", mac, ip)
|
2024-08-14 04:09:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return node, ok
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
// WriteUDPPacketNoNAT writes a UDP packet to the network, without
|
|
|
|
// doing any NAT translation.
|
|
|
|
//
|
|
|
|
// The packet will always have the ethernet src MAC of the router
|
|
|
|
// so this should not be used for packets between clients on the
|
|
|
|
// same ethernet segment.
|
|
|
|
func (n *network) WriteUDPPacketNoNAT(p UDPPacket) {
|
|
|
|
src, dst := p.Src, p.Dst
|
2024-08-26 03:50:22 +00:00
|
|
|
node, ok := n.nodeByIP(dst.Addr())
|
2024-08-05 19:06:48 +00:00
|
|
|
if !ok {
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("no node for dest IP %v in UDP packet %v=>%v", dst.Addr(), p.Src, p.Dst)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
eth := &layers.Ethernet{
|
2024-08-31 02:23:49 +00:00
|
|
|
SrcMAC: n.mac.HWAddr(), // of gateway
|
|
|
|
DstMAC: node.mac.HWAddr(),
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-09 04:29:09 +00:00
|
|
|
ethRaw, err := n.serializedUDPPacket(src, dst, p.Payload, eth)
|
|
|
|
if err != nil {
|
|
|
|
n.logf("serializing UDP packet: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n.writeEth(ethRaw)
|
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
type serializableNetworkLayer interface {
|
|
|
|
gopacket.SerializableLayer
|
|
|
|
gopacket.NetworkLayer
|
|
|
|
}
|
|
|
|
|
|
|
|
func mkIPLayer(proto layers.IPProtocol, src, dst netip.Addr) serializableNetworkLayer {
|
|
|
|
if src.Is4() {
|
|
|
|
return &layers.IPv4{
|
|
|
|
Protocol: proto,
|
|
|
|
SrcIP: src.AsSlice(),
|
|
|
|
DstIP: dst.AsSlice(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if src.Is6() {
|
|
|
|
return &layers.IPv6{
|
|
|
|
NextHeader: proto,
|
|
|
|
SrcIP: src.AsSlice(),
|
|
|
|
DstIP: dst.AsSlice(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
panic("invalid src IP")
|
|
|
|
}
|
|
|
|
|
2024-08-09 04:29:09 +00:00
|
|
|
// serializedUDPPacket serializes a UDP packet with the given source and
|
|
|
|
// destination IP:port pairs, and payload.
|
|
|
|
//
|
|
|
|
// If eth is non-nil, it will be used as the Ethernet layer, otherwise the
|
|
|
|
// Ethernet layer will be omitted from the serialization.
|
|
|
|
func (n *network) serializedUDPPacket(src, dst netip.AddrPort, payload []byte, eth *layers.Ethernet) ([]byte, error) {
|
2024-08-14 04:09:53 +00:00
|
|
|
ip := mkIPLayer(layers.IPProtocolUDP, src.Addr(), dst.Addr())
|
2024-08-05 19:06:48 +00:00
|
|
|
udp := &layers.UDP{
|
|
|
|
SrcPort: layers.UDPPort(src.Port()),
|
|
|
|
DstPort: layers.UDPPort(dst.Port()),
|
|
|
|
}
|
2024-08-09 04:29:09 +00:00
|
|
|
if eth == nil {
|
2024-08-31 02:23:49 +00:00
|
|
|
return mkPacket(ip, udp, gopacket.Payload(payload))
|
2024-08-28 19:55:46 +00:00
|
|
|
} else {
|
2024-08-31 02:23:49 +00:00
|
|
|
return mkPacket(eth, ip, udp, gopacket.Payload(payload))
|
2024-08-09 04:29:09 +00:00
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
// HandleEthernetPacketForRouter handles a packet that is
|
2024-08-05 19:06:48 +00:00
|
|
|
// directed to the router/gateway itself. The packet may be to the
|
|
|
|
// broadcast MAC address, or to the router's MAC address. The target
|
|
|
|
// IP may be the router's IP, or an internet (routed) IP.
|
2024-08-14 04:09:53 +00:00
|
|
|
func (n *network) HandleEthernetPacketForRouter(ep EthernetPacket) {
|
2024-08-05 19:06:48 +00:00
|
|
|
packet := ep.gp
|
2024-08-14 04:09:53 +00:00
|
|
|
flow, ok := flow(packet)
|
2024-08-05 19:06:48 +00:00
|
|
|
if !ok {
|
2024-08-14 04:09:53 +00:00
|
|
|
n.logf("dropping non-IP packet: %v", packet)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
2024-08-25 01:43:40 +00:00
|
|
|
dstIP := flow.dst
|
2024-08-14 04:09:53 +00:00
|
|
|
toForward := dstIP != n.lanIP4.Addr() && dstIP != netip.IPv4Unspecified() && !dstIP.IsLinkLocalUnicast()
|
2024-08-05 19:06:48 +00:00
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
// Pre-NAT mapping, for DNS/etc responses:
|
2024-08-25 01:43:40 +00:00
|
|
|
if flow.src.Is6() {
|
2024-08-14 04:09:53 +00:00
|
|
|
n.macMu.Lock()
|
2024-08-25 01:43:40 +00:00
|
|
|
mak.Set(&n.macOfIPv6, flow.src, ep.SrcMAC())
|
2024-08-14 04:09:53 +00:00
|
|
|
n.macMu.Unlock()
|
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
if udp, ok := packet.Layer(layers.LayerTypeUDP).(*layers.UDP); ok {
|
|
|
|
n.handleUDPPacketForRouter(ep, udp, toForward, flow)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if toForward && n.s.shouldInterceptTCP(packet) {
|
2024-09-03 22:00:18 +00:00
|
|
|
if flow.dst.Is4() && n.breakWAN4 {
|
|
|
|
// Blackhole the packet.
|
|
|
|
return
|
|
|
|
}
|
2024-08-25 01:43:40 +00:00
|
|
|
var base *layers.BaseLayer
|
|
|
|
proto := header.IPv4ProtocolNumber
|
|
|
|
if v4, ok := packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4); ok {
|
|
|
|
base = &v4.BaseLayer
|
|
|
|
} else if v6, ok := packet.Layer(layers.LayerTypeIPv6).(*layers.IPv6); ok {
|
|
|
|
base = &v6.BaseLayer
|
|
|
|
proto = header.IPv6ProtocolNumber
|
|
|
|
} else {
|
|
|
|
panic("not v4, not v6")
|
|
|
|
}
|
|
|
|
pktCopy := make([]byte, 0, len(base.Contents)+len(base.Payload))
|
|
|
|
pktCopy = append(pktCopy, base.Contents...)
|
|
|
|
pktCopy = append(pktCopy, base.Payload...)
|
|
|
|
packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
|
|
|
Payload: buffer.MakeWithData(pktCopy),
|
|
|
|
})
|
|
|
|
n.linkEP.InjectInbound(proto, packetBuf)
|
|
|
|
packetBuf.DecRef()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-26 03:43:20 +00:00
|
|
|
if flow.src.Is6() && flow.src.IsLinkLocalUnicast() && !flow.dst.IsLinkLocalUnicast() {
|
|
|
|
// Don't log.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
n.logf("router got unknown packet: %v", packet)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) handleUDPPacketForRouter(ep EthernetPacket, udp *layers.UDP, toForward bool, flow ipSrcDst) {
|
|
|
|
packet := ep.gp
|
|
|
|
srcIP, dstIP := flow.src, flow.dst
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
if isDHCPRequest(packet) {
|
2024-08-29 14:02:49 +00:00
|
|
|
if !n.v4 {
|
|
|
|
n.logf("dropping DHCPv4 packet on v6-only network")
|
|
|
|
return
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
res, err := n.s.createDHCPResponse(packet)
|
|
|
|
if err != nil {
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("createDHCPResponse: %v", err)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
2024-08-09 03:11:50 +00:00
|
|
|
n.writeEth(res)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if isMDNSQuery(packet) || isIGMP(packet) {
|
|
|
|
// Don't log. Spammy for now.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if isDNSRequest(packet) {
|
|
|
|
res, err := n.s.createDNSResponse(packet)
|
|
|
|
if err != nil {
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("createDNSResponse: %v", err)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
2024-08-09 03:11:50 +00:00
|
|
|
n.writeEth(res)
|
2024-08-05 19:06:48 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
if fakeSyslog.Match(dstIP) {
|
2024-08-26 03:50:22 +00:00
|
|
|
node, ok := n.nodeByIP(srcIP)
|
2024-08-13 04:39:28 +00:00
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if node.verboseSyslog {
|
|
|
|
// TODO(bradfitz): parse this and capture it, structured, into
|
|
|
|
// node's log buffer.
|
2024-08-30 17:54:51 +00:00
|
|
|
n.logf("syslog from %v: %s", node, udp.Payload)
|
2024-08-13 04:39:28 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
if dstIP == n.lanIP4.Addr() && isNATPMP(udp) {
|
2024-08-05 19:06:48 +00:00
|
|
|
n.handleNATPMPRequest(UDPPacket{
|
|
|
|
Src: netip.AddrPortFrom(srcIP, uint16(udp.SrcPort)),
|
|
|
|
Dst: netip.AddrPortFrom(dstIP, uint16(udp.DstPort)),
|
|
|
|
Payload: udp.Payload,
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
if toForward {
|
2024-09-03 22:00:18 +00:00
|
|
|
if dstIP.Is4() && n.breakWAN4 {
|
|
|
|
// Blackhole the packet.
|
|
|
|
return
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
src := netip.AddrPortFrom(srcIP, uint16(udp.SrcPort))
|
|
|
|
dst := netip.AddrPortFrom(dstIP, uint16(udp.DstPort))
|
2024-08-09 04:29:09 +00:00
|
|
|
buf, err := n.serializedUDPPacket(src, dst, udp.Payload, nil)
|
|
|
|
if err != nil {
|
|
|
|
n.logf("serializing UDP packet: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n.s.pcapWriter.WritePacket(gopacket.CaptureInfo{
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
CaptureLength: len(buf),
|
|
|
|
Length: len(buf),
|
|
|
|
InterfaceIndex: n.lanInterfaceID,
|
|
|
|
}, buf)
|
|
|
|
|
2024-08-23 21:14:28 +00:00
|
|
|
lanSrc := src // the original src, before NAT (for logging only)
|
2024-08-05 19:06:48 +00:00
|
|
|
src = n.doNATOut(src, dst)
|
2024-08-23 21:14:28 +00:00
|
|
|
if !src.IsValid() {
|
|
|
|
n.logf("warning: NAT dropped packet; no NAT out mapping for %v=>%v", lanSrc, dst)
|
|
|
|
return
|
|
|
|
}
|
2024-08-09 04:29:09 +00:00
|
|
|
buf, err = n.serializedUDPPacket(src, dst, udp.Payload, nil)
|
|
|
|
if err != nil {
|
|
|
|
n.logf("serializing UDP packet: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n.s.pcapWriter.WritePacket(gopacket.CaptureInfo{
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
CaptureLength: len(buf),
|
|
|
|
Length: len(buf),
|
|
|
|
InterfaceIndex: n.wanInterfaceID,
|
|
|
|
}, buf)
|
2024-08-05 19:06:48 +00:00
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
if src.Addr().Is6() {
|
|
|
|
n.macMu.Lock()
|
|
|
|
mak.Set(&n.macOfIPv6, src.Addr(), ep.SrcMAC())
|
|
|
|
n.macMu.Unlock()
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
n.s.routeUDPPacket(UDPPacket{
|
|
|
|
Src: src,
|
|
|
|
Dst: dst,
|
|
|
|
Payload: udp.Payload,
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
if udp.DstPort == pcpPort || udp.DstPort == ssdpPort {
|
2024-08-23 18:43:12 +00:00
|
|
|
// We handle NAT-PMP, but not these yet.
|
|
|
|
// TODO(bradfitz): handle? marginal utility so far.
|
|
|
|
// Don't log about them being unknown.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
n.logf("router got unknown UDP packet: %v", packet)
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
func (n *network) handleIPv6RouterSolicitation(ep EthernetPacket, rs *layers.ICMPv6RouterSolicitation) {
|
|
|
|
v6 := ep.gp.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
|
|
|
|
|
|
|
|
// Send a router advertisement back.
|
|
|
|
eth := &layers.Ethernet{
|
|
|
|
SrcMAC: n.mac.HWAddr(),
|
|
|
|
DstMAC: ep.SrcMAC().HWAddr(),
|
|
|
|
EthernetType: layers.EthernetTypeIPv6,
|
|
|
|
}
|
2024-08-27 05:21:14 +00:00
|
|
|
n.logf("sending IPv6 router advertisement to %v from %v", eth.DstMAC, eth.SrcMAC)
|
2024-08-14 04:09:53 +00:00
|
|
|
ip := &layers.IPv6{
|
|
|
|
NextHeader: layers.IPProtocolICMPv6,
|
2024-08-31 02:23:49 +00:00
|
|
|
HopLimit: 255, // per RFC 4861, 7.1.1 etc (all NDP messages); don't use mkPacket's default of 64
|
2024-08-14 04:09:53 +00:00
|
|
|
SrcIP: net.ParseIP("fe80::1"),
|
|
|
|
DstIP: v6.SrcIP,
|
|
|
|
}
|
|
|
|
icmp := &layers.ICMPv6{
|
|
|
|
TypeCode: layers.CreateICMPv6TypeCode(layers.ICMPv6TypeRouterAdvertisement, 0),
|
|
|
|
}
|
|
|
|
pfx := make([]byte, 0, 30) // it's 32 on the wire, once gopacket adds two byte header
|
|
|
|
pfx = append(pfx, byte(64)) // CIDR length
|
|
|
|
pfx = append(pfx, byte(0xc0)) // flags: On-Link, Autonomous
|
|
|
|
pfx = binary.BigEndian.AppendUint32(pfx, 86400) // valid lifetime
|
|
|
|
pfx = binary.BigEndian.AppendUint32(pfx, 14400) // preferred lifetime
|
|
|
|
pfx = binary.BigEndian.AppendUint32(pfx, 0) // reserved
|
|
|
|
wanIP := n.wanIP6.Addr().As16()
|
|
|
|
pfx = append(pfx, wanIP[:]...)
|
|
|
|
|
|
|
|
ra := &layers.ICMPv6RouterAdvertisement{
|
|
|
|
RouterLifetime: 1800,
|
|
|
|
Options: []layers.ICMPv6Option{
|
|
|
|
{
|
|
|
|
Type: layers.ICMPv6OptPrefixInfo,
|
|
|
|
Data: pfx,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
2024-08-31 02:23:49 +00:00
|
|
|
pkt, err := mkPacket(eth, ip, icmp, ra)
|
2024-08-28 19:55:46 +00:00
|
|
|
if err != nil {
|
2024-08-14 04:09:53 +00:00
|
|
|
n.logf("serializing ICMPv6 RA: %v", err)
|
|
|
|
return
|
|
|
|
}
|
2024-08-28 19:55:46 +00:00
|
|
|
n.writeEth(pkt)
|
2024-08-14 04:09:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) handleIPv6NeighborSolicitation(ep EthernetPacket, ns *layers.ICMPv6NeighborSolicitation) {
|
|
|
|
v6 := ep.gp.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
|
|
|
|
|
|
|
|
targetIP, ok := netip.AddrFromSlice(ns.TargetAddress)
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
var srcMAC MAC
|
|
|
|
if targetIP == netip.MustParseAddr("fe80::1") {
|
|
|
|
srcMAC = n.mac
|
|
|
|
} else {
|
|
|
|
n.logf("Ignoring IPv6 NS request from %v for target %v", ep.SrcMAC(), targetIP)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n.logf("replying to IPv6 NS %v->%v about target %v (replySrc=%v)", ep.SrcMAC(), ep.DstMAC(), targetIP, srcMAC)
|
|
|
|
|
|
|
|
// Send a neighbor advertisement back.
|
|
|
|
eth := &layers.Ethernet{
|
|
|
|
SrcMAC: srcMAC.HWAddr(),
|
|
|
|
DstMAC: ep.SrcMAC().HWAddr(),
|
|
|
|
EthernetType: layers.EthernetTypeIPv6,
|
|
|
|
}
|
|
|
|
ip := &layers.IPv6{
|
2024-08-31 02:23:49 +00:00
|
|
|
HopLimit: 255, // per RFC 4861, 7.1.1 etc (all NDP messages); don't use mkPacket's default of 64
|
2024-08-14 04:09:53 +00:00
|
|
|
NextHeader: layers.IPProtocolICMPv6,
|
|
|
|
SrcIP: ns.TargetAddress,
|
|
|
|
DstIP: v6.SrcIP,
|
|
|
|
}
|
|
|
|
icmp := &layers.ICMPv6{
|
|
|
|
TypeCode: layers.CreateICMPv6TypeCode(layers.ICMPv6TypeNeighborAdvertisement, 0),
|
|
|
|
}
|
|
|
|
var flags uint8 = 0x40 // solicited
|
|
|
|
if srcMAC == n.mac {
|
|
|
|
flags |= 0x80 // router
|
|
|
|
}
|
|
|
|
flags |= 0x20 // override
|
|
|
|
|
|
|
|
na := &layers.ICMPv6NeighborAdvertisement{
|
|
|
|
TargetAddress: ns.TargetAddress,
|
|
|
|
Flags: flags,
|
|
|
|
}
|
|
|
|
na.Options = append(na.Options, layers.ICMPv6Option{
|
|
|
|
Type: layers.ICMPv6OptTargetAddress,
|
|
|
|
Data: srcMAC.HWAddr(),
|
|
|
|
})
|
2024-08-31 02:23:49 +00:00
|
|
|
pkt, err := mkPacket(eth, ip, icmp, na)
|
2024-08-29 13:59:06 +00:00
|
|
|
if err != nil {
|
|
|
|
n.logf("serializing ICMPv6 NA: %v", err)
|
2024-08-14 04:09:53 +00:00
|
|
|
}
|
2024-08-29 13:59:06 +00:00
|
|
|
if !n.writeEth(pkt) {
|
2024-08-14 04:09:53 +00:00
|
|
|
n.logf("failed to writeEth for IPv6 NA reply for %v", targetIP)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// createDHCPResponse creates a DHCPv4 response for the given DHCPv4 request.
|
2024-08-05 19:06:48 +00:00
|
|
|
func (s *Server) createDHCPResponse(request gopacket.Packet) ([]byte, error) {
|
|
|
|
ethLayer := request.Layer(layers.LayerTypeEthernet).(*layers.Ethernet)
|
|
|
|
srcMAC, ok := macOf(ethLayer.SrcMAC)
|
|
|
|
if !ok {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
node, ok := s.nodeByMAC[srcMAC]
|
|
|
|
if !ok {
|
|
|
|
log.Printf("DHCP request from unknown node %v; ignoring", srcMAC)
|
|
|
|
return nil, nil
|
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
gwIP := node.net.lanIP4.Addr()
|
2024-08-05 19:06:48 +00:00
|
|
|
|
|
|
|
ipLayer := request.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
|
|
|
|
udpLayer := request.Layer(layers.LayerTypeUDP).(*layers.UDP)
|
|
|
|
dhcpLayer := request.Layer(layers.LayerTypeDHCPv4).(*layers.DHCPv4)
|
|
|
|
|
|
|
|
response := &layers.DHCPv4{
|
|
|
|
Operation: layers.DHCPOpReply,
|
|
|
|
HardwareType: layers.LinkTypeEthernet,
|
|
|
|
HardwareLen: 6,
|
|
|
|
Xid: dhcpLayer.Xid,
|
|
|
|
ClientHWAddr: dhcpLayer.ClientHWAddr,
|
|
|
|
Flags: dhcpLayer.Flags,
|
|
|
|
YourClientIP: node.lanIP.AsSlice(),
|
|
|
|
Options: []layers.DHCPOption{
|
|
|
|
{
|
|
|
|
Type: layers.DHCPOptServerID,
|
|
|
|
Data: gwIP.AsSlice(), // DHCP server's IP
|
|
|
|
Length: 4,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
var msgType layers.DHCPMsgType
|
|
|
|
for _, opt := range dhcpLayer.Options {
|
|
|
|
if opt.Type == layers.DHCPOptMessageType && opt.Length > 0 {
|
|
|
|
msgType = layers.DHCPMsgType(opt.Data[0])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
switch msgType {
|
|
|
|
case layers.DHCPMsgTypeDiscover:
|
|
|
|
response.Options = append(response.Options, layers.DHCPOption{
|
|
|
|
Type: layers.DHCPOptMessageType,
|
|
|
|
Data: []byte{byte(layers.DHCPMsgTypeOffer)},
|
|
|
|
Length: 1,
|
|
|
|
})
|
|
|
|
case layers.DHCPMsgTypeRequest:
|
|
|
|
response.Options = append(response.Options,
|
|
|
|
layers.DHCPOption{
|
|
|
|
Type: layers.DHCPOptMessageType,
|
|
|
|
Data: []byte{byte(layers.DHCPMsgTypeAck)},
|
|
|
|
Length: 1,
|
|
|
|
},
|
|
|
|
layers.DHCPOption{
|
|
|
|
Type: layers.DHCPOptLeaseTime,
|
|
|
|
Data: binary.BigEndian.AppendUint32(nil, 3600), // hour? sure.
|
|
|
|
Length: 4,
|
|
|
|
},
|
|
|
|
layers.DHCPOption{
|
|
|
|
Type: layers.DHCPOptRouter,
|
|
|
|
Data: gwIP.AsSlice(),
|
|
|
|
Length: 4,
|
|
|
|
},
|
|
|
|
layers.DHCPOption{
|
|
|
|
Type: layers.DHCPOptDNS,
|
2024-08-23 19:49:51 +00:00
|
|
|
Data: fakeDNS.v4.AsSlice(),
|
2024-08-05 19:06:48 +00:00
|
|
|
Length: 4,
|
|
|
|
},
|
|
|
|
layers.DHCPOption{
|
|
|
|
Type: layers.DHCPOptSubnetMask,
|
2024-08-14 04:09:53 +00:00
|
|
|
Data: net.CIDRMask(node.net.lanIP4.Bits(), 32),
|
2024-08-05 19:06:48 +00:00
|
|
|
Length: 4,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
eth := &layers.Ethernet{
|
|
|
|
SrcMAC: node.net.mac.HWAddr(),
|
|
|
|
DstMAC: ethLayer.SrcMAC,
|
2024-08-14 04:09:53 +00:00
|
|
|
EthernetType: layers.EthernetTypeIPv4, // never IPv6 for DHCP
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
ip := &layers.IPv4{
|
|
|
|
Protocol: layers.IPProtocolUDP,
|
|
|
|
SrcIP: ipLayer.DstIP,
|
|
|
|
DstIP: ipLayer.SrcIP,
|
|
|
|
}
|
|
|
|
udp := &layers.UDP{
|
|
|
|
SrcPort: udpLayer.DstPort,
|
|
|
|
DstPort: udpLayer.SrcPort,
|
|
|
|
}
|
2024-08-31 02:23:49 +00:00
|
|
|
return mkPacket(eth, ip, udp, response)
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
2024-08-29 14:02:49 +00:00
|
|
|
// isDHCPRequest reports whether pkt is a DHCPv4 request.
|
2024-08-05 19:06:48 +00:00
|
|
|
func isDHCPRequest(pkt gopacket.Packet) bool {
|
|
|
|
v4, ok := pkt.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
|
|
|
|
if !ok || v4.Protocol != layers.IPProtocolUDP {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
udp, ok := pkt.Layer(layers.LayerTypeUDP).(*layers.UDP)
|
|
|
|
return ok && udp.DstPort == 67 && udp.SrcPort == 68
|
|
|
|
}
|
|
|
|
|
|
|
|
func isIGMP(pkt gopacket.Packet) bool {
|
|
|
|
return pkt.Layer(layers.LayerTypeIGMP) != nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func isMDNSQuery(pkt gopacket.Packet) bool {
|
|
|
|
udp, ok := pkt.Layer(layers.LayerTypeUDP).(*layers.UDP)
|
|
|
|
// TODO(bradfitz): also check IPv4 DstIP=224.0.0.251 (or whatever)
|
|
|
|
return ok && udp.SrcPort == 5353 && udp.DstPort == 5353
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) shouldInterceptTCP(pkt gopacket.Packet) bool {
|
|
|
|
tcp, ok := pkt.Layer(layers.LayerTypeTCP).(*layers.TCP)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
2024-08-23 18:27:42 +00:00
|
|
|
if tcp.DstPort == 123 {
|
|
|
|
// Test port for TCP interception. Not really useful, but cute for
|
|
|
|
// demos.
|
2024-08-05 19:06:48 +00:00
|
|
|
return true
|
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
flow, ok := flow(pkt)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
2024-08-26 03:43:20 +00:00
|
|
|
if flow.src.Is6() && flow.src.IsLinkLocalUnicast() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
if tcp.DstPort == 80 || tcp.DstPort == 443 {
|
2024-08-23 19:49:51 +00:00
|
|
|
for _, v := range []virtualIP{fakeControl, fakeDERP1, fakeDERP2, fakeLogCatcher} {
|
2024-08-14 04:09:53 +00:00
|
|
|
if v.Match(flow.dst) {
|
2024-08-23 19:49:51 +00:00
|
|
|
return true
|
|
|
|
}
|
2024-08-07 00:33:45 +00:00
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
if fakeProxyControlplane.Match(flow.dst) {
|
2024-08-07 00:33:45 +00:00
|
|
|
return s.blendReality
|
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
if s.derpIPs.Contains(flow.dst) {
|
2024-08-05 19:06:48 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
if tcp.DstPort == 8008 && fakeTestAgent.Match(flow.dst) {
|
2024-08-05 19:06:48 +00:00
|
|
|
// Connection from cmd/tta.
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
type ipSrcDst struct {
|
|
|
|
src netip.Addr
|
|
|
|
dst netip.Addr
|
|
|
|
}
|
|
|
|
|
|
|
|
func flow(gp gopacket.Packet) (f ipSrcDst, ok bool) {
|
|
|
|
if gp == nil {
|
|
|
|
return f, false
|
|
|
|
}
|
|
|
|
n := gp.NetworkLayer()
|
|
|
|
if n == nil {
|
|
|
|
return f, false
|
|
|
|
}
|
|
|
|
sb, db := n.NetworkFlow().Endpoints()
|
|
|
|
src, _ := netip.AddrFromSlice(sb.Raw())
|
|
|
|
dst, _ := netip.AddrFromSlice(db.Raw())
|
|
|
|
return ipSrcDst{src: src, dst: dst}, src.IsValid() && dst.IsValid()
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
// isDNSRequest reports whether pkt is a DNS request to the fake DNS server.
|
|
|
|
func isDNSRequest(pkt gopacket.Packet) bool {
|
|
|
|
udp, ok := pkt.Layer(layers.LayerTypeUDP).(*layers.UDP)
|
|
|
|
if !ok || udp.DstPort != 53 {
|
|
|
|
return false
|
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
f, ok := flow(pkt)
|
2024-08-05 19:06:48 +00:00
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
if !fakeDNS.Match(f.dst) {
|
|
|
|
// TODO(bradfitz): maybe support configs where DNS is local in the LAN
|
2024-08-05 19:06:48 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
dns, ok := pkt.Layer(layers.LayerTypeDNS).(*layers.DNS)
|
|
|
|
return ok && dns.QR == false && len(dns.Questions) > 0
|
|
|
|
}
|
|
|
|
|
2024-08-25 01:43:40 +00:00
|
|
|
func isNATPMP(udp *layers.UDP) bool {
|
|
|
|
return udp.DstPort == 5351 && len(udp.Payload) > 0 && udp.Payload[0] == 0 // version 0, not 2 for PCP
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func makeSTUNReply(req UDPPacket) (res UDPPacket, ok bool) {
|
|
|
|
txid, err := stun.ParseBindingRequest(req.Payload)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("invalid STUN request: %v", err)
|
|
|
|
return res, false
|
|
|
|
}
|
|
|
|
return UDPPacket{
|
|
|
|
Src: req.Dst,
|
|
|
|
Dst: req.Src,
|
|
|
|
Payload: stun.Response(txid, req.Src),
|
|
|
|
}, true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) createDNSResponse(pkt gopacket.Packet) ([]byte, error) {
|
2024-08-14 04:09:53 +00:00
|
|
|
flow, ok := flow(pkt)
|
|
|
|
if !ok {
|
|
|
|
return nil, nil
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
ethLayer := pkt.Layer(layers.LayerTypeEthernet).(*layers.Ethernet)
|
|
|
|
udpLayer := pkt.Layer(layers.LayerTypeUDP).(*layers.UDP)
|
|
|
|
dnsLayer := pkt.Layer(layers.LayerTypeDNS).(*layers.DNS)
|
|
|
|
|
|
|
|
if dnsLayer.OpCode != layers.DNSOpCodeQuery || dnsLayer.QR || len(dnsLayer.Questions) == 0 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
response := &layers.DNS{
|
|
|
|
ID: dnsLayer.ID,
|
|
|
|
QR: true,
|
|
|
|
AA: true,
|
|
|
|
TC: false,
|
|
|
|
RD: dnsLayer.RD,
|
|
|
|
RA: true,
|
|
|
|
OpCode: layers.DNSOpCodeQuery,
|
|
|
|
ResponseCode: layers.DNSResponseCodeNoErr,
|
|
|
|
}
|
|
|
|
|
|
|
|
var names []string
|
|
|
|
for _, q := range dnsLayer.Questions {
|
|
|
|
response.QDCount++
|
|
|
|
response.Questions = append(response.Questions, q)
|
|
|
|
|
|
|
|
if mem.HasSuffix(mem.B(q.Name), mem.S(".pool.ntp.org")) {
|
|
|
|
// Just drop DNS queries for NTP servers. For Debian/etc guests used
|
|
|
|
// during development. Not needed. Assume VM guests get correct time
|
|
|
|
// via their hypervisor.
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
names = append(names, q.Type.String()+"/"+string(q.Name))
|
2024-08-14 04:09:53 +00:00
|
|
|
if q.Class != layers.DNSClassIN {
|
2024-08-05 19:06:48 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
if q.Type == layers.DNSTypeA || q.Type == layers.DNSTypeAAAA {
|
|
|
|
if v, ok := vips[string(q.Name)]; ok {
|
|
|
|
ip := v.v4
|
|
|
|
if q.Type == layers.DNSTypeAAAA {
|
|
|
|
ip = v.v6
|
|
|
|
}
|
|
|
|
response.ANCount++
|
|
|
|
response.Answers = append(response.Answers, layers.DNSResourceRecord{
|
|
|
|
Name: q.Name,
|
|
|
|
Type: q.Type,
|
|
|
|
Class: q.Class,
|
|
|
|
IP: ip.AsSlice(),
|
|
|
|
TTL: 60,
|
|
|
|
})
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
// Make reply layers, all reversed.
|
2024-08-05 19:06:48 +00:00
|
|
|
eth2 := &layers.Ethernet{
|
2024-08-31 02:23:49 +00:00
|
|
|
SrcMAC: ethLayer.DstMAC,
|
|
|
|
DstMAC: ethLayer.SrcMAC,
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-14 04:09:53 +00:00
|
|
|
ip2 := mkIPLayer(layers.IPProtocolUDP, flow.dst, flow.src)
|
2024-08-05 19:06:48 +00:00
|
|
|
udp2 := &layers.UDP{
|
|
|
|
SrcPort: udpLayer.DstPort,
|
|
|
|
DstPort: udpLayer.SrcPort,
|
|
|
|
}
|
|
|
|
|
2024-08-31 02:23:49 +00:00
|
|
|
resPkt, err := mkPacket(eth2, ip2, udp2, response)
|
2024-08-29 13:59:06 +00:00
|
|
|
if err != nil {
|
2024-08-05 19:06:48 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
const debugDNS = false
|
|
|
|
if debugDNS {
|
|
|
|
if len(response.Answers) > 0 {
|
2024-08-29 13:59:06 +00:00
|
|
|
back := gopacket.NewPacket(resPkt, layers.LayerTypeEthernet, gopacket.Lazy)
|
2024-08-14 04:09:53 +00:00
|
|
|
log.Printf("createDNSResponse generated answers: %v", back)
|
2024-08-05 19:06:48 +00:00
|
|
|
} else {
|
|
|
|
log.Printf("made empty response for %q", names)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-29 13:59:06 +00:00
|
|
|
return resPkt, nil
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// doNATOut performs NAT on an outgoing packet from src to dst, where
|
|
|
|
// src is a LAN IP and dst is a WAN IP.
|
|
|
|
//
|
2024-08-08 19:10:00 +00:00
|
|
|
// It returns the source WAN ip:port to use.
|
2024-08-23 21:14:28 +00:00
|
|
|
//
|
|
|
|
// If newSrc is invalid, the packet should be dropped.
|
2024-08-05 19:06:48 +00:00
|
|
|
func (n *network) doNATOut(src, dst netip.AddrPort) (newSrc netip.AddrPort) {
|
2024-08-14 04:09:53 +00:00
|
|
|
if src.Addr().Is6() {
|
|
|
|
// TODO(bradfitz): IPv6 NAT? For now, normal IPv6 only.
|
|
|
|
return src
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
n.natMu.Lock()
|
|
|
|
defer n.natMu.Unlock()
|
2024-08-08 19:10:00 +00:00
|
|
|
|
|
|
|
// First see if there's a port mapping, before doing NAT.
|
|
|
|
if wanAP, ok := n.portMapFlow[portmapFlowKey{
|
|
|
|
peerWAN: dst,
|
|
|
|
lanAP: src,
|
|
|
|
}]; ok {
|
|
|
|
return wanAP
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
return n.natTable.PickOutgoingSrc(src, dst, time.Now())
|
|
|
|
}
|
|
|
|
|
2024-08-08 19:10:00 +00:00
|
|
|
type portmapFlowKey struct {
|
|
|
|
peerWAN netip.AddrPort // the peer's WAN ip:port
|
|
|
|
lanAP netip.AddrPort
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
// doNATIn performs NAT on an incoming packet from WAN src to WAN dst, returning
|
|
|
|
// a new destination LAN ip:port to use.
|
2024-08-23 21:14:28 +00:00
|
|
|
//
|
|
|
|
// If newDst is invalid, the packet should be dropped.
|
2024-08-05 19:06:48 +00:00
|
|
|
func (n *network) doNATIn(src, dst netip.AddrPort) (newDst netip.AddrPort) {
|
2024-08-14 04:09:53 +00:00
|
|
|
if dst.Addr().Is6() {
|
|
|
|
// TODO(bradfitz): IPv6 NAT? For now, normal IPv6 only.
|
|
|
|
return dst
|
|
|
|
}
|
|
|
|
|
2024-08-05 19:06:48 +00:00
|
|
|
n.natMu.Lock()
|
|
|
|
defer n.natMu.Unlock()
|
2024-08-08 04:43:25 +00:00
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
|
|
|
|
// First see if there's a port mapping, before doing NAT.
|
|
|
|
if lanAP, ok := n.portMap[dst]; ok {
|
|
|
|
if now.Before(lanAP.expiry) {
|
2024-08-08 19:10:00 +00:00
|
|
|
mak.Set(&n.portMapFlow, portmapFlowKey{
|
|
|
|
peerWAN: src,
|
|
|
|
lanAP: lanAP.dst,
|
|
|
|
}, dst)
|
2024-08-08 19:47:54 +00:00
|
|
|
//n.logf("NAT: doNatIn: port mapping %v=>%v", dst, lanAP.dst)
|
2024-08-08 04:43:25 +00:00
|
|
|
return lanAP.dst
|
|
|
|
}
|
2024-08-08 19:47:54 +00:00
|
|
|
n.logf("NAT: doNatIn: port mapping EXPIRED for %v=>%v", dst, lanAP.dst)
|
2024-08-08 04:43:25 +00:00
|
|
|
delete(n.portMap, dst)
|
|
|
|
return netip.AddrPort{}
|
|
|
|
}
|
|
|
|
|
|
|
|
return n.natTable.PickIncomingDst(src, dst, now)
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsPublicPortUsed reports whether the given public port is currently in use.
|
|
|
|
//
|
|
|
|
// n.natMu must be held by the caller. (It's only called by nat implementations
|
|
|
|
// which are always called with natMu held))
|
|
|
|
func (n *network) IsPublicPortUsed(ap netip.AddrPort) bool {
|
|
|
|
_, ok := n.portMap[ap]
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) doPortMap(src netip.Addr, dstLANPort, wantExtPort uint16, sec int) (gotPort uint16, ok bool) {
|
|
|
|
n.natMu.Lock()
|
|
|
|
defer n.natMu.Unlock()
|
|
|
|
|
|
|
|
if !n.portmap {
|
|
|
|
return 0, false
|
|
|
|
}
|
|
|
|
|
2024-08-14 04:09:53 +00:00
|
|
|
wanAP := netip.AddrPortFrom(n.wanIP4, wantExtPort)
|
2024-08-08 04:43:25 +00:00
|
|
|
dst := netip.AddrPortFrom(src, dstLANPort)
|
|
|
|
|
|
|
|
if sec == 0 {
|
|
|
|
lanAP, ok := n.portMap[wanAP]
|
|
|
|
if ok && lanAP.dst.Addr() == src {
|
|
|
|
delete(n.portMap, wanAP)
|
|
|
|
}
|
|
|
|
return 0, false
|
|
|
|
}
|
|
|
|
|
|
|
|
// See if they already have a mapping and extend expiry if so.
|
|
|
|
for k, v := range n.portMap {
|
|
|
|
if v.dst == dst {
|
|
|
|
n.portMap[k] = portMapping{
|
|
|
|
dst: dst,
|
|
|
|
expiry: time.Now().Add(time.Duration(sec) * time.Second),
|
|
|
|
}
|
|
|
|
return k.Port(), true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for try := 0; try < 20_000; try++ {
|
|
|
|
if wanAP.Port() > 0 && !n.natTable.IsPublicPortUsed(wanAP) {
|
|
|
|
mak.Set(&n.portMap, wanAP, portMapping{
|
|
|
|
dst: dst,
|
|
|
|
expiry: time.Now().Add(time.Duration(sec) * time.Second),
|
|
|
|
})
|
2024-08-08 19:47:54 +00:00
|
|
|
n.logf("vnet: allocated NAT mapping from %v to %v", wanAP, dst)
|
2024-08-08 04:43:25 +00:00
|
|
|
return wanAP.Port(), true
|
|
|
|
}
|
|
|
|
wantExtPort = rand.N(uint16(32<<10)) + 32<<10
|
2024-08-14 04:09:53 +00:00
|
|
|
wanAP = netip.AddrPortFrom(n.wanIP4, wantExtPort)
|
2024-08-08 04:43:25 +00:00
|
|
|
}
|
|
|
|
return 0, false
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) createARPResponse(pkt gopacket.Packet) ([]byte, error) {
|
|
|
|
ethLayer, ok := pkt.Layer(layers.LayerTypeEthernet).(*layers.Ethernet)
|
|
|
|
if !ok {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
arpLayer, ok := pkt.Layer(layers.LayerTypeARP).(*layers.ARP)
|
|
|
|
if !ok ||
|
|
|
|
arpLayer.Operation != layers.ARPRequest ||
|
|
|
|
arpLayer.AddrType != layers.LinkTypeEthernet ||
|
|
|
|
arpLayer.Protocol != layers.EthernetTypeIPv4 ||
|
|
|
|
arpLayer.HwAddressSize != 6 ||
|
|
|
|
arpLayer.ProtAddressSize != 4 ||
|
|
|
|
len(arpLayer.DstProtAddress) != 4 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
wantIP := netip.AddrFrom4([4]byte(arpLayer.DstProtAddress))
|
|
|
|
foundMAC, ok := n.MACOfIP(wantIP)
|
|
|
|
if !ok {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
eth := &layers.Ethernet{
|
|
|
|
SrcMAC: foundMAC.HWAddr(),
|
|
|
|
DstMAC: ethLayer.SrcMAC,
|
|
|
|
EthernetType: layers.EthernetTypeARP,
|
|
|
|
}
|
|
|
|
|
|
|
|
a2 := &layers.ARP{
|
|
|
|
AddrType: layers.LinkTypeEthernet,
|
2024-08-14 04:09:53 +00:00
|
|
|
Protocol: layers.EthernetTypeIPv4, // never IPv6; IPv6 equivalent of ARP is handleIPv6NeighborSolicitation
|
2024-08-05 19:06:48 +00:00
|
|
|
HwAddressSize: 6,
|
|
|
|
ProtAddressSize: 4,
|
|
|
|
Operation: layers.ARPReply,
|
|
|
|
SourceHwAddress: foundMAC.HWAddr(),
|
|
|
|
SourceProtAddress: arpLayer.DstProtAddress,
|
|
|
|
DstHwAddress: ethLayer.SrcMAC,
|
|
|
|
DstProtAddress: arpLayer.SourceProtAddress,
|
|
|
|
}
|
|
|
|
|
|
|
|
buffer := gopacket.NewSerializeBuffer()
|
|
|
|
options := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}
|
|
|
|
if err := gopacket.SerializeLayers(buffer, options, eth, a2); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return buffer.Bytes(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *network) handleNATPMPRequest(req UDPPacket) {
|
2024-08-08 04:43:25 +00:00
|
|
|
if !n.portmap {
|
|
|
|
return
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
if string(req.Payload) == "\x00\x00" {
|
|
|
|
// https://www.rfc-editor.org/rfc/rfc6886#section-3.2
|
|
|
|
|
|
|
|
res := make([]byte, 0, 12)
|
|
|
|
res = append(res,
|
|
|
|
0, // version 0 (NAT-PMP)
|
|
|
|
128, // response to op 0 (128+0)
|
|
|
|
0, 0, // result code success
|
|
|
|
)
|
|
|
|
res = binary.BigEndian.AppendUint32(res, uint32(time.Now().Unix()))
|
2024-08-14 04:09:53 +00:00
|
|
|
wan4 := n.wanIP4.As4()
|
2024-08-05 19:06:48 +00:00
|
|
|
res = append(res, wan4[:]...)
|
|
|
|
n.WriteUDPPacketNoNAT(UDPPacket{
|
|
|
|
Src: req.Dst,
|
|
|
|
Dst: req.Src,
|
|
|
|
Payload: res,
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-08 04:43:25 +00:00
|
|
|
// Map UDP request
|
|
|
|
if len(req.Payload) == 12 && req.Payload[0] == 0 && req.Payload[1] == 1 {
|
|
|
|
// https://www.rfc-editor.org/rfc/rfc6886#section-3.3
|
|
|
|
// "00 01 00 00 ed 40 00 00 00 00 1c 20" =>
|
|
|
|
// 00 ver
|
|
|
|
// 01 op=map UDP
|
|
|
|
// 00 00 reserved (0 in request; in response, this is the result code)
|
|
|
|
// ed 40 internal port 60736
|
|
|
|
// 00 00 suggested external port
|
|
|
|
// 00 00 1c 20 suggested lifetime in seconds (7200 sec = 2 hours)
|
|
|
|
internalPort := binary.BigEndian.Uint16(req.Payload[4:6])
|
|
|
|
wantExtPort := binary.BigEndian.Uint16(req.Payload[6:8])
|
|
|
|
lifetimeSec := binary.BigEndian.Uint32(req.Payload[8:12])
|
|
|
|
gotPort, ok := n.doPortMap(req.Src.Addr(), internalPort, wantExtPort, int(lifetimeSec))
|
|
|
|
if !ok {
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("NAT-PMP map request for %v:%d failed", req.Src.Addr(), internalPort)
|
2024-08-08 04:43:25 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
res := make([]byte, 0, 16)
|
|
|
|
res = append(res,
|
|
|
|
0, // version 0 (NAT-PMP)
|
|
|
|
1+128, // response to op 1
|
|
|
|
0, 0, // result code success
|
|
|
|
)
|
|
|
|
res = binary.BigEndian.AppendUint32(res, uint32(time.Now().Unix()))
|
|
|
|
res = binary.BigEndian.AppendUint16(res, internalPort)
|
|
|
|
res = binary.BigEndian.AppendUint16(res, gotPort)
|
|
|
|
res = binary.BigEndian.AppendUint32(res, lifetimeSec)
|
|
|
|
n.WriteUDPPacketNoNAT(UDPPacket{
|
|
|
|
Src: req.Dst,
|
|
|
|
Dst: req.Src,
|
|
|
|
Payload: res,
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-08 17:36:07 +00:00
|
|
|
n.logf("TODO: handle NAT-PMP packet % 02x", req.Payload)
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// UDPPacket is a UDP packet.
|
|
|
|
//
|
|
|
|
// For the purposes of this project, a UDP packet
|
|
|
|
// (not a general IP packet) is the unit to be NAT'ed,
|
|
|
|
// as that's all that Tailscale uses.
|
|
|
|
type UDPPacket struct {
|
|
|
|
Src netip.AddrPort
|
|
|
|
Dst netip.AddrPort
|
|
|
|
Payload []byte // everything after UDP header
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) WriteStartingBanner(w io.Writer) {
|
|
|
|
fmt.Fprintf(w, "vnet serving clients:\n")
|
|
|
|
|
|
|
|
for _, n := range s.nodes {
|
2024-08-14 04:09:53 +00:00
|
|
|
fmt.Fprintf(w, " %v %15v (%v, %v)\n", n.mac, n.lanIP, n.net.wanIP4, n.net.natStyle.Load())
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type agentConn struct {
|
|
|
|
node *node
|
|
|
|
tc *gonet.TCPConn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) addIdleAgentConn(ac *agentConn) {
|
2024-08-08 17:36:07 +00:00
|
|
|
//log.Printf("got agent conn from %v", ac.node.mac)
|
2024-08-05 19:06:48 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
|
|
|
|
s.agentConns.Make()
|
|
|
|
s.agentConns.Add(ac)
|
|
|
|
|
|
|
|
if waiter, ok := s.agentConnWaiter[ac.node]; ok {
|
|
|
|
select {
|
|
|
|
case waiter <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) takeAgentConn(ctx context.Context, n *node) (_ *agentConn, ok bool) {
|
2024-08-26 03:43:20 +00:00
|
|
|
const debug = false
|
2024-08-05 19:06:48 +00:00
|
|
|
for {
|
|
|
|
ac, ok := s.takeAgentConnOne(n)
|
|
|
|
if ok {
|
2024-08-26 03:43:20 +00:00
|
|
|
if debug {
|
|
|
|
log.Printf("takeAgentConn: got agent conn for %v", n.mac)
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
return ac, true
|
|
|
|
}
|
|
|
|
s.mu.Lock()
|
|
|
|
ready := make(chan struct{})
|
|
|
|
mak.Set(&s.agentConnWaiter, n, ready)
|
|
|
|
s.mu.Unlock()
|
2024-08-07 00:33:45 +00:00
|
|
|
|
2024-08-26 03:43:20 +00:00
|
|
|
if debug {
|
|
|
|
log.Printf("takeAgentConn: waiting for agent conn for %v", n.mac)
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, false
|
|
|
|
case <-ready:
|
|
|
|
case <-time.After(time.Second):
|
|
|
|
// Try again regularly anyway, in case we have multiple clients
|
|
|
|
// trying to hit the same node, or if a race means we weren't in the
|
|
|
|
// select by the time addIdleAgentConn tried to signal us.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) takeAgentConnOne(n *node) (_ *agentConn, ok bool) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2024-08-26 03:43:20 +00:00
|
|
|
miss := 0
|
2024-08-05 19:06:48 +00:00
|
|
|
for ac := range s.agentConns {
|
|
|
|
if ac.node == n {
|
|
|
|
s.agentConns.Delete(ac)
|
|
|
|
return ac, true
|
|
|
|
}
|
2024-08-26 03:43:20 +00:00
|
|
|
miss++
|
|
|
|
}
|
|
|
|
if miss > 0 {
|
|
|
|
log.Printf("takeAgentConnOne: missed %d times for %v", miss, n.mac)
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
2024-08-08 04:31:50 +00:00
|
|
|
type NodeAgentClient struct {
|
|
|
|
*tailscale.LocalClient
|
|
|
|
HTTPClient *http.Client
|
|
|
|
}
|
|
|
|
|
2024-08-07 00:33:45 +00:00
|
|
|
func (s *Server) NodeAgentDialer(n *Node) DialFunc {
|
2024-08-05 19:06:48 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
|
2024-08-07 00:33:45 +00:00
|
|
|
if d, ok := s.agentDialer[n.n]; ok {
|
|
|
|
return d
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-07 00:33:45 +00:00
|
|
|
d := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
|
|
ac, ok := s.takeAgentConn(ctx, n.n)
|
|
|
|
if !ok {
|
|
|
|
return nil, ctx.Err()
|
|
|
|
}
|
|
|
|
return ac.tc, nil
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
2024-08-07 00:33:45 +00:00
|
|
|
mak.Set(&s.agentDialer, n.n, d)
|
|
|
|
return d
|
|
|
|
}
|
2024-08-05 19:06:48 +00:00
|
|
|
|
2024-08-08 04:31:50 +00:00
|
|
|
func (s *Server) NodeAgentClient(n *Node) *NodeAgentClient {
|
|
|
|
d := s.NodeAgentDialer(n)
|
|
|
|
return &NodeAgentClient{
|
|
|
|
LocalClient: &tailscale.LocalClient{
|
2024-08-10 20:46:47 +00:00
|
|
|
UseSocketOnly: true,
|
|
|
|
OmitAuth: true,
|
|
|
|
Dial: d,
|
2024-08-08 04:31:50 +00:00
|
|
|
},
|
|
|
|
HTTPClient: &http.Client{
|
|
|
|
Transport: &http.Transport{
|
|
|
|
DialContext: d,
|
|
|
|
},
|
|
|
|
},
|
2024-08-05 19:06:48 +00:00
|
|
|
}
|
|
|
|
}
|
2024-08-10 20:46:47 +00:00
|
|
|
|
|
|
|
// EnableHostFirewall enables the host's stateful firewall.
|
|
|
|
func (c *NodeAgentClient) EnableHostFirewall(ctx context.Context) error {
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "GET", "http://unused/fw", nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
res, err := c.HTTPClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
all, _ := io.ReadAll(res.Body)
|
|
|
|
if res.StatusCode != 200 {
|
|
|
|
return fmt.Errorf("unexpected status code %v: %s", res.Status, all)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2024-08-28 19:55:46 +00:00
|
|
|
|
2024-08-31 02:23:49 +00:00
|
|
|
// mkPacket is a serializes a number of layers into a packet.
|
|
|
|
//
|
|
|
|
// It's a convenience wrapper around gopacket.SerializeLayers
|
|
|
|
// that does some things automatically:
|
|
|
|
//
|
|
|
|
// * layers.Ethernet.EthernetType is set to IPv4 or IPv6 if not already set
|
|
|
|
// * layers.IPv4/IPv6 Version is set to 4/6 if not already set
|
|
|
|
// * layers.IPv4/IPv6 TTL/HopLimit is set to 64 if not already set
|
|
|
|
// * the TCP/UDP/ICMPv6 checksum is set based on the network layer
|
|
|
|
//
|
|
|
|
// The provided layers in ll must be sorted from lowest (e.g. *layers.Ethernet)
|
|
|
|
// to highest. (Depending on the need, the first layer will be either *layers.Ethernet
|
|
|
|
// or *layers.IPv4/IPv6).
|
|
|
|
func mkPacket(ll ...gopacket.SerializableLayer) ([]byte, error) {
|
|
|
|
var el *layers.Ethernet
|
2024-08-28 19:55:46 +00:00
|
|
|
var nl gopacket.NetworkLayer
|
|
|
|
for _, la := range ll {
|
|
|
|
switch la := la.(type) {
|
|
|
|
case *layers.IPv4:
|
|
|
|
nl = la
|
2024-08-31 02:23:49 +00:00
|
|
|
if el != nil && el.EthernetType == 0 {
|
|
|
|
el.EthernetType = layers.EthernetTypeIPv4
|
|
|
|
}
|
|
|
|
if la.Version == 0 {
|
|
|
|
la.Version = 4
|
|
|
|
}
|
|
|
|
if la.TTL == 0 {
|
|
|
|
la.TTL = 64
|
|
|
|
}
|
2024-08-28 19:55:46 +00:00
|
|
|
case *layers.IPv6:
|
|
|
|
nl = la
|
2024-08-31 02:23:49 +00:00
|
|
|
if el != nil && el.EthernetType == 0 {
|
|
|
|
el.EthernetType = layers.EthernetTypeIPv6
|
|
|
|
}
|
|
|
|
if la.Version == 0 {
|
|
|
|
la.Version = 6
|
|
|
|
}
|
|
|
|
if la.HopLimit == 0 {
|
|
|
|
la.HopLimit = 64
|
|
|
|
}
|
|
|
|
case *layers.Ethernet:
|
|
|
|
el = la
|
2024-08-28 19:55:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, la := range ll {
|
|
|
|
switch la := la.(type) {
|
|
|
|
case *layers.TCP:
|
|
|
|
la.SetNetworkLayerForChecksum(nl)
|
|
|
|
case *layers.UDP:
|
|
|
|
la.SetNetworkLayerForChecksum(nl)
|
|
|
|
case *layers.ICMPv6:
|
|
|
|
la.SetNetworkLayerForChecksum(nl)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
buf := gopacket.NewSerializeBuffer()
|
|
|
|
opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}
|
|
|
|
if err := gopacket.SerializeLayers(buf, opts, ll...); err != nil {
|
|
|
|
return nil, fmt.Errorf("serializing packet: %v", err)
|
|
|
|
}
|
|
|
|
return buf.Bytes(), nil
|
|
|
|
}
|