netstack.go 59 KB

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