netstack.go 40 KB

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