2
0

netstack.go 48 KB

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