-
Notifications
You must be signed in to change notification settings - Fork 0
/
certificates.go
255 lines (238 loc) · 6.7 KB
/
certificates.go
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
package certificates
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"strings"
"time"
"github.com/90poe/vault-secrets-operator/internal/consts"
"github.com/hashicorp/vault/sdk/helper/certutil"
)
const (
CertificateRSA = "rsa"
CertificateEC = "ec"
CertificateECDSA = "ecdsa"
)
type (
// Certificate is representation of x509.Certificate
Certificate struct {
Serial string
CommonName string
AltNames []string
Issuer string
Type string
ECDSACurve string
KeyBits int
ValidFrom time.Time
ValidUntil time.Time
PrivateKey any
IssuingCA string
PemCert string
PemKey string
Revoked bool
}
)
// NewCertificate would convert x509 Certificate to Certificate
func NewCertificate(cert *x509.Certificate, revoked bool) *Certificate {
sn := certutil.GetHexFormatted(cert.SerialNumber.Bytes(), "-")
return &Certificate{
Serial: sn,
CommonName: cert.Subject.String(),
Issuer: cert.Issuer.String(),
ValidFrom: cert.NotBefore,
ValidUntil: cert.NotAfter,
Revoked: revoked,
}
}
func GetCertificateFromPem(cert, key, ca string, crl *x509.RevocationList) (*Certificate, error) {
valid := true
if crl != nil {
valid, cn, err := IsCertificateValid(cert, crl)
if err != nil {
return nil, err
}
if !valid {
return nil, &CertificateInvalid{
cn: cn,
}
}
}
tlsCert, err := LoadCertPair([]byte(cert), []byte(key))
if err != nil {
return nil, err
}
certType, certLength, err := GetPrivateKeyTypeAndBitLenght(tlsCert)
if err != nil {
return nil, err
}
cert2Ret := &Certificate{
Serial: certutil.GetHexFormatted(tlsCert.Leaf.SerialNumber.Bytes(), "-"),
CommonName: tlsCert.Leaf.Subject.String(),
AltNames: tlsCert.Leaf.DNSNames,
Issuer: tlsCert.Leaf.Issuer.String(),
Type: certType,
KeyBits: certLength,
ValidFrom: tlsCert.Leaf.NotBefore,
ValidUntil: tlsCert.Leaf.NotAfter,
PrivateKey: tlsCert.PrivateKey,
IssuingCA: ca,
PemCert: cert,
PemKey: key,
Revoked: valid,
}
if cert2Ret.Type == consts.CertTypeECDCA {
cert2Ret.ECDSACurve = fmt.Sprintf("p%v", certLength)
}
return cert2Ret, nil
}
// GetRawCertificate would return certificate from string
func GetRawCertificate(pemStr string) (*x509.Certificate, error) {
block, _ := pem.Decode([]byte(pemStr))
if block == nil {
return nil, fmt.Errorf("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse certificate: %w", err)
}
return cert, nil
}
func LoadCertPair(cert, key []byte) (*tls.Certificate, error) {
certParsed, err := tls.X509KeyPair(cert, key)
if err != nil {
return nil, err
}
certParsed.Leaf, err = GetRawCertificate(string(cert))
if err != nil {
return nil, err
}
return &certParsed, nil
}
func GetPrivateKeyTypeAndBitLenght(cert *tls.Certificate) (string, int, error) {
var bitLen int
var keyType string
var err error
switch privKey := cert.PrivateKey.(type) {
case *rsa.PrivateKey:
keyType = consts.CertTypeRSA
bitLen = privKey.N.BitLen()
case *ed25519.PrivateKey:
keyType = consts.CertTypeEC
bitLen = 256
case *ecdsa.PrivateKey:
keyType = consts.CertTypeECDCA
bitLen = privKey.Curve.Params().BitSize
default:
// Unsuported private key
err = fmt.Errorf("unsuported private key for cert with CN=%s", cert.Leaf.Issuer.CommonName)
}
return keyType, bitLen, err
}
// IsCertificateInRevokedList would check if cert is in revoked certificates list
func IsCertificateInRevokedList(cert *x509.Certificate, crl *x509.RevocationList) bool {
for _, revokedCert := range crl.RevokedCertificateEntries {
if cert.SerialNumber.Cmp(revokedCert.SerialNumber) == 0 {
return true
}
}
return false
}
// IsCertificateValid would verify if:
// 1. Certificate is not expired
// 2. Certificate is not in revokation list
// It would return true and certificate CN
func IsCertificateValid(pem string, crl *x509.RevocationList) (bool, string, error) {
rawCert, err := GetRawCertificate(pem)
if err != nil {
return false, "", err
}
revoked := IsCertificateInRevokedList(rawCert, crl)
if revoked {
return false, rawCert.Subject.CommonName, err
}
certInfo := NewCertificate(rawCert, revoked)
now := time.Now()
if now.Before(certInfo.ValidFrom) || now.After(certInfo.ValidUntil) {
// Certificate is either expired or not yet valid
return false, certInfo.CommonName, fmt.Errorf("%s: certificate expired", certInfo.CommonName)
}
return true, certInfo.CommonName, nil
}
func (c *Certificate) SetParsedPrivateKey(privateKey crypto.Signer, privateKeyType certutil.PrivateKeyType, privateKeyBytes []byte) {
c.PrivateKey = privateKey
c.PemKey = string(privateKeyBytes)
c.Type = string(privateKeyType)
}
func (c *Certificate) GeneratePrivateKey() error {
var err error
switch c.ECDSACurve {
case "":
if c.Type != CertificateRSA {
_, c.PrivateKey, err = ed25519.GenerateKey(rand.Reader)
} else {
c.PrivateKey, err = rsa.GenerateKey(rand.Reader, c.KeyBits)
}
case "p224":
c.PrivateKey, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
case "p256":
c.PrivateKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case "p384":
c.PrivateKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case "p521":
c.PrivateKey, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
default:
err = fmt.Errorf("unrecognized elliptic curve: %q", c.ECDSACurve)
}
if err != nil {
return fmt.Errorf("can't generate private key for certificate: %w", err)
}
// Create text representation of the private key
marshaledKey, err := x509.MarshalPKCS8PrivateKey(c.PrivateKey)
if err != nil {
return fmt.Errorf("can't marshal private key: %w", err)
}
keyPEMBlock := &pem.Block{
Type: "PRIVATE KEY",
Bytes: marshaledKey,
}
c.PemKey = strings.TrimSpace(string(pem.EncodeToMemory(keyPEMBlock)))
return nil
}
func (c *Certificate) PublicKey() any {
switch k := c.PrivateKey.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
case ed25519.PrivateKey:
return k.Public().(ed25519.PublicKey)
default:
return nil
}
}
func (c *Certificate) GenerateCSR() (string, error) {
csrTemplate := &x509.CertificateRequest{
Subject: pkix.Name{
CommonName: c.CommonName,
},
DNSNames: append(c.AltNames, c.CommonName),
}
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, c.PrivateKey)
if err != nil {
return "", fmt.Errorf("can't create certificate request: %w", err)
}
csrPEMBlock := &pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csrBytes,
}
csrRSAPem := strings.TrimSpace(string(pem.EncodeToMemory(csrPEMBlock)))
return csrRSAPem, nil
}