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
|
package tls
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net/http"
"golang.org/x/crypto/ocsp"
)
func GetOcspResponse(chain *tls.Certificate) ([]byte, *ocsp.Response, error) {
var certs []*x509.Certificate
for _, c := range chain.Certificate {
cert, err := x509.ParseCertificate(c)
if err != nil {
return nil, nil, err
}
certs = append(certs, cert)
}
if len(certs) == 0 {
return nil, nil, fmt.Errorf("no certificates found in bundle")
}
// We expect the certificate slice to be ordered downwards the chain.
// SRV CRT -> CA. We need to pull the leaf and issuer certs out of it,
// which should always be the first two certificates. If there's no
// OCSP server listed in the leaf cert, there's nothing to do. And if
// we have only one certificate so far, we need to get the issuer cert.
leaf := certs[0]
if len(leaf.OCSPServer) == 0 {
return nil, nil, fmt.Errorf("no OCSP server specified in certificate")
}
if len(certs) == 1 {
if len(leaf.IssuingCertificateURL) == 0 {
return nil, nil, fmt.Errorf("no URL to issuing certificate")
}
resp, err := http.Get(leaf.IssuingCertificateURL[0])
if err != nil {
return nil, nil, fmt.Errorf("getting issuer certificate: %w", err)
}
defer resp.Body.Close()
issuerBytes, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))
if err != nil {
return nil, nil, fmt.Errorf("reading issuer certificate: %w", err)
}
issuer, err := x509.ParseCertificate(issuerBytes)
if err != nil {
return nil, nil, fmt.Errorf("parsing issuer certificate: %w", err)
}
certs = append(certs, issuer)
}
issuer := certs[1]
req, err := ocsp.CreateRequest(leaf, issuer, nil)
if err != nil {
return nil, nil, fmt.Errorf("creating OCSP request: %w", err)
}
httpRes, err := http.Post(leaf.OCSPServer[0], "application/ocsp-request", bytes.NewReader(req))
if err != nil {
return nil, nil, fmt.Errorf("making OCSP request: %w", err)
}
defer httpRes.Body.Close()
rawRes, err := io.ReadAll(io.LimitReader(httpRes.Body, 1024*1024))
if err != nil {
return nil, nil, fmt.Errorf("reading OCSP response: %w", err)
}
res, err := ocsp.ParseResponse(rawRes, issuer)
if err != nil {
return nil, nil, fmt.Errorf("parsing OCSP response: %w", err)
}
if res.Status != ocsp.Good {
return nil, nil, fmt.Errorf("invalid: OCSP response was not of Good status")
}
// This is invalid, the response expires after the certificate
if res.NextUpdate.After(leaf.NotAfter) {
return nil, nil, fmt.Errorf("invalid: OCSP response valid after certificate expiration")
}
return rawRes, res, nil
}
|