endpoint.go 16 KB

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