2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2021-04-30 04:52:31 +00:00
|
|
|
|
|
|
|
// Package testcontrol contains a minimal control plane server for testing purposes.
|
|
|
|
package testcontrol
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2021-06-10 22:12:25 +00:00
|
|
|
"context"
|
2021-04-30 04:52:31 +00:00
|
|
|
"encoding/binary"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"math/rand"
|
|
|
|
"net/http"
|
2021-06-18 17:09:16 +00:00
|
|
|
"net/http/httptest"
|
2022-07-26 03:55:44 +00:00
|
|
|
"net/netip"
|
2021-05-12 04:57:25 +00:00
|
|
|
"net/url"
|
2023-08-17 05:09:53 +00:00
|
|
|
"slices"
|
2021-05-12 21:43:43 +00:00
|
|
|
"sort"
|
2021-04-30 04:52:31 +00:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/klauspost/compress/zstd"
|
2021-09-03 20:17:46 +00:00
|
|
|
"go4.org/mem"
|
2022-07-25 03:08:42 +00:00
|
|
|
"tailscale.com/net/netaddr"
|
2021-07-13 17:10:08 +00:00
|
|
|
"tailscale.com/net/tsaddr"
|
2021-04-30 04:52:31 +00:00
|
|
|
"tailscale.com/smallzstd"
|
|
|
|
"tailscale.com/tailcfg"
|
2021-08-18 21:20:40 +00:00
|
|
|
"tailscale.com/types/key"
|
2021-04-30 04:52:31 +00:00
|
|
|
"tailscale.com/types/logger"
|
2023-04-13 17:12:31 +00:00
|
|
|
"tailscale.com/types/ptr"
|
2023-09-05 16:02:40 +00:00
|
|
|
"tailscale.com/util/rands"
|
2023-09-12 18:43:34 +00:00
|
|
|
"tailscale.com/util/set"
|
2021-04-30 04:52:31 +00:00
|
|
|
)
|
|
|
|
|
2021-08-30 13:54:35 +00:00
|
|
|
const msgLimit = 1 << 20 // encrypted message length limit
|
|
|
|
|
2021-04-30 04:52:31 +00:00
|
|
|
// Server is a control plane server. Its zero value is ready for use.
|
|
|
|
// Everything is stored in-memory in one tailnet.
|
|
|
|
type Server struct {
|
2023-03-09 20:52:18 +00:00
|
|
|
Logf logger.Logf // nil means to use the log package
|
|
|
|
DERPMap *tailcfg.DERPMap // nil means to use prod DERP map
|
|
|
|
RequireAuth bool
|
|
|
|
Verbose bool
|
|
|
|
DNSConfig *tailcfg.DNSConfig // nil means no DNS config
|
|
|
|
MagicDNSDomain string
|
2021-04-30 04:52:31 +00:00
|
|
|
|
2021-06-18 17:09:16 +00:00
|
|
|
// ExplicitBaseURL or HTTPTestServer must be set.
|
|
|
|
ExplicitBaseURL string // e.g. "http://127.0.0.1:1234" with no trailing URL
|
|
|
|
HTTPTestServer *httptest.Server // if non-nil, used to get BaseURL
|
|
|
|
|
2021-04-30 04:52:31 +00:00
|
|
|
initMuxOnce sync.Once
|
|
|
|
mux *http.ServeMux
|
|
|
|
|
2022-03-07 18:55:02 +00:00
|
|
|
mu sync.Mutex
|
|
|
|
inServeMap int
|
|
|
|
cond *sync.Cond // lazily initialized by condLocked
|
|
|
|
pubKey key.MachinePublic
|
|
|
|
privKey key.ControlPrivate // not strictly needed vs. MachinePrivate, but handy to test type interactions.
|
|
|
|
|
2023-03-03 00:00:19 +00:00
|
|
|
// masquerades is the set of masquerades that should be applied to
|
|
|
|
// MapResponses sent to clients. It is keyed by the requesting nodes
|
|
|
|
// public key, and then the peer node's public key. The value is the
|
|
|
|
// masquerade address to use for that peer.
|
|
|
|
masquerades map[key.NodePublic]map[key.NodePublic]netip.Addr // node => peer => SelfNodeV4MasqAddrForThisPeer IP
|
|
|
|
|
2023-09-12 18:43:34 +00:00
|
|
|
// suppressAutoMapResponses is the set of nodes that should not be sent
|
|
|
|
// automatic map responses from serveMap. (They should only get manually sent ones)
|
|
|
|
suppressAutoMapResponses set.Set[key.NodePublic]
|
|
|
|
|
2022-03-07 18:55:02 +00:00
|
|
|
noisePubKey key.MachinePublic
|
|
|
|
noisePrivKey key.ControlPrivate // not strictly needed vs. MachinePrivate, but handy to test type interactions.
|
|
|
|
|
2021-10-30 00:49:16 +00:00
|
|
|
nodes map[key.NodePublic]*tailcfg.Node
|
|
|
|
users map[key.NodePublic]*tailcfg.User
|
|
|
|
logins map[key.NodePublic]*tailcfg.Login
|
2021-05-12 04:57:25 +00:00
|
|
|
updates map[tailcfg.NodeID]chan updateType
|
|
|
|
authPath map[string]*AuthPath
|
2021-10-30 00:49:16 +00:00
|
|
|
nodeKeyAuthed map[key.NodePublic]bool // key => true once authenticated
|
2023-09-12 18:43:34 +00:00
|
|
|
msgToSend map[key.NodePublic]any // value is *tailcfg.PingRequest or entire *tailcfg.MapResponse
|
|
|
|
allExpired bool // All nodes will be told their node key is expired.
|
2021-05-12 04:57:25 +00:00
|
|
|
}
|
|
|
|
|
2021-06-18 17:09:16 +00:00
|
|
|
// BaseURL returns the server's base URL, without trailing slash.
|
|
|
|
func (s *Server) BaseURL() string {
|
|
|
|
if e := s.ExplicitBaseURL; e != "" {
|
|
|
|
return e
|
|
|
|
}
|
|
|
|
if hs := s.HTTPTestServer; hs != nil {
|
|
|
|
if hs.URL != "" {
|
|
|
|
return hs.URL
|
|
|
|
}
|
|
|
|
panic("Server.HTTPTestServer not started")
|
|
|
|
}
|
|
|
|
panic("Server ExplicitBaseURL and HTTPTestServer both unset")
|
|
|
|
}
|
|
|
|
|
2021-05-26 18:10:10 +00:00
|
|
|
// NumNodes returns the number of nodes in the testcontrol server.
|
|
|
|
//
|
|
|
|
// This is useful when connecting a bunch of virtual machines to a testcontrol
|
|
|
|
// server to see how many of them connected successfully.
|
|
|
|
func (s *Server) NumNodes() int {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
|
|
|
|
return len(s.nodes)
|
|
|
|
}
|
|
|
|
|
2021-06-10 22:12:25 +00:00
|
|
|
// condLocked lazily initializes and returns s.cond.
|
|
|
|
// s.mu must be held.
|
|
|
|
func (s *Server) condLocked() *sync.Cond {
|
|
|
|
if s.cond == nil {
|
|
|
|
s.cond = sync.NewCond(&s.mu)
|
|
|
|
}
|
|
|
|
return s.cond
|
|
|
|
}
|
|
|
|
|
|
|
|
// AwaitNodeInMapRequest waits for node k to be stuck in a map poll.
|
|
|
|
// It returns an error if and only if the context is done first.
|
2021-10-30 00:49:16 +00:00
|
|
|
func (s *Server) AwaitNodeInMapRequest(ctx context.Context, k key.NodePublic) error {
|
2021-06-10 22:12:25 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
cond := s.condLocked()
|
|
|
|
|
|
|
|
done := make(chan struct{})
|
|
|
|
defer close(done)
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-done:
|
|
|
|
case <-ctx.Done():
|
|
|
|
cond.Broadcast()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
for {
|
|
|
|
node := s.nodeLocked(k)
|
|
|
|
if node == nil {
|
|
|
|
return errors.New("unknown node key")
|
|
|
|
}
|
|
|
|
if _, ok := s.updates[node.ID]; ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
cond.Wait()
|
|
|
|
if err := ctx.Err(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-12 18:43:34 +00:00
|
|
|
// AddPingRequest sends the ping pr to nodeKeyDst.
|
|
|
|
//
|
|
|
|
// It reports whether the message was enqueued. That is, it reports whether
|
|
|
|
// nodeKeyDst was connected.
|
2021-10-30 00:49:16 +00:00
|
|
|
func (s *Server) AddPingRequest(nodeKeyDst key.NodePublic, pr *tailcfg.PingRequest) bool {
|
2023-09-12 18:43:34 +00:00
|
|
|
return s.addDebugMessage(nodeKeyDst, pr)
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddRawMapResponse delivers the raw MapResponse mr to nodeKeyDst. It's meant
|
|
|
|
// for testing incremental map updates.
|
|
|
|
//
|
|
|
|
// Once AddRawMapResponse has been sent to a node, all future automatic
|
|
|
|
// MapResponses to that node will be suppressed and only explicit MapResponses
|
|
|
|
// injected via AddRawMapResponse will be sent.
|
|
|
|
//
|
|
|
|
// It reports whether the message was enqueued. That is, it reports whether
|
|
|
|
// nodeKeyDst was connected.
|
|
|
|
func (s *Server) AddRawMapResponse(nodeKeyDst key.NodePublic, mr *tailcfg.MapResponse) bool {
|
|
|
|
return s.addDebugMessage(nodeKeyDst, mr)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) addDebugMessage(nodeKeyDst key.NodePublic, msg any) bool {
|
2021-06-02 15:23:24 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2023-09-12 18:43:34 +00:00
|
|
|
if s.msgToSend == nil {
|
|
|
|
s.msgToSend = map[key.NodePublic]any{}
|
2021-06-02 15:23:24 +00:00
|
|
|
}
|
|
|
|
// Now send the update to the channel
|
|
|
|
node := s.nodeLocked(nodeKeyDst)
|
|
|
|
if node == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-09-12 18:43:34 +00:00
|
|
|
if _, ok := msg.(*tailcfg.MapResponse); ok {
|
|
|
|
if s.suppressAutoMapResponses == nil {
|
|
|
|
s.suppressAutoMapResponses = set.Set[key.NodePublic]{}
|
|
|
|
}
|
|
|
|
s.suppressAutoMapResponses.Add(nodeKeyDst)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.msgToSend[nodeKeyDst] = msg
|
2021-06-02 15:23:24 +00:00
|
|
|
nodeID := node.ID
|
|
|
|
oldUpdatesCh := s.updates[nodeID]
|
2021-06-10 22:12:25 +00:00
|
|
|
return sendUpdate(oldUpdatesCh, updateDebugInjection)
|
2021-06-02 15:23:24 +00:00
|
|
|
}
|
|
|
|
|
2021-10-29 00:44:18 +00:00
|
|
|
// Mark the Node key of every node as expired
|
|
|
|
func (s *Server) SetExpireAllNodes(expired bool) {
|
|
|
|
s.mu.Lock()
|
2021-11-11 16:12:45 +00:00
|
|
|
defer s.mu.Unlock()
|
|
|
|
|
2021-10-29 00:44:18 +00:00
|
|
|
s.allExpired = expired
|
|
|
|
|
2021-11-11 16:12:45 +00:00
|
|
|
for _, node := range s.nodes {
|
2021-10-29 00:44:18 +00:00
|
|
|
sendUpdate(s.updates[node.ID], updateSelfChanged)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-12 04:57:25 +00:00
|
|
|
type AuthPath struct {
|
2021-10-30 00:49:16 +00:00
|
|
|
nodeKey key.NodePublic
|
2021-05-12 04:57:25 +00:00
|
|
|
|
|
|
|
closeOnce sync.Once
|
|
|
|
ch chan struct{}
|
|
|
|
success bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ap *AuthPath) completeSuccessfully() {
|
|
|
|
ap.success = true
|
|
|
|
close(ap.ch)
|
|
|
|
}
|
|
|
|
|
|
|
|
// CompleteSuccessfully completes the login path successfully, as if
|
|
|
|
// the user did the whole auth dance.
|
|
|
|
func (ap *AuthPath) CompleteSuccessfully() {
|
|
|
|
ap.closeOnce.Do(ap.completeSuccessfully)
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
|
2022-03-16 23:27:57 +00:00
|
|
|
func (s *Server) logf(format string, a ...any) {
|
2021-04-30 04:52:31 +00:00
|
|
|
if s.Logf != nil {
|
|
|
|
s.Logf(format, a...)
|
|
|
|
} else {
|
|
|
|
log.Printf(format, a...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) initMux() {
|
|
|
|
s.mux = http.NewServeMux()
|
|
|
|
s.mux.HandleFunc("/", s.serveUnhandled)
|
2022-09-20 19:31:49 +00:00
|
|
|
s.mux.HandleFunc("/generate_204", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
|
|
})
|
2021-04-30 04:52:31 +00:00
|
|
|
s.mux.HandleFunc("/key", s.serveKey)
|
|
|
|
s.mux.HandleFunc("/machine/", s.serveMachine)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
s.initMuxOnce.Do(s.initMux)
|
|
|
|
s.mux.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) serveUnhandled(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var got bytes.Buffer
|
|
|
|
r.Write(&got)
|
|
|
|
go panic(fmt.Sprintf("testcontrol.Server received unhandled request: %s", got.Bytes()))
|
|
|
|
}
|
|
|
|
|
2022-03-07 18:55:02 +00:00
|
|
|
func (s *Server) publicKeys() (noiseKey, pubKey key.MachinePublic) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
s.ensureKeyPairLocked()
|
|
|
|
return s.noisePubKey, s.pubKey
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
|
2021-09-03 20:17:46 +00:00
|
|
|
func (s *Server) privateKey() key.ControlPrivate {
|
2021-04-30 04:52:31 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2022-03-07 18:55:02 +00:00
|
|
|
s.ensureKeyPairLocked()
|
|
|
|
return s.privKey
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) ensureKeyPairLocked() {
|
|
|
|
if !s.pubKey.IsZero() {
|
|
|
|
return
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
2022-03-07 18:55:02 +00:00
|
|
|
s.noisePrivKey = key.NewControl()
|
|
|
|
s.noisePubKey = s.noisePrivKey.Public()
|
|
|
|
s.privKey = key.NewControl()
|
|
|
|
s.pubKey = s.privKey.Public()
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) serveKey(w http.ResponseWriter, r *http.Request) {
|
2022-03-08 18:53:19 +00:00
|
|
|
_, legacyKey := s.publicKeys()
|
2022-03-07 18:55:02 +00:00
|
|
|
if r.FormValue("v") == "" {
|
|
|
|
w.Header().Set("Content-Type", "text/plain")
|
|
|
|
io.WriteString(w, legacyKey.UntypedHexString())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
2022-03-08 18:53:19 +00:00
|
|
|
// TODO(maisem/bradfitz): support noise protocol here.
|
2022-03-07 18:55:02 +00:00
|
|
|
json.NewEncoder(w).Encode(&tailcfg.OverTLSPublicKeyResponse{
|
|
|
|
LegacyPublicKey: legacyKey,
|
2022-03-08 18:53:19 +00:00
|
|
|
// PublicKey: noiseKey,
|
2022-03-07 18:55:02 +00:00
|
|
|
})
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) serveMachine(w http.ResponseWriter, r *http.Request) {
|
|
|
|
mkeyStr := strings.TrimPrefix(r.URL.Path, "/machine/")
|
|
|
|
rem := ""
|
|
|
|
if i := strings.IndexByte(mkeyStr, '/'); i != -1 {
|
|
|
|
rem = mkeyStr[i:]
|
|
|
|
mkeyStr = mkeyStr[:i]
|
|
|
|
}
|
|
|
|
|
2022-03-07 18:55:02 +00:00
|
|
|
// TODO(maisem/bradfitz): support noise protocol here.
|
2021-09-03 20:17:46 +00:00
|
|
|
mkey, err := key.ParseMachinePublicUntyped(mem.S(mkeyStr))
|
2021-04-30 04:52:31 +00:00
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "bad machine key hex", 400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if r.Method != "POST" {
|
|
|
|
http.Error(w, "POST required", 400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
switch rem {
|
|
|
|
case "":
|
|
|
|
s.serveRegister(w, r, mkey)
|
|
|
|
case "/map":
|
|
|
|
s.serveMap(w, r, mkey)
|
|
|
|
default:
|
|
|
|
s.serveUnhandled(w, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-03 00:00:19 +00:00
|
|
|
// MasqueradePair is a pair of nodes and the IP address that the
|
|
|
|
// Node masquerades as for the Peer.
|
|
|
|
//
|
|
|
|
// Setting this will have future MapResponses for Node to have
|
|
|
|
// Peer.SelfNodeV4MasqAddrForThisPeer set to NodeMasqueradesAs.
|
|
|
|
// MapResponses for the Peer will now see Node.Addresses as
|
|
|
|
// NodeMasqueradesAs.
|
|
|
|
type MasqueradePair struct {
|
|
|
|
Node key.NodePublic
|
|
|
|
Peer key.NodePublic
|
|
|
|
NodeMasqueradesAs netip.Addr
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetMasqueradeAddresses sets the masquerade addresses for the server.
|
|
|
|
// See MasqueradePair for more details.
|
|
|
|
func (s *Server) SetMasqueradeAddresses(pairs []MasqueradePair) {
|
|
|
|
m := make(map[key.NodePublic]map[key.NodePublic]netip.Addr)
|
|
|
|
for _, p := range pairs {
|
|
|
|
if m[p.Node] == nil {
|
|
|
|
m[p.Node] = make(map[key.NodePublic]netip.Addr)
|
|
|
|
}
|
|
|
|
m[p.Node][p.Peer] = p.NodeMasqueradesAs
|
|
|
|
}
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
s.masquerades = m
|
|
|
|
s.updateLocked("SetMasqueradeAddresses", s.nodeIDsLocked(0))
|
|
|
|
}
|
|
|
|
|
|
|
|
// nodeIDsLocked returns the node IDs of all nodes in the server, except
|
|
|
|
// for the node with the given ID.
|
|
|
|
func (s *Server) nodeIDsLocked(except tailcfg.NodeID) []tailcfg.NodeID {
|
|
|
|
var ids []tailcfg.NodeID
|
|
|
|
for _, n := range s.nodes {
|
|
|
|
if n.ID == except {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
ids = append(ids, n.ID)
|
|
|
|
}
|
|
|
|
return ids
|
|
|
|
}
|
|
|
|
|
2021-04-30 04:52:31 +00:00
|
|
|
// Node returns the node for nodeKey. It's always nil or cloned memory.
|
2021-10-30 00:49:16 +00:00
|
|
|
func (s *Server) Node(nodeKey key.NodePublic) *tailcfg.Node {
|
2021-04-30 04:52:31 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2021-06-04 15:19:23 +00:00
|
|
|
return s.nodeLocked(nodeKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
// nodeLocked returns the node for nodeKey. It's always nil or cloned memory.
|
|
|
|
//
|
|
|
|
// s.mu must be held.
|
2021-10-30 00:49:16 +00:00
|
|
|
func (s *Server) nodeLocked(nodeKey key.NodePublic) *tailcfg.Node {
|
2021-04-30 04:52:31 +00:00
|
|
|
return s.nodes[nodeKey].Clone()
|
|
|
|
}
|
|
|
|
|
2021-08-18 21:20:40 +00:00
|
|
|
// AddFakeNode injects a fake node into the server.
|
|
|
|
func (s *Server) AddFakeNode() {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if s.nodes == nil {
|
2021-10-30 00:49:16 +00:00
|
|
|
s.nodes = make(map[key.NodePublic]*tailcfg.Node)
|
2021-08-18 21:20:40 +00:00
|
|
|
}
|
2021-10-30 00:49:16 +00:00
|
|
|
nk := key.NewNode().Public()
|
2021-09-03 20:17:46 +00:00
|
|
|
mk := key.NewMachine().Public()
|
2021-11-02 21:41:56 +00:00
|
|
|
dk := key.NewDisco().Public()
|
2021-10-30 00:49:16 +00:00
|
|
|
r := nk.Raw32()
|
|
|
|
id := int64(binary.LittleEndian.Uint64(r[:]))
|
|
|
|
ip := netaddr.IPv4(r[0], r[1], r[2], r[3])
|
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
|
|
|
addr := netip.PrefixFrom(ip, 32)
|
2021-08-18 21:20:40 +00:00
|
|
|
s.nodes[nk] = &tailcfg.Node{
|
|
|
|
ID: tailcfg.NodeID(id),
|
|
|
|
StableID: tailcfg.StableNodeID(fmt.Sprintf("TESTCTRL%08x", id)),
|
|
|
|
User: tailcfg.UserID(id),
|
|
|
|
Machine: mk,
|
2021-11-02 03:55:52 +00:00
|
|
|
Key: nk,
|
2021-08-18 21:20:40 +00:00
|
|
|
MachineAuthorized: true,
|
|
|
|
DiscoKey: dk,
|
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
|
|
|
Addresses: []netip.Prefix{addr},
|
|
|
|
AllowedIPs: []netip.Prefix{addr},
|
2021-08-18 21:20:40 +00:00
|
|
|
}
|
|
|
|
// TODO: send updates to other (non-fake?) nodes
|
|
|
|
}
|
|
|
|
|
2023-03-09 20:52:18 +00:00
|
|
|
func (s *Server) AllUsers() (users []*tailcfg.User) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
for _, u := range s.users {
|
|
|
|
users = append(users, u.Clone())
|
|
|
|
}
|
|
|
|
return users
|
|
|
|
}
|
|
|
|
|
2021-05-12 21:43:43 +00:00
|
|
|
func (s *Server) AllNodes() (nodes []*tailcfg.Node) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
for _, n := range s.nodes {
|
|
|
|
nodes = append(nodes, n.Clone())
|
|
|
|
}
|
|
|
|
sort.Slice(nodes, func(i, j int) bool {
|
|
|
|
return nodes[i].StableID < nodes[j].StableID
|
|
|
|
})
|
|
|
|
return nodes
|
|
|
|
}
|
|
|
|
|
2023-08-18 15:15:13 +00:00
|
|
|
const domain = "fake-control.example.net"
|
|
|
|
|
2021-10-30 00:49:16 +00:00
|
|
|
func (s *Server) getUser(nodeKey key.NodePublic) (*tailcfg.User, *tailcfg.Login) {
|
2021-04-30 04:52:31 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if s.users == nil {
|
2021-10-30 00:49:16 +00:00
|
|
|
s.users = map[key.NodePublic]*tailcfg.User{}
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
if s.logins == nil {
|
2021-10-30 00:49:16 +00:00
|
|
|
s.logins = map[key.NodePublic]*tailcfg.Login{}
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
if u, ok := s.users[nodeKey]; ok {
|
|
|
|
return u, s.logins[nodeKey]
|
|
|
|
}
|
|
|
|
id := tailcfg.UserID(len(s.users) + 1)
|
|
|
|
loginName := fmt.Sprintf("user-%d@%s", id, domain)
|
|
|
|
displayName := fmt.Sprintf("User %d", id)
|
|
|
|
login := &tailcfg.Login{
|
|
|
|
ID: tailcfg.LoginID(id),
|
|
|
|
Provider: "testcontrol",
|
|
|
|
LoginName: loginName,
|
|
|
|
DisplayName: displayName,
|
|
|
|
ProfilePicURL: "https://tailscale.com/static/images/marketing/team-carney.jpg",
|
|
|
|
}
|
|
|
|
user := &tailcfg.User{
|
|
|
|
ID: id,
|
|
|
|
LoginName: loginName,
|
|
|
|
DisplayName: displayName,
|
|
|
|
Logins: []tailcfg.LoginID{login.ID},
|
|
|
|
}
|
|
|
|
s.users[nodeKey] = user
|
|
|
|
s.logins[nodeKey] = login
|
|
|
|
return user, login
|
|
|
|
}
|
|
|
|
|
2021-05-12 04:57:25 +00:00
|
|
|
// authPathDone returns a close-only struct that's closed when the
|
|
|
|
// authPath ("/auth/XXXXXX") has authenticated.
|
|
|
|
func (s *Server) authPathDone(authPath string) <-chan struct{} {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if a, ok := s.authPath[authPath]; ok {
|
|
|
|
return a.ch
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-30 00:49:16 +00:00
|
|
|
func (s *Server) addAuthPath(authPath string, nodeKey key.NodePublic) {
|
2021-05-12 04:57:25 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if s.authPath == nil {
|
|
|
|
s.authPath = map[string]*AuthPath{}
|
|
|
|
}
|
|
|
|
s.authPath[authPath] = &AuthPath{
|
|
|
|
ch: make(chan struct{}),
|
|
|
|
nodeKey: nodeKey,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// CompleteAuth marks the provided path or URL (containing
|
|
|
|
// "/auth/...") as successfully authenticated, unblocking any
|
|
|
|
// requests blocked on that in serveRegister.
|
|
|
|
func (s *Server) CompleteAuth(authPathOrURL string) bool {
|
|
|
|
i := strings.Index(authPathOrURL, "/auth/")
|
|
|
|
if i == -1 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
authPath := authPathOrURL[i:]
|
|
|
|
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
ap, ok := s.authPath[authPath]
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if ap.nodeKey.IsZero() {
|
|
|
|
panic("zero AuthPath.NodeKey")
|
|
|
|
}
|
|
|
|
if s.nodeKeyAuthed == nil {
|
2021-10-30 00:49:16 +00:00
|
|
|
s.nodeKeyAuthed = map[key.NodePublic]bool{}
|
2021-05-12 04:57:25 +00:00
|
|
|
}
|
|
|
|
s.nodeKeyAuthed[ap.nodeKey] = true
|
|
|
|
ap.CompleteSuccessfully()
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2021-09-03 20:17:46 +00:00
|
|
|
func (s *Server) serveRegister(w http.ResponseWriter, r *http.Request, mkey key.MachinePublic) {
|
2022-09-15 12:06:59 +00:00
|
|
|
msg, err := io.ReadAll(io.LimitReader(r.Body, msgLimit))
|
2022-03-06 17:32:52 +00:00
|
|
|
r.Body.Close()
|
2021-08-30 13:54:35 +00:00
|
|
|
if err != nil {
|
|
|
|
http.Error(w, fmt.Sprintf("bad map request read: %v", err), 400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-04-30 04:52:31 +00:00
|
|
|
var req tailcfg.RegisterRequest
|
2021-08-30 13:54:35 +00:00
|
|
|
if err := s.decode(mkey, msg, &req); err != nil {
|
|
|
|
go panic(fmt.Sprintf("serveRegister: decode: %v", err))
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
2022-03-06 17:32:52 +00:00
|
|
|
if req.Version == 0 {
|
|
|
|
panic("serveRegister: zero Version")
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
if req.NodeKey.IsZero() {
|
2021-08-30 13:54:35 +00:00
|
|
|
go panic("serveRegister: request has zero node key")
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
2021-05-12 04:57:25 +00:00
|
|
|
if s.Verbose {
|
|
|
|
j, _ := json.MarshalIndent(req, "", "\t")
|
|
|
|
log.Printf("Got %T: %s", req, j)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If this is a followup request, wait until interactive followup URL visit complete.
|
|
|
|
if req.Followup != "" {
|
|
|
|
followupURL, err := url.Parse(req.Followup)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
doneCh := s.authPathDone(followupURL.Path)
|
|
|
|
select {
|
|
|
|
case <-r.Context().Done():
|
|
|
|
return
|
|
|
|
case <-doneCh:
|
|
|
|
}
|
|
|
|
// TODO(bradfitz): support a side test API to mark an
|
2022-09-25 18:29:55 +00:00
|
|
|
// auth as failed so we can send an error response in
|
2021-05-12 04:57:25 +00:00
|
|
|
// some follow-ups? For now all are successes.
|
|
|
|
}
|
2021-04-30 04:52:31 +00:00
|
|
|
|
2021-11-02 03:55:52 +00:00
|
|
|
nk := req.NodeKey
|
2021-10-30 00:49:16 +00:00
|
|
|
|
|
|
|
user, login := s.getUser(nk)
|
2021-04-30 04:52:31 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
if s.nodes == nil {
|
2021-10-30 00:49:16 +00:00
|
|
|
s.nodes = map[key.NodePublic]*tailcfg.Node{}
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
2021-05-12 04:57:25 +00:00
|
|
|
|
|
|
|
machineAuthorized := true // TODO: add Server.RequireMachineAuth
|
|
|
|
|
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
|
|
|
v4Prefix := netip.PrefixFrom(netaddr.IPv4(100, 64, uint8(tailcfg.NodeID(user.ID)>>8), uint8(tailcfg.NodeID(user.ID))), 32)
|
|
|
|
v6Prefix := netip.PrefixFrom(tsaddr.Tailscale4To6(v4Prefix.Addr()), 128)
|
2021-07-13 17:10:08 +00:00
|
|
|
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
allowedIPs := []netip.Prefix{
|
2021-07-13 17:10:08 +00:00
|
|
|
v4Prefix,
|
|
|
|
v6Prefix,
|
2021-05-18 20:20:29 +00:00
|
|
|
}
|
|
|
|
|
2021-10-30 00:49:16 +00:00
|
|
|
s.nodes[nk] = &tailcfg.Node{
|
2021-04-30 04:52:31 +00:00
|
|
|
ID: tailcfg.NodeID(user.ID),
|
|
|
|
StableID: tailcfg.StableNodeID(fmt.Sprintf("TESTCTRL%08x", int(user.ID))),
|
|
|
|
User: user.ID,
|
|
|
|
Machine: mkey,
|
|
|
|
Key: req.NodeKey,
|
2021-05-12 04:57:25 +00:00
|
|
|
MachineAuthorized: machineAuthorized,
|
2021-05-18 20:20:29 +00:00
|
|
|
Addresses: allowedIPs,
|
|
|
|
AllowedIPs: allowedIPs,
|
2022-02-15 16:19:44 +00:00
|
|
|
Hostinfo: req.Hostinfo.View(),
|
2023-03-09 20:52:18 +00:00
|
|
|
Name: req.Hostinfo.Hostname,
|
|
|
|
Capabilities: []string{
|
2023-08-09 14:06:58 +00:00
|
|
|
tailcfg.CapabilityHTTPS,
|
2023-03-09 20:52:18 +00:00
|
|
|
tailcfg.NodeAttrFunnel,
|
|
|
|
tailcfg.CapabilityFunnelPorts + "?ports=8080,443",
|
|
|
|
},
|
2021-05-12 04:57:25 +00:00
|
|
|
}
|
|
|
|
requireAuth := s.RequireAuth
|
2021-10-30 00:49:16 +00:00
|
|
|
if requireAuth && s.nodeKeyAuthed[nk] {
|
2021-05-12 04:57:25 +00:00
|
|
|
requireAuth = false
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
2021-10-29 00:44:18 +00:00
|
|
|
allExpired := s.allExpired
|
2021-04-30 04:52:31 +00:00
|
|
|
s.mu.Unlock()
|
|
|
|
|
2021-05-12 04:57:25 +00:00
|
|
|
authURL := ""
|
|
|
|
if requireAuth {
|
2023-09-05 16:02:40 +00:00
|
|
|
authPath := fmt.Sprintf("/auth/%s", rands.HexString(20))
|
2021-10-30 00:49:16 +00:00
|
|
|
s.addAuthPath(authPath, nk)
|
2021-06-18 17:09:16 +00:00
|
|
|
authURL = s.BaseURL() + authPath
|
2021-05-12 04:57:25 +00:00
|
|
|
}
|
|
|
|
|
2021-04-30 04:52:31 +00:00
|
|
|
res, err := s.encode(mkey, false, tailcfg.RegisterResponse{
|
|
|
|
User: *user,
|
|
|
|
Login: *login,
|
2021-10-29 00:44:18 +00:00
|
|
|
NodeKeyExpired: allExpired,
|
2021-05-12 04:57:25 +00:00
|
|
|
MachineAuthorized: machineAuthorized,
|
|
|
|
AuthURL: authURL,
|
2021-04-30 04:52:31 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
go panic(fmt.Sprintf("serveRegister: encode: %v", err))
|
|
|
|
}
|
|
|
|
w.WriteHeader(200)
|
|
|
|
w.Write(res)
|
|
|
|
}
|
|
|
|
|
|
|
|
// updateType indicates why a long-polling map request is being woken
|
|
|
|
// up for an update.
|
|
|
|
type updateType int
|
|
|
|
|
|
|
|
const (
|
|
|
|
// updatePeerChanged is an update that a peer has changed.
|
|
|
|
updatePeerChanged updateType = iota + 1
|
|
|
|
|
|
|
|
// updateSelfChanged is an update that the node changed itself
|
|
|
|
// via a lite endpoint update. These ones are never dup-suppressed,
|
|
|
|
// as the client is expecting an answer regardless.
|
|
|
|
updateSelfChanged
|
2021-06-02 15:23:24 +00:00
|
|
|
|
|
|
|
// updateDebugInjection is an update used for PingRequests
|
2023-09-12 18:43:34 +00:00
|
|
|
// or a raw MapResponse.
|
2021-06-02 15:23:24 +00:00
|
|
|
updateDebugInjection
|
2021-04-30 04:52:31 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Server) updateLocked(source string, peers []tailcfg.NodeID) {
|
|
|
|
for _, peer := range peers {
|
|
|
|
sendUpdate(s.updates[peer], updatePeerChanged)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// sendUpdate sends updateType to dst if dst is non-nil and
|
2021-06-10 22:12:25 +00:00
|
|
|
// has capacity. It reports whether a value was sent.
|
|
|
|
func sendUpdate(dst chan<- updateType, updateType updateType) bool {
|
2021-04-30 04:52:31 +00:00
|
|
|
if dst == nil {
|
2021-06-10 22:12:25 +00:00
|
|
|
return false
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
// The dst channel has a buffer size of 1.
|
|
|
|
// If we fail to insert an update into the buffer that
|
|
|
|
// means there is already an update pending.
|
|
|
|
select {
|
|
|
|
case dst <- updateType:
|
2021-06-10 22:12:25 +00:00
|
|
|
return true
|
2021-04-30 04:52:31 +00:00
|
|
|
default:
|
2021-06-10 22:12:25 +00:00
|
|
|
return false
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-12 21:43:43 +00:00
|
|
|
func (s *Server) UpdateNode(n *tailcfg.Node) (peersToUpdate []tailcfg.NodeID) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if n.Key.IsZero() {
|
|
|
|
panic("zero nodekey")
|
|
|
|
}
|
2021-11-02 03:55:52 +00:00
|
|
|
s.nodes[n.Key] = n.Clone()
|
2023-03-03 00:00:19 +00:00
|
|
|
return s.nodeIDsLocked(n.ID)
|
2021-05-12 21:43:43 +00:00
|
|
|
}
|
|
|
|
|
2021-07-16 22:21:00 +00:00
|
|
|
func (s *Server) incrInServeMap(delta int) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
s.inServeMap += delta
|
|
|
|
}
|
|
|
|
|
|
|
|
// InServeMap returns the number of clients currently in a MapRequest HTTP handler.
|
|
|
|
func (s *Server) InServeMap() int {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
return s.inServeMap
|
|
|
|
}
|
|
|
|
|
2021-09-03 20:17:46 +00:00
|
|
|
func (s *Server) serveMap(w http.ResponseWriter, r *http.Request, mkey key.MachinePublic) {
|
2021-07-16 22:21:00 +00:00
|
|
|
s.incrInServeMap(1)
|
|
|
|
defer s.incrInServeMap(-1)
|
2021-04-30 04:52:31 +00:00
|
|
|
ctx := r.Context()
|
|
|
|
|
2022-09-15 12:06:59 +00:00
|
|
|
msg, err := io.ReadAll(io.LimitReader(r.Body, msgLimit))
|
2021-08-30 13:54:35 +00:00
|
|
|
if err != nil {
|
|
|
|
r.Body.Close()
|
|
|
|
http.Error(w, fmt.Sprintf("bad map request read: %v", err), 400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
r.Body.Close()
|
|
|
|
|
2021-04-30 04:52:31 +00:00
|
|
|
req := new(tailcfg.MapRequest)
|
2021-08-30 13:54:35 +00:00
|
|
|
if err := s.decode(mkey, msg, req); err != nil {
|
2021-04-30 04:52:31 +00:00
|
|
|
go panic(fmt.Sprintf("bad map request: %v", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
jitter := time.Duration(rand.Intn(8000)) * time.Millisecond
|
|
|
|
keepAlive := 50*time.Second + jitter
|
|
|
|
|
2021-11-02 03:55:52 +00:00
|
|
|
node := s.Node(req.NodeKey)
|
2021-04-30 04:52:31 +00:00
|
|
|
if node == nil {
|
|
|
|
http.Error(w, "node not found", 400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if node.Machine != mkey {
|
|
|
|
http.Error(w, "node doesn't match machine key", 400)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var peersToUpdate []tailcfg.NodeID
|
|
|
|
if !req.ReadOnly {
|
|
|
|
endpoints := filterInvalidIPv6Endpoints(req.Endpoints)
|
|
|
|
node.Endpoints = endpoints
|
2021-05-12 21:43:43 +00:00
|
|
|
node.DiscoKey = req.DiscoKey
|
2021-08-30 13:55:55 +00:00
|
|
|
if req.Hostinfo != nil {
|
2022-02-15 16:19:44 +00:00
|
|
|
node.Hostinfo = req.Hostinfo.View()
|
|
|
|
if ni := node.Hostinfo.NetInfo(); ni.Valid() {
|
|
|
|
if ni.PreferredDERP() != 0 {
|
|
|
|
node.DERP = fmt.Sprintf("127.3.3.40:%d", ni.PreferredDERP())
|
2021-08-30 13:55:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-05-12 21:43:43 +00:00
|
|
|
peersToUpdate = s.UpdateNode(node)
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
nodeID := node.ID
|
|
|
|
|
|
|
|
s.mu.Lock()
|
|
|
|
updatesCh := make(chan updateType, 1)
|
|
|
|
oldUpdatesCh := s.updates[nodeID]
|
|
|
|
if breakSameNodeMapResponseStreams(req) {
|
|
|
|
if oldUpdatesCh != nil {
|
|
|
|
close(oldUpdatesCh)
|
|
|
|
}
|
|
|
|
if s.updates == nil {
|
|
|
|
s.updates = map[tailcfg.NodeID]chan updateType{}
|
|
|
|
}
|
|
|
|
s.updates[nodeID] = updatesCh
|
|
|
|
} else {
|
|
|
|
sendUpdate(oldUpdatesCh, updateSelfChanged)
|
|
|
|
}
|
|
|
|
s.updateLocked("serveMap", peersToUpdate)
|
2021-06-10 22:12:25 +00:00
|
|
|
s.condLocked().Broadcast()
|
2021-04-30 04:52:31 +00:00
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
|
|
// ReadOnly implies no streaming, as it doesn't
|
|
|
|
// register an updatesCh to get updates.
|
|
|
|
streaming := req.Stream && !req.ReadOnly
|
|
|
|
compress := req.Compress != ""
|
|
|
|
|
|
|
|
w.WriteHeader(200)
|
|
|
|
for {
|
2023-09-12 18:43:34 +00:00
|
|
|
if resBytes, ok := s.takeRawMapMessage(req.NodeKey); ok {
|
|
|
|
if err := s.sendMapMsg(w, mkey, compress, resBytes); err != nil {
|
|
|
|
s.logf("sendMapMsg of raw message: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if streaming {
|
|
|
|
continue
|
|
|
|
}
|
2021-04-30 04:52:31 +00:00
|
|
|
return
|
|
|
|
}
|
2021-10-29 00:44:18 +00:00
|
|
|
|
2023-09-12 18:43:34 +00:00
|
|
|
if s.canGenerateAutomaticMapResponseFor(req.NodeKey) {
|
|
|
|
res, err := s.MapResponse(req)
|
|
|
|
if err != nil {
|
|
|
|
// TODO: log
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if res == nil {
|
|
|
|
return // done
|
|
|
|
}
|
|
|
|
|
|
|
|
s.mu.Lock()
|
|
|
|
allExpired := s.allExpired
|
|
|
|
s.mu.Unlock()
|
|
|
|
if allExpired {
|
|
|
|
res.Node.KeyExpiry = time.Now().Add(-1 * time.Minute)
|
|
|
|
}
|
|
|
|
// TODO: add minner if/when needed
|
|
|
|
resBytes, err := json.Marshal(res)
|
|
|
|
if err != nil {
|
|
|
|
s.logf("json.Marshal: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err := s.sendMapMsg(w, mkey, compress, resBytes); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
if !streaming {
|
|
|
|
return
|
|
|
|
}
|
2023-09-12 18:43:34 +00:00
|
|
|
if s.hasPendingRawMapMessage(req.NodeKey) {
|
|
|
|
continue
|
|
|
|
}
|
2021-04-30 04:52:31 +00:00
|
|
|
keepAliveLoop:
|
|
|
|
for {
|
|
|
|
var keepAliveTimer *time.Timer
|
|
|
|
var keepAliveTimerCh <-chan time.Time
|
|
|
|
if keepAlive > 0 {
|
|
|
|
keepAliveTimer = time.NewTimer(keepAlive)
|
|
|
|
keepAliveTimerCh = keepAliveTimer.C
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
if keepAliveTimer != nil {
|
|
|
|
keepAliveTimer.Stop()
|
|
|
|
}
|
|
|
|
return
|
|
|
|
case _, ok := <-updatesCh:
|
|
|
|
if !ok {
|
|
|
|
// replaced by new poll request
|
|
|
|
return
|
|
|
|
}
|
|
|
|
break keepAliveLoop
|
|
|
|
case <-keepAliveTimerCh:
|
|
|
|
if err := s.sendMapMsg(w, mkey, compress, keepAliveMsg); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var keepAliveMsg = &struct {
|
|
|
|
KeepAlive bool
|
|
|
|
}{
|
|
|
|
KeepAlive: true,
|
|
|
|
}
|
|
|
|
|
2023-03-09 20:52:18 +00:00
|
|
|
func packetFilterWithIngressCaps() []tailcfg.FilterRule {
|
|
|
|
out := slices.Clone(tailcfg.FilterAllowAll)
|
|
|
|
out = append(out, tailcfg.FilterRule{
|
|
|
|
SrcIPs: []string{"*"},
|
|
|
|
CapGrant: []tailcfg.CapGrant{
|
|
|
|
{
|
|
|
|
Dsts: []netip.Prefix{tsaddr.AllIPv4(), tsaddr.AllIPv6()},
|
2023-07-25 04:07:00 +00:00
|
|
|
Caps: []tailcfg.PeerCapability{tailcfg.PeerCapabilityIngress},
|
2023-03-09 20:52:18 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
return out
|
|
|
|
}
|
|
|
|
|
2021-04-30 04:52:31 +00:00
|
|
|
// MapResponse generates a MapResponse for a MapRequest.
|
|
|
|
//
|
|
|
|
// No updates to s are done here.
|
|
|
|
func (s *Server) MapResponse(req *tailcfg.MapRequest) (res *tailcfg.MapResponse, err error) {
|
2021-11-02 03:55:52 +00:00
|
|
|
nk := req.NodeKey
|
2021-10-30 00:49:16 +00:00
|
|
|
node := s.Node(nk)
|
2021-04-30 04:52:31 +00:00
|
|
|
if node == nil {
|
|
|
|
// node key rotated away (once test server supports that)
|
|
|
|
return nil, nil
|
|
|
|
}
|
2023-08-17 04:43:56 +00:00
|
|
|
node.Capabilities = append(node.Capabilities, tailcfg.NodeAttrDisableUPnP)
|
|
|
|
|
2021-10-30 00:49:16 +00:00
|
|
|
user, _ := s.getUser(nk)
|
2022-02-18 18:14:14 +00:00
|
|
|
t := time.Date(2020, 8, 3, 0, 0, 0, 1, time.UTC)
|
2023-03-09 20:52:18 +00:00
|
|
|
dns := s.DNSConfig
|
|
|
|
if dns != nil && s.MagicDNSDomain != "" {
|
|
|
|
dns = dns.Clone()
|
|
|
|
dns.CertDomains = []string{
|
|
|
|
fmt.Sprintf(node.Hostinfo.Hostname() + "." + s.MagicDNSDomain),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-30 04:52:31 +00:00
|
|
|
res = &tailcfg.MapResponse{
|
|
|
|
Node: node,
|
2021-06-25 18:44:40 +00:00
|
|
|
DERPMap: s.DERPMap,
|
2023-08-18 15:15:13 +00:00
|
|
|
Domain: domain,
|
2021-04-30 04:52:31 +00:00
|
|
|
CollectServices: "true",
|
2023-03-09 20:52:18 +00:00
|
|
|
PacketFilter: packetFilterWithIngressCaps(),
|
2023-08-17 04:43:56 +00:00
|
|
|
DNSConfig: dns,
|
|
|
|
ControlTime: &t,
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
2023-03-03 00:00:19 +00:00
|
|
|
|
|
|
|
s.mu.Lock()
|
|
|
|
nodeMasqs := s.masquerades[node.Key]
|
|
|
|
s.mu.Unlock()
|
2021-05-12 21:43:43 +00:00
|
|
|
for _, p := range s.AllNodes() {
|
2023-03-03 00:00:19 +00:00
|
|
|
if p.StableID == node.StableID {
|
|
|
|
continue
|
2021-05-12 21:43:43 +00:00
|
|
|
}
|
2023-03-03 00:00:19 +00:00
|
|
|
if masqIP := nodeMasqs[p.Key]; masqIP.IsValid() {
|
2023-04-13 17:12:31 +00:00
|
|
|
p.SelfNodeV4MasqAddrForThisPeer = ptr.To(masqIP)
|
2023-03-03 00:00:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
s.mu.Lock()
|
|
|
|
peerAddress := s.masquerades[p.Key][node.Key]
|
|
|
|
s.mu.Unlock()
|
|
|
|
if peerAddress.IsValid() {
|
|
|
|
p.Addresses[0] = netip.PrefixFrom(peerAddress, peerAddress.BitLen())
|
|
|
|
p.AllowedIPs[0] = netip.PrefixFrom(peerAddress, peerAddress.BitLen())
|
|
|
|
}
|
|
|
|
res.Peers = append(res.Peers, p)
|
2021-05-12 21:43:43 +00:00
|
|
|
}
|
2023-03-03 00:00:19 +00:00
|
|
|
|
2021-08-18 21:19:21 +00:00
|
|
|
sort.Slice(res.Peers, func(i, j int) bool {
|
|
|
|
return res.Peers[i].ID < res.Peers[j].ID
|
|
|
|
})
|
2023-03-09 20:52:18 +00:00
|
|
|
for _, u := range s.AllUsers() {
|
|
|
|
res.UserProfiles = append(res.UserProfiles, tailcfg.UserProfile{
|
|
|
|
ID: u.ID,
|
|
|
|
LoginName: u.LoginName,
|
|
|
|
DisplayName: u.DisplayName,
|
|
|
|
})
|
|
|
|
}
|
2021-05-12 21:43:43 +00:00
|
|
|
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
v4Prefix := netip.PrefixFrom(netaddr.IPv4(100, 64, uint8(tailcfg.NodeID(user.ID)>>8), uint8(tailcfg.NodeID(user.ID))), 32)
|
|
|
|
v6Prefix := netip.PrefixFrom(tsaddr.Tailscale4To6(v4Prefix.Addr()), 128)
|
2021-07-13 17:10:08 +00:00
|
|
|
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
res.Node.Addresses = []netip.Prefix{
|
2021-07-13 17:10:08 +00:00
|
|
|
v4Prefix,
|
|
|
|
v6Prefix,
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
res.Node.AllowedIPs = res.Node.Addresses
|
2021-06-02 15:23:24 +00:00
|
|
|
|
2023-09-12 18:43:34 +00:00
|
|
|
// Consume a PingRequest while protected by mutex if it exists
|
2021-06-02 15:23:24 +00:00
|
|
|
s.mu.Lock()
|
2023-09-12 18:43:34 +00:00
|
|
|
defer s.mu.Unlock()
|
|
|
|
switch m := s.msgToSend[nk].(type) {
|
|
|
|
case *tailcfg.PingRequest:
|
|
|
|
res.PingRequest = m
|
|
|
|
delete(s.msgToSend, nk)
|
2021-06-02 15:23:24 +00:00
|
|
|
}
|
2021-04-30 04:52:31 +00:00
|
|
|
return res, nil
|
|
|
|
}
|
|
|
|
|
2023-09-12 18:43:34 +00:00
|
|
|
func (s *Server) canGenerateAutomaticMapResponseFor(nk key.NodePublic) bool {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
return !s.suppressAutoMapResponses.Contains(nk)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) hasPendingRawMapMessage(nk key.NodePublic) bool {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
_, ok := s.msgToSend[nk].(*tailcfg.MapResponse)
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) takeRawMapMessage(nk key.NodePublic) (mapResJSON []byte, ok bool) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
mr, ok := s.msgToSend[nk].(*tailcfg.MapResponse)
|
|
|
|
if !ok {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
delete(s.msgToSend, nk)
|
|
|
|
var err error
|
|
|
|
mapResJSON, err = json.Marshal(mr)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return mapResJSON, true
|
|
|
|
}
|
|
|
|
|
2022-03-16 23:27:57 +00:00
|
|
|
func (s *Server) sendMapMsg(w http.ResponseWriter, mkey key.MachinePublic, compress bool, msg any) error {
|
2021-04-30 04:52:31 +00:00
|
|
|
resBytes, err := s.encode(mkey, compress, msg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(resBytes) > 16<<20 {
|
|
|
|
return fmt.Errorf("map message too big: %d", len(resBytes))
|
|
|
|
}
|
|
|
|
var siz [4]byte
|
|
|
|
binary.LittleEndian.PutUint32(siz[:], uint32(len(resBytes)))
|
|
|
|
if _, err := w.Write(siz[:]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if _, err := w.Write(resBytes); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if f, ok := w.(http.Flusher); ok {
|
|
|
|
f.Flush()
|
|
|
|
} else {
|
|
|
|
s.logf("[unexpected] ResponseWriter %T is not a Flusher", w)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-03-16 23:27:57 +00:00
|
|
|
func (s *Server) decode(mkey key.MachinePublic, msg []byte, v any) error {
|
2021-04-30 04:52:31 +00:00
|
|
|
if len(msg) == msgLimit {
|
|
|
|
return errors.New("encrypted message too long")
|
|
|
|
}
|
|
|
|
|
2021-09-03 20:17:46 +00:00
|
|
|
decrypted, ok := s.privateKey().OpenFrom(mkey, msg)
|
2021-04-30 04:52:31 +00:00
|
|
|
if !ok {
|
|
|
|
return errors.New("can't decrypt request")
|
|
|
|
}
|
|
|
|
return json.Unmarshal(decrypted, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
var zstdEncoderPool = &sync.Pool{
|
2022-03-16 23:27:57 +00:00
|
|
|
New: func() any {
|
2021-04-30 04:52:31 +00:00
|
|
|
encoder, err := smallzstd.NewEncoder(nil, zstd.WithEncoderLevel(zstd.SpeedFastest))
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return encoder
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2022-03-16 23:27:57 +00:00
|
|
|
func (s *Server) encode(mkey key.MachinePublic, compress bool, v any) (b []byte, err error) {
|
2021-04-30 04:52:31 +00:00
|
|
|
var isBytes bool
|
|
|
|
if b, isBytes = v.([]byte); !isBytes {
|
|
|
|
b, err = json.Marshal(v)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if compress {
|
|
|
|
encoder := zstdEncoderPool.Get().(*zstd.Encoder)
|
|
|
|
b = encoder.EncodeAll(b, nil)
|
|
|
|
encoder.Close()
|
|
|
|
zstdEncoderPool.Put(encoder)
|
|
|
|
}
|
2021-09-03 20:17:46 +00:00
|
|
|
return s.privateKey().SealTo(mkey, b), nil
|
2021-04-30 04:52:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// filterInvalidIPv6Endpoints removes invalid IPv6 endpoints from eps,
|
|
|
|
// modify the slice in place, returning the potentially smaller subset (aliasing
|
|
|
|
// the original memory).
|
|
|
|
//
|
|
|
|
// Two types of IPv6 endpoints are considered invalid: link-local
|
|
|
|
// addresses, and anything with a zone.
|
|
|
|
func filterInvalidIPv6Endpoints(eps []string) []string {
|
|
|
|
clean := eps[:0]
|
|
|
|
for _, ep := range eps {
|
|
|
|
if keepClientEndpoint(ep) {
|
|
|
|
clean = append(clean, ep)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return clean
|
|
|
|
}
|
|
|
|
|
|
|
|
func keepClientEndpoint(ep string) bool {
|
2022-07-26 03:55:44 +00:00
|
|
|
ipp, err := netip.ParseAddrPort(ep)
|
2021-04-30 04:52:31 +00:00
|
|
|
if err != nil {
|
|
|
|
// Shouldn't have made it this far if we unmarshalled
|
|
|
|
// the incoming JSON response.
|
|
|
|
return false
|
|
|
|
}
|
2022-07-25 03:08:42 +00:00
|
|
|
ip := ipp.Addr()
|
2021-04-30 04:52:31 +00:00
|
|
|
if ip.Zone() != "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if ip.Is6() && ip.IsLinkLocalUnicast() {
|
|
|
|
// We let clients send these for now, but
|
|
|
|
// tailscaled doesn't know how to use them yet
|
|
|
|
// so we filter them out for now. A future
|
|
|
|
// MapRequest.Version might signal that
|
|
|
|
// clients know how to use them (e.g. try all
|
|
|
|
// local scopes).
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// breakSameNodeMapResponseStreams reports whether req should break a
|
|
|
|
// prior long-polling MapResponse stream (if active) from the same
|
|
|
|
// node ID.
|
|
|
|
func breakSameNodeMapResponseStreams(req *tailcfg.MapRequest) bool {
|
|
|
|
if req.ReadOnly {
|
|
|
|
// Don't register our updatesCh for closability
|
|
|
|
// nor close another peer's if we're a read-only request.
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if !req.Stream && req.OmitPeers {
|
|
|
|
// Likewise, if we're not streaming and not asking for peers,
|
|
|
|
// (but still mutable, without Readonly set), consider this an endpoint
|
|
|
|
// update request only, and don't close any existing map response
|
|
|
|
// for this nodeID. It's likely the same client with a built-up
|
|
|
|
// compression context. We want to let them update their
|
|
|
|
// new endpoints with us without breaking that other long-running
|
|
|
|
// map response.
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|