2023-01-27 21:37:20 +00:00
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
2020-02-05 22:16:58 +00:00
2021-02-04 21:12:42 +00:00
package ipnlocal
2020-02-05 22:16:58 +00:00
import (
2024-06-04 02:24:53 +00:00
"bytes"
2023-12-18 22:43:01 +00:00
"cmp"
2020-03-14 03:53:58 +00:00
"context"
2022-11-02 03:37:13 +00:00
"encoding/base64"
2022-11-07 23:32:53 +00:00
"encoding/json"
2020-02-03 18:35:52 +00:00
"errors"
2020-02-05 22:16:58 +00:00
"fmt"
2021-03-30 19:56:00 +00:00
"io"
2023-03-08 00:22:23 +00:00
"log"
2023-09-05 17:51:52 +00:00
"maps"
2024-03-26 20:14:43 +00:00
"math"
2024-06-05 21:37:31 +00:00
"math/rand/v2"
2021-03-26 20:44:55 +00:00
"net"
2021-04-07 15:39:08 +00:00
"net/http"
2022-07-25 03:08:42 +00:00
"net/netip"
2022-11-02 03:37:13 +00:00
"net/url"
2020-09-17 14:59:55 +00:00
"os"
2024-06-04 02:24:53 +00:00
"os/exec"
2021-04-17 04:01:29 +00:00
"os/user"
2021-03-29 17:42:33 +00:00
"path/filepath"
2020-10-21 19:55:03 +00:00
"runtime"
2023-08-17 05:09:53 +00:00
"slices"
2021-04-08 21:54:25 +00:00
"sort"
2021-03-26 20:44:55 +00:00
"strconv"
2020-02-05 22:16:58 +00:00
"strings"
"sync"
2021-04-02 15:21:40 +00:00
"sync/atomic"
2020-02-05 22:16:58 +00:00
"time"
2022-11-07 23:32:53 +00:00
"go4.org/mem"
2022-07-25 03:08:42 +00:00
"go4.org/netipx"
2023-09-17 09:17:59 +00:00
xmaps "golang.org/x/exp/maps"
2023-06-08 23:57:40 +00:00
"gvisor.dev/gvisor/pkg/tcpip"
2023-10-27 21:20:10 +00:00
"tailscale.com/appc"
2021-04-13 15:13:46 +00:00
"tailscale.com/client/tailscale/apitype"
2023-11-09 21:00:47 +00:00
"tailscale.com/clientupdate"
2020-02-05 22:16:58 +00:00
"tailscale.com/control/controlclient"
2023-09-11 19:03:39 +00:00
"tailscale.com/control/controlknobs"
2022-09-26 17:07:28 +00:00
"tailscale.com/doctor"
2024-02-15 00:19:59 +00:00
"tailscale.com/doctor/ethtool"
2023-03-29 15:27:12 +00:00
"tailscale.com/doctor/permissions"
2022-09-26 17:07:28 +00:00
"tailscale.com/doctor/routetable"
2024-04-02 20:32:30 +00:00
"tailscale.com/drive"
2022-01-24 18:52:57 +00:00
"tailscale.com/envknob"
2021-02-25 05:29:51 +00:00
"tailscale.com/health"
2022-11-11 17:43:49 +00:00
"tailscale.com/health/healthmsg"
2021-08-20 17:34:13 +00:00
"tailscale.com/hostinfo"
2021-02-04 21:12:42 +00:00
"tailscale.com/ipn"
2023-10-11 20:55:57 +00:00
"tailscale.com/ipn/conffile"
2022-11-23 19:18:18 +00:00
"tailscale.com/ipn/ipnauth"
2020-03-26 05:57:46 +00:00
"tailscale.com/ipn/ipnstate"
2020-04-01 04:48:33 +00:00
"tailscale.com/ipn/policy"
2023-03-08 00:22:23 +00:00
"tailscale.com/log/sockstatlog"
"tailscale.com/logpolicy"
2021-03-25 21:50:21 +00:00
"tailscale.com/net/dns"
2023-01-24 19:31:20 +00:00
"tailscale.com/net/dnscache"
2022-09-05 18:36:30 +00:00
"tailscale.com/net/dnsfallback"
2024-04-15 22:14:20 +00:00
"tailscale.com/net/netcheck"
2023-11-09 19:34:41 +00:00
"tailscale.com/net/netkernelconf"
2023-08-23 17:05:21 +00:00
"tailscale.com/net/netmon"
2023-01-25 18:17:40 +00:00
"tailscale.com/net/netns"
2022-03-28 17:24:11 +00:00
"tailscale.com/net/netutil"
2020-07-31 20:27:09 +00:00
"tailscale.com/net/tsaddr"
2021-12-01 04:39:12 +00:00
"tailscale.com/net/tsdial"
2021-03-29 17:42:33 +00:00
"tailscale.com/paths"
2020-02-05 22:16:58 +00:00
"tailscale.com/portlist"
2022-08-04 17:43:49 +00:00
"tailscale.com/syncs"
2020-02-05 22:16:58 +00:00
"tailscale.com/tailcfg"
2023-10-05 23:05:45 +00:00
"tailscale.com/taildrop"
2022-08-01 22:46:41 +00:00
"tailscale.com/tka"
2023-05-03 20:57:17 +00:00
"tailscale.com/tsd"
2023-07-27 19:41:31 +00:00
"tailscale.com/tstime"
2023-10-31 21:59:18 +00:00
"tailscale.com/types/appctype"
2021-08-05 21:05:24 +00:00
"tailscale.com/types/dnstype"
2020-02-14 21:09:19 +00:00
"tailscale.com/types/empty"
2020-03-26 05:57:46 +00:00
"tailscale.com/types/key"
2024-06-03 20:49:55 +00:00
"tailscale.com/types/lazy"
2020-02-15 03:23:16 +00:00
"tailscale.com/types/logger"
2023-03-23 17:49:56 +00:00
"tailscale.com/types/logid"
2021-02-05 23:44:46 +00:00
"tailscale.com/types/netmap"
2023-12-18 22:57:03 +00:00
"tailscale.com/types/opt"
2021-02-05 23:23:01 +00:00
"tailscale.com/types/persist"
2021-05-27 17:07:17 +00:00
"tailscale.com/types/preftype"
2022-12-01 01:39:43 +00:00
"tailscale.com/types/ptr"
2022-02-22 17:52:49 +00:00
"tailscale.com/types/views"
2021-07-03 04:30:29 +00:00
"tailscale.com/util/deephash"
2021-04-09 22:24:47 +00:00
"tailscale.com/util/dnsname"
2024-03-26 20:14:43 +00:00
"tailscale.com/util/httpm"
2022-10-04 03:39:45 +00:00
"tailscale.com/util/mak"
2021-11-02 21:30:48 +00:00
"tailscale.com/util/multierr"
2021-04-22 07:25:00 +00:00
"tailscale.com/util/osshare"
2023-08-31 16:43:54 +00:00
"tailscale.com/util/rands"
2022-11-28 18:34:35 +00:00
"tailscale.com/util/set"
2023-11-29 21:48:25 +00:00
"tailscale.com/util/syspolicy"
2020-11-24 23:35:04 +00:00
"tailscale.com/util/systemd"
2023-08-08 16:29:35 +00:00
"tailscale.com/util/testenv"
2022-11-07 23:32:53 +00:00
"tailscale.com/util/uniq"
2020-02-05 22:16:58 +00:00
"tailscale.com/version"
2021-05-27 17:07:17 +00:00
"tailscale.com/version/distro"
2020-02-05 22:16:58 +00:00
"tailscale.com/wgengine"
2023-01-19 22:28:49 +00:00
"tailscale.com/wgengine/capture"
2020-02-05 22:16:58 +00:00
"tailscale.com/wgengine/filter"
2021-12-28 21:39:04 +00:00
"tailscale.com/wgengine/magicsock"
2020-05-11 21:02:12 +00:00
"tailscale.com/wgengine/router"
2021-01-29 20:16:36 +00:00
"tailscale.com/wgengine/wgcfg"
2021-02-05 20:44:43 +00:00
"tailscale.com/wgengine/wgcfg/nmcfg"
2020-02-05 22:16:58 +00:00
)
2020-10-20 17:40:12 +00:00
var controlDebugFlags = getControlDebugFlags ( )
func getControlDebugFlags ( ) [ ] string {
2022-01-24 18:52:57 +00:00
if e := envknob . String ( "TS_DEBUG_CONTROL_FLAGS" ) ; e != "" {
2020-10-20 17:40:12 +00:00
return strings . Split ( e , "," )
}
return nil
}
2020-10-19 22:56:59 +00:00
2022-04-15 20:19:13 +00:00
// SSHServer is the interface of the conditionally linked ssh/tailssh.server.
type SSHServer interface {
HandleSSHConn ( net . Conn ) error
2022-04-17 18:49:56 +00:00
2024-04-22 16:27:12 +00:00
// NumActiveConns returns the number of connections passed to HandleSSHConn
// that are still active.
NumActiveConns ( ) int
2022-04-17 18:49:56 +00:00
// OnPolicyChange is called when the SSH access policy changes,
// so that existing sessions can be re-evaluated for validity
// and closed if they'd no longer be accepted.
OnPolicyChange ( )
2022-05-28 11:33:46 +00:00
// Shutdown is called when tailscaled is shutting down.
Shutdown ( )
2022-04-15 20:19:13 +00:00
}
type newSSHServerFunc func ( logger . Logf , * LocalBackend ) ( SSHServer , error )
var newSSHServer newSSHServerFunc // or nil
// RegisterNewSSHServer lets the conditionally linked ssh/tailssh package register itself.
func RegisterNewSSHServer ( fn newSSHServerFunc ) {
newSSHServer = fn
}
2023-09-18 14:30:58 +00:00
// watchSession represents a WatchNotifications channel
// and sessionID as required to close targeted buses.
type watchSession struct {
ch chan * ipn . Notify
sessionID string
}
2020-05-19 02:32:20 +00:00
// LocalBackend is the glue between the major pieces of the Tailscale
// network software: the cloud control plane (via controlclient), the
// network data plane (via wgengine), and the user-facing UIs and CLIs
// (collectively called "frontends", via LocalBackend's implementation
// of the Backend interface).
//
// LocalBackend implements the overall state machine for the Tailscale
// application. Frontends, controlclient and wgengine can feed events
// into LocalBackend to advance the state machine, and advancing the
// state machine generates events back out to zero or more components.
2020-02-05 22:16:58 +00:00
type LocalBackend struct {
2020-05-19 02:32:20 +00:00
// Elements that are thread-safe or constant after construction.
2021-03-16 05:20:48 +00:00
ctx context . Context // canceled by Close
ctxCancel context . CancelFunc // cancels ctx
logf logger . Logf // general logging
keyLogf logger . Logf // for printing list of peers on change
statsLogf logger . Logf // for printing peers stats on change
2023-05-03 20:57:17 +00:00
sys * tsd . System
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
health * health . Tracker // always non-nil
2023-05-03 20:57:17 +00:00
e wgengine . Engine // non-nil; TODO(bradfitz): remove; use sys
2023-09-01 00:55:47 +00:00
store ipn . StateStore // non-nil; TODO(bradfitz): remove; use sys
dialer * tsdial . Dialer // non-nil; TODO(bradfitz): remove; use sys
2023-10-23 17:22:34 +00:00
pushDeviceToken syncs . AtomicValue [ string ]
2023-03-23 17:49:56 +00:00
backendLogID logid . PublicID
2023-04-18 21:26:58 +00:00
unregisterNetMon func ( )
2021-03-16 05:20:48 +00:00
unregisterHealthWatch func ( )
portpoll * portlist . Poller // may be nil
portpollOnce sync . Once // guards starting readPoller
gotPortPollRes chan struct { } // closed upon first readPoller result
2023-09-10 14:24:51 +00:00
varRoot string // or empty if SetVarRoot never called
logFlushFunc func ( ) // or nil if SetLogFlusher wasn't called
em * expiryManager // non-nil
2022-08-04 04:51:02 +00:00
sshAtomicBool atomic . Bool
2024-03-18 21:47:21 +00:00
// webClientAtomicBool controls whether the web client is running. This should
// be true unless the disable-web-client node attribute has been set.
webClientAtomicBool atomic . Bool
// exposeRemoteWebClientAtomicBool controls whether the web client is exposed over
// Tailscale on port 5252.
exposeRemoteWebClientAtomicBool atomic . Bool
shutdownCalled bool // if Shutdown has been called
debugSink * capture . Sink
sockstatLogger * sockstatlog . Logger
2020-05-19 02:32:20 +00:00
2023-03-08 20:36:41 +00:00
// getTCPHandlerForFunnelFlow returns a handler for an incoming TCP flow for
// the provided srcAddr and dstPort if one exists.
//
// srcAddr is the source address of the flow, not the address of the Funnel
// node relaying the flow.
// dstPort is the destination port of the flow.
//
// It returns nil if there is no known handler for this flow.
//
// This is specifically used to handle TCP flows for Funnel connections to tsnet
// servers.
//
// It is set once during initialization, and can be nil if SetTCPHandlerForFunnelFlow
// is never called.
getTCPHandlerForFunnelFlow func ( srcAddr netip . AddrPort , dstPort uint16 ) ( handler func ( net . Conn ) )
2022-11-07 23:32:53 +00:00
filterAtomic atomic . Pointer [ filter . Filter ]
containsViaIPFuncAtomic syncs . AtomicValue [ func ( netip . Addr ) bool ]
shouldInterceptTCPPortAtomic syncs . AtomicValue [ func ( uint16 ) bool ]
2023-01-11 20:59:08 +00:00
numClientStatusCalls atomic . Uint32
2021-11-25 17:43:39 +00:00
2020-02-05 22:16:58 +00:00
// The mutex protects the following elements.
2020-09-28 22:28:26 +00:00
mu sync . Mutex
2023-10-11 20:55:57 +00:00
conf * conffile . Config // latest parsed config, or nil if not in declarative mode
pm * profileManager // mu guards access
2022-04-17 21:49:16 +00:00
filterHash deephash . Sum
2023-11-01 23:56:30 +00:00
httpTestClient * http . Client // for controlclient. nil by default, used by tests.
ccGen clientGen // function for producing controlclient; lazily populated
sshServer SSHServer // or nil, initialized lazily.
appConnector * appc . AppConnector // or nil, initialized when configured.
2024-05-08 00:31:10 +00:00
// notifyCancel cancels notifications to the current SetNotifyCallback.
notifyCancel context . CancelFunc
2021-04-30 03:27:00 +00:00
cc controlclient . Client
2022-06-20 01:00:50 +00:00
ccAuto * controlclient . Auto // if cc is of type *controlclient.Auto
2021-09-03 20:17:46 +00:00
machinePrivKey key . MachinePrivate
2022-08-26 16:45:16 +00:00
tka * tkaState
2021-02-04 21:12:42 +00:00
state ipn . State
2021-04-22 07:25:00 +00:00
capFileSharing bool // whether netMap contains the file sharing capability
2022-11-30 18:34:59 +00:00
capTailnetLock bool // whether netMap contains the tailnet lock capability
2020-06-15 23:04:12 +00:00
// hostinfo is mutated in-place while mu is held.
2023-09-17 07:13:52 +00:00
hostinfo * tailcfg . Hostinfo
// netMap is the most recently set full netmap from the controlclient.
// It can't be mutated in place once set. Because it can't be mutated in place,
// delta updates from the control server don't apply to it. Instead, use
// the peers map to get up-to-date information on the state of peers.
// In general, avoid using the netMap.Peers slice. We'd like it to go away
// as of 2023-09-17.
netMap * netmap . NetworkMap
// peers is the set of current peers and their current values after applying
// delta node mutations as they come in (with mu held). The map values can
// be given out to callers, but the map itself must not escape the LocalBackend.
peers map [ tailcfg . NodeID ] tailcfg . NodeView
nodeByAddr map [ netip . Addr ] tailcfg . NodeID
2023-07-27 19:41:31 +00:00
nmExpiryTimer tstime . TimerController // for updating netMap on node expiry; can be nil
2023-09-17 07:13:52 +00:00
activeLogin string // last logged LoginName from netMap
2021-03-25 22:38:40 +00:00
engineStatus ipn . EngineStatus
tailcfg: add Endpoint, EndpointType, MapRequest.EndpointType
Track endpoints internally with a new tailcfg.Endpoint type that
includes a typed netaddr.IPPort (instead of just a string) and
includes a type for how that endpoint was discovered (STUN, local,
etc).
Use []tailcfg.Endpoint instead of []string internally.
At the last second, send it to the control server as the existing
[]string for endpoints, but also include a new parallel
MapRequest.EndpointType []tailcfg.EndpointType, so the control server
can start filtering out less-important endpoint changes from
new-enough clients. Notably, STUN-discovered endpoints can be filtered
out from 1.6+ clients, as they can discover them amongst each other
via CallMeMaybe disco exchanges started over DERP. And STUN endpoints
change a lot, causing a lot of MapResposne updates. But portmapped
endpoints are worth keeping for now, as they they work right away
without requiring the firewall traversal extra RTT dance.
End result will be less control->client bandwidth. (despite negligible
increase in client->control bandwidth)
Updates tailscale/corp#1543
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2021-04-12 20:24:29 +00:00
endpoints [ ] tailcfg . Endpoint
2021-03-25 22:38:40 +00:00
blocked bool
2021-11-04 19:19:00 +00:00
keyExpired bool
2024-05-10 20:25:08 +00:00
authURL string // non-empty if not Running
2024-02-08 21:04:01 +00:00
authURLTime time . Time // when the authURL was received from the control server
2022-09-01 16:27:06 +00:00
egg bool
2024-04-28 04:01:54 +00:00
prevIfState * netmon . State
2021-03-30 18:19:42 +00:00
peerAPIServer * peerAPIServer // or nil
2021-03-25 22:38:40 +00:00
peerAPIListeners [ ] * peerAPIListener
2022-02-18 20:55:22 +00:00
loginFlags controlclient . LoginFlags
2022-11-28 18:34:35 +00:00
fileWaiters set . HandleSet [ context . CancelFunc ] // of wake-up funcs
2024-02-28 21:56:30 +00:00
notifyWatchers map [ string ] * watchSession // by session ID
lastStatusTime time . Time // status.AsOf value of the last processed status update
2021-04-12 21:05:44 +00:00
// directFileRoot, if non-empty, means to write received files
// directly to this directory, without staging them in an
// intermediate buffered directory for "pick-up" later. If
// empty, the files are received in a daemon-owned location
// and the localapi is used to enumerate, download, and delete
// them. This is used on macOS where the GUI lifetime is the
// same as the Network Extension lifetime and we can thus avoid
// double-copying files by writing them to the right location
// immediately.
2022-07-17 17:05:36 +00:00
// It's also used on several NAS platforms (Synology, TrueNAS, etc)
// but in that case DoFinalRename is also set true, which moves the
// *.partial file to its final name on completion.
2024-01-09 20:11:34 +00:00
directFileRoot string
componentLogUntil map [ string ] componentLogState
2023-09-08 21:26:55 +00:00
// c2nUpdateStatus is the status of c2n-triggered client update.
2023-11-09 21:00:47 +00:00
c2nUpdateStatus updateStatus
currentUser ipnauth . WindowsToken
selfUpdateProgress [ ] ipnstate . UpdateProgress
lastSelfUpdateState ipnstate . SelfUpdateStatus
2023-12-04 17:08:56 +00:00
// capForcedNetfilter is the netfilter that control instructs Linux clients
// to use, unless overridden locally.
capForcedNetfilter string
2024-06-04 02:24:53 +00:00
// offlineAutoUpdateCancel stops offline auto-updates when called. It
// should be used via stopOfflineAutoUpdate and
// maybeStartOfflineAutoUpdate. It is nil when offline auto-updates are
// note running.
//
//lint:ignore U1000 only used in Linux and Windows builds in autoupdate.go
offlineAutoUpdateCancel func ( )
2020-02-05 22:16:58 +00:00
2022-11-07 23:32:53 +00:00
// ServeConfig fields. (also guarded by mu)
2024-02-28 21:56:30 +00:00
lastServeConfJSON mem . RO // last JSON that was parsed into serveConfig
serveConfig ipn . ServeConfigView // or !Valid if none
2022-11-07 23:32:53 +00:00
2023-11-09 00:05:33 +00:00
webClient webClient
webClientListeners map [ netip . AddrPort ] * localListener // listeners for local web client traffic
serveListeners map [ netip . AddrPort ] * localListener // listeners for local serve traffic
2023-10-20 11:04:00 +00:00
serveProxyHandlers sync . Map // string (HTTPHandler.Proxy) => *reverseProxy
2022-11-12 02:46:26 +00:00
2020-05-19 02:32:20 +00:00
// statusLock must be held before calling statusChanged.Wait() or
2020-02-05 22:16:58 +00:00
// statusChanged.Broadcast().
statusLock sync . Mutex
statusChanged * sync . Cond
2022-09-23 17:06:55 +00:00
// dialPlan is any dial plan that we've received from the control
// server during a previous connection; it is cleared on logout.
dialPlan atomic . Pointer [ tailcfg . ControlDialPlan ]
2022-10-06 18:09:13 +00:00
// tkaSyncLock is used to make tkaSyncIfNeeded an exclusive
// section. This is needed to stop two map-responses in quick succession
// from racing each other through TKA sync logic / RPCs.
//
// tkaSyncLock MUST be taken before mu (or inversely, mu must not be held
// at the moment that tkaSyncLock is taken).
tkaSyncLock sync . Mutex
2023-07-27 19:41:31 +00:00
clock tstime . Clock
2023-09-08 21:27:49 +00:00
// Last ClientVersion received in MapResponse, guarded by mu.
lastClientVersion * tailcfg . ClientVersion
2024-02-29 19:49:45 +00:00
2024-04-03 17:09:58 +00:00
// lastNotifiedDriveShares keeps track of the last set of shares that we
2024-03-07 16:56:11 +00:00
// notified about.
2024-04-03 17:09:58 +00:00
lastNotifiedDriveShares atomic . Pointer [ views . SliceView [ * drive . Share , drive . ShareView ] ]
2024-03-20 02:54:37 +00:00
2024-03-26 12:27:58 +00:00
// outgoingFiles keeps track of Taildrop outgoing files keyed to their OutgoingFile.ID
2024-03-20 02:54:37 +00:00
outgoingFiles map [ string ] * ipn . OutgoingFile
2024-05-03 17:24:26 +00:00
2024-05-31 13:54:46 +00:00
// lastSuggestedExitNode stores the last suggested exit node suggestion to
// avoid unnecessary churn between multiple equally-good options.
lastSuggestedExitNode tailcfg . StableNodeID
2020-02-05 22:16:58 +00:00
}
2024-04-26 15:06:06 +00:00
// HealthTracker returns the health tracker for the backend.
func ( b * LocalBackend ) HealthTracker ( ) * health . Tracker {
return b . health
}
// NetMon returns the network monitor for the backend.
func ( b * LocalBackend ) NetMon ( ) * netmon . Monitor {
return b . sys . NetMon . Get ( )
}
2023-09-08 21:26:55 +00:00
type updateStatus struct {
started bool
}
2021-04-30 14:23:22 +00:00
// clientGen is a func that creates a control plane client.
// It's the type used by LocalBackend.SetControlClientGetterForTesting.
2021-04-30 03:27:00 +00:00
type clientGen func ( controlclient . Options ) ( controlclient . Client , error )
2020-02-03 18:35:52 +00:00
// NewLocalBackend returns a new LocalBackend that is ready to run,
// but is not actually running.
2021-12-01 04:39:12 +00:00
//
// If dialer is nil, a new one is made.
2023-05-03 20:57:17 +00:00
func NewLocalBackend ( logf logger . Logf , logID logid . PublicID , sys * tsd . System , loginFlags controlclient . LoginFlags ) ( * LocalBackend , error ) {
e := sys . Engine . Get ( )
store := sys . StateStore . Get ( )
dialer := sys . Dialer . Get ( )
2024-04-27 05:06:20 +00:00
if dialer == nil {
return nil , errors . New ( "dialer to NewLocalBackend must be set" )
}
if dialer . NetMon ( ) == nil {
return nil , errors . New ( "dialer to NewLocalBackend must have a NetMon" )
}
2024-05-07 23:57:04 +00:00
mConn := sys . MagicSock . Get ( )
2022-02-14 16:32:23 +00:00
2023-09-29 13:05:12 +00:00
goos := envknob . GOOS ( )
if loginFlags & controlclient . LocalBackendStartKeyOSNeutral != 0 {
goos = ""
}
2024-05-03 14:59:22 +00:00
pm , err := newProfileManagerWithGOOS ( store , logf , sys . HealthTracker ( ) , goos )
2022-11-09 05:58:10 +00:00
if err != nil {
return nil , err
}
2023-03-29 20:51:53 +00:00
if sds , ok := store . ( ipn . StateStoreDialerSetter ) ; ok {
sds . SetDialer ( dialer . SystemDial )
}
2022-11-09 05:58:10 +00:00
2023-10-16 19:15:03 +00:00
if sys . InitialConfig != nil {
p := pm . CurrentPrefs ( ) . AsStruct ( )
mp , err := sys . InitialConfig . Parsed . ToPrefs ( )
if err != nil {
return nil , err
}
p . ApplyEdits ( & mp )
2023-11-17 02:40:23 +00:00
if err := pm . SetPrefs ( p . View ( ) , ipn . NetworkProfile { } ) ; err != nil {
2023-10-16 19:15:03 +00:00
return nil , err
}
}
2022-02-13 04:42:38 +00:00
envknob . LogCurrent ( logf )
2021-04-22 07:25:00 +00:00
osshare . SetFileSharingEnabled ( false , logf )
2020-03-14 03:53:58 +00:00
ctx , cancel := context . WithCancel ( context . Background ( ) )
2023-07-27 19:41:31 +00:00
clock := tstime . StdClock { }
2020-02-05 22:16:58 +00:00
2020-02-25 15:36:32 +00:00
b := & LocalBackend {
2023-09-05 17:51:52 +00:00
ctx : ctx ,
ctxCancel : cancel ,
logf : logf ,
keyLogf : logger . LogOnChange ( logf , 5 * time . Minute , clock . Now ) ,
statsLogf : logger . LogOnChange ( logf , 5 * time . Minute , clock . Now ) ,
sys : sys ,
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
health : sys . HealthTracker ( ) ,
2023-10-11 20:55:57 +00:00
conf : sys . InitialConfig ,
2023-09-05 17:51:52 +00:00
e : e ,
dialer : dialer ,
store : store ,
pm : pm ,
backendLogID : logID ,
state : ipn . NoState ,
2024-05-07 23:42:45 +00:00
portpoll : new ( portlist . Poller ) ,
2023-09-05 17:51:52 +00:00
em : newExpiryManager ( logf ) ,
gotPortPollRes : make ( chan struct { } ) ,
loginFlags : loginFlags ,
clock : clock ,
2023-11-09 21:00:47 +00:00
selfUpdateProgress : make ( [ ] ipnstate . UpdateProgress , 0 ) ,
lastSelfUpdateState : ipnstate . UpdateFinished ,
2020-02-05 22:16:58 +00:00
}
2024-05-07 23:57:04 +00:00
mConn . SetNetInfoCallback ( b . setNetInfo )
2021-12-01 04:39:12 +00:00
2023-05-03 20:57:17 +00:00
netMon := sys . NetMon . Get ( )
2024-04-26 17:12:46 +00:00
b . sockstatLogger , err = sockstatlog . NewLogger ( logpolicy . LogsDir ( logf ) , logf , logID , netMon , sys . HealthTracker ( ) )
2023-04-03 21:21:48 +00:00
if err != nil {
log . Printf ( "error setting up sockstat logger: %v" , err )
}
2024-04-01 21:17:09 +00:00
// Enable sockstats logs only on non-mobile unstable builds
if version . IsUnstableBuild ( ) && ! version . IsMobile ( ) && b . sockstatLogger != nil {
2023-04-03 21:21:48 +00:00
b . sockstatLogger . SetLoggingEnabled ( true )
2023-03-08 00:22:23 +00:00
}
2021-11-25 17:43:39 +00:00
// Default filter blocks everything and logs nothing, until Start() is called.
2024-05-06 18:09:10 +00:00
noneFilter := filter . NewAllowNone ( logf , & netipx . IPSet { } )
b . setFilter ( noneFilter )
b . e . SetJailedFilter ( noneFilter )
2021-11-25 17:43:39 +00:00
2022-11-07 23:32:53 +00:00
b . setTCPPortsIntercepted ( nil )
2020-02-05 22:16:58 +00:00
b . statusChanged = sync . NewCond ( & b . statusLock )
2021-07-19 18:07:42 +00:00
b . e . SetStatusCallback ( b . setWgengineStatus )
2020-02-05 22:16:58 +00:00
2023-04-18 21:26:58 +00:00
b . prevIfState = netMon . InterfaceState ( )
2021-03-02 04:45:30 +00:00
// Call our linkChange code once with the current state, and
// then also whenever it changes:
2023-08-23 17:05:21 +00:00
b . linkChange ( & netmon . ChangeDelta { New : netMon . InterfaceState ( ) } )
2023-04-18 21:26:58 +00:00
b . unregisterNetMon = netMon . RegisterChangeCallback ( b . linkChange )
2021-03-02 04:45:30 +00:00
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
b . unregisterHealthWatch = b . health . RegisterWatcher ( b . onHealthChange )
2021-03-16 05:20:48 +00:00
2023-05-03 20:57:17 +00:00
if tunWrap , ok := b . sys . Tun . GetOK ( ) ; ok {
tunWrap . PeerAPIPort = b . GetPeerAPIPort
} else {
2022-11-16 17:38:38 +00:00
b . logf ( "[unexpected] failed to wire up PeerAPI port for engine %T" , e )
2021-03-29 22:17:05 +00:00
}
2023-10-03 10:31:56 +00:00
for _ , component := range ipn . DebuggableComponents {
2022-10-04 03:39:45 +00:00
key := componentStateKey ( component )
2022-11-09 05:58:10 +00:00
if ut , err := ipn . ReadStoreInt ( pm . Store ( ) , key ) ; err == nil {
2023-07-27 19:41:31 +00:00
if until := time . Unix ( ut , 0 ) ; until . After ( b . clock . Now ( ) ) {
2022-10-04 03:39:45 +00:00
// conditional to avoid log spam at start when off
b . SetComponentDebugLogging ( component , until )
}
}
}
2024-04-03 17:09:58 +00:00
// initialize Taildrive shares from saved state
fs , ok := b . sys . DriveForRemote . GetOK ( )
2024-02-09 22:23:42 +00:00
if ok {
2024-04-03 17:09:58 +00:00
currentShares := b . pm . prefs . DriveShares ( )
2024-03-07 16:56:11 +00:00
if currentShares . Len ( ) > 0 {
2024-04-02 20:32:30 +00:00
var shares [ ] * drive . Share
2024-04-16 20:15:13 +00:00
for i := range currentShares . Len ( ) {
2024-03-07 16:56:11 +00:00
shares = append ( shares , currentShares . At ( i ) . AsStruct ( ) )
}
2024-02-09 17:26:43 +00:00
fs . SetShares ( shares )
}
2024-02-02 18:45:32 +00:00
}
2020-02-25 15:36:32 +00:00
return b , nil
2020-02-05 22:16:58 +00:00
}
2022-10-04 03:39:45 +00:00
type componentLogState struct {
until time . Time
2023-07-27 19:41:31 +00:00
timer tstime . TimerController // if non-nil, the AfterFunc to disable it
2022-10-04 03:39:45 +00:00
}
func componentStateKey ( component string ) ipn . StateKey {
return ipn . StateKey ( "_debug_" + component + "_until" )
}
// SetComponentDebugLogging sets component's debug logging enabled until the until time.
// If until is in the past, the component's debug logging is disabled.
//
// The following components are recognized:
//
// - magicsock
2023-03-30 14:03:09 +00:00
// - sockstats
2022-10-04 03:39:45 +00:00
func ( b * LocalBackend ) SetComponentDebugLogging ( component string , until time . Time ) error {
b . mu . Lock ( )
defer b . mu . Unlock ( )
var setEnabled func ( bool )
switch component {
case "magicsock" :
2023-11-15 23:10:45 +00:00
setEnabled = b . MagicConn ( ) . SetDebugLoggingEnabled
2023-03-27 21:34:56 +00:00
case "sockstats" :
if b . sockstatLogger != nil {
2023-04-03 21:16:53 +00:00
setEnabled = func ( v bool ) {
b . sockstatLogger . SetLoggingEnabled ( v )
// Flush (and thus upload) logs when the enabled period ends,
// so that the logs are available for debugging.
if ! v {
b . sockstatLogger . Flush ( )
}
}
2023-03-27 21:34:56 +00:00
}
2022-10-04 03:39:45 +00:00
}
2023-10-03 10:31:56 +00:00
if setEnabled == nil || ! slices . Contains ( ipn . DebuggableComponents , component ) {
2022-10-04 03:39:45 +00:00
return fmt . Errorf ( "unknown component %q" , component )
}
timeUnixOrZero := func ( t time . Time ) int64 {
if t . IsZero ( ) {
return 0
}
return t . Unix ( )
}
ipn . PutStoreInt ( b . store , componentStateKey ( component ) , timeUnixOrZero ( until ) )
2023-07-27 19:41:31 +00:00
now := b . clock . Now ( )
2022-10-04 03:39:45 +00:00
on := now . Before ( until )
setEnabled ( on )
var onFor time . Duration
if on {
onFor = until . Sub ( now )
b . logf ( "debugging logging for component %q enabled for %v (until %v)" , component , onFor . Round ( time . Second ) , until . UTC ( ) . Format ( time . RFC3339 ) )
} else {
b . logf ( "debugging logging for component %q disabled" , component )
}
if oldSt , ok := b . componentLogUntil [ component ] ; ok && oldSt . timer != nil {
oldSt . timer . Stop ( )
}
newSt := componentLogState { until : until }
if on {
2023-07-27 19:41:31 +00:00
newSt . timer = b . clock . AfterFunc ( onFor , func ( ) {
2022-10-04 03:39:45 +00:00
// Turn off logging after the timer fires, as long as the state is
// unchanged when the timer actually fires.
b . mu . Lock ( )
defer b . mu . Unlock ( )
2023-04-20 01:54:19 +00:00
if ls := b . componentLogUntil [ component ] ; ls . until . Equal ( until ) {
2022-10-04 03:39:45 +00:00
setEnabled ( false )
b . logf ( "debugging logging for component %q disabled (by timer)" , component )
}
} )
}
mak . Set ( & b . componentLogUntil , component , newSt )
return nil
}
2022-10-15 17:31:35 +00:00
// GetComponentDebugLogging gets the time that component's debug logging is
// enabled until, or the zero time if component's time is not currently
// enabled.
func ( b * LocalBackend ) GetComponentDebugLogging ( component string ) time . Time {
b . mu . Lock ( )
defer b . mu . Unlock ( )
2023-07-27 19:41:31 +00:00
now := b . clock . Now ( )
2022-10-15 17:31:35 +00:00
ls := b . componentLogUntil [ component ]
if ls . until . IsZero ( ) || ls . until . Before ( now ) {
return time . Time { }
}
return ls . until
}
2021-12-01 04:39:12 +00:00
// Dialer returns the backend's dialer.
2023-05-03 20:57:17 +00:00
// It is always non-nil.
2021-12-01 04:39:12 +00:00
func ( b * LocalBackend ) Dialer ( ) * tsdial . Dialer {
return b . dialer
}
2021-04-12 21:05:44 +00:00
// SetDirectFileRoot sets the directory to download files to directly,
// without buffering them through an intermediate daemon-owned
// tailcfg.UserID-specific directory.
//
// This must be called before the LocalBackend starts being used.
func ( b * LocalBackend ) SetDirectFileRoot ( dir string ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
b . directFileRoot = dir
}
2023-11-01 18:51:07 +00:00
// ReloadConfig reloads the backend's config from disk.
2023-10-11 20:55:57 +00:00
//
// It returns (false, nil) if not running in declarative mode, (true, nil) on
// success, or (false, error) on failure.
func ( b * LocalBackend ) ReloadConfig ( ) ( ok bool , err error ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
if b . conf == nil {
return false , nil
}
conf , err := conffile . Load ( b . conf . Path )
if err != nil {
return false , err
}
b . conf = conf
// TODO(bradfitz): apply things
return true , nil
}
2024-05-05 18:57:47 +00:00
var assumeNetworkUpdateForTest = envknob . RegisterBool ( "TS_ASSUME_NETWORK_UP_FOR_TEST" )
2023-08-04 05:37:52 +00:00
// pauseOrResumeControlClientLocked pauses b.cc if there is no network available
// or if the LocalBackend is in Stopped state with a valid NetMap. In all other
// cases, it unpauses it. It is a no-op if b.cc is nil.
//
2021-07-16 22:21:00 +00:00
// b.mu must be held.
2023-08-04 05:37:52 +00:00
func ( b * LocalBackend ) pauseOrResumeControlClientLocked ( ) {
2021-07-16 22:21:00 +00:00
if b . cc == nil {
return
}
networkUp := b . prevIfState . AnyInterfaceUp ( )
2024-05-05 18:57:47 +00:00
b . cc . SetPaused ( ( b . state == ipn . Stopped && b . netMap != nil ) || ( ! networkUp && ! testenv . InTest ( ) && ! assumeNetworkUpdateForTest ( ) ) )
2021-07-16 22:21:00 +00:00
}
2023-04-18 21:26:58 +00:00
// linkChange is our network monitor callback, called whenever the network changes.
2023-08-23 17:05:21 +00:00
func ( b * LocalBackend ) linkChange ( delta * netmon . ChangeDelta ) {
2020-10-02 05:03:25 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2023-08-23 17:05:21 +00:00
ifst := delta . New
2020-10-05 22:12:35 +00:00
hadPAC := b . prevIfState . HasPAC ( )
b . prevIfState = ifst
2023-08-04 05:37:52 +00:00
b . pauseOrResumeControlClientLocked ( )
2020-10-06 22:22:46 +00:00
2020-10-05 22:12:35 +00:00
// If the PAC-ness of the network changed, reconfig wireguard+route to
// add/remove subnets.
if hadPAC != ifst . HasPAC ( ) {
b . logf ( "linkChange: in state %v; PAC changed from %v->%v" , b . state , hadPAC , ifst . HasPAC ( ) )
switch b . state {
2021-02-04 21:12:42 +00:00
case ipn . NoState , ipn . Stopped :
2020-10-05 22:12:35 +00:00
// Do nothing.
default :
go b . authReconfig ( )
2020-10-02 05:03:25 +00:00
}
}
2021-02-23 04:43:35 +00:00
// If the local network configuration has changed, our filter may
// need updating to tweak default routes.
2022-11-09 05:58:10 +00:00
b . updateFilterLocked ( b . netMap , b . pm . CurrentPrefs ( ) )
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
updateExitNodeUsageWarning ( b . pm . CurrentPrefs ( ) , delta . New , b . health )
2021-03-30 20:49:08 +00:00
2021-06-14 15:59:09 +00:00
if peerAPIListenAsync && b . netMap != nil && b . state == ipn . Running {
2023-09-17 17:53:23 +00:00
want := b . netMap . GetAddresses ( ) . Len ( )
2021-03-30 20:49:08 +00:00
if len ( b . peerAPIListeners ) < want {
2021-07-06 16:07:18 +00:00
b . logf ( "linkChange: peerAPIListeners too low; trying again" )
2021-03-30 20:49:08 +00:00
go b . initPeerAPIListener ( )
}
}
2020-08-28 04:25:17 +00:00
}
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
func ( b * LocalBackend ) onHealthChange ( w * health . Warnable , us * health . UnhealthyState ) {
if us == nil {
b . logf ( "health(warnable=%s): ok" , w . Code )
2021-03-16 05:20:48 +00:00
} else {
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
b . logf ( "health(warnable=%s): error: %s" , w . Code , us . Text )
2021-03-16 05:20:48 +00:00
}
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
// Whenever health changes, send the current health state to the frontend.
state := b . health . CurrentState ( )
b . send ( ipn . Notify {
Health : state ,
} )
2021-03-16 05:20:48 +00:00
}
2020-05-19 02:32:20 +00:00
// Shutdown halts the backend and all its sub-components. The backend
// can no longer be used after Shutdown returns.
2020-02-05 22:16:58 +00:00
func ( b * LocalBackend ) Shutdown ( ) {
2020-05-19 02:32:20 +00:00
b . mu . Lock ( )
2022-07-19 03:36:14 +00:00
if b . shutdownCalled {
b . mu . Unlock ( )
return
}
2022-04-25 18:02:59 +00:00
b . shutdownCalled = true
2022-07-19 03:36:14 +00:00
if b . loginFlags & controlclient . LoginEphemeral != 0 {
b . mu . Unlock ( )
ctx , cancel := context . WithTimeout ( b . ctx , 5 * time . Second )
defer cancel ( )
2023-08-31 16:13:04 +00:00
t0 := time . Now ( )
2023-09-01 02:11:20 +00:00
err := b . Logout ( ctx ) // best effort
2023-08-31 16:13:04 +00:00
td := time . Since ( t0 ) . Round ( time . Millisecond )
if err != nil {
b . logf ( "failed to log out ephemeral node on shutdown after %v: %v" , td , err )
} else {
b . logf ( "logged out ephemeral node on shutdown" )
}
2022-07-19 03:36:14 +00:00
b . mu . Lock ( )
}
2021-04-08 04:12:16 +00:00
cc := b . cc
2022-05-28 11:33:46 +00:00
if b . sshServer != nil {
b . sshServer . Shutdown ( )
2022-05-30 09:06:46 +00:00
b . sshServer = nil
2022-05-28 11:33:46 +00:00
}
2022-04-21 02:15:43 +00:00
b . closePeerAPIListenersLocked ( )
2023-01-19 22:28:49 +00:00
if b . debugSink != nil {
b . e . InstallCaptureHook ( nil )
b . debugSink . Close ( )
b . debugSink = nil
}
2024-05-08 00:31:10 +00:00
if b . notifyCancel != nil {
b . notifyCancel ( )
}
2020-05-19 02:32:20 +00:00
b . mu . Unlock ( )
2023-11-15 22:40:37 +00:00
b . webClientShutdown ( )
2020-05-21 20:30:20 +00:00
2023-03-08 00:22:23 +00:00
if b . sockstatLogger != nil {
b . sockstatLogger . Shutdown ( )
}
2023-10-17 20:46:05 +00:00
if b . peerAPIServer != nil {
b . peerAPIServer . taildrop . Shutdown ( )
}
2024-06-04 14:59:59 +00:00
b . stopOfflineAutoUpdate ( )
2023-03-08 00:22:23 +00:00
2023-04-18 21:26:58 +00:00
b . unregisterNetMon ( )
2021-03-16 05:20:48 +00:00
b . unregisterHealthWatch ( )
2021-04-08 04:12:16 +00:00
if cc != nil {
cc . Shutdown ( )
2020-05-19 02:32:20 +00:00
}
2020-05-21 20:30:20 +00:00
b . ctxCancel ( )
2020-02-05 22:16:58 +00:00
b . e . Close ( )
2024-02-24 01:55:08 +00:00
<- b . e . Done ( )
2020-02-05 22:16:58 +00:00
}
2022-10-24 00:15:04 +00:00
func stripKeysFromPrefs ( p ipn . PrefsView ) ipn . PrefsView {
2022-11-29 20:00:40 +00:00
if ! p . Valid ( ) || ! p . Persist ( ) . Valid ( ) {
2022-10-24 00:15:04 +00:00
return p
}
p2 := p . AsStruct ( )
p2 . Persist . LegacyFrontendPrivateMachineKey = key . MachinePrivate { }
p2 . Persist . PrivateNodeKey = key . NodePrivate { }
p2 . Persist . OldPrivateNodeKey = key . NodePrivate { }
2022-11-18 19:23:57 +00:00
p2 . Persist . NetworkLockKey = key . NLPrivate { }
2022-10-24 00:15:04 +00:00
return p2 . View ( )
}
2021-04-07 15:27:35 +00:00
// Prefs returns a copy of b's current prefs, with any private keys removed.
2022-10-24 00:15:04 +00:00
func ( b * LocalBackend ) Prefs ( ) ipn . PrefsView {
2021-04-07 15:27:35 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-12-02 08:54:32 +00:00
return b . sanitizedPrefsLocked ( )
2022-12-01 01:39:43 +00:00
}
2022-12-02 08:54:32 +00:00
func ( b * LocalBackend ) sanitizedPrefsLocked ( ) ipn . PrefsView {
2022-11-09 05:58:10 +00:00
return stripKeysFromPrefs ( b . pm . CurrentPrefs ( ) )
2021-04-07 15:27:35 +00:00
}
2020-05-19 02:32:20 +00:00
// Status returns the latest status of the backend and its
// sub-components.
2020-03-26 05:57:46 +00:00
func ( b * LocalBackend ) Status ( ) * ipnstate . Status {
2022-12-19 18:23:47 +00:00
sb := & ipnstate . StatusBuilder { WantPeers : true }
2020-03-26 05:57:46 +00:00
b . UpdateStatus ( sb )
return sb . Status ( )
}
2021-03-19 04:07:58 +00:00
// StatusWithoutPeers is like Status but omits any details
// of peers.
func ( b * LocalBackend ) StatusWithoutPeers ( ) * ipnstate . Status {
2022-12-19 18:23:47 +00:00
sb := & ipnstate . StatusBuilder { WantPeers : false }
b . UpdateStatus ( sb )
2021-03-19 04:07:58 +00:00
return sb . Status ( )
}
2020-05-19 02:32:20 +00:00
// UpdateStatus implements ipnstate.StatusUpdater.
2020-03-26 05:57:46 +00:00
func ( b * LocalBackend ) UpdateStatus ( sb * ipnstate . StatusBuilder ) {
2023-09-17 12:20:50 +00:00
b . e . UpdateStatus ( sb ) // does wireguard + magicsock status
2020-03-26 05:57:46 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2023-08-23 19:13:38 +00:00
2021-03-25 22:38:40 +00:00
sb . MutateStatus ( func ( s * ipnstate . Status ) {
2023-02-11 06:20:36 +00:00
s . Version = version . Long ( )
2023-05-03 20:57:17 +00:00
s . TUN = ! b . sys . IsNetstack ( )
2021-03-25 22:38:40 +00:00
s . BackendState = b . state . String ( )
2024-05-10 20:25:08 +00:00
s . AuthURL = b . authURL
2023-09-08 21:27:49 +00:00
if prefs := b . pm . CurrentPrefs ( ) ; prefs . Valid ( ) && prefs . AutoUpdate ( ) . Check {
s . ClientVersion = b . lastClientVersion
2021-09-02 02:27:22 +00:00
}
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
s . Health = b . health . Strings ( )
2024-05-07 04:33:37 +00:00
s . HaveNodeKey = b . hasNodeKeyLocked ( )
2024-05-01 20:54:56 +00:00
// TODO(bradfitz): move this health check into a health.Warnable
// and remove from here.
2022-06-17 19:09:23 +00:00
if m := b . sshOnButUnusableHealthCheckMessageLocked ( ) ; m != "" {
s . Health = append ( s . Health , m )
}
2021-03-25 22:38:40 +00:00
if b . netMap != nil {
2021-06-15 19:12:15 +00:00
s . CertDomains = append ( [ ] string ( nil ) , b . netMap . DNS . CertDomains ... )
2022-02-15 17:36:01 +00:00
s . MagicDNSSuffix = b . netMap . MagicDNSSuffix ( )
if s . CurrentTailnet == nil {
s . CurrentTailnet = & ipnstate . TailnetStatus { }
}
s . CurrentTailnet . MagicDNSSuffix = b . netMap . MagicDNSSuffix ( )
s . CurrentTailnet . MagicDNSEnabled = b . netMap . DNS . Proxied
s . CurrentTailnet . Name = b . netMap . Domain
2022-11-11 17:43:49 +00:00
if prefs := b . pm . CurrentPrefs ( ) ; prefs . Valid ( ) {
if ! prefs . RouteAll ( ) && b . netMap . AnyPeersAdvertiseRoutes ( ) {
s . Health = append ( s . Health , healthmsg . WarnAcceptRoutesOff )
}
if ! prefs . ExitNodeID ( ) . IsZero ( ) {
if exitPeer , ok := b . netMap . PeerWithStableID ( prefs . ExitNodeID ( ) ) ; ok {
2023-12-19 17:33:38 +00:00
online := false
2023-08-18 14:57:44 +00:00
if v := exitPeer . Online ( ) ; v != nil {
online = * v
2022-11-11 17:43:49 +00:00
}
s . ExitNodeStatus = & ipnstate . ExitNodeStatus {
ID : prefs . ExitNodeID ( ) ,
Online : online ,
2023-08-18 14:57:44 +00:00
TailscaleIPs : exitPeer . Addresses ( ) . AsSlice ( ) ,
2022-11-11 17:43:49 +00:00
}
2022-06-07 19:31:10 +00:00
}
}
}
2021-03-25 22:38:40 +00:00
}
} )
2023-08-23 19:13:38 +00:00
var tailscaleIPs [ ] netip . Addr
if b . netMap != nil {
2023-09-17 17:53:23 +00:00
addrs := b . netMap . GetAddresses ( )
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-09-17 17:53:23 +00:00
if addr := addrs . At ( i ) ; addr . IsSingleIP ( ) {
2023-08-23 19:13:38 +00:00
sb . AddTailscaleIP ( addr . Addr ( ) )
tailscaleIPs = append ( tailscaleIPs , addr . Addr ( ) )
}
}
}
2021-03-25 22:38:40 +00:00
sb . MutateSelfStatus ( func ( ss * ipnstate . PeerStatus ) {
2023-08-23 19:13:38 +00:00
ss . OS = version . OS ( )
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
ss . Online = b . health . GetInPollNetMap ( )
2021-11-26 01:11:01 +00:00
if b . netMap != nil {
2022-10-28 16:39:01 +00:00
ss . InNetworkMap = true
2023-08-22 16:41:52 +00:00
if hi := b . netMap . SelfNode . Hostinfo ( ) ; hi . Valid ( ) {
ss . HostName = hi . Hostname ( )
}
2021-11-26 01:11:01 +00:00
ss . DNSName = b . netMap . Name
2023-08-20 22:17:25 +00:00
ss . UserID = b . netMap . User ( )
2023-08-21 17:53:57 +00:00
if sn := b . netMap . SelfNode ; sn . Valid ( ) {
peerStatusFromNode ( ss , sn )
2023-09-18 15:52:22 +00:00
if cm := sn . CapMap ( ) ; cm . Len ( ) > 0 {
2024-03-23 23:23:59 +00:00
ss . Capabilities = make ( [ ] tailcfg . NodeCapability , 1 , cm . Len ( ) + 1 )
ss . Capabilities [ 0 ] = "HTTPS://TAILSCALE.COM/s/DEPRECATED-NODE-CAPS#see-https://github.com/tailscale/tailscale/issues/11508"
2023-09-18 15:52:22 +00:00
ss . CapMap = make ( tailcfg . NodeCapMap , sn . CapMap ( ) . Len ( ) )
cm . Range ( func ( k tailcfg . NodeCapability , v views . Slice [ tailcfg . RawMessage ] ) bool {
ss . CapMap [ k ] = v . AsSlice ( )
2024-03-23 23:23:59 +00:00
ss . Capabilities = append ( ss . Capabilities , k )
2023-09-18 15:52:22 +00:00
return true
} )
2024-03-23 23:23:59 +00:00
slices . Sort ( ss . Capabilities [ 1 : ] )
2023-09-18 15:52:22 +00:00
}
2021-11-26 01:11:01 +00:00
}
2023-08-23 19:13:38 +00:00
for _ , addr := range tailscaleIPs {
ss . TailscaleIPs = append ( ss . TailscaleIPs , addr )
}
2021-11-26 01:11:01 +00:00
} else {
ss . HostName , _ = os . Hostname ( )
2021-05-07 14:27:14 +00:00
}
2021-03-25 22:38:40 +00:00
for _ , pln := range b . peerAPIListeners {
2021-03-26 20:44:55 +00:00
ss . PeerAPIURL = append ( ss . PeerAPIURL , pln . urlStr )
2021-03-25 22:38:40 +00:00
}
} )
2020-03-26 05:57:46 +00:00
// TODO: hostinfo, and its networkinfo
// TODO: EngineStatus copy (and deprecate it?)
2021-03-19 04:07:58 +00:00
2023-09-17 12:20:50 +00:00
if sb . WantPeers {
b . populatePeerStatusLocked ( sb )
2021-03-19 04:07:58 +00:00
}
}
func ( b * LocalBackend ) populatePeerStatusLocked ( sb * ipnstate . StatusBuilder ) {
if b . netMap == nil {
return
}
for id , up := range b . netMap . UserProfiles {
sb . AddUser ( id , up )
}
2022-11-09 05:58:10 +00:00
exitNodeID := b . pm . CurrentPrefs ( ) . ExitNodeID ( )
2023-09-17 07:13:52 +00:00
for _ , p := range b . peers {
2021-03-19 04:07:58 +00:00
var lastSeen time . Time
2023-08-18 14:57:44 +00:00
if p . LastSeen ( ) != nil {
lastSeen = * p . LastSeen ( )
2020-03-26 05:57:46 +00:00
}
2023-12-19 17:33:38 +00:00
tailscaleIPs := make ( [ ] netip . Addr , 0 , p . Addresses ( ) . Len ( ) )
2024-02-25 15:57:11 +00:00
for i := range p . Addresses ( ) . Len ( ) {
2023-08-18 14:57:44 +00:00
addr := p . Addresses ( ) . At ( i )
2022-07-25 03:08:42 +00:00
if addr . IsSingleIP ( ) && tsaddr . IsTailscaleIP ( addr . Addr ( ) ) {
tailscaleIPs = append ( tailscaleIPs , addr . Addr ( ) )
2020-03-26 05:57:46 +00:00
}
}
2023-08-18 14:57:44 +00:00
online := p . Online ( )
2022-10-28 16:39:01 +00:00
ps := & ipnstate . PeerStatus {
2023-08-19 22:06:23 +00:00
InNetworkMap : true ,
UserID : p . User ( ) ,
AltSharerUserID : p . Sharer ( ) ,
TailscaleIPs : tailscaleIPs ,
HostName : p . Hostinfo ( ) . Hostname ( ) ,
DNSName : p . Name ( ) ,
OS : p . Hostinfo ( ) . OS ( ) ,
LastSeen : lastSeen ,
Online : online != nil && * online ,
ShareeNode : p . Hostinfo ( ) . ShareeNode ( ) ,
ExitNode : p . StableID ( ) != "" && p . StableID ( ) == exitNodeID ,
SSH_HostKeys : p . Hostinfo ( ) . SSH_HostKeys ( ) . AsSlice ( ) ,
Location : p . Hostinfo ( ) . Location ( ) ,
2024-04-03 14:55:28 +00:00
Capabilities : p . Capabilities ( ) . AsSlice ( ) ,
}
if cm := p . CapMap ( ) ; cm . Len ( ) > 0 {
ps . CapMap = make ( tailcfg . NodeCapMap , cm . Len ( ) )
cm . Range ( func ( k tailcfg . NodeCapability , v views . Slice [ tailcfg . RawMessage ] ) bool {
ps . CapMap [ k ] = v . AsSlice ( )
return true
} )
2022-02-22 17:52:49 +00:00
}
2022-10-28 16:39:01 +00:00
peerStatusFromNode ( ps , p )
2022-11-17 20:22:00 +00:00
p4 , p6 := peerAPIPorts ( p )
2022-11-19 21:10:45 +00:00
if u := peerAPIURL ( nodeIP ( p , netip . Addr . Is4 ) , p4 ) ; u != "" {
ps . PeerAPIURL = append ( ps . PeerAPIURL , u )
2022-11-17 20:22:00 +00:00
}
2022-11-19 21:10:45 +00:00
if u := peerAPIURL ( nodeIP ( p , netip . Addr . Is6 ) , p6 ) ; u != "" {
ps . PeerAPIURL = append ( ps . PeerAPIURL , u )
2022-11-17 20:22:00 +00:00
}
2023-08-18 14:57:44 +00:00
sb . AddPeer ( p . Key ( ) , ps )
2022-10-28 16:39:01 +00:00
}
}
// peerStatusFromNode copies fields that exist in the Node struct for
// current node and peers into the provided PeerStatus.
2023-08-18 14:57:44 +00:00
func peerStatusFromNode ( ps * ipnstate . PeerStatus , n tailcfg . NodeView ) {
2023-08-23 19:13:38 +00:00
ps . PublicKey = n . Key ( )
2023-08-18 14:57:44 +00:00
ps . ID = n . StableID ( )
ps . Created = n . Created ( )
ps . ExitNodeOption = tsaddr . ContainsExitRoutes ( n . AllowedIPs ( ) )
if n . Tags ( ) . Len ( ) != 0 {
v := n . Tags ( )
2022-10-28 16:39:01 +00:00
ps . Tags = & v
}
2023-08-18 14:57:44 +00:00
if n . PrimaryRoutes ( ) . Len ( ) != 0 {
v := n . PrimaryRoutes ( )
2022-10-28 16:39:01 +00:00
ps . PrimaryRoutes = & v
2020-03-26 05:57:46 +00:00
}
2023-11-29 16:17:00 +00:00
if n . AllowedIPs ( ) . Len ( ) != 0 {
v := n . AllowedIPs ( )
ps . AllowedIPs = & v
}
2023-01-13 23:41:11 +00:00
2023-08-18 14:57:44 +00:00
if n . Expired ( ) {
2023-01-13 23:41:11 +00:00
ps . Expired = true
}
2023-08-18 14:57:44 +00:00
if t := n . KeyExpiry ( ) ; ! t . IsZero ( ) {
2023-01-23 20:33:58 +00:00
t = t . Round ( time . Second )
ps . KeyExpiry = & t
}
2021-01-28 23:29:17 +00:00
}
2020-03-26 05:57:46 +00:00
2024-06-14 15:05:47 +00:00
// WhoIsNodeKey returns the peer info of given public key, if it exists.
func ( b * LocalBackend ) WhoIsNodeKey ( k key . NodePublic ) ( n tailcfg . NodeView , u tailcfg . UserProfile , ok bool ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
// TODO(bradfitz): add nodeByKey like nodeByAddr instead of walking peers.
if b . netMap == nil {
return n , u , false
}
if self := b . netMap . SelfNode ; self . Valid ( ) && self . Key ( ) == k {
return self , b . netMap . UserProfiles [ self . User ( ) ] , true
}
for _ , n := range b . peers {
if n . Key ( ) == k {
u , ok = b . netMap . UserProfiles [ n . User ( ) ]
return n , u , ok
}
}
return n , u , false
}
2021-03-15 21:59:35 +00:00
// WhoIs reports the node and user who owns the node with the given IP:port.
// If the IP address is a Tailscale IP, the provided port may be 0.
2021-01-28 23:29:17 +00:00
// If ok == true, n and u are valid.
2023-08-18 14:57:44 +00:00
func ( b * LocalBackend ) WhoIs ( ipp netip . AddrPort ) ( n tailcfg . NodeView , u tailcfg . UserProfile , ok bool ) {
var zero tailcfg . NodeView
2021-01-28 23:29:17 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2024-02-02 18:45:32 +00:00
2023-09-17 07:13:52 +00:00
nid , ok := b . nodeByAddr [ ipp . Addr ( ) ]
2021-01-28 23:29:17 +00:00
if ! ok {
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
var ip netip . Addr
2021-05-15 01:07:28 +00:00
if ipp . Port ( ) != 0 {
2023-09-13 18:38:05 +00:00
ip , ok = b . sys . ProxyMapper ( ) . WhoIsIPPort ( ipp )
2021-03-15 21:59:35 +00:00
}
if ! ok {
2023-08-18 14:57:44 +00:00
return zero , u , false
2021-03-15 21:59:35 +00:00
}
2023-09-17 07:13:52 +00:00
nid , ok = b . nodeByAddr [ ip ]
2021-03-15 21:59:35 +00:00
if ! ok {
2023-08-18 14:57:44 +00:00
return zero , u , false
2021-03-15 21:59:35 +00:00
}
2021-01-28 23:29:17 +00:00
}
2023-09-20 20:46:19 +00:00
if b . netMap == nil {
return zero , u , false
}
2023-09-17 07:13:52 +00:00
n , ok = b . peers [ nid ]
if ! ok {
2023-09-20 20:46:19 +00:00
// Check if this the self-node, which would not appear in peers.
if ! b . netMap . SelfNode . Valid ( ) || nid != b . netMap . SelfNode . ID ( ) {
return zero , u , false
}
n = b . netMap . SelfNode
2023-09-17 07:13:52 +00:00
}
2023-08-18 14:57:44 +00:00
u , ok = b . netMap . UserProfiles [ n . User ( ) ]
2021-01-28 23:29:17 +00:00
if ! ok {
2023-08-18 14:57:44 +00:00
return zero , u , false
2021-01-28 23:29:17 +00:00
}
return n , u , true
2020-03-26 05:57:46 +00:00
}
2022-03-18 18:48:40 +00:00
// PeerCaps returns the capabilities that remote src IP has to
// ths current node.
2023-07-25 04:07:00 +00:00
func ( b * LocalBackend ) PeerCaps ( src netip . Addr ) tailcfg . PeerCapMap {
2022-03-18 18:48:40 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-09-19 17:36:07 +00:00
return b . peerCapsLocked ( src )
}
2023-07-25 04:07:00 +00:00
func ( b * LocalBackend ) peerCapsLocked ( src netip . Addr ) tailcfg . PeerCapMap {
2022-03-18 18:48:40 +00:00
if b . netMap == nil {
return nil
}
2022-08-04 04:31:40 +00:00
filt := b . filterAtomic . Load ( )
if filt == nil {
2022-03-18 18:48:40 +00:00
return nil
}
2023-09-17 17:53:23 +00:00
addrs := b . netMap . GetAddresses ( )
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-09-17 17:53:23 +00:00
a := addrs . At ( i )
2022-03-18 18:48:40 +00:00
if ! a . IsSingleIP ( ) {
continue
}
2022-09-19 17:36:07 +00:00
dst := a . Addr ( )
if dst . BitLen ( ) == src . BitLen ( ) { // match on family
2023-07-25 04:07:00 +00:00
return filt . CapsWithValues ( src , dst )
2022-03-18 18:48:40 +00:00
}
}
return nil
}
2023-08-28 22:27:39 +00:00
// SetControlClientStatus is the callback invoked by the control client whenever it posts a new status.
2020-06-15 23:04:12 +00:00
// Among other things, this is where we update the netmap, packet filters, DNS and DERP maps.
2023-09-02 19:04:03 +00:00
func ( b * LocalBackend ) SetControlClientStatus ( c controlclient . Client , st controlclient . Status ) {
2024-04-07 04:16:00 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2023-09-02 19:04:03 +00:00
if b . cc != c {
b . logf ( "Ignoring SetControlClientStatus from old client" )
return
}
2021-10-26 17:19:35 +00:00
if st . Err != nil {
2024-04-07 04:16:00 +00:00
// The following do not depend on any data for which we need b locked.
unlock . UnlockEarly ( )
2021-10-26 17:19:35 +00:00
if errors . Is ( st . Err , io . EOF ) {
2020-12-21 18:58:06 +00:00
b . logf ( "[v1] Received error: EOF" )
2021-11-03 22:42:40 +00:00
return
}
b . logf ( "Received error: %v" , st . Err )
var uerr controlclient . UserVisibleError
if errors . As ( st . Err , & uerr ) {
s := uerr . UserVisibleError ( )
b . send ( ipn . Notify { ErrMessage : & s } )
2020-12-21 18:58:06 +00:00
}
2020-07-29 01:47:23 +00:00
return
}
2021-05-06 03:28:29 +00:00
2023-01-11 20:59:08 +00:00
// Track the number of calls
currCall := b . numClientStatusCalls . Add ( 1 )
// Handle node expiry in the netmap
if st . NetMap != nil {
2023-07-27 19:41:31 +00:00
now := b . clock . Now ( )
2023-02-06 23:24:48 +00:00
b . em . flagExpiredPeers ( st . NetMap , now )
2023-01-11 20:59:08 +00:00
// Always stop the existing netmap timer if we have a netmap;
// it's possible that we have no nodes expiring, so we should
// always cancel the timer and then possibly restart it below.
if b . nmExpiryTimer != nil {
// Ignore if we can't stop; the atomic check in the
// AfterFunc (below) will skip running.
b . nmExpiryTimer . Stop ( )
// Nil so we don't attempt to stop on the next netmap
b . nmExpiryTimer = nil
}
// Figure out when the next node in the netmap is expiring so we can
// start a timer to reconfigure at that point.
2023-02-06 23:24:48 +00:00
nextExpiry := b . em . nextPeerExpiry ( st . NetMap , now )
2023-01-11 20:59:08 +00:00
if ! nextExpiry . IsZero ( ) {
tmrDuration := nextExpiry . Sub ( now ) + 10 * time . Second
2023-07-27 19:41:31 +00:00
b . nmExpiryTimer = b . clock . AfterFunc ( tmrDuration , func ( ) {
2023-01-11 20:59:08 +00:00
// Skip if the world has moved on past the
// saved call (e.g. if we race stopping this
// timer).
if b . numClientStatusCalls . Load ( ) != currCall {
return
}
b . logf ( "setClientStatus: netmap expiry timer triggered after %v" , tmrDuration )
// Call ourselves with the current status again; the logic in
// setClientStatus will take care of updating the expired field
// of peers in the netmap.
2023-09-02 19:04:03 +00:00
b . SetControlClientStatus ( c , st )
2023-01-11 20:59:08 +00:00
} )
}
}
2021-05-06 03:28:29 +00:00
wasBlocked := b . blocked
2021-11-04 19:19:00 +00:00
keyExpiryExtended := false
if st . NetMap != nil {
wasExpired := b . keyExpired
2023-07-27 19:41:31 +00:00
isExpired := ! st . NetMap . Expiry . IsZero ( ) && st . NetMap . Expiry . Before ( b . clock . Now ( ) )
2021-11-04 19:19:00 +00:00
if wasExpired && ! isExpired {
keyExpiryExtended = true
}
b . keyExpired = isExpired
}
2024-04-07 04:16:00 +00:00
unlock . UnlockEarly ( )
2021-05-06 03:28:29 +00:00
2021-11-04 19:19:00 +00:00
if keyExpiryExtended && wasBlocked {
// Key extended, unblock the engine
b . blockEngineUpdates ( false )
}
2024-01-04 17:29:04 +00:00
if st . LoginFinished ( ) && ( wasBlocked || b . seamlessRenewalEnabled ( ) ) {
if wasBlocked {
// Auth completed, unblock the engine
b . blockEngineUpdates ( false )
}
2020-06-15 23:04:12 +00:00
b . authReconfig ( )
2021-02-04 21:12:42 +00:00
b . send ( ipn . Notify { LoginFinished : & empty . Message { } } )
2020-06-15 23:04:12 +00:00
}
2020-07-29 01:47:23 +00:00
2024-04-07 04:16:00 +00:00
// Lock b again and do only the things that require locking.
2020-07-29 01:47:23 +00:00
b . mu . Lock ( )
ipnlocal: don't assume NeedsLogin immediately after StartLogout().
Previously, there was no server round trip required to log out, so when
you asked ipnlocal to Logout(), it could clear the netmap immediately
and switch to NeedsLogin state.
In v1.8, we added a true Logout operation. ipn.Logout() would trigger
an async cc.StartLogout() and *also* immediately switch to NeedsLogin.
Unfortunately, some frontends would see NeedsLogin and immediately
trigger a new StartInteractiveLogin() operation, before the
controlclient auth state machine actually acted on the Logout command,
thus accidentally invalidating the entire logout operation, retaining
the netmap, and violating the user's expectations.
Instead, add a new LogoutFinished signal from controlclient
(paralleling LoginFinished) and, upon starting a logout, don't update
the ipn state machine until it's received.
Updates: #1918 (BUG-2)
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2021-05-20 06:46:57 +00:00
2022-11-12 12:39:29 +00:00
prefsChanged := false
2022-11-09 05:58:10 +00:00
prefs := b . pm . CurrentPrefs ( ) . AsStruct ( )
2020-07-29 01:47:23 +00:00
netMap := b . netMap
ipn{,/ipnlocal}, cmd/tailscale/cli: don't check pref reverts on initial up
The ipn.NewPrefs func returns a populated ipn.Prefs for historical
reasons. It's not used or as important as it once was, but it hasn't
yet been removed. Meanwhile, it contains some default values that are
used on some platforms. Notably, for this bug (#1725), Windows/Mac use
its Prefs.RouteAll true value (to accept subnets), but Linux users
have always gotten a "false" value for that, because that's what
cmd/tailscale's CLI default flag is _for all operating systems_. That
meant that "tailscale up" was rightfully reporting that the user was
changing an implicit setting: RouteAll was changing from true with
false with the user explicitly saying so.
An obvious fix might be to change ipn.NewPrefs to return
Prefs.RouteAll == false on some platforms, but the logic is
complicated by darwin: we want RouteAll true on windows, android, ios,
and the GUI mac app, but not the CLI tailscaled-on-macOS mode. But
even if we used build tags (e.g. the "redo" build tag) to determine
what the default is, that then means we have duplicated and differing
"defaults" between both the CLI up flags and ipn.NewPrefs. Furthering
that complication didn't seem like a good idea.
So, changing the NewPrefs defaults is too invasive at this stage of
the release, as is removing the NewPrefs func entirely.
Instead, tweak slightly the semantics of the ipn.Prefs.ControlURL
field. This now defines that a ControlURL of the empty string means
both "we're uninitialized" and also "just use the default".
Then, once we have the "empty-string-means-unintialized" semantics,
use that to suppress "tailscale up"'s recent implicit-setting-revert
checking safety net, if we've never initialized Tailscale yet.
And update/add tests.
Fixes #1725
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2021-04-18 05:50:58 +00:00
if prefs . ControlURL == "" {
// Once we get a message from the control plane, set
// our ControlURL pref explicitly. This causes a
// future "tailscale up" to start checking for
// implicit setting reverts, which it doesn't do when
// ControlURL is blank.
prefs . ControlURL = prefs . ControlURLOrDefault ( )
prefsChanged = true
}
2023-08-30 18:35:43 +00:00
if st . Persist . Valid ( ) {
if ! prefs . Persist . View ( ) . Equals ( st . Persist ) {
2020-07-29 01:47:23 +00:00
prefsChanged = true
2022-11-10 14:43:59 +00:00
prefs . Persist = st . Persist . AsStruct ( )
2020-07-29 01:47:23 +00:00
}
}
if st . URL != "" {
b . authURL = st . URL
2024-02-08 21:04:01 +00:00
b . authURLTime = b . clock . Now ( )
2020-07-29 01:47:23 +00:00
}
2024-01-04 17:29:04 +00:00
if ( wasBlocked || b . seamlessRenewalEnabled ( ) ) && st . LoginFinished ( ) {
2021-05-06 03:28:29 +00:00
// Interactive login finished successfully (URL visited).
// After an interactive login, the user always wants
// WantRunning.
2022-10-23 17:07:10 +00:00
if ! prefs . WantRunning || prefs . LoggedOut {
2020-07-29 01:47:23 +00:00
prefsChanged = true
}
2022-10-23 17:07:10 +00:00
prefs . WantRunning = true
prefs . LoggedOut = false
2020-07-29 01:47:23 +00:00
}
2023-08-04 05:37:52 +00:00
if setExitNodeID ( prefs , st . NetMap ) {
2022-10-25 18:01:33 +00:00
prefsChanged = true
}
2023-11-01 21:20:25 +00:00
if applySysPolicy ( prefs ) {
prefsChanged = true
}
2022-12-05 04:07:03 +00:00
2023-11-17 02:40:23 +00:00
// Until recently, we did not store the account's tailnet name. So check if this is the case,
// and backfill it on incoming status update.
if b . pm . requiresBackfill ( ) && st . NetMap != nil && st . NetMap . Domain != "" {
prefsChanged = true
}
2022-12-05 04:07:03 +00:00
// Perform all mutations of prefs based on the netmap here.
if prefsChanged {
2023-08-04 05:29:27 +00:00
// Prefs will be written out if stale; this is not safe unless locked or cloned.
2023-11-17 02:40:23 +00:00
if err := b . pm . SetPrefs ( prefs . View ( ) , ipn . NetworkProfile {
MagicDNSName : st . NetMap . MagicDNSSuffix ( ) ,
DomainName : st . NetMap . DomainName ( ) ,
} ) ; err != nil {
2022-12-05 04:07:03 +00:00
b . logf ( "Failed to save new controlclient state: %v" , err )
}
}
// initTKALocked is dependent on CurrentProfile.ID, which is initialized
// (for new profiles) on the first call to b.pm.SetPrefs.
if err := b . initTKALocked ( ) ; err != nil {
b . logf ( "initTKALocked: %v" , err )
}
// Perform all reconfiguration based on the netmap here.
2022-04-17 21:49:16 +00:00
if st . NetMap != nil {
2024-03-22 21:33:41 +00:00
b . capTailnetLock = st . NetMap . HasCap ( tailcfg . CapabilityTailnetLock )
2024-03-18 21:47:21 +00:00
b . setWebClientAtomicBoolLocked ( st . NetMap )
2022-11-30 18:34:59 +00:00
2022-10-25 18:01:33 +00:00
b . mu . Unlock ( ) // respect locking rules for tkaSyncIfNeeded
2022-11-11 06:29:03 +00:00
if err := b . tkaSyncIfNeeded ( st . NetMap , prefs . View ( ) ) ; err != nil {
2022-10-25 18:01:33 +00:00
b . logf ( "[v1] TKA sync error: %v" , err )
}
b . mu . Lock ( )
2023-11-07 20:19:43 +00:00
// As we stepped outside of the lock, it's possible for b.cc
// to now be nil.
if b . cc != nil {
if b . tka != nil {
head , err := b . tka . authority . Head ( ) . MarshalText ( )
if err != nil {
b . logf ( "[v1] error marshalling tka head: %v" , err )
} else {
b . cc . SetTKAHead ( string ( head ) )
}
2022-10-27 20:40:31 +00:00
} else {
2023-11-07 20:19:43 +00:00
b . cc . SetTKAHead ( "" )
2022-10-27 20:40:31 +00:00
}
}
2022-10-25 18:01:33 +00:00
if ! envknob . TKASkipSignatureCheck ( ) {
b . tkaFilterNetmapLocked ( st . NetMap )
}
b . setNetMapLocked ( st . NetMap )
2022-11-09 05:58:10 +00:00
b . updateFilterLocked ( st . NetMap , prefs . View ( ) )
2022-04-17 21:49:16 +00:00
}
2022-11-09 05:58:10 +00:00
b . mu . Unlock ( )
2022-11-09 23:28:36 +00:00
2022-11-09 05:58:10 +00:00
// Now complete the lock-free parts of what we started while locked.
if prefsChanged {
2022-12-02 08:54:32 +00:00
b . send ( ipn . Notify { Prefs : ptr . To ( prefs . View ( ) ) } )
2020-06-15 23:04:12 +00:00
}
2022-11-09 05:58:10 +00:00
2020-06-15 23:04:12 +00:00
if st . NetMap != nil {
2024-03-22 21:33:41 +00:00
if envknob . NoLogsNoSupport ( ) && st . NetMap . HasCap ( tailcfg . CapabilityDataPlaneAuditLogs ) {
2022-11-29 18:51:10 +00:00
msg := "tailnet requires logging to be enabled. Remove --no-logs-no-support from tailscaled command line."
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
b . health . SetLocalLogConfigHealth ( errors . New ( msg ) )
2022-10-18 20:54:07 +00:00
// Connecting to this tailnet without logging is forbidden; boot us outta here.
b . mu . Lock ( )
prefs . WantRunning = false
p := prefs . View ( )
2023-11-17 02:40:23 +00:00
if err := b . pm . SetPrefs ( p , ipn . NetworkProfile {
MagicDNSName : st . NetMap . MagicDNSSuffix ( ) ,
DomainName : st . NetMap . DomainName ( ) ,
} ) ; err != nil {
2022-10-18 20:54:07 +00:00
b . logf ( "Failed to save new controlclient state: %v" , err )
}
b . mu . Unlock ( )
2022-12-02 08:54:32 +00:00
b . send ( ipn . Notify { ErrMessage : & msg , Prefs : & p } )
2022-10-18 20:54:07 +00:00
return
}
2020-07-29 01:47:23 +00:00
if netMap != nil {
diff := st . NetMap . ConciseDiffFrom ( netMap )
2020-06-15 23:04:12 +00:00
if strings . TrimSpace ( diff ) == "" {
2020-12-21 18:58:06 +00:00
b . logf ( "[v1] netmap diff: (none)" )
2020-06-15 23:04:12 +00:00
} else {
2022-02-13 00:22:33 +00:00
b . logf ( "[v1] netmap diff:\n%v" , diff )
2020-06-15 23:04:12 +00:00
}
}
2020-07-29 01:47:23 +00:00
b . e . SetNetworkMap ( st . NetMap )
2023-11-15 23:10:45 +00:00
b . MagicConn ( ) . SetDERPMap ( st . NetMap . DERPMap )
2024-03-22 21:18:04 +00:00
b . MagicConn ( ) . SetOnlyTCP443 ( st . NetMap . HasCap ( tailcfg . NodeAttrOnlyTCP443 ) )
2020-07-29 01:47:23 +00:00
2022-09-05 18:36:30 +00:00
// Update our cached DERP map
2023-04-17 17:58:40 +00:00
dnsfallback . UpdateCache ( st . NetMap . DERPMap , b . logf )
2022-09-05 18:36:30 +00:00
2021-02-04 21:12:42 +00:00
b . send ( ipn . Notify { NetMap : st . NetMap } )
2020-06-15 23:04:12 +00:00
}
if st . URL != "" {
b . logf ( "Received auth URL: %.20v..." , st . URL )
2024-05-10 20:25:08 +00:00
b . popBrowserAuthNow ( )
2020-06-15 23:04:12 +00:00
}
b . stateMachine ( )
2020-07-29 01:47:23 +00:00
// This is currently (2020-07-28) necessary; conditionally disabling it is fragile!
// This is where netmap information gets propagated to router and magicsock.
b . authReconfig ( )
2020-06-15 23:04:12 +00:00
}
2023-12-05 22:16:34 +00:00
type preferencePolicyInfo struct {
key syspolicy . Key
get func ( ipn . PrefsView ) bool
set func ( * ipn . Prefs , bool )
}
var preferencePolicies = [ ] preferencePolicyInfo {
{
key : syspolicy . EnableIncomingConnections ,
// Allow Incoming (used by the UI) is the negation of ShieldsUp (used by the
// backend), so this has to convert between the two conventions.
get : func ( p ipn . PrefsView ) bool { return ! p . ShieldsUp ( ) } ,
set : func ( p * ipn . Prefs , v bool ) { p . ShieldsUp = ! v } ,
} ,
{
key : syspolicy . EnableServerMode ,
get : func ( p ipn . PrefsView ) bool { return p . ForceDaemon ( ) } ,
set : func ( p * ipn . Prefs , v bool ) { p . ForceDaemon = v } ,
} ,
{
key : syspolicy . ExitNodeAllowLANAccess ,
get : func ( p ipn . PrefsView ) bool { return p . ExitNodeAllowLANAccess ( ) } ,
set : func ( p * ipn . Prefs , v bool ) { p . ExitNodeAllowLANAccess = v } ,
} ,
{
key : syspolicy . EnableTailscaleDNS ,
get : func ( p ipn . PrefsView ) bool { return p . CorpDNS ( ) } ,
set : func ( p * ipn . Prefs , v bool ) { p . CorpDNS = v } ,
} ,
{
key : syspolicy . EnableTailscaleSubnets ,
get : func ( p ipn . PrefsView ) bool { return p . RouteAll ( ) } ,
set : func ( p * ipn . Prefs , v bool ) { p . RouteAll = v } ,
} ,
2023-12-07 17:01:31 +00:00
{
key : syspolicy . CheckUpdates ,
get : func ( p ipn . PrefsView ) bool { return p . AutoUpdate ( ) . Check } ,
set : func ( p * ipn . Prefs , v bool ) { p . AutoUpdate . Check = v } ,
} ,
{
key : syspolicy . ApplyUpdates ,
2023-12-18 22:57:03 +00:00
get : func ( p ipn . PrefsView ) bool { v , _ := p . AutoUpdate ( ) . Apply . Get ( ) ; return v } ,
set : func ( p * ipn . Prefs , v bool ) { p . AutoUpdate . Apply . Set ( v ) } ,
2023-12-07 17:01:31 +00:00
} ,
2023-12-07 17:01:31 +00:00
{
key : syspolicy . EnableRunExitNode ,
get : func ( p ipn . PrefsView ) bool { return p . AdvertisesExitNode ( ) } ,
set : func ( p * ipn . Prefs , v bool ) { p . SetAdvertiseExitNode ( v ) } ,
} ,
2023-12-05 22:16:34 +00:00
}
2023-11-01 21:20:25 +00:00
// applySysPolicy overwrites configured preferences with policies that may be
// configured by the system administrator in an OS-specific way.
func applySysPolicy ( prefs * ipn . Prefs ) ( anyChange bool ) {
if controlURL , err := syspolicy . GetString ( syspolicy . ControlURL , prefs . ControlURL ) ; err == nil && prefs . ControlURL != controlURL {
prefs . ControlURL = controlURL
anyChange = true
}
2023-12-05 22:16:34 +00:00
for _ , opt := range preferencePolicies {
if po , err := syspolicy . GetPreferenceOption ( opt . key ) ; err == nil {
curVal := opt . get ( prefs . View ( ) )
newVal := po . ShouldEnable ( curVal )
if curVal != newVal {
opt . set ( prefs , newVal )
anyChange = true
}
2023-11-01 21:20:25 +00:00
}
}
return anyChange
}
2023-09-02 02:28:00 +00:00
var _ controlclient . NetmapDeltaUpdater = ( * LocalBackend ) ( nil )
// UpdateNetmapDelta implements controlclient.NetmapDeltaUpdater.
func ( b * LocalBackend ) UpdateNetmapDelta ( muts [ ] netmap . NodeMutation ) ( handled bool ) {
2023-11-15 23:10:45 +00:00
if ! b . MagicConn ( ) . UpdateNetmapDelta ( muts ) {
2023-09-02 02:28:00 +00:00
return false
}
2023-09-17 07:13:52 +00:00
var notify * ipn . Notify // non-nil if we need to send a Notify
defer func ( ) {
if notify != nil {
b . send ( * notify )
}
} ( )
2023-09-02 02:28:00 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2023-09-17 07:13:52 +00:00
if ! b . updateNetmapDeltaLocked ( muts ) {
2023-09-02 02:28:00 +00:00
return false
}
2023-09-17 07:13:52 +00:00
if b . netMap != nil && mutationsAreWorthyOfTellingIPNBus ( muts ) {
nm := ptr . To ( * b . netMap ) // shallow clone
nm . Peers = make ( [ ] tailcfg . NodeView , 0 , len ( b . peers ) )
for _ , p := range b . peers {
nm . Peers = append ( nm . Peers , p )
}
slices . SortFunc ( nm . Peers , func ( a , b tailcfg . NodeView ) int {
2023-12-18 22:43:01 +00:00
return cmp . Compare ( a . ID ( ) , b . ID ( ) )
2023-09-17 07:13:52 +00:00
} )
notify = & ipn . Notify { NetMap : nm }
} else if testenv . InTest ( ) {
// In tests, send an empty Notify as a wake-up so end-to-end
// integration tests in another repo can check on the status of
// LocalBackend after processing deltas.
notify = new ( ipn . Notify )
}
return true
}
// mutationsAreWorthyOfTellingIPNBus reports whether any mutation type in muts is
// worthy of spamming the IPN bus (the Windows & Mac GUIs, basically) to tell them
// about the update.
func mutationsAreWorthyOfTellingIPNBus ( muts [ ] netmap . NodeMutation ) bool {
2023-09-02 02:28:00 +00:00
for _ , m := range muts {
switch m . ( type ) {
2023-09-17 07:13:52 +00:00
case netmap . NodeMutationLastSeen ,
netmap . NodeMutationOnline :
// The GUI clients might render peers differently depending on whether
// they're online.
return true
2023-09-02 02:28:00 +00:00
}
2023-09-17 07:13:52 +00:00
}
return false
}
2023-09-02 02:28:00 +00:00
2023-09-17 07:13:52 +00:00
func ( b * LocalBackend ) updateNetmapDeltaLocked ( muts [ ] netmap . NodeMutation ) ( handled bool ) {
if b . netMap == nil || len ( b . peers ) == 0 {
return false
}
// Locally cloned mutable nodes, to avoid calling AsStruct (clone)
// multiple times on a node if it's mutated multiple times in this
// call (e.g. its endpoints + online status both change)
var mutableNodes map [ tailcfg . NodeID ] * tailcfg . Node
2023-09-02 02:28:00 +00:00
2023-09-17 07:13:52 +00:00
for _ , m := range muts {
n , ok := mutableNodes [ m . NodeIDBeingMutated ( ) ]
if ! ok {
nv , ok := b . peers [ m . NodeIDBeingMutated ( ) ]
if ! ok {
// TODO(bradfitz): unexpected metric?
return false
}
n = nv . AsStruct ( )
mak . Set ( & mutableNodes , nv . ID ( ) , n )
2023-09-02 02:28:00 +00:00
}
2023-09-17 07:13:52 +00:00
m . Apply ( n )
}
for nid , n := range mutableNodes {
b . peers [ nid ] = n . View ( )
2023-09-02 02:28:00 +00:00
}
return true
}
2023-08-04 05:37:52 +00:00
// setExitNodeID updates prefs to reference an exit node by ID, rather
2022-10-23 17:07:10 +00:00
// than by IP. It returns whether prefs was mutated.
2023-08-04 05:37:52 +00:00
func setExitNodeID ( prefs * ipn . Prefs , nm * netmap . NetworkMap ) ( prefsChanged bool ) {
2023-11-29 21:48:25 +00:00
if exitNodeIDStr , _ := syspolicy . GetString ( syspolicy . ExitNodeID , "" ) ; exitNodeIDStr != "" {
exitNodeID := tailcfg . StableNodeID ( exitNodeIDStr )
changed := prefs . ExitNodeID != exitNodeID || prefs . ExitNodeIP . IsValid ( )
prefs . ExitNodeID = exitNodeID
prefs . ExitNodeIP = netip . Addr { }
return changed
}
oldExitNodeID := prefs . ExitNodeID
if exitNodeIPStr , _ := syspolicy . GetString ( syspolicy . ExitNodeIP , "" ) ; exitNodeIPStr != "" {
exitNodeIP , err := netip . ParseAddr ( exitNodeIPStr )
if exitNodeIP . IsValid ( ) && err == nil {
prefsChanged = prefs . ExitNodeID != "" || prefs . ExitNodeIP != exitNodeIP
prefs . ExitNodeID = ""
prefs . ExitNodeIP = exitNodeIP
}
}
2021-12-01 23:33:14 +00:00
if nm == nil {
// No netmap, can't resolve anything.
return false
}
2021-01-21 01:24:16 +00:00
// If we have a desired IP on file, try to find the corresponding
// node.
2022-10-23 17:07:10 +00:00
if ! prefs . ExitNodeIP . IsValid ( ) {
2021-02-25 04:05:23 +00:00
return false
}
2021-01-21 01:24:16 +00:00
2021-02-25 04:05:23 +00:00
// IP takes precedence over ID, so if both are set, clear ID.
2022-10-23 17:07:10 +00:00
if prefs . ExitNodeID != "" {
prefs . ExitNodeID = ""
2021-02-25 04:05:23 +00:00
prefsChanged = true
2021-01-21 01:24:16 +00:00
}
for _ , peer := range nm . Peers {
2024-02-25 15:57:11 +00:00
for i := range peer . Addresses ( ) . Len ( ) {
2023-08-18 14:57:44 +00:00
addr := peer . Addresses ( ) . At ( i )
2022-10-23 17:07:10 +00:00
if ! addr . IsSingleIP ( ) || addr . Addr ( ) != prefs . ExitNodeIP {
2021-01-21 01:24:16 +00:00
continue
}
2021-02-25 04:05:23 +00:00
// Found the node being referenced, upgrade prefs to
// reference it directly for next time.
2023-08-18 14:57:44 +00:00
prefs . ExitNodeID = peer . StableID ( )
2022-10-23 17:07:10 +00:00
prefs . ExitNodeIP = netip . Addr { }
2023-11-29 21:48:25 +00:00
return oldExitNodeID != prefs . ExitNodeID
2021-01-21 01:24:16 +00:00
}
}
2022-10-23 17:07:10 +00:00
return prefsChanged
2021-01-21 01:24:16 +00:00
}
2020-06-15 23:04:12 +00:00
// setWgengineStatus is the callback by the wireguard engine whenever it posts a new status.
// This updates the endpoints both in the backend and in the control client.
func ( b * LocalBackend ) setWgengineStatus ( s * wgengine . Status , err error ) {
if err != nil {
2021-01-07 04:18:29 +00:00
b . logf ( "wgengine status error: %v" , err )
2021-09-15 19:59:47 +00:00
b . broadcastStatusChanged ( )
2020-06-15 23:04:12 +00:00
return
}
if s == nil {
b . logf ( "[unexpected] non-error wgengine update with status=nil: %v" , s )
2021-09-15 19:59:47 +00:00
b . broadcastStatusChanged ( )
2020-06-15 23:04:12 +00:00
return
}
b . mu . Lock ( )
2022-03-27 03:12:12 +00:00
if s . AsOf . Before ( b . lastStatusTime ) {
// Don't process a status update that is older than the one we have
// already processed. (corp#2579)
b . mu . Unlock ( )
return
}
b . lastStatusTime = s . AsOf
2020-10-29 22:26:10 +00:00
es := b . parseWgStatusLocked ( s )
2021-04-08 04:12:16 +00:00
cc := b . cc
2020-06-15 23:04:12 +00:00
b . engineStatus = es
2021-09-15 19:10:15 +00:00
needUpdateEndpoints := ! endpointsEqual ( s . LocalAddrs , b . endpoints )
if needUpdateEndpoints {
b . endpoints = append ( [ ] tailcfg . Endpoint { } , s . LocalAddrs ... )
}
2020-06-15 23:04:12 +00:00
b . mu . Unlock ( )
2021-04-08 04:12:16 +00:00
if cc != nil {
2021-09-15 19:10:15 +00:00
if needUpdateEndpoints {
2022-06-19 23:31:54 +00:00
cc . UpdateEndpoints ( s . LocalAddrs )
2021-09-15 19:10:15 +00:00
}
2021-07-19 18:07:42 +00:00
b . stateMachine ( )
2020-06-15 23:04:12 +00:00
}
2021-09-15 19:59:47 +00:00
b . broadcastStatusChanged ( )
b . send ( ipn . Notify { Engine : & es } )
}
2021-09-16 19:56:43 +00:00
2021-09-15 19:59:47 +00:00
func ( b * LocalBackend ) broadcastStatusChanged ( ) {
// The sync.Cond docs say: "It is allowed but not required for the caller to hold c.L during the call."
// In this particular case, we must acquire b.statusLock. Otherwise we might broadcast before
// the waiter (in requestEngineStatusAndWait) starts to wait, in which case
// the waiter can get stuck indefinitely. See PR 2865.
2021-09-16 19:56:43 +00:00
b . statusLock . Lock ( )
2020-06-15 23:04:12 +00:00
b . statusChanged . Broadcast ( )
2021-09-16 19:56:43 +00:00
b . statusLock . Unlock ( )
2020-06-15 23:04:12 +00:00
}
2021-09-15 19:10:15 +00:00
func endpointsEqual ( x , y [ ] tailcfg . Endpoint ) bool {
if len ( x ) != len ( y ) {
return false
}
for i := range x {
if x [ i ] != y [ i ] {
return false
}
}
return true
}
2024-05-08 00:31:10 +00:00
// SetNotifyCallback sets the function to call when the backend has something to
// notify the frontend about. Only one callback can be set at a time, so calling
// this function will replace the previous callback.
2021-04-07 05:11:50 +00:00
func ( b * LocalBackend ) SetNotifyCallback ( notify func ( ipn . Notify ) ) {
2024-05-08 00:31:10 +00:00
ctx , cancel := context . WithCancel ( b . ctx )
2021-04-07 05:11:50 +00:00
b . mu . Lock ( )
2024-05-08 00:31:10 +00:00
prevCancel := b . notifyCancel
b . notifyCancel = cancel
b . mu . Unlock ( )
if prevCancel != nil {
prevCancel ( )
}
var wg sync . WaitGroup
wg . Add ( 1 )
go b . WatchNotifications ( ctx , 0 , wg . Done , func ( n * ipn . Notify ) bool {
notify ( * n )
return true
} )
wg . Wait ( )
2021-04-07 05:11:50 +00:00
}
2021-04-07 15:39:08 +00:00
// SetHTTPTestClient sets an alternate HTTP client to use with
// connections to the coordination server. It exists for
// testing. Using nil means to use the default.
func ( b * LocalBackend ) SetHTTPTestClient ( c * http . Client ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
b . httpTestClient = c
}
2021-04-30 14:23:22 +00:00
// SetControlClientGetterForTesting sets the func that creates a
// control plane client. It can be called at most once, before Start.
func ( b * LocalBackend ) SetControlClientGetterForTesting ( newControlClient func ( controlclient . Options ) ( controlclient . Client , error ) ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
if b . ccGen != nil {
panic ( "invalid use of SetControlClientGetterForTesting after Start" )
}
b . ccGen = newControlClient
}
2023-09-17 09:17:59 +00:00
// NodeViewByIDForTest returns the state of the node with the given ID
// for integration tests in another repo.
func ( b * LocalBackend ) NodeViewByIDForTest ( id tailcfg . NodeID ) ( _ tailcfg . NodeView , ok bool ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
n , ok := b . peers [ id ]
return n , ok
}
2024-05-07 23:42:45 +00:00
// DisablePortMapperForTest disables the portmapper for tests.
// It must be called before Start.
func ( b * LocalBackend ) DisablePortMapperForTest ( ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
b . portpoll = nil
}
2023-09-17 09:17:59 +00:00
// PeersForTest returns all the current peers, sorted by Node.ID,
// for integration tests in another repo.
func ( b * LocalBackend ) PeersForTest ( ) [ ] tailcfg . NodeView {
b . mu . Lock ( )
defer b . mu . Unlock ( )
ret := xmaps . Values ( b . peers )
slices . SortFunc ( ret , func ( a , b tailcfg . NodeView ) int {
2023-12-18 22:43:01 +00:00
return cmp . Compare ( a . ID ( ) , b . ID ( ) )
2023-09-17 09:17:59 +00:00
} )
return ret
}
2024-05-07 23:42:45 +00:00
func ( b * LocalBackend ) getNewControlClientFuncLocked ( ) clientGen {
2021-04-30 14:23:22 +00:00
if b . ccGen == nil {
// Initialize it rather than just returning the
// default to make any future call to
// SetControlClientGetterForTesting panic.
b . ccGen = func ( opts controlclient . Options ) ( controlclient . Client , error ) {
return controlclient . New ( opts )
}
}
return b . ccGen
}
2020-05-19 02:32:20 +00:00
// Start applies the configuration specified in opts, and starts the
// state machine.
//
// TODO(danderson): this function is trying to do too many things at
// once: it loads state, or imports it, or updates prefs sometimes,
// contains some settings that are one-shot things done by `tailscale
// up` because we had nowhere else to put them, and there's no clear
// guarantee that switching from one user's state to another is
// actually a supported operation (it should be, but it's very unclear
// from the following whether or not that is a safe transition).
2021-02-04 21:12:42 +00:00
func ( b * LocalBackend ) Start ( opts ipn . Options ) error {
2024-04-16 04:40:21 +00:00
b . logf ( "Start" )
2020-02-05 22:16:58 +00:00
2024-05-07 23:42:45 +00:00
var clientToShutdown controlclient . Client
defer func ( ) {
if clientToShutdown != nil {
clientToShutdown . Shutdown ( )
}
} ( )
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2023-09-01 00:55:47 +00:00
2022-11-21 23:11:44 +00:00
if opts . UpdatePrefs != nil {
if err := b . checkPrefsLocked ( opts . UpdatePrefs ) ; err != nil {
return err
}
}
2023-10-16 19:15:03 +00:00
if b . state != ipn . Running && b . conf != nil && b . conf . Parsed . AuthKey != nil && opts . AuthKey == "" {
v := * b . conf . Parsed . AuthKey
if filename , ok := strings . CutPrefix ( v , "file:" ) ; ok {
b , err := os . ReadFile ( filename )
if err != nil {
return fmt . Errorf ( "error reading config file authKey: %w" , err )
}
v = strings . TrimSpace ( string ( b ) )
}
opts . AuthKey = v
}
2021-04-23 17:26:25 +00:00
2021-08-20 17:34:13 +00:00
hostinfo := hostinfo . New ( )
2023-10-16 19:15:03 +00:00
applyConfigToHostinfo ( hostinfo , b . conf )
2023-03-23 17:49:56 +00:00
hostinfo . BackendLogID = b . backendLogID . String ( )
2020-06-15 23:04:12 +00:00
hostinfo . FrontendLogID = opts . FrontendLogID
2023-05-03 20:57:17 +00:00
hostinfo . Userspace . Set ( b . sys . IsNetstack ( ) )
hostinfo . UserspaceRouter . Set ( b . sys . IsNetstackRouter ( ) )
2023-11-10 02:00:56 +00:00
hostinfo . AppConnector . Set ( b . appConnector != nil )
2023-10-16 19:15:03 +00:00
b . logf . JSON ( 1 , "Hostinfo" , hostinfo )
2020-02-05 22:16:58 +00:00
2023-09-02 19:04:03 +00:00
// TODO(apenwarr): avoid the need to reinit controlclient.
// This will trigger a full relogin/reconfigure cycle every
// time a Handle reconnects to the backend. Ideally, we
// would send the new Prefs and everything would get back
// into sync with the minimal changes. But that's not how it
// is right now, which is a sign that the code is still too
// complicated.
2024-05-07 23:42:45 +00:00
clientToShutdown = b . resetControlClientLocked ( )
2021-04-07 15:39:08 +00:00
httpTestClient := b . httpTestClient
2020-02-25 20:30:28 +00:00
2020-06-15 23:04:12 +00:00
if b . hostinfo != nil {
2022-05-03 22:07:30 +00:00
hostinfo . Services = b . hostinfo . Services // keep any previous services
2020-02-25 18:04:20 +00:00
}
2020-06-15 23:04:12 +00:00
b . hostinfo = hostinfo
2021-02-04 21:12:42 +00:00
b . state = ipn . NoState
2020-02-03 18:35:52 +00:00
ipnlocal: accept a new opts.UpdatePrefs field.
This is needed because the original opts.Prefs field was at some point
subverted for use in frontend->backend state migration for backward
compatibility on some platforms. We still need that feature, but we
also need the feature of providing the full set of prefs from
`tailscale up`, *not* including overwriting the prefs.Persist keys, so
we can't use the original field from `tailscale up`.
`tailscale up` had attempted to compensate for that by doing SetPrefs()
before Start(), but that violates the ipn.Backend contract, which says
you should call Start() before anything else (that's why it's called
Start()). As a result, doing SetPrefs({ControlURL=...,
WantRunning=true}) would cause a connection to the *previous* control
server (because WantRunning=true), and then connect to the *new*
control server only after running Start().
This problem may have been avoided before, but only by pure luck.
It turned out to be relatively harmless since the connection to the old
control server was immediately closed and replaced anyway, but it
created a race condition that could have caused spurious notifications
or rejected keys if the server responded quickly.
As already covered by existing TODOs, a better fix would be to have
Start() get out of the business of state migration altogether. But
we're approaching a release so I want to make the minimum possible fix.
Fixes #1840.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2021-05-04 08:26:07 +00:00
if opts . UpdatePrefs != nil {
2022-11-09 05:58:10 +00:00
oldPrefs := b . pm . CurrentPrefs ( )
newPrefs := opts . UpdatePrefs . Clone ( )
2022-11-29 20:00:40 +00:00
newPrefs . Persist = oldPrefs . Persist ( ) . AsStruct ( )
2022-11-09 05:58:10 +00:00
pv := newPrefs . View ( )
2023-11-17 02:40:23 +00:00
if err := b . pm . SetPrefs ( pv , ipn . NetworkProfile {
MagicDNSName : b . netMap . MagicDNSSuffix ( ) ,
DomainName : b . netMap . DomainName ( ) ,
} ) ; err != nil {
2022-11-09 05:58:10 +00:00
b . logf ( "failed to save UpdatePrefs state: %v" , err )
2021-07-13 21:03:05 +00:00
}
2022-11-16 20:51:26 +00:00
b . setAtomicValuesFromPrefsLocked ( pv )
2024-04-16 04:40:21 +00:00
} else {
b . setAtomicValuesFromPrefsLocked ( b . pm . CurrentPrefs ( ) )
ipnlocal: accept a new opts.UpdatePrefs field.
This is needed because the original opts.Prefs field was at some point
subverted for use in frontend->backend state migration for backward
compatibility on some platforms. We still need that feature, but we
also need the feature of providing the full set of prefs from
`tailscale up`, *not* including overwriting the prefs.Persist keys, so
we can't use the original field from `tailscale up`.
`tailscale up` had attempted to compensate for that by doing SetPrefs()
before Start(), but that violates the ipn.Backend contract, which says
you should call Start() before anything else (that's why it's called
Start()). As a result, doing SetPrefs({ControlURL=...,
WantRunning=true}) would cause a connection to the *previous* control
server (because WantRunning=true), and then connect to the *new*
control server only after running Start().
This problem may have been avoided before, but only by pure luck.
It turned out to be relatively harmless since the connection to the old
control server was immediately closed and replaced anyway, but it
created a race condition that could have caused spurious notifications
or rejected keys if the server responded quickly.
As already covered by existing TODOs, a better fix would be to have
Start() get out of the business of state migration altogether. But
we're approaching a release so I want to make the minimum possible fix.
Fixes #1840.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2021-05-04 08:26:07 +00:00
}
2022-11-09 05:58:10 +00:00
prefs := b . pm . CurrentPrefs ( )
wantRunning := prefs . WantRunning ( )
2021-04-02 15:21:40 +00:00
if wantRunning {
if err := b . initMachineKeyLocked ( ) ; err != nil {
return fmt . Errorf ( "initMachineKeyLocked: %w" , err )
}
}
2022-11-09 05:58:10 +00:00
loggedOut := prefs . LoggedOut ( )
2021-04-30 07:56:11 +00:00
2022-11-22 11:27:05 +00:00
serverURL := prefs . ControlURLOrDefault ( )
2022-11-25 14:50:15 +00:00
if inServerMode := prefs . ForceDaemon ( ) ; inServerMode || runtime . GOOS == "windows" {
b . logf ( "Start: serverMode=%v" , inServerMode )
2020-11-04 18:24:33 +00:00
}
2022-11-16 05:22:09 +00:00
b . applyPrefsToHostinfoLocked ( hostinfo , prefs )
2020-02-18 03:33:01 +00:00
2020-10-27 19:51:48 +00:00
b . setNetMapLocked ( nil )
2022-11-29 20:00:40 +00:00
persistv := prefs . Persist ( ) . AsStruct ( )
2022-11-09 05:58:10 +00:00
if persistv == nil {
persistv = new ( persist . Persist )
}
2022-10-23 17:07:10 +00:00
b . updateFilterLocked ( nil , ipn . PrefsView { } )
2020-02-05 22:16:58 +00:00
2020-10-14 21:07:40 +00:00
if b . portpoll != nil {
b . portpollOnce . Do ( func ( ) {
go b . readPoller ( )
// Give the poller a second to get results to
// prevent it from restarting our map poll
// HTTP request (via doSetHostinfoFilterServices >
// cli.SetHostinfo). In practice this is very quick.
2023-07-27 19:41:31 +00:00
t0 := b . clock . Now ( )
timer , timerChannel := b . clock . NewTimer ( time . Second )
2020-10-14 21:07:40 +00:00
select {
case <- b . gotPortPollRes :
2023-07-27 19:41:31 +00:00
b . logf ( "[v1] got initial portlist info in %v" , b . clock . Since ( t0 ) . Round ( time . Millisecond ) )
2020-10-14 21:07:40 +00:00
timer . Stop ( )
2023-07-27 19:41:31 +00:00
case <- timerChannel :
2020-10-14 21:07:40 +00:00
b . logf ( "timeout waiting for initial portlist" )
}
} )
}
2023-11-15 23:10:45 +00:00
discoPublic := b . MagicConn ( ) . DiscoPublicKey ( )
2020-06-19 19:06:49 +00:00
2020-02-05 22:16:58 +00:00
var err error
2021-04-14 16:37:54 +00:00
2023-05-03 20:57:17 +00:00
isNetstack := b . sys . IsNetstackRouter ( )
2021-04-14 16:37:54 +00:00
debugFlags := controlDebugFlags
if isNetstack {
debugFlags = append ( [ ] string { "netstack" } , debugFlags ... )
}
ipnlocal: accept a new opts.UpdatePrefs field.
This is needed because the original opts.Prefs field was at some point
subverted for use in frontend->backend state migration for backward
compatibility on some platforms. We still need that feature, but we
also need the feature of providing the full set of prefs from
`tailscale up`, *not* including overwriting the prefs.Persist keys, so
we can't use the original field from `tailscale up`.
`tailscale up` had attempted to compensate for that by doing SetPrefs()
before Start(), but that violates the ipn.Backend contract, which says
you should call Start() before anything else (that's why it's called
Start()). As a result, doing SetPrefs({ControlURL=...,
WantRunning=true}) would cause a connection to the *previous* control
server (because WantRunning=true), and then connect to the *new*
control server only after running Start().
This problem may have been avoided before, but only by pure luck.
It turned out to be relatively harmless since the connection to the old
control server was immediately closed and replaced anyway, but it
created a race condition that could have caused spurious notifications
or rejected keys if the server responded quickly.
As already covered by existing TODOs, a better fix would be to have
Start() get out of the business of state migration altogether. But
we're approaching a release so I want to make the minimum possible fix.
Fixes #1840.
Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
2021-05-04 08:26:07 +00:00
// TODO(apenwarr): The only way to change the ServerURL is to
2024-04-16 04:40:21 +00:00
// re-run b.Start, because this is the only place we create a
// new controlclient. EditPrefs allows you to overwrite ServerURL,
// but it won't take effect until the next Start.
2024-05-07 23:42:45 +00:00
cc , err := b . getNewControlClientFuncLocked ( ) ( controlclient . Options {
2023-12-18 22:57:03 +00:00
GetMachinePrivateKey : b . createGetMachinePrivateKeyFunc ( ) ,
Logf : logger . WithPrefix ( b . logf , "control: " ) ,
Persist : * persistv ,
ServerURL : serverURL ,
AuthKey : opts . AuthKey ,
Hostinfo : hostinfo ,
HTTPTestClient : httpTestClient ,
DiscoPublicKey : discoPublic ,
DebugFlags : debugFlags ,
2024-04-26 16:49:30 +00:00
HealthTracker : b . health ,
2023-12-18 22:57:03 +00:00
Pinger : b ,
PopBrowserURL : b . tellClientToBrowseToURL ,
OnClientVersion : b . onClientVersion ,
OnTailnetDefaultAutoUpdate : b . onTailnetDefaultAutoUpdate ,
OnControlTime : b . em . onControlTime ,
Dialer : b . Dialer ( ) ,
Observer : b ,
C2NHandler : http . HandlerFunc ( b . handleC2N ) ,
DialPlan : & b . dialPlan , // pointer because it can't be copied
ControlKnobs : b . sys . ControlKnobs ( ) ,
2021-03-31 18:55:21 +00:00
2021-09-15 23:26:38 +00:00
// Don't warn about broken Linux IP forwarding when
2021-03-31 18:55:21 +00:00
// netstack is being used.
2021-04-14 16:37:54 +00:00
SkipIPForwardingCheck : isNetstack ,
2020-02-05 22:16:58 +00:00
} )
if err != nil {
return err
}
2024-04-13 23:20:42 +00:00
b . setControlClientLocked ( cc )
2020-02-28 20:12:49 +00:00
endpoints := b . endpoints
2022-11-22 18:48:07 +00:00
if err := b . initTKALocked ( ) ; err != nil {
b . logf ( "initTKALocked: %v" , err )
}
2022-10-27 20:40:31 +00:00
var tkaHead string
if b . tka != nil {
head , err := b . tka . authority . Head ( ) . MarshalText ( )
if err != nil {
return fmt . Errorf ( "marshalling tka head: %w" , err )
}
tkaHead = string ( head )
}
2023-10-16 19:15:03 +00:00
confWantRunning := b . conf != nil && wantRunning
2020-02-05 22:16:58 +00:00
2020-02-28 20:12:49 +00:00
if endpoints != nil {
2022-06-19 23:31:54 +00:00
cc . UpdateEndpoints ( endpoints )
2020-02-05 22:16:58 +00:00
}
2022-10-27 20:40:31 +00:00
cc . SetTKAHead ( tkaHead )
2020-02-05 22:16:58 +00:00
2023-03-23 17:49:56 +00:00
blid := b . backendLogID . String ( )
2020-04-11 15:35:34 +00:00
b . logf ( "Backend: logs: be:%v fe:%v" , blid , opts . FrontendLogID )
2024-05-08 00:31:10 +00:00
b . sendLocked ( ipn . Notify {
BackendLogID : & blid ,
Prefs : & prefs ,
} )
2020-02-05 22:16:58 +00:00
2024-05-08 00:31:10 +00:00
if ! loggedOut && ( b . hasNodeKeyLocked ( ) || confWantRunning ) {
// If we know that we're either logged in or meant to be
// running, tell the controlclient that it should also assume
// that we need to be logged in.
//
// Without this, the state machine transitions to "NeedsLogin" implying
// that user interaction is required, which is not the case and can
// regress tsnet.Server restarts.
2024-05-17 21:54:41 +00:00
cc . Login ( controlclient . LoginDefault )
2021-04-02 15:21:40 +00:00
}
2024-05-08 00:31:10 +00:00
b . stateMachineLockedOnEntry ( unlock )
2020-02-05 22:16:58 +00:00
return nil
}
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
// invalidPacketFilterWarnable is a Warnable to warn the user that the control server sent an invalid packet filter.
var invalidPacketFilterWarnable = health . Register ( & health . Warnable {
Code : "invalid-packet-filter" ,
Title : "Invalid packet filter" ,
Severity : health . SeverityHigh ,
Text : health . StaticMessage ( "The coordination server sent an invalid packet filter permitting traffic to unlocked nodes; rejecting all packets for safety" ) ,
} )
2022-11-13 15:32:37 +00:00
2022-04-17 21:49:16 +00:00
// updateFilterLocked updates the packet filter in wgengine based on the
2020-05-19 02:32:20 +00:00
// given netMap and user preferences.
2022-04-17 21:49:16 +00:00
//
// b.mu must be held.
2022-10-23 17:07:10 +00:00
func ( b * LocalBackend ) updateFilterLocked ( netMap * netmap . NetworkMap , prefs ipn . PrefsView ) {
2020-07-31 20:03:00 +00:00
// NOTE(danderson): keep change detection as the first thing in
// this function. Don't try to optimize by returning early, more
// likely than not you'll just end up breaking the change
// detection and end up with the wrong filter installed. This is
// quite hard to debug, so save yourself the trouble.
var (
haveNetmap = netMap != nil
2023-09-17 17:53:23 +00:00
addrs views . Slice [ netip . Prefix ]
2020-11-10 05:33:41 +00:00
packetFilter [ ] filter . Match
2022-07-25 03:08:42 +00:00
localNetsB netipx . IPSetBuilder
logNetsB netipx . IPSetBuilder
2022-10-23 17:07:10 +00:00
shieldsUp = ! prefs . Valid ( ) || prefs . ShieldsUp ( ) // Be conservative when not ready
2020-07-31 20:03:00 +00:00
)
2021-03-10 00:10:30 +00:00
// Log traffic for Tailscale IPs.
logNetsB . AddPrefix ( tsaddr . CGNATRange ( ) )
logNetsB . AddPrefix ( tsaddr . TailscaleULARange ( ) )
logNetsB . RemovePrefix ( tsaddr . ChromeOSVMRange ( ) )
2020-07-31 20:03:00 +00:00
if haveNetmap {
2023-09-17 17:53:23 +00:00
addrs = netMap . GetAddresses ( )
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-09-17 17:53:23 +00:00
localNetsB . AddPrefix ( addrs . At ( i ) )
2021-02-22 22:34:15 +00:00
}
2020-07-31 20:03:00 +00:00
packetFilter = netMap . PacketFilter
2022-11-02 20:13:26 +00:00
2023-09-17 07:13:52 +00:00
if packetFilterPermitsUnlockedNodes ( b . peers , packetFilter ) {
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
b . health . SetUnhealthy ( invalidPacketFilterWarnable , nil )
2022-11-02 20:13:26 +00:00
packetFilter = nil
} else {
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
b . health . SetHealthy ( invalidPacketFilterWarnable )
2022-11-02 20:13:26 +00:00
}
2020-05-22 02:41:18 +00:00
}
2022-10-23 17:07:10 +00:00
if prefs . Valid ( ) {
ar := prefs . AdvertiseRoutes ( )
2024-04-16 20:15:13 +00:00
for i := range ar . Len ( ) {
2022-10-23 17:07:10 +00:00
r := ar . At ( i )
2021-05-15 01:07:28 +00:00
if r . Bits ( ) == 0 {
2021-02-23 04:43:35 +00:00
// When offering a default route to the world, we
// filter out locally reachable LANs, so that the
// default route effectively appears to be a "guest
// wifi": you get internet access, but to additionally
// get LAN access the LAN(s) need to be offered
// explicitly as well.
2021-12-16 19:15:45 +00:00
localInterfaceRoutes , hostIPs , err := interfaceRoutes ( )
if err != nil {
b . logf ( "getting local interface routes: %v" , err )
continue
}
s , err := shrinkDefaultRoute ( r , localInterfaceRoutes , hostIPs )
2021-02-23 04:43:35 +00:00
if err != nil {
b . logf ( "computing default route filter: %v" , err )
continue
}
localNetsB . AddSet ( s )
} else {
localNetsB . AddPrefix ( r )
2021-03-10 00:10:30 +00:00
// When advertising a non-default route, we assume
// this is a corporate subnet that should be present
// in the audit logs.
logNetsB . AddPrefix ( r )
2021-02-23 04:43:35 +00:00
}
2021-02-22 22:34:15 +00:00
}
2023-11-07 23:45:46 +00:00
// App connectors handle DNS requests for app domains over PeerAPI (corp#11961),
// but a safety check verifies the requesting peer has at least permission
// to send traffic to 0.0.0.0:53 (or 2000:: for IPv6) before handling the DNS
// request (see peerAPIHandler.replyToDNSQueries in peerapi.go).
// The correct filter rules are synthesized by the coordination server
// and sent down, but the address needs to be part of the 'local net' for the
// filter package to even bother checking the filter rules, so we set them here.
if prefs . AppConnector ( ) . Advertise {
localNetsB . Add ( netip . MustParseAddr ( "0.0.0.0" ) )
localNetsB . Add ( netip . MustParseAddr ( "::0" ) )
}
2020-07-29 01:47:23 +00:00
}
2021-06-02 16:04:37 +00:00
localNets , _ := localNetsB . IPSet ( )
logNets , _ := logNetsB . IPSet ( )
2022-04-18 23:17:10 +00:00
var sshPol tailcfg . SSHPolicy
if haveNetmap && netMap . SSHPolicy != nil {
sshPol = * netMap . SSHPolicy
}
2020-07-29 01:47:23 +00:00
2022-08-15 18:22:28 +00:00
changed := deephash . Update ( & b . filterHash , & struct {
HaveNetmap bool
2023-09-17 17:53:23 +00:00
Addrs views . Slice [ netip . Prefix ]
2022-08-15 18:22:28 +00:00
FilterMatch [ ] filter . Match
LocalNets [ ] netipx . IPRange
LogNets [ ] netipx . IPRange
ShieldsUp bool
SSHPolicy tailcfg . SSHPolicy
} { haveNetmap , addrs , packetFilter , localNets . Ranges ( ) , logNets . Ranges ( ) , shieldsUp , sshPol } )
2020-07-29 01:47:23 +00:00
if ! changed {
return
}
2020-05-22 02:41:18 +00:00
2020-08-01 02:07:14 +00:00
if ! haveNetmap {
2022-02-12 16:05:24 +00:00
b . logf ( "[v1] netmap packet filter: (not ready yet)" )
2024-05-06 18:09:10 +00:00
noneFilter := filter . NewAllowNone ( b . logf , logNets )
b . setFilter ( noneFilter )
b . e . SetJailedFilter ( noneFilter )
2020-08-01 02:07:14 +00:00
return
}
2021-01-22 21:39:53 +00:00
oldFilter := b . e . GetFilter ( )
2020-08-01 02:07:14 +00:00
if shieldsUp {
2022-02-12 16:05:24 +00:00
b . logf ( "[v1] netmap packet filter: (shields up)" )
2021-11-25 17:43:39 +00:00
b . setFilter ( filter . NewShieldsUpFilter ( localNets , logNets , oldFilter , b . logf ) )
2020-08-01 02:07:14 +00:00
} else {
2022-02-12 16:05:24 +00:00
b . logf ( "[v1] netmap packet filter: %v filters" , len ( packetFilter ) )
2021-11-25 17:43:39 +00:00
b . setFilter ( filter . New ( packetFilter , localNets , logNets , oldFilter , b . logf ) )
2020-05-22 02:41:18 +00:00
}
2024-05-06 18:09:10 +00:00
// The filter for a jailed node is the exact same as a ShieldsUp filter.
oldJailedFilter := b . e . GetJailedFilter ( )
b . e . SetJailedFilter ( filter . NewShieldsUpFilter ( localNets , logNets , oldJailedFilter , b . logf ) )
2022-04-17 18:49:56 +00:00
if b . sshServer != nil {
go b . sshServer . OnPolicyChange ( )
}
2020-07-29 01:47:23 +00:00
}
2022-11-02 20:13:26 +00:00
// packetFilterPermitsUnlockedNodes reports any peer in peers with the
// UnsignedPeerAPIOnly bool set true has any of its allowed IPs in the packet
// filter.
//
// If this reports true, the packet filter is invalid (the server is either broken
// or malicious) and should be ignored for safety.
2023-09-17 07:13:52 +00:00
func packetFilterPermitsUnlockedNodes ( peers map [ tailcfg . NodeID ] tailcfg . NodeView , packetFilter [ ] filter . Match ) bool {
2022-11-02 20:13:26 +00:00
var b netipx . IPSetBuilder
var numUnlocked int
for _ , p := range peers {
2023-08-18 14:57:44 +00:00
if ! p . UnsignedPeerAPIOnly ( ) {
2022-11-02 20:13:26 +00:00
continue
}
numUnlocked ++
2024-02-25 15:57:11 +00:00
for i := range p . AllowedIPs ( ) . Len ( ) { // not only addresses!
2023-08-18 14:57:44 +00:00
b . AddPrefix ( p . AllowedIPs ( ) . At ( i ) )
2022-11-02 20:13:26 +00:00
}
}
if numUnlocked == 0 {
return false
}
s , err := b . IPSet ( )
if err != nil {
// Shouldn't happen, but if it does, fail closed.
return true
}
for _ , m := range packetFilter {
for _ , r := range m . Srcs {
if ! s . OverlapsPrefix ( r ) {
continue
}
if len ( m . Dsts ) != 0 {
return true
}
}
}
return false
}
2021-11-25 17:43:39 +00:00
func ( b * LocalBackend ) setFilter ( f * filter . Filter ) {
b . filterAtomic . Store ( f )
b . e . SetFilter ( f )
}
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
var removeFromDefaultRoute = [ ] netip . Prefix {
2021-02-23 04:43:35 +00:00
// RFC1918 LAN ranges
2022-07-26 03:55:44 +00:00
netip . MustParsePrefix ( "192.168.0.0/16" ) ,
netip . MustParsePrefix ( "172.16.0.0/12" ) ,
netip . MustParsePrefix ( "10.0.0.0/8" ) ,
2021-03-18 00:04:32 +00:00
// IPv4 link-local
2022-07-26 03:55:44 +00:00
netip . MustParsePrefix ( "169.254.0.0/16" ) ,
2021-03-18 00:04:32 +00:00
// IPv4 multicast
2022-07-26 03:55:44 +00:00
netip . MustParsePrefix ( "224.0.0.0/4" ) ,
2021-02-23 04:43:35 +00:00
// Tailscale IPv4 range
tsaddr . CGNATRange ( ) ,
// IPv6 Link-local addresses
2022-07-26 03:55:44 +00:00
netip . MustParsePrefix ( "fe80::/10" ) ,
2021-03-18 00:04:32 +00:00
// IPv6 multicast
2022-07-26 03:55:44 +00:00
netip . MustParsePrefix ( "ff00::/8" ) ,
2021-02-23 04:43:35 +00:00
// Tailscale IPv6 range
tsaddr . TailscaleULARange ( ) ,
}
2021-07-02 14:15:28 +00:00
// internalAndExternalInterfaces splits interface routes into "internal"
// and "external" sets. Internal routes are those of virtual ethernet
// network interfaces used by guest VMs and containers, such as WSL and
// Docker.
//
// Given that "internal" routes don't leave the device, we choose to
// trust them more, allowing access to them when an Exit Node is enabled.
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
func internalAndExternalInterfaces ( ) ( internal , external [ ] netip . Prefix , err error ) {
2024-04-28 04:18:18 +00:00
il , err := netmon . GetInterfaceList ( )
2021-10-14 20:40:06 +00:00
if err != nil {
return nil , nil , err
}
return internalAndExternalInterfacesFrom ( il , runtime . GOOS )
}
2024-04-28 04:18:18 +00:00
func internalAndExternalInterfacesFrom ( il netmon . InterfaceList , goos string ) ( internal , external [ ] netip . Prefix , err error ) {
2021-10-14 20:40:06 +00:00
// We use an IPSetBuilder here to canonicalize the prefixes
// and to remove any duplicate entries.
2022-07-25 03:08:42 +00:00
var internalBuilder , externalBuilder netipx . IPSetBuilder
2024-04-28 04:18:18 +00:00
if err := il . ForeachInterfaceAddress ( func ( iface netmon . Interface , pfx netip . Prefix ) {
2022-07-25 03:08:42 +00:00
if tsaddr . IsTailscaleIP ( pfx . Addr ( ) ) {
2021-07-02 14:15:28 +00:00
return
}
if pfx . IsSingleIP ( ) {
return
}
2021-10-14 20:09:06 +00:00
if iface . IsLoopback ( ) {
2021-10-14 20:40:06 +00:00
internalBuilder . AddPrefix ( pfx )
2021-10-14 20:09:06 +00:00
return
}
2021-10-14 20:40:06 +00:00
if goos == "windows" {
2021-07-02 14:15:28 +00:00
// Windows Hyper-V prefixes all MAC addresses with 00:15:5d.
// https://docs.microsoft.com/en-us/troubleshoot/windows-server/virtualization/default-limit-256-dynamic-mac-addresses
//
// This includes WSL2 vEthernet.
// Importantly: by default WSL2 /etc/resolv.conf points to
// a stub resolver running on the host vEthernet IP.
// So enabling exit nodes with the default tailnet
// configuration breaks WSL2 DNS without this.
mac := iface . Interface . HardwareAddr
if len ( mac ) == 6 && mac [ 0 ] == 0x00 && mac [ 1 ] == 0x15 && mac [ 2 ] == 0x5d {
2021-10-14 20:40:06 +00:00
internalBuilder . AddPrefix ( pfx )
2021-07-02 14:15:28 +00:00
return
}
}
2021-10-14 20:40:06 +00:00
externalBuilder . AddPrefix ( pfx )
2021-07-02 14:15:28 +00:00
} ) ; err != nil {
return nil , nil , err
}
2021-10-14 20:40:06 +00:00
iSet , err := internalBuilder . IPSet ( )
if err != nil {
return nil , nil , err
}
eSet , err := externalBuilder . IPSet ( )
if err != nil {
return nil , nil , err
}
2021-07-02 14:15:28 +00:00
2021-10-14 20:40:06 +00:00
return iSet . Prefixes ( ) , eSet . Prefixes ( ) , nil
2021-07-02 14:15:28 +00:00
}
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
func interfaceRoutes ( ) ( ips * netipx . IPSet , hostIPs [ ] netip . Addr , err error ) {
2022-07-25 03:08:42 +00:00
var b netipx . IPSetBuilder
2024-04-28 04:18:18 +00:00
if err := netmon . ForeachInterfaceAddress ( func ( _ netmon . Interface , pfx netip . Prefix ) {
2022-07-25 03:08:42 +00:00
if tsaddr . IsTailscaleIP ( pfx . Addr ( ) ) {
2021-02-23 04:43:35 +00:00
return
}
if pfx . IsSingleIP ( ) {
return
}
2022-07-25 03:08:42 +00:00
hostIPs = append ( hostIPs , pfx . Addr ( ) )
2021-04-08 22:56:51 +00:00
b . AddPrefix ( pfx )
} ) ; err != nil {
return nil , nil , err
}
2021-06-02 16:04:37 +00:00
ipSet , _ := b . IPSet ( )
return ipSet , hostIPs , nil
2021-04-08 22:56:51 +00:00
}
// shrinkDefaultRoute returns an IPSet representing the IPs in route,
2021-12-16 19:15:45 +00:00
// minus those in removeFromDefaultRoute and localInterfaceRoutes,
// plus the IPs in hostIPs.
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
func shrinkDefaultRoute ( route netip . Prefix , localInterfaceRoutes * netipx . IPSet , hostIPs [ ] netip . Addr ) ( * netipx . IPSet , error ) {
2022-07-25 03:08:42 +00:00
var b netipx . IPSetBuilder
2021-04-08 22:56:51 +00:00
// Add the default route.
b . AddPrefix ( route )
// Remove the local interface routes.
2021-12-16 19:15:45 +00:00
b . RemoveSet ( localInterfaceRoutes )
2021-03-18 00:04:32 +00:00
// Having removed all the LAN subnets, re-add the hosts's own
// IPs. It's fine for clients to connect to an exit node's public
// IP address, just not the attached subnet.
//
// Truly forbidden subnets (in removeFromDefaultRoute) will still
// be stripped back out by the next step.
for _ , ip := range hostIPs {
if route . Contains ( ip ) {
b . Add ( ip )
}
}
2021-02-23 04:43:35 +00:00
for _ , pfx := range removeFromDefaultRoute {
b . RemovePrefix ( pfx )
}
2021-06-02 16:04:37 +00:00
return b . IPSet ( )
2021-02-23 04:43:35 +00:00
}
2020-05-19 02:32:20 +00:00
// readPoller is a goroutine that receives service lists from
// b.portpoll and propagates them into the controlclient's HostInfo.
2020-04-29 09:23:29 +00:00
func ( b * LocalBackend ) readPoller ( ) {
2023-06-05 16:33:59 +00:00
isFirst := true
2023-07-27 19:41:31 +00:00
ticker , tickerChannel := b . clock . NewTicker ( portlist . PollInterval ( ) )
2023-06-05 16:33:59 +00:00
defer ticker . Stop ( )
initChan := make ( chan struct { } )
close ( initChan )
2020-02-05 22:16:58 +00:00
for {
2023-06-05 16:33:59 +00:00
select {
2023-07-27 19:41:31 +00:00
case <- tickerChannel :
2023-06-05 16:33:59 +00:00
case <- b . ctx . Done ( ) :
2020-03-14 03:53:58 +00:00
return
2023-06-05 16:33:59 +00:00
case <- initChan :
// Preserving old behavior: readPoller should
// immediately poll the first time, then wait
// for a tick after.
initChan = nil
}
ports , changed , err := b . portpoll . Poll ( )
if err != nil {
b . logf ( "error polling for open ports: %v" , err )
return
}
if ! changed {
continue
2020-02-05 22:16:58 +00:00
}
sl := [ ] tailcfg . Service { }
for _ , p := range ports {
s := tailcfg . Service {
2020-04-01 04:48:33 +00:00
Proto : tailcfg . ServiceProto ( p . Proto ) ,
2020-02-05 22:16:58 +00:00
Port : p . Port ,
Description : p . Process ,
}
2020-04-01 04:48:33 +00:00
if policy . IsInterestingService ( s , version . OS ( ) ) {
sl = append ( sl , s )
}
2020-02-05 22:16:58 +00:00
}
b . mu . Lock ( )
2020-06-15 23:04:12 +00:00
if b . hostinfo == nil {
b . hostinfo = new ( tailcfg . Hostinfo )
2020-02-25 19:01:20 +00:00
}
2020-06-15 23:04:12 +00:00
b . hostinfo . Services = sl
2020-02-05 22:16:58 +00:00
b . mu . Unlock ( )
2023-10-23 17:18:40 +00:00
b . doSetHostinfoFilterServices ( )
2020-10-14 21:07:40 +00:00
2023-06-05 16:33:59 +00:00
if isFirst {
isFirst = false
2020-10-14 21:07:40 +00:00
close ( b . gotPortPollRes )
}
2020-02-05 22:16:58 +00:00
}
}
2023-10-23 17:22:34 +00:00
// GetPushDeviceToken returns the push notification device token.
func ( b * LocalBackend ) GetPushDeviceToken ( ) string {
return b . pushDeviceToken . Load ( )
}
2023-01-29 22:04:40 +00:00
2023-10-23 17:22:34 +00:00
// SetPushDeviceToken sets the push notification device token and informs the
// controlclient of the new value.
func ( b * LocalBackend ) SetPushDeviceToken ( tk string ) {
old := b . pushDeviceToken . Swap ( tk )
if old == tk {
return
2023-01-29 22:04:40 +00:00
}
2023-10-23 17:22:34 +00:00
b . doSetHostinfoFilterServices ( )
2023-01-29 22:04:40 +00:00
}
2023-10-16 19:15:03 +00:00
func applyConfigToHostinfo ( hi * tailcfg . Hostinfo , c * conffile . Config ) {
if c == nil {
return
}
if c . Parsed . Hostname != nil {
hi . Hostname = * c . Parsed . Hostname
}
}
2022-11-22 19:41:03 +00:00
// WatchNotifications subscribes to the ipn.Notify message bus notification
// messages.
//
// WatchNotifications blocks until ctx is done.
//
2023-01-17 20:59:03 +00:00
// The provided onWatchAdded, if non-nil, will be called once the watcher
// is installed.
//
// The provided fn will be called for each notification. It will only be
// called with non-nil pointers. The caller must not modify roNotify. If
// fn returns false, the watch also stops.
2022-11-22 19:41:03 +00:00
//
// Failure to consume many notifications in a row will result in dropped
// notifications. There is currently (2022-11-22) no mechanism provided to
// detect when a message has been dropped.
2023-01-17 20:59:03 +00:00
func ( b * LocalBackend ) WatchNotifications ( ctx context . Context , mask ipn . NotifyWatchOpt , onWatchAdded func ( ) , fn func ( roNotify * ipn . Notify ) ( keepGoing bool ) ) {
2022-11-22 19:41:03 +00:00
ch := make ( chan * ipn . Notify , 128 )
2023-08-31 16:43:54 +00:00
sessionID := rands . HexString ( 16 )
2022-12-21 20:44:51 +00:00
origFn := fn
if mask & ipn . NotifyNoPrivateKeys != 0 {
fn = func ( n * ipn . Notify ) bool {
if n . NetMap == nil || n . NetMap . PrivateKey . IsZero ( ) {
return origFn ( n )
}
// The netmap in n is shared across all watchers, so to mutate it for a
// single watcher we have to clone the notify and the netmap. We can
// make shallow clones, at least.
nm2 := * n . NetMap
n2 := * n
n2 . NetMap = & nm2
n2 . NetMap . PrivateKey = key . NodePrivate { }
return origFn ( & n2 )
}
}
2022-12-01 01:39:43 +00:00
var ini * ipn . Notify
2020-02-25 20:30:28 +00:00
b . mu . Lock ( )
2023-08-31 16:43:54 +00:00
2024-04-03 17:09:58 +00:00
const initialBits = ipn . NotifyInitialState | ipn . NotifyInitialPrefs | ipn . NotifyInitialNetMap | ipn . NotifyInitialDriveShares
2022-12-01 01:39:43 +00:00
if mask & initialBits != 0 {
2023-02-11 06:20:36 +00:00
ini = & ipn . Notify { Version : version . Long ( ) }
2022-12-01 01:39:43 +00:00
if mask & ipn . NotifyInitialState != 0 {
2023-08-31 16:43:54 +00:00
ini . SessionID = sessionID
2022-12-01 01:39:43 +00:00
ini . State = ptr . To ( b . state )
2024-05-10 20:25:08 +00:00
if b . state == ipn . NeedsLogin && b . authURL != "" {
ini . BrowseToURL = ptr . To ( b . authURL )
2022-12-01 01:39:43 +00:00
}
}
if mask & ipn . NotifyInitialPrefs != 0 {
2022-12-02 08:54:32 +00:00
ini . Prefs = ptr . To ( b . sanitizedPrefsLocked ( ) )
2022-12-01 01:39:43 +00:00
}
if mask & ipn . NotifyInitialNetMap != 0 {
ini . NetMap = b . netMap
}
2024-04-03 17:09:58 +00:00
if mask & ipn . NotifyInitialDriveShares != 0 && b . driveSharingEnabledLocked ( ) {
ini . DriveShares = b . pm . prefs . DriveShares ( )
2024-02-02 18:45:32 +00:00
}
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
if mask & ipn . NotifyInitialHealthState != 0 {
ini . Health = b . HealthTracker ( ) . CurrentState ( )
}
2022-12-01 01:39:43 +00:00
}
2024-02-28 21:56:30 +00:00
mak . Set ( & b . notifyWatchers , sessionID , & watchSession { ch , sessionID } )
2020-02-25 20:30:28 +00:00
b . mu . Unlock ( )
2022-12-01 01:39:43 +00:00
2022-11-22 19:41:03 +00:00
defer func ( ) {
b . mu . Lock ( )
2024-02-28 21:56:30 +00:00
delete ( b . notifyWatchers , sessionID )
2022-11-22 19:41:03 +00:00
b . mu . Unlock ( )
} ( )
2020-02-25 20:30:28 +00:00
2023-01-17 20:59:03 +00:00
if onWatchAdded != nil {
onWatchAdded ( )
}
2022-12-01 01:39:43 +00:00
if ini != nil {
if ! fn ( ini ) {
return
}
}
2022-11-26 20:19:16 +00:00
// The GUI clients want to know when peers become active or inactive.
// They've historically got this information by polling for it, which is
// wasteful. As a step towards making it efficient, they now set this
// NotifyWatchEngineUpdates bit to ask for us to send it to them only on
// change. That's not yet (as of 2022-11-26) plumbed everywhere in
// tailscaled yet, so just do the polling here. This ends up causing all IPN
// bus watchers to get the notification every 2 seconds instead of just the
// GUI client's bus watcher, but in practice there's only 1 total connection
// anyway. And if we're polling, at least the client isn't making a new HTTP
// request every 2 seconds.
// TODO(bradfitz): plumb this further and only send a Notify on change.
if mask & ipn . NotifyWatchEngineUpdates != 0 {
2022-12-01 01:31:36 +00:00
ctx , cancel := context . WithCancel ( ctx )
defer cancel ( )
2022-11-26 20:19:16 +00:00
go b . pollRequestEngineStatus ( ctx )
}
2023-09-05 17:51:52 +00:00
// TODO(marwan-at-work): check err
// TODO(marwan-at-work): streaming background logs?
defer b . DeleteForegroundSession ( sessionID )
2023-09-05 18:33:18 +00:00
2024-05-10 20:25:08 +00:00
var lastURLPop string // to dup suppress URL popups
2022-11-22 19:41:03 +00:00
for {
select {
case <- ctx . Done ( ) :
return
2023-09-18 14:30:58 +00:00
case n , ok := <- ch :
2024-05-10 20:25:08 +00:00
// URLs flow into Notify.BrowseToURL via two means:
// 1. From MapResponse.PopBrowserURL, which already says they're dup
// suppressed if identical, and that's done by the controlclient,
// so this added later adds nothing.
//
// 2. From the controlclient auth routes, on register. This makes sure
// we don't tell clients (mac, windows, android) to pop the same URL
// multiple times.
if n != nil && n . BrowseToURL != nil {
if v := * n . BrowseToURL ; v == lastURLPop {
n . BrowseToURL = nil
} else {
lastURLPop = v
}
}
2023-09-18 14:30:58 +00:00
if ! ok || ! fn ( n ) {
2022-11-22 19:41:03 +00:00
return
}
}
2021-03-30 18:19:42 +00:00
}
2022-11-22 19:41:03 +00:00
}
2021-03-30 18:19:42 +00:00
2024-04-15 02:47:32 +00:00
// pollRequestEngineStatus calls b.e.RequestStatus every 2 seconds until ctx
2022-11-26 20:19:16 +00:00
// is done.
func ( b * LocalBackend ) pollRequestEngineStatus ( ctx context . Context ) {
2023-07-27 19:41:31 +00:00
ticker , tickerChannel := b . clock . NewTicker ( 2 * time . Second )
2022-11-26 20:19:16 +00:00
defer ticker . Stop ( )
for {
select {
2023-07-27 19:41:31 +00:00
case <- tickerChannel :
2024-04-15 02:47:32 +00:00
b . e . RequestStatus ( )
2022-11-26 20:19:16 +00:00
case <- ctx . Done ( ) :
return
}
}
}
2022-12-03 04:13:36 +00:00
// DebugNotify injects a fake notify message to clients.
//
// It should only be used via the LocalAPI's debug handler.
func ( b * LocalBackend ) DebugNotify ( n ipn . Notify ) {
b . send ( n )
}
2024-03-10 00:46:45 +00:00
// DebugNotifyLastNetMap injects a fake notify message to clients,
// repeating whatever the last netmap was.
//
// It should only be used via the LocalAPI's debug handler.
func ( b * LocalBackend ) DebugNotifyLastNetMap ( ) {
b . mu . Lock ( )
nm := b . netMap
b . mu . Unlock ( )
if nm != nil {
b . send ( ipn . Notify { NetMap : nm } )
}
}
2023-09-24 15:08:28 +00:00
// DebugForceNetmapUpdate forces a full no-op netmap update of the current
// netmap in all the various subsystems (wireguard, magicsock, LocalBackend).
//
// It exists for load testing reasons (for issue 1909), doing what would happen
// if a new MapResponse came in from the control server that couldn't be handled
// incrementally.
func ( b * LocalBackend ) DebugForceNetmapUpdate ( ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
nm := b . netMap
b . e . SetNetworkMap ( nm )
if nm != nil {
2023-11-15 23:10:45 +00:00
b . MagicConn ( ) . SetDERPMap ( nm . DERPMap )
2023-09-24 15:08:28 +00:00
}
b . setNetMapLocked ( nm )
}
2023-10-07 03:39:23 +00:00
// DebugPickNewDERP forwards to magicsock.Conn.DebugPickNewDERP.
// See its docs.
func ( b * LocalBackend ) DebugPickNewDERP ( ) error {
return b . sys . MagicSock . Get ( ) . DebugPickNewDERP ( )
}
2022-11-22 19:41:03 +00:00
// send delivers n to the connected frontend and any API watchers from
// LocalBackend.WatchNotifications (via the LocalAPI).
//
// If no frontend is connected or API watchers are backed up, the notification
// is dropped without being delivered.
2022-11-29 05:57:44 +00:00
//
2022-12-02 08:54:32 +00:00
// If n contains Prefs, those will be sanitized before being delivered.
//
2022-11-29 05:57:44 +00:00
// b.mu must not be held.
2022-11-22 19:41:03 +00:00
func ( b * LocalBackend ) send ( n ipn . Notify ) {
2024-05-08 00:31:10 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
b . sendLocked ( n )
}
// sendLocked is like send, but assumes b.mu is already held.
func ( b * LocalBackend ) sendLocked ( n ipn . Notify ) {
2022-12-02 08:54:32 +00:00
if n . Prefs != nil {
n . Prefs = ptr . To ( stripKeysFromPrefs ( * n . Prefs ) )
}
2022-12-03 04:13:36 +00:00
if n . Version == "" {
2023-02-11 06:20:36 +00:00
n . Version = version . Long ( )
2022-12-03 04:13:36 +00:00
}
2022-11-22 19:41:03 +00:00
apiSrv := b . peerAPIServer
2023-10-05 23:05:45 +00:00
if mayDeref ( apiSrv ) . taildrop . HasFilesWaiting ( ) {
2021-04-09 14:57:32 +00:00
n . FilesWaiting = & empty . Message { }
}
2023-09-18 14:30:58 +00:00
for _ , sess := range b . notifyWatchers {
2022-11-22 19:41:03 +00:00
select {
2023-09-18 14:30:58 +00:00
case sess . ch <- & n :
2022-11-22 19:41:03 +00:00
default :
// Drop the notification if the channel is full.
}
}
2021-04-08 21:54:25 +00:00
}
func ( b * LocalBackend ) sendFileNotify ( ) {
var n ipn . Notify
b . mu . Lock ( )
2022-11-20 21:25:54 +00:00
for _ , wakeWaiter := range b . fileWaiters {
wakeWaiter ( )
}
2021-04-08 21:54:25 +00:00
apiSrv := b . peerAPIServer
2024-05-08 00:31:10 +00:00
if apiSrv == nil {
2021-04-08 21:54:25 +00:00
b . mu . Unlock ( )
return
}
2021-04-09 14:57:32 +00:00
// Make sure we always set n.IncomingFiles non-nil so it gets encoded
// in JSON to clients. They distinguish between empty and non-nil
// to know whether a Notify should be able about files.
2023-10-06 14:47:03 +00:00
n . IncomingFiles = apiSrv . taildrop . IncomingFiles ( )
2021-04-08 21:54:25 +00:00
b . mu . Unlock ( )
sort . Slice ( n . IncomingFiles , func ( i , j int ) bool {
return n . IncomingFiles [ i ] . Started . Before ( n . IncomingFiles [ j ] . Started )
} )
b . send ( n )
2020-02-05 22:16:58 +00:00
}
2020-05-19 02:32:20 +00:00
// popBrowserAuthNow shuts down the data plane and sends an auth URL
// to the connected frontend, if any.
2020-02-05 22:16:58 +00:00
func ( b * LocalBackend ) popBrowserAuthNow ( ) {
b . mu . Lock ( )
url := b . authURL
2024-05-08 05:15:56 +00:00
expired := b . keyExpired
2020-02-05 22:16:58 +00:00
b . mu . Unlock ( )
2020-02-25 22:05:17 +00:00
2024-05-08 05:15:56 +00:00
b . logf ( "popBrowserAuthNow: url=%v, key-expired=%v, seamless-key-renewal=%v" , url != "" , expired , b . seamlessRenewalEnabled ( ) )
2020-02-05 22:16:58 +00:00
2024-04-19 12:43:07 +00:00
// Deconfigure the local network data plane if:
// - seamless key renewal is not enabled;
// - key is expired (in which case tailnet connectivity is down anyway).
2024-05-08 05:43:07 +00:00
if ! b . seamlessRenewalEnabled ( ) || expired {
2024-01-04 17:29:04 +00:00
b . blockEngineUpdates ( true )
b . stopEngineAndWait ( )
}
2022-03-21 21:10:25 +00:00
b . tellClientToBrowseToURL ( url )
2021-02-04 21:12:42 +00:00
if b . State ( ) == ipn . Running {
b . enterState ( ipn . Starting )
2020-02-05 22:16:58 +00:00
}
}
2022-11-16 16:18:28 +00:00
// validPopBrowserURL reports whether urlStr is a valid value for a
// control server to send in a *URL field.
2022-11-16 17:19:59 +00:00
//
2022-11-16 16:18:28 +00:00
// b.mu must *not* be held.
func ( b * LocalBackend ) validPopBrowserURL ( urlStr string ) bool {
if urlStr == "" {
2022-11-16 17:19:59 +00:00
return false
2022-11-16 16:18:28 +00:00
}
u , err := url . Parse ( urlStr )
if err != nil {
return false
}
2024-03-14 00:31:07 +00:00
serverURL := b . Prefs ( ) . ControlURLOrDefault ( )
if ipn . IsLoginServerSynonym ( serverURL ) {
// When connected to the official Tailscale control plane, only allow
// URLs from tailscale.com or its subdomains.
if h := u . Hostname ( ) ; h != "tailscale.com" && ! strings . HasSuffix ( u . Hostname ( ) , ".tailscale.com" ) {
return false
}
// When using a different ControlURL, we cannot be sure what legitimate
// PopBrowserURLs they will send. Allow any domain there to avoid
// breaking existing user setups.
}
2022-11-16 16:18:28 +00:00
switch u . Scheme {
case "https" :
return true
case "http" :
// If the control server is using plain HTTP (likely a dev server),
// then permit http://.
return strings . HasPrefix ( serverURL , "http://" )
}
return false
}
2022-03-21 21:10:25 +00:00
func ( b * LocalBackend ) tellClientToBrowseToURL ( url string ) {
2022-11-16 17:19:59 +00:00
if b . validPopBrowserURL ( url ) {
2022-03-21 21:10:25 +00:00
b . send ( ipn . Notify { BrowseToURL : & url } )
}
}
2022-11-24 03:13:41 +00:00
// onClientVersion is called on MapResponse updates when a MapResponse contains
// a non-nil ClientVersion message.
func ( b * LocalBackend ) onClientVersion ( v * tailcfg . ClientVersion ) {
2023-09-08 21:27:49 +00:00
b . mu . Lock ( )
b . lastClientVersion = v
2024-05-01 20:54:56 +00:00
b . health . SetLatestVersion ( v )
2023-09-08 21:27:49 +00:00
b . mu . Unlock ( )
2023-10-19 19:50:21 +00:00
b . send ( ipn . Notify { ClientVersion : v } )
2022-11-24 03:13:41 +00:00
}
2023-12-18 22:57:03 +00:00
func ( b * LocalBackend ) onTailnetDefaultAutoUpdate ( au bool ) {
2024-04-18 03:15:09 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2023-12-18 22:57:03 +00:00
prefs := b . pm . CurrentPrefs ( )
if ! prefs . Valid ( ) {
b . logf ( "[unexpected]: received tailnet default auto-update callback but current prefs are nil" )
return
}
if _ , ok := prefs . AutoUpdate ( ) . Apply . Get ( ) ; ok {
// Apply was already set from a previous default or manually by the
// user. Tailnet default should not affect us, even if it changes.
return
}
2024-06-06 23:31:52 +00:00
if au && b . hostinfo != nil && b . hostinfo . Container . EqualBool ( true ) {
// This is a containerized node, which is usually meant to be
// immutable. Do not enable auto-updates if the tailnet does. But users
// can still manually enable auto-updates on this node.
return
}
2023-12-18 22:57:03 +00:00
b . logf ( "using tailnet default auto-update setting: %v" , au )
prefsClone := prefs . AsStruct ( )
prefsClone . AutoUpdate . Apply = opt . NewBool ( au )
2024-04-18 03:15:09 +00:00
_ , err := b . editPrefsLockedOnEntry ( & ipn . MaskedPrefs {
2023-12-18 22:57:03 +00:00
Prefs : * prefsClone ,
AutoUpdateSet : ipn . AutoUpdatePrefsMask {
ApplySet : true ,
} ,
2024-04-18 03:15:09 +00:00
} , unlock )
2023-12-18 22:57:03 +00:00
if err != nil {
b . logf ( "failed to apply tailnet-wide default for auto-updates (%v): %v" , au , err )
return
}
}
2021-04-02 15:21:40 +00:00
// For testing lazy machine key generation.
2022-09-14 19:49:39 +00:00
var panicOnMachineKeyGeneration = envknob . RegisterBool ( "TS_DEBUG_PANIC_MACHINE_KEY" )
2021-04-02 15:21:40 +00:00
2021-09-03 20:17:46 +00:00
func ( b * LocalBackend ) createGetMachinePrivateKeyFunc ( ) func ( ) ( key . MachinePrivate , error ) {
2022-08-04 17:43:49 +00:00
var cache syncs . AtomicValue [ key . MachinePrivate ]
2021-09-03 20:17:46 +00:00
return func ( ) ( key . MachinePrivate , error ) {
2022-09-14 19:49:39 +00:00
if panicOnMachineKeyGeneration ( ) {
2021-04-02 15:21:40 +00:00
panic ( "machine key generated" )
}
2022-08-04 17:43:49 +00:00
if v , ok := cache . LoadOk ( ) ; ok {
2021-04-02 15:21:40 +00:00
return v , nil
}
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-08-04 17:43:49 +00:00
if v , ok := cache . LoadOk ( ) ; ok {
2021-04-02 15:21:40 +00:00
return v , nil
}
if err := b . initMachineKeyLocked ( ) ; err != nil {
2021-09-03 20:17:46 +00:00
return key . MachinePrivate { } , err
2021-04-02 15:21:40 +00:00
}
cache . Store ( b . machinePrivKey )
return b . machinePrivKey , nil
}
}
2020-09-28 22:28:26 +00:00
// initMachineKeyLocked is called to initialize b.machinePrivKey.
//
// b.prefs must already be initialized.
2020-11-04 17:35:58 +00:00
// b.stateKey should be set too, but just for nicer log messages.
2020-09-28 22:28:26 +00:00
// b.mu must be held.
2020-10-21 19:55:03 +00:00
func ( b * LocalBackend ) initMachineKeyLocked ( ) ( err error ) {
2020-09-28 22:28:26 +00:00
if ! b . machinePrivKey . IsZero ( ) {
// Already set.
return nil
}
2021-09-03 20:17:46 +00:00
var legacyMachineKey key . MachinePrivate
2022-11-29 20:00:40 +00:00
if p := b . pm . CurrentPrefs ( ) . Persist ( ) ; p . Valid ( ) {
legacyMachineKey = p . LegacyFrontendPrivateMachineKey ( )
2020-09-28 22:28:26 +00:00
}
2021-02-04 21:12:42 +00:00
keyText , err := b . store . ReadState ( ipn . MachineKeyStateKey )
2020-09-28 22:28:26 +00:00
if err == nil {
if err := b . machinePrivKey . UnmarshalText ( keyText ) ; err != nil {
2021-02-04 21:12:42 +00:00
return fmt . Errorf ( "invalid key in %s key of %v: %w" , ipn . MachineKeyStateKey , b . store , err )
2020-09-28 22:28:26 +00:00
}
if b . machinePrivKey . IsZero ( ) {
2021-02-04 21:12:42 +00:00
return fmt . Errorf ( "invalid zero key stored in %v key of %v" , ipn . MachineKeyStateKey , b . store )
2020-09-28 22:28:26 +00:00
}
2021-09-03 20:17:46 +00:00
if ! legacyMachineKey . IsZero ( ) && ! legacyMachineKey . Equal ( b . machinePrivKey ) {
2020-09-28 22:28:26 +00:00
b . logf ( "frontend-provided legacy machine key ignored; used value from server state" )
}
return nil
}
2021-02-04 21:12:42 +00:00
if err != ipn . ErrStateNotExist {
return fmt . Errorf ( "error reading %v key of %v: %w" , ipn . MachineKeyStateKey , b . store , err )
2020-09-28 22:28:26 +00:00
}
// If we didn't find one already on disk and the prefs already
// have a legacy machine key, use that. Otherwise generate a
// new one.
if ! legacyMachineKey . IsZero ( ) {
b . machinePrivKey = legacyMachineKey
} else {
b . logf ( "generating new machine key" )
2021-09-03 20:17:46 +00:00
b . machinePrivKey = key . NewMachine ( )
2020-09-28 22:28:26 +00:00
}
keyText , _ = b . machinePrivKey . MarshalText ( )
2023-08-04 14:55:59 +00:00
if err := ipn . WriteState ( b . store , ipn . MachineKeyStateKey , keyText ) ; err != nil {
2020-09-28 22:28:26 +00:00
b . logf ( "error writing machine key to store: %v" , err )
return err
}
b . logf ( "machine key written to store" )
return nil
}
2023-01-27 23:41:03 +00:00
// clearMachineKeyLocked is called to clear the persisted and in-memory
// machine key, so that initMachineKeyLocked (called as part of starting)
// generates a new machine key.
//
// b.mu must be held.
func ( b * LocalBackend ) clearMachineKeyLocked ( ) error {
2023-08-04 14:55:59 +00:00
if err := ipn . WriteState ( b . store , ipn . MachineKeyStateKey , nil ) ; err != nil {
2023-01-27 23:41:03 +00:00
return err
}
b . machinePrivKey = key . MachinePrivate { }
b . logf ( "machine key cleared" )
return nil
}
2022-11-07 23:32:53 +00:00
// setTCPPortsIntercepted populates b.shouldInterceptTCPPortAtomic with an
// efficient func for ShouldInterceptTCPPort to use, which is called on every
// incoming packet.
func ( b * LocalBackend ) setTCPPortsIntercepted ( ports [ ] uint16 ) {
slices . Sort ( ports )
uniq . ModifySlice ( & ports )
var f func ( uint16 ) bool
switch len ( ports ) {
case 0 :
f = func ( uint16 ) bool { return false }
case 1 :
f = func ( p uint16 ) bool { return ports [ 0 ] == p }
case 2 :
f = func ( p uint16 ) bool { return ports [ 0 ] == p || ports [ 1 ] == p }
case 3 :
f = func ( p uint16 ) bool { return ports [ 0 ] == p || ports [ 1 ] == p || ports [ 2 ] == p }
default :
if len ( ports ) > 16 {
m := map [ uint16 ] bool { }
for _ , p := range ports {
m [ p ] = true
}
f = func ( p uint16 ) bool { return m [ p ] }
} else {
f = func ( p uint16 ) bool {
for _ , x := range ports {
if p == x {
return true
}
}
return false
}
}
}
b . shouldInterceptTCPPortAtomic . Store ( f )
}
2024-03-18 21:47:21 +00:00
// setAtomicValuesFromPrefsLocked populates sshAtomicBool, containsViaIPFuncAtomic,
// shouldInterceptTCPPortAtomic, and exposeRemoteWebClientAtomicBool from the prefs p,
// which may be !Valid().
2022-11-16 20:51:26 +00:00
func ( b * LocalBackend ) setAtomicValuesFromPrefsLocked ( p ipn . PrefsView ) {
2022-10-23 17:07:10 +00:00
b . sshAtomicBool . Store ( p . Valid ( ) && p . RunSSH ( ) && envknob . CanSSHD ( ) )
2024-03-18 21:47:21 +00:00
b . setExposeRemoteWebClientAtomicBoolLocked ( p )
2022-03-30 15:47:16 +00:00
2022-10-23 17:07:10 +00:00
if ! p . Valid ( ) {
2023-09-18 06:31:34 +00:00
b . containsViaIPFuncAtomic . Store ( tsaddr . FalseContainsIPFunc ( ) )
2022-11-07 23:32:53 +00:00
b . setTCPPortsIntercepted ( nil )
2022-11-16 20:51:26 +00:00
b . lastServeConfJSON = mem . B ( nil )
b . serveConfig = ipn . ServeConfigView { }
2022-03-30 15:47:16 +00:00
} else {
2023-08-18 17:57:04 +00:00
filtered := tsaddr . FilterPrefixesCopy ( p . AdvertiseRoutes ( ) , tsaddr . IsViaPrefix )
2023-09-18 06:31:34 +00:00
b . containsViaIPFuncAtomic . Store ( tsaddr . NewContainsIPFunc ( views . SliceOf ( filtered ) ) )
2022-11-09 05:58:10 +00:00
b . setTCPPortsInterceptedFromNetmapAndPrefsLocked ( p )
2022-03-30 15:47:16 +00:00
}
}
2020-05-19 02:32:20 +00:00
// State returns the backend state machine's current state.
2021-02-04 21:12:42 +00:00
func ( b * LocalBackend ) State ( ) ipn . State {
2020-02-05 22:16:58 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
return b . state
}
2022-11-25 14:02:40 +00:00
// InServerMode reports whether the Tailscale backend is explicitly running in
// "server mode" where it continues to run despite whatever the platform's
// default is. In practice, this is only used on Windows, where the default
// tailscaled behavior is to shut down whenever the GUI disconnects.
//
// On non-Windows platforms, this usually returns false (because people don't
// set unattended mode on other platforms) and also isn't checked on other
// platforms.
//
// TODO(bradfitz): rename to InWindowsUnattendedMode or something? Or make this
// return true on Linux etc and always be called? It's kinda messy now.
2020-11-02 17:52:59 +00:00
func ( b * LocalBackend ) InServerMode ( ) bool {
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-11-25 14:50:15 +00:00
return b . pm . CurrentPrefs ( ) . ForceDaemon ( )
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
}
2022-11-23 19:18:18 +00:00
// CheckIPNConnectionAllowed returns an error if the identity in ci should not
// be allowed to connect or make requests to the LocalAPI currently.
//
// Currently (as of 2022-11-23), this is only used on Windows to check if
// we started in server mode and ci is from an identity other than the one
// that started the server.
func ( b * LocalBackend ) CheckIPNConnectionAllowed ( ci * ipnauth . ConnIdentity ) error {
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-11-25 14:11:06 +00:00
serverModeUid := b . pm . CurrentUserID ( )
2022-11-23 19:18:18 +00:00
if serverModeUid == "" {
// Either this platform isn't a "multi-user" platform or we're not yet
// running as one.
return nil
}
2022-11-25 14:50:15 +00:00
if ! b . pm . CurrentPrefs ( ) . ForceDaemon ( ) {
2022-11-23 19:18:18 +00:00
return nil
}
2024-01-10 21:58:51 +00:00
// Always allow Windows SYSTEM user to connect,
// even if Tailscale is currently being used by another user.
if tok , err := ci . WindowsToken ( ) ; err == nil {
defer tok . Close ( )
if tok . IsLocalSystem ( ) {
return nil
}
}
2022-11-27 17:04:00 +00:00
uid := ci . WindowsUserID ( )
2022-11-23 19:18:18 +00:00
if uid == "" {
return errors . New ( "empty user uid in connection identity" )
}
if uid != serverModeUid {
2022-11-27 17:04:00 +00:00
return fmt . Errorf ( "Tailscale running in server mode (%q); connection from %q not allowed" , b . tryLookupUserName ( string ( serverModeUid ) ) , b . tryLookupUserName ( string ( uid ) ) )
2022-11-23 19:18:18 +00:00
}
return nil
}
2022-11-25 14:11:06 +00:00
// tryLookupUserName tries to look up the username for the uid.
// It returns the username on success, or the UID on failure.
func ( b * LocalBackend ) tryLookupUserName ( uid string ) string {
u , err := ipnauth . LookupUserFromID ( b . logf , uid )
if err != nil {
return uid
}
return u . Username
}
2024-04-15 22:05:50 +00:00
// StartLoginInteractive requests a new interactive login from controlclient,
// unless such a flow is already in progress, in which case
// StartLoginInteractive attempts to pick up the in-progress flow where it left
// off.
func ( b * LocalBackend ) StartLoginInteractive ( ctx context . Context ) error {
2020-02-05 22:16:58 +00:00
b . mu . Lock ( )
2024-04-13 23:13:57 +00:00
if b . cc == nil {
panic ( "LocalBackend.assertClient: b.cc == nil" )
}
2020-02-05 22:16:58 +00:00
url := b . authURL
2024-02-08 21:04:01 +00:00
timeSinceAuthURLCreated := b . clock . Since ( b . authURLTime )
2021-04-08 04:12:16 +00:00
cc := b . cc
2020-02-05 22:16:58 +00:00
b . mu . Unlock ( )
2020-04-11 15:35:34 +00:00
b . logf ( "StartLoginInteractive: url=%v" , url != "" )
2020-02-05 22:16:58 +00:00
2024-02-08 21:04:01 +00:00
// Only use an authURL if it was sent down from control in the last
// 6 days and 23 hours. Avoids using a stale URL that is no longer valid
// server-side. Server-side URLs expire after 7 days.
if url != "" && timeSinceAuthURLCreated < ( ( 7 * 24 * time . Hour ) - ( 1 * time . Hour ) ) {
2020-02-05 22:16:58 +00:00
b . popBrowserAuthNow ( )
} else {
2024-05-17 21:54:41 +00:00
cc . Login ( b . loginFlags | controlclient . LoginInteractive )
2020-02-05 22:16:58 +00:00
}
2024-04-15 22:05:50 +00:00
return nil
2020-02-05 22:16:58 +00:00
}
2023-08-08 12:11:28 +00:00
func ( b * LocalBackend ) Ping ( ctx context . Context , ip netip . Addr , pingType tailcfg . PingType , size int ) ( * ipnstate . PingResult , error ) {
2022-05-28 04:34:36 +00:00
if pingType == tailcfg . PingPeerAPI {
2023-07-27 19:41:31 +00:00
t0 := b . clock . Now ( )
2022-05-28 04:34:36 +00:00
node , base , err := b . pingPeerAPI ( ctx , ip )
if err != nil && ctx . Err ( ) != nil {
return nil , ctx . Err ( )
}
2023-07-27 19:41:31 +00:00
d := b . clock . Since ( t0 )
2022-05-28 04:34:36 +00:00
pr := & ipnstate . PingResult {
IP : ip . String ( ) ,
NodeIP : ip . String ( ) ,
LatencySeconds : d . Seconds ( ) ,
PeerAPIURL : base ,
}
if err != nil {
pr . Err = err . Error ( )
}
2023-08-18 14:57:44 +00:00
if node . Valid ( ) {
pr . NodeName = node . Name ( )
2022-05-28 04:34:36 +00:00
}
return pr , nil
}
2022-05-03 21:16:34 +00:00
ch := make ( chan * ipnstate . PingResult , 1 )
2023-08-08 12:11:28 +00:00
b . e . Ping ( ip , pingType , size , func ( pr * ipnstate . PingResult ) {
2022-05-03 21:16:34 +00:00
select {
case ch <- pr :
default :
}
2020-08-09 21:49:42 +00:00
} )
2022-05-03 21:16:34 +00:00
select {
case pr := <- ch :
return pr , nil
case <- ctx . Done ( ) :
return nil , ctx . Err ( )
}
2020-08-09 21:49:42 +00:00
}
2023-08-18 14:57:44 +00:00
func ( b * LocalBackend ) pingPeerAPI ( ctx context . Context , ip netip . Addr ) ( peer tailcfg . NodeView , peerBase string , err error ) {
var zero tailcfg . NodeView
2022-05-28 04:34:36 +00:00
ctx , cancel := context . WithTimeout ( ctx , 10 * time . Second )
defer cancel ( )
nm := b . NetMap ( )
if nm == nil {
2023-08-18 14:57:44 +00:00
return zero , "" , errors . New ( "no netmap" )
2022-05-28 04:34:36 +00:00
}
peer , ok := nm . PeerByTailscaleIP ( ip )
if ! ok {
2023-08-18 14:57:44 +00:00
return zero , "" , fmt . Errorf ( "no peer found with Tailscale IP %v" , ip )
2022-05-28 04:34:36 +00:00
}
2023-08-18 14:57:44 +00:00
if peer . Expired ( ) {
return zero , "" , errors . New ( "peer's node key has expired" )
2023-01-13 19:29:41 +00:00
}
2022-05-28 04:34:36 +00:00
base := peerAPIBase ( nm , peer )
if base == "" {
2023-08-18 14:57:44 +00:00
return zero , "" , fmt . Errorf ( "no PeerAPI base found for peer %v (%v)" , peer . ID ( ) , ip )
2022-05-28 04:34:36 +00:00
}
outReq , err := http . NewRequestWithContext ( ctx , "HEAD" , base , nil )
if err != nil {
2023-08-18 14:57:44 +00:00
return zero , "" , err
2022-05-28 04:34:36 +00:00
}
tr := b . Dialer ( ) . PeerAPITransport ( )
res , err := tr . RoundTrip ( outReq )
if err != nil {
2023-08-18 14:57:44 +00:00
return zero , "" , err
2022-05-28 04:34:36 +00:00
}
defer res . Body . Close ( ) // but unnecessary on HEAD responses
if res . StatusCode != http . StatusOK {
2023-08-18 14:57:44 +00:00
return zero , "" , fmt . Errorf ( "HTTP status %v" , res . Status )
2022-05-28 04:34:36 +00:00
}
return peer , base , nil
}
2020-10-29 22:26:10 +00:00
// parseWgStatusLocked returns an EngineStatus based on s.
//
// b.mu must be held; mostly because the caller is about to anyway, and doing so
// gives us slightly better guarantees about the two peers stats lines not
// being intermixed if there are concurrent calls to our caller.
2021-02-04 21:12:42 +00:00
func ( b * LocalBackend ) parseWgStatusLocked ( s * wgengine . Status ) ( ret ipn . EngineStatus ) {
2020-10-29 22:26:10 +00:00
var peerStats , peerKeys strings . Builder
2020-02-05 22:16:58 +00:00
2020-05-29 16:53:04 +00:00
ret . LiveDERPs = s . DERPs
2021-11-02 01:40:39 +00:00
ret . LivePeers = map [ key . NodePublic ] ipnstate . PeerStatusLite { }
2020-02-05 22:16:58 +00:00
for _ , p := range s . Peers {
2020-05-15 20:13:44 +00:00
if ! p . LastHandshake . IsZero ( ) {
2020-10-29 22:26:10 +00:00
fmt . Fprintf ( & peerStats , "%d/%d " , p . RxBytes , p . TxBytes )
fmt . Fprintf ( & peerKeys , "%s " , p . NodeKey . ShortString ( ) )
2020-05-19 02:32:20 +00:00
ret . NumLive ++
2021-11-02 01:40:39 +00:00
ret . LivePeers [ p . NodeKey ] = p
2020-05-15 20:13:44 +00:00
2020-02-05 22:16:58 +00:00
}
2020-05-19 02:32:20 +00:00
ret . RBytes += p . RxBytes
ret . WBytes += p . TxBytes
2020-05-12 16:14:37 +00:00
}
2020-10-29 22:26:10 +00:00
// [GRINDER STATS LINES] - please don't remove (used for log parsing)
if peerStats . Len ( ) > 0 {
2020-12-21 18:58:06 +00:00
b . keyLogf ( "[v1] peer keys: %s" , strings . TrimSpace ( peerKeys . String ( ) ) )
2023-04-26 17:04:06 +00:00
b . statsLogf ( "[v1] v%v peers: %v" , version . Long ( ) , strings . TrimSpace ( peerStats . String ( ) ) )
2020-02-05 22:16:58 +00:00
}
2020-05-19 02:32:20 +00:00
return ret
2020-02-05 22:16:58 +00:00
}
2021-01-11 22:24:32 +00:00
// shouldUploadServices reports whether this node should include services
// in Hostinfo. When the user preferences currently request "shields up"
// mode, all inbound connections are refused, so services are not reported.
// Otherwise, shouldUploadServices respects NetMap.CollectServices.
func ( b * LocalBackend ) shouldUploadServices ( ) bool {
2020-02-05 22:16:58 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-11-09 05:58:10 +00:00
p := b . pm . CurrentPrefs ( )
if ! p . Valid ( ) || b . netMap == nil {
2021-01-11 22:24:32 +00:00
return false // default to safest setting
2020-05-19 02:32:20 +00:00
}
2022-11-09 05:58:10 +00:00
return ! p . ShieldsUp ( ) && b . netMap . CollectServices
2020-02-05 22:16:58 +00:00
}
ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.
The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.
This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).
Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.
I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.
Updates https://github.com/tailscale/tailscale/issues/755
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-10-25 20:48:05 +00:00
// SetCurrentUser is used to implement support for multi-user systems (only
2022-11-25 11:52:47 +00:00
// Windows 2022-11-25). On such systems, the uid is used to determine which
// user's state should be used. The current user is maintained by active
// connections open to the backend.
//
// When the backend initially starts it will typically start with no user. Then,
// the first connection to the backend from the GUI frontend will set the
// current user. Once set, the current user cannot be changed until all previous
// connections are closed. The user is also used to determine which
// LoginProfiles are accessible.
//
// In unattended mode, the backend will start with the user which enabled
// unattended mode. The user must disable unattended mode before the user can be
// changed.
//
ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.
The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.
This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).
Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.
I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.
Updates https://github.com/tailscale/tailscale/issues/755
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-10-25 20:48:05 +00:00
// On non-multi-user systems, the token should be set to nil.
//
// SetCurrentUser returns the ipn.WindowsUserID associated with token
// when successful.
func ( b * LocalBackend ) SetCurrentUser ( token ipnauth . WindowsToken ) ( ipn . WindowsUserID , error ) {
var uid ipn . WindowsUserID
if token != nil {
var err error
uid , err = token . UID ( )
if err != nil {
return "" , err
}
}
2024-04-06 18:05:56 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2022-11-25 14:11:06 +00:00
if b . pm . CurrentUserID ( ) == uid {
ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.
The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.
This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).
Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.
I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.
Updates https://github.com/tailscale/tailscale/issues/755
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-10-25 20:48:05 +00:00
return uid , nil
2022-11-12 07:38:17 +00:00
}
2022-11-25 14:11:06 +00:00
if err := b . pm . SetCurrentUserID ( uid ) ; err != nil {
ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.
The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.
This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).
Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.
I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.
Updates https://github.com/tailscale/tailscale/issues/755
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-10-25 20:48:05 +00:00
return uid , nil
2022-11-12 07:38:17 +00:00
}
ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.
The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.
This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).
Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.
I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.
Updates https://github.com/tailscale/tailscale/issues/755
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-10-25 20:48:05 +00:00
if b . currentUser != nil {
b . currentUser . Close ( )
}
b . currentUser = token
2024-04-06 18:05:56 +00:00
b . resetForProfileChangeLockedOnEntry ( unlock )
ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.
The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.
This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).
Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.
I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.
Updates https://github.com/tailscale/tailscale/issues/755
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-10-25 20:48:05 +00:00
return uid , nil
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
}
2022-04-18 16:37:23 +00:00
func ( b * LocalBackend ) CheckPrefs ( p * ipn . Prefs ) error {
b . mu . Lock ( )
defer b . mu . Unlock ( )
return b . checkPrefsLocked ( p )
}
2023-10-20 22:37:25 +00:00
// isConfigLocked_Locked reports whether the parsed config file is locked.
// b.mu must be held.
func ( b * LocalBackend ) isConfigLocked_Locked ( ) bool {
// TODO(bradfitz,maisem): make this more fine-grained, permit changing
// some things if they're not explicitly set in the config. But for now
// (2023-10-16), just blanket disable everything.
return b . conf != nil && ! b . conf . Parsed . Locked . EqualBool ( false )
}
2022-04-18 16:37:23 +00:00
func ( b * LocalBackend ) checkPrefsLocked ( p * ipn . Prefs ) error {
2023-10-20 22:37:25 +00:00
if b . isConfigLocked_Locked ( ) {
2023-10-16 19:15:03 +00:00
return errors . New ( "can't reconfigure tailscaled when using a config file; config file is locked" )
}
2022-06-17 19:09:23 +00:00
var errs [ ] error
2022-04-18 16:37:23 +00:00
if p . Hostname == "badhostname.tailscale." {
// Keep this one just for testing.
2022-06-17 19:09:23 +00:00
errs = append ( errs , errors . New ( "bad hostname [test]" ) )
2022-04-18 16:37:23 +00:00
}
2022-11-18 09:36:45 +00:00
if err := b . checkProfileNameLocked ( p ) ; err != nil {
errs = append ( errs , err )
}
2022-06-17 19:09:23 +00:00
if err := b . checkSSHPrefsLocked ( p ) ; err != nil {
errs = append ( errs , err )
}
2022-11-18 13:07:55 +00:00
if err := b . checkExitNodePrefsLocked ( p ) ; err != nil {
errs = append ( errs , err )
}
2023-04-05 02:20:27 +00:00
if err := b . checkFunnelEnabledLocked ( p ) ; err != nil {
errs = append ( errs , err )
}
2024-04-19 20:37:21 +00:00
if err := b . checkAutoUpdatePrefsLocked ( p ) ; err != nil {
errs = append ( errs , err )
}
2022-06-17 19:09:23 +00:00
return multierr . New ( errs ... )
}
func ( b * LocalBackend ) checkSSHPrefsLocked ( p * ipn . Prefs ) error {
if ! p . RunSSH {
return nil
}
2023-11-30 18:01:29 +00:00
if err := envknob . CanRunTailscaleSSH ( ) ; err != nil {
return err
2022-06-17 19:09:23 +00:00
}
2023-11-30 18:01:29 +00:00
if runtime . GOOS == "linux" {
b . updateSELinuxHealthWarning ( )
2022-06-17 19:09:23 +00:00
}
if envknob . SSHIgnoreTailnetPolicy ( ) || envknob . SSHPolicyFile ( ) != "" {
return nil
}
if b . netMap != nil {
2024-03-22 21:33:41 +00:00
if ! b . netMap . HasCap ( tailcfg . CapabilitySSH ) {
2022-06-17 19:09:23 +00:00
if b . isDefaultServerLocked ( ) {
return errors . New ( "Unable to enable local Tailscale SSH server; not enabled on Tailnet. See https://tailscale.com/s/ssh" )
}
return errors . New ( "Unable to enable local Tailscale SSH server; not enabled on Tailnet." )
2022-04-20 18:22:54 +00:00
}
2022-04-18 16:37:23 +00:00
}
return nil
}
2022-06-17 19:09:23 +00:00
func ( b * LocalBackend ) sshOnButUnusableHealthCheckMessageLocked ( ) ( healthMessage string ) {
2022-11-09 05:58:10 +00:00
if p := b . pm . CurrentPrefs ( ) ; ! p . Valid ( ) || ! p . RunSSH ( ) {
2022-06-17 19:09:23 +00:00
return ""
}
if envknob . SSHIgnoreTailnetPolicy ( ) || envknob . SSHPolicyFile ( ) != "" {
return "development SSH policy in use"
}
nm := b . netMap
if nm == nil {
return ""
}
if nm . SSHPolicy != nil && len ( nm . SSHPolicy . Rules ) > 0 {
return ""
}
isDefault := b . isDefaultServerLocked ( )
2024-03-22 21:33:41 +00:00
if ! nm . HasCap ( tailcfg . CapabilityAdmin ) {
2022-11-11 17:43:49 +00:00
return healthmsg . TailscaleSSHOnBut + "access controls don't allow anyone to access this device. Ask your admin to update your tailnet's ACLs to allow access."
2022-06-17 19:09:23 +00:00
}
if ! isDefault {
2022-11-11 17:43:49 +00:00
return healthmsg . TailscaleSSHOnBut + "access controls don't allow anyone to access this device. Update your tailnet's ACLs to allow access."
2022-06-17 19:09:23 +00:00
}
2022-11-11 17:43:49 +00:00
return healthmsg . TailscaleSSHOnBut + "access controls don't allow anyone to access this device. Update your tailnet's ACLs at https://tailscale.com/s/ssh-policy"
2022-06-17 19:09:23 +00:00
}
func ( b * LocalBackend ) isDefaultServerLocked ( ) bool {
2022-11-09 05:58:10 +00:00
prefs := b . pm . CurrentPrefs ( )
if ! prefs . Valid ( ) {
2022-06-17 19:09:23 +00:00
return true // assume true until set otherwise
}
2022-11-09 05:58:10 +00:00
return prefs . ControlURLOrDefault ( ) == ipn . DefaultControlURL
2022-06-17 19:09:23 +00:00
}
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
var exitNodeMisconfigurationWarnable = health . Register ( & health . Warnable {
Code : "exit-node-misconfiguration" ,
Title : "Exit node misconfiguration" ,
Severity : health . SeverityMedium ,
Text : func ( args health . Args ) string {
return "Exit node misconfiguration: " + args [ health . ArgError ]
} ,
} )
2024-01-03 00:23:58 +00:00
// updateExitNodeUsageWarning updates a warnable meant to notify users of
// configuration issues that could break exit node usage.
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
func updateExitNodeUsageWarning ( p ipn . PrefsView , state * netmon . State , healthTracker * health . Tracker ) {
var msg string
2024-01-03 00:23:58 +00:00
if p . ExitNodeIP ( ) . IsValid ( ) || p . ExitNodeID ( ) != "" {
warn , _ := netutil . CheckReversePathFiltering ( state )
const comment = "please set rp_filter=2 instead of rp_filter=1; see https://github.com/tailscale/tailscale/issues/3310"
if len ( warn ) > 0 {
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
msg = fmt . Sprintf ( "%s: %v, %s" , healthmsg . WarnExitNodeUsage , warn , comment )
2024-01-03 00:23:58 +00:00
}
}
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
if len ( msg ) > 0 {
healthTracker . SetUnhealthy ( exitNodeMisconfigurationWarnable , health . Args { health . ArgError : msg } )
} else {
healthTracker . SetHealthy ( exitNodeMisconfigurationWarnable )
}
2024-01-03 00:23:58 +00:00
}
2022-11-18 13:07:55 +00:00
func ( b * LocalBackend ) checkExitNodePrefsLocked ( p * ipn . Prefs ) error {
if ( p . ExitNodeIP . IsValid ( ) || p . ExitNodeID != "" ) && p . AdvertisesExitNode ( ) {
return errors . New ( "Cannot advertise an exit node and use an exit node at the same time." )
}
return nil
}
2023-04-05 02:20:27 +00:00
func ( b * LocalBackend ) checkFunnelEnabledLocked ( p * ipn . Prefs ) error {
if p . ShieldsUp && b . serveConfig . IsFunnelOn ( ) {
return errors . New ( "Cannot enable shields-up when Funnel is enabled." )
}
return nil
}
2024-04-19 20:37:21 +00:00
func ( b * LocalBackend ) checkAutoUpdatePrefsLocked ( p * ipn . Prefs ) error {
if p . AutoUpdate . Apply . EqualBool ( true ) && ! clientupdate . CanAutoUpdate ( ) {
return errors . New ( "Auto-updates are not supported on this platform." )
}
return nil
}
2024-04-03 17:51:51 +00:00
// SetUseExitNodeEnabled turns on or off the most recently selected exit node.
//
// On success, it returns the resulting prefs (or current prefs, in the case of no change).
// Setting the value to false when use of an exit node is already false is not an error,
// nor is true when the exit node is already in use.
func ( b * LocalBackend ) SetUseExitNodeEnabled ( v bool ) ( ipn . PrefsView , error ) {
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
p0 := b . pm . CurrentPrefs ( )
if v && p0 . ExitNodeID ( ) != "" {
// Already on.
return p0 , nil
}
if ! v && p0 . ExitNodeID ( ) == "" {
// Already off.
return p0 , nil
}
var zero ipn . PrefsView
if v && p0 . InternalExitNodePrior ( ) == "" {
if ! p0 . ExitNodeIP ( ) . IsValid ( ) {
return zero , errors . New ( "no exit node IP to enable & prior exit node IP was never resolved an a node" )
}
return zero , errors . New ( "no prior exit node to enable" )
}
mp := & ipn . MaskedPrefs { }
if v {
mp . ExitNodeIDSet = true
mp . ExitNodeID = tailcfg . StableNodeID ( p0 . InternalExitNodePrior ( ) )
} else {
mp . ExitNodeIDSet = true
mp . ExitNodeID = ""
mp . InternalExitNodePriorSet = true
2024-04-16 18:53:56 +00:00
mp . InternalExitNodePrior = p0 . ExitNodeID ( )
2024-04-03 17:51:51 +00:00
}
return b . editPrefsLockedOnEntry ( mp , unlock )
}
2024-04-15 18:30:00 +00:00
// MaybeClearAppConnector clears the routes from any AppConnector if
// AdvertiseRoutes has been set in the MaskedPrefs.
func ( b * LocalBackend ) MaybeClearAppConnector ( mp * ipn . MaskedPrefs ) error {
var err error
if b . appConnector != nil && mp . AdvertiseRoutesSet {
err = b . appConnector . ClearRoutes ( )
if err != nil {
b . logf ( "appc: clear routes error: %v" , err )
}
}
return err
}
2022-10-23 17:07:10 +00:00
func ( b * LocalBackend ) EditPrefs ( mp * ipn . MaskedPrefs ) ( ipn . PrefsView , error ) {
2024-04-03 17:51:51 +00:00
if mp . SetsInternal ( ) {
return ipn . PrefsView { } , errors . New ( "can't set Internal fields" )
}
2024-04-16 18:53:56 +00:00
// Zeroing the ExitNodeId via localAPI must also zero the prior exit node.
if mp . ExitNodeIDSet && mp . ExitNodeID == "" {
mp . InternalExitNodePrior = ""
mp . InternalExitNodePriorSet = true
}
2024-04-07 04:16:00 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2024-04-03 17:51:51 +00:00
return b . editPrefsLockedOnEntry ( mp , unlock )
}
// Warning: b.mu must be held on entry, but it unlocks it on the way out.
// TODO(bradfitz): redo the locking on all these weird methods like this.
func ( b * LocalBackend ) editPrefsLockedOnEntry ( mp * ipn . MaskedPrefs , unlock unlockOnce ) ( ipn . PrefsView , error ) {
defer unlock ( ) // for error paths
2024-04-07 04:16:00 +00:00
2022-09-01 16:27:06 +00:00
if mp . EggSet {
mp . EggSet = false
b . egg = true
2023-10-23 17:18:40 +00:00
go b . doSetHostinfoFilterServices ( )
2022-09-01 16:27:06 +00:00
}
2022-11-09 05:58:10 +00:00
p0 := b . pm . CurrentPrefs ( )
p1 := b . pm . CurrentPrefs ( ) . AsStruct ( )
2021-04-01 04:35:21 +00:00
p1 . ApplyEdits ( mp )
2022-04-18 16:37:23 +00:00
if err := b . checkPrefsLocked ( p1 ) ; err != nil {
b . logf ( "EditPrefs check error: %v" , err )
2022-10-23 17:07:10 +00:00
return ipn . PrefsView { } , err
2022-04-18 16:37:23 +00:00
}
2022-09-14 19:49:39 +00:00
if p1 . RunSSH && ! envknob . CanSSHD ( ) {
2022-03-23 20:52:29 +00:00
b . logf ( "EditPrefs requests SSH, but disabled by envknob; returning error" )
2022-10-23 17:07:10 +00:00
return ipn . PrefsView { } , errors . New ( "Tailscale SSH server administratively disabled." )
2022-03-23 20:52:29 +00:00
}
2022-10-23 17:07:10 +00:00
if p1 . View ( ) . Equals ( p0 ) {
2022-10-24 00:15:04 +00:00
return stripKeysFromPrefs ( p0 ) , nil
2020-08-11 02:42:04 +00:00
}
2021-04-01 04:35:21 +00:00
b . logf ( "EditPrefs: %v" , mp . Pretty ( ) )
2024-04-15 02:47:32 +00:00
newPrefs := b . setPrefsLockedOnEntry ( p1 , unlock )
2021-04-11 04:56:18 +00:00
2021-04-30 08:29:22 +00:00
// Note: don't perform any actions for the new prefs here. Not
// every prefs change goes through EditPrefs. Put your actions
// in setPrefsLocksOnEntry instead.
2022-10-24 00:15:04 +00:00
// This should return the public prefs, not the private ones.
return stripKeysFromPrefs ( newPrefs ) , nil
2020-08-11 02:42:04 +00:00
}
2022-11-18 09:36:45 +00:00
func ( b * LocalBackend ) checkProfileNameLocked ( p * ipn . Prefs ) error {
if p . ProfileName == "" {
// It is always okay to clear the profile name.
return nil
}
id := b . pm . ProfileIDForName ( p . ProfileName )
if id == "" {
// No profile with that name exists. That's fine.
return nil
}
if id != b . pm . CurrentProfile ( ) . ID {
// Name is already in use by another profile.
return fmt . Errorf ( "profile name %q already in use" , p . ProfileName )
}
return nil
}
2022-11-16 20:51:26 +00:00
// wantIngressLocked reports whether this node has ingress configured. This bool
// is sent to the coordination server (in Hostinfo.WireIngress) as an
// optimization hint to know primarily which nodes are NOT using ingress, to
// avoid doing work for regular nodes.
//
2022-11-17 21:09:43 +00:00
// Even if the user's ServeConfig.AllowFunnel map was manually edited in raw
2022-11-16 20:51:26 +00:00
// mode and contains map entries with false values, sending true (from Len > 0)
// is still fine. This is only an optimization hint for the control plane and
// doesn't affect security or correctness. And we also don't expect people to
// modify their ServeConfig in raw mode.
func ( b * LocalBackend ) wantIngressLocked ( ) bool {
2023-09-05 17:51:52 +00:00
return b . serveConfig . Valid ( ) && b . serveConfig . HasAllowFunnel ( )
2022-11-16 20:51:26 +00:00
}
2021-04-01 04:35:21 +00:00
// setPrefsLockedOnEntry requires b.mu be held to call it, but it
2021-12-01 23:33:14 +00:00
// unlocks b.mu when done. newp ownership passes to this function.
2022-10-24 00:15:04 +00:00
// It returns a readonly copy of the new prefs.
2024-04-15 02:47:32 +00:00
func ( b * LocalBackend ) setPrefsLockedOnEntry ( newp * ipn . Prefs , unlock unlockOnce ) ipn . PrefsView {
2024-04-07 04:16:00 +00:00
defer unlock ( )
2020-07-29 01:47:23 +00:00
netMap := b . netMap
2022-11-16 20:51:26 +00:00
b . setAtomicValuesFromPrefsLocked ( newp . View ( ) )
2022-10-23 17:07:10 +00:00
2022-11-09 05:58:10 +00:00
oldp := b . pm . CurrentPrefs ( )
if oldp . Valid ( ) {
2022-11-29 20:00:40 +00:00
newp . Persist = oldp . Persist ( ) . AsStruct ( ) // caller isn't allowed to override this
2022-11-09 05:58:10 +00:00
}
2023-11-01 21:20:25 +00:00
// setExitNodeID returns whether it updated b.prefs, but
2021-12-01 23:33:14 +00:00
// everything in this function treats b.prefs as completely new
// anyway. No-op if no exit node resolution is needed.
2023-08-04 05:37:52 +00:00
setExitNodeID ( newp , netMap )
2023-11-01 21:20:25 +00:00
// applySysPolicy does likewise so we can also ignore its return value.
applySysPolicy ( newp )
2020-07-29 01:47:23 +00:00
// We do this to avoid holding the lock while doing everything else.
2020-06-15 23:04:12 +00:00
oldHi := b . hostinfo
2020-02-27 20:20:29 +00:00
newHi := oldHi . Clone ( )
2023-10-27 21:20:10 +00:00
if newHi == nil {
newHi = new ( tailcfg . Hostinfo )
}
2022-11-16 05:22:09 +00:00
b . applyPrefsToHostinfoLocked ( newHi , newp . View ( ) )
2020-06-15 23:04:12 +00:00
b . hostinfo = newHi
2020-07-08 23:49:02 +00:00
hostInfoChanged := ! oldHi . Equal ( newHi )
2021-04-30 08:29:22 +00:00
cc := b . cc
2020-07-29 01:47:23 +00:00
2022-11-09 05:58:10 +00:00
b . updateFilterLocked ( netMap , newp . View ( ) )
2022-04-17 21:49:16 +00:00
2022-11-09 05:58:10 +00:00
if oldp . ShouldSSHBeRunning ( ) && ! newp . ShouldSSHBeRunning ( ) {
2022-05-30 09:06:46 +00:00
if b . sshServer != nil {
go b . sshServer . Shutdown ( )
b . sshServer = nil
}
}
2020-10-27 19:51:48 +00:00
if netMap != nil {
2023-08-20 22:17:25 +00:00
newProfile := netMap . UserProfiles [ netMap . User ( ) ]
2023-08-04 00:38:28 +00:00
if newLoginName := newProfile . LoginName ; newLoginName != "" {
if ! oldp . Persist ( ) . Valid ( ) {
b . logf ( "active login: %s" , newLoginName )
2022-11-09 05:58:10 +00:00
} else {
2024-02-11 16:35:02 +00:00
oldLoginName := oldp . Persist ( ) . UserProfile ( ) . LoginName
2023-08-04 00:38:28 +00:00
if oldLoginName != newLoginName {
b . logf ( "active login: %q (changed from %q)" , newLoginName , oldLoginName )
2022-11-09 05:58:10 +00:00
}
2023-08-04 00:38:28 +00:00
newp . Persist . UserProfile = newProfile
2020-10-27 19:51:48 +00:00
}
}
}
2020-04-10 15:42:34 +00:00
2022-11-09 05:58:10 +00:00
prefs := newp . View ( )
2023-11-17 02:40:23 +00:00
if err := b . pm . SetPrefs ( prefs , ipn . NetworkProfile {
MagicDNSName : b . netMap . MagicDNSSuffix ( ) ,
DomainName : b . netMap . DomainName ( ) ,
} ) ; err != nil {
2022-11-09 05:58:10 +00:00
b . logf ( "failed to save new controlclient state: %v" , err )
}
2024-04-07 04:16:00 +00:00
2024-06-04 02:24:53 +00:00
if newp . AutoUpdate . Apply . EqualBool ( true ) {
if b . state != ipn . Running {
b . maybeStartOfflineAutoUpdate ( newp . View ( ) )
}
} else {
b . stopOfflineAutoUpdate ( )
}
2024-04-07 04:16:00 +00:00
unlock . UnlockEarly ( )
2022-11-09 05:58:10 +00:00
if oldp . ShieldsUp ( ) != newp . ShieldsUp || hostInfoChanged {
2023-10-23 17:18:40 +00:00
b . doSetHostinfoFilterServices ( )
2020-02-18 03:33:01 +00:00
}
2020-09-18 14:44:01 +00:00
if netMap != nil {
2023-11-15 23:10:45 +00:00
b . MagicConn ( ) . SetDERPMap ( netMap . DERPMap )
2020-06-09 17:09:43 +00:00
}
2020-04-29 06:37:35 +00:00
2022-11-09 05:58:10 +00:00
if ! oldp . WantRunning ( ) && newp . WantRunning {
2021-04-30 08:29:22 +00:00
b . logf ( "transitioning to running; doing Login..." )
2024-05-17 21:54:41 +00:00
cc . Login ( controlclient . LoginDefault )
2021-04-30 08:29:22 +00:00
}
2022-11-09 05:58:10 +00:00
if oldp . WantRunning ( ) != newp . WantRunning {
2020-02-05 22:16:58 +00:00
b . stateMachine ( )
} else {
b . authReconfig ( )
}
2022-12-02 08:54:32 +00:00
b . send ( ipn . Notify { Prefs : & prefs } )
2022-10-24 00:15:04 +00:00
return prefs
2020-02-05 22:16:58 +00:00
}
2022-01-31 17:20:22 +00:00
// GetPeerAPIPort returns the port number for the peerapi server
// running on the provided IP.
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
func ( b * LocalBackend ) GetPeerAPIPort ( ip netip . Addr ) ( port uint16 , ok bool ) {
2021-03-29 22:17:05 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
for _ , pln := range b . peerAPIListeners {
2021-04-07 18:32:53 +00:00
if pln . ip == ip {
2021-04-02 05:04:46 +00:00
return uint16 ( pln . port ) , true
2021-03-29 22:17:05 +00:00
}
}
return 0 , false
}
2023-06-08 23:57:40 +00:00
// handlePeerAPIConn serves an already-accepted connection c.
2022-01-31 17:20:22 +00:00
//
// The remote parameter is the remote address.
2022-09-25 18:29:55 +00:00
// The local parameter is the local address (either a Tailscale IPv4
2022-01-31 17:20:22 +00:00
// or IPv6 IP and the peerapi port for that address).
//
2023-06-08 23:57:40 +00:00
// The connection will be closed by handlePeerAPIConn.
func ( b * LocalBackend ) handlePeerAPIConn ( remote , local netip . AddrPort , c net . Conn ) {
2022-01-31 17:20:22 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
for _ , pln := range b . peerAPIListeners {
2022-07-25 03:08:42 +00:00
if pln . ip == local . Addr ( ) {
2022-01-31 17:20:22 +00:00
go pln . ServeConn ( remote , c )
return
}
}
b . logf ( "[unexpected] no peerAPI listener found for %v" , local )
c . Close ( )
return
}
2023-06-08 23:57:40 +00:00
func ( b * LocalBackend ) isLocalIP ( ip netip . Addr ) bool {
nm := b . NetMap ( )
2023-09-17 17:53:23 +00:00
return nm != nil && views . SliceContains ( nm . GetAddresses ( ) , netip . PrefixFrom ( ip , ip . BitLen ( ) ) )
2023-06-08 23:57:40 +00:00
}
var (
magicDNSIP = tsaddr . TailscaleServiceIP ( )
magicDNSIPv6 = tsaddr . TailscaleServiceIPv6 ( )
)
// TCPHandlerForDst returns a TCP handler for connections to dst, or nil if
// no handler is needed. It also returns a list of TCP socket options to
// apply to the socket before calling the handler.
2024-02-28 17:44:42 +00:00
// TCPHandlerForDst is called both for connections to our node's local IP
// as well as to the service IP (quad 100).
2023-06-08 23:57:40 +00:00
func ( b * LocalBackend ) TCPHandlerForDst ( src , dst netip . AddrPort ) ( handler func ( c net . Conn ) error , opts [ ] tcpip . SettableSocketOption ) {
2024-02-28 17:44:42 +00:00
// First handle internal connections to the service IP
hittingServiceIP := dst . Addr ( ) == magicDNSIP || dst . Addr ( ) == magicDNSIPv6
if hittingServiceIP {
switch dst . Port ( ) {
case 80 :
2024-03-18 21:47:21 +00:00
// TODO(mpminardi): do we want to show an error message if the web client
// has been disabled instead of the more "basic" web UI?
2024-02-28 17:44:42 +00:00
if b . ShouldRunWebClient ( ) {
return b . handleWebClientConn , opts
}
return b . HandleQuad100Port80Conn , opts
2024-04-03 17:09:58 +00:00
case DriveLocalPort :
return b . handleDriveConn , opts
2023-11-03 16:11:46 +00:00
}
2023-06-08 23:57:40 +00:00
}
2024-02-28 17:44:42 +00:00
// Then handle external connections to the local IP.
2023-06-08 23:57:40 +00:00
if ! b . isLocalIP ( dst . Addr ( ) ) {
return nil , nil
}
if dst . Port ( ) == 22 && b . ShouldRunSSH ( ) {
// Use a higher keepalive idle time for SSH connections, as they are
// typically long lived and idle connections are more likely to be
// intentional. Ideally we would turn this off entirely, but we can't
// tell the difference between a long lived connection that is idle
// vs a connection that is dead because the peer has gone away.
// We pick 72h as that is typically sufficient for a long weekend.
opts = append ( opts , ptr . To ( tcpip . KeepaliveIdleOption ( 72 * time . Hour ) ) )
return b . handleSSHConn , opts
}
2023-10-26 18:39:20 +00:00
// TODO(will,sonia): allow customizing web client port ?
2024-03-18 21:47:21 +00:00
if dst . Port ( ) == webClientPort && b . ShouldExposeRemoteWebClient ( ) {
2023-10-26 18:39:20 +00:00
return b . handleWebClientConn , opts
}
2023-06-08 23:57:40 +00:00
if port , ok := b . GetPeerAPIPort ( dst . Addr ( ) ) ; ok && dst . Port ( ) == port {
return func ( c net . Conn ) error {
b . handlePeerAPIConn ( src , dst , c )
return nil
} , opts
}
if handler := b . tcpHandlerForServe ( dst . Port ( ) , src ) ; handler != nil {
return handler , opts
}
return nil , nil
}
2024-04-03 17:09:58 +00:00
func ( b * LocalBackend ) handleDriveConn ( conn net . Conn ) error {
fs , ok := b . sys . DriveForLocal . GetOK ( )
if ! ok || ! b . DriveAccessEnabled ( ) {
2024-02-28 17:44:42 +00:00
conn . Close ( )
return nil
}
return fs . HandleConn ( conn , conn . RemoteAddr ( ) )
}
2021-03-29 19:49:13 +00:00
func ( b * LocalBackend ) peerAPIServicesLocked ( ) ( ret [ ] tailcfg . Service ) {
for _ , pln := range b . peerAPIListeners {
2021-11-30 01:19:17 +00:00
proto := tailcfg . PeerAPI4
2021-03-29 19:49:13 +00:00
if pln . ip . Is6 ( ) {
2021-11-30 01:19:17 +00:00
proto = tailcfg . PeerAPI6
2021-03-29 19:49:13 +00:00
}
ret = append ( ret , tailcfg . Service {
Proto : proto ,
2021-04-02 05:04:46 +00:00
Port : uint16 ( pln . port ) ,
2021-03-29 19:49:13 +00:00
} )
}
2021-11-30 01:19:17 +00:00
switch runtime . GOOS {
2023-10-05 19:18:21 +00:00
case "linux" , "freebsd" , "openbsd" , "illumos" , "darwin" , "windows" , "android" , "ios" :
2021-11-30 01:19:17 +00:00
// These are the platforms currently supported by
// net/dns/resolver/tsdns.go:Resolver.HandleExitNodeDNSQuery.
ret = append ( ret , tailcfg . Service {
Proto : tailcfg . PeerAPIDNS ,
Port : 1 , // version
} )
}
2021-03-29 19:49:13 +00:00
return ret
}
2020-05-19 02:32:20 +00:00
// doSetHostinfoFilterServices calls SetHostinfo on the controlclient,
// possibly after mangling the given hostinfo.
//
// TODO(danderson): we shouldn't be mangling hostinfo here after
// painstakingly constructing it in twelvety other places.
2023-10-23 17:18:40 +00:00
func ( b * LocalBackend ) doSetHostinfoFilterServices ( ) {
2024-04-07 04:16:00 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2021-04-08 04:12:16 +00:00
cc := b . cc
2021-03-29 19:49:13 +00:00
if cc == nil {
// Control client isn't up yet.
return
}
2023-10-23 17:18:40 +00:00
if b . hostinfo == nil {
b . logf ( "[unexpected] doSetHostinfoFilterServices with nil hostinfo" )
return
}
2021-03-29 19:49:13 +00:00
peerAPIServices := b . peerAPIServicesLocked ( )
2022-09-01 16:27:06 +00:00
if b . egg {
2022-10-18 04:28:32 +00:00
peerAPIServices = append ( peerAPIServices , tailcfg . Service { Proto : "egg" , Port : 1 } )
2022-09-01 16:27:06 +00:00
}
2023-10-23 17:18:40 +00:00
// TODO(maisem,bradfitz): store hostinfo as a view, not as a mutable struct.
hi := * b . hostinfo // shallow copy
2024-04-07 04:16:00 +00:00
unlock . UnlockEarly ( )
2020-04-29 09:23:29 +00:00
2021-03-29 19:49:13 +00:00
// Make a shallow copy of hostinfo so we can mutate
// at the Service field.
if ! b . shouldUploadServices ( ) {
2023-10-23 17:18:40 +00:00
hi . Services = [ ] tailcfg . Service { }
2020-04-29 09:23:29 +00:00
}
2021-03-29 19:49:13 +00:00
// Don't mutate hi.Service's underlying array. Append to
// the slice with no free capacity.
2023-10-23 17:18:40 +00:00
c := len ( hi . Services )
hi . Services = append ( hi . Services [ : c : c ] , peerAPIServices ... )
2023-10-23 17:22:34 +00:00
hi . PushDeviceToken = b . pushDeviceToken . Load ( )
2023-10-23 17:18:40 +00:00
cc . SetHostinfo ( & hi )
2020-04-29 09:23:29 +00:00
}
2020-05-19 02:32:20 +00:00
// NetMap returns the latest cached network map received from
// controlclient, or nil if no network map was received yet.
2021-02-05 23:44:46 +00:00
func ( b * LocalBackend ) NetMap ( ) * netmap . NetworkMap {
2020-06-24 20:55:56 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2020-06-15 23:04:12 +00:00
return b . netMap
2020-02-05 22:16:58 +00:00
}
2021-11-04 19:19:00 +00:00
func ( b * LocalBackend ) isEngineBlocked ( ) bool {
b . mu . Lock ( )
defer b . mu . Unlock ( )
return b . blocked
}
2020-05-19 02:32:20 +00:00
// blockEngineUpdate sets b.blocked to block, while holding b.mu. Its
// indirect effect is to turn b.authReconfig() into a no-op if block
// is true.
2020-02-05 22:16:58 +00:00
func ( b * LocalBackend ) blockEngineUpdates ( block bool ) {
2020-04-11 15:35:34 +00:00
b . logf ( "blockEngineUpdates(%v)" , block )
2020-02-05 22:16:58 +00:00
b . mu . Lock ( )
b . blocked = block
b . mu . Unlock ( )
}
2023-10-31 21:59:18 +00:00
// reconfigAppConnectorLocked updates the app connector state based on the
// current network map and preferences.
// b.mu must be held.
func ( b * LocalBackend ) reconfigAppConnectorLocked ( nm * netmap . NetworkMap , prefs ipn . PrefsView ) {
const appConnectorCapName = "tailscale.com/app-connectors"
2023-11-10 02:00:56 +00:00
defer func ( ) {
if b . hostinfo != nil {
b . hostinfo . AppConnector . Set ( b . appConnector != nil )
}
} ( )
2023-10-31 21:59:18 +00:00
if ! prefs . AppConnector ( ) . Advertise {
2023-11-10 05:22:16 +00:00
b . appConnector = nil
2023-10-31 21:59:18 +00:00
return
}
2024-04-11 17:12:13 +00:00
shouldAppCStoreRoutes := b . ControlKnobs ( ) . AppCStoreRoutes . Load ( )
if b . appConnector == nil || b . appConnector . ShouldStoreRoutes ( ) != shouldAppCStoreRoutes {
var ri * appc . RouteInfo
var storeFunc func ( * appc . RouteInfo ) error
if shouldAppCStoreRoutes {
var err error
ri , err = b . readRouteInfoLocked ( )
if err != nil {
ri = & appc . RouteInfo { }
if err != ipn . ErrStateNotExist {
b . logf ( "Unsuccessful Read RouteInfo: " , err )
}
}
storeFunc = b . storeRouteInfo
}
b . appConnector = appc . NewAppConnector ( b . logf , b , ri , storeFunc )
2023-10-31 21:59:18 +00:00
}
if nm == nil {
return
}
// TODO(raggi): rework the view infrastructure so the large deep clone is no
// longer required
sn := nm . SelfNode . AsStruct ( )
attrs , err := tailcfg . UnmarshalNodeCapJSON [ appctype . AppConnectorAttr ] ( sn . CapMap , appConnectorCapName )
if err != nil {
b . logf ( "[unexpected] error parsing app connector mapcap: %v" , err )
return
}
2023-11-22 22:12:50 +00:00
// Geometric cost, assumes that the number of advertised tags is small
selfHasTag := func ( attrTags [ ] string ) bool {
return nm . SelfNode . Tags ( ) . ContainsFunc ( func ( tag string ) bool {
return slices . Contains ( attrTags , tag )
} )
}
2024-01-17 19:35:55 +00:00
var (
domains [ ] string
routes [ ] netip . Prefix
)
2023-10-31 21:59:18 +00:00
for _ , attr := range attrs {
2023-11-22 22:12:50 +00:00
if slices . Contains ( attr . Connectors , "*" ) || selfHasTag ( attr . Connectors ) {
domains = append ( domains , attr . Domains ... )
2024-01-17 19:35:55 +00:00
routes = append ( routes , attr . Routes ... )
2023-10-31 21:59:18 +00:00
}
}
slices . Sort ( domains )
2024-01-17 19:35:55 +00:00
slices . SortFunc ( routes , func ( i , j netip . Prefix ) int { return i . Addr ( ) . Compare ( j . Addr ( ) ) } )
2023-12-14 16:55:34 +00:00
domains = slices . Compact ( domains )
2024-01-17 19:35:55 +00:00
routes = slices . Compact ( routes )
2024-01-18 18:18:25 +00:00
b . appConnector . UpdateDomainsAndRoutes ( domains , routes )
2023-10-31 21:59:18 +00:00
}
2020-05-19 02:32:20 +00:00
// authReconfig pushes a new configuration into wgengine, if engine
// updates are not currently blocked, based on the cached netmap and
// user prefs.
2020-02-05 22:16:58 +00:00
func ( b * LocalBackend ) authReconfig ( ) {
b . mu . Lock ( )
blocked := b . blocked
2022-11-09 05:58:10 +00:00
prefs := b . pm . CurrentPrefs ( )
2020-06-15 23:04:12 +00:00
nm := b . netMap
2020-10-05 22:12:35 +00:00
hasPAC := b . prevIfState . HasPAC ( )
2024-03-22 21:33:41 +00:00
disableSubnetsIfPAC := nm . HasCap ( tailcfg . NodeAttrDisableSubnetsIfPAC )
2024-05-02 19:36:26 +00:00
userDialUseRoutes := nm . HasCap ( tailcfg . NodeAttrUserDialUseRoutes )
2023-09-17 07:13:52 +00:00
dohURL , dohURLOK := exitNodeCanProxyDNS ( nm , b . peers , prefs . ExitNodeID ( ) )
dcfg := dnsConfigForNetmap ( nm , b . peers , prefs , b . logf , version . OS ( ) )
2023-10-27 21:20:10 +00:00
// If the current node is an app connector, ensure the app connector machine is started
2023-10-31 21:59:18 +00:00
b . reconfigAppConnectorLocked ( nm , prefs )
2020-02-05 22:16:58 +00:00
b . mu . Unlock ( )
if blocked {
2022-02-12 16:05:24 +00:00
b . logf ( "[v1] authReconfig: blocked, skipping." )
2020-02-05 22:16:58 +00:00
return
}
if nm == nil {
2022-02-12 16:05:24 +00:00
b . logf ( "[v1] authReconfig: netmap not yet valid. Skipping." )
2020-02-05 22:16:58 +00:00
return
}
2022-10-23 17:07:10 +00:00
if ! prefs . WantRunning ( ) {
2022-02-12 16:05:24 +00:00
b . logf ( "[v1] authReconfig: skipping because !WantRunning." )
2020-02-05 22:16:58 +00:00
return
}
2021-02-05 23:44:46 +00:00
var flags netmap . WGConfigFlags
2022-10-23 17:07:10 +00:00
if prefs . RouteAll ( ) {
2021-02-05 23:44:46 +00:00
flags |= netmap . AllowSubnetRoutes
2020-02-05 22:16:58 +00:00
}
2020-11-10 18:31:07 +00:00
if hasPAC && disableSubnetsIfPAC {
2021-02-05 23:44:46 +00:00
if flags & netmap . AllowSubnetRoutes != 0 {
2020-10-05 22:12:35 +00:00
b . logf ( "authReconfig: have PAC; disabling subnet routes" )
2021-02-05 23:44:46 +00:00
flags &^= netmap . AllowSubnetRoutes
2020-10-05 22:12:35 +00:00
}
}
2020-02-05 22:16:58 +00:00
2021-12-03 16:33:05 +00:00
// Keep the dialer updated about whether we're supposed to use
// an exit node's DNS server (so SOCKS5/HTTP outgoing dials
// can use it for name resolution)
2023-09-17 07:13:52 +00:00
if dohURLOK {
2021-12-03 16:33:05 +00:00
b . dialer . SetExitDNSDoH ( dohURL )
} else {
b . dialer . SetExitDNSDoH ( "" )
}
2022-10-23 17:07:10 +00:00
cfg , err := nmcfg . WGCfg ( nm , b . logf , flags , prefs . ExitNodeID ( ) )
2020-04-10 14:52:30 +00:00
if err != nil {
2020-05-21 19:51:22 +00:00
b . logf ( "wgcfg: %v" , err )
return
2020-04-10 14:52:30 +00:00
}
2020-02-05 22:16:58 +00:00
2023-09-11 19:03:39 +00:00
oneCGNATRoute := shouldUseOneCGNATRoute ( b . logf , b . sys . ControlKnobs ( ) , version . OS ( ) )
2022-04-14 21:40:17 +00:00
rcfg := b . routerConfig ( cfg , prefs , oneCGNATRoute )
2021-09-07 21:38:26 +00:00
2023-08-18 00:29:15 +00:00
err = b . e . Reconfig ( cfg , rcfg , dcfg )
2021-09-07 21:38:26 +00:00
if err == wgengine . ErrNoChanges {
return
}
2022-10-28 22:21:24 +00:00
b . logf ( "[v1] authReconfig: ra=%v dns=%v 0x%02x: %v" , prefs . RouteAll ( ) , prefs . CorpDNS ( ) , flags , err )
2021-09-07 21:38:26 +00:00
2024-05-02 19:36:26 +00:00
if userDialUseRoutes {
b . dialer . SetRoutes ( rcfg . Routes , rcfg . LocalRoutes )
} else {
b . dialer . SetRoutes ( nil , nil )
}
2021-09-07 21:38:26 +00:00
b . initPeerAPIListener ( )
}
2020-07-31 20:27:09 +00:00
2022-06-29 20:25:45 +00:00
// shouldUseOneCGNATRoute reports whether we should prefer to make one big
// CGNAT /10 route rather than a /32 per peer.
//
// The versionOS is a Tailscale-style version ("iOS", "macOS") and not
// a runtime.GOOS.
2023-09-11 19:03:39 +00:00
func shouldUseOneCGNATRoute ( logf logger . Logf , controlKnobs * controlknobs . Knobs , versionOS string ) bool {
if controlKnobs != nil {
// Explicit enabling or disabling always take precedence.
if v , ok := controlKnobs . OneCGNAT . Load ( ) . Get ( ) ; ok {
logf ( "[v1] shouldUseOneCGNATRoute: explicit=%v" , v )
return v
}
2023-08-17 19:29:51 +00:00
}
2022-06-29 20:25:45 +00:00
// Also prefer to do this on the Mac, so that we don't need to constantly
// update the network extension configuration (which is disruptive to
// Chrome, see https://github.com/tailscale/tailscale/issues/3102). Only
// use fine-grained routes if another interfaces is also using the CGNAT
// IP range.
if versionOS == "macOS" {
2024-04-28 04:18:18 +00:00
hasCGNATInterface , err := netmon . HasCGNATInterface ( )
2022-06-29 20:25:45 +00:00
if err != nil {
logf ( "shouldUseOneCGNATRoute: Could not determine if any interfaces use CGNAT: %v" , err )
return false
}
logf ( "[v1] shouldUseOneCGNATRoute: macOS automatic=%v" , ! hasCGNATInterface )
if ! hasCGNATInterface {
return true
}
}
return false
}
2021-09-08 00:58:04 +00:00
// dnsConfigForNetmap returns a *dns.Config for the given netmap,
ipn/ipnlocal, net/dns*, util/cloudenv: specialize DNS config on Google Cloud
This does three things:
* If you're on GCP, it adds a *.internal DNS split route to the
metadata server, so we never break GCP DNS names. This lets people
have some Tailscale nodes on GCP and some not (e.g. laptops at home)
without having to add a Tailnet-wide *.internal DNS route.
If you already have such a route, though, it won't overwrite it.
* If the 100.100.100.100 DNS forwarder has nowhere to forward to,
it forwards it to the GCP metadata IP, which forwards to 8.8.8.8.
This means there are never errNoUpstreams ("upstream nameservers not set")
errors on GCP due to e.g. mangled /etc/resolv.conf (GCP default VMs
don't have systemd-resolved, so it's likely a DNS supremacy fight)
* makes the DNS fallback mechanism use the GCP metadata IP as a
fallback before our hosted HTTP-based fallbacks
I created a default GCP VM from their web wizard. It has no
systemd-resolved.
I then made its /etc/resolv.conf be empty and deleted its GCP
hostnames in /etc/hosts.
I then logged in to a tailnet with no global DNS settings.
With this, tailscaled writes /etc/resolv.conf (direct mode, as no
systemd-resolved) and sets it to 100.100.100.100, which then has
regular DNS via the metadata IP and *.internal DNS via the metadata IP
as well. If the tailnet configures explicit DNS servers, those are used
instead, except for *.internal.
This also adds a new util/cloudenv package based on version/distro
where the cloud type is only detected once. We'll likely expand it in
the future for other clouds, doing variants of this change for other
popular cloud environments.
Fixes #4911
RELNOTES=Google Cloud DNS improvements
Change-Id: I19f3c2075983669b2b2c0f29a548da8de373c7cf
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-06-29 20:19:34 +00:00
// prefs, client OS version, and cloud hosting environment.
2021-09-08 00:58:04 +00:00
//
// The versionOS is a Tailscale-style version ("iOS", "macOS") and not
// a runtime.GOOS.
2023-09-17 07:13:52 +00:00
func dnsConfigForNetmap ( nm * netmap . NetworkMap , peers map [ tailcfg . NodeID ] tailcfg . NodeView , prefs ipn . PrefsView , logf logger . Logf , versionOS string ) * dns . Config {
if nm == nil {
return nil
}
2021-09-07 21:38:26 +00:00
dcfg := & dns . Config {
2022-05-03 21:41:58 +00:00
Routes : map [ dnsname . FQDN ] [ ] * dnstype . Resolver { } ,
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
Hosts : map [ dnsname . FQDN ] [ ] netip . Addr { } ,
2021-05-21 03:22:21 +00:00
}
2021-04-02 07:34:32 +00:00
2021-10-04 14:54:16 +00:00
// selfV6Only is whether we only have IPv6 addresses ourselves.
2024-05-04 01:38:59 +00:00
selfV6Only := nm . GetAddresses ( ) . ContainsFunc ( tsaddr . PrefixIs6 ) &&
! nm . GetAddresses ( ) . ContainsFunc ( tsaddr . PrefixIs4 )
2022-01-04 21:33:08 +00:00
dcfg . OnlyIPv6 = selfV6Only
2021-10-04 14:54:16 +00:00
2021-05-17 22:18:25 +00:00
// Populate MagicDNS records. We do this unconditionally so that
// quad-100 can always respond to MagicDNS queries, even if the OS
// isn't configured to make MagicDNS resolution truly
// magic. Details in
// https://github.com/tailscale/tailscale/issues/1886.
2023-08-18 14:57:44 +00:00
set := func ( name string , addrs views . Slice [ netip . Prefix ] ) {
if addrs . Len ( ) == 0 || name == "" {
2021-05-17 22:18:25 +00:00
return
}
fqdn , err := dnsname . ToFQDN ( name )
if err != nil {
return // TODO: propagate error?
}
2023-08-18 14:57:44 +00:00
var have4 bool
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-08-18 14:57:44 +00:00
if addrs . At ( i ) . Addr ( ) . Is4 ( ) {
have4 = true
break
}
}
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
var ips [ ] netip . Addr
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-08-18 14:57:44 +00:00
addr := addrs . At ( i )
2021-10-04 14:54:16 +00:00
if selfV6Only {
2022-07-25 03:08:42 +00:00
if addr . Addr ( ) . Is6 ( ) {
ips = append ( ips , addr . Addr ( ) )
2021-10-04 14:54:16 +00:00
}
continue
}
// If this node has an IPv4 address, then
// remove peers' IPv6 addresses for now, as we
// don't guarantee that the peer node actually
// can speak IPv6 correctly.
2021-05-17 22:18:25 +00:00
//
// https://github.com/tailscale/tailscale/issues/1152
// tracks adding the right capability reporting to
// enable AAAA in MagicDNS.
2022-07-25 03:08:42 +00:00
if addr . Addr ( ) . Is6 ( ) && have4 {
2021-05-17 22:18:25 +00:00
continue
}
2022-07-25 03:08:42 +00:00
ips = append ( ips , addr . Addr ( ) )
2021-05-17 22:18:25 +00:00
}
dcfg . Hosts [ fqdn ] = ips
}
2023-09-18 06:31:34 +00:00
set ( nm . Name , nm . GetAddresses ( ) )
2023-09-17 07:13:52 +00:00
for _ , peer := range peers {
2023-08-18 14:57:44 +00:00
set ( peer . Name ( ) , peer . Addresses ( ) )
2021-05-17 22:18:25 +00:00
}
2021-06-16 17:58:25 +00:00
for _ , rec := range nm . DNS . ExtraRecords {
switch rec . Type {
case "" , "A" , "AAAA" :
// Treat these all the same for now: infer from the value
default :
// TODO: more
continue
}
2022-07-26 03:55:44 +00:00
ip , err := netip . ParseAddr ( rec . Value )
2021-06-16 17:58:25 +00:00
if err != nil {
// Ignore.
continue
}
fqdn , err := dnsname . ToFQDN ( rec . Name )
if err != nil {
continue
}
dcfg . Hosts [ fqdn ] = append ( dcfg . Hosts [ fqdn ] , ip )
}
2021-05-17 22:18:25 +00:00
2022-10-23 17:07:10 +00:00
if ! prefs . CorpDNS ( ) {
2021-09-07 21:56:45 +00:00
return dcfg
}
2021-11-30 23:19:18 +00:00
for _ , dom := range nm . DNS . Domains {
fqdn , err := dnsname . ToFQDN ( dom )
if err != nil {
logf ( "[unexpected] non-FQDN search domain %q" , dom )
}
dcfg . SearchDomains = append ( dcfg . SearchDomains , fqdn )
}
if nm . DNS . Proxied { // actually means "enable MagicDNS"
for _ , dom := range magicDNSRootDomains ( nm ) {
dcfg . Routes [ dom ] = nil // resolve internally with dcfg.Hosts
}
}
2022-05-03 21:41:58 +00:00
addDefault := func ( resolvers [ ] * dnstype . Resolver ) {
2023-09-20 20:07:48 +00:00
dcfg . DefaultResolvers = append ( dcfg . DefaultResolvers , resolvers ... )
2021-09-07 21:56:45 +00:00
}
2021-04-20 04:58:26 +00:00
2021-11-30 23:19:18 +00:00
// If we're using an exit node and that exit node is new enough (1.19.x+)
// to run a DoH DNS proxy, then send all our DNS traffic through it.
2023-09-17 07:13:52 +00:00
if dohURL , ok := exitNodeCanProxyDNS ( nm , peers , prefs . ExitNodeID ( ) ) ; ok {
2022-05-03 21:41:58 +00:00
addDefault ( [ ] * dnstype . Resolver { { Addr : dohURL } } )
2021-11-30 23:19:18 +00:00
return dcfg
}
2023-09-20 20:07:48 +00:00
// If the user has set default resolvers ("override local DNS"), prefer to
// use those resolvers as the default, otherwise if there are WireGuard exit
// node resolvers, use those as the default.
if len ( nm . DNS . Resolvers ) > 0 {
addDefault ( nm . DNS . Resolvers )
} else {
if resolvers , ok := wireguardExitNodeDNSResolvers ( nm , peers , prefs . ExitNodeID ( ) ) ; ok {
addDefault ( resolvers )
}
}
2021-09-07 21:56:45 +00:00
for suffix , resolvers := range nm . DNS . Routes {
fqdn , err := dnsname . ToFQDN ( suffix )
if err != nil {
logf ( "[unexpected] non-FQDN route suffix %q" , suffix )
}
2021-08-25 16:07:21 +00:00
2021-09-07 21:56:45 +00:00
// Create map entry even if len(resolvers) == 0; Issue 2706.
// This lets the control plane send ExtraRecords for which we
// can authoritatively answer "name not exists" for when the
// control plane also sends this explicit but empty route
// making it as something we handle.
//
// While we're already populating it, might as well size the
// slice appropriately.
2023-09-20 20:07:48 +00:00
// Per #9498 the exact requirements of nil vs empty slice remain
// unclear, this is a haunted graveyard to be resolved.
2023-09-20 03:22:51 +00:00
dcfg . Routes [ fqdn ] = make ( [ ] * dnstype . Resolver , 0 , len ( resolvers ) )
2023-09-20 20:07:48 +00:00
dcfg . Routes [ fqdn ] = append ( dcfg . Routes [ fqdn ] , resolvers ... )
2021-09-07 21:56:45 +00:00
}
2021-04-20 04:58:26 +00:00
2021-09-07 21:56:45 +00:00
// Set FallbackResolvers as the default resolvers in the
// scenarios that can't handle a purely split-DNS config. See
// https://github.com/tailscale/tailscale/issues/1743 for
// details.
switch {
case len ( dcfg . DefaultResolvers ) != 0 :
// Default resolvers already set.
2022-10-23 17:07:10 +00:00
case ! prefs . ExitNodeID ( ) . IsZero ( ) :
2022-11-23 11:01:25 +00:00
// When using an exit node, we send all DNS traffic to the exit node, so
// we don't need a fallback resolver.
//
// However, if the exit node is too old to run a DoH DNS proxy, then we
// need to use a fallback resolver as it's very likely the LAN resolvers
// will become unreachable.
2021-09-07 21:56:45 +00:00
//
// This is especially important on Apple OSes, where
// adding the default route to the tunnel interface makes
// it "primary", and we MUST provide VPN-sourced DNS
// settings or we break all DNS resolution.
//
// https://github.com/tailscale/tailscale/issues/1713
addDefault ( nm . DNS . FallbackResolvers )
case len ( dcfg . Routes ) == 0 :
// No settings requiring split DNS, no problem.
2021-04-01 08:33:58 +00:00
}
2021-09-07 21:56:45 +00:00
2021-09-07 21:38:26 +00:00
return dcfg
2021-03-25 22:38:40 +00:00
}
2023-03-08 20:36:41 +00:00
// SetTCPHandlerForFunnelFlow sets the TCP handler for Funnel flows.
// It should only be called before the LocalBackend is used.
func ( b * LocalBackend ) SetTCPHandlerForFunnelFlow ( h func ( src netip . AddrPort , dstPort uint16 ) ( handler func ( net . Conn ) ) ) {
b . getTCPHandlerForFunnelFlow = h
}
2021-11-03 16:03:11 +00:00
// SetVarRoot sets the root directory of Tailscale's writable
// storage area . (e.g. "/var/lib/tailscale")
//
// It should only be called before the LocalBackend is used.
func ( b * LocalBackend ) SetVarRoot ( dir string ) {
b . varRoot = dir
}
2023-01-05 19:00:42 +00:00
// SetLogFlusher sets a func to be called to flush log uploads.
//
// It should only be called before the LocalBackend is used.
func ( b * LocalBackend ) SetLogFlusher ( flushFunc func ( ) ) {
b . logFlushFunc = flushFunc
}
// TryFlushLogs calls the log flush function. It returns false if a log flush
// function was never initialized with SetLogFlusher.
//
// TryFlushLogs should not block.
func ( b * LocalBackend ) TryFlushLogs ( ) bool {
if b . logFlushFunc == nil {
return false
}
b . logFlushFunc ( )
return true
}
2021-09-27 20:31:40 +00:00
// TailscaleVarRoot returns the root directory of Tailscale's writable
2021-03-31 21:08:32 +00:00
// storage area. (e.g. "/var/lib/tailscale")
2021-09-27 20:31:40 +00:00
//
// It returns an empty string if there's no configured or discovered
// location.
func ( b * LocalBackend ) TailscaleVarRoot ( ) string {
2021-11-03 16:03:11 +00:00
if b . varRoot != "" {
return b . varRoot
}
2021-05-20 12:33:49 +00:00
switch runtime . GOOS {
2022-01-06 15:43:24 +00:00
case "ios" , "android" , "darwin" :
2022-08-04 17:43:49 +00:00
return paths . AppSharedDir . Load ( )
2023-04-05 05:04:56 +00:00
case "linux" :
if distro . Get ( ) == distro . Gokrazy {
return "/perm/tailscaled"
}
2021-03-31 21:08:32 +00:00
}
2021-11-03 16:03:11 +00:00
return ""
2021-03-31 21:08:32 +00:00
}
2021-04-12 21:05:44 +00:00
func ( b * LocalBackend ) fileRootLocked ( uid tailcfg . UserID ) string {
if v := b . directFileRoot ; v != "" {
return v
}
2021-09-27 20:31:40 +00:00
varRoot := b . TailscaleVarRoot ( )
2021-04-12 21:05:44 +00:00
if varRoot == "" {
2021-12-01 23:00:23 +00:00
b . logf ( "Taildrop disabled; no state directory" )
2021-04-12 21:05:44 +00:00
return ""
}
baseDir := fmt . Sprintf ( "%s-uid-%d" ,
strings . ReplaceAll ( b . activeLogin , "@" , "-" ) ,
uid )
dir := filepath . Join ( varRoot , "files" , baseDir )
if err := os . MkdirAll ( dir , 0700 ) ; err != nil {
2021-12-01 23:00:23 +00:00
b . logf ( "Taildrop disabled; error making directory: %v" , err )
2021-04-12 21:05:44 +00:00
return ""
}
return dir
}
2022-11-16 17:38:38 +00:00
// closePeerAPIListenersLocked closes any existing PeerAPI listeners
// and clears out the PeerAPI server state.
2021-04-23 18:45:48 +00:00
//
// It does not kick off any Hostinfo update with new services.
//
// b.mu must be held.
func ( b * LocalBackend ) closePeerAPIListenersLocked ( ) {
b . peerAPIServer = nil
for _ , pln := range b . peerAPIListeners {
pln . Close ( )
}
b . peerAPIListeners = nil
}
2021-06-14 15:59:09 +00:00
// peerAPIListenAsync is whether the operating system requires that we
// retry listening on the peerAPI ip/port for whatever reason.
//
// On Windows, see Issue 1620.
// On Android, see Issue 1960.
const peerAPIListenAsync = runtime . GOOS == "windows" || runtime . GOOS == "android"
2021-03-25 22:38:40 +00:00
func ( b * LocalBackend ) initPeerAPIListener ( ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-04-25 18:02:59 +00:00
if b . shutdownCalled {
return
}
2021-03-25 22:38:40 +00:00
2021-06-03 16:39:30 +00:00
if b . netMap == nil {
// We're called from authReconfig which checks that
// netMap is non-nil, but if a concurrent Logout,
// ResetForClientDisconnect, or Start happens when its
// mutex was released, the netMap could be
// nil'ed out (Issue 1996). Bail out early here if so.
return
}
2023-09-17 17:53:23 +00:00
addrs := b . netMap . GetAddresses ( )
if addrs . Len ( ) == len ( b . peerAPIListeners ) {
2021-04-09 18:13:42 +00:00
allSame := true
for i , pln := range b . peerAPIListeners {
2023-09-17 17:53:23 +00:00
if pln . ip != addrs . At ( i ) . Addr ( ) {
2021-04-09 18:13:42 +00:00
allSame = false
break
}
}
if allSame {
// Nothing to do.
return
}
}
2021-04-23 18:45:48 +00:00
b . closePeerAPIListenersLocked ( )
2021-03-25 22:38:40 +00:00
2021-03-29 17:42:33 +00:00
selfNode := b . netMap . SelfNode
2023-09-17 17:53:23 +00:00
if ! selfNode . Valid ( ) || b . netMap . GetAddresses ( ) . Len ( ) == 0 {
2021-03-29 17:42:33 +00:00
return
}
2023-08-21 17:53:57 +00:00
fileRoot := b . fileRootLocked ( selfNode . User ( ) )
2021-04-12 21:05:44 +00:00
if fileRoot == "" {
2021-12-01 23:00:23 +00:00
b . logf ( "peerapi starting without Taildrop directory configured" )
2021-03-27 04:24:02 +00:00
}
2021-03-29 17:42:33 +00:00
ps := & peerAPIServer {
2023-10-05 23:05:45 +00:00
b : b ,
2023-10-17 20:46:05 +00:00
taildrop : taildrop . ManagerOptions {
2024-01-09 20:11:34 +00:00
Logf : b . logf ,
Clock : tstime . DefaultClock { Clock : b . clock } ,
State : b . store ,
Dir : fileRoot ,
DirectFileMode : b . directFileRoot != "" ,
SendFileNotify : b . sendFileNotify ,
2023-10-17 20:46:05 +00:00
} . New ( ) ,
2021-03-29 17:42:33 +00:00
}
2023-05-03 20:57:17 +00:00
if dm , ok := b . sys . DNSManager . GetOK ( ) ; ok {
ps . resolver = dm . Resolver ( )
2021-11-23 05:45:34 +00:00
}
2021-03-30 18:19:42 +00:00
b . peerAPIServer = ps
2021-03-29 17:42:33 +00:00
2023-05-03 20:57:17 +00:00
isNetstack := b . sys . IsNetstack ( )
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-09-17 17:53:23 +00:00
a := addrs . At ( i )
2021-03-30 16:54:52 +00:00
var ln net . Listener
var err error
skipListen := i > 0 && isNetstack
if ! skipListen {
2022-07-25 03:08:42 +00:00
ln , err = ps . listen ( a . Addr ( ) , b . prevIfState )
2021-03-30 16:54:52 +00:00
if err != nil {
2021-06-14 15:59:09 +00:00
if peerAPIListenAsync {
// Expected. But we fix it later in linkChange
2021-04-27 16:58:05 +00:00
// ("peerAPIListeners too low").
continue
}
2022-07-25 03:08:42 +00:00
b . logf ( "[unexpected] peerapi listen(%q) error: %v" , a . Addr ( ) , err )
2021-03-30 16:54:52 +00:00
continue
}
2021-03-25 22:38:40 +00:00
}
pln := & peerAPIListener {
2021-03-29 17:42:33 +00:00
ps : ps ,
2022-07-25 03:08:42 +00:00
ip : a . Addr ( ) ,
2021-03-30 16:54:52 +00:00
ln : ln , // nil for 2nd+ on netstack
2021-03-29 17:42:33 +00:00
lb : b ,
2021-03-25 22:38:40 +00:00
}
2021-03-30 16:54:52 +00:00
if skipListen {
2021-04-02 05:04:46 +00:00
pln . port = b . peerAPIListeners [ 0 ] . port
2021-03-30 16:54:52 +00:00
} else {
2021-04-02 05:04:46 +00:00
pln . port = ln . Addr ( ) . ( * net . TCPAddr ) . Port
2021-03-30 16:54:52 +00:00
}
2022-07-25 03:08:42 +00:00
pln . urlStr = "http://" + net . JoinHostPort ( a . Addr ( ) . String ( ) , strconv . Itoa ( pln . port ) )
2021-03-30 16:54:52 +00:00
b . logf ( "peerapi: serving on %s" , pln . urlStr )
2021-03-25 22:38:40 +00:00
go pln . serve ( )
b . peerAPIListeners = append ( b . peerAPIListeners , pln )
}
2021-04-09 19:10:52 +00:00
2023-10-23 17:18:40 +00:00
go b . doSetHostinfoFilterServices ( )
2020-02-05 22:16:58 +00:00
}
2021-01-05 18:37:15 +00:00
// magicDNSRootDomains returns the subset of nm.DNS.Domains that are the search domains for MagicDNS.
2021-04-09 22:24:47 +00:00
func magicDNSRootDomains ( nm * netmap . NetworkMap ) [ ] dnsname . FQDN {
2021-01-10 20:03:01 +00:00
if v := nm . MagicDNSSuffix ( ) ; v != "" {
2021-04-09 22:24:47 +00:00
fqdn , err := dnsname . ToFQDN ( v )
if err != nil {
// TODO: propagate error
return nil
}
2021-04-21 01:05:17 +00:00
ret := [ ] dnsname . FQDN {
fqdn ,
dnsname . FQDN ( "0.e.1.a.c.5.1.1.a.7.d.f.ip6.arpa." ) ,
}
for i := 64 ; i <= 127 ; i ++ {
fqdn , err = dnsname . ToFQDN ( fmt . Sprintf ( "%d.100.in-addr.arpa." , i ) )
if err != nil {
// TODO: propagate error
continue
}
ret = append ( ret , fqdn )
}
return ret
2020-07-31 20:27:09 +00:00
}
2021-01-10 20:03:01 +00:00
return nil
2020-07-31 20:27:09 +00:00
}
2021-01-21 01:24:16 +00:00
var (
2022-07-26 03:55:44 +00:00
ipv4Default = netip . MustParsePrefix ( "0.0.0.0/0" )
ipv6Default = netip . MustParsePrefix ( "::/0" )
2021-01-21 01:24:16 +00:00
)
2021-03-04 20:04:31 +00:00
// peerRoutes returns the routerConfig.Routes to access peers.
// If there are over cgnatThreshold CGNAT routes, one big CGNAT route
// is used instead.
2023-02-19 16:17:06 +00:00
func peerRoutes ( logf logger . Logf , peers [ ] wgcfg . Peer , cgnatThreshold int ) ( routes [ ] netip . Prefix ) {
2021-03-04 20:04:31 +00:00
tsULA := tsaddr . TailscaleULARange ( )
cgNAT := tsaddr . CGNATRange ( )
var didULA bool
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
var cgNATIPs [ ] netip . Prefix
2021-03-04 20:04:31 +00:00
for _ , peer := range peers {
for _ , aip := range peer . AllowedIPs {
aip = unmapIPPrefix ( aip )
2023-02-19 16:17:06 +00:00
// Ensure that we're only accepting properly-masked
// prefixes; the control server should be masking
// these, so if we get them, skip.
if mm := aip . Masked ( ) ; aip != mm {
// To avoid a DoS where a peer could cause all
// reconfigs to fail by sending a bad prefix, we just
// skip, but don't error, on an unmasked route.
logf ( "advertised route %s from %s has non-address bits set; expected %s" , aip , peer . PublicKey . ShortString ( ) , mm )
continue
}
2021-03-04 20:04:31 +00:00
// Only add the Tailscale IPv6 ULA once, if we see anybody using part of it.
2022-07-25 03:08:42 +00:00
if aip . Addr ( ) . Is6 ( ) && aip . IsSingleIP ( ) && tsULA . Contains ( aip . Addr ( ) ) {
2021-03-04 20:04:31 +00:00
if ! didULA {
didULA = true
routes = append ( routes , tsULA )
}
continue
}
2022-07-25 03:08:42 +00:00
if aip . IsSingleIP ( ) && cgNAT . Contains ( aip . Addr ( ) ) {
2021-03-04 20:04:31 +00:00
cgNATIPs = append ( cgNATIPs , aip )
} else {
routes = append ( routes , aip )
}
}
}
if len ( cgNATIPs ) > cgnatThreshold {
// Probably the hello server. Just append one big route.
routes = append ( routes , cgNAT )
} else {
routes = append ( routes , cgNATIPs ... )
}
2022-04-13 22:41:04 +00:00
2022-11-12 09:53:36 +00:00
tsaddr . SortPrefixes ( routes )
2021-03-04 20:04:31 +00:00
return routes
}
2020-07-31 20:27:09 +00:00
// routerConfig produces a router.Config from a wireguard config and IPN prefs.
2022-10-23 17:07:10 +00:00
func ( b * LocalBackend ) routerConfig ( cfg * wgcfg . Config , prefs ipn . PrefsView , oneCGNATRoute bool ) * router . Config {
2022-04-14 21:40:17 +00:00
singleRouteThreshold := 10_000
if oneCGNATRoute {
singleRouteThreshold = 1
}
2023-02-19 16:17:06 +00:00
2023-12-22 02:19:13 +00:00
b . mu . Lock ( )
netfilterKind := b . capForcedNetfilter // protected by b.mu
b . mu . Unlock ( )
2023-12-04 17:08:56 +00:00
if prefs . NetfilterKind ( ) != "" {
2023-12-22 02:19:13 +00:00
if netfilterKind != "" {
b . logf ( "nodeattr netfilter preference %s overridden by c2n pref %s" , netfilterKind , prefs . NetfilterKind ( ) )
2023-12-04 17:08:56 +00:00
}
netfilterKind = prefs . NetfilterKind ( )
}
2024-05-06 22:22:17 +00:00
var doStatefulFiltering bool
2024-05-20 18:44:29 +00:00
if v , ok := prefs . NoStatefulFiltering ( ) . Get ( ) ; ok && ! v {
2024-05-06 22:22:17 +00:00
// The preferences explicitly "do stateful filtering" is turned
// off, or to expand the double negative, to do stateful
// filtering. Do so.
doStatefulFiltering = true
}
2020-05-12 07:08:52 +00:00
rs := & router . Config {
2024-05-06 22:22:17 +00:00
LocalAddrs : unmapIPPrefixes ( cfg . Addresses ) ,
SubnetRoutes : unmapIPPrefixes ( prefs . AdvertiseRoutes ( ) . AsSlice ( ) ) ,
SNATSubnetRoutes : ! prefs . NoSNAT ( ) ,
StatefulFiltering : doStatefulFiltering ,
NetfilterMode : prefs . NetfilterMode ( ) ,
Routes : peerRoutes ( b . logf , cfg . Peers , singleRouteThreshold ) ,
NetfilterKind : netfilterKind ,
2020-05-11 21:02:12 +00:00
}
2021-05-27 17:07:17 +00:00
if distro . Get ( ) == distro . Synology {
// Issue 1995: we don't use iptables on Synology.
rs . NetfilterMode = preftype . NetfilterOff
}
2021-01-21 01:24:16 +00:00
// Sanity check: we expect the control server to program both a v4
// and a v6 default route, if default routing is on. Fill in
// blackhole routes appropriately if we're missing some. This is
// likely to break some functionality, but if the user expressed a
// preference for routing remotely, we want to avoid leaking
// traffic at the expense of functionality.
2022-10-23 17:07:10 +00:00
if prefs . ExitNodeID ( ) != "" || prefs . ExitNodeIP ( ) . IsValid ( ) {
2021-01-21 01:24:16 +00:00
var default4 , default6 bool
for _ , route := range rs . Routes {
2021-04-08 22:56:51 +00:00
switch route {
case ipv4Default :
2021-01-21 01:24:16 +00:00
default4 = true
2021-04-08 22:56:51 +00:00
case ipv6Default :
2021-01-21 01:24:16 +00:00
default6 = true
}
if default4 && default6 {
break
}
}
if ! default4 {
rs . Routes = append ( rs . Routes , ipv4Default )
}
if ! default6 {
rs . Routes = append ( rs . Routes , ipv6Default )
}
2021-07-02 14:15:28 +00:00
internalIPs , externalIPs , err := internalAndExternalInterfaces ( )
if err != nil {
b . logf ( "failed to discover interface ips: %v" , err )
}
2023-11-13 21:18:30 +00:00
switch runtime . GOOS {
2024-04-13 00:01:32 +00:00
case "linux" , "windows" , "darwin" , "ios" , "android" :
2021-07-02 14:15:28 +00:00
rs . LocalRoutes = internalIPs // unconditionally allow access to guest VM networks
2022-10-23 17:07:10 +00:00
if prefs . ExitNodeAllowLANAccess ( ) {
2021-07-02 14:15:28 +00:00
rs . LocalRoutes = append ( rs . LocalRoutes , externalIPs ... )
2021-04-19 23:03:03 +00:00
} else {
// Explicitly add routes to the local network so that we do not
// leak any traffic.
2021-07-02 14:15:28 +00:00
rs . Routes = append ( rs . Routes , externalIPs ... )
2021-04-19 23:03:03 +00:00
}
2022-08-05 17:32:11 +00:00
b . logf ( "allowing exit node access to local IPs: %v" , rs . LocalRoutes )
2023-11-13 21:18:30 +00:00
default :
if prefs . ExitNodeAllowLANAccess ( ) {
b . logf ( "warning: ExitNodeAllowLANAccess has no effect on " + runtime . GOOS )
}
2021-04-08 22:56:51 +00:00
}
2021-01-21 01:24:16 +00:00
}
2022-12-06 02:22:53 +00:00
if slices . ContainsFunc ( rs . LocalAddrs , tsaddr . PrefixIs4 ) {
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
rs . Routes = append ( rs . Routes , netip . PrefixFrom ( tsaddr . TailscaleServiceIP ( ) , 32 ) )
2022-01-04 21:33:08 +00:00
}
2020-06-08 22:19:26 +00:00
2020-05-11 21:02:12 +00:00
return rs
}
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
func unmapIPPrefix ( ipp netip . Prefix ) netip . Prefix {
2022-07-25 03:08:42 +00:00
return netip . PrefixFrom ( ipp . Addr ( ) . Unmap ( ) , ipp . Bits ( ) )
2021-03-04 20:04:31 +00:00
}
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
func unmapIPPrefixes ( ippsList ... [ ] netip . Prefix ) ( ret [ ] netip . Prefix ) {
2020-12-24 20:33:55 +00:00
for _ , ipps := range ippsList {
for _ , ipp := range ipps {
2021-03-04 20:04:31 +00:00
ret = append ( ret , unmapIPPrefix ( ipp ) )
2020-05-11 21:02:12 +00:00
}
}
return ret
}
2022-11-16 05:22:09 +00:00
// b.mu must be held.
func ( b * LocalBackend ) applyPrefsToHostinfoLocked ( hi * tailcfg . Hostinfo , prefs ipn . PrefsView ) {
2022-10-23 17:07:10 +00:00
if h := prefs . Hostname ( ) ; h != "" {
2020-07-24 21:05:04 +00:00
hi . Hostname = h
}
2022-10-23 17:07:10 +00:00
hi . RoutableIPs = prefs . AdvertiseRoutes ( ) . AsSlice ( )
hi . RequestTags = prefs . AdvertiseTags ( ) . AsSlice ( )
hi . ShieldsUp = prefs . ShieldsUp ( )
2023-12-18 22:57:03 +00:00
hi . AllowsUpdate = envknob . AllowsRemoteUpdate ( ) || prefs . AutoUpdate ( ) . Apply . EqualBool ( true )
2022-02-17 23:00:41 +00:00
var sshHostKeys [ ] string
2022-10-23 17:07:10 +00:00
if prefs . RunSSH ( ) && envknob . CanSSHD ( ) {
2022-02-17 23:00:41 +00:00
// TODO(bradfitz): this is called with b.mu held. Not ideal.
// If the filesystem gets wedged or something we could block for
// a long time. But probably fine.
2024-01-30 21:49:02 +00:00
var err error
sshHostKeys , err = b . getSSHHostKeyPublicStrings ( )
if err != nil {
b . logf ( "warning: unable to get SSH host keys, SSH will appear as disabled for this node: %v" , err )
}
2022-02-17 23:00:41 +00:00
}
hi . SSH_HostKeys = sshHostKeys
2022-11-16 20:51:26 +00:00
// The Hostinfo.WantIngress field tells control whether this node wants to
// be wired up for ingress connections. If harmless if it's accidentally
// true; the actual policy is controlled in tailscaled by ServeConfig. But
// if this is accidentally false, then control may not configure DNS
// properly. This exists as an optimization to control to program fewer DNS
// records that have ingress enabled but are not actually being used.
hi . WireIngress = b . wantIngressLocked ( )
2023-11-28 23:38:01 +00:00
hi . AppConnector . Set ( prefs . AppConnector ( ) . Advertise )
2020-07-24 21:05:04 +00:00
}
2020-05-19 02:32:20 +00:00
// enterState transitions the backend into newState, updating internal
// state and propagating events out as needed.
//
// TODO(danderson): while this isn't a lie, exactly, a ton of other
// places twiddle IPN internal state without going through here, so
// really this is more "one of several places in which random things
// happen".
2021-02-04 21:12:42 +00:00
func ( b * LocalBackend ) enterState ( newState ipn . State ) {
2024-04-06 18:05:56 +00:00
unlock := b . lockAndGetUnlock ( )
b . enterStateLockedOnEntry ( newState , unlock )
2022-11-09 05:58:10 +00:00
}
// enterStateLockedOnEntry is like enterState but requires b.mu be held to call
2024-04-06 18:05:56 +00:00
// it, but it unlocks b.mu when done (via unlock, a once func).
2024-04-07 04:16:00 +00:00
func ( b * LocalBackend ) enterStateLockedOnEntry ( newState ipn . State , unlock unlockOnce ) {
2021-04-23 18:45:48 +00:00
oldState := b . state
2020-06-19 17:43:55 +00:00
b . state = newState
2022-11-09 05:58:10 +00:00
prefs := b . pm . CurrentPrefs ( )
2024-05-06 00:41:13 +00:00
// Some temporary (2024-05-05) debugging code to help us catch
// https://github.com/tailscale/tailscale/issues/11962 in the act.
if prefs . WantRunning ( ) &&
prefs . ControlURLOrDefault ( ) == ipn . DefaultControlURL &&
envknob . Bool ( "TS_PANIC_IF_HIT_MAIN_CONTROL" ) {
panic ( "[unexpected] use of main control server in integration test" )
}
2021-04-30 10:08:26 +00:00
netMap := b . netMap
2020-11-24 23:35:04 +00:00
activeLogin := b . activeLogin
authURL := b . authURL
2021-04-21 20:37:36 +00:00
if newState == ipn . Running {
b . authURL = ""
2024-02-08 21:04:01 +00:00
b . authURLTime = time . Time { }
2021-04-23 18:45:48 +00:00
} else if oldState == ipn . Running {
// Transitioning away from running.
b . closePeerAPIListenersLocked ( )
2021-04-21 20:37:36 +00:00
}
2023-08-04 05:37:52 +00:00
b . pauseOrResumeControlClientLocked ( )
2024-04-07 04:16:00 +00:00
2024-06-04 02:24:53 +00:00
if newState == ipn . Running {
b . stopOfflineAutoUpdate ( )
} else {
b . maybeStartOfflineAutoUpdate ( prefs )
}
2024-04-07 04:16:00 +00:00
unlock . UnlockEarly ( )
2020-02-05 22:16:58 +00:00
2022-06-03 17:52:07 +00:00
// prefs may change irrespective of state; WantRunning should be explicitly
// set before potential early return even if the state is unchanged.
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
b . health . SetIPNState ( newState . String ( ) , prefs . Valid ( ) && prefs . WantRunning ( ) )
2021-04-23 18:45:48 +00:00
if oldState == newState {
2020-02-05 22:16:58 +00:00
return
}
2021-05-06 03:28:29 +00:00
b . logf ( "Switching ipn state %v -> %v (WantRunning=%v, nm=%v)" ,
2022-11-09 05:58:10 +00:00
oldState , newState , prefs . WantRunning ( ) , netMap != nil )
2021-04-12 17:36:19 +00:00
b . send ( ipn . Notify { State : & newState } )
2020-02-05 22:16:58 +00:00
switch newState {
2021-02-04 21:12:42 +00:00
case ipn . NeedsLogin :
2020-11-24 23:35:04 +00:00
systemd . Status ( "Needs login: %s" , authURL )
2024-01-04 17:29:04 +00:00
if b . seamlessRenewalEnabled ( ) {
break
}
2020-02-05 22:16:58 +00:00
b . blockEngineUpdates ( true )
fallthrough
2021-02-04 21:12:42 +00:00
case ipn . Stopped :
2023-08-18 00:29:15 +00:00
err := b . e . Reconfig ( & wgcfg . Config { } , & router . Config { } , & dns . Config { } )
2020-02-05 22:16:58 +00:00
if err != nil {
2020-04-11 15:35:34 +00:00
b . logf ( "Reconfig(down): %v" , err )
2020-02-05 22:16:58 +00:00
}
2020-11-24 23:35:04 +00:00
if authURL == "" {
systemd . Status ( "Stopped; run 'tailscale up' to log in" )
}
2021-02-04 21:12:42 +00:00
case ipn . Starting , ipn . NeedsMachineAuth :
2020-02-05 22:16:58 +00:00
b . authReconfig ( )
// Needed so that UpdateEndpoints can run
b . e . RequestStatus ( )
2021-02-04 21:12:42 +00:00
case ipn . Running :
2023-09-17 17:53:23 +00:00
var addrStrs [ ] string
addrs := netMap . GetAddresses ( )
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-09-17 17:53:23 +00:00
addrStrs = append ( addrStrs , addrs . At ( i ) . Addr ( ) . String ( ) )
2020-11-24 23:35:04 +00:00
}
2023-09-17 17:53:23 +00:00
systemd . Status ( "Connected; %s; %s" , activeLogin , strings . Join ( addrStrs , " " ) )
2022-11-09 05:58:10 +00:00
case ipn . NoState :
// Do nothing.
2020-02-05 22:16:58 +00:00
default :
2020-04-11 15:35:34 +00:00
b . logf ( "[unexpected] unknown newState %#v" , newState )
2020-02-05 22:16:58 +00:00
}
}
2023-09-01 00:44:13 +00:00
func ( b * LocalBackend ) hasNodeKeyLocked ( ) bool {
// we can't use b.Prefs(), because it strips the keys, oops!
2022-11-09 05:58:10 +00:00
p := b . pm . CurrentPrefs ( )
2022-11-29 20:00:40 +00:00
return p . Valid ( ) && p . Persist ( ) . Valid ( ) && ! p . Persist ( ) . PrivateNodeKey ( ) . IsZero ( )
2021-04-30 09:27:37 +00:00
}
2023-05-05 00:34:44 +00:00
// NodeKey returns the public node key.
func ( b * LocalBackend ) NodeKey ( ) key . NodePublic {
b . mu . Lock ( )
defer b . mu . Unlock ( )
2023-09-01 00:44:13 +00:00
if ! b . hasNodeKeyLocked ( ) {
2023-05-05 00:34:44 +00:00
return key . NodePublic { }
}
2023-09-01 00:44:13 +00:00
return b . pm . CurrentPrefs ( ) . Persist ( ) . PublicNodeKey ( )
2023-05-05 00:34:44 +00:00
}
ipn/ipnlocal: fix race in enterState
It would acquire the lock, calculate `nextState`, relase
the lock, then call `enterState` which would acquire the lock
again. There were obvious races there which could lead to
nil panics as seen in a test in a different repo.
```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x70 pc=0x1050f2c7c]
goroutine 42240 [running]:
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterStateLockedOnEntry(0x14002154e00, 0x6)
tailscale.com/ipn/ipnlocal/local.go:3715 +0x30c
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterState(0x14002154e00?, 0x14002e3a140?)
tailscale.com/ipn/ipnlocal/local.go:3663 +0x8c
tailscale.com/ipn/ipnlocal.(*LocalBackend).stateMachine(0x14001f5e280?)
tailscale.com/ipn/ipnlocal/local.go:3836 +0x2c
tailscale.com/ipn/ipnlocal.(*LocalBackend).setWgengineStatus(0x14002154e00, 0x14002e3a190, {0x0?, 0x0?})
tailscale.com/ipn/ipnlocal/local.go:1193 +0x4d0
tailscale.com/wgengine.(*userspaceEngine).RequestStatus(0x14005d90300)
tailscale.com/wgengine/userspace.go:1051 +0x80
tailscale.com/wgengine.NewUserspaceEngine.func2({0x14002e3a0a0, 0x2, 0x140025cce40?})
tailscale.com/wgengine/userspace.go:318 +0x1a0
tailscale.com/wgengine/magicsock.(*Conn).updateEndpoints(0x14002154700, {0x105c13eaf, 0xf})
tailscale.com/wgengine/magicsock/magicsock.go:531 +0x424
created by tailscale.com/wgengine/magicsock.(*Conn).ReSTUN in goroutine 42077
tailscale.com/wgengine/magicsock/magicsock.go:2142 +0x3a4
```
Updates tailscale/corp#14480
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2023-09-05 17:28:01 +00:00
// nextStateLocked returns the state the backend seems to be in, based on
2020-05-19 02:32:20 +00:00
// its internal state.
ipn/ipnlocal: fix race in enterState
It would acquire the lock, calculate `nextState`, relase
the lock, then call `enterState` which would acquire the lock
again. There were obvious races there which could lead to
nil panics as seen in a test in a different repo.
```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x70 pc=0x1050f2c7c]
goroutine 42240 [running]:
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterStateLockedOnEntry(0x14002154e00, 0x6)
tailscale.com/ipn/ipnlocal/local.go:3715 +0x30c
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterState(0x14002154e00?, 0x14002e3a140?)
tailscale.com/ipn/ipnlocal/local.go:3663 +0x8c
tailscale.com/ipn/ipnlocal.(*LocalBackend).stateMachine(0x14001f5e280?)
tailscale.com/ipn/ipnlocal/local.go:3836 +0x2c
tailscale.com/ipn/ipnlocal.(*LocalBackend).setWgengineStatus(0x14002154e00, 0x14002e3a190, {0x0?, 0x0?})
tailscale.com/ipn/ipnlocal/local.go:1193 +0x4d0
tailscale.com/wgengine.(*userspaceEngine).RequestStatus(0x14005d90300)
tailscale.com/wgengine/userspace.go:1051 +0x80
tailscale.com/wgengine.NewUserspaceEngine.func2({0x14002e3a0a0, 0x2, 0x140025cce40?})
tailscale.com/wgengine/userspace.go:318 +0x1a0
tailscale.com/wgengine/magicsock.(*Conn).updateEndpoints(0x14002154700, {0x105c13eaf, 0xf})
tailscale.com/wgengine/magicsock/magicsock.go:531 +0x424
created by tailscale.com/wgengine/magicsock.(*Conn).ReSTUN in goroutine 42077
tailscale.com/wgengine/magicsock/magicsock.go:2142 +0x3a4
```
Updates tailscale/corp#14480
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2023-09-05 17:28:01 +00:00
//
// b.mu must be held
func ( b * LocalBackend ) nextStateLocked ( ) ipn . State {
2020-02-29 02:34:56 +00:00
var (
2022-11-09 05:58:10 +00:00
cc = b . cc
netMap = b . netMap
state = b . state
blocked = b . blocked
st = b . engineStatus
keyExpired = b . keyExpired
wantRunning = false
loggedOut = false
2020-02-29 02:34:56 +00:00
)
2022-11-09 05:58:10 +00:00
if p := b . pm . CurrentPrefs ( ) ; p . Valid ( ) {
wantRunning = p . WantRunning ( )
loggedOut = p . LoggedOut ( )
}
2020-02-28 19:39:13 +00:00
2020-05-19 02:32:20 +00:00
switch {
ipn/ipnlocal: fix race in enterState
It would acquire the lock, calculate `nextState`, relase
the lock, then call `enterState` which would acquire the lock
again. There were obvious races there which could lead to
nil panics as seen in a test in a different repo.
```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x70 pc=0x1050f2c7c]
goroutine 42240 [running]:
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterStateLockedOnEntry(0x14002154e00, 0x6)
tailscale.com/ipn/ipnlocal/local.go:3715 +0x30c
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterState(0x14002154e00?, 0x14002e3a140?)
tailscale.com/ipn/ipnlocal/local.go:3663 +0x8c
tailscale.com/ipn/ipnlocal.(*LocalBackend).stateMachine(0x14001f5e280?)
tailscale.com/ipn/ipnlocal/local.go:3836 +0x2c
tailscale.com/ipn/ipnlocal.(*LocalBackend).setWgengineStatus(0x14002154e00, 0x14002e3a190, {0x0?, 0x0?})
tailscale.com/ipn/ipnlocal/local.go:1193 +0x4d0
tailscale.com/wgengine.(*userspaceEngine).RequestStatus(0x14005d90300)
tailscale.com/wgengine/userspace.go:1051 +0x80
tailscale.com/wgengine.NewUserspaceEngine.func2({0x14002e3a0a0, 0x2, 0x140025cce40?})
tailscale.com/wgengine/userspace.go:318 +0x1a0
tailscale.com/wgengine/magicsock.(*Conn).updateEndpoints(0x14002154700, {0x105c13eaf, 0xf})
tailscale.com/wgengine/magicsock/magicsock.go:531 +0x424
created by tailscale.com/wgengine/magicsock.(*Conn).ReSTUN in goroutine 42077
tailscale.com/wgengine/magicsock/magicsock.go:2142 +0x3a4
```
Updates tailscale/corp#14480
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2023-09-05 17:28:01 +00:00
case ! wantRunning && ! loggedOut && ! blocked && b . hasNodeKeyLocked ( ) :
2021-04-30 07:56:11 +00:00
return ipn . Stopped
2020-05-19 02:32:20 +00:00
case netMap == nil :
2022-11-15 04:17:28 +00:00
if ( cc != nil && cc . AuthCantContinue ( ) ) || loggedOut {
2020-02-05 22:16:58 +00:00
// Auth was interrupted or waiting for URL visit,
// so it won't proceed without human help.
2021-02-04 21:12:42 +00:00
return ipn . NeedsLogin
2021-09-15 19:49:09 +00:00
}
switch state {
case ipn . Stopped :
2021-04-30 08:29:22 +00:00
// If we were already in the Stopped state, then
// we can assume auth is in good shape (or we would
// have been in NeedsLogin), so transition to Starting
// right away.
return ipn . Starting
2021-09-15 19:49:09 +00:00
case ipn . NoState :
2021-04-30 08:29:22 +00:00
// Our first time connecting to control, and we
// don't know if we'll NeedsLogin or not yet.
// UIs should print "Loading..." in this state.
return ipn . NoState
2021-09-15 19:49:09 +00:00
case ipn . Starting , ipn . Running , ipn . NeedsLogin :
2021-04-30 08:29:22 +00:00
return state
2021-09-15 19:49:09 +00:00
default :
2021-04-30 08:29:22 +00:00
b . logf ( "unexpected no-netmap state transition for %v" , state )
2020-02-05 22:16:58 +00:00
return state
}
2020-05-19 02:32:20 +00:00
case ! wantRunning :
2021-02-04 21:12:42 +00:00
return ipn . Stopped
2021-11-04 19:19:00 +00:00
case keyExpired :
// NetMap must be non-nil for us to get here.
// The node key expired, need to relogin.
2021-02-04 21:12:42 +00:00
return ipn . NeedsLogin
2023-09-13 17:20:51 +00:00
case netMap . GetMachineStatus ( ) != tailcfg . MachineAuthorized :
2020-02-05 22:16:58 +00:00
// TODO(crawshaw): handle tailcfg.MachineInvalid
2021-02-04 21:12:42 +00:00
return ipn . NeedsMachineAuth
case state == ipn . NeedsMachineAuth :
2020-02-05 22:16:58 +00:00
// (if we get here, we know MachineAuthorized == true)
2021-02-04 21:12:42 +00:00
return ipn . Starting
case state == ipn . Starting :
2021-09-15 19:43:09 +00:00
if st . NumLive > 0 || st . LiveDERPs > 0 {
2021-02-04 21:12:42 +00:00
return ipn . Running
2020-02-05 22:16:58 +00:00
} else {
return state
}
2021-02-04 21:12:42 +00:00
case state == ipn . Running :
return ipn . Running
2020-05-19 02:32:20 +00:00
default :
2021-02-04 21:12:42 +00:00
return ipn . Starting
2020-02-05 22:16:58 +00:00
}
}
2020-05-19 02:32:20 +00:00
// stateMachine updates the state machine state based on other things
// that have happened. It is invoked from the various callbacks that
// feed events into LocalBackend.
//
2022-09-25 18:29:55 +00:00
// TODO(apenwarr): use a channel or something to prevent reentrancy?
2022-08-02 16:33:46 +00:00
// Or maybe just call the state machine from fewer places.
2020-02-05 22:16:58 +00:00
func ( b * LocalBackend ) stateMachine ( ) {
2024-04-06 18:05:56 +00:00
unlock := b . lockAndGetUnlock ( )
2024-05-08 00:31:10 +00:00
b . stateMachineLockedOnEntry ( unlock )
}
// stateMachineLockedOnEntry is like stateMachine but requires b.mu be held to
// call it, but it unlocks b.mu when done (via unlock, a once func).
func ( b * LocalBackend ) stateMachineLockedOnEntry ( unlock unlockOnce ) {
2024-04-06 18:05:56 +00:00
b . enterStateLockedOnEntry ( b . nextStateLocked ( ) , unlock )
}
// lockAndGetUnlock locks b.mu and returns a sync.OnceFunc function that will
// unlock it at most once.
//
// This is all very unfortunate but exists as a guardrail against the
// unfortunate "lockedOnEntry" methods in this package (primarily
// enterStateLockedOnEntry) that require b.mu held to be locked on entry to the
// function but unlock the mutex on their way out. As a stepping stone to
// cleaning things up (as of 2024-04-06), we at least pass the unlock func
// around now and defer unlock in the caller to avoid missing unlocks and double
// unlocks. TODO(bradfitz,maisem): make the locking in this package more
// traditional (simple). See https://github.com/tailscale/tailscale/issues/11649
2024-04-07 04:16:00 +00:00
func ( b * LocalBackend ) lockAndGetUnlock ( ) ( unlock unlockOnce ) {
ipn/ipnlocal: fix race in enterState
It would acquire the lock, calculate `nextState`, relase
the lock, then call `enterState` which would acquire the lock
again. There were obvious races there which could lead to
nil panics as seen in a test in a different repo.
```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x70 pc=0x1050f2c7c]
goroutine 42240 [running]:
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterStateLockedOnEntry(0x14002154e00, 0x6)
tailscale.com/ipn/ipnlocal/local.go:3715 +0x30c
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterState(0x14002154e00?, 0x14002e3a140?)
tailscale.com/ipn/ipnlocal/local.go:3663 +0x8c
tailscale.com/ipn/ipnlocal.(*LocalBackend).stateMachine(0x14001f5e280?)
tailscale.com/ipn/ipnlocal/local.go:3836 +0x2c
tailscale.com/ipn/ipnlocal.(*LocalBackend).setWgengineStatus(0x14002154e00, 0x14002e3a190, {0x0?, 0x0?})
tailscale.com/ipn/ipnlocal/local.go:1193 +0x4d0
tailscale.com/wgengine.(*userspaceEngine).RequestStatus(0x14005d90300)
tailscale.com/wgengine/userspace.go:1051 +0x80
tailscale.com/wgengine.NewUserspaceEngine.func2({0x14002e3a0a0, 0x2, 0x140025cce40?})
tailscale.com/wgengine/userspace.go:318 +0x1a0
tailscale.com/wgengine/magicsock.(*Conn).updateEndpoints(0x14002154700, {0x105c13eaf, 0xf})
tailscale.com/wgengine/magicsock/magicsock.go:531 +0x424
created by tailscale.com/wgengine/magicsock.(*Conn).ReSTUN in goroutine 42077
tailscale.com/wgengine/magicsock/magicsock.go:2142 +0x3a4
```
Updates tailscale/corp#14480
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2023-09-05 17:28:01 +00:00
b . mu . Lock ( )
2024-04-07 04:16:00 +00:00
var unlocked atomic . Bool
return func ( ) bool {
if unlocked . CompareAndSwap ( false , true ) {
b . mu . Unlock ( )
return true
}
return false
}
}
// unlockOnce is a func that unlocks only b.mu the first time it's called.
// Therefore it can be safely deferred to catch error paths, without worrying
// about double unlocks if a different point in the code later needs to explicitly
// unlock it first as well. It reports whether it was unlocked.
type unlockOnce func ( ) bool
// UnlockEarly unlocks the LocalBackend.mu. It panics if u returns false,
// indicating that this unlocker was already used.
//
// We're using this method to help us document & find the places that have
// atypical locking patterns. See
// https://github.com/tailscale/tailscale/issues/11649 for background.
//
// A normal unlock is a deferred one or an explicit b.mu.Unlock a few lines
// after the lock, without lots of control flow in-between. An "early" unlock is
// one that happens in weird places, like in various "LockedOnEntry" methods in
// this package that require the mutex to be locked on entry but unlock it
// somewhere in the middle (maybe several calls away) and then sometimes proceed
// to lock it again.
//
// The reason UnlockeEarly panics if already called is because these are the
// points at which it's assumed that the mutex is already held and it now needs
// to be released. If somebody already released it, that invariant was violated.
// On the other hand, simply calling u only returns false instead of panicking
// so you can defer it without care, confident you got all the error return
// paths which were previously done by hand.
func ( u unlockOnce ) UnlockEarly ( ) {
if ! u ( ) {
panic ( "Unlock on already-called unlockOnce" )
}
2020-02-05 22:16:58 +00:00
}
2020-05-19 02:32:20 +00:00
// stopEngineAndWait deconfigures the local network data plane, and
// waits for it to deliver a status update before returning.
//
// TODO(danderson): this may be racy. We could unblock upon receiving
// a status update that predates the "I've shut down" update.
2020-02-05 22:16:58 +00:00
func ( b * LocalBackend ) stopEngineAndWait ( ) {
2020-04-11 15:35:34 +00:00
b . logf ( "stopEngineAndWait..." )
2023-08-18 00:29:15 +00:00
b . e . Reconfig ( & wgcfg . Config { } , & router . Config { } , & dns . Config { } )
2020-02-05 22:16:58 +00:00
b . requestEngineStatusAndWait ( )
2020-04-11 15:35:34 +00:00
b . logf ( "stopEngineAndWait: done." )
2020-02-05 22:16:58 +00:00
}
// Requests the wgengine status, and does not return until the status
// was delivered (to the usual callback).
func ( b * LocalBackend ) requestEngineStatusAndWait ( ) {
2020-04-11 15:35:34 +00:00
b . logf ( "requestEngineStatusAndWait" )
2020-02-05 22:16:58 +00:00
b . statusLock . Lock ( )
2024-04-15 02:47:32 +00:00
defer b . statusLock . Unlock ( )
2020-02-05 22:16:58 +00:00
go b . e . RequestStatus ( )
2020-04-11 15:35:34 +00:00
b . logf ( "requestEngineStatusAndWait: waiting..." )
2020-02-05 22:16:58 +00:00
b . statusChanged . Wait ( ) // temporarily releases lock while waiting
2020-04-11 15:35:34 +00:00
b . logf ( "requestEngineStatusAndWait: got status update." )
2020-02-05 22:16:58 +00:00
}
2024-04-13 23:20:42 +00:00
// setControlClientLocked sets the control client to cc,
// which may be nil.
//
// b.mu must be held.
func ( b * LocalBackend ) setControlClientLocked ( cc controlclient . Client ) {
b . cc = cc
b . ccAuto , _ = cc . ( * controlclient . Auto )
}
2023-09-02 19:04:03 +00:00
// resetControlClientLocked sets b.cc to nil and returns the old value. If the
// returned value is non-nil, the caller must call Shutdown on it after
// releasing b.mu.
func ( b * LocalBackend ) resetControlClientLocked ( ) controlclient . Client {
2022-11-15 04:17:28 +00:00
if b . cc == nil {
2023-09-02 19:04:03 +00:00
return nil
2022-11-15 04:17:28 +00:00
}
2023-03-06 14:57:28 +00:00
2024-05-07 04:33:37 +00:00
b . authURL = ""
2023-03-06 14:57:28 +00:00
// When we clear the control client, stop any outstanding netmap expiry
// timer; synthesizing a new netmap while we don't have a control
// client will break things.
//
// See https://github.com/tailscale/tailscale/issues/7392
if b . nmExpiryTimer != nil {
b . nmExpiryTimer . Stop ( )
b . nmExpiryTimer = nil
// Also bump the epoch to ensure that if the timer started, it
// will abort.
b . numClientStatusCalls . Add ( 1 )
}
2023-09-02 19:04:03 +00:00
prev := b . cc
2024-04-13 23:20:42 +00:00
b . setControlClientLocked ( nil )
2023-09-02 19:04:03 +00:00
return prev
2022-11-15 04:17:28 +00:00
}
2021-04-20 18:56:36 +00:00
// ResetForClientDisconnect resets the backend for GUI clients running
// in interactive (non-headless) mode. This is currently used only by
// Windows. This causes all state to be cleared, lest an unrelated user
// connect to tailscaled next. But it does not trigger a logout; we
// don't want to the user to have to reauthenticate in the future
// when they restart the GUI.
func ( b * LocalBackend ) ResetForClientDisconnect ( ) {
2023-09-02 19:04:03 +00:00
b . logf ( "LocalBackend.ResetForClientDisconnect" )
2024-04-06 18:05:56 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2023-09-02 19:04:03 +00:00
prevCC := b . resetControlClientLocked ( )
if prevCC != nil {
// Needs to happen without b.mu held.
defer prevCC . Shutdown ( )
}
2021-04-20 18:56:36 +00:00
b . setNetMapLocked ( nil )
2022-11-09 05:58:10 +00:00
b . pm . Reset ( )
ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.
The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.
This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).
Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.
I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.
Updates https://github.com/tailscale/tailscale/issues/755
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-10-25 20:48:05 +00:00
if b . currentUser != nil {
b . currentUser . Close ( )
b . currentUser = nil
}
2021-11-04 19:19:00 +00:00
b . keyExpired = false
2021-04-20 18:56:36 +00:00
b . authURL = ""
2024-02-08 21:04:01 +00:00
b . authURLTime = time . Time { }
2021-04-20 18:56:36 +00:00
b . activeLogin = ""
2024-04-30 19:09:12 +00:00
b . resetDialPlan ( )
2022-11-16 20:51:26 +00:00
b . setAtomicValuesFromPrefsLocked ( ipn . PrefsView { } )
2024-04-06 18:05:56 +00:00
b . enterStateLockedOnEntry ( ipn . Stopped , unlock )
2021-04-20 18:56:36 +00:00
}
2022-09-14 19:49:39 +00:00
func ( b * LocalBackend ) ShouldRunSSH ( ) bool { return b . sshAtomicBool . Load ( ) && envknob . CanSSHD ( ) }
2021-08-26 21:50:55 +00:00
2023-11-02 16:32:36 +00:00
// ShouldRunWebClient reports whether the web client is being run
// within this tailscaled instance. ShouldRunWebClient is safe to
// call regardless of whether b.mu is held or not.
2023-11-02 16:55:01 +00:00
func ( b * LocalBackend ) ShouldRunWebClient ( ) bool { return b . webClientAtomicBool . Load ( ) }
2024-03-18 21:47:21 +00:00
// ShouldExposeRemoteWebClient reports whether the web client should
// accept connections via [tailscale IP]:5252 in addition to the default
// behaviour of accepting local connections over 100.100.100.100.
//
// This function checks both the web client user pref via
// exposeRemoteWebClientAtomicBool and the disable-web-client node attr
// via ShouldRunWebClient to determine whether the web client should be
// exposed.
func ( b * LocalBackend ) ShouldExposeRemoteWebClient ( ) bool {
return b . ShouldRunWebClient ( ) && b . exposeRemoteWebClientAtomicBool . Load ( )
}
2024-03-18 16:32:33 +00:00
// setWebClientAtomicBoolLocked sets webClientAtomicBool based on whether
2024-03-18 21:47:21 +00:00
// tailcfg.NodeAttrDisableWebClient has been set in the netmap.NetworkMap.
2024-03-18 16:32:33 +00:00
//
// b.mu must be held.
2024-03-18 21:47:21 +00:00
func ( b * LocalBackend ) setWebClientAtomicBoolLocked ( nm * netmap . NetworkMap ) {
2024-03-22 21:33:41 +00:00
shouldRun := ! nm . HasCap ( tailcfg . NodeAttrDisableWebClient )
2023-11-02 16:55:01 +00:00
wasRunning := b . webClientAtomicBool . Swap ( shouldRun )
if wasRunning && ! shouldRun {
2023-11-15 22:40:37 +00:00
go b . webClientShutdown ( ) // stop web client
2023-11-02 16:55:01 +00:00
}
2023-10-26 18:35:41 +00:00
}
2024-03-18 21:47:21 +00:00
// setExposeRemoteWebClientAtomicBoolLocked sets exposeRemoteWebClientAtomicBool
// based on whether the RunWebClient pref is set.
//
// b.mu must be held.
func ( b * LocalBackend ) setExposeRemoteWebClientAtomicBoolLocked ( prefs ipn . PrefsView ) {
shouldExpose := prefs . Valid ( ) && prefs . RunWebClient ( )
b . exposeRemoteWebClientAtomicBool . Store ( shouldExpose )
}
2022-09-25 18:29:55 +00:00
// ShouldHandleViaIP reports whether ip is an IPv6 address in the
2022-03-30 15:47:16 +00:00
// Tailscale ULA's v6 "via" range embedding an IPv4 address to be forwarded to
// by Tailscale.
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
func ( b * LocalBackend ) ShouldHandleViaIP ( ip netip . Addr ) bool {
2022-08-04 17:43:49 +00:00
if f , ok := b . containsViaIPFuncAtomic . LoadOk ( ) ; ok {
2022-03-30 15:47:16 +00:00
return f ( ip )
}
return false
}
2023-09-01 02:11:20 +00:00
// Logout logs out the current profile, if any, and waits for the logout to
// complete.
func ( b * LocalBackend ) Logout ( ctx context . Context ) error {
2024-04-07 04:16:00 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2023-09-01 00:44:13 +00:00
if ! b . hasNodeKeyLocked ( ) {
// Already logged out.
return nil
}
2021-04-08 04:12:16 +00:00
cc := b . cc
2023-09-01 00:44:13 +00:00
// Grab the current profile before we unlock the mutex, so that we can
// delete it later.
profile := b . pm . CurrentProfile ( )
2020-02-28 19:39:13 +00:00
2024-04-03 17:51:51 +00:00
_ , err := b . editPrefsLockedOnEntry ( & ipn . MaskedPrefs {
2021-04-08 04:06:31 +00:00
WantRunningSet : true ,
2021-04-30 07:56:11 +00:00
LoggedOutSet : true ,
Prefs : ipn . Prefs { WantRunning : false , LoggedOut : true } ,
2024-04-03 17:51:51 +00:00
} , unlock )
2023-09-01 00:44:13 +00:00
if err != nil {
return err
}
2024-04-03 17:51:51 +00:00
// b.mu is now unlocked, after editPrefsLockedOnEntry.
2021-04-08 04:06:31 +00:00
2022-09-23 17:06:55 +00:00
// Clear any previous dial plan(s), if set.
2024-04-30 19:09:12 +00:00
b . resetDialPlan ( )
2022-09-23 17:06:55 +00:00
2021-04-08 04:12:16 +00:00
if cc == nil {
2020-09-11 22:10:29 +00:00
// Double Logout can happen via repeated IPN
// connections to ipnserver making it repeatedly
// transition from 1->0 total connections, which on
// Windows by default ("client mode") causes a Logout
// on the transition to zero.
// Previously this crashed when we asserted that c was non-nil
// here.
2021-04-08 04:06:31 +00:00
return errors . New ( "no controlclient" )
2020-09-11 22:10:29 +00:00
}
2023-09-01 00:44:13 +00:00
if err := cc . Logout ( ctx ) ; err != nil {
return err
}
2024-04-06 18:05:56 +00:00
2024-04-07 04:16:00 +00:00
unlock = b . lockAndGetUnlock ( )
2024-04-06 18:05:56 +00:00
defer unlock ( )
2023-09-01 00:44:13 +00:00
if err := b . pm . DeleteProfile ( profile . ID ) ; err != nil {
b . logf ( "error deleting profile: %v" , err )
return err
}
2024-04-06 18:05:56 +00:00
return b . resetForProfileChangeLockedOnEntry ( unlock )
2020-02-25 20:30:28 +00:00
}
2020-06-15 23:04:12 +00:00
// setNetInfo sets b.hostinfo.NetInfo to ni, and passes ni along to the
2020-05-19 02:32:20 +00:00
// controlclient, if one exists.
func ( b * LocalBackend ) setNetInfo ( ni * tailcfg . NetInfo ) {
2020-03-04 06:21:56 +00:00
b . mu . Lock ( )
2021-04-08 04:12:16 +00:00
cc := b . cc
2020-03-04 06:21:56 +00:00
b . mu . Unlock ( )
2020-02-25 22:05:17 +00:00
2021-04-08 04:12:16 +00:00
if cc == nil {
2020-03-04 06:21:56 +00:00
return
2020-02-25 22:05:17 +00:00
}
2021-04-08 04:12:16 +00:00
cc . SetNetInfo ( ni )
2020-02-25 22:05:17 +00:00
}
2020-05-27 19:23:17 +00:00
2023-08-04 05:29:27 +00:00
// setNetMapLocked updates the LocalBackend state to reflect the newly
// received nm. If nm is nil, it resets all configuration as though
// Tailscale is turned off.
2021-02-05 23:44:46 +00:00
func ( b * LocalBackend ) setNetMapLocked ( nm * netmap . NetworkMap ) {
2021-12-02 19:10:35 +00:00
b . dialer . SetNetMap ( nm )
2023-09-12 20:37:51 +00:00
if ns , ok := b . sys . Netstack . GetOK ( ) ; ok {
ns . UpdateNetstackIPs ( nm )
}
2020-10-27 19:51:48 +00:00
var login string
if nm != nil {
2024-02-07 22:27:29 +00:00
login = cmp . Or ( nm . UserProfiles [ nm . User ( ) ] . LoginName , "<missing-profile>" )
2020-10-27 19:51:48 +00:00
}
b . netMap = nm
2023-09-17 07:13:52 +00:00
b . updatePeersFromNetmapLocked ( nm )
2020-10-27 19:51:48 +00:00
if login != b . activeLogin {
b . logf ( "active login: %v" , login )
b . activeLogin = login
}
2023-08-04 05:37:52 +00:00
b . pauseOrResumeControlClientLocked ( )
2021-01-28 23:29:17 +00:00
2021-09-18 19:59:55 +00:00
if nm != nil {
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
b . health . SetControlHealth ( nm . ControlHealth )
2021-09-18 19:59:55 +00:00
} else {
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
b . health . SetControlHealth ( nil )
2021-09-18 19:59:55 +00:00
}
2021-04-22 07:25:00 +00:00
// Determine if file sharing is enabled
2024-03-22 21:33:41 +00:00
fs := nm . HasCap ( tailcfg . CapabilityFileSharing )
2021-04-22 07:25:00 +00:00
if fs != b . capFileSharing {
osshare . SetFileSharingEnabled ( fs , b . logf )
}
b . capFileSharing = fs
2024-03-22 21:33:41 +00:00
if nm . HasCap ( tailcfg . NodeAttrLinuxMustUseIPTables ) {
2023-12-04 17:08:56 +00:00
b . capForcedNetfilter = "iptables"
2024-03-22 21:33:41 +00:00
} else if nm . HasCap ( tailcfg . NodeAttrLinuxMustUseNfTables ) {
2023-12-04 17:08:56 +00:00
b . capForcedNetfilter = "nftables"
} else {
b . capForcedNetfilter = "" // empty string means client can auto-detect
}
2023-11-15 23:10:45 +00:00
b . MagicConn ( ) . SetSilentDisco ( b . ControlKnobs ( ) . SilentDisco . Load ( ) )
2024-01-23 17:37:32 +00:00
b . MagicConn ( ) . SetProbeUDPLifetime ( b . ControlKnobs ( ) . ProbeUDPLifetime . Load ( ) )
2023-11-13 18:05:04 +00:00
2023-01-24 19:31:20 +00:00
b . setDebugLogsByCapabilityLocked ( nm )
2023-01-25 18:17:40 +00:00
// See the netns package for documentation on what this capability does.
2024-03-22 21:33:41 +00:00
netns . SetBindToInterfaceByRoute ( nm . HasCap ( tailcfg . CapabilityBindToInterfaceByRoute ) )
netns . SetDisableBindConnToInterface ( nm . HasCap ( tailcfg . CapabilityDebugDisableBindConnToInterface ) )
2023-01-25 18:17:40 +00:00
2022-11-09 05:58:10 +00:00
b . setTCPPortsInterceptedFromNetmapAndPrefsLocked ( b . pm . CurrentPrefs ( ) )
2021-01-28 23:29:17 +00:00
if nm == nil {
b . nodeByAddr = nil
return
}
// Update the nodeByAddr index.
if b . nodeByAddr == nil {
2023-09-17 07:13:52 +00:00
b . nodeByAddr = map [ netip . Addr ] tailcfg . NodeID { }
2021-01-28 23:29:17 +00:00
}
// First pass, mark everything unwanted.
for k := range b . nodeByAddr {
2023-09-17 07:13:52 +00:00
b . nodeByAddr [ k ] = 0
2021-01-28 23:29:17 +00:00
}
2023-08-18 14:57:44 +00:00
addNode := func ( n tailcfg . NodeView ) {
2024-02-25 15:57:11 +00:00
for i := range n . Addresses ( ) . Len ( ) {
2023-08-18 14:57:44 +00:00
if ipp := n . Addresses ( ) . At ( i ) ; ipp . IsSingleIP ( ) {
2023-09-17 07:13:52 +00:00
b . nodeByAddr [ ipp . Addr ( ) ] = n . ID ( )
2021-01-28 23:29:17 +00:00
}
}
}
2023-08-21 17:53:57 +00:00
if nm . SelfNode . Valid ( ) {
addNode ( nm . SelfNode )
2021-01-28 23:29:17 +00:00
}
for _ , p := range nm . Peers {
addNode ( p )
}
// Third pass, actually delete the unwanted items.
for k , v := range b . nodeByAddr {
2023-09-17 07:13:52 +00:00
if v == 0 {
2021-01-28 23:29:17 +00:00
delete ( b . nodeByAddr , k )
}
}
2024-02-02 18:45:32 +00:00
2024-04-03 17:09:58 +00:00
b . updateDrivePeersLocked ( nm )
b . driveNotifyCurrentSharesLocked ( )
2020-10-27 19:51:48 +00:00
}
2023-09-17 07:13:52 +00:00
func ( b * LocalBackend ) updatePeersFromNetmapLocked ( nm * netmap . NetworkMap ) {
if nm == nil {
b . peers = nil
return
}
2024-02-02 18:45:32 +00:00
2023-09-17 07:13:52 +00:00
// First pass, mark everything unwanted.
for k := range b . peers {
b . peers [ k ] = tailcfg . NodeView { }
}
2024-02-02 18:45:32 +00:00
2023-09-17 07:13:52 +00:00
// Second pass, add everything wanted.
for _ , p := range nm . Peers {
mak . Set ( & b . peers , p . ID ( ) , p )
}
2024-02-02 18:45:32 +00:00
2023-09-17 07:13:52 +00:00
// Third pass, remove deleted things.
for k , v := range b . peers {
if ! v . Valid ( ) {
delete ( b . peers , k )
}
}
}
2024-03-26 20:14:43 +00:00
// responseBodyWrapper wraps an io.ReadCloser and stores
// the number of bytesRead.
type responseBodyWrapper struct {
io . ReadCloser
bytesRx int64
bytesTx int64
log logger . Logf
method string
statusCode int
contentType string
fileExtension string
shareNodeKey string
selfNodeKey string
contentLength int64
}
2024-04-04 20:07:58 +00:00
// logAccess logs the taildrive: access: log line. If the logger is nil,
2024-03-26 20:14:43 +00:00
// the log will not be written.
func ( rbw * responseBodyWrapper ) logAccess ( err string ) {
if rbw . log == nil {
return
}
2024-03-26 20:53:17 +00:00
// Some operating systems create and copy lots of 0 length hidden files for
// tracking various states. Omit these to keep logs from being too verbose.
if rbw . contentLength > 0 {
2024-04-04 20:07:58 +00:00
rbw . log ( "taildrive: access: %s from %s to %s: status-code=%d ext=%q content-type=%q content-length=%.f tx=%.f rx=%.f err=%q" , rbw . method , rbw . selfNodeKey , rbw . shareNodeKey , rbw . statusCode , rbw . fileExtension , rbw . contentType , roundTraffic ( rbw . contentLength ) , roundTraffic ( rbw . bytesTx ) , roundTraffic ( rbw . bytesRx ) , err )
2024-03-26 20:53:17 +00:00
}
2024-03-26 20:14:43 +00:00
}
// Read implements the io.Reader interface.
func ( rbw * responseBodyWrapper ) Read ( b [ ] byte ) ( int , error ) {
n , err := rbw . ReadCloser . Read ( b )
rbw . bytesRx += int64 ( n )
if err != nil && ! errors . Is ( err , io . EOF ) {
rbw . logAccess ( err . Error ( ) )
}
return n , err
}
// Close implements the io.Close interface.
func ( rbw * responseBodyWrapper ) Close ( ) error {
err := rbw . ReadCloser . Close ( )
var errStr string
if err != nil {
errStr = err . Error ( )
}
rbw . logAccess ( errStr )
return err
}
2024-05-03 12:21:30 +00:00
// driveTransport is an http.RoundTripper that wraps
// b.Dialer().PeerAPITransport() with metrics tracking.
type driveTransport struct {
b * LocalBackend
tr * http . Transport
}
func ( b * LocalBackend ) newDriveTransport ( ) * driveTransport {
return & driveTransport {
b : b ,
tr : b . Dialer ( ) . PeerAPITransport ( ) ,
}
}
2024-04-03 17:09:58 +00:00
func ( dt * driveTransport ) RoundTrip ( req * http . Request ) ( resp * http . Response , err error ) {
2024-04-16 15:13:30 +00:00
// Some WebDAV clients include origin and refer headers, which peerapi does
// not like. Remove them.
req . Header . Del ( "origin" )
req . Header . Del ( "referer" )
2024-03-26 20:14:43 +00:00
bw := & requestBodyWrapper { }
if req . Body != nil {
bw . ReadCloser = req . Body
req . Body = bw
}
defer func ( ) {
contentType := "unknown"
switch req . Method {
case httpm . PUT :
if ct := req . Header . Get ( "Content-Type" ) ; ct != "" {
contentType = ct
}
case httpm . GET :
if ct := resp . Header . Get ( "Content-Type" ) ; ct != "" {
contentType = ct
}
default :
return
}
2024-04-03 17:09:58 +00:00
dt . b . mu . Lock ( )
selfNodeKey := dt . b . netMap . SelfNode . Key ( ) . ShortString ( )
dt . b . mu . Unlock ( )
n , _ , ok := dt . b . WhoIs ( netip . MustParseAddrPort ( req . URL . Host ) )
2024-03-26 20:14:43 +00:00
shareNodeKey := "unknown"
if ok {
shareNodeKey = string ( n . Key ( ) . ShortString ( ) )
}
rbw := responseBodyWrapper {
2024-04-03 17:09:58 +00:00
log : dt . b . logf ,
2024-03-26 20:14:43 +00:00
method : req . Method ,
bytesTx : int64 ( bw . bytesRead ) ,
selfNodeKey : selfNodeKey ,
shareNodeKey : shareNodeKey ,
contentType : contentType ,
contentLength : resp . ContentLength ,
2024-04-03 17:09:58 +00:00
fileExtension : parseDriveFileExtensionForLog ( req . URL . Path ) ,
2024-03-26 20:14:43 +00:00
statusCode : resp . StatusCode ,
ReadCloser : resp . Body ,
}
2024-03-26 20:53:17 +00:00
if resp . StatusCode >= 400 {
// in case of error response, just log immediately
rbw . logAccess ( "" )
} else {
resp . Body = & rbw
}
2024-03-26 20:14:43 +00:00
} ( )
2024-05-03 12:21:30 +00:00
return dt . tr . RoundTrip ( req )
2024-02-02 18:45:32 +00:00
}
2024-03-26 20:14:43 +00:00
// roundTraffic rounds bytes. This is used to preserve user privacy within logs.
func roundTraffic ( bytes int64 ) float64 {
var x float64
switch {
case bytes <= 5 :
return float64 ( bytes )
case bytes < 1000 :
x = 10
case bytes < 10_000 :
x = 100
case bytes < 100_000 :
x = 1000
case bytes < 1_000_000 :
x = 10_000
case bytes < 10_000_000 :
x = 100_000
case bytes < 100_000_000 :
x = 1_000_000
case bytes < 1_000_000_000 :
x = 10_000_000
default :
x = 100_000_000
}
return math . Round ( float64 ( bytes ) / x ) * x
}
2023-01-24 19:31:20 +00:00
// setDebugLogsByCapabilityLocked sets debug logging based on the self node's
// capabilities in the provided NetMap.
func ( b * LocalBackend ) setDebugLogsByCapabilityLocked ( nm * netmap . NetworkMap ) {
// These are sufficiently cheap (atomic bools) that we don't need to
// store state and compare.
2024-03-22 21:33:41 +00:00
if nm . HasCap ( tailcfg . CapabilityDebugTSDNSResolution ) {
2023-01-24 19:31:20 +00:00
dnscache . SetDebugLoggingEnabled ( true )
} else {
dnscache . SetDebugLoggingEnabled ( false )
}
}
2023-09-05 17:51:52 +00:00
// reloadServeConfigLocked reloads the serve config from the store or resets the
// serve config to nil if not logged in. The "changed" parameter, when false, instructs
// the method to only run the reset-logic and not reload the store from memory to ensure
// foreground sessions are not removed if they are not saved on disk.
2022-11-16 20:51:26 +00:00
func ( b * LocalBackend ) reloadServeConfigLocked ( prefs ipn . PrefsView ) {
2023-08-21 17:53:57 +00:00
if b . netMap == nil || ! b . netMap . SelfNode . Valid ( ) || ! prefs . Valid ( ) || b . pm . CurrentProfile ( ) . ID == "" {
2022-11-16 20:51:26 +00:00
// We're not logged in, so we don't have a profile.
// Don't try to load the serve config.
b . lastServeConfJSON = mem . B ( nil )
b . serveConfig = ipn . ServeConfigView { }
return
}
2023-09-05 17:51:52 +00:00
2022-11-16 20:51:26 +00:00
confKey := ipn . ServeConfigKey ( b . pm . CurrentProfile ( ) . ID )
// TODO(maisem,bradfitz): prevent reading the config from disk
// if the profile has not changed.
confj , err := b . store . ReadState ( confKey )
if err != nil {
b . lastServeConfJSON = mem . B ( nil )
b . serveConfig = ipn . ServeConfigView { }
return
}
if b . lastServeConfJSON . Equal ( mem . B ( confj ) ) {
return
}
b . lastServeConfJSON = mem . B ( confj )
var conf ipn . ServeConfig
if err := json . Unmarshal ( confj , & conf ) ; err != nil {
b . logf ( "invalid ServeConfig %q in StateStore: %v" , confKey , err )
b . serveConfig = ipn . ServeConfigView { }
return
}
2023-09-05 17:51:52 +00:00
// remove inactive sessions
2024-02-28 21:56:30 +00:00
maps . DeleteFunc ( conf . Foreground , func ( sessionID string , sc * ipn . ServeConfig ) bool {
_ , ok := b . notifyWatchers [ sessionID ]
return ! ok
2023-09-05 17:51:52 +00:00
} )
2022-11-16 20:51:26 +00:00
b . serveConfig = conf . View ( )
}
2022-11-07 23:32:53 +00:00
// setTCPPortsInterceptedFromNetmapAndPrefsLocked calls setTCPPortsIntercepted with
// the ports that tailscaled should handle as a function of b.netMap and b.prefs.
//
// b.mu must be held.
2022-11-09 05:58:10 +00:00
func ( b * LocalBackend ) setTCPPortsInterceptedFromNetmapAndPrefsLocked ( prefs ipn . PrefsView ) {
2022-11-07 23:32:53 +00:00
handlePorts := make ( [ ] uint16 , 0 , 4 )
if prefs . Valid ( ) && prefs . RunSSH ( ) && envknob . CanSSHD ( ) {
handlePorts = append ( handlePorts , 22 )
}
2024-03-18 21:47:21 +00:00
if b . ShouldExposeRemoteWebClient ( ) {
2023-11-03 03:05:40 +00:00
handlePorts = append ( handlePorts , webClientPort )
2023-11-09 00:05:33 +00:00
// don't listen on netmap addresses if we're in userspace mode
if ! b . sys . IsNetstack ( ) {
b . updateWebClientListenersLocked ( )
}
2023-11-02 16:32:36 +00:00
}
2022-11-07 23:32:53 +00:00
2022-11-16 20:51:26 +00:00
b . reloadServeConfigLocked ( prefs )
if b . serveConfig . Valid ( ) {
servePorts := make ( [ ] uint16 , 0 , 3 )
2023-09-05 17:51:52 +00:00
b . serveConfig . RangeOverTCPs ( func ( port uint16 , _ ipn . TCPPortHandlerView ) bool {
2022-11-16 20:51:26 +00:00
if port > 0 {
servePorts = append ( servePorts , uint16 ( port ) )
2022-11-07 23:32:53 +00:00
}
2022-11-16 20:51:26 +00:00
return true
} )
handlePorts = append ( handlePorts , servePorts ... )
2022-12-21 18:36:58 +00:00
b . setServeProxyHandlersLocked ( )
2022-11-16 20:51:26 +00:00
// don't listen on netmap addresses if we're in userspace mode
2023-05-03 20:57:17 +00:00
if ! b . sys . IsNetstack ( ) {
2022-11-16 20:51:26 +00:00
b . updateServeTCPPortNetMapAddrListenersLocked ( servePorts )
2022-11-07 23:32:53 +00:00
}
}
2022-11-16 20:51:26 +00:00
// Kick off a Hostinfo update to control if WireIngress changed.
if wire := b . wantIngressLocked ( ) ; b . hostinfo != nil && b . hostinfo . WireIngress != wire {
b . logf ( "Hostinfo.WireIngress changed to %v" , wire )
b . hostinfo . WireIngress = wire
2023-10-23 17:18:40 +00:00
go b . doSetHostinfoFilterServices ( )
2022-11-16 20:51:26 +00:00
}
2022-11-07 23:32:53 +00:00
b . setTCPPortsIntercepted ( handlePorts )
}
2022-12-21 18:36:58 +00:00
// setServeProxyHandlersLocked ensures there is an http proxy handler for each
// backend specified in serveConfig. It expects serveConfig to be valid and
// up-to-date, so should be called after reloadServeConfigLocked.
func ( b * LocalBackend ) setServeProxyHandlersLocked ( ) {
if ! b . serveConfig . Valid ( ) {
return
}
var backends map [ string ] bool
2023-09-05 17:51:52 +00:00
b . serveConfig . RangeOverWebs ( func ( _ ipn . HostPort , conf ipn . WebServerConfigView ) ( cont bool ) {
2022-12-21 18:36:58 +00:00
conf . Handlers ( ) . Range ( func ( _ string , h ipn . HTTPHandlerView ) ( cont bool ) {
backend := h . Proxy ( )
2023-06-21 16:32:20 +00:00
if backend == "" {
// Only create proxy handlers for servers with a proxy backend.
return true
}
2022-12-21 18:36:58 +00:00
mak . Set ( & backends , backend , true )
if _ , ok := b . serveProxyHandlers . Load ( backend ) ; ok {
return true
}
b . logf ( "serve: creating a new proxy handler for %s" , backend )
p , err := b . proxyHandlerForBackend ( backend )
if err != nil {
// The backend endpoint (h.Proxy) should have been validated by expandProxyTarget
// in the CLI, so just log the error here.
b . logf ( "[unexpected] could not create proxy for %v: %s" , backend , err )
return true
}
b . serveProxyHandlers . Store ( backend , p )
return true
} )
return true
} )
// Clean up handlers for proxy backends that are no longer present
// in configuration.
b . serveProxyHandlers . Range ( func ( key , value any ) bool {
backend := key . ( string )
if ! backends [ backend ] {
b . logf ( "serve: closing idle connections to %s" , backend )
b . serveProxyHandlers . Delete ( backend )
2023-10-20 11:04:00 +00:00
value . ( * reverseProxy ) . close ( )
2022-12-21 18:36:58 +00:00
}
return true
} )
}
2022-09-21 20:35:22 +00:00
// operatorUserName returns the current pref's OperatorUser's name, or the
// empty string if none.
func ( b * LocalBackend ) operatorUserName ( ) string {
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-11-09 05:58:10 +00:00
prefs := b . pm . CurrentPrefs ( )
if ! prefs . Valid ( ) {
2022-09-21 20:35:22 +00:00
return ""
}
2022-11-09 05:58:10 +00:00
return prefs . OperatorUser ( )
2022-09-21 20:35:22 +00:00
}
2021-04-17 04:01:29 +00:00
// OperatorUserID returns the current pref's OperatorUser's ID (in
// os/user.User.Uid string form), or the empty string if none.
func ( b * LocalBackend ) OperatorUserID ( ) string {
2022-10-23 17:07:10 +00:00
opUserName := b . operatorUserName ( )
2021-04-17 04:01:29 +00:00
if opUserName == "" {
return ""
}
u , err := user . Lookup ( opUserName )
if err != nil {
b . logf ( "error looking up operator %q uid: %v" , opUserName , err )
return ""
}
return u . Uid
}
2020-05-27 19:23:17 +00:00
// TestOnlyPublicKeys returns the current machine and node public
// keys. Used in tests only to facilitate automated node authorization
// in the test harness.
2021-11-02 01:40:39 +00:00
func ( b * LocalBackend ) TestOnlyPublicKeys ( ) ( machineKey key . MachinePublic , nodeKey key . NodePublic ) {
2020-05-27 19:23:17 +00:00
b . mu . Lock ( )
2020-09-28 22:28:26 +00:00
machinePrivKey := b . machinePrivKey
2022-11-09 05:58:10 +00:00
prefs := b . pm . CurrentPrefs ( )
2020-05-27 19:23:17 +00:00
b . mu . Unlock ( )
2022-10-23 17:07:10 +00:00
if ! prefs . Valid ( ) || machinePrivKey . IsZero ( ) {
2020-05-27 19:23:17 +00:00
return
}
2020-09-28 22:28:26 +00:00
mk := machinePrivKey . Public ( )
2022-10-23 07:48:12 +00:00
nk := prefs . Persist ( ) . PublicNodeKey ( )
2021-11-02 01:40:39 +00:00
return mk , nk
2020-05-27 19:23:17 +00:00
}
2020-10-21 19:55:03 +00:00
2022-11-28 18:34:35 +00:00
func ( b * LocalBackend ) removeFileWaiter ( handle set . Handle ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
delete ( b . fileWaiters , handle )
}
2022-11-20 21:25:54 +00:00
2022-11-28 18:34:35 +00:00
func ( b * LocalBackend ) addFileWaiter ( wakeWaiter context . CancelFunc ) set . Handle {
2022-11-20 21:25:54 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-11-28 18:34:35 +00:00
return b . fileWaiters . Add ( wakeWaiter )
2022-11-20 21:25:54 +00:00
}
2021-04-13 15:13:46 +00:00
func ( b * LocalBackend ) WaitingFiles ( ) ( [ ] apitype . WaitingFile , error ) {
2021-03-30 19:56:00 +00:00
b . mu . Lock ( )
apiSrv := b . peerAPIServer
b . mu . Unlock ( )
2023-10-05 23:05:45 +00:00
return mayDeref ( apiSrv ) . taildrop . WaitingFiles ( )
2021-03-30 19:56:00 +00:00
}
2022-11-20 21:25:54 +00:00
// AwaitWaitingFiles is like WaitingFiles but blocks while ctx is not done,
// waiting for any files to be available.
//
// On return, exactly one of the results will be non-empty or non-nil,
// respectively.
func ( b * LocalBackend ) AwaitWaitingFiles ( ctx context . Context ) ( [ ] apitype . WaitingFile , error ) {
if ff , err := b . WaitingFiles ( ) ; err != nil || len ( ff ) > 0 {
return ff , err
}
for {
gotFile , gotFileCancel := context . WithCancel ( context . Background ( ) )
defer gotFileCancel ( )
2022-11-28 18:34:35 +00:00
handle := b . addFileWaiter ( gotFileCancel )
defer b . removeFileWaiter ( handle )
2022-11-20 21:25:54 +00:00
// Now that we've registered ourselves, check again, in case
// of race. Otherwise there's a small window where we could
// miss a file arrival and wait forever.
if ff , err := b . WaitingFiles ( ) ; err != nil || len ( ff ) > 0 {
return ff , err
}
select {
case <- gotFile . Done ( ) :
if ff , err := b . WaitingFiles ( ) ; err != nil || len ( ff ) > 0 {
return ff , err
}
case <- ctx . Done ( ) :
return nil , ctx . Err ( )
}
}
}
2021-03-30 19:56:00 +00:00
func ( b * LocalBackend ) DeleteFile ( name string ) error {
b . mu . Lock ( )
apiSrv := b . peerAPIServer
b . mu . Unlock ( )
2023-10-05 23:05:45 +00:00
return mayDeref ( apiSrv ) . taildrop . DeleteFile ( name )
2021-03-30 19:56:00 +00:00
}
func ( b * LocalBackend ) OpenFile ( name string ) ( rc io . ReadCloser , size int64 , err error ) {
b . mu . Lock ( )
apiSrv := b . peerAPIServer
b . mu . Unlock ( )
2023-10-05 23:05:45 +00:00
return mayDeref ( apiSrv ) . taildrop . OpenFile ( name )
2021-03-30 19:56:00 +00:00
}
2021-03-31 18:55:21 +00:00
2021-04-16 17:57:46 +00:00
// hasCapFileSharing reports whether the current node has the file
// sharing capability enabled.
func ( b * LocalBackend ) hasCapFileSharing ( ) bool {
b . mu . Lock ( )
defer b . mu . Unlock ( )
2021-04-22 07:25:00 +00:00
return b . capFileSharing
2021-04-16 17:57:46 +00:00
}
2021-04-05 04:35:52 +00:00
// FileTargets lists nodes that the current node can send files to.
2021-04-13 15:13:46 +00:00
func ( b * LocalBackend ) FileTargets ( ) ( [ ] * apitype . FileTarget , error ) {
var ret [ ] * apitype . FileTarget
2021-04-05 04:35:52 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
nm := b . netMap
if b . state != ipn . Running || nm == nil {
2022-06-08 16:11:50 +00:00
return nil , errors . New ( "not connected to the tailnet" )
2021-04-05 04:35:52 +00:00
}
2021-04-29 17:26:53 +00:00
if ! b . capFileSharing {
return nil , errors . New ( "file sharing not enabled by Tailscale admin" )
}
2023-09-17 07:13:52 +00:00
for _ , p := range b . peers {
2022-10-08 04:03:36 +00:00
if ! b . peerIsTaildropTargetLocked ( p ) {
2021-04-05 04:35:52 +00:00
continue
}
2023-10-27 21:35:18 +00:00
if p . Hostinfo ( ) . OS ( ) == "tvOS" {
continue
}
2021-04-05 04:35:52 +00:00
peerAPI := peerAPIBase ( b . netMap , p )
if peerAPI == "" {
continue
}
2021-04-13 15:13:46 +00:00
ret = append ( ret , & apitype . FileTarget {
2023-08-18 14:57:44 +00:00
Node : p . AsStruct ( ) ,
2021-04-05 04:35:52 +00:00
PeerAPIURL : peerAPI ,
} )
}
2023-09-17 07:13:52 +00:00
slices . SortFunc ( ret , func ( a , b * apitype . FileTarget ) int {
2023-12-18 22:43:01 +00:00
return cmp . Compare ( a . Node . Name , b . Node . Name )
2023-09-17 07:13:52 +00:00
} )
2021-04-05 04:35:52 +00:00
return ret , nil
}
2022-10-08 04:03:36 +00:00
// peerIsTaildropTargetLocked reports whether p is a valid Taildrop file
// recipient from this node according to its ownership and the capabilities in
// the netmap.
//
// b.mu must be locked.
2023-08-18 14:57:44 +00:00
func ( b * LocalBackend ) peerIsTaildropTargetLocked ( p tailcfg . NodeView ) bool {
if b . netMap == nil || ! p . Valid ( ) {
2022-10-08 04:03:36 +00:00
return false
}
2023-08-20 22:17:25 +00:00
if b . netMap . User ( ) == p . User ( ) {
2022-10-08 04:03:36 +00:00
return true
}
2023-08-18 14:57:44 +00:00
if p . Addresses ( ) . Len ( ) > 0 &&
b . peerHasCapLocked ( p . Addresses ( ) . At ( 0 ) . Addr ( ) , tailcfg . PeerCapabilityFileSharingTarget ) {
2022-10-08 04:03:36 +00:00
// Explicitly noted in the netmap ACL caps as a target.
return true
}
return false
}
2023-07-25 04:07:00 +00:00
func ( b * LocalBackend ) peerHasCapLocked ( addr netip . Addr , wantCap tailcfg . PeerCapability ) bool {
return b . peerCapsLocked ( addr ) . HasCapability ( wantCap )
2022-09-19 17:36:07 +00:00
}
2021-06-07 23:03:16 +00:00
// SetDNS adds a DNS record for the given domain name & TXT record
// value.
//
// It's meant for use with dns-01 ACME (LetsEncrypt) challenges.
//
// This is the low-level interface. Other layers will provide more
// friendly options to get HTTPS certs.
func ( b * LocalBackend ) SetDNS ( ctx context . Context , name , value string ) error {
req := & tailcfg . SetDNSRequest {
2022-03-06 17:32:52 +00:00
Version : 1 , // TODO(bradfitz,maisem): use tailcfg.CurrentCapabilityVersion when using the Noise transport
2021-06-07 23:03:16 +00:00
Type : "TXT" ,
Name : name ,
Value : value ,
}
b . mu . Lock ( )
2022-06-20 01:00:50 +00:00
cc := b . ccAuto
2022-11-29 20:00:40 +00:00
if prefs := b . pm . CurrentPrefs ( ) ; prefs . Valid ( ) && prefs . Persist ( ) . Valid ( ) {
req . NodeKey = prefs . Persist ( ) . PrivateNodeKey ( ) . Public ( )
2021-06-07 23:03:16 +00:00
}
b . mu . Unlock ( )
if cc == nil {
return errors . New ( "not connected" )
}
if req . NodeKey . IsZero ( ) {
return errors . New ( "no nodekey" )
}
if name == "" {
return errors . New ( "missing 'name'" )
}
if value == "" {
return errors . New ( "missing 'value'" )
}
return cc . SetDNS ( ctx , req )
}
2023-08-18 14:57:44 +00:00
func peerAPIPorts ( peer tailcfg . NodeView ) ( p4 , p6 uint16 ) {
svcs := peer . Hostinfo ( ) . Services ( )
2024-02-25 15:57:11 +00:00
for i := range svcs . Len ( ) {
2022-11-17 20:22:00 +00:00
s := svcs . At ( i )
switch s . Proto {
case tailcfg . PeerAPI4 :
p4 = s . Port
case tailcfg . PeerAPI6 :
p6 = s . Port
}
}
return
}
2022-11-19 21:10:45 +00:00
// peerAPIURL returns an HTTP URL for the peer's peerapi service,
// without a trailing slash.
//
// If ip or port is the zero value then it returns the empty string.
2022-11-17 20:22:00 +00:00
func peerAPIURL ( ip netip . Addr , port uint16 ) string {
if port == 0 || ! ip . IsValid ( ) {
return ""
}
return fmt . Sprintf ( "http://%v" , netip . AddrPortFrom ( ip , port ) )
}
2021-04-05 04:35:52 +00:00
// peerAPIBase returns the "http://ip:port" URL base to reach peer's peerAPI.
// It returns the empty string if the peer doesn't support the peerapi
// or there's no matching address family based on the netmap's own addresses.
2023-08-18 14:57:44 +00:00
func peerAPIBase ( nm * netmap . NetworkMap , peer tailcfg . NodeView ) string {
if nm == nil || ! peer . Valid ( ) || ! peer . Hostinfo ( ) . Valid ( ) {
2021-04-05 04:35:52 +00:00
return ""
}
2022-02-15 16:19:44 +00:00
2021-04-05 04:35:52 +00:00
var have4 , have6 bool
2023-09-18 06:31:34 +00:00
addrs := nm . GetAddresses ( )
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-09-18 06:31:34 +00:00
a := addrs . At ( i )
2021-04-05 04:35:52 +00:00
if ! a . IsSingleIP ( ) {
continue
}
switch {
2022-07-25 03:08:42 +00:00
case a . Addr ( ) . Is4 ( ) :
2021-04-05 04:35:52 +00:00
have4 = true
2022-07-25 03:08:42 +00:00
case a . Addr ( ) . Is6 ( ) :
2021-04-05 04:35:52 +00:00
have6 = true
}
}
2022-11-17 20:22:00 +00:00
p4 , p6 := peerAPIPorts ( peer )
2021-04-05 04:35:52 +00:00
switch {
case have4 && p4 != 0 :
2022-11-17 20:22:00 +00:00
return peerAPIURL ( nodeIP ( peer , netip . Addr . Is4 ) , p4 )
2021-04-05 04:35:52 +00:00
case have6 && p6 != 0 :
2022-11-17 20:22:00 +00:00
return peerAPIURL ( nodeIP ( peer , netip . Addr . Is6 ) , p6 )
2021-04-05 04:35:52 +00:00
}
2022-11-17 20:22:00 +00:00
return ""
2021-04-05 04:35:52 +00:00
}
2023-08-18 14:57:44 +00:00
func nodeIP ( n tailcfg . NodeView , pred func ( netip . Addr ) bool ) netip . Addr {
2024-02-25 15:57:11 +00:00
for i := range n . Addresses ( ) . Len ( ) {
2023-08-18 14:57:44 +00:00
a := n . Addresses ( ) . At ( i )
2022-07-25 03:08:42 +00:00
if a . IsSingleIP ( ) && pred ( a . Addr ( ) ) {
return a . Addr ( )
2021-04-05 04:35:52 +00:00
}
}
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
return netip . Addr { }
2021-04-05 04:35:52 +00:00
}
2021-03-31 18:55:21 +00:00
func ( b * LocalBackend ) CheckIPForwarding ( ) error {
2023-05-03 20:57:17 +00:00
if b . sys . IsNetstackRouter ( ) {
2021-03-31 18:55:21 +00:00
return nil
}
2021-11-26 00:12:08 +00:00
2022-03-28 17:24:11 +00:00
// TODO: let the caller pass in the ranges.
2023-08-01 22:47:54 +00:00
warn , err := netutil . CheckIPForwarding ( tsaddr . ExitRoutes ( ) , b . sys . NetMon . Get ( ) . InterfaceState ( ) )
2021-11-26 00:12:08 +00:00
if err != nil {
2022-03-28 17:24:11 +00:00
return err
2021-03-31 18:55:21 +00:00
}
2022-03-28 17:24:11 +00:00
return warn
2021-03-31 18:55:21 +00:00
}
2021-04-06 20:38:47 +00:00
2023-11-09 19:34:41 +00:00
// CheckUDPGROForwarding checks if the machine is optimally configured to
// forward UDP packets between the default route and Tailscale TUN interfaces.
// It returns an error if the check fails or if suboptimal configuration is
// detected. No error is returned if we are unable to gather the interface
// names from the relevant subsystems.
func ( b * LocalBackend ) CheckUDPGROForwarding ( ) error {
if b . sys . IsNetstackRouter ( ) {
return nil
}
// We return nil when the interface name or subsystem it's tied to can't be
// fetched. This is intentional as answering the question "are netdev
// features optimal for performance?" is a low priority in that situation.
tunSys , ok := b . sys . Tun . GetOK ( )
if ! ok {
return nil
}
tunInterface , err := tunSys . Name ( )
if err != nil {
return nil
}
netmonSys , ok := b . sys . NetMon . GetOK ( )
if ! ok {
return nil
}
state := netmonSys . InterfaceState ( )
if state == nil {
return nil
}
// We return warn or err. If err is non-nil there was a problem
// communicating with the kernel via ethtool semantics/ioctl. ethtool ioctl
// errors are interesting for our future selves as we consider tweaking
// netdev features automatically using similar API infra.
warn , err := netkernelconf . CheckUDPGROForwarding ( tunInterface , state . DefaultRouteInterface )
if err != nil {
return err
}
return warn
}
2024-06-10 18:19:03 +00:00
// SetUDPGROForwarding enables UDP GRO forwarding for the default network
// interface of this machine. It can be done to improve performance for nodes
// acting as Tailscale subnet routers or exit nodes. Currently (9/5/2024) this
// functionality is considered experimental and only safe to use via explicit
// user opt-in for ephemeral devices, such as containers.
// https://tailscale.com/kb/1320/performance-best-practices#linux-optimizations-for-subnet-routers-and-exit-nodes
func ( b * LocalBackend ) SetUDPGROForwarding ( ) error {
if b . sys . IsNetstackRouter ( ) {
return errors . New ( "UDP GRO forwarding cannot be enabled in userspace mode" )
}
tunSys , ok := b . sys . Tun . GetOK ( )
if ! ok {
return errors . New ( "[unexpected] unable to retrieve tun device configuration" )
}
tunInterface , err := tunSys . Name ( )
if err != nil {
return errors . New ( "[unexpected] unable to determine name of the tun device" )
}
netmonSys , ok := b . sys . NetMon . GetOK ( )
if ! ok {
return errors . New ( "[unexpected] unable to retrieve tailscale netmon configuration" )
}
state := netmonSys . InterfaceState ( )
if state == nil {
return errors . New ( "[unexpected] unable to retrieve machine's network interface state" )
}
if err := netkernelconf . SetUDPGROForwarding ( tunInterface , state . DefaultRouteInterface ) ; err != nil {
return fmt . Errorf ( "error enabling UDP GRO forwarding: %w" , err )
}
return nil
}
2021-06-25 18:44:40 +00:00
// DERPMap returns the current DERPMap in use, or nil if not connected.
func ( b * LocalBackend ) DERPMap ( ) * tailcfg . DERPMap {
b . mu . Lock ( )
defer b . mu . Unlock ( )
if b . netMap == nil {
return nil
}
return b . netMap . DERPMap
}
2021-11-23 05:45:34 +00:00
// OfferingExitNode reports whether b is currently offering exit node
// access.
func ( b * LocalBackend ) OfferingExitNode ( ) bool {
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-11-09 05:58:10 +00:00
if ! b . pm . CurrentPrefs ( ) . Valid ( ) {
2021-11-23 05:45:34 +00:00
return false
}
var def4 , def6 bool
2022-11-09 05:58:10 +00:00
ar := b . pm . CurrentPrefs ( ) . AdvertiseRoutes ( )
2024-04-16 20:15:13 +00:00
for i := range ar . Len ( ) {
2022-10-23 17:07:10 +00:00
r := ar . At ( i )
2021-11-23 05:45:34 +00:00
if r . Bits ( ) != 0 {
continue
}
2022-07-25 03:08:42 +00:00
if r . Addr ( ) . Is4 ( ) {
2021-11-23 05:45:34 +00:00
def4 = true
2022-07-25 03:08:42 +00:00
} else if r . Addr ( ) . Is6 ( ) {
2021-11-23 05:45:34 +00:00
def6 = true
}
}
return def4 && def6
}
2021-11-29 22:18:09 +00:00
2023-10-27 21:20:10 +00:00
// OfferingAppConnector reports whether b is currently offering app
// connector services.
func ( b * LocalBackend ) OfferingAppConnector ( ) bool {
b . mu . Lock ( )
defer b . mu . Unlock ( )
return b . appConnector != nil
}
2021-11-29 22:18:09 +00:00
// allowExitNodeDNSProxyToServeName reports whether the Exit Node DNS
// proxy is allowed to serve responses for the provided DNS name.
func ( b * LocalBackend ) allowExitNodeDNSProxyToServeName ( name string ) bool {
b . mu . Lock ( )
defer b . mu . Unlock ( )
nm := b . netMap
if nm == nil {
return false
}
name = strings . ToLower ( name )
for _ , bad := range nm . DNS . ExitNodeFilteredSet {
if bad == "" {
// Invalid, ignore.
continue
}
if bad [ 0 ] == '.' {
// Entries beginning with a dot are suffix matches.
if dnsname . HasSuffix ( name , bad ) {
return false
}
continue
}
// Otherwise entries are exact matches. They're
// guaranteed to be lowercase already.
if name == bad {
return false
}
}
return true
}
2021-11-30 23:19:18 +00:00
2022-03-09 22:42:42 +00:00
// SetExpiry updates the expiry of the current node key to t, as long as it's
// only sooner than the old expiry.
//
// If t is in the past, the key is expired immediately.
// If t is after the current expiry, an error is returned.
func ( b * LocalBackend ) SetExpirySooner ( ctx context . Context , expiry time . Time ) error {
2022-06-20 05:00:22 +00:00
b . mu . Lock ( )
cc := b . ccAuto
b . mu . Unlock ( )
if cc == nil {
return errors . New ( "not running" )
}
return cc . SetExpirySooner ( ctx , expiry )
2022-03-09 22:42:42 +00:00
}
2021-11-30 23:19:18 +00:00
// exitNodeCanProxyDNS reports the DoH base URL ("http://foo/dns-query") without query parameters
// to exitNodeID's DoH service, if available.
//
// If exitNodeID is the zero valid, it returns "", false.
2023-09-17 07:13:52 +00:00
func exitNodeCanProxyDNS ( nm * netmap . NetworkMap , peers map [ tailcfg . NodeID ] tailcfg . NodeView , exitNodeID tailcfg . StableNodeID ) ( dohURL string , ok bool ) {
2021-11-30 23:19:18 +00:00
if exitNodeID . IsZero ( ) {
return "" , false
}
2023-09-17 07:13:52 +00:00
for _ , p := range peers {
2023-08-18 14:57:44 +00:00
if p . StableID ( ) == exitNodeID && peerCanProxyDNS ( p ) {
2023-01-19 20:40:58 +00:00
return peerAPIBase ( nm , p ) + "/dns-query" , true
2021-11-30 23:19:18 +00:00
}
}
return "" , false
}
2021-12-28 21:39:04 +00:00
2023-09-20 20:07:48 +00:00
// wireguardExitNodeDNSResolvers returns the DNS resolvers to use for a
// WireGuard-only exit node, if it has resolver addresses.
func wireguardExitNodeDNSResolvers ( nm * netmap . NetworkMap , peers map [ tailcfg . NodeID ] tailcfg . NodeView , exitNodeID tailcfg . StableNodeID ) ( [ ] * dnstype . Resolver , bool ) {
if exitNodeID . IsZero ( ) {
return nil , false
}
for _ , p := range peers {
if p . StableID ( ) == exitNodeID {
if p . IsWireGuardOnly ( ) {
resolvers := p . ExitNodeDNSResolvers ( )
if ! resolvers . IsNil ( ) && resolvers . Len ( ) > 0 {
copies := make ( [ ] * dnstype . Resolver , resolvers . Len ( ) )
2024-02-25 15:57:11 +00:00
for i := range resolvers . Len ( ) {
2023-09-20 20:07:48 +00:00
copies [ i ] = resolvers . At ( i ) . AsStruct ( )
}
return copies , true
}
}
return nil , false
}
}
return nil , false
}
2023-08-18 14:57:44 +00:00
func peerCanProxyDNS ( p tailcfg . NodeView ) bool {
if p . Cap ( ) >= 26 {
2023-01-19 20:40:58 +00:00
// Actually added at 25
// (https://github.com/tailscale/tailscale/blob/3ae6f898cfdb58fd0e30937147dd6ce28c6808dd/tailcfg/tailcfg.go#L51)
// so anything >= 26 can do it.
return true
}
// If p.Cap is not populated (e.g. older control server), then do the old
// thing of searching through services.
2023-08-18 14:57:44 +00:00
services := p . Hostinfo ( ) . Services ( )
2024-02-25 15:57:11 +00:00
for i := range services . Len ( ) {
2023-08-18 14:57:44 +00:00
if s := services . At ( i ) ; s . Proto == tailcfg . PeerAPIDNS && s . Port >= 1 {
2023-01-19 20:40:58 +00:00
return true
}
}
return false
}
2021-12-28 21:39:04 +00:00
func ( b * LocalBackend ) DebugRebind ( ) error {
2023-11-15 23:10:45 +00:00
b . MagicConn ( ) . Rebind ( )
2021-12-28 21:39:04 +00:00
return nil
}
func ( b * LocalBackend ) DebugReSTUN ( ) error {
2023-11-15 23:10:45 +00:00
b . MagicConn ( ) . ReSTUN ( "explicit-debug" )
2021-12-28 21:39:04 +00:00
return nil
}
2023-09-11 19:03:39 +00:00
// ControlKnobs returns the node's control knobs.
func ( b * LocalBackend ) ControlKnobs ( ) * controlknobs . Knobs {
return b . sys . ControlKnobs ( )
}
2023-11-15 23:10:45 +00:00
// MagicConn returns the backend's *magicsock.Conn.
func ( b * LocalBackend ) MagicConn ( ) * magicsock . Conn {
2023-09-13 03:34:44 +00:00
return b . sys . MagicSock . Get ( )
2021-12-28 21:39:04 +00:00
}
2022-03-10 18:28:42 +00:00
2022-11-02 03:37:13 +00:00
type keyProvingNoiseRoundTripper struct {
b * LocalBackend
2022-10-16 20:56:46 +00:00
}
2022-11-02 03:37:13 +00:00
func ( n keyProvingNoiseRoundTripper ) RoundTrip ( req * http . Request ) ( * http . Response , error ) {
b := n . b
var priv key . NodePrivate
b . mu . Lock ( )
cc := b . ccAuto
if nm := b . netMap ; nm != nil {
priv = nm . PrivateKey
}
b . mu . Unlock ( )
if cc == nil {
return nil , errors . New ( "no client" )
}
if priv . IsZero ( ) {
return nil , errors . New ( "no netmap or private key" )
}
rt , ep , err := cc . GetSingleUseNoiseRoundTripper ( req . Context ( ) )
if err != nil {
return nil , err
}
if ep == nil || ep . NodeKeyChallenge . IsZero ( ) {
go rt . RoundTrip ( new ( http . Request ) ) // return our reservation with a bogus request
return nil , errors . New ( "this coordination server does not support API calls over the Noise channel" )
}
// QueryEscape the node key since it has a colon in it.
nk := url . QueryEscape ( priv . Public ( ) . String ( ) )
req . SetBasicAuth ( nk , "" )
// genNodeProofHeaderValue returns the Tailscale-Node-Proof header's value to prove
// to chalPub that we control claimedPrivate.
genNodeProofHeaderValue := func ( claimedPrivate key . NodePrivate , chalPub key . ChallengePublic ) string {
// TODO(bradfitz): cache this somewhere?
box := claimedPrivate . SealToChallenge ( chalPub , [ ] byte ( chalPub . String ( ) ) )
return claimedPrivate . Public ( ) . String ( ) + " " + base64 . StdEncoding . EncodeToString ( box )
}
// And prove we have the private key corresponding to the public key sent
// tin the basic auth username.
req . Header . Set ( "Tailscale-Node-Proof" , genNodeProofHeaderValue ( priv , ep . NodeKeyChallenge ) )
return rt . RoundTrip ( req )
2022-10-16 20:56:46 +00:00
}
2022-11-02 03:37:13 +00:00
// KeyProvingNoiseRoundTripper returns an http.RoundTripper that uses the LocalBackend's
// DoNoiseRequest method and mutates the request to add an authorization header
// to prove the client's nodekey.
func ( b * LocalBackend ) KeyProvingNoiseRoundTripper ( ) http . RoundTripper {
return keyProvingNoiseRoundTripper { b }
2022-10-16 20:56:46 +00:00
}
2022-09-25 18:29:55 +00:00
// DoNoiseRequest sends a request to URL over the control plane
2022-03-10 18:28:42 +00:00
// Noise connection.
func ( b * LocalBackend ) DoNoiseRequest ( req * http . Request ) ( * http . Response , error ) {
b . mu . Lock ( )
2022-06-20 01:00:50 +00:00
cc := b . ccAuto
2022-03-10 18:28:42 +00:00
b . mu . Unlock ( )
if cc == nil {
return nil , errors . New ( "no client" )
}
return cc . DoNoiseRequest ( req )
}
2022-04-15 20:19:13 +00:00
2022-05-30 09:06:46 +00:00
func ( b * LocalBackend ) sshServerOrInit ( ) ( _ SSHServer , err error ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
if b . sshServer != nil {
return b . sshServer , nil
}
if newSSHServer == nil {
return nil , errors . New ( "no SSH server support" )
}
b . sshServer , err = newSSHServer ( b . logf , b )
if err != nil {
return nil , fmt . Errorf ( "newSSHServer: %w" , err )
}
return b . sshServer , nil
}
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
var warnSSHSELinuxWarnable = health . Register ( & health . Warnable {
Code : "ssh-unavailable-selinux-enabled" ,
Title : "Tailscale SSH and SELinux" ,
Severity : health . SeverityLow ,
Text : health . StaticMessage ( "SELinux is enabled; Tailscale SSH may not work. See https://tailscale.com/s/ssh-selinux" ) ,
} )
2023-01-24 03:48:19 +00:00
2023-06-01 23:13:18 +00:00
func ( b * LocalBackend ) updateSELinuxHealthWarning ( ) {
if hostinfo . IsSELinuxEnforcing ( ) {
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
b . health . SetUnhealthy ( warnSSHSELinuxWarnable , nil )
2023-01-24 03:48:19 +00:00
} else {
health: begin work to use structured health warnings instead of strings, pipe changes into ipn.Notify (#12406)
Updates tailscale/tailscale#4136
This PR is the first round of work to move from encoding health warnings as strings and use structured data instead. The current health package revolves around the idea of Subsystems. Each subsystem can have (or not have) a Go error associated with it. The overall health of the backend is given by the concatenation of all these errors.
This PR polishes the concept of Warnable introduced by @bradfitz a few weeks ago. Each Warnable is a component of the backend (for instance, things like 'dns' or 'magicsock' are Warnables). Each Warnable has a unique identifying code. A Warnable is an entity we can warn the user about, by setting (or unsetting) a WarningState for it. Warnables have:
- an identifying Code, so that the GUI can track them as their WarningStates come and go
- a Title, which the GUIs can use to tell the user what component of the backend is broken
- a Text, which is a function that is called with a set of Args to generate a more detailed error message to explain the unhappy state
Additionally, this PR also begins to send Warnables and their WarningStates through LocalAPI to the clients, using ipn.Notify messages. An ipn.Notify is only issued when a warning is added or removed from the Tracker.
In a next PR, we'll get rid of subsystems entirely, and we'll start using structured warnings for all errors affecting the backend functionality.
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2024-06-14 18:53:56 +00:00
b . health . SetHealthy ( warnSSHSELinuxWarnable )
2023-01-24 03:48:19 +00:00
}
}
2023-06-08 23:57:40 +00:00
func ( b * LocalBackend ) handleSSHConn ( c net . Conn ) ( err error ) {
2022-05-30 09:06:46 +00:00
s , err := b . sshServerOrInit ( )
if err != nil {
return err
2022-04-15 20:19:13 +00:00
}
2023-06-01 23:13:18 +00:00
b . updateSELinuxHealthWarning ( )
2022-05-30 09:06:46 +00:00
return s . HandleSSHConn ( c )
2022-04-15 20:19:13 +00:00
}
2022-05-05 21:53:36 +00:00
// HandleQuad100Port80Conn serves http://100.100.100.100/ on port 80 (and
// the equivalent tsaddr.TailscaleServiceIPv6 address).
2023-06-08 23:57:40 +00:00
func ( b * LocalBackend ) HandleQuad100Port80Conn ( c net . Conn ) error {
2022-05-05 21:53:36 +00:00
var s http . Server
s . Handler = http . HandlerFunc ( b . handleQuad100Port80Conn )
2023-06-08 23:57:40 +00:00
return s . Serve ( netutil . NewOneConnListener ( c , nil ) )
2022-05-05 21:53:36 +00:00
}
2022-11-16 19:38:25 +00:00
func validQuad100Host ( h string ) bool {
switch h {
case "" ,
tsaddr . TailscaleServiceIPString ,
tsaddr . TailscaleServiceIPv6String ,
"[" + tsaddr . TailscaleServiceIPv6String + "]" :
return true
}
return false
}
2022-05-05 21:53:36 +00:00
func ( b * LocalBackend ) handleQuad100Port80Conn ( w http . ResponseWriter , r * http . Request ) {
w . Header ( ) . Set ( "X-Frame-Options" , "DENY" )
w . Header ( ) . Set ( "Content-Security-Policy" , "default-src 'self';" )
if r . Method != "GET" && r . Method != "HEAD" {
http . Error ( w , "method not allowed" , http . StatusMethodNotAllowed )
return
}
2022-11-16 19:38:25 +00:00
if ! validQuad100Host ( r . Host ) {
2022-11-16 16:16:17 +00:00
http . Error ( w , "bad request" , http . StatusBadRequest )
return
}
2022-05-05 21:53:36 +00:00
b . mu . Lock ( )
defer b . mu . Unlock ( )
io . WriteString ( w , "<h1>Tailscale</h1>\n" )
if b . netMap == nil {
io . WriteString ( w , "No netmap.\n" )
return
}
2023-09-17 17:53:23 +00:00
addrs := b . netMap . GetAddresses ( )
if addrs . Len ( ) == 0 {
2022-05-05 21:53:36 +00:00
io . WriteString ( w , "No local addresses.\n" )
return
}
io . WriteString ( w , "<p>Local addresses:</p><ul>\n" )
2024-02-25 15:57:11 +00:00
for i := range addrs . Len ( ) {
2023-09-17 17:53:23 +00:00
fmt . Fprintf ( w , "<li>%v</li>\n" , addrs . At ( i ) . Addr ( ) )
2022-05-05 21:53:36 +00:00
}
io . WriteString ( w , "</ul>\n" )
}
2022-09-26 17:07:28 +00:00
func ( b * LocalBackend ) Doctor ( ctx context . Context , logf logger . Logf ) {
2023-01-31 18:35:11 +00:00
// We can write logs too fast for logtail to handle, even when
// opting-out of rate limits. Limit ourselves to at most one message
// per 20ms and a burst of 60 log lines, which should be fast enough to
// not block for too long but slow enough that we can upload all lines.
2023-07-27 19:41:31 +00:00
logf = logger . SlowLoggerWithClock ( ctx , logf , 20 * time . Millisecond , 60 , b . clock . Now )
2022-09-26 17:07:28 +00:00
2023-01-31 18:35:11 +00:00
var checks [ ] doctor . Check
2023-03-29 15:27:12 +00:00
checks = append ( checks ,
permissions . Check { } ,
routetable . Check { } ,
2024-02-15 00:19:59 +00:00
ethtool . Check { } ,
2023-03-29 15:27:12 +00:00
)
2022-09-26 17:07:28 +00:00
2023-02-02 16:14:24 +00:00
// Print a log message if any of the global DNS resolvers are Tailscale
// IPs; this can interfere with our ability to connect to the Tailscale
// controlplane.
checks = append ( checks , doctor . CheckFunc ( "dns-resolvers" , func ( _ context . Context , logf logger . Logf ) error {
b . mu . Lock ( )
nm := b . netMap
b . mu . Unlock ( )
if nm == nil {
return nil
}
for i , resolver := range nm . DNS . Resolvers {
ipp , ok := resolver . IPPort ( )
if ok && tsaddr . IsTailscaleIP ( ipp . Addr ( ) ) {
logf ( "resolver %d is a Tailscale address: %v" , i , resolver )
}
}
for i , resolver := range nm . DNS . FallbackResolvers {
ipp , ok := resolver . IPPort ( )
if ok && tsaddr . IsTailscaleIP ( ipp . Addr ( ) ) {
logf ( "fallback resolver %d is a Tailscale address: %v" , i , resolver )
}
}
return nil
} ) )
2022-09-26 17:07:28 +00:00
// TODO(andrew): more
numChecks := len ( checks )
checks = append ( checks , doctor . CheckFunc ( "numchecks" , func ( _ context . Context , log logger . Logf ) error {
log ( "%d checks" , numChecks )
return nil
} ) )
doctor . RunChecks ( ctx , logf , checks ... )
}
2022-11-07 21:04:10 +00:00
// SetDevStateStore updates the LocalBackend's state storage to the provided values.
//
// It's meant only for development.
func ( b * LocalBackend ) SetDevStateStore ( key , value string ) error {
if b . store == nil {
return errors . New ( "no state store" )
}
2023-08-04 14:55:59 +00:00
err := ipn . WriteState ( b . store , ipn . StateKey ( key ) , [ ] byte ( value ) )
2022-11-07 21:04:10 +00:00
b . logf ( "SetDevStateStore(%q, %q) = %v" , key , value , err )
2022-11-07 23:32:53 +00:00
if err != nil {
return err
}
b . mu . Lock ( )
defer b . mu . Unlock ( )
2022-11-09 05:58:10 +00:00
b . setTCPPortsInterceptedFromNetmapAndPrefsLocked ( b . pm . CurrentPrefs ( ) )
2022-11-07 23:32:53 +00:00
return nil
}
// ShouldInterceptTCPPort reports whether the given TCP port number to a
// Tailscale IP (not a subnet router, service IP, etc) should be intercepted by
// Tailscaled and handled in-process.
func ( b * LocalBackend ) ShouldInterceptTCPPort ( port uint16 ) bool {
return b . shouldInterceptTCPPortAtomic . Load ( ) ( port )
}
2022-11-09 05:58:10 +00:00
// SwitchProfile switches to the profile with the given id.
// It will restart the backend on success.
// If the profile is not known, it returns an errProfileNotFound.
func ( b * LocalBackend ) SwitchProfile ( profile ipn . ProfileID ) error {
if b . CurrentProfile ( ) . ID == profile {
return nil
}
2024-04-06 18:05:56 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2024-04-30 19:09:12 +00:00
oldControlURL := b . pm . CurrentPrefs ( ) . ControlURLOrDefault ( )
2022-11-09 05:58:10 +00:00
if err := b . pm . SwitchProfile ( profile ) ; err != nil {
return err
}
2024-04-30 17:42:49 +00:00
2024-04-30 19:09:12 +00:00
// As an optimization, only reset the dialPlan if the control URL
// changed; we treat an empty URL as "unknown" and always reset.
newControlURL := b . pm . CurrentPrefs ( ) . ControlURLOrDefault ( )
if oldControlURL != newControlURL || oldControlURL == "" || newControlURL == "" {
b . resetDialPlan ( )
}
2024-04-30 17:42:49 +00:00
2024-04-06 18:05:56 +00:00
return b . resetForProfileChangeLockedOnEntry ( unlock )
2022-11-09 05:58:10 +00:00
}
2022-11-14 12:29:49 +00:00
func ( b * LocalBackend ) initTKALocked ( ) error {
cp := b . pm . CurrentProfile ( )
if cp . ID == "" {
b . tka = nil
return nil
}
if b . tka != nil {
if b . tka . profile == cp . ID {
// Already initialized.
return nil
}
// As we're switching profiles, we need to reset the TKA to nil.
b . tka = nil
}
root := b . TailscaleVarRoot ( )
if root == "" {
b . tka = nil
b . logf ( "network-lock unavailable; no state directory" )
return nil
}
chonkDir := b . chonkPathLocked ( )
if _ , err := os . Stat ( chonkDir ) ; err == nil {
// The directory exists, which means network-lock has been initialized.
storage , err := tka . ChonkDir ( chonkDir )
if err != nil {
return fmt . Errorf ( "opening tailchonk: %v" , err )
}
authority , err := tka . Open ( storage )
if err != nil {
return fmt . Errorf ( "initializing tka: %v" , err )
}
2023-03-01 22:14:35 +00:00
if err := authority . Compact ( storage , tkaCompactionDefaults ) ; err != nil {
b . logf ( "tka compaction failed: %v" , err )
}
2022-11-14 12:29:49 +00:00
b . tka = & tkaState {
profile : cp . ID ,
authority : authority ,
storage : storage ,
}
b . logf ( "tka initialized at head %x" , authority . Head ( ) )
}
return nil
}
2024-04-30 19:09:12 +00:00
// resetDialPlan resets the dialPlan for this LocalBackend. It will log if
// anything is reset.
//
// It is safe to call this concurrently, with or without b.mu held.
func ( b * LocalBackend ) resetDialPlan ( ) {
old := b . dialPlan . Swap ( nil )
if old != nil {
b . logf ( "resetDialPlan: did reset" )
}
}
2022-11-09 05:58:10 +00:00
// resetForProfileChangeLockedOnEntry resets the backend for a profile change.
2023-08-31 21:08:09 +00:00
//
// b.mu must held on entry. It is released on exit.
2024-04-07 04:16:00 +00:00
func ( b * LocalBackend ) resetForProfileChangeLockedOnEntry ( unlock unlockOnce ) error {
2024-04-06 18:05:56 +00:00
defer unlock ( )
2023-09-01 17:58:43 +00:00
if b . shutdownCalled {
// Prevent a call back to Start during Shutdown, which calls Logout for
// ephemeral nodes, which can then call back here. But we're shutting
// down, so no need to do any work.
return nil
}
2022-11-09 05:58:10 +00:00
b . setNetMapLocked ( nil ) // Reset netmap.
// Reset the NetworkMap in the engine
b . e . SetNetworkMap ( new ( netmap . NetworkMap ) )
2022-11-14 12:29:49 +00:00
if err := b . initTKALocked ( ) ; err != nil {
return err
}
2022-11-16 20:51:26 +00:00
b . lastServeConfJSON = mem . B ( nil )
b . serveConfig = ipn . ServeConfigView { }
2024-05-31 13:54:46 +00:00
b . lastSuggestedExitNode = ""
b . enterStateLockedOnEntry ( ipn . NoState , unlock ) // Reset state; releases b.mu
tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.
In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.
The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).
Updates #11874
Updates #4136
Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2024-04-26 03:29:20 +00:00
b . health . SetLocalLogConfigHealth ( nil )
2022-11-09 05:58:10 +00:00
return b . Start ( ipn . Options { } )
}
// DeleteProfile deletes a profile with the given ID.
// If the profile is not known, it is a no-op.
func ( b * LocalBackend ) DeleteProfile ( p ipn . ProfileID ) error {
2024-04-06 18:05:56 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2022-11-09 05:58:10 +00:00
needToRestart := b . pm . CurrentProfile ( ) . ID == p
if err := b . pm . DeleteProfile ( p ) ; err != nil {
if err == errProfileNotFound {
return nil
}
return err
}
if ! needToRestart {
return nil
}
2024-04-06 18:05:56 +00:00
return b . resetForProfileChangeLockedOnEntry ( unlock )
2022-11-09 05:58:10 +00:00
}
// CurrentProfile returns the current LoginProfile.
// The value may be zero if the profile is not persisted.
func ( b * LocalBackend ) CurrentProfile ( ) ipn . LoginProfile {
b . mu . Lock ( )
defer b . mu . Unlock ( )
return b . pm . CurrentProfile ( )
}
// NewProfile creates and switches to the new profile.
func ( b * LocalBackend ) NewProfile ( ) error {
2024-04-06 18:05:56 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2022-11-09 05:58:10 +00:00
b . pm . NewProfile ( )
2024-04-30 19:09:12 +00:00
// The new profile doesn't yet have a ControlURL because it hasn't been
// set. Conservatively reset the dialPlan.
b . resetDialPlan ( )
2024-04-06 18:05:56 +00:00
return b . resetForProfileChangeLockedOnEntry ( unlock )
2022-11-09 05:58:10 +00:00
}
// ListProfiles returns a list of all LoginProfiles.
func ( b * LocalBackend ) ListProfiles ( ) [ ] ipn . LoginProfile {
b . mu . Lock ( )
defer b . mu . Unlock ( )
return b . pm . Profiles ( )
}
2023-01-27 23:41:03 +00:00
// ResetAuth resets the authentication state, including persisted keys. Also
// has the side effect of removing all profiles and reseting preferences. The
// backend is left with a new profile, ready for StartLoginInterative to be
// called to register it as new node.
func ( b * LocalBackend ) ResetAuth ( ) error {
2024-04-06 18:05:56 +00:00
unlock := b . lockAndGetUnlock ( )
defer unlock ( )
2023-09-02 19:04:03 +00:00
prevCC := b . resetControlClientLocked ( )
if prevCC != nil {
defer prevCC . Shutdown ( ) // call must happen after release b.mu
}
2023-01-27 23:41:03 +00:00
if err := b . clearMachineKeyLocked ( ) ; err != nil {
return err
}
if err := b . pm . DeleteAllProfiles ( ) ; err != nil {
return err
}
2024-04-30 19:09:12 +00:00
b . resetDialPlan ( ) // always reset if we're removing everything
2024-04-06 18:05:56 +00:00
return b . resetForProfileChangeLockedOnEntry ( unlock )
2023-01-27 23:41:03 +00:00
}
2023-01-19 22:28:49 +00:00
// StreamDebugCapture writes a pcap stream of packets traversing
// tailscaled to the provided response writer.
func ( b * LocalBackend ) StreamDebugCapture ( ctx context . Context , w io . Writer ) error {
var s * capture . Sink
b . mu . Lock ( )
if b . debugSink == nil {
s = capture . New ( )
b . debugSink = s
b . e . InstallCaptureHook ( s . LogPacket )
} else {
s = b . debugSink
}
b . mu . Unlock ( )
unregister := s . RegisterOutput ( w )
select {
case <- ctx . Done ( ) :
case <- s . WaitCh ( ) :
}
unregister ( )
// Shut down & uninstall the sink if there are no longer
// any outputs on it.
b . mu . Lock ( )
defer b . mu . Unlock ( )
select {
case <- b . ctx . Done ( ) :
return nil
default :
}
if b . debugSink != nil && b . debugSink . NumOutputs ( ) == 0 {
s := b . debugSink
b . e . InstallCaptureHook ( nil )
b . debugSink = nil
return s . Close ( )
}
return nil
}
2023-02-21 20:57:08 +00:00
func ( b * LocalBackend ) GetPeerEndpointChanges ( ctx context . Context , ip netip . Addr ) ( [ ] magicsock . EndpointChange , error ) {
pip , ok := b . e . PeerForIP ( ip )
if ! ok {
return nil , fmt . Errorf ( "no matching peer" )
}
if pip . IsSelf {
return nil , fmt . Errorf ( "%v is local Tailscale IP" , ip )
}
peer := pip . Node
2023-11-15 23:10:45 +00:00
chs , err := b . MagicConn ( ) . GetEndpointChanges ( peer )
2023-02-21 20:57:08 +00:00
if err != nil {
return nil , fmt . Errorf ( "getting endpoint changes: %w" , err )
}
return chs , nil
}
2023-08-11 04:45:16 +00:00
var breakTCPConns func ( ) error
func ( b * LocalBackend ) DebugBreakTCPConns ( ) error {
if breakTCPConns == nil {
return errors . New ( "TCP connection breaking not available on this platform" )
}
return breakTCPConns ( )
}
func ( b * LocalBackend ) DebugBreakDERPConns ( ) error {
2023-11-15 23:10:45 +00:00
return b . MagicConn ( ) . DebugBreakDERPConns ( )
2023-08-11 04:45:16 +00:00
}
2023-10-05 23:05:45 +00:00
2023-11-09 21:00:47 +00:00
func ( b * LocalBackend ) pushSelfUpdateProgress ( up ipnstate . UpdateProgress ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
b . selfUpdateProgress = append ( b . selfUpdateProgress , up )
b . lastSelfUpdateState = up . Status
}
func ( b * LocalBackend ) clearSelfUpdateProgress ( ) {
b . mu . Lock ( )
defer b . mu . Unlock ( )
b . selfUpdateProgress = make ( [ ] ipnstate . UpdateProgress , 0 )
b . lastSelfUpdateState = ipnstate . UpdateFinished
}
func ( b * LocalBackend ) GetSelfUpdateProgress ( ) [ ] ipnstate . UpdateProgress {
b . mu . Lock ( )
defer b . mu . Unlock ( )
res := make ( [ ] ipnstate . UpdateProgress , len ( b . selfUpdateProgress ) )
copy ( res , b . selfUpdateProgress )
return res
}
func ( b * LocalBackend ) DoSelfUpdate ( ) {
b . mu . Lock ( )
updateState := b . lastSelfUpdateState
b . mu . Unlock ( )
// don't start an update if one is already in progress
if updateState == ipnstate . UpdateInProgress {
return
}
b . clearSelfUpdateProgress ( )
b . pushSelfUpdateProgress ( ipnstate . NewUpdateProgress ( ipnstate . UpdateInProgress , "" ) )
up , err := clientupdate . NewUpdater ( clientupdate . Arguments {
Logf : func ( format string , args ... any ) {
b . pushSelfUpdateProgress ( ipnstate . NewUpdateProgress ( ipnstate . UpdateInProgress , fmt . Sprintf ( format , args ... ) ) )
} ,
} )
if err != nil {
b . pushSelfUpdateProgress ( ipnstate . NewUpdateProgress ( ipnstate . UpdateFailed , err . Error ( ) ) )
}
err = up . Update ( )
if err != nil {
b . pushSelfUpdateProgress ( ipnstate . NewUpdateProgress ( ipnstate . UpdateFailed , err . Error ( ) ) )
} else {
b . pushSelfUpdateProgress ( ipnstate . NewUpdateProgress ( ipnstate . UpdateFinished , "tailscaled did not restart; please restart Tailscale manually." ) )
}
}
2023-10-27 21:20:10 +00:00
// ObserveDNSResponse passes a DNS response from the PeerAPI DNS server to the
// App Connector to enable route discovery.
func ( b * LocalBackend ) ObserveDNSResponse ( res [ ] byte ) {
2023-11-01 23:56:30 +00:00
var appConnector * appc . AppConnector
2023-10-27 21:20:10 +00:00
b . mu . Lock ( )
if b . appConnector == nil {
b . mu . Unlock ( )
return
}
appConnector = b . appConnector
b . mu . Unlock ( )
appConnector . ObserveDNSResponse ( res )
}
2023-12-19 17:33:38 +00:00
// ErrDisallowedAutoRoute is returned by AdvertiseRoute when a route that is not allowed is requested.
var ErrDisallowedAutoRoute = errors . New ( "route is not allowed" )
2023-10-27 21:20:10 +00:00
// AdvertiseRoute implements the appc.RouteAdvertiser interface. It sets a new
// route advertisement if one is not already present in the existing routes.
2023-12-19 17:33:38 +00:00
// If the route is disallowed, ErrDisallowedAutoRoute is returned.
2024-01-23 00:57:31 +00:00
func ( b * LocalBackend ) AdvertiseRoute ( ipps ... netip . Prefix ) error {
finalRoutes := b . Prefs ( ) . AdvertiseRoutes ( ) . AsSlice ( )
newRoutes := false
for _ , ipp := range ipps {
if ! allowedAutoRoute ( ipp ) {
continue
}
if slices . Contains ( finalRoutes , ipp ) {
continue
}
// If the new prefix is already contained by existing routes, skip it.
2024-02-01 01:36:39 +00:00
if coveredRouteRangeNoDefault ( finalRoutes , ipp ) {
2024-01-23 00:57:31 +00:00
continue
}
finalRoutes = append ( finalRoutes , ipp )
newRoutes = true
}
if ! newRoutes {
2023-10-27 21:20:10 +00:00
return nil
}
2024-01-23 00:57:31 +00:00
2023-10-27 21:20:10 +00:00
_ , err := b . EditPrefs ( & ipn . MaskedPrefs {
Prefs : ipn . Prefs {
2024-01-23 00:57:31 +00:00
AdvertiseRoutes : finalRoutes ,
2023-10-27 21:20:10 +00:00
} ,
AdvertiseRoutesSet : true ,
} )
return err
}
2024-02-01 01:36:39 +00:00
// coveredRouteRangeNoDefault checks if a route is already included in a slice of
// prefixes, ignoring default routes in the range.
func coveredRouteRangeNoDefault ( finalRoutes [ ] netip . Prefix , ipp netip . Prefix ) bool {
2024-01-23 00:57:31 +00:00
for _ , r := range finalRoutes {
2024-02-01 01:36:39 +00:00
if r == tsaddr . AllIPv4 ( ) || r == tsaddr . AllIPv6 ( ) {
continue
}
2024-01-23 00:57:31 +00:00
if ipp . IsSingleIP ( ) {
if r . Contains ( ipp . Addr ( ) ) {
return true
}
} else {
if r . Contains ( ipp . Addr ( ) ) && r . Contains ( netipx . PrefixLastIP ( ipp ) ) {
return true
}
}
}
return false
}
2024-01-17 19:35:55 +00:00
// UnadvertiseRoute implements the appc.RouteAdvertiser interface. It removes
// a route advertisement if one is present in the existing routes.
2024-01-23 00:57:31 +00:00
func ( b * LocalBackend ) UnadvertiseRoute ( toRemove ... netip . Prefix ) error {
2024-01-17 19:35:55 +00:00
currentRoutes := b . Prefs ( ) . AdvertiseRoutes ( ) . AsSlice ( )
2024-01-23 00:57:31 +00:00
finalRoutes := currentRoutes [ : 0 ]
2024-01-17 19:35:55 +00:00
2024-01-23 00:57:31 +00:00
for _ , ipp := range currentRoutes {
if slices . Contains ( toRemove , ipp ) {
continue
2024-01-17 19:35:55 +00:00
}
2024-01-23 00:57:31 +00:00
finalRoutes = append ( finalRoutes , ipp )
2024-01-17 19:35:55 +00:00
}
_ , err := b . EditPrefs ( & ipn . MaskedPrefs {
Prefs : ipn . Prefs {
2024-01-23 00:57:31 +00:00
AdvertiseRoutes : finalRoutes ,
2024-01-17 19:35:55 +00:00
} ,
AdvertiseRoutesSet : true ,
} )
return err
}
2024-04-11 21:06:12 +00:00
// namespace a key with the profile manager's current profile key, if any
func namespaceKeyForCurrentProfile ( pm * profileManager , key ipn . StateKey ) ipn . StateKey {
return pm . CurrentProfile ( ) . Key + "||" + key
}
const routeInfoStateStoreKey ipn . StateKey = "_routeInfo"
func ( b * LocalBackend ) storeRouteInfo ( ri * appc . RouteInfo ) error {
b . mu . Lock ( )
defer b . mu . Unlock ( )
if b . pm . CurrentProfile ( ) . ID == "" {
return nil
}
key := namespaceKeyForCurrentProfile ( b . pm , routeInfoStateStoreKey )
bs , err := json . Marshal ( ri )
if err != nil {
return err
}
return b . pm . WriteState ( key , bs )
}
func ( b * LocalBackend ) readRouteInfoLocked ( ) ( * appc . RouteInfo , error ) {
if b . pm . CurrentProfile ( ) . ID == "" {
return & appc . RouteInfo { } , nil
}
key := namespaceKeyForCurrentProfile ( b . pm , routeInfoStateStoreKey )
bs , err := b . pm . Store ( ) . ReadState ( key )
ri := & appc . RouteInfo { }
if err != nil {
return nil , err
}
if err := json . Unmarshal ( bs , ri ) ; err != nil {
return nil , err
}
return ri , nil
}
2024-01-04 17:29:04 +00:00
// seamlessRenewalEnabled reports whether seamless key renewals are enabled
// (i.e. we saw our self node with the SeamlessKeyRenewal attr in a netmap).
// This enables beta functionality of renewing node keys without breaking
// connections.
func ( b * LocalBackend ) seamlessRenewalEnabled ( ) bool {
return b . ControlKnobs ( ) . SeamlessKeyRenewal . Load ( )
}
2023-12-19 17:33:38 +00:00
var (
disallowedAddrs = [ ] netip . Addr {
netip . MustParseAddr ( "::1" ) ,
netip . MustParseAddr ( "::" ) ,
netip . MustParseAddr ( "0.0.0.0" ) ,
}
disallowedRanges = [ ] netip . Prefix {
netip . MustParsePrefix ( "127.0.0.0/8" ) ,
netip . MustParsePrefix ( "224.0.0.0/4" ) ,
netip . MustParsePrefix ( "ff00::/8" ) ,
}
)
// allowedAutoRoute determines if the route being added via AdvertiseRoute (the app connector featuge) should be allowed.
func allowedAutoRoute ( ipp netip . Prefix ) bool {
// Note: blocking the addrs for globals, not solely the prefixes.
for _ , addr := range disallowedAddrs {
if ipp . Addr ( ) == addr {
return false
}
}
for _ , pfx := range disallowedRanges {
if pfx . Overlaps ( ipp ) {
return false
}
}
// TODO(raggi): exclude tailscale service IPs and so on as well.
return true
}
2023-10-05 23:05:45 +00:00
// mayDeref dereferences p if non-nil, otherwise it returns the zero value.
func mayDeref [ T any ] ( p * T ) ( v T ) {
if p == nil {
return v
}
return * p
}
2024-04-15 22:14:20 +00:00
var ErrNoPreferredDERP = errors . New ( "no preferred DERP, try again later" )
2024-04-26 21:35:11 +00:00
var ErrCannotSuggestExitNode = errors . New ( "unable to suggest an exit node, try again later" )
2024-04-15 22:14:20 +00:00
// SuggestExitNode computes a suggestion based on the current netmap and last netcheck report. If
// there are multiple equally good options, one is selected at random, so the result is not stable. To be
// eligible for consideration, the peer must have NodeAttrSuggestExitNode in its CapMap.
//
// Currently, peers with a DERP home are preferred over those without (typically this means Mullvad).
// Peers are selected based on having a DERP home that is the lowest latency to this device. For peers
// without a DERP home, we look for geographic proximity to this device's DERP home.
func ( b * LocalBackend ) SuggestExitNode ( ) ( response apitype . ExitNodeSuggestionResponse , err error ) {
b . mu . Lock ( )
lastReport := b . MagicConn ( ) . GetLastNetcheckReport ( b . ctx )
netMap := b . netMap
2024-05-31 13:54:46 +00:00
prevSuggestion := b . lastSuggestedExitNode
2024-04-15 22:14:20 +00:00
b . mu . Unlock ( )
2024-06-03 20:12:12 +00:00
2024-05-31 13:54:46 +00:00
res , err := suggestExitNode ( lastReport , netMap , prevSuggestion , randomRegion , randomNode , getAllowedSuggestions ( ) )
2024-05-03 17:24:26 +00:00
if err != nil {
2024-05-31 13:54:46 +00:00
return res , err
2024-05-03 17:24:26 +00:00
}
b . mu . Lock ( )
2024-05-31 13:54:46 +00:00
b . lastSuggestedExitNode = res . ID
2024-05-03 17:24:26 +00:00
b . mu . Unlock ( )
return res , err
}
2024-06-03 20:12:12 +00:00
// selectRegionFunc returns a DERP region from the slice of candidate regions.
// The value is returned, not the slice index.
type selectRegionFunc func ( views . Slice [ int ] ) int
2024-05-31 13:54:46 +00:00
// selectNodeFunc returns a node from the slice of candidate nodes. The last
// selected node is provided for when that information is needed to make a better
// choice.
type selectNodeFunc func ( nodes views . Slice [ tailcfg . NodeView ] , last tailcfg . StableNodeID ) tailcfg . NodeView
2024-04-15 22:14:20 +00:00
2024-06-03 20:49:55 +00:00
var getAllowedSuggestions = lazy . SyncFunc ( fillAllowedSuggestions )
func fillAllowedSuggestions ( ) set . Set [ tailcfg . StableNodeID ] {
nodes , err := syspolicy . GetStringArray ( syspolicy . AllowedSuggestedExitNodes , nil )
if err != nil {
log . Printf ( "fillAllowedSuggestions: unable to look up %q policy: %v" , syspolicy . AllowedSuggestedExitNodes , err )
return nil
}
if nodes == nil {
return nil
}
s := make ( set . Set [ tailcfg . StableNodeID ] , len ( nodes ) )
for _ , n := range nodes {
s . Add ( tailcfg . StableNodeID ( n ) )
}
return s
}
2024-05-31 13:54:46 +00:00
func suggestExitNode ( report * netcheck . Report , netMap * netmap . NetworkMap , prevSuggestion tailcfg . StableNodeID , selectRegion selectRegionFunc , selectNode selectNodeFunc , allowList set . Set [ tailcfg . StableNodeID ] ) ( res apitype . ExitNodeSuggestionResponse , err error ) {
2024-06-03 20:12:12 +00:00
if report . PreferredDERP == 0 || netMap == nil || netMap . DERPMap == nil {
2024-04-15 22:14:20 +00:00
return res , ErrNoPreferredDERP
}
candidates := make ( [ ] tailcfg . NodeView , 0 , len ( netMap . Peers ) )
for _ , peer := range netMap . Peers {
2024-06-03 20:12:12 +00:00
if ! peer . Valid ( ) {
continue
}
2024-06-03 20:49:55 +00:00
if allowList != nil && ! allowList . Contains ( peer . StableID ( ) ) {
2024-05-27 20:22:36 +00:00
continue
}
2024-06-16 04:42:34 +00:00
if peer . CapMap ( ) . Contains ( tailcfg . NodeAttrSuggestExitNode ) && tsaddr . ContainsExitRoutes ( peer . AllowedIPs ( ) ) {
2024-04-15 22:14:20 +00:00
candidates = append ( candidates , peer )
}
}
if len ( candidates ) == 0 {
return res , nil
}
if len ( candidates ) == 1 {
peer := candidates [ 0 ]
if hi := peer . Hostinfo ( ) ; hi . Valid ( ) {
if loc := hi . Location ( ) ; loc != nil {
res . Location = loc . View ( )
}
}
res . ID = peer . StableID ( )
res . Name = peer . Name ( )
return res , nil
}
candidatesByRegion := make ( map [ int ] [ ] tailcfg . NodeView , len ( netMap . DERPMap . Regions ) )
2024-06-03 20:12:12 +00:00
preferredDERP , ok := netMap . DERPMap . Regions [ report . PreferredDERP ]
if ! ok {
return res , ErrNoPreferredDERP
}
2024-04-15 22:14:20 +00:00
var minDistance float64 = math . MaxFloat64
type nodeDistance struct {
nv tailcfg . NodeView
distance float64 // in meters, approximately
}
distances := make ( [ ] nodeDistance , 0 , len ( candidates ) )
for _ , c := range candidates {
if c . DERP ( ) != "" {
ipp , err := netip . ParseAddrPort ( c . DERP ( ) )
if err != nil {
continue
}
if ipp . Addr ( ) != tailcfg . DerpMagicIPAddr {
continue
}
regionID := int ( ipp . Port ( ) )
candidatesByRegion [ regionID ] = append ( candidatesByRegion [ regionID ] , c )
continue
}
if len ( candidatesByRegion ) > 0 {
// Since a candidate exists that does have a DERP home, skip this candidate. We never select
// a candidate without a DERP home if there is a candidate available with a DERP home.
continue
}
// This candidate does not have a DERP home.
// Use geographic distance from our DERP home to estimate how good this candidate is.
hi := c . Hostinfo ( )
if ! hi . Valid ( ) {
continue
}
loc := hi . Location ( )
if loc == nil {
continue
}
distance := longLatDistance ( preferredDERP . Latitude , preferredDERP . Longitude , loc . Latitude , loc . Longitude )
if distance < minDistance {
minDistance = distance
}
distances = append ( distances , nodeDistance { nv : c , distance : distance } )
}
// First, try to select an exit node that has the closest DERP home, based on lastReport's DERP latency.
// If there are no latency values, it returns an arbitrary region
if len ( candidatesByRegion ) > 0 {
minRegion := minLatencyDERPRegion ( xmaps . Keys ( candidatesByRegion ) , report )
if minRegion == 0 {
2024-06-03 20:12:12 +00:00
minRegion = selectRegion ( views . SliceOf ( xmaps . Keys ( candidatesByRegion ) ) )
2024-04-15 22:14:20 +00:00
}
regionCandidates , ok := candidatesByRegion [ minRegion ]
if ! ok {
return res , errors . New ( "no candidates in expected region: this is a bug" )
}
2024-05-31 13:54:46 +00:00
chosen := selectNode ( views . SliceOf ( regionCandidates ) , prevSuggestion )
2024-04-15 22:14:20 +00:00
res . ID = chosen . StableID ( )
res . Name = chosen . Name ( )
if hi := chosen . Hostinfo ( ) ; hi . Valid ( ) {
if loc := hi . Location ( ) ; loc != nil {
res . Location = loc . View ( )
}
}
return res , nil
}
// None of the candidates have a DERP home, so proceed to select based on geographical distance from our preferred DERP region.
// allowanceMeters is the extra distance that will be permitted when considering peers. By this point, there
// are multiple approximations taking place (DERP location standing in for this device's location, the peer's
// location may only be city granularity, the distance algorithm assumes a spherical planet, etc.) so it is
// reasonable to consider peers that are similar distances. Those peers are good enough to be within
// measurement error. 100km corresponds to approximately 1ms of additional round trip light
// propagation delay in a fiber optic cable and seems like a reasonable heuristic. It may be adjusted in
// future.
const allowanceMeters = 100000
pickFrom := make ( [ ] tailcfg . NodeView , 0 , len ( distances ) )
for _ , candidate := range distances {
if candidate . nv . Valid ( ) && candidate . distance <= minDistance + allowanceMeters {
pickFrom = append ( pickFrom , candidate . nv )
}
}
2024-06-03 20:12:12 +00:00
bestCandidates := pickWeighted ( pickFrom )
2024-05-31 13:54:46 +00:00
chosen := selectNode ( views . SliceOf ( bestCandidates ) , prevSuggestion )
2024-04-15 22:14:20 +00:00
if ! chosen . Valid ( ) {
return res , errors . New ( "chosen candidate invalid: this is a bug" )
}
res . ID = chosen . StableID ( )
res . Name = chosen . Name ( )
if hi := chosen . Hostinfo ( ) ; hi . Valid ( ) {
if loc := hi . Location ( ) ; loc != nil {
res . Location = loc . View ( )
}
}
return res , nil
}
// pickWeighted chooses the node with highest priority given a list of mullvad nodes.
2024-06-03 20:12:12 +00:00
func pickWeighted ( candidates [ ] tailcfg . NodeView ) [ ] tailcfg . NodeView {
2024-04-15 22:14:20 +00:00
maxWeight := 0
2024-06-03 20:12:12 +00:00
best := make ( [ ] tailcfg . NodeView , 0 , 1 )
2024-04-15 22:14:20 +00:00
for _ , c := range candidates {
hi := c . Hostinfo ( )
if ! hi . Valid ( ) {
continue
}
loc := hi . Location ( )
2024-06-03 20:12:12 +00:00
if loc == nil || loc . Priority < maxWeight {
2024-04-15 22:14:20 +00:00
continue
}
2024-06-03 20:12:12 +00:00
if maxWeight != loc . Priority {
best = best [ : 0 ]
}
2024-04-15 22:14:20 +00:00
maxWeight = loc . Priority
2024-06-03 20:12:12 +00:00
best = append ( best , c )
2024-04-15 22:14:20 +00:00
}
return best
}
2024-06-03 20:12:12 +00:00
// randomRegion is a selectRegionFunc that selects a uniformly random region.
func randomRegion ( regions views . Slice [ int ] ) int {
2024-06-05 21:37:31 +00:00
return regions . At ( rand . IntN ( regions . Len ( ) ) )
2024-04-15 22:14:20 +00:00
}
2024-05-31 13:54:46 +00:00
// randomNode is a selectNodeFunc that will return the node matching prefer if
// present, otherwise a uniformly random node will be selected.
func randomNode ( nodes views . Slice [ tailcfg . NodeView ] , prefer tailcfg . StableNodeID ) tailcfg . NodeView {
if ! prefer . IsZero ( ) {
for i := range nodes . Len ( ) {
nv := nodes . At ( i )
if nv . StableID ( ) == prefer {
return nv
}
}
}
2024-06-05 21:37:31 +00:00
return nodes . At ( rand . IntN ( nodes . Len ( ) ) )
2024-04-15 22:14:20 +00:00
}
// minLatencyDERPRegion returns the region with the lowest latency value given the last netcheck report.
// If there are no latency values, it returns 0.
func minLatencyDERPRegion ( regions [ ] int , report * netcheck . Report ) int {
min := slices . MinFunc ( regions , func ( i , j int ) int {
const largeDuration time . Duration = math . MaxInt64
iLatency , ok := report . RegionLatency [ i ]
if ! ok {
iLatency = largeDuration
}
jLatency , ok := report . RegionLatency [ j ]
if ! ok {
jLatency = largeDuration
}
if c := cmp . Compare ( iLatency , jLatency ) ; c != 0 {
return c
}
return cmp . Compare ( i , j )
} )
latency , ok := report . RegionLatency [ min ]
if ! ok || latency == 0 {
return 0
} else {
return min
}
}
// longLatDistance returns an estimated distance given the geographic coordinates of two locations, in degrees.
// The coordinates are separated into four separate float64 values.
// Value is returned in meters.
func longLatDistance ( fromLat , fromLong , toLat , toLong float64 ) float64 {
const toRadians = math . Pi / 180
diffLat := ( fromLat - toLat ) * toRadians
diffLong := ( fromLong - toLong ) * toRadians
lat1 := fromLat * toRadians
lat2 := toLat * toRadians
a := math . Pow ( math . Sin ( diffLat / 2 ) , 2 ) + math . Cos ( lat1 ) * math . Cos ( lat2 ) * math . Pow ( math . Sin ( diffLong / 2 ) , 2 )
const earthRadiusMeters = 6371000
c := 2 * math . Atan2 ( math . Sqrt ( a ) , math . Sqrt ( 1 - a ) )
return earthRadiusMeters * c
}
2024-06-04 02:24:53 +00:00
// startAutoUpdate triggers an auto-update attempt. The actual update happens
// asynchronously. If another update is in progress, an error is returned.
func ( b * LocalBackend ) startAutoUpdate ( logPrefix string ) ( retErr error ) {
// Check if update was already started, and mark as started.
if ! b . trySetC2NUpdateStarted ( ) {
return errors . New ( "update already started" )
}
defer func ( ) {
// Clear the started flag if something failed.
if retErr != nil {
b . setC2NUpdateStarted ( false )
}
} ( )
cmdTS , err := findCmdTailscale ( )
if err != nil {
return fmt . Errorf ( "failed to find cmd/tailscale binary: %w" , err )
}
var ver struct {
Long string ` json:"long" `
}
out , err := exec . Command ( cmdTS , "version" , "--json" ) . Output ( )
if err != nil {
return fmt . Errorf ( "failed to find cmd/tailscale binary: %w" , err )
}
if err := json . Unmarshal ( out , & ver ) ; err != nil {
return fmt . Errorf ( "invalid JSON from cmd/tailscale version --json: %w" , err )
}
if ver . Long != version . Long ( ) {
return fmt . Errorf ( "cmd/tailscale version %q does not match tailscaled version %q" , ver . Long , version . Long ( ) )
}
cmd := tailscaleUpdateCmd ( cmdTS )
buf := new ( bytes . Buffer )
cmd . Stdout = buf
cmd . Stderr = buf
b . logf ( "%s: running %q" , logPrefix , strings . Join ( cmd . Args , " " ) )
if err := cmd . Start ( ) ; err != nil {
return fmt . Errorf ( "failed to start cmd/tailscale update: %w" , err )
}
go func ( ) {
if err := cmd . Wait ( ) ; err != nil {
b . logf ( "%s: update command failed: %v, output: %s" , logPrefix , err , buf )
} else {
b . logf ( "%s: update attempt complete" , logPrefix )
}
b . setC2NUpdateStarted ( false )
} ( )
return nil
}