netstack.go 76 KB

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