netstack.go 68 KB

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