endpoint.go 13 KB

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