netstack.go 28 KB

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