From ded36374e8ab30b6504d4c63ae24bc49b2ee75ae Mon Sep 17 00:00:00 2001 From: Anis Eleuch Date: Thu, 18 Jul 2024 17:08:07 +0100 Subject: [PATCH] Show a warning when the server certificate duration is expiring soon (#4989) When 90% of the validity time of a server is elapsed, print a warning reminding the user to change the certificate. --- cmd/client-s3.go | 30 ++++++++++++++++++++++++++++++ cmd/main.go | 11 +++++++++++ 2 files changed, 41 insertions(+) diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 9cb875bf..f9512ca3 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -147,6 +147,31 @@ func isHostTLS(config *Config) bool { return useTLS } +type notifyExpiringTLS struct { + transport http.RoundTripper +} + +var globalExpiringCerts sync.Map + +func (n notifyExpiringTLS) RoundTrip(req *http.Request) (res *http.Response, err error) { + if n.transport == nil { + return nil, errors.New("invalid transport") + } + + res, err = n.transport.RoundTrip(req) + if err != nil || res.TLS == nil || len(res.TLS.PeerCertificates) == 0 { + return res, err + } + + cert := res.TLS.PeerCertificates[0] // leaf certificate + validityDur := cert.NotAfter.Sub(cert.NotBefore) + if time.Since(cert.NotBefore) > time.Duration(0.9*float64(validityDur)) { + globalExpiringCerts.Store(req.Host, cert.NotAfter) + } + + return res, err +} + // getTransportForConfig returns a corresponding *http.Transport for the *Config // set withS3v2 bool to true to add traceV2 tracer. func getTransportForConfig(config *Config, withS3v2 bool) http.RoundTripper { @@ -208,7 +233,12 @@ func getTransportForConfig(config *Config, withS3v2 bool) http.RoundTripper { } else if strings.EqualFold(config.Signature, "S3v2") && withS3v2 { transport = httptracer.GetNewTraceTransport(newTraceV2(), transport) } + } else { + if !globalJSONLine && !globalJSON { + transport = notifyExpiringTLS{transport: transport} + } } + transport = gzhttp.Transport(transport) return transport } diff --git a/cmd/main.go b/cmd/main.go index a32c3059..569fecd3 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -507,6 +507,17 @@ func registerApp(name string) *cli.App { app.CustomAppHelpTemplate = mcHelpTemplate app.EnableBashCompletion = true app.OnUsageError = onUsageError + app.After = func(*cli.Context) error { + globalExpiringCerts.Range(func(k, v interface{}) bool { + host := k.(string) + expires := v.(time.Time) + fmt.Fprintf(os.Stderr, "\n") + fmt.Fprintf(os.Stderr, "== WARN: `%s` certificate will expire in %s. Renew soon to avoid outage.\n", host, expires) + fmt.Fprintf(os.Stderr, "\n") + return true + }) + return nil + } if isTerminal() && !globalPagerDisabled { app.HelpWriter = globalHelpPager