forked from megaease/easeprobe
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* introduce tls probe * load str instead of byte * add readme * fix type * add metrics * metric inspired from blackbox * happy lint * add comments * update the README.md Co-authored-by: Hao Chen <[email protected]>
- Loading branch information
Showing
5 changed files
with
520 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
/* | ||
* Copyright (c) 2022, MegaEase | ||
* All rights reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http:https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package tls | ||
|
||
import ( | ||
"crypto/tls" | ||
"time" | ||
|
||
"github.com/megaease/easeprobe/global" | ||
"github.com/megaease/easeprobe/metric" | ||
"github.com/prometheus/client_golang/prometheus" | ||
) | ||
|
||
// code and metric idea from https://github.com/prometheus/blackbox_exporter/blob/master/prober/tls.go | ||
type metrics struct { | ||
EarliestCertExpiry *prometheus.GaugeVec | ||
LastChainExpiryTimestampSeconds *prometheus.GaugeVec | ||
} | ||
|
||
// newMetrics create the HTTP metrics | ||
func newMetrics(subsystem, name string) *metrics { | ||
namespace := global.GetEaseProbe().Name | ||
return &metrics{ | ||
EarliestCertExpiry: metric.NewGauge(namespace, subsystem, name, "earliest_cert_expiry", | ||
"last TLS chain expiry in timestamp seconds", []string{}), | ||
LastChainExpiryTimestampSeconds: metric.NewGauge(namespace, subsystem, name, "last_chain_expiry_timestamp_seconds", | ||
"earliest TLS cert expiry in unixtime", []string{}), | ||
} | ||
} | ||
|
||
func getEarliestCertExpiry(state *tls.ConnectionState) time.Time { | ||
earliest := time.Time{} | ||
for _, cert := range state.PeerCertificates { | ||
if (earliest.IsZero() || cert.NotAfter.Before(earliest)) && !cert.NotAfter.IsZero() { | ||
earliest = cert.NotAfter | ||
} | ||
} | ||
return earliest | ||
} | ||
|
||
func getLastChainExpiry(state *tls.ConnectionState) time.Time { | ||
lastChainExpiry := time.Time{} | ||
for _, chain := range state.VerifiedChains { | ||
earliestCertExpiry := time.Time{} | ||
for _, cert := range chain { | ||
if (earliestCertExpiry.IsZero() || cert.NotAfter.Before(earliestCertExpiry)) && !cert.NotAfter.IsZero() { | ||
earliestCertExpiry = cert.NotAfter | ||
} | ||
} | ||
if lastChainExpiry.IsZero() || lastChainExpiry.Before(earliestCertExpiry) { | ||
lastChainExpiry = earliestCertExpiry | ||
} | ||
|
||
} | ||
return lastChainExpiry | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/* | ||
* Copyright (c) 2022, MegaEase | ||
* All rights reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http:https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package tls | ||
|
||
import ( | ||
"context" | ||
"crypto/tls" | ||
"crypto/x509" | ||
"fmt" | ||
"io/ioutil" | ||
"net" | ||
"strings" | ||
"time" | ||
|
||
"github.com/megaease/easeprobe/global" | ||
"github.com/megaease/easeprobe/probe/base" | ||
"github.com/prometheus/client_golang/prometheus" | ||
|
||
log "github.com/sirupsen/logrus" | ||
) | ||
|
||
// TLS implements a config for TLS | ||
type TLS struct { | ||
base.DefaultOptions `yaml:",inline"` | ||
Host string `yaml:"host"` | ||
InsecureSkipVerify bool `yaml:"insecure_skip_verify"` | ||
|
||
RootCAPemPath string `yaml:"root_ca_pem_path"` | ||
RootCaPem string `yaml:"root_ca_pem"` | ||
rootCAs *x509.CertPool | ||
|
||
ExpireSkipVerify bool `yaml:"expire_skip_verify"` | ||
|
||
metrics *metrics | ||
} | ||
|
||
// Config HTTP Config Object | ||
func (t *TLS) Config(gConf global.ProbeSettings) error { | ||
kind := "tls" | ||
tag := "" | ||
name := t.ProbeName | ||
t.DefaultOptions.Config(gConf, kind, tag, name, t.Host, t.DoProbe) | ||
|
||
rootCaPem := []byte(t.RootCaPem) | ||
|
||
if len(rootCaPem) == 0 && t.RootCAPemPath != "" { | ||
var err error | ||
rootCaPem, err = ioutil.ReadFile(t.RootCAPemPath) | ||
if err != nil { | ||
return err | ||
} | ||
} | ||
|
||
if len(rootCaPem) > 0 { | ||
t.rootCAs = x509.NewCertPool() | ||
if !(t.rootCAs.AppendCertsFromPEM(rootCaPem)) { | ||
return fmt.Errorf("cannot parse root ca pem") | ||
} | ||
} | ||
|
||
t.metrics = newMetrics(kind, tag) | ||
|
||
log.Debugf("[%s] configuration: %+v, %+v", t.ProbeKind, t, t.Result()) | ||
return nil | ||
} | ||
|
||
// DoProbe return the checking result | ||
func (t *TLS) DoProbe() (bool, string) { | ||
addr := t.Host | ||
conn, err := net.DialTimeout("tcp", addr, t.Timeout()) | ||
if err != nil { | ||
log.Errorf("tcp dial error: %v", err) | ||
return false, fmt.Sprintf("tcp dial error: %v", err) | ||
} | ||
defer conn.Close() | ||
|
||
colonPos := strings.LastIndex(addr, ":") | ||
if colonPos == -1 { | ||
colonPos = len(addr) | ||
} | ||
hostname := addr[:colonPos] | ||
|
||
tconn := tls.Client(conn, &tls.Config{ | ||
InsecureSkipVerify: t.InsecureSkipVerify, | ||
RootCAs: t.rootCAs, | ||
ServerName: hostname, | ||
}) | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), t.Timeout()) | ||
defer cancel() | ||
err = tconn.HandshakeContext(ctx) | ||
if err != nil { | ||
log.Errorf("tls handshake error: %v", err) | ||
return false, fmt.Sprintf("tls handshake error: %v", err) | ||
} | ||
|
||
if !t.ExpireSkipVerify { | ||
for _, cert := range tconn.ConnectionState().PeerCertificates { | ||
valid := true | ||
valid = valid && !time.Now().After(cert.NotAfter) | ||
valid = valid && !time.Now().Before(cert.NotBefore) | ||
|
||
if !valid { | ||
log.Errorf("host %v cert expired", t.Host) | ||
return false, "certificate is expired or not yet valid" | ||
} | ||
} | ||
} | ||
|
||
state := tconn.ConnectionState() | ||
|
||
t.metrics.EarliestCertExpiry.With(prometheus.Labels{}).Set(float64(getEarliestCertExpiry(&state).Unix())) | ||
t.metrics.LastChainExpiryTimestampSeconds.With(prometheus.Labels{}).Set(float64(getLastChainExpiry(&state).Unix())) | ||
|
||
return true, "TLS Endpoint Verified Successfully!" | ||
} |
Oops, something went wrong.