2016-07-26 01:30:28 +05:30
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2017-03-09 00:03:19 +05:30
|
|
|
"context"
|
2016-07-26 01:30:28 +05:30
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"encoding/hex"
|
2017-07-19 22:49:20 +05:30
|
|
|
"errors"
|
2016-07-26 01:30:28 +05:30
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"gopkg.in/square/go-jose.v2"
|
|
|
|
|
2019-02-22 17:49:23 +05:30
|
|
|
"github.com/dexidp/dex/pkg/log"
|
2018-09-03 12:14:44 +05:30
|
|
|
"github.com/dexidp/dex/storage"
|
2016-07-26 01:30:28 +05:30
|
|
|
)
|
|
|
|
|
2017-07-19 22:49:20 +05:30
|
|
|
var errAlreadyRotated = errors.New("keys already rotated by another server instance")
|
|
|
|
|
2016-07-26 01:30:28 +05:30
|
|
|
// rotationStrategy describes a strategy for generating cryptographic keys, how
|
|
|
|
// often to rotate them, and how long they can validate signatures after rotation.
|
|
|
|
type rotationStrategy struct {
|
|
|
|
// Time between rotations.
|
2016-10-17 23:25:05 +05:30
|
|
|
rotationFrequency time.Duration
|
2016-07-26 01:30:28 +05:30
|
|
|
|
2017-03-02 01:33:28 +05:30
|
|
|
// After being rotated how long should the key be kept around for validating
|
2020-12-20 08:31:59 +05:30
|
|
|
// signatures?
|
2017-03-02 01:33:28 +05:30
|
|
|
idTokenValidFor time.Duration
|
2016-07-26 01:30:28 +05:30
|
|
|
|
|
|
|
// Keys are always RSA keys. Though cryptopasta recommends ECDSA keys, not every
|
|
|
|
// client may support these (e.g. github.com/coreos/go-oidc/oidc).
|
|
|
|
key func() (*rsa.PrivateKey, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// staticRotationStrategy returns a strategy which never rotates keys.
|
|
|
|
func staticRotationStrategy(key *rsa.PrivateKey) rotationStrategy {
|
|
|
|
return rotationStrategy{
|
|
|
|
// Setting these values to 100 years is easier than having a flag indicating no rotation.
|
2016-10-17 23:25:05 +05:30
|
|
|
rotationFrequency: time.Hour * 8760 * 100,
|
2017-03-02 01:33:28 +05:30
|
|
|
idTokenValidFor: time.Hour * 8760 * 100,
|
2016-10-17 23:25:05 +05:30
|
|
|
key: func() (*rsa.PrivateKey, error) { return key, nil },
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// defaultRotationStrategy returns a strategy which rotates keys every provided period,
|
|
|
|
// holding onto the public parts for some specified amount of time.
|
2017-03-02 01:33:28 +05:30
|
|
|
func defaultRotationStrategy(rotationFrequency, idTokenValidFor time.Duration) rotationStrategy {
|
2016-07-26 01:30:28 +05:30
|
|
|
return rotationStrategy{
|
2016-10-17 23:25:05 +05:30
|
|
|
rotationFrequency: rotationFrequency,
|
2017-03-02 01:33:28 +05:30
|
|
|
idTokenValidFor: idTokenValidFor,
|
2016-07-26 01:30:28 +05:30
|
|
|
key: func() (*rsa.PrivateKey, error) {
|
|
|
|
return rsa.GenerateKey(rand.Reader, 2048)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-20 08:31:56 +05:30
|
|
|
type keyRotator struct {
|
2016-07-26 01:30:28 +05:30
|
|
|
storage.Storage
|
|
|
|
|
|
|
|
strategy rotationStrategy
|
2016-10-13 07:21:32 +05:30
|
|
|
now func() time.Time
|
2016-12-13 04:24:01 +05:30
|
|
|
|
2019-02-22 17:49:23 +05:30
|
|
|
logger log.Logger
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
2016-10-13 07:21:32 +05:30
|
|
|
// startKeyRotation begins key rotation in a new goroutine, closing once the context is canceled.
|
|
|
|
//
|
|
|
|
// The method blocks until after the first attempt to rotate keys has completed. That way
|
|
|
|
// healthy storages will return from this call with valid keys.
|
2016-12-13 04:24:01 +05:30
|
|
|
func (s *Server) startKeyRotation(ctx context.Context, strategy rotationStrategy, now func() time.Time) {
|
2020-12-20 08:31:56 +05:30
|
|
|
rotator := keyRotator{s.storage, strategy, now, s.logger}
|
2016-07-26 01:30:28 +05:30
|
|
|
|
2016-10-13 07:21:32 +05:30
|
|
|
// Try to rotate immediately so properly configured storages will have keys.
|
2020-12-20 08:31:56 +05:30
|
|
|
if err := rotator.rotate(); err != nil {
|
2017-07-19 22:49:20 +05:30
|
|
|
if err == errAlreadyRotated {
|
|
|
|
s.logger.Infof("Key rotation not needed: %v", err)
|
|
|
|
} else {
|
|
|
|
s.logger.Errorf("failed to rotate keys: %v", err)
|
|
|
|
}
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
2016-10-13 07:21:32 +05:30
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
2016-10-17 23:17:47 +05:30
|
|
|
case <-time.After(time.Second * 30):
|
2020-12-20 08:31:56 +05:30
|
|
|
if err := rotator.rotate(); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to rotate keys: %v", err)
|
2016-10-13 07:21:32 +05:30
|
|
|
}
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2020-12-20 08:31:56 +05:30
|
|
|
func (k keyRotator) rotate() error {
|
2016-07-26 01:30:28 +05:30
|
|
|
keys, err := k.GetKeys()
|
|
|
|
if err != nil && err != storage.ErrNotFound {
|
|
|
|
return fmt.Errorf("get keys: %v", err)
|
|
|
|
}
|
|
|
|
if k.now().Before(keys.NextRotation) {
|
|
|
|
return nil
|
|
|
|
}
|
2016-12-13 04:24:01 +05:30
|
|
|
k.logger.Infof("keys expired, rotating")
|
2016-07-26 01:30:28 +05:30
|
|
|
|
|
|
|
// Generate the key outside of a storage transaction.
|
|
|
|
key, err := k.strategy.key()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("generate key: %v", err)
|
|
|
|
}
|
|
|
|
b := make([]byte, 20)
|
|
|
|
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
keyID := hex.EncodeToString(b)
|
|
|
|
priv := &jose.JSONWebKey{
|
|
|
|
Key: key,
|
|
|
|
KeyID: keyID,
|
|
|
|
Algorithm: "RS256",
|
|
|
|
Use: "sig",
|
|
|
|
}
|
|
|
|
pub := &jose.JSONWebKey{
|
|
|
|
Key: key.Public(),
|
|
|
|
KeyID: keyID,
|
|
|
|
Algorithm: "RS256",
|
|
|
|
Use: "sig",
|
|
|
|
}
|
|
|
|
|
|
|
|
var nextRotation time.Time
|
|
|
|
err = k.Storage.UpdateKeys(func(keys storage.Keys) (storage.Keys, error) {
|
|
|
|
tNow := k.now()
|
2017-04-11 23:18:08 +05:30
|
|
|
|
|
|
|
// if you are running multiple instances of dex, another instance
|
|
|
|
// could have already rotated the keys.
|
2016-07-26 01:30:28 +05:30
|
|
|
if tNow.Before(keys.NextRotation) {
|
2017-07-19 22:49:20 +05:30
|
|
|
return storage.Keys{}, errAlreadyRotated
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
2017-03-02 01:33:28 +05:30
|
|
|
expired := func(key storage.VerificationKey) bool {
|
|
|
|
return tNow.After(key.Expiry)
|
|
|
|
}
|
2017-01-10 00:16:16 +05:30
|
|
|
|
2017-03-02 01:33:28 +05:30
|
|
|
// Remove any verification keys that have expired.
|
|
|
|
i := 0
|
2016-07-26 01:30:28 +05:30
|
|
|
for _, key := range keys.VerificationKeys {
|
2017-03-02 01:33:28 +05:30
|
|
|
if !expired(key) {
|
2016-07-26 01:30:28 +05:30
|
|
|
keys.VerificationKeys[i] = key
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
keys.VerificationKeys = keys.VerificationKeys[:i]
|
|
|
|
|
|
|
|
if keys.SigningKeyPub != nil {
|
2017-03-02 01:33:28 +05:30
|
|
|
// Move current signing key to a verification only key, throwing
|
|
|
|
// away the private part.
|
2016-07-26 01:30:28 +05:30
|
|
|
verificationKey := storage.VerificationKey{
|
|
|
|
PublicKey: keys.SigningKeyPub,
|
2017-03-02 01:33:28 +05:30
|
|
|
// After demoting the signing key, keep the token around for at least
|
|
|
|
// the amount of time an ID Token is valid for. This ensures the
|
|
|
|
// verification key won't expire until all ID Tokens it's signed
|
|
|
|
// expired as well.
|
|
|
|
Expiry: tNow.Add(k.strategy.idTokenValidFor),
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
keys.VerificationKeys = append(keys.VerificationKeys, verificationKey)
|
|
|
|
}
|
|
|
|
|
2016-10-17 23:25:05 +05:30
|
|
|
nextRotation = k.now().Add(k.strategy.rotationFrequency)
|
2016-07-26 01:30:28 +05:30
|
|
|
keys.SigningKey = priv
|
|
|
|
keys.SigningKeyPub = pub
|
|
|
|
keys.NextRotation = nextRotation
|
|
|
|
return keys, nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-12-13 04:24:01 +05:30
|
|
|
k.logger.Infof("keys rotated, next rotation: %s", nextRotation)
|
2016-07-26 01:30:28 +05:30
|
|
|
return nil
|
|
|
|
}
|
2020-10-28 11:56:34 +05:30
|
|
|
|
|
|
|
type RefreshTokenPolicy struct {
|
|
|
|
rotateRefreshTokens bool // enable rotation
|
|
|
|
|
|
|
|
absoluteLifetime time.Duration // interval from token creation to the end of its life
|
|
|
|
validIfNotUsedFor time.Duration // interval from last token update to the end of its life
|
|
|
|
reuseInterval time.Duration // interval within which old refresh token is allowed to be reused
|
|
|
|
|
2020-11-15 23:56:34 +05:30
|
|
|
now func() time.Time
|
2020-10-28 11:56:34 +05:30
|
|
|
|
|
|
|
logger log.Logger
|
|
|
|
}
|
|
|
|
|
2020-11-15 23:56:34 +05:30
|
|
|
func NewRefreshTokenPolicy(logger log.Logger, rotation bool, validIfNotUsedFor, absoluteLifetime, reuseInterval string) (*RefreshTokenPolicy, error) {
|
|
|
|
r := RefreshTokenPolicy{now: time.Now, logger: logger}
|
2020-10-28 11:56:34 +05:30
|
|
|
var err error
|
|
|
|
|
|
|
|
if validIfNotUsedFor != "" {
|
|
|
|
r.validIfNotUsedFor, err = time.ParseDuration(validIfNotUsedFor)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid config value %q for refresh token valid if not used for: %v", validIfNotUsedFor, err)
|
|
|
|
}
|
|
|
|
logger.Infof("config refresh tokens valid if not used for: %v", validIfNotUsedFor)
|
|
|
|
}
|
|
|
|
|
|
|
|
if absoluteLifetime != "" {
|
|
|
|
r.absoluteLifetime, err = time.ParseDuration(absoluteLifetime)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid config value %q for refresh tokens absolute lifetime: %v", absoluteLifetime, err)
|
|
|
|
}
|
|
|
|
logger.Infof("config refresh tokens absolute lifetime: %v", absoluteLifetime)
|
|
|
|
}
|
|
|
|
|
|
|
|
if reuseInterval != "" {
|
|
|
|
r.reuseInterval, err = time.ParseDuration(reuseInterval)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid config value %q for refresh tokens reuse interval: %v", reuseInterval, err)
|
|
|
|
}
|
|
|
|
logger.Infof("config refresh tokens reuse interval: %v", reuseInterval)
|
|
|
|
}
|
|
|
|
|
|
|
|
r.rotateRefreshTokens = !rotation
|
|
|
|
logger.Infof("config refresh tokens rotation enabled: %v", r.rotateRefreshTokens)
|
|
|
|
return &r, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RefreshTokenPolicy) RotationEnabled() bool {
|
|
|
|
return r.rotateRefreshTokens
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RefreshTokenPolicy) CompletelyExpired(lastUsed time.Time) bool {
|
|
|
|
if r.absoluteLifetime == 0 {
|
|
|
|
return false // expiration disabled
|
|
|
|
}
|
2020-11-15 23:56:34 +05:30
|
|
|
return r.now().After(lastUsed.Add(r.absoluteLifetime))
|
2020-10-28 11:56:34 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RefreshTokenPolicy) ExpiredBecauseUnused(lastUsed time.Time) bool {
|
|
|
|
if r.validIfNotUsedFor == 0 {
|
|
|
|
return false // expiration disabled
|
|
|
|
}
|
2020-11-15 23:56:34 +05:30
|
|
|
return r.now().After(lastUsed.Add(r.validIfNotUsedFor))
|
2020-10-28 11:56:34 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RefreshTokenPolicy) AllowedToReuse(lastUsed time.Time) bool {
|
|
|
|
if r.reuseInterval == 0 {
|
|
|
|
return false // expiration disabled
|
|
|
|
}
|
2020-11-15 23:56:34 +05:30
|
|
|
return !r.now().After(lastUsed.Add(r.reuseInterval))
|
2020-10-28 11:56:34 +05:30
|
|
|
}
|