netstack.go 23 KB

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