Debian Codegraph @

server/certidp/ocsp_responder.go

raw
1 // Copyright 2023-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package certidp
15
16 import (
17 "encoding/base64"
18 "errors"
19 "fmt"
20 "io"
21 "net/http"
22 "net/url"
23 "strings"
24 "time"
25
26 "golang.org/x/crypto/ocsp"
27 )
28
29 func FetchOCSPResponse(link *ChainLink, opts *OCSPPeerConfig, log *Log) ([]byte, error) {
30 if link == nil || link.Leaf == nil || link.Issuer == nil || opts == nil || log == nil {
31 return nil, errors.New(ErrInvalidChainlink)
32 }
33
34 timeout := time.Duration(opts.Timeout * float64(time.Second))
35 if timeout <= 0*time.Second {
36 timeout = DefaultOCSPResponderTimeout
37 }
38
39 getRequestBytes := func(u string, hc *http.Client) ([]byte, error) {
40 resp, err := hc.Get(u)
41 if err != nil {
42 return nil, err
43 }
44 defer resp.Body.Close()
45 if resp.StatusCode != http.StatusOK {
46 return nil, fmt.Errorf(ErrBadResponderHTTPStatus, resp.StatusCode)
47 }
48 return io.ReadAll(resp.Body)
49 }
50
51 // Request documentation:
52 // https://tools.ietf.org/html/rfc6960#appendix-A.1
53
54 reqDER, err := ocsp.CreateRequest(link.Leaf, link.Issuer, nil)
55 if err != nil {
56 return nil, err
57 }
58
59 reqEnc := encodeOCSPRequest(reqDER)
60
61 responders := *link.OCSPWebEndpoints
62
63 if len(responders) == 0 {
64 return nil, errors.New(ErrNoAvailOCSPServers)
65 }
66
67 var raw []byte
68 hc := &http.Client{
69 Timeout: timeout,
70 }
71 for _, u := range responders {
72 responderURL := u.String()
73 log.Debugf(DbgMakingCARequest, responderURL)
74 responderURL = strings.TrimSuffix(responderURL, "/")
75 raw, err = getRequestBytes(fmt.Sprintf("%s/%s", responderURL, reqEnc), hc)
76 if err == nil {
77 break
78 }
79 }
80 if err != nil {
81 return nil, fmt.Errorf(ErrFailedWithAllRequests, err)
82 }
83
84 return raw, nil
85 }
86
87 // encodeOCSPRequest encodes the OCSP request in base64 and URL-encodes it.
88 // This is needed to fulfill the OCSP responder's requirements for the request format. (X.690)
89 func encodeOCSPRequest(reqDER []byte) string {
90 reqEnc := base64.StdEncoding.EncodeToString(reqDER)
91 return url.QueryEscape(reqEnc)
92 }