netstack.go 62 KB

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