Debian Codegraph @

server/ocsp.go

raw
1 // Copyright 2021-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 server
15
16 import (
17 "bytes"
18 "crypto/sha256"
19 "crypto/tls"
20 "crypto/x509"
21 "encoding/asn1"
22 "encoding/base64"
23 "encoding/pem"
24 "errors"
25 "fmt"
26 "io"
27 "net/http"
28 "os"
29 "path/filepath"
30 "strings"
31 "sync"
32 "time"
33
34 "golang.org/x/crypto/ocsp"
35
36 "github.com/nats-io/nats-server/v2/server/certidp"
37 "github.com/nats-io/nats-server/v2/server/certstore"
38 )
39
40 const (
41 defaultOCSPStoreDir = "ocsp"
42 defaultOCSPCheckInterval = 24 * time.Hour
43 minOCSPCheckInterval = 2 * time.Minute
44 )
45
46 type OCSPMode uint8
47
48 const (
49 // OCSPModeAuto staples a status, only if "status_request" is set in cert.
50 OCSPModeAuto OCSPMode = iota
51
52 // OCSPModeAlways enforces OCSP stapling for certs and shuts down the server in
53 // case a server is revoked or cannot get OCSP staples.
54 OCSPModeAlways
55
56 // OCSPModeNever disables OCSP stapling even if cert has Must-Staple flag.
57 OCSPModeNever
58
59 // OCSPModeMust honors the Must-Staple flag from a certificate but also causing shutdown
60 // in case the certificate has been revoked.
61 OCSPModeMust
62 )
63
64 // OCSPMonitor monitors the state of a staple per certificate.
65 type OCSPMonitor struct {
66 kind string
67 mu sync.Mutex
68 raw []byte
69 srv *Server
70 certFile string
71 resp *ocsp.Response
72 hc *http.Client
73 stopCh chan struct{}
74 Leaf *x509.Certificate
75 Issuer *x509.Certificate
76
77 shutdownOnRevoke bool
78 }
79
80 func (oc *OCSPMonitor) getNextRun() time.Duration {
81 oc.mu.Lock()
82 nextUpdate := oc.resp.NextUpdate
83 oc.mu.Unlock()
84
85 now := time.Now()
86 if nextUpdate.IsZero() {
87 // If response is missing NextUpdate, we check the day after.
88 // Technically, if NextUpdate is missing, we can try whenever.
89 // https://tools.ietf.org/html/rfc6960#section-4.2.2.1
90 return defaultOCSPCheckInterval
91 }
92 dur := nextUpdate.Sub(now) / 2
93
94 // If negative, then wait a couple of minutes before getting another staple.
95 if dur < 0 {
96 return minOCSPCheckInterval
97 }
98
99 return dur
100 }
101
102 func (oc *OCSPMonitor) getStatus() ([]byte, *ocsp.Response, error) {
103 raw, resp := oc.getCacheStatus()
104 if len(raw) > 0 && resp != nil {
105 // Check if the OCSP is still valid.
106 if err := validOCSPResponse(resp); err == nil {
107 return raw, resp, nil
108 }
109 }
110 var err error
111 raw, resp, err = oc.getLocalStatus()
112 if err == nil {
113 return raw, resp, nil
114 }
115
116 return oc.getRemoteStatus()
117 }
118
119 func (oc *OCSPMonitor) getCacheStatus() ([]byte, *ocsp.Response) {
120 oc.mu.Lock()
121 defer oc.mu.Unlock()
122 return oc.raw, oc.resp
123 }
124
125 func (oc *OCSPMonitor) getLocalStatus() ([]byte, *ocsp.Response, error) {
126 opts := oc.srv.getOpts()
127 storeDir := opts.StoreDir
128 if storeDir == _EMPTY_ {
129 return nil, nil, fmt.Errorf("store_dir not set")
130 }
131
132 // This key must be based upon the current full certificate, not the public key,
133 // so MUST be on the full raw certificate and not an SPKI or other reduced form.
134 key := fmt.Sprintf("%x", sha256.Sum256(oc.Leaf.Raw))
135
136 oc.mu.Lock()
137 raw, err := os.ReadFile(filepath.Join(storeDir, defaultOCSPStoreDir, key))
138 oc.mu.Unlock()
139 if err != nil {
140 return nil, nil, err
141 }
142
143 resp, err := ocsp.ParseResponse(raw, oc.Issuer)
144 if err != nil {
145 return nil, nil, fmt.Errorf("failed to get local status: %w", err)
146 }
147 if err := validOCSPResponse(resp); err != nil {
148 return nil, nil, err
149 }
150
151 // Cache the response.
152 oc.mu.Lock()
153 oc.raw = raw
154 oc.resp = resp
155 oc.mu.Unlock()
156
157 return raw, resp, nil
158 }
159
160 func (oc *OCSPMonitor) getRemoteStatus() ([]byte, *ocsp.Response, error) {
161 opts := oc.srv.getOpts()
162 var overrideURLs []string
163 if config := opts.OCSPConfig; config != nil {
164 overrideURLs = config.OverrideURLs
165 }
166 getRequestBytes := func(u string, reqDER []byte, hc *http.Client) ([]byte, error) {
167 reqEnc := base64.StdEncoding.EncodeToString(reqDER)
168 u = fmt.Sprintf("%s/%s", u, reqEnc)
169 start := time.Now()
170 resp, err := hc.Get(u)
171 if err != nil {
172 return nil, err
173 }
174 defer resp.Body.Close()
175
176 oc.srv.Debugf("Received OCSP response (method=GET, status=%v, url=%s, duration=%.3fs)",
177 resp.StatusCode, u, time.Since(start).Seconds())
178 if resp.StatusCode > 299 {
179 return nil, fmt.Errorf("non-ok http status on GET request (reqlen=%d): %d", len(reqEnc), resp.StatusCode)
180 }
181 return io.ReadAll(resp.Body)
182 }
183 postRequestBytes := func(u string, body []byte, hc *http.Client) ([]byte, error) {
184 hreq, err := http.NewRequest("POST", u, bytes.NewReader(body))
185 if err != nil {
186 return nil, err
187 }
188 hreq.Header.Add("Content-Type", "application/ocsp-request")
189 hreq.Header.Add("Accept", "application/ocsp-response")
190
191 start := time.Now()
192 resp, err := hc.Do(hreq)
193 if err != nil {
194 return nil, err
195 }
196 defer resp.Body.Close()
197
198 oc.srv.Debugf("Received OCSP response (method=POST, status=%v, url=%s, duration=%.3fs)",
199 resp.StatusCode, u, time.Since(start).Seconds())
200 if resp.StatusCode > 299 {
201 return nil, fmt.Errorf("non-ok http status on POST request (reqlen=%d): %d", len(body), resp.StatusCode)
202 }
203 return io.ReadAll(resp.Body)
204 }
205
206 // Request documentation:
207 // https://tools.ietf.org/html/rfc6960#appendix-A.1
208
209 reqDER, err := ocsp.CreateRequest(oc.Leaf, oc.Issuer, nil)
210 if err != nil {
211 return nil, nil, err
212 }
213
214 responders := oc.Leaf.OCSPServer
215 if len(overrideURLs) > 0 {
216 responders = overrideURLs
217 }
218 if len(responders) == 0 {
219 return nil, nil, fmt.Errorf("no available ocsp servers")
220 }
221
222 oc.mu.Lock()
223 hc := oc.hc
224 oc.mu.Unlock()
225
226 var raw []byte
227 for _, u := range responders {
228 var postErr, getErr error
229 u = strings.TrimSuffix(u, "/")
230 // Prefer to make POST requests first.
231 raw, postErr = postRequestBytes(u, reqDER, hc)
232 if postErr == nil {
233 err = nil
234 break
235 } else {
236 // Fallback to use a GET request.
237 raw, getErr = getRequestBytes(u, reqDER, hc)
238 if getErr == nil {
239 err = nil
240 break
241 } else {
242 err = errors.Join(postErr, getErr)
243 }
244 }
245 }
246 if err != nil {
247 return nil, nil, fmt.Errorf("exhausted ocsp servers: %w", err)
248 }
249 resp, err := ocsp.ParseResponse(raw, oc.Issuer)
250 if err != nil {
251 return nil, nil, fmt.Errorf("failed to get remote status: %w", err)
252 }
253 if err := validOCSPResponse(resp); err != nil {
254 return nil, nil, err
255 }
256
257 if storeDir := opts.StoreDir; storeDir != _EMPTY_ {
258 key := fmt.Sprintf("%x", sha256.Sum256(oc.Leaf.Raw))
259 if err := oc.writeOCSPStatus(storeDir, key, raw); err != nil {
260 return nil, nil, fmt.Errorf("failed to write ocsp status: %w", err)
261 }
262 }
263
264 oc.mu.Lock()
265 oc.raw = raw
266 oc.resp = resp
267 oc.mu.Unlock()
268
269 return raw, resp, nil
270 }
271
272 func (oc *OCSPMonitor) run() {
273 s := oc.srv
274 s.mu.Lock()
275 quitCh := s.quitCh
276 s.mu.Unlock()
277
278 var doShutdown bool
279 defer func() {
280 // Need to decrement before shuting down, otherwise shutdown
281 // would be stuck waiting on grWG to go down to 0.
282 s.grWG.Done()
283 if doShutdown {
284 s.Shutdown()
285 }
286 }()
287
288 oc.mu.Lock()
289 shutdownOnRevoke := oc.shutdownOnRevoke
290 certFile := oc.certFile
291 stopCh := oc.stopCh
292 kind := oc.kind
293 oc.mu.Unlock()
294
295 var nextRun time.Duration
296 _, resp, err := oc.getStatus()
297 if err == nil && resp.Status == ocsp.Good {
298 nextRun = oc.getNextRun()
299 t := resp.NextUpdate.Format(time.RFC3339Nano)
300 s.Noticef(
301 "Found OCSP status for %s certificate at '%s': good, next update %s, checking again in %s",
302 kind, certFile, t, nextRun,
303 )
304 } else if err == nil && shutdownOnRevoke {
305 // If resp.Status is ocsp.Revoked, ocsp.Unknown, or any other value.
306 s.Errorf("Found OCSP status for %s certificate at '%s': %s", kind, certFile, ocspStatusString(resp.Status))
307 doShutdown = true
308 return
309 }
310
311 nextRunTimer := time.NewTimer(nextRun)
312 defer stopAndClearTimer(&nextRunTimer)
313
314 for {
315 // On reload, if the certificate changes then need to stop this monitor.
316 select {
317 case <-nextRunTimer.C:
318 case <-stopCh:
319 // In case of reload and have to restart the OCSP stapling monitoring.
320 return
321 case <-quitCh:
322 // Server quit channel.
323 return
324 }
325 _, resp, err := oc.getRemoteStatus()
326 if err != nil {
327 nextRun = oc.getNextRun()
328 s.Errorf("Bad OCSP status update for certificate '%s': %s, trying again in %v", certFile, err, nextRun)
329 nextRunTimer.Reset(nextRun)
330 continue
331 }
332
333 switch n := resp.Status; n {
334 case ocsp.Good:
335 nextRun = oc.getNextRun()
336 t := resp.NextUpdate.Format(time.RFC3339Nano)
337 s.Noticef(
338 "Received OCSP status for %s certificate '%s': good, next update %s, checking again in %s",
339 kind, certFile, t, nextRun,
340 )
341 nextRunTimer.Reset(nextRun)
342 continue
343 default:
344 s.Errorf("Received OCSP status for %s certificate '%s': %s", kind, certFile, ocspStatusString(n))
345 if shutdownOnRevoke {
346 doShutdown = true
347 }
348 return
349 }
350 }
351 }
352
353 func (oc *OCSPMonitor) stop() {
354 oc.mu.Lock()
355 stopCh := oc.stopCh
356 oc.mu.Unlock()
357 stopCh <- struct{}{}
358 }
359
360 // NewOCSPMonitor takes a TLS configuration then wraps it with the callbacks set for OCSP verification
361 // along with a monitor that will periodically fetch OCSP staples.
362 func (srv *Server) NewOCSPMonitor(config *tlsConfigKind) (*tls.Config, *OCSPMonitor, error) {
363 kind := config.kind
364 tc := config.tlsConfig
365 tcOpts := config.tlsOpts
366 opts := srv.getOpts()
367 oc := opts.OCSPConfig
368
369 // We need to track the CA certificate in case the CA is not present
370 // in the chain to be able to verify the signature of the OCSP staple.
371 var (
372 certFile string
373 caFile string
374 )
375 if kind == kindStringMap[CLIENT] {
376 tcOpts = opts.tlsConfigOpts
377 if opts.TLSCert != _EMPTY_ {
378 certFile = opts.TLSCert
379 }
380 if opts.TLSCaCert != _EMPTY_ {
381 caFile = opts.TLSCaCert
382 }
383 }
384 if tcOpts != nil {
385 certFile = tcOpts.CertFile
386 caFile = tcOpts.CaFile
387 }
388
389 // NOTE: Currently OCSP Stapling is enabled only for the first certificate found.
390 var mon *OCSPMonitor
391 for _, currentCert := range tc.Certificates {
392 // Create local copy since this will be used in the GetCertificate callback.
393 cert := currentCert
394
395 // This is normally non-nil, but can still be nil here when in tests
396 // or in some embedded scenarios.
397 if cert.Leaf == nil {
398 if len(cert.Certificate) <= 0 {
399 return nil, nil, fmt.Errorf("no certificate found")
400 }
401 var err error
402 cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
403 if err != nil {
404 return nil, nil, fmt.Errorf("error parsing certificate: %v", err)
405 }
406 }
407 var shutdownOnRevoke bool
408 mustStaple := hasOCSPStatusRequest(cert.Leaf)
409 if oc != nil {
410 switch {
411 case oc.Mode == OCSPModeNever:
412 if mustStaple {
413 srv.Warnf("Certificate at '%s' has MustStaple but OCSP is disabled", certFile)
414 }
415 return tc, nil, nil
416 case oc.Mode == OCSPModeAlways:
417 // Start the monitor for this cert even if it does not have
418 // the MustStaple flag and shutdown the server in case the
419 // staple ever gets revoked.
420 mustStaple = true
421 shutdownOnRevoke = true
422 case oc.Mode == OCSPModeMust && mustStaple:
423 shutdownOnRevoke = true
424 case oc.Mode == OCSPModeAuto && !mustStaple:
425 // "status_request" MustStaple flag not set in certificate. No need to do anything.
426 return tc, nil, nil
427 }
428 }
429 if !mustStaple {
430 // No explicit OCSP config and cert does not have MustStaple flag either.
431 return tc, nil, nil
432 }
433
434 if err := srv.setupOCSPStapleStoreDir(); err != nil {
435 return nil, nil, err
436 }
437
438 // TODO: Add OCSP 'responder_cert' option in case CA cert not available.
439 issuer, err := getOCSPIssuer(caFile, cert.Certificate)
440 if err != nil {
441 return nil, nil, err
442 }
443
444 mon = &OCSPMonitor{
445 kind: kind,
446 srv: srv,
447 hc: &http.Client{Timeout: 30 * time.Second},
448 shutdownOnRevoke: shutdownOnRevoke,
449 certFile: certFile,
450 stopCh: make(chan struct{}, 1),
451 Leaf: cert.Leaf,
452 Issuer: issuer,
453 }
454
455 // Get the certificate status from the memory, then remote OCSP responder.
456 if _, resp, err := mon.getStatus(); err != nil {
457 return nil, nil, fmt.Errorf("bad OCSP status update for certificate at '%s': %s", certFile, err)
458 } else if resp != nil && resp.Status != ocsp.Good && shutdownOnRevoke {
459 return nil, nil, fmt.Errorf("found existing OCSP status for certificate at '%s': %s", certFile, ocspStatusString(resp.Status))
460 }
461
462 // Callbacks below will be in charge of returning the certificate instead,
463 // so this has to be nil.
464 tc.Certificates = nil
465
466 // GetCertificate returns a certificate that's presented to a client.
467 tc.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
468 ccert := cert
469 raw, _, err := mon.getStatus()
470 if err != nil {
471 return nil, err
472 }
473 return &tls.Certificate{
474 OCSPStaple: raw,
475 Certificate: ccert.Certificate,
476 PrivateKey: ccert.PrivateKey,
477 SupportedSignatureAlgorithms: ccert.SupportedSignatureAlgorithms,
478 SignedCertificateTimestamps: ccert.SignedCertificateTimestamps,
479 Leaf: ccert.Leaf,
480 }, nil
481 }
482
483 // Check whether need to verify staples from a peer router or gateway connection.
484 switch kind {
485 case kindStringMap[ROUTER], kindStringMap[GATEWAY]:
486 tc.VerifyConnection = func(s tls.ConnectionState) error {
487 oresp := s.OCSPResponse
488 if oresp == nil {
489 return fmt.Errorf("%s peer missing OCSP Staple", kind)
490 }
491
492 // Peer connections will verify the response of the staple.
493 if len(s.VerifiedChains) == 0 {
494 return fmt.Errorf("%s peer missing TLS verified chains", kind)
495 }
496
497 chain := s.VerifiedChains[0]
498 peerLeaf := chain[0]
499 peerIssuer := certidp.GetLeafIssuerCert(chain, 0)
500 if peerIssuer == nil {
501 return fmt.Errorf("failed to get issuer certificate for %s peer", kind)
502 }
503
504 // Response signature of issuer or issuer delegate is checked in the library parse
505 resp, err := ocsp.ParseResponseForCert(oresp, peerLeaf, peerIssuer)
506 if err != nil {
507 return fmt.Errorf("failed to parse OCSP response from %s peer: %w", kind, err)
508 }
509
510 // If signer was issuer delegate double-check issuer delegate authorization
511 if resp.Certificate != nil {
512 ok := false
513 for _, eku := range resp.Certificate.ExtKeyUsage {
514 if eku == x509.ExtKeyUsageOCSPSigning {
515 ok = true
516 break
517 }
518 }
519 if !ok {
520 return fmt.Errorf("OCSP staple's signer missing authorization by CA to act as OCSP signer")
521 }
522 }
523
524 // Check that the OCSP response is effective, take defaults for clockskew and default validity
525 peerOpts := certidp.OCSPPeerConfig{ClockSkew: -1, TTLUnsetNextUpdate: -1}
526 sLog := certidp.Log{Debugf: srv.Debugf}
527 if !certidp.OCSPResponseCurrent(resp, &peerOpts, &sLog) {
528 return fmt.Errorf("OCSP staple from %s peer not current", kind)
529 }
530
531 if resp.Status != ocsp.Good {
532 return fmt.Errorf("bad status for OCSP Staple from %s peer: %s", kind, ocspStatusString(resp.Status))
533 }
534
535 return nil
536 }
537
538 // When server makes a peer connection, need to also present an OCSP Staple.
539 tc.GetClientCertificate = func(info *tls.CertificateRequestInfo) (*tls.Certificate, error) {
540 ccert := cert
541 raw, _, err := mon.getStatus()
542 if err != nil {
543 return nil, err
544 }
545 // NOTE: crypto/tls.sendClientCertificate internally also calls getClientCertificate
546 // so if for some reason these callbacks are triggered concurrently during a reconnect
547 // there can be a race. To avoid that, the OCSP monitor lock is used to serialize access
548 // to the staple which could also change inflight during an update.
549 mon.mu.Lock()
550 ccert.OCSPStaple = raw
551 mon.mu.Unlock()
552
553 return &ccert, nil
554 }
555 default:
556 // GetClientCertificate returns a certificate that's presented to a server.
557 tc.GetClientCertificate = func(info *tls.CertificateRequestInfo) (*tls.Certificate, error) {
558 return &cert, nil
559 }
560 }
561 }
562 return tc, mon, nil
563 }
564
565 func (s *Server) setupOCSPStapleStoreDir() error {
566 opts := s.getOpts()
567 storeDir := opts.StoreDir
568 if storeDir == _EMPTY_ {
569 return nil
570 }
571 storeDir = filepath.Join(storeDir, defaultOCSPStoreDir)
572 if stat, err := os.Stat(storeDir); os.IsNotExist(err) {
573 if err := os.MkdirAll(storeDir, defaultDirPerms); err != nil {
574 return fmt.Errorf("could not create OCSP storage directory - %v", err)
575 }
576 } else if stat == nil || !stat.IsDir() {
577 return fmt.Errorf("OCSP storage directory is not a directory")
578 }
579 return nil
580 }
581
582 type tlsConfigKind struct {
583 tlsConfig *tls.Config
584 tlsOpts *TLSConfigOpts
585 kind string
586 isLeafSpoke bool
587 apply func(*tls.Config)
588 }
589
590 func (s *Server) configureOCSP() []*tlsConfigKind {
591 sopts := s.getOpts()
592
593 configs := make([]*tlsConfigKind, 0)
594
595 if config := sopts.TLSConfig; config != nil {
596 opts := sopts.tlsConfigOpts
597 o := &tlsConfigKind{
598 kind: kindStringMap[CLIENT],
599 tlsConfig: config,
600 tlsOpts: opts,
601 apply: func(tc *tls.Config) { sopts.TLSConfig = tc },
602 }
603 configs = append(configs, o)
604 }
605 if config := sopts.Websocket.TLSConfig; config != nil {
606 opts := sopts.Websocket.tlsConfigOpts
607 o := &tlsConfigKind{
608 kind: kindStringMap[CLIENT],
609 tlsConfig: config,
610 tlsOpts: opts,
611 apply: func(tc *tls.Config) { sopts.Websocket.TLSConfig = tc },
612 }
613 configs = append(configs, o)
614 }
615 if config := sopts.MQTT.TLSConfig; config != nil {
616 opts := sopts.tlsConfigOpts
617 o := &tlsConfigKind{
618 kind: kindStringMap[CLIENT],
619 tlsConfig: config,
620 tlsOpts: opts,
621 apply: func(tc *tls.Config) { sopts.MQTT.TLSConfig = tc },
622 }
623 configs = append(configs, o)
624 }
625 if config := sopts.Cluster.TLSConfig; config != nil {
626 opts := sopts.Cluster.tlsConfigOpts
627 o := &tlsConfigKind{
628 kind: kindStringMap[ROUTER],
629 tlsConfig: config,
630 tlsOpts: opts,
631 apply: func(tc *tls.Config) { sopts.Cluster.TLSConfig = tc },
632 }
633 configs = append(configs, o)
634 }
635 if config := sopts.LeafNode.TLSConfig; config != nil {
636 opts := sopts.LeafNode.tlsConfigOpts
637 o := &tlsConfigKind{
638 kind: kindStringMap[LEAF],
639 tlsConfig: config,
640 tlsOpts: opts,
641 apply: func(tc *tls.Config) { sopts.LeafNode.TLSConfig = tc },
642 }
643 configs = append(configs, o)
644 }
645 for _, remote := range sopts.LeafNode.Remotes {
646 if config := remote.TLSConfig; config != nil {
647 // Use a copy of the remote here since will be used
648 // in the apply func callback below.
649 r, opts := remote, remote.tlsConfigOpts
650 o := &tlsConfigKind{
651 kind: kindStringMap[LEAF],
652 tlsConfig: config,
653 tlsOpts: opts,
654 isLeafSpoke: true,
655 apply: func(tc *tls.Config) { r.TLSConfig = tc },
656 }
657 configs = append(configs, o)
658 }
659 }
660 if config := sopts.Gateway.TLSConfig; config != nil {
661 opts := sopts.Gateway.tlsConfigOpts
662 o := &tlsConfigKind{
663 kind: kindStringMap[GATEWAY],
664 tlsConfig: config,
665 tlsOpts: opts,
666 apply: func(tc *tls.Config) { sopts.Gateway.TLSConfig = tc },
667 }
668 configs = append(configs, o)
669 }
670 for _, remote := range sopts.Gateway.Gateways {
671 if config := remote.TLSConfig; config != nil {
672 gw, opts := remote, remote.tlsConfigOpts
673 o := &tlsConfigKind{
674 kind: kindStringMap[GATEWAY],
675 tlsConfig: config,
676 tlsOpts: opts,
677 apply: func(tc *tls.Config) { gw.TLSConfig = tc },
678 }
679 configs = append(configs, o)
680 }
681 }
682 return configs
683 }
684
685 func (s *Server) enableOCSP() error {
686 configs := s.configureOCSP()
687
688 for _, config := range configs {
689
690 // We do not staple Leaf Hub and Leaf Spokes, use ocsp_peer
691 if config.kind != kindStringMap[LEAF] {
692 // OCSP Stapling feature, will also enable tls server peer check for gateway and route peers
693 tc, mon, err := s.NewOCSPMonitor(config)
694 if err != nil {
695 return err
696 }
697 // Check if an OCSP stapling monitor is required for this certificate.
698 if mon != nil {
699 s.ocsps = append(s.ocsps, mon)
700
701 // Override the TLS config with one that follows OCSP stapling
702 config.apply(tc)
703 }
704 }
705
706 // OCSP peer check (client mTLS, leaf mTLS, leaf remote TLS)
707 if config.kind == kindStringMap[CLIENT] || config.kind == kindStringMap[LEAF] {
708 tc, plugged, err := s.plugTLSOCSPPeer(config)
709 if err != nil {
710 return err
711 }
712 if plugged && tc != nil {
713 s.ocspPeerVerify = true
714 config.apply(tc)
715 }
716 }
717 }
718
719 return nil
720 }
721
722 func (s *Server) startOCSPMonitoring() {
723 s.mu.Lock()
724 ocsps := s.ocsps
725 s.mu.Unlock()
726 if ocsps == nil {
727 return
728 }
729 for _, mon := range ocsps {
730 m := mon
731 m.mu.Lock()
732 kind := m.kind
733 m.mu.Unlock()
734 s.Noticef("OCSP Stapling enabled for %s connections", kind)
735 s.startGoRoutine(func() { m.run() })
736 }
737 }
738
739 func (s *Server) reloadOCSP() error {
740 if err := s.setupOCSPStapleStoreDir(); err != nil {
741 return err
742 }
743
744 s.mu.Lock()
745 ocsps := s.ocsps
746 s.mu.Unlock()
747
748 // Stop all OCSP Stapling monitors in case there were any running.
749 for _, oc := range ocsps {
750 oc.stop()
751 }
752
753 configs := s.configureOCSP()
754
755 // Restart the monitors under the new configuration.
756 ocspm := make([]*OCSPMonitor, 0)
757
758 // Reset server's ocspPeerVerify flag to re-detect at least one plugged OCSP peer
759 s.mu.Lock()
760 s.ocspPeerVerify = false
761 s.mu.Unlock()
762 s.stopOCSPResponseCache()
763
764 for _, config := range configs {
765 // We do not staple Leaf Hub and Leaf Spokes, use ocsp_peer
766 if config.kind != kindStringMap[LEAF] {
767 tc, mon, err := s.NewOCSPMonitor(config)
768 if err != nil {
769 return err
770 }
771 // Check if an OCSP stapling monitor is required for this certificate.
772 if mon != nil {
773 ocspm = append(ocspm, mon)
774
775 // Apply latest TLS configuration after OCSP monitors have started.
776 defer config.apply(tc)
777 }
778 }
779
780 // OCSP peer check (client mTLS, leaf mTLS, leaf remote TLS)
781 if config.kind == kindStringMap[CLIENT] || config.kind == kindStringMap[LEAF] {
782 tc, plugged, err := s.plugTLSOCSPPeer(config)
783 if err != nil {
784 return err
785 }
786 if plugged && tc != nil {
787 s.ocspPeerVerify = true
788 defer config.apply(tc)
789 }
790 }
791 }
792
793 // Replace stopped monitors with the new ones.
794 s.mu.Lock()
795 s.ocsps = ocspm
796 s.mu.Unlock()
797
798 // Dispatch all goroutines once again.
799 s.startOCSPMonitoring()
800
801 // Init and restart OCSP responder cache
802 s.stopOCSPResponseCache()
803 s.initOCSPResponseCache()
804 s.startOCSPResponseCache()
805
806 return nil
807 }
808
809 func hasOCSPStatusRequest(cert *x509.Certificate) bool {
810 // OID for id-pe-tlsfeature defined in RFC here:
811 // https://datatracker.ietf.org/doc/html/rfc7633
812 tlsFeatures := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 24}
813 const statusRequestExt = 5
814
815 // Example values:
816 // * [48 3 2 1 5] - seen when creating own certs locally
817 // * [30 3 2 1 5] - seen in the wild
818 // Documentation:
819 // https://tools.ietf.org/html/rfc6066
820
821 for _, ext := range cert.Extensions {
822 if !ext.Id.Equal(tlsFeatures) {
823 continue
824 }
825
826 var val []int
827 rest, err := asn1.Unmarshal(ext.Value, &val)
828 if err != nil || len(rest) > 0 {
829 return false
830 }
831
832 for _, n := range val {
833 if n == statusRequestExt {
834 return true
835 }
836 }
837 break
838 }
839
840 return false
841 }
842
843 // writeOCSPStatus writes an OCSP status to a temporary file then moves it to a
844 // new path, in an attempt to avoid corrupting existing data.
845 func (oc *OCSPMonitor) writeOCSPStatus(storeDir, file string, data []byte) error {
846 storeDir = filepath.Join(storeDir, defaultOCSPStoreDir)
847 tmp, err := os.CreateTemp(storeDir, "tmp-cert-status")
848 if err != nil {
849 return err
850 }
851
852 if _, err := tmp.Write(data); err != nil {
853 tmp.Close()
854 os.Remove(tmp.Name())
855 return err
856 }
857 if err := tmp.Close(); err != nil {
858 return err
859 }
860
861 oc.mu.Lock()
862 err = os.Rename(tmp.Name(), filepath.Join(storeDir, file))
863 oc.mu.Unlock()
864 if err != nil {
865 os.Remove(tmp.Name())
866 return err
867 }
868
869 return nil
870 }
871
872 func parseCertPEM(name string) ([]*x509.Certificate, error) {
873 data, err := os.ReadFile(name)
874 if err != nil {
875 return nil, err
876 }
877
878 var pemBytes []byte
879
880 var block *pem.Block
881 for len(data) != 0 {
882 block, data = pem.Decode(data)
883 if block == nil {
884 break
885 }
886 if block.Type != "CERTIFICATE" {
887 return nil, fmt.Errorf("unexpected PEM certificate type: %s", block.Type)
888 }
889
890 pemBytes = append(pemBytes, block.Bytes...)
891 }
892
893 return x509.ParseCertificates(pemBytes)
894 }
895
896 // getOCSPIssuerLocally determines a leaf's issuer from locally configured certificates
897 func getOCSPIssuerLocally(trustedCAs []*x509.Certificate, certBundle []*x509.Certificate) (*x509.Certificate, error) {
898 var vOpts x509.VerifyOptions
899 var leaf *x509.Certificate
900 trustedCAPool := x509.NewCertPool()
901
902 // Require Leaf as first cert in bundle
903 if len(certBundle) > 0 {
904 leaf = certBundle[0]
905 } else {
906 return nil, fmt.Errorf("invalid ocsp ca configuration")
907 }
908
909 // Allow Issuer to be configured as second cert in bundle
910 if len(certBundle) > 1 {
911 // The operator may have misconfigured the cert bundle
912 issuerCandidate := certBundle[1]
913 err := issuerCandidate.CheckSignature(leaf.SignatureAlgorithm, leaf.RawTBSCertificate, leaf.Signature)
914 if err != nil {
915 return nil, fmt.Errorf("invalid issuer configuration: %w", err)
916 } else {
917 return issuerCandidate, nil
918 }
919 }
920
921 // Operator did not provide the Leaf Issuer in cert bundle second position
922 // so we will attempt to create at least one ordered verified chain from the
923 // trusted CA pool.
924
925 // Specify CA trust store to validator; if unset, system trust store used
926 if len(trustedCAs) > 0 {
927 for _, ca := range trustedCAs {
928 trustedCAPool.AddCert(ca)
929 }
930 vOpts.Roots = trustedCAPool
931 }
932
933 return certstore.GetLeafIssuer(leaf, vOpts), nil
934 }
935
936 // getOCSPIssuer determines an issuer certificate from the cert (bundle) or the file-based CA trust store
937 func getOCSPIssuer(caFile string, chain [][]byte) (*x509.Certificate, error) {
938 var issuer *x509.Certificate
939 var trustedCAs []*x509.Certificate
940 var certBundle []*x509.Certificate
941 var err error
942
943 // FIXME(tgb): extend if pluggable CA store provider added to NATS (i.e. other than PEM file)
944
945 // Non-system default CA trust store passed
946 if caFile != _EMPTY_ {
947 trustedCAs, err = parseCertPEM(caFile)
948 if err != nil {
949 return nil, fmt.Errorf("failed to parse ca_file: %v", err)
950 }
951 }
952
953 // Specify bundled intermediate CA store
954 for _, certBytes := range chain {
955 cert, err := x509.ParseCertificate(certBytes)
956 if err != nil {
957 return nil, fmt.Errorf("failed to parse cert: %v", err)
958 }
959 certBundle = append(certBundle, cert)
960 }
961
962 issuer, err = getOCSPIssuerLocally(trustedCAs, certBundle)
963 if err != nil || issuer == nil {
964 return nil, fmt.Errorf("no issuers found")
965 }
966
967 if !issuer.IsCA {
968 return nil, fmt.Errorf("%s invalid ca basic constraints: is not ca", issuer.Subject)
969 }
970 return issuer, nil
971 }
972
973 func ocspStatusString(n int) string {
974 switch n {
975 case ocsp.Good:
976 return "good"
977 case ocsp.Revoked:
978 return "revoked"
979 default:
980 return "unknown"
981 }
982 }
983
984 func validOCSPResponse(r *ocsp.Response) error {
985 // Time validation not handled by ParseResponse.
986 // https://tools.ietf.org/html/rfc6960#section-4.2.2.1
987 if !r.NextUpdate.IsZero() && r.NextUpdate.Before(time.Now()) {
988 t := r.NextUpdate.Format(time.RFC3339Nano)
989 return fmt.Errorf("invalid ocsp NextUpdate, is past time: %s", t)
990 }
991 if r.ThisUpdate.After(time.Now()) {
992 t := r.ThisUpdate.Format(time.RFC3339Nano)
993 return fmt.Errorf("invalid ocsp ThisUpdate, is future time: %s", t)
994 }
995
996 return nil
997 }