1
0

endpoint.go 15 KB

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