-
Notifications
You must be signed in to change notification settings - Fork 1
/
ocsp.go
234 lines (209 loc) · 6.19 KB
/
ocsp.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
package authority
import (
"bytes"
"crypto"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"strconv"
"strings"
"time"
"github.com/effective-security/xlog"
"github.com/effective-security/xpki/cryptoprov/inmemcrypto"
"github.com/effective-security/xpki/csr"
"github.com/pkg/errors"
"golang.org/x/crypto/ocsp"
)
// revocationReasonCodes is a map between string reason codes
// to integers as defined in RFC 5280
var revocationReasonCodes = map[string]int{
"unspecified": ocsp.Unspecified,
"keycompromise": ocsp.KeyCompromise,
"cacompromise": ocsp.CACompromise,
"affiliationchanged": ocsp.AffiliationChanged,
"superseded": ocsp.Superseded,
"cessationofoperation": ocsp.CessationOfOperation,
"certificatehold": ocsp.CertificateHold,
"removefromcrl": ocsp.RemoveFromCRL,
"privilegewithdrawn": ocsp.PrivilegeWithdrawn,
"aacompromise": ocsp.AACompromise,
}
const (
// OCSPStatusGood specifies name for good status
OCSPStatusGood = "good"
// OCSPStatusRevoked specifies name for revoked status
OCSPStatusRevoked = "revoked"
// OCSPStatusUnknown specifies name for unknown status
OCSPStatusUnknown = "unknown"
)
// OCSPStatusCode is a map between string statuses sent by cli/api
// to ocsp int statuses
var OCSPStatusCode = map[string]int{
OCSPStatusGood: ocsp.Good,
OCSPStatusRevoked: ocsp.Revoked,
OCSPStatusUnknown: ocsp.Unknown,
}
// OCSPSignRequest represents the desired contents of a
// specific OCSP response.
type OCSPSignRequest struct {
SerialNumber *big.Int
Status string
Reason int
RevokedAt time.Time
Extensions []pkix.Extension
// IssuerHash is the hashing function used to hash the issuer subject and public key
// in the OCSP response. Valid values are crypto.SHA1, crypto.SHA256, crypto.SHA384,
// and crypto.SHA512. If zero, the default is crypto.SHA1.
IssuerHash crypto.Hash
// If provided ThisUpdate will override the default usage of time.Now().Truncate(time.Hour)
ThisUpdate *time.Time
// If provided NextUpdate will override the default usage of ThisUpdate.Add(signerInterval)
NextUpdate *time.Time
}
// OCSPReasonStringToCode tries to convert a reason string to an integer code
func OCSPReasonStringToCode(reason string) (reasonCode int, err error) {
// default to 0
if reason == "" {
return 0, nil
}
reasonCode, present := revocationReasonCodes[strings.ToLower(reason)]
if !present {
reasonCode, err = strconv.Atoi(reason)
if err != nil {
return
}
if reasonCode > ocsp.AACompromise || reasonCode < ocsp.Unspecified {
return 0, errors.Errorf("invalid status: %s", reason)
}
}
return
}
// SignOCSP return an OCSP response.
func (i *Issuer) SignOCSP(req *OCSPSignRequest) ([]byte, error) {
var thisUpdate, nextUpdate time.Time
if req.ThisUpdate != nil {
thisUpdate = *req.ThisUpdate
} else {
// Round thisUpdate times down to the nearest minute
thisUpdate = time.Now().Truncate(time.Minute)
}
if req.NextUpdate != nil {
nextUpdate = *req.NextUpdate
} else {
nextUpdate = thisUpdate.Add(i.ocspExpiry)
}
status, ok := OCSPStatusCode[req.Status]
if !ok {
return nil, errors.Errorf("invalid status: %s", req.Status)
}
template := ocsp.Response{
Status: status,
SerialNumber: req.SerialNumber,
ThisUpdate: thisUpdate.UTC(),
NextUpdate: nextUpdate.UTC(),
ExtraExtensions: req.Extensions,
IssuerHash: req.IssuerHash,
}
if status == ocsp.Revoked {
template.RevokedAt = req.RevokedAt
template.RevocationReason = req.Reason
}
issuer := i.bundle.Cert
responder, err := i.CreateDelegatedOCSPSigner()
if err != nil {
logger.KV(xlog.ERROR, "reason", "delegated_ocsp", "err", err)
responder = i.responder
}
if !bytes.Equal(issuer.RawSubject, responder.Cert.RawSubject) {
logger.KV(xlog.DEBUG,
"reason", "delegated_ocsp",
"responder", responder.Cert.Subject.CommonName,
"issuer", issuer.Subject.CommonName,
)
template.Certificate = responder.Cert
}
res, err := ocsp.CreateResponse(issuer, responder.Cert, template, responder.Signer)
if err != nil {
return nil, errors.WithStack(err)
}
return res, nil
}
// OCSPResponder provides responder
type OCSPResponder struct {
Signer crypto.Signer
Cert *x509.Certificate
}
// CreateDelegatedOCSPSigner create OCSP signing certificate,
// if needed, or returns an existing one.
// if the delegation is not allowed, the CA Signer is returned
func (i *Issuer) CreateDelegatedOCSPSigner() (*OCSPResponder, error) {
if i.cfg.AIA == nil ||
i.cfg.AIA.DelegatedOCSPProfile == "" {
if i.responder == nil {
i.responder = &OCSPResponder{
Signer: i.signer,
Cert: i.bundle.Cert,
}
}
return i.responder, nil
}
i.lock.Lock()
defer i.lock.Unlock()
ocsp := i.responder
// check if existing cert is valid or needs to be renewed before
// OCSP validity period
cutoff := time.Now().Add(i.ocspExpiry).UTC()
if ocsp != nil &&
ocsp.Cert != nil &&
cutoff.Before(ocsp.Cert.NotAfter.UTC()) {
logger.KV(xlog.DEBUG,
"reason", "valid_delegated",
"valid_for", time.Until(ocsp.Cert.NotAfter).Truncate(time.Minute).String(),
"expires", ocsp.Cert.NotAfter,
)
return ocsp, nil
}
inmem := inmemcrypto.NewProvider()
req := &csr.CertificateRequest{
CommonName: "OCSP Responder",
KeyRequest: csr.NewKeyRequest(
inmem,
i.cfg.AIA.DelegatedOCSPProfile,
"ecdsa", 256,
csr.SigningKey,
),
}
csrPEM, priv, _, err := csr.NewProvider(inmem).GenerateKeyAndRequest(req)
if err != nil {
return nil, errors.WithMessage(err, "failed to create CSR")
}
s, ok := priv.(crypto.Signer)
if !ok {
return nil, errors.Errorf("unable to convert key to crypto.Signer")
}
crt, _, err := i.Sign(csr.SignRequest{
Request: string(csrPEM),
Profile: i.cfg.AIA.DelegatedOCSPProfile,
Subject: &csr.X509Subject{
CommonName: req.CommonName,
Names: req.Names,
SerialNumber: req.SerialNumber,
},
})
if err != nil {
return nil, errors.WithMessage(err, "failed to sign OCSP responder")
}
logger.KV(xlog.NOTICE,
"reason", "cert_signed",
"profile", i.cfg.AIA.DelegatedOCSPProfile,
"type", "delegated_ocsp",
"cn", crt.Subject.CommonName,
"expires", crt.NotAfter.UTC().Format(time.RFC3339),
)
r := &OCSPResponder{
Signer: s,
Cert: crt,
}
i.responder = r
return r, nil
}