endpoint.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. ipStack.SetTransportProtocolHandler(tcp.ProtocolNumber, tun.NewTCPForwarder(t.ctx, ipStack, t).HandlePacket)
  215. udpForwarder := tun.NewUDPForwarder(t.ctx, ipStack, t, t.udpTimeout)
  216. ipStack.SetTransportProtocolHandler(udp.ProtocolNumber, udpForwarder.HandlePacket)
  217. t.stack = ipStack
  218. localBackend := t.server.ExportLocalBackend()
  219. perfs := &ipn.MaskedPrefs{
  220. Prefs: ipn.Prefs{
  221. RouteAll: t.acceptRoutes,
  222. },
  223. RouteAllSet: true,
  224. ExitNodeIPSet: true,
  225. AdvertiseRoutesSet: true,
  226. }
  227. if len(t.advertiseRoutes) > 0 {
  228. perfs.AdvertiseRoutes = t.advertiseRoutes
  229. }
  230. if t.advertiseExitNode {
  231. perfs.AdvertiseRoutes = append(perfs.AdvertiseRoutes, tsaddr.ExitRoutes()...)
  232. }
  233. _, err = localBackend.EditPrefs(perfs)
  234. if err != nil {
  235. return E.Cause(err, "update prefs")
  236. }
  237. t.filter = localBackend.ExportFilter()
  238. go t.watchState()
  239. return nil
  240. }
  241. func (t *Endpoint) watchState() {
  242. localBackend := t.server.ExportLocalBackend()
  243. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  244. if roNotify.State != nil && *roNotify.State != ipn.NeedsLogin && *roNotify.State != ipn.NoState {
  245. return false
  246. }
  247. authURL := localBackend.StatusWithoutPeers().AuthURL
  248. if authURL != "" {
  249. t.logger.Info("Waiting for authentication: ", authURL)
  250. if t.platformInterface != nil {
  251. err := t.platformInterface.SendNotification(&platform.Notification{
  252. Identifier: "tailscale-authentication",
  253. TypeName: "Tailscale Authentication Notifications",
  254. TypeID: 10,
  255. Title: "Tailscale Authentication",
  256. Body: F.ToString("Tailscale outbound[", t.Tag(), "] is waiting for authentication."),
  257. OpenURL: authURL,
  258. })
  259. if err != nil {
  260. t.logger.Error("send authentication notification: ", err)
  261. }
  262. }
  263. return false
  264. }
  265. return true
  266. })
  267. if t.exitNode != "" {
  268. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  269. if roNotify.State == nil || *roNotify.State != ipn.Running {
  270. return true
  271. }
  272. status, err := common.Must1(t.server.LocalClient()).Status(t.ctx)
  273. if err != nil {
  274. t.logger.Error("set exit node: ", err)
  275. return
  276. }
  277. perfs := &ipn.MaskedPrefs{
  278. Prefs: ipn.Prefs{
  279. ExitNodeAllowLANAccess: t.exitNodeAllowLANAccess,
  280. },
  281. ExitNodeIPSet: true,
  282. ExitNodeAllowLANAccessSet: true,
  283. }
  284. err = perfs.SetExitNodeIP(t.exitNode, status)
  285. if err != nil {
  286. t.logger.Error("set exit node: ", err)
  287. return true
  288. }
  289. _, err = localBackend.EditPrefs(perfs)
  290. if err != nil {
  291. t.logger.Error("set exit node: ", err)
  292. return true
  293. }
  294. return false
  295. })
  296. }
  297. }
  298. func (t *Endpoint) Close() error {
  299. netmon.RegisterInterfaceGetter(nil)
  300. if runtime.GOOS == "android" {
  301. setAndroidProtectFunc(nil)
  302. }
  303. return common.Close(common.PtrOrNil(t.server))
  304. }
  305. func (t *Endpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  306. switch network {
  307. case N.NetworkTCP:
  308. t.logger.InfoContext(ctx, "outbound connection to ", destination)
  309. case N.NetworkUDP:
  310. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  311. }
  312. if destination.IsFqdn() {
  313. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  314. if err != nil {
  315. return nil, err
  316. }
  317. return N.DialSerial(ctx, t, network, destination, destinationAddresses)
  318. }
  319. addr := tcpip.FullAddress{
  320. NIC: 1,
  321. Port: destination.Port,
  322. Addr: addressFromAddr(destination.Addr),
  323. }
  324. var networkProtocol tcpip.NetworkProtocolNumber
  325. if destination.IsIPv4() {
  326. networkProtocol = header.IPv4ProtocolNumber
  327. } else {
  328. networkProtocol = header.IPv6ProtocolNumber
  329. }
  330. switch N.NetworkName(network) {
  331. case N.NetworkTCP:
  332. tcpConn, err := gonet.DialContextTCP(ctx, t.stack, addr, networkProtocol)
  333. if err != nil {
  334. return nil, err
  335. }
  336. return tcpConn, nil
  337. case N.NetworkUDP:
  338. udpConn, err := gonet.DialUDP(t.stack, nil, &addr, networkProtocol)
  339. if err != nil {
  340. return nil, err
  341. }
  342. return udpConn, nil
  343. default:
  344. return nil, E.Extend(N.ErrUnknownNetwork, network)
  345. }
  346. }
  347. func (t *Endpoint) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  348. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  349. if destination.IsFqdn() {
  350. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  351. if err != nil {
  352. return nil, err
  353. }
  354. packetConn, _, err := N.ListenSerial(ctx, t, destination, destinationAddresses)
  355. if err != nil {
  356. return nil, err
  357. }
  358. return packetConn, err
  359. }
  360. addr4, addr6 := t.server.TailscaleIPs()
  361. bind := tcpip.FullAddress{
  362. NIC: 1,
  363. }
  364. var networkProtocol tcpip.NetworkProtocolNumber
  365. if destination.IsIPv4() {
  366. if !addr4.IsValid() {
  367. return nil, E.New("missing Tailscale IPv4 address")
  368. }
  369. networkProtocol = header.IPv4ProtocolNumber
  370. bind.Addr = addressFromAddr(addr4)
  371. } else {
  372. if !addr6.IsValid() {
  373. return nil, E.New("missing Tailscale IPv6 address")
  374. }
  375. networkProtocol = header.IPv6ProtocolNumber
  376. bind.Addr = addressFromAddr(addr6)
  377. }
  378. udpConn, err := gonet.DialUDP(t.stack, &bind, nil, networkProtocol)
  379. if err != nil {
  380. return nil, err
  381. }
  382. return udpConn, nil
  383. }
  384. func (t *Endpoint) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr) error {
  385. tsFilter := t.filter.Load()
  386. if tsFilter != nil {
  387. var ipProto ipproto.Proto
  388. switch N.NetworkName(network) {
  389. case N.NetworkTCP:
  390. ipProto = ipproto.TCP
  391. case N.NetworkUDP:
  392. ipProto = ipproto.UDP
  393. }
  394. response := tsFilter.Check(source.Addr, destination.Addr, destination.Port, ipProto)
  395. switch response {
  396. case filter.Drop:
  397. return syscall.ECONNRESET
  398. case filter.DropSilently:
  399. return tun.ErrDrop
  400. }
  401. }
  402. return t.router.PreMatch(adapter.InboundContext{
  403. Inbound: t.Tag(),
  404. InboundType: t.Type(),
  405. Network: network,
  406. Source: source,
  407. Destination: destination,
  408. })
  409. }
  410. func (t *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  411. var metadata adapter.InboundContext
  412. metadata.Inbound = t.Tag()
  413. metadata.InboundType = t.Type()
  414. metadata.Source = source
  415. addr4, addr6 := t.server.TailscaleIPs()
  416. switch destination.Addr {
  417. case addr4:
  418. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  419. case addr6:
  420. destination.Addr = netip.IPv6Loopback()
  421. }
  422. metadata.Destination = destination
  423. t.logger.InfoContext(ctx, "inbound connection from ", source)
  424. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  425. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  426. }
  427. func (t *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  428. var metadata adapter.InboundContext
  429. metadata.Inbound = t.Tag()
  430. metadata.InboundType = t.Type()
  431. metadata.Source = source
  432. metadata.Destination = destination
  433. addr4, addr6 := t.server.TailscaleIPs()
  434. switch destination.Addr {
  435. case addr4:
  436. metadata.OriginDestination = destination
  437. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  438. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  439. case addr6:
  440. metadata.OriginDestination = destination
  441. destination.Addr = netip.IPv6Loopback()
  442. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  443. }
  444. t.logger.InfoContext(ctx, "inbound packet connection from ", source)
  445. t.logger.InfoContext(ctx, "inbound packet connection to ", destination)
  446. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  447. }
  448. func (t *Endpoint) Server() *tsnet.Server {
  449. return t.server
  450. }
  451. func addressFromAddr(destination netip.Addr) tcpip.Address {
  452. if destination.Is6() {
  453. return tcpip.AddrFrom16(destination.As16())
  454. } else {
  455. return tcpip.AddrFrom4(destination.As4())
  456. }
  457. }
  458. type endpointDialer struct {
  459. N.Dialer
  460. logger logger.ContextLogger
  461. }
  462. func (d *endpointDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  463. switch N.NetworkName(network) {
  464. case N.NetworkTCP:
  465. d.logger.InfoContext(ctx, "output connection to ", destination)
  466. case N.NetworkUDP:
  467. d.logger.InfoContext(ctx, "output packet connection to ", destination)
  468. }
  469. return d.Dialer.DialContext(ctx, network, destination)
  470. }
  471. func (d *endpointDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  472. d.logger.InfoContext(ctx, "output packet connection")
  473. return d.Dialer.ListenPacket(ctx, destination)
  474. }
  475. type dnsConfigurtor struct {
  476. baseConfig tsDNS.OSConfig
  477. }
  478. func (c *dnsConfigurtor) SetDNS(cfg tsDNS.OSConfig) error {
  479. c.baseConfig = cfg
  480. return nil
  481. }
  482. func (c *dnsConfigurtor) SupportsSplitDNS() bool {
  483. return true
  484. }
  485. func (c *dnsConfigurtor) GetBaseConfig() (tsDNS.OSConfig, error) {
  486. return c.baseConfig, nil
  487. }
  488. func (c *dnsConfigurtor) Close() error {
  489. return nil
  490. }