netstack.go 64 KB

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