netstack.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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. // handleSSH 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 handleSSH func(logger.Logf, *ipnlocal.LocalBackend, 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. if debugPackets {
  353. ns.logf("[v2] packet Write out: % x", stack.PayloadSince(pkt.NetworkHeader()))
  354. }
  355. // pkt has a non-zero refcount, InjectOutboundPacketBuffer takes
  356. // ownership of one count and will decrement on completion.
  357. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  358. log.Printf("netstack inject outbound: %v", err)
  359. return
  360. }
  361. }
  362. }
  363. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  364. // node directly (but not a subnet-routed IP).
  365. func (ns *Impl) isLocalIP(ip netaddr.IP) bool {
  366. return ns.atomicIsLocalIPFunc.Load().(func(netaddr.IP) bool)(ip)
  367. }
  368. func (ns *Impl) processSSH() bool {
  369. return ns.lb != nil && ns.lb.ShouldRunSSH()
  370. }
  371. func (ns *Impl) peerAPIPortAtomic(ip netaddr.IP) *uint32 {
  372. if ip.Is4() {
  373. return &ns.peerapiPort4Atomic
  374. } else {
  375. return &ns.peerapiPort6Atomic
  376. }
  377. }
  378. // shouldProcessInbound reports whether an inbound packet should be
  379. // handled by netstack.
  380. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  381. // Handle incoming peerapi connections in netstack.
  382. if ns.lb != nil && p.IPProto == ipproto.TCP {
  383. var peerAPIPort uint16
  384. dstIP := p.Dst.IP()
  385. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn && ns.isLocalIP(dstIP) {
  386. if port, ok := ns.lb.GetPeerAPIPort(p.Dst.IP()); ok {
  387. peerAPIPort = port
  388. atomic.StoreUint32(ns.peerAPIPortAtomic(dstIP), uint32(port))
  389. }
  390. } else {
  391. peerAPIPort = uint16(atomic.LoadUint32(ns.peerAPIPortAtomic(dstIP)))
  392. }
  393. if p.IPProto == ipproto.TCP && p.Dst.Port() == peerAPIPort {
  394. return true
  395. }
  396. }
  397. if ns.isInboundTSSH(p) && ns.processSSH() {
  398. return true
  399. }
  400. if !ns.ProcessLocalIPs && !ns.ProcessSubnets {
  401. // Fast path for common case (e.g. Linux server in TUN mode) where
  402. // netstack isn't used at all; don't even do an isLocalIP lookup.
  403. return false
  404. }
  405. isLocal := ns.isLocalIP(p.Dst.IP())
  406. if ns.ProcessLocalIPs && isLocal {
  407. return true
  408. }
  409. if ns.ProcessSubnets && !isLocal {
  410. return true
  411. }
  412. return false
  413. }
  414. // setAmbientCapsRaw is non-nil on Linux for Synology, to run ping with
  415. // CAP_NET_RAW from tailscaled's binary.
  416. var setAmbientCapsRaw func(*exec.Cmd)
  417. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  418. var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
  419. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  420. // into the tundev.
  421. //
  422. // It's used in userspace/netstack mode when we don't have kernel
  423. // support or raw socket access. As such, this does the dumbest thing
  424. // that can work: runs the ping command. It's not super efficient, so
  425. // it bounds the number of pings going on at once. The idea is that
  426. // people only use ping occasionally to see if their internet's working
  427. // so this doesn't need to be great.
  428. //
  429. // TODO(bradfitz): when we're running on Windows as the system user, use
  430. // raw socket APIs instead of ping child processes.
  431. func (ns *Impl) userPing(dstIP netaddr.IP, pingResPkt []byte) {
  432. if !userPingSem.TryAcquire() {
  433. return
  434. }
  435. defer userPingSem.Release()
  436. t0 := time.Now()
  437. var err error
  438. switch runtime.GOOS {
  439. case "windows":
  440. err = exec.Command("ping", "-n", "1", "-w", "3000", dstIP.String()).Run()
  441. case "darwin":
  442. // Note: 2000 ms is actually 1 second + 2,000
  443. // milliseconds extra for 3 seconds total.
  444. // See https://github.com/tailscale/tailscale/pull/3753 for details.
  445. err = exec.Command("ping", "-c", "1", "-W", "2000", dstIP.String()).Run()
  446. case "android":
  447. ping := "/system/bin/ping"
  448. if dstIP.Is6() {
  449. ping = "/system/bin/ping6"
  450. }
  451. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  452. default:
  453. ping := "ping"
  454. if isSynology {
  455. ping = "/bin/ping"
  456. }
  457. cmd := exec.Command(ping, "-c", "1", "-W", "3", dstIP.String())
  458. if isSynology && os.Getuid() != 0 {
  459. // On DSM7 we run as non-root and need to pass
  460. // CAP_NET_RAW if our binary has it.
  461. setAmbientCapsRaw(cmd)
  462. }
  463. err = cmd.Run()
  464. }
  465. d := time.Since(t0)
  466. if err != nil {
  467. if d < time.Second/2 {
  468. // If it failed quicker than the 3 second
  469. // timeout we gave above (500 ms is a
  470. // reasonable threshold), then assume the ping
  471. // failed for problems finding/running
  472. // ping. We don't want to log if the host is
  473. // just down.
  474. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  475. }
  476. return
  477. }
  478. if debugNetstack {
  479. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  480. }
  481. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  482. ns.logf("InjectOutbound ping response: %v", err)
  483. }
  484. }
  485. func (ns *Impl) isInboundTSSH(p *packet.Parsed) bool {
  486. return p.IPProto == ipproto.TCP &&
  487. p.Dst.Port() == 22 &&
  488. ns.isLocalIP(p.Dst.IP())
  489. }
  490. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  491. if !ns.shouldProcessInbound(p, t) {
  492. // Let the host network stack (if any) deal with it.
  493. return filter.Accept
  494. }
  495. destIP := p.Dst.IP()
  496. if p.IsEchoRequest() && ns.ProcessSubnets && !tsaddr.IsTailscaleIP(destIP) {
  497. var pong []byte // the reply to the ping, if our relayed ping works
  498. if destIP.Is4() {
  499. h := p.ICMP4Header()
  500. h.ToResponse()
  501. pong = packet.Generate(&h, p.Payload())
  502. } else if destIP.Is6() {
  503. h := p.ICMP6Header()
  504. h.ToResponse()
  505. pong = packet.Generate(&h, p.Payload())
  506. }
  507. go ns.userPing(destIP, pong)
  508. return filter.DropSilently
  509. }
  510. var pn tcpip.NetworkProtocolNumber
  511. switch p.IPVersion {
  512. case 4:
  513. pn = header.IPv4ProtocolNumber
  514. case 6:
  515. pn = header.IPv6ProtocolNumber
  516. }
  517. p.RemoveECNBits() // Issue 2642
  518. if debugPackets {
  519. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  520. }
  521. vv := buffer.View(append([]byte(nil), p.Buffer()...)).ToVectorisedView()
  522. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  523. Data: vv,
  524. })
  525. ns.linkEP.InjectInbound(pn, packetBuf)
  526. packetBuf.DecRef()
  527. // We've now delivered this to netstack, so we're done.
  528. // Instead of returning a filter.Accept here (which would also
  529. // potentially deliver it to the host OS), and instead of
  530. // filter.Drop (which would log about rejected traffic),
  531. // instead return filter.DropSilently which just quietly stops
  532. // processing it in the tstun TUN wrapper.
  533. return filter.DropSilently
  534. }
  535. func netaddrIPFromNetstackIP(s tcpip.Address) netaddr.IP {
  536. switch len(s) {
  537. case 4:
  538. return netaddr.IPv4(s[0], s[1], s[2], s[3])
  539. case 16:
  540. var a [16]byte
  541. copy(a[:], s)
  542. return netaddr.IPFrom16(a)
  543. }
  544. return netaddr.IP{}
  545. }
  546. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  547. reqDetails := r.ID()
  548. if debugNetstack {
  549. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  550. }
  551. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  552. if !clientRemoteIP.IsValid() {
  553. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  554. r.Complete(true) // sends a RST
  555. return
  556. }
  557. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  558. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  559. defer func() {
  560. if !isTailscaleIP {
  561. // if this is a subnet IP, we added this in before the TCP handshake
  562. // so netstack is happy TCP-handshaking as a subnet IP
  563. ns.removeSubnetAddress(dialIP)
  564. }
  565. }()
  566. var wq waiter.Queue
  567. ep, err := r.CreateEndpoint(&wq)
  568. if err != nil {
  569. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  570. r.Complete(true) // sends a RST
  571. return
  572. }
  573. r.Complete(false)
  574. // The ForwarderRequest.CreateEndpoint above asynchronously
  575. // starts the TCP handshake. Note that the gonet.TCPConn
  576. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  577. // until the handshake actually completes. But we have the
  578. // remote address in reqDetails instead, so we don't use
  579. // gonet.TCPConn.RemoteAddr. The byte copies in both
  580. // directions to/from the gonet.TCPConn in forwardTCP will
  581. // block until the TCP handshake is complete.
  582. c := gonet.NewTCPConn(&wq, ep)
  583. if ns.lb != nil {
  584. if reqDetails.LocalPort == 22 && ns.processSSH() && ns.isLocalIP(dialIP) && handleSSH != nil {
  585. ns.logf("handling SSH connection....")
  586. if err := handleSSH(ns.logf, ns.lb, c); err != nil {
  587. ns.logf("ssh error: %v", err)
  588. } else {
  589. ns.logf("ssh: ok")
  590. }
  591. return
  592. }
  593. if port, ok := ns.lb.GetPeerAPIPort(dialIP); ok {
  594. if reqDetails.LocalPort == port && ns.isLocalIP(dialIP) {
  595. src := netaddr.IPPortFrom(clientRemoteIP, reqDetails.RemotePort)
  596. dst := netaddr.IPPortFrom(dialIP, port)
  597. ns.lb.ServePeerAPIConnection(src, dst, c)
  598. return
  599. }
  600. }
  601. }
  602. if ns.ForwardTCPIn != nil {
  603. ns.ForwardTCPIn(c, reqDetails.LocalPort)
  604. return
  605. }
  606. if isTailscaleIP {
  607. dialIP = netaddr.IPv4(127, 0, 0, 1)
  608. }
  609. dialAddr := netaddr.IPPortFrom(dialIP, uint16(reqDetails.LocalPort))
  610. ns.forwardTCP(c, clientRemoteIP, &wq, dialAddr)
  611. }
  612. func (ns *Impl) forwardTCP(client *gonet.TCPConn, clientRemoteIP netaddr.IP, wq *waiter.Queue, dialAddr netaddr.IPPort) {
  613. defer client.Close()
  614. dialAddrStr := dialAddr.String()
  615. if debugNetstack {
  616. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  617. }
  618. ctx, cancel := context.WithCancel(context.Background())
  619. defer cancel()
  620. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  621. wq.EventRegister(&waitEntry)
  622. defer wq.EventUnregister(&waitEntry)
  623. done := make(chan bool)
  624. // netstack doesn't close the notification channel automatically if there was no
  625. // hup signal, so we close done after we're done to not leak the goroutine below.
  626. defer close(done)
  627. go func() {
  628. select {
  629. case <-notifyCh:
  630. if debugNetstack {
  631. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  632. }
  633. case <-done:
  634. }
  635. cancel()
  636. }()
  637. var stdDialer net.Dialer
  638. server, err := stdDialer.DialContext(ctx, "tcp", dialAddrStr)
  639. if err != nil {
  640. ns.logf("netstack: could not connect to local server at %s: %v", dialAddrStr, err)
  641. return
  642. }
  643. defer server.Close()
  644. backendLocalAddr := server.LocalAddr().(*net.TCPAddr)
  645. backendLocalIPPort, _ := netaddr.FromStdAddr(backendLocalAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  646. ns.e.RegisterIPPortIdentity(backendLocalIPPort, clientRemoteIP)
  647. defer ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  648. connClosed := make(chan error, 2)
  649. go func() {
  650. _, err := io.Copy(server, client)
  651. connClosed <- err
  652. }()
  653. go func() {
  654. _, err := io.Copy(client, server)
  655. connClosed <- err
  656. }()
  657. err = <-connClosed
  658. if err != nil {
  659. ns.logf("proxy connection closed with error: %v", err)
  660. }
  661. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  662. }
  663. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  664. sess := r.ID()
  665. if debugNetstack {
  666. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  667. }
  668. var wq waiter.Queue
  669. ep, err := r.CreateEndpoint(&wq)
  670. if err != nil {
  671. ns.logf("acceptUDP: could not create endpoint: %v", err)
  672. return
  673. }
  674. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  675. if !ok {
  676. return
  677. }
  678. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  679. if !ok {
  680. return
  681. }
  682. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  683. go ns.forwardUDP(c, &wq, srcAddr, dstAddr)
  684. }
  685. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  686. //
  687. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  688. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  689. // proxy to it directly.
  690. func (ns *Impl) forwardUDP(client *gonet.UDPConn, wq *waiter.Queue, clientAddr, dstAddr netaddr.IPPort) {
  691. port, srcPort := dstAddr.Port(), clientAddr.Port()
  692. if debugNetstack {
  693. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  694. }
  695. var backendListenAddr *net.UDPAddr
  696. var backendRemoteAddr *net.UDPAddr
  697. isLocal := ns.isLocalIP(dstAddr.IP())
  698. if isLocal {
  699. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  700. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  701. } else {
  702. backendRemoteAddr = dstAddr.UDPAddr()
  703. if dstAddr.IP().Is4() {
  704. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  705. } else {
  706. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  707. }
  708. }
  709. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  710. if err != nil {
  711. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  712. backendListenAddr.Port = 0
  713. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  714. if err != nil {
  715. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  716. return
  717. }
  718. }
  719. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  720. backendLocalIPPort, ok := netaddr.FromStdAddr(backendListenAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  721. if !ok {
  722. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  723. }
  724. if isLocal {
  725. ns.e.RegisterIPPortIdentity(backendLocalIPPort, dstAddr.IP())
  726. }
  727. ctx, cancel := context.WithCancel(context.Background())
  728. idleTimeout := 2 * time.Minute
  729. if port == 53 {
  730. // Make DNS packet copies time out much sooner.
  731. //
  732. // TODO(bradfitz): make DNS queries over UDP forwarding even
  733. // cheaper by adding an additional idleTimeout post-DNS-reply.
  734. // For instance, after the DNS response goes back out, then only
  735. // wait a few seconds (or zero, really)
  736. idleTimeout = 30 * time.Second
  737. }
  738. timer := time.AfterFunc(idleTimeout, func() {
  739. if isLocal {
  740. ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  741. }
  742. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  743. cancel()
  744. client.Close()
  745. backendConn.Close()
  746. })
  747. extend := func() {
  748. timer.Reset(idleTimeout)
  749. }
  750. startPacketCopy(ctx, cancel, client, clientAddr.UDPAddr(), backendConn, ns.logf, extend)
  751. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  752. if isLocal {
  753. // Wait for the copies to be done before decrementing the
  754. // subnet address count to potentially remove the route.
  755. <-ctx.Done()
  756. ns.removeSubnetAddress(dstAddr.IP())
  757. }
  758. }
  759. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  760. if debugNetstack {
  761. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  762. }
  763. go func() {
  764. defer cancel() // tear down the other direction's copy
  765. pkt := make([]byte, mtu)
  766. for {
  767. select {
  768. case <-ctx.Done():
  769. return
  770. default:
  771. n, srcAddr, err := src.ReadFrom(pkt)
  772. if err != nil {
  773. if ctx.Err() == nil {
  774. logf("read packet from %s failed: %v", srcAddr, err)
  775. }
  776. return
  777. }
  778. _, err = dst.WriteTo(pkt[:n], dstAddr)
  779. if err != nil {
  780. if ctx.Err() == nil {
  781. logf("write packet to %s failed: %v", dstAddr, err)
  782. }
  783. return
  784. }
  785. if debugNetstack {
  786. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  787. }
  788. extend()
  789. }
  790. }
  791. }()
  792. }
  793. func stringifyTEI(tei stack.TransportEndpointID) string {
  794. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  795. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  796. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  797. }
  798. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netaddr.IPPort, ok bool) {
  799. return netaddr.FromStdAddr(net.IP(a), int(port), "") // TODO(bradfitz): can do without allocs
  800. }