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 330 331 332 333 334 335 336 337 338 339 340 341 342
|
package cautils
import (
"crypto"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/api"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/certificates/ca"
"github.com/smallstep/certificates/pki"
"github.com/smallstep/cli/crypto/keys"
"github.com/smallstep/cli/crypto/pemutil"
"github.com/smallstep/cli/crypto/x509util"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/flags"
"github.com/smallstep/cli/token"
"github.com/smallstep/cli/ui"
"github.com/smallstep/cli/utils"
"github.com/urfave/cli"
)
// CertificateFlow manages the flow to retrieve a new certificate.
type CertificateFlow struct {
offlineCA *OfflineCA
offline bool
}
// sharedContext is used to share information between commands.
var sharedContext = struct {
DisableCustomSANs bool
}{}
// NewCertificateFlow initializes a cli flow to get a new certificate.
func NewCertificateFlow(ctx *cli.Context) (*CertificateFlow, error) {
var err error
var offlineClient *OfflineCA
offline := ctx.Bool("offline")
if offline {
caConfig := ctx.String("ca-config")
if caConfig == "" {
return nil, errs.InvalidFlagValue(ctx, "ca-config", "", "")
}
offlineClient, err = NewOfflineCA(caConfig)
if err != nil {
return nil, err
}
}
return &CertificateFlow{
offlineCA: offlineClient,
offline: offline,
}, nil
}
// GetClient returns the client used to send requests to the CA.
func (f *CertificateFlow) GetClient(ctx *cli.Context, tok string, options ...ca.ClientOption) (CaClient, error) {
if f.offline {
return f.offlineCA, nil
}
// Create online client
root := ctx.String("root")
caURL, err := flags.ParseCaURLIfExists(ctx)
if err != nil {
return nil, err
}
jwt, err := token.ParseInsecure(tok)
if err != nil {
return nil, errors.Wrap(err, "error parsing flag '--token'")
}
// Prepare client for bootstrap or provisioning tokens
if len(jwt.Payload.SHA) > 0 && len(jwt.Payload.Audience) > 0 && strings.HasPrefix(strings.ToLower(jwt.Payload.Audience[0]), "http") {
if len(caURL) == 0 {
caURL = jwt.Payload.Audience[0]
}
options = append(options, ca.WithRootSHA256(jwt.Payload.SHA))
} else {
if len(caURL) == 0 {
return nil, errs.RequiredFlag(ctx, "ca-url")
}
if len(root) == 0 {
root = pki.GetRootCAPath()
if _, err := os.Stat(root); err != nil {
return nil, errs.RequiredFlag(ctx, "root")
}
}
options = append(options, ca.WithRootFile(root))
}
ui.PrintSelected("CA", caURL)
return ca.NewClient(caURL, options...)
}
// GenerateToken generates a token for immediate use (therefore only default
// validity values will be used). The token is generated either with the offline
// token flow or the online mode.
func (f *CertificateFlow) GenerateToken(ctx *cli.Context, subject string, sans []string) (string, error) {
if f.offline {
return f.offlineCA.GenerateToken(ctx, SignType, subject, sans, time.Time{}, time.Time{}, provisioner.TimeDuration{}, provisioner.TimeDuration{})
}
// Use online CA to get the provisioners and generate the token
caURL, err := flags.ParseCaURLIfExists(ctx)
if err != nil {
return "", err
} else if len(caURL) == 0 {
return "", errs.RequiredUnlessFlag(ctx, "ca-url", "token")
}
root := ctx.String("root")
if len(root) == 0 {
root = pki.GetRootCAPath()
if _, err := os.Stat(root); err != nil {
return "", errs.RequiredUnlessFlag(ctx, "root", "token")
}
}
if subject == "" {
subject, err = ui.Prompt("What DNS names or IP addresses would you like to use? (e.g. internal.smallstep.com)", ui.WithValidateNotEmpty())
if err != nil {
return "", err
}
}
return NewTokenFlow(ctx, SignType, subject, sans, caURL, root, time.Time{}, time.Time{}, provisioner.TimeDuration{}, provisioner.TimeDuration{})
}
// GenerateSSHToken generates a token used to authorize the sign of an SSH
// certificate.
func (f *CertificateFlow) GenerateSSHToken(ctx *cli.Context, subject string, typ int, principals []string, validAfter, validBefore provisioner.TimeDuration) (string, error) {
if f.offline {
return f.offlineCA.GenerateToken(ctx, typ, subject, principals, time.Time{}, time.Time{}, validAfter, validBefore)
}
// Use online CA to get the provisioners and generate the token
caURL, err := flags.ParseCaURLIfExists(ctx)
if err != nil {
return "", err
} else if len(caURL) == 0 {
return "", errs.RequiredUnlessFlag(ctx, "ca-url", "token")
}
root := ctx.String("root")
if len(root) == 0 {
root = pki.GetRootCAPath()
if _, err := os.Stat(root); err != nil {
return "", errs.RequiredUnlessFlag(ctx, "root", "token")
}
}
if subject == "" {
subject, err = ui.Prompt("What DNS names or IP addresses would you like to use? (e.g. internal.smallstep.com)", ui.WithValidateNotEmpty())
if err != nil {
return "", err
}
}
return NewTokenFlow(ctx, typ, subject, principals, caURL, root, time.Time{}, time.Time{}, validAfter, validBefore)
}
// GenerateIdentityToken generates a token using only an OIDC provisioner.
func (f *CertificateFlow) GenerateIdentityToken(ctx *cli.Context) (string, error) {
caURL, err := flags.ParseCaURL(ctx)
if err != nil {
return "", err
}
root := ctx.String("root")
if len(root) == 0 {
root = pki.GetRootCAPath()
if _, err := os.Stat(root); err != nil {
return "", errs.RequiredFlag(ctx, "root")
}
}
return NewIdentityTokenFlow(ctx, caURL, root)
}
// Sign signs the CSR using the online or the offline certificate authority.
func (f *CertificateFlow) Sign(ctx *cli.Context, token string, csr api.CertificateRequest, crtFile string) error {
client, err := f.GetClient(ctx, token)
if err != nil {
return err
}
// parse times or durations
notBefore, notAfter, err := flags.ParseTimeDuration(ctx)
if err != nil {
return err
}
// parse template data
templateData, err := flags.ParseTemplateData(ctx)
if err != nil {
return err
}
req := &api.SignRequest{
CsrPEM: csr,
OTT: token,
NotBefore: notBefore,
NotAfter: notAfter,
TemplateData: templateData,
}
resp, err := client.Sign(req)
if err != nil {
return err
}
if resp.CertChainPEM == nil || len(resp.CertChainPEM) == 0 {
resp.CertChainPEM = []api.Certificate{resp.ServerPEM, resp.CaPEM}
}
var data []byte
for _, certPEM := range resp.CertChainPEM {
pemblk, err := pemutil.Serialize(certPEM.Certificate)
if err != nil {
return errors.Wrap(err, "error serializing from step-ca API response")
}
data = append(data, pem.EncodeToMemory(pemblk)...)
}
return utils.WriteFile(crtFile, data, 0600)
}
// CreateSignRequest is a helper function that given an x509 OTT returns a
// simple but secure sign request as well as the private key used.
func (f *CertificateFlow) CreateSignRequest(ctx *cli.Context, tok, subject string, sans []string) (*api.SignRequest, crypto.PrivateKey, error) {
jwt, err := token.ParseInsecure(tok)
if err != nil {
return nil, nil, err
}
kty, crv, size, err := utils.GetKeyDetailsFromCLI(ctx, false, "kty", "curve", "size")
if err != nil {
return nil, nil, err
}
pk, err := keys.GenerateKey(kty, crv, size)
if err != nil {
return nil, nil, err
}
dnsNames, ips, emails, uris := splitSANs(sans, jwt.Payload.SANs)
switch jwt.Payload.Type() {
case token.AWS:
doc := jwt.Payload.Amazon.InstanceIdentityDocument
if len(ips) == 0 && len(dnsNames) == 0 {
defaultSANs := []string{
doc.PrivateIP,
fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region),
}
if !sharedContext.DisableCustomSANs {
defaultSANs = append(defaultSANs, subject)
}
dnsNames, ips, emails, uris = splitSANs(defaultSANs)
}
case token.GCP:
ce := jwt.Payload.Google.ComputeEngine
if len(ips) == 0 && len(dnsNames) == 0 {
defaultSANs := []string{
fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID),
fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID),
}
if !sharedContext.DisableCustomSANs {
defaultSANs = append(defaultSANs, subject)
}
dnsNames, ips, emails, uris = splitSANs(defaultSANs)
}
case token.Azure:
if len(ips) == 0 && len(dnsNames) == 0 {
defaultSANs := []string{
jwt.Payload.Azure.VirtualMachine,
}
if !sharedContext.DisableCustomSANs {
defaultSANs = append(defaultSANs, subject)
}
dnsNames, ips, emails, uris = splitSANs(defaultSANs)
}
case token.OIDC:
if jwt.Payload.Email != "" {
emails = append(emails, jwt.Payload.Email)
}
subject = jwt.Payload.Subject
case token.K8sSA:
// Use subject from command line. K8sSA tokens are multi-use so the
// subject of the token is not necessarily related to the requested
// resource.
default: // Use common name in the token
subject = jwt.Payload.Subject
}
template := &x509.CertificateRequest{
Subject: pkix.Name{
CommonName: subject,
},
DNSNames: dnsNames,
IPAddresses: ips,
EmailAddresses: emails,
URIs: uris,
}
csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
if err != nil {
return nil, nil, errors.Wrap(err, "error creating certificate request")
}
cr, err := x509.ParseCertificateRequest(csr)
if err != nil {
return nil, nil, errors.Wrap(err, "error parsing certificate request")
}
if err := cr.CheckSignature(); err != nil {
return nil, nil, errors.Wrap(err, "error signing certificate request")
}
return &api.SignRequest{
CsrPEM: api.CertificateRequest{CertificateRequest: cr},
OTT: tok,
}, pk, nil
}
// splitSANs unifies the SAN collections passed as arguments and returns a list
// of DNS names, a list of IP addresses, and a list of emails.
func splitSANs(args ...[]string) (dnsNames []string, ipAddresses []net.IP, email []string, uris []*url.URL) {
m := make(map[string]bool)
var unique []string
for _, sans := range args {
for _, san := range sans {
if ok := m[san]; !ok {
m[san] = true
unique = append(unique, san)
}
}
}
return x509util.SplitSANs(unique)
}
|