netstack.go 66 KB

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