Debian Codegraph @

crypto/x509util/profile.go

raw symbols SCIP
1 package x509util
2
3 import (
4 "crypto"
5 "crypto/rand"
6 "crypto/rsa"
7 "crypto/sha1"
8 "crypto/x509"
9 "crypto/x509/pkix"
10 "encoding/asn1"
11 "encoding/pem"
12 "math/big"
13 "net"
14 "net/url"
15 "strings"
16 "time"
17
18 "github.com/pkg/errors"
19 "github.com/smallstep/cli/crypto/keys"
20 "github.com/smallstep/cli/crypto/pemutil"
21 "github.com/smallstep/cli/utils"
22 )
23
24 // Cribbed directly from golang src crypto/x509/x509.go
25 var (
26 oidExtSubjectKeyID = asn1.ObjectIdentifier([]int{2, 5, 29, 14})
27 oidExtKeyUsage = asn1.ObjectIdentifier([]int{2, 5, 29, 15})
28 oidExtExtendedKeyUsage = asn1.ObjectIdentifier([]int{2, 5, 29, 37})
29 oidExtAuthorityKeyID = asn1.ObjectIdentifier([]int{2, 5, 29, 35})
30 oidExtBasicConstraints = asn1.ObjectIdentifier([]int{2, 5, 29, 19})
31 oidExtSubjectAltName = asn1.ObjectIdentifier([]int{2, 5, 29, 17})
32 oidExtCertificatePolicies = asn1.ObjectIdentifier([]int{2, 5, 29, 32})
33 oidExtNameConstraints = asn1.ObjectIdentifier([]int{2, 5, 29, 30})
34 oidExtCRLDistributionPoints = asn1.ObjectIdentifier([]int{2, 5, 29, 31})
35 oidExtAuthorityInfoAccess = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 5, 5, 7, 1, 1})
36 oidStdExtHashMap = map[string]struct{}{}
37 emptyStruct struct{}
38 )
39
40 func init() {
41 oidStdExtHashMap[oidExtSubjectKeyID.String()] = emptyStruct
42 oidStdExtHashMap[oidExtKeyUsage.String()] = emptyStruct
43 oidStdExtHashMap[oidExtExtendedKeyUsage.String()] = emptyStruct
44 oidStdExtHashMap[oidExtAuthorityKeyID.String()] = emptyStruct
45 oidStdExtHashMap[oidExtBasicConstraints.String()] = emptyStruct
46 oidStdExtHashMap[oidExtSubjectAltName.String()] = emptyStruct
47 oidStdExtHashMap[oidExtCertificatePolicies.String()] = emptyStruct
48 oidStdExtHashMap[oidExtNameConstraints.String()] = emptyStruct
49 oidStdExtHashMap[oidExtCRLDistributionPoints.String()] = emptyStruct
50 oidStdExtHashMap[oidExtAuthorityInfoAccess.String()] = emptyStruct
51 }
52
53 var (
54 // DefaultCertValidity is the minimum validity of an end-entity (not root or intermediate) certificate.
55 DefaultCertValidity = 24 * time.Hour
56
57 // DefaultTLSMinVersion default minimum version of TLS.
58 DefaultTLSMinVersion = TLSVersion(1.2)
59 // DefaultTLSMaxVersion default maximum version of TLS.
60 DefaultTLSMaxVersion = TLSVersion(1.2)
61 // DefaultTLSRenegotiation default TLS connection renegotiation policy.
62 DefaultTLSRenegotiation = false // Never regnegotiate.
63 // DefaultTLSCipherSuites specifies default step ciphersuite(s).
64 DefaultTLSCipherSuites = CipherSuites{
65 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
66 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
67 }
68 // ApprovedTLSCipherSuites smallstep approved ciphersuites.
69 ApprovedTLSCipherSuites = CipherSuites{
70 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
71 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
72 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
73 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
74 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
75 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
76 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
77 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
78 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
79 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
80 "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
81 "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
82 }
83
84 // oidExtensionCTPoison is the OID for the certificate transparency poison
85 // extension defined in RFC6962.
86 oidExtensionCTPoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}
87 )
88
89 // Profile is an interface that certificate profiles (e.g. leaf,
90 // intermediate, root) must implement.
91 type Profile interface {
92 Issuer() *x509.Certificate
93 Subject() *x509.Certificate
94 SubjectPrivateKey() interface{}
95 SubjectPublicKey() interface{}
96 SetIssuer(*x509.Certificate)
97 SetSubject(*x509.Certificate)
98 SetSubjectPrivateKey(interface{})
99 SetSubjectPublicKey(interface{})
100 SetIssuerPrivateKey(interface{})
101 CreateCertificate() ([]byte, error)
102 GenerateKeyPair(string, string, int) error
103 DefaultDuration() time.Duration
104 CreateWriteCertificate(crtOut, keyOut, pass string) ([]byte, error)
105 AddExtension(pkix.Extension)
106 RemoveExtension(asn1.ObjectIdentifier)
107 }
108
109 type base struct {
110 iss *x509.Certificate
111 sub *x509.Certificate
112 ext []pkix.Extension
113 subPub interface{}
114 subPriv interface{}
115 issPriv interface{}
116 }
117
118 // WithOption is a modifier function on base.
119 type WithOption func(Profile) error
120
121 // GenerateKeyPair returns a Profile modifier that generates a public/private
122 // key pair for a profile.
123 func GenerateKeyPair(kty, crv string, size int) WithOption {
124 return func(p Profile) error {
125 return p.GenerateKeyPair(kty, crv, size)
126 }
127 }
128
129 // GenerateDefaultKeyPair generates a new public/private key pair using the
130 // default values and sets them in the given profile.
131 func GenerateDefaultKeyPair(p Profile) error {
132 pub, priv, err := keys.GenerateDefaultKeyPair()
133 if err != nil {
134 return err
135 }
136 p.SetSubjectPublicKey(pub)
137 p.SetSubjectPrivateKey(priv)
138 return nil
139 }
140
141 // WithPublicKey returns a Profile modifier that sets the public key for a profile.
142 func WithPublicKey(pub interface{}) WithOption {
143 return func(p Profile) error {
144 p.SetSubjectPublicKey(pub)
145 return nil
146 }
147 }
148
149 // WithSubject returns a Profile modifier that sets the Subject for a x509
150 // Certificate.
151 func WithSubject(sub pkix.Name) WithOption {
152 return func(p Profile) error {
153 crt := p.Subject()
154 crt.Subject = sub
155 return nil
156 }
157 }
158
159 // WithIssuer returns a Profile modifier that sets the Subject for a x509
160 // Certificate.
161 func WithIssuer(iss pkix.Name) WithOption {
162 return func(p Profile) error {
163 crt := p.Subject()
164 crt.Issuer = iss
165 return nil
166 }
167 }
168
169 // WithNotBeforeAfterDuration returns a Profile modifier that sets the
170 // `NotBefore` and `NotAfter` attributes of the subject x509 Certificate.
171 func WithNotBeforeAfterDuration(nb, na time.Time, d time.Duration) WithOption {
172 return func(p Profile) error {
173 crt := p.Subject()
174
175 now := time.Now()
176 if nb.IsZero() {
177 nb = now
178 }
179 if na.IsZero() {
180 if d == 0 {
181 na = nb.Add(p.DefaultDuration())
182 } else {
183 na = nb.Add(d)
184 }
185 }
186
187 crt.NotBefore = nb
188 crt.NotAfter = na
189 return nil
190 }
191 }
192
193 func appendIfMissingString(slice []string, s string) []string {
194 for _, e := range slice {
195 if e == s {
196 return slice
197 }
198 }
199 return append(slice, s)
200 }
201
202 func appendIfMissingIP(ips []net.IP, ip net.IP) []net.IP {
203 for _, e := range ips {
204 if ip.Equal(e) {
205 return ips
206 }
207 }
208 return append(ips, ip)
209 }
210
211 // WithDNSNames returns a Profile modifier which sets the DNS Names
212 // that will be bound to the subject alternative name extension of the Certificate.
213 func WithDNSNames(dns []string) WithOption {
214 return func(p Profile) error {
215 crt := p.Subject()
216 crt.DNSNames = dns
217 return nil
218 }
219 }
220
221 // WithIPAddresses returns a Profile modifier which sets the IP Addresses
222 // that will be bound to the subject alternative name extension of the Certificate.
223 func WithIPAddresses(ips []net.IP) WithOption {
224 return func(p Profile) error {
225 crt := p.Subject()
226 crt.IPAddresses = ips
227 return nil
228 }
229 }
230
231 // WithEmailAddresses returns a Profile modifier which sets the Email Addresses
232 // that will be bound to the subject alternative name extension of the Certificate.
233 func WithEmailAddresses(emails []string) WithOption {
234 return func(p Profile) error {
235 crt := p.Subject()
236 crt.EmailAddresses = emails
237 return nil
238 }
239 }
240
241 // WithURIs returns a Profile modifier which sets the URIs
242 // that will be bound to the subject alternative name extension of the Certificate.
243 func WithURIs(uris []*url.URL) WithOption {
244 return func(p Profile) error {
245 crt := p.Subject()
246 crt.URIs = uris
247 return nil
248 }
249 }
250
251 // WithSANs returns a profile modifier which set the dnsNames, emailAddresses,
252 // ipAddresses, and URIs attributes of the Certificate.
253 func WithSANs(sans []string) WithOption {
254 return func(p Profile) error {
255 dnsNames, ips, emails, uris := SplitSANs(sans)
256 cert := p.Subject()
257 cert.DNSNames = dnsNames
258 cert.IPAddresses = ips
259 cert.EmailAddresses = emails
260 cert.URIs = uris
261 return nil
262 }
263 }
264
265 // WithHosts returns a Profile modifier which sets the DNS Names and IP Addresses
266 // that will be bound to the subject Certificate.
267 //
268 // `hosts` should be a comma separated string of DNS Names and IP Addresses.
269 // e.g. `127.0.0.1,internal.smallstep.com,blog.smallstep.com,1.1.1.1`.
270 func WithHosts(hosts string) WithOption {
271 return func(p Profile) error {
272 hostsL := strings.Split(hosts, ",")
273 crt := p.Subject()
274 for _, h := range hostsL {
275 if h == "" {
276 continue
277 } else if ip := net.ParseIP(h); ip != nil {
278 crt.IPAddresses = appendIfMissingIP(crt.IPAddresses, ip)
279 } else {
280 crt.DNSNames = appendIfMissingString(crt.DNSNames, h)
281 }
282 }
283
284 return nil
285 }
286 }
287
288 // WithCTPoison returns a Profile modifier that adds the CT poison extension
289 // defined in RFC6962.
290 func WithCTPoison() WithOption {
291 return func(p Profile) error {
292 crt := p.Subject()
293 crt.ExtraExtensions = append(crt.ExtraExtensions, pkix.Extension{
294 Id: oidExtensionCTPoison,
295 Critical: true,
296 Value: asn1.NullBytes,
297 })
298 return nil
299 }
300
301 }
302
303 // newProfile initializes the given profile.
304 //
305 // If the public/private key pair of the subject identity are not set by
306 // the optional modifiers then a pair will be generated using sane defaults.
307 func newProfile(p Profile, sub, iss *x509.Certificate, issPriv crypto.PrivateKey, withOps ...WithOption) (Profile, error) {
308 if p == nil {
309 return nil, errors.New("profile cannot be nil")
310 }
311 if sub == nil {
312 return nil, errors.New("subject certificate cannot be nil")
313 }
314 if iss == nil {
315 return nil, errors.New("issuing certificate cannot be nil")
316 }
317
318 p.SetSubject(sub)
319 p.SetIssuer(iss)
320 p.SetIssuerPrivateKey(issPriv)
321
322 for _, op := range withOps {
323 if err := op(p); err != nil {
324 return nil, err
325 }
326 }
327
328 if p.SubjectPublicKey() == nil {
329 if err := GenerateDefaultKeyPair(p); err != nil {
330 return nil, err
331 }
332 }
333
334 if sub.SubjectKeyId == nil {
335 id, err := generateSubjectKeyID(p.SubjectPublicKey())
336 if err != nil {
337 return nil, err
338 }
339 sub.SubjectKeyId = id
340 }
341
342 if sub.SerialNumber == nil {
343 serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
344 sn, err := rand.Int(rand.Reader, serialNumberLimit)
345 if err != nil {
346 return nil, errors.Wrapf(err, "Failed to generate serial number for "+
347 "certificate with common name '%s'", sub.Subject.CommonName)
348 }
349 sub.SerialNumber = sn
350 }
351
352 return p, nil
353 }
354
355 func (b *base) Issuer() *x509.Certificate {
356 return b.iss
357 }
358
359 func (b *base) Subject() *x509.Certificate {
360 return b.sub
361 }
362
363 func (b *base) SubjectPrivateKey() interface{} {
364 return b.subPriv
365 }
366
367 func (b *base) SubjectPublicKey() interface{} {
368 return b.subPub
369 }
370
371 func (b *base) SetIssuer(iss *x509.Certificate) {
372 b.iss = iss
373 }
374
375 func (b *base) SetSubject(sub *x509.Certificate) {
376 b.sub = sub
377 }
378
379 func (b *base) SetSubjectPrivateKey(priv interface{}) {
380 b.subPriv = priv
381 }
382
383 func (b *base) SetIssuerPrivateKey(priv interface{}) {
384 b.issPriv = priv
385 }
386
387 func (b *base) SetSubjectPublicKey(pub interface{}) {
388 b.subPub = pub
389 }
390
391 func (b *base) AddExtension(ext pkix.Extension) {
392 b.ext = append(b.ext, ext)
393 }
394
395 func (b *base) RemoveExtension(oid asn1.ObjectIdentifier) {
396 for i, ext := range b.ext {
397 if ext.Id.Equal(oid) {
398 b.ext = append(b.ext[:i], b.ext[i+1:]...)
399 break
400 }
401 }
402 if b.sub != nil {
403 for i, ext := range b.sub.ExtraExtensions {
404 if ext.Id.Equal(oid) {
405 b.sub.ExtraExtensions = append(b.sub.ExtraExtensions[:i], b.sub.ExtraExtensions[i+1:]...)
406 break
407 }
408 }
409 }
410 }
411
412 func (b *base) DefaultDuration() time.Duration {
413 return DefaultCertValidity
414 }
415
416 func (b *base) GenerateKeyPair(kty, crv string, size int) error {
417 pub, priv, err := keys.GenerateKeyPair(kty, crv, size)
418 if err != nil {
419 return err
420 }
421 b.SetSubjectPublicKey(pub)
422 b.SetSubjectPrivateKey(priv)
423 return nil
424 }
425
426 func (b *base) GenerateDefaultKeyPair() error {
427 pub, priv, err := keys.GenerateDefaultKeyPair()
428 if err != nil {
429 return err
430 }
431 b.SetSubjectPublicKey(pub)
432 b.SetSubjectPrivateKey(priv)
433 return nil
434 }
435
436 // CreateCertificate creates an x509 Certificate using the configuration stored
437 // in the profile.
438 func (b *base) CreateCertificate() ([]byte, error) {
439 pub := b.SubjectPublicKey()
440 if pub == nil {
441 return nil, errors.Errorf("Profile does not have subject public key. Need to call 'profile.GenerateKeyPair(...)' or use setters to populate keys")
442 }
443 if b.issPriv == nil {
444 return nil, errors.Errorf("Profile does not have issuer private key. Use setters to populate this field.")
445 }
446
447 sub := b.Subject()
448 iss := b.Issuer()
449 if len(b.ext) > 0 {
450 sub.ExtraExtensions = append(sub.ExtraExtensions, b.ext...)
451 }
452
453 // Remove KeyEncipherment and DataEncipherment for non-rsa keys.
454 // See:
455 // https://github.com/golang/go/issues/36499
456 // https://tools.ietf.org/html/draft-ietf-lamps-5480-ku-clarifications-02
457 if _, ok := pub.(*rsa.PublicKey); !ok {
458 sub.KeyUsage &= ^x509.KeyUsageKeyEncipherment
459 sub.KeyUsage &= ^x509.KeyUsageDataEncipherment
460 }
461
462 // Only keep those extensions that are not considered standard x509 Ext as
463 // defined in RFC 5280 4.2.1. The x509/crypto lib applies extra (often
464 // necessary) logic when converting x509 templates to certificates -- but
465 // that logic is superseded by extensions in the ExtraExtensions list, which
466 // are copied to the certificate verbatim.
467 var exts []pkix.Extension
468 for _, ext := range sub.ExtraExtensions {
469 if _, ok := oidStdExtHashMap[ext.Id.String()]; !ok {
470 exts = append(exts, ext)
471 }
472 }
473 sub.ExtraExtensions = exts
474
475 bytes, err := x509.CreateCertificate(rand.Reader, sub, iss, pub, b.issPriv)
476 return bytes, errors.WithStack(err)
477 }
478
479 // Create Certificate from profile and write the certificate and private key
480 // to disk.
481 func (b *base) CreateWriteCertificate(crtOut, keyOut, pass string) ([]byte, error) {
482 crtBytes, err := b.CreateCertificate()
483 if err != nil {
484 return nil, errors.WithStack(err)
485 }
486 if err = utils.WriteFile(crtOut, pem.EncodeToMemory(&pem.Block{
487 Type: "CERTIFICATE",
488 Bytes: crtBytes,
489 }), 0600); err != nil {
490 return nil, errors.WithStack(err)
491 }
492
493 _, err = pemutil.Serialize(b.SubjectPrivateKey(),
494 pemutil.WithPassword([]byte(pass)), pemutil.ToFile(keyOut, 0600))
495 if err != nil {
496 return nil, errors.WithStack(err)
497 }
498 return crtBytes, nil
499 }
500
501 // subjectPublicKeyInfo is a PKIX public key structure defined in RFC 5280.
502 type subjectPublicKeyInfo struct {
503 Algorithm pkix.AlgorithmIdentifier
504 SubjectPublicKey asn1.BitString
505 }
506
507 // generateSubjectKeyID generates the key identifier according the the RFC 5280
508 // section 4.2.1.2.
509 //
510 // The keyIdentifier is composed of the 160-bit SHA-1 hash of the value of the
511 // BIT STRING subjectPublicKey (excluding the tag, length, and number of unused
512 // bits).
513 func generateSubjectKeyID(pub crypto.PublicKey) ([]byte, error) {
514 b, err := x509.MarshalPKIXPublicKey(pub)
515 if err != nil {
516 return nil, errors.Wrap(err, "error marshaling public key")
517 }
518 var info subjectPublicKeyInfo
519 if _, err = asn1.Unmarshal(b, &info); err != nil {
520 return nil, errors.Wrap(err, "error unmarshaling public key")
521 }
522 hash := sha1.Sum(info.SubjectPublicKey.Bytes)
523 return hash[:], nil
524 }