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
308 lines
8.9 KiB
Go
308 lines
8.9 KiB
Go
package check
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"net/url"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/go-sql-driver/mysql"
|
|
"github.com/jackc/pgx/v5"
|
|
mssql "github.com/microsoft/go-mssqldb"
|
|
"github.com/microsoft/go-mssqldb/msdsn"
|
|
"github.com/redis/go-redis/v9"
|
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
|
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
|
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
|
)
|
|
|
|
// Database checks connect to host:port with the configured credentials and
|
|
// run a query. Every connection goes through the network guard.
|
|
const (
|
|
Postgres Type = "postgres"
|
|
MySQL Type = "mysql"
|
|
MSSQL Type = "mssql"
|
|
MongoDB Type = "mongodb"
|
|
Redis Type = "redis"
|
|
)
|
|
|
|
// DBConfig configures database checks. Password is a secret: the API
|
|
// stores it sealed and hands it only to checkers.
|
|
type DBConfig struct {
|
|
User string `json:"user,omitempty"`
|
|
Password string `json:"password,omitempty"`
|
|
Database string `json:"database,omitempty"`
|
|
// TLS is "disable", "require" (encrypt without verifying) or "verify".
|
|
TLS string `json:"tls"`
|
|
// Query runs after connecting; it must succeed. Empty uses a ping.
|
|
// Not used for MongoDB and Redis.
|
|
Query string `json:"query,omitempty"`
|
|
// Expect, when set, must equal the first column of the first row.
|
|
Expect string `json:"expect,omitempty"`
|
|
}
|
|
|
|
// SecretFields lists the settings of t the API stores sealed.
|
|
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
|
|
}
|
|
|
|
type dbCheck struct{ typ Type }
|
|
|
|
func (d dbCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
|
host, port, err := net.SplitHostPort(target)
|
|
if n, perr := strconv.Atoi(port); err != nil || host == "" || perr != nil || n < 1 || n > 65535 {
|
|
return nil, invalid("invalid_target")
|
|
}
|
|
c := DBConfig{TLS: "require"}
|
|
if err := json.Unmarshal(config, &c); err != nil {
|
|
return nil, invalid("invalid_config")
|
|
}
|
|
if c.TLS == "" {
|
|
c.TLS = "require"
|
|
}
|
|
if !validTLSMode(c.TLS) {
|
|
return nil, invalid("invalid_config")
|
|
}
|
|
if len(c.User) > 200 || len(c.Password) > 500 || len(c.Database) > 200 || len(c.Query) > 2000 || len(c.Expect) > 500 {
|
|
return nil, invalid("invalid_config")
|
|
}
|
|
if (d.typ == MongoDB || d.typ == Redis) && (c.Query != "" || c.Expect != "") {
|
|
return nil, invalid("invalid_config")
|
|
}
|
|
if d.typ == Redis && c.Database != "" {
|
|
if n, err := strconv.Atoi(c.Database); err != nil || n < 0 || n > 15 {
|
|
return nil, invalid("invalid_config")
|
|
}
|
|
}
|
|
return encode(c), nil
|
|
}
|
|
|
|
func (d dbCheck) run(ctx context.Context, s Spec) Outcome {
|
|
c, err := decode[DBConfig](s.Config)
|
|
if err != nil {
|
|
return Outcome{Error: "invalid configuration"}
|
|
}
|
|
dialer := netguard.Dialer(s.AllowPrivate, s.Timeout)
|
|
tlsConfig := tlsFor(c.TLS, s.Target)
|
|
var got string
|
|
switch d.typ {
|
|
case Postgres:
|
|
got, err = queryPostgres(ctx, s.Target, c, dialer, tlsConfig)
|
|
case MySQL:
|
|
got, err = queryMySQL(ctx, s.Target, c, s.AllowPrivate, tlsConfig)
|
|
case MSSQL:
|
|
got, err = queryMSSQL(ctx, s.Target, c, dialer)
|
|
case MongoDB:
|
|
err = pingMongo(ctx, s.Target, c, dialer, tlsConfig)
|
|
case Redis:
|
|
err = pingRedis(ctx, s.Target, c, dialer, tlsConfig)
|
|
}
|
|
if err != nil {
|
|
return Outcome{Error: redact(err, c.Password)}
|
|
}
|
|
if c.Expect != "" && got != c.Expect {
|
|
return Outcome{Error: fmt.Sprintf("query returned %q, expected %q", truncate(got, 100), truncate(c.Expect, 100))}
|
|
}
|
|
return Outcome{OK: true}
|
|
}
|
|
|
|
func queryPostgres(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) (string, error) {
|
|
u := url.URL{Scheme: "postgres", Host: target, Path: "/" + c.Database}
|
|
if c.User != "" {
|
|
u.User = url.UserPassword(c.User, c.Password)
|
|
}
|
|
cfg, err := pgx.ParseConfig(u.String())
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
cfg.TLSConfig = tlsConfig
|
|
cfg.Fallbacks = nil
|
|
cfg.DialFunc = d.DialContext
|
|
conn, err := pgx.ConnectConfig(ctx, cfg)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer func() { _ = conn.Close(context.WithoutCancel(ctx)) }()
|
|
q := c.Query
|
|
if q == "" {
|
|
q = "SELECT 1"
|
|
}
|
|
rows, err := conn.Query(ctx, q)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer rows.Close()
|
|
var first string
|
|
if rows.Next() {
|
|
if vals, err := rows.Values(); err == nil && len(vals) > 0 {
|
|
first = fmt.Sprint(vals[0])
|
|
}
|
|
}
|
|
return first, rows.Err()
|
|
}
|
|
|
|
var registerMySQLDial sync.Once
|
|
|
|
// mysqlNetwork names a dial function registered with the MySQL driver,
|
|
// which only accepts dialers by name.
|
|
func mysqlNetwork(allowPrivate bool) string {
|
|
registerMySQLDial.Do(func() {
|
|
for _, private := range []bool{false, true} {
|
|
d := netguard.Dialer(private, 0)
|
|
mysql.RegisterDialContext(mysqlNetworkName(private), func(ctx context.Context, addr string) (net.Conn, error) {
|
|
return d.DialContext(ctx, "tcp", addr)
|
|
})
|
|
}
|
|
})
|
|
return mysqlNetworkName(allowPrivate)
|
|
}
|
|
|
|
func mysqlNetworkName(private bool) string {
|
|
if private {
|
|
return "guard-private"
|
|
}
|
|
return "guard-public"
|
|
}
|
|
|
|
var mysqlTLS sync.Map
|
|
|
|
func queryMySQL(ctx context.Context, target string, c DBConfig, allowPrivate bool, tlsConfig *tls.Config) (string, error) {
|
|
cfg := mysql.NewConfig()
|
|
cfg.User, cfg.Passwd, cfg.DBName = c.User, c.Password, c.Database
|
|
cfg.Net, cfg.Addr = mysqlNetwork(allowPrivate), target
|
|
if tlsConfig != nil {
|
|
// The driver takes TLS settings by registered name.
|
|
name := "uptimesebi-" + strconv.FormatBool(tlsConfig.InsecureSkipVerify) + "-" + tlsConfig.ServerName
|
|
if _, done := mysqlTLS.LoadOrStore(name, true); !done {
|
|
if err := mysql.RegisterTLSConfig(name, tlsConfig); err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
cfg.TLSConfig = name
|
|
}
|
|
connector, err := mysql.NewConnector(cfg)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return querySQL(ctx, sql.OpenDB(connector), c, "SELECT 1")
|
|
}
|
|
|
|
func queryMSSQL(ctx context.Context, target string, c DBConfig, d *net.Dialer) (string, error) {
|
|
host, port, _ := net.SplitHostPort(target)
|
|
q := url.Values{"database": {c.Database}}
|
|
switch c.TLS {
|
|
case "disable":
|
|
q.Set("encrypt", "disable")
|
|
case "require":
|
|
q.Set("encrypt", "true")
|
|
q.Set("TrustServerCertificate", "true")
|
|
default:
|
|
q.Set("encrypt", "true")
|
|
}
|
|
u := url.URL{Scheme: "sqlserver", User: url.UserPassword(c.User, c.Password), Host: net.JoinHostPort(host, port), RawQuery: q.Encode()}
|
|
cfg, err := msdsn.Parse(u.String())
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
connector := mssql.NewConnectorConfig(cfg)
|
|
connector.Dialer = dialer{d}
|
|
return querySQL(ctx, sql.OpenDB(connector), c, "SELECT 1")
|
|
}
|
|
|
|
// dialer adapts net.Dialer to the SQL Server driver's interface.
|
|
type dialer struct{ d *net.Dialer }
|
|
|
|
// DialContext implements the driver's Dialer.
|
|
func (d dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
return d.d.DialContext(ctx, network, addr)
|
|
}
|
|
|
|
func querySQL(ctx context.Context, db *sql.DB, c DBConfig, ping string) (string, error) {
|
|
defer func() { _ = db.Close() }()
|
|
db.SetMaxOpenConns(1)
|
|
q := c.Query
|
|
if q == "" {
|
|
q = ping
|
|
}
|
|
rows, err := db.QueryContext(ctx, q)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer func() { _ = rows.Close() }()
|
|
var first sql.NullString
|
|
if rows.Next() {
|
|
cols, _ := rows.Columns()
|
|
dest := make([]any, len(cols))
|
|
for i := range dest {
|
|
dest[i] = new(any)
|
|
}
|
|
if len(cols) > 0 {
|
|
dest[0] = &first
|
|
}
|
|
if err := rows.Scan(dest...); err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
return first.String, rows.Err()
|
|
}
|
|
|
|
func pingMongo(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) error {
|
|
opts := options.Client().SetHosts([]string{target}).SetDialer(d).SetTLSConfig(tlsConfig).
|
|
SetDirect(true).SetServerSelectionTimeout(timeoutOf(ctx)).SetConnectTimeout(timeoutOf(ctx))
|
|
if c.User != "" {
|
|
cred := options.Credential{Username: c.User, Password: c.Password}
|
|
if c.Database != "" {
|
|
cred.AuthSource = c.Database
|
|
}
|
|
opts.SetAuth(cred)
|
|
}
|
|
client, err := mongo.Connect(opts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = client.Disconnect(context.WithoutCancel(ctx)) }()
|
|
return client.Ping(ctx, readpref.Primary())
|
|
}
|
|
|
|
func pingRedis(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) error {
|
|
db, _ := strconv.Atoi(c.Database)
|
|
client := redis.NewClient(&redis.Options{
|
|
Addr: target, Username: c.User, Password: c.Password, DB: db,
|
|
Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
conn, err := d.DialContext(ctx, network, addr)
|
|
if err != nil || tlsConfig == nil {
|
|
return conn, err
|
|
}
|
|
return tls.Client(conn, tlsConfig), nil
|
|
},
|
|
MaxRetries: -1, PoolSize: 1, DisableIdentity: true,
|
|
})
|
|
defer func() { _ = client.Close() }()
|
|
return client.Ping(ctx).Err()
|
|
}
|
|
|
|
// timeoutOf is the time left until ctx's deadline, for drivers that take a
|
|
// timeout instead of a context.
|
|
func timeoutOf(ctx context.Context) time.Duration {
|
|
if dl, ok := ctx.Deadline(); ok {
|
|
return max(time.Until(dl), time.Millisecond)
|
|
}
|
|
return 10 * time.Second
|
|
}
|