headscale/hscontrol/auth.go

267 lines
6.7 KiB
Go
Raw Normal View History

package hscontrol
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/juanfont/headscale/hscontrol/db"
"github.com/juanfont/headscale/hscontrol/types"
"github.com/juanfont/headscale/hscontrol/util"
"gorm.io/gorm"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
"tailscale.com/types/ptr"
)
Redo OIDC configuration (#2020) expand user, add claims to user This commit expands the user table with additional fields that can be retrieved from OIDC providers (and other places) and uses this data in various tailscale response objects if it is available. This is the beginning of implementing https://docs.google.com/document/d/1X85PMxIaVWDF6T_UPji3OeeUqVBcGj_uHRM5CI-AwlY/edit trying to make OIDC more coherant and maintainable in addition to giving the user a better experience and integration with a provider. remove usernames in magic dns, normalisation of emails this commit removes the option to have usernames as part of MagicDNS domains and headscale will now align with Tailscale, where there is a root domain, and the machine name. In addition, the various normalisation functions for dns names has been made lighter not caring about username and special character that wont occur. Email are no longer normalised as part of the policy processing. untagle oidc and regcache, use typed cache This commits stops reusing the registration cache for oidc purposes and switches the cache to be types and not use any allowing the removal of a bunch of casting. try to make reauth/register branches clearer in oidc Currently there was a function that did a bunch of stuff, finding the machine key, trying to find the node, reauthing the node, returning some status, and it was called validate which was very confusing. This commit tries to split this into what to do if the node exists, if it needs to register etc. Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
2024-10-02 21:50:17 +09:00
type AuthProvider interface {
RegisterHandler(http.ResponseWriter, *http.Request)
AuthURL(types.RegistrationID) string
Redo OIDC configuration (#2020) expand user, add claims to user This commit expands the user table with additional fields that can be retrieved from OIDC providers (and other places) and uses this data in various tailscale response objects if it is available. This is the beginning of implementing https://docs.google.com/document/d/1X85PMxIaVWDF6T_UPji3OeeUqVBcGj_uHRM5CI-AwlY/edit trying to make OIDC more coherant and maintainable in addition to giving the user a better experience and integration with a provider. remove usernames in magic dns, normalisation of emails this commit removes the option to have usernames as part of MagicDNS domains and headscale will now align with Tailscale, where there is a root domain, and the machine name. In addition, the various normalisation functions for dns names has been made lighter not caring about username and special character that wont occur. Email are no longer normalised as part of the policy processing. untagle oidc and regcache, use typed cache This commits stops reusing the registration cache for oidc purposes and switches the cache to be types and not use any allowing the removal of a bunch of casting. try to make reauth/register branches clearer in oidc Currently there was a function that did a bunch of stuff, finding the machine key, trying to find the node, reauthing the node, returning some status, and it was called validate which was very confusing. This commit tries to split this into what to do if the node exists, if it needs to register etc. Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
2024-10-02 21:50:17 +09:00
}
func (h *Headscale) handleRegister(
2025-02-01 18:16:51 +09:00
ctx context.Context,
regReq tailcfg.RegisterRequest,
machineKey key.MachinePublic,
2025-02-01 18:16:51 +09:00
) (*tailcfg.RegisterResponse, error) {
node, err := h.db.GetNodeByNodeKey(regReq.NodeKey)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("looking up node in database: %w", err)
}
2023-09-24 20:42:05 +09:00
if node != nil {
2025-02-01 18:16:51 +09:00
resp, err := h.handleExistingNode(node, regReq, machineKey)
if err != nil {
return nil, fmt.Errorf("handling existing node: %w", err)
}
2025-02-01 18:16:51 +09:00
return resp, nil
}
2025-02-01 18:16:51 +09:00
if regReq.Followup != "" {
// TODO(kradalby): Does this need to return an error of some sort?
// Maybe if the registration fails down the line it can be sent
// on the channel and returned here?
h.waitForFollowup(ctx, regReq)
}
2025-02-01 18:16:51 +09:00
if regReq.Auth != nil && regReq.Auth.AuthKey != "" {
resp, err := h.handleRegisterWithAuthKey(regReq, machineKey)
if err != nil {
2025-02-01 18:16:51 +09:00
return nil, fmt.Errorf("handling register with auth key: %w", err)
}
2025-02-01 18:16:51 +09:00
return resp, nil
}
2025-02-01 18:16:51 +09:00
resp, err := h.handleRegisterInteractive(regReq, machineKey)
if err != nil {
return nil, fmt.Errorf("handling register interactive: %w", err)
}
2025-02-01 18:16:51 +09:00
return resp, nil
}
2025-02-01 18:16:51 +09:00
func (h *Headscale) handleExistingNode(
node *types.Node,
regReq tailcfg.RegisterRequest,
machineKey key.MachinePublic,
) (*tailcfg.RegisterResponse, error) {
if node.MachineKey != machineKey {
return nil, errors.New("node already exists with different machine key")
}
2025-02-01 18:16:51 +09:00
expired := node.IsExpired()
if !expired && !regReq.Expiry.IsZero() {
requestExpiry := regReq.Expiry
2025-02-01 18:16:51 +09:00
// The client is trying to extend their key, this is not allowed.
if requestExpiry.After(time.Now()) {
return nil, errors.New("extending key is not allowed")
}
2025-02-01 18:16:51 +09:00
// If the request expiry is in the past, we consider it a logout.
if requestExpiry.Before(time.Now()) {
if node.IsEphemeral() {
changedNodes, err := h.db.DeleteNode(node, h.nodeNotifier.LikelyConnectedMap())
if err != nil {
return nil, fmt.Errorf("deleting ephemeral node: %w", err)
}
ctx := types.NotifyCtx(context.Background(), "logout-ephemeral", "na")
h.nodeNotifier.NotifyAll(ctx, types.StateUpdate{
Type: types.StatePeerRemoved,
Removed: []types.NodeID{node.ID},
})
if changedNodes != nil {
h.nodeNotifier.NotifyAll(ctx, types.StateUpdate{
Type: types.StatePeerChanged,
ChangeNodes: changedNodes,
})
}
2022-09-23 16:58:06 +09:00
}
2025-02-01 18:16:51 +09:00
expired = true
}
2025-02-01 18:16:51 +09:00
err := h.db.NodeSetExpiry(node.ID, requestExpiry)
if err != nil {
2025-02-01 18:16:51 +09:00
return nil, fmt.Errorf("setting node expiry: %w", err)
}
2025-02-01 18:16:51 +09:00
ctx := types.NotifyCtx(context.Background(), "logout-expiry", "na")
h.nodeNotifier.NotifyWithIgnore(ctx, types.StateUpdateExpire(node.ID, requestExpiry), node.ID)
}
2025-02-01 18:16:51 +09:00
return &tailcfg.RegisterResponse{
// TODO(kradalby): Only send for user-owned nodes
// and not tagged nodes when tags is working.
User: *node.User.TailscaleUser(),
Login: *node.User.TailscaleLogin(),
NodeKeyExpired: expired,
// Headscale does not implement the concept of machine authorization
// so we always return true here.
// Revisit this if #2176 gets implemented.
MachineAuthorized: true,
}, nil
}
2025-02-01 18:16:51 +09:00
func (h *Headscale) waitForFollowup(
ctx context.Context,
regReq tailcfg.RegisterRequest,
) {
2025-02-01 18:16:51 +09:00
fu, err := url.Parse(regReq.Followup)
if err != nil {
return
}
2025-02-01 18:16:51 +09:00
followupReg, err := types.RegistrationIDFromString(strings.ReplaceAll(fu.Path, "/register/", ""))
if err != nil {
2025-02-01 18:16:51 +09:00
return
}
2025-02-01 18:16:51 +09:00
if reg, ok := h.registrationCache.Get(followupReg); ok {
select {
case <-ctx.Done():
return
case <-reg.Registered:
return
}
}
}
2025-02-01 18:16:51 +09:00
func (h *Headscale) handleRegisterWithAuthKey(
regReq tailcfg.RegisterRequest,
machineKey key.MachinePublic,
) (*tailcfg.RegisterResponse, error) {
pak, err := h.db.ValidatePreAuthKey(regReq.Auth.AuthKey)
if err != nil {
2025-02-01 18:16:51 +09:00
return nil, fmt.Errorf("invalid pre auth key: %w", err)
}
2025-02-01 18:16:51 +09:00
nodeToRegister := types.Node{
Hostname: regReq.Hostinfo.Hostname,
UserID: pak.User.ID,
User: pak.User,
MachineKey: machineKey,
NodeKey: regReq.NodeKey,
Hostinfo: regReq.Hostinfo,
LastSeen: ptr.To(time.Now()),
RegisterMethod: util.RegisterMethodAuthKey,
// TODO(kradalby): This should not be set on the node,
// they should be looked up through the key, which is
// attached to the node.
ForcedTags: pak.Proto().GetAclTags(),
AuthKey: pak,
AuthKeyID: &pak.ID,
}
2025-02-01 18:16:51 +09:00
if !regReq.Expiry.IsZero() {
nodeToRegister.Expiry = &regReq.Expiry
}
2025-02-01 18:16:51 +09:00
ipv4, ipv6, err := h.ipAlloc.Next()
if err != nil {
2025-02-01 18:16:51 +09:00
return nil, fmt.Errorf("allocating IPs: %w", err)
}
2025-02-01 18:16:51 +09:00
node, err := db.Write(h.db.DB, func(tx *gorm.DB) (*types.Node, error) {
node, err := db.RegisterNode(tx,
nodeToRegister,
ipv4, ipv6,
)
if err != nil {
2025-02-01 18:16:51 +09:00
return nil, fmt.Errorf("registering node: %w", err)
}
2025-02-01 18:16:51 +09:00
if !pak.Reusable {
err = db.UsePreAuthKey(tx, pak)
if err != nil {
return nil, fmt.Errorf("using pre auth key: %w", err)
}
}
2025-02-01 18:16:51 +09:00
return node, nil
})
if err != nil {
2025-02-01 18:16:51 +09:00
return nil, err
}
2025-02-01 18:16:51 +09:00
updateSent, err := nodesChangedHook(h.db, h.polMan, h.nodeNotifier)
if err != nil {
2025-02-01 18:16:51 +09:00
return nil, fmt.Errorf("nodes changed hook: %w", err)
}
2025-02-01 18:16:51 +09:00
if !updateSent {
ctx := types.NotifyCtx(context.Background(), "node updated", node.Hostname)
h.nodeNotifier.NotifyAll(ctx, types.StateUpdatePeerAdded(node.ID))
}
2025-02-01 18:16:51 +09:00
return &tailcfg.RegisterResponse{
MachineAuthorized: true,
NodeKeyExpired: node.IsExpired(),
User: *pak.User.TailscaleUser(),
Login: *pak.User.TailscaleLogin(),
}, nil
}
2025-02-01 18:16:51 +09:00
func (h *Headscale) handleRegisterInteractive(
regReq tailcfg.RegisterRequest,
machineKey key.MachinePublic,
2025-02-01 18:16:51 +09:00
) (*tailcfg.RegisterResponse, error) {
registrationId, err := types.NewRegistrationID()
if err != nil {
2025-02-01 18:16:51 +09:00
return nil, fmt.Errorf("generating registration ID: %w", err)
}
2025-02-01 18:16:51 +09:00
newNode := types.RegisterNode{
Node: types.Node{
Hostname: regReq.Hostinfo.Hostname,
MachineKey: machineKey,
NodeKey: regReq.NodeKey,
Hostinfo: regReq.Hostinfo,
LastSeen: ptr.To(time.Now()),
},
Registered: make(chan struct{}),
}
2025-02-01 18:16:51 +09:00
if !regReq.Expiry.IsZero() {
newNode.Node.Expiry = &regReq.Expiry
}
2025-02-01 18:16:51 +09:00
h.registrationCache.Set(
registrationId,
newNode,
)
return &tailcfg.RegisterResponse{
AuthURL: h.authProvider.AuthURL(registrationId),
}, nil
}