endpoint.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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/icmp"
  20. "github.com/sagernet/gvisor/pkg/tcpip/transport/tcp"
  21. "github.com/sagernet/gvisor/pkg/tcpip/transport/udp"
  22. "github.com/sagernet/sing-box/adapter"
  23. "github.com/sagernet/sing-box/adapter/endpoint"
  24. "github.com/sagernet/sing-box/common/dialer"
  25. C "github.com/sagernet/sing-box/constant"
  26. "github.com/sagernet/sing-box/experimental/libbox/platform"
  27. "github.com/sagernet/sing-box/log"
  28. "github.com/sagernet/sing-box/option"
  29. "github.com/sagernet/sing-tun"
  30. "github.com/sagernet/sing/common"
  31. "github.com/sagernet/sing/common/bufio"
  32. "github.com/sagernet/sing/common/control"
  33. E "github.com/sagernet/sing/common/exceptions"
  34. F "github.com/sagernet/sing/common/format"
  35. "github.com/sagernet/sing/common/logger"
  36. M "github.com/sagernet/sing/common/metadata"
  37. N "github.com/sagernet/sing/common/network"
  38. "github.com/sagernet/sing/service"
  39. "github.com/sagernet/sing/service/filemanager"
  40. "github.com/sagernet/tailscale/ipn"
  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. }
  142. return &Endpoint{
  143. Adapter: endpoint.NewAdapter(C.TypeTailscale, tag, []string{N.NetworkTCP, N.NetworkUDP}, nil),
  144. ctx: ctx,
  145. router: router,
  146. logger: logger,
  147. dnsRouter: dnsRouter,
  148. network: service.FromContext[adapter.NetworkManager](ctx),
  149. platformInterface: service.FromContext[platform.Interface](ctx),
  150. server: server,
  151. exitNode: options.ExitNode,
  152. exitNodeAllowLANAccess: options.ExitNodeAllowLANAccess,
  153. advertiseRoutes: options.AdvertiseRoutes,
  154. advertiseExitNode: options.AdvertiseExitNode,
  155. udpTimeout: udpTimeout,
  156. }, nil
  157. }
  158. func (t *Endpoint) Start(stage adapter.StartStage) error {
  159. if stage != adapter.StartStateStart {
  160. return nil
  161. }
  162. if t.platformInterface != nil {
  163. err := t.network.UpdateInterfaces()
  164. if err != nil {
  165. return err
  166. }
  167. netmon.RegisterInterfaceGetter(func() ([]netmon.Interface, error) {
  168. return common.Map(t.network.InterfaceFinder().Interfaces(), func(it control.Interface) netmon.Interface {
  169. return netmon.Interface{
  170. Interface: &net.Interface{
  171. Index: it.Index,
  172. MTU: it.MTU,
  173. Name: it.Name,
  174. HardwareAddr: it.HardwareAddr,
  175. Flags: it.Flags,
  176. },
  177. AltAddrs: common.Map(it.Addresses, func(it netip.Prefix) net.Addr {
  178. return &net.IPNet{
  179. IP: it.Addr().AsSlice(),
  180. Mask: net.CIDRMask(it.Bits(), it.Addr().BitLen()),
  181. }
  182. }),
  183. }
  184. }), nil
  185. })
  186. if runtime.GOOS == "android" {
  187. setAndroidProtectFunc(t.platformInterface)
  188. }
  189. }
  190. err := t.server.Start()
  191. if err != nil {
  192. return err
  193. }
  194. if t.onReconfig != nil {
  195. t.server.ExportLocalBackend().ExportEngine().(wgengine.ExportedUserspaceEngine).SetOnReconfigListener(t.onReconfig)
  196. }
  197. ipStack := t.server.ExportNetstack().ExportIPStack()
  198. ipStack.SetTransportProtocolHandler(tcp.ProtocolNumber, tun.NewTCPForwarder(t.ctx, ipStack, t).HandlePacket)
  199. ipStack.SetTransportProtocolHandler(udp.ProtocolNumber, tun.NewUDPForwarder(t.ctx, ipStack, t, t.udpTimeout).HandlePacket)
  200. icmpForwarder := tun.NewICMPForwarder(t.ctx, ipStack, t, t.udpTimeout)
  201. ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber4, icmpForwarder.HandlePacket)
  202. ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber6, icmpForwarder.HandlePacket)
  203. t.stack = ipStack
  204. localBackend := t.server.ExportLocalBackend()
  205. perfs := &ipn.MaskedPrefs{
  206. ExitNodeIPSet: true,
  207. AdvertiseRoutesSet: true,
  208. }
  209. if len(t.advertiseRoutes) > 0 {
  210. perfs.AdvertiseRoutes = t.advertiseRoutes
  211. }
  212. if t.advertiseExitNode {
  213. perfs.AdvertiseRoutes = append(perfs.AdvertiseRoutes, tsaddr.ExitRoutes()...)
  214. }
  215. _, err = localBackend.EditPrefs(perfs)
  216. if err != nil {
  217. return E.Cause(err, "update prefs")
  218. }
  219. t.filter = localBackend.ExportFilter()
  220. go t.watchState()
  221. return nil
  222. }
  223. func (t *Endpoint) watchState() {
  224. localBackend := t.server.ExportLocalBackend()
  225. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  226. if roNotify.State != nil && *roNotify.State != ipn.NeedsLogin && *roNotify.State != ipn.NoState {
  227. return false
  228. }
  229. authURL := localBackend.StatusWithoutPeers().AuthURL
  230. if authURL != "" {
  231. t.logger.Info("Waiting for authentication: ", authURL)
  232. if t.platformInterface != nil {
  233. err := t.platformInterface.SendNotification(&platform.Notification{
  234. Identifier: "tailscale-authentication",
  235. TypeName: "Tailscale Authentication Notifications",
  236. TypeID: 10,
  237. Title: "Tailscale Authentication",
  238. Body: F.ToString("Tailscale outbound[", t.Tag(), "] is waiting for authentication."),
  239. OpenURL: authURL,
  240. })
  241. if err != nil {
  242. t.logger.Error("send authentication notification: ", err)
  243. }
  244. }
  245. return false
  246. }
  247. return true
  248. })
  249. if t.exitNode != "" {
  250. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  251. if roNotify.State == nil || *roNotify.State != ipn.Running {
  252. return true
  253. }
  254. status, err := common.Must1(t.server.LocalClient()).Status(t.ctx)
  255. if err != nil {
  256. t.logger.Error("set exit node: ", err)
  257. return
  258. }
  259. perfs := &ipn.MaskedPrefs{
  260. Prefs: ipn.Prefs{
  261. ExitNodeAllowLANAccess: t.exitNodeAllowLANAccess,
  262. },
  263. ExitNodeIPSet: true,
  264. ExitNodeAllowLANAccessSet: true,
  265. }
  266. err = perfs.SetExitNodeIP(t.exitNode, status)
  267. if err != nil {
  268. t.logger.Error("set exit node: ", err)
  269. return true
  270. }
  271. _, err = localBackend.EditPrefs(perfs)
  272. if err != nil {
  273. t.logger.Error("set exit node: ", err)
  274. return true
  275. }
  276. return false
  277. })
  278. }
  279. }
  280. func (t *Endpoint) Close() error {
  281. netmon.RegisterInterfaceGetter(nil)
  282. if runtime.GOOS == "android" {
  283. setAndroidProtectFunc(nil)
  284. }
  285. return common.Close(common.PtrOrNil(t.server))
  286. }
  287. func (t *Endpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  288. switch network {
  289. case N.NetworkTCP:
  290. t.logger.InfoContext(ctx, "outbound connection to ", destination)
  291. case N.NetworkUDP:
  292. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  293. }
  294. if destination.IsFqdn() {
  295. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  296. if err != nil {
  297. return nil, err
  298. }
  299. return N.DialSerial(ctx, t, network, destination, destinationAddresses)
  300. }
  301. addr := tcpip.FullAddress{
  302. NIC: 1,
  303. Port: destination.Port,
  304. Addr: addressFromAddr(destination.Addr),
  305. }
  306. var networkProtocol tcpip.NetworkProtocolNumber
  307. if destination.IsIPv4() {
  308. networkProtocol = header.IPv4ProtocolNumber
  309. } else {
  310. networkProtocol = header.IPv6ProtocolNumber
  311. }
  312. switch N.NetworkName(network) {
  313. case N.NetworkTCP:
  314. tcpConn, err := gonet.DialContextTCP(ctx, t.stack, addr, networkProtocol)
  315. if err != nil {
  316. return nil, err
  317. }
  318. return tcpConn, nil
  319. case N.NetworkUDP:
  320. udpConn, err := gonet.DialUDP(t.stack, nil, &addr, networkProtocol)
  321. if err != nil {
  322. return nil, err
  323. }
  324. return udpConn, nil
  325. default:
  326. return nil, E.Extend(N.ErrUnknownNetwork, network)
  327. }
  328. }
  329. func (t *Endpoint) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  330. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  331. if destination.IsFqdn() {
  332. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  333. if err != nil {
  334. return nil, err
  335. }
  336. packetConn, _, err := N.ListenSerial(ctx, t, destination, destinationAddresses)
  337. if err != nil {
  338. return nil, err
  339. }
  340. return packetConn, err
  341. }
  342. addr4, addr6 := t.server.TailscaleIPs()
  343. bind := tcpip.FullAddress{
  344. NIC: 1,
  345. }
  346. var networkProtocol tcpip.NetworkProtocolNumber
  347. if destination.IsIPv4() {
  348. if !addr4.IsValid() {
  349. return nil, E.New("missing Tailscale IPv4 address")
  350. }
  351. networkProtocol = header.IPv4ProtocolNumber
  352. bind.Addr = addressFromAddr(addr4)
  353. } else {
  354. if !addr6.IsValid() {
  355. return nil, E.New("missing Tailscale IPv6 address")
  356. }
  357. networkProtocol = header.IPv6ProtocolNumber
  358. bind.Addr = addressFromAddr(addr6)
  359. }
  360. udpConn, err := gonet.DialUDP(t.stack, &bind, nil, networkProtocol)
  361. if err != nil {
  362. return nil, err
  363. }
  364. return udpConn, nil
  365. }
  366. func (t *Endpoint) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr, routeContext tun.DirectRouteContext) (tun.DirectRouteDestination, error) {
  367. tsFilter := t.filter.Load()
  368. if tsFilter != nil {
  369. var ipProto ipproto.Proto
  370. switch N.NetworkName(network) {
  371. case N.NetworkTCP:
  372. ipProto = ipproto.TCP
  373. case N.NetworkUDP:
  374. ipProto = ipproto.UDP
  375. }
  376. response := tsFilter.Check(source.Addr, destination.Addr, destination.Port, ipProto)
  377. switch response {
  378. case filter.Drop:
  379. return nil, syscall.ECONNREFUSED
  380. case filter.DropSilently:
  381. return nil, tun.ErrDrop
  382. }
  383. }
  384. return t.router.PreMatch(adapter.InboundContext{
  385. Inbound: t.Tag(),
  386. InboundType: t.Type(),
  387. Network: network,
  388. Source: source,
  389. Destination: destination,
  390. }, routeContext)
  391. }
  392. func (t *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  393. var metadata adapter.InboundContext
  394. metadata.Inbound = t.Tag()
  395. metadata.InboundType = t.Type()
  396. metadata.Source = source
  397. addr4, addr6 := t.server.TailscaleIPs()
  398. switch destination.Addr {
  399. case addr4:
  400. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  401. case addr6:
  402. destination.Addr = netip.IPv6Loopback()
  403. }
  404. metadata.Destination = destination
  405. t.logger.InfoContext(ctx, "inbound connection from ", source)
  406. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  407. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  408. }
  409. func (t *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  410. var metadata adapter.InboundContext
  411. metadata.Inbound = t.Tag()
  412. metadata.InboundType = t.Type()
  413. metadata.Source = source
  414. metadata.Destination = destination
  415. addr4, addr6 := t.server.TailscaleIPs()
  416. switch destination.Addr {
  417. case addr4:
  418. metadata.OriginDestination = destination
  419. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  420. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  421. case addr6:
  422. metadata.OriginDestination = destination
  423. destination.Addr = netip.IPv6Loopback()
  424. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, metadata.Destination)
  425. }
  426. t.logger.InfoContext(ctx, "inbound packet connection from ", source)
  427. t.logger.InfoContext(ctx, "inbound packet connection to ", destination)
  428. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  429. }
  430. func addressFromAddr(destination netip.Addr) tcpip.Address {
  431. if destination.Is6() {
  432. return tcpip.AddrFrom16(destination.As16())
  433. } else {
  434. return tcpip.AddrFrom4(destination.As4())
  435. }
  436. }
  437. type endpointDialer struct {
  438. N.Dialer
  439. logger logger.ContextLogger
  440. }
  441. func (d *endpointDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  442. switch N.NetworkName(network) {
  443. case N.NetworkTCP:
  444. d.logger.InfoContext(ctx, "output connection to ", destination)
  445. case N.NetworkUDP:
  446. d.logger.InfoContext(ctx, "output packet connection to ", destination)
  447. }
  448. return d.Dialer.DialContext(ctx, network, destination)
  449. }
  450. func (d *endpointDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  451. d.logger.InfoContext(ctx, "output packet connection")
  452. return d.Dialer.ListenPacket(ctx, destination)
  453. }