netstack.go 27 KB

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