netstack.go 39 KB

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