-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathservice.go
More file actions
338 lines (304 loc) · 9.91 KB
/
service.go
File metadata and controls
338 lines (304 loc) · 9.91 KB
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
package est
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"math/big"
"time"
"go.mozilla.org/pkcs7"
)
var (
ErrEst = errors.New("base EstError")
)
type EstErrorType int
const (
ErrInvalidSignatureAlgorithm EstErrorType = iota
ErrSubjectMismatch
ErrSubjectAltNameMismatch
ErrInvalidBase64
ErrInvalidCsr
ErrInvalidCsrSignature
)
func (e EstErrorType) Unwrap() error {
return ErrEst
}
func (e EstErrorType) Error() string {
switch e {
case ErrInvalidSignatureAlgorithm:
return "Signature algorithm of the CSR does not match that of the CA"
case ErrSubjectMismatch:
return "Subject field of CSR must match the current client certificate"
case ErrSubjectAltNameMismatch:
return "SubjectAltName field of CSR must match the current client certificate"
case ErrInvalidBase64:
return "The CSR payload is not base64 encoded"
case ErrInvalidCsr:
return "The CSR could not be decoded"
case ErrInvalidCsrSignature:
return "The CSR signature is invalid"
}
panic("Unsupported error type")
}
var (
oidKeyUsage = asn1.ObjectIdentifier([]int{2, 5, 29, 15})
oidSubjectAltName = asn1.ObjectIdentifier([]int{2, 5, 29, 17})
oidExtendedKeyUsage = asn1.ObjectIdentifier([]int{2, 5, 29, 37})
asn1DigitalSignature = []byte{3, 2, 7, 128}
asn1TlsWebClientAuth = []byte{48, 10, 6, 8, 43, 6, 1, 5, 5, 7, 3, 2}
)
type ServiceHandler interface {
GetService(ctx context.Context, serverName string) (Service, error)
}
type staticSvcHandler struct {
Service
}
func (s staticSvcHandler) GetService(ctx context.Context, serverName string) (Service, error) {
return s.Service, nil
}
func NewStaticServiceHandler(svc Service) ServiceHandler {
return &staticSvcHandler{svc}
}
// Service represents a thin API to handle required operations of EST7030.
// This service implements the required parts of EST. Specifically:
//
// "cas" - Section 4.1
// "enroll" and "reenroll" - Section 4.2
//
// Optional APIs are not implemented including:
//
// 4.3 - cmc
// 4.4 - server side key generation is supported partially, without the key encryption.
// 4.5 - CSR attributes
type Service struct {
// Root CAs for a Factory
rootCa []*x509.Certificate
// ca and key are the EST7030 keypair used for signing EST7030 requests
ca *x509.Certificate
key crypto.Signer
allowServerKeygen bool
certDuration time.Duration
}
// NewService creates an EST7030 API for a Factory
func NewService(rootCa []*x509.Certificate, ca *x509.Certificate, key crypto.Signer, certDuration time.Duration, allowServerKeygen bool) Service {
return Service{
rootCa: rootCa,
ca: ca,
key: key,
allowServerKeygen: allowServerKeygen,
certDuration: certDuration,
}
}
// CaCerts return the root CA certificates as per:
// https://www.rfc-editor.org/rfc/rfc7030.html#section-4.1.2
func (s Service) CaCerts(ctx context.Context) ([]byte, error) {
if envelope, err := pkcs7.NewSignedData(nil); err != nil {
return nil, err
} else {
for _, cert := range s.rootCa {
envelope.AddCertificate(cert)
}
if bytes, err := envelope.Finish(); err != nil {
return nil, err
} else {
return []byte(base64.StdEncoding.EncodeToString(bytes)), nil
}
}
}
// Enroll perform EST7030 enrollment operation as per
// https://www.rfc-editor.org/rfc/rfc7030.html#section-4.2.1
// Errors can be generic errors or of the type EstError
func (s Service) Enroll(ctx context.Context, csrBytes []byte) ([]byte, error) {
csr, err := s.loadCsr(ctx, csrBytes)
if err != nil {
return nil, err
}
return s.signCsr(ctx, csr)
}
// ReEnroll perform EST7030 enrollment operation as per
// https://www.rfc-editor.org/rfc/rfc7030.html#section-4.2.2
// Errors can be generic errors or of the type EstError
func (s Service) ReEnroll(ctx context.Context, csrBytes []byte, curCert *x509.Certificate) ([]byte, error) {
log := CtxGetLog(ctx)
csr, err := s.loadCsr(ctx, csrBytes)
if err != nil {
return nil, err
}
if !bytes.Equal(csr.RawSubject, curCert.RawSubject) {
log.Warn().
Str("current-subject", curCert.Subject.String()).
Str("requests-subject", csr.Subject.String()).
Msg("Subject name mismatch")
return nil, ErrSubjectMismatch
}
var csrSAN pkix.Extension
var certSAN pkix.Extension
for _, ext := range csr.Extensions {
if ext.Id.Equal(oidSubjectAltName) {
csrSAN = ext
break
}
}
for _, ext := range curCert.Extensions {
if ext.Id.Equal(oidSubjectAltName) {
certSAN = ext
break
}
}
if !bytes.Equal(csrSAN.Value, certSAN.Value) {
return nil, ErrSubjectAltNameMismatch
}
// TODO: Should we allow this:
// "The ChangeSubjectName attribute, as defined in [RFC6402], MAY be included
// in the CSR to request that these fields be changed in the new certificate."
// Parts of the subject like dn,ou, and businessCategory=production *can't* be altered
return s.signCsr(ctx, csr)
}
// ServerKeygen performs EST7030 enrollment operation with server generated key as per
// https://www.rfc-editor.org/rfc/rfc7030.html#section-4.1.1
// Errors can be generic errors or of the type EstError.
// server won't use additional encryption independent from TLS.
func (s Service) ServerKeygen(ctx context.Context, csrBytes []byte, curCert *x509.Certificate) ([]byte, []byte, error) {
if !s.allowServerKeygen {
return nil, nil, fmt.Errorf("server not allow serverside keygen")
}
originalCsr, err := s.loadCsr(ctx, csrBytes)
if err != nil {
return nil, nil, err
}
var newCertKey crypto.Signer
switch capub := s.ca.PublicKey.(type) {
case *rsa.PublicKey:
newCertKey, err = rsa.GenerateKey(rand.Reader, 2048)
case *ecdsa.PublicKey:
newCertKey, err = ecdsa.GenerateKey(capub.Curve, rand.Reader)
default:
return nil, nil, fmt.Errorf("nullkeytype")
}
if err != nil {
return nil, nil, err
}
// Re-key CSR, only add things that signCsr needs.
// Make a new variable because Golang does not support modifying the CSR object fields directly.
newCsrTemplate := x509.CertificateRequest{
SignatureAlgorithm: s.ca.SignatureAlgorithm,
RawSubject: originalCsr.RawSubject,
PublicKey: newCertKey.Public(),
Extensions: originalCsr.Extensions,
}
newCertKeyByte, _ := x509.MarshalPKCS8PrivateKey(newCertKey)
cert, err := s.signCsr(ctx, &newCsrTemplate)
if err != nil {
return nil, nil, err
}
return cert, []byte(base64.StdEncoding.EncodeToString(newCertKeyByte)), nil
}
// loadCsr parses the certifcate signing request based on rules of
// https://www.rfc-editor.org/rfc/rfc7030.html#section-4.2.1
// - content is a base64 encoded certificate signing request
func (s Service) loadCsr(ctx context.Context, bytes []byte) (*x509.CertificateRequest, error) {
bytes, err := base64.StdEncoding.DecodeString(string(bytes))
log := CtxGetLog(ctx)
if err != nil {
log.Error().Err(err).Msg("Unable to decode base64 data")
return nil, fmt.Errorf("%w: %s", ErrInvalidBase64, err)
}
csr, err := x509.ParseCertificateRequest(bytes)
if err != nil {
log.Error().Err(err).Msg("Unable to parse CSR")
return nil, fmt.Errorf("%w: %s", ErrInvalidCsr, err)
}
if err = csr.CheckSignature(); err != nil {
log.Error().Err(err).Msg("Invalid CSR Signature")
return nil, fmt.Errorf("%w: %s", ErrInvalidCsrSignature, err)
}
return csr, nil
}
// signCsr returns a base64 PCKS7 encoded certificate as per
// https://www.rfc-editor.org/rfc/rfc7030.html#section-4.1.3
func (s Service) signCsr(ctx context.Context, csr *x509.CertificateRequest) ([]byte, error) {
log := CtxGetLog(ctx)
if s.ca.SignatureAlgorithm != csr.SignatureAlgorithm {
return nil, ErrInvalidSignatureAlgorithm
}
sn, err := rand.Int(rand.Reader, big.NewInt(1).Exp(big.NewInt(2), big.NewInt(128), nil))
if err != nil {
return nil, err
}
now := time.Now()
notAfter := now.Add(s.certDuration)
if notAfter.After(s.ca.NotAfter) {
log.Warn().Msg("Adjusting default cert expiry")
notAfter = s.ca.NotAfter
}
// This deviates from 4.2.1, but we limit the extensions and not allow
// clients to create CAs
var ku x509.KeyUsage
var eku []x509.ExtKeyUsage
for _, e := range csr.Extensions {
if e.Id.Equal(oidKeyUsage) {
if !bytes.Equal(e.Value, asn1DigitalSignature) {
log.Error().Bytes("Value", e.Value).Msg("Unsupported CSR KeyUsage options")
return nil, fmt.Errorf("%w: Unsupported CSR KeyUsage value", ErrInvalidCsr)
}
ku |= x509.KeyUsageDigitalSignature
} else if e.Id.Equal(oidExtendedKeyUsage) {
if !bytes.Equal(e.Value, asn1TlsWebClientAuth) {
log.Error().Bytes("Value", e.Value).Msg("Unsupported CSR ExtendedKeyUsage options")
return nil, fmt.Errorf("%w: Unsupported CSR ExtendedKeyUsage value", ErrInvalidCsr)
}
eku = append(eku, x509.ExtKeyUsageClientAuth)
} else {
log.Error().Str("OID", e.Id.String()).Msg("Unsupported CSR Extension")
}
}
var tmpl = &x509.Certificate{
SerialNumber: sn,
NotBefore: now,
NotAfter: notAfter,
RawSubject: csr.RawSubject,
Issuer: s.ca.Subject,
BasicConstraintsValid: true,
IsCA: false,
KeyUsage: ku,
ExtKeyUsage: eku,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, s.ca, csr.PublicKey, s.key)
if err != nil {
log.Error().Err(err).Msg("Unable to create new certificate")
return nil, err
}
cert, err := x509.ParseCertificate(der)
if err != nil {
log.Error().Err(err).Msg("Unable to parse created certificate")
return nil, err
}
bytes, err := pkcs7.DegenerateCertificate(cert.Raw)
if err != nil {
log.Error().Err(err).Msg("Unable to PKCS7 encode certificate")
return nil, err
}
pub, _ := pubkey(cert)
log.Info().Str("value", pub).Msg("New certificate for key")
return []byte(base64.StdEncoding.EncodeToString(bytes)), nil
}
func pubkey(cert *x509.Certificate) (string, error) {
derBytes, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
if err != nil {
return "", err
}
block := &pem.Block{
Type: "PUBLIC KEY",
Bytes: derBytes,
}
return string(pem.EncodeToMemory(block)), nil
}