Debian Codegraph @

utils/cautils/certificate_flow.go

raw symbols SCIP
1 package cautils
2
3 import (
4 "crypto"
5 "crypto/rand"
6 "crypto/x509"
7 "crypto/x509/pkix"
8 "encoding/pem"
9 "fmt"
10 "net"
11 "net/url"
12 "os"
13 "strings"
14 "time"
15
16 "github.com/pkg/errors"
17 "github.com/smallstep/certificates/api"
18 "github.com/smallstep/certificates/authority/provisioner"
19 "github.com/smallstep/certificates/ca"
20 "github.com/smallstep/certificates/pki"
21 "github.com/smallstep/cli/crypto/keys"
22 "github.com/smallstep/cli/crypto/pemutil"
23 "github.com/smallstep/cli/crypto/x509util"
24 "github.com/smallstep/cli/errs"
25 "github.com/smallstep/cli/flags"
26 "github.com/smallstep/cli/token"
27 "github.com/smallstep/cli/ui"
28 "github.com/smallstep/cli/utils"
29 "github.com/urfave/cli"
30 )
31
32 // CertificateFlow manages the flow to retrieve a new certificate.
33 type CertificateFlow struct {
34 offlineCA *OfflineCA
35 offline bool
36 }
37
38 // sharedContext is used to share information between commands.
39 var sharedContext = struct {
40 DisableCustomSANs bool
41 }{}
42
43 // NewCertificateFlow initializes a cli flow to get a new certificate.
44 func NewCertificateFlow(ctx *cli.Context) (*CertificateFlow, error) {
45 var err error
46 var offlineClient *OfflineCA
47
48 offline := ctx.Bool("offline")
49 if offline {
50 caConfig := ctx.String("ca-config")
51 if caConfig == "" {
52 return nil, errs.InvalidFlagValue(ctx, "ca-config", "", "")
53 }
54 offlineClient, err = NewOfflineCA(caConfig)
55 if err != nil {
56 return nil, err
57 }
58 }
59
60 return &CertificateFlow{
61 offlineCA: offlineClient,
62 offline: offline,
63 }, nil
64 }
65
66 // GetClient returns the client used to send requests to the CA.
67 func (f *CertificateFlow) GetClient(ctx *cli.Context, tok string, options ...ca.ClientOption) (CaClient, error) {
68 if f.offline {
69 return f.offlineCA, nil
70 }
71
72 // Create online client
73 root := ctx.String("root")
74 caURL, err := flags.ParseCaURLIfExists(ctx)
75 if err != nil {
76 return nil, err
77 }
78
79 jwt, err := token.ParseInsecure(tok)
80 if err != nil {
81 return nil, errors.Wrap(err, "error parsing flag '--token'")
82 }
83 // Prepare client for bootstrap or provisioning tokens
84 if len(jwt.Payload.SHA) > 0 && len(jwt.Payload.Audience) > 0 && strings.HasPrefix(strings.ToLower(jwt.Payload.Audience[0]), "http") {
85 if len(caURL) == 0 {
86 caURL = jwt.Payload.Audience[0]
87 }
88 options = append(options, ca.WithRootSHA256(jwt.Payload.SHA))
89 } else {
90 if len(caURL) == 0 {
91 return nil, errs.RequiredFlag(ctx, "ca-url")
92 }
93 if len(root) == 0 {
94 root = pki.GetRootCAPath()
95 if _, err := os.Stat(root); err != nil {
96 return nil, errs.RequiredFlag(ctx, "root")
97 }
98 }
99 options = append(options, ca.WithRootFile(root))
100 }
101
102 ui.PrintSelected("CA", caURL)
103 return ca.NewClient(caURL, options...)
104 }
105
106 // GenerateToken generates a token for immediate use (therefore only default
107 // validity values will be used). The token is generated either with the offline
108 // token flow or the online mode.
109 func (f *CertificateFlow) GenerateToken(ctx *cli.Context, subject string, sans []string) (string, error) {
110 if f.offline {
111 return f.offlineCA.GenerateToken(ctx, SignType, subject, sans, time.Time{}, time.Time{}, provisioner.TimeDuration{}, provisioner.TimeDuration{})
112 }
113
114 // Use online CA to get the provisioners and generate the token
115 caURL, err := flags.ParseCaURLIfExists(ctx)
116 if err != nil {
117 return "", err
118 } else if len(caURL) == 0 {
119 return "", errs.RequiredUnlessFlag(ctx, "ca-url", "token")
120 }
121
122 root := ctx.String("root")
123 if len(root) == 0 {
124 root = pki.GetRootCAPath()
125 if _, err := os.Stat(root); err != nil {
126 return "", errs.RequiredUnlessFlag(ctx, "root", "token")
127 }
128 }
129
130 if subject == "" {
131 subject, err = ui.Prompt("What DNS names or IP addresses would you like to use? (e.g. internal.smallstep.com)", ui.WithValidateNotEmpty())
132 if err != nil {
133 return "", err
134 }
135 }
136
137 return NewTokenFlow(ctx, SignType, subject, sans, caURL, root, time.Time{}, time.Time{}, provisioner.TimeDuration{}, provisioner.TimeDuration{})
138 }
139
140 // GenerateSSHToken generates a token used to authorize the sign of an SSH
141 // certificate.
142 func (f *CertificateFlow) GenerateSSHToken(ctx *cli.Context, subject string, typ int, principals []string, validAfter, validBefore provisioner.TimeDuration) (string, error) {
143 if f.offline {
144 return f.offlineCA.GenerateToken(ctx, typ, subject, principals, time.Time{}, time.Time{}, validAfter, validBefore)
145 }
146
147 // Use online CA to get the provisioners and generate the token
148 caURL, err := flags.ParseCaURLIfExists(ctx)
149 if err != nil {
150 return "", err
151 } else if len(caURL) == 0 {
152 return "", errs.RequiredUnlessFlag(ctx, "ca-url", "token")
153 }
154
155 root := ctx.String("root")
156 if len(root) == 0 {
157 root = pki.GetRootCAPath()
158 if _, err := os.Stat(root); err != nil {
159 return "", errs.RequiredUnlessFlag(ctx, "root", "token")
160 }
161 }
162
163 if subject == "" {
164 subject, err = ui.Prompt("What DNS names or IP addresses would you like to use? (e.g. internal.smallstep.com)", ui.WithValidateNotEmpty())
165 if err != nil {
166 return "", err
167 }
168 }
169
170 return NewTokenFlow(ctx, typ, subject, principals, caURL, root, time.Time{}, time.Time{}, validAfter, validBefore)
171 }
172
173 // GenerateIdentityToken generates a token using only an OIDC provisioner.
174 func (f *CertificateFlow) GenerateIdentityToken(ctx *cli.Context) (string, error) {
175 caURL, err := flags.ParseCaURL(ctx)
176 if err != nil {
177 return "", err
178 }
179 root := ctx.String("root")
180 if len(root) == 0 {
181 root = pki.GetRootCAPath()
182 if _, err := os.Stat(root); err != nil {
183 return "", errs.RequiredFlag(ctx, "root")
184 }
185 }
186 return NewIdentityTokenFlow(ctx, caURL, root)
187 }
188
189 // Sign signs the CSR using the online or the offline certificate authority.
190 func (f *CertificateFlow) Sign(ctx *cli.Context, token string, csr api.CertificateRequest, crtFile string) error {
191 client, err := f.GetClient(ctx, token)
192 if err != nil {
193 return err
194 }
195
196 // parse times or durations
197 notBefore, notAfter, err := flags.ParseTimeDuration(ctx)
198 if err != nil {
199 return err
200 }
201
202 // parse template data
203 templateData, err := flags.ParseTemplateData(ctx)
204 if err != nil {
205 return err
206 }
207
208 req := &api.SignRequest{
209 CsrPEM: csr,
210 OTT: token,
211 NotBefore: notBefore,
212 NotAfter: notAfter,
213 TemplateData: templateData,
214 }
215
216 resp, err := client.Sign(req)
217 if err != nil {
218 return err
219 }
220
221 if resp.CertChainPEM == nil || len(resp.CertChainPEM) == 0 {
222 resp.CertChainPEM = []api.Certificate{resp.ServerPEM, resp.CaPEM}
223 }
224 var data []byte
225 for _, certPEM := range resp.CertChainPEM {
226 pemblk, err := pemutil.Serialize(certPEM.Certificate)
227 if err != nil {
228 return errors.Wrap(err, "error serializing from step-ca API response")
229 }
230 data = append(data, pem.EncodeToMemory(pemblk)...)
231 }
232 return utils.WriteFile(crtFile, data, 0600)
233 }
234
235 // CreateSignRequest is a helper function that given an x509 OTT returns a
236 // simple but secure sign request as well as the private key used.
237 func (f *CertificateFlow) CreateSignRequest(ctx *cli.Context, tok, subject string, sans []string) (*api.SignRequest, crypto.PrivateKey, error) {
238 jwt, err := token.ParseInsecure(tok)
239 if err != nil {
240 return nil, nil, err
241 }
242
243 kty, crv, size, err := utils.GetKeyDetailsFromCLI(ctx, false, "kty", "curve", "size")
244 if err != nil {
245 return nil, nil, err
246 }
247 pk, err := keys.GenerateKey(kty, crv, size)
248 if err != nil {
249 return nil, nil, err
250 }
251
252 dnsNames, ips, emails, uris := splitSANs(sans, jwt.Payload.SANs)
253 switch jwt.Payload.Type() {
254 case token.AWS:
255 doc := jwt.Payload.Amazon.InstanceIdentityDocument
256 if len(ips) == 0 && len(dnsNames) == 0 {
257 defaultSANs := []string{
258 doc.PrivateIP,
259 fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region),
260 }
261 if !sharedContext.DisableCustomSANs {
262 defaultSANs = append(defaultSANs, subject)
263 }
264 dnsNames, ips, emails, uris = splitSANs(defaultSANs)
265 }
266 case token.GCP:
267 ce := jwt.Payload.Google.ComputeEngine
268 if len(ips) == 0 && len(dnsNames) == 0 {
269 defaultSANs := []string{
270 fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID),
271 fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID),
272 }
273 if !sharedContext.DisableCustomSANs {
274 defaultSANs = append(defaultSANs, subject)
275 }
276 dnsNames, ips, emails, uris = splitSANs(defaultSANs)
277 }
278 case token.Azure:
279 if len(ips) == 0 && len(dnsNames) == 0 {
280 defaultSANs := []string{
281 jwt.Payload.Azure.VirtualMachine,
282 }
283 if !sharedContext.DisableCustomSANs {
284 defaultSANs = append(defaultSANs, subject)
285 }
286 dnsNames, ips, emails, uris = splitSANs(defaultSANs)
287 }
288 case token.OIDC:
289 if jwt.Payload.Email != "" {
290 emails = append(emails, jwt.Payload.Email)
291 }
292 subject = jwt.Payload.Subject
293 case token.K8sSA:
294 // Use subject from command line. K8sSA tokens are multi-use so the
295 // subject of the token is not necessarily related to the requested
296 // resource.
297 default: // Use common name in the token
298 subject = jwt.Payload.Subject
299 }
300
301 template := &x509.CertificateRequest{
302 Subject: pkix.Name{
303 CommonName: subject,
304 },
305 DNSNames: dnsNames,
306 IPAddresses: ips,
307 EmailAddresses: emails,
308 URIs: uris,
309 }
310
311 csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
312 if err != nil {
313 return nil, nil, errors.Wrap(err, "error creating certificate request")
314 }
315 cr, err := x509.ParseCertificateRequest(csr)
316 if err != nil {
317 return nil, nil, errors.Wrap(err, "error parsing certificate request")
318 }
319 if err := cr.CheckSignature(); err != nil {
320 return nil, nil, errors.Wrap(err, "error signing certificate request")
321 }
322 return &api.SignRequest{
323 CsrPEM: api.CertificateRequest{CertificateRequest: cr},
324 OTT: tok,
325 }, pk, nil
326 }
327
328 // splitSANs unifies the SAN collections passed as arguments and returns a list
329 // of DNS names, a list of IP addresses, and a list of emails.
330 func splitSANs(args ...[]string) (dnsNames []string, ipAddresses []net.IP, email []string, uris []*url.URL) {
331 m := make(map[string]bool)
332 var unique []string
333 for _, sans := range args {
334 for _, san := range sans {
335 if ok := m[san]; !ok {
336 m[san] = true
337 unique = append(unique, san)
338 }
339 }
340 }
341 return x509util.SplitSANs(unique)
342 }