netstack.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  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 := ns.shouldSendToHost(pkt)
  740. // pkt has a non-zero refcount, so injection methods takes
  741. // ownership of one count and will decrement on completion.
  742. if sendToHost {
  743. if err := ns.tundev.InjectInboundPacketBuffer(pkt); err != nil {
  744. log.Printf("netstack inject inbound: %v", err)
  745. return
  746. }
  747. } else {
  748. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  749. log.Printf("netstack inject outbound: %v", err)
  750. return
  751. }
  752. }
  753. }
  754. }
  755. // shouldSendToHost determines if the provided packet should be sent to the
  756. // host (i.e the current machine running Tailscale), in which case it will
  757. // return true. It will return false if the packet should be sent outbound, for
  758. // transit via WireGuard to another Tailscale node.
  759. func (ns *Impl) shouldSendToHost(pkt *stack.PacketBuffer) bool {
  760. // Determine if the packet is from a service IP (100.100.100.100 or the
  761. // IPv6 variant), in which case it needs to go back into the machine's
  762. // network (inbound) instead of out.
  763. hdr := pkt.Network()
  764. switch v := hdr.(type) {
  765. case header.IPv4:
  766. srcIP := netip.AddrFrom4(v.SourceAddress().As4())
  767. if serviceIP == srcIP {
  768. return true
  769. }
  770. case header.IPv6:
  771. srcIP := netip.AddrFrom16(v.SourceAddress().As16())
  772. if srcIP == serviceIPv6 {
  773. return true
  774. }
  775. if viaRange.Contains(srcIP) {
  776. // Only send to the host if this 4via6 route is
  777. // something this node handles.
  778. if ns.lb != nil && ns.lb.ShouldHandleViaIP(srcIP) {
  779. dstIP := netip.AddrFrom16(v.DestinationAddress().As16())
  780. // Also, only forward to the host if the packet
  781. // is destined for a local IP; otherwise, we'd
  782. // send traffic that's intended for another
  783. // peer from the local 4via6 address to the
  784. // host instead of outbound to WireGuard. See:
  785. // https://github.com/tailscale/tailscale/issues/12448
  786. if ns.isLocalIP(dstIP) {
  787. return true
  788. }
  789. if debugNetstack() {
  790. ns.logf("netstack: sending 4via6 packet to host: src=%v dst=%v", srcIP, dstIP)
  791. }
  792. }
  793. }
  794. default:
  795. // unknown; don't forward to host
  796. if debugNetstack() {
  797. ns.logf("netstack: unexpected packet in shouldSendToHost: %T", v)
  798. }
  799. }
  800. return false
  801. }
  802. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  803. // node directly (but not a subnet-routed IP).
  804. func (ns *Impl) isLocalIP(ip netip.Addr) bool {
  805. return ns.atomicIsLocalIPFunc.Load()(ip)
  806. }
  807. func (ns *Impl) peerAPIPortAtomic(ip netip.Addr) *atomic.Uint32 {
  808. if ip.Is4() {
  809. return &ns.peerapiPort4Atomic
  810. } else {
  811. return &ns.peerapiPort6Atomic
  812. }
  813. }
  814. var viaRange = tsaddr.TailscaleViaRange()
  815. // shouldProcessInbound reports whether an inbound packet (a packet from a
  816. // WireGuard peer) should be handled by netstack.
  817. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  818. // Handle incoming peerapi connections in netstack.
  819. dstIP := p.Dst.Addr()
  820. isLocal := ns.isLocalIP(dstIP)
  821. // Handle TCP connection to the Tailscale IP(s) in some cases:
  822. if ns.lb != nil && p.IPProto == ipproto.TCP && isLocal {
  823. var peerAPIPort uint16
  824. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn {
  825. if port, ok := ns.lb.GetPeerAPIPort(dstIP); ok {
  826. peerAPIPort = port
  827. ns.peerAPIPortAtomic(dstIP).Store(uint32(port))
  828. }
  829. } else {
  830. peerAPIPort = uint16(ns.peerAPIPortAtomic(dstIP).Load())
  831. }
  832. dport := p.Dst.Port()
  833. if dport == peerAPIPort {
  834. return true
  835. }
  836. // Also handle SSH connections, webserver, etc, if enabled:
  837. if ns.lb.ShouldInterceptTCPPort(dport) {
  838. return true
  839. }
  840. }
  841. if p.IPVersion == 6 && !isLocal && viaRange.Contains(dstIP) {
  842. return ns.lb != nil && ns.lb.ShouldHandleViaIP(dstIP)
  843. }
  844. if ns.ProcessLocalIPs && isLocal {
  845. return true
  846. }
  847. if ns.ProcessSubnets && !isLocal {
  848. return true
  849. }
  850. return false
  851. }
  852. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  853. type userPingDirection int
  854. const (
  855. // userPingDirectionOutbound is used when the pong packet is to be sent
  856. // "outbound"–i.e. from this node to a peer via WireGuard.
  857. userPingDirectionOutbound userPingDirection = iota
  858. // userPingDirectionInbound is used when the pong packet is to be sent
  859. // "inbound"–i.e. from Tailscale to another process on this host.
  860. userPingDirectionInbound
  861. )
  862. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  863. // into the tundev.
  864. //
  865. // It's used in userspace/netstack mode when we don't have kernel
  866. // support or raw socket access. As such, this does the dumbest thing
  867. // that can work: runs the ping command. It's not super efficient, so
  868. // it bounds the number of pings going on at once. The idea is that
  869. // people only use ping occasionally to see if their internet's working
  870. // so this doesn't need to be great.
  871. // On Apple platforms, this function doesn't run the ping command. Instead,
  872. // it sends a non-privileged ping.
  873. //
  874. // The 'direction' parameter is used to determine where the response "pong"
  875. // packet should be written, if the ping succeeds. See the documentation on the
  876. // constants for more details.
  877. //
  878. // TODO(bradfitz): when we're running on Windows as the system user, use
  879. // raw socket APIs instead of ping child processes.
  880. func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte, direction userPingDirection) {
  881. if !userPingSem.TryAcquire() {
  882. return
  883. }
  884. defer userPingSem.Release()
  885. t0 := time.Now()
  886. err := ns.sendOutboundUserPing(dstIP, 3*time.Second)
  887. d := time.Since(t0)
  888. if err != nil {
  889. if d < time.Second/2 {
  890. // If it failed quicker than the 3 second
  891. // timeout we gave above (500 ms is a
  892. // reasonable threshold), then assume the ping
  893. // failed for problems finding/running
  894. // ping. We don't want to log if the host is
  895. // just down.
  896. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  897. }
  898. return
  899. }
  900. if debugNetstack() {
  901. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  902. }
  903. if direction == userPingDirectionOutbound {
  904. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  905. ns.logf("InjectOutbound ping response: %v", err)
  906. }
  907. } else if direction == userPingDirectionInbound {
  908. if err := ns.tundev.InjectInboundCopy(pingResPkt); err != nil {
  909. ns.logf("InjectInboundCopy ping response: %v", err)
  910. }
  911. }
  912. }
  913. // injectInbound is installed as a packet hook on the 'inbound' (from a
  914. // WireGuard peer) path. Returning filter.Accept releases the packet to
  915. // continue normally (typically being delivered to the host networking stack),
  916. // whereas returning filter.DropSilently is done when netstack intercepts the
  917. // packet and no further processing towards to host should be done.
  918. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  919. if ns.ctx.Err() != nil {
  920. return filter.DropSilently
  921. }
  922. if !ns.shouldProcessInbound(p, t) {
  923. // Let the host network stack (if any) deal with it.
  924. return filter.Accept
  925. }
  926. destIP := p.Dst.Addr()
  927. // If this is an echo request and we're a subnet router, handle pings
  928. // ourselves instead of forwarding the packet on.
  929. pingIP, handlePing := ns.shouldHandlePing(p)
  930. if handlePing {
  931. var pong []byte // the reply to the ping, if our relayed ping works
  932. if destIP.Is4() {
  933. h := p.ICMP4Header()
  934. h.ToResponse()
  935. pong = packet.Generate(&h, p.Payload())
  936. } else if destIP.Is6() {
  937. h := p.ICMP6Header()
  938. h.ToResponse()
  939. pong = packet.Generate(&h, p.Payload())
  940. }
  941. go ns.userPing(pingIP, pong, userPingDirectionOutbound)
  942. return filter.DropSilently
  943. }
  944. var pn tcpip.NetworkProtocolNumber
  945. switch p.IPVersion {
  946. case 4:
  947. pn = header.IPv4ProtocolNumber
  948. case 6:
  949. pn = header.IPv6ProtocolNumber
  950. }
  951. if debugPackets {
  952. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  953. }
  954. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  955. Payload: buffer.MakeWithData(bytes.Clone(p.Buffer())),
  956. })
  957. ns.linkEP.InjectInbound(pn, packetBuf)
  958. packetBuf.DecRef()
  959. // We've now delivered this to netstack, so we're done.
  960. // Instead of returning a filter.Accept here (which would also
  961. // potentially deliver it to the host OS), and instead of
  962. // filter.Drop (which would log about rejected traffic),
  963. // instead return filter.DropSilently which just quietly stops
  964. // processing it in the tstun TUN wrapper.
  965. return filter.DropSilently
  966. }
  967. // shouldHandlePing returns whether or not netstack should handle an incoming
  968. // ICMP echo request packet, and the IP address that should be pinged from this
  969. // process. The IP address can be different from the destination in the packet
  970. // if the destination is a 4via6 address.
  971. func (ns *Impl) shouldHandlePing(p *packet.Parsed) (_ netip.Addr, ok bool) {
  972. if !p.IsEchoRequest() {
  973. return netip.Addr{}, false
  974. }
  975. destIP := p.Dst.Addr()
  976. // We need to handle pings for all 4via6 addresses, even if this
  977. // netstack instance normally isn't responsible for processing subnets.
  978. //
  979. // For example, on Linux, subnet router traffic could be handled via
  980. // tun+iptables rules for most packets, but we still need to handle
  981. // ICMP echo requests over 4via6 since the host networking stack
  982. // doesn't know what to do with a 4via6 address.
  983. //
  984. // shouldProcessInbound returns 'true' to say that we should process
  985. // all IPv6 packets with a destination address in the 'via' range, so
  986. // check before we check the "ProcessSubnets" boolean below.
  987. if viaRange.Contains(destIP) {
  988. // The input echo request was to a 4via6 address, which we cannot
  989. // simply ping as-is from this process. Translate the destination to an
  990. // IPv4 address, so that our relayed ping (in userPing) is pinging the
  991. // underlying destination IP.
  992. //
  993. // ICMPv4 and ICMPv6 are different protocols with different on-the-wire
  994. // representations, so normally you can't send an ICMPv6 message over
  995. // IPv4 and expect to get a useful result. However, in this specific
  996. // case things are safe because the 'userPing' function doesn't make
  997. // use of the input packet.
  998. return tsaddr.UnmapVia(destIP), true
  999. }
  1000. // If we get here, we don't do anything unless this netstack instance
  1001. // is responsible for processing subnet traffic.
  1002. if !ns.ProcessSubnets {
  1003. return netip.Addr{}, false
  1004. }
  1005. // For non-4via6 addresses, we don't handle pings if they're destined
  1006. // for a Tailscale IP.
  1007. if tsaddr.IsTailscaleIP(destIP) {
  1008. return netip.Addr{}, false
  1009. }
  1010. // This netstack instance is processing subnet traffic, so handle the
  1011. // ping ourselves.
  1012. return destIP, true
  1013. }
  1014. func netaddrIPFromNetstackIP(s tcpip.Address) netip.Addr {
  1015. switch s.Len() {
  1016. case 4:
  1017. s := s.As4()
  1018. return netaddr.IPv4(s[0], s[1], s[2], s[3])
  1019. case 16:
  1020. s := s.As16()
  1021. return netip.AddrFrom16(s).Unmap()
  1022. }
  1023. return netip.Addr{}
  1024. }
  1025. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  1026. reqDetails := r.ID()
  1027. if debugNetstack() {
  1028. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  1029. }
  1030. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  1031. if !clientRemoteIP.IsValid() {
  1032. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  1033. r.Complete(true) // sends a RST
  1034. return
  1035. }
  1036. // After we've returned from this function or have otherwise reached a
  1037. // non-pending state, decrement the per-client in-flight count and
  1038. // remove this endpoint from our packet tracking map so future TCP
  1039. // connections aren't dropped.
  1040. inFlightCompleted := false
  1041. tei := r.ID()
  1042. defer func() {
  1043. if !inFlightCompleted {
  1044. ns.decrementInFlightTCPForward(tei, clientRemoteIP)
  1045. }
  1046. }()
  1047. clientRemotePort := reqDetails.RemotePort
  1048. clientRemoteAddrPort := netip.AddrPortFrom(clientRemoteIP, clientRemotePort)
  1049. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  1050. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  1051. dstAddrPort := netip.AddrPortFrom(dialIP, reqDetails.LocalPort)
  1052. if viaRange.Contains(dialIP) {
  1053. isTailscaleIP = false
  1054. dialIP = tsaddr.UnmapVia(dialIP)
  1055. }
  1056. defer func() {
  1057. if !isTailscaleIP {
  1058. // if this is a subnet IP, we added this in before the TCP handshake
  1059. // so netstack is happy TCP-handshaking as a subnet IP
  1060. ns.removeSubnetAddress(dialIP)
  1061. }
  1062. }()
  1063. var wq waiter.Queue
  1064. // We can't actually create the endpoint or complete the inbound
  1065. // request until we're sure that the connection can be handled by this
  1066. // endpoint. This function sets up the TCP connection and should be
  1067. // called immediately before a connection is handled.
  1068. getConnOrReset := func(opts ...tcpip.SettableSocketOption) *gonet.TCPConn {
  1069. ep, err := r.CreateEndpoint(&wq)
  1070. if err != nil {
  1071. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  1072. r.Complete(true) // sends a RST
  1073. return nil
  1074. }
  1075. r.Complete(false)
  1076. for _, opt := range opts {
  1077. ep.SetSockOpt(opt)
  1078. }
  1079. // SetKeepAlive so that idle connections to peers that have forgotten about
  1080. // the connection or gone completely offline eventually time out.
  1081. // Applications might be setting this on a forwarded connection, but from
  1082. // userspace we can not see those, so the best we can do is to always
  1083. // perform them with conservative timing.
  1084. // TODO(tailscale/tailscale#4522): Netstack defaults match the Linux
  1085. // defaults, and results in a little over two hours before the socket would
  1086. // be closed due to keepalive. A shorter default might be better, or seeking
  1087. // a default from the host IP stack. This also might be a useful
  1088. // user-tunable, as in userspace mode this can have broad implications such
  1089. // as lingering connections to fork style daemons. On the other side of the
  1090. // fence, the long duration timers are low impact values for battery powered
  1091. // peers.
  1092. ep.SocketOptions().SetKeepAlive(true)
  1093. // This function is called when we're ready to use the
  1094. // underlying connection, and thus it's no longer in a
  1095. // "in-flight" state; decrement our per-client limit right now,
  1096. // and tell the defer in acceptTCP that it doesn't need to do
  1097. // so upon return.
  1098. ns.decrementInFlightTCPForward(tei, clientRemoteIP)
  1099. inFlightCompleted = true
  1100. // The ForwarderRequest.CreateEndpoint above asynchronously
  1101. // starts the TCP handshake. Note that the gonet.TCPConn
  1102. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  1103. // until the handshake actually completes. But we have the
  1104. // remote address in reqDetails instead, so we don't use
  1105. // gonet.TCPConn.RemoteAddr. The byte copies in both
  1106. // directions to/from the gonet.TCPConn in forwardTCP will
  1107. // block until the TCP handshake is complete.
  1108. return gonet.NewTCPConn(&wq, ep)
  1109. }
  1110. // Local Services (DNS and WebDAV)
  1111. hittingServiceIP := dialIP == serviceIP || dialIP == serviceIPv6
  1112. hittingDNS := hittingServiceIP && reqDetails.LocalPort == 53
  1113. if hittingDNS {
  1114. c := getConnOrReset()
  1115. if c == nil {
  1116. return
  1117. }
  1118. addrPort := netip.AddrPortFrom(clientRemoteIP, reqDetails.RemotePort)
  1119. go ns.dns.HandleTCPConn(c, addrPort)
  1120. return
  1121. }
  1122. if ns.lb != nil {
  1123. handler, opts := ns.lb.TCPHandlerForDst(clientRemoteAddrPort, dstAddrPort)
  1124. if handler != nil {
  1125. c := getConnOrReset(opts...) // will send a RST if it fails
  1126. if c == nil {
  1127. return
  1128. }
  1129. handler(c)
  1130. return
  1131. }
  1132. }
  1133. if ns.GetTCPHandlerForFlow != nil {
  1134. handler, ok := ns.GetTCPHandlerForFlow(clientRemoteAddrPort, dstAddrPort)
  1135. if ok {
  1136. if handler == nil {
  1137. r.Complete(true)
  1138. return
  1139. }
  1140. c := getConnOrReset() // will send a RST if it fails
  1141. if c == nil {
  1142. return
  1143. }
  1144. handler(c)
  1145. return
  1146. }
  1147. }
  1148. if isTailscaleIP {
  1149. dialIP = netaddr.IPv4(127, 0, 0, 1)
  1150. }
  1151. dialAddr := netip.AddrPortFrom(dialIP, uint16(reqDetails.LocalPort))
  1152. if !ns.forwardTCP(getConnOrReset, clientRemoteIP, &wq, dialAddr) {
  1153. r.Complete(true) // sends a RST
  1154. }
  1155. }
  1156. func (ns *Impl) forwardTCP(getClient func(...tcpip.SettableSocketOption) *gonet.TCPConn, clientRemoteIP netip.Addr, wq *waiter.Queue, dialAddr netip.AddrPort) (handled bool) {
  1157. dialAddrStr := dialAddr.String()
  1158. if debugNetstack() {
  1159. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  1160. }
  1161. ctx, cancel := context.WithCancel(context.Background())
  1162. defer cancel()
  1163. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  1164. wq.EventRegister(&waitEntry)
  1165. defer wq.EventUnregister(&waitEntry)
  1166. done := make(chan bool)
  1167. // netstack doesn't close the notification channel automatically if there was no
  1168. // hup signal, so we close done after we're done to not leak the goroutine below.
  1169. defer close(done)
  1170. go func() {
  1171. select {
  1172. case <-notifyCh:
  1173. if debugNetstack() {
  1174. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  1175. }
  1176. case <-done:
  1177. }
  1178. cancel()
  1179. }()
  1180. // Attempt to dial the outbound connection before we accept the inbound one.
  1181. var dialFunc func(context.Context, string, string) (net.Conn, error)
  1182. if ns.forwardDialFunc != nil {
  1183. dialFunc = ns.forwardDialFunc
  1184. } else {
  1185. var stdDialer net.Dialer
  1186. dialFunc = stdDialer.DialContext
  1187. }
  1188. server, err := dialFunc(ctx, "tcp", dialAddrStr)
  1189. if err != nil {
  1190. ns.logf("netstack: could not connect to local server at %s: %v", dialAddr.String(), err)
  1191. return
  1192. }
  1193. defer server.Close()
  1194. // If we get here, either the getClient call below will succeed and
  1195. // return something we can Close, or it will fail and will properly
  1196. // respond to the client with a RST. Either way, the caller no longer
  1197. // needs to clean up the client connection.
  1198. handled = true
  1199. // We dialed the connection; we can complete the client's TCP handshake.
  1200. client := getClient()
  1201. if client == nil {
  1202. return
  1203. }
  1204. defer client.Close()
  1205. backendLocalAddr := server.LocalAddr().(*net.TCPAddr)
  1206. backendLocalIPPort := netaddr.Unmap(backendLocalAddr.AddrPort())
  1207. ns.pm.RegisterIPPortIdentity(backendLocalIPPort, clientRemoteIP)
  1208. defer ns.pm.UnregisterIPPortIdentity(backendLocalIPPort)
  1209. connClosed := make(chan error, 2)
  1210. go func() {
  1211. _, err := io.Copy(server, client)
  1212. connClosed <- err
  1213. }()
  1214. go func() {
  1215. _, err := io.Copy(client, server)
  1216. connClosed <- err
  1217. }()
  1218. err = <-connClosed
  1219. if err != nil {
  1220. ns.logf("proxy connection closed with error: %v", err)
  1221. }
  1222. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  1223. return
  1224. }
  1225. // ListenPacket listens for incoming packets for the given network and address.
  1226. // Address must be of the form "ip:port" or "[ip]:port".
  1227. //
  1228. // As of 2024-05-18, only udp4 and udp6 are supported.
  1229. func (ns *Impl) ListenPacket(network, address string) (net.PacketConn, error) {
  1230. ap, err := netip.ParseAddrPort(address)
  1231. if err != nil {
  1232. return nil, fmt.Errorf("netstack: ParseAddrPort(%q): %v", address, err)
  1233. }
  1234. var networkProto tcpip.NetworkProtocolNumber
  1235. switch network {
  1236. case "udp":
  1237. return nil, fmt.Errorf("netstack: udp not supported; use udp4 or udp6")
  1238. case "udp4":
  1239. networkProto = ipv4.ProtocolNumber
  1240. if !ap.Addr().Is4() {
  1241. return nil, fmt.Errorf("netstack: udp4 requires an IPv4 address")
  1242. }
  1243. case "udp6":
  1244. networkProto = ipv6.ProtocolNumber
  1245. if !ap.Addr().Is6() {
  1246. return nil, fmt.Errorf("netstack: udp6 requires an IPv6 address")
  1247. }
  1248. default:
  1249. return nil, fmt.Errorf("netstack: unsupported network %q", network)
  1250. }
  1251. var wq waiter.Queue
  1252. ep, nserr := ns.ipstack.NewEndpoint(udp.ProtocolNumber, networkProto, &wq)
  1253. if nserr != nil {
  1254. return nil, fmt.Errorf("netstack: NewEndpoint: %v", nserr)
  1255. }
  1256. localAddress := tcpip.FullAddress{
  1257. NIC: nicID,
  1258. Addr: tcpip.AddrFromSlice(ap.Addr().AsSlice()),
  1259. Port: ap.Port(),
  1260. }
  1261. if err := ep.Bind(localAddress); err != nil {
  1262. ep.Close()
  1263. return nil, fmt.Errorf("netstack: Bind(%v): %v", localAddress, err)
  1264. }
  1265. return gonet.NewUDPConn(&wq, ep), nil
  1266. }
  1267. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  1268. sess := r.ID()
  1269. if debugNetstack() {
  1270. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  1271. }
  1272. var wq waiter.Queue
  1273. ep, err := r.CreateEndpoint(&wq)
  1274. if err != nil {
  1275. ns.logf("acceptUDP: could not create endpoint: %v", err)
  1276. return
  1277. }
  1278. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  1279. if !ok {
  1280. ep.Close()
  1281. return
  1282. }
  1283. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  1284. if !ok {
  1285. ep.Close()
  1286. return
  1287. }
  1288. // Handle magicDNS traffic (via UDP) here.
  1289. if dst := dstAddr.Addr(); dst == serviceIP || dst == serviceIPv6 {
  1290. if dstAddr.Port() != 53 {
  1291. ep.Close()
  1292. return // Only MagicDNS traffic runs on the service IPs for now.
  1293. }
  1294. c := gonet.NewUDPConn(&wq, ep)
  1295. go ns.handleMagicDNSUDP(srcAddr, c)
  1296. return
  1297. }
  1298. if get := ns.GetUDPHandlerForFlow; get != nil {
  1299. h, intercept := get(srcAddr, dstAddr)
  1300. if intercept {
  1301. if h == nil {
  1302. ep.Close()
  1303. return
  1304. }
  1305. go h(gonet.NewUDPConn(&wq, ep))
  1306. return
  1307. }
  1308. }
  1309. c := gonet.NewUDPConn(&wq, ep)
  1310. go ns.forwardUDP(c, srcAddr, dstAddr)
  1311. }
  1312. // Buffer pool for forwarding UDP packets. Implementations are advised not to
  1313. // exceed 512 bytes per DNS request due to fragmenting but in reality can and do
  1314. // send much larger packets, so use the maximum possible UDP packet size.
  1315. var udpBufPool = &sync.Pool{
  1316. New: func() any {
  1317. b := make([]byte, maxUDPPacketSize)
  1318. return &b
  1319. },
  1320. }
  1321. func (ns *Impl) handleMagicDNSUDP(srcAddr netip.AddrPort, c *gonet.UDPConn) {
  1322. // Packets are being generated by the local host, so there should be
  1323. // very, very little latency. 150ms was chosen as something of an upper
  1324. // bound on resource usage, while hopefully still being long enough for
  1325. // a heavily loaded system.
  1326. const readDeadline = 150 * time.Millisecond
  1327. defer c.Close()
  1328. bufp := udpBufPool.Get().(*[]byte)
  1329. defer udpBufPool.Put(bufp)
  1330. q := *bufp
  1331. // libresolv from glibc is quite adamant that transmitting multiple DNS
  1332. // requests down the same UDP socket is valid. To support this, we read
  1333. // in a loop (with a tight deadline so we don't chew too many resources).
  1334. //
  1335. // See: https://github.com/bminor/glibc/blob/f7fbb99652eceb1b6b55e4be931649df5946497c/resolv/res_send.c#L995
  1336. for {
  1337. c.SetReadDeadline(time.Now().Add(readDeadline))
  1338. n, _, err := c.ReadFrom(q)
  1339. if err != nil {
  1340. if oe, ok := err.(*net.OpError); !(ok && oe.Timeout()) {
  1341. ns.logf("dns udp read: %v", err) // log non-timeout errors
  1342. }
  1343. return
  1344. }
  1345. resp, err := ns.dns.Query(context.Background(), q[:n], "udp", srcAddr)
  1346. if err != nil {
  1347. ns.logf("dns udp query: %v", err)
  1348. return
  1349. }
  1350. c.Write(resp)
  1351. }
  1352. }
  1353. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  1354. //
  1355. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  1356. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  1357. // proxy to it directly.
  1358. func (ns *Impl) forwardUDP(client *gonet.UDPConn, clientAddr, dstAddr netip.AddrPort) {
  1359. port, srcPort := dstAddr.Port(), clientAddr.Port()
  1360. if debugNetstack() {
  1361. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  1362. }
  1363. var backendListenAddr *net.UDPAddr
  1364. var backendRemoteAddr *net.UDPAddr
  1365. isLocal := ns.isLocalIP(dstAddr.Addr())
  1366. if isLocal {
  1367. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  1368. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  1369. } else {
  1370. if dstIP := dstAddr.Addr(); viaRange.Contains(dstIP) {
  1371. dstAddr = netip.AddrPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
  1372. }
  1373. backendRemoteAddr = net.UDPAddrFromAddrPort(dstAddr)
  1374. if dstAddr.Addr().Is4() {
  1375. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  1376. } else {
  1377. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  1378. }
  1379. }
  1380. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  1381. if err != nil {
  1382. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  1383. backendListenAddr.Port = 0
  1384. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  1385. if err != nil {
  1386. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  1387. return
  1388. }
  1389. }
  1390. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  1391. backendLocalIPPort := netip.AddrPortFrom(backendListenAddr.AddrPort().Addr().Unmap().WithZone(backendLocalAddr.Zone), backendLocalAddr.AddrPort().Port())
  1392. if !backendLocalIPPort.IsValid() {
  1393. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  1394. }
  1395. if isLocal {
  1396. ns.pm.RegisterIPPortIdentity(backendLocalIPPort, dstAddr.Addr())
  1397. }
  1398. ctx, cancel := context.WithCancel(context.Background())
  1399. idleTimeout := 2 * time.Minute
  1400. if port == 53 {
  1401. // Make DNS packet copies time out much sooner.
  1402. //
  1403. // TODO(bradfitz): make DNS queries over UDP forwarding even
  1404. // cheaper by adding an additional idleTimeout post-DNS-reply.
  1405. // For instance, after the DNS response goes back out, then only
  1406. // wait a few seconds (or zero, really)
  1407. idleTimeout = 30 * time.Second
  1408. }
  1409. timer := time.AfterFunc(idleTimeout, func() {
  1410. if isLocal {
  1411. ns.pm.UnregisterIPPortIdentity(backendLocalIPPort)
  1412. }
  1413. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  1414. cancel()
  1415. client.Close()
  1416. backendConn.Close()
  1417. })
  1418. extend := func() {
  1419. timer.Reset(idleTimeout)
  1420. }
  1421. startPacketCopy(ctx, cancel, client, net.UDPAddrFromAddrPort(clientAddr), backendConn, ns.logf, extend)
  1422. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  1423. if isLocal {
  1424. // Wait for the copies to be done before decrementing the
  1425. // subnet address count to potentially remove the route.
  1426. <-ctx.Done()
  1427. ns.removeSubnetAddress(dstAddr.Addr())
  1428. }
  1429. }
  1430. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  1431. if debugNetstack() {
  1432. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  1433. }
  1434. go func() {
  1435. defer cancel() // tear down the other direction's copy
  1436. bufp := udpBufPool.Get().(*[]byte)
  1437. defer udpBufPool.Put(bufp)
  1438. pkt := *bufp
  1439. for {
  1440. select {
  1441. case <-ctx.Done():
  1442. return
  1443. default:
  1444. n, srcAddr, err := src.ReadFrom(pkt)
  1445. if err != nil {
  1446. if ctx.Err() == nil {
  1447. logf("read packet from %s failed: %v", srcAddr, err)
  1448. }
  1449. return
  1450. }
  1451. _, err = dst.WriteTo(pkt[:n], dstAddr)
  1452. if err != nil {
  1453. if ctx.Err() == nil {
  1454. logf("write packet to %s failed: %v", dstAddr, err)
  1455. }
  1456. return
  1457. }
  1458. if debugNetstack() {
  1459. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  1460. }
  1461. extend()
  1462. }
  1463. }
  1464. }()
  1465. }
  1466. func stringifyTEI(tei stack.TransportEndpointID) string {
  1467. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  1468. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  1469. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  1470. }
  1471. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netip.AddrPort, ok bool) {
  1472. if addr, ok := netip.AddrFromSlice(a.AsSlice()); ok {
  1473. return netip.AddrPortFrom(addr, port), true
  1474. }
  1475. return netip.AddrPort{}, false
  1476. }
  1477. func readStatCounter(sc *tcpip.StatCounter) int64 {
  1478. vv := sc.Value()
  1479. if vv > math.MaxInt64 {
  1480. return int64(math.MaxInt64)
  1481. }
  1482. return int64(vv)
  1483. }
  1484. // ExpVar returns an expvar variable suitable for registering with expvar.Publish.
  1485. func (ns *Impl) ExpVar() expvar.Var {
  1486. m := new(metrics.Set)
  1487. // Global metrics
  1488. stats := ns.ipstack.Stats()
  1489. m.Set("counter_dropped_packets", expvar.Func(func() any {
  1490. return readStatCounter(stats.DroppedPackets)
  1491. }))
  1492. // IP statistics
  1493. ipStats := ns.ipstack.Stats().IP
  1494. ipMetrics := []struct {
  1495. name string
  1496. field *tcpip.StatCounter
  1497. }{
  1498. {"packets_received", ipStats.PacketsReceived},
  1499. {"valid_packets_received", ipStats.ValidPacketsReceived},
  1500. {"disabled_packets_received", ipStats.DisabledPacketsReceived},
  1501. {"invalid_destination_addresses_received", ipStats.InvalidDestinationAddressesReceived},
  1502. {"invalid_source_addresses_received", ipStats.InvalidSourceAddressesReceived},
  1503. {"packets_delivered", ipStats.PacketsDelivered},
  1504. {"packets_sent", ipStats.PacketsSent},
  1505. {"outgoing_packet_errors", ipStats.OutgoingPacketErrors},
  1506. {"malformed_packets_received", ipStats.MalformedPacketsReceived},
  1507. {"malformed_fragments_received", ipStats.MalformedFragmentsReceived},
  1508. {"iptables_prerouting_dropped", ipStats.IPTablesPreroutingDropped},
  1509. {"iptables_input_dropped", ipStats.IPTablesInputDropped},
  1510. {"iptables_forward_dropped", ipStats.IPTablesForwardDropped},
  1511. {"iptables_output_dropped", ipStats.IPTablesOutputDropped},
  1512. {"iptables_postrouting_dropped", ipStats.IPTablesPostroutingDropped},
  1513. {"option_timestamp_received", ipStats.OptionTimestampReceived},
  1514. {"option_record_route_received", ipStats.OptionRecordRouteReceived},
  1515. {"option_router_alert_received", ipStats.OptionRouterAlertReceived},
  1516. {"option_unknown_received", ipStats.OptionUnknownReceived},
  1517. }
  1518. for _, metric := range ipMetrics {
  1519. metric := metric
  1520. m.Set("counter_ip_"+metric.name, expvar.Func(func() any {
  1521. return readStatCounter(metric.field)
  1522. }))
  1523. }
  1524. // IP forwarding statistics
  1525. fwdStats := ipStats.Forwarding
  1526. fwdMetrics := []struct {
  1527. name string
  1528. field *tcpip.StatCounter
  1529. }{
  1530. {"unrouteable", fwdStats.Unrouteable},
  1531. {"exhausted_ttl", fwdStats.ExhaustedTTL},
  1532. {"initializing_source", fwdStats.InitializingSource},
  1533. {"link_local_source", fwdStats.LinkLocalSource},
  1534. {"link_local_destination", fwdStats.LinkLocalDestination},
  1535. {"packet_too_big", fwdStats.PacketTooBig},
  1536. {"host_unreachable", fwdStats.HostUnreachable},
  1537. {"extension_header_problem", fwdStats.ExtensionHeaderProblem},
  1538. {"unexpected_multicast_input_interface", fwdStats.UnexpectedMulticastInputInterface},
  1539. {"unknown_output_endpoint", fwdStats.UnknownOutputEndpoint},
  1540. {"no_multicast_pending_queue_buffer_space", fwdStats.NoMulticastPendingQueueBufferSpace},
  1541. {"outgoing_device_no_buffer_space", fwdStats.OutgoingDeviceNoBufferSpace},
  1542. {"errors", fwdStats.Errors},
  1543. }
  1544. for _, metric := range fwdMetrics {
  1545. metric := metric
  1546. m.Set("counter_ip_forward_"+metric.name, expvar.Func(func() any {
  1547. return readStatCounter(metric.field)
  1548. }))
  1549. }
  1550. // TCP metrics
  1551. tcpStats := ns.ipstack.Stats().TCP
  1552. tcpMetrics := []struct {
  1553. name string
  1554. field *tcpip.StatCounter
  1555. }{
  1556. {"active_connection_openings", tcpStats.ActiveConnectionOpenings},
  1557. {"passive_connection_openings", tcpStats.PassiveConnectionOpenings},
  1558. {"established_resets", tcpStats.EstablishedResets},
  1559. {"established_closed", tcpStats.EstablishedClosed},
  1560. {"established_timeout", tcpStats.EstablishedTimedout},
  1561. {"listen_overflow_syn_drop", tcpStats.ListenOverflowSynDrop},
  1562. {"listen_overflow_ack_drop", tcpStats.ListenOverflowAckDrop},
  1563. {"listen_overflow_syn_cookie_sent", tcpStats.ListenOverflowSynCookieSent},
  1564. {"listen_overflow_syn_cookie_rcvd", tcpStats.ListenOverflowSynCookieRcvd},
  1565. {"listen_overflow_invalid_syn_cookie_rcvd", tcpStats.ListenOverflowInvalidSynCookieRcvd},
  1566. {"failed_connection_attempts", tcpStats.FailedConnectionAttempts},
  1567. {"valid_segments_received", tcpStats.ValidSegmentsReceived},
  1568. {"invalid_segments_received", tcpStats.InvalidSegmentsReceived},
  1569. {"segments_sent", tcpStats.SegmentsSent},
  1570. {"segment_send_errors", tcpStats.SegmentSendErrors},
  1571. {"resets_sent", tcpStats.ResetsSent},
  1572. {"resets_received", tcpStats.ResetsReceived},
  1573. {"retransmits", tcpStats.Retransmits},
  1574. {"fast_recovery", tcpStats.FastRecovery},
  1575. {"sack_recovery", tcpStats.SACKRecovery},
  1576. {"tlp_recovery", tcpStats.TLPRecovery},
  1577. {"slow_start_retransmits", tcpStats.SlowStartRetransmits},
  1578. {"fast_retransmit", tcpStats.FastRetransmit},
  1579. {"timeouts", tcpStats.Timeouts},
  1580. {"checksum_errors", tcpStats.ChecksumErrors},
  1581. {"failed_port_reservations", tcpStats.FailedPortReservations},
  1582. {"segments_acked_with_dsack", tcpStats.SegmentsAckedWithDSACK},
  1583. {"spurious_recovery", tcpStats.SpuriousRecovery},
  1584. {"spurious_rto_recovery", tcpStats.SpuriousRTORecovery},
  1585. {"forward_max_in_flight_drop", tcpStats.ForwardMaxInFlightDrop},
  1586. }
  1587. for _, metric := range tcpMetrics {
  1588. metric := metric
  1589. m.Set("counter_tcp_"+metric.name, expvar.Func(func() any {
  1590. return readStatCounter(metric.field)
  1591. }))
  1592. }
  1593. m.Set("gauge_tcp_current_established", expvar.Func(func() any {
  1594. return readStatCounter(tcpStats.CurrentEstablished)
  1595. }))
  1596. m.Set("gauge_tcp_current_connected", expvar.Func(func() any {
  1597. return readStatCounter(tcpStats.CurrentConnected)
  1598. }))
  1599. // UDP metrics
  1600. udpStats := ns.ipstack.Stats().UDP
  1601. udpMetrics := []struct {
  1602. name string
  1603. field *tcpip.StatCounter
  1604. }{
  1605. {"packets_received", udpStats.PacketsReceived},
  1606. {"unknown_port_errors", udpStats.UnknownPortErrors},
  1607. {"receive_buffer_errors", udpStats.ReceiveBufferErrors},
  1608. {"malformed_packets_received", udpStats.MalformedPacketsReceived},
  1609. {"packets_sent", udpStats.PacketsSent},
  1610. {"packet_send_errors", udpStats.PacketSendErrors},
  1611. {"checksum_errors", udpStats.ChecksumErrors},
  1612. }
  1613. for _, metric := range udpMetrics {
  1614. metric := metric
  1615. m.Set("counter_udp_"+metric.name, expvar.Func(func() any {
  1616. return readStatCounter(metric.field)
  1617. }))
  1618. }
  1619. // Export gauges that show the current TCP forwarding limits.
  1620. m.Set("gauge_tcp_forward_in_flight_limit", expvar.Func(func() any {
  1621. return maxInFlightConnectionAttempts()
  1622. }))
  1623. m.Set("gauge_tcp_forward_in_flight_per_client_limit", expvar.Func(func() any {
  1624. return maxInFlightConnectionAttemptsPerClient()
  1625. }))
  1626. // This metric tracks the number of in-flight TCP forwarding
  1627. // connections that are "in-flight"–i.e. waiting to complete.
  1628. m.Set("gauge_tcp_forward_in_flight", expvar.Func(func() any {
  1629. ns.mu.Lock()
  1630. defer ns.mu.Unlock()
  1631. var sum int64
  1632. for _, n := range ns.connsInFlightByClient {
  1633. sum += int64(n)
  1634. }
  1635. return sum
  1636. }))
  1637. m.Set("counter_tcp_forward_max_in_flight_per_client_drop", &ns.forwardInFlightPerClientDropped)
  1638. // This metric tracks how many (if any) of the per-client limit on
  1639. // in-flight TCP forwarding requests have been reached.
  1640. m.Set("gauge_tcp_forward_in_flight_per_client_limit_reached", expvar.Func(func() any {
  1641. ns.mu.Lock()
  1642. defer ns.mu.Unlock()
  1643. limit := maxInFlightConnectionAttemptsPerClient()
  1644. var count int64
  1645. for _, n := range ns.connsInFlightByClient {
  1646. if n == limit {
  1647. count++
  1648. }
  1649. }
  1650. return count
  1651. }))
  1652. return m
  1653. }