565 lines
20 KiB
Go
565 lines
20 KiB
Go
// Command secprobe — инструмент ОТРИЦАТЕЛЬНЫХ проверок lab7 (только тестовый образ
|
|
// target=probe, в образ приложения не входит). Проверяет, что разрешено/запрещено
|
|
// предъявителю конкретной identity, и печатает JSON-матрицу allowed/denied.
|
|
//
|
|
// secprobe tls -addr api:8443 -name api [-cert c -key k] [-ca ca] [-path /health/ready]
|
|
// secprobe amqp -cert c -key k права в RabbitMQ (SASL EXTERNAL по CN)
|
|
// secprobe otlp -cert c -key k ingest в Collector
|
|
// secprobe db -user u -password-file f права роли PostgreSQL (TLS verify-full)
|
|
// secprobe s3 -access a -secret-file f права ключа S3 по префиксам
|
|
// secprobe bao -cert c -key k -role r -path p OpenBao: свой/чужой путь, запись, sys
|
|
// secprobe compromise -cert c -key k -otel-cert -otel-key -role r -path p
|
|
// всё сразу от имени сервиса: вход в OpenBao его сертификатом, чтение его
|
|
// секретов, затем DB/S3/AMQP/OTLP с ними (модель «получены права worker»)
|
|
//
|
|
// Секреты не печатаются; в выводе только имена операций и allowed/denied/ошибка.
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
)
|
|
|
|
type result map[string]any
|
|
|
|
func main() {
|
|
if len(os.Args) < 2 {
|
|
fmt.Fprintln(os.Stderr, "usage: secprobe tls|amqp|otlp|db|s3|bao|compromise ...")
|
|
os.Exit(2)
|
|
}
|
|
fs := flag.NewFlagSet(os.Args[1], flag.ExitOnError)
|
|
addr := fs.String("addr", "", "host:port")
|
|
name := fs.String("name", "", "TLS server name")
|
|
ca := fs.String("ca", "/pki/ca.crt", "CA file")
|
|
cert := fs.String("cert", "", "client certificate")
|
|
key := fs.String("key", "", "client key")
|
|
otelCert := fs.String("otel-cert", "", "telemetry client certificate")
|
|
otelKey := fs.String("otel-key", "", "telemetry client key")
|
|
path := fs.String("path", "/health/ready", "HTTP path / KV path")
|
|
role := fs.String("role", "", "OpenBao cert role")
|
|
user := fs.String("user", "", "db user")
|
|
pwFile := fs.String("password-file", "", "file with db password")
|
|
access := fs.String("access", "", "s3 access key")
|
|
secretFile := fs.String("secret-file", "", "file with s3 secret key")
|
|
sslmode := fs.String("sslmode", "verify-full", "postgres sslmode")
|
|
stdinSecret := fs.Bool("stdin", false, "read password/secret from stdin")
|
|
send := fs.String("send", "", "plaintext bytes to send (plain)")
|
|
_ = fs.Parse(os.Args[2:])
|
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
defer cancel()
|
|
|
|
var out result
|
|
switch os.Args[1] {
|
|
case "tls":
|
|
out = probeTLS(*addr, *name, *ca, *cert, *key, *path, *send)
|
|
case "amqp":
|
|
out = probeAMQP(*ca, *cert, *key)
|
|
case "otlp":
|
|
out = probeOTLP(*ca, *cert, *key)
|
|
case "db":
|
|
pw := readFile(*pwFile)
|
|
if *stdinSecret {
|
|
pw = readStdin()
|
|
}
|
|
out = probeDB(ctx, *ca, *user, pw, *sslmode)
|
|
case "s3":
|
|
sec := readFile(*secretFile)
|
|
if *stdinSecret {
|
|
sec = readStdin()
|
|
}
|
|
out = probeS3(ctx, *ca, *access, sec)
|
|
case "plain":
|
|
out = probePlain(*addr, *send)
|
|
case "bao":
|
|
out = probeBao(*ca, *cert, *key, *role, *path)
|
|
case "compromise":
|
|
out = compromise(ctx, *ca, *cert, *key, *otelCert, *otelKey, *role, *path)
|
|
default:
|
|
fmt.Fprintln(os.Stderr, "unknown command")
|
|
os.Exit(2)
|
|
}
|
|
b, _ := json.MarshalIndent(out, "", " ")
|
|
fmt.Println(string(b))
|
|
}
|
|
|
|
func readStdin() string {
|
|
b, _ := io.ReadAll(io.LimitReader(os.Stdin, 4096))
|
|
return strings.TrimSpace(string(b))
|
|
}
|
|
|
|
// probePlain — отвечает ли порт по plaintext-протоколу (без TLS).
|
|
func probePlain(addr, send string) result {
|
|
c, err := net.DialTimeout("tcp", addr, 5*time.Second)
|
|
if err != nil {
|
|
return result{"addr": addr, "plaintext": "no listener (" + short(err) + ")"}
|
|
}
|
|
defer c.Close()
|
|
_ = c.SetDeadline(time.Now().Add(5 * time.Second))
|
|
payload := strings.ReplaceAll(send, `\r\n`, "\r\n") // CRLF в аргументе как \r\n
|
|
_, _ = c.Write([]byte(payload))
|
|
buf := make([]byte, 256)
|
|
n, err := c.Read(buf)
|
|
reply := string(buf[:n])
|
|
if len(reply) > 80 {
|
|
reply = reply[:80]
|
|
}
|
|
return result{"addr": addr, "reply_bytes": n, "reply_prefix": fmt.Sprintf("%q", reply), "read_err": errString(err)}
|
|
}
|
|
|
|
func errString(err error) string {
|
|
if err == nil {
|
|
return ""
|
|
}
|
|
return short(err)
|
|
}
|
|
|
|
func readFile(p string) string {
|
|
if p == "" {
|
|
return ""
|
|
}
|
|
b, err := os.ReadFile(p)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(string(b))
|
|
}
|
|
|
|
func pool(ca string) *x509.CertPool {
|
|
p := x509.NewCertPool()
|
|
b, _ := os.ReadFile(ca)
|
|
p.AppendCertsFromPEM(b)
|
|
return p
|
|
}
|
|
|
|
func tlsConf(ca, cert, key, name string) (*tls.Config, error) {
|
|
c := &tls.Config{RootCAs: pool(ca), ServerName: name, MinVersion: tls.VersionTLS12}
|
|
if cert != "" {
|
|
kp, err := tls.LoadX509KeyPair(cert, key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
c.Certificates = []tls.Certificate{kp}
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// classify — причина отказа TLS: сервер отверг клиента (alert), клиент отверг сервер, сеть.
|
|
func classify(err error) string {
|
|
if err == nil {
|
|
return "ok"
|
|
}
|
|
s := err.Error()
|
|
var uae x509.UnknownAuthorityError
|
|
var hne x509.HostnameError
|
|
switch {
|
|
case errors.As(err, &uae):
|
|
return "client_rejected_server: unknown authority"
|
|
case errors.As(err, &hne):
|
|
return "client_rejected_server: hostname mismatch"
|
|
case strings.Contains(s, "certificate required"):
|
|
return "server_rejected: certificate required"
|
|
case strings.Contains(s, "unknown certificate authority") || strings.Contains(s, "unknown ca"):
|
|
return "server_rejected: unknown certificate authority"
|
|
case strings.Contains(s, "bad certificate"):
|
|
return "server_rejected: bad certificate"
|
|
case strings.Contains(s, "access denied") || strings.Contains(s, "handshake failure"):
|
|
return "server_rejected: " + s
|
|
case strings.Contains(s, "connection reset") || strings.Contains(s, "EOF") || strings.Contains(s, "broken pipe"):
|
|
return "server_rejected: connection closed after handshake (" + s + ")"
|
|
}
|
|
var ne net.Error
|
|
if errors.As(err, &ne) {
|
|
return "network: " + s
|
|
}
|
|
return "error: " + s
|
|
}
|
|
|
|
func probeTLS(addr, name, ca, cert, key, path, send string) result {
|
|
tc, err := tlsConf(ca, cert, key, name)
|
|
if err != nil {
|
|
return result{"result": "error: " + err.Error()}
|
|
}
|
|
if send != "" {
|
|
// Не-HTTP протокол (Redis): рукопожатие с проверкой сертификата сервера + команда.
|
|
c, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", addr, tc)
|
|
if err != nil {
|
|
return result{"addr": addr, "result": classify(err)}
|
|
}
|
|
defer c.Close()
|
|
_ = c.SetDeadline(time.Now().Add(5 * time.Second))
|
|
if _, err := c.Write([]byte(strings.ReplaceAll(send, `\r\n`, "\r\n"))); err != nil {
|
|
return result{"addr": addr, "result": classify(err)}
|
|
}
|
|
buf := make([]byte, 128)
|
|
n, err := c.Read(buf)
|
|
if n == 0 {
|
|
return result{"addr": addr, "result": classify(err)}
|
|
}
|
|
return result{"addr": addr, "result": "ok", "reply_prefix": strings.TrimSpace(string(buf[:n])),
|
|
"server_serial": c.ConnectionState().PeerCertificates[0].SerialNumber.Text(16)}
|
|
}
|
|
// TLS 1.3: отказ сервера в клиентском сертификате приходит после рукопожатия —
|
|
// поэтому делаем реальный HTTP-запрос и классифицируем его ошибку.
|
|
cl := &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{TLSClientConfig: tc, DisableKeepAlives: true}}
|
|
resp, err := cl.Get("https://" + addr + path)
|
|
if err != nil {
|
|
return result{"addr": addr, "result": classify(err)}
|
|
}
|
|
defer resp.Body.Close()
|
|
serial := ""
|
|
if resp.TLS != nil && len(resp.TLS.PeerCertificates) > 0 {
|
|
serial = resp.TLS.PeerCertificates[0].SerialNumber.Text(16)
|
|
}
|
|
return result{"addr": addr, "result": "ok", "status": resp.StatusCode, "instance": resp.Header.Get("X-Instance-Id"),
|
|
"server_serial": serial}
|
|
}
|
|
|
|
// ---------------- RabbitMQ ----------------
|
|
|
|
func probeAMQP(ca, cert, key string) result {
|
|
tc, err := tlsConf(ca, cert, key, "rabbitmq")
|
|
if err != nil {
|
|
return result{"connect": "error: " + err.Error()}
|
|
}
|
|
cfg := amqp.Config{TLSClientConfig: tc, SASL: []amqp.Authentication{&amqp.ExternalAuth{}}, Heartbeat: 10 * time.Second}
|
|
conn, err := amqp.DialConfig("amqps://rabbitmq:5671/", cfg)
|
|
if err != nil {
|
|
return result{"connect": "denied: " + short(err)}
|
|
}
|
|
defer conn.Close()
|
|
res := result{"connect": "allowed"}
|
|
try := func(label string, f func(ch *amqp.Channel) error) {
|
|
ch, err := conn.Channel()
|
|
if err != nil {
|
|
res[label] = "error: " + short(err)
|
|
return
|
|
}
|
|
defer ch.Close()
|
|
if err := f(ch); err != nil {
|
|
res[label] = "denied: " + short(err)
|
|
return
|
|
}
|
|
res[label] = "allowed"
|
|
}
|
|
try("publish attachments (job)", func(ch *amqp.Channel) error {
|
|
if err := ch.Confirm(false); err != nil {
|
|
return err
|
|
}
|
|
dc, err := ch.PublishWithDeferredConfirm("attachments", "process", true, false,
|
|
amqp.Publishing{ContentType: "application/json", Body: []byte(`{"probe":true}`)})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
ok, err := dc.WaitContext(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !ok {
|
|
return errors.New("nack")
|
|
}
|
|
return nil
|
|
})
|
|
try("consume attachment.process", func(ch *amqp.Channel) error {
|
|
_, err := ch.Consume("attachment.process", "probe", false, true, false, false, nil)
|
|
if err == nil {
|
|
_ = ch.Cancel("probe", false) // неподтверждённое вернётся в очередь
|
|
}
|
|
return err
|
|
})
|
|
try("consume attachment.dead (DLQ)", func(ch *amqp.Channel) error {
|
|
_, err := ch.Consume("attachment.dead", "probe-dlq", false, true, false, false, nil)
|
|
return err
|
|
})
|
|
try("declare queue evil", func(ch *amqp.Channel) error {
|
|
_, err := ch.QueueDeclare("evil.probe", false, true, false, false, nil)
|
|
return err
|
|
})
|
|
// queue.purge в RabbitMQ авторизуется правом read — оно у worker есть по необходимости
|
|
// (consume). Зонд purge НЕ выполняет: это разрушило бы очередь стенда. Остаточный
|
|
// риск описан в security/THREAT_MODEL.md (обнаружение — возраст старейшей queued-работы).
|
|
try("delete queue attachment.process", func(ch *amqp.Channel) error {
|
|
_, err := ch.QueueDelete("attachment.process", true, true, false) // ifUnused+ifEmpty: не разрушает
|
|
return err
|
|
})
|
|
return res
|
|
}
|
|
|
|
func short(err error) string {
|
|
s := err.Error()
|
|
if len(s) > 160 {
|
|
s = s[:160]
|
|
}
|
|
return s
|
|
}
|
|
|
|
// ---------------- Collector ----------------
|
|
|
|
func probeOTLP(ca, cert, key string) result {
|
|
tc, err := tlsConf(ca, cert, key, "otel-collector")
|
|
if err != nil {
|
|
return result{"ingest": "error: " + err.Error()}
|
|
}
|
|
cl := &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{TLSClientConfig: tc, DisableKeepAlives: true}}
|
|
// Пустой ExportTraceServiceRequest (protobuf длины 0) — валидный запрос без данных.
|
|
resp, err := cl.Post("https://otel-collector:4318/v1/traces", "application/x-protobuf", bytes.NewReader(nil))
|
|
if err != nil {
|
|
return result{"ingest": classify(err)}
|
|
}
|
|
defer resp.Body.Close()
|
|
return result{"ingest": "allowed", "status": resp.StatusCode}
|
|
}
|
|
|
|
// ---------------- PostgreSQL ----------------
|
|
|
|
func probeDB(ctx context.Context, ca, user, password, sslmode string) result {
|
|
dsn := fmt.Sprintf("postgres://%s@postgres:5432/messenger?sslmode=%s&sslrootcert=%s", user, sslmode, ca)
|
|
cc, err := pgx.ParseConfig(dsn)
|
|
if err != nil {
|
|
return result{"connect": "error: " + err.Error()}
|
|
}
|
|
cc.Password = password
|
|
conn, err := pgx.ConnectConfig(ctx, cc)
|
|
if err != nil {
|
|
return result{"connect": "denied: " + short(err)}
|
|
}
|
|
defer conn.Close(ctx)
|
|
res := result{"connect": "allowed", "role": user}
|
|
// Каждая проверка — в транзакции с ROLLBACK: ничего не меняется даже при «allowed».
|
|
try := func(label, sql string) {
|
|
tx, err := conn.Begin(ctx)
|
|
if err != nil {
|
|
res[label] = "error: " + short(err)
|
|
return
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
if _, err := tx.Exec(ctx, sql); err != nil {
|
|
if strings.Contains(err.Error(), "permission denied") {
|
|
res[label] = "denied"
|
|
} else {
|
|
res[label] = "error: " + short(err)
|
|
}
|
|
return
|
|
}
|
|
res[label] = "allowed"
|
|
}
|
|
try("read users.password_hash", `SELECT password_hash FROM users LIMIT 1`)
|
|
try("read messages", `SELECT text FROM messages LIMIT 1`)
|
|
try("read chat_members", `SELECT * FROM chat_members LIMIT 1`)
|
|
try("insert message", `INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
SELECT gen_random_uuid(), chat_id, user_id, 'probe', now() FROM chat_members LIMIT 1`)
|
|
try("read jobs", `SELECT job_id FROM jobs LIMIT 1`)
|
|
try("update jobs.state", `UPDATE jobs SET state = state WHERE false`)
|
|
try("update attachments.owner_id", `UPDATE attachments SET owner_id = owner_id WHERE false`)
|
|
try("update attachments.status", `UPDATE attachments SET status = status WHERE false`)
|
|
try("delete attachments", `DELETE FROM attachments WHERE false`)
|
|
try("insert attachment_variants", `INSERT INTO attachment_variants SELECT * FROM attachment_variants WHERE false`)
|
|
try("truncate jobs", `TRUNCATE jobs CASCADE`)
|
|
try("create table", `CREATE TABLE probe_evil (x int)`)
|
|
try("create role", `CREATE ROLE probe_evil`)
|
|
return res
|
|
}
|
|
|
|
// ---------------- S3 ----------------
|
|
|
|
func probeS3(ctx context.Context, ca, access, secret string) result {
|
|
tr, _ := minio.DefaultTransport(true)
|
|
tr.TLSClientConfig = &tls.Config{RootCAs: pool(ca), MinVersion: tls.VersionTLS12}
|
|
c, err := minio.New("s3:9000", &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: true,
|
|
Transport: tr, BucketLookup: minio.BucketLookupPath, MaxRetries: 1})
|
|
if err != nil {
|
|
return result{"client": "error: " + err.Error()}
|
|
}
|
|
const b = "messenger-attachments"
|
|
res := result{}
|
|
verdict := func(err error) string {
|
|
if err == nil {
|
|
return "allowed"
|
|
}
|
|
code := minio.ToErrorResponse(err).Code
|
|
switch code {
|
|
case "AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch":
|
|
return "denied (" + code + ")"
|
|
case "NoSuchKey":
|
|
return "allowed (no such key)"
|
|
}
|
|
return "error: " + short(err)
|
|
}
|
|
probe := "probe-" + fmt.Sprint(time.Now().UnixNano())
|
|
for _, p := range []string{"s/", "o/", "v/", "a/"} {
|
|
_, err := c.PutObject(ctx, b, p+probe, bytes.NewReader([]byte("x")), 1, minio.PutObjectOptions{})
|
|
res["put "+p+"*"] = verdict(err)
|
|
if err == nil {
|
|
defer c.RemoveObject(context.Background(), b, p+probe, minio.RemoveObjectOptions{})
|
|
}
|
|
o, err := c.GetObject(ctx, b, p+"no-such-"+probe, minio.GetObjectOptions{})
|
|
if err == nil {
|
|
_, err = io.ReadAll(o)
|
|
}
|
|
res["get "+p+"*"] = verdict(err)
|
|
err = c.RemoveObject(ctx, b, p+"no-such-"+probe, minio.RemoveObjectOptions{})
|
|
res["delete "+p+"*"] = verdict(err)
|
|
}
|
|
n, err := 0, error(nil)
|
|
for o := range c.ListObjects(ctx, b, minio.ListObjectsOptions{Recursive: true, MaxKeys: 10}) {
|
|
if o.Err != nil {
|
|
err = o.Err
|
|
break
|
|
}
|
|
n++
|
|
if n > 10 {
|
|
break
|
|
}
|
|
}
|
|
res["list bucket"] = verdict(err)
|
|
res["make bucket"] = verdict(c.MakeBucket(ctx, "evil-"+probe[len(probe)-8:], minio.MakeBucketOptions{}))
|
|
_, err = c.ListBuckets(ctx)
|
|
res["list all buckets"] = verdict(err)
|
|
return res
|
|
}
|
|
|
|
// ---------------- OpenBao ----------------
|
|
|
|
type bao struct {
|
|
cl *http.Client
|
|
token string
|
|
}
|
|
|
|
func newBao(ca, cert, key string) (*bao, error) {
|
|
tc, err := tlsConf(ca, cert, key, "openbao")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &bao{cl: &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{TLSClientConfig: tc}}}, nil
|
|
}
|
|
|
|
func (b *bao) do(method, path string, body any) (int, map[string]any, error) {
|
|
var rd io.Reader
|
|
if body != nil {
|
|
j, _ := json.Marshal(body)
|
|
rd = bytes.NewReader(j)
|
|
}
|
|
req, _ := http.NewRequest(method, "https://openbao:8200"+path, rd)
|
|
if b.token != "" {
|
|
req.Header.Set("X-Vault-Token", b.token)
|
|
}
|
|
resp, err := b.cl.Do(req)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
var m map[string]any
|
|
_ = json.NewDecoder(resp.Body).Decode(&m)
|
|
return resp.StatusCode, m, nil
|
|
}
|
|
|
|
func (b *bao) login(role string) error {
|
|
code, m, err := b.do("POST", "/v1/auth/cert/login", map[string]any{"name": role})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if code != 200 {
|
|
return fmt.Errorf("login %d", code)
|
|
}
|
|
b.token, _ = m["auth"].(map[string]any)["client_token"].(string)
|
|
return nil
|
|
}
|
|
|
|
func verdictHTTP(code int, err error) string {
|
|
switch {
|
|
case err != nil:
|
|
return "error: " + short(err)
|
|
case code == 200 || code == 204:
|
|
return "allowed"
|
|
case code == 403:
|
|
return "denied (403)"
|
|
case code == 404:
|
|
return "not found (404)"
|
|
}
|
|
return fmt.Sprintf("status %d", code)
|
|
}
|
|
|
|
func probeBao(ca, cert, key, role, path string) result {
|
|
b, err := newBao(ca, cert, key)
|
|
if err != nil {
|
|
return result{"login": "error: " + err.Error()}
|
|
}
|
|
if err := b.login(role); err != nil {
|
|
return result{"login": "denied: " + short(err)}
|
|
}
|
|
res := result{"login": "allowed"}
|
|
code, _, err := b.do("GET", "/v1/secret/data/"+path, nil)
|
|
res["read own "+path] = verdictHTTP(code, err)
|
|
for _, other := range []string{"messenger/api", "messenger/worker", "messenger/relay", "messenger/reconciler"} {
|
|
if other == path {
|
|
continue
|
|
}
|
|
code, _, err := b.do("GET", "/v1/secret/data/"+other, nil)
|
|
res["read "+other] = verdictHTTP(code, err)
|
|
}
|
|
code, _, err = b.do("POST", "/v1/secret/data/"+path, map[string]any{"data": map[string]string{"x": "y"}})
|
|
res["write own secret"] = verdictHTTP(code, err)
|
|
code, _, err = b.do("LIST", "/v1/secret/metadata/messenger", nil)
|
|
res["list secrets"] = verdictHTTP(code, err)
|
|
code, _, err = b.do("PUT", "/v1/sys/policies/acl/evil", map[string]any{"policy": `path "*" { capabilities = ["sudo","read"] }`})
|
|
res["write policy"] = verdictHTTP(code, err)
|
|
code, _, err = b.do("POST", "/v1/auth/token/create", map[string]any{"policies": []string{"messenger-api"}})
|
|
res["create token with other policy"] = verdictHTTP(code, err)
|
|
code, _, err = b.do("PUT", "/v1/sys/seal", nil)
|
|
res["seal openbao"] = verdictHTTP(code, err)
|
|
return res
|
|
}
|
|
|
|
// ---------------- полная модель компрометации сервиса ----------------
|
|
|
|
func compromise(ctx context.Context, ca, cert, key, otelCert, otelKey, role, path string) result {
|
|
res := result{"identity_cert": cert}
|
|
res["openbao"] = probeBao(ca, cert, key, role, path)
|
|
b, err := newBao(ca, cert, key)
|
|
if err == nil {
|
|
err = b.login(role)
|
|
}
|
|
if err != nil {
|
|
res["stolen_secrets"] = "none: openbao login denied (" + short(err) + ")"
|
|
} else {
|
|
code, m, err := b.do("GET", "/v1/secret/data/"+path, nil)
|
|
if err != nil || code != 200 {
|
|
res["stolen_secrets"] = fmt.Sprintf("none: read %d", code)
|
|
} else {
|
|
d, _ := m["data"].(map[string]any)["data"].(map[string]any)
|
|
keys := []string{}
|
|
for k := range d {
|
|
keys = append(keys, k)
|
|
}
|
|
res["stolen_secrets"] = keys // только имена
|
|
str := func(k string) string { s, _ := d[k].(string); return s }
|
|
res["db"] = probeDB(ctx, ca, str("db_user"), str("db_password"), "verify-full")
|
|
res["s3"] = probeS3(ctx, ca, str("s3_access_key"), str("s3_secret_key"))
|
|
}
|
|
}
|
|
res["amqp"] = probeAMQP(ca, cert, key)
|
|
if otelCert != "" {
|
|
res["otlp"] = probeOTLP(ca, otelCert, otelKey)
|
|
}
|
|
res["api_as_lb"] = probeTLS("api:8443", "api", ca, cert, key, "/api/v1/users/me", "")
|
|
return res
|
|
}
|