/
ocsp.go
279 lines (242 loc) · 7.06 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
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
// Copyright 2021 HEARTBEATS Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ocsputil
import (
"bytes"
"crypto"
"crypto/x509"
"encoding/base64"
"errors"
"io"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"time"
"github.com/heartbeatsjp/check-tls-cert/x509util"
"golang.org/x/crypto/ocsp"
)
const ocspClientTimeout = 5
const NoResponseStatus = ocsp.ResponseStatus(-1)
// CertificateStatus is an OCSP certificate status.
type CertificateStatus int
const (
// Good means that the certificate is valid.
Good CertificateStatus = iota
// Revoked means that the certificate has been deliberately revoked.
Revoked
// Unknown means that the OCSP responder doesn't know about the certificate.
Unknown
)
var certificateStatusString = [...]string{
Good: "good",
Revoked: "revoked",
Unknown: "unknown",
}
func (c CertificateStatus) String() string {
i := int(c)
if 0 <= i && i < len(certificateStatusString) {
return certificateStatusString[i]
}
return "unknown OCSP certificate status: " + strconv.Itoa(i)
}
var certificateStatusMessage = [...]string{
Good: "certificate is valid",
Revoked: "certificate has been deliberately revoked",
Unknown: "OCSP responder doesn't know about the certificate",
}
func (c CertificateStatus) Message() string {
i := int(c)
if 0 <= i && i < len(certificateStatusMessage) {
return certificateStatusMessage[i]
}
return "unknown OCSP certificate status: " + strconv.Itoa(i)
}
// CRLReasonCode is a CRL reason code.
type CRLReasonCode int
const (
Unspecified CRLReasonCode = 0
KeyCompromise CRLReasonCode = 1
CACompromise CRLReasonCode = 2
AffiliationChanged CRLReasonCode = 3
Superseded CRLReasonCode = 4
CessationOfOperation CRLReasonCode = 5
CertificateHold CRLReasonCode = 6
RemoveFromCRL CRLReasonCode = 8
PrivilegeWithdrawn CRLReasonCode = 9
AACompromise CRLReasonCode = 10
)
func (c CRLReasonCode) String() string {
switch c {
case ocsp.Unspecified:
return "unspecified"
case ocsp.KeyCompromise:
return "keyCompromise"
case ocsp.CACompromise:
return "cACompromise"
case ocsp.AffiliationChanged:
return "affiliationChanged"
case ocsp.Superseded:
return "superseded"
case ocsp.CessationOfOperation:
return "cessationOfOperation"
case ocsp.CertificateHold:
return "certificateHold"
case ocsp.RemoveFromCRL:
return "removeFromCRL"
case ocsp.PrivilegeWithdrawn:
return "privilegeWithdrawn"
case ocsp.AACompromise:
return "aACompromise"
default:
return "unknown CRL reason code: " + strconv.Itoa(int(c))
}
}
// ResponseStatus is a wrapper of ocsp.ResponseStatus.
type ResponseStatus ocsp.ResponseStatus
const (
Successful ResponseStatus = 0
MalformedRequest ResponseStatus = 1
InternalError ResponseStatus = 2
TryLater ResponseStatus = 3
SigRequired ResponseStatus = 5
Unauthorized ResponseStatus = 6
)
func (r ResponseStatus) String() string {
switch r {
case Successful:
return "successful"
case MalformedRequest:
return "malformedRequest"
case InternalError:
return "internalError"
case TryLater:
return "tryLater"
case SigRequired:
return "sigRequired"
case Unauthorized:
return "unauthorized"
default:
return "unknown OCSP response status: " + strconv.Itoa(int(r))
}
}
func (r ResponseStatus) Message() string {
switch r {
case Successful:
return "response has valid confirmations"
case MalformedRequest:
return "illegal confirmation request"
case InternalError:
return "internal error in issuer"
case TryLater:
return "try again later"
case SigRequired:
return "must sign the request"
case Unauthorized:
return "request unauthorized"
default:
return "unknown OCSP response status: " + strconv.Itoa(int(r))
}
}
// GetOCSPResponse sends the request to the OCSP Responder and gets the response from the OCSP Responder.
func GetOCSPResponse(cert *x509.Certificate, issuer *x509.Certificate) (string, []byte, error) {
var err error
if cert == nil {
return "", nil, errors.New("no server certificate")
}
if issuer == nil {
return "", nil, errors.New("no issuer certificate")
}
if len(cert.OCSPServer) == 0 {
return "", nil, errors.New("no OCSP server in certificate")
}
requestOption := ocsp.RequestOptions{
Hash: crypto.SHA1,
}
ocspRequest, err := ocsp.CreateRequest(cert, issuer, &requestOption)
if err != nil {
return "", nil, err
}
encodedOCSPRequest := base64.StdEncoding.EncodeToString(ocspRequest)
client := &http.Client{
Timeout: ocspClientTimeout * time.Second,
}
var ocspResponse []byte
var server string
for _, server = range cert.OCSPServer {
var req *http.Request
if len(encodedOCSPRequest) < 255 {
if !strings.HasSuffix(server, "/") {
server = server + "/"
}
u, _ := url.Parse(server + encodedOCSPRequest)
req, err = http.NewRequest("GET", u.String(), nil)
if err != nil {
continue
}
} else {
req, err = http.NewRequest("POST", server, strings.NewReader(string(ocspRequest)))
if err != nil {
continue
}
req.Header.Set("Content-Type", "application/ocsp-request")
}
var resp *http.Response
resp, err = client.Do(req)
if err != nil {
continue
}
ocspResponse, err = io.ReadAll(resp.Body)
resp.Body.Close()
if err == nil {
break
}
}
return server, ocspResponse, err
}
// VerifyAuthorizedResponder verifies the certificate of the authorized responder.
func VerifyAuthorizedResponder(responderCert, issuer *x509.Certificate, intermediateCerts []*x509.Certificate, rootCertPool *x509.CertPool, currentTime time.Time) error {
if responderCert == nil {
return nil
}
if currentTime.IsZero() {
currentTime = time.Now()
}
// See RFC 6969 4.2.2.2. Authorized Responders
if responderCert.Equal(issuer) {
// valid
} else if bytes.Equal(responderCert.RawIssuer, issuer.RawSubject) {
incompatibleKeyUsage := true
for _, usage := range responderCert.ExtKeyUsage {
if usage == x509.ExtKeyUsageOCSPSigning {
incompatibleKeyUsage = false
}
}
if incompatibleKeyUsage {
return errors.New("certificate specifies an incompatible key usage")
}
if err := responderCert.CheckSignatureFrom(issuer); err != nil {
return errors.New("signer's certificate does not issued by target certificate's issuer")
}
} else {
return errors.New("invalid certificate")
}
opts := x509.VerifyOptions{
Intermediates: x509util.GetIntermediateCertPool(intermediateCerts),
Roots: rootCertPool,
CurrentTime: currentTime,
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
}
_, err := responderCert.Verify(opts)
// Workaround for verification error on macOS and iOS.
// Because most of OCSP responder certificates does not have SCT, verifications using the platform APIs fail on macOS and iOS.
// See https://support.apple.com/en-us/HT205280
if err != nil && (runtime.GOOS == "darwin" || runtime.GOOS == "ios") {
if strings.Contains(err.Error(), "certificate is not standards compliant") {
err = x509util.VerifyCertificate(responderCert, intermediateCerts[0], currentTime, false)
}
}
return err
}