-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify.go
173 lines (136 loc) · 4.86 KB
/
verify.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"os"
"regexp"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
log "github.com/sirupsen/logrus"
)
var (
expiredCertsGauge = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "tls_verifier_seconds_to_expiration_tls_certificate",
Help: "Seconds to expiration for the TLS certificate of the service",
}, []string{"namespace", "service", "port", "issuer", "serialnumber"})
discoveredCertsGauge = promauto.NewGauge(prometheus.GaugeOpts{
Name: "tls_verifier_discovered_tls_certificates_of_services",
Help: "How many TLS certificates have been discovered across all the services",
})
hearthbeatCounter = promauto.NewCounter(prometheus.CounterOpts{
Name: "tls_verifier_heartbeat",
Help: "heartbeat counter that keeps increasing if service is healthy",
})
)
func testTLS(tlsTimeout time.Duration, svc string, namespace string, port int32) (bool, int) {
fullhostname := fmt.Sprintf("%s.%s.svc.cluster.local:%d", svc, namespace, port)
conf := tls.Config{
InsecureSkipVerify: true,
}
dialer := &net.Dialer{
Timeout: tlsTimeout,
}
conn, err := tls.DialWithDialer(dialer, "tcp", fullhostname, &conf)
if err != nil {
log.Errorf("Could not start a TLS connection to %s: %v\n", fullhostname, err)
return false, 0
}
defer conn.Close()
_, err = conn.Write([]byte("ping\n"))
if err != nil {
log.Errorf("Could not send data to %s: %v\n", fullhostname, err)
return false, 0
}
certs := conn.ConnectionState().PeerCertificates
certsExpiryDates := make([]string, 10)
discoveredTLScerts := 0
for _, cert := range certs {
discoveredTLScerts++
certsExpiryDates = append(certsExpiryDates, cert.NotAfter.Format("2006-January-02"))
timeToExpiration := cert.NotAfter.Sub(time.Now())
expiredCertsGauge.WithLabelValues(namespace, svc, strconv.Itoa(int(port)), cert.Issuer.CommonName, cert.Issuer.SerialNumber).Set(timeToExpiration.Seconds())
}
log.Infof("TLS connection was successful to %s. Certs expiration dates: %v\n", fullhostname, certsExpiryDates)
return true, discoveredTLScerts
}
func discoverServices(discoverFrequency time.Duration, tlsTimeout time.Duration, skipNamespaceRegex string) int {
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
r, err := regexp.Compile(skipNamespaceRegex)
if skipNamespaceRegex != "" && err != nil {
panic(err.Error())
}
for {
discoveredTLScertificates := 0
services, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
log.Infof("Scanning for %d services for expired TLS certificates ...\n", len(services.Items))
for _, svc := range services.Items {
ports := svc.Spec.Ports
ns := svc.GetNamespace()
svcName := svc.GetName()
if skipNamespaceRegex != "" && r.Match([]byte(ns)) {
log.Infof("Skipping service:%s in namespace: %s", svcName, ns)
continue
}
for _, port := range ports {
if ok, certsNum := testTLS(tlsTimeout, svcName, ns, port.Port); ok {
discoveredTLScertificates += certsNum
}
}
}
discoveredCertsGauge.Set(float64(discoveredTLScertificates))
hearthbeatCounter.Inc()
log.Infof("Sleeping for %v until the next scan", discoverFrequency)
time.Sleep(discoverFrequency)
}
}
func main() {
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
discoverFrequency := flag.String("frequency", "2h", "How often to scan for new TLS certs")
tlsTimeout := flag.String("timeout", "400ms", "Connection timeout to TLS endpoints")
skipNamespaceRegex := flag.String("skip-namespace-regex", "", "Namespaces matching this regex get skipped")
port := flag.Int("port", 9999, "the tcp port where to listen on")
flag.Parse()
discoverFrequencyDuration, err := time.ParseDuration(*discoverFrequency)
if err != nil {
fmt.Printf("Invalid specified frequency: %v\n", err)
os.Exit(1)
}
tlsTimeoutDuration, err := time.ParseDuration(*tlsTimeout)
if err != nil {
fmt.Printf("Invalid specified TLS timeout: %v\n", err)
os.Exit(1)
}
go discoverServices(discoverFrequencyDuration, tlsTimeoutDuration, *skipNamespaceRegex)
healthcheckHandler := func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Mi sento bene!")
}
listenAddr := fmt.Sprintf(":%d", *port)
log.Infof("Listening for metrics and healthchecks on %s", listenAddr)
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/livez", healthcheckHandler) /* useful for k8s healthchecks */
http.HandleFunc("/healthz", healthcheckHandler)
http.ListenAndServe(listenAddr, nil)
}