netstack.go 33 KB

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