2
0

netstack.go 39 KB

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