Skip to content

Commit

Permalink
Emit certificate expiration metrics for client certificates used in h…
Browse files Browse the repository at this point in the history
…andshake
  • Loading branch information
Mitali Rawat committed Jul 8, 2020
1 parent cdf0b58 commit cd1c948
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
51 changes: 51 additions & 0 deletions certmetrics/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Package certmetrics will be used to register and emit metrics for certificates in memory
package certmetrics

import (
"crypto/x509"
"sort"
"strings"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)

var certificateExpirationTimes = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "certificate_expiration_timestamp_seconds",
Help: "Expiration times of gokeyless certs",
},
[]string{"serial_no", "cn", "hostnames", "ca", "server", "client"},
)

// Observe takes in a list of certs and emits its expiration times
func Observe(certs ...*x509.Certificate) {
for _, cert := range certs {
hostnames := cert.DNSNames
sort.Strings(hostnames)
labels := prometheus.Labels{
"serial_no": cert.SerialNumber.String(),
"cn": cert.Subject.CommonName,
"hostnames": strings.Join(hostnames, ","),
"ca": boolToBinaryString(cert.IsCA),
"server": containsKeyUsage(cert.ExtKeyUsage, x509.ExtKeyUsageServerAuth),
"client": containsKeyUsage(cert.ExtKeyUsage, x509.ExtKeyUsageClientAuth)}
certificateExpirationTimes.With(labels).Set(float64(cert.NotAfter.Unix()))
}
}

func boolToBinaryString(val bool) string {
if val {
return "1"
}
return "0"
}

func containsKeyUsage(a []x509.ExtKeyUsage, x x509.ExtKeyUsage) string {
for _, e := range a {
if e == x || e == x509.ExtKeyUsageAny {
return "1"
}
}
return "0"
}
6 changes: 5 additions & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import (
"sync"
"time"

"github.com/cloudflare/gokeyless/certmetrics"

"github.com/cloudflare/cfssl/helpers"
"github.com/cloudflare/cfssl/helpers/derhelpers"
"github.com/cloudflare/cfssl/log"
Expand Down Expand Up @@ -644,7 +646,9 @@ func (s *Server) spawn(l net.Listener, c net.Conn) {
tconn.Close()
return
}
limited, err := s.config.isLimited(tconn.ConnectionState())
connState := tconn.ConnectionState()
certmetrics.Observe(connState.PeerCertificates...)
limited, err := s.config.isLimited(connState)
if err != nil {
log.Errorf("connection %v: could not determine if limited: %v", c.RemoteAddr(), err)
tconn.Close()
Expand Down

0 comments on commit cd1c948

Please # to comment.