netstack.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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. "fmt"
  10. "io"
  11. "log"
  12. "net"
  13. "net/netip"
  14. "os"
  15. "os/exec"
  16. "runtime"
  17. "strconv"
  18. "sync"
  19. "sync/atomic"
  20. "time"
  21. "gvisor.dev/gvisor/pkg/buffer"
  22. "gvisor.dev/gvisor/pkg/refs"
  23. "gvisor.dev/gvisor/pkg/tcpip"
  24. "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
  25. "gvisor.dev/gvisor/pkg/tcpip/header"
  26. "gvisor.dev/gvisor/pkg/tcpip/link/channel"
  27. "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
  28. "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
  29. "gvisor.dev/gvisor/pkg/tcpip/stack"
  30. "gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
  31. "gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
  32. "gvisor.dev/gvisor/pkg/tcpip/transport/udp"
  33. "gvisor.dev/gvisor/pkg/waiter"
  34. "tailscale.com/envknob"
  35. "tailscale.com/ipn/ipnlocal"
  36. "tailscale.com/net/dns"
  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/version/distro"
  50. "tailscale.com/wgengine"
  51. "tailscale.com/wgengine/filter"
  52. "tailscale.com/wgengine/magicsock"
  53. )
  54. const debugPackets = false
  55. var debugNetstack = envknob.RegisterBool("TS_DEBUG_NETSTACK")
  56. var (
  57. magicDNSIP = tsaddr.TailscaleServiceIP()
  58. magicDNSIPv6 = tsaddr.TailscaleServiceIPv6()
  59. )
  60. func init() {
  61. mode := envknob.String("TS_DEBUG_NETSTACK_LEAK_MODE")
  62. if mode == "" {
  63. return
  64. }
  65. var lm refs.LeakMode
  66. if err := lm.Set(mode); err != nil {
  67. panic(err)
  68. }
  69. refs.SetLeakMode(lm)
  70. }
  71. // Impl contains the state for the netstack implementation,
  72. // and implements wgengine.FakeImpl to act as a userspace network
  73. // stack when Tailscale is running in fake mode.
  74. type Impl struct {
  75. // GetTCPHandlerForFlow conditionally handles an incoming TCP flow for the
  76. // provided (src/port, dst/port) 4-tuple.
  77. //
  78. // A nil value is equivalent to a func returning (nil, false).
  79. //
  80. // If func returns intercept=false, the default forwarding behavior (if
  81. // ProcessLocalIPs and/or ProcesssSubnetIPs) takes place.
  82. //
  83. // When intercept=true, the behavior depends on whether the returned handler
  84. // is non-nil: if nil, the connection is rejected. If non-nil, handler takes
  85. // over the TCP conn.
  86. GetTCPHandlerForFlow func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool)
  87. // GetUDPHandlerForFlow conditionally handles an incoming UDP flow for the
  88. // provided (src/port, dst/port) 4-tuple.
  89. //
  90. // A nil value is equivalent to a func returning (nil, false).
  91. //
  92. // If func returns intercept=false, the default forwarding behavior (if
  93. // ProcessLocalIPs and/or ProcesssSubnetIPs) takes place.
  94. //
  95. // When intercept=true, the behavior depends on whether the returned handler
  96. // is non-nil: if nil, the connection is rejected. If non-nil, handler takes
  97. // over the UDP flow.
  98. GetUDPHandlerForFlow func(src, dst netip.AddrPort) (handler func(nettype.ConnPacketConn), intercept bool)
  99. // ProcessLocalIPs is whether netstack should handle incoming
  100. // traffic directed at the Node.Addresses (local IPs).
  101. // It can only be set before calling Start.
  102. ProcessLocalIPs bool
  103. // ProcessSubnets is whether netstack should handle incoming
  104. // traffic destined to non-local IPs (i.e. whether it should
  105. // be a subnet router).
  106. // It can only be set before calling Start.
  107. ProcessSubnets bool
  108. ipstack *stack.Stack
  109. linkEP *channel.Endpoint
  110. tundev *tstun.Wrapper
  111. e wgengine.Engine
  112. pm *proxymap.Mapper
  113. mc *magicsock.Conn
  114. logf logger.Logf
  115. dialer *tsdial.Dialer
  116. ctx context.Context // alive until Close
  117. ctxCancel context.CancelFunc // called on Close
  118. lb *ipnlocal.LocalBackend // or nil
  119. dns *dns.Manager
  120. peerapiPort4Atomic atomic.Uint32 // uint16 port number for IPv4 peerapi
  121. peerapiPort6Atomic atomic.Uint32 // uint16 port number for IPv6 peerapi
  122. // atomicIsLocalIPFunc holds a func that reports whether an IP
  123. // is a local (non-subnet) Tailscale IP address of this
  124. // machine. It's always a non-nil func. It's changed on netmap
  125. // updates.
  126. atomicIsLocalIPFunc syncs.AtomicValue[func(netip.Addr) bool]
  127. mu sync.Mutex
  128. // connsOpenBySubnetIP keeps track of number of connections open
  129. // for each subnet IP temporarily registered on netstack for active
  130. // TCP connections, so they can be unregistered when connections are
  131. // closed.
  132. connsOpenBySubnetIP map[netip.Addr]int
  133. }
  134. const nicID = 1
  135. // maxUDPPacketSize is the maximum size of a UDP packet we copy in
  136. // startPacketCopy when relaying UDP packets. The user can configure
  137. // the tailscale MTU to anything up to this size so we can potentially
  138. // have a UDP packet as big as the MTU.
  139. const maxUDPPacketSize = tstun.MaxPacketSize
  140. // Create creates and populates a new Impl.
  141. 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) {
  142. if mc == nil {
  143. return nil, errors.New("nil magicsock.Conn")
  144. }
  145. if tundev == nil {
  146. return nil, errors.New("nil tundev")
  147. }
  148. if logf == nil {
  149. return nil, errors.New("nil logger")
  150. }
  151. if e == nil {
  152. return nil, errors.New("nil Engine")
  153. }
  154. if pm == nil {
  155. return nil, errors.New("nil proxymap.Mapper")
  156. }
  157. if dialer == nil {
  158. return nil, errors.New("nil Dialer")
  159. }
  160. ipstack := stack.New(stack.Options{
  161. NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
  162. TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
  163. })
  164. sackEnabledOpt := tcpip.TCPSACKEnabled(true) // TCP SACK is disabled by default
  165. tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt)
  166. if tcpipErr != nil {
  167. return nil, fmt.Errorf("could not enable TCP SACK: %v", tcpipErr)
  168. }
  169. if runtime.GOOS == "windows" {
  170. // See https://github.com/tailscale/tailscale/issues/9707
  171. // Windows w/RACK performs poorly. ACKs do not appear to be handled in a
  172. // timely manner, leading to spurious retransmissions and a reduced
  173. // congestion window.
  174. tcpRecoveryOpt := tcpip.TCPRecovery(0)
  175. tcpipErr = ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpRecoveryOpt)
  176. if tcpipErr != nil {
  177. return nil, fmt.Errorf("could not disable TCP RACK: %v", tcpipErr)
  178. }
  179. }
  180. linkEP := channel.New(512, uint32(tstun.DefaultTUNMTU()), "")
  181. if tcpipProblem := ipstack.CreateNIC(nicID, linkEP); tcpipProblem != nil {
  182. return nil, fmt.Errorf("could not create netstack NIC: %v", tcpipProblem)
  183. }
  184. // By default the netstack NIC will only accept packets for the IPs
  185. // registered to it. Since in some cases we dynamically register IPs
  186. // based on the packets that arrive, the NIC needs to accept all
  187. // incoming packets. The NIC won't receive anything it isn't meant to
  188. // since WireGuard will only send us packets that are meant for us.
  189. ipstack.SetPromiscuousMode(nicID, true)
  190. // Add IPv4 and IPv6 default routes, so all incoming packets from the Tailscale side
  191. // are handled by the one fake NIC we use.
  192. ipv4Subnet, err := tcpip.NewSubnet(tcpip.AddrFromSlice(make([]byte, 4)), tcpip.MaskFromBytes(make([]byte, 4)))
  193. if err != nil {
  194. return nil, fmt.Errorf("could not create IPv4 subnet: %v", err)
  195. }
  196. ipv6Subnet, err := tcpip.NewSubnet(tcpip.AddrFromSlice(make([]byte, 16)), tcpip.MaskFromBytes(make([]byte, 16)))
  197. if err != nil {
  198. return nil, fmt.Errorf("could not create IPv6 subnet: %v", err)
  199. }
  200. ipstack.SetRouteTable([]tcpip.Route{
  201. {
  202. Destination: ipv4Subnet,
  203. NIC: nicID,
  204. },
  205. {
  206. Destination: ipv6Subnet,
  207. NIC: nicID,
  208. },
  209. })
  210. ns := &Impl{
  211. logf: logf,
  212. ipstack: ipstack,
  213. linkEP: linkEP,
  214. tundev: tundev,
  215. e: e,
  216. pm: pm,
  217. mc: mc,
  218. dialer: dialer,
  219. connsOpenBySubnetIP: make(map[netip.Addr]int),
  220. dns: dns,
  221. }
  222. ns.ctx, ns.ctxCancel = context.WithCancel(context.Background())
  223. ns.atomicIsLocalIPFunc.Store(tsaddr.FalseContainsIPFunc())
  224. ns.tundev.PostFilterPacketInboundFromWireGaurd = ns.injectInbound
  225. ns.tundev.PreFilterPacketOutboundToWireGuardNetstackIntercept = ns.handleLocalPackets
  226. return ns, nil
  227. }
  228. func (ns *Impl) Close() error {
  229. ns.ctxCancel()
  230. ns.ipstack.Close()
  231. ns.ipstack.Wait()
  232. return nil
  233. }
  234. // wrapProtoHandler returns protocol handler h wrapped in a version
  235. // that dynamically reconfigures ns's subnet addresses as needed for
  236. // outbound traffic.
  237. func (ns *Impl) wrapProtoHandler(h func(stack.TransportEndpointID, stack.PacketBufferPtr) bool) func(stack.TransportEndpointID, stack.PacketBufferPtr) bool {
  238. return func(tei stack.TransportEndpointID, pb stack.PacketBufferPtr) bool {
  239. addr := tei.LocalAddress
  240. ip, ok := netip.AddrFromSlice(addr.AsSlice())
  241. if !ok {
  242. ns.logf("netstack: could not parse local address for incoming connection")
  243. return false
  244. }
  245. ip = ip.Unmap()
  246. if !ns.isLocalIP(ip) {
  247. ns.addSubnetAddress(ip)
  248. }
  249. return h(tei, pb)
  250. }
  251. }
  252. // Start sets up all the handlers so netstack can start working. Implements
  253. // wgengine.FakeImpl.
  254. func (ns *Impl) Start(lb *ipnlocal.LocalBackend) error {
  255. if lb == nil {
  256. panic("nil LocalBackend")
  257. }
  258. ns.lb = lb
  259. // size = 0 means use default buffer size
  260. const tcpReceiveBufferSize = 0
  261. const maxInFlightConnectionAttempts = 1024
  262. tcpFwd := tcp.NewForwarder(ns.ipstack, tcpReceiveBufferSize, maxInFlightConnectionAttempts, ns.acceptTCP)
  263. udpFwd := udp.NewForwarder(ns.ipstack, ns.acceptUDP)
  264. ns.ipstack.SetTransportProtocolHandler(tcp.ProtocolNumber, ns.wrapProtoHandler(tcpFwd.HandlePacket))
  265. ns.ipstack.SetTransportProtocolHandler(udp.ProtocolNumber, ns.wrapProtoHandler(udpFwd.HandlePacket))
  266. go ns.inject()
  267. return nil
  268. }
  269. func (ns *Impl) addSubnetAddress(ip netip.Addr) {
  270. ns.mu.Lock()
  271. ns.connsOpenBySubnetIP[ip]++
  272. needAdd := ns.connsOpenBySubnetIP[ip] == 1
  273. ns.mu.Unlock()
  274. // Only register address into netstack for first concurrent connection.
  275. if needAdd {
  276. pa := tcpip.ProtocolAddress{
  277. AddressWithPrefix: tcpip.AddrFromSlice(ip.AsSlice()).WithPrefix(),
  278. }
  279. if ip.Is4() {
  280. pa.Protocol = ipv4.ProtocolNumber
  281. } else if ip.Is6() {
  282. pa.Protocol = ipv6.ProtocolNumber
  283. }
  284. ns.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{
  285. PEB: stack.CanBePrimaryEndpoint, // zero value default
  286. ConfigType: stack.AddressConfigStatic, // zero value default
  287. })
  288. }
  289. }
  290. func (ns *Impl) removeSubnetAddress(ip netip.Addr) {
  291. ns.mu.Lock()
  292. defer ns.mu.Unlock()
  293. ns.connsOpenBySubnetIP[ip]--
  294. // Only unregister address from netstack after last concurrent connection.
  295. if ns.connsOpenBySubnetIP[ip] == 0 {
  296. ns.ipstack.RemoveAddress(nicID, tcpip.AddrFromSlice(ip.AsSlice()))
  297. delete(ns.connsOpenBySubnetIP, ip)
  298. }
  299. }
  300. func ipPrefixToAddressWithPrefix(ipp netip.Prefix) tcpip.AddressWithPrefix {
  301. return tcpip.AddressWithPrefix{
  302. Address: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  303. PrefixLen: int(ipp.Bits()),
  304. }
  305. }
  306. var v4broadcast = netaddr.IPv4(255, 255, 255, 255)
  307. // UpdateNetstackIPs updates the set of local IPs that netstack should handle
  308. // from nm.
  309. //
  310. // TODO(bradfitz): don't pass the whole netmap here; just pass the two
  311. // address slice views.
  312. func (ns *Impl) UpdateNetstackIPs(nm *netmap.NetworkMap) {
  313. var selfNode tailcfg.NodeView
  314. if nm != nil {
  315. ns.atomicIsLocalIPFunc.Store(tsaddr.NewContainsIPFunc(nm.GetAddresses()))
  316. selfNode = nm.SelfNode
  317. } else {
  318. ns.atomicIsLocalIPFunc.Store(tsaddr.FalseContainsIPFunc())
  319. }
  320. oldPfx := make(map[netip.Prefix]bool)
  321. for _, protocolAddr := range ns.ipstack.AllAddresses()[nicID] {
  322. ap := protocolAddr.AddressWithPrefix
  323. ip := netaddrIPFromNetstackIP(ap.Address)
  324. if ip == v4broadcast && ap.PrefixLen == 32 {
  325. // Don't add 255.255.255.255/32 to oldIPs so we don't
  326. // delete it later. We didn't install it, so it's not
  327. // ours to delete.
  328. continue
  329. }
  330. p := netip.PrefixFrom(ip, ap.PrefixLen)
  331. oldPfx[p] = true
  332. }
  333. newPfx := make(map[netip.Prefix]bool)
  334. if selfNode.Valid() {
  335. for i := range selfNode.Addresses().LenIter() {
  336. p := selfNode.Addresses().At(i)
  337. newPfx[p] = true
  338. }
  339. if ns.ProcessSubnets {
  340. for i := range selfNode.AllowedIPs().LenIter() {
  341. p := selfNode.AllowedIPs().At(i)
  342. newPfx[p] = true
  343. }
  344. }
  345. }
  346. pfxToAdd := make(map[netip.Prefix]bool)
  347. for p := range newPfx {
  348. if !oldPfx[p] {
  349. pfxToAdd[p] = true
  350. }
  351. }
  352. pfxToRemove := make(map[netip.Prefix]bool)
  353. for p := range oldPfx {
  354. if !newPfx[p] {
  355. pfxToRemove[p] = true
  356. }
  357. }
  358. ns.mu.Lock()
  359. for ip := range ns.connsOpenBySubnetIP {
  360. // TODO(maisem): this looks like a bug, remove or document. It seems as
  361. // though we might end up either leaking the address on the netstack
  362. // NIC, or where we do accounting for connsOpenBySubnetIP from 1 to 0,
  363. // we might end up removing the address from the netstack NIC that was
  364. // still being advertised.
  365. delete(pfxToRemove, netip.PrefixFrom(ip, ip.BitLen()))
  366. }
  367. ns.mu.Unlock()
  368. for p := range pfxToRemove {
  369. err := ns.ipstack.RemoveAddress(nicID, tcpip.AddrFromSlice(p.Addr().AsSlice()))
  370. if err != nil {
  371. ns.logf("netstack: could not deregister IP %s: %v", p, err)
  372. } else {
  373. ns.logf("[v2] netstack: deregistered IP %s", p)
  374. }
  375. }
  376. for p := range pfxToAdd {
  377. if !p.IsValid() {
  378. ns.logf("netstack: [unexpected] skipping invalid IP (%v/%v)", p.Addr(), p.Bits())
  379. continue
  380. }
  381. tcpAddr := tcpip.ProtocolAddress{
  382. AddressWithPrefix: ipPrefixToAddressWithPrefix(p),
  383. }
  384. if p.Addr().Is6() {
  385. tcpAddr.Protocol = ipv6.ProtocolNumber
  386. } else {
  387. tcpAddr.Protocol = ipv4.ProtocolNumber
  388. }
  389. var tcpErr tcpip.Error // not error
  390. tcpErr = ns.ipstack.AddProtocolAddress(nicID, tcpAddr, stack.AddressProperties{
  391. PEB: stack.CanBePrimaryEndpoint, // zero value default
  392. ConfigType: stack.AddressConfigStatic, // zero value default
  393. })
  394. if tcpErr != nil {
  395. ns.logf("netstack: could not register IP %s: %v", p, tcpErr)
  396. } else {
  397. ns.logf("[v2] netstack: registered IP %s", p)
  398. }
  399. }
  400. }
  401. // handleLocalPackets is hooked into the tun datapath for packets leaving
  402. // the host and arriving at tailscaled. This method returns filter.DropSilently
  403. // to intercept a packet for handling, for instance traffic to quad-100.
  404. func (ns *Impl) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  405. if ns.ctx.Err() != nil {
  406. return filter.DropSilently
  407. }
  408. // If it's not traffic to the service IP (i.e. magicDNS) we don't
  409. // care; resume processing.
  410. if dst := p.Dst.Addr(); dst != magicDNSIP && dst != magicDNSIPv6 {
  411. return filter.Accept
  412. }
  413. // Of traffic to the service IP, we only care about UDP 53, and TCP
  414. // on port 80 & 53.
  415. switch p.IPProto {
  416. case ipproto.TCP:
  417. if port := p.Dst.Port(); port != 53 && port != 80 {
  418. return filter.Accept
  419. }
  420. case ipproto.UDP:
  421. if port := p.Dst.Port(); port != 53 {
  422. return filter.Accept
  423. }
  424. }
  425. var pn tcpip.NetworkProtocolNumber
  426. switch p.IPVersion {
  427. case 4:
  428. pn = header.IPv4ProtocolNumber
  429. case 6:
  430. pn = header.IPv6ProtocolNumber
  431. }
  432. if debugPackets {
  433. ns.logf("[v2] service packet in (from %v): % x", p.Src, p.Buffer())
  434. }
  435. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  436. Payload: buffer.MakeWithData(bytes.Clone(p.Buffer())),
  437. })
  438. ns.linkEP.InjectInbound(pn, packetBuf)
  439. packetBuf.DecRef()
  440. return filter.DropSilently
  441. }
  442. func (ns *Impl) DialContextTCP(ctx context.Context, ipp netip.AddrPort) (*gonet.TCPConn, error) {
  443. remoteAddress := tcpip.FullAddress{
  444. NIC: nicID,
  445. Addr: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  446. Port: ipp.Port(),
  447. }
  448. var ipType tcpip.NetworkProtocolNumber
  449. if ipp.Addr().Is4() {
  450. ipType = ipv4.ProtocolNumber
  451. } else {
  452. ipType = ipv6.ProtocolNumber
  453. }
  454. return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
  455. }
  456. func (ns *Impl) DialContextUDP(ctx context.Context, ipp netip.AddrPort) (*gonet.UDPConn, error) {
  457. remoteAddress := &tcpip.FullAddress{
  458. NIC: nicID,
  459. Addr: tcpip.AddrFromSlice(ipp.Addr().AsSlice()),
  460. Port: ipp.Port(),
  461. }
  462. var ipType tcpip.NetworkProtocolNumber
  463. if ipp.Addr().Is4() {
  464. ipType = ipv4.ProtocolNumber
  465. } else {
  466. ipType = ipv6.ProtocolNumber
  467. }
  468. return gonet.DialUDP(ns.ipstack, nil, remoteAddress, ipType)
  469. }
  470. // The inject goroutine reads in packets that netstack generated, and delivers
  471. // them to the correct path.
  472. func (ns *Impl) inject() {
  473. for {
  474. pkt := ns.linkEP.ReadContext(ns.ctx)
  475. if pkt.IsNil() {
  476. if ns.ctx.Err() != nil {
  477. // Return without logging.
  478. return
  479. }
  480. ns.logf("[v2] ReadContext-for-write = ok=false")
  481. continue
  482. }
  483. if debugPackets {
  484. ns.logf("[v2] packet Write out: % x", stack.PayloadSince(pkt.NetworkHeader()))
  485. }
  486. // In the normal case, netstack synthesizes the bytes for
  487. // traffic which should transit back into WG and go to peers.
  488. // However, some uses of netstack (presently, magic DNS)
  489. // send traffic destined for the local device, hence must
  490. // be injected 'inbound'.
  491. sendToHost := false
  492. // Determine if the packet is from a service IP, in which case it
  493. // needs to go back into the machines network (inbound) instead of
  494. // out.
  495. // TODO(tom): Work out a way to avoid parsing packets to determine if
  496. // its from the service IP. Maybe gvisor netstack magic. I
  497. // went through the fields of PacketBuffer, and nop :/
  498. // TODO(tom): Figure out if its safe to modify packet.Parsed to fill in
  499. // the IP src/dest even if its missing the rest of the pkt.
  500. // That way we dont have to do this twitchy-af byte-yeeting.
  501. if b := pkt.NetworkHeader().Slice(); len(b) >= 20 { // min ipv4 header
  502. switch b[0] >> 4 { // ip proto field
  503. case 4:
  504. if srcIP := netaddr.IPv4(b[12], b[13], b[14], b[15]); magicDNSIP == srcIP {
  505. sendToHost = true
  506. }
  507. case 6:
  508. if len(b) >= 40 { // min ipv6 header
  509. if srcIP, ok := netip.AddrFromSlice(net.IP(b[8:24])); ok && magicDNSIPv6 == srcIP {
  510. sendToHost = true
  511. }
  512. }
  513. }
  514. }
  515. // pkt has a non-zero refcount, so injection methods takes
  516. // ownership of one count and will decrement on completion.
  517. if sendToHost {
  518. if err := ns.tundev.InjectInboundPacketBuffer(pkt); err != nil {
  519. log.Printf("netstack inject inbound: %v", err)
  520. return
  521. }
  522. } else {
  523. if err := ns.tundev.InjectOutboundPacketBuffer(pkt); err != nil {
  524. log.Printf("netstack inject outbound: %v", err)
  525. return
  526. }
  527. }
  528. }
  529. }
  530. // isLocalIP reports whether ip is a Tailscale IP assigned to this
  531. // node directly (but not a subnet-routed IP).
  532. func (ns *Impl) isLocalIP(ip netip.Addr) bool {
  533. return ns.atomicIsLocalIPFunc.Load()(ip)
  534. }
  535. func (ns *Impl) peerAPIPortAtomic(ip netip.Addr) *atomic.Uint32 {
  536. if ip.Is4() {
  537. return &ns.peerapiPort4Atomic
  538. } else {
  539. return &ns.peerapiPort6Atomic
  540. }
  541. }
  542. var viaRange = tsaddr.TailscaleViaRange()
  543. // shouldProcessInbound reports whether an inbound packet (a packet from a
  544. // WireGuard peer) should be handled by netstack.
  545. func (ns *Impl) shouldProcessInbound(p *packet.Parsed, t *tstun.Wrapper) bool {
  546. // Handle incoming peerapi connections in netstack.
  547. dstIP := p.Dst.Addr()
  548. isLocal := ns.isLocalIP(dstIP)
  549. // Handle TCP connection to the Tailscale IP(s) in some cases:
  550. if ns.lb != nil && p.IPProto == ipproto.TCP && isLocal {
  551. var peerAPIPort uint16
  552. if p.TCPFlags&packet.TCPSynAck == packet.TCPSyn {
  553. if port, ok := ns.lb.GetPeerAPIPort(dstIP); ok {
  554. peerAPIPort = port
  555. ns.peerAPIPortAtomic(dstIP).Store(uint32(port))
  556. }
  557. } else {
  558. peerAPIPort = uint16(ns.peerAPIPortAtomic(dstIP).Load())
  559. }
  560. dport := p.Dst.Port()
  561. if dport == peerAPIPort {
  562. return true
  563. }
  564. // Also handle SSH connections, webserver, etc, if enabled:
  565. if ns.lb.ShouldInterceptTCPPort(dport) {
  566. return true
  567. }
  568. }
  569. if p.IPVersion == 6 && !isLocal && viaRange.Contains(dstIP) {
  570. return ns.lb != nil && ns.lb.ShouldHandleViaIP(dstIP)
  571. }
  572. if ns.ProcessLocalIPs && isLocal {
  573. return true
  574. }
  575. if ns.ProcessSubnets && !isLocal {
  576. return true
  577. }
  578. return false
  579. }
  580. // setAmbientCapsRaw is non-nil on Linux for Synology, to run ping with
  581. // CAP_NET_RAW from tailscaled's binary.
  582. var setAmbientCapsRaw func(*exec.Cmd)
  583. var userPingSem = syncs.NewSemaphore(20) // 20 child ping processes at once
  584. var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
  585. // userPing tried to ping dstIP and if it succeeds, injects pingResPkt
  586. // into the tundev.
  587. //
  588. // It's used in userspace/netstack mode when we don't have kernel
  589. // support or raw socket access. As such, this does the dumbest thing
  590. // that can work: runs the ping command. It's not super efficient, so
  591. // it bounds the number of pings going on at once. The idea is that
  592. // people only use ping occasionally to see if their internet's working
  593. // so this doesn't need to be great.
  594. //
  595. // TODO(bradfitz): when we're running on Windows as the system user, use
  596. // raw socket APIs instead of ping child processes.
  597. func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte) {
  598. if !userPingSem.TryAcquire() {
  599. return
  600. }
  601. defer userPingSem.Release()
  602. t0 := time.Now()
  603. var err error
  604. switch runtime.GOOS {
  605. case "windows":
  606. err = exec.Command("ping", "-n", "1", "-w", "3000", dstIP.String()).Run()
  607. case "darwin", "freebsd":
  608. // Note: 2000 ms is actually 1 second + 2,000
  609. // milliseconds extra for 3 seconds total.
  610. // See https://github.com/tailscale/tailscale/pull/3753 for details.
  611. ping := "ping"
  612. if dstIP.Is6() {
  613. ping = "ping6"
  614. }
  615. err = exec.Command(ping, "-c", "1", "-W", "2000", dstIP.String()).Run()
  616. case "openbsd":
  617. ping := "ping"
  618. if dstIP.Is6() {
  619. ping = "ping6"
  620. }
  621. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  622. case "android":
  623. ping := "/system/bin/ping"
  624. if dstIP.Is6() {
  625. ping = "/system/bin/ping6"
  626. }
  627. err = exec.Command(ping, "-c", "1", "-w", "3", dstIP.String()).Run()
  628. default:
  629. ping := "ping"
  630. if isSynology {
  631. ping = "/bin/ping"
  632. }
  633. cmd := exec.Command(ping, "-c", "1", "-W", "3", dstIP.String())
  634. if isSynology && os.Getuid() != 0 {
  635. // On DSM7 we run as non-root and need to pass
  636. // CAP_NET_RAW if our binary has it.
  637. setAmbientCapsRaw(cmd)
  638. }
  639. err = cmd.Run()
  640. }
  641. d := time.Since(t0)
  642. if err != nil {
  643. if d < time.Second/2 {
  644. // If it failed quicker than the 3 second
  645. // timeout we gave above (500 ms is a
  646. // reasonable threshold), then assume the ping
  647. // failed for problems finding/running
  648. // ping. We don't want to log if the host is
  649. // just down.
  650. ns.logf("exec ping of %v failed in %v: %v", dstIP, d, err)
  651. }
  652. return
  653. }
  654. if debugNetstack() {
  655. ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
  656. }
  657. if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
  658. ns.logf("InjectOutbound ping response: %v", err)
  659. }
  660. }
  661. // injectInbound is installed as a packet hook on the 'inbound' (from a
  662. // WireGuard peer) path. Returning filter.Accept releases the packet to
  663. // continue normally (typically being delivered to the host networking stack),
  664. // whereas returning filter.DropSilently is done when netstack intercepts the
  665. // packet and no further processing towards to host should be done.
  666. func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
  667. if ns.ctx.Err() != nil {
  668. return filter.DropSilently
  669. }
  670. if !ns.shouldProcessInbound(p, t) {
  671. // Let the host network stack (if any) deal with it.
  672. return filter.Accept
  673. }
  674. destIP := p.Dst.Addr()
  675. // If this is an echo request and we're a subnet router, handle pings
  676. // ourselves instead of forwarding the packet on.
  677. pingIP, handlePing := ns.shouldHandlePing(p)
  678. if handlePing {
  679. var pong []byte // the reply to the ping, if our relayed ping works
  680. if destIP.Is4() {
  681. h := p.ICMP4Header()
  682. h.ToResponse()
  683. pong = packet.Generate(&h, p.Payload())
  684. } else if destIP.Is6() {
  685. h := p.ICMP6Header()
  686. h.ToResponse()
  687. pong = packet.Generate(&h, p.Payload())
  688. }
  689. go ns.userPing(pingIP, pong)
  690. return filter.DropSilently
  691. }
  692. var pn tcpip.NetworkProtocolNumber
  693. switch p.IPVersion {
  694. case 4:
  695. pn = header.IPv4ProtocolNumber
  696. case 6:
  697. pn = header.IPv6ProtocolNumber
  698. }
  699. if debugPackets {
  700. ns.logf("[v2] packet in (from %v): % x", p.Src, p.Buffer())
  701. }
  702. packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{
  703. Payload: buffer.MakeWithData(bytes.Clone(p.Buffer())),
  704. })
  705. ns.linkEP.InjectInbound(pn, packetBuf)
  706. packetBuf.DecRef()
  707. // We've now delivered this to netstack, so we're done.
  708. // Instead of returning a filter.Accept here (which would also
  709. // potentially deliver it to the host OS), and instead of
  710. // filter.Drop (which would log about rejected traffic),
  711. // instead return filter.DropSilently which just quietly stops
  712. // processing it in the tstun TUN wrapper.
  713. return filter.DropSilently
  714. }
  715. // shouldHandlePing returns whether or not netstack should handle an incoming
  716. // ICMP echo request packet, and the IP address that should be pinged from this
  717. // process. The IP address can be different from the destination in the packet
  718. // if the destination is a 4via6 address.
  719. func (ns *Impl) shouldHandlePing(p *packet.Parsed) (_ netip.Addr, ok bool) {
  720. if !p.IsEchoRequest() {
  721. return netip.Addr{}, false
  722. }
  723. destIP := p.Dst.Addr()
  724. // We need to handle pings for all 4via6 addresses, even if this
  725. // netstack instance normally isn't responsible for processing subnets.
  726. //
  727. // For example, on Linux, subnet router traffic could be handled via
  728. // tun+iptables rules for most packets, but we still need to handle
  729. // ICMP echo requests over 4via6 since the host networking stack
  730. // doesn't know what to do with a 4via6 address.
  731. //
  732. // shouldProcessInbound returns 'true' to say that we should process
  733. // all IPv6 packets with a destination address in the 'via' range, so
  734. // check before we check the "ProcessSubnets" boolean below.
  735. if viaRange.Contains(destIP) {
  736. // The input echo request was to a 4via6 address, which we cannot
  737. // simply ping as-is from this process. Translate the destination to an
  738. // IPv4 address, so that our relayed ping (in userPing) is pinging the
  739. // underlying destination IP.
  740. //
  741. // ICMPv4 and ICMPv6 are different protocols with different on-the-wire
  742. // representations, so normally you can't send an ICMPv6 message over
  743. // IPv4 and expect to get a useful result. However, in this specific
  744. // case things are safe because the 'userPing' function doesn't make
  745. // use of the input packet.
  746. return tsaddr.UnmapVia(destIP), true
  747. }
  748. // If we get here, we don't do anything unless this netstack instance
  749. // is responsible for processing subnet traffic.
  750. if !ns.ProcessSubnets {
  751. return netip.Addr{}, false
  752. }
  753. // For non-4via6 addresses, we don't handle pings if they're destined
  754. // for a Tailscale IP.
  755. if tsaddr.IsTailscaleIP(destIP) {
  756. return netip.Addr{}, false
  757. }
  758. // This netstack instance is processing subnet traffic, so handle the
  759. // ping ourselves.
  760. return destIP, true
  761. }
  762. func netaddrIPFromNetstackIP(s tcpip.Address) netip.Addr {
  763. switch s.Len() {
  764. case 4:
  765. s := s.As4()
  766. return netaddr.IPv4(s[0], s[1], s[2], s[3])
  767. case 16:
  768. s := s.As16()
  769. return netip.AddrFrom16(s).Unmap()
  770. }
  771. return netip.Addr{}
  772. }
  773. func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
  774. reqDetails := r.ID()
  775. if debugNetstack() {
  776. ns.logf("[v2] TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  777. }
  778. clientRemoteIP := netaddrIPFromNetstackIP(reqDetails.RemoteAddress)
  779. if !clientRemoteIP.IsValid() {
  780. ns.logf("invalid RemoteAddress in TCP ForwarderRequest: %s", stringifyTEI(reqDetails))
  781. r.Complete(true) // sends a RST
  782. return
  783. }
  784. clientRemotePort := reqDetails.RemotePort
  785. clientRemoteAddrPort := netip.AddrPortFrom(clientRemoteIP, clientRemotePort)
  786. dialIP := netaddrIPFromNetstackIP(reqDetails.LocalAddress)
  787. isTailscaleIP := tsaddr.IsTailscaleIP(dialIP)
  788. dstAddrPort := netip.AddrPortFrom(dialIP, reqDetails.LocalPort)
  789. if viaRange.Contains(dialIP) {
  790. isTailscaleIP = false
  791. dialIP = tsaddr.UnmapVia(dialIP)
  792. }
  793. defer func() {
  794. if !isTailscaleIP {
  795. // if this is a subnet IP, we added this in before the TCP handshake
  796. // so netstack is happy TCP-handshaking as a subnet IP
  797. ns.removeSubnetAddress(dialIP)
  798. }
  799. }()
  800. var wq waiter.Queue
  801. // We can't actually create the endpoint or complete the inbound
  802. // request until we're sure that the connection can be handled by this
  803. // endpoint. This function sets up the TCP connection and should be
  804. // called immediately before a connection is handled.
  805. getConnOrReset := func(opts ...tcpip.SettableSocketOption) *gonet.TCPConn {
  806. ep, err := r.CreateEndpoint(&wq)
  807. if err != nil {
  808. ns.logf("CreateEndpoint error for %s: %v", stringifyTEI(reqDetails), err)
  809. r.Complete(true) // sends a RST
  810. return nil
  811. }
  812. r.Complete(false)
  813. for _, opt := range opts {
  814. ep.SetSockOpt(opt)
  815. }
  816. // SetKeepAlive so that idle connections to peers that have forgotten about
  817. // the connection or gone completely offline eventually time out.
  818. // Applications might be setting this on a forwarded connection, but from
  819. // userspace we can not see those, so the best we can do is to always
  820. // perform them with conservative timing.
  821. // TODO(tailscale/tailscale#4522): Netstack defaults match the Linux
  822. // defaults, and results in a little over two hours before the socket would
  823. // be closed due to keepalive. A shorter default might be better, or seeking
  824. // a default from the host IP stack. This also might be a useful
  825. // user-tunable, as in userspace mode this can have broad implications such
  826. // as lingering connections to fork style daemons. On the other side of the
  827. // fence, the long duration timers are low impact values for battery powered
  828. // peers.
  829. ep.SocketOptions().SetKeepAlive(true)
  830. // The ForwarderRequest.CreateEndpoint above asynchronously
  831. // starts the TCP handshake. Note that the gonet.TCPConn
  832. // methods c.RemoteAddr() and c.LocalAddr() will return nil
  833. // until the handshake actually completes. But we have the
  834. // remote address in reqDetails instead, so we don't use
  835. // gonet.TCPConn.RemoteAddr. The byte copies in both
  836. // directions to/from the gonet.TCPConn in forwardTCP will
  837. // block until the TCP handshake is complete.
  838. return gonet.NewTCPConn(&wq, ep)
  839. }
  840. // DNS
  841. if reqDetails.LocalPort == 53 && (dialIP == magicDNSIP || dialIP == magicDNSIPv6) {
  842. c := getConnOrReset()
  843. if c == nil {
  844. return
  845. }
  846. go ns.dns.HandleTCPConn(c, netip.AddrPortFrom(clientRemoteIP, reqDetails.RemotePort))
  847. return
  848. }
  849. if ns.lb != nil {
  850. handler, opts := ns.lb.TCPHandlerForDst(clientRemoteAddrPort, dstAddrPort)
  851. if handler != nil {
  852. c := getConnOrReset(opts...) // will send a RST if it fails
  853. if c == nil {
  854. return
  855. }
  856. handler(c)
  857. return
  858. }
  859. }
  860. if ns.GetTCPHandlerForFlow != nil {
  861. handler, ok := ns.GetTCPHandlerForFlow(clientRemoteAddrPort, dstAddrPort)
  862. if ok {
  863. if handler == nil {
  864. r.Complete(true)
  865. return
  866. }
  867. c := getConnOrReset() // will send a RST if it fails
  868. if c == nil {
  869. return
  870. }
  871. handler(c)
  872. return
  873. }
  874. }
  875. if isTailscaleIP {
  876. dialIP = netaddr.IPv4(127, 0, 0, 1)
  877. }
  878. dialAddr := netip.AddrPortFrom(dialIP, uint16(reqDetails.LocalPort))
  879. if !ns.forwardTCP(getConnOrReset, clientRemoteIP, &wq, dialAddr) {
  880. r.Complete(true) // sends a RST
  881. }
  882. }
  883. func (ns *Impl) forwardTCP(getClient func(...tcpip.SettableSocketOption) *gonet.TCPConn, clientRemoteIP netip.Addr, wq *waiter.Queue, dialAddr netip.AddrPort) (handled bool) {
  884. dialAddrStr := dialAddr.String()
  885. if debugNetstack() {
  886. ns.logf("[v2] netstack: forwarding incoming connection to %s", dialAddrStr)
  887. }
  888. ctx, cancel := context.WithCancel(context.Background())
  889. defer cancel()
  890. waitEntry, notifyCh := waiter.NewChannelEntry(waiter.EventHUp) // TODO(bradfitz): right EventMask?
  891. wq.EventRegister(&waitEntry)
  892. defer wq.EventUnregister(&waitEntry)
  893. done := make(chan bool)
  894. // netstack doesn't close the notification channel automatically if there was no
  895. // hup signal, so we close done after we're done to not leak the goroutine below.
  896. defer close(done)
  897. go func() {
  898. select {
  899. case <-notifyCh:
  900. if debugNetstack() {
  901. ns.logf("[v2] netstack: forwardTCP notifyCh fired; canceling context for %s", dialAddrStr)
  902. }
  903. case <-done:
  904. }
  905. cancel()
  906. }()
  907. // Attempt to dial the outbound connection before we accept the inbound one.
  908. var stdDialer net.Dialer
  909. server, err := stdDialer.DialContext(ctx, "tcp", dialAddrStr)
  910. if err != nil {
  911. ns.logf("netstack: could not connect to local server at %s: %v", dialAddr.String(), err)
  912. return
  913. }
  914. defer server.Close()
  915. // If we get here, either the getClient call below will succeed and
  916. // return something we can Close, or it will fail and will properly
  917. // respond to the client with a RST. Either way, the caller no longer
  918. // needs to clean up the client connection.
  919. handled = true
  920. // We dialed the connection; we can complete the client's TCP handshake.
  921. client := getClient()
  922. if client == nil {
  923. return
  924. }
  925. defer client.Close()
  926. backendLocalAddr := server.LocalAddr().(*net.TCPAddr)
  927. backendLocalIPPort := netaddr.Unmap(backendLocalAddr.AddrPort())
  928. ns.pm.RegisterIPPortIdentity(backendLocalIPPort, clientRemoteIP)
  929. defer ns.pm.UnregisterIPPortIdentity(backendLocalIPPort)
  930. connClosed := make(chan error, 2)
  931. go func() {
  932. _, err := io.Copy(server, client)
  933. connClosed <- err
  934. }()
  935. go func() {
  936. _, err := io.Copy(client, server)
  937. connClosed <- err
  938. }()
  939. err = <-connClosed
  940. if err != nil {
  941. ns.logf("proxy connection closed with error: %v", err)
  942. }
  943. ns.logf("[v2] netstack: forwarder connection to %s closed", dialAddrStr)
  944. return
  945. }
  946. func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
  947. sess := r.ID()
  948. if debugNetstack() {
  949. ns.logf("[v2] UDP ForwarderRequest: %v", stringifyTEI(sess))
  950. }
  951. var wq waiter.Queue
  952. ep, err := r.CreateEndpoint(&wq)
  953. if err != nil {
  954. ns.logf("acceptUDP: could not create endpoint: %v", err)
  955. return
  956. }
  957. dstAddr, ok := ipPortOfNetstackAddr(sess.LocalAddress, sess.LocalPort)
  958. if !ok {
  959. ep.Close()
  960. return
  961. }
  962. srcAddr, ok := ipPortOfNetstackAddr(sess.RemoteAddress, sess.RemotePort)
  963. if !ok {
  964. ep.Close()
  965. return
  966. }
  967. // Handle magicDNS traffic (via UDP) here.
  968. if dst := dstAddr.Addr(); dst == magicDNSIP || dst == magicDNSIPv6 {
  969. if dstAddr.Port() != 53 {
  970. ep.Close()
  971. return // Only MagicDNS traffic runs on the service IPs for now.
  972. }
  973. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  974. go ns.handleMagicDNSUDP(srcAddr, c)
  975. return
  976. }
  977. if get := ns.GetUDPHandlerForFlow; get != nil {
  978. h, intercept := get(srcAddr, dstAddr)
  979. if intercept {
  980. if h == nil {
  981. ep.Close()
  982. return
  983. }
  984. go h(gonet.NewUDPConn(ns.ipstack, &wq, ep))
  985. return
  986. }
  987. }
  988. c := gonet.NewUDPConn(ns.ipstack, &wq, ep)
  989. go ns.forwardUDP(c, srcAddr, dstAddr)
  990. }
  991. // Buffer pool for forwarding UDP packets. Implementations are advised not to
  992. // exceed 512 bytes per DNS request due to fragmenting but in reality can and do
  993. // send much larger packets, so use the maximum possible UDP packet size.
  994. var udpBufPool = &sync.Pool{
  995. New: func() any {
  996. b := make([]byte, maxUDPPacketSize)
  997. return &b
  998. },
  999. }
  1000. func (ns *Impl) handleMagicDNSUDP(srcAddr netip.AddrPort, c *gonet.UDPConn) {
  1001. // Packets are being generated by the local host, so there should be
  1002. // very, very little latency. 150ms was chosen as something of an upper
  1003. // bound on resource usage, while hopefully still being long enough for
  1004. // a heavily loaded system.
  1005. const readDeadline = 150 * time.Millisecond
  1006. defer c.Close()
  1007. bufp := udpBufPool.Get().(*[]byte)
  1008. defer udpBufPool.Put(bufp)
  1009. q := *bufp
  1010. // libresolv from glibc is quite adamant that transmitting multiple DNS
  1011. // requests down the same UDP socket is valid. To support this, we read
  1012. // in a loop (with a tight deadline so we don't chew too many resources).
  1013. //
  1014. // See: https://github.com/bminor/glibc/blob/f7fbb99652eceb1b6b55e4be931649df5946497c/resolv/res_send.c#L995
  1015. for {
  1016. c.SetReadDeadline(time.Now().Add(readDeadline))
  1017. n, _, err := c.ReadFrom(q)
  1018. if err != nil {
  1019. if oe, ok := err.(*net.OpError); !(ok && oe.Timeout()) {
  1020. ns.logf("dns udp read: %v", err) // log non-timeout errors
  1021. }
  1022. return
  1023. }
  1024. resp, err := ns.dns.Query(context.Background(), q[:n], "udp", srcAddr)
  1025. if err != nil {
  1026. ns.logf("dns udp query: %v", err)
  1027. return
  1028. }
  1029. c.Write(resp)
  1030. }
  1031. }
  1032. // forwardUDP proxies between client (with addr clientAddr) and dstAddr.
  1033. //
  1034. // dstAddr may be either a local Tailscale IP, in which we case we proxy to
  1035. // 127.0.0.1, or any other IP (from an advertised subnet), in which case we
  1036. // proxy to it directly.
  1037. func (ns *Impl) forwardUDP(client *gonet.UDPConn, clientAddr, dstAddr netip.AddrPort) {
  1038. port, srcPort := dstAddr.Port(), clientAddr.Port()
  1039. if debugNetstack() {
  1040. ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
  1041. }
  1042. var backendListenAddr *net.UDPAddr
  1043. var backendRemoteAddr *net.UDPAddr
  1044. isLocal := ns.isLocalIP(dstAddr.Addr())
  1045. if isLocal {
  1046. backendRemoteAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(port)}
  1047. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
  1048. } else {
  1049. if dstIP := dstAddr.Addr(); viaRange.Contains(dstIP) {
  1050. dstAddr = netip.AddrPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
  1051. }
  1052. backendRemoteAddr = net.UDPAddrFromAddrPort(dstAddr)
  1053. if dstAddr.Addr().Is4() {
  1054. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port: int(srcPort)}
  1055. } else {
  1056. backendListenAddr = &net.UDPAddr{IP: net.ParseIP("::"), Port: int(srcPort)}
  1057. }
  1058. }
  1059. backendConn, err := net.ListenUDP("udp", backendListenAddr)
  1060. if err != nil {
  1061. ns.logf("netstack: could not bind local port %v: %v, trying again with random port", backendListenAddr.Port, err)
  1062. backendListenAddr.Port = 0
  1063. backendConn, err = net.ListenUDP("udp", backendListenAddr)
  1064. if err != nil {
  1065. ns.logf("netstack: could not create UDP socket, preventing forwarding to %v: %v", dstAddr, err)
  1066. return
  1067. }
  1068. }
  1069. backendLocalAddr := backendConn.LocalAddr().(*net.UDPAddr)
  1070. backendLocalIPPort := netip.AddrPortFrom(backendListenAddr.AddrPort().Addr().Unmap().WithZone(backendLocalAddr.Zone), backendLocalAddr.AddrPort().Port())
  1071. if !backendLocalIPPort.IsValid() {
  1072. ns.logf("could not get backend local IP:port from %v:%v", backendLocalAddr.IP, backendLocalAddr.Port)
  1073. }
  1074. if isLocal {
  1075. ns.pm.RegisterIPPortIdentity(backendLocalIPPort, dstAddr.Addr())
  1076. }
  1077. ctx, cancel := context.WithCancel(context.Background())
  1078. idleTimeout := 2 * time.Minute
  1079. if port == 53 {
  1080. // Make DNS packet copies time out much sooner.
  1081. //
  1082. // TODO(bradfitz): make DNS queries over UDP forwarding even
  1083. // cheaper by adding an additional idleTimeout post-DNS-reply.
  1084. // For instance, after the DNS response goes back out, then only
  1085. // wait a few seconds (or zero, really)
  1086. idleTimeout = 30 * time.Second
  1087. }
  1088. timer := time.AfterFunc(idleTimeout, func() {
  1089. if isLocal {
  1090. ns.pm.UnregisterIPPortIdentity(backendLocalIPPort)
  1091. }
  1092. ns.logf("netstack: UDP session between %s and %s timed out", backendListenAddr, backendRemoteAddr)
  1093. cancel()
  1094. client.Close()
  1095. backendConn.Close()
  1096. })
  1097. extend := func() {
  1098. timer.Reset(idleTimeout)
  1099. }
  1100. startPacketCopy(ctx, cancel, client, net.UDPAddrFromAddrPort(clientAddr), backendConn, ns.logf, extend)
  1101. startPacketCopy(ctx, cancel, backendConn, backendRemoteAddr, client, ns.logf, extend)
  1102. if isLocal {
  1103. // Wait for the copies to be done before decrementing the
  1104. // subnet address count to potentially remove the route.
  1105. <-ctx.Done()
  1106. ns.removeSubnetAddress(dstAddr.Addr())
  1107. }
  1108. }
  1109. func startPacketCopy(ctx context.Context, cancel context.CancelFunc, dst net.PacketConn, dstAddr net.Addr, src net.PacketConn, logf logger.Logf, extend func()) {
  1110. if debugNetstack() {
  1111. logf("[v2] netstack: startPacketCopy to %v (%T) from %T", dstAddr, dst, src)
  1112. }
  1113. go func() {
  1114. defer cancel() // tear down the other direction's copy
  1115. bufp := udpBufPool.Get().(*[]byte)
  1116. defer udpBufPool.Put(bufp)
  1117. pkt := *bufp
  1118. for {
  1119. select {
  1120. case <-ctx.Done():
  1121. return
  1122. default:
  1123. n, srcAddr, err := src.ReadFrom(pkt)
  1124. if err != nil {
  1125. if ctx.Err() == nil {
  1126. logf("read packet from %s failed: %v", srcAddr, err)
  1127. }
  1128. return
  1129. }
  1130. _, err = dst.WriteTo(pkt[:n], dstAddr)
  1131. if err != nil {
  1132. if ctx.Err() == nil {
  1133. logf("write packet to %s failed: %v", dstAddr, err)
  1134. }
  1135. return
  1136. }
  1137. if debugNetstack() {
  1138. logf("[v2] wrote UDP packet %s -> %s", srcAddr, dstAddr)
  1139. }
  1140. extend()
  1141. }
  1142. }
  1143. }()
  1144. }
  1145. func stringifyTEI(tei stack.TransportEndpointID) string {
  1146. localHostPort := net.JoinHostPort(tei.LocalAddress.String(), strconv.Itoa(int(tei.LocalPort)))
  1147. remoteHostPort := net.JoinHostPort(tei.RemoteAddress.String(), strconv.Itoa(int(tei.RemotePort)))
  1148. return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
  1149. }
  1150. func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netip.AddrPort, ok bool) {
  1151. if addr, ok := netip.AddrFromSlice(a.AsSlice()); ok {
  1152. return netip.AddrPortFrom(addr, port), true
  1153. }
  1154. return netip.AddrPort{}, false
  1155. }