-
Notifications
You must be signed in to change notification settings - Fork 2
/
ocsp.go
84 lines (71 loc) · 2.18 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
package external_clients
import (
"bytes"
"crypto"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net/http"
"net/url"
"github.com/lamassuiot/lamassuiot/v2/pkg/helpers"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ocsp"
)
func GetOCSPResponse(ocspServerURL string, certificate *x509.Certificate, issuer *x509.Certificate, serverCertificate *x509.Certificate, verifyOCSPResponse bool) (*ocsp.Response, error) {
opts := &ocsp.RequestOptions{Hash: crypto.SHA1}
buffer, err := ocsp.CreateRequest(certificate, issuer, opts)
if err != nil {
return nil, fmt.Errorf("could not generate OCSP request: %s", err)
}
httpRequest, err := http.NewRequest(http.MethodPost, ocspServerURL, bytes.NewBuffer(buffer))
if err != nil {
return nil, fmt.Errorf("could not generate HTTP OCSP request: %s", err)
}
ocspUrl, err := url.Parse(ocspServerURL)
if err != nil {
return nil, fmt.Errorf("could not parse OCSP server URL: %s", err)
}
httpRequest.Header.Add("Content-Type", "application/ocsp-request")
httpRequest.Header.Add("Accept", "application/ocsp-response")
httpRequest.Header.Add("host", ocspUrl.Host)
httpClient := &http.Client{}
if serverCertificate == nil {
logrus.Warn("using insecure server validation in OCSP request")
httpClient.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
} else {
pool := helpers.LoadSytemCACertPool()
pool.AddCert(serverCertificate)
httpClient.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
},
}
}
httpResponse, err := httpClient.Do(httpRequest)
if err != nil {
return nil, fmt.Errorf("could not DO OCSP request: %s", err)
}
defer httpResponse.Body.Close()
output, err := io.ReadAll(httpResponse.Body)
if err != nil {
return nil, fmt.Errorf("could not decode OCSP response: %s", err)
}
if verifyOCSPResponse {
response, err := ocsp.ParseResponse(output, issuer)
if err != nil {
return nil, fmt.Errorf("could not parse OCSP response: %s", err)
}
return response, nil
} else {
response, err := ocsp.ParseResponse(output, nil)
if err != nil {
return nil, fmt.Errorf("could not parse OCSP response: %s", err)
}
return response, nil
}
}