endpoint.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. package tailscale
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "net/netip"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "sync/atomic"
  15. "syscall"
  16. "time"
  17. "github.com/sagernet/gvisor/pkg/tcpip"
  18. "github.com/sagernet/gvisor/pkg/tcpip/adapters/gonet"
  19. "github.com/sagernet/gvisor/pkg/tcpip/header"
  20. "github.com/sagernet/gvisor/pkg/tcpip/stack"
  21. "github.com/sagernet/gvisor/pkg/tcpip/transport/tcp"
  22. "github.com/sagernet/gvisor/pkg/tcpip/transport/udp"
  23. "github.com/sagernet/sing-box/adapter"
  24. "github.com/sagernet/sing-box/adapter/endpoint"
  25. "github.com/sagernet/sing-box/common/dialer"
  26. C "github.com/sagernet/sing-box/constant"
  27. "github.com/sagernet/sing-box/experimental/libbox/platform"
  28. "github.com/sagernet/sing-box/log"
  29. "github.com/sagernet/sing-box/option"
  30. "github.com/sagernet/sing-tun"
  31. "github.com/sagernet/sing/common"
  32. "github.com/sagernet/sing/common/bufio"
  33. "github.com/sagernet/sing/common/control"
  34. E "github.com/sagernet/sing/common/exceptions"
  35. F "github.com/sagernet/sing/common/format"
  36. "github.com/sagernet/sing/common/logger"
  37. M "github.com/sagernet/sing/common/metadata"
  38. N "github.com/sagernet/sing/common/network"
  39. "github.com/sagernet/sing/service"
  40. "github.com/sagernet/sing/service/filemanager"
  41. "github.com/sagernet/tailscale/ipn"
  42. tsDNS "github.com/sagernet/tailscale/net/dns"
  43. "github.com/sagernet/tailscale/net/netmon"
  44. "github.com/sagernet/tailscale/net/tsaddr"
  45. "github.com/sagernet/tailscale/tsnet"
  46. "github.com/sagernet/tailscale/types/ipproto"
  47. "github.com/sagernet/tailscale/version"
  48. "github.com/sagernet/tailscale/wgengine"
  49. "github.com/sagernet/tailscale/wgengine/filter"
  50. )
  51. func init() {
  52. version.SetVersion("sing-box " + C.Version)
  53. }
  54. func RegisterEndpoint(registry *endpoint.Registry) {
  55. endpoint.Register[option.TailscaleEndpointOptions](registry, C.TypeTailscale, NewEndpoint)
  56. }
  57. type Endpoint struct {
  58. endpoint.Adapter
  59. ctx context.Context
  60. router adapter.Router
  61. logger logger.ContextLogger
  62. dnsRouter adapter.DNSRouter
  63. network adapter.NetworkManager
  64. platformInterface platform.Interface
  65. server *tsnet.Server
  66. stack *stack.Stack
  67. filter *atomic.Pointer[filter.Filter]
  68. onReconfig wgengine.ReconfigListener
  69. acceptRoutes bool
  70. exitNode string
  71. exitNodeAllowLANAccess bool
  72. advertiseRoutes []netip.Prefix
  73. advertiseExitNode bool
  74. udpTimeout time.Duration
  75. }
  76. func NewEndpoint(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TailscaleEndpointOptions) (adapter.Endpoint, error) {
  77. stateDirectory := options.StateDirectory
  78. if stateDirectory == "" {
  79. stateDirectory = "tailscale"
  80. }
  81. hostname := options.Hostname
  82. if hostname == "" {
  83. osHostname, _ := os.Hostname()
  84. osHostname = strings.TrimSpace(osHostname)
  85. hostname = osHostname
  86. }
  87. if hostname == "" {
  88. hostname = "sing-box"
  89. }
  90. stateDirectory = filemanager.BasePath(ctx, os.ExpandEnv(stateDirectory))
  91. stateDirectory, _ = filepath.Abs(stateDirectory)
  92. for _, advertiseRoute := range options.AdvertiseRoutes {
  93. if advertiseRoute.Addr().IsUnspecified() && advertiseRoute.Bits() == 0 {
  94. return nil, E.New("`advertise_routes` cannot be default, use `advertise_exit_node` instead.")
  95. }
  96. }
  97. if options.AdvertiseExitNode && options.ExitNode != "" {
  98. return nil, E.New("cannot advertise an exit node and use an exit node at the same time.")
  99. }
  100. var udpTimeout time.Duration
  101. if options.UDPTimeout != 0 {
  102. udpTimeout = time.Duration(options.UDPTimeout)
  103. } else {
  104. udpTimeout = C.UDPTimeout
  105. }
  106. var remoteIsDomain bool
  107. if options.ControlURL != "" {
  108. controlURL, err := url.Parse(options.ControlURL)
  109. if err != nil {
  110. return nil, E.Cause(err, "parse control URL")
  111. }
  112. remoteIsDomain = M.IsDomainName(controlURL.Hostname())
  113. } else {
  114. // controlplane.tailscale.com
  115. remoteIsDomain = true
  116. }
  117. outboundDialer, err := dialer.NewWithOptions(dialer.Options{
  118. Context: ctx,
  119. Options: options.DialerOptions,
  120. RemoteIsDomain: remoteIsDomain,
  121. ResolverOnDetour: true,
  122. NewDialer: true,
  123. })
  124. if err != nil {
  125. return nil, err
  126. }
  127. dnsRouter := service.FromContext[adapter.DNSRouter](ctx)
  128. server := &tsnet.Server{
  129. Dir: stateDirectory,
  130. Hostname: hostname,
  131. Logf: func(format string, args ...any) {
  132. logger.Trace(fmt.Sprintf(format, args...))
  133. },
  134. UserLogf: func(format string, args ...any) {
  135. logger.Debug(fmt.Sprintf(format, args...))
  136. },
  137. Ephemeral: options.Ephemeral,
  138. AuthKey: options.AuthKey,
  139. ControlURL: options.ControlURL,
  140. Dialer: &endpointDialer{Dialer: outboundDialer, logger: logger},
  141. LookupHook: func(ctx context.Context, host string) ([]netip.Addr, error) {
  142. return dnsRouter.Lookup(ctx, host, outboundDialer.(dialer.ResolveDialer).QueryOptions())
  143. },
  144. DNS: &dnsConfigurtor{},
  145. HTTPClient: &http.Client{
  146. Transport: &http.Transport{
  147. ForceAttemptHTTP2: true,
  148. DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
  149. return outboundDialer.DialContext(ctx, network, M.ParseSocksaddr(address))
  150. },
  151. TLSClientConfig: &tls.Config{
  152. RootCAs: adapter.RootPoolFromContext(ctx),
  153. },
  154. },
  155. },
  156. }
  157. return &Endpoint{
  158. Adapter: endpoint.NewAdapter(C.TypeTailscale, tag, []string{N.NetworkTCP, N.NetworkUDP}, nil),
  159. ctx: ctx,
  160. router: router,
  161. logger: logger,
  162. dnsRouter: dnsRouter,
  163. network: service.FromContext[adapter.NetworkManager](ctx),
  164. platformInterface: service.FromContext[platform.Interface](ctx),
  165. server: server,
  166. acceptRoutes: options.AcceptRoutes,
  167. exitNode: options.ExitNode,
  168. exitNodeAllowLANAccess: options.ExitNodeAllowLANAccess,
  169. advertiseRoutes: options.AdvertiseRoutes,
  170. advertiseExitNode: options.AdvertiseExitNode,
  171. udpTimeout: udpTimeout,
  172. }, nil
  173. }
  174. func (t *Endpoint) Start(stage adapter.StartStage) error {
  175. if stage != adapter.StartStateStart {
  176. return nil
  177. }
  178. if t.platformInterface != nil {
  179. err := t.network.UpdateInterfaces()
  180. if err != nil {
  181. return err
  182. }
  183. netmon.RegisterInterfaceGetter(func() ([]netmon.Interface, error) {
  184. return common.Map(t.network.InterfaceFinder().Interfaces(), func(it control.Interface) netmon.Interface {
  185. return netmon.Interface{
  186. Interface: &net.Interface{
  187. Index: it.Index,
  188. MTU: it.MTU,
  189. Name: it.Name,
  190. HardwareAddr: it.HardwareAddr,
  191. Flags: it.Flags,
  192. },
  193. AltAddrs: common.Map(it.Addresses, func(it netip.Prefix) net.Addr {
  194. return &net.IPNet{
  195. IP: it.Addr().AsSlice(),
  196. Mask: net.CIDRMask(it.Bits(), it.Addr().BitLen()),
  197. }
  198. }),
  199. }
  200. }), nil
  201. })
  202. if runtime.GOOS == "android" {
  203. setAndroidProtectFunc(t.platformInterface)
  204. }
  205. }
  206. err := t.server.Start()
  207. if err != nil {
  208. return err
  209. }
  210. if t.onReconfig != nil {
  211. t.server.ExportLocalBackend().ExportEngine().(wgengine.ExportedUserspaceEngine).SetOnReconfigListener(t.onReconfig)
  212. }
  213. ipStack := t.server.ExportNetstack().ExportIPStack()
  214. gErr := ipStack.SetSpoofing(tun.DefaultNIC, true)
  215. if gErr != nil {
  216. return gonet.TranslateNetstackError(gErr)
  217. }
  218. gErr = ipStack.SetPromiscuousMode(tun.DefaultNIC, true)
  219. if gErr != nil {
  220. return gonet.TranslateNetstackError(gErr)
  221. }
  222. ipStack.SetTransportProtocolHandler(tcp.ProtocolNumber, tun.NewTCPForwarder(t.ctx, ipStack, t).HandlePacket)
  223. udpForwarder := tun.NewUDPForwarder(t.ctx, ipStack, t, t.udpTimeout)
  224. ipStack.SetTransportProtocolHandler(udp.ProtocolNumber, udpForwarder.HandlePacket)
  225. t.stack = ipStack
  226. localBackend := t.server.ExportLocalBackend()
  227. perfs := &ipn.MaskedPrefs{
  228. Prefs: ipn.Prefs{
  229. RouteAll: t.acceptRoutes,
  230. },
  231. RouteAllSet: true,
  232. ExitNodeIPSet: true,
  233. AdvertiseRoutesSet: true,
  234. }
  235. if len(t.advertiseRoutes) > 0 {
  236. perfs.AdvertiseRoutes = t.advertiseRoutes
  237. }
  238. if t.advertiseExitNode {
  239. perfs.AdvertiseRoutes = append(perfs.AdvertiseRoutes, tsaddr.ExitRoutes()...)
  240. }
  241. _, err = localBackend.EditPrefs(perfs)
  242. if err != nil {
  243. return E.Cause(err, "update prefs")
  244. }
  245. t.filter = localBackend.ExportFilter()
  246. go t.watchState()
  247. return nil
  248. }
  249. func (t *Endpoint) watchState() {
  250. localBackend := t.server.ExportLocalBackend()
  251. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  252. if roNotify.State != nil && *roNotify.State != ipn.NeedsLogin && *roNotify.State != ipn.NoState {
  253. return false
  254. }
  255. authURL := localBackend.StatusWithoutPeers().AuthURL
  256. if authURL != "" {
  257. t.logger.Info("Waiting for authentication: ", authURL)
  258. if t.platformInterface != nil {
  259. err := t.platformInterface.SendNotification(&platform.Notification{
  260. Identifier: "tailscale-authentication",
  261. TypeName: "Tailscale Authentication Notifications",
  262. TypeID: 10,
  263. Title: "Tailscale Authentication",
  264. Body: F.ToString("Tailscale outbound[", t.Tag(), "] is waiting for authentication."),
  265. OpenURL: authURL,
  266. })
  267. if err != nil {
  268. t.logger.Error("send authentication notification: ", err)
  269. }
  270. }
  271. return false
  272. }
  273. return true
  274. })
  275. if t.exitNode != "" {
  276. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  277. if roNotify.State == nil || *roNotify.State != ipn.Running {
  278. return true
  279. }
  280. status, err := common.Must1(t.server.LocalClient()).Status(t.ctx)
  281. if err != nil {
  282. t.logger.Error("set exit node: ", err)
  283. return
  284. }
  285. perfs := &ipn.MaskedPrefs{
  286. Prefs: ipn.Prefs{
  287. ExitNodeAllowLANAccess: t.exitNodeAllowLANAccess,
  288. },
  289. ExitNodeIPSet: true,
  290. ExitNodeAllowLANAccessSet: true,
  291. }
  292. err = perfs.SetExitNodeIP(t.exitNode, status)
  293. if err != nil {
  294. t.logger.Error("set exit node: ", err)
  295. return true
  296. }
  297. _, err = localBackend.EditPrefs(perfs)
  298. if err != nil {
  299. t.logger.Error("set exit node: ", err)
  300. return true
  301. }
  302. return false
  303. })
  304. }
  305. }
  306. func (t *Endpoint) Close() error {
  307. netmon.RegisterInterfaceGetter(nil)
  308. if runtime.GOOS == "android" {
  309. setAndroidProtectFunc(nil)
  310. }
  311. return common.Close(common.PtrOrNil(t.server))
  312. }
  313. func (t *Endpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  314. switch network {
  315. case N.NetworkTCP:
  316. t.logger.InfoContext(ctx, "outbound connection to ", destination)
  317. case N.NetworkUDP:
  318. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  319. }
  320. if destination.IsFqdn() {
  321. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  322. if err != nil {
  323. return nil, err
  324. }
  325. return N.DialSerial(ctx, t, network, destination, destinationAddresses)
  326. }
  327. addr := tcpip.FullAddress{
  328. NIC: 1,
  329. Port: destination.Port,
  330. Addr: addressFromAddr(destination.Addr),
  331. }
  332. var networkProtocol tcpip.NetworkProtocolNumber
  333. if destination.IsIPv4() {
  334. networkProtocol = header.IPv4ProtocolNumber
  335. } else {
  336. networkProtocol = header.IPv6ProtocolNumber
  337. }
  338. switch N.NetworkName(network) {
  339. case N.NetworkTCP:
  340. tcpConn, err := gonet.DialContextTCP(ctx, t.stack, addr, networkProtocol)
  341. if err != nil {
  342. return nil, err
  343. }
  344. return tcpConn, nil
  345. case N.NetworkUDP:
  346. udpConn, err := gonet.DialUDP(t.stack, nil, &addr, networkProtocol)
  347. if err != nil {
  348. return nil, err
  349. }
  350. return udpConn, nil
  351. default:
  352. return nil, E.Extend(N.ErrUnknownNetwork, network)
  353. }
  354. }
  355. func (t *Endpoint) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  356. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  357. if destination.IsFqdn() {
  358. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  359. if err != nil {
  360. return nil, err
  361. }
  362. packetConn, _, err := N.ListenSerial(ctx, t, destination, destinationAddresses)
  363. if err != nil {
  364. return nil, err
  365. }
  366. return packetConn, err
  367. }
  368. addr4, addr6 := t.server.TailscaleIPs()
  369. bind := tcpip.FullAddress{
  370. NIC: 1,
  371. }
  372. var networkProtocol tcpip.NetworkProtocolNumber
  373. if destination.IsIPv4() {
  374. if !addr4.IsValid() {
  375. return nil, E.New("missing Tailscale IPv4 address")
  376. }
  377. networkProtocol = header.IPv4ProtocolNumber
  378. bind.Addr = addressFromAddr(addr4)
  379. } else {
  380. if !addr6.IsValid() {
  381. return nil, E.New("missing Tailscale IPv6 address")
  382. }
  383. networkProtocol = header.IPv6ProtocolNumber
  384. bind.Addr = addressFromAddr(addr6)
  385. }
  386. udpConn, err := gonet.DialUDP(t.stack, &bind, nil, networkProtocol)
  387. if err != nil {
  388. return nil, err
  389. }
  390. return udpConn, nil
  391. }
  392. func (t *Endpoint) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  393. tsFilter := t.filter.Load()
  394. if tsFilter != nil {
  395. var ipProto ipproto.Proto
  396. switch N.NetworkName(network) {
  397. case N.NetworkTCP:
  398. ipProto = ipproto.TCP
  399. case N.NetworkUDP:
  400. ipProto = ipproto.UDP
  401. }
  402. response := tsFilter.Check(source.Addr, destination.Addr, destination.Port, ipProto)
  403. switch response {
  404. case filter.Drop:
  405. return syscall.ECONNRESET
  406. case filter.DropSilently:
  407. return tun.ErrDrop
  408. }
  409. }
  410. return t.router.PreMatch(adapter.InboundContext{
  411. Inbound: t.Tag(),
  412. InboundType: t.Type(),
  413. Network: network,
  414. Source: source,
  415. Destination: destination,
  416. })
  417. }
  418. func (t *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  419. var metadata adapter.InboundContext
  420. metadata.Inbound = t.Tag()
  421. metadata.InboundType = t.Type()
  422. metadata.Source = source
  423. addr4, addr6 := t.server.TailscaleIPs()
  424. switch destination.Addr {
  425. case addr4:
  426. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  427. case addr6:
  428. destination.Addr = netip.IPv6Loopback()
  429. }
  430. metadata.Destination = destination
  431. t.logger.InfoContext(ctx, "inbound connection from ", source)
  432. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  433. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  434. }
  435. func (t *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  436. var metadata adapter.InboundContext
  437. metadata.Inbound = t.Tag()
  438. metadata.InboundType = t.Type()
  439. metadata.Source = source
  440. metadata.Destination = destination
  441. addr4, addr6 := t.server.TailscaleIPs()
  442. switch destination.Addr {
  443. case addr4:
  444. metadata.OriginDestination = destination
  445. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  446. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  447. case addr6:
  448. metadata.OriginDestination = destination
  449. destination.Addr = netip.IPv6Loopback()
  450. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  451. }
  452. t.logger.InfoContext(ctx, "inbound packet connection from ", source)
  453. t.logger.InfoContext(ctx, "inbound packet connection to ", destination)
  454. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  455. }
  456. func (t *Endpoint) Server() *tsnet.Server {
  457. return t.server
  458. }
  459. func addressFromAddr(destination netip.Addr) tcpip.Address {
  460. if destination.Is6() {
  461. return tcpip.AddrFrom16(destination.As16())
  462. } else {
  463. return tcpip.AddrFrom4(destination.As4())
  464. }
  465. }
  466. type endpointDialer struct {
  467. N.Dialer
  468. logger logger.ContextLogger
  469. }
  470. func (d *endpointDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  471. switch N.NetworkName(network) {
  472. case N.NetworkTCP:
  473. d.logger.InfoContext(ctx, "output connection to ", destination)
  474. case N.NetworkUDP:
  475. d.logger.InfoContext(ctx, "output packet connection to ", destination)
  476. }
  477. return d.Dialer.DialContext(ctx, network, destination)
  478. }
  479. func (d *endpointDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  480. d.logger.InfoContext(ctx, "output packet connection")
  481. return d.Dialer.ListenPacket(ctx, destination)
  482. }
  483. type dnsConfigurtor struct {
  484. baseConfig tsDNS.OSConfig
  485. }
  486. func (c *dnsConfigurtor) SetDNS(cfg tsDNS.OSConfig) error {
  487. c.baseConfig = cfg
  488. return nil
  489. }
  490. func (c *dnsConfigurtor) SupportsSplitDNS() bool {
  491. return true
  492. }
  493. func (c *dnsConfigurtor) GetBaseConfig() (tsDNS.OSConfig, error) {
  494. return c.baseConfig, nil
  495. }
  496. func (c *dnsConfigurtor) Close() error {
  497. return nil
  498. }