netstack.go 68 KB

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