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
|
|
|
|
|
|
|
package controlclient
|
|
|
|
|
|
|
|
import (
|
2022-08-27 19:55:41 +00:00
|
|
|
"bufio"
|
2020-02-05 22:16:58 +00:00
|
|
|
"bytes"
|
|
|
|
"context"
|
2023-03-02 21:24:26 +00:00
|
|
|
"crypto/ed25519"
|
|
|
|
"encoding/base64"
|
2020-02-05 22:16:58 +00:00
|
|
|
"encoding/binary"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2022-08-27 19:55:41 +00:00
|
|
|
"net/http/httptest"
|
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
|
|
|
"net/netip"
|
2020-04-27 15:18:35 +00:00
|
|
|
"net/url"
|
2020-02-05 22:16:58 +00:00
|
|
|
"os"
|
2020-04-02 00:18:39 +00:00
|
|
|
"reflect"
|
2020-07-28 04:14:28 +00:00
|
|
|
"runtime"
|
2023-08-30 20:34:22 +00:00
|
|
|
"slices"
|
2020-02-05 22:16:58 +00:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2021-09-03 20:17:46 +00:00
|
|
|
"go4.org/mem"
|
2021-06-22 22:29:01 +00:00
|
|
|
"tailscale.com/control/controlknobs"
|
2022-01-24 18:52:57 +00:00
|
|
|
"tailscale.com/envknob"
|
2021-02-18 16:58:13 +00:00
|
|
|
"tailscale.com/health"
|
2021-08-20 17:34:13 +00:00
|
|
|
"tailscale.com/hostinfo"
|
2021-06-08 15:02:05 +00:00
|
|
|
"tailscale.com/ipn/ipnstate"
|
2022-04-18 20:43:03 +00:00
|
|
|
"tailscale.com/logtail"
|
2020-11-11 20:37:53 +00:00
|
|
|
"tailscale.com/net/dnscache"
|
2021-02-26 20:49:54 +00:00
|
|
|
"tailscale.com/net/dnsfallback"
|
2021-03-04 03:19:41 +00:00
|
|
|
"tailscale.com/net/interfaces"
|
2023-04-18 21:26:58 +00:00
|
|
|
"tailscale.com/net/netmon"
|
2022-03-28 17:24:11 +00:00
|
|
|
"tailscale.com/net/netutil"
|
2020-04-25 20:24:53 +00:00
|
|
|
"tailscale.com/net/tlsdial"
|
2022-04-27 18:57:59 +00:00
|
|
|
"tailscale.com/net/tsdial"
|
2020-08-13 22:25:54 +00:00
|
|
|
"tailscale.com/net/tshttpproxy"
|
2023-09-10 14:24:51 +00:00
|
|
|
"tailscale.com/smallzstd"
|
2020-02-05 22:16:58 +00:00
|
|
|
"tailscale.com/tailcfg"
|
2022-10-13 17:43:00 +00:00
|
|
|
"tailscale.com/tka"
|
2023-08-04 23:29:44 +00:00
|
|
|
"tailscale.com/tstime"
|
2021-09-03 20:17:46 +00:00
|
|
|
"tailscale.com/types/key"
|
2020-02-15 03:23:16 +00:00
|
|
|
"tailscale.com/types/logger"
|
2021-02-05 23:44:46 +00:00
|
|
|
"tailscale.com/types/netmap"
|
2021-02-05 23:23:01 +00:00
|
|
|
"tailscale.com/types/persist"
|
2023-08-10 02:56:43 +00:00
|
|
|
"tailscale.com/types/ptr"
|
2022-10-13 17:43:00 +00:00
|
|
|
"tailscale.com/types/tkatype"
|
2021-11-16 16:34:25 +00:00
|
|
|
"tailscale.com/util/clientmetric"
|
2022-03-07 18:55:02 +00:00
|
|
|
"tailscale.com/util/multierr"
|
2022-06-17 17:09:23 +00:00
|
|
|
"tailscale.com/util/singleflight"
|
2023-10-13 18:13:41 +00:00
|
|
|
"tailscale.com/util/syspolicy"
|
2020-11-24 23:35:04 +00:00
|
|
|
"tailscale.com/util/systemd"
|
2020-02-05 22:16:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Direct is the client that connects to a tailcontrol server for a node.
|
|
|
|
type Direct struct {
|
2023-12-18 22:57:03 +00:00
|
|
|
httpc *http.Client // HTTP client used to talk to tailcontrol
|
|
|
|
dialer *tsdial.Dialer
|
|
|
|
dnsCache *dnscache.Resolver
|
|
|
|
controlKnobs *controlknobs.Knobs // always non-nil
|
|
|
|
serverURL string // URL of the tailcontrol server
|
|
|
|
clock tstime.Clock
|
|
|
|
logf logger.Logf
|
|
|
|
netMon *netmon.Monitor // or nil
|
|
|
|
discoPubKey key.DiscoPublic
|
|
|
|
getMachinePrivKey func() (key.MachinePrivate, error)
|
|
|
|
debugFlags []string
|
|
|
|
skipIPForwardingCheck bool
|
|
|
|
pinger Pinger
|
|
|
|
popBrowser func(url string) // or nil
|
|
|
|
c2nHandler http.Handler // or nil
|
|
|
|
onClientVersion func(*tailcfg.ClientVersion) // or nil
|
|
|
|
onControlTime func(time.Time) // or nil
|
|
|
|
onTailnetDefaultAutoUpdate func(bool) // or nil
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-09-23 17:06:55 +00:00
|
|
|
dialPlan ControlDialPlanner // can be nil
|
|
|
|
|
2022-03-07 18:55:02 +00:00
|
|
|
mu sync.Mutex // mutex guards the following fields
|
|
|
|
serverKey key.MachinePublic // original ("legacy") nacl crypto_box-based public key
|
|
|
|
serverNoiseKey key.MachinePublic
|
|
|
|
|
2022-11-03 07:17:16 +00:00
|
|
|
sfGroup singleflight.Group[struct{}, *NoiseClient] // protects noiseClient creation.
|
|
|
|
noiseClient *NoiseClient
|
2022-03-07 23:32:53 +00:00
|
|
|
|
2023-03-09 01:15:47 +00:00
|
|
|
persist persist.PersistView
|
|
|
|
authKey string
|
|
|
|
tryingNewKey key.NodePrivate
|
2023-08-20 21:55:07 +00:00
|
|
|
expiry time.Time // or zero value if none/unknown
|
2023-03-09 01:15:47 +00:00
|
|
|
hostinfo *tailcfg.Hostinfo // always non-nil
|
|
|
|
netinfo *tailcfg.NetInfo
|
|
|
|
endpoints []tailcfg.Endpoint
|
|
|
|
tkaHead string
|
|
|
|
lastPingURL string // last PingRequest.URL received, for dup suppression
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2023-08-28 22:27:39 +00:00
|
|
|
// Observer is implemented by users of the control client (such as LocalBackend)
|
|
|
|
// to get notified of changes in the control client's status.
|
|
|
|
type Observer interface {
|
2023-09-02 19:04:03 +00:00
|
|
|
// SetControlClientStatus is called when the client has a new status to
|
|
|
|
// report. The Client is provided to allow the Observer to track which
|
|
|
|
// Client is reporting the status, allowing it to ignore stale status
|
|
|
|
// reports from previous Clients.
|
|
|
|
SetControlClientStatus(Client, Status)
|
2023-08-28 22:27:39 +00:00
|
|
|
}
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
type Options struct {
|
2023-12-18 22:57:03 +00:00
|
|
|
Persist persist.Persist // initial persistent data
|
|
|
|
GetMachinePrivateKey func() (key.MachinePrivate, error) // returns the machine key to use
|
|
|
|
ServerURL string // URL of the tailcontrol server
|
|
|
|
AuthKey string // optional node auth key for auto registration
|
|
|
|
Clock tstime.Clock
|
|
|
|
Hostinfo *tailcfg.Hostinfo // non-nil passes ownership, nil means to use default using os.Hostname, etc
|
|
|
|
DiscoPublicKey key.DiscoPublic
|
|
|
|
Logf logger.Logf
|
|
|
|
HTTPTestClient *http.Client // optional HTTP client to use (for tests only)
|
|
|
|
NoiseTestClient *http.Client // optional HTTP client to use for noise RPCs (tests only)
|
|
|
|
DebugFlags []string // debug settings to send to control
|
|
|
|
NetMon *netmon.Monitor // optional network monitor
|
|
|
|
PopBrowserURL func(url string) // optional func to open browser
|
|
|
|
OnClientVersion func(*tailcfg.ClientVersion) // optional func to inform GUI of client version status
|
|
|
|
OnControlTime func(time.Time) // optional func to notify callers of new time from control
|
|
|
|
OnTailnetDefaultAutoUpdate func(bool) // optional func to inform GUI of default auto-update setting for the tailnet
|
|
|
|
Dialer *tsdial.Dialer // non-nil
|
|
|
|
C2NHandler http.Handler // or nil
|
|
|
|
ControlKnobs *controlknobs.Knobs // or nil to ignore
|
2022-08-03 23:31:41 +00:00
|
|
|
|
2023-08-28 22:27:39 +00:00
|
|
|
// Observer is called when there's a change in status to report
|
|
|
|
// from the control client.
|
|
|
|
Observer Observer
|
2022-06-20 01:14:45 +00:00
|
|
|
|
2021-03-31 18:55:21 +00:00
|
|
|
// SkipIPForwardingCheck declares that the host's IP
|
|
|
|
// forwarding works and should not be double-checked by the
|
|
|
|
// controlclient package.
|
|
|
|
SkipIPForwardingCheck bool
|
2021-06-08 15:02:05 +00:00
|
|
|
|
|
|
|
// Pinger optionally specifies the Pinger to use to satisfy
|
|
|
|
// MapResponse.PingRequest queries from the control plane.
|
|
|
|
// If nil, PingRequest queries are not answered.
|
|
|
|
Pinger Pinger
|
2022-09-23 17:06:55 +00:00
|
|
|
|
|
|
|
// DialPlan contains and stores a previous dial plan that we received
|
|
|
|
// from the control server; if nil, we fall back to using DNS.
|
|
|
|
//
|
|
|
|
// If we receive a new DialPlan from the server, this value will be
|
|
|
|
// updated.
|
|
|
|
DialPlan ControlDialPlanner
|
|
|
|
}
|
|
|
|
|
|
|
|
// ControlDialPlanner is the interface optionally supplied when creating a
|
|
|
|
// control client to control exactly how TCP connections to the control plane
|
|
|
|
// are dialed.
|
|
|
|
//
|
|
|
|
// It is usually implemented by an atomic.Pointer.
|
|
|
|
type ControlDialPlanner interface {
|
|
|
|
// Load returns the current plan for how to connect to control.
|
|
|
|
//
|
|
|
|
// The returned plan can be nil. If so, connections should be made by
|
|
|
|
// resolving the control URL using DNS.
|
|
|
|
Load() *tailcfg.ControlDialPlan
|
|
|
|
|
|
|
|
// Store updates the dial plan with new directions from the control
|
|
|
|
// server.
|
|
|
|
//
|
|
|
|
// The dial plan can span multiple connections to the control server.
|
|
|
|
// That is, a dial plan received when connected over Wi-Fi is still
|
|
|
|
// valid for a subsequent connection over LTE after a network switch.
|
|
|
|
Store(*tailcfg.ControlDialPlan)
|
2021-06-08 15:02:05 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 20:07:14 +00:00
|
|
|
// Pinger is the LocalBackend.Ping method.
|
2021-06-08 15:02:05 +00:00
|
|
|
type Pinger interface {
|
2022-06-06 20:07:14 +00:00
|
|
|
// Ping is a request to do a ping with the peer handling the given IP.
|
2023-08-08 12:11:28 +00:00
|
|
|
Ping(ctx context.Context, ip netip.Addr, pingType tailcfg.PingType, size int) (*ipnstate.PingResult, error)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type Decompressor interface {
|
|
|
|
DecodeAll(input, dst []byte) ([]byte, error)
|
|
|
|
Close()
|
|
|
|
}
|
|
|
|
|
2023-08-12 15:18:10 +00:00
|
|
|
// NetmapUpdater is the interface needed by the controlclient to enact change in
|
|
|
|
// the world as a function of updates received from the network.
|
|
|
|
type NetmapUpdater interface {
|
|
|
|
UpdateFullNetmap(*netmap.NetworkMap)
|
|
|
|
|
|
|
|
// TODO(bradfitz): add methods to do fine-grained updates, mutating just
|
|
|
|
// parts of peers, without implementations of NetmapUpdater needing to do
|
|
|
|
// the diff themselves between the previous full & next full network maps.
|
|
|
|
}
|
|
|
|
|
2023-09-02 02:28:00 +00:00
|
|
|
// NetmapDeltaUpdater is an optional interface that can be implemented by
|
|
|
|
// NetmapUpdater implementations to receive delta updates from the controlclient
|
|
|
|
// rather than just full updates.
|
|
|
|
type NetmapDeltaUpdater interface {
|
|
|
|
// UpdateNetmapDelta is called with discrete changes to the network map.
|
|
|
|
//
|
|
|
|
// The ok result is whether the implementation was able to apply the
|
|
|
|
// mutations. It might return false if its internal state doesn't
|
|
|
|
// support applying them or a NetmapUpdater it's wrapping doesn't
|
|
|
|
// implement the NetmapDeltaUpdater optional method.
|
|
|
|
UpdateNetmapDelta([]netmap.NodeMutation) (ok bool)
|
|
|
|
}
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
// NewDirect returns a new Direct client.
|
|
|
|
func NewDirect(opts Options) (*Direct, error) {
|
|
|
|
if opts.ServerURL == "" {
|
|
|
|
return nil, errors.New("controlclient.New: no server URL specified")
|
|
|
|
}
|
2021-03-31 15:51:22 +00:00
|
|
|
if opts.GetMachinePrivateKey == nil {
|
|
|
|
return nil, errors.New("controlclient.New: no GetMachinePrivateKey specified")
|
2020-09-28 22:28:26 +00:00
|
|
|
}
|
2023-09-11 19:03:39 +00:00
|
|
|
if opts.ControlKnobs == nil {
|
|
|
|
opts.ControlKnobs = &controlknobs.Knobs{}
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
opts.ServerURL = strings.TrimRight(opts.ServerURL, "/")
|
2020-04-27 15:18:35 +00:00
|
|
|
serverURL, err := url.Parse(opts.ServerURL)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-08-04 23:29:44 +00:00
|
|
|
if opts.Clock == nil {
|
|
|
|
opts.Clock = tstime.StdClock{}
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
if opts.Logf == nil {
|
|
|
|
// TODO(apenwarr): remove this default and fail instead.
|
2020-02-25 18:04:20 +00:00
|
|
|
// TODO(bradfitz): ... but then it shouldn't be in Options.
|
2020-02-05 22:16:58 +00:00
|
|
|
opts.Logf = log.Printf
|
|
|
|
}
|
2020-04-25 20:24:53 +00:00
|
|
|
|
2023-04-30 03:25:37 +00:00
|
|
|
dnsCache := &dnscache.Resolver{
|
|
|
|
Forward: dnscache.Get().Forward, // use default cache's forwarder
|
|
|
|
UseLastGood: true,
|
|
|
|
LookupIPFallback: dnsfallback.MakeLookupFunc(opts.Logf, opts.NetMon),
|
|
|
|
Logf: opts.Logf,
|
|
|
|
NetMon: opts.NetMon,
|
|
|
|
}
|
|
|
|
|
2020-04-26 14:45:42 +00:00
|
|
|
httpc := opts.HTTPTestClient
|
2021-11-07 21:49:55 +00:00
|
|
|
if httpc == nil && runtime.GOOS == "js" {
|
|
|
|
// In js/wasm, net/http.Transport (as of Go 1.18) will
|
|
|
|
// only use the browser's Fetch API if you're using
|
|
|
|
// the DefaultClient (or a client without dial hooks
|
|
|
|
// etc set).
|
|
|
|
httpc = http.DefaultClient
|
|
|
|
}
|
2020-04-26 14:45:42 +00:00
|
|
|
if httpc == nil {
|
|
|
|
tr := http.DefaultTransport.(*http.Transport).Clone()
|
2020-08-13 22:25:54 +00:00
|
|
|
tr.Proxy = tshttpproxy.ProxyFromEnvironment
|
2020-08-27 03:02:16 +00:00
|
|
|
tshttpproxy.SetTransportGetProxyConnectHeader(tr)
|
2021-04-10 02:09:22 +00:00
|
|
|
tr.TLSClientConfig = tlsdial.Config(serverURL.Hostname(), tr.TLSClientConfig)
|
2022-04-27 18:57:59 +00:00
|
|
|
tr.DialContext = dnscache.Dialer(opts.Dialer.SystemDial, dnsCache)
|
|
|
|
tr.DialTLSContext = dnscache.TLSDialer(opts.Dialer.SystemDial, dnsCache, tr.TLSClientConfig)
|
2020-04-26 14:45:42 +00:00
|
|
|
tr.ForceAttemptHTTP2 = true
|
2022-02-07 21:42:28 +00:00
|
|
|
// Disable implicit gzip compression; the various
|
|
|
|
// handlers (register, map, set-dns, etc) do their own
|
|
|
|
// zstd compression per naclbox.
|
|
|
|
tr.DisableCompression = true
|
2020-04-26 14:45:42 +00:00
|
|
|
httpc = &http.Client{Transport: tr}
|
|
|
|
}
|
2020-04-25 20:24:53 +00:00
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
c := &Direct{
|
2023-12-18 22:57:03 +00:00
|
|
|
httpc: httpc,
|
|
|
|
controlKnobs: opts.ControlKnobs,
|
|
|
|
getMachinePrivKey: opts.GetMachinePrivateKey,
|
|
|
|
serverURL: opts.ServerURL,
|
|
|
|
clock: opts.Clock,
|
|
|
|
logf: opts.Logf,
|
|
|
|
persist: opts.Persist.View(),
|
|
|
|
authKey: opts.AuthKey,
|
|
|
|
discoPubKey: opts.DiscoPublicKey,
|
|
|
|
debugFlags: opts.DebugFlags,
|
|
|
|
netMon: opts.NetMon,
|
|
|
|
skipIPForwardingCheck: opts.SkipIPForwardingCheck,
|
|
|
|
pinger: opts.Pinger,
|
|
|
|
popBrowser: opts.PopBrowserURL,
|
|
|
|
onClientVersion: opts.OnClientVersion,
|
|
|
|
onTailnetDefaultAutoUpdate: opts.OnTailnetDefaultAutoUpdate,
|
|
|
|
onControlTime: opts.OnControlTime,
|
|
|
|
c2nHandler: opts.C2NHandler,
|
|
|
|
dialer: opts.Dialer,
|
|
|
|
dnsCache: dnsCache,
|
|
|
|
dialPlan: opts.DialPlan,
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
if opts.Hostinfo == nil {
|
2021-08-20 17:34:13 +00:00
|
|
|
c.SetHostinfo(hostinfo.New())
|
2020-02-05 22:16:58 +00:00
|
|
|
} else {
|
2020-02-25 18:04:20 +00:00
|
|
|
c.SetHostinfo(opts.Hostinfo)
|
2023-08-10 02:56:43 +00:00
|
|
|
if ni := opts.Hostinfo.NetInfo; ni != nil {
|
2022-05-03 22:07:30 +00:00
|
|
|
c.SetNetInfo(ni)
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-09-06 23:34:16 +00:00
|
|
|
if opts.NoiseTestClient != nil {
|
2022-11-03 07:17:16 +00:00
|
|
|
c.noiseClient = &NoiseClient{
|
2022-09-06 23:34:16 +00:00
|
|
|
Client: opts.NoiseTestClient,
|
|
|
|
}
|
|
|
|
c.serverNoiseKey = key.NewMachine().Public() // prevent early error before hitting test client
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
2022-03-07 23:32:53 +00:00
|
|
|
// Close closes the underlying Noise connection(s).
|
|
|
|
func (c *Direct) Close() error {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
if c.noiseClient != nil {
|
|
|
|
if err := c.noiseClient.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.noiseClient = nil
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-25 18:04:20 +00:00
|
|
|
// SetHostinfo clones the provided Hostinfo and remembers it for the
|
2020-04-02 00:18:39 +00:00
|
|
|
// next update. It reports whether the Hostinfo has changed.
|
|
|
|
func (c *Direct) SetHostinfo(hi *tailcfg.Hostinfo) bool {
|
2020-02-25 18:04:20 +00:00
|
|
|
if hi == nil {
|
|
|
|
panic("nil Hostinfo")
|
|
|
|
}
|
2023-08-10 02:56:43 +00:00
|
|
|
hi = ptr.To(*hi)
|
|
|
|
hi.NetInfo = nil
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
2020-04-02 00:18:39 +00:00
|
|
|
if hi.Equal(c.hostinfo) {
|
|
|
|
return false
|
|
|
|
}
|
2020-02-27 20:20:29 +00:00
|
|
|
c.hostinfo = hi.Clone()
|
2020-10-19 15:30:36 +00:00
|
|
|
j, _ := json.Marshal(c.hostinfo)
|
2022-02-12 16:05:24 +00:00
|
|
|
c.logf("[v1] HostInfo: %s", j)
|
2020-04-02 00:18:39 +00:00
|
|
|
return true
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-03-04 06:21:56 +00:00
|
|
|
// SetNetInfo clones the provided NetInfo and remembers it for the
|
2020-04-02 00:18:39 +00:00
|
|
|
// next update. It reports whether the NetInfo has changed.
|
|
|
|
func (c *Direct) SetNetInfo(ni *tailcfg.NetInfo) bool {
|
2020-03-04 06:21:56 +00:00
|
|
|
if ni == nil {
|
|
|
|
panic("nil NetInfo")
|
|
|
|
}
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
2022-05-03 22:07:30 +00:00
|
|
|
if reflect.DeepEqual(ni, c.netinfo) {
|
2020-04-02 00:18:39 +00:00
|
|
|
return false
|
2020-03-04 06:21:56 +00:00
|
|
|
}
|
2022-05-03 22:07:30 +00:00
|
|
|
c.netinfo = ni.Clone()
|
|
|
|
c.logf("NetInfo: %v", ni)
|
2020-04-02 00:18:39 +00:00
|
|
|
return true
|
2020-03-04 06:21:56 +00:00
|
|
|
}
|
|
|
|
|
2022-10-27 20:40:31 +00:00
|
|
|
// SetNetInfo stores a new TKA head value for next update.
|
|
|
|
// It reports whether the TKA head changed.
|
|
|
|
func (c *Direct) SetTKAHead(tkaHead string) bool {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
if tkaHead == c.tkaHead {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
c.tkaHead = tkaHead
|
|
|
|
c.logf("tkaHead: %v", tkaHead)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-11-09 05:58:10 +00:00
|
|
|
func (c *Direct) GetPersist() persist.PersistView {
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
2022-11-10 14:43:59 +00:00
|
|
|
return c.persist
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Direct) TryLogout(ctx context.Context) error {
|
2022-02-12 16:05:24 +00:00
|
|
|
c.logf("[v1] direct.TryLogout()")
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-10-13 17:43:00 +00:00
|
|
|
mustRegen, newURL, _, err := c.doLogin(ctx, loginOpt{Logout: true})
|
2022-02-12 16:05:24 +00:00
|
|
|
c.logf("[v1] TryLogout control response: mustRegen=%v, newURL=%v, err=%v", mustRegen, newURL, err)
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2021-04-08 04:06:31 +00:00
|
|
|
c.mu.Lock()
|
2022-11-10 14:43:59 +00:00
|
|
|
c.persist = new(persist.Persist).View()
|
2021-04-08 04:06:31 +00:00
|
|
|
c.mu.Unlock()
|
|
|
|
|
|
|
|
return err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-03-19 17:21:33 +00:00
|
|
|
func (c *Direct) TryLogin(ctx context.Context, t *tailcfg.Oauth2Token, flags LoginFlags) (url string, err error) {
|
2022-02-12 16:05:24 +00:00
|
|
|
c.logf("[v1] direct.TryLogin(token=%v, flags=%v)", t != nil, flags)
|
2021-04-08 04:06:31 +00:00
|
|
|
return c.doLoginOrRegen(ctx, loginOpt{Token: t, Flags: flags})
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-03-31 15:25:39 +00:00
|
|
|
// WaitLoginURL sits in a long poll waiting for the user to authenticate at url.
|
|
|
|
//
|
|
|
|
// On success, newURL and err will both be nil.
|
|
|
|
func (c *Direct) WaitLoginURL(ctx context.Context, url string) (newURL string, err error) {
|
2022-02-12 16:05:24 +00:00
|
|
|
c.logf("[v1] direct.WaitLoginURL")
|
2021-04-08 04:06:31 +00:00
|
|
|
return c.doLoginOrRegen(ctx, loginOpt{URL: url})
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-04-08 04:06:31 +00:00
|
|
|
func (c *Direct) doLoginOrRegen(ctx context.Context, opt loginOpt) (newURL string, err error) {
|
2022-10-13 17:43:00 +00:00
|
|
|
mustRegen, url, oldNodeKeySignature, err := c.doLogin(ctx, opt)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return url, err
|
|
|
|
}
|
2021-04-08 04:06:31 +00:00
|
|
|
if mustRegen {
|
|
|
|
opt.Regen = true
|
2022-10-13 17:43:00 +00:00
|
|
|
opt.OldNodeKeySignature = oldNodeKeySignature
|
|
|
|
_, url, _, err = c.doLogin(ctx, opt)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
return url, err
|
|
|
|
}
|
|
|
|
|
2022-03-09 22:42:42 +00:00
|
|
|
// SetExpirySooner attempts to shorten the expiry to the specified time.
|
|
|
|
func (c *Direct) SetExpirySooner(ctx context.Context, expiry time.Time) error {
|
|
|
|
c.logf("[v1] direct.SetExpirySooner()")
|
|
|
|
|
|
|
|
newURL, err := c.doLoginOrRegen(ctx, loginOpt{Expiry: &expiry})
|
|
|
|
c.logf("[v1] SetExpirySooner control response: newURL=%v, err=%v", newURL, err)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-04-08 04:06:31 +00:00
|
|
|
type loginOpt struct {
|
2021-04-08 04:06:31 +00:00
|
|
|
Token *tailcfg.Oauth2Token
|
|
|
|
Flags LoginFlags
|
2022-03-09 22:42:42 +00:00
|
|
|
Regen bool // generate a new nodekey, can be overridden in doLogin
|
2021-04-08 04:06:31 +00:00
|
|
|
URL string
|
2022-03-09 22:42:42 +00:00
|
|
|
Logout bool // set the expiry to the far past, expiring the node
|
|
|
|
// Expiry, if non-nil, attempts to set the node expiry to the
|
|
|
|
// specified time and cannot be used to extend the expiry.
|
|
|
|
// It is ignored if Logout is set since Logout works by setting a
|
|
|
|
// expiry time in the far past.
|
|
|
|
Expiry *time.Time
|
2022-10-13 17:43:00 +00:00
|
|
|
|
|
|
|
// OldNodeKeySignature indicates the former NodeKeySignature
|
|
|
|
// that must be resigned for the new node-key.
|
|
|
|
OldNodeKeySignature tkatype.MarshaledSignature
|
2021-04-08 04:06:31 +00:00
|
|
|
}
|
|
|
|
|
2022-03-08 18:53:19 +00:00
|
|
|
// httpClient provides a common interface for the noiseClient and
|
|
|
|
// the NaCl box http.Client.
|
|
|
|
type httpClient interface {
|
|
|
|
Do(req *http.Request) (*http.Response, error)
|
|
|
|
}
|
|
|
|
|
2022-05-03 22:07:30 +00:00
|
|
|
// hostInfoLocked returns a Clone of c.hostinfo and c.netinfo.
|
|
|
|
// It must only be called with c.mu held.
|
|
|
|
func (c *Direct) hostInfoLocked() *tailcfg.Hostinfo {
|
|
|
|
hi := c.hostinfo.Clone()
|
|
|
|
hi.NetInfo = c.netinfo.Clone()
|
|
|
|
return hi
|
|
|
|
}
|
|
|
|
|
2022-10-13 17:43:00 +00:00
|
|
|
func (c *Direct) doLogin(ctx context.Context, opt loginOpt) (mustRegen bool, newURL string, nks tkatype.MarshaledSignature, err error) {
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Lock()
|
2022-11-10 14:43:59 +00:00
|
|
|
persist := c.persist.AsStruct()
|
2020-02-05 22:16:58 +00:00
|
|
|
tryingNewKey := c.tryingNewKey
|
|
|
|
serverKey := c.serverKey
|
2022-03-08 18:53:19 +00:00
|
|
|
serverNoiseKey := c.serverNoiseKey
|
2023-03-02 21:24:26 +00:00
|
|
|
authKey, isWrapped, wrappedSig, wrappedKey := decodeWrappedAuthkey(c.authKey, c.logf)
|
2022-05-03 22:07:30 +00:00
|
|
|
hi := c.hostInfoLocked()
|
2021-11-10 16:11:14 +00:00
|
|
|
backendLogID := hi.BackendLogID
|
2023-08-20 21:55:07 +00:00
|
|
|
expired := !c.expiry.IsZero() && c.expiry.Before(c.clock.Now())
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Unlock()
|
|
|
|
|
2021-03-31 15:51:22 +00:00
|
|
|
machinePrivKey, err := c.getMachinePrivKey()
|
|
|
|
if err != nil {
|
2022-10-13 17:43:00 +00:00
|
|
|
return false, "", nil, fmt.Errorf("getMachinePrivKey: %w", err)
|
2021-03-31 15:51:22 +00:00
|
|
|
}
|
|
|
|
if machinePrivKey.IsZero() {
|
2022-10-13 17:43:00 +00:00
|
|
|
return false, "", nil, errors.New("getMachinePrivKey returned zero key")
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-04-08 04:06:31 +00:00
|
|
|
regen := opt.Regen
|
2021-04-08 04:06:31 +00:00
|
|
|
if opt.Logout {
|
|
|
|
c.logf("logging out...")
|
|
|
|
} else {
|
|
|
|
if expired {
|
|
|
|
c.logf("Old key expired -> regen=true")
|
|
|
|
systemd.Status("key expired; run 'tailscale up' to authenticate")
|
|
|
|
regen = true
|
|
|
|
}
|
|
|
|
if (opt.Flags & LoginInteractive) != 0 {
|
|
|
|
c.logf("LoginInteractive -> regen=true")
|
|
|
|
regen = true
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-04-08 04:06:31 +00:00
|
|
|
c.logf("doLogin(regen=%v, hasUrl=%v)", regen, opt.URL != "")
|
2020-12-30 01:22:56 +00:00
|
|
|
if serverKey.IsZero() {
|
2022-03-07 18:55:02 +00:00
|
|
|
keys, err := loadServerPubKeys(ctx, c.httpc, c.serverURL)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, opt.URL, nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-04-27 02:11:55 +00:00
|
|
|
c.logf("control server key from %s: ts2021=%s, legacy=%v", c.serverURL, keys.PublicKey.ShortString(), keys.LegacyPublicKey.ShortString())
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
c.mu.Lock()
|
2022-03-07 18:55:02 +00:00
|
|
|
c.serverKey = keys.LegacyPublicKey
|
|
|
|
c.serverNoiseKey = keys.PublicKey
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Unlock()
|
2022-03-07 18:55:02 +00:00
|
|
|
serverKey = keys.LegacyPublicKey
|
2022-03-08 18:53:19 +00:00
|
|
|
serverNoiseKey = keys.PublicKey
|
2022-03-10 21:19:21 +00:00
|
|
|
|
|
|
|
// For servers supporting the Noise transport,
|
|
|
|
// proactively shut down our TLS TCP connection.
|
|
|
|
// We're not going to need it and it's nicer to the
|
|
|
|
// server.
|
|
|
|
if !serverNoiseKey.IsZero() {
|
|
|
|
c.httpc.CloseIdleConnections()
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-10-28 21:22:51 +00:00
|
|
|
var oldNodeKey key.NodePublic
|
2021-04-08 04:06:31 +00:00
|
|
|
switch {
|
|
|
|
case opt.Logout:
|
2021-10-28 21:22:51 +00:00
|
|
|
tryingNewKey = persist.PrivateNodeKey
|
2021-04-08 04:06:31 +00:00
|
|
|
case opt.URL != "":
|
|
|
|
// Nothing.
|
|
|
|
case regen || persist.PrivateNodeKey.IsZero():
|
2020-04-11 15:35:34 +00:00
|
|
|
c.logf("Generating a new nodekey.")
|
2020-02-05 22:16:58 +00:00
|
|
|
persist.OldPrivateNodeKey = persist.PrivateNodeKey
|
2021-10-28 21:22:51 +00:00
|
|
|
tryingNewKey = key.NewNode()
|
2021-04-08 04:06:31 +00:00
|
|
|
default:
|
2020-02-05 22:16:58 +00:00
|
|
|
// Try refreshing the current key first
|
2021-10-28 21:22:51 +00:00
|
|
|
tryingNewKey = persist.PrivateNodeKey
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-10-01 00:13:41 +00:00
|
|
|
if !persist.OldPrivateNodeKey.IsZero() {
|
2021-10-28 21:22:51 +00:00
|
|
|
oldNodeKey = persist.OldPrivateNodeKey.Public()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-11-14 12:29:49 +00:00
|
|
|
if persist.NetworkLockKey.IsZero() {
|
|
|
|
persist.NetworkLockKey = key.NewNLPrivate()
|
|
|
|
}
|
|
|
|
nlPub := persist.NetworkLockKey.Public()
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-10-13 17:43:00 +00:00
|
|
|
if tryingNewKey.IsZero() {
|
|
|
|
if opt.Logout {
|
|
|
|
return false, "", nil, errors.New("no nodekey to log out")
|
|
|
|
}
|
|
|
|
log.Fatalf("tryingNewKey is empty, give up")
|
|
|
|
}
|
|
|
|
|
|
|
|
var nodeKeySignature tkatype.MarshaledSignature
|
2022-11-14 12:29:49 +00:00
|
|
|
if !oldNodeKey.IsZero() && opt.OldNodeKeySignature != nil {
|
|
|
|
if nodeKeySignature, err = resignNKS(persist.NetworkLockKey, tryingNewKey.Public(), opt.OldNodeKeySignature); err != nil {
|
|
|
|
c.logf("Failed re-signing node-key signature: %v", err)
|
2021-04-08 04:06:31 +00:00
|
|
|
}
|
2023-03-02 21:24:26 +00:00
|
|
|
} else if isWrapped {
|
|
|
|
// We were given a wrapped pre-auth key, which means that in addition
|
|
|
|
// to being a regular pre-auth key there was a suffix with information to
|
|
|
|
// generate a tailnet-lock signature.
|
|
|
|
nk, err := tryingNewKey.Public().MarshalBinary()
|
|
|
|
if err != nil {
|
|
|
|
return false, "", nil, fmt.Errorf("marshalling node-key: %w", err)
|
|
|
|
}
|
|
|
|
sig := &tka.NodeKeySignature{
|
|
|
|
SigKind: tka.SigRotation,
|
|
|
|
Pubkey: nk,
|
|
|
|
Nested: wrappedSig,
|
|
|
|
}
|
|
|
|
sigHash := sig.SigHash()
|
|
|
|
sig.Signature = ed25519.Sign(wrappedKey, sigHash[:])
|
|
|
|
nodeKeySignature = sig.Serialize()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-10-13 17:43:00 +00:00
|
|
|
|
2020-06-15 23:04:12 +00:00
|
|
|
if backendLogID == "" {
|
2020-02-05 22:16:58 +00:00
|
|
|
err = errors.New("hostinfo: BackendLogID missing")
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, opt.URL, nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2023-10-13 18:13:41 +00:00
|
|
|
|
|
|
|
tailnet, err := syspolicy.GetString(syspolicy.Tailnet, "")
|
|
|
|
if err != nil {
|
|
|
|
c.logf("unable to provide Tailnet field in register request. err: %v", err)
|
|
|
|
}
|
2023-08-04 23:29:44 +00:00
|
|
|
now := c.clock.Now().Round(time.Second)
|
2020-02-05 22:16:58 +00:00
|
|
|
request := tailcfg.RegisterRequest{
|
2022-10-13 17:43:00 +00:00
|
|
|
Version: 1,
|
|
|
|
OldNodeKey: oldNodeKey,
|
|
|
|
NodeKey: tryingNewKey.Public(),
|
|
|
|
NLKey: nlPub,
|
|
|
|
Hostinfo: hi,
|
|
|
|
Followup: opt.URL,
|
|
|
|
Timestamp: &now,
|
|
|
|
Ephemeral: (opt.Flags & LoginEphemeral) != 0,
|
|
|
|
NodeKeySignature: nodeKeySignature,
|
2023-10-13 18:13:41 +00:00
|
|
|
Tailnet: tailnet,
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-04-08 04:06:31 +00:00
|
|
|
if opt.Logout {
|
|
|
|
request.Expiry = time.Unix(123, 0) // far in the past
|
2022-03-09 22:42:42 +00:00
|
|
|
} else if opt.Expiry != nil {
|
|
|
|
request.Expiry = *opt.Expiry
|
2021-04-08 04:06:31 +00:00
|
|
|
}
|
2022-10-13 17:43:00 +00:00
|
|
|
c.logf("RegisterReq: onode=%v node=%v fup=%v nks=%v",
|
2020-03-18 22:10:46 +00:00
|
|
|
request.OldNodeKey.ShortString(),
|
2022-10-13 17:43:00 +00:00
|
|
|
request.NodeKey.ShortString(), opt.URL != "", len(nodeKeySignature) > 0)
|
2021-04-08 04:06:31 +00:00
|
|
|
request.Auth.Oauth2Token = opt.Token
|
2020-02-05 22:16:58 +00:00
|
|
|
request.Auth.Provider = persist.Provider
|
2023-08-04 00:38:28 +00:00
|
|
|
request.Auth.LoginName = persist.UserProfile.LoginName
|
2020-05-19 06:51:27 +00:00
|
|
|
request.Auth.AuthKey = authKey
|
2021-03-31 15:51:22 +00:00
|
|
|
err = signRegisterRequest(&request, c.serverURL, c.serverKey, machinePrivKey.Public())
|
2021-03-26 14:01:08 +00:00
|
|
|
if err != nil {
|
|
|
|
// If signing failed, clear all related fields
|
|
|
|
request.SignatureType = tailcfg.SignatureNone
|
|
|
|
request.Timestamp = nil
|
|
|
|
request.DeviceCert = nil
|
|
|
|
request.Signature = nil
|
|
|
|
|
|
|
|
// Don't log the common error types. Signatures are not usually enabled,
|
|
|
|
// so these are expected.
|
2021-04-22 18:59:03 +00:00
|
|
|
if !errors.Is(err, errCertificateNotConfigured) && !errors.Is(err, errNoCertStore) {
|
2021-03-26 14:01:08 +00:00
|
|
|
c.logf("RegisterReq sign error: %v", err)
|
|
|
|
}
|
|
|
|
}
|
2022-09-14 19:49:39 +00:00
|
|
|
if debugRegister() {
|
2021-04-08 04:06:31 +00:00
|
|
|
j, _ := json.MarshalIndent(request, "", "\t")
|
|
|
|
c.logf("RegisterRequest: %s", j)
|
|
|
|
}
|
|
|
|
|
2022-03-08 18:53:19 +00:00
|
|
|
// URL and httpc are protocol specific.
|
|
|
|
var url string
|
|
|
|
var httpc httpClient
|
|
|
|
if serverNoiseKey.IsZero() {
|
|
|
|
httpc = c.httpc
|
|
|
|
url = fmt.Sprintf("%s/machine/%s", c.serverURL, machinePrivKey.Public().UntypedHexString())
|
|
|
|
} else {
|
|
|
|
request.Version = tailcfg.CurrentCapabilityVersion
|
|
|
|
httpc, err = c.getNoiseClient()
|
|
|
|
if err != nil {
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, opt.URL, nil, fmt.Errorf("getNoiseClient: %w", err)
|
2022-03-08 18:53:19 +00:00
|
|
|
}
|
|
|
|
url = fmt.Sprintf("%s/machine/register", c.serverURL)
|
|
|
|
url = strings.Replace(url, "http:", "https:", 1)
|
|
|
|
}
|
|
|
|
bodyData, err := encode(request, serverKey, serverNoiseKey, machinePrivKey)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, opt.URL, nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-03-08 18:53:19 +00:00
|
|
|
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyData))
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, opt.URL, nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-03-08 18:53:19 +00:00
|
|
|
res, err := httpc.Do(req)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, opt.URL, nil, fmt.Errorf("register request: %w", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-10-06 02:57:14 +00:00
|
|
|
if res.StatusCode != 200 {
|
2022-09-15 12:06:59 +00:00
|
|
|
msg, _ := io.ReadAll(res.Body)
|
2020-10-06 02:57:14 +00:00
|
|
|
res.Body.Close()
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, opt.URL, nil, fmt.Errorf("register request: http %d: %.200s",
|
2020-10-06 02:57:14 +00:00
|
|
|
res.StatusCode, strings.TrimSpace(string(msg)))
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
resp := tailcfg.RegisterResponse{}
|
2022-03-08 18:53:19 +00:00
|
|
|
if err := decode(res, &resp, serverKey, serverNoiseKey, machinePrivKey); err != nil {
|
2021-03-31 15:51:22 +00:00
|
|
|
c.logf("error decoding RegisterResponse with server key %s and machine key %s: %v", serverKey, machinePrivKey.Public(), err)
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, opt.URL, nil, fmt.Errorf("register request: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-09-14 19:49:39 +00:00
|
|
|
if debugRegister() {
|
2021-04-08 04:06:31 +00:00
|
|
|
j, _ := json.MarshalIndent(resp, "", "\t")
|
|
|
|
c.logf("RegisterResponse: %s", j)
|
|
|
|
}
|
|
|
|
|
2020-09-28 22:28:26 +00:00
|
|
|
// Log without PII:
|
|
|
|
c.logf("RegisterReq: got response; nodeKeyExpired=%v, machineAuthorized=%v; authURL=%v",
|
|
|
|
resp.NodeKeyExpired, resp.MachineAuthorized, resp.AuthURL != "")
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2021-10-26 17:19:35 +00:00
|
|
|
if resp.Error != "" {
|
2022-10-13 17:43:00 +00:00
|
|
|
return false, "", nil, UserVisibleError(resp.Error)
|
|
|
|
}
|
|
|
|
if len(resp.NodeKeySignature) > 0 {
|
|
|
|
return true, "", resp.NodeKeySignature, nil
|
2021-10-26 17:19:35 +00:00
|
|
|
}
|
2022-10-13 17:43:00 +00:00
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
if resp.NodeKeyExpired {
|
|
|
|
if regen {
|
2022-10-13 17:43:00 +00:00
|
|
|
return true, "", nil, fmt.Errorf("weird: regen=true but server says NodeKeyExpired: %v", request.NodeKey)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
c.logf("server reports new node key %v has expired",
|
2020-03-18 22:10:46 +00:00
|
|
|
request.NodeKey.ShortString())
|
2022-10-13 17:43:00 +00:00
|
|
|
return true, "", nil, nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-05-06 03:16:44 +00:00
|
|
|
if resp.Login.Provider != "" {
|
2020-02-05 22:16:58 +00:00
|
|
|
persist.Provider = resp.Login.Provider
|
|
|
|
}
|
2022-11-09 05:58:10 +00:00
|
|
|
persist.UserProfile = tailcfg.UserProfile{
|
|
|
|
ID: resp.User.ID,
|
|
|
|
DisplayName: resp.Login.DisplayName,
|
|
|
|
ProfilePicURL: resp.Login.ProfilePicURL,
|
|
|
|
LoginName: resp.Login.LoginName,
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
// TODO(crawshaw): RegisterResponse should be able to mechanically
|
|
|
|
// communicate some extra instructions from the server:
|
|
|
|
// - new node key required
|
|
|
|
// - machine key no longer supported
|
|
|
|
// - user is disabled
|
|
|
|
|
|
|
|
if resp.AuthURL != "" {
|
2020-07-02 16:45:08 +00:00
|
|
|
c.logf("AuthURL is %v", resp.AuthURL)
|
2020-02-05 22:16:58 +00:00
|
|
|
} else {
|
2022-02-12 16:05:24 +00:00
|
|
|
c.logf("[v1] No AuthURL")
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
c.mu.Lock()
|
|
|
|
if resp.AuthURL == "" {
|
|
|
|
// key rotation is complete
|
2021-10-28 21:22:51 +00:00
|
|
|
persist.PrivateNodeKey = tryingNewKey
|
2020-02-05 22:16:58 +00:00
|
|
|
} else {
|
|
|
|
// save it for the retry-with-URL
|
|
|
|
c.tryingNewKey = tryingNewKey
|
|
|
|
}
|
2022-11-10 14:43:59 +00:00
|
|
|
c.persist = persist.View()
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Unlock()
|
|
|
|
|
|
|
|
if ctx.Err() != nil {
|
2022-10-13 17:43:00 +00:00
|
|
|
return regen, "", nil, ctx.Err()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-10-13 17:43:00 +00:00
|
|
|
return false, resp.AuthURL, nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// resignNKS re-signs a node-key signature for a new node-key.
|
|
|
|
//
|
|
|
|
// This only matters on network-locked tailnets, because node-key signatures are
|
|
|
|
// how other nodes know that a node-key is authentic. When the node-key is
|
|
|
|
// rotated then the existing signature becomes invalid, so this function is
|
|
|
|
// responsible for generating a new wrapping signature to certify the new node-key.
|
|
|
|
//
|
|
|
|
// The signature itself is a SigRotation signature, which embeds the old signature
|
|
|
|
// and certifies the new node-key as a replacement for the old by signing the new
|
|
|
|
// signature with RotationPubkey (which is the node's own network-lock key).
|
|
|
|
func resignNKS(priv key.NLPrivate, nodeKey key.NodePublic, oldNKS tkatype.MarshaledSignature) (tkatype.MarshaledSignature, error) {
|
|
|
|
var oldSig tka.NodeKeySignature
|
|
|
|
if err := oldSig.Unserialize(oldNKS); err != nil {
|
|
|
|
return nil, fmt.Errorf("decoding NKS: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
nk, err := nodeKey.MarshalBinary()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("marshalling node-key: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if bytes.Equal(nk, oldSig.Pubkey) {
|
|
|
|
// The old signature is valid for the node-key we are using, so just
|
|
|
|
// use it verbatim.
|
|
|
|
return oldNKS, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
newSig := tka.NodeKeySignature{
|
|
|
|
SigKind: tka.SigRotation,
|
|
|
|
Pubkey: nk,
|
|
|
|
Nested: &oldSig,
|
|
|
|
}
|
|
|
|
if newSig.Signature, err = priv.SignNKS(newSig.SigHash()); err != nil {
|
|
|
|
return nil, fmt.Errorf("signing NKS: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return newSig.Serialize(), nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-02-14 17:28:29 +00:00
|
|
|
// newEndpoints acquires c.mu and sets the local port and endpoints and reports
|
|
|
|
// whether they've changed.
|
|
|
|
//
|
|
|
|
// It does not retain the provided slice.
|
2022-06-19 23:31:54 +00:00
|
|
|
func (c *Direct) newEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
// Nothing new?
|
2023-08-30 20:34:22 +00:00
|
|
|
if slices.Equal(c.endpoints, endpoints) {
|
2020-02-05 22:16:58 +00:00
|
|
|
return false // unchanged
|
|
|
|
}
|
2023-08-30 20:34:22 +00:00
|
|
|
c.logf("[v2] client.newEndpoints(%v)", endpoints)
|
|
|
|
c.endpoints = slices.Clone(endpoints)
|
2020-02-05 22:16:58 +00:00
|
|
|
return true // changed
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetEndpoints updates the list of locally advertised endpoints.
|
|
|
|
// It won't be replicated to the server until a *fresh* call to PollNetMap().
|
|
|
|
// You don't need to restart PollNetMap if we return changed==false.
|
2022-06-19 23:31:54 +00:00
|
|
|
func (c *Direct) SetEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
|
2020-02-05 22:16:58 +00:00
|
|
|
// (no log message on function entry, because it clutters the logs
|
|
|
|
// if endpoints haven't changed. newEndpoints() will log it.)
|
2022-06-19 23:31:54 +00:00
|
|
|
return c.newEndpoints(endpoints)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2023-08-12 15:18:10 +00:00
|
|
|
// PollNetMap makes a /map request to download the network map, calling
|
|
|
|
// NetmapUpdater on each update from the control plane.
|
|
|
|
//
|
|
|
|
// It always returns a non-nil error describing the reason for the failure or
|
|
|
|
// why the request ended.
|
|
|
|
func (c *Direct) PollNetMap(ctx context.Context, nu NetmapUpdater) error {
|
|
|
|
return c.sendMapRequest(ctx, true, nu)
|
|
|
|
}
|
|
|
|
|
|
|
|
type rememberLastNetmapUpdater struct {
|
|
|
|
last *netmap.NetworkMap
|
|
|
|
}
|
|
|
|
|
|
|
|
func (nu *rememberLastNetmapUpdater) UpdateFullNetmap(nm *netmap.NetworkMap) {
|
|
|
|
nu.last = nm
|
2022-06-19 22:06:33 +00:00
|
|
|
}
|
|
|
|
|
2023-08-10 02:56:43 +00:00
|
|
|
// FetchNetMapForTest fetches the netmap once.
|
|
|
|
func (c *Direct) FetchNetMapForTest(ctx context.Context) (*netmap.NetworkMap, error) {
|
2023-08-12 15:18:10 +00:00
|
|
|
var nu rememberLastNetmapUpdater
|
|
|
|
err := c.sendMapRequest(ctx, false, &nu)
|
|
|
|
if err == nil && nu.last == nil {
|
2022-06-19 22:06:33 +00:00
|
|
|
return nil, errors.New("[unexpected] sendMapRequest success without callback")
|
|
|
|
}
|
2023-08-12 15:18:10 +00:00
|
|
|
return nu.last, err
|
2020-12-23 21:03:16 +00:00
|
|
|
}
|
|
|
|
|
2023-08-10 02:56:43 +00:00
|
|
|
// SendUpdate makes a /map request to update the server of our latest state, but
|
|
|
|
// does not fetch anything. It returns an error if the server did not return a
|
2020-12-23 21:03:16 +00:00
|
|
|
// successful 200 OK response.
|
2023-08-10 02:56:43 +00:00
|
|
|
func (c *Direct) SendUpdate(ctx context.Context) error {
|
|
|
|
return c.sendMapRequest(ctx, false, nil)
|
2020-12-23 21:03:16 +00:00
|
|
|
}
|
|
|
|
|
2023-08-21 02:52:52 +00:00
|
|
|
// If we go more than watchdogTimeout without hearing from the server,
|
2021-04-21 21:17:21 +00:00
|
|
|
// end the long poll. We should be receiving a keep alive ping
|
|
|
|
// every minute.
|
2023-08-21 02:52:52 +00:00
|
|
|
const watchdogTimeout = 120 * time.Second
|
2021-04-21 21:17:21 +00:00
|
|
|
|
2023-08-10 02:56:43 +00:00
|
|
|
// sendMapRequest makes a /map request to download the network map, calling cb
|
|
|
|
// with each new netmap. If isStreaming, it will poll forever and only returns
|
|
|
|
// if the context expires or the server returns an error/closes the connection
|
|
|
|
// and as such always returns a non-nil error.
|
2023-07-14 03:45:12 +00:00
|
|
|
//
|
2023-11-05 18:41:13 +00:00
|
|
|
// If nu is nil, OmitPeers will be set to true.
|
2023-08-12 15:18:10 +00:00
|
|
|
func (c *Direct) sendMapRequest(ctx context.Context, isStreaming bool, nu NetmapUpdater) error {
|
|
|
|
if isStreaming && nu == nil {
|
2023-08-10 02:56:43 +00:00
|
|
|
panic("cb must be non-nil if isStreaming is true")
|
|
|
|
}
|
|
|
|
|
2021-11-16 16:34:25 +00:00
|
|
|
metricMapRequests.Add(1)
|
|
|
|
metricMapRequestsActive.Add(1)
|
|
|
|
defer metricMapRequestsActive.Add(-1)
|
2023-08-10 02:56:43 +00:00
|
|
|
if isStreaming {
|
2021-11-16 16:34:25 +00:00
|
|
|
metricMapRequestsPoll.Add(1)
|
|
|
|
} else {
|
|
|
|
metricMapRequestsLite.Add(1)
|
|
|
|
}
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
persist := c.persist
|
|
|
|
serverURL := c.serverURL
|
|
|
|
serverKey := c.serverKey
|
2022-03-09 18:58:44 +00:00
|
|
|
serverNoiseKey := c.serverNoiseKey
|
2022-05-03 22:07:30 +00:00
|
|
|
hi := c.hostInfoLocked()
|
2021-11-10 16:11:14 +00:00
|
|
|
backendLogID := hi.BackendLogID
|
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
|
|
|
var epStrs []string
|
2023-10-01 04:05:02 +00:00
|
|
|
var eps []netip.AddrPort
|
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
|
|
|
var epTypes []tailcfg.EndpointType
|
|
|
|
for _, ep := range c.endpoints {
|
2023-10-01 04:05:02 +00:00
|
|
|
eps = append(eps, ep.Addr)
|
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
|
|
|
epStrs = append(epStrs, ep.Addr.String())
|
|
|
|
epTypes = append(epTypes, ep.Type)
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
c.mu.Unlock()
|
|
|
|
|
2021-03-31 15:51:22 +00:00
|
|
|
machinePrivKey, err := c.getMachinePrivKey()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("getMachinePrivKey: %w", err)
|
|
|
|
}
|
|
|
|
if machinePrivKey.IsZero() {
|
|
|
|
return errors.New("getMachinePrivKey returned zero key")
|
|
|
|
}
|
|
|
|
|
2022-11-10 14:43:59 +00:00
|
|
|
if persist.PrivateNodeKey().IsZero() {
|
2021-02-05 00:23:16 +00:00
|
|
|
return errors.New("privateNodeKey is zero")
|
|
|
|
}
|
2020-06-15 23:04:12 +00:00
|
|
|
if backendLogID == "" {
|
2020-02-05 22:16:58 +00:00
|
|
|
return errors.New("hostinfo: BackendLogID missing")
|
|
|
|
}
|
|
|
|
|
2023-08-10 02:56:43 +00:00
|
|
|
c.logf("[v1] PollNetMap: stream=%v ep=%v", isStreaming, epStrs)
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf := logger.Discard
|
2022-09-14 19:49:39 +00:00
|
|
|
if DevKnob.DumpNetMaps() {
|
2020-12-21 18:58:06 +00:00
|
|
|
// TODO(bradfitz): update this to use "[v2]" prefix perhaps? but we don't
|
|
|
|
// want to upload it always.
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf = c.logf
|
|
|
|
}
|
|
|
|
|
2021-02-25 05:29:51 +00:00
|
|
|
request := &tailcfg.MapRequest{
|
2022-03-06 17:32:52 +00:00
|
|
|
Version: tailcfg.CurrentCapabilityVersion,
|
2023-09-01 05:28:47 +00:00
|
|
|
KeepAlive: true,
|
2022-10-23 07:48:12 +00:00
|
|
|
NodeKey: persist.PublicNodeKey(),
|
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
|
|
|
DiscoKey: c.discoPubKey,
|
2023-10-01 04:05:02 +00:00
|
|
|
Endpoints: eps,
|
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
|
|
|
EndpointTypes: epTypes,
|
2023-08-10 02:56:43 +00:00
|
|
|
Stream: isStreaming,
|
2021-11-10 16:11:14 +00:00
|
|
|
Hostinfo: hi,
|
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
|
|
|
DebugFlags: c.debugFlags,
|
2023-08-12 15:18:10 +00:00
|
|
|
OmitPeers: nu == nil,
|
2022-10-27 20:40:31 +00:00
|
|
|
TKAHead: c.tkaHead,
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-02-18 16:58:13 +00:00
|
|
|
var extraDebugFlags []string
|
2023-04-18 21:26:58 +00:00
|
|
|
if hi != nil && c.netMon != nil && !c.skipIPForwardingCheck &&
|
|
|
|
ipForwardingBroken(hi.RoutableIPs, c.netMon.InterfaceState()) {
|
2021-02-18 16:58:13 +00:00
|
|
|
extraDebugFlags = append(extraDebugFlags, "warn-ip-forwarding-off")
|
|
|
|
}
|
|
|
|
if health.RouterHealth() != nil {
|
|
|
|
extraDebugFlags = append(extraDebugFlags, "warn-router-unhealthy")
|
|
|
|
}
|
2022-11-13 15:32:37 +00:00
|
|
|
extraDebugFlags = health.AppendWarnableDebugFlags(extraDebugFlags)
|
2021-11-10 16:09:29 +00:00
|
|
|
if hostinfo.DisabledEtcAptSource() {
|
|
|
|
extraDebugFlags = append(extraDebugFlags, "warn-etc-apt-source-disabled")
|
|
|
|
}
|
2021-02-18 16:58:13 +00:00
|
|
|
if len(extraDebugFlags) > 0 {
|
2020-11-04 21:48:50 +00:00
|
|
|
old := request.DebugFlags
|
2021-02-18 16:58:13 +00:00
|
|
|
request.DebugFlags = append(old[:len(old):len(old)], extraDebugFlags...)
|
2020-11-04 21:48:50 +00:00
|
|
|
}
|
2023-09-10 14:24:51 +00:00
|
|
|
request.Compress = "zstd"
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-03-08 18:53:19 +00:00
|
|
|
bodyData, err := encode(request, serverKey, serverNoiseKey, machinePrivKey)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: encode: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-10-14 21:01:33 +00:00
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
defer cancel()
|
|
|
|
|
2021-09-03 20:17:46 +00:00
|
|
|
machinePubKey := machinePrivKey.Public()
|
2023-08-04 23:29:44 +00:00
|
|
|
t0 := c.clock.Now()
|
2020-10-14 21:01:33 +00:00
|
|
|
|
2022-03-09 18:58:44 +00:00
|
|
|
// Url and httpc are protocol specific.
|
|
|
|
var url string
|
|
|
|
var httpc httpClient
|
|
|
|
if serverNoiseKey.IsZero() {
|
|
|
|
httpc = c.httpc
|
|
|
|
url = fmt.Sprintf("%s/machine/%s/map", serverURL, machinePubKey.UntypedHexString())
|
|
|
|
} else {
|
|
|
|
httpc, err = c.getNoiseClient()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("getNoiseClient: %w", err)
|
|
|
|
}
|
|
|
|
url = fmt.Sprintf("%s/machine/map", serverURL)
|
|
|
|
url = strings.Replace(url, "http:", "https:", 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyData))
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-03-09 18:58:44 +00:00
|
|
|
res, err := httpc.Do(req)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: Do: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: Do = %v after %v", res.StatusCode, time.Since(t0).Round(time.Millisecond))
|
2020-02-05 22:16:58 +00:00
|
|
|
if res.StatusCode != 200 {
|
2022-09-15 12:06:59 +00:00
|
|
|
msg, _ := io.ReadAll(res.Body)
|
2020-02-05 22:16:58 +00:00
|
|
|
res.Body.Close()
|
2020-10-06 02:57:14 +00:00
|
|
|
return fmt.Errorf("initial fetch failed %d: %.200s",
|
2020-02-05 22:16:58 +00:00
|
|
|
res.StatusCode, strings.TrimSpace(string(msg)))
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
2021-02-25 05:29:51 +00:00
|
|
|
health.NoteMapRequestHeard(request)
|
|
|
|
|
2023-08-12 15:18:10 +00:00
|
|
|
if nu == nil {
|
2022-09-15 12:06:59 +00:00
|
|
|
io.Copy(io.Discard, res.Body)
|
2020-12-23 21:03:16 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-11 19:03:39 +00:00
|
|
|
sess := newMapSession(persist.PrivateNodeKey(), nu, c.controlKnobs)
|
2023-08-21 02:52:52 +00:00
|
|
|
defer sess.Close()
|
|
|
|
sess.cancel = cancel
|
2021-04-19 02:49:25 +00:00
|
|
|
sess.logf = c.logf
|
|
|
|
sess.vlogf = vlogf
|
2023-08-21 02:52:52 +00:00
|
|
|
sess.altClock = c.clock
|
2021-04-19 02:49:25 +00:00
|
|
|
sess.machinePubKey = machinePubKey
|
2023-08-21 02:52:52 +00:00
|
|
|
sess.onDebug = c.handleDebugMessage
|
|
|
|
sess.onSelfNodeChanged = func(nm *netmap.NetworkMap) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
// If we are the ones who last updated persist, then we can update it
|
|
|
|
// again. Otherwise, we should not touch it. Also, it's only worth
|
|
|
|
// change it if the Node info changed.
|
|
|
|
if persist == c.persist {
|
|
|
|
newPersist := persist.AsStruct()
|
2023-08-21 17:53:57 +00:00
|
|
|
newPersist.NodeID = nm.SelfNode.StableID()
|
2023-08-21 02:52:52 +00:00
|
|
|
newPersist.UserProfile = nm.UserProfiles[nm.User()]
|
|
|
|
|
|
|
|
c.persist = newPersist.View()
|
|
|
|
persist = c.persist
|
|
|
|
}
|
|
|
|
c.expiry = nm.Expiry
|
|
|
|
}
|
2023-11-05 18:41:13 +00:00
|
|
|
|
|
|
|
// Create a watchdog timer that breaks the connection if we don't receive a
|
|
|
|
// MapResponse from the network at least once every two minutes. The
|
|
|
|
// watchdog timer is stopped every time we receive a MapResponse (so it
|
|
|
|
// doesn't run when we're processing a MapResponse message, including any
|
|
|
|
// long-running requested operations like Debug.Sleep) and is reset whenever
|
|
|
|
// we go back to blocking on network reads.
|
|
|
|
watchdogTimer, watchdogTimedOut := c.clock.NewTimer(watchdogTimeout)
|
|
|
|
defer watchdogTimer.Stop()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
vlogf("netmap: ending timeout goroutine")
|
|
|
|
return
|
|
|
|
case <-watchdogTimedOut:
|
|
|
|
c.logf("map response long-poll timed out!")
|
|
|
|
cancel()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}()
|
2023-08-21 02:52:52 +00:00
|
|
|
|
|
|
|
// gotNonKeepAliveMessage is whether we've yet received a MapResponse message without
|
|
|
|
// KeepAlive set.
|
|
|
|
var gotNonKeepAliveMessage bool
|
2020-05-17 16:51:38 +00:00
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
// If allowStream, then the server will use an HTTP long poll to
|
|
|
|
// return incremental results. There is always one response right
|
|
|
|
// away, followed by a delay, and eventually others.
|
|
|
|
// If !allowStream, it'll still send the first result in exactly
|
|
|
|
// the same format before just closing the connection.
|
|
|
|
// We can use this same read loop either way.
|
|
|
|
var msg []byte
|
2023-11-05 15:31:06 +00:00
|
|
|
for mapResIdx := 0; mapResIdx == 0 || isStreaming; mapResIdx++ {
|
2023-11-05 18:41:13 +00:00
|
|
|
watchdogTimer.Reset(watchdogTimeout)
|
2023-08-21 02:52:52 +00:00
|
|
|
vlogf("netmap: starting size read after %v (poll %v)", time.Since(t0).Round(time.Millisecond), mapResIdx)
|
2020-02-05 22:16:58 +00:00
|
|
|
var siz [4]byte
|
|
|
|
if _, err := io.ReadFull(res.Body, siz[:]); err != nil {
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: size read error after %v: %v", time.Since(t0).Round(time.Millisecond), err)
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
size := binary.LittleEndian.Uint32(siz[:])
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: read size %v after %v", size, time.Since(t0).Round(time.Millisecond))
|
2020-02-05 22:16:58 +00:00
|
|
|
msg = append(msg[:0], make([]byte, size)...)
|
|
|
|
if _, err := io.ReadFull(res.Body, msg); err != nil {
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: body read error: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: read body after %v", time.Since(t0).Round(time.Millisecond))
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
var resp tailcfg.MapResponse
|
2021-09-03 20:17:46 +00:00
|
|
|
if err := c.decodeMsg(msg, &resp, machinePrivKey); err != nil {
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: decode error: %v")
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-11-05 18:41:13 +00:00
|
|
|
watchdogTimer.Stop()
|
2020-08-08 03:44:04 +00:00
|
|
|
|
2021-11-16 16:34:25 +00:00
|
|
|
metricMapResponseMessages.Add(1)
|
|
|
|
|
2023-08-10 02:56:43 +00:00
|
|
|
if isStreaming {
|
2021-02-25 05:29:51 +00:00
|
|
|
health.GotStreamedMapResponse()
|
|
|
|
}
|
|
|
|
|
2021-06-15 19:28:34 +00:00
|
|
|
if pr := resp.PingRequest; pr != nil && c.isUniquePingRequest(pr) {
|
2021-11-16 16:34:25 +00:00
|
|
|
metricMapResponsePings.Add(1)
|
2022-08-10 21:52:02 +00:00
|
|
|
go c.answerPing(pr)
|
2021-03-05 04:54:44 +00:00
|
|
|
}
|
2022-03-21 21:10:25 +00:00
|
|
|
if u := resp.PopBrowserURL; u != "" && u != sess.lastPopBrowserURL {
|
|
|
|
sess.lastPopBrowserURL = u
|
|
|
|
if c.popBrowser != nil {
|
|
|
|
c.logf("netmap: control says to open URL %v; opening...", u)
|
|
|
|
c.popBrowser(u)
|
|
|
|
} else {
|
|
|
|
c.logf("netmap: control says to open URL %v; no popBrowser func", u)
|
|
|
|
}
|
|
|
|
}
|
2022-11-24 03:13:41 +00:00
|
|
|
if resp.ClientVersion != nil && c.onClientVersion != nil {
|
|
|
|
c.onClientVersion(resp.ClientVersion)
|
|
|
|
}
|
2022-02-18 18:14:14 +00:00
|
|
|
if resp.ControlTime != nil && !resp.ControlTime.IsZero() {
|
2022-02-18 21:00:08 +00:00
|
|
|
c.logf.JSON(1, "controltime", resp.ControlTime.UTC())
|
2023-01-11 20:59:08 +00:00
|
|
|
if c.onControlTime != nil {
|
|
|
|
c.onControlTime(*resp.ControlTime)
|
|
|
|
}
|
2022-02-17 02:36:04 +00:00
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
if resp.KeepAlive {
|
2020-04-11 16:22:33 +00:00
|
|
|
vlogf("netmap: got keep-alive")
|
2020-08-07 04:24:31 +00:00
|
|
|
} else {
|
|
|
|
vlogf("netmap: got new map")
|
|
|
|
}
|
2022-09-23 17:06:55 +00:00
|
|
|
if resp.ControlDialPlan != nil {
|
|
|
|
if c.dialPlan != nil {
|
|
|
|
c.logf("netmap: got new dial plan from control")
|
|
|
|
c.dialPlan.Store(resp.ControlDialPlan)
|
|
|
|
} else {
|
|
|
|
c.logf("netmap: [unexpected] new dial plan; nowhere to store it")
|
|
|
|
}
|
|
|
|
}
|
2020-08-07 04:24:31 +00:00
|
|
|
if resp.KeepAlive {
|
2021-11-16 16:34:25 +00:00
|
|
|
metricMapResponseKeepAlives.Add(1)
|
2020-02-05 22:16:58 +00:00
|
|
|
continue
|
|
|
|
}
|
2023-12-18 22:57:03 +00:00
|
|
|
if au, ok := resp.DefaultAutoUpdate.Get(); ok {
|
|
|
|
if c.onTailnetDefaultAutoUpdate != nil {
|
|
|
|
c.onTailnetDefaultAutoUpdate(au)
|
|
|
|
}
|
|
|
|
}
|
2020-08-08 03:44:04 +00:00
|
|
|
|
2021-11-16 16:34:25 +00:00
|
|
|
metricMapResponseMap.Add(1)
|
2023-08-21 02:52:52 +00:00
|
|
|
if gotNonKeepAliveMessage {
|
|
|
|
// If we've already seen a non-keep-alive message, this is a delta update.
|
2021-11-16 16:34:25 +00:00
|
|
|
metricMapResponseMapDelta.Add(1)
|
2023-08-21 02:52:52 +00:00
|
|
|
} else if resp.Node == nil {
|
|
|
|
// The very first non-keep-alive message should have Node populated.
|
|
|
|
c.logf("initial MapResponse lacked Node")
|
|
|
|
return errors.New("initial MapResponse lacked node")
|
2021-11-16 16:34:25 +00:00
|
|
|
}
|
2023-08-21 02:52:52 +00:00
|
|
|
gotNonKeepAliveMessage = true
|
2021-11-16 16:34:25 +00:00
|
|
|
|
2023-08-21 02:52:52 +00:00
|
|
|
if err := sess.HandleNonKeepAliveMapResponse(ctx, &resp); err != nil {
|
|
|
|
return err
|
2023-08-04 05:29:27 +00:00
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
if ctx.Err() != nil {
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-11-05 18:41:13 +00:00
|
|
|
func (c *Direct) handleDebugMessage(ctx context.Context, debug *tailcfg.Debug) error {
|
2023-08-21 02:52:52 +00:00
|
|
|
if code := debug.Exit; code != nil {
|
|
|
|
c.logf("exiting process with status %v per controlplane", *code)
|
|
|
|
os.Exit(*code)
|
|
|
|
}
|
|
|
|
if debug.DisableLogTail {
|
|
|
|
logtail.Disable()
|
|
|
|
envknob.SetNoLogsNoSupport()
|
|
|
|
}
|
|
|
|
if sleep := time.Duration(debug.SleepSeconds * float64(time.Second)); sleep > 0 {
|
2023-11-05 18:41:13 +00:00
|
|
|
if err := sleepAsRequested(ctx, c.logf, sleep, c.clock); err != nil {
|
2023-08-21 02:52:52 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-08-20 22:17:25 +00:00
|
|
|
// initDisplayNames mutates any tailcfg.Nodes in resp to populate their display names,
|
|
|
|
// calling InitDisplayNames on each.
|
|
|
|
//
|
|
|
|
// The magicDNSSuffix used is based on selfNode.
|
|
|
|
func initDisplayNames(selfNode tailcfg.NodeView, resp *tailcfg.MapResponse) {
|
|
|
|
if resp.Node == nil && len(resp.Peers) == 0 && len(resp.PeersChanged) == 0 {
|
|
|
|
// Fast path for a common case (delta updates). No need to compute
|
|
|
|
// magicDNSSuffix.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
magicDNSSuffix := netmap.MagicDNSSuffixOfNodeName(selfNode.Name())
|
|
|
|
if resp.Node != nil {
|
|
|
|
resp.Node.InitDisplayNames(magicDNSSuffix)
|
|
|
|
}
|
|
|
|
for _, n := range resp.Peers {
|
|
|
|
n.InitDisplayNames(magicDNSSuffix)
|
|
|
|
}
|
|
|
|
for _, n := range resp.PeersChanged {
|
|
|
|
n.InitDisplayNames(magicDNSSuffix)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-08 18:53:19 +00:00
|
|
|
// decode JSON decodes the res.Body into v. If serverNoiseKey is not specified,
|
|
|
|
// it uses the serverKey and mkey to decode the message from the NaCl-crypto-box.
|
2022-03-16 23:27:57 +00:00
|
|
|
func decode(res *http.Response, v any, serverKey, serverNoiseKey key.MachinePublic, mkey key.MachinePrivate) error {
|
2020-02-05 22:16:58 +00:00
|
|
|
defer res.Body.Close()
|
2022-09-15 12:06:59 +00:00
|
|
|
msg, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if res.StatusCode != 200 {
|
|
|
|
return fmt.Errorf("%d: %v", res.StatusCode, string(msg))
|
|
|
|
}
|
2022-03-08 18:53:19 +00:00
|
|
|
if !serverNoiseKey.IsZero() {
|
|
|
|
return json.Unmarshal(msg, v)
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
return decodeMsg(msg, v, serverKey, mkey)
|
|
|
|
}
|
|
|
|
|
2021-04-08 04:06:31 +00:00
|
|
|
var (
|
2022-09-14 19:49:39 +00:00
|
|
|
debugMap = envknob.RegisterBool("TS_DEBUG_MAP")
|
|
|
|
debugRegister = envknob.RegisterBool("TS_DEBUG_REGISTER")
|
2021-04-08 04:06:31 +00:00
|
|
|
)
|
2020-09-15 16:54:52 +00:00
|
|
|
|
2020-11-12 21:31:29 +00:00
|
|
|
var jsonEscapedZero = []byte(`\u0000`)
|
|
|
|
|
2022-03-09 18:58:44 +00:00
|
|
|
// decodeMsg is responsible for uncompressing msg and unmarshaling into v.
|
|
|
|
// If c.serverNoiseKey is not specified, it uses the c.serverKey and mkey
|
|
|
|
// to first the decrypt msg from the NaCl-crypto-box.
|
2022-03-16 23:27:57 +00:00
|
|
|
func (c *Direct) decodeMsg(msg []byte, v any, mkey key.MachinePrivate) error {
|
2020-07-09 18:42:19 +00:00
|
|
|
c.mu.Lock()
|
2020-02-05 22:16:58 +00:00
|
|
|
serverKey := c.serverKey
|
2022-03-09 18:58:44 +00:00
|
|
|
serverNoiseKey := c.serverNoiseKey
|
2020-07-09 18:42:19 +00:00
|
|
|
c.mu.Unlock()
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-03-09 18:58:44 +00:00
|
|
|
var decrypted []byte
|
|
|
|
if serverNoiseKey.IsZero() {
|
|
|
|
var ok bool
|
|
|
|
decrypted, ok = mkey.OpenFrom(serverKey, msg)
|
|
|
|
if !ok {
|
|
|
|
return errors.New("cannot decrypt response")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
decrypted = msg
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2023-09-10 14:24:51 +00:00
|
|
|
decoder, err := smallzstd.NewDecoder(nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer decoder.Close()
|
|
|
|
b, err := decoder.DecodeAll(decrypted, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-09-14 19:49:39 +00:00
|
|
|
if debugMap() {
|
2020-09-15 16:54:52 +00:00
|
|
|
var buf bytes.Buffer
|
|
|
|
json.Indent(&buf, b, "", " ")
|
|
|
|
log.Printf("MapResponse: %s", buf.Bytes())
|
|
|
|
}
|
2020-11-12 21:31:29 +00:00
|
|
|
|
|
|
|
if bytes.Contains(b, jsonEscapedZero) {
|
|
|
|
log.Printf("[unexpected] zero byte in controlclient.Direct.decodeMsg into %T: %q", v, b)
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
if err := json.Unmarshal(b, v); err != nil {
|
|
|
|
return fmt.Errorf("response: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2022-03-16 23:27:57 +00:00
|
|
|
func decodeMsg(msg []byte, v any, serverKey key.MachinePublic, machinePrivKey key.MachinePrivate) error {
|
2021-09-03 20:17:46 +00:00
|
|
|
decrypted, ok := machinePrivKey.OpenFrom(serverKey, msg)
|
|
|
|
if !ok {
|
|
|
|
return errors.New("cannot decrypt response")
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-11-12 21:31:29 +00:00
|
|
|
if bytes.Contains(decrypted, jsonEscapedZero) {
|
|
|
|
log.Printf("[unexpected] zero byte in controlclient decodeMsg into %T: %q", v, decrypted)
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
if err := json.Unmarshal(decrypted, v); err != nil {
|
|
|
|
return fmt.Errorf("response: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-03-08 18:53:19 +00:00
|
|
|
// encode JSON encodes v. If serverNoiseKey is not specified, it uses the serverKey and mkey to
|
|
|
|
// seal the message into a NaCl-crypto-box.
|
2022-03-16 23:27:57 +00:00
|
|
|
func encode(v any, serverKey, serverNoiseKey key.MachinePublic, mkey key.MachinePrivate) ([]byte, error) {
|
2020-02-05 22:16:58 +00:00
|
|
|
b, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-09-14 19:49:39 +00:00
|
|
|
if debugMap() {
|
2021-03-29 19:42:43 +00:00
|
|
|
if _, ok := v.(*tailcfg.MapRequest); ok {
|
2020-03-04 06:21:56 +00:00
|
|
|
log.Printf("MapRequest: %s", b)
|
|
|
|
}
|
|
|
|
}
|
2022-03-08 18:53:19 +00:00
|
|
|
if !serverNoiseKey.IsZero() {
|
|
|
|
return b, nil
|
|
|
|
}
|
2021-09-03 20:17:46 +00:00
|
|
|
return mkey.SealTo(serverKey, b), nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2022-03-07 18:55:02 +00:00
|
|
|
func loadServerPubKeys(ctx context.Context, httpc *http.Client, serverURL string) (*tailcfg.OverTLSPublicKeyResponse, error) {
|
|
|
|
keyURL := fmt.Sprintf("%v/key?v=%d", serverURL, tailcfg.CurrentCapabilityVersion)
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "GET", keyURL, nil)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-03-07 18:55:02 +00:00
|
|
|
return nil, fmt.Errorf("create control key request: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
res, err := httpc.Do(req)
|
|
|
|
if err != nil {
|
2022-03-07 18:55:02 +00:00
|
|
|
return nil, fmt.Errorf("fetch control key: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
2022-09-15 12:06:59 +00:00
|
|
|
b, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-03-07 18:55:02 +00:00
|
|
|
return nil, fmt.Errorf("fetch control key response: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
if res.StatusCode != 200 {
|
2022-03-07 18:55:02 +00:00
|
|
|
return nil, fmt.Errorf("fetch control key: %d", res.StatusCode)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-03-07 18:55:02 +00:00
|
|
|
var out tailcfg.OverTLSPublicKeyResponse
|
|
|
|
jsonErr := json.Unmarshal(b, &out)
|
|
|
|
if jsonErr == nil {
|
|
|
|
return &out, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Some old control servers might not be updated to send the new format.
|
|
|
|
// Accept the old pre-JSON format too.
|
|
|
|
out = tailcfg.OverTLSPublicKeyResponse{}
|
2021-09-03 20:17:46 +00:00
|
|
|
k, err := key.ParseMachinePublicUntyped(mem.B(b))
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-03-07 18:55:02 +00:00
|
|
|
return nil, multierr.New(jsonErr, err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-03-07 18:55:02 +00:00
|
|
|
out.LegacyPublicKey = k
|
|
|
|
return &out, nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-06-28 18:53:37 +00:00
|
|
|
|
2022-08-09 17:16:34 +00:00
|
|
|
// DevKnob contains temporary internal-only debug knobs.
|
2020-06-28 18:53:37 +00:00
|
|
|
// They're unexported to not draw attention to them.
|
2022-08-09 17:16:34 +00:00
|
|
|
var DevKnob = initDevKnob()
|
2020-06-28 18:53:37 +00:00
|
|
|
|
2022-08-09 17:16:34 +00:00
|
|
|
type devKnobs struct {
|
2022-09-14 19:49:39 +00:00
|
|
|
DumpNetMaps func() bool
|
|
|
|
ForceProxyDNS func() bool
|
|
|
|
StripEndpoints func() bool // strip endpoints from control (only use disco messages)
|
|
|
|
StripCaps func() bool // strip all local node's control-provided capabilities
|
2020-06-28 18:53:37 +00:00
|
|
|
}
|
|
|
|
|
2022-08-09 17:16:34 +00:00
|
|
|
func initDevKnob() devKnobs {
|
|
|
|
return devKnobs{
|
2022-09-14 19:49:39 +00:00
|
|
|
DumpNetMaps: envknob.RegisterBool("TS_DEBUG_NETMAP"),
|
|
|
|
ForceProxyDNS: envknob.RegisterBool("TS_DEBUG_PROXY_DNS"),
|
|
|
|
StripEndpoints: envknob.RegisterBool("TS_DEBUG_STRIP_ENDPOINTS"),
|
|
|
|
StripCaps: envknob.RegisterBool("TS_DEBUG_STRIP_CAPS"),
|
2020-06-28 18:53:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-04 23:29:44 +00:00
|
|
|
var clock tstime.Clock = tstime.StdClock{}
|
2021-04-15 23:03:59 +00:00
|
|
|
|
2020-11-04 21:48:50 +00:00
|
|
|
// ipForwardingBroken reports whether the system's IP forwarding is disabled
|
|
|
|
// and will definitely not work for the routes provided.
|
|
|
|
//
|
|
|
|
// It should not return false positives.
|
2021-03-31 18:55:21 +00:00
|
|
|
//
|
2022-03-28 17:24:11 +00:00
|
|
|
// TODO(bradfitz): Change controlclient.Options.SkipIPForwardingCheck into a
|
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([]netip.Prefix) error signature instead.
|
|
|
|
func ipForwardingBroken(routes []netip.Prefix, state *interfaces.State) bool {
|
2022-03-28 17:24:11 +00:00
|
|
|
warn, err := netutil.CheckIPForwarding(routes, state)
|
|
|
|
if err != nil {
|
|
|
|
// Oh well, we tried. This is just for debugging.
|
|
|
|
// We don't want false positives.
|
|
|
|
// TODO: maybe we want a different warning for inability to check?
|
2020-11-04 21:48:50 +00:00
|
|
|
return false
|
|
|
|
}
|
2022-03-28 17:24:11 +00:00
|
|
|
return warn != nil
|
2020-11-04 21:48:50 +00:00
|
|
|
}
|
2021-03-05 04:54:44 +00:00
|
|
|
|
2021-06-15 19:28:34 +00:00
|
|
|
// isUniquePingRequest reports whether pr contains a new PingRequest.URL
|
|
|
|
// not already handled, noting its value when returning true.
|
|
|
|
func (c *Direct) isUniquePingRequest(pr *tailcfg.PingRequest) bool {
|
|
|
|
if pr == nil || pr.URL == "" {
|
|
|
|
// Bogus.
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
if pr.URL == c.lastPingURL {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
c.lastPingURL = pr.URL
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-08-10 21:52:02 +00:00
|
|
|
func (c *Direct) answerPing(pr *tailcfg.PingRequest) {
|
|
|
|
httpc := c.httpc
|
2022-08-27 19:55:41 +00:00
|
|
|
useNoise := pr.URLIsNoise || pr.Types == "c2n" && c.noiseConfigured()
|
|
|
|
if useNoise {
|
2022-08-10 21:52:02 +00:00
|
|
|
nc, err := c.getNoiseClient()
|
|
|
|
if err != nil {
|
|
|
|
c.logf("failed to get noise client for ping request: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
httpc = nc.Client
|
|
|
|
}
|
2021-03-05 04:54:44 +00:00
|
|
|
if pr.URL == "" {
|
2022-08-10 21:52:02 +00:00
|
|
|
c.logf("invalid PingRequest with no URL")
|
2021-03-05 04:54:44 +00:00
|
|
|
return
|
|
|
|
}
|
2022-08-27 19:55:41 +00:00
|
|
|
switch pr.Types {
|
|
|
|
case "":
|
2022-08-10 21:52:02 +00:00
|
|
|
answerHeadPing(c.logf, httpc, pr)
|
2022-04-15 16:00:27 +00:00
|
|
|
return
|
2022-08-27 19:55:41 +00:00
|
|
|
case "c2n":
|
|
|
|
if !useNoise && !envknob.Bool("TS_DEBUG_PERMIT_HTTP_C2N") {
|
|
|
|
c.logf("refusing to answer c2n ping without noise")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
answerC2NPing(c.logf, c.c2nHandler, httpc, pr)
|
|
|
|
return
|
2022-04-15 16:00:27 +00:00
|
|
|
}
|
|
|
|
for _, t := range strings.Split(pr.Types, ",") {
|
2022-04-22 01:49:01 +00:00
|
|
|
switch pt := tailcfg.PingType(t); pt {
|
2022-06-06 20:07:14 +00:00
|
|
|
case tailcfg.PingTSMP, tailcfg.PingDisco, tailcfg.PingICMP, tailcfg.PingPeerAPI:
|
2022-08-10 21:52:02 +00:00
|
|
|
go doPingerPing(c.logf, httpc, pr, c.pinger, pt)
|
2022-04-15 16:00:27 +00:00
|
|
|
default:
|
2022-08-10 21:52:02 +00:00
|
|
|
c.logf("unsupported ping request type: %q", t)
|
2022-04-15 16:00:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func answerHeadPing(logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest) {
|
2021-03-05 04:54:44 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "HEAD", pr.URL, nil)
|
|
|
|
if err != nil {
|
2022-04-15 16:00:27 +00:00
|
|
|
logf("answerHeadPing: NewRequestWithContext: %v", err)
|
2021-03-05 04:54:44 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if pr.Log {
|
2022-04-15 16:00:27 +00:00
|
|
|
logf("answerHeadPing: sending HEAD ping to %v ...", pr.URL)
|
2021-03-05 04:54:44 +00:00
|
|
|
}
|
2023-08-04 23:29:44 +00:00
|
|
|
t0 := clock.Now()
|
2021-03-05 04:54:44 +00:00
|
|
|
_, err = c.Do(req)
|
2023-08-04 23:29:44 +00:00
|
|
|
d := clock.Since(t0).Round(time.Millisecond)
|
2021-03-05 04:54:44 +00:00
|
|
|
if err != nil {
|
2022-04-15 16:00:27 +00:00
|
|
|
logf("answerHeadPing error: %v to %v (after %v)", err, pr.URL, d)
|
2021-03-05 04:54:44 +00:00
|
|
|
} else if pr.Log {
|
2022-04-15 16:00:27 +00:00
|
|
|
logf("answerHeadPing complete to %v (after %v)", pr.URL, d)
|
2021-03-05 04:54:44 +00:00
|
|
|
}
|
|
|
|
}
|
2021-04-21 21:17:21 +00:00
|
|
|
|
2022-08-27 19:55:41 +00:00
|
|
|
func answerC2NPing(logf logger.Logf, c2nHandler http.Handler, c *http.Client, pr *tailcfg.PingRequest) {
|
|
|
|
if c2nHandler == nil {
|
|
|
|
logf("answerC2NPing: c2nHandler not defined")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
hreq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(pr.Payload)))
|
|
|
|
if err != nil {
|
|
|
|
logf("answerC2NPing: ReadRequest: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if pr.Log {
|
|
|
|
logf("answerC2NPing: got c2n request for %v ...", hreq.RequestURI)
|
|
|
|
}
|
|
|
|
handlerTimeout := time.Minute
|
|
|
|
if v := hreq.Header.Get("C2n-Handler-Timeout"); v != "" {
|
|
|
|
handlerTimeout, _ = time.ParseDuration(v)
|
|
|
|
}
|
|
|
|
handlerCtx, cancel := context.WithTimeout(context.Background(), handlerTimeout)
|
|
|
|
defer cancel()
|
|
|
|
hreq = hreq.WithContext(handlerCtx)
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
c2nHandler.ServeHTTP(rec, hreq)
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
c2nResBuf := new(bytes.Buffer)
|
|
|
|
rec.Result().Write(c2nResBuf)
|
|
|
|
|
|
|
|
replyCtx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(replyCtx, "POST", pr.URL, c2nResBuf)
|
|
|
|
if err != nil {
|
|
|
|
logf("answerC2NPing: NewRequestWithContext: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if pr.Log {
|
|
|
|
logf("answerC2NPing: sending POST ping to %v ...", pr.URL)
|
|
|
|
}
|
2023-08-04 23:29:44 +00:00
|
|
|
t0 := clock.Now()
|
2022-08-27 19:55:41 +00:00
|
|
|
_, err = c.Do(req)
|
|
|
|
d := time.Since(t0).Round(time.Millisecond)
|
|
|
|
if err != nil {
|
|
|
|
logf("answerC2NPing error: %v to %v (after %v)", err, pr.URL, d)
|
|
|
|
} else if pr.Log {
|
|
|
|
logf("answerC2NPing complete to %v (after %v)", pr.URL, d)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-21 02:52:52 +00:00
|
|
|
// sleepAsRequest implements the sleep for a tailcfg.Debug message requesting
|
|
|
|
// that the client sleep. The complication is that while we're sleeping (if for
|
|
|
|
// a long time), we need to periodically reset the watchdog timer before it
|
|
|
|
// expires.
|
2023-11-05 18:41:13 +00:00
|
|
|
func sleepAsRequested(ctx context.Context, logf logger.Logf, d time.Duration, clock tstime.Clock) error {
|
2021-04-21 21:17:21 +00:00
|
|
|
const maxSleep = 5 * time.Minute
|
|
|
|
if d > maxSleep {
|
|
|
|
logf("sleeping for %v, capped from server-requested %v ...", maxSleep, d)
|
|
|
|
d = maxSleep
|
|
|
|
} else {
|
|
|
|
logf("sleeping for server-requested %v ...", d)
|
|
|
|
}
|
|
|
|
|
2023-08-04 23:29:44 +00:00
|
|
|
timer, timerChannel := clock.NewTimer(d)
|
2021-04-21 21:17:21 +00:00
|
|
|
defer timer.Stop()
|
2023-11-05 18:41:13 +00:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case <-timerChannel:
|
|
|
|
return nil
|
2021-04-21 21:17:21 +00:00
|
|
|
}
|
|
|
|
}
|
2021-06-07 23:03:16 +00:00
|
|
|
|
2022-03-07 23:32:53 +00:00
|
|
|
// getNoiseClient returns the noise client, creating one if one doesn't exist.
|
2022-11-03 07:17:16 +00:00
|
|
|
func (c *Direct) getNoiseClient() (*NoiseClient, error) {
|
2022-03-07 23:32:53 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
serverNoiseKey := c.serverNoiseKey
|
|
|
|
nc := c.noiseClient
|
|
|
|
c.mu.Unlock()
|
|
|
|
if serverNoiseKey.IsZero() {
|
|
|
|
return nil, errors.New("zero serverNoiseKey")
|
|
|
|
}
|
|
|
|
if nc != nil {
|
|
|
|
return nc, nil
|
|
|
|
}
|
2022-09-23 17:06:55 +00:00
|
|
|
var dp func() *tailcfg.ControlDialPlan
|
|
|
|
if c.dialPlan != nil {
|
|
|
|
dp = c.dialPlan.Load
|
|
|
|
}
|
2022-11-03 07:17:16 +00:00
|
|
|
nc, err, _ := c.sfGroup.Do(struct{}{}, func() (*NoiseClient, error) {
|
2022-03-07 23:32:53 +00:00
|
|
|
k, err := c.getMachinePrivKey()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-09-23 18:21:47 +00:00
|
|
|
c.logf("[v1] creating new noise client")
|
2023-04-30 03:25:37 +00:00
|
|
|
nc, err := NewNoiseClient(NoiseOpts{
|
|
|
|
PrivKey: k,
|
|
|
|
ServerPubKey: serverNoiseKey,
|
|
|
|
ServerURL: c.serverURL,
|
|
|
|
Dialer: c.dialer,
|
|
|
|
DNSCache: c.dnsCache,
|
|
|
|
Logf: c.logf,
|
|
|
|
NetMon: c.netMon,
|
|
|
|
DialPlan: dp,
|
|
|
|
})
|
2022-03-07 23:32:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
c.noiseClient = nc
|
|
|
|
return nc, nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-06-17 17:09:23 +00:00
|
|
|
return nc, nil
|
2022-03-07 23:32:53 +00:00
|
|
|
}
|
|
|
|
|
2022-03-08 00:16:15 +00:00
|
|
|
// setDNSNoise sends the SetDNSRequest request to the control plane server over Noise,
|
|
|
|
// requesting a DNS record be created or updated.
|
|
|
|
func (c *Direct) setDNSNoise(ctx context.Context, req *tailcfg.SetDNSRequest) error {
|
|
|
|
newReq := *req
|
|
|
|
newReq.Version = tailcfg.CurrentCapabilityVersion
|
2022-09-23 20:09:33 +00:00
|
|
|
nc, err := c.getNoiseClient()
|
2022-03-08 00:16:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-09-25 23:17:31 +00:00
|
|
|
res, err := nc.post(ctx, "/machine/set-dns", &newReq)
|
2022-03-08 00:16:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
if res.StatusCode != 200 {
|
2022-09-15 12:06:59 +00:00
|
|
|
msg, _ := io.ReadAll(res.Body)
|
2022-03-08 00:16:15 +00:00
|
|
|
return fmt.Errorf("set-dns response: %v, %.200s", res.Status, strings.TrimSpace(string(msg)))
|
|
|
|
}
|
|
|
|
var setDNSRes tailcfg.SetDNSResponse
|
|
|
|
if err := json.NewDecoder(res.Body).Decode(&setDNSRes); err != nil {
|
|
|
|
c.logf("error decoding SetDNSResponse: %v", err)
|
|
|
|
return fmt.Errorf("set-dns-response: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// noiseConfigured reports whether the client can communicate with Control
|
|
|
|
// over Noise.
|
|
|
|
func (c *Direct) noiseConfigured() bool {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
return !c.serverNoiseKey.IsZero()
|
|
|
|
}
|
|
|
|
|
2021-06-07 23:03:16 +00:00
|
|
|
// SetDNS sends the SetDNSRequest request to the control plane server,
|
|
|
|
// requesting a DNS record be created or updated.
|
2021-11-16 16:34:25 +00:00
|
|
|
func (c *Direct) SetDNS(ctx context.Context, req *tailcfg.SetDNSRequest) (err error) {
|
|
|
|
metricSetDNS.Add(1)
|
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
|
|
|
metricSetDNSError.Add(1)
|
|
|
|
}
|
|
|
|
}()
|
2022-03-08 00:16:15 +00:00
|
|
|
if c.noiseConfigured() {
|
|
|
|
return c.setDNSNoise(ctx, req)
|
|
|
|
}
|
2021-06-07 23:03:16 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
serverKey := c.serverKey
|
|
|
|
c.mu.Unlock()
|
|
|
|
|
|
|
|
if serverKey.IsZero() {
|
|
|
|
return errors.New("zero serverKey")
|
|
|
|
}
|
|
|
|
machinePrivKey, err := c.getMachinePrivKey()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("getMachinePrivKey: %w", err)
|
|
|
|
}
|
|
|
|
if machinePrivKey.IsZero() {
|
|
|
|
return errors.New("getMachinePrivKey returned zero key")
|
|
|
|
}
|
|
|
|
|
2022-03-08 18:53:19 +00:00
|
|
|
// TODO(maisem): dedupe this codepath from SetDNSNoise.
|
|
|
|
var serverNoiseKey key.MachinePublic
|
|
|
|
bodyData, err := encode(req, serverKey, serverNoiseKey, machinePrivKey)
|
2021-06-07 23:03:16 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
body := bytes.NewReader(bodyData)
|
|
|
|
|
2021-09-03 20:17:46 +00:00
|
|
|
u := fmt.Sprintf("%s/machine/%s/set-dns", c.serverURL, machinePrivKey.Public().UntypedHexString())
|
2021-06-07 23:03:16 +00:00
|
|
|
hreq, err := http.NewRequestWithContext(ctx, "POST", u, body)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
res, err := c.httpc.Do(hreq)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
if res.StatusCode != 200 {
|
2022-09-15 12:06:59 +00:00
|
|
|
msg, _ := io.ReadAll(res.Body)
|
2021-06-16 22:55:02 +00:00
|
|
|
return fmt.Errorf("set-dns response: %v, %.200s", res.Status, strings.TrimSpace(string(msg)))
|
2021-06-07 23:03:16 +00:00
|
|
|
}
|
2022-03-07 20:37:06 +00:00
|
|
|
var setDNSRes tailcfg.SetDNSResponse
|
2022-03-08 18:53:19 +00:00
|
|
|
if err := decode(res, &setDNSRes, serverKey, serverNoiseKey, machinePrivKey); err != nil {
|
2021-06-07 23:03:16 +00:00
|
|
|
c.logf("error decoding SetDNSResponse with server key %s and machine key %s: %v", serverKey, machinePrivKey.Public(), err)
|
2022-03-08 00:16:15 +00:00
|
|
|
return fmt.Errorf("set-dns-response: %w", err)
|
2021-06-07 23:03:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2021-07-16 14:51:54 +00:00
|
|
|
|
2022-03-10 18:28:42 +00:00
|
|
|
func (c *Direct) DoNoiseRequest(req *http.Request) (*http.Response, error) {
|
|
|
|
nc, err := c.getNoiseClient()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return nc.Do(req)
|
|
|
|
}
|
|
|
|
|
2022-11-02 03:37:13 +00:00
|
|
|
// GetSingleUseNoiseRoundTripper returns a RoundTripper that can be only be used
|
|
|
|
// once (and must be used once) to make a single HTTP request over the noise
|
|
|
|
// channel to the coordination server.
|
|
|
|
//
|
|
|
|
// In addition to the RoundTripper, it returns the HTTP/2 channel's early noise
|
|
|
|
// payload, if any.
|
|
|
|
func (c *Direct) GetSingleUseNoiseRoundTripper(ctx context.Context) (http.RoundTripper, *tailcfg.EarlyNoise, error) {
|
|
|
|
nc, err := c.getNoiseClient()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2022-11-03 07:17:16 +00:00
|
|
|
return nc.GetSingleUseRoundTripper(ctx)
|
2022-11-02 03:37:13 +00:00
|
|
|
}
|
|
|
|
|
2022-04-15 16:00:27 +00:00
|
|
|
// doPingerPing sends a Ping to pr.IP using pinger, and sends an http request back to
|
|
|
|
// pr.URL with ping response data.
|
2022-04-22 01:49:01 +00:00
|
|
|
func doPingerPing(logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest, pinger Pinger, pingType tailcfg.PingType) {
|
2022-07-25 03:08:42 +00:00
|
|
|
if pr.URL == "" || !pr.IP.IsValid() || pinger == nil {
|
2022-04-15 16:00:27 +00:00
|
|
|
logf("invalid ping request: missing url, ip or pinger")
|
|
|
|
return
|
2021-07-16 14:51:54 +00:00
|
|
|
}
|
2023-08-04 23:29:44 +00:00
|
|
|
start := clock.Now()
|
2022-06-06 20:07:14 +00:00
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2023-08-08 12:11:28 +00:00
|
|
|
res, err := pinger.Ping(ctx, pr.IP, pingType, 0)
|
2022-06-06 20:07:14 +00:00
|
|
|
if err != nil {
|
|
|
|
d := time.Since(start).Round(time.Millisecond)
|
|
|
|
logf("doPingerPing: ping error of type %q to %v after %v: %v", pingType, pr.IP, d, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
postPingResult(start, logf, c, pr, res.ToPingResponse(pingType))
|
2021-07-16 14:51:54 +00:00
|
|
|
}
|
|
|
|
|
2022-04-15 16:00:27 +00:00
|
|
|
func postPingResult(start time.Time, logf logger.Logf, c *http.Client, pr *tailcfg.PingRequest, res *tailcfg.PingResponse) error {
|
|
|
|
duration := time.Since(start)
|
2021-07-16 14:51:54 +00:00
|
|
|
if pr.Log {
|
2022-04-15 16:00:27 +00:00
|
|
|
if res.Err == "" {
|
|
|
|
logf("ping to %v completed in %v. pinger.Ping took %v seconds", pr.IP, res.LatencySeconds, duration)
|
|
|
|
} else {
|
|
|
|
logf("ping to %v failed after %v: %v", pr.IP, duration, res.Err)
|
|
|
|
}
|
2021-07-16 14:51:54 +00:00
|
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
jsonPingRes, err := json.Marshal(res)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Send the results of the Ping, back to control URL.
|
2022-04-15 16:00:27 +00:00
|
|
|
req, err := http.NewRequestWithContext(ctx, "POST", pr.URL, bytes.NewReader(jsonPingRes))
|
2021-07-16 14:51:54 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("http.NewRequestWithContext(%q): %w", pr.URL, err)
|
|
|
|
}
|
|
|
|
if pr.Log {
|
2022-04-15 16:00:27 +00:00
|
|
|
logf("postPingResult: sending ping results to %v ...", pr.URL)
|
2021-07-16 14:51:54 +00:00
|
|
|
}
|
2023-08-04 23:29:44 +00:00
|
|
|
t0 := clock.Now()
|
2021-07-16 14:51:54 +00:00
|
|
|
_, err = c.Do(req)
|
|
|
|
d := time.Since(t0).Round(time.Millisecond)
|
|
|
|
if err != nil {
|
2022-04-15 16:00:27 +00:00
|
|
|
return fmt.Errorf("postPingResult error: %w to %v (after %v)", err, pr.URL, d)
|
2021-07-16 14:51:54 +00:00
|
|
|
} else if pr.Log {
|
2022-04-15 16:00:27 +00:00
|
|
|
logf("postPingResult complete to %v (after %v)", pr.URL, d)
|
2021-07-16 14:51:54 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2021-11-16 16:34:25 +00:00
|
|
|
|
2022-06-21 14:44:11 +00:00
|
|
|
// ReportHealthChange reports to the control plane a change to this node's
|
|
|
|
// health.
|
|
|
|
func (c *Direct) ReportHealthChange(sys health.Subsystem, sysErr error) {
|
|
|
|
if sys == health.SysOverall {
|
|
|
|
// We don't report these. These include things like the network is down
|
|
|
|
// (in which case we can't report anyway) or the user wanted things
|
|
|
|
// stopped, as opposed to the more unexpected failure types in the other
|
|
|
|
// subsystems.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
np, err := c.getNoiseClient()
|
|
|
|
if err != nil {
|
|
|
|
// Don't report errors to control if the server doesn't support noise.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
req := &tailcfg.HealthChangeRequest{
|
|
|
|
Subsys: string(sys),
|
|
|
|
}
|
|
|
|
if sysErr != nil {
|
|
|
|
req.Error = sysErr.Error()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Best effort, no logging:
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
res, err := np.post(ctx, "/machine/update-health", req)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
res.Body.Close()
|
|
|
|
}
|
|
|
|
|
2023-03-02 21:24:26 +00:00
|
|
|
// decodeWrappedAuthkey separates wrapping information from an authkey, if any.
|
|
|
|
// In all cases the authkey is returned, sans wrapping information if any.
|
|
|
|
//
|
|
|
|
// If the authkey is wrapped, isWrapped returns true, along with the wrapping signature
|
|
|
|
// and private key.
|
|
|
|
func decodeWrappedAuthkey(key string, logf logger.Logf) (authKey string, isWrapped bool, sig *tka.NodeKeySignature, priv ed25519.PrivateKey) {
|
|
|
|
authKey, suffix, found := strings.Cut(key, "--TL")
|
|
|
|
if !found {
|
|
|
|
return key, false, nil, nil
|
|
|
|
}
|
|
|
|
sigBytes, privBytes, found := strings.Cut(suffix, "-")
|
|
|
|
if !found {
|
|
|
|
logf("decoding wrapped auth-key: did not find delimiter")
|
|
|
|
return key, false, nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
rawSig, err := base64.RawStdEncoding.DecodeString(sigBytes)
|
|
|
|
if err != nil {
|
|
|
|
logf("decoding wrapped auth-key: signature decode: %v", err)
|
|
|
|
return key, false, nil, nil
|
|
|
|
}
|
|
|
|
rawPriv, err := base64.RawStdEncoding.DecodeString(privBytes)
|
|
|
|
if err != nil {
|
|
|
|
logf("decoding wrapped auth-key: priv decode: %v", err)
|
|
|
|
return key, false, nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
sig = new(tka.NodeKeySignature)
|
|
|
|
if err := sig.Unserialize([]byte(rawSig)); err != nil {
|
|
|
|
logf("decoding wrapped auth-key: signature: %v", err)
|
|
|
|
return key, false, nil, nil
|
|
|
|
}
|
|
|
|
priv = ed25519.PrivateKey(rawPriv)
|
|
|
|
|
|
|
|
return authKey, true, sig, priv
|
|
|
|
}
|
|
|
|
|
2021-11-16 16:34:25 +00:00
|
|
|
var (
|
|
|
|
metricMapRequestsActive = clientmetric.NewGauge("controlclient_map_requests_active")
|
|
|
|
|
|
|
|
metricMapRequests = clientmetric.NewCounter("controlclient_map_requests")
|
|
|
|
metricMapRequestsLite = clientmetric.NewCounter("controlclient_map_requests_lite")
|
|
|
|
metricMapRequestsPoll = clientmetric.NewCounter("controlclient_map_requests_poll")
|
|
|
|
|
|
|
|
metricMapResponseMessages = clientmetric.NewCounter("controlclient_map_response_message") // any message type
|
|
|
|
metricMapResponsePings = clientmetric.NewCounter("controlclient_map_response_ping")
|
|
|
|
metricMapResponseKeepAlives = clientmetric.NewCounter("controlclient_map_response_keepalive")
|
|
|
|
metricMapResponseMap = clientmetric.NewCounter("controlclient_map_response_map") // any non-keepalive map response
|
|
|
|
metricMapResponseMapDelta = clientmetric.NewCounter("controlclient_map_response_map_delta") // 2nd+ non-keepalive map response
|
|
|
|
|
|
|
|
metricSetDNS = clientmetric.NewCounter("controlclient_setdns")
|
|
|
|
metricSetDNSError = clientmetric.NewCounter("controlclient_setdns_error")
|
|
|
|
)
|