Files
uptimesebi/internal/check/protocols.go
T
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

347 lines
11 KiB
Go

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
}