1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
|
package cautils
import (
"crypto"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/certificates/pki"
"github.com/smallstep/cli/crypto/randutil"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/exec"
"github.com/smallstep/cli/jose"
"github.com/smallstep/cli/token"
"github.com/smallstep/cli/token/provision"
"github.com/smallstep/cli/ui"
"github.com/urfave/cli"
)
// TokenGenerator is a helper used to generate different types of tokens used in
// the CA.
type TokenGenerator struct {
kid, iss, aud string
root string
notBefore, notAfter time.Time
jwk *jose.JSONWebKey
}
// NewTokenGenerator initializes a new token generator with the common fields.
func NewTokenGenerator(kid, iss, aud, root string, notBefore, notAfter time.Time, jwk *jose.JSONWebKey) *TokenGenerator {
return &TokenGenerator{
kid: kid,
iss: iss,
aud: aud,
root: root,
notBefore: notBefore,
notAfter: notAfter,
jwk: jwk,
}
}
// Token generates a generic token with the given subject and options.
func (t *TokenGenerator) Token(sub string, opts ...token.Options) (string, error) {
// A random jwt id will be used to identify duplicated tokens
jwtID, err := randutil.Hex(64) // 256 bits
if err != nil {
return "", err
}
tokOptions := []token.Options{
token.WithJWTID(jwtID),
token.WithKid(t.kid),
token.WithIssuer(t.iss),
token.WithAudience(t.aud),
}
if len(t.root) > 0 {
tokOptions = append(tokOptions, token.WithRootCA(t.root))
}
// Add custom options
tokOptions = append(tokOptions, opts...)
// Add token validity
notBefore, notAfter := t.notBefore, t.notAfter
if !notBefore.IsZero() || !notAfter.IsZero() {
if notBefore.IsZero() {
notBefore = time.Now()
}
if notAfter.IsZero() {
notAfter = notBefore.Add(token.DefaultValidity)
}
tokOptions = append(tokOptions, token.WithValidity(notBefore, notAfter))
}
tok, err := provision.New(sub, tokOptions...)
if err != nil {
return "", err
}
return tok.SignedString(t.jwk.Algorithm, t.jwk.Key)
}
// SignToken generates a X.509 certificate signing token. If sans is empty, we
// will use the subject (common name) as the only SAN.
func (t *TokenGenerator) SignToken(sub string, sans []string, opts ...token.Options) (string, error) {
if len(sans) == 0 {
sans = []string{sub}
}
opts = append(opts, token.WithSANS(sans))
return t.Token(sub, opts...)
}
// RevokeToken generates a X.509 certificate revoke token.
func (t *TokenGenerator) RevokeToken(sub string, opts ...token.Options) (string, error) {
return t.Token(sub, opts...)
}
// SignSSHToken generates a SSH certificate signing token.
func (t *TokenGenerator) SignSSHToken(sub, certType string, principals []string, notBefore, notAfter provisioner.TimeDuration, opts ...token.Options) (string, error) {
opts = append([]token.Options{token.WithSSH(provisioner.SignSSHOptions{
CertType: certType,
KeyID: sub,
Principals: principals,
ValidAfter: notBefore,
ValidBefore: notAfter,
})}, opts...)
return t.Token(sub, opts...)
}
// generateOIDCToken performs the necessary protocol to retrieve an OIDC token
// using a configured provisioner.
func generateOIDCToken(ctx *cli.Context, p *provisioner.OIDC) (string, error) {
args := []string{"oauth", "--oidc", "--bare",
"--provider", p.ConfigurationEndpoint,
"--client-id", p.ClientID, "--client-secret", p.ClientSecret}
if ctx.Bool("console") {
args = append(args, "--console")
}
if p.ListenAddress != "" {
args = append(args, "--listen", p.ListenAddress)
}
out, err := exec.Step(args...)
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
type tokenAttrs struct {
subject string
root string
caURL string
audience string
issuer string
kid string
sans []string
notBefore, notAfter time.Time
certNotBefore, certNotAfter provisioner.TimeDuration
}
func generateK8sSAToken(ctx *cli.Context, p *provisioner.K8sSA) (string, error) {
path := ctx.String("k8ssa-token-path")
if len(path) == 0 {
path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
}
tokBytes, err := ioutil.ReadFile(path)
if err != nil {
return "", errors.Wrap(err, "error reading kubernetes service account token")
}
return string(tokBytes), nil
}
func generateX5CToken(ctx *cli.Context, p *provisioner.X5C, tokType int, tokAttrs tokenAttrs) (string, error) {
x5cCertFile := ctx.String("x5c-cert")
x5cKeyFile := ctx.String("x5c-key")
if len(x5cCertFile) == 0 {
return "", errs.RequiredWithProvisionerTypeFlag(ctx, "X5C", "x5c-cert")
}
if len(x5cKeyFile) == 0 {
return "", errs.RequiredWithProvisionerTypeFlag(ctx, "X5C", "x5c-key")
}
// Get private key from given key file
var opts []jose.Option
if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 {
opts = append(opts, jose.WithPasswordFile(passwordFile))
}
jwk, err := jose.ParseKey(x5cKeyFile, opts...)
if err != nil {
return "", err
}
tokenGen := NewTokenGenerator(jwk.KeyID, p.Name,
fmt.Sprintf("%s#%s", tokAttrs.audience, p.GetID()), tokAttrs.root,
tokAttrs.notBefore, tokAttrs.notAfter, jwk)
switch tokType {
case SignType:
return tokenGen.SignToken(tokAttrs.subject, tokAttrs.sans, token.WithX5CFile(x5cCertFile, jwk.Key))
case RevokeType:
return tokenGen.RevokeToken(tokAttrs.subject, token.WithX5CFile(x5cCertFile, jwk.Key))
case SSHUserSignType:
return tokenGen.SignSSHToken(tokAttrs.subject, provisioner.SSHUserCert, tokAttrs.sans,
tokAttrs.certNotBefore, tokAttrs.certNotAfter, token.WithX5CFile(x5cCertFile, jwk.Key))
case SSHHostSignType:
return tokenGen.SignSSHToken(tokAttrs.subject, provisioner.SSHHostCert, tokAttrs.sans,
tokAttrs.certNotBefore, tokAttrs.certNotAfter, token.WithX5CFile(x5cCertFile, jwk.Key))
default:
return tokenGen.Token(tokAttrs.subject, token.WithX5CFile(x5cCertFile, jwk.Key))
}
}
func generateSSHPOPToken(ctx *cli.Context, p *provisioner.SSHPOP, tokType int, tokAttrs tokenAttrs) (string, error) {
sshPOPCertFile := ctx.String("sshpop-cert")
sshPOPKeyFile := ctx.String("sshpop-key")
if len(sshPOPCertFile) == 0 {
return "", errs.RequiredWithProvisionerTypeFlag(ctx, "SSHPOP", "sshpop-cert")
}
if len(sshPOPKeyFile) == 0 {
return "", errs.RequiredWithProvisionerTypeFlag(ctx, "SSHPOP", "sshpop-key")
}
// Get private key from given key file
var opts []jose.Option
if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 {
opts = append(opts, jose.WithPasswordFile(passwordFile))
}
jwk, err := jose.ParseKey(sshPOPKeyFile, opts...)
if err != nil {
return "", err
}
tokenGen := NewTokenGenerator(jwk.KeyID, p.Name,
fmt.Sprintf("%s#%s", tokAttrs.audience, p.GetID()), tokAttrs.root,
tokAttrs.notBefore, tokAttrs.notAfter, jwk)
switch tokType {
case SSHRevokeType:
return tokenGen.Token(tokAttrs.subject, token.WithSSHPOPFile(sshPOPCertFile, jwk.Key))
case SSHRenewType:
return tokenGen.Token(tokAttrs.subject, token.WithSSHPOPFile(sshPOPCertFile, jwk.Key))
case SSHRekeyType:
return tokenGen.Token(tokAttrs.subject, token.WithSSHPOPFile(sshPOPCertFile, jwk.Key))
default:
return "", errors.Errorf("unexpected requested token type for SSHPOP token: %d", tokType)
}
}
// loadJWK loads a JWK based on the following system:
// 1. If a private key is specified on the command line, then load the JWK from
// that private key.
// 2. No private key was given on the command line. We'll need to use the
// provided provisioner to load a signing key.
// a) Offline-mode: load the JWK directly from the provisioner in the CA-config.
// b) Online-mode: get the provisioner private key from the CA.
func loadJWK(ctx *cli.Context, p *provisioner.JWK, tokAttrs tokenAttrs) (jwk *jose.JSONWebKey, kid string, err error) {
var opts []jose.Option
switch {
case ctx.String("provisioner-password-file") != "":
opts = append(opts, jose.WithPasswordFile(ctx.String("provisioner-password-file")))
case ctx.String("password-file") != "":
opts = append(opts, jose.WithPasswordFile(ctx.String("password-file")))
}
if keyFile := ctx.String("key"); len(keyFile) == 0 {
if p == nil {
return nil, "", errors.New("no provisioner selected")
}
kid = p.Key.KeyID
// If provisioner is not nil then we must be using the offlineCA.
var encryptedKey string
if ctx.IsSet("offline") {
encryptedKey = p.EncryptedKey
if len(encryptedKey) == 0 {
return nil, "", errors.Errorf("provisioner '%s' does not have an 'encryptedKey' property", kid)
}
} else {
// Get private key from CA.
encryptedKey, err = pki.GetProvisionerKey(tokAttrs.caURL, tokAttrs.root, kid)
if err != nil {
return nil, "", err
}
}
// Add template with check mark
opts = append(opts, jose.WithUIOptions(
ui.WithPromptTemplates(ui.PromptTemplates()),
))
decrypted, err := jose.Decrypt("Please enter the password to decrypt the provisioner key", []byte(encryptedKey), opts...)
if err != nil {
return nil, "", err
}
jwk = new(jose.JSONWebKey)
if err := json.Unmarshal(decrypted, jwk); err != nil {
return nil, "", errors.Wrap(err, "error unmarshalling provisioning key")
}
} else {
// Get private key from given key file
jwk, err = jose.ParseKey(keyFile, opts...)
if err != nil {
return nil, "", err
}
if p != nil {
kid = p.Key.KeyID
} else if len(tokAttrs.kid) > 0 {
kid = tokAttrs.kid
} else {
hash, err := jwk.Thumbprint(crypto.SHA256)
if err != nil {
return nil, "", errors.Wrap(err, "error generating JWK thumbprint")
}
kid = base64.RawURLEncoding.EncodeToString(hash)
}
}
return
}
func generateJWKToken(ctx *cli.Context, p *provisioner.JWK, tokType int, tokAttrs tokenAttrs) (string, error) {
jwk, kid, err := loadJWK(ctx, p, tokAttrs)
if err != nil {
return "", err
}
issuer := tokAttrs.issuer
if p != nil {
issuer = p.Name
}
// Generate token
tokenGen := NewTokenGenerator(kid, issuer, tokAttrs.audience, tokAttrs.root,
tokAttrs.notBefore, tokAttrs.notAfter, jwk)
switch tokType {
case SignType:
return tokenGen.SignToken(tokAttrs.subject, tokAttrs.sans)
case RevokeType:
return tokenGen.RevokeToken(tokAttrs.subject)
case SSHUserSignType:
return tokenGen.SignSSHToken(tokAttrs.subject, provisioner.SSHUserCert,
tokAttrs.sans, tokAttrs.certNotBefore, tokAttrs.certNotAfter)
case SSHHostSignType:
return tokenGen.SignSSHToken(tokAttrs.subject, provisioner.SSHHostCert,
tokAttrs.sans, tokAttrs.certNotBefore, tokAttrs.certNotAfter)
default:
return tokenGen.Token(tokAttrs.subject)
}
}
|