1/*
2Copyright 2019 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package authority
18
19import (
20	"crypto"
21	"crypto/rand"
22	"crypto/x509"
23	"fmt"
24	"math/big"
25)
26
27var serialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128)
28
29// CertificateAuthority implements a certificate authority that supports policy
30// based signing. It's used by the signing controller.
31type CertificateAuthority struct {
32	// RawCert is an optional field to determine if signing cert/key pairs have changed
33	RawCert []byte
34	// RawKey is an optional field to determine if signing cert/key pairs have changed
35	RawKey []byte
36
37	Certificate *x509.Certificate
38	PrivateKey  crypto.Signer
39}
40
41// Sign signs a certificate request, applying a SigningPolicy and returns a DER
42// encoded x509 certificate.
43func (ca *CertificateAuthority) Sign(crDER []byte, policy SigningPolicy) ([]byte, error) {
44	cr, err := x509.ParseCertificateRequest(crDER)
45	if err != nil {
46		return nil, fmt.Errorf("unable to parse certificate request: %v", err)
47	}
48	if err := cr.CheckSignature(); err != nil {
49		return nil, fmt.Errorf("unable to verify certificate request signature: %v", err)
50	}
51
52	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
53	if err != nil {
54		return nil, fmt.Errorf("unable to generate a serial number for %s: %v", cr.Subject.CommonName, err)
55	}
56
57	tmpl := &x509.Certificate{
58		SerialNumber:       serialNumber,
59		Subject:            cr.Subject,
60		DNSNames:           cr.DNSNames,
61		IPAddresses:        cr.IPAddresses,
62		EmailAddresses:     cr.EmailAddresses,
63		URIs:               cr.URIs,
64		PublicKeyAlgorithm: cr.PublicKeyAlgorithm,
65		PublicKey:          cr.PublicKey,
66		Extensions:         cr.Extensions,
67		ExtraExtensions:    cr.ExtraExtensions,
68	}
69	if err := policy.apply(tmpl, ca.Certificate.NotAfter); err != nil {
70		return nil, err
71	}
72
73	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.Certificate, cr.PublicKey, ca.PrivateKey)
74	if err != nil {
75		return nil, fmt.Errorf("failed to sign certificate: %v", err)
76	}
77	return der, nil
78}
79