netstack.go 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package netstack wires up gVisor's netstack into Tailscale.
  4. package netstack
  5. import (
  6. "bytes"
  7. "context"
  8. "errors"
  9. "expvar"
  10. "fmt"
  11. "io"
  12. "log"
  13. "math"
  14. "net"
  15. "net/netip"
  16. "os"
  17. "os/exec"
  18. "runtime"
  19. "strconv"
  20. "sync"
  21. "sync/atomic"
  22. "time"
  23. "gvisor.dev/gvisor/pkg/buffer"
  24. "gvisor.dev/gvisor/pkg/refs"
  25. "gvisor.dev/gvisor/pkg/tcpip"
  26. "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
  27. "gvisor.dev/gvisor/pkg/tcpip/header"
  28. "gvisor.dev/gvisor/pkg/tcpip/link/channel"
  29. "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
  30. "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
  31. "gvisor.dev/gvisor/pkg/tcpip/stack"
  32. "gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
  33. "gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
  34. "gvisor.dev/gvisor/pkg/tcpip/transport/udp"
  35. "gvisor.dev/gvisor/pkg/waiter"
  36. "tailscale.com/envknob"
  37. "tailscale.com/ipn/ipnlocal"
  38. "tailscale.com/metrics"
  39. "tailscale.com/net/dns"
  40. "tailscale.com/net/netaddr"
  41. "tailscale.com/net/packet"
  42. "tailscale.com/net/tsaddr"
  43. "tailscale.com/net/tsdial"
  44. "tailscale.com/net/tstun"
  45. "tailscale.com/proxymap"
  46. "tailscale.com/syncs"
  47. "tailscale.com/tailcfg"
  48. "tailscale.com/types/ipproto"
  49. "tailscale.com/types/logger"
  50. "tailscale.com/types/netmap"
  51. "tailscale.com/types/nettype"
  52. "tailscale.com/version/distro"
  53. "tailscale.com/wgengine"
  54. "tailscale.com/wgengine/filter"
  55. "tailscale.com/wgengine/magicsock"
  56. )
  57. const debugPackets = false
  58. var debugNetstack = envknob.RegisterBool("TS_DEBUG_NETSTACK")
  59. var (
  60. magicDNSIP = tsaddr.TailscaleServiceIP()
  61. magicDNSIPv6 = tsaddr.TailscaleServiceIPv6()
  62. )
  63. func init() {
  64. mode := envknob.String("TS_DEBUG_NETSTACK_LEAK_MODE")
  65. if mode == "" {
  66. return
  67. }
  68. var lm refs.LeakMode
  69. if err := lm.Set(mode); err != nil {
  70. panic(err)
  71. }
  72. refs.SetLeakMode(lm)
  73. }
  74. // Impl contains the state for the netstack implementation,
  75. // and implements wgengine.FakeImpl to act as a userspace network
  76. // stack when Tailscale is running in fake mode.
  77. type Impl struct {
  78. // GetTCPHandlerForFlow conditionally handles an incoming TCP flow for the
  79. // provided (src/port, dst/port) 4-tuple.
  80. //
  81. // A nil value is equivalent to a func returning (nil, false).
  82. //
  83. // If func returns intercept=false, the default forwarding behavior (if
  84. // ProcessLocalIPs and/or ProcesssSubnetIPs) takes place.
  85. //
  86. // When intercept=true, the behavior depends on whether the returned handler
  87. // is non-nil: if nil, the connection is rejected. If non-nil, handler takes
  88. // over the TCP conn.
  89. GetTCPHandlerForFlow func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool)
  90. // GetUDPHandlerForFlow conditionally handles an incoming UDP flow for the
  91. // provided (src/port, dst/port) 4-tuple.
  92. //
  93. // A nil value is equivalent to a func returning (nil, false).
  94. //
  95. // If func returns intercept=false, the default forwarding behavior (if
  96. // ProcessLocalIPs and/or ProcesssSubnetIPs) takes place.
  97. //
  98. // When intercept=true, the behavior depends on whether the returned handler
  99. // is non-nil: if nil, the connection is rejected. If non-nil, handler takes
  100. // over the UDP flow.
  101. GetUDPHandlerForFlow func(src, dst netip.AddrPort) (handler func(nettype.ConnPacketConn), intercept bool)
  102. // ProcessLocalIPs is whether netstack should handle incoming
  103. // traffic directed at the Node.Addresses (local IPs).
  104. // It can only be set before calling Start.
  105. ProcessLocalIPs bool
  106. // ProcessSubnets is whether netstack should handle incoming
  107. // traffic destined to non-local IPs (i.e. whether it should
  108. // be a subnet router).
  109. // It can only be set before calling Start.
  110. ProcessSubnets bool
  111. ipstack *stack.Stack
  112. linkEP *channel.Endpoint
  113. tundev *tstun.Wrapper
  114. e wgengine.Engine
  115. pm *proxymap.Mapper
  116. mc *magicsock.Conn
  117. logf logger.Logf
  118. dialer *tsdial.Dialer
  119. ctx context.Context // alive until Close
  120. ctxCancel context.CancelFunc // called on Close
  121. lb *ipnlocal.LocalBackend // or nil
  122. dns *dns.Manager
  123. peerapiPort4Atomic atomic.Uint32 // uint16 port number for IPv4 peerapi
  124. peerapiPort6Atomic atomic.Uint32 // uint16 port number for IPv6 peerapi
  125. // atomicIsLocalIPFunc holds a func that reports whether an IP
  126. // is a local (non-subnet) Tailscale IP address of this
  127. // machine. It's always a non-nil func. It's changed on netmap
  128. // updates.
  129. atomicIsLocalIPFunc syncs.AtomicValue[func(netip.Addr) bool]
  130. mu sync.Mutex
  131. // connsOpenBySubnetIP keeps track of number of connections open
  132. // for each subnet IP temporarily registered on netstack for active
  133. // TCP connections, so they can be unregistered when connections are
  134. // closed.
  135. connsOpenBySubnetIP map[netip.Addr]int
  136. }
  137. const nicID = 1
  138. // maxUDPPacketSize is the maximum size of a UDP packet we copy in
  139. // startPacketCopy when relaying UDP packets. The user can configure
  140. // the tailscale MTU to anything up to this size so we can potentially
  141. // have a UDP packet as big as the MTU.
  142. const maxUDPPacketSize = tstun.MaxPacketSize
  143. // Create creates and populates a new Impl.
  144. func Create(logf logger.Logf, tundev *tstun.Wrapper, e wgengine.Engine, mc *magicsock.Conn, dialer *tsdial.Dialer, dns *dns.Manager, pm *proxymap.Mapper) (*Impl, error) {
  145. if mc == nil {
  146. return nil, errors.New("nil magicsock.Conn")
  147. }
  148. if tundev == nil {
  149. return nil, errors.New("nil tundev")
  150. }
  151. if logf == nil {
  152. return nil, errors.New("nil logger")
  153. }
  154. if e == nil {
  155. return nil, errors.New("nil Engine")
  156. }
  157. if pm == nil {
  158. return nil, errors.New("nil proxymap.Mapper")
  159. }
  160. if dialer == nil {
  161. return nil, errors.New("nil Dialer")
  162. }
  163. ipstack := stack.New(stack.Options{
  164. NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
  165. TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
  166. })
  167. sackEnabledOpt := tcpip.TCPSACKEnabled(true) // TCP SACK is disabled by default
  168. tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt)
  169. if tcpipErr != nil {
  170. return nil, fmt.Errorf("could not enable TCP SACK: %v", tcpipErr)
  171. }
  172. if runtime.GOOS == "windows" {
  173. // See https://github.com/tailscale/tailscale/issues/9707
  174. // Windows w/RACK performs poorly. ACKs do not appear to be handled in a
  175. // timely manner, leading to spurious retransmissions and a reduced
  176. // congestion window.
  177. tcpRecoveryOpt := tcpip.TCPRecovery(0)
  178. tcpipErr = ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpRecoveryOpt)
  179. if tcpipErr != nil {
  180. return nil, fmt.Errorf("could not disable TCP RACK: %v", tcpipErr)
  181. }
  182. }
  183. linkEP := channel.New(512, uint32(tstun.DefaultTUNMTU()), "")
  184. if tcpipProblem := ipstack.CreateNIC(nicID, linkEP); tcpipProblem != nil {
  185. return nil, fmt.Errorf("could not create netstack NIC: %v", tcpipProblem)
  186. }
  187. // By default the netstack NIC will only accept packets for the IPs
  188. // registered to it. Since in some cases we dynamically register IPs
  189. // based on the packets that arrive, the NIC needs to accept all
  190. // incoming packets. The NIC won't receive anything it isn't meant to
  191. // since WireGuard will only send us packets that are meant for us.
  192. ipstack.SetPromiscuousMode(nicID, true)
  193. // Add IPv4 and IPv6 default routes, so all incoming packets from the Tailscale side
  194. // are handled by the one fake NIC we use.
  195. ipv4Subnet, err := tcpip.NewSubnet(tcpip.AddrFromSlice(make([]byte, 4)), tcpip.MaskFromBytes(make([]byte, 4)))
  196. if err != nil {
  197. return nil, fmt.Errorf("could not create IPv4 subnet: %v", err)
  198. }
  199. ipv6Subnet, err := tcpip.NewSubnet(tcpip.AddrFromSlice(make([]byte, 16)), tcpip.MaskFromBytes(make([]byte, 16)))
  200. if err != nil {
  201. return nil, fmt.Errorf("could not create IPv6 subnet: %v", err)
  202. }
  203. ipstack.SetRouteTable([]tcpip.Route{
  204. {
  205. Destination: ipv4Subnet,
  206. NIC: nicID,
  207. },
  208. {
  209. Destination: ipv6Subnet,
  210. NIC: nicID,
  211. },
  212. })
  213. ns := &Impl{
  214. logf: logf,
  215. ipstack: ipstack,
  216. linkEP: linkEP,
  217. tundev: tundev,
  218. e: e,
  219. pm: pm,
  220. mc: mc,
  221. dialer: dialer,
  222. connsOpenBySubnetIP: make(map[netip.Addr]int),
  223. dns: dns,
  224. }
  225. ns.ctx, ns.ctxCancel = context.WithCancel(context.Background())
  226. ns.atomicIsLocalIPFunc.Store(tsaddr.FalseContainsIPFunc())
  227. ns.tundev.PostFilterPacketInboundFromWireGaurd = ns.injectInbound
  228. ns.tundev.PreFilterPacketOutboundToWireGuardNetstackIntercept = ns.handleLocalPackets
  229. return ns, nil
  230. }
  231. func (ns *Impl) Close() error {
  232. ns.ctxCancel()
  233. ns.ipstack.Close()
  234. ns.ipstack.Wait()
  235. return nil
  236. }
  237. // wrapProtoHandler returns protocol handler h wrapped in a version
  238. // that dynamically reconfigures ns's subnet addresses as needed for
  239. // outbound traffic.
  240. func (ns *Impl) wrapProtoHandler(h func(stack.TransportEndpointID, stack.PacketBufferPtr) bool) func(stack.TransportEndpointID, stack.PacketBufferPtr) bool {
  241. return func(tei stack.TransportEndpointID, pb stack.PacketBufferPtr) bool {
  242. addr := tei.LocalAddress
  243. ip, ok := netip.AddrFromSlice(addr.AsSlice())
  244. if !ok {
  245. ns.logf("netstack: could not parse local address for incoming connection")
  246. return false
  247. }
  248. ip = ip.Unmap()
  249. if !ns.isLocalIP(ip) {
  250. ns.addSubnetAddress(ip)
  251. }
  252. return h(tei, pb)
  253. }
  254. }
  255. // Start sets up all the handlers so netstack can start working. Implements
  256. // wgengine.FakeImpl.
  257. func (ns *Impl) Start(lb *ipnlocal.LocalBackend) error {
  258. if lb == nil {
  259. panic("nil LocalBackend")
  260. }
  261. ns.lb = lb
  262. // size = 0 means use default buffer size
  263. const tcpReceiveBufferSize = 0
  264. const maxInFlightConnectionAttempts = 1024
  265. tcpFwd := tcp.NewForwarder(ns.ipstack, tcpReceiveBufferSize, maxInFlightConnectionAttempts, ns.acceptTCP)
  266. udpFwd := udp.NewForwarder(ns.ipstack, ns.acceptUDP)
  267. ns.ipstack.SetTransportProtocolHandler(tcp.ProtocolNumber, ns.wrapProtoHandler(tcpFwd.HandlePacket))
  268. ns.ipstack.SetTransportProtocolHandler(udp.ProtocolNumber, ns.wrapProtoHandler(udpFwd.HandlePacket))
  269. go ns.inject()
  270. return nil
  271. }
  272. func (ns *Impl) addSubnetAddress(ip netip.Addr) {
  273. ns.mu.Lock()
  274. ns.connsOpenBySubnetIP[ip]++
  275. needAdd := ns.connsOpenBySubnetIP[ip] == 1
  276. ns.mu.Unlock()
  277. // Only register address into netstack for first concurrent connection.
  278. if needAdd {
  279. pa := tcpip.ProtocolAddress{
  280. AddressWithPrefix: tcpip.AddrFromSlice(ip.AsSlice()).WithPrefix(),
  281. }
  282. if ip.Is4() {
  283. pa.Protocol = ipv4.ProtocolNumber
  284. } else if ip.Is6() {
  285. pa.Protocol = ipv6.ProtocolNumber
  286. }
  287. ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  288. PEB: stack.CanBePrimaryEndpoint, // zero value default
  289. ConfigType: stack.AddressConfigStatic, // zero value default
  290. })
  291. }
  292. }
  293. func (ns *Impl) removeSubnetAddress(ip netip.Addr) {
  294. ns.mu.Lock()
  295. defer ns.mu.Unlock()
  296. ns.connsOpenBySubnetIP[ip]--
  297. // Only unregister address from netstack after last concurrent connection.
  298. if ns.connsOpenBySubnetIP[ip] == 0 {
  299. ns.ipstack.RemoveAddress(nicID, tcpip.AddrFromSlice(ip.AsSlice()))
  300. delete(ns.connsOpenBySubnetIP, ip)
  301. }
  302. }
  303. func ipPrefixToAddressWithPrefix(ipp netip.Prefix) tcpip.AddressWithPrefix {
  304. return tcpip.AddressWithPrefix{
  305. Address: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  306. PrefixLen: int(ipp.Bits()),
  307. }
  308. }
  309. var v4broadcast = netaddr.IPv4(255, 255, 255, 255)
  310. // UpdateNetstackIPs updates the set of local IPs that netstack should handle
  311. // from nm.
  312. //
  313. // TODO(bradfitz): don't pass the whole netmap here; just pass the two
  314. // address slice views.
  315. func (ns *Impl) UpdateNetstackIPs(nm *netmap.NetworkMap) {
  316. var selfNode tailcfg.NodeView
  317. if nm != nil {
  318. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nm.GetAddresses()))
  319. selfNode = nm.SelfNode
  320. } else {
  321. ns.atomicIsLocalIPFunc.Store(tsaddr.FalseContainsIPFunc())
  322. }
  323. oldPfx := make(map[netip.Prefix]bool)
  324. for _, protocolAddr := range ns.ipstack.AllAddresses()[nicID] {
  325. ap := protocolAddr.AddressWithPrefix
  326. ip := netaddrIPFromNetstackIP(ap.Address)
  327. if ip == v4broadcast && ap.PrefixLen == 32 {
  328. // Don't add 255.255.255.255/32 to oldIPs so we don't
  329. // delete it later. We didn't install it, so it's not
  330. // ours to delete.
  331. continue
  332. }
  333. p := netip.PrefixFrom(ip, ap.PrefixLen)
  334. oldPfx[p] = true
  335. }
  336. newPfx := make(map[netip.Prefix]bool)
  337. if selfNode.Valid() {
  338. for i := range selfNode.Addresses().LenIter() {
  339. p := selfNode.Addresses().At(i)
  340. newPfx[p] = true
  341. }
  342. if ns.ProcessSubnets {
  343. for i := range selfNode.AllowedIPs().LenIter() {
  344. p := selfNode.AllowedIPs().At(i)
  345. newPfx[p] = true
  346. }
  347. }
  348. }
  349. pfxToAdd := make(map[netip.Prefix]bool)
  350. for p := range newPfx {
  351. if !oldPfx[p] {
  352. pfxToAdd[p] = true
  353. }
  354. }
  355. pfxToRemove := make(map[netip.Prefix]bool)
  356. for p := range oldPfx {
  357. if !newPfx[p] {
  358. pfxToRemove[p] = true
  359. }
  360. }
  361. ns.mu.Lock()
  362. for ip := range ns.connsOpenBySubnetIP {
  363. // TODO(maisem): this looks like a bug, remove or document. It seems as
  364. // though we might end up either leaking the address on the netstack
  365. // NIC, or where we do accounting for connsOpenBySubnetIP from 1 to 0,
  366. // we might end up removing the address from the netstack NIC that was
  367. // still being advertised.
  368. delete(pfxToRemove, netip.PrefixFrom(ip, ip.BitLen()))
  369. }
  370. ns.mu.Unlock()
  371. for p := range pfxToRemove {
  372. err := ns.ipstack.RemoveAddress(nicID, tcpip.AddrFromSlice(p.Addr().AsSlice()))
  373. if err != nil {
  374. ns.logf("netstack: could not deregister IP %s: %v", p, err)
  375. } else {
  376. ns.logf("[v2] netstack: deregistered IP %s", p)
  377. }
  378. }
  379. for p := range pfxToAdd {
  380. if !p.IsValid() {
  381. ns.logf("netstack: [unexpected] skipping invalid IP (%v/%v)", p.Addr(), p.Bits())
  382. continue
  383. }
  384. tcpAddr := tcpip.ProtocolAddress{
  385. AddressWithPrefix: ipPrefixToAddressWithPrefix(p),
  386. }
  387. if p.Addr().Is6() {
  388. tcpAddr.Protocol = ipv6.ProtocolNumber
  389. } else {
  390. tcpAddr.Protocol = ipv4.ProtocolNumber
  391. }
  392. var tcpErr tcpip.Error // not error
  393. tcpErr = ns.ipstack.AddProtocolAddress(nicID, tcpAddr, stack.AddressProperties{
  394. PEB: stack.CanBePrimaryEndpoint, // zero value default
  395. ConfigType: stack.AddressConfigStatic, // zero value default
  396. })
  397. if tcpErr != nil {
  398. ns.logf("netstack: could not register IP %s: %v", p, tcpErr)
  399. } else {
  400. ns.logf("[v2] netstack: registered IP %s", p)
  401. }
  402. }
  403. }
  404. // handleLocalPackets is hooked into the tun datapath for packets leaving
  405. // the host and arriving at tailscaled. This method returns filter.DropSilently
  406. // to intercept a packet for handling, for instance traffic to quad-100.
  407. func (ns *Impl) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  408. if ns.ctx.Err() != nil {
  409. return filter.DropSilently
  410. }
  411. // If it's not traffic to the service IP (i.e. magicDNS) we don't
  412. // care; resume processing.
  413. if dst := p.Dst.Addr(); dst != magicDNSIP && dst != magicDNSIPv6 {
  414. return filter.Accept
  415. }
  416. // Of traffic to the service IP, we only care about UDP 53, and TCP
  417. // on port 80 & 53.
  418. switch p.IPProto {
  419. case ipproto.TCP:
  420. if port := p.Dst.Port(); port != 53 && port != 80 {
  421. return filter.Accept
  422. }
  423. case ipproto.UDP:
  424. if port := p.Dst.Port(); port != 53 {
  425. return filter.Accept
  426. }
  427. }
  428. var pn tcpip.NetworkProtocolNumber
  429. switch p.IPVersion {
  430. case 4:
  431. pn = header.IPv4ProtocolNumber
  432. case 6:
  433. pn = header.IPv6ProtocolNumber
  434. }
  435. if debugPackets {
  436. ns.logf("[v2] service packet in (from %v): % x", p.Src, p.Buffer())
  437. }
  438. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  439. Payload: buffer.MakeWithData(bytes.Clone(p.Buffer())),
  440. })
  441. ns.linkEP.InjectInbound(pn, packetBuf)
  442. packetBuf.DecRef()
  443. return filter.DropSilently
  444. }
  445. func (ns *Impl) DialContextTCP(ctx context.Context, ipp netip.AddrPort) (*gonet.TCPConn, error) {
  446. remoteAddress := tcpip.FullAddress{
  447. NIC: nicID,
  448. Addr: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  449. Port: ipp.Port(),
  450. }
  451. var ipType tcpip.NetworkProtocolNumber
  452. if ipp.Addr().Is4() {
  453. ipType = ipv4.ProtocolNumber
  454. } else {
  455. ipType = ipv6.ProtocolNumber
  456. }
  457. return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
  458. }
  459. func (ns *Impl) DialContextUDP(ctx context.Context, ipp netip.AddrPort) (*gonet.UDPConn, error) {
  460. remoteAddress := &tcpip.FullAddress{
  461. NIC: nicID,
  462. Addr: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  463. Port: ipp.Port(),
  464. }
  465. var ipType tcpip.NetworkProtocolNumber
  466. if ipp.Addr().Is4() {
  467. ipType = ipv4.ProtocolNumber
  468. } else {
  469. ipType = ipv6.ProtocolNumber
  470. }
  471. return gonet.DialUDP(ns.ipstack, nil, remoteAddress, ipType)
  472. }
  473. // The inject goroutine reads in packets that netstack generated, and delivers
  474. // them to the correct path.
  475. func (ns *Impl) inject() {
  476. for {
  477. pkt := ns.linkEP.ReadContext(ns.ctx)
  478. if pkt.IsNil() {
  479. if ns.ctx.Err() != nil {
  480. // Return without logging.
  481. return
  482. }
  483. ns.logf("[v2] ReadContext-for-write = ok=false")
  484. continue
  485. }
  486. if debugPackets {
  487. ns.logf("[v2] packet Write out: % x", stack.PayloadSince(pkt.NetworkHeader()))
  488. }
  489. // In the normal case, netstack synthesizes the bytes for
  490. // traffic which should transit back into WG and go to peers.
  491. // However, some uses of netstack (presently, magic DNS)
  492. // send traffic destined for the local device, hence must
  493. // be injected 'inbound'.
  494. sendToHost := false
  495. // Determine if the packet is from a service IP, in which case it
  496. // needs to go back into the machines network (inbound) instead of
  497. // out.
  498. // TODO(tom): Work out a way to avoid parsing packets to determine if
  499. // its from the service IP. Maybe gvisor netstack magic. I
  500. // went through the fields of PacketBuffer, and nop :/
  501. // TODO(tom): Figure out if its safe to modify packet.Parsed to fill in
  502. // the IP src/dest even if its missing the rest of the pkt.
  503. // That way we dont have to do this twitchy-af byte-yeeting.
  504. if b := pkt.NetworkHeader().Slice(); len(b) >= 20 { // min ipv4 header
  505. switch b[0] >> 4 { // ip proto field
  506. case 4:
  507. if srcIP := netaddr.IPv4(b[12], b[13], b[14], b[15]); magicDNSIP == srcIP {
  508. sendToHost = true
  509. }
  510. case 6:
  511. if len(b) >= 40 { // min ipv6 header
  512. if srcIP, ok := netip.AddrFromSlice(net.IP(b[8:24])); ok && magicDNSIPv6 == srcIP {
  513. sendToHost = true
  514. }
  515. }
  516. }
  517. }
  518. // pkt has a non-zero refcount, so injection methods takes
  519. // ownership of one count and will decrement on completion.
  520. if sendToHost {
  521. if err := ns.tundev.InjectInboundPacketBuffer(pkt); err != nil {
  522. log.Printf("netstack inject inbound: %v", err)
  523. return
  524. }
  525. } else {
  526. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  527. log.Printf("netstack inject outbound: %v", err)
  528. return
  529. }
  530. }
  531. }
  532. }
  533. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  534. // node directly (but not a subnet-routed IP).
  535. func (ns *Impl) isLocalIP(ip netip.Addr) bool {
  536. return ns.atomicIsLocalIPFunc.Load()(ip)
  537. }
  538. func (ns *Impl) peerAPIPortAtomic(ip netip.Addr) *atomic.Uint32 {
  539. if ip.Is4() {
  540. return &ns.peerapiPort4Atomic
  541. } else {
  542. return &ns.peerapiPort6Atomic
  543. }
  544. }
  545. var viaRange = tsaddr.TailscaleViaRange()
  546. // shouldProcessInbound reports whether an inbound packet (a packet from a
  547. // WireGuard peer) should be handled by netstack.
  548. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  549. // Handle incoming peerapi connections in netstack.
  550. dstIP := p.Dst.Addr()
  551. isLocal := ns.isLocalIP(dstIP)
  552. // Handle TCP connection to the Tailscale IP(s) in some cases:
  553. if ns.lb != nil && p.IPProto == ipproto.TCP && isLocal {
  554. var peerAPIPort uint16
  555. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn {
  556. if port, ok := ns.lb.GetPeerAPIPort(dstIP); ok {
  557. peerAPIPort = port
  558. ns.peerAPIPortAtomic(dstIP).Store(uint32(port))
  559. }
  560. } else {
  561. peerAPIPort = uint16(ns.peerAPIPortAtomic(dstIP).Load())
  562. }
  563. dport := p.Dst.Port()
  564. if dport == peerAPIPort {
  565. return true
  566. }
  567. // Also handle SSH connections, webserver, etc, if enabled:
  568. if ns.lb.ShouldInterceptTCPPort(dport) {
  569. return true
  570. }
  571. }
  572. if p.IPVersion == 6 && !isLocal && viaRange.Contains(dstIP) {
  573. return ns.lb != nil && ns.lb.ShouldHandleViaIP(dstIP)
  574. }
  575. if ns.ProcessLocalIPs && isLocal {
  576. return true
  577. }
  578. if ns.ProcessSubnets && !isLocal {
  579. return true
  580. }
  581. return false
  582. }
  583. // setAmbientCapsRaw is non-nil on Linux for Synology, to run ping with
  584. // CAP_NET_RAW from tailscaled's binary.
  585. var setAmbientCapsRaw func(*exec.Cmd)
  586. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  587. var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
  588. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  589. // into the tundev.
  590. //
  591. // It's used in userspace/netstack mode when we don't have kernel
  592. // support or raw socket access. As such, this does the dumbest thing
  593. // that can work: runs the ping command. It's not super efficient, so
  594. // it bounds the number of pings going on at once. The idea is that
  595. // people only use ping occasionally to see if their internet's working
  596. // so this doesn't need to be great.
  597. //
  598. // TODO(bradfitz): when we're running on Windows as the system user, use
  599. // raw socket APIs instead of ping child processes.
  600. func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte) {
  601. if !userPingSem.TryAcquire() {
  602. return
  603. }
  604. defer userPingSem.Release()
  605. t0 := time.Now()
  606. var err error
  607. switch runtime.GOOS {
  608. case "windows":
  609. err = exec.Command("ping", "-n", "1", "-w", "3000", dstIP.String()).Run()
  610. case "darwin", "freebsd":
  611. // Note: 2000 ms is actually 1 second + 2,000
  612. // milliseconds extra for 3 seconds total.
  613. // See https://github.com/tailscale/tailscale/pull/3753 for details.
  614. ping := "ping"
  615. if dstIP.Is6() {
  616. ping = "ping6"
  617. }
  618. err = exec.Command(ping, "-c", "1", "-W", "2000", dstIP.String()).Run()
  619. case "openbsd":
  620. ping := "ping"
  621. if dstIP.Is6() {
  622. ping = "ping6"
  623. }
  624. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  625. case "android":
  626. ping := "/system/bin/ping"
  627. if dstIP.Is6() {
  628. ping = "/system/bin/ping6"
  629. }
  630. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  631. default:
  632. ping := "ping"
  633. if isSynology {
  634. ping = "/bin/ping"
  635. }
  636. cmd := exec.Command(ping, "-c", "1", "-W", "3", dstIP.String())
  637. if isSynology && os.Getuid() != 0 {
  638. // On DSM7 we run as non-root and need to pass
  639. // CAP_NET_RAW if our binary has it.
  640. setAmbientCapsRaw(cmd)
  641. }
  642. err = cmd.Run()
  643. }
  644. d := time.Since(t0)
  645. if err != nil {
  646. if d < time.Second/2 {
  647. // If it failed quicker than the 3 second
  648. // timeout we gave above (500 ms is a
  649. // reasonable threshold), then assume the ping
  650. // failed for problems finding/running
  651. // ping. We don't want to log if the host is
  652. // just down.
  653. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  654. }
  655. return
  656. }
  657. if debugNetstack() {
  658. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  659. }
  660. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  661. ns.logf("InjectOutbound ping response: %v", err)
  662. }
  663. }
  664. // injectInbound is installed as a packet hook on the 'inbound' (from a
  665. // WireGuard peer) path. Returning filter.Accept releases the packet to
  666. // continue normally (typically being delivered to the host networking stack),
  667. // whereas returning filter.DropSilently is done when netstack intercepts the
  668. // packet and no further processing towards to host should be done.
  669. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  670. if ns.ctx.Err() != nil {
  671. return filter.DropSilently
  672. }
  673. if !ns.shouldProcessInbound(p, t) {
  674. // Let the host network stack (if any) deal with it.
  675. return filter.Accept
  676. }
  677. destIP := p.Dst.Addr()
  678. // If this is an echo request and we're a subnet router, handle pings
  679. // ourselves instead of forwarding the packet on.
  680. pingIP, handlePing := ns.shouldHandlePing(p)
  681. if handlePing {
  682. var pong []byte // the reply to the ping, if our relayed ping works
  683. if destIP.Is4() {
  684. h := p.ICMP4Header()
  685. h.ToResponse()
  686. pong = packet.Generate(&h, p.Payload())
  687. } else if destIP.Is6() {
  688. h := p.ICMP6Header()
  689. h.ToResponse()
  690. pong = packet.Generate(&h, p.Payload())
  691. }
  692. go ns.userPing(pingIP, pong)
  693. return filter.DropSilently
  694. }
  695. var pn tcpip.NetworkProtocolNumber
  696. switch p.IPVersion {
  697. case 4:
  698. pn = header.IPv4ProtocolNumber
  699. case 6:
  700. pn = header.IPv6ProtocolNumber
  701. }
  702. if debugPackets {
  703. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  704. }
  705. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  706. Payload: buffer.MakeWithData(bytes.Clone(p.Buffer())),
  707. })
  708. ns.linkEP.InjectInbound(pn, packetBuf)
  709. packetBuf.DecRef()
  710. // We've now delivered this to netstack, so we're done.
  711. // Instead of returning a filter.Accept here (which would also
  712. // potentially deliver it to the host OS), and instead of
  713. // filter.Drop (which would log about rejected traffic),
  714. // instead return filter.DropSilently which just quietly stops
  715. // processing it in the tstun TUN wrapper.
  716. return filter.DropSilently
  717. }
  718. // shouldHandlePing returns whether or not netstack should handle an incoming
  719. // ICMP echo request packet, and the IP address that should be pinged from this
  720. // process. The IP address can be different from the destination in the packet
  721. // if the destination is a 4via6 address.
  722. func (ns *Impl) shouldHandlePing(p *packet.Parsed) (_ netip.Addr, ok bool) {
  723. if !p.IsEchoRequest() {
  724. return netip.Addr{}, false
  725. }
  726. destIP := p.Dst.Addr()
  727. // We need to handle pings for all 4via6 addresses, even if this
  728. // netstack instance normally isn't responsible for processing subnets.
  729. //
  730. // For example, on Linux, subnet router traffic could be handled via
  731. // tun+iptables rules for most packets, but we still need to handle
  732. // ICMP echo requests over 4via6 since the host networking stack
  733. // doesn't know what to do with a 4via6 address.
  734. //
  735. // shouldProcessInbound returns 'true' to say that we should process
  736. // all IPv6 packets with a destination address in the 'via' range, so
  737. // check before we check the "ProcessSubnets" boolean below.
  738. if viaRange.Contains(destIP) {
  739. // The input echo request was to a 4via6 address, which we cannot
  740. // simply ping as-is from this process. Translate the destination to an
  741. // IPv4 address, so that our relayed ping (in userPing) is pinging the
  742. // underlying destination IP.
  743. //
  744. // ICMPv4 and ICMPv6 are different protocols with different on-the-wire
  745. // representations, so normally you can't send an ICMPv6 message over
  746. // IPv4 and expect to get a useful result. However, in this specific
  747. // case things are safe because the 'userPing' function doesn't make
  748. // use of the input packet.
  749. return tsaddr.UnmapVia(destIP), true
  750. }
  751. // If we get here, we don't do anything unless this netstack instance
  752. // is responsible for processing subnet traffic.
  753. if !ns.ProcessSubnets {
  754. return netip.Addr{}, false
  755. }
  756. // For non-4via6 addresses, we don't handle pings if they're destined
  757. // for a Tailscale IP.
  758. if tsaddr.IsTailscaleIP(destIP) {
  759. return netip.Addr{}, false
  760. }
  761. // This netstack instance is processing subnet traffic, so handle the
  762. // ping ourselves.
  763. return destIP, true
  764. }
  765. func netaddrIPFromNetstackIP(s tcpip.Address) netip.Addr {
  766. switch s.Len() {
  767. case 4:
  768. s := s.As4()
  769. return netaddr.IPv4(s[0], s[1], s[2], s[3])
  770. case 16:
  771. s := s.As16()
  772. return netip.AddrFrom16(s).Unmap()
  773. }
  774. return netip.Addr{}
  775. }
  776. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  777. reqDetails := r.ID()
  778. if debugNetstack() {
  779. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  780. }
  781. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  782. if !clientRemoteIP.IsValid() {
  783. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  784. r.Complete(true) // sends a RST
  785. return
  786. }
  787. clientRemotePort := reqDetails.RemotePort
  788. clientRemoteAddrPort := netip.AddrPortFrom(clientRemoteIP, clientRemotePort)
  789. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  790. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  791. dstAddrPort := netip.AddrPortFrom(dialIP, reqDetails.LocalPort)
  792. if viaRange.Contains(dialIP) {
  793. isTailscaleIP = false
  794. dialIP = tsaddr.UnmapVia(dialIP)
  795. }
  796. defer func() {
  797. if !isTailscaleIP {
  798. // if this is a subnet IP, we added this in before the TCP handshake
  799. // so netstack is happy TCP-handshaking as a subnet IP
  800. ns.removeSubnetAddress(dialIP)
  801. }
  802. }()
  803. var wq waiter.Queue
  804. // We can't actually create the endpoint or complete the inbound
  805. // request until we're sure that the connection can be handled by this
  806. // endpoint. This function sets up the TCP connection and should be
  807. // called immediately before a connection is handled.
  808. getConnOrReset := func(opts ...tcpip.SettableSocketOption) *gonet.TCPConn {
  809. ep, err := r.CreateEndpoint(&wq)
  810. if err != nil {
  811. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  812. r.Complete(true) // sends a RST
  813. return nil
  814. }
  815. r.Complete(false)
  816. for _, opt := range opts {
  817. ep.SetSockOpt(opt)
  818. }
  819. // SetKeepAlive so that idle connections to peers that have forgotten about
  820. // the connection or gone completely offline eventually time out.
  821. // Applications might be setting this on a forwarded connection, but from
  822. // userspace we can not see those, so the best we can do is to always
  823. // perform them with conservative timing.
  824. // TODO(tailscale/tailscale#4522): Netstack defaults match the Linux
  825. // defaults, and results in a little over two hours before the socket would
  826. // be closed due to keepalive. A shorter default might be better, or seeking
  827. // a default from the host IP stack. This also might be a useful
  828. // user-tunable, as in userspace mode this can have broad implications such
  829. // as lingering connections to fork style daemons. On the other side of the
  830. // fence, the long duration timers are low impact values for battery powered
  831. // peers.
  832. ep.SocketOptions().SetKeepAlive(true)
  833. // The ForwarderRequest.CreateEndpoint above asynchronously
  834. // starts the TCP handshake. Note that the gonet.TCPConn
  835. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  836. // until the handshake actually completes. But we have the
  837. // remote address in reqDetails instead, so we don't use
  838. // gonet.TCPConn.RemoteAddr. The byte copies in both
  839. // directions to/from the gonet.TCPConn in forwardTCP will
  840. // block until the TCP handshake is complete.
  841. return gonet.NewTCPConn(&wq, ep)
  842. }
  843. // DNS
  844. if reqDetails.LocalPort == 53 && (dialIP == magicDNSIP || dialIP == magicDNSIPv6) {
  845. c := getConnOrReset()
  846. if c == nil {
  847. return
  848. }
  849. go ns.dns.HandleTCPConn(c, netip.AddrPortFrom(clientRemoteIP, reqDetails.RemotePort))
  850. return
  851. }
  852. if ns.lb != nil {
  853. handler, opts := ns.lb.TCPHandlerForDst(clientRemoteAddrPort, dstAddrPort)
  854. if handler != nil {
  855. c := getConnOrReset(opts...) // will send a RST if it fails
  856. if c == nil {
  857. return
  858. }
  859. handler(c)
  860. return
  861. }
  862. }
  863. if ns.GetTCPHandlerForFlow != nil {
  864. handler, ok := ns.GetTCPHandlerForFlow(clientRemoteAddrPort, dstAddrPort)
  865. if ok {
  866. if handler == nil {
  867. r.Complete(true)
  868. return
  869. }
  870. c := getConnOrReset() // will send a RST if it fails
  871. if c == nil {
  872. return
  873. }
  874. handler(c)
  875. return
  876. }
  877. }
  878. if isTailscaleIP {
  879. dialIP = netaddr.IPv4(127, 0, 0, 1)
  880. }
  881. dialAddr := netip.AddrPortFrom(dialIP, uint16(reqDetails.LocalPort))
  882. if !ns.forwardTCP(getConnOrReset, clientRemoteIP, &wq, dialAddr) {
  883. r.Complete(true) // sends a RST
  884. }
  885. }
  886. func (ns *Impl) forwardTCP(getClient func(...tcpip.SettableSocketOption) *gonet.TCPConn, clientRemoteIP netip.Addr, wq *waiter.Queue, dialAddr netip.AddrPort) (handled bool) {
  887. dialAddrStr := dialAddr.String()
  888. if debugNetstack() {
  889. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  890. }
  891. ctx, cancel := context.WithCancel(context.Background())
  892. defer cancel()
  893. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  894. wq.EventRegister(&waitEntry)
  895. defer wq.EventUnregister(&waitEntry)
  896. done := make(chan bool)
  897. // netstack doesn't close the notification channel automatically if there was no
  898. // hup signal, so we close done after we're done to not leak the goroutine below.
  899. defer close(done)
  900. go func() {
  901. select {
  902. case <-notifyCh:
  903. if debugNetstack() {
  904. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  905. }
  906. case <-done:
  907. }
  908. cancel()
  909. }()
  910. // Attempt to dial the outbound connection before we accept the inbound one.
  911. var stdDialer net.Dialer
  912. server, err := stdDialer.DialContext(ctx, "tcp", dialAddrStr)
  913. if err != nil {
  914. ns.logf("netstack: could not connect to local server at %s: %v", dialAddr.String(), err)
  915. return
  916. }
  917. defer server.Close()
  918. // If we get here, either the getClient call below will succeed and
  919. // return something we can Close, or it will fail and will properly
  920. // respond to the client with a RST. Either way, the caller no longer
  921. // needs to clean up the client connection.
  922. handled = true
  923. // We dialed the connection; we can complete the client's TCP handshake.
  924. client := getClient()
  925. if client == nil {
  926. return
  927. }
  928. defer client.Close()
  929. backendLocalAddr := server.LocalAddr().(*net.TCPAddr)
  930. backendLocalIPPort := netaddr.Unmap(backendLocalAddr.AddrPort())
  931. ns.pm.RegisterIPPortIdentity(backendLocalIPPort, clientRemoteIP)
  932. defer ns.pm.UnregisterIPPortIdentity(backendLocalIPPort)
  933. connClosed := make(chan error, 2)
  934. go func() {
  935. _, err := io.Copy(server, client)
  936. connClosed <- err
  937. }()
  938. go func() {
  939. _, err := io.Copy(client, server)
  940. connClosed <- err
  941. }()
  942. err = <-connClosed
  943. if err != nil {
  944. ns.logf("proxy connection closed with error: %v", err)
  945. }
  946. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  947. return
  948. }
  949. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  950. sess := r.ID()
  951. if debugNetstack() {
  952. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  953. }
  954. var wq waiter.Queue
  955. ep, err := r.CreateEndpoint(&wq)
  956. if err != nil {
  957. ns.logf("acceptUDP: could not create endpoint: %v", err)
  958. return
  959. }
  960. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  961. if !ok {
  962. ep.Close()
  963. return
  964. }
  965. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  966. if !ok {
  967. ep.Close()
  968. return
  969. }
  970. // Handle magicDNS traffic (via UDP) here.
  971. if dst := dstAddr.Addr(); dst == magicDNSIP || dst == magicDNSIPv6 {
  972. if dstAddr.Port() != 53 {
  973. ep.Close()
  974. return // Only MagicDNS traffic runs on the service IPs for now.
  975. }
  976. c := gonet.NewUDPConn(&wq, ep)
  977. go ns.handleMagicDNSUDP(srcAddr, c)
  978. return
  979. }
  980. if get := ns.GetUDPHandlerForFlow; get != nil {
  981. h, intercept := get(srcAddr, dstAddr)
  982. if intercept {
  983. if h == nil {
  984. ep.Close()
  985. return
  986. }
  987. go h(gonet.NewUDPConn(&wq, ep))
  988. return
  989. }
  990. }
  991. c := gonet.NewUDPConn(&wq, ep)
  992. go ns.forwardUDP(c, srcAddr, dstAddr)
  993. }
  994. // Buffer pool for forwarding UDP packets. Implementations are advised not to
  995. // exceed 512 bytes per DNS request due to fragmenting but in reality can and do
  996. // send much larger packets, so use the maximum possible UDP packet size.
  997. var udpBufPool = &sync.Pool{
  998. New: func() any {
  999. b := make([]byte, maxUDPPacketSize)
  1000. return &b
  1001. },
  1002. }
  1003. func (ns *Impl) handleMagicDNSUDP(srcAddr netip.AddrPort, c *gonet.UDPConn) {
  1004. // Packets are being generated by the local host, so there should be
  1005. // very, very little latency. 150ms was chosen as something of an upper
  1006. // bound on resource usage, while hopefully still being long enough for
  1007. // a heavily loaded system.
  1008. const readDeadline = 150 * time.Millisecond
  1009. defer c.Close()
  1010. bufp := udpBufPool.Get().(*[]byte)
  1011. defer udpBufPool.Put(bufp)
  1012. q := *bufp
  1013. // libresolv from glibc is quite adamant that transmitting multiple DNS
  1014. // requests down the same UDP socket is valid. To support this, we read
  1015. // in a loop (with a tight deadline so we don't chew too many resources).
  1016. //
  1017. // See: https://github.com/bminor/glibc/blob/f7fbb99652eceb1b6b55e4be931649df5946497c/resolv/res_send.c#L995
  1018. for {
  1019. c.SetReadDeadline(time.Now().Add(readDeadline))
  1020. n, _, err := c.ReadFrom(q)
  1021. if err != nil {
  1022. if oe, ok := err.(*net.OpError); !(ok && oe.Timeout()) {
  1023. ns.logf("dns udp read: %v", err) // log non-timeout errors
  1024. }
  1025. return
  1026. }
  1027. resp, err := ns.dns.Query(context.Background(), q[:n], "udp", srcAddr)
  1028. if err != nil {
  1029. ns.logf("dns udp query: %v", err)
  1030. return
  1031. }
  1032. c.Write(resp)
  1033. }
  1034. }
  1035. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  1036. //
  1037. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  1038. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  1039. // proxy to it directly.
  1040. func (ns *Impl) forwardUDP(client *gonet.UDPConn, clientAddr, dstAddr netip.AddrPort) {
  1041. port, srcPort := dstAddr.Port(), clientAddr.Port()
  1042. if debugNetstack() {
  1043. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  1044. }
  1045. var backendListenAddr *net.UDPAddr
  1046. var backendRemoteAddr *net.UDPAddr
  1047. isLocal := ns.isLocalIP(dstAddr.Addr())
  1048. if isLocal {
  1049. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  1050. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  1051. } else {
  1052. if dstIP := dstAddr.Addr(); viaRange.Contains(dstIP) {
  1053. dstAddr = netip.AddrPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
  1054. }
  1055. backendRemoteAddr = net.UDPAddrFromAddrPort(dstAddr)
  1056. if dstAddr.Addr().Is4() {
  1057. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  1058. } else {
  1059. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  1060. }
  1061. }
  1062. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  1063. if err != nil {
  1064. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  1065. backendListenAddr.Port = 0
  1066. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  1067. if err != nil {
  1068. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  1069. return
  1070. }
  1071. }
  1072. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  1073. backendLocalIPPort := netip.AddrPortFrom(backendListenAddr.AddrPort().Addr().Unmap().WithZone(backendLocalAddr.Zone), backendLocalAddr.AddrPort().Port())
  1074. if !backendLocalIPPort.IsValid() {
  1075. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  1076. }
  1077. if isLocal {
  1078. ns.pm.RegisterIPPortIdentity(backendLocalIPPort, dstAddr.Addr())
  1079. }
  1080. ctx, cancel := context.WithCancel(context.Background())
  1081. idleTimeout := 2 * time.Minute
  1082. if port == 53 {
  1083. // Make DNS packet copies time out much sooner.
  1084. //
  1085. // TODO(bradfitz): make DNS queries over UDP forwarding even
  1086. // cheaper by adding an additional idleTimeout post-DNS-reply.
  1087. // For instance, after the DNS response goes back out, then only
  1088. // wait a few seconds (or zero, really)
  1089. idleTimeout = 30 * time.Second
  1090. }
  1091. timer := time.AfterFunc(idleTimeout, func() {
  1092. if isLocal {
  1093. ns.pm.UnregisterIPPortIdentity(backendLocalIPPort)
  1094. }
  1095. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  1096. cancel()
  1097. client.Close()
  1098. backendConn.Close()
  1099. })
  1100. extend := func() {
  1101. timer.Reset(idleTimeout)
  1102. }
  1103. startPacketCopy(ctx, cancel, client, net.UDPAddrFromAddrPort(clientAddr), backendConn, ns.logf, extend)
  1104. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  1105. if isLocal {
  1106. // Wait for the copies to be done before decrementing the
  1107. // subnet address count to potentially remove the route.
  1108. <-ctx.Done()
  1109. ns.removeSubnetAddress(dstAddr.Addr())
  1110. }
  1111. }
  1112. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  1113. if debugNetstack() {
  1114. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  1115. }
  1116. go func() {
  1117. defer cancel() // tear down the other direction's copy
  1118. bufp := udpBufPool.Get().(*[]byte)
  1119. defer udpBufPool.Put(bufp)
  1120. pkt := *bufp
  1121. for {
  1122. select {
  1123. case <-ctx.Done():
  1124. return
  1125. default:
  1126. n, srcAddr, err := src.ReadFrom(pkt)
  1127. if err != nil {
  1128. if ctx.Err() == nil {
  1129. logf("read packet from %s failed: %v", srcAddr, err)
  1130. }
  1131. return
  1132. }
  1133. _, err = dst.WriteTo(pkt[:n], dstAddr)
  1134. if err != nil {
  1135. if ctx.Err() == nil {
  1136. logf("write packet to %s failed: %v", dstAddr, err)
  1137. }
  1138. return
  1139. }
  1140. if debugNetstack() {
  1141. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  1142. }
  1143. extend()
  1144. }
  1145. }
  1146. }()
  1147. }
  1148. func stringifyTEI(tei stack.TransportEndpointID) string {
  1149. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  1150. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  1151. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  1152. }
  1153. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netip.AddrPort, ok bool) {
  1154. if addr, ok := netip.AddrFromSlice(a.AsSlice()); ok {
  1155. return netip.AddrPortFrom(addr, port), true
  1156. }
  1157. return netip.AddrPort{}, false
  1158. }
  1159. func readStatCounter(sc *tcpip.StatCounter) int64 {
  1160. vv := sc.Value()
  1161. if vv > math.MaxInt64 {
  1162. return int64(math.MaxInt64)
  1163. }
  1164. return int64(vv)
  1165. }
  1166. // ExpVar returns an expvar variable suitable for registering with expvar.Publish.
  1167. func (ns *Impl) ExpVar() expvar.Var {
  1168. m := new(metrics.Set)
  1169. // Global metrics
  1170. stats := ns.ipstack.Stats()
  1171. m.Set("gauge_dropped_packets", expvar.Func(func() any {
  1172. return readStatCounter(stats.DroppedPackets)
  1173. }))
  1174. // IP statistics
  1175. ipStats := ns.ipstack.Stats().IP
  1176. ipMetrics := []struct {
  1177. name string
  1178. field *tcpip.StatCounter
  1179. }{
  1180. {"packets_received", ipStats.PacketsReceived},
  1181. {"valid_packets_received", ipStats.ValidPacketsReceived},
  1182. {"disabled_packets_received", ipStats.DisabledPacketsReceived},
  1183. {"invalid_destination_addresses_received", ipStats.InvalidDestinationAddressesReceived},
  1184. {"invalid_source_addresses_received", ipStats.InvalidSourceAddressesReceived},
  1185. {"packets_delivered", ipStats.PacketsDelivered},
  1186. {"packets_sent", ipStats.PacketsSent},
  1187. {"outgoing_packet_errors", ipStats.OutgoingPacketErrors},
  1188. {"malformed_packets_received", ipStats.MalformedPacketsReceived},
  1189. {"malformed_fragments_received", ipStats.MalformedFragmentsReceived},
  1190. {"iptables_prerouting_dropped", ipStats.IPTablesPreroutingDropped},
  1191. {"iptables_input_dropped", ipStats.IPTablesInputDropped},
  1192. {"iptables_forward_dropped", ipStats.IPTablesForwardDropped},
  1193. {"iptables_output_dropped", ipStats.IPTablesOutputDropped},
  1194. {"iptables_postrouting_dropped", ipStats.IPTablesPostroutingDropped},
  1195. {"option_timestamp_received", ipStats.OptionTimestampReceived},
  1196. {"option_record_route_received", ipStats.OptionRecordRouteReceived},
  1197. {"option_router_alert_received", ipStats.OptionRouterAlertReceived},
  1198. {"option_unknown_received", ipStats.OptionUnknownReceived},
  1199. }
  1200. for _, metric := range ipMetrics {
  1201. metric := metric
  1202. m.Set("gauge_ip_"+metric.name, expvar.Func(func() any {
  1203. return readStatCounter(metric.field)
  1204. }))
  1205. }
  1206. // IP forwarding statistics
  1207. fwdStats := ipStats.Forwarding
  1208. fwdMetrics := []struct {
  1209. name string
  1210. field *tcpip.StatCounter
  1211. }{
  1212. {"unrouteable", fwdStats.Unrouteable},
  1213. {"exhausted_ttl", fwdStats.ExhaustedTTL},
  1214. {"initializing_source", fwdStats.InitializingSource},
  1215. {"link_local_source", fwdStats.LinkLocalSource},
  1216. {"link_local_destination", fwdStats.LinkLocalDestination},
  1217. {"packet_too_big", fwdStats.PacketTooBig},
  1218. {"host_unreachable", fwdStats.HostUnreachable},
  1219. {"extension_header_problem", fwdStats.ExtensionHeaderProblem},
  1220. {"unexpected_multicast_input_interface", fwdStats.UnexpectedMulticastInputInterface},
  1221. {"unknown_output_endpoint", fwdStats.UnknownOutputEndpoint},
  1222. {"no_multicast_pending_queue_buffer_space", fwdStats.NoMulticastPendingQueueBufferSpace},
  1223. {"outgoing_device_no_buffer_space", fwdStats.OutgoingDeviceNoBufferSpace},
  1224. {"errors", fwdStats.Errors},
  1225. }
  1226. for _, metric := range fwdMetrics {
  1227. metric := metric
  1228. m.Set("gauge_ip_forward_"+metric.name, expvar.Func(func() any {
  1229. return readStatCounter(metric.field)
  1230. }))
  1231. }
  1232. // TCP metrics
  1233. tcpStats := ns.ipstack.Stats().TCP
  1234. tcpMetrics := []struct {
  1235. name string
  1236. field *tcpip.StatCounter
  1237. }{
  1238. {"active_connection_openings", tcpStats.ActiveConnectionOpenings},
  1239. {"passive_connection_openings", tcpStats.PassiveConnectionOpenings},
  1240. {"current_established", tcpStats.CurrentEstablished},
  1241. {"current_connected", tcpStats.CurrentConnected},
  1242. {"established_resets", tcpStats.EstablishedResets},
  1243. {"established_closed", tcpStats.EstablishedClosed},
  1244. {"established_timeout", tcpStats.EstablishedTimedout},
  1245. {"listen_overflow_syn_drop", tcpStats.ListenOverflowSynDrop},
  1246. {"listen_overflow_ack_drop", tcpStats.ListenOverflowAckDrop},
  1247. {"listen_overflow_syn_cookie_sent", tcpStats.ListenOverflowSynCookieSent},
  1248. {"listen_overflow_syn_cookie_rcvd", tcpStats.ListenOverflowSynCookieRcvd},
  1249. {"listen_overflow_invalid_syn_cookie_rcvd", tcpStats.ListenOverflowInvalidSynCookieRcvd},
  1250. {"failed_connection_attempts", tcpStats.FailedConnectionAttempts},
  1251. {"valid_segments_received", tcpStats.ValidSegmentsReceived},
  1252. {"invalid_segments_received", tcpStats.InvalidSegmentsReceived},
  1253. {"segments_sent", tcpStats.SegmentsSent},
  1254. {"segment_send_errors", tcpStats.SegmentSendErrors},
  1255. {"resets_sent", tcpStats.ResetsSent},
  1256. {"resets_received", tcpStats.ResetsReceived},
  1257. {"retransmits", tcpStats.Retransmits},
  1258. {"fast_recovery", tcpStats.FastRecovery},
  1259. {"sack_recovery", tcpStats.SACKRecovery},
  1260. {"tlp_recovery", tcpStats.TLPRecovery},
  1261. {"slow_start_retransmits", tcpStats.SlowStartRetransmits},
  1262. {"fast_retransmit", tcpStats.FastRetransmit},
  1263. {"timeouts", tcpStats.Timeouts},
  1264. {"checksum_errors", tcpStats.ChecksumErrors},
  1265. {"failed_port_reservations", tcpStats.FailedPortReservations},
  1266. {"segments_acked_with_dsack", tcpStats.SegmentsAckedWithDSACK},
  1267. {"spurious_recovery", tcpStats.SpuriousRecovery},
  1268. {"spurious_rto_recovery", tcpStats.SpuriousRTORecovery},
  1269. {"gauge_tcp_forward_max_in_flight_drop", tcpStats.ForwardMaxInFlightDrop},
  1270. }
  1271. for _, metric := range tcpMetrics {
  1272. metric := metric
  1273. m.Set("gauge_tcp_"+metric.name, expvar.Func(func() any {
  1274. return readStatCounter(metric.field)
  1275. }))
  1276. }
  1277. // UDP metrics
  1278. udpStats := ns.ipstack.Stats().UDP
  1279. udpMetrics := []struct {
  1280. name string
  1281. field *tcpip.StatCounter
  1282. }{
  1283. {"packets_received", udpStats.PacketsReceived},
  1284. {"unknown_port_errors", udpStats.UnknownPortErrors},
  1285. {"receive_buffer_errors", udpStats.ReceiveBufferErrors},
  1286. {"malformed_packets_received", udpStats.MalformedPacketsReceived},
  1287. {"packets_sent", udpStats.PacketsSent},
  1288. {"packet_send_errors", udpStats.PacketSendErrors},
  1289. {"checksum_errors", udpStats.ChecksumErrors},
  1290. }
  1291. for _, metric := range udpMetrics {
  1292. metric := metric
  1293. m.Set("gauge_udp_"+metric.name, expvar.Func(func() any {
  1294. return readStatCounter(metric.field)
  1295. }))
  1296. }
  1297. return m
  1298. }