netstack.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. // Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package netstack wires up gVisor's netstack into Tailscale.
  5. package netstack
  6. import (
  7. "context"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log"
  12. "net"
  13. "net/netip"
  14. "os"
  15. "os/exec"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. "gvisor.dev/gvisor/pkg/bufferv2"
  23. "gvisor.dev/gvisor/pkg/refs"
  24. "gvisor.dev/gvisor/pkg/tcpip"
  25. "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
  26. "gvisor.dev/gvisor/pkg/tcpip/header"
  27. "gvisor.dev/gvisor/pkg/tcpip/link/channel"
  28. "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
  29. "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
  30. "gvisor.dev/gvisor/pkg/tcpip/stack"
  31. "gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
  32. "gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
  33. "gvisor.dev/gvisor/pkg/tcpip/transport/udp"
  34. "gvisor.dev/gvisor/pkg/waiter"
  35. "tailscale.com/envknob"
  36. "tailscale.com/ipn/ipnlocal"
  37. "tailscale.com/net/dns"
  38. "tailscale.com/net/netaddr"
  39. "tailscale.com/net/packet"
  40. "tailscale.com/net/tsaddr"
  41. "tailscale.com/net/tsdial"
  42. "tailscale.com/net/tstun"
  43. "tailscale.com/syncs"
  44. "tailscale.com/types/ipproto"
  45. "tailscale.com/types/logger"
  46. "tailscale.com/types/netmap"
  47. "tailscale.com/version/distro"
  48. "tailscale.com/wgengine"
  49. "tailscale.com/wgengine/filter"
  50. "tailscale.com/wgengine/magicsock"
  51. )
  52. const debugPackets = false
  53. var debugNetstack = envknob.Bool("TS_DEBUG_NETSTACK")
  54. var (
  55. magicDNSIP = tsaddr.TailscaleServiceIP()
  56. magicDNSIPv6 = tsaddr.TailscaleServiceIPv6()
  57. )
  58. func init() {
  59. var debugNetstackLeakMode = envknob.String("TS_DEBUG_NETSTACK_LEAK_MODE")
  60. // Note: netstacks refsvfs2 package that will eventually replace refs
  61. // consumes the refs.LeakMode setting, but enables some checks when set to
  62. // UninitializedLeakChecking which is what empty string becomes. This mode
  63. // is largely un-useful, so it is explicitly disabled here, and more useful
  64. // modes can be set via the envknob. See #4309 for more references.
  65. if debugNetstackLeakMode == "" {
  66. debugNetstackLeakMode = "disabled"
  67. }
  68. var lm refs.LeakMode
  69. lm.Set(debugNetstackLeakMode)
  70. refs.SetLeakMode(lm)
  71. }
  72. // Impl contains the state for the netstack implementation,
  73. // and implements wgengine.FakeImpl to act as a userspace network
  74. // stack when Tailscale is running in fake mode.
  75. type Impl struct {
  76. // ForwardTCPIn, if non-nil, handles forwarding an inbound TCP
  77. // connection.
  78. // TODO(bradfitz): provide mechanism for tsnet to reject a
  79. // port other than accepting it and closing it.
  80. ForwardTCPIn func(c net.Conn, port uint16)
  81. // ProcessLocalIPs is whether netstack should handle incoming
  82. // traffic directed at the Node.Addresses (local IPs).
  83. // It can only be set before calling Start.
  84. ProcessLocalIPs bool
  85. // ProcessSubnets is whether netstack should handle incoming
  86. // traffic destined to non-local IPs (i.e. whether it should
  87. // be a subnet router).
  88. // It can only be set before calling Start.
  89. ProcessSubnets bool
  90. ipstack *stack.Stack
  91. linkEP *channel.Endpoint
  92. tundev *tstun.Wrapper
  93. e wgengine.Engine
  94. mc *magicsock.Conn
  95. logf logger.Logf
  96. dialer *tsdial.Dialer
  97. ctx context.Context // alive until Close
  98. ctxCancel context.CancelFunc // called on Close
  99. lb *ipnlocal.LocalBackend // or nil
  100. dns *dns.Manager
  101. peerapiPort4Atomic uint32 // uint16 port number for IPv4 peerapi
  102. peerapiPort6Atomic uint32 // uint16 port number for IPv6 peerapi
  103. // atomicIsLocalIPFunc holds a func that reports whether an IP
  104. // is a local (non-subnet) Tailscale IP address of this
  105. // machine. It's always a non-nil func. It's changed on netmap
  106. // updates.
  107. atomicIsLocalIPFunc atomic.Value // of func(netip.Addr) bool
  108. mu sync.Mutex
  109. // connsOpenBySubnetIP keeps track of number of connections open
  110. // for each subnet IP temporarily registered on netstack for active
  111. // TCP connections, so they can be unregistered when connections are
  112. // closed.
  113. connsOpenBySubnetIP map[netip.Addr]int
  114. }
  115. // handleSSH is initialized in ssh.go (on Linux only) to register an SSH server
  116. // handler. See https://github.com/tailscale/tailscale/issues/3802.
  117. var handleSSH func(logger.Logf, *ipnlocal.LocalBackend, net.Conn) error
  118. const nicID = 1
  119. const mtu = tstun.DefaultMTU
  120. // maxUDPPacketSize is the maximum size of a UDP packet we copy in startPacketCopy
  121. // when relaying UDP packets. We don't use the 'mtu' const in anticipation of
  122. // one day making the MTU more dynamic.
  123. const maxUDPPacketSize = 1500
  124. // Create creates and populates a new Impl.
  125. func Create(logf logger.Logf, tundev *tstun.Wrapper, e wgengine.Engine, mc *magicsock.Conn, dialer *tsdial.Dialer, dns *dns.Manager) (*Impl, error) {
  126. if mc == nil {
  127. return nil, errors.New("nil magicsock.Conn")
  128. }
  129. if tundev == nil {
  130. return nil, errors.New("nil tundev")
  131. }
  132. if logf == nil {
  133. return nil, errors.New("nil logger")
  134. }
  135. if e == nil {
  136. return nil, errors.New("nil Engine")
  137. }
  138. if dialer == nil {
  139. return nil, errors.New("nil Dialer")
  140. }
  141. ipstack := stack.New(stack.Options{
  142. NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
  143. TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
  144. })
  145. linkEP := channel.New(512, mtu, "")
  146. if tcpipProblem := ipstack.CreateNIC(nicID, linkEP); tcpipProblem != nil {
  147. return nil, fmt.Errorf("could not create netstack NIC: %v", tcpipProblem)
  148. }
  149. // By default the netstack NIC will only accept packets for the IPs
  150. // registered to it. Since in some cases we dynamically register IPs
  151. // based on the packets that arrive, the NIC needs to accept all
  152. // incoming packets. The NIC won't receive anything it isn't meant to
  153. // since WireGuard will only send us packets that are meant for us.
  154. ipstack.SetPromiscuousMode(nicID, true)
  155. // Add IPv4 and IPv6 default routes, so all incoming packets from the Tailscale side
  156. // are handled by the one fake NIC we use.
  157. ipv4Subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 4)), tcpip.AddressMask(strings.Repeat("\x00", 4)))
  158. ipv6Subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 16)), tcpip.AddressMask(strings.Repeat("\x00", 16)))
  159. ipstack.SetRouteTable([]tcpip.Route{
  160. {
  161. Destination: ipv4Subnet,
  162. NIC: nicID,
  163. },
  164. {
  165. Destination: ipv6Subnet,
  166. NIC: nicID,
  167. },
  168. })
  169. ns := &Impl{
  170. logf: logf,
  171. ipstack: ipstack,
  172. linkEP: linkEP,
  173. tundev: tundev,
  174. e: e,
  175. mc: mc,
  176. dialer: dialer,
  177. connsOpenBySubnetIP: make(map[netip.Addr]int),
  178. dns: dns,
  179. }
  180. ns.ctx, ns.ctxCancel = context.WithCancel(context.Background())
  181. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nil))
  182. return ns, nil
  183. }
  184. func (ns *Impl) Close() error {
  185. ns.ctxCancel()
  186. ns.ipstack.Close()
  187. return nil
  188. }
  189. // SetLocalBackend sets the LocalBackend; it should only be run before
  190. // the Start method is called.
  191. func (ns *Impl) SetLocalBackend(lb *ipnlocal.LocalBackend) {
  192. ns.lb = lb
  193. }
  194. // wrapProtoHandler returns protocol handler h wrapped in a version
  195. // that dynamically reconfigures ns's subnet addresses as needed for
  196. // outbound traffic.
  197. func (ns *Impl) wrapProtoHandler(h func(stack.TransportEndpointID, *stack.PacketBuffer) bool) func(stack.TransportEndpointID, *stack.PacketBuffer) bool {
  198. return func(tei stack.TransportEndpointID, pb *stack.PacketBuffer) bool {
  199. addr := tei.LocalAddress
  200. ip, ok := netip.AddrFromSlice(net.IP(addr))
  201. if !ok {
  202. ns.logf("netstack: could not parse local address for incoming connection")
  203. return false
  204. }
  205. ip = ip.Unmap()
  206. if !ns.isLocalIP(ip) {
  207. ns.addSubnetAddress(ip)
  208. }
  209. return h(tei, pb)
  210. }
  211. }
  212. // Start sets up all the handlers so netstack can start working. Implements
  213. // wgengine.FakeImpl.
  214. func (ns *Impl) Start() error {
  215. ns.e.AddNetworkMapCallback(ns.updateIPs)
  216. // size = 0 means use default buffer size
  217. const tcpReceiveBufferSize = 0
  218. const maxInFlightConnectionAttempts = 16
  219. tcpFwd := tcp.NewForwarder(ns.ipstack, tcpReceiveBufferSize, maxInFlightConnectionAttempts, ns.acceptTCP)
  220. udpFwd := udp.NewForwarder(ns.ipstack, ns.acceptUDP)
  221. ns.ipstack.SetTransportProtocolHandler(tcp.ProtocolNumber, ns.wrapProtoHandler(tcpFwd.HandlePacket))
  222. ns.ipstack.SetTransportProtocolHandler(udp.ProtocolNumber, ns.wrapProtoHandler(udpFwd.HandlePacket))
  223. go ns.inject()
  224. ns.tundev.PostFilterIn = ns.injectInbound
  225. ns.tundev.PreFilterFromTunToNetstack = ns.handleLocalPackets
  226. return nil
  227. }
  228. func (ns *Impl) addSubnetAddress(ip netip.Addr) {
  229. ns.mu.Lock()
  230. ns.connsOpenBySubnetIP[ip]++
  231. needAdd := ns.connsOpenBySubnetIP[ip] == 1
  232. ns.mu.Unlock()
  233. // Only register address into netstack for first concurrent connection.
  234. if needAdd {
  235. pa := tcpip.ProtocolAddress{
  236. AddressWithPrefix: tcpip.AddressWithPrefix{
  237. Address: tcpip.Address(ip.AsSlice()),
  238. PrefixLen: int(ip.BitLen()),
  239. },
  240. }
  241. if ip.Is4() {
  242. pa.Protocol = ipv4.ProtocolNumber
  243. } else if ip.Is6() {
  244. pa.Protocol = ipv6.ProtocolNumber
  245. }
  246. ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  247. PEB: stack.CanBePrimaryEndpoint, // zero value default
  248. ConfigType: stack.AddressConfigStatic, // zero value default
  249. })
  250. }
  251. }
  252. func (ns *Impl) removeSubnetAddress(ip netip.Addr) {
  253. ns.mu.Lock()
  254. defer ns.mu.Unlock()
  255. ns.connsOpenBySubnetIP[ip]--
  256. // Only unregister address from netstack after last concurrent connection.
  257. if ns.connsOpenBySubnetIP[ip] == 0 {
  258. ns.ipstack.RemoveAddress(nicID, tcpip.Address(ip.AsSlice()))
  259. delete(ns.connsOpenBySubnetIP, ip)
  260. }
  261. }
  262. func ipPrefixToAddressWithPrefix(ipp netip.Prefix) tcpip.AddressWithPrefix {
  263. return tcpip.AddressWithPrefix{
  264. Address: tcpip.Address(ipp.Addr().AsSlice()),
  265. PrefixLen: int(ipp.Bits()),
  266. }
  267. }
  268. var v4broadcast = netaddr.IPv4(255, 255, 255, 255)
  269. func (ns *Impl) updateIPs(nm *netmap.NetworkMap) {
  270. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nm.Addresses))
  271. oldIPs := make(map[tcpip.AddressWithPrefix]bool)
  272. for _, protocolAddr := range ns.ipstack.AllAddresses()[nicID] {
  273. ap := protocolAddr.AddressWithPrefix
  274. ip := netaddrIPFromNetstackIP(ap.Address)
  275. if ip == v4broadcast && ap.PrefixLen == 32 {
  276. // Don't add 255.255.255.255/32 to oldIPs so we don't
  277. // delete it later. We didn't install it, so it's not
  278. // ours to delete.
  279. continue
  280. }
  281. oldIPs[ap] = true
  282. }
  283. newIPs := make(map[tcpip.AddressWithPrefix]bool)
  284. isAddr := map[netip.Prefix]bool{}
  285. if nm.SelfNode != nil {
  286. for _, ipp := range nm.SelfNode.Addresses {
  287. isAddr[ipp] = true
  288. newIPs[ipPrefixToAddressWithPrefix(ipp)] = true
  289. }
  290. for _, ipp := range nm.SelfNode.AllowedIPs {
  291. if !isAddr[ipp] && ns.ProcessSubnets {
  292. newIPs[ipPrefixToAddressWithPrefix(ipp)] = true
  293. }
  294. }
  295. }
  296. ipsToBeAdded := make(map[tcpip.AddressWithPrefix]bool)
  297. for ipp := range newIPs {
  298. if !oldIPs[ipp] {
  299. ipsToBeAdded[ipp] = true
  300. }
  301. }
  302. ipsToBeRemoved := make(map[tcpip.AddressWithPrefix]bool)
  303. for ip := range oldIPs {
  304. if !newIPs[ip] {
  305. ipsToBeRemoved[ip] = true
  306. }
  307. }
  308. ns.mu.Lock()
  309. for ip := range ns.connsOpenBySubnetIP {
  310. ipp := tcpip.Address(ip.AsSlice()).WithPrefix()
  311. delete(ipsToBeRemoved, ipp)
  312. }
  313. ns.mu.Unlock()
  314. for ipp := range ipsToBeRemoved {
  315. err := ns.ipstack.RemoveAddress(nicID, ipp.Address)
  316. if err != nil {
  317. ns.logf("netstack: could not deregister IP %s: %v", ipp, err)
  318. } else {
  319. ns.logf("[v2] netstack: deregistered IP %s", ipp)
  320. }
  321. }
  322. for ipp := range ipsToBeAdded {
  323. pa := tcpip.ProtocolAddress{
  324. AddressWithPrefix: ipp,
  325. }
  326. if ipp.Address.To4() == "" {
  327. pa.Protocol = ipv6.ProtocolNumber
  328. } else {
  329. pa.Protocol = ipv4.ProtocolNumber
  330. }
  331. var err tcpip.Error
  332. err = ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  333. PEB: stack.CanBePrimaryEndpoint, // zero value default
  334. ConfigType: stack.AddressConfigStatic, // zero value default
  335. })
  336. if err != nil {
  337. ns.logf("netstack: could not register IP %s: %v", ipp, err)
  338. } else {
  339. ns.logf("[v2] netstack: registered IP %s", ipp)
  340. }
  341. }
  342. }
  343. // handleLocalPackets is hooked into the tun datapath for packets leaving
  344. // the host and arriving at tailscaled. This method returns filter.DropSilently
  345. // to intercept a packet for handling, for instance traffic to quad-100.
  346. func (ns *Impl) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  347. // If it's not traffic to the service IP (i.e. magicDNS) we don't
  348. // care; resume processing.
  349. if dst := p.Dst.Addr(); dst != magicDNSIP && dst != magicDNSIPv6 {
  350. return filter.Accept
  351. }
  352. // Of traffic to the service IP, we only care about UDP 53, and TCP
  353. // on port 80 & 53.
  354. switch p.IPProto {
  355. case ipproto.TCP:
  356. if port := p.Dst.Port(); port != 53 && port != 80 {
  357. return filter.Accept
  358. }
  359. case ipproto.UDP:
  360. if port := p.Dst.Port(); port != 53 {
  361. return filter.Accept
  362. }
  363. }
  364. var pn tcpip.NetworkProtocolNumber
  365. switch p.IPVersion {
  366. case 4:
  367. pn = header.IPv4ProtocolNumber
  368. case 6:
  369. pn = header.IPv6ProtocolNumber
  370. }
  371. if debugPackets {
  372. ns.logf("[v2] service packet in (from %v): % x", p.Src, p.Buffer())
  373. }
  374. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  375. Payload: bufferv2.MakeWithData(append([]byte(nil), p.Buffer()...)),
  376. })
  377. ns.linkEP.InjectInbound(pn, packetBuf)
  378. packetBuf.DecRef()
  379. return filter.DropSilently
  380. }
  381. func (ns *Impl) DialContextTCP(ctx context.Context, ipp netip.AddrPort) (*gonet.TCPConn, error) {
  382. remoteAddress := tcpip.FullAddress{
  383. NIC: nicID,
  384. Addr: tcpip.Address(ipp.Addr().AsSlice()),
  385. Port: ipp.Port(),
  386. }
  387. var ipType tcpip.NetworkProtocolNumber
  388. if ipp.Addr().Is4() {
  389. ipType = ipv4.ProtocolNumber
  390. } else {
  391. ipType = ipv6.ProtocolNumber
  392. }
  393. return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
  394. }
  395. func (ns *Impl) DialContextUDP(ctx context.Context, ipp netip.AddrPort) (*gonet.UDPConn, error) {
  396. remoteAddress := &tcpip.FullAddress{
  397. NIC: nicID,
  398. Addr: tcpip.Address(ipp.Addr().AsSlice()),
  399. Port: ipp.Port(),
  400. }
  401. var ipType tcpip.NetworkProtocolNumber
  402. if ipp.Addr().Is4() {
  403. ipType = ipv4.ProtocolNumber
  404. } else {
  405. ipType = ipv6.ProtocolNumber
  406. }
  407. return gonet.DialUDP(ns.ipstack, nil, remoteAddress, ipType)
  408. }
  409. // The inject goroutine reads in packets that netstack generated, and delivers
  410. // them to the correct path.
  411. func (ns *Impl) inject() {
  412. for {
  413. pkt := ns.linkEP.ReadContext(ns.ctx)
  414. if pkt == nil {
  415. if ns.ctx.Err() != nil {
  416. // Return without logging.
  417. return
  418. }
  419. ns.logf("[v2] ReadContext-for-write = ok=false")
  420. continue
  421. }
  422. if debugPackets {
  423. ns.logf("[v2] packet Write out: % x", stack.PayloadSince(pkt.NetworkHeader()))
  424. }
  425. // In the normal case, netstack synthesizes the bytes for
  426. // traffic which should transit back into WG and go to peers.
  427. // However, some uses of netstack (presently, magic DNS)
  428. // send traffic destined for the local device, hence must
  429. // be injected 'inbound'.
  430. sendToHost := false
  431. // Determine if the packet is from a service IP, in which case it
  432. // needs to go back into the machines network (inbound) instead of
  433. // out.
  434. // TODO(tom): Work out a way to avoid parsing packets to determine if
  435. // its from the service IP. Maybe gvisor netstack magic. I
  436. // went through the fields of PacketBuffer, and nop :/
  437. // TODO(tom): Figure out if its safe to modify packet.Parsed to fill in
  438. // the IP src/dest even if its missing the rest of the pkt.
  439. // That way we dont have to do this twitchy-af byte-yeeting.
  440. if b := pkt.NetworkHeader().Slice(); len(b) >= 20 { // min ipv4 header
  441. switch b[0] >> 4 { // ip proto field
  442. case 4:
  443. if srcIP := netaddr.IPv4(b[12], b[13], b[14], b[15]); magicDNSIP == srcIP {
  444. sendToHost = true
  445. }
  446. case 6:
  447. if len(b) >= 40 { // min ipv6 header
  448. if srcIP, ok := netip.AddrFromSlice(net.IP(b[8:24])); ok && magicDNSIPv6 == srcIP {
  449. sendToHost = true
  450. }
  451. }
  452. }
  453. }
  454. // pkt has a non-zero refcount, so injection methods takes
  455. // ownership of one count and will decrement on completion.
  456. if sendToHost {
  457. if err := ns.tundev.InjectInboundPacketBuffer(pkt); err != nil {
  458. log.Printf("netstack inject inbound: %v", err)
  459. return
  460. }
  461. } else {
  462. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  463. log.Printf("netstack inject outbound: %v", err)
  464. return
  465. }
  466. }
  467. }
  468. }
  469. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  470. // node directly (but not a subnet-routed IP).
  471. func (ns *Impl) isLocalIP(ip netip.Addr) bool {
  472. return ns.atomicIsLocalIPFunc.Load().(func(netip.Addr) bool)(ip)
  473. }
  474. func (ns *Impl) processSSH() bool {
  475. return ns.lb != nil && ns.lb.ShouldRunSSH()
  476. }
  477. func (ns *Impl) peerAPIPortAtomic(ip netip.Addr) *uint32 {
  478. if ip.Is4() {
  479. return &ns.peerapiPort4Atomic
  480. } else {
  481. return &ns.peerapiPort6Atomic
  482. }
  483. }
  484. var viaRange = tsaddr.TailscaleViaRange()
  485. // shouldProcessInbound reports whether an inbound packet (a packet from a
  486. // WireGuard peer) should be handled by netstack.
  487. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  488. // Handle incoming peerapi connections in netstack.
  489. if ns.lb != nil && p.IPProto == ipproto.TCP {
  490. var peerAPIPort uint16
  491. dstIP := p.Dst.Addr()
  492. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn && ns.isLocalIP(dstIP) {
  493. if port, ok := ns.lb.GetPeerAPIPort(p.Dst.Addr()); ok {
  494. peerAPIPort = port
  495. atomic.StoreUint32(ns.peerAPIPortAtomic(dstIP), uint32(port))
  496. }
  497. } else {
  498. peerAPIPort = uint16(atomic.LoadUint32(ns.peerAPIPortAtomic(dstIP)))
  499. }
  500. if p.IPProto == ipproto.TCP && p.Dst.Port() == peerAPIPort {
  501. return true
  502. }
  503. }
  504. if ns.isInboundTSSH(p) && ns.processSSH() {
  505. return true
  506. }
  507. if p.IPVersion == 6 && viaRange.Contains(p.Dst.Addr()) {
  508. return ns.lb != nil && ns.lb.ShouldHandleViaIP(p.Dst.Addr())
  509. }
  510. if !ns.ProcessLocalIPs && !ns.ProcessSubnets {
  511. // Fast path for common case (e.g. Linux server in TUN mode) where
  512. // netstack isn't used at all; don't even do an isLocalIP lookup.
  513. return false
  514. }
  515. isLocal := ns.isLocalIP(p.Dst.Addr())
  516. if ns.ProcessLocalIPs && isLocal {
  517. return true
  518. }
  519. if ns.ProcessSubnets && !isLocal {
  520. return true
  521. }
  522. return false
  523. }
  524. // setAmbientCapsRaw is non-nil on Linux for Synology, to run ping with
  525. // CAP_NET_RAW from tailscaled's binary.
  526. var setAmbientCapsRaw func(*exec.Cmd)
  527. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  528. var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
  529. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  530. // into the tundev.
  531. //
  532. // It's used in userspace/netstack mode when we don't have kernel
  533. // support or raw socket access. As such, this does the dumbest thing
  534. // that can work: runs the ping command. It's not super efficient, so
  535. // it bounds the number of pings going on at once. The idea is that
  536. // people only use ping occasionally to see if their internet's working
  537. // so this doesn't need to be great.
  538. //
  539. // TODO(bradfitz): when we're running on Windows as the system user, use
  540. // raw socket APIs instead of ping child processes.
  541. func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte) {
  542. if !userPingSem.TryAcquire() {
  543. return
  544. }
  545. defer userPingSem.Release()
  546. t0 := time.Now()
  547. var err error
  548. switch runtime.GOOS {
  549. case "windows":
  550. err = exec.Command("ping", "-n", "1", "-w", "3000", dstIP.String()).Run()
  551. case "darwin":
  552. // Note: 2000 ms is actually 1 second + 2,000
  553. // milliseconds extra for 3 seconds total.
  554. // See https://github.com/tailscale/tailscale/pull/3753 for details.
  555. err = exec.Command("ping", "-c", "1", "-W", "2000", dstIP.String()).Run()
  556. case "android":
  557. ping := "/system/bin/ping"
  558. if dstIP.Is6() {
  559. ping = "/system/bin/ping6"
  560. }
  561. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  562. default:
  563. ping := "ping"
  564. if isSynology {
  565. ping = "/bin/ping"
  566. }
  567. cmd := exec.Command(ping, "-c", "1", "-W", "3", dstIP.String())
  568. if isSynology && os.Getuid() != 0 {
  569. // On DSM7 we run as non-root and need to pass
  570. // CAP_NET_RAW if our binary has it.
  571. setAmbientCapsRaw(cmd)
  572. }
  573. err = cmd.Run()
  574. }
  575. d := time.Since(t0)
  576. if err != nil {
  577. if d < time.Second/2 {
  578. // If it failed quicker than the 3 second
  579. // timeout we gave above (500 ms is a
  580. // reasonable threshold), then assume the ping
  581. // failed for problems finding/running
  582. // ping. We don't want to log if the host is
  583. // just down.
  584. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  585. }
  586. return
  587. }
  588. if debugNetstack {
  589. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  590. }
  591. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  592. ns.logf("InjectOutbound ping response: %v", err)
  593. }
  594. }
  595. func (ns *Impl) isInboundTSSH(p *packet.Parsed) bool {
  596. return p.IPProto == ipproto.TCP &&
  597. p.Dst.Port() == 22 &&
  598. ns.isLocalIP(p.Dst.Addr())
  599. }
  600. // injectInbound is installed as a packet hook on the 'inbound' (from a
  601. // WireGuard peer) path. Returning filter.Accept releases the packet to
  602. // continue normally (typically being delivered to the host networking stack),
  603. // whereas returning filter.DropSilently is done when netstack intercepts the
  604. // packet and no further processing towards to host should be done.
  605. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  606. if !ns.shouldProcessInbound(p, t) {
  607. // Let the host network stack (if any) deal with it.
  608. return filter.Accept
  609. }
  610. destIP := p.Dst.Addr()
  611. if p.IsEchoRequest() && ns.ProcessSubnets && !tsaddr.IsTailscaleIP(destIP) {
  612. var pong []byte // the reply to the ping, if our relayed ping works
  613. if destIP.Is4() {
  614. h := p.ICMP4Header()
  615. h.ToResponse()
  616. pong = packet.Generate(&h, p.Payload())
  617. } else if destIP.Is6() {
  618. h := p.ICMP6Header()
  619. h.ToResponse()
  620. pong = packet.Generate(&h, p.Payload())
  621. }
  622. go ns.userPing(destIP, pong)
  623. return filter.DropSilently
  624. }
  625. var pn tcpip.NetworkProtocolNumber
  626. switch p.IPVersion {
  627. case 4:
  628. pn = header.IPv4ProtocolNumber
  629. case 6:
  630. pn = header.IPv6ProtocolNumber
  631. }
  632. if debugPackets {
  633. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  634. }
  635. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  636. Payload: bufferv2.MakeWithData(append([]byte(nil), p.Buffer()...)),
  637. })
  638. ns.linkEP.InjectInbound(pn, packetBuf)
  639. packetBuf.DecRef()
  640. // We've now delivered this to netstack, so we're done.
  641. // Instead of returning a filter.Accept here (which would also
  642. // potentially deliver it to the host OS), and instead of
  643. // filter.Drop (which would log about rejected traffic),
  644. // instead return filter.DropSilently which just quietly stops
  645. // processing it in the tstun TUN wrapper.
  646. return filter.DropSilently
  647. }
  648. func netaddrIPFromNetstackIP(s tcpip.Address) netip.Addr {
  649. switch len(s) {
  650. case 4:
  651. return netaddr.IPv4(s[0], s[1], s[2], s[3])
  652. case 16:
  653. var a [16]byte
  654. copy(a[:], s)
  655. return netip.AddrFrom16(a).Unmap()
  656. }
  657. return netip.Addr{}
  658. }
  659. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  660. reqDetails := r.ID()
  661. if debugNetstack {
  662. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  663. }
  664. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  665. if !clientRemoteIP.IsValid() {
  666. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  667. r.Complete(true) // sends a RST
  668. return
  669. }
  670. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  671. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  672. if viaRange.Contains(dialIP) {
  673. isTailscaleIP = false
  674. dialIP = tsaddr.UnmapVia(dialIP)
  675. }
  676. defer func() {
  677. if !isTailscaleIP {
  678. // if this is a subnet IP, we added this in before the TCP handshake
  679. // so netstack is happy TCP-handshaking as a subnet IP
  680. ns.removeSubnetAddress(dialIP)
  681. }
  682. }()
  683. var wq waiter.Queue
  684. ep, err := r.CreateEndpoint(&wq)
  685. if err != nil {
  686. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  687. r.Complete(true) // sends a RST
  688. return
  689. }
  690. r.Complete(false)
  691. // SetKeepAlive so that idle connections to peers that have forgotten about
  692. // the connection or gone completely offline eventually time out.
  693. // Applications might be setting this on a forwarded connection, but from
  694. // userspace we can not see those, so the best we can do is to always
  695. // perform them with conservative timing.
  696. // TODO(tailscale/tailscale#4522): Netstack defaults match the Linux
  697. // defaults, and results in a little over two hours before the socket would
  698. // be closed due to keepalive. A shorter default might be better, or seeking
  699. // a default from the host IP stack. This also might be a useful
  700. // user-tunable, as in userspace mode this can have broad implications such
  701. // as lingering connections to fork style daemons. On the other side of the
  702. // fence, the long duration timers are low impact values for battery powered
  703. // peers.
  704. ep.SocketOptions().SetKeepAlive(true)
  705. // The ForwarderRequest.CreateEndpoint above asynchronously
  706. // starts the TCP handshake. Note that the gonet.TCPConn
  707. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  708. // until the handshake actually completes. But we have the
  709. // remote address in reqDetails instead, so we don't use
  710. // gonet.TCPConn.RemoteAddr. The byte copies in both
  711. // directions to/from the gonet.TCPConn in forwardTCP will
  712. // block until the TCP handshake is complete.
  713. c := gonet.NewTCPConn(&wq, ep)
  714. if reqDetails.LocalPort == 53 && (dialIP == magicDNSIP || dialIP == magicDNSIPv6) {
  715. go ns.dns.HandleTCPConn(c, netip.AddrPortFrom(clientRemoteIP, reqDetails.RemotePort))
  716. return
  717. }
  718. if ns.lb != nil {
  719. if reqDetails.LocalPort == 22 && ns.processSSH() && ns.isLocalIP(dialIP) {
  720. if err := ns.lb.HandleSSHConn(c); err != nil {
  721. ns.logf("ssh error: %v", err)
  722. }
  723. return
  724. }
  725. if port, ok := ns.lb.GetPeerAPIPort(dialIP); ok {
  726. if reqDetails.LocalPort == port && ns.isLocalIP(dialIP) {
  727. src := netip.AddrPortFrom(clientRemoteIP, reqDetails.RemotePort)
  728. dst := netip.AddrPortFrom(dialIP, port)
  729. ns.lb.ServePeerAPIConnection(src, dst, c)
  730. return
  731. }
  732. }
  733. if reqDetails.LocalPort == 80 && (dialIP == magicDNSIP || dialIP == magicDNSIPv6) {
  734. ns.lb.HandleQuad100Port80Conn(c)
  735. return
  736. }
  737. }
  738. if ns.ForwardTCPIn != nil {
  739. ns.ForwardTCPIn(c, reqDetails.LocalPort)
  740. return
  741. }
  742. if isTailscaleIP {
  743. dialIP = netaddr.IPv4(127, 0, 0, 1)
  744. }
  745. dialAddr := netip.AddrPortFrom(dialIP, uint16(reqDetails.LocalPort))
  746. ns.forwardTCP(c, clientRemoteIP, &wq, dialAddr)
  747. }
  748. func (ns *Impl) forwardTCP(client *gonet.TCPConn, clientRemoteIP netip.Addr, wq *waiter.Queue, dialAddr netip.AddrPort) {
  749. defer client.Close()
  750. dialAddrStr := dialAddr.String()
  751. if debugNetstack {
  752. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  753. }
  754. ctx, cancel := context.WithCancel(context.Background())
  755. defer cancel()
  756. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  757. wq.EventRegister(&waitEntry)
  758. defer wq.EventUnregister(&waitEntry)
  759. done := make(chan bool)
  760. // netstack doesn't close the notification channel automatically if there was no
  761. // hup signal, so we close done after we're done to not leak the goroutine below.
  762. defer close(done)
  763. go func() {
  764. select {
  765. case <-notifyCh:
  766. if debugNetstack {
  767. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  768. }
  769. case <-done:
  770. }
  771. cancel()
  772. }()
  773. var stdDialer net.Dialer
  774. server, err := stdDialer.DialContext(ctx, "tcp", dialAddrStr)
  775. if err != nil {
  776. ns.logf("netstack: could not connect to local server at %s: %v", dialAddrStr, err)
  777. return
  778. }
  779. defer server.Close()
  780. backendLocalAddr := server.LocalAddr().(*net.TCPAddr)
  781. backendLocalIPPort, _ := netaddr.FromStdAddr(backendLocalAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  782. ns.e.RegisterIPPortIdentity(backendLocalIPPort, clientRemoteIP)
  783. defer ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  784. connClosed := make(chan error, 2)
  785. go func() {
  786. _, err := io.Copy(server, client)
  787. connClosed <- err
  788. }()
  789. go func() {
  790. _, err := io.Copy(client, server)
  791. connClosed <- err
  792. }()
  793. err = <-connClosed
  794. if err != nil {
  795. ns.logf("proxy connection closed with error: %v", err)
  796. }
  797. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  798. }
  799. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  800. sess := r.ID()
  801. if debugNetstack {
  802. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  803. }
  804. var wq waiter.Queue
  805. ep, err := r.CreateEndpoint(&wq)
  806. if err != nil {
  807. ns.logf("acceptUDP: could not create endpoint: %v", err)
  808. return
  809. }
  810. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  811. if !ok {
  812. return
  813. }
  814. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  815. if !ok {
  816. return
  817. }
  818. // Handle magicDNS traffic (via UDP) here.
  819. if dst := dstAddr.Addr(); dst == magicDNSIP || dst == magicDNSIPv6 {
  820. if dstAddr.Port() != 53 {
  821. return // Only MagicDNS traffic runs on the service IPs for now.
  822. }
  823. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  824. go ns.handleMagicDNSUDP(srcAddr, c)
  825. return
  826. }
  827. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  828. go ns.forwardUDP(c, &wq, srcAddr, dstAddr)
  829. }
  830. func (ns *Impl) handleMagicDNSUDP(srcAddr netip.AddrPort, c *gonet.UDPConn) {
  831. // In practice, implementations are advised not to exceed 512 bytes
  832. // due to fragmenting. Just to be sure, we bump all the way to the MTU.
  833. const maxUDPReqSize = mtu
  834. // Packets are being generated by the local host, so there should be
  835. // very, very little latency. 150ms was chosen as something of an upper
  836. // bound on resource usage, while hopefully still being long enough for
  837. // a heavily loaded system.
  838. const readDeadline = 150 * time.Millisecond
  839. defer c.Close()
  840. q := make([]byte, maxUDPReqSize)
  841. // libresolv from glibc is quite adamant that transmitting multiple DNS
  842. // requests down the same UDP socket is valid. To support this, we read
  843. // in a loop (with a tight deadline so we don't chew too many resources).
  844. //
  845. // See: https://github.com/bminor/glibc/blob/f7fbb99652eceb1b6b55e4be931649df5946497c/resolv/res_send.c#L995
  846. for {
  847. c.SetReadDeadline(time.Now().Add(readDeadline))
  848. n, _, err := c.ReadFrom(q)
  849. if err != nil {
  850. if oe, ok := err.(*net.OpError); !(ok && oe.Timeout()) {
  851. ns.logf("dns udp read: %v", err) // log non-timeout errors
  852. }
  853. return
  854. }
  855. resp, err := ns.dns.Query(context.Background(), q[:n], srcAddr)
  856. if err != nil {
  857. ns.logf("dns udp query: %v", err)
  858. return
  859. }
  860. c.Write(resp)
  861. }
  862. }
  863. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  864. //
  865. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  866. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  867. // proxy to it directly.
  868. func (ns *Impl) forwardUDP(client *gonet.UDPConn, wq *waiter.Queue, clientAddr, dstAddr netip.AddrPort) {
  869. port, srcPort := dstAddr.Port(), clientAddr.Port()
  870. if debugNetstack {
  871. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  872. }
  873. var backendListenAddr *net.UDPAddr
  874. var backendRemoteAddr *net.UDPAddr
  875. isLocal := ns.isLocalIP(dstAddr.Addr())
  876. if isLocal {
  877. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  878. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  879. } else {
  880. if dstIP := dstAddr.Addr(); viaRange.Contains(dstIP) {
  881. dstAddr = netip.AddrPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
  882. }
  883. backendRemoteAddr = net.UDPAddrFromAddrPort(dstAddr)
  884. if dstAddr.Addr().Is4() {
  885. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  886. } else {
  887. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  888. }
  889. }
  890. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  891. if err != nil {
  892. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  893. backendListenAddr.Port = 0
  894. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  895. if err != nil {
  896. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  897. return
  898. }
  899. }
  900. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  901. backendLocalIPPort, ok := netaddr.FromStdAddr(backendListenAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  902. if !ok {
  903. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  904. }
  905. if isLocal {
  906. ns.e.RegisterIPPortIdentity(backendLocalIPPort, dstAddr.Addr())
  907. }
  908. ctx, cancel := context.WithCancel(context.Background())
  909. idleTimeout := 2 * time.Minute
  910. if port == 53 {
  911. // Make DNS packet copies time out much sooner.
  912. //
  913. // TODO(bradfitz): make DNS queries over UDP forwarding even
  914. // cheaper by adding an additional idleTimeout post-DNS-reply.
  915. // For instance, after the DNS response goes back out, then only
  916. // wait a few seconds (or zero, really)
  917. idleTimeout = 30 * time.Second
  918. }
  919. timer := time.AfterFunc(idleTimeout, func() {
  920. if isLocal {
  921. ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  922. }
  923. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  924. cancel()
  925. client.Close()
  926. backendConn.Close()
  927. })
  928. extend := func() {
  929. timer.Reset(idleTimeout)
  930. }
  931. startPacketCopy(ctx, cancel, client, net.UDPAddrFromAddrPort(clientAddr), backendConn, ns.logf, extend)
  932. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  933. if isLocal {
  934. // Wait for the copies to be done before decrementing the
  935. // subnet address count to potentially remove the route.
  936. <-ctx.Done()
  937. ns.removeSubnetAddress(dstAddr.Addr())
  938. }
  939. }
  940. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  941. if debugNetstack {
  942. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  943. }
  944. go func() {
  945. defer cancel() // tear down the other direction's copy
  946. pkt := make([]byte, maxUDPPacketSize)
  947. for {
  948. select {
  949. case <-ctx.Done():
  950. return
  951. default:
  952. n, srcAddr, err := src.ReadFrom(pkt)
  953. if err != nil {
  954. if ctx.Err() == nil {
  955. logf("read packet from %s failed: %v", srcAddr, err)
  956. }
  957. return
  958. }
  959. _, err = dst.WriteTo(pkt[:n], dstAddr)
  960. if err != nil {
  961. if ctx.Err() == nil {
  962. logf("write packet to %s failed: %v", dstAddr, err)
  963. }
  964. return
  965. }
  966. if debugNetstack {
  967. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  968. }
  969. extend()
  970. }
  971. }
  972. }()
  973. }
  974. func stringifyTEI(tei stack.TransportEndpointID) string {
  975. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  976. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  977. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  978. }
  979. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netip.AddrPort, ok bool) {
  980. return netaddr.FromStdAddr(net.IP(a), int(port), "") // TODO(bradfitz): can do without allocs
  981. }