endpoint.go 15 KB

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