endpoint.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. //go:build with_gvisor
  2. package tailscale
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/netip"
  10. "net/url"
  11. "os"
  12. "path/filepath"
  13. "reflect"
  14. "runtime"
  15. "strings"
  16. "sync/atomic"
  17. "syscall"
  18. "time"
  19. "github.com/sagernet/gvisor/pkg/tcpip"
  20. "github.com/sagernet/gvisor/pkg/tcpip/adapters/gonet"
  21. "github.com/sagernet/gvisor/pkg/tcpip/header"
  22. "github.com/sagernet/gvisor/pkg/tcpip/stack"
  23. "github.com/sagernet/gvisor/pkg/tcpip/transport/icmp"
  24. "github.com/sagernet/sing-box/adapter"
  25. "github.com/sagernet/sing-box/adapter/endpoint"
  26. "github.com/sagernet/sing-box/common/dialer"
  27. C "github.com/sagernet/sing-box/constant"
  28. "github.com/sagernet/sing-box/log"
  29. "github.com/sagernet/sing-box/option"
  30. "github.com/sagernet/sing-box/route/rule"
  31. "github.com/sagernet/sing-tun"
  32. "github.com/sagernet/sing-tun/ping"
  33. "github.com/sagernet/sing/common"
  34. "github.com/sagernet/sing/common/bufio"
  35. "github.com/sagernet/sing/common/control"
  36. E "github.com/sagernet/sing/common/exceptions"
  37. F "github.com/sagernet/sing/common/format"
  38. "github.com/sagernet/sing/common/logger"
  39. M "github.com/sagernet/sing/common/metadata"
  40. N "github.com/sagernet/sing/common/network"
  41. "github.com/sagernet/sing/common/ntp"
  42. "github.com/sagernet/sing/service"
  43. "github.com/sagernet/sing/service/filemanager"
  44. _ "github.com/sagernet/tailscale/feature/relayserver"
  45. "github.com/sagernet/tailscale/ipn"
  46. tsDNS "github.com/sagernet/tailscale/net/dns"
  47. "github.com/sagernet/tailscale/net/netmon"
  48. "github.com/sagernet/tailscale/net/netns"
  49. "github.com/sagernet/tailscale/net/tsaddr"
  50. tsTUN "github.com/sagernet/tailscale/net/tstun"
  51. "github.com/sagernet/tailscale/tsnet"
  52. "github.com/sagernet/tailscale/types/ipproto"
  53. "github.com/sagernet/tailscale/types/nettype"
  54. "github.com/sagernet/tailscale/version"
  55. "github.com/sagernet/tailscale/wgengine"
  56. "github.com/sagernet/tailscale/wgengine/filter"
  57. "github.com/sagernet/tailscale/wgengine/router"
  58. "github.com/sagernet/tailscale/wgengine/wgcfg"
  59. "go4.org/netipx"
  60. )
  61. var (
  62. _ adapter.OutboundWithPreferredRoutes = (*Endpoint)(nil)
  63. _ adapter.DirectRouteOutbound = (*Endpoint)(nil)
  64. _ dialer.PacketDialerWithDestination = (*Endpoint)(nil)
  65. )
  66. func init() {
  67. version.SetVersion("sing-box " + C.Version)
  68. }
  69. func RegisterEndpoint(registry *endpoint.Registry) {
  70. endpoint.Register[option.TailscaleEndpointOptions](registry, C.TypeTailscale, NewEndpoint)
  71. }
  72. type Endpoint struct {
  73. endpoint.Adapter
  74. ctx context.Context
  75. router adapter.Router
  76. logger logger.ContextLogger
  77. dnsRouter adapter.DNSRouter
  78. network adapter.NetworkManager
  79. platformInterface adapter.PlatformInterface
  80. server *tsnet.Server
  81. stack *stack.Stack
  82. icmpForwarder *tun.ICMPForwarder
  83. filter *atomic.Pointer[filter.Filter]
  84. onReconfigHook wgengine.ReconfigListener
  85. cfg *wgcfg.Config
  86. dnsCfg *tsDNS.Config
  87. routeDomains common.TypedValue[map[string]bool]
  88. routePrefixes atomic.Pointer[netipx.IPSet]
  89. acceptRoutes bool
  90. exitNode string
  91. exitNodeAllowLANAccess bool
  92. advertiseRoutes []netip.Prefix
  93. advertiseExitNode bool
  94. advertiseTags []string
  95. relayServerPort *uint16
  96. relayServerStaticEndpoints []netip.AddrPort
  97. udpTimeout time.Duration
  98. systemInterface bool
  99. systemInterfaceName string
  100. systemInterfaceMTU uint32
  101. systemTun tun.Tun
  102. systemDialer *dialer.DefaultDialer
  103. fallbackTCPCloser func()
  104. }
  105. func (t *Endpoint) registerNetstackHandlers() {
  106. netstack := t.server.ExportNetstack()
  107. if netstack == nil {
  108. return
  109. }
  110. previousTCP := netstack.GetTCPHandlerForFlow
  111. netstack.GetTCPHandlerForFlow = func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool) {
  112. if previousTCP != nil {
  113. handler, intercept = previousTCP(src, dst)
  114. if handler != nil || !intercept {
  115. return handler, intercept
  116. }
  117. }
  118. return func(conn net.Conn) {
  119. ctx := log.ContextWithNewID(t.ctx)
  120. source := M.SocksaddrFrom(src.Addr(), src.Port())
  121. destination := M.SocksaddrFrom(dst.Addr(), dst.Port())
  122. t.NewConnectionEx(ctx, conn, source, destination, nil)
  123. }, true
  124. }
  125. previousUDP := netstack.GetUDPHandlerForFlow
  126. netstack.GetUDPHandlerForFlow = func(src, dst netip.AddrPort) (handler func(nettype.ConnPacketConn), intercept bool) {
  127. if previousUDP != nil {
  128. handler, intercept = previousUDP(src, dst)
  129. if handler != nil || !intercept {
  130. return handler, intercept
  131. }
  132. }
  133. return func(conn nettype.ConnPacketConn) {
  134. ctx := log.ContextWithNewID(t.ctx)
  135. source := M.SocksaddrFrom(src.Addr(), src.Port())
  136. destination := M.SocksaddrFrom(dst.Addr(), dst.Port())
  137. packetConn := bufio.NewUnbindPacketConnWithAddr(conn, destination)
  138. t.NewPacketConnectionEx(ctx, packetConn, source, destination, nil)
  139. }, true
  140. }
  141. }
  142. func NewEndpoint(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TailscaleEndpointOptions) (adapter.Endpoint, error) {
  143. stateDirectory := options.StateDirectory
  144. if stateDirectory == "" {
  145. stateDirectory = "tailscale"
  146. }
  147. hostname := options.Hostname
  148. if hostname == "" {
  149. osHostname, _ := os.Hostname()
  150. osHostname = strings.TrimSpace(osHostname)
  151. hostname = osHostname
  152. }
  153. if hostname == "" {
  154. hostname = "sing-box"
  155. }
  156. stateDirectory = filemanager.BasePath(ctx, os.ExpandEnv(stateDirectory))
  157. stateDirectory, _ = filepath.Abs(stateDirectory)
  158. for _, advertiseRoute := range options.AdvertiseRoutes {
  159. if advertiseRoute.Addr().IsUnspecified() && advertiseRoute.Bits() == 0 {
  160. return nil, E.New("`advertise_routes` cannot be default, use `advertise_exit_node` instead.")
  161. }
  162. }
  163. if options.AdvertiseExitNode && options.ExitNode != "" {
  164. return nil, E.New("cannot advertise an exit node and use an exit node at the same time.")
  165. }
  166. var udpTimeout time.Duration
  167. if options.UDPTimeout != 0 {
  168. udpTimeout = time.Duration(options.UDPTimeout)
  169. } else {
  170. udpTimeout = C.UDPTimeout
  171. }
  172. var remoteIsDomain bool
  173. if options.ControlURL != "" {
  174. controlURL, err := url.Parse(options.ControlURL)
  175. if err != nil {
  176. return nil, E.Cause(err, "parse control URL")
  177. }
  178. remoteIsDomain = M.IsDomainName(controlURL.Hostname())
  179. } else {
  180. // controlplane.tailscale.com
  181. remoteIsDomain = true
  182. }
  183. outboundDialer, err := dialer.NewWithOptions(dialer.Options{
  184. Context: ctx,
  185. Options: options.DialerOptions,
  186. RemoteIsDomain: remoteIsDomain,
  187. ResolverOnDetour: true,
  188. NewDialer: true,
  189. })
  190. if err != nil {
  191. return nil, err
  192. }
  193. dnsRouter := service.FromContext[adapter.DNSRouter](ctx)
  194. server := &tsnet.Server{
  195. Dir: stateDirectory,
  196. Hostname: hostname,
  197. Logf: func(format string, args ...any) {
  198. logger.Trace(fmt.Sprintf(format, args...))
  199. },
  200. UserLogf: func(format string, args ...any) {
  201. logger.Debug(fmt.Sprintf(format, args...))
  202. },
  203. Ephemeral: options.Ephemeral,
  204. AuthKey: options.AuthKey,
  205. ControlURL: options.ControlURL,
  206. AdvertiseTags: options.AdvertiseTags,
  207. Dialer: &endpointDialer{Dialer: outboundDialer, logger: logger},
  208. LookupHook: func(ctx context.Context, host string) ([]netip.Addr, error) {
  209. return dnsRouter.Lookup(ctx, host, outboundDialer.(dialer.ResolveDialer).QueryOptions())
  210. },
  211. DNS: &dnsConfigurtor{},
  212. HTTPClient: &http.Client{
  213. Transport: &http.Transport{
  214. ForceAttemptHTTP2: true,
  215. DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
  216. return outboundDialer.DialContext(ctx, network, M.ParseSocksaddr(address))
  217. },
  218. TLSClientConfig: &tls.Config{
  219. RootCAs: adapter.RootPoolFromContext(ctx),
  220. Time: ntp.TimeFuncFromContext(ctx),
  221. },
  222. },
  223. },
  224. }
  225. return &Endpoint{
  226. Adapter: endpoint.NewAdapter(C.TypeTailscale, tag, []string{N.NetworkTCP, N.NetworkUDP, N.NetworkICMP}, nil),
  227. ctx: ctx,
  228. router: router,
  229. logger: logger,
  230. dnsRouter: dnsRouter,
  231. network: service.FromContext[adapter.NetworkManager](ctx),
  232. platformInterface: service.FromContext[adapter.PlatformInterface](ctx),
  233. server: server,
  234. acceptRoutes: options.AcceptRoutes,
  235. exitNode: options.ExitNode,
  236. exitNodeAllowLANAccess: options.ExitNodeAllowLANAccess,
  237. advertiseRoutes: options.AdvertiseRoutes,
  238. advertiseExitNode: options.AdvertiseExitNode,
  239. advertiseTags: options.AdvertiseTags,
  240. relayServerPort: options.RelayServerPort,
  241. relayServerStaticEndpoints: options.RelayServerStaticEndpoints,
  242. udpTimeout: udpTimeout,
  243. systemInterface: options.SystemInterface,
  244. systemInterfaceName: options.SystemInterfaceName,
  245. systemInterfaceMTU: options.SystemInterfaceMTU,
  246. }, nil
  247. }
  248. func (t *Endpoint) Start(stage adapter.StartStage) error {
  249. if stage != adapter.StartStateStart {
  250. return nil
  251. }
  252. if t.platformInterface != nil {
  253. err := t.network.UpdateInterfaces()
  254. if err != nil {
  255. return err
  256. }
  257. netmon.RegisterInterfaceGetter(func() ([]netmon.Interface, error) {
  258. return common.Map(t.network.InterfaceFinder().Interfaces(), func(it control.Interface) netmon.Interface {
  259. return netmon.Interface{
  260. Interface: &net.Interface{
  261. Index: it.Index,
  262. MTU: it.MTU,
  263. Name: it.Name,
  264. HardwareAddr: it.HardwareAddr,
  265. Flags: it.Flags,
  266. },
  267. AltAddrs: common.Map(it.Addresses, func(it netip.Prefix) net.Addr {
  268. return &net.IPNet{
  269. IP: it.Addr().AsSlice(),
  270. Mask: net.CIDRMask(it.Bits(), it.Addr().BitLen()),
  271. }
  272. }),
  273. }
  274. }), nil
  275. })
  276. }
  277. if t.systemInterface {
  278. mtu := t.systemInterfaceMTU
  279. if mtu == 0 {
  280. mtu = uint32(tsTUN.DefaultTUNMTU())
  281. }
  282. tunName := t.systemInterfaceName
  283. if tunName == "" {
  284. tunName = tun.CalculateInterfaceName("tailscale")
  285. }
  286. tunOptions := tun.Options{
  287. Name: tunName,
  288. MTU: mtu,
  289. GSO: true,
  290. InterfaceScope: true,
  291. InterfaceMonitor: t.network.InterfaceMonitor(),
  292. InterfaceFinder: t.network.InterfaceFinder(),
  293. Logger: t.logger,
  294. EXP_ExternalConfiguration: true,
  295. }
  296. systemTun, err := tun.New(tunOptions)
  297. if err != nil {
  298. return err
  299. }
  300. err = systemTun.Start()
  301. if err != nil {
  302. _ = systemTun.Close()
  303. return err
  304. }
  305. wgTunDevice, err := newTunDeviceAdapter(systemTun, int(mtu), t.logger)
  306. if err != nil {
  307. _ = systemTun.Close()
  308. return err
  309. }
  310. systemDialer, err := dialer.NewDefault(t.ctx, option.DialerOptions{
  311. BindInterface: tunName,
  312. })
  313. if err != nil {
  314. _ = systemTun.Close()
  315. return err
  316. }
  317. t.systemTun = systemTun
  318. t.systemDialer = systemDialer
  319. t.server.TunDevice = wgTunDevice
  320. }
  321. if mark := t.network.AutoRedirectOutputMark(); mark > 0 {
  322. controlFunc := t.network.AutoRedirectOutputMarkFunc()
  323. if bindFunc := t.network.AutoDetectInterfaceFunc(); bindFunc != nil {
  324. controlFunc = control.Append(controlFunc, bindFunc)
  325. }
  326. netns.SetControlFunc(controlFunc)
  327. } else if runtime.GOOS == "android" && t.platformInterface != nil {
  328. netns.SetControlFunc(func(network, address string, c syscall.RawConn) error {
  329. return control.Raw(c, func(fd uintptr) error {
  330. return t.platformInterface.AutoDetectInterfaceControl(int(fd))
  331. })
  332. })
  333. }
  334. err := t.server.Start()
  335. if err != nil {
  336. if t.systemTun != nil {
  337. _ = t.systemTun.Close()
  338. }
  339. return err
  340. }
  341. if t.fallbackTCPCloser == nil {
  342. t.fallbackTCPCloser = t.server.RegisterFallbackTCPHandler(func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool) {
  343. return func(conn net.Conn) {
  344. ctx := log.ContextWithNewID(t.ctx)
  345. source := M.SocksaddrFrom(src.Addr(), src.Port())
  346. destination := M.SocksaddrFrom(dst.Addr(), dst.Port())
  347. t.NewConnectionEx(ctx, conn, source, destination, nil)
  348. }, true
  349. })
  350. }
  351. t.server.ExportLocalBackend().ExportEngine().(wgengine.ExportedUserspaceEngine).SetOnReconfigListener(t.onReconfig)
  352. ipStack := t.server.ExportNetstack().ExportIPStack()
  353. gErr := ipStack.SetSpoofing(tun.DefaultNIC, true)
  354. if gErr != nil {
  355. return gonet.TranslateNetstackError(gErr)
  356. }
  357. gErr = ipStack.SetPromiscuousMode(tun.DefaultNIC, true)
  358. if gErr != nil {
  359. return gonet.TranslateNetstackError(gErr)
  360. }
  361. icmpForwarder := tun.NewICMPForwarder(t.ctx, ipStack, t, t.udpTimeout)
  362. ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber4, icmpForwarder.HandlePacket)
  363. ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber6, icmpForwarder.HandlePacket)
  364. t.stack = ipStack
  365. t.icmpForwarder = icmpForwarder
  366. t.registerNetstackHandlers()
  367. localBackend := t.server.ExportLocalBackend()
  368. perfs := &ipn.MaskedPrefs{
  369. Prefs: ipn.Prefs{
  370. RouteAll: t.acceptRoutes,
  371. AdvertiseRoutes: t.advertiseRoutes,
  372. },
  373. RouteAllSet: true,
  374. ExitNodeIPSet: true,
  375. AdvertiseRoutesSet: true,
  376. RelayServerPortSet: true,
  377. RelayServerStaticEndpointsSet: true,
  378. }
  379. if t.advertiseExitNode {
  380. perfs.AdvertiseRoutes = append(perfs.AdvertiseRoutes, tsaddr.ExitRoutes()...)
  381. }
  382. if t.relayServerPort != nil {
  383. perfs.RelayServerPort = t.relayServerPort
  384. }
  385. if len(t.relayServerStaticEndpoints) > 0 {
  386. perfs.RelayServerStaticEndpoints = t.relayServerStaticEndpoints
  387. }
  388. _, err = localBackend.EditPrefs(perfs)
  389. if err != nil {
  390. return E.Cause(err, "update prefs")
  391. }
  392. t.filter = localBackend.ExportFilter()
  393. go t.watchState()
  394. return nil
  395. }
  396. func (t *Endpoint) watchState() {
  397. localBackend := t.server.ExportLocalBackend()
  398. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  399. if roNotify.State != nil && *roNotify.State != ipn.NeedsLogin && *roNotify.State != ipn.NoState {
  400. return false
  401. }
  402. authURL := localBackend.StatusWithoutPeers().AuthURL
  403. if authURL != "" {
  404. t.logger.Info("Waiting for authentication: ", authURL)
  405. if t.platformInterface != nil {
  406. err := t.platformInterface.SendNotification(&adapter.Notification{
  407. Identifier: "tailscale-authentication",
  408. TypeName: "Tailscale Authentication Notifications",
  409. TypeID: 10,
  410. Title: "Tailscale Authentication",
  411. Body: F.ToString("Tailscale outbound[", t.Tag(), "] is waiting for authentication."),
  412. OpenURL: authURL,
  413. })
  414. if err != nil {
  415. t.logger.Error("send authentication notification: ", err)
  416. }
  417. }
  418. return false
  419. }
  420. return true
  421. })
  422. if t.exitNode != "" {
  423. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  424. if roNotify.State == nil || *roNotify.State != ipn.Running {
  425. return true
  426. }
  427. status, err := common.Must1(t.server.LocalClient()).Status(t.ctx)
  428. if err != nil {
  429. t.logger.Error("set exit node: ", err)
  430. return
  431. }
  432. perfs := &ipn.MaskedPrefs{
  433. Prefs: ipn.Prefs{
  434. ExitNodeAllowLANAccess: t.exitNodeAllowLANAccess,
  435. },
  436. ExitNodeIPSet: true,
  437. ExitNodeAllowLANAccessSet: true,
  438. }
  439. err = perfs.SetExitNodeIP(t.exitNode, status)
  440. if err != nil {
  441. t.logger.Error("set exit node: ", err)
  442. return true
  443. }
  444. _, err = localBackend.EditPrefs(perfs)
  445. if err != nil {
  446. t.logger.Error("set exit node: ", err)
  447. return true
  448. }
  449. return false
  450. })
  451. }
  452. }
  453. func (t *Endpoint) Close() error {
  454. netmon.RegisterInterfaceGetter(nil)
  455. netns.SetControlFunc(nil)
  456. if t.fallbackTCPCloser != nil {
  457. t.fallbackTCPCloser()
  458. t.fallbackTCPCloser = nil
  459. }
  460. err := common.Close(common.PtrOrNil(t.server))
  461. if t.systemTun != nil {
  462. t.systemTun.Close()
  463. t.systemTun = nil
  464. }
  465. return err
  466. }
  467. func (t *Endpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  468. switch network {
  469. case N.NetworkTCP:
  470. t.logger.InfoContext(ctx, "outbound connection to ", destination)
  471. case N.NetworkUDP:
  472. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  473. }
  474. if destination.IsFqdn() {
  475. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  476. if err != nil {
  477. return nil, err
  478. }
  479. return N.DialSerial(ctx, t, network, destination, destinationAddresses)
  480. }
  481. if t.systemDialer != nil {
  482. return t.systemDialer.DialContext(ctx, network, destination)
  483. }
  484. addr4, addr6 := t.server.TailscaleIPs()
  485. remoteAddr := tcpip.FullAddress{
  486. NIC: 1,
  487. Port: destination.Port,
  488. Addr: addressFromAddr(destination.Addr),
  489. }
  490. var localAddr tcpip.FullAddress
  491. var networkProtocol tcpip.NetworkProtocolNumber
  492. if destination.IsIPv4() {
  493. if !addr4.IsValid() {
  494. return nil, E.New("missing Tailscale IPv4 address")
  495. }
  496. networkProtocol = header.IPv4ProtocolNumber
  497. localAddr = tcpip.FullAddress{
  498. NIC: 1,
  499. Addr: addressFromAddr(addr4),
  500. }
  501. } else {
  502. if !addr6.IsValid() {
  503. return nil, E.New("missing Tailscale IPv6 address")
  504. }
  505. networkProtocol = header.IPv6ProtocolNumber
  506. localAddr = tcpip.FullAddress{
  507. NIC: 1,
  508. Addr: addressFromAddr(addr6),
  509. }
  510. }
  511. switch N.NetworkName(network) {
  512. case N.NetworkTCP:
  513. tcpConn, err := gonet.DialTCPWithBind(ctx, t.stack, localAddr, remoteAddr, networkProtocol)
  514. if err != nil {
  515. return nil, err
  516. }
  517. return tcpConn, nil
  518. case N.NetworkUDP:
  519. udpConn, err := gonet.DialUDP(t.stack, &localAddr, &remoteAddr, networkProtocol)
  520. if err != nil {
  521. return nil, err
  522. }
  523. return udpConn, nil
  524. default:
  525. return nil, E.Extend(N.ErrUnknownNetwork, network)
  526. }
  527. }
  528. func (t *Endpoint) listenPacketWithAddress(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  529. if t.systemDialer != nil {
  530. return t.systemDialer.ListenPacket(ctx, destination)
  531. }
  532. addr4, addr6 := t.server.TailscaleIPs()
  533. bind := tcpip.FullAddress{
  534. NIC: 1,
  535. }
  536. var networkProtocol tcpip.NetworkProtocolNumber
  537. if destination.IsIPv4() {
  538. if !addr4.IsValid() {
  539. return nil, E.New("missing Tailscale IPv4 address")
  540. }
  541. networkProtocol = header.IPv4ProtocolNumber
  542. bind.Addr = addressFromAddr(addr4)
  543. } else {
  544. if !addr6.IsValid() {
  545. return nil, E.New("missing Tailscale IPv6 address")
  546. }
  547. networkProtocol = header.IPv6ProtocolNumber
  548. bind.Addr = addressFromAddr(addr6)
  549. }
  550. udpConn, err := gonet.DialUDP(t.stack, &bind, nil, networkProtocol)
  551. if err != nil {
  552. return nil, err
  553. }
  554. return udpConn, nil
  555. }
  556. func (t *Endpoint) ListenPacketWithDestination(ctx context.Context, destination M.Socksaddr) (net.PacketConn, netip.Addr, error) {
  557. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  558. if destination.IsFqdn() {
  559. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  560. if err != nil {
  561. return nil, netip.Addr{}, err
  562. }
  563. var errors []error
  564. for _, address := range destinationAddresses {
  565. packetConn, packetErr := t.listenPacketWithAddress(ctx, M.SocksaddrFrom(address, destination.Port))
  566. if packetErr == nil {
  567. return packetConn, address, nil
  568. }
  569. errors = append(errors, packetErr)
  570. }
  571. return nil, netip.Addr{}, E.Errors(errors...)
  572. }
  573. packetConn, err := t.listenPacketWithAddress(ctx, destination)
  574. if err != nil {
  575. return nil, netip.Addr{}, err
  576. }
  577. if destination.IsIP() {
  578. return packetConn, destination.Addr, nil
  579. }
  580. return packetConn, netip.Addr{}, nil
  581. }
  582. func (t *Endpoint) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  583. packetConn, destinationAddress, err := t.ListenPacketWithDestination(ctx, destination)
  584. if err != nil {
  585. return nil, err
  586. }
  587. if destinationAddress.IsValid() && destination != M.SocksaddrFrom(destinationAddress, destination.Port) {
  588. return bufio.NewNATPacketConn(bufio.NewPacketConn(packetConn), M.SocksaddrFrom(destinationAddress, destination.Port), destination), nil
  589. }
  590. return packetConn, nil
  591. }
  592. func (t *Endpoint) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) {
  593. tsFilter := t.filter.Load()
  594. if tsFilter != nil {
  595. var ipProto ipproto.Proto
  596. switch N.NetworkName(network) {
  597. case N.NetworkTCP:
  598. ipProto = ipproto.TCP
  599. case N.NetworkUDP:
  600. ipProto = ipproto.UDP
  601. case N.NetworkICMP:
  602. if !destination.IsIPv6() {
  603. ipProto = ipproto.ICMPv4
  604. } else {
  605. ipProto = ipproto.ICMPv6
  606. }
  607. }
  608. response := tsFilter.Check(source.Addr, destination.Addr, destination.Port, ipProto)
  609. switch response {
  610. case filter.Drop:
  611. return nil, syscall.ECONNREFUSED
  612. case filter.DropSilently:
  613. return nil, tun.ErrDrop
  614. }
  615. }
  616. var ipVersion uint8
  617. if !destination.IsIPv6() {
  618. ipVersion = 4
  619. } else {
  620. ipVersion = 6
  621. }
  622. routeDestination, err := t.router.PreMatch(adapter.InboundContext{
  623. Inbound: t.Tag(),
  624. InboundType: t.Type(),
  625. IPVersion: ipVersion,
  626. Network: network,
  627. Source: source,
  628. Destination: destination,
  629. }, routeContext, timeout, false)
  630. if err != nil {
  631. switch {
  632. case rule.IsBypassed(err):
  633. err = nil
  634. case rule.IsRejected(err):
  635. t.logger.Trace("reject ", network, " connection from ", source.AddrString(), " to ", destination.AddrString())
  636. default:
  637. if network == N.NetworkICMP {
  638. t.logger.Warn(E.Cause(err, "link ", network, " connection from ", source.AddrString(), " to ", destination.AddrString()))
  639. }
  640. }
  641. }
  642. return routeDestination, err
  643. }
  644. func (t *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  645. var metadata adapter.InboundContext
  646. metadata.Inbound = t.Tag()
  647. metadata.InboundType = t.Type()
  648. metadata.Source = source
  649. addr4, addr6 := t.server.TailscaleIPs()
  650. switch destination.Addr {
  651. case addr4:
  652. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  653. case addr6:
  654. destination.Addr = netip.IPv6Loopback()
  655. }
  656. metadata.Destination = destination
  657. t.logger.InfoContext(ctx, "inbound connection from ", source)
  658. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  659. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  660. }
  661. func (t *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  662. var metadata adapter.InboundContext
  663. metadata.Inbound = t.Tag()
  664. metadata.InboundType = t.Type()
  665. metadata.Source = source
  666. addr4, addr6 := t.server.TailscaleIPs()
  667. switch destination.Addr {
  668. case addr4:
  669. metadata.OriginDestination = destination
  670. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  671. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, destination)
  672. case addr6:
  673. metadata.OriginDestination = destination
  674. destination.Addr = netip.IPv6Loopback()
  675. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, destination)
  676. }
  677. metadata.Destination = destination
  678. t.logger.InfoContext(ctx, "inbound packet connection from ", source)
  679. t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  680. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  681. }
  682. func (t *Endpoint) NewDirectRouteConnection(metadata adapter.InboundContext, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) {
  683. ctx := log.ContextWithNewID(t.ctx)
  684. var destination tun.DirectRouteDestination
  685. var err error
  686. if t.systemDialer != nil {
  687. destination, err = ping.ConnectDestination(
  688. ctx, t.logger,
  689. t.systemDialer.DialerForICMPDestination(metadata.Destination.Addr).Control,
  690. metadata.Destination.Addr, routeContext, timeout,
  691. )
  692. } else {
  693. inet4Address, inet6Address := t.server.TailscaleIPs()
  694. if metadata.Destination.Addr.Is4() && !inet4Address.IsValid() || metadata.Destination.Addr.Is6() && !inet6Address.IsValid() {
  695. return nil, E.New("Tailscale is not ready yet")
  696. }
  697. destination, err = ping.ConnectGVisor(
  698. ctx, t.logger,
  699. metadata.Source.Addr, metadata.Destination.Addr,
  700. routeContext,
  701. t.stack,
  702. inet4Address, inet6Address,
  703. timeout,
  704. )
  705. }
  706. if err != nil {
  707. return nil, err
  708. }
  709. t.logger.InfoContext(ctx, "linked ", metadata.Network, " connection from ", metadata.Source.AddrString(), " to ", metadata.Destination.AddrString())
  710. return destination, nil
  711. }
  712. func (t *Endpoint) PreferredDomain(domain string) bool {
  713. routeDomains := t.routeDomains.Load()
  714. if routeDomains == nil {
  715. return false
  716. }
  717. return routeDomains[strings.ToLower(domain)]
  718. }
  719. func (t *Endpoint) PreferredAddress(address netip.Addr) bool {
  720. routePrefixes := t.routePrefixes.Load()
  721. if routePrefixes == nil {
  722. return false
  723. }
  724. return routePrefixes.Contains(address)
  725. }
  726. func (t *Endpoint) Server() *tsnet.Server {
  727. return t.server
  728. }
  729. func (t *Endpoint) onReconfig(cfg *wgcfg.Config, routerCfg *router.Config, dnsCfg *tsDNS.Config) {
  730. if cfg == nil || dnsCfg == nil {
  731. return
  732. }
  733. if (t.cfg != nil && reflect.DeepEqual(t.cfg, cfg)) && (t.dnsCfg != nil && reflect.DeepEqual(t.dnsCfg, dnsCfg)) {
  734. return
  735. }
  736. var inet4Address, inet6Address netip.Addr
  737. for _, address := range cfg.Addresses {
  738. if address.Addr().Is4() {
  739. inet4Address = address.Addr()
  740. } else if address.Addr().Is6() {
  741. inet6Address = address.Addr()
  742. }
  743. }
  744. t.icmpForwarder.SetLocalAddresses(inet4Address, inet6Address)
  745. t.cfg = cfg
  746. t.dnsCfg = dnsCfg
  747. routeDomains := make(map[string]bool)
  748. for fqdn := range dnsCfg.Routes {
  749. routeDomains[fqdn.WithoutTrailingDot()] = true
  750. }
  751. for _, fqdn := range dnsCfg.SearchDomains {
  752. routeDomains[fqdn.WithoutTrailingDot()] = true
  753. }
  754. t.routeDomains.Store(routeDomains)
  755. var builder netipx.IPSetBuilder
  756. for _, peer := range cfg.Peers {
  757. for _, allowedIP := range peer.AllowedIPs {
  758. builder.AddPrefix(allowedIP)
  759. }
  760. }
  761. t.routePrefixes.Store(common.Must1(builder.IPSet()))
  762. if t.onReconfigHook != nil {
  763. t.onReconfigHook(cfg, routerCfg, dnsCfg)
  764. }
  765. }
  766. func addressFromAddr(destination netip.Addr) tcpip.Address {
  767. if destination.Is6() {
  768. return tcpip.AddrFrom16(destination.As16())
  769. } else {
  770. return tcpip.AddrFrom4(destination.As4())
  771. }
  772. }
  773. type endpointDialer struct {
  774. N.Dialer
  775. logger logger.ContextLogger
  776. }
  777. func (d *endpointDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  778. switch N.NetworkName(network) {
  779. case N.NetworkTCP:
  780. d.logger.InfoContext(ctx, "output connection to ", destination)
  781. case N.NetworkUDP:
  782. d.logger.InfoContext(ctx, "output packet connection to ", destination)
  783. }
  784. return d.Dialer.DialContext(ctx, network, destination)
  785. }
  786. func (d *endpointDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  787. d.logger.InfoContext(ctx, "output packet connection")
  788. return d.Dialer.ListenPacket(ctx, destination)
  789. }
  790. type dnsConfigurtor struct {
  791. baseConfig tsDNS.OSConfig
  792. }
  793. func (c *dnsConfigurtor) SetDNS(cfg tsDNS.OSConfig) error {
  794. c.baseConfig = cfg
  795. return nil
  796. }
  797. func (c *dnsConfigurtor) SupportsSplitDNS() bool {
  798. return true
  799. }
  800. func (c *dnsConfigurtor) GetBaseConfig() (tsDNS.OSConfig, error) {
  801. return c.baseConfig, nil
  802. }
  803. func (c *dnsConfigurtor) Close() error {
  804. return nil
  805. }