netstack.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. var pn tcpip.NetworkProtocolNumber
  346. switch p.IPVersion {
  347. case 4:
  348. pn = header.IPv4ProtocolNumber
  349. case 6:
  350. pn = header.IPv6ProtocolNumber
  351. }
  352. if debugPackets {
  353. ns.logf("[v2] service packet in (from %v): % x", p.Src, p.Buffer())
  354. }
  355. vv := buffer.View(append([]byte(nil), p.Buffer()...)).ToVectorisedView()
  356. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  357. Data: vv,
  358. })
  359. ns.linkEP.InjectInbound(pn, packetBuf)
  360. packetBuf.DecRef()
  361. return filter.DropSilently
  362. }
  363. func (ns *Impl) DialContextTCP(ctx context.Context, ipp netaddr.IPPort) (*gonet.TCPConn, error) {
  364. remoteAddress := tcpip.FullAddress{
  365. NIC: nicID,
  366. Addr: tcpip.Address(ipp.IP().IPAddr().IP),
  367. Port: ipp.Port(),
  368. }
  369. var ipType tcpip.NetworkProtocolNumber
  370. if ipp.IP().Is4() {
  371. ipType = ipv4.ProtocolNumber
  372. } else {
  373. ipType = ipv6.ProtocolNumber
  374. }
  375. return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
  376. }
  377. func (ns *Impl) DialContextUDP(ctx context.Context, ipp netaddr.IPPort) (*gonet.UDPConn, error) {
  378. remoteAddress := &tcpip.FullAddress{
  379. NIC: nicID,
  380. Addr: tcpip.Address(ipp.IP().IPAddr().IP),
  381. Port: ipp.Port(),
  382. }
  383. var ipType tcpip.NetworkProtocolNumber
  384. if ipp.IP().Is4() {
  385. ipType = ipv4.ProtocolNumber
  386. } else {
  387. ipType = ipv6.ProtocolNumber
  388. }
  389. return gonet.DialUDP(ns.ipstack, nil, remoteAddress, ipType)
  390. }
  391. // The inject goroutine reads in packets that netstack generated, and delivers
  392. // them to the correct path.
  393. func (ns *Impl) inject() {
  394. for {
  395. pkt := ns.linkEP.ReadContext(ns.ctx)
  396. if pkt == nil {
  397. if ns.ctx.Err() != nil {
  398. // Return without logging.
  399. return
  400. }
  401. ns.logf("[v2] ReadContext-for-write = ok=false")
  402. continue
  403. }
  404. if debugPackets {
  405. ns.logf("[v2] packet Write out: % x", stack.PayloadSince(pkt.NetworkHeader()))
  406. }
  407. // In the normal case, netstack synthesizes the bytes for
  408. // traffic which should transit back into WG and go to peers.
  409. // However, some uses of netstack (presently, magic DNS)
  410. // send traffic destined for the local device, hence must
  411. // be injected 'inbound'.
  412. sendToHost := false
  413. // Determine if the packet is from a service IP, in which case it
  414. // needs to go back into the machines network (inbound) instead of
  415. // out.
  416. // TODO(tom): Work out a way to avoid parsing packets to determine if
  417. // its from the service IP. Maybe gvisor netstack magic. I
  418. // went through the fields of PacketBuffer, and nop :/
  419. // TODO(tom): Figure out if its safe to modify packet.Parsed to fill in
  420. // the IP src/dest even if its missing the rest of the pkt.
  421. // That way we dont have to do this twitchy-af byte-yeeting.
  422. if b := pkt.NetworkHeader().View(); len(b) >= 20 { // min ipv4 header
  423. switch b[0] >> 4 { // ip proto field
  424. case 4:
  425. if srcIP := netaddr.IPv4(b[12], b[13], b[14], b[15]); magicDNSIP == srcIP {
  426. sendToHost = true
  427. }
  428. case 6:
  429. if len(b) >= 40 { // min ipv6 header
  430. if srcIP, ok := netaddr.FromStdIP(net.IP(b[8:24])); ok && magicDNSIPv6 == srcIP {
  431. sendToHost = true
  432. }
  433. }
  434. }
  435. }
  436. // pkt has a non-zero refcount, so injection methods takes
  437. // ownership of one count and will decrement on completion.
  438. if sendToHost {
  439. if err := ns.tundev.InjectInboundPacketBuffer(pkt); err != nil {
  440. log.Printf("netstack inject inbound: %v", err)
  441. return
  442. }
  443. } else {
  444. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  445. log.Printf("netstack inject outbound: %v", err)
  446. return
  447. }
  448. }
  449. }
  450. }
  451. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  452. // node directly (but not a subnet-routed IP).
  453. func (ns *Impl) isLocalIP(ip netaddr.IP) bool {
  454. return ns.atomicIsLocalIPFunc.Load().(func(netaddr.IP) bool)(ip)
  455. }
  456. func (ns *Impl) processSSH() bool {
  457. return ns.lb != nil && ns.lb.ShouldRunSSH()
  458. }
  459. func (ns *Impl) peerAPIPortAtomic(ip netaddr.IP) *uint32 {
  460. if ip.Is4() {
  461. return &ns.peerapiPort4Atomic
  462. } else {
  463. return &ns.peerapiPort6Atomic
  464. }
  465. }
  466. var viaRange = tsaddr.TailscaleViaRange()
  467. // shouldProcessInbound reports whether an inbound packet (a packet from a
  468. // WireGuard peer) should be handled by netstack.
  469. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  470. // Handle incoming peerapi connections in netstack.
  471. if ns.lb != nil && p.IPProto == ipproto.TCP {
  472. var peerAPIPort uint16
  473. dstIP := p.Dst.IP()
  474. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn && ns.isLocalIP(dstIP) {
  475. if port, ok := ns.lb.GetPeerAPIPort(p.Dst.IP()); ok {
  476. peerAPIPort = port
  477. atomic.StoreUint32(ns.peerAPIPortAtomic(dstIP), uint32(port))
  478. }
  479. } else {
  480. peerAPIPort = uint16(atomic.LoadUint32(ns.peerAPIPortAtomic(dstIP)))
  481. }
  482. if p.IPProto == ipproto.TCP && p.Dst.Port() == peerAPIPort {
  483. return true
  484. }
  485. }
  486. if ns.isInboundTSSH(p) && ns.processSSH() {
  487. return true
  488. }
  489. if p.IPVersion == 6 && viaRange.Contains(p.Dst.IP()) {
  490. return ns.lb != nil && ns.lb.ShouldHandleViaIP(p.Dst.IP())
  491. }
  492. if !ns.ProcessLocalIPs && !ns.ProcessSubnets {
  493. // Fast path for common case (e.g. Linux server in TUN mode) where
  494. // netstack isn't used at all; don't even do an isLocalIP lookup.
  495. return false
  496. }
  497. isLocal := ns.isLocalIP(p.Dst.IP())
  498. if ns.ProcessLocalIPs && isLocal {
  499. return true
  500. }
  501. if ns.ProcessSubnets && !isLocal {
  502. return true
  503. }
  504. return false
  505. }
  506. // setAmbientCapsRaw is non-nil on Linux for Synology, to run ping with
  507. // CAP_NET_RAW from tailscaled's binary.
  508. var setAmbientCapsRaw func(*exec.Cmd)
  509. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  510. var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
  511. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  512. // into the tundev.
  513. //
  514. // It's used in userspace/netstack mode when we don't have kernel
  515. // support or raw socket access. As such, this does the dumbest thing
  516. // that can work: runs the ping command. It's not super efficient, so
  517. // it bounds the number of pings going on at once. The idea is that
  518. // people only use ping occasionally to see if their internet's working
  519. // so this doesn't need to be great.
  520. //
  521. // TODO(bradfitz): when we're running on Windows as the system user, use
  522. // raw socket APIs instead of ping child processes.
  523. func (ns *Impl) userPing(dstIP netaddr.IP, pingResPkt []byte) {
  524. if !userPingSem.TryAcquire() {
  525. return
  526. }
  527. defer userPingSem.Release()
  528. t0 := time.Now()
  529. var err error
  530. switch runtime.GOOS {
  531. case "windows":
  532. err = exec.Command("ping", "-n", "1", "-w", "3000", dstIP.String()).Run()
  533. case "darwin":
  534. // Note: 2000 ms is actually 1 second + 2,000
  535. // milliseconds extra for 3 seconds total.
  536. // See https://github.com/tailscale/tailscale/pull/3753 for details.
  537. err = exec.Command("ping", "-c", "1", "-W", "2000", dstIP.String()).Run()
  538. case "android":
  539. ping := "/system/bin/ping"
  540. if dstIP.Is6() {
  541. ping = "/system/bin/ping6"
  542. }
  543. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  544. default:
  545. ping := "ping"
  546. if isSynology {
  547. ping = "/bin/ping"
  548. }
  549. cmd := exec.Command(ping, "-c", "1", "-W", "3", dstIP.String())
  550. if isSynology && os.Getuid() != 0 {
  551. // On DSM7 we run as non-root and need to pass
  552. // CAP_NET_RAW if our binary has it.
  553. setAmbientCapsRaw(cmd)
  554. }
  555. err = cmd.Run()
  556. }
  557. d := time.Since(t0)
  558. if err != nil {
  559. if d < time.Second/2 {
  560. // If it failed quicker than the 3 second
  561. // timeout we gave above (500 ms is a
  562. // reasonable threshold), then assume the ping
  563. // failed for problems finding/running
  564. // ping. We don't want to log if the host is
  565. // just down.
  566. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  567. }
  568. return
  569. }
  570. if debugNetstack {
  571. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  572. }
  573. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  574. ns.logf("InjectOutbound ping response: %v", err)
  575. }
  576. }
  577. func (ns *Impl) isInboundTSSH(p *packet.Parsed) bool {
  578. return p.IPProto == ipproto.TCP &&
  579. p.Dst.Port() == 22 &&
  580. ns.isLocalIP(p.Dst.IP())
  581. }
  582. // injectInbound is installed as a packet hook on the 'inbound' (from a
  583. // WireGuard peer) path. Returning filter.Accept releases the packet to
  584. // continue normally (typically being delivered to the host networking stack),
  585. // whereas returning filter.DropSilently is done when netstack intercepts the
  586. // packet and no further processing towards to host should be done.
  587. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  588. if !ns.shouldProcessInbound(p, t) {
  589. // Let the host network stack (if any) deal with it.
  590. return filter.Accept
  591. }
  592. destIP := p.Dst.IP()
  593. if p.IsEchoRequest() && ns.ProcessSubnets && !tsaddr.IsTailscaleIP(destIP) {
  594. var pong []byte // the reply to the ping, if our relayed ping works
  595. if destIP.Is4() {
  596. h := p.ICMP4Header()
  597. h.ToResponse()
  598. pong = packet.Generate(&h, p.Payload())
  599. } else if destIP.Is6() {
  600. h := p.ICMP6Header()
  601. h.ToResponse()
  602. pong = packet.Generate(&h, p.Payload())
  603. }
  604. go ns.userPing(destIP, pong)
  605. return filter.DropSilently
  606. }
  607. var pn tcpip.NetworkProtocolNumber
  608. switch p.IPVersion {
  609. case 4:
  610. pn = header.IPv4ProtocolNumber
  611. case 6:
  612. pn = header.IPv6ProtocolNumber
  613. }
  614. if debugPackets {
  615. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  616. }
  617. vv := buffer.View(append([]byte(nil), p.Buffer()...)).ToVectorisedView()
  618. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  619. Data: vv,
  620. })
  621. ns.linkEP.InjectInbound(pn, packetBuf)
  622. packetBuf.DecRef()
  623. // We've now delivered this to netstack, so we're done.
  624. // Instead of returning a filter.Accept here (which would also
  625. // potentially deliver it to the host OS), and instead of
  626. // filter.Drop (which would log about rejected traffic),
  627. // instead return filter.DropSilently which just quietly stops
  628. // processing it in the tstun TUN wrapper.
  629. return filter.DropSilently
  630. }
  631. func netaddrIPFromNetstackIP(s tcpip.Address) netaddr.IP {
  632. switch len(s) {
  633. case 4:
  634. return netaddr.IPv4(s[0], s[1], s[2], s[3])
  635. case 16:
  636. var a [16]byte
  637. copy(a[:], s)
  638. return netaddr.IPFrom16(a)
  639. }
  640. return netaddr.IP{}
  641. }
  642. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  643. reqDetails := r.ID()
  644. if debugNetstack {
  645. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  646. }
  647. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  648. if !clientRemoteIP.IsValid() {
  649. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  650. r.Complete(true) // sends a RST
  651. return
  652. }
  653. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  654. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  655. if viaRange.Contains(dialIP) {
  656. isTailscaleIP = false
  657. dialIP = tsaddr.UnmapVia(dialIP)
  658. }
  659. defer func() {
  660. if !isTailscaleIP {
  661. // if this is a subnet IP, we added this in before the TCP handshake
  662. // so netstack is happy TCP-handshaking as a subnet IP
  663. ns.removeSubnetAddress(dialIP)
  664. }
  665. }()
  666. var wq waiter.Queue
  667. ep, err := r.CreateEndpoint(&wq)
  668. if err != nil {
  669. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  670. r.Complete(true) // sends a RST
  671. return
  672. }
  673. r.Complete(false)
  674. // SetKeepAlive so that idle connections to peers that have forgotten about
  675. // the connection or gone completely offline eventually time out.
  676. // Applications might be setting this on a forwarded connection, but from
  677. // userspace we can not see those, so the best we can do is to always
  678. // perform them with conservative timing.
  679. // TODO(tailscale/tailscale#4522): Netstack defaults match the Linux
  680. // defaults, and results in a little over two hours before the socket would
  681. // be closed due to keepalive. A shorter default might be better, or seeking
  682. // a default from the host IP stack. This also might be a useful
  683. // user-tunable, as in userspace mode this can have broad implications such
  684. // as lingering connections to fork style daemons. On the other side of the
  685. // fence, the long duration timers are low impact values for battery powered
  686. // peers.
  687. ep.SocketOptions().SetKeepAlive(true)
  688. // The ForwarderRequest.CreateEndpoint above asynchronously
  689. // starts the TCP handshake. Note that the gonet.TCPConn
  690. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  691. // until the handshake actually completes. But we have the
  692. // remote address in reqDetails instead, so we don't use
  693. // gonet.TCPConn.RemoteAddr. The byte copies in both
  694. // directions to/from the gonet.TCPConn in forwardTCP will
  695. // block until the TCP handshake is complete.
  696. c := gonet.NewTCPConn(&wq, ep)
  697. if ns.lb != nil {
  698. if reqDetails.LocalPort == 22 && ns.processSSH() && ns.isLocalIP(dialIP) {
  699. if err := ns.lb.HandleSSHConn(c); err != nil {
  700. ns.logf("ssh error: %v", err)
  701. }
  702. return
  703. }
  704. if port, ok := ns.lb.GetPeerAPIPort(dialIP); ok {
  705. if reqDetails.LocalPort == port && ns.isLocalIP(dialIP) {
  706. src := netaddr.IPPortFrom(clientRemoteIP, reqDetails.RemotePort)
  707. dst := netaddr.IPPortFrom(dialIP, port)
  708. ns.lb.ServePeerAPIConnection(src, dst, c)
  709. return
  710. }
  711. }
  712. }
  713. if ns.ForwardTCPIn != nil {
  714. ns.ForwardTCPIn(c, reqDetails.LocalPort)
  715. return
  716. }
  717. if isTailscaleIP {
  718. dialIP = netaddr.IPv4(127, 0, 0, 1)
  719. }
  720. dialAddr := netaddr.IPPortFrom(dialIP, uint16(reqDetails.LocalPort))
  721. ns.forwardTCP(c, clientRemoteIP, &wq, dialAddr)
  722. }
  723. func (ns *Impl) forwardTCP(client *gonet.TCPConn, clientRemoteIP netaddr.IP, wq *waiter.Queue, dialAddr netaddr.IPPort) {
  724. defer client.Close()
  725. dialAddrStr := dialAddr.String()
  726. if debugNetstack {
  727. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  728. }
  729. ctx, cancel := context.WithCancel(context.Background())
  730. defer cancel()
  731. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  732. wq.EventRegister(&waitEntry)
  733. defer wq.EventUnregister(&waitEntry)
  734. done := make(chan bool)
  735. // netstack doesn't close the notification channel automatically if there was no
  736. // hup signal, so we close done after we're done to not leak the goroutine below.
  737. defer close(done)
  738. go func() {
  739. select {
  740. case <-notifyCh:
  741. if debugNetstack {
  742. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  743. }
  744. case <-done:
  745. }
  746. cancel()
  747. }()
  748. var stdDialer net.Dialer
  749. server, err := stdDialer.DialContext(ctx, "tcp", dialAddrStr)
  750. if err != nil {
  751. ns.logf("netstack: could not connect to local server at %s: %v", dialAddrStr, err)
  752. return
  753. }
  754. defer server.Close()
  755. backendLocalAddr := server.LocalAddr().(*net.TCPAddr)
  756. backendLocalIPPort, _ := netaddr.FromStdAddr(backendLocalAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  757. ns.e.RegisterIPPortIdentity(backendLocalIPPort, clientRemoteIP)
  758. defer ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  759. connClosed := make(chan error, 2)
  760. go func() {
  761. _, err := io.Copy(server, client)
  762. connClosed <- err
  763. }()
  764. go func() {
  765. _, err := io.Copy(client, server)
  766. connClosed <- err
  767. }()
  768. err = <-connClosed
  769. if err != nil {
  770. ns.logf("proxy connection closed with error: %v", err)
  771. }
  772. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  773. }
  774. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  775. sess := r.ID()
  776. if debugNetstack {
  777. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  778. }
  779. var wq waiter.Queue
  780. ep, err := r.CreateEndpoint(&wq)
  781. if err != nil {
  782. ns.logf("acceptUDP: could not create endpoint: %v", err)
  783. return
  784. }
  785. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  786. if !ok {
  787. return
  788. }
  789. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  790. if !ok {
  791. return
  792. }
  793. // Handle magicDNS traffic (via UDP) here.
  794. if dst := dstAddr.IP(); dst == magicDNSIP || dst == magicDNSIPv6 {
  795. if dstAddr.Port() != 53 {
  796. return // Only MagicDNS traffic runs on the service IPs for now.
  797. }
  798. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  799. go ns.handleMagicDNSUDP(srcAddr, c)
  800. return
  801. }
  802. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  803. go ns.forwardUDP(c, &wq, srcAddr, dstAddr)
  804. }
  805. func (ns *Impl) handleMagicDNSUDP(srcAddr netaddr.IPPort, c *gonet.UDPConn) {
  806. // In practice, implementations are advised not to exceed 512 bytes
  807. // due to fragmenting. Just to be sure, we bump all the way to the MTU.
  808. const maxUDPReqSize = mtu
  809. defer c.Close()
  810. q := make([]byte, maxUDPReqSize)
  811. n, err := c.Read(q)
  812. if err != nil {
  813. ns.logf("dns udp read: %v", err)
  814. return
  815. }
  816. resp, err := ns.dns.Query(context.Background(), q[:n], srcAddr)
  817. if err != nil {
  818. ns.logf("dns udp query: %v", err)
  819. return
  820. }
  821. c.Write(resp)
  822. }
  823. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  824. //
  825. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  826. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  827. // proxy to it directly.
  828. func (ns *Impl) forwardUDP(client *gonet.UDPConn, wq *waiter.Queue, clientAddr, dstAddr netaddr.IPPort) {
  829. port, srcPort := dstAddr.Port(), clientAddr.Port()
  830. if debugNetstack {
  831. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  832. }
  833. var backendListenAddr *net.UDPAddr
  834. var backendRemoteAddr *net.UDPAddr
  835. isLocal := ns.isLocalIP(dstAddr.IP())
  836. if isLocal {
  837. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  838. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  839. } else {
  840. if dstIP := dstAddr.IP(); viaRange.Contains(dstIP) {
  841. dstAddr = netaddr.IPPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
  842. }
  843. backendRemoteAddr = dstAddr.UDPAddr()
  844. if dstAddr.IP().Is4() {
  845. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  846. } else {
  847. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  848. }
  849. }
  850. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  851. if err != nil {
  852. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  853. backendListenAddr.Port = 0
  854. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  855. if err != nil {
  856. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  857. return
  858. }
  859. }
  860. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  861. backendLocalIPPort, ok := netaddr.FromStdAddr(backendListenAddr.IP, backendLocalAddr.Port, backendLocalAddr.Zone)
  862. if !ok {
  863. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  864. }
  865. if isLocal {
  866. ns.e.RegisterIPPortIdentity(backendLocalIPPort, dstAddr.IP())
  867. }
  868. ctx, cancel := context.WithCancel(context.Background())
  869. idleTimeout := 2 * time.Minute
  870. if port == 53 {
  871. // Make DNS packet copies time out much sooner.
  872. //
  873. // TODO(bradfitz): make DNS queries over UDP forwarding even
  874. // cheaper by adding an additional idleTimeout post-DNS-reply.
  875. // For instance, after the DNS response goes back out, then only
  876. // wait a few seconds (or zero, really)
  877. idleTimeout = 30 * time.Second
  878. }
  879. timer := time.AfterFunc(idleTimeout, func() {
  880. if isLocal {
  881. ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
  882. }
  883. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  884. cancel()
  885. client.Close()
  886. backendConn.Close()
  887. })
  888. extend := func() {
  889. timer.Reset(idleTimeout)
  890. }
  891. startPacketCopy(ctx, cancel, client, clientAddr.UDPAddr(), backendConn, ns.logf, extend)
  892. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  893. if isLocal {
  894. // Wait for the copies to be done before decrementing the
  895. // subnet address count to potentially remove the route.
  896. <-ctx.Done()
  897. ns.removeSubnetAddress(dstAddr.IP())
  898. }
  899. }
  900. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  901. if debugNetstack {
  902. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  903. }
  904. go func() {
  905. defer cancel() // tear down the other direction's copy
  906. pkt := make([]byte, mtu)
  907. for {
  908. select {
  909. case <-ctx.Done():
  910. return
  911. default:
  912. n, srcAddr, err := src.ReadFrom(pkt)
  913. if err != nil {
  914. if ctx.Err() == nil {
  915. logf("read packet from %s failed: %v", srcAddr, err)
  916. }
  917. return
  918. }
  919. _, err = dst.WriteTo(pkt[:n], dstAddr)
  920. if err != nil {
  921. if ctx.Err() == nil {
  922. logf("write packet to %s failed: %v", dstAddr, err)
  923. }
  924. return
  925. }
  926. if debugNetstack {
  927. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  928. }
  929. extend()
  930. }
  931. }
  932. }()
  933. }
  934. func stringifyTEI(tei stack.TransportEndpointID) string {
  935. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  936. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  937. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  938. }
  939. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netaddr.IPPort, ok bool) {
  940. return netaddr.FromStdAddr(net.IP(a), int(port), "") // TODO(bradfitz): can do without allocs
  941. }