netstack.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. "os"
  14. "os/exec"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "sync/atomic"
  20. "time"
  21. "gvisor.dev/gvisor/pkg/refs"
  22. "gvisor.dev/gvisor/pkg/tcpip"
  23. "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
  24. "gvisor.dev/gvisor/pkg/tcpip/buffer"
  25. "gvisor.dev/gvisor/pkg/tcpip/header"
  26. "gvisor.dev/gvisor/pkg/tcpip/link/channel"
  27. "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
  28. "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
  29. "gvisor.dev/gvisor/pkg/tcpip/stack"
  30. "gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
  31. "gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
  32. "gvisor.dev/gvisor/pkg/tcpip/transport/udp"
  33. "gvisor.dev/gvisor/pkg/waiter"
  34. "inet.af/netaddr"
  35. "tailscale.com/envknob"
  36. "tailscale.com/ipn/ipnlocal"
  37. "tailscale.com/net/dns"
  38. "tailscale.com/net/packet"
  39. "tailscale.com/net/tsaddr"
  40. "tailscale.com/net/tsdial"
  41. "tailscale.com/net/tstun"
  42. "tailscale.com/syncs"
  43. "tailscale.com/types/ipproto"
  44. "tailscale.com/types/logger"
  45. "tailscale.com/types/netmap"
  46. "tailscale.com/version/distro"
  47. "tailscale.com/wgengine"
  48. "tailscale.com/wgengine/filter"
  49. "tailscale.com/wgengine/magicsock"
  50. )
  51. const debugPackets = false
  52. var debugNetstack = envknob.Bool("TS_DEBUG_NETSTACK")
  53. var (
  54. magicDNSIP = tsaddr.TailscaleServiceIP()
  55. magicDNSIPv6 = tsaddr.TailscaleServiceIPv6()
  56. )
  57. func init() {
  58. var debugNetstackLeakMode = envknob.String("TS_DEBUG_NETSTACK_LEAK_MODE")
  59. // Note: netstacks refsvfs2 package that will eventually replace refs
  60. // consumes the refs.LeakMode setting, but enables some checks when set to
  61. // UninitializedLeakChecking which is what empty string becomes. This mode
  62. // is largely un-useful, so it is explicitly disabled here, and more useful
  63. // modes can be set via the envknob. See #4309 for more references.
  64. if debugNetstackLeakMode == "" {
  65. debugNetstackLeakMode = "disabled"
  66. }
  67. var lm refs.LeakMode
  68. lm.Set(debugNetstackLeakMode)
  69. refs.SetLeakMode(lm)
  70. }
  71. // Impl contains the state for the netstack implementation,
  72. // and implements wgengine.FakeImpl to act as a userspace network
  73. // stack when Tailscale is running in fake mode.
  74. type Impl struct {
  75. // ForwardTCPIn, if non-nil, handles forwarding an inbound TCP
  76. // connection.
  77. // TODO(bradfitz): provide mechanism for tsnet to reject a
  78. // port other than accepting it and closing it.
  79. ForwardTCPIn func(c net.Conn, port uint16)
  80. // ProcessLocalIPs is whether netstack should handle incoming
  81. // traffic directed at the Node.Addresses (local IPs).
  82. // It can only be set before calling Start.
  83. ProcessLocalIPs bool
  84. // ProcessSubnets is whether netstack should handle incoming
  85. // traffic destined to non-local IPs (i.e. whether it should
  86. // be a subnet router).
  87. // It can only be set before calling Start.
  88. ProcessSubnets bool
  89. ipstack *stack.Stack
  90. linkEP *channel.Endpoint
  91. tundev *tstun.Wrapper
  92. e wgengine.Engine
  93. mc *magicsock.Conn
  94. logf logger.Logf
  95. dialer *tsdial.Dialer
  96. ctx context.Context // alive until Close
  97. ctxCancel context.CancelFunc // called on Close
  98. lb *ipnlocal.LocalBackend // or nil
  99. dns *dns.Manager
  100. peerapiPort4Atomic uint32 // uint16 port number for IPv4 peerapi
  101. peerapiPort6Atomic uint32 // uint16 port number for IPv6 peerapi
  102. // atomicIsLocalIPFunc holds a func that reports whether an IP
  103. // is a local (non-subnet) Tailscale IP address of this
  104. // machine. It's always a non-nil func. It's changed on netmap
  105. // updates.
  106. atomicIsLocalIPFunc atomic.Value // of func(netaddr.IP) bool
  107. mu sync.Mutex
  108. // connsOpenBySubnetIP keeps track of number of connections open
  109. // for each subnet IP temporarily registered on netstack for active
  110. // TCP connections, so they can be unregistered when connections are
  111. // closed.
  112. connsOpenBySubnetIP map[netaddr.IP]int
  113. }
  114. // handleSSH is initialized in ssh.go (on Linux only) to register an SSH server
  115. // handler. See https://github.com/tailscale/tailscale/issues/3802.
  116. var handleSSH func(logger.Logf, *ipnlocal.LocalBackend, net.Conn) error
  117. const nicID = 1
  118. const mtu = tstun.DefaultMTU
  119. // maxUDPPacketSize is the maximum size of a UDP packet we copy in startPacketCopy
  120. // when relaying UDP packets. We don't use the 'mtu' const in anticipation of
  121. // one day making the MTU more dynamic.
  122. const maxUDPPacketSize = 1500
  123. // Create creates and populates a new Impl.
  124. func Create(logf logger.Logf, tundev *tstun.Wrapper, e wgengine.Engine, mc *magicsock.Conn, dialer *tsdial.Dialer, dns *dns.Manager) (*Impl, error) {
  125. if mc == nil {
  126. return nil, errors.New("nil magicsock.Conn")
  127. }
  128. if tundev == nil {
  129. return nil, errors.New("nil tundev")
  130. }
  131. if logf == nil {
  132. return nil, errors.New("nil logger")
  133. }
  134. if e == nil {
  135. return nil, errors.New("nil Engine")
  136. }
  137. if dialer == nil {
  138. return nil, errors.New("nil Dialer")
  139. }
  140. ipstack := stack.New(stack.Options{
  141. NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
  142. TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
  143. })
  144. linkEP := channel.New(512, mtu, "")
  145. if tcpipProblem := ipstack.CreateNIC(nicID, linkEP); tcpipProblem != nil {
  146. return nil, fmt.Errorf("could not create netstack NIC: %v", tcpipProblem)
  147. }
  148. // By default the netstack NIC will only accept packets for the IPs
  149. // registered to it. Since in some cases we dynamically register IPs
  150. // based on the packets that arrive, the NIC needs to accept all
  151. // incoming packets. The NIC won't receive anything it isn't meant to
  152. // since WireGuard will only send us packets that are meant for us.
  153. ipstack.SetPromiscuousMode(nicID, true)
  154. // Add IPv4 and IPv6 default routes, so all incoming packets from the Tailscale side
  155. // are handled by the one fake NIC we use.
  156. ipv4Subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 4)), tcpip.AddressMask(strings.Repeat("\x00", 4)))
  157. ipv6Subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 16)), tcpip.AddressMask(strings.Repeat("\x00", 16)))
  158. ipstack.SetRouteTable([]tcpip.Route{
  159. {
  160. Destination: ipv4Subnet,
  161. NIC: nicID,
  162. },
  163. {
  164. Destination: ipv6Subnet,
  165. NIC: nicID,
  166. },
  167. })
  168. ns := &Impl{
  169. logf: logf,
  170. ipstack: ipstack,
  171. linkEP: linkEP,
  172. tundev: tundev,
  173. e: e,
  174. mc: mc,
  175. dialer: dialer,
  176. connsOpenBySubnetIP: make(map[netaddr.IP]int),
  177. dns: dns,
  178. }
  179. ns.ctx, ns.ctxCancel = context.WithCancel(context.Background())
  180. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nil))
  181. return ns, nil
  182. }
  183. func (ns *Impl) Close() error {
  184. ns.ctxCancel()
  185. ns.ipstack.Close()
  186. return nil
  187. }
  188. // SetLocalBackend sets the LocalBackend; it should only be run before
  189. // the Start method is called.
  190. func (ns *Impl) SetLocalBackend(lb *ipnlocal.LocalBackend) {
  191. ns.lb = lb
  192. }
  193. // wrapProtoHandler returns protocol handler h wrapped in a version
  194. // that dynamically reconfigures ns's subnet addresses as needed for
  195. // outbound traffic.
  196. func (ns *Impl) wrapProtoHandler(h func(stack.TransportEndpointID, *stack.PacketBuffer) bool) func(stack.TransportEndpointID, *stack.PacketBuffer) bool {
  197. return func(tei stack.TransportEndpointID, pb *stack.PacketBuffer) bool {
  198. addr := tei.LocalAddress
  199. ip, ok := netaddr.FromStdIP(net.IP(addr))
  200. if !ok {
  201. ns.logf("netstack: could not parse local address for incoming connection")
  202. return false
  203. }
  204. if !ns.isLocalIP(ip) {
  205. ns.addSubnetAddress(ip)
  206. }
  207. return h(tei, pb)
  208. }
  209. }
  210. // Start sets up all the handlers so netstack can start working. Implements
  211. // wgengine.FakeImpl.
  212. func (ns *Impl) Start() error {
  213. ns.e.AddNetworkMapCallback(ns.updateIPs)
  214. // size = 0 means use default buffer size
  215. const tcpReceiveBufferSize = 0
  216. const maxInFlightConnectionAttempts = 16
  217. tcpFwd := tcp.NewForwarder(ns.ipstack, tcpReceiveBufferSize, maxInFlightConnectionAttempts, ns.acceptTCP)
  218. udpFwd := udp.NewForwarder(ns.ipstack, ns.acceptUDP)
  219. ns.ipstack.SetTransportProtocolHandler(tcp.ProtocolNumber, ns.wrapProtoHandler(tcpFwd.HandlePacket))
  220. ns.ipstack.SetTransportProtocolHandler(udp.ProtocolNumber, ns.wrapProtoHandler(udpFwd.HandlePacket))
  221. go ns.inject()
  222. ns.tundev.PostFilterIn = ns.injectInbound
  223. ns.tundev.PreFilterFromTunToNetstack = ns.handleLocalPackets
  224. return nil
  225. }
  226. func (ns *Impl) addSubnetAddress(ip netaddr.IP) {
  227. ns.mu.Lock()
  228. ns.connsOpenBySubnetIP[ip]++
  229. needAdd := ns.connsOpenBySubnetIP[ip] == 1
  230. ns.mu.Unlock()
  231. // Only register address into netstack for first concurrent connection.
  232. if needAdd {
  233. pa := tcpip.ProtocolAddress{
  234. AddressWithPrefix: tcpip.AddressWithPrefix{
  235. Address: tcpip.Address(ip.IPAddr().IP),
  236. PrefixLen: int(ip.BitLen()),
  237. },
  238. }
  239. if ip.Is4() {
  240. pa.Protocol = ipv4.ProtocolNumber
  241. } else if ip.Is6() {
  242. pa.Protocol = ipv6.ProtocolNumber
  243. }
  244. ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  245. PEB: stack.CanBePrimaryEndpoint, // zero value default
  246. ConfigType: stack.AddressConfigStatic, // zero value default
  247. })
  248. }
  249. }
  250. func (ns *Impl) removeSubnetAddress(ip netaddr.IP) {
  251. ns.mu.Lock()
  252. defer ns.mu.Unlock()
  253. ns.connsOpenBySubnetIP[ip]--
  254. // Only unregister address from netstack after last concurrent connection.
  255. if ns.connsOpenBySubnetIP[ip] == 0 {
  256. ns.ipstack.RemoveAddress(nicID, tcpip.Address(ip.IPAddr().IP))
  257. delete(ns.connsOpenBySubnetIP, ip)
  258. }
  259. }
  260. func ipPrefixToAddressWithPrefix(ipp netaddr.IPPrefix) tcpip.AddressWithPrefix {
  261. return tcpip.AddressWithPrefix{
  262. Address: tcpip.Address(ipp.IP().IPAddr().IP),
  263. PrefixLen: int(ipp.Bits()),
  264. }
  265. }
  266. var v4broadcast = netaddr.IPv4(255, 255, 255, 255)
  267. func (ns *Impl) updateIPs(nm *netmap.NetworkMap) {
  268. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nm.Addresses))
  269. oldIPs := make(map[tcpip.AddressWithPrefix]bool)
  270. for _, protocolAddr := range ns.ipstack.AllAddresses()[nicID] {
  271. ap := protocolAddr.AddressWithPrefix
  272. ip := netaddrIPFromNetstackIP(ap.Address)
  273. if ip == v4broadcast && ap.PrefixLen == 32 {
  274. // Don't add 255.255.255.255/32 to oldIPs so we don't
  275. // delete it later. We didn't install it, so it's not
  276. // ours to delete.
  277. continue
  278. }
  279. oldIPs[ap] = true
  280. }
  281. newIPs := make(map[tcpip.AddressWithPrefix]bool)
  282. isAddr := map[netaddr.IPPrefix]bool{}
  283. if nm.SelfNode != nil {
  284. for _, ipp := range nm.SelfNode.Addresses {
  285. isAddr[ipp] = true
  286. newIPs[ipPrefixToAddressWithPrefix(ipp)] = true
  287. }
  288. for _, ipp := range nm.SelfNode.AllowedIPs {
  289. if !isAddr[ipp] && ns.ProcessSubnets {
  290. newIPs[ipPrefixToAddressWithPrefix(ipp)] = true
  291. }
  292. }
  293. }
  294. ipsToBeAdded := make(map[tcpip.AddressWithPrefix]bool)
  295. for ipp := range newIPs {
  296. if !oldIPs[ipp] {
  297. ipsToBeAdded[ipp] = true
  298. }
  299. }
  300. ipsToBeRemoved := make(map[tcpip.AddressWithPrefix]bool)
  301. for ip := range oldIPs {
  302. if !newIPs[ip] {
  303. ipsToBeRemoved[ip] = true
  304. }
  305. }
  306. ns.mu.Lock()
  307. for ip := range ns.connsOpenBySubnetIP {
  308. ipp := tcpip.Address(ip.IPAddr().IP).WithPrefix()
  309. delete(ipsToBeRemoved, ipp)
  310. }
  311. ns.mu.Unlock()
  312. for ipp := range ipsToBeRemoved {
  313. err := ns.ipstack.RemoveAddress(nicID, ipp.Address)
  314. if err != nil {
  315. ns.logf("netstack: could not deregister IP %s: %v", ipp, err)
  316. } else {
  317. ns.logf("[v2] netstack: deregistered IP %s", ipp)
  318. }
  319. }
  320. for ipp := range ipsToBeAdded {
  321. pa := tcpip.ProtocolAddress{
  322. AddressWithPrefix: ipp,
  323. }
  324. if ipp.Address.To4() == "" {
  325. pa.Protocol = ipv6.ProtocolNumber
  326. } else {
  327. pa.Protocol = ipv4.ProtocolNumber
  328. }
  329. var err tcpip.Error
  330. err = ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  331. PEB: stack.CanBePrimaryEndpoint, // zero value default
  332. ConfigType: stack.AddressConfigStatic, // zero value default
  333. })
  334. if err != nil {
  335. ns.logf("netstack: could not register IP %s: %v", ipp, err)
  336. } else {
  337. ns.logf("[v2] netstack: registered IP %s", ipp)
  338. }
  339. }
  340. }
  341. // handleLocalPackets is hooked into the tun datapath for packets leaving
  342. // the host and arriving at tailscaled. This method returns filter.DropSilently
  343. // to intercept a packet for handling, for instance traffic to quad-100.
  344. func (ns *Impl) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  345. // If it's not traffic to the service IP (i.e. magicDNS) we don't
  346. // care; resume processing.
  347. if dst := p.Dst.IP(); dst != magicDNSIP && dst != magicDNSIPv6 {
  348. return filter.Accept
  349. }
  350. // Of traffic to the service IP, we only care about UDP 53, and TCP
  351. // on port 80 & 53.
  352. switch p.IPProto {
  353. case ipproto.TCP:
  354. if port := p.Dst.Port(); port != 53 && port != 80 {
  355. return filter.Accept
  356. }
  357. case ipproto.UDP:
  358. if port := p.Dst.Port(); port != 53 {
  359. return filter.Accept
  360. }
  361. }
  362. var pn tcpip.NetworkProtocolNumber
  363. switch p.IPVersion {
  364. case 4:
  365. pn = header.IPv4ProtocolNumber
  366. case 6:
  367. pn = header.IPv6ProtocolNumber
  368. }
  369. if debugPackets {
  370. ns.logf("[v2] service packet in (from %v): % x", p.Src, p.Buffer())
  371. }
  372. vv := buffer.View(append([]byte(nil), p.Buffer()...)).ToVectorisedView()
  373. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  374. Data: vv,
  375. })
  376. ns.linkEP.InjectInbound(pn, packetBuf)
  377. packetBuf.DecRef()
  378. return filter.DropSilently
  379. }
  380. func (ns *Impl) DialContextTCP(ctx context.Context, ipp netaddr.IPPort) (*gonet.TCPConn, error) {
  381. remoteAddress := tcpip.FullAddress{
  382. NIC: nicID,
  383. Addr: tcpip.Address(ipp.IP().IPAddr().IP),
  384. Port: ipp.Port(),
  385. }
  386. var ipType tcpip.NetworkProtocolNumber
  387. if ipp.IP().Is4() {
  388. ipType = ipv4.ProtocolNumber
  389. } else {
  390. ipType = ipv6.ProtocolNumber
  391. }
  392. return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
  393. }
  394. func (ns *Impl) DialContextUDP(ctx context.Context, ipp netaddr.IPPort) (*gonet.UDPConn, error) {
  395. remoteAddress := &tcpip.FullAddress{
  396. NIC: nicID,
  397. Addr: tcpip.Address(ipp.IP().IPAddr().IP),
  398. Port: ipp.Port(),
  399. }
  400. var ipType tcpip.NetworkProtocolNumber
  401. if ipp.IP().Is4() {
  402. ipType = ipv4.ProtocolNumber
  403. } else {
  404. ipType = ipv6.ProtocolNumber
  405. }
  406. return gonet.DialUDP(ns.ipstack, nil, remoteAddress, ipType)
  407. }
  408. // The inject goroutine reads in packets that netstack generated, and delivers
  409. // them to the correct path.
  410. func (ns *Impl) inject() {
  411. for {
  412. pkt := ns.linkEP.ReadContext(ns.ctx)
  413. if pkt == nil {
  414. if ns.ctx.Err() != nil {
  415. // Return without logging.
  416. return
  417. }
  418. ns.logf("[v2] ReadContext-for-write = ok=false")
  419. continue
  420. }
  421. if debugPackets {
  422. ns.logf("[v2] packet Write out: % x", stack.PayloadSince(pkt.NetworkHeader()))
  423. }
  424. // In the normal case, netstack synthesizes the bytes for
  425. // traffic which should transit back into WG and go to peers.
  426. // However, some uses of netstack (presently, magic DNS)
  427. // send traffic destined for the local device, hence must
  428. // be injected 'inbound'.
  429. sendToHost := false
  430. // Determine if the packet is from a service IP, in which case it
  431. // needs to go back into the machines network (inbound) instead of
  432. // out.
  433. // TODO(tom): Work out a way to avoid parsing packets to determine if
  434. // its from the service IP. Maybe gvisor netstack magic. I
  435. // went through the fields of PacketBuffer, and nop :/
  436. // TODO(tom): Figure out if its safe to modify packet.Parsed to fill in
  437. // the IP src/dest even if its missing the rest of the pkt.
  438. // That way we dont have to do this twitchy-af byte-yeeting.
  439. if b := pkt.NetworkHeader().View(); len(b) >= 20 { // min ipv4 header
  440. switch b[0] >> 4 { // ip proto field
  441. case 4:
  442. if srcIP := netaddr.IPv4(b[12], b[13], b[14], b[15]); magicDNSIP == srcIP {
  443. sendToHost = true
  444. }
  445. case 6:
  446. if len(b) >= 40 { // min ipv6 header
  447. if srcIP, ok := netaddr.FromStdIP(net.IP(b[8:24])); ok && magicDNSIPv6 == srcIP {
  448. sendToHost = true
  449. }
  450. }
  451. }
  452. }
  453. // pkt has a non-zero refcount, so injection methods takes
  454. // ownership of one count and will decrement on completion.
  455. if sendToHost {
  456. if err := ns.tundev.InjectInboundPacketBuffer(pkt); err != nil {
  457. log.Printf("netstack inject inbound: %v", err)
  458. return
  459. }
  460. } else {
  461. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  462. log.Printf("netstack inject outbound: %v", err)
  463. return
  464. }
  465. }
  466. }
  467. }
  468. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  469. // node directly (but not a subnet-routed IP).
  470. func (ns *Impl) isLocalIP(ip netaddr.IP) bool {
  471. return ns.atomicIsLocalIPFunc.Load().(func(netaddr.IP) bool)(ip)
  472. }
  473. func (ns *Impl) processSSH() bool {
  474. return ns.lb != nil && ns.lb.ShouldRunSSH()
  475. }
  476. func (ns *Impl) peerAPIPortAtomic(ip netaddr.IP) *uint32 {
  477. if ip.Is4() {
  478. return &ns.peerapiPort4Atomic
  479. } else {
  480. return &ns.peerapiPort6Atomic
  481. }
  482. }
  483. var viaRange = tsaddr.TailscaleViaRange()
  484. // shouldProcessInbound reports whether an inbound packet (a packet from a
  485. // WireGuard peer) should be handled by netstack.
  486. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  487. // Handle incoming peerapi connections in netstack.
  488. if ns.lb != nil && p.IPProto == ipproto.TCP {
  489. var peerAPIPort uint16
  490. dstIP := p.Dst.IP()
  491. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn && ns.isLocalIP(dstIP) {
  492. if port, ok := ns.lb.GetPeerAPIPort(p.Dst.IP()); ok {
  493. peerAPIPort = port
  494. atomic.StoreUint32(ns.peerAPIPortAtomic(dstIP), uint32(port))
  495. }
  496. } else {
  497. peerAPIPort = uint16(atomic.LoadUint32(ns.peerAPIPortAtomic(dstIP)))
  498. }
  499. if p.IPProto == ipproto.TCP && p.Dst.Port() == peerAPIPort {
  500. return true
  501. }
  502. }
  503. if ns.isInboundTSSH(p) && ns.processSSH() {
  504. return true
  505. }
  506. if p.IPVersion == 6 && viaRange.Contains(p.Dst.IP()) {
  507. return ns.lb != nil && ns.lb.ShouldHandleViaIP(p.Dst.IP())
  508. }
  509. if !ns.ProcessLocalIPs && !ns.ProcessSubnets {
  510. // Fast path for common case (e.g. Linux server in TUN mode) where
  511. // netstack isn't used at all; don't even do an isLocalIP lookup.
  512. return false
  513. }
  514. isLocal := ns.isLocalIP(p.Dst.IP())
  515. if ns.ProcessLocalIPs && isLocal {
  516. return true
  517. }
  518. if ns.ProcessSubnets && !isLocal {
  519. return true
  520. }
  521. return false
  522. }
  523. // setAmbientCapsRaw is non-nil on Linux for Synology, to run ping with
  524. // CAP_NET_RAW from tailscaled's binary.
  525. var setAmbientCapsRaw func(*exec.Cmd)
  526. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  527. var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
  528. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  529. // into the tundev.
  530. //
  531. // It's used in userspace/netstack mode when we don't have kernel
  532. // support or raw socket access. As such, this does the dumbest thing
  533. // that can work: runs the ping command. It's not super efficient, so
  534. // it bounds the number of pings going on at once. The idea is that
  535. // people only use ping occasionally to see if their internet's working
  536. // so this doesn't need to be great.
  537. //
  538. // TODO(bradfitz): when we're running on Windows as the system user, use
  539. // raw socket APIs instead of ping child processes.
  540. func (ns *Impl) userPing(dstIP netaddr.IP, pingResPkt []byte) {
  541. if !userPingSem.TryAcquire() {
  542. return
  543. }
  544. defer userPingSem.Release()
  545. t0 := time.Now()
  546. var err error
  547. switch runtime.GOOS {
  548. case "windows":
  549. err = exec.Command("ping", "-n", "1", "-w", "3000", dstIP.String()).Run()
  550. case "darwin":
  551. // Note: 2000 ms is actually 1 second + 2,000
  552. // milliseconds extra for 3 seconds total.
  553. // See https://github.com/tailscale/tailscale/pull/3753 for details.
  554. err = exec.Command("ping", "-c", "1", "-W", "2000", dstIP.String()).Run()
  555. case "android":
  556. ping := "/system/bin/ping"
  557. if dstIP.Is6() {
  558. ping = "/system/bin/ping6"
  559. }
  560. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  561. default:
  562. ping := "ping"
  563. if isSynology {
  564. ping = "/bin/ping"
  565. }
  566. cmd := exec.Command(ping, "-c", "1", "-W", "3", dstIP.String())
  567. if isSynology && os.Getuid() != 0 {
  568. // On DSM7 we run as non-root and need to pass
  569. // CAP_NET_RAW if our binary has it.
  570. setAmbientCapsRaw(cmd)
  571. }
  572. err = cmd.Run()
  573. }
  574. d := time.Since(t0)
  575. if err != nil {
  576. if d < time.Second/2 {
  577. // If it failed quicker than the 3 second
  578. // timeout we gave above (500 ms is a
  579. // reasonable threshold), then assume the ping
  580. // failed for problems finding/running
  581. // ping. We don't want to log if the host is
  582. // just down.
  583. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  584. }
  585. return
  586. }
  587. if debugNetstack {
  588. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  589. }
  590. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  591. ns.logf("InjectOutbound ping response: %v", err)
  592. }
  593. }
  594. func (ns *Impl) isInboundTSSH(p *packet.Parsed) bool {
  595. return p.IPProto == ipproto.TCP &&
  596. p.Dst.Port() == 22 &&
  597. ns.isLocalIP(p.Dst.IP())
  598. }
  599. // injectInbound is installed as a packet hook on the 'inbound' (from a
  600. // WireGuard peer) path. Returning filter.Accept releases the packet to
  601. // continue normally (typically being delivered to the host networking stack),
  602. // whereas returning filter.DropSilently is done when netstack intercepts the
  603. // packet and no further processing towards to host should be done.
  604. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  605. if !ns.shouldProcessInbound(p, t) {
  606. // Let the host network stack (if any) deal with it.
  607. return filter.Accept
  608. }
  609. destIP := p.Dst.IP()
  610. if p.IsEchoRequest() && ns.ProcessSubnets && !tsaddr.IsTailscaleIP(destIP) {
  611. var pong []byte // the reply to the ping, if our relayed ping works
  612. if destIP.Is4() {
  613. h := p.ICMP4Header()
  614. h.ToResponse()
  615. pong = packet.Generate(&h, p.Payload())
  616. } else if destIP.Is6() {
  617. h := p.ICMP6Header()
  618. h.ToResponse()
  619. pong = packet.Generate(&h, p.Payload())
  620. }
  621. go ns.userPing(destIP, pong)
  622. return filter.DropSilently
  623. }
  624. var pn tcpip.NetworkProtocolNumber
  625. switch p.IPVersion {
  626. case 4:
  627. pn = header.IPv4ProtocolNumber
  628. case 6:
  629. pn = header.IPv6ProtocolNumber
  630. }
  631. if debugPackets {
  632. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  633. }
  634. vv := buffer.View(append([]byte(nil), p.Buffer()...)).ToVectorisedView()
  635. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  636. Data: vv,
  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) netaddr.IP {
  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 netaddr.IPFrom16(a)
  656. }
  657. return netaddr.IP{}
  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, netaddr.IPPortFrom(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 := netaddr.IPPortFrom(clientRemoteIP, reqDetails.RemotePort)
  728. dst := netaddr.IPPortFrom(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 := netaddr.IPPortFrom(dialIP, uint16(reqDetails.LocalPort))
  746. ns.forwardTCP(c, clientRemoteIP, &wq, dialAddr)
  747. }
  748. func (ns *Impl) forwardTCP(client *gonet.TCPConn, clientRemoteIP netaddr.IP, wq *waiter.Queue, dialAddr netaddr.IPPort) {
  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.IP(); 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 netaddr.IPPort, 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 netaddr.IPPort) {
  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.IP())
  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.IP(); viaRange.Contains(dstIP) {
  881. dstAddr = netaddr.IPPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
  882. }
  883. backendRemoteAddr = dstAddr.UDPAddr()
  884. if dstAddr.IP().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.IP())
  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, clientAddr.UDPAddr(), 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.IP())
  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 netaddr.IPPort, ok bool) {
  980. return netaddr.FromStdAddr(net.IP(a), int(port), "") // TODO(bradfitz): can do without allocs
  981. }