feat(check): gRPC, SMTP, RADIUS and SNMP checks
gRPC asks the standard health service, optionally about one service. SMTP waits for the greeting, says EHLO and, unless disabled, requires STARTTLS or connects with implicit TLS. RADIUS sends an Access-Request signed with a Message-Authenticator and tells a rejected login from a wrong shared secret. SNMP v1/v2c reads one OID and compares its value textually or numerically, hinting at the community when the agent stays silent. All go through the network guard. Errors from dialing are no longer passed through redaction, and secrets shorter than four characters are left in messages instead of garbling them. Refs #95 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
302514dc35
commit
03f6e9137f
8 files changed
+675
-4
No files matched your search
@@ -34,7 +34,7 @@ const (
|
||||
)
|
||||
|
||||
// Types lists every check type.
|
||||
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ, Heartbeat, Alertmanager}
|
||||
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ, GRPC, SMTP, RADIUS, SNMP, Heartbeat, Alertmanager}
|
||||
|
||||
// Passive reports whether t is reported to us rather than run by checkers.
|
||||
func Passive(t Type) bool { return t == Heartbeat || t == Alertmanager }
|
||||
@@ -105,6 +105,10 @@ var impls = map[Type]impl{
|
||||
MQTT: brokerCheck{MQTT},
|
||||
Kafka: brokerCheck{Kafka},
|
||||
RabbitMQ: brokerCheck{RabbitMQ},
|
||||
GRPC: grpcCheck{},
|
||||
SMTP: smtpCheck{},
|
||||
RADIUS: radiusCheck{},
|
||||
SNMP: snmpCheck{},
|
||||
Heartbeat: heartbeatCheck{},
|
||||
Alertmanager: alertmanagerCheck{},
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ func TestValidate(t *testing.T) {
|
||||
{TCP, "x.test:0", `{}`, "invalid_target"},
|
||||
{DNS, "x.test", `{"record":"SRV"}`, "invalid_record"},
|
||||
{TLS, "x.test:443", `{"min_days_valid":-1}`, "invalid_config"},
|
||||
{"smtp", "x.test", `{}`, "invalid_type"},
|
||||
{"gopher", "x.test", `{}`, "invalid_type"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
_, err := Validate(tt.typ, tt.target, json.RawMessage(tt.config))
|
||||
|
||||
@@ -54,6 +54,10 @@ func SecretFields(t Type) []string {
|
||||
switch t {
|
||||
case Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ:
|
||||
return []string{"password"}
|
||||
case RADIUS:
|
||||
return []string{"password", "secret"}
|
||||
case SNMP:
|
||||
return []string{"community"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
package check
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/md5" //nolint:gosec // RADIUS defines Message-Authenticator as HMAC-MD5
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gosnmp/gosnmp"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
healthpb "google.golang.org/grpc/health/grpc_health_v1"
|
||||
"layeh.com/radius"
|
||||
"layeh.com/radius/rfc2865"
|
||||
"layeh.com/radius/rfc2869"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
||||
)
|
||||
|
||||
// Protocol checks speak a service's own protocol beyond a TCP connect.
|
||||
const (
|
||||
GRPC Type = "grpc"
|
||||
SMTP Type = "smtp"
|
||||
RADIUS Type = "radius"
|
||||
SNMP Type = "snmp"
|
||||
)
|
||||
|
||||
// GRPCConfig configures a check against the standard gRPC health service.
|
||||
type GRPCConfig struct {
|
||||
// Service is asked about; empty asks about the server as a whole.
|
||||
Service string `json:"service,omitempty"`
|
||||
TLS string `json:"tls"`
|
||||
}
|
||||
|
||||
type grpcCheck struct{}
|
||||
|
||||
func (grpcCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validHostPort(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
c := GRPCConfig{TLS: "verify"}
|
||||
if err := json.Unmarshal(config, &c); err != nil || !validTLSMode(c.TLS) || len(c.Service) > 200 {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
return encode(c), nil
|
||||
}
|
||||
|
||||
func (grpcCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
c, err := decode[GRPCConfig](s.Config)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid configuration"}
|
||||
}
|
||||
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
|
||||
creds := insecure.NewCredentials()
|
||||
if c.TLS != "disable" {
|
||||
creds = credentials.NewTLS(tlsFor(c.TLS, s.Target))
|
||||
}
|
||||
conn, err := grpc.NewClient("passthrough:///"+s.Target,
|
||||
grpc.WithTransportCredentials(creds),
|
||||
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
|
||||
return d.DialContext(ctx, "tcp", addr)
|
||||
}))
|
||||
if err != nil {
|
||||
return Outcome{Error: truncate(err.Error(), 300)}
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
resp, err := healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{Service: c.Service})
|
||||
if err != nil {
|
||||
return Outcome{Error: truncate(err.Error(), 300)}
|
||||
}
|
||||
if st := resp.GetStatus(); st != healthpb.HealthCheckResponse_SERVING {
|
||||
return Outcome{Error: "health status " + st.String()}
|
||||
}
|
||||
return Outcome{OK: true}
|
||||
}
|
||||
|
||||
// SMTPConfig configures a mail server check.
|
||||
type SMTPConfig struct {
|
||||
// TLS "disable" only greets; otherwise STARTTLS must succeed, or, with
|
||||
// ImplicitTLS (port 465), the connection starts encrypted.
|
||||
TLS string `json:"tls"`
|
||||
ImplicitTLS bool `json:"implicit_tls,omitempty"`
|
||||
}
|
||||
|
||||
type smtpCheck struct{}
|
||||
|
||||
func (smtpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validHostPort(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
c := SMTPConfig{TLS: "verify"}
|
||||
if err := json.Unmarshal(config, &c); err != nil || !validTLSMode(c.TLS) || c.ImplicitTLS && c.TLS == "disable" {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
return encode(c), nil
|
||||
}
|
||||
|
||||
func (smtpCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
c, err := decode[SMTPConfig](s.Config)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid configuration"}
|
||||
}
|
||||
conn, err := netguard.Dialer(s.AllowPrivate, s.Timeout).DialContext(ctx, "tcp", s.Target)
|
||||
if err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
if dl, ok := ctx.Deadline(); ok {
|
||||
_ = conn.SetDeadline(dl)
|
||||
}
|
||||
if c.ImplicitTLS {
|
||||
tc := tls.Client(conn, tlsFor(c.TLS, s.Target))
|
||||
if err := tc.HandshakeContext(ctx); err != nil {
|
||||
return Outcome{Error: truncate(err.Error(), 300)}
|
||||
}
|
||||
conn = tc
|
||||
}
|
||||
host, _, _ := net.SplitHostPort(s.Target)
|
||||
client, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return Outcome{Error: "greeting: " + truncate(err.Error(), 300)}
|
||||
}
|
||||
if err := client.Hello("uptimesebi"); err != nil {
|
||||
return Outcome{Error: "EHLO: " + truncate(err.Error(), 300)}
|
||||
}
|
||||
if c.TLS != "disable" && !c.ImplicitTLS {
|
||||
if ok, _ := client.Extension("STARTTLS"); !ok {
|
||||
return Outcome{Error: "server does not offer STARTTLS"}
|
||||
}
|
||||
if err := client.StartTLS(tlsFor(c.TLS, s.Target)); err != nil {
|
||||
return Outcome{Error: "STARTTLS: " + truncate(err.Error(), 300)}
|
||||
}
|
||||
}
|
||||
_ = client.Quit()
|
||||
return Outcome{OK: true}
|
||||
}
|
||||
|
||||
// RADIUSConfig configures an authentication check. Secret and Password
|
||||
// are secrets.
|
||||
type RADIUSConfig struct {
|
||||
Secret string `json:"secret,omitempty"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password,omitempty"`
|
||||
NASIdentifier string `json:"nas_identifier,omitempty"`
|
||||
}
|
||||
|
||||
type radiusCheck struct{}
|
||||
|
||||
func (radiusCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validHostPort(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
var c RADIUSConfig
|
||||
if err := json.Unmarshal(config, &c); err != nil || c.User == "" || len(c.User) > 200 ||
|
||||
len(c.Secret) > 200 || len(c.Password) > 128 || len(c.NASIdentifier) > 200 {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
return encode(c), nil
|
||||
}
|
||||
|
||||
func (radiusCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
c, err := decode[RADIUSConfig](s.Config)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid configuration"}
|
||||
}
|
||||
if c.Secret == "" {
|
||||
return Outcome{Error: "no shared secret configured"}
|
||||
}
|
||||
p := radius.New(radius.CodeAccessRequest, []byte(c.Secret))
|
||||
_ = rfc2865.UserName_SetString(p, c.User)
|
||||
_ = rfc2865.UserPassword_SetString(p, c.Password)
|
||||
nas := c.NASIdentifier
|
||||
if nas == "" {
|
||||
nas = "uptimesebi"
|
||||
}
|
||||
_ = rfc2865.NASIdentifier_SetString(p, nas)
|
||||
if err := signRADIUS(p); err != nil {
|
||||
return Outcome{Error: err.Error()}
|
||||
}
|
||||
client := radius.Client{Dialer: *netguard.Dialer(s.AllowPrivate, s.Timeout), Retry: timeoutOf(ctx) / 3, MaxPacketErrors: 1}
|
||||
resp, err := client.Exchange(ctx, p, s.Target)
|
||||
switch {
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return Outcome{Error: "no answer from the server"}
|
||||
case err != nil:
|
||||
var nonAuth *radius.NonAuthenticResponseError
|
||||
if errors.As(err, &nonAuth) {
|
||||
return Outcome{Error: "answer not signed with the shared secret"}
|
||||
}
|
||||
return Outcome{Error: redact(err, c.Secret, c.Password)}
|
||||
}
|
||||
switch resp.Code {
|
||||
case radius.CodeAccessAccept, radius.CodeAccessChallenge:
|
||||
return Outcome{OK: true}
|
||||
case radius.CodeAccessReject:
|
||||
msg := "access rejected"
|
||||
if reply := rfc2865.ReplyMessage_GetString(resp); reply != "" {
|
||||
msg += ": " + truncate(reply, 200)
|
||||
}
|
||||
return Outcome{Error: msg}
|
||||
}
|
||||
return Outcome{Error: "unexpected answer " + resp.Code.String()}
|
||||
}
|
||||
|
||||
// signRADIUS adds a Message-Authenticator, which servers protecting
|
||||
// against BlastRADIUS require.
|
||||
func signRADIUS(p *radius.Packet) error {
|
||||
if err := rfc2869.MessageAuthenticator_Set(p, make([]byte, md5.Size)); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := p.Encode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mac := hmac.New(md5.New, p.Secret)
|
||||
mac.Write(raw)
|
||||
return rfc2869.MessageAuthenticator_Set(p, mac.Sum(nil))
|
||||
}
|
||||
|
||||
// SNMPConfig configures a check reading one OID. Community is a secret.
|
||||
type SNMPConfig struct {
|
||||
// Version is "1" or "2c".
|
||||
Version string `json:"version"`
|
||||
Community string `json:"community,omitempty"`
|
||||
OID string `json:"oid"`
|
||||
// Condition compares the value with Value: "" (any value), "eq", "ne",
|
||||
// "contains", or numerically "gt", "ge", "lt", "le".
|
||||
Condition string `json:"condition,omitempty"`
|
||||
Value string `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
var oidPattern = regexp.MustCompile(`^\.?[0-9]+(\.[0-9]+){1,127}$`)
|
||||
|
||||
type snmpCheck struct{}
|
||||
|
||||
func (snmpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validHostPort(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
c := SNMPConfig{Version: "2c"}
|
||||
if err := json.Unmarshal(config, &c); err != nil || !oidPattern.MatchString(c.OID) || len(c.Community) > 200 || len(c.Value) > 500 {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
if c.Version != "1" && c.Version != "2c" {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
switch c.Condition {
|
||||
case "":
|
||||
c.Value = ""
|
||||
case "eq", "ne", "contains":
|
||||
case "gt", "ge", "lt", "le":
|
||||
if _, ok := new(big.Float).SetString(c.Value); !ok {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
default:
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
return encode(c), nil
|
||||
}
|
||||
|
||||
func (snmpCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
c, err := decode[SNMPConfig](s.Config)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid configuration"}
|
||||
}
|
||||
host, port, _ := net.SplitHostPort(s.Target)
|
||||
p, _ := strconv.Atoi(port)
|
||||
g := &gosnmp.GoSNMP{
|
||||
Target: host, Port: uint16(p), Transport: "udp", Community: c.Community, Version: gosnmp.Version2c,
|
||||
// Give up before the check's deadline to say why.
|
||||
Timeout: timeoutOf(ctx) * 4 / 5, Retries: 0, Context: ctx, MaxOids: 1,
|
||||
Control: netguard.Dialer(s.AllowPrivate, s.Timeout).Control,
|
||||
}
|
||||
if c.Community == "" {
|
||||
g.Community = "public"
|
||||
}
|
||||
if c.Version == "1" {
|
||||
g.Version = gosnmp.Version1
|
||||
}
|
||||
if err := g.Connect(); err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
defer func() { _ = g.Conn.Close() }()
|
||||
resp, err := g.Get([]string{c.OID})
|
||||
if err != nil && strings.Contains(err.Error(), "timeout") {
|
||||
// Agents silently drop requests with a wrong community.
|
||||
return Outcome{Error: "no answer from the agent; is the community or version right?"}
|
||||
}
|
||||
if err != nil {
|
||||
return Outcome{Error: redact(err, c.Community)}
|
||||
}
|
||||
if resp.Error != gosnmp.NoError {
|
||||
return Outcome{Error: "agent answered " + resp.Error.String()}
|
||||
}
|
||||
if len(resp.Variables) == 0 {
|
||||
return Outcome{Error: "agent returned no value"}
|
||||
}
|
||||
v := resp.Variables[0]
|
||||
var got string
|
||||
switch v.Type {
|
||||
case gosnmp.NoSuchObject, gosnmp.NoSuchInstance, gosnmp.EndOfMibView, gosnmp.Null:
|
||||
return Outcome{Error: c.OID + " does not exist on the agent"}
|
||||
case gosnmp.OctetString:
|
||||
b, _ := v.Value.([]byte)
|
||||
got = string(b)
|
||||
default:
|
||||
got = fmt.Sprint(v.Value)
|
||||
if n := gosnmp.ToBigInt(v.Value); n != nil && v.Type != gosnmp.ObjectIdentifier && v.Type != gosnmp.IPAddress {
|
||||
got = n.String()
|
||||
}
|
||||
}
|
||||
if !snmpMatches(c.Condition, got, c.Value) {
|
||||
return Outcome{Error: fmt.Sprintf("value %q does not satisfy %s %q", truncate(got, 100), c.Condition, truncate(c.Value, 100))}
|
||||
}
|
||||
return Outcome{OK: true}
|
||||
}
|
||||
|
||||
func snmpMatches(cond, got, want string) bool {
|
||||
switch cond {
|
||||
case "eq":
|
||||
return got == want
|
||||
case "ne":
|
||||
return got != want
|
||||
case "contains":
|
||||
return strings.Contains(got, want)
|
||||
case "gt", "ge", "lt", "le":
|
||||
a, ok1 := new(big.Float).SetString(strings.TrimSpace(got))
|
||||
b, ok2 := new(big.Float).SetString(want)
|
||||
if !ok1 || !ok2 {
|
||||
return false
|
||||
}
|
||||
r := a.Cmp(b)
|
||||
return cond == "gt" && r > 0 || cond == "ge" && r >= 0 || cond == "lt" && r < 0 || cond == "le" && r <= 0
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package check
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"math/big"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gosnmp/gosnmp"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/health"
|
||||
healthpb "google.golang.org/grpc/health/grpc_health_v1"
|
||||
"layeh.com/radius"
|
||||
"layeh.com/radius/rfc2865"
|
||||
)
|
||||
|
||||
func listen(t *testing.T) net.Listener {
|
||||
t.Helper()
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = l.Close() })
|
||||
return l
|
||||
}
|
||||
|
||||
func selfSigned(t *testing.T) tls.Certificate {
|
||||
t.Helper()
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "mail.test"},
|
||||
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
|
||||
}
|
||||
|
||||
func expectOutcomes(t *testing.T, typ Type, target string, cases map[string]string) {
|
||||
t.Helper()
|
||||
for cfg, want := range cases {
|
||||
o := runShort(t, typ, target, cfg)
|
||||
switch {
|
||||
case want == "" && !o.OK:
|
||||
t.Errorf("%s %s: %+v", typ, cfg, o)
|
||||
case want != "" && (o.OK || !strings.Contains(o.Error, want)):
|
||||
t.Errorf("%s %s: %+v, want error containing %q", typ, cfg, o, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGRPCCheck(t *testing.T) {
|
||||
l := listen(t)
|
||||
srv := grpc.NewServer()
|
||||
hs := health.NewServer()
|
||||
hs.SetServingStatus("shop", healthpb.HealthCheckResponse_SERVING)
|
||||
hs.SetServingStatus("billing", healthpb.HealthCheckResponse_NOT_SERVING)
|
||||
healthpb.RegisterHealthServer(srv, hs)
|
||||
go func() { _ = srv.Serve(l) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
expectOutcomes(t, GRPC, l.Addr().String(), map[string]string{
|
||||
`{"tls":"disable"}`: "",
|
||||
`{"tls":"disable","service":"shop"}`: "",
|
||||
`{"tls":"disable","service":"billing"}`: "NOT_SERVING",
|
||||
`{"tls":"disable","service":"unknown"}`: "NotFound",
|
||||
`{"tls":"require","service":"shop"}`: "Unavailable",
|
||||
})
|
||||
}
|
||||
|
||||
// smtpServer answers like a mail server, offering STARTTLS if cert is set.
|
||||
func smtpServer(t *testing.T, cert *tls.Certificate) string {
|
||||
l := listen(t)
|
||||
go func() {
|
||||
for {
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func(conn net.Conn) {
|
||||
defer func() { _ = conn.Close() }()
|
||||
r := bufio.NewReader(conn)
|
||||
write := func(s string) { _, _ = conn.Write([]byte(s + "\r\n")) }
|
||||
write("220 mail.test ESMTP")
|
||||
encrypted := false
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch cmd := strings.ToUpper(strings.Fields(line + " x")[0]); {
|
||||
case cmd == "EHLO" && cert != nil && !encrypted:
|
||||
write("250-mail.test")
|
||||
write("250 STARTTLS")
|
||||
case cmd == "EHLO":
|
||||
write("250 mail.test")
|
||||
case cmd == "STARTTLS":
|
||||
write("220 go ahead")
|
||||
tc := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{*cert}})
|
||||
if tc.Handshake() != nil {
|
||||
return
|
||||
}
|
||||
conn, r, encrypted = tc, bufio.NewReader(tc), true
|
||||
case cmd == "QUIT":
|
||||
write("221 bye")
|
||||
return
|
||||
default:
|
||||
write("250 ok")
|
||||
}
|
||||
}
|
||||
}(conn)
|
||||
}
|
||||
}()
|
||||
return l.Addr().String()
|
||||
}
|
||||
|
||||
func TestSMTPCheck(t *testing.T) {
|
||||
cert := selfSigned(t)
|
||||
expectOutcomes(t, SMTP, smtpServer(t, &cert), map[string]string{
|
||||
`{"tls":"disable"}`: "",
|
||||
`{"tls":"require"}`: "",
|
||||
`{"tls":"verify"}`: "certificate",
|
||||
})
|
||||
expectOutcomes(t, SMTP, smtpServer(t, nil), map[string]string{
|
||||
`{"tls":"disable"}`: "",
|
||||
`{"tls":"require"}`: "does not offer STARTTLS",
|
||||
})
|
||||
|
||||
// Implicit TLS (SMTPS).
|
||||
l := listen(t)
|
||||
tl := tls.NewListener(l, &tls.Config{Certificates: []tls.Certificate{cert}})
|
||||
go func() {
|
||||
for {
|
||||
conn, err := tl.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer func() { _ = conn.Close() }()
|
||||
_, _ = conn.Write([]byte("220 mail.test\r\n"))
|
||||
r := bufio.NewReader(conn)
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, _ = conn.Write([]byte("250 ok\r\n"))
|
||||
if strings.HasPrefix(line, "QUIT") {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}()
|
||||
expectOutcomes(t, SMTP, l.Addr().String(), map[string]string{`{"tls":"require","implicit_tls":true}`: ""})
|
||||
}
|
||||
|
||||
func TestRADIUSCheck(t *testing.T) {
|
||||
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := radius.PacketServer{
|
||||
SecretSource: radius.StaticSecretSource([]byte("shared-s3cret")),
|
||||
Handler: radius.HandlerFunc(func(w radius.ResponseWriter, r *radius.Request) {
|
||||
code := radius.CodeAccessReject
|
||||
if rfc2865.UserName_GetString(r.Packet) == "probe" && rfc2865.UserPassword_GetString(r.Packet) == "probe-pw" {
|
||||
code = radius.CodeAccessAccept
|
||||
}
|
||||
resp := r.Response(code)
|
||||
if code == radius.CodeAccessReject {
|
||||
_ = rfc2865.ReplyMessage_SetString(resp, "bad credentials")
|
||||
}
|
||||
_ = w.Write(resp)
|
||||
}),
|
||||
}
|
||||
go func() { _ = srv.Serve(pc) }()
|
||||
t.Cleanup(func() { _ = pc.Close() })
|
||||
expectOutcomes(t, RADIUS, pc.LocalAddr().String(), map[string]string{
|
||||
`{"secret":"shared-s3cret","user":"probe","password":"probe-pw"}`: "",
|
||||
`{"secret":"shared-s3cret","user":"probe","password":"wrong-pw-123"}`: "access rejected: bad credentials",
|
||||
`{"secret":"wrong-secret","user":"probe","password":"probe-pw"}`: "not signed with the shared secret",
|
||||
})
|
||||
}
|
||||
|
||||
// snmpAgent answers GET requests with community s3cret.
|
||||
func snmpAgent(t *testing.T) string {
|
||||
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pc.Close() })
|
||||
values := map[string]gosnmp.SnmpPDU{
|
||||
".1.3.6.1.2.1.1.5.0": {Type: gosnmp.OctetString, Value: []byte("core-sw-1")},
|
||||
".1.3.6.1.2.1.2.1.0": {Type: gosnmp.Integer, Value: 48},
|
||||
}
|
||||
go func() {
|
||||
buf := make([]byte, 65535)
|
||||
for {
|
||||
n, addr, err := pc.ReadFrom(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req, err := (&gosnmp.GoSNMP{}).SnmpDecodePacket(buf[:n])
|
||||
if err != nil || req.Community != "s3cret" || len(req.Variables) == 0 {
|
||||
continue
|
||||
}
|
||||
name := req.Variables[0].Name
|
||||
v, ok := values[name]
|
||||
if !ok {
|
||||
v = gosnmp.SnmpPDU{Type: gosnmp.NoSuchObject}
|
||||
}
|
||||
v.Name = name
|
||||
resp := &gosnmp.SnmpPacket{Version: req.Version, Community: req.Community, PDUType: gosnmp.GetResponse, RequestID: req.RequestID, Variables: []gosnmp.SnmpPDU{v}}
|
||||
out, err := resp.MarshalMsg()
|
||||
if err == nil {
|
||||
_, _ = pc.WriteTo(out, addr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return pc.LocalAddr().String()
|
||||
}
|
||||
|
||||
func TestSNMPCheck(t *testing.T) {
|
||||
expectOutcomes(t, SNMP, snmpAgent(t), map[string]string{
|
||||
`{"community":"s3cret","oid":"1.3.6.1.2.1.1.5.0"}`: "",
|
||||
`{"community":"s3cret","oid":"1.3.6.1.2.1.1.5.0","condition":"eq","value":"core-sw-1"}`: "",
|
||||
`{"community":"s3cret","oid":"1.3.6.1.2.1.1.5.0","condition":"contains","value":"sw"}`: "",
|
||||
`{"community":"s3cret","oid":"1.3.6.1.2.1.2.1.0","condition":"ge","value":"48"}`: "",
|
||||
`{"community":"s3cret","oid":"1.3.6.1.2.1.2.1.0","condition":"lt","value":"10"}`: `value "48" does not satisfy lt "10"`,
|
||||
`{"community":"s3cret","oid":"1.3.6.1.2.1.99.0"}`: "does not exist",
|
||||
`{"community":"wrong-community","oid":"1.3.6.1.2.1.1.5.0"}`: "is the community or version right",
|
||||
})
|
||||
}
|
||||
|
||||
func TestProtocolValidate(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
typ Type
|
||||
target, cfg string
|
||||
}{
|
||||
{GRPC, "api", `{}`},
|
||||
{SMTP, "mail:25", `{"tls":"disable","implicit_tls":true}`},
|
||||
{RADIUS, "radius:1812", `{}`},
|
||||
{SNMP, "switch:161", `{"oid":"system.name"}`},
|
||||
{SNMP, "switch:161", `{"oid":"1.3.6","version":"3"}`},
|
||||
{SNMP, "switch:161", `{"oid":"1.3.6","condition":"gt","value":"many"}`},
|
||||
} {
|
||||
if _, err := Validate(tc.typ, tc.target, []byte(tc.cfg)); err == nil {
|
||||
t.Errorf("Validate(%s, %s, %s) accepted", tc.typ, tc.target, tc.cfg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolChecksStayOffPrivateNetworks(t *testing.T) {
|
||||
for typ, cfg := range map[Type]string{
|
||||
GRPC: `{"tls":"disable"}`,
|
||||
SMTP: `{"tls":"disable"}`,
|
||||
RADIUS: `{"secret":"s","user":"u","password":"p"}`,
|
||||
SNMP: `{"oid":"1.3.6.1.2.1.1.5.0"}`,
|
||||
} {
|
||||
c, err := Validate(typ, "127.0.0.1:9", []byte(cfg))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o := Run(t.Context(), Spec{Type: typ, Target: "127.0.0.1:9", Timeout: 2 * time.Second, Config: c})
|
||||
if o.OK || !strings.Contains(o.Error, "non-public") {
|
||||
t.Errorf("%s: %+v", typ, o)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package check
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
@@ -20,11 +21,16 @@ func tlsFor(mode, target string) *tls.Config {
|
||||
}
|
||||
|
||||
// redact shortens err for customers and removes secrets some clients
|
||||
// repeat in their errors.
|
||||
// repeat in their errors. Secrets shorter than four characters are left:
|
||||
// replacing them would garble the message while hiding little.
|
||||
func redact(err error, secrets ...string) string {
|
||||
var op *net.OpError
|
||||
if errors.As(err, &op) && op.Op == "dial" {
|
||||
return describeNetErr(err)
|
||||
}
|
||||
msg := err.Error()
|
||||
for _, s := range secrets {
|
||||
if s != "" {
|
||||
if len(s) >= 4 {
|
||||
msg = strings.ReplaceAll(msg, s, "***")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user