186 lines
5.9 KiB
Go
186 lines
5.9 KiB
Go
package security
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// Operator-only verifier. Inputs arrive on stdin; private values never appear
|
|
// in argv or output. SQL outputs only allow/deny, never returned row contents.
|
|
func Probe() error {
|
|
var in struct {
|
|
Kind, Role, Cert, URL, Method, Body, Query, Key, CredentialsFile, ServerName, Auth string
|
|
NoCert, WrongCA, ReturnBody bool
|
|
Command []string
|
|
}
|
|
if json.NewDecoder(io.LimitReader(os.Stdin, 65536)).Decode(&in) != nil {
|
|
return fmt.Errorf("invalid probe input")
|
|
}
|
|
if in.Cert == "" {
|
|
in.Cert = "operator"
|
|
}
|
|
os.Setenv("TLS_CERT_FILE", "/fixtures/"+in.Cert+"/cert.crt")
|
|
os.Setenv("TLS_KEY_FILE", "/fixtures/"+in.Cert+"/key.key")
|
|
tc, e := ClientTLS()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if in.NoCert {
|
|
tc.GetClientCertificate = nil
|
|
}
|
|
if in.ServerName != "" {
|
|
tc.ServerName = in.ServerName
|
|
}
|
|
if in.WrongCA {
|
|
b, _ := os.ReadFile("/operator/alien-ca/ca.crt")
|
|
p := x509.NewCertPool()
|
|
p.AppendCertsFromPEM(b)
|
|
tc.RootCAs = p
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
|
|
defer cancel()
|
|
result := map[string]any{"ok": false}
|
|
var creds map[string]json.RawMessage
|
|
path := in.CredentialsFile
|
|
if path == "" {
|
|
path = "/operator/credentials.json"
|
|
}
|
|
raw, _ := os.ReadFile(path)
|
|
json.Unmarshal(raw, &creds)
|
|
var role struct {
|
|
DBPassword string `json:"db_password"`
|
|
BrokerPassword string `json:"broker_password"`
|
|
CachePassword string `json:"cache_password"`
|
|
Access string `json:"s3_access_key_id"`
|
|
Secret string `json:"s3_secret_access_key"`
|
|
}
|
|
json.Unmarshal(creds[in.Role], &role)
|
|
switch in.Kind {
|
|
case "http":
|
|
if in.Method == "" {
|
|
in.Method = "GET"
|
|
}
|
|
r, e2 := http.NewRequestWithContext(ctx, in.Method, in.URL, strings.NewReader(in.Body))
|
|
if e2 != nil {
|
|
return fmt.Errorf("invalid probe URL")
|
|
}
|
|
r.Header.Set("Content-Type", "application/json")
|
|
if in.Auth == "grafana" {
|
|
var password string
|
|
json.Unmarshal(creds["grafana_password"], &password)
|
|
r.SetBasicAuth("admin", password)
|
|
}
|
|
tr := &http.Transport{TLSClientConfig: tc, DisableKeepAlives: true}
|
|
defer tr.CloseIdleConnections()
|
|
client := &http.Client{Transport: tr, Timeout: 6 * time.Second}
|
|
resp, err := client.Do(r)
|
|
e = err
|
|
if e == nil {
|
|
defer resp.Body.Close()
|
|
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
result["status"] = resp.StatusCode
|
|
result["ok"] = resp.StatusCode >= 200 && resp.StatusCode < 300
|
|
result["tls"] = resp.TLS != nil && resp.TLS.Version >= tls.VersionTLS12
|
|
if in.ReturnBody {
|
|
result["body"] = string(b)
|
|
}
|
|
}
|
|
case "postgres":
|
|
cfg, err := pgx.ParseConfig("postgres://messenger_" + in.Role + ":" + role.DBPassword + "@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.crt")
|
|
if err != nil {
|
|
return fmt.Errorf("invalid probe role")
|
|
}
|
|
cfg.TLSConfig = tc.Clone()
|
|
if cfg.TLSConfig.ServerName == "" {
|
|
cfg.TLSConfig.ServerName = "postgres"
|
|
}
|
|
cfg.Fallbacks = nil
|
|
var conn *pgx.Conn
|
|
conn, e = pgx.ConnectConfig(ctx, cfg)
|
|
if e == nil {
|
|
defer conn.Close(ctx)
|
|
_, e = conn.Exec(ctx, in.Query)
|
|
result["ok"] = e == nil
|
|
}
|
|
case "redis":
|
|
pass := role.BrokerPassword
|
|
user := in.Role
|
|
host := "broker"
|
|
if in.URL == "cache" {
|
|
pass = role.CachePassword
|
|
host = "cache"
|
|
}
|
|
rc := redis.NewClient(&redis.Options{Addr: host + ":6379", Username: user, Password: pass, TLSConfig: tc, MaxRetries: -1, DialTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second})
|
|
defer rc.Close()
|
|
args := make([]any, len(in.Command))
|
|
for i, v := range in.Command {
|
|
args[i] = v
|
|
}
|
|
_, e = rc.Do(ctx, args...).Result()
|
|
result["ok"] = e == nil
|
|
case "s3":
|
|
tr := &http.Transport{TLSClientConfig: tc}
|
|
defer tr.CloseIdleConnections()
|
|
client, err := minio.New("s3:9000", &minio.Options{Secure: true, Creds: credentials.NewStaticV4(role.Access, role.Secret, ""), Region: "us-east-1", Transport: tr, MaxRetries: 1})
|
|
if err != nil {
|
|
return fmt.Errorf("invalid probe object client")
|
|
}
|
|
switch in.Method {
|
|
case "PUT":
|
|
_, e = client.PutObject(ctx, "messenger-attachments", in.Key, strings.NewReader(in.Body), int64(len(in.Body)), minio.PutObjectOptions{})
|
|
case "DELETE":
|
|
e = client.RemoveObject(ctx, "messenger-attachments", in.Key, minio.RemoveObjectOptions{})
|
|
case "LIST_BUCKETS":
|
|
_, e = client.ListBuckets(ctx)
|
|
default:
|
|
_, e = client.StatObject(ctx, "messenger-attachments", in.Key, minio.StatObjectOptions{})
|
|
}
|
|
result["ok"] = e == nil
|
|
default:
|
|
return fmt.Errorf("unknown probe kind")
|
|
}
|
|
if e != nil {
|
|
category := "connection_or_action_denied"
|
|
if strings.Contains(e.Error(), "NOPERM") || strings.Contains(e.Error(), "permission denied") || strings.Contains(e.Error(), "Access Denied") {
|
|
category = "permission_denied"
|
|
}
|
|
var authority x509.UnknownAuthorityError
|
|
var hostname x509.HostnameError
|
|
var pg *pgconn.PgError
|
|
switch {
|
|
case errors.As(e, &authority):
|
|
category = "ca_verification_failed"
|
|
case errors.As(e, &hostname):
|
|
category = "hostname_verification_failed"
|
|
case errors.As(e, &pg):
|
|
if pg.Code == "42501" {
|
|
category = "permission_denied"
|
|
} else if pg.Code == "28P01" {
|
|
category = "credential_denied"
|
|
}
|
|
case strings.Contains(e.Error(), "tls:") || strings.Contains(e.Error(), "certificate"):
|
|
category = "tls_handshake_denied"
|
|
case strings.Contains(e.Error(), "timeout") || strings.Contains(e.Error(), "deadline exceeded"):
|
|
category = "timeout"
|
|
}
|
|
// Generic category only: upstream errors can contain SQL/user names/keys.
|
|
result["error_category"] = category
|
|
}
|
|
return json.NewEncoder(os.Stdout).Encode(result)
|
|
}
|