-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathocsp.go
More file actions
184 lines (163 loc) · 6.19 KB
/
Copy pathocsp.go
File metadata and controls
184 lines (163 loc) · 6.19 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
package certkit
import (
"bytes"
"context"
"crypto/x509"
"errors"
"fmt"
"io"
"net/http"
"time"
"golang.org/x/crypto/ocsp"
)
var (
errOCSPCertRequired = errors.New("checking OCSP: certificate is required")
errOCSPIssuerRequired = errors.New("checking OCSP: issuer certificate is required")
errOCSPResponderURLMissing = errors.New("checking OCSP: certificate has no OCSP responder URL")
errOCSPTooManyRedirects = errors.New("OCSP redirect limit exceeded")
errOCSPResponderHTTPStatus = errors.New("OCSP responder returned non-200 status")
errOCSPResponseExpired = errors.New("OCSP response expired")
)
// CheckOCSPInput contains parameters for an OCSP revocation check.
type CheckOCSPInput struct {
// Cert is the certificate to check.
Cert *x509.Certificate
// Issuer is the issuer certificate (used to build the OCSP request).
Issuer *x509.Certificate
// AllowPrivateNetworks allows OCSP requests to private/internal endpoints.
AllowPrivateNetworks bool
}
// OCSPResult contains the OCSP response details.
type OCSPResult struct {
// Status is "good", "revoked", "unknown", "unavailable", or "skipped".
Status string `json:"status"`
// SerialNumber is the certificate serial in hex.
SerialNumber string `json:"serial,omitempty"`
// URL is the OCSP responder that was queried.
URL string `json:"url,omitempty"`
// ThisUpdate is when the OCSP response was generated (RFC 3339). OCSP keeps
// RFC freshness terminology instead of certificate validity keys.
ThisUpdate string `json:"this_update,omitempty"`
// NextUpdate is when the OCSP response expires (RFC 3339). OCSP keeps RFC
// freshness terminology instead of certificate validity keys.
NextUpdate string `json:"next_update,omitempty"`
// RevokedAt is the revocation time in RFC 3339 (only set when Status is "revoked").
RevokedAt *string `json:"revoked_at,omitempty"`
// RevocationReason is the reason code (only set when Status is "revoked").
RevocationReason *string `json:"revocation_reason,omitempty"`
// Detail provides context when Status is "skipped" or "unavailable".
Detail string `json:"detail,omitempty"`
}
// CheckOCSP queries the OCSP responder for a certificate's revocation status.
// The OCSP responder URL is read from the certificate's AIA extension.
func CheckOCSP(ctx context.Context, input CheckOCSPInput) (*OCSPResult, error) {
if input.Cert == nil {
return nil, errOCSPCertRequired
}
if input.Issuer == nil {
return nil, errOCSPIssuerRequired
}
if len(input.Cert.OCSPServer) == 0 {
return nil, errOCSPResponderURLMissing
}
responderURL := input.Cert.OCSPServer[0]
if err := ValidateAIAURLWithOptions(ctx, ValidateAIAURLInput{URL: responderURL, AllowPrivateNetworks: input.AllowPrivateNetworks}); err != nil {
return nil, fmt.Errorf("validating OCSP responder URL: %w", err)
}
reqBytes, err := ocsp.CreateRequest(input.Cert, input.Issuer, nil)
if err != nil {
return nil, fmt.Errorf("creating OCSP request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, responderURL, bytes.NewReader(reqBytes))
if err != nil {
return nil, fmt.Errorf("creating HTTP request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/ocsp-request")
const maxRedirects = 3
client := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= maxRedirects {
return fmt.Errorf("%w: stopped after %d redirects", errOCSPTooManyRedirects, maxRedirects)
}
if err := ValidateAIAURLWithOptions(req.Context(), ValidateAIAURLInput{URL: req.URL.String(), AllowPrivateNetworks: input.AllowPrivateNetworks}); err != nil {
return fmt.Errorf("redirect blocked: %w", err)
}
return nil
},
}
httpResp, err := client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("querying OCSP responder %s: %w", responderURL, err)
}
defer func() { _ = httpResp.Body.Close() }()
if httpResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: HTTP %d", errOCSPResponderHTTPStatus, httpResp.StatusCode)
}
respBytes, err := io.ReadAll(io.LimitReader(httpResp.Body, 1<<20)) // 1MB limit
if err != nil {
return nil, fmt.Errorf("reading OCSP response: %w", err)
}
resp, err := ocsp.ParseResponseForCert(respBytes, input.Cert, input.Issuer)
if err != nil {
return nil, fmt.Errorf("parsing OCSP response: %w", err)
}
// Reject expired OCSP responses to prevent replay of stale data over HTTP.
if !resp.NextUpdate.IsZero() && time.Now().After(resp.NextUpdate) {
return nil, fmt.Errorf("%w at %s", errOCSPResponseExpired, resp.NextUpdate.UTC().Format(time.RFC3339))
}
result := &OCSPResult{
SerialNumber: FormatSerialNumber(input.Cert.SerialNumber),
URL: responderURL,
ThisUpdate: resp.ThisUpdate.UTC().Format(time.RFC3339),
NextUpdate: resp.NextUpdate.UTC().Format(time.RFC3339),
}
switch resp.Status {
case ocsp.Good:
result.Status = "good"
case ocsp.Revoked:
result.Status = "revoked"
revokedAt := resp.RevokedAt.UTC().Format(time.RFC3339)
result.RevokedAt = &revokedAt
reason := ocspRevocationReason(resp.RevocationReason)
result.RevocationReason = &reason
default:
result.Status = "unknown"
}
return result, nil
}
// ocspRevocationReason returns a human-readable revocation reason.
func ocspRevocationReason(code int) string {
reasons := map[int]string{
0: "unspecified",
1: "key compromise",
2: "CA compromise",
3: "affiliation changed",
4: "superseded",
5: "cessation of operation",
6: "certificate hold",
8: "remove from CRL",
9: "privilege withdrawn",
10: "AA compromise",
}
if reason, ok := reasons[code]; ok {
return reason
}
return fmt.Sprintf("unknown (%d)", code)
}
// FormatOCSPResult formats an OCSPResult as human-readable text.
func FormatOCSPResult(r *OCSPResult) string {
var out string
out += fmt.Sprintf("Serial: %s\n", r.SerialNumber)
out += fmt.Sprintf("Status: %s\n", r.Status)
out += fmt.Sprintf("Responder: %s\n", r.URL)
out += fmt.Sprintf("This Update: %s\n", r.ThisUpdate)
out += fmt.Sprintf("Next Update: %s\n", r.NextUpdate)
if r.RevokedAt != nil {
out += fmt.Sprintf("Revoked At: %s\n", *r.RevokedAt)
}
if r.RevocationReason != nil {
out += fmt.Sprintf("Reason: %s\n", *r.RevocationReason)
}
return out
}