endpoint.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. //go:build with_gvisor
  2. package tailscale
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/netip"
  10. "net/url"
  11. "os"
  12. "path/filepath"
  13. "reflect"
  14. "runtime"
  15. "strings"
  16. "sync/atomic"
  17. "syscall"
  18. "time"
  19. "github.com/sagernet/gvisor/pkg/tcpip"
  20. "github.com/sagernet/gvisor/pkg/tcpip/adapters/gonet"
  21. "github.com/sagernet/gvisor/pkg/tcpip/header"
  22. "github.com/sagernet/gvisor/pkg/tcpip/stack"
  23. "github.com/sagernet/gvisor/pkg/tcpip/transport/icmp"
  24. "github.com/sagernet/sing-box/adapter"
  25. "github.com/sagernet/sing-box/adapter/endpoint"
  26. "github.com/sagernet/sing-box/common/dialer"
  27. C "github.com/sagernet/sing-box/constant"
  28. "github.com/sagernet/sing-box/log"
  29. "github.com/sagernet/sing-box/option"
  30. "github.com/sagernet/sing-box/route/rule"
  31. "github.com/sagernet/sing-tun"
  32. "github.com/sagernet/sing-tun/ping"
  33. "github.com/sagernet/sing/common"
  34. "github.com/sagernet/sing/common/bufio"
  35. "github.com/sagernet/sing/common/control"
  36. E "github.com/sagernet/sing/common/exceptions"
  37. F "github.com/sagernet/sing/common/format"
  38. "github.com/sagernet/sing/common/logger"
  39. M "github.com/sagernet/sing/common/metadata"
  40. N "github.com/sagernet/sing/common/network"
  41. "github.com/sagernet/sing/common/ntp"
  42. "github.com/sagernet/sing/service"
  43. "github.com/sagernet/sing/service/filemanager"
  44. _ "github.com/sagernet/tailscale/feature/relayserver"
  45. "github.com/sagernet/tailscale/ipn"
  46. tsDNS "github.com/sagernet/tailscale/net/dns"
  47. "github.com/sagernet/tailscale/net/netmon"
  48. "github.com/sagernet/tailscale/net/netns"
  49. "github.com/sagernet/tailscale/net/tsaddr"
  50. tsTUN "github.com/sagernet/tailscale/net/tstun"
  51. "github.com/sagernet/tailscale/tsnet"
  52. "github.com/sagernet/tailscale/types/ipproto"
  53. "github.com/sagernet/tailscale/types/nettype"
  54. "github.com/sagernet/tailscale/version"
  55. "github.com/sagernet/tailscale/wgengine"
  56. "github.com/sagernet/tailscale/wgengine/filter"
  57. "github.com/sagernet/tailscale/wgengine/router"
  58. "github.com/sagernet/tailscale/wgengine/wgcfg"
  59. "go4.org/netipx"
  60. )
  61. var (
  62. _ adapter.OutboundWithPreferredRoutes = (*Endpoint)(nil)
  63. _ adapter.DirectRouteOutbound = (*Endpoint)(nil)
  64. _ dialer.PacketDialerWithDestination = (*Endpoint)(nil)
  65. )
  66. func init() {
  67. version.SetVersion("sing-box " + C.Version)
  68. }
  69. func RegisterEndpoint(registry *endpoint.Registry) {
  70. endpoint.Register[option.TailscaleEndpointOptions](registry, C.TypeTailscale, NewEndpoint)
  71. }
  72. type Endpoint struct {
  73. endpoint.Adapter
  74. ctx context.Context
  75. router adapter.Router
  76. logger logger.ContextLogger
  77. dnsRouter adapter.DNSRouter
  78. network adapter.NetworkManager
  79. platformInterface adapter.PlatformInterface
  80. server *tsnet.Server
  81. stack *stack.Stack
  82. icmpForwarder *tun.ICMPForwarder
  83. filter *atomic.Pointer[filter.Filter]
  84. onReconfigHook wgengine.ReconfigListener
  85. cfg *wgcfg.Config
  86. dnsCfg *tsDNS.Config
  87. routeDomains common.TypedValue[map[string]bool]
  88. routePrefixes atomic.Pointer[netipx.IPSet]
  89. acceptRoutes bool
  90. exitNode string
  91. exitNodeAllowLANAccess bool
  92. advertiseRoutes []netip.Prefix
  93. advertiseExitNode bool
  94. advertiseTags []string
  95. relayServerPort *uint16
  96. relayServerStaticEndpoints []netip.AddrPort
  97. udpTimeout time.Duration
  98. systemInterface bool
  99. systemInterfaceName string
  100. systemInterfaceMTU uint32
  101. systemTun tun.Tun
  102. systemDialer *dialer.DefaultDialer
  103. fallbackTCPCloser func()
  104. }
  105. func (t *Endpoint) registerNetstackHandlers() {
  106. netstack := t.server.ExportNetstack()
  107. if netstack == nil {
  108. return
  109. }
  110. previousTCP := netstack.GetTCPHandlerForFlow
  111. netstack.GetTCPHandlerForFlow = func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool) {
  112. if previousTCP != nil {
  113. handler, intercept = previousTCP(src, dst)
  114. if handler != nil || !intercept {
  115. return handler, intercept
  116. }
  117. }
  118. return func(conn net.Conn) {
  119. ctx := log.ContextWithNewID(t.ctx)
  120. source := M.SocksaddrFrom(src.Addr(), src.Port())
  121. destination := M.SocksaddrFrom(dst.Addr(), dst.Port())
  122. t.NewConnectionEx(ctx, conn, source, destination, nil)
  123. }, true
  124. }
  125. previousUDP := netstack.GetUDPHandlerForFlow
  126. netstack.GetUDPHandlerForFlow = func(src, dst netip.AddrPort) (handler func(nettype.ConnPacketConn), intercept bool) {
  127. if previousUDP != nil {
  128. handler, intercept = previousUDP(src, dst)
  129. if handler != nil || !intercept {
  130. return handler, intercept
  131. }
  132. }
  133. return func(conn nettype.ConnPacketConn) {
  134. ctx := log.ContextWithNewID(t.ctx)
  135. source := M.SocksaddrFrom(src.Addr(), src.Port())
  136. destination := M.SocksaddrFrom(dst.Addr(), dst.Port())
  137. packetConn := bufio.NewUnbindPacketConnWithAddr(conn, destination)
  138. t.NewPacketConnectionEx(ctx, packetConn, source, destination, nil)
  139. }, true
  140. }
  141. }
  142. func NewEndpoint(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TailscaleEndpointOptions) (adapter.Endpoint, error) {
  143. stateDirectory := options.StateDirectory
  144. if stateDirectory == "" {
  145. stateDirectory = "tailscale"
  146. }
  147. hostname := options.Hostname
  148. if hostname == "" {
  149. osHostname, _ := os.Hostname()
  150. osHostname = strings.TrimSpace(osHostname)
  151. hostname = osHostname
  152. }
  153. if hostname == "" {
  154. hostname = "sing-box"
  155. }
  156. stateDirectory = filemanager.BasePath(ctx, os.ExpandEnv(stateDirectory))
  157. stateDirectory, _ = filepath.Abs(stateDirectory)
  158. for _, advertiseRoute := range options.AdvertiseRoutes {
  159. if advertiseRoute.Addr().IsUnspecified() && advertiseRoute.Bits() == 0 {
  160. return nil, E.New("`advertise_routes` cannot be default, use `advertise_exit_node` instead.")
  161. }
  162. }
  163. if options.AdvertiseExitNode && options.ExitNode != "" {
  164. return nil, E.New("cannot advertise an exit node and use an exit node at the same time.")
  165. }
  166. var udpTimeout time.Duration
  167. if options.UDPTimeout != 0 {
  168. udpTimeout = time.Duration(options.UDPTimeout)
  169. } else {
  170. udpTimeout = C.UDPTimeout
  171. }
  172. var remoteIsDomain bool
  173. if options.ControlURL != "" {
  174. controlURL, err := url.Parse(options.ControlURL)
  175. if err != nil {
  176. return nil, E.Cause(err, "parse control URL")
  177. }
  178. remoteIsDomain = M.ParseSocksaddr(controlURL.Hostname()).IsDomain()
  179. } else {
  180. // controlplane.tailscale.com
  181. remoteIsDomain = true
  182. }
  183. outboundDialer, err := dialer.NewWithOptions(dialer.Options{
  184. Context: ctx,
  185. Options: options.DialerOptions,
  186. RemoteIsDomain: remoteIsDomain,
  187. ResolverOnDetour: true,
  188. NewDialer: true,
  189. })
  190. if err != nil {
  191. return nil, err
  192. }
  193. dnsRouter := service.FromContext[adapter.DNSRouter](ctx)
  194. server := &tsnet.Server{
  195. Dir: stateDirectory,
  196. Hostname: hostname,
  197. Logf: func(format string, args ...any) {
  198. logger.Trace(fmt.Sprintf(format, args...))
  199. },
  200. UserLogf: func(format string, args ...any) {
  201. logger.Debug(fmt.Sprintf(format, args...))
  202. },
  203. Ephemeral: options.Ephemeral,
  204. AuthKey: options.AuthKey,
  205. ControlURL: options.ControlURL,
  206. AdvertiseTags: options.AdvertiseTags,
  207. Dialer: &endpointDialer{Dialer: outboundDialer, logger: logger},
  208. LookupHook: func(ctx context.Context, host string) ([]netip.Addr, error) {
  209. return dnsRouter.Lookup(ctx, host, outboundDialer.(dialer.ResolveDialer).QueryOptions())
  210. },
  211. DNS: &dnsConfigurtor{},
  212. HTTPClient: &http.Client{
  213. Transport: &http.Transport{
  214. ForceAttemptHTTP2: true,
  215. DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
  216. return outboundDialer.DialContext(ctx, network, M.ParseSocksaddr(address))
  217. },
  218. TLSClientConfig: &tls.Config{
  219. RootCAs: adapter.RootPoolFromContext(ctx),
  220. Time: ntp.TimeFuncFromContext(ctx),
  221. },
  222. },
  223. },
  224. }
  225. return &Endpoint{
  226. Adapter: endpoint.NewAdapter(C.TypeTailscale, tag, []string{N.NetworkTCP, N.NetworkUDP, N.NetworkICMP}, nil),
  227. ctx: ctx,
  228. router: router,
  229. logger: logger,
  230. dnsRouter: dnsRouter,
  231. network: service.FromContext[adapter.NetworkManager](ctx),
  232. platformInterface: service.FromContext[adapter.PlatformInterface](ctx),
  233. server: server,
  234. acceptRoutes: options.AcceptRoutes,
  235. exitNode: options.ExitNode,
  236. exitNodeAllowLANAccess: options.ExitNodeAllowLANAccess,
  237. advertiseRoutes: options.AdvertiseRoutes,
  238. advertiseExitNode: options.AdvertiseExitNode,
  239. advertiseTags: options.AdvertiseTags,
  240. relayServerPort: options.RelayServerPort,
  241. relayServerStaticEndpoints: options.RelayServerStaticEndpoints,
  242. udpTimeout: udpTimeout,
  243. systemInterface: options.SystemInterface,
  244. systemInterfaceName: options.SystemInterfaceName,
  245. systemInterfaceMTU: options.SystemInterfaceMTU,
  246. }, nil
  247. }
  248. func (t *Endpoint) Start(stage adapter.StartStage) error {
  249. switch stage {
  250. case adapter.StartStateStart:
  251. return t.start()
  252. case adapter.StartStatePostStart:
  253. return t.postStart()
  254. }
  255. return nil
  256. }
  257. func (t *Endpoint) start() error {
  258. if t.platformInterface != nil {
  259. err := t.network.UpdateInterfaces()
  260. if err != nil {
  261. return err
  262. }
  263. netmon.RegisterInterfaceGetter(func() ([]netmon.Interface, error) {
  264. return common.Map(t.network.InterfaceFinder().Interfaces(), func(it control.Interface) netmon.Interface {
  265. return netmon.Interface{
  266. Interface: &net.Interface{
  267. Index: it.Index,
  268. MTU: it.MTU,
  269. Name: it.Name,
  270. HardwareAddr: it.HardwareAddr,
  271. Flags: it.Flags,
  272. },
  273. AltAddrs: common.Map(it.Addresses, func(it netip.Prefix) net.Addr {
  274. return &net.IPNet{
  275. IP: it.Addr().AsSlice(),
  276. Mask: net.CIDRMask(it.Bits(), it.Addr().BitLen()),
  277. }
  278. }),
  279. }
  280. }), nil
  281. })
  282. }
  283. if t.systemInterface {
  284. mtu := t.systemInterfaceMTU
  285. if mtu == 0 {
  286. mtu = uint32(tsTUN.DefaultTUNMTU())
  287. }
  288. tunName := t.systemInterfaceName
  289. if tunName == "" {
  290. tunName = tun.CalculateInterfaceName("tailscale")
  291. }
  292. tunOptions := tun.Options{
  293. Name: tunName,
  294. MTU: mtu,
  295. GSO: true,
  296. InterfaceScope: true,
  297. InterfaceMonitor: t.network.InterfaceMonitor(),
  298. InterfaceFinder: t.network.InterfaceFinder(),
  299. Logger: t.logger,
  300. EXP_ExternalConfiguration: true,
  301. }
  302. systemTun, err := tun.New(tunOptions)
  303. if err != nil {
  304. return err
  305. }
  306. err = systemTun.Start()
  307. if err != nil {
  308. _ = systemTun.Close()
  309. return err
  310. }
  311. wgTunDevice, err := newTunDeviceAdapter(systemTun, int(mtu), t.logger)
  312. if err != nil {
  313. _ = systemTun.Close()
  314. return err
  315. }
  316. systemDialer, err := dialer.NewDefault(t.ctx, option.DialerOptions{
  317. BindInterface: tunName,
  318. })
  319. if err != nil {
  320. _ = systemTun.Close()
  321. return err
  322. }
  323. t.systemTun = systemTun
  324. t.systemDialer = systemDialer
  325. t.server.TunDevice = wgTunDevice
  326. }
  327. if mark := t.network.AutoRedirectOutputMark(); mark > 0 {
  328. controlFunc := t.network.AutoRedirectOutputMarkFunc()
  329. if bindFunc := t.network.AutoDetectInterfaceFunc(); bindFunc != nil {
  330. controlFunc = control.Append(controlFunc, bindFunc)
  331. }
  332. netns.SetControlFunc(controlFunc)
  333. } else if runtime.GOOS == "android" && t.platformInterface != nil {
  334. netns.SetControlFunc(func(network, address string, c syscall.RawConn) error {
  335. return control.Raw(c, func(fd uintptr) error {
  336. return t.platformInterface.AutoDetectInterfaceControl(int(fd))
  337. })
  338. })
  339. }
  340. return nil
  341. }
  342. func (t *Endpoint) postStart() error {
  343. err := t.server.Start()
  344. if err != nil {
  345. if t.systemTun != nil {
  346. _ = t.systemTun.Close()
  347. }
  348. return err
  349. }
  350. if t.fallbackTCPCloser == nil {
  351. t.fallbackTCPCloser = t.server.RegisterFallbackTCPHandler(func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool) {
  352. return func(conn net.Conn) {
  353. ctx := log.ContextWithNewID(t.ctx)
  354. source := M.SocksaddrFrom(src.Addr(), src.Port())
  355. destination := M.SocksaddrFrom(dst.Addr(), dst.Port())
  356. t.NewConnectionEx(ctx, conn, source, destination, nil)
  357. }, true
  358. })
  359. }
  360. t.server.ExportLocalBackend().ExportEngine().(wgengine.ExportedUserspaceEngine).SetOnReconfigListener(t.onReconfig)
  361. ipStack := t.server.ExportNetstack().ExportIPStack()
  362. gErr := ipStack.SetSpoofing(tun.DefaultNIC, true)
  363. if gErr != nil {
  364. return gonet.TranslateNetstackError(gErr)
  365. }
  366. gErr = ipStack.SetPromiscuousMode(tun.DefaultNIC, true)
  367. if gErr != nil {
  368. return gonet.TranslateNetstackError(gErr)
  369. }
  370. icmpForwarder := tun.NewICMPForwarder(t.ctx, ipStack, t, t.udpTimeout)
  371. ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber4, icmpForwarder.HandlePacket)
  372. ipStack.SetTransportProtocolHandler(icmp.ProtocolNumber6, icmpForwarder.HandlePacket)
  373. t.stack = ipStack
  374. t.icmpForwarder = icmpForwarder
  375. t.registerNetstackHandlers()
  376. localBackend := t.server.ExportLocalBackend()
  377. perfs := &ipn.MaskedPrefs{
  378. Prefs: ipn.Prefs{
  379. RouteAll: t.acceptRoutes,
  380. AdvertiseRoutes: t.advertiseRoutes,
  381. },
  382. RouteAllSet: true,
  383. ExitNodeIPSet: true,
  384. AdvertiseRoutesSet: true,
  385. RelayServerPortSet: true,
  386. RelayServerStaticEndpointsSet: true,
  387. }
  388. if t.advertiseExitNode {
  389. perfs.AdvertiseRoutes = append(perfs.AdvertiseRoutes, tsaddr.ExitRoutes()...)
  390. }
  391. if t.relayServerPort != nil {
  392. perfs.RelayServerPort = t.relayServerPort
  393. }
  394. if len(t.relayServerStaticEndpoints) > 0 {
  395. perfs.RelayServerStaticEndpoints = t.relayServerStaticEndpoints
  396. }
  397. _, err = localBackend.EditPrefs(perfs)
  398. if err != nil {
  399. return E.Cause(err, "update prefs")
  400. }
  401. t.filter = localBackend.ExportFilter()
  402. go t.watchState()
  403. return nil
  404. }
  405. func (t *Endpoint) watchState() {
  406. localBackend := t.server.ExportLocalBackend()
  407. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  408. if roNotify.State != nil && *roNotify.State != ipn.NeedsLogin && *roNotify.State != ipn.NoState {
  409. return false
  410. }
  411. authURL := localBackend.StatusWithoutPeers().AuthURL
  412. if authURL != "" {
  413. t.logger.Info("Waiting for authentication: ", authURL)
  414. if t.platformInterface != nil {
  415. err := t.platformInterface.SendNotification(&adapter.Notification{
  416. Identifier: "tailscale-authentication",
  417. TypeName: "Tailscale Authentication Notifications",
  418. TypeID: 10,
  419. Title: "Tailscale Authentication",
  420. Body: F.ToString("Tailscale outbound[", t.Tag(), "] is waiting for authentication."),
  421. OpenURL: authURL,
  422. })
  423. if err != nil {
  424. t.logger.Error("send authentication notification: ", err)
  425. }
  426. }
  427. return false
  428. }
  429. return true
  430. })
  431. if t.exitNode != "" {
  432. localBackend.WatchNotifications(t.ctx, ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
  433. if roNotify.State == nil || *roNotify.State != ipn.Running {
  434. return true
  435. }
  436. status, err := common.Must1(t.server.LocalClient()).Status(t.ctx)
  437. if err != nil {
  438. t.logger.Error("set exit node: ", err)
  439. return
  440. }
  441. perfs := &ipn.MaskedPrefs{
  442. Prefs: ipn.Prefs{
  443. ExitNodeAllowLANAccess: t.exitNodeAllowLANAccess,
  444. },
  445. ExitNodeIPSet: true,
  446. ExitNodeAllowLANAccessSet: true,
  447. }
  448. err = perfs.SetExitNodeIP(t.exitNode, status)
  449. if err != nil {
  450. t.logger.Error("set exit node: ", err)
  451. return true
  452. }
  453. _, err = localBackend.EditPrefs(perfs)
  454. if err != nil {
  455. t.logger.Error("set exit node: ", err)
  456. return true
  457. }
  458. return false
  459. })
  460. }
  461. }
  462. func (t *Endpoint) Close() error {
  463. err := common.Close(common.PtrOrNil(t.server))
  464. netmon.RegisterInterfaceGetter(nil)
  465. netns.SetControlFunc(nil)
  466. if t.fallbackTCPCloser != nil {
  467. t.fallbackTCPCloser()
  468. t.fallbackTCPCloser = nil
  469. }
  470. if t.systemTun != nil {
  471. t.systemTun.Close()
  472. t.systemTun = nil
  473. }
  474. return err
  475. }
  476. func (t *Endpoint) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  477. switch network {
  478. case N.NetworkTCP:
  479. t.logger.InfoContext(ctx, "outbound connection to ", destination)
  480. case N.NetworkUDP:
  481. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  482. }
  483. if destination.IsDomain() {
  484. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  485. if err != nil {
  486. return nil, err
  487. }
  488. return N.DialSerial(ctx, t, network, destination, destinationAddresses)
  489. }
  490. if t.systemDialer != nil {
  491. return t.systemDialer.DialContext(ctx, network, destination)
  492. }
  493. addr4, addr6 := t.server.TailscaleIPs()
  494. remoteAddr := tcpip.FullAddress{
  495. NIC: 1,
  496. Port: destination.Port,
  497. Addr: addressFromAddr(destination.Addr),
  498. }
  499. var localAddr tcpip.FullAddress
  500. var networkProtocol tcpip.NetworkProtocolNumber
  501. if destination.IsIPv4() {
  502. if !addr4.IsValid() {
  503. return nil, E.New("missing Tailscale IPv4 address")
  504. }
  505. networkProtocol = header.IPv4ProtocolNumber
  506. localAddr = tcpip.FullAddress{
  507. NIC: 1,
  508. Addr: addressFromAddr(addr4),
  509. }
  510. } else {
  511. if !addr6.IsValid() {
  512. return nil, E.New("missing Tailscale IPv6 address")
  513. }
  514. networkProtocol = header.IPv6ProtocolNumber
  515. localAddr = tcpip.FullAddress{
  516. NIC: 1,
  517. Addr: addressFromAddr(addr6),
  518. }
  519. }
  520. switch N.NetworkName(network) {
  521. case N.NetworkTCP:
  522. tcpConn, err := gonet.DialTCPWithBind(ctx, t.stack, localAddr, remoteAddr, networkProtocol)
  523. if err != nil {
  524. return nil, err
  525. }
  526. return tcpConn, nil
  527. case N.NetworkUDP:
  528. udpConn, err := gonet.DialUDP(t.stack, &localAddr, &remoteAddr, networkProtocol)
  529. if err != nil {
  530. return nil, err
  531. }
  532. return udpConn, nil
  533. default:
  534. return nil, E.Extend(N.ErrUnknownNetwork, network)
  535. }
  536. }
  537. func (t *Endpoint) listenPacketWithAddress(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  538. if t.systemDialer != nil {
  539. return t.systemDialer.ListenPacket(ctx, destination)
  540. }
  541. addr4, addr6 := t.server.TailscaleIPs()
  542. bind := tcpip.FullAddress{
  543. NIC: 1,
  544. }
  545. var networkProtocol tcpip.NetworkProtocolNumber
  546. if destination.IsIPv4() {
  547. if !addr4.IsValid() {
  548. return nil, E.New("missing Tailscale IPv4 address")
  549. }
  550. networkProtocol = header.IPv4ProtocolNumber
  551. bind.Addr = addressFromAddr(addr4)
  552. } else {
  553. if !addr6.IsValid() {
  554. return nil, E.New("missing Tailscale IPv6 address")
  555. }
  556. networkProtocol = header.IPv6ProtocolNumber
  557. bind.Addr = addressFromAddr(addr6)
  558. }
  559. udpConn, err := gonet.DialUDP(t.stack, &bind, nil, networkProtocol)
  560. if err != nil {
  561. return nil, err
  562. }
  563. return udpConn, nil
  564. }
  565. func (t *Endpoint) ListenPacketWithDestination(ctx context.Context, destination M.Socksaddr) (net.PacketConn, netip.Addr, error) {
  566. t.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  567. if destination.IsDomain() {
  568. destinationAddresses, err := t.dnsRouter.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{})
  569. if err != nil {
  570. return nil, netip.Addr{}, err
  571. }
  572. var errors []error
  573. for _, address := range destinationAddresses {
  574. packetConn, packetErr := t.listenPacketWithAddress(ctx, M.SocksaddrFrom(address, destination.Port))
  575. if packetErr == nil {
  576. return packetConn, address, nil
  577. }
  578. errors = append(errors, packetErr)
  579. }
  580. return nil, netip.Addr{}, E.Errors(errors...)
  581. }
  582. packetConn, err := t.listenPacketWithAddress(ctx, destination)
  583. if err != nil {
  584. return nil, netip.Addr{}, err
  585. }
  586. if destination.IsIP() {
  587. return packetConn, destination.Addr, nil
  588. }
  589. return packetConn, netip.Addr{}, nil
  590. }
  591. func (t *Endpoint) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  592. packetConn, destinationAddress, err := t.ListenPacketWithDestination(ctx, destination)
  593. if err != nil {
  594. return nil, err
  595. }
  596. if destinationAddress.IsValid() && destination != M.SocksaddrFrom(destinationAddress, destination.Port) {
  597. return bufio.NewNATPacketConn(bufio.NewPacketConn(packetConn), M.SocksaddrFrom(destinationAddress, destination.Port), destination), nil
  598. }
  599. return packetConn, nil
  600. }
  601. func (t *Endpoint) PrepareConnection(network string, source M.Socksaddr, destination M.Socksaddr, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) {
  602. tsFilter := t.filter.Load()
  603. if tsFilter != nil {
  604. var ipProto ipproto.Proto
  605. switch N.NetworkName(network) {
  606. case N.NetworkTCP:
  607. ipProto = ipproto.TCP
  608. case N.NetworkUDP:
  609. ipProto = ipproto.UDP
  610. case N.NetworkICMP:
  611. if !destination.IsIPv6() {
  612. ipProto = ipproto.ICMPv4
  613. } else {
  614. ipProto = ipproto.ICMPv6
  615. }
  616. }
  617. response := tsFilter.Check(source.Addr, destination.Addr, destination.Port, ipProto)
  618. switch response {
  619. case filter.Drop:
  620. return nil, syscall.ECONNREFUSED
  621. case filter.DropSilently:
  622. return nil, tun.ErrDrop
  623. }
  624. }
  625. var ipVersion uint8
  626. if !destination.IsIPv6() {
  627. ipVersion = 4
  628. } else {
  629. ipVersion = 6
  630. }
  631. routeDestination, err := t.router.PreMatch(adapter.InboundContext{
  632. Inbound: t.Tag(),
  633. InboundType: t.Type(),
  634. IPVersion: ipVersion,
  635. Network: network,
  636. Source: source,
  637. Destination: destination,
  638. }, routeContext, timeout, false)
  639. if err != nil {
  640. switch {
  641. case rule.IsBypassed(err):
  642. err = nil
  643. case rule.IsRejected(err):
  644. t.logger.Trace("reject ", network, " connection from ", source.AddrString(), " to ", destination.AddrString())
  645. default:
  646. if network == N.NetworkICMP {
  647. t.logger.Warn(E.Cause(err, "link ", network, " connection from ", source.AddrString(), " to ", destination.AddrString()))
  648. }
  649. }
  650. }
  651. return routeDestination, err
  652. }
  653. func (t *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  654. var metadata adapter.InboundContext
  655. metadata.Inbound = t.Tag()
  656. metadata.InboundType = t.Type()
  657. metadata.Source = source
  658. addr4, addr6 := t.server.TailscaleIPs()
  659. switch destination.Addr {
  660. case addr4:
  661. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  662. case addr6:
  663. destination.Addr = netip.IPv6Loopback()
  664. }
  665. metadata.Destination = destination
  666. t.logger.InfoContext(ctx, "inbound connection from ", source)
  667. t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  668. t.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  669. }
  670. func (t *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  671. var metadata adapter.InboundContext
  672. metadata.Inbound = t.Tag()
  673. metadata.InboundType = t.Type()
  674. metadata.Source = source
  675. addr4, addr6 := t.server.TailscaleIPs()
  676. switch destination.Addr {
  677. case addr4:
  678. metadata.OriginDestination = destination
  679. destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1})
  680. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, destination)
  681. case addr6:
  682. metadata.OriginDestination = destination
  683. destination.Addr = netip.IPv6Loopback()
  684. conn = bufio.NewNATPacketConn(bufio.NewNetPacketConn(conn), metadata.OriginDestination, destination)
  685. }
  686. metadata.Destination = destination
  687. t.logger.InfoContext(ctx, "inbound packet connection from ", source)
  688. t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  689. t.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  690. }
  691. func (t *Endpoint) NewDirectRouteConnection(metadata adapter.InboundContext, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) {
  692. ctx := log.ContextWithNewID(t.ctx)
  693. var destination tun.DirectRouteDestination
  694. var err error
  695. if t.systemDialer != nil {
  696. destination, err = ping.ConnectDestination(
  697. ctx, t.logger,
  698. t.systemDialer.DialerForICMPDestination(metadata.Destination.Addr).Control,
  699. metadata.Destination.Addr, routeContext, timeout,
  700. )
  701. } else {
  702. inet4Address, inet6Address := t.server.TailscaleIPs()
  703. if metadata.Destination.Addr.Is4() && !inet4Address.IsValid() || metadata.Destination.Addr.Is6() && !inet6Address.IsValid() {
  704. return nil, E.New("Tailscale is not ready yet")
  705. }
  706. destination, err = ping.ConnectGVisor(
  707. ctx, t.logger,
  708. metadata.Source.Addr, metadata.Destination.Addr,
  709. routeContext,
  710. t.stack,
  711. inet4Address, inet6Address,
  712. timeout,
  713. )
  714. }
  715. if err != nil {
  716. return nil, err
  717. }
  718. t.logger.InfoContext(ctx, "linked ", metadata.Network, " connection from ", metadata.Source.AddrString(), " to ", metadata.Destination.AddrString())
  719. return destination, nil
  720. }
  721. func (t *Endpoint) PreferredDomain(domain string) bool {
  722. routeDomains := t.routeDomains.Load()
  723. if routeDomains == nil {
  724. return false
  725. }
  726. return routeDomains[strings.ToLower(domain)]
  727. }
  728. func (t *Endpoint) PreferredAddress(address netip.Addr) bool {
  729. routePrefixes := t.routePrefixes.Load()
  730. if routePrefixes == nil {
  731. return false
  732. }
  733. return routePrefixes.Contains(address)
  734. }
  735. func (t *Endpoint) Server() *tsnet.Server {
  736. return t.server
  737. }
  738. func (t *Endpoint) onReconfig(cfg *wgcfg.Config, routerCfg *router.Config, dnsCfg *tsDNS.Config) {
  739. if cfg == nil || dnsCfg == nil {
  740. return
  741. }
  742. if (t.cfg != nil && reflect.DeepEqual(t.cfg, cfg)) && (t.dnsCfg != nil && reflect.DeepEqual(t.dnsCfg, dnsCfg)) {
  743. return
  744. }
  745. var inet4Address, inet6Address netip.Addr
  746. for _, address := range cfg.Addresses {
  747. if address.Addr().Is4() {
  748. inet4Address = address.Addr()
  749. } else if address.Addr().Is6() {
  750. inet6Address = address.Addr()
  751. }
  752. }
  753. t.icmpForwarder.SetLocalAddresses(inet4Address, inet6Address)
  754. t.cfg = cfg
  755. t.dnsCfg = dnsCfg
  756. routeDomains := make(map[string]bool)
  757. for fqdn := range dnsCfg.Routes {
  758. routeDomains[fqdn.WithoutTrailingDot()] = true
  759. }
  760. for _, fqdn := range dnsCfg.SearchDomains {
  761. routeDomains[fqdn.WithoutTrailingDot()] = true
  762. }
  763. t.routeDomains.Store(routeDomains)
  764. var builder netipx.IPSetBuilder
  765. for _, peer := range cfg.Peers {
  766. for _, allowedIP := range peer.AllowedIPs {
  767. builder.AddPrefix(allowedIP)
  768. }
  769. }
  770. t.routePrefixes.Store(common.Must1(builder.IPSet()))
  771. if t.onReconfigHook != nil {
  772. t.onReconfigHook(cfg, routerCfg, dnsCfg)
  773. }
  774. }
  775. func addressFromAddr(destination netip.Addr) tcpip.Address {
  776. if destination.Is6() {
  777. return tcpip.AddrFrom16(destination.As16())
  778. } else {
  779. return tcpip.AddrFrom4(destination.As4())
  780. }
  781. }
  782. type endpointDialer struct {
  783. N.Dialer
  784. logger logger.ContextLogger
  785. }
  786. func (d *endpointDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  787. switch N.NetworkName(network) {
  788. case N.NetworkTCP:
  789. d.logger.InfoContext(ctx, "output connection to ", destination)
  790. case N.NetworkUDP:
  791. d.logger.InfoContext(ctx, "output packet connection to ", destination)
  792. }
  793. return d.Dialer.DialContext(ctx, network, destination)
  794. }
  795. func (d *endpointDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  796. d.logger.InfoContext(ctx, "output packet connection")
  797. return d.Dialer.ListenPacket(ctx, destination)
  798. }
  799. type dnsConfigurtor struct {
  800. baseConfig tsDNS.OSConfig
  801. }
  802. func (c *dnsConfigurtor) SetDNS(cfg tsDNS.OSConfig) error {
  803. c.baseConfig = cfg
  804. return nil
  805. }
  806. func (c *dnsConfigurtor) SupportsSplitDNS() bool {
  807. return true
  808. }
  809. func (c *dnsConfigurtor) GetBaseConfig() (tsDNS.OSConfig, error) {
  810. return c.baseConfig, nil
  811. }
  812. func (c *dnsConfigurtor) Close() error {
  813. return nil
  814. }