Add tests for SSH certs with JWK provisioners.

This commit is contained in:
Mariano Cano 2019-07-30 18:23:54 -07:00
parent 780eeb5487
commit b0240772da
2 changed files with 321 additions and 4 deletions

View file

@ -2,14 +2,17 @@ package provisioner
import ( import (
"context" "context"
"crypto"
"crypto/x509" "crypto/x509"
"errors" "errors"
"math"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/smallstep/assert" "github.com/smallstep/assert"
"github.com/smallstep/cli/jose" "github.com/smallstep/cli/jose"
"golang.org/x/crypto/ssh"
) )
var ( var (
@ -19,6 +22,12 @@ var (
MaxTLSDur: &Duration{24 * time.Hour}, MaxTLSDur: &Duration{24 * time.Hour},
DefaultTLSDur: &Duration{24 * time.Hour}, DefaultTLSDur: &Duration{24 * time.Hour},
DisableRenewal: &defaultDisableRenewal, DisableRenewal: &defaultDisableRenewal,
MinUserSSHDur: &Duration{Duration: 5 * time.Minute}, // User SSH certs
MaxUserSSHDur: &Duration{Duration: 24 * time.Hour},
DefaultUserSSHDur: &Duration{Duration: 4 * time.Hour},
MinHostSSHDur: &Duration{Duration: 5 * time.Minute}, // Host SSH certs
MaxHostSSHDur: &Duration{Duration: 30 * 24 * time.Hour},
DefaultHostSSHDur: &Duration{Duration: 30 * 24 * time.Hour},
} }
) )
@ -320,3 +329,179 @@ func TestJWK_AuthorizeRenewal(t *testing.T) {
}) })
} }
} }
func TestJWK_AuthorizeSign_SSH(t *testing.T) {
p1, err := generateJWK()
assert.FatalError(t, err)
jwk, err := decryptJSONWebKey(p1.EncryptedKey)
assert.FatalError(t, err)
iss, aud := p1.Name, testAudiences.Sign[0]
t1, err := generateSimpleSSHUserToken(iss, aud, jwk)
assert.FatalError(t, err)
t2, err := generateSimpleSSHHostToken(iss, aud, jwk)
assert.FatalError(t, err)
// invalid signature
failSig := t1[0 : len(t1)-2]
key, err := generateJSONWebKey()
assert.FatalError(t, err)
signer, err := generateJSONWebKey()
assert.FatalError(t, err)
type args struct {
token string
}
type expected struct {
certType uint32
principals []string
}
tests := []struct {
name string
prov *JWK
args args
expected expected
err error
}{
{"ok-user", p1, args{t1}, expected{ssh.UserCert, []string{"name"}}, nil},
{"ok-host", p1, args{t2}, expected{ssh.HostCert, []string{"smallstep.com"}}, nil},
{"fail-signature", p1, args{failSig}, expected{}, errors.New("error parsing claims: square/go-jose: error in cryptographic primitive")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := NewContextWithMethod(context.Background(), SignSSHMethod)
if got, err := tt.prov.AuthorizeSign(ctx, tt.args.token); err != nil {
if assert.NotNil(t, tt.err) {
assert.HasPrefix(t, err.Error(), tt.err.Error())
}
} else if assert.NotNil(t, got) {
cert, err := signSSHCertificate(key.Public().Key, SSHOptions{}, got, signer.Key.(crypto.Signer))
assert.FatalError(t, err)
assert.NotNil(t, cert.Signature)
assert.Equals(t, tt.expected.certType, cert.CertType)
assert.Equals(t, tt.expected.principals, cert.ValidPrincipals)
if cert.CertType == ssh.UserCert {
assert.Len(t, 5, cert.Extensions)
} else {
assert.Nil(t, cert.Extensions)
}
}
})
}
}
func TestJWK_AuthorizeSign_SSHOptions(t *testing.T) {
p1, err := generateJWK()
assert.FatalError(t, err)
jwk, err := decryptJSONWebKey(p1.EncryptedKey)
assert.FatalError(t, err)
userDuration := p1.claimer.DefaultUserSSHCertDuration()
hostDuration := p1.claimer.DefaultHostSSHCertDuration()
now := time.Now()
sub, iss, aud := "subject@smallstep.com", p1.Name, testAudiences.Sign[0]
iat := now
key, err := generateJSONWebKey()
assert.FatalError(t, err)
signer, err := generateJSONWebKey()
assert.FatalError(t, err)
type args struct {
sub, iss, aud string
iat time.Time
tokSSHOpts *SSHOptions
userSSHOpts *SSHOptions
jwk *jose.JSONWebKey
}
type expected struct {
certType uint32
principals []string
validAfter time.Time
validBefore time.Time
}
tests := []struct {
name string
prov *JWK
args args
expected expected
wantErr bool
wantSignErr bool
}{
{"ok-user", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, expected{ssh.UserCert, []string{"name"}, now, now.Add(userDuration)}, false, false},
{"ok-host", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "host", Principals: []string{"smallstep.com"}}, &SSHOptions{}, jwk}, expected{ssh.HostCert, []string{"smallstep.com"}, now, now.Add(hostDuration)}, false, false},
{"ok-user-opts", p1, args{sub, iss, aud, iat, &SSHOptions{}, &SSHOptions{CertType: "user", Principals: []string{"name"}}, jwk}, expected{ssh.UserCert, []string{"name"}, now, now.Add(userDuration)}, false, false},
{"ok-host-opts", p1, args{sub, iss, aud, iat, &SSHOptions{}, &SSHOptions{CertType: "host", Principals: []string{"smallstep.com"}}, jwk}, expected{ssh.HostCert, []string{"smallstep.com"}, now, now.Add(hostDuration)}, false, false},
{"ok-user-mixed", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user"}, &SSHOptions{Principals: []string{"name"}}, jwk}, expected{ssh.UserCert, []string{"name"}, now, now.Add(userDuration)}, false, false},
{"ok-host-mixed", p1, args{sub, iss, aud, iat, &SSHOptions{Principals: []string{"smallstep.com"}}, &SSHOptions{CertType: "host"}, jwk}, expected{ssh.HostCert, []string{"smallstep.com"}, now, now.Add(hostDuration)}, false, false},
{"ok-user-validAfter", p1, args{sub, iss, aud, iat, &SSHOptions{
CertType: "user", Principals: []string{"name"},
}, &SSHOptions{
ValidAfter: NewTimeDuration(now.Add(-time.Hour)),
}, jwk}, expected{ssh.UserCert, []string{"name"}, now.Add(-time.Hour), now.Add(userDuration - time.Hour)}, false, false},
{"ok-user-validBefore", p1, args{sub, iss, aud, iat, &SSHOptions{
CertType: "user", Principals: []string{"name"},
}, &SSHOptions{
ValidBefore: NewTimeDuration(now.Add(time.Hour)),
}, jwk}, expected{ssh.UserCert, []string{"name"}, now, now.Add(time.Hour)}, false, false},
{"ok-user-validAfter-validBefore", p1, args{sub, iss, aud, iat, &SSHOptions{
CertType: "user", Principals: []string{"name"},
}, &SSHOptions{
ValidAfter: NewTimeDuration(now.Add(10 * time.Minute)), ValidBefore: NewTimeDuration(now.Add(time.Hour)),
}, jwk}, expected{ssh.UserCert, []string{"name"}, now.Add(10 * time.Minute), now.Add(time.Hour)}, false, false},
{"ok-user-match", p1, args{sub, iss, aud, iat, &SSHOptions{
CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(now), ValidBefore: NewTimeDuration(now.Add(1 * time.Hour)),
}, &SSHOptions{
CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(now), ValidBefore: NewTimeDuration(now.Add(1 * time.Hour)),
}, jwk}, expected{ssh.UserCert, []string{"name"}, now, now.Add(1 * time.Hour)}, false, false},
{"fail-certType", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{CertType: "host"}, jwk}, expected{}, false, true},
{"fail-principals", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{Principals: []string{"root"}}, jwk}, expected{}, false, true},
{"fail-validAfter", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(now)}, &SSHOptions{ValidAfter: NewTimeDuration(now.Add(time.Hour))}, jwk}, expected{}, false, true},
{"fail-validBefore", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}, ValidBefore: NewTimeDuration(now.Add(time.Hour))}, &SSHOptions{ValidBefore: NewTimeDuration(now.Add(10 * time.Hour))}, jwk}, expected{}, false, true},
{"fail-subject", p1, args{"", iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, expected{}, true, false},
{"fail-issuer", p1, args{sub, "invalid", aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, expected{}, true, false},
{"fail-audience", p1, args{sub, iss, "invalid", iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, expected{}, true, false},
{"fail-expired", p1, args{sub, iss, aud, iat.Add(-6 * time.Minute), &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, expected{}, true, false},
{"fail-notBefore", p1, args{sub, iss, aud, iat.Add(5 * time.Minute), &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, expected{}, true, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := NewContextWithMethod(context.Background(), SignSSHMethod)
token, err := generateSSHToken(tt.args.sub, tt.args.iss, tt.args.aud, tt.args.iat, tt.args.tokSSHOpts, tt.args.jwk)
assert.FatalError(t, err)
if got, err := tt.prov.AuthorizeSign(ctx, token); (err != nil) != tt.wantErr {
t.Errorf("JWK.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr)
} else if !tt.wantErr && assert.NotNil(t, got) {
var opts SSHOptions
if tt.args.userSSHOpts != nil {
opts = *tt.args.userSSHOpts
}
if cert, err := signSSHCertificate(key.Public().Key, opts, got, signer.Key.(crypto.Signer)); (err != nil) != tt.wantSignErr {
t.Errorf("SignSSH error = %v, wantSignErr %v", err, tt.wantSignErr)
} else if !tt.wantSignErr && assert.NotNil(t, cert) {
assert.NotNil(t, cert.Signature)
assert.NotNil(t, cert.SignatureKey)
assert.Equals(t, tt.expected.certType, cert.CertType)
assert.Equals(t, tt.expected.principals, cert.ValidPrincipals)
assert.True(t, equalsUint64Delta(uint64(tt.expected.validAfter.Unix()), cert.ValidAfter, 60))
assert.True(t, equalsUint64Delta(uint64(tt.expected.validBefore.Unix()), cert.ValidBefore, 60))
if cert.CertType == ssh.UserCert {
assert.Len(t, 5, cert.Extensions)
} else {
assert.Nil(t, cert.Extensions)
}
}
}
})
}
}
func equalsUint64Delta(a, b uint64, delta uint64) bool {
return math.Abs(float64(a)-float64(b)) <= float64(delta)
}

View file

@ -14,6 +14,8 @@ import (
"net/http/httptest" "net/http/httptest"
"time" "time"
"golang.org/x/crypto/ssh"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/smallstep/cli/crypto/randutil" "github.com/smallstep/cli/crypto/randutil"
"github.com/smallstep/cli/jose" "github.com/smallstep/cli/jose"
@ -480,6 +482,54 @@ func generateToken(sub, iss, aud string, email string, sans []string, iat time.T
return jose.Signed(sig).Claims(claims).CompactSerialize() return jose.Signed(sig).Claims(claims).CompactSerialize()
} }
func generateSimpleSSHUserToken(iss, aud string, jwk *jose.JSONWebKey) (string, error) {
return generateSSHToken("subject@localhost", iss, aud, time.Now(), &SSHOptions{
CertType: "user",
Principals: []string{"name"},
}, jwk)
}
func generateSimpleSSHHostToken(iss, aud string, jwk *jose.JSONWebKey) (string, error) {
return generateSSHToken("subject@localhost", iss, aud, time.Now(), &SSHOptions{
CertType: "host",
Principals: []string{"smallstep.com"},
}, jwk)
}
func generateSSHToken(sub, iss, aud string, iat time.Time, sshOpts *SSHOptions, jwk *jose.JSONWebKey) (string, error) {
sig, err := jose.NewSigner(
jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
new(jose.SignerOptions).WithType("JWT").WithHeader("kid", jwk.KeyID),
)
if err != nil {
return "", err
}
id, err := randutil.ASCII(64)
if err != nil {
return "", err
}
claims := struct {
jose.Claims
Step *stepPayload `json:"step,omitempty"`
}{
Claims: jose.Claims{
ID: id,
Subject: sub,
Issuer: iss,
IssuedAt: jose.NewNumericDate(iat),
NotBefore: jose.NewNumericDate(iat),
Expiry: jose.NewNumericDate(iat.Add(5 * time.Minute)),
Audience: []string{aud},
},
Step: &stepPayload{
SSH: sshOpts,
},
}
return jose.Signed(sig).Claims(claims).CompactSerialize()
}
func generateGCPToken(sub, iss, aud, instanceID, instanceName, projectID, zone string, iat time.Time, jwk *jose.JSONWebKey) (string, error) { func generateGCPToken(sub, iss, aud, instanceID, instanceName, projectID, zone string, iat time.Time, jwk *jose.JSONWebKey) (string, error) {
sig, err := jose.NewSigner( sig, err := jose.NewSigner(
jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key}, jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
@ -682,3 +732,85 @@ func generateJWKServer(n int) *httptest.Server {
srv.Start() srv.Start()
return srv return srv
} }
func signSSHCertificate(key crypto.PublicKey, opts SSHOptions, signOpts []SignOption, signKey crypto.Signer) (*ssh.Certificate, error) {
pub, err := ssh.NewPublicKey(key)
if err != nil {
return nil, err
}
var mods []SSHCertificateModifier
var validators []SSHCertificateValidator
for _, op := range signOpts {
switch o := op.(type) {
// modify the ssh.Certificate
case SSHCertificateModifier:
mods = append(mods, o)
// modify the ssh.Certificate given the SSHOptions
case SSHCertificateOptionModifier:
mods = append(mods, o.Option(opts))
// validate the ssh.Certificate
case SSHCertificateValidator:
validators = append(validators, o)
// validate the given SSHOptions
case SSHCertificateOptionsValidator:
if err := o.Valid(opts); err != nil {
return nil, err
}
default:
return nil, errors.Errorf("signSSH: invalid extra option type %T", o)
}
}
// Build base certificate with the key and some random values
cert := &ssh.Certificate{
Nonce: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0},
Key: pub,
Serial: 1234567890,
}
// Use opts to modify the certificate
if err := opts.Modify(cert); err != nil {
return nil, err
}
// Use provisioner modifiers
for _, m := range mods {
if err := m.Modify(cert); err != nil {
return nil, err
}
}
// Get signer from authority keys
var signer ssh.Signer
switch cert.CertType {
case ssh.UserCert:
signer, err = ssh.NewSignerFromSigner(signKey)
case ssh.HostCert:
signer, err = ssh.NewSignerFromSigner(signKey)
default:
return nil, errors.Errorf("unexpected ssh certificate type: %d", cert.CertType)
}
cert.SignatureKey = signer.PublicKey()
// Get bytes for signing trailing the signature length.
data := cert.Marshal()
data = data[:len(data)-4]
// Sign the certificate
sig, err := signer.Sign(rand.Reader, data)
if err != nil {
return nil, err
}
cert.Signature = sig
// User provisioners validators
for _, v := range validators {
if err := v.Valid(cert); err != nil {
return nil, err
}
}
return cert, nil
}