Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 176 additions & 0 deletions lib/boundkeypair/bound_keypair.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/*
* Teleport
* Copyright (C) 2025 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package boundkeypair

import (
"crypto"
"crypto/subtle"
"time"

"github.com/go-jose/go-jose/v3/jwt"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"

"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/utils"
)

const (
// challengeExpiration is the TTL for a bound keypair challenge document
// once generated by the server, used to calculate the JWT `exp` field.
challengeExpiration time.Duration = time.Minute

// challengeNotBeforeOffset is the offset applied to the `nbf` field to
// allow for a small amount of clock drift.
challengeNotBeforeOffset = -10 * time.Second
)

// RecoveryMode is a recovery configuration mode
type RecoveryMode string

const (
// RecoveryModeStandard is the standard recovery mode, and enforces the
// recovery count limit and verifies client state.
RecoveryModeStandard RecoveryMode = "standard"

// RecoveryModeRelaxed does not enforce the recovery count limit, but still
// verifies client state.
RecoveryModeRelaxed = "relaxed"

// RecoveryModeInsecure does enforces neither the recovery count limit nor
// the client state.
RecoveryModeInsecure = "insecure"
)

// RecoveryModes returns a list of all supported recovery modes
func RecoveryModes() []RecoveryMode {
return []RecoveryMode{
RecoveryModeStandard,
RecoveryModeRelaxed,
RecoveryModeInsecure,
}
}

// ChallengeDocument is a bound keypair challenge document. These documents are
// sent in JSON form to clients attempting to authenticate, and are expected to
// be sent back signed with the private counterpart of a known public key.
type ChallengeDocument struct {
*jwt.Claims

// Nonce is a secure random string, unique to a particular challenge
Nonce string `json:"nonce"`
}

// ChallengeValidator is used to issue and validate bound keypair challenges for
// a given public key.
type ChallengeValidator struct {
clock clockwork.Clock

subject string
clusterName string
publicKey crypto.PublicKey
}

// NewChallengeValidator creates a new challenge validation helper using the
// given subject, cluster name, and public key. Subjects are arbitrary but a
// public key ID is recommended.
func NewChallengeValidator(
subject string,
clusterName string,
publicKey crypto.PublicKey,
) (*ChallengeValidator, error) {
return &ChallengeValidator{
clock: clockwork.NewRealClock(),

subject: subject,
clusterName: clusterName,

// TODO: API design issue to consider when implementing rotation: the
// public key will change during rotation. Should a new validator be
// created, or can we design this better?
publicKey: publicKey,
}, nil
}

func (v *ChallengeValidator) IssueChallenge() (*ChallengeDocument, error) {
// Implementation note: these challenges are only ever sent to a single
// client once, and we expect a valid reply as the next exchange in the
// join ceremony. There is not an opportunity for reuse, multiple attempts,
// or for clients to select their own nonce, so we won't bother storing it.
nonce, err := utils.CryptoRandomHex(defaults.TokenLenBytes)
if err != nil {
return nil, trace.Wrap(err, "generating nonce")
}

return &ChallengeDocument{
Claims: &jwt.Claims{
Issuer: v.clusterName,
Audience: jwt.Audience{v.clusterName}, // the cluster is both the issuer and audience
NotBefore: jwt.NewNumericDate(v.clock.Now().Add(challengeNotBeforeOffset)),
IssuedAt: jwt.NewNumericDate(v.clock.Now()),
Expiry: jwt.NewNumericDate(v.clock.Now().Add(challengeExpiration)),
Subject: v.subject,
},
Nonce: nonce,
}, nil
}

// ValidateChallengeResponse validates a signed challenge document, ensuring the
// signature matches the requested public key, and that the claims pass JWT
// validation.
func (v *ChallengeValidator) ValidateChallengeResponse(issued *ChallengeDocument, compactResponse string) error {
token, err := jwt.ParseSigned(compactResponse)
if err != nil {
return trace.Wrap(err, "parsing signed response")
}

var document ChallengeDocument
if err := token.Claims(v.publicKey, &document); err != nil {
return trace.Wrap(err)
}

// Validate the challenge document claims per JWT rules.
const leeway time.Duration = time.Minute
if err := document.Claims.ValidateWithLeeway(jwt.Expected{
Issuer: v.clusterName,
Subject: v.subject,
Audience: jwt.Audience{v.clusterName},
Time: v.clock.Now(),
}, leeway); err != nil {
return trace.Wrap(err, "validating challenge claims")
}

// JWT validation won't check equality on the time fields, so we'll manually
// check them.
if !issued.Claims.IssuedAt.Time().Equal(document.Claims.IssuedAt.Time()) {
return trace.AccessDenied("invalid challenge document")
}
if !issued.Claims.Expiry.Time().Equal(document.Claims.Expiry.Time()) {
return trace.AccessDenied("invalid challenge document")
}
if !issued.Claims.NotBefore.Time().Equal(document.Claims.NotBefore.Time()) {
return trace.AccessDenied("invalid challenge document")
}

if subtle.ConstantTimeCompare([]byte(issued.Nonce), []byte(document.Nonce)) == 0 {
return trace.AccessDenied("invalid nonce")
}

return nil
}
Loading
Loading