netstack.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. "inet.af/netaddr"
  22. "inet.af/netstack/tcpip"
  23. "inet.af/netstack/tcpip/adapters/gonet"
  24. "inet.af/netstack/tcpip/buffer"
  25. "inet.af/netstack/tcpip/header"
  26. "inet.af/netstack/tcpip/link/channel"
  27. "inet.af/netstack/tcpip/network/ipv4"
  28. "inet.af/netstack/tcpip/network/ipv6"
  29. "inet.af/netstack/tcpip/stack"
  30. "inet.af/netstack/tcpip/transport/icmp"
  31. "inet.af/netstack/tcpip/transport/tcp"
  32. "inet.af/netstack/tcpip/transport/udp"
  33. "inet.af/netstack/waiter"
  34. "tailscale.com/envknob"
  35. "tailscale.com/net/packet"
  36. "tailscale.com/net/tsaddr"
  37. "tailscale.com/net/tsdial"
  38. "tailscale.com/net/tstun"
  39. "tailscale.com/syncs"
  40. "tailscale.com/types/logger"
  41. "tailscale.com/types/netmap"
  42. "tailscale.com/version/distro"
  43. "tailscale.com/wgengine"
  44. "tailscale.com/wgengine/filter"
  45. "tailscale.com/wgengine/magicsock"
  46. )
  47. const debugPackets = false
  48. var debugNetstack = envknob.Bool("TS_DEBUG_NETSTACK")
  49. // Impl contains the state for the netstack implementation,
  50. // and implements wgengine.FakeImpl to act as a userspace network
  51. // stack when Tailscale is running in fake mode.
  52. type Impl struct {
  53. // ForwardTCPIn, if non-nil, handles forwarding an inbound TCP
  54. // connection.
  55. // TODO(bradfitz): provide mechanism for tsnet to reject a
  56. // port other than accepting it and closing it.
  57. ForwardTCPIn func(c net.Conn, port uint16)
  58. // ProcessLocalIPs is whether netstack should handle incoming
  59. // traffic directed at the Node.Addresses (local IPs).
  60. // It can only be set before calling Start.
  61. ProcessLocalIPs bool
  62. // ProcessSubnets is whether netstack should handle incoming
  63. // traffic destined to non-local IPs (i.e. whether it should
  64. // be a subnet router).
  65. // It can only be set before calling Start.
  66. ProcessSubnets bool
  67. ipstack *stack.Stack
  68. linkEP *channel.Endpoint
  69. tundev *tstun.Wrapper
  70. e wgengine.Engine
  71. mc *magicsock.Conn
  72. logf logger.Logf
  73. dialer *tsdial.Dialer
  74. ctx context.Context // alive until Close
  75. ctxCancel context.CancelFunc // called on Close
  76. // atomicIsLocalIPFunc holds a func that reports whether an IP
  77. // is a local (non-subnet) Tailscale IP address of this
  78. // machine. It's always a non-nil func. It's changed on netmap
  79. // updates.
  80. atomicIsLocalIPFunc atomic.Value // of func(netaddr.IP) bool
  81. mu sync.Mutex
  82. // connsOpenBySubnetIP keeps track of number of connections open
  83. // for each subnet IP temporarily registered on netstack for active
  84. // TCP connections, so they can be unregistered when connections are
  85. // closed.
  86. connsOpenBySubnetIP map[netaddr.IP]int
  87. }
  88. const nicID = 1
  89. const mtu = 1500
  90. // Create creates and populates a new Impl.
  91. func Create(logf logger.Logf, tundev *tstun.Wrapper, e wgengine.Engine, mc *magicsock.Conn, dialer *tsdial.Dialer) (*Impl, error) {
  92. if mc == nil {
  93. return nil, errors.New("nil magicsock.Conn")
  94. }
  95. if tundev == nil {
  96. return nil, errors.New("nil tundev")
  97. }
  98. if logf == nil {
  99. return nil, errors.New("nil logger")
  100. }
  101. if e == nil {
  102. return nil, errors.New("nil Engine")
  103. }
  104. if dialer == nil {
  105. return nil, errors.New("nil Dialer")
  106. }
  107. ipstack := stack.New(stack.Options{
  108. NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
  109. TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
  110. })
  111. linkEP := channel.New(512, mtu, "")
  112. if tcpipProblem := ipstack.CreateNIC(nicID, linkEP); tcpipProblem != nil {
  113. return nil, fmt.Errorf("could not create netstack NIC: %v", tcpipProblem)
  114. }
  115. // By default the netstack NIC will only accept packets for the IPs
  116. // registered to it. Since in some cases we dynamically register IPs
  117. // based on the packets that arrive, the NIC needs to accept all
  118. // incoming packets. The NIC won't receive anything it isn't meant to
  119. // since Wireguard will only send us packets that are meant for us.
  120. ipstack.SetPromiscuousMode(nicID, true)
  121. // Add IPv4 and IPv6 default routes, so all incoming packets from the Tailscale side
  122. // are handled by the one fake NIC we use.
  123. ipv4Subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 4)), tcpip.AddressMask(strings.Repeat("\x00", 4)))
  124. ipv6Subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 16)), tcpip.AddressMask(strings.Repeat("\x00", 16)))
  125. ipstack.SetRouteTable([]tcpip.Route{
  126. {
  127. Destination: ipv4Subnet,
  128. NIC: nicID,
  129. },
  130. {
  131. Destination: ipv6Subnet,
  132. NIC: nicID,
  133. },
  134. })
  135. ns := &Impl{
  136. logf: logf,
  137. ipstack: ipstack,
  138. linkEP: linkEP,
  139. tundev: tundev,
  140. e: e,
  141. mc: mc,
  142. dialer: dialer,
  143. connsOpenBySubnetIP: make(map[netaddr.IP]int),
  144. }
  145. ns.ctx, ns.ctxCancel = context.WithCancel(context.Background())
  146. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nil))
  147. return ns, nil
  148. }
  149. func (ns *Impl) Close() error {
  150. ns.ctxCancel()
  151. return nil
  152. }
  153. // wrapProtoHandler returns protocol handler h wrapped in a version
  154. // that dynamically reconfigures ns's subnet addresses as needed for
  155. // outbound traffic.
  156. func (ns *Impl) wrapProtoHandler(h func(stack.TransportEndpointID, *stack.PacketBuffer) bool) func(stack.TransportEndpointID, *stack.PacketBuffer) bool {
  157. return func(tei stack.TransportEndpointID, pb *stack.PacketBuffer) bool {
  158. addr := tei.LocalAddress
  159. ip, ok := netaddr.FromStdIP(net.IP(addr))
  160. if !ok {
  161. ns.logf("netstack: could not parse local address for incoming connection")
  162. return false
  163. }
  164. if !ns.isLocalIP(ip) {
  165. ns.addSubnetAddress(ip)
  166. }
  167. return h(tei, pb)
  168. }
  169. }
  170. // Start sets up all the handlers so netstack can start working. Implements
  171. // wgengine.FakeImpl.
  172. func (ns *Impl) Start() error {
  173. ns.e.AddNetworkMapCallback(ns.updateIPs)
  174. // size = 0 means use default buffer size
  175. const tcpReceiveBufferSize = 0
  176. const maxInFlightConnectionAttempts = 16
  177. tcpFwd := tcp.NewForwarder(ns.ipstack, tcpReceiveBufferSize, maxInFlightConnectionAttempts, ns.acceptTCP)
  178. udpFwd := udp.NewForwarder(ns.ipstack, ns.acceptUDP)
  179. ns.ipstack.SetTransportProtocolHandler(tcp.ProtocolNumber, ns.wrapProtoHandler(tcpFwd.HandlePacket))
  180. ns.ipstack.SetTransportProtocolHandler(udp.ProtocolNumber, ns.wrapProtoHandler(udpFwd.HandlePacket))
  181. go ns.injectOutbound()
  182. ns.tundev.PostFilterIn = ns.injectInbound
  183. return nil
  184. }
  185. func (ns *Impl) addSubnetAddress(ip netaddr.IP) {
  186. ns.mu.Lock()
  187. ns.connsOpenBySubnetIP[ip]++
  188. needAdd := ns.connsOpenBySubnetIP[ip] == 1
  189. ns.mu.Unlock()
  190. // Only register address into netstack for first concurrent connection.
  191. if needAdd {
  192. pa := tcpip.ProtocolAddress{
  193. AddressWithPrefix: tcpip.AddressWithPrefix{
  194. Address: tcpip.Address(ip.IPAddr().IP),
  195. PrefixLen: int(ip.BitLen()),
  196. },
  197. }
  198. if ip.Is4() {
  199. pa.Protocol = ipv4.ProtocolNumber
  200. } else if ip.Is6() {
  201. pa.Protocol = ipv6.ProtocolNumber
  202. }
  203. ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  204. PEB: stack.CanBePrimaryEndpoint, // zero value default
  205. ConfigType: stack.AddressConfigStatic, // zero value default
  206. })
  207. }
  208. }
  209. func (ns *Impl) removeSubnetAddress(ip netaddr.IP) {
  210. ns.mu.Lock()
  211. defer ns.mu.Unlock()
  212. ns.connsOpenBySubnetIP[ip]--
  213. // Only unregister address from netstack after last concurrent connection.
  214. if ns.connsOpenBySubnetIP[ip] == 0 {
  215. ns.ipstack.RemoveAddress(nicID, tcpip.Address(ip.IPAddr().IP))
  216. delete(ns.connsOpenBySubnetIP, ip)
  217. }
  218. }
  219. func ipPrefixToAddressWithPrefix(ipp netaddr.IPPrefix) tcpip.AddressWithPrefix {
  220. return tcpip.AddressWithPrefix{
  221. Address: tcpip.Address(ipp.IP().IPAddr().IP),
  222. PrefixLen: int(ipp.Bits()),
  223. }
  224. }
  225. var v4broadcast = netaddr.IPv4(255, 255, 255, 255)
  226. func (ns *Impl) updateIPs(nm *netmap.NetworkMap) {
  227. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nm.Addresses))
  228. oldIPs := make(map[tcpip.AddressWithPrefix]bool)
  229. for _, protocolAddr := range ns.ipstack.AllAddresses()[nicID] {
  230. ap := protocolAddr.AddressWithPrefix
  231. ip := netaddrIPFromNetstackIP(ap.Address)
  232. if ip == v4broadcast && ap.PrefixLen == 32 {
  233. // Don't delete this one later. It seems to be important.
  234. // Related to Issue 2642? Likely.
  235. continue
  236. }
  237. oldIPs[ap] = true
  238. }
  239. newIPs := make(map[tcpip.AddressWithPrefix]bool)
  240. isAddr := map[netaddr.IPPrefix]bool{}
  241. if nm.SelfNode != nil {
  242. for _, ipp := range nm.SelfNode.Addresses {
  243. isAddr[ipp] = true
  244. }
  245. for _, ipp := range nm.SelfNode.AllowedIPs {
  246. local := isAddr[ipp]
  247. if local && ns.ProcessLocalIPs || !local && ns.ProcessSubnets {
  248. newIPs[ipPrefixToAddressWithPrefix(ipp)] = true
  249. }
  250. }
  251. }
  252. ipsToBeAdded := make(map[tcpip.AddressWithPrefix]bool)
  253. for ipp := range newIPs {
  254. if !oldIPs[ipp] {
  255. ipsToBeAdded[ipp] = true
  256. }
  257. }
  258. ipsToBeRemoved := make(map[tcpip.AddressWithPrefix]bool)
  259. for ip := range oldIPs {
  260. if !newIPs[ip] {
  261. ipsToBeRemoved[ip] = true
  262. }
  263. }
  264. ns.mu.Lock()
  265. for ip := range ns.connsOpenBySubnetIP {
  266. ipp := tcpip.Address(ip.IPAddr().IP).WithPrefix()
  267. delete(ipsToBeRemoved, ipp)
  268. }
  269. ns.mu.Unlock()
  270. for ipp := range ipsToBeRemoved {
  271. err := ns.ipstack.RemoveAddress(nicID, ipp.Address)
  272. if err != nil {
  273. ns.logf("netstack: could not deregister IP %s: %v", ipp, err)
  274. } else {
  275. ns.logf("[v2] netstack: deregistered IP %s", ipp)
  276. }
  277. }
  278. for ipp := range ipsToBeAdded {
  279. pa := tcpip.ProtocolAddress{
  280. AddressWithPrefix: ipp,
  281. }
  282. if ipp.Address.To4() == "" {
  283. pa.Protocol = ipv6.ProtocolNumber
  284. } else {
  285. pa.Protocol = ipv4.ProtocolNumber
  286. }
  287. var err tcpip.Error
  288. err = ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  289. PEB: stack.CanBePrimaryEndpoint, // zero value default
  290. ConfigType: stack.AddressConfigStatic, // zero value default
  291. })
  292. if err != nil {
  293. ns.logf("netstack: could not register IP %s: %v", ipp, err)
  294. } else {
  295. ns.logf("[v2] netstack: registered IP %s", ipp)
  296. }
  297. }
  298. }
  299. func (ns *Impl) DialContextTCP(ctx context.Context, ipp netaddr.IPPort) (*gonet.TCPConn, error) {
  300. remoteAddress := tcpip.FullAddress{
  301. NIC: nicID,
  302. Addr: tcpip.Address(ipp.IP().IPAddr().IP),
  303. Port: ipp.Port(),
  304. }
  305. var ipType tcpip.NetworkProtocolNumber
  306. if ipp.IP().Is4() {
  307. ipType = ipv4.ProtocolNumber
  308. } else {
  309. ipType = ipv6.ProtocolNumber
  310. }
  311. return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
  312. }
  313. func (ns *Impl) DialContextUDP(ctx context.Context, ipp netaddr.IPPort) (*gonet.UDPConn, error) {
  314. remoteAddress := &tcpip.FullAddress{
  315. NIC: nicID,
  316. Addr: tcpip.Address(ipp.IP().IPAddr().IP),
  317. Port: ipp.Port(),
  318. }
  319. var ipType tcpip.NetworkProtocolNumber
  320. if ipp.IP().Is4() {
  321. ipType = ipv4.ProtocolNumber
  322. } else {
  323. ipType = ipv6.ProtocolNumber
  324. }
  325. return gonet.DialUDP(ns.ipstack, nil, remoteAddress, ipType)
  326. }
  327. func (ns *Impl) injectOutbound() {
  328. for {
  329. packetInfo, ok := ns.linkEP.ReadContext(ns.ctx)
  330. if !ok {
  331. if ns.ctx.Err() != nil {
  332. // Return without logging.
  333. return
  334. }
  335. ns.logf("[v2] ReadContext-for-write = ok=false")
  336. continue
  337. }
  338. pkt := packetInfo.Pkt
  339. hdrNetwork := pkt.NetworkHeader()
  340. hdrTransport := pkt.TransportHeader()
  341. full := make([]byte, 0, pkt.Size())
  342. full = append(full, hdrNetwork.View()...)
  343. full = append(full, hdrTransport.View()...)
  344. full = append(full, pkt.Data().AsRange().AsView()...)
  345. if debugPackets {
  346. ns.logf("[v2] packet Write out: % x", full)
  347. }
  348. if err := ns.tundev.InjectOutbound(full); err != nil {
  349. log.Printf("netstack inject outbound: %v", err)
  350. return
  351. }
  352. }
  353. }
  354. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  355. // node directly (but not a subnet-routed IP).
  356. func (ns *Impl) isLocalIP(ip netaddr.IP) bool {
  357. return ns.atomicIsLocalIPFunc.Load().(func(netaddr.IP) bool)(ip)
  358. }
  359. // shouldProcessInbound reports whether an inbound packet should be
  360. // handled by netstack.
  361. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  362. if !ns.ProcessLocalIPs && !ns.ProcessSubnets {
  363. // Fast path for common case (e.g. Linux server in TUN mode) where
  364. // netstack isn't used at all; don't even do an isLocalIP lookup.
  365. return false
  366. }
  367. isLocal := ns.isLocalIP(p.Dst.IP())
  368. if ns.ProcessLocalIPs && isLocal {
  369. return true
  370. }
  371. if ns.ProcessSubnets && !isLocal {
  372. return true
  373. }
  374. return false
  375. }
  376. // setAmbientCapsRaw is non-nil on Linux for Synology, to run ping with
  377. // CAP_NET_RAW from tailscaled's binary.
  378. var setAmbientCapsRaw func(*exec.Cmd)
  379. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  380. var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
  381. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  382. // into the tundev.
  383. //
  384. // It's used in userspace/netstack mode when we don't have kernel
  385. // support or raw socket access. As such, this does the dumbest thing
  386. // that can work: runs the ping command. It's not super efficient, so
  387. // it bounds the number of pings going on at once. The idea is that
  388. // people only use ping occasionally to see if their internet's working
  389. // so this doesn't need to be great.
  390. //
  391. // TODO(bradfitz): when we're running on Windows as the system user, use
  392. // raw socket APIs instead of ping child processes.
  393. func (ns *Impl) userPing(dstIP netaddr.IP, pingResPkt []byte) {
  394. if !userPingSem.TryAcquire() {
  395. return
  396. }
  397. defer userPingSem.Release()
  398. t0 := time.Now()
  399. var err error
  400. switch runtime.GOOS {
  401. case "windows":
  402. err = exec.Command("ping", "-n", "1", "-w", "3000", dstIP.String()).Run()
  403. case "darwin":
  404. // Note: 2000 ms is actually 1 second + 2,000
  405. // milliseconds extra for 3 seconds total.
  406. // See https://github.com/tailscale/tailscale/pull/3753 for details.
  407. err = exec.Command("ping", "-c", "1", "-W", "2000", dstIP.String()).Run()
  408. case "android":
  409. ping := "/system/bin/ping"
  410. if dstIP.Is6() {
  411. ping = "/system/bin/ping6"
  412. }
  413. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  414. default:
  415. ping := "ping"
  416. if isSynology {
  417. ping = "/bin/ping"
  418. }
  419. cmd := exec.Command(ping, "-c", "1", "-W", "3", dstIP.String())
  420. if isSynology && os.Getuid() != 0 {
  421. // On DSM7 we run as non-root and need to pass
  422. // CAP_NET_RAW if our binary has it.
  423. setAmbientCapsRaw(cmd)
  424. }
  425. err = cmd.Run()
  426. }
  427. d := time.Since(t0)
  428. if err != nil {
  429. if d < time.Second/2 {
  430. // If it failed quicker than the 3 second
  431. // timeout we gave above (500 ms is a
  432. // reasonable threshold), then assume the ping
  433. // failed for problems finding/running
  434. // ping. We don't want to log if the host is
  435. // just down.
  436. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  437. }
  438. return
  439. }
  440. if debugNetstack {
  441. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  442. }
  443. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  444. ns.logf("InjectOutbound ping response: %v", err)
  445. }
  446. }
  447. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  448. if !ns.shouldProcessInbound(p, t) {
  449. // Let the host network stack (if any) deal with it.
  450. return filter.Accept
  451. }
  452. destIP := p.Dst.IP()
  453. if p.IsEchoRequest() && ns.ProcessSubnets && !tsaddr.IsTailscaleIP(destIP) {
  454. var pong []byte // the reply to the ping, if our relayed ping works
  455. if destIP.Is4() {
  456. h := p.ICMP4Header()
  457. h.ToResponse()
  458. pong = packet.Generate(&h, p.Payload())
  459. } else if destIP.Is6() {
  460. h := p.ICMP6Header()
  461. h.ToResponse()
  462. pong = packet.Generate(&h, p.Payload())
  463. }
  464. go ns.userPing(destIP, pong)
  465. return filter.DropSilently
  466. }
  467. var pn tcpip.NetworkProtocolNumber
  468. switch p.IPVersion {
  469. case 4:
  470. pn = header.IPv4ProtocolNumber
  471. case 6:
  472. pn = header.IPv6ProtocolNumber
  473. }
  474. p.RemoveECNBits() // Issue 2642
  475. if debugPackets {
  476. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  477. }
  478. vv := buffer.View(append([]byte(nil), p.Buffer()...)).ToVectorisedView()
  479. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  480. Data: vv,
  481. })
  482. ns.linkEP.InjectInbound(pn, packetBuf)
  483. packetBuf.DecRef()
  484. // We've now delivered this to netstack, so we're done.
  485. // Instead of returning a filter.Accept here (which would also
  486. // potentially deliver it to the host OS), and instead of
  487. // filter.Drop (which would log about rejected traffic),
  488. // instead return filter.DropSilently which just quietly stops
  489. // processing it in the tstun TUN wrapper.
  490. return filter.DropSilently
  491. }
  492. func netaddrIPFromNetstackIP(s tcpip.Address) netaddr.IP {
  493. switch len(s) {
  494. case 4:
  495. return netaddr.IPv4(s[0], s[1], s[2], s[3])
  496. case 16:
  497. var a [16]byte
  498. copy(a[:], s)
  499. return netaddr.IPFrom16(a)
  500. }
  501. return netaddr.IP{}
  502. }
  503. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  504. reqDetails := r.ID()
  505. if debugNetstack {
  506. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  507. }
  508. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  509. if !clientRemoteIP.IsValid() {
  510. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  511. r.Complete(true) // sends a RST
  512. return
  513. }
  514. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  515. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  516. defer func() {
  517. if !isTailscaleIP {
  518. // if this is a subnet IP, we added this in before the TCP handshake
  519. // so netstack is happy TCP-handshaking as a subnet IP
  520. ns.removeSubnetAddress(dialIP)
  521. }
  522. }()
  523. var wq waiter.Queue
  524. ep, err := r.CreateEndpoint(&wq)
  525. if err != nil {
  526. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  527. r.Complete(true) // sends a RST
  528. return
  529. }
  530. r.Complete(false)
  531. // The ForwarderRequest.CreateEndpoint above asynchronously
  532. // starts the TCP handshake. Note that the gonet.TCPConn
  533. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  534. // until the handshake actually completes. But we have the
  535. // remote address in reqDetails instead, so we don't use
  536. // gonet.TCPConn.RemoteAddr. The byte copies in both
  537. // directions to/from the gonet.TCPConn in forwardTCP will
  538. // block until the TCP handshake is complete.
  539. c := gonet.NewTCPConn(&wq, ep)
  540. if ns.ForwardTCPIn != nil {
  541. ns.ForwardTCPIn(c, reqDetails.LocalPort)
  542. return
  543. }
  544. if isTailscaleIP {
  545. dialIP = netaddr.IPv4(127, 0, 0, 1)
  546. }
  547. dialAddr := netaddr.IPPortFrom(dialIP, uint16(reqDetails.LocalPort))
  548. ns.forwardTCP(c, clientRemoteIP, &wq, dialAddr)
  549. }
  550. func (ns *Impl) forwardTCP(client *gonet.TCPConn, clientRemoteIP netaddr.IP, wq *waiter.Queue, dialAddr netaddr.IPPort) {
  551. defer client.Close()
  552. dialAddrStr := dialAddr.String()
  553. if debugNetstack {
  554. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  555. }
  556. ctx, cancel := context.WithCancel(context.Background())
  557. defer cancel()
  558. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  559. wq.EventRegister(&waitEntry)
  560. defer wq.EventUnregister(&waitEntry)
  561. done := make(chan bool)
  562. // netstack doesn't close the notification channel automatically if there was no
  563. // hup signal, so we close done after we're done to not leak the goroutine below.
  564. defer close(done)
  565. go func() {
  566. select {
  567. case <-notifyCh:
  568. if debugNetstack {
  569. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  570. }
  571. case <-done:
  572. }
  573. cancel()
  574. }()
  575. var stdDialer net.Dialer
  576. server, err := stdDialer.DialContext(ctx, "tcp", dialAddrStr)
  577. if err != nil {
  578. ns.logf("netstack: could not connect to local server at %s: %v", dialAddrStr, err)
  579. return
  580. }
  581. defer server.Close()
  582. backendLocalAddr := server.LocalAddr().(*net.TCPAddr)
  583. backendLocalIPPort, _ := netaddr.FromStdAddr(backendLocalAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  584. ns.e.RegisterIPPortIdentity(backendLocalIPPort, clientRemoteIP)
  585. defer ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  586. connClosed := make(chan error, 2)
  587. go func() {
  588. _, err := io.Copy(server, client)
  589. connClosed <- err
  590. }()
  591. go func() {
  592. _, err := io.Copy(client, server)
  593. connClosed <- err
  594. }()
  595. err = <-connClosed
  596. if err != nil {
  597. ns.logf("proxy connection closed with error: %v", err)
  598. }
  599. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  600. }
  601. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  602. sess := r.ID()
  603. if debugNetstack {
  604. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  605. }
  606. var wq waiter.Queue
  607. ep, err := r.CreateEndpoint(&wq)
  608. if err != nil {
  609. ns.logf("acceptUDP: could not create endpoint: %v", err)
  610. return
  611. }
  612. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  613. if !ok {
  614. return
  615. }
  616. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  617. if !ok {
  618. return
  619. }
  620. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  621. go ns.forwardUDP(c, &wq, srcAddr, dstAddr)
  622. }
  623. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  624. //
  625. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  626. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  627. // proxy to it directly.
  628. func (ns *Impl) forwardUDP(client *gonet.UDPConn, wq *waiter.Queue, clientAddr, dstAddr netaddr.IPPort) {
  629. port, srcPort := dstAddr.Port(), clientAddr.Port()
  630. if debugNetstack {
  631. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  632. }
  633. var backendListenAddr *net.UDPAddr
  634. var backendRemoteAddr *net.UDPAddr
  635. isLocal := ns.isLocalIP(dstAddr.IP())
  636. if isLocal {
  637. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  638. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  639. } else {
  640. backendRemoteAddr = dstAddr.UDPAddr()
  641. if dstAddr.IP().Is4() {
  642. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  643. } else {
  644. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  645. }
  646. }
  647. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  648. if err != nil {
  649. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  650. backendListenAddr.Port = 0
  651. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  652. if err != nil {
  653. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  654. return
  655. }
  656. }
  657. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  658. backendLocalIPPort, ok := netaddr.FromStdAddr(backendListenAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  659. if !ok {
  660. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  661. }
  662. if isLocal {
  663. ns.e.RegisterIPPortIdentity(backendLocalIPPort, dstAddr.IP())
  664. }
  665. ctx, cancel := context.WithCancel(context.Background())
  666. idleTimeout := 2 * time.Minute
  667. if port == 53 {
  668. // Make DNS packet copies time out much sooner.
  669. //
  670. // TODO(bradfitz): make DNS queries over UDP forwarding even
  671. // cheaper by adding an additional idleTimeout post-DNS-reply.
  672. // For instance, after the DNS response goes back out, then only
  673. // wait a few seconds (or zero, really)
  674. idleTimeout = 30 * time.Second
  675. }
  676. timer := time.AfterFunc(idleTimeout, func() {
  677. if isLocal {
  678. ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  679. }
  680. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  681. cancel()
  682. client.Close()
  683. backendConn.Close()
  684. })
  685. extend := func() {
  686. timer.Reset(idleTimeout)
  687. }
  688. startPacketCopy(ctx, cancel, client, clientAddr.UDPAddr(), backendConn, ns.logf, extend)
  689. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  690. if isLocal {
  691. // Wait for the copies to be done before decrementing the
  692. // subnet address count to potentially remove the route.
  693. <-ctx.Done()
  694. ns.removeSubnetAddress(dstAddr.IP())
  695. }
  696. }
  697. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  698. if debugNetstack {
  699. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  700. }
  701. go func() {
  702. defer cancel() // tear down the other direction's copy
  703. pkt := make([]byte, mtu)
  704. for {
  705. select {
  706. case <-ctx.Done():
  707. return
  708. default:
  709. n, srcAddr, err := src.ReadFrom(pkt)
  710. if err != nil {
  711. if ctx.Err() == nil {
  712. logf("read packet from %s failed: %v", srcAddr, err)
  713. }
  714. return
  715. }
  716. _, err = dst.WriteTo(pkt[:n], dstAddr)
  717. if err != nil {
  718. if ctx.Err() == nil {
  719. logf("write packet to %s failed: %v", dstAddr, err)
  720. }
  721. return
  722. }
  723. if debugNetstack {
  724. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  725. }
  726. extend()
  727. }
  728. }
  729. }()
  730. }
  731. func stringifyTEI(tei stack.TransportEndpointID) string {
  732. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  733. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  734. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  735. }
  736. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netaddr.IPPort, ok bool) {
  737. return netaddr.FromStdAddr(net.IP(a), int(port), "") // TODO(bradfitz): can do without allocs
  738. }