Documentation
¶
Overview ¶
Package tsnet embeds a Tailscale node directly into a Go program, allowing it to join a tailnet and accept or dial connections without running a separate tailscaled daemon or requiring any system-level configuration.
Overview ¶
Normally, Tailscale runs as a background system service (tailscaled) that manages a virtual network interface for the whole machine. tsnet takes a different approach: it runs a fully self-contained Tailscale node inside your process using a userspace TCP/IP stack (gVisor). This means:
- No root privileges required.
- No system daemons to install or manage.
- Multiple independent Tailscale nodes can run within a single binary.
- The node's Tailscale identity and state are stored in a directory you control.
The core type is Server, which represents one embedded Tailscale node. Calling Server.Listen or Server.Dial routes traffic exclusively over the tailnet. The standard library's net.Listener and net.Conn interfaces are returned, so any existing Go HTTP server, gRPC server, or other net-based code works without modification.
Usage ¶
import "github.com/metacubex/tailscale/tsnet"
s := &tsnet.Server{
Hostname: "my-service",
AuthKey: os.Getenv("TS_AUTHKEY"),
}
defer s.Close()
ln, err := s.Listen("tcp", ":80")
if err != nil {
log.Fatal(err)
}
log.Fatal(http.Serve(ln, myHandler))
On first run, if no [Server.AuthKey] is provided and the node is not already enrolled, the server logs an authentication URL. Open it in a browser to add the node to your tailnet.
Authentication ¶
A Server authenticates using, in order of precedence:
[Server.AuthKey].
The TS_AUTHKEY environment variable.
The TS_AUTH_KEY environment variable.
An OAuth client secret ([Server.ClientSecret] or TS_CLIENT_SECRET), used to mint an auth key.
Workload identity federation ([Server.ClientID] plus [Server.IDToken] or [Server.Audience]). Available only if the program imports the feature:
import _ "github.com/metacubex/tailscale/feature/identityfederation"
The feature is not linked by default to keep the AWS SDK and other cloud-provider dependencies out of programs that don't use workload identity federation.
An interactive login URL printed to [Server.UserLogf].
If the node is already enrolled (state found in [Server.Store]), the auth key is ignored unless TSNET_FORCE_LOGIN=1 is set.
Identifying callers ¶
Use the WhoIs method on the client returned by Server.LocalClient to identify who is making a request:
lc, _ := srv.LocalClient()
http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
fmt.Fprintf(w, "Hello, %s!", who.UserProfile.LoginName)
}))
Tailscale Funnel ¶
Server.ListenFunnel exposes your service on the public internet. Tailscale Funnel currently supports TCP on ports 443, 8443, and 10000. HTTPS must be enabled in the Tailscale admin console.
ln, err := srv.ListenFunnel("tcp", ":443")
// ln is a TLS listener; connections can come from anywhere on the
// internet as well as from your tailnet.
// To restrict to public traffic only:
ln, err = srv.ListenFunnel("tcp", ":443", tsnet.FunnelOnly())
Tailscale Services ¶
Server.ListenService advertises the node as a host for a named Tailscale Service. The node must use a tag-based identity. To advertise multiple ports, call ListenService once per port.
srv.AdvertiseTags = []string{"tag:myservice"}
ln, err := srv.ListenService("svc:my-service", tsnet.ServiceModeHTTP{
HTTPS: true,
Port: 443,
})
log.Printf("Listening on https://%s", ln.FQDN)
Running multiple nodes in one process ¶
Each Server instance is an independent node. Give each a unique [Server.Dir] and [Server.Hostname]:
for _, name := range []string{"frontend", "backend"} {
srv := &tsnet.Server{
Hostname: name,
Dir: filepath.Join(baseDir, name),
AuthKey: os.Getenv("TS_AUTHKEY"),
Ephemeral: true,
}
srv.Start()
}
Index ¶
- Variables
- type FallbackTCPHandler
- type FallbackUDPHandler
- type FunnelOption
- type Server
- func (s *Server) CapturePcap(ctx context.Context, pcapFile string) error
- func (s *Server) CertDomains() []string
- func (s *Server) Close() error
- func (s *Server) Dial(ctx context.Context, network, address string) (net.Conn, error)
- func (s *Server) DialPlan(ctx context.Context, network, address string) (ipp netip.AddrPort, viaTailscale bool, err error)
- func (s *Server) GetRootPath() string
- func (s *Server) HTTPClient() *http.Client
- func (s *Server) Listen(network, addr string) (net.Listener, error)
- func (s *Server) ListenFunnel(network, addr string, opts ...FunnelOption) (net.Listener, error)
- func (s *Server) ListenPacket(network, addr string) (net.PacketConn, error)
- func (s *Server) ListenService(name string, mode ServiceMode) (*ServiceListener, error)
- func (s *Server) ListenTLS(network, addr string) (net.Listener, error)
- func (s *Server) LocalClient() (*local.Client, error)
- func (s *Server) LogtailWriter() io.Writer
- func (s *Server) Loopback() (addr string, proxyCred, localAPICred string, err error)
- func (s *Server) Netstack(ctx context.Context) (*netstack.Impl, error)
- func (s *Server) RegisterFallbackTCPHandler(cb FallbackTCPHandler) func()
- func (s *Server) RegisterFallbackUDPHandler(cb FallbackUDPHandler) func()
- func (s *Server) Start() error
- func (s *Server) Sys() *tsd.System
- func (s *Server) TailscaleIPs() (ip4, ip6 netip.Addr)
- func (s *Server) Up(ctx context.Context) (*ipnstate.Status, error)
- type ServiceListener
- type ServiceMode
- type ServiceModeHTTP
- type ServiceModeTCP
Constants ¶
This section is empty.
Variables ¶
var ErrUntaggedServiceHost = errors.New("service hosts must be tagged nodes")
ErrUntaggedServiceHost is returned by ListenService when run on a node without any ACL tags. A node must use a tag-based identity to act as a Service host. For more information, see: https://github.com/metacubex/tailscale/kb/1552/tailscale-services#prerequisites
var TestHooks testHooks
TestHooks are hooks meant for internal-testing only; they're not stable or documented, intentionally.
Functions ¶
This section is empty.
Types ¶
type FallbackTCPHandler ¶
FallbackTCPHandler describes the callback which conditionally handles an incoming TCP flow for the provided (src/port, dst/port) 4-tuple. These are registered as handlers of last resort, and are called only if no listener could handle the incoming flow.
If the callback returns intercept=false, the flow is rejected.
When intercept=true, the behavior depends on whether the returned handler is non-nil: if nil, the connection is rejected. If non-nil, handler takes over the TCP conn.
type FallbackUDPHandler ¶
type FallbackUDPHandler func(src, dst netip.AddrPort) (handler func(nettype.ConnPacketConn), intercept bool)
FallbackUDPHandler describes the callback which conditionally handles an incoming UDP flow for the provided (src/port, dst/port) 4-tuple. These are registered as handlers of last resort, and are called only if no listener could handle the incoming flow.
If the callback returns intercept=false, the flow is rejected.
When intercept=true, the behavior depends on whether the returned handler is non-nil: if nil, the connection is rejected. If non-nil, handler takes over the TCP conn.
type FunnelOption ¶
type FunnelOption interface {
// contains filtered or unexported methods
}
FunnelOption is an option passed to ListenFunnel to configure the listener.
func FunnelOnly ¶
func FunnelOnly() FunnelOption
FunnelOnly configures the listener to only respond to connections from Tailscale Funnel. The local tailnet will not be able to connect to the listener.
func FunnelTLSConfig ¶
func FunnelTLSConfig(conf *tls.Config) FunnelOption
FunnelTLSConfig configures the TLS configuration for Server.ListenFunnel
This is rarely needed but can permit requiring client certificates, specific ciphers suites, etc.
The provided conf should at least be able to get a certificate, setting GetCertificate, Certificates or GetConfigForClient appropriately. The most common configuration is to set GetCertificate to Server.LocalClient's GetCertificate method.
Unless FunnelOnly is also used, the configuration is also used for in-tailnet connections that don't arrive over Funnel.
type Server ¶
type Server struct {
// Dir specifies the name of the directory to use for
// state. If empty, a directory is selected automatically
// under os.UserConfigDir (https://golang.org/pkg/os/#UserConfigDir).
// based on the name of the binary.
//
// If you want to use multiple tsnet services in the same
// binary, you will need to make sure that Dir is set uniquely
// for each service. A good pattern for this is to have a
// "base" directory (such as your mutable storage folder) and
// then append the hostname on the end of it.
Dir string
// Store specifies the state store to use.
//
// If nil, a new FileStore is initialized at `Dir/tailscaled.state`.
// See github.com/metacubex/tailscale/ipn/store for supported stores.
//
// Logs will automatically be uploaded to log.tailscale.com,
// where the configuration file for logging will be saved at
// `Dir/tailscaled.log.conf`.
Store ipn.StateStore
// Hostname is the hostname to present to the control server.
// If empty, the binary name is used.
Hostname string
// UserLogf, if non-nil, specifies the logger to use for logs generated by
// the Server itself intended to be seen by the user such as the AuthURL for
// login and status updates. If unset, log.Printf is used.
UserLogf logger.Logf
// Logf, if set is used for logs generated by the backend such as the
// LocalBackend and MagicSock. It is verbose and intended for debugging.
// If unset, logs are discarded.
Logf logger.Logf
// Ephemeral, if true, specifies that the instance should register
// as an Ephemeral node (https://github.com/metacubex/tailscale/s/ephemeral-nodes).
Ephemeral bool
// AuthKey, if non-empty, is the auth key to create the node
// and will be preferred over the TS_AUTHKEY environment
// variable. If the node is already created (from state
// previously stored in Store), then this field is not
// used.
AuthKey string
// ClientSecret, if non-empty, is the OAuth client secret
// that will be used to generate authkeys via OAuth. It
// will be preferred over the TS_CLIENT_SECRET environment
// variable. If the node is already created (from state
// previously stored in Store), then this field is not
// used.
ClientSecret string
// ClientID, if non-empty, is the client ID used to generate
// authkeys via workload identity federation. It will be
// preferred over the TS_CLIENT_ID environment variable.
// If the node is already created (from state previously
// stored in Store), then this field is not used.
ClientID string
// IDToken, if non-empty, is the ID token from the identity
// provider to exchange with the control server for workload
// identity federation. It will be preferred over the
// TS_ID_TOKEN environment variable. If the node is already
// created (from state previously stored in Store), then this
// field is not used.
IDToken string
// Audience, if non-empty, is the audience to use when requesting
// an ID token from a well-known identity provider to exchange
// with the control server for workload identity federation. It
// will be preferred over the TS_AUDIENCE environment variable. If
// the node is already created (from state previously stored in Store),
// then this field is not used.
Audience string
// ControlURL optionally specifies the coordination server URL.
// If empty, the Tailscale default is used.
// If empty, it defaults to the TS_CONTROL_URL environment variable.
// If that is also empty, the Tailscale default is used.
ControlURL string
// RunWebClient, if true, runs a client for managing this node over
// its Tailscale interface on port 5252.
RunWebClient bool
// Port is the UDP port to listen on for WireGuard and peer-to-peer
// traffic. If zero, a port is automatically selected. Leave this
// field at zero unless you know what you are doing.
Port uint16
// SystemDialer optionally specifies how tsnet dials non-Tailscale
// infrastructure such as control, DERP, STUN, and logtail.
SystemDialer netx.DialFunc
// SystemPacketListener optionally specifies how tsnet opens UDP sockets
// for non-Tailscale infrastructure such as STUN and peer paths.
SystemPacketListener netx.ListenPacketFunc
// ExtraRootCAs optionally specifies additional trusted root CAs for
// Tailscale control connections.
ExtraRootCAs *x509.CertPool
// LookupHook optionally specifies how tsnet resolves non-Tailscale
// infrastructure hostnames such as control and DERP.
LookupHook dnscache.LookupHookFunc
// AdvertiseTags specifies tags that should be applied to this node, for
// purposes of ACL enforcement. These can be referenced from the ACL policy
// document. Note that advertising a tag on the client doesn't guarantee
// that the control server will allow the node to adopt that tag.
AdvertiseTags []string
// Tun, if non-nil, specifies a custom tun.Device to use for packet I/O.
//
// This field must be set before calling Start.
Tun tun.Device
// contains filtered or unexported fields
}
Server is an embedded Tailscale server.
Its exported fields may be changed until the first method call.
func (*Server) CapturePcap ¶
CapturePcap can be called by the application code compiled with tsnet to save a pcap of packets which the netstack within tsnet sees. This is expected to be useful during debugging, probably not useful for production.
Packets will be written to the pcap until the process exits. The pcap needs a Lua dissector to be installed in Wireshark in order to decode properly: wgengine/capture/ts-dissector.lua in this repository. https://github.com/metacubex/tailscale/docs/reference/troubleshooting/network-configuration/inspect-unencrypted-packets
func (*Server) CertDomains ¶
CertDomains returns the list of domains for which the server can provide TLS certificates. These are also the DNS names for the Server. If the server is not running, it returns nil.
func (*Server) Close ¶
Close stops the server.
It must not be called before or concurrently with Start.
func (*Server) Dial ¶
Dial connects to the address on the tailnet. It will start the server if it has not been started yet.
func (*Server) DialPlan ¶
func (s *Server) DialPlan(ctx context.Context, network, address string) (ipp netip.AddrPort, viaTailscale bool, err error)
DialPlan resolves address and reports whether Dial would route it via Tailscale instead of falling back to the system dialer.
func (*Server) GetRootPath ¶
GetRootPath returns the root path of the tsnet server. This is where the state file and other data is stored.
func (*Server) HTTPClient ¶
HTTPClient returns an HTTP client that is configured to connect over Tailscale.
This is useful if you need to have your tsnet services connect to other devices on your tailnet.
func (*Server) Listen ¶
Listen announces only on the Tailscale network. It will start the server if it has not been started yet.
Listeners which do not specify an IP address will match for traffic for the local node (that is, a destination address of the IPv4 or IPv6 address of this node) only. To listen for traffic on other addresses such as those routed inbound via subnet routes, explicitly specify the listening address or use RegisterFallbackTCPHandler.
func (*Server) ListenFunnel ¶
ListenFunnel announces on the public internet using Tailscale Funnel.
It also by default listens on your local tailnet, so connections can come from either inside or outside your network. To restrict connections to be just from the internet, use the FunnelOnly option.
Currently (2023-03-10), Funnel only supports TCP on ports 443, 8443, and 10000. The supported host name is limited to that configured for the tsnet.Server. As such, the standard way to create funnel is:
s.ListenFunnel("tcp", ":443")
and the only other supported addrs currently are ":8443" and ":10000".
It will start the server if it has not been started yet.
func (*Server) ListenPacket ¶
func (s *Server) ListenPacket(network, addr string) (net.PacketConn, error)
ListenPacket announces on the Tailscale network.
The network must be "udp", "udp4" or "udp6". The addr must be of the form "ip:port" (or "[ip]:port") where ip is a valid IPv4 or IPv6 address corresponding to "udp4" or "udp6" respectively. IP must be specified.
If s has not been started yet, it will be started.
func (*Server) ListenService ¶
func (s *Server) ListenService(name string, mode ServiceMode) (*ServiceListener, error)
ListenService creates a network listener for a Tailscale Service. This will advertise this node as hosting the Service. Note that:
- Approval must still be granted by an admin or by ACL auto-approval rules.
- Service hosts must be tagged nodes.
- A valid Service host must advertise all ports defined for the Service.
To advertise a Service with multiple ports, run ListenService multiple times. For more information about Services, see https://github.com/metacubex/tailscale/kb/1552/tailscale-services
This function will start the server if it is not already started.
func (*Server) ListenTLS ¶
ListenTLS announces only on the Tailscale network. It returns a TLS listener wrapping the tsnet listener. It will start the server if it has not been started yet.
func (*Server) LocalClient ¶
LocalClient returns a LocalClient that speaks to s.
It will start the server if it has not been started yet. If the server's already been started successfully, it doesn't return an error.
func (*Server) LogtailWriter ¶
LogtailWriter returns an io.Writer that writes to Tailscale's logging service and will be only visible to Tailscale's support team. Logs written there cannot be retrieved by the user. This method always returns a non-nil value.
func (*Server) Loopback ¶
Loopback starts a routing server on a loopback address.
The server has multiple functions.
It can be used as a SOCKS5 proxy onto the tailnet. Authentication is required with the username "tsnet" and the value of proxyCred used as the password.
The HTTP server also serves out the "LocalAPI" on /localapi. As the LocalAPI is powerful, access to endpoints requires BOTH passing a "Sec-Tailscale: localapi" HTTP header and passing localAPICred as basic auth.
If you only need to use the LocalAPI from Go, then prefer LocalClient as it does not require communication via TCP.
func (*Server) Netstack ¶
Netstack returns the *netstack.Impl for the server. It will start the server if it has not been started yet.
func (*Server) RegisterFallbackTCPHandler ¶
func (s *Server) RegisterFallbackTCPHandler(cb FallbackTCPHandler) func()
RegisterFallbackTCPHandler registers a callback which will be called to handle a TCP flow to this tsnet node, for which no listeners will handle.
If multiple fallback handlers are registered, they will be called in an undefined order. See FallbackTCPHandler for details on handling a flow.
The returned function can be used to deregister this callback.
func (*Server) RegisterFallbackUDPHandler ¶
func (s *Server) RegisterFallbackUDPHandler(cb FallbackUDPHandler) func()
RegisterFallbackUDPHandler registers a callback which will be called to handle a UDP flow to this tsnet node, for which no listeners will handle.
If multiple fallback handlers are registered, they will be called in an undefined order. See FallbackUDPHandler for details on handling a flow.
The returned function can be used to deregister this callback.
func (*Server) Start ¶
Start connects the server to the tailnet. Optional: any calls to Dial/Listen will also call Start.
func (*Server) Sys ¶
Sys returns a handle to the Tailscale subsystems of this node.
This is not a stable API, nor are the APIs of the returned subsystems.
func (*Server) TailscaleIPs ¶
TailscaleIPs returns IPv4 and IPv6 addresses for this node. If the node has not yet joined a tailnet or is otherwise unaware of its own IP addresses, the returned ip4, ip6 will be !netip.IsValid().
type ServiceListener ¶
type ServiceListener struct {
net.Listener
// FQDN is the fully-qualifed domain name of this Service.
FQDN string
// contains filtered or unexported fields
}
A ServiceListener is a network listener for a Tailscale Service. For more information about Services, see https://github.com/metacubex/tailscale/kb/1552/tailscale-services
func (*ServiceListener) Addr ¶
func (sl *ServiceListener) Addr() net.Addr
Addr returns the listener's network address. This will be the Service's fully-qualified domain name (FQDN) and the port.
A hostname is not truly a network address, but Services listen on multiple addresses (the IPv4 and IPv6 virtual IPs).
func (*ServiceListener) Close ¶
func (sl *ServiceListener) Close() error
Close closes the listener and clears state related to hosting the Service. Behavior is undefined after the Server has been closed.
type ServiceMode ¶
type ServiceMode interface {
// contains filtered or unexported methods
}
ServiceMode defines how a Service is run. Currently supported modes are:
For more information, see Server.ListenService.
type ServiceModeHTTP ¶
type ServiceModeHTTP struct {
// Port is the TCP port to advertise. If this Service needs to advertise
// multiple ports, call ListenService multiple times.
Port uint16
// HTTPS, if true, means that the listener should handle connections as
// HTTPS connections. In this case, the only server name indicator (SNI)
// permitted is the Service's fully-qualified domain name.
HTTPS bool
// AcceptAppCaps defines the app capabilities to forward to the server. The
// keys in this map are the mount points for each set of capabilities.
//
// By example,
//
// AcceptAppCaps: map[string][]string{
// "/": {"example.com/cap/all-paths"},
// "/foo": {"example.com/cap/all-paths", "example.com/cap/foo"},
// }
//
// would forward example.com/cap/all-paths to all paths on the server and
// example.com/cap/foo only to paths beginning with /foo.
//
// For more information on app capabilities, see
// https://github.com/metacubex/tailscale/kb/1537/grants-app-capabilities
AcceptAppCaps map[string][]string
// PROXYProtocolVersion indicates whether to send a PROXY protocol header
// before forwarding the connection to the listener and which version of the
// protocol to use.
//
// For more information, see
// https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt
PROXYProtocol int
}
ServiceModeHTTP is used to configure an HTTP Service via Server.ListenService.
type ServiceModeTCP ¶
type ServiceModeTCP struct {
// Port is the TCP port to advertise. If this Service needs to advertise
// multiple ports, call ListenService multiple times.
Port uint16
// TerminateTLS means that TLS connections will be terminated before being
// forwarded to the listener. In this case, the only server name indicator
// (SNI) permitted is the Service's fully-qualified domain name.
TerminateTLS bool
// PROXYProtocolVersion indicates whether to send a PROXY protocol header
// before forwarding the connection to the listener and which version of the
// protocol to use.
//
// For more information, see
// https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt
PROXYProtocolVersion int
}
ServiceModeTCP is used to configure a TCP Service via Server.ListenService.
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
tshello
command
The tshello server demonstrates how to use Tailscale as a library.
|
The tshello server demonstrates how to use Tailscale as a library. |
|
tsnet-funnel
command
The tsnet-funnel server demonstrates how to use tsnet with Funnel.
|
The tsnet-funnel server demonstrates how to use tsnet with Funnel. |
|
tsnet-http-client
command
The tshello server demonstrates how to use Tailscale as a library.
|
The tshello server demonstrates how to use Tailscale as a library. |
|
tsnet-services
command
The tsnet-services example demonstrates how to use tsnet with Services.
|
The tsnet-services example demonstrates how to use tsnet with Services. |
|
web-client
command
The web-client command demonstrates serving the Tailscale web client over tsnet.
|
The web-client command demonstrates serving the Tailscale web client over tsnet. |