Files
uptimesebi/internal/check/protocols_test.go
Sebastian UnterschützandClaude Opus 5.5 03f6e9137f 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
2026-11-22 16:51:23 +01:00

281 lines
8.4 KiB
Go

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)
}
}
}