336 lines
11 KiB
Go
336 lines
11 KiB
Go
// securityprobe exercises real dependency authorization and emits no secrets.
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/binary"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"gitea.privcloud.tech/mtusi2026/internal/config"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/openbao"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/transportsecurity"
|
|
"github.com/aws/smithy-go"
|
|
"github.com/jackc/pgx/v5"
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
"github.com/redis/go-redis/v9"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"sort"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
if err := run(); err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
func run() error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
mode := os.Getenv("PROBE_MODE")
|
|
target := os.Getenv("PROBE_TARGET")
|
|
expect := os.Getenv("PROBE_EXPECT")
|
|
if mode == "hash" || mode == "kdf" {
|
|
encryptor := encrypting.New()
|
|
if mode == "hash" {
|
|
h, e := encryptor.EncryptSecretUsingArgon2id(ctx, os.Getenv("PROBE_PASSWORD"))
|
|
if e != nil {
|
|
return e
|
|
}
|
|
fmt.Print(h)
|
|
return nil
|
|
}
|
|
times := []float64{}
|
|
for i := 0; i < 12; i++ {
|
|
start := time.Now()
|
|
_, e := encryptor.EncryptSecretUsingArgon2id(ctx, "synthetic-benchmark-password")
|
|
if e != nil {
|
|
return e
|
|
}
|
|
times = append(times, float64(time.Since(start).Microseconds())/1000)
|
|
}
|
|
sort.Float64s(times)
|
|
return json.NewEncoder(os.Stdout).Encode(map[string]any{"samples": 12, "memory_kib": 65536, "iterations": 3, "parallelism": 1, "max_parallel_kdf": 2, "p50_ms": times[6], "p95_ms": times[11], "max_ms": times[11]})
|
|
}
|
|
tc, err := transportsecurity.Client()
|
|
if err != nil {
|
|
return fmt.Errorf("probe TLS material unavailable")
|
|
}
|
|
if os.Getenv("PROBE_UNTRUST_SERVER") == "1" {
|
|
tc.RootCAs = x509.NewCertPool()
|
|
}
|
|
if os.Getenv("PROBE_NO_CERT") == "1" {
|
|
tc.Certificates = nil
|
|
}
|
|
if mode == "telemetry" {
|
|
client := http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{TLSClientConfig: tc}}
|
|
endpoints := map[string]string{"metrics": "https://prometheus:9443/api/v1/query?query=up", "logs": "https://loki:9443/loki/api/v1/query_range?query=%7Bservice_name%3D%22messenger-worker%22%7D&limit=5", "traces": "https://tempo:9443/api/traces/" + os.Getenv("PROBE_TRACE_ID")}
|
|
result := map[string]any{}
|
|
for name, url := range endpoints {
|
|
r, e := client.Get(url)
|
|
if e != nil {
|
|
return fmt.Errorf("telemetry %s transport failed", name)
|
|
}
|
|
b, e := io.ReadAll(io.LimitReader(r.Body, 2<<20))
|
|
r.Body.Close()
|
|
if e != nil || r.StatusCode != 200 {
|
|
return fmt.Errorf("telemetry %s query failed", name)
|
|
}
|
|
var data map[string]json.RawMessage
|
|
if json.Unmarshal(b, &data) != nil {
|
|
return fmt.Errorf("invalid telemetry response")
|
|
}
|
|
result[name] = json.RawMessage(b)
|
|
}
|
|
return json.NewEncoder(os.Stdout).Encode(result)
|
|
}
|
|
if mode == "db-tls" {
|
|
raw, e := net.DialTimeout("tcp", "postgres:5432", 3*time.Second)
|
|
if e != nil {
|
|
return fmt.Errorf("DB listener unreachable")
|
|
}
|
|
defer raw.Close()
|
|
raw.SetDeadline(time.Now().Add(3 * time.Second))
|
|
packet := make([]byte, 8)
|
|
binary.BigEndian.PutUint32(packet, 8)
|
|
binary.BigEndian.PutUint32(packet[4:], 80877103)
|
|
if _, e = raw.Write(packet); e != nil {
|
|
return e
|
|
}
|
|
answer := make([]byte, 1)
|
|
if _, e = io.ReadFull(raw, answer); e != nil || answer[0] != 'S' {
|
|
return fmt.Errorf("Postgres SSLRequest failed")
|
|
}
|
|
tc.ServerName = "postgres"
|
|
if v := os.Getenv("PROBE_SERVER_NAME"); v != "" {
|
|
tc.ServerName = v
|
|
}
|
|
e = tls.Client(raw, tc).HandshakeContext(ctx)
|
|
if (e != nil) != (expect == "deny") {
|
|
return fmt.Errorf("DB TLS expectation failed")
|
|
}
|
|
return json.NewEncoder(os.Stdout).Encode(map[string]any{"mode": mode, "matched": true})
|
|
}
|
|
if mode == "amqp-tls" {
|
|
conn, e := amqp.DialConfig("amqps://broker:5671/attachments", amqp.Config{TLSClientConfig: tc, SASL: []amqp.Authentication{&amqp.ExternalAuth{}}})
|
|
if conn != nil {
|
|
defer conn.Close()
|
|
}
|
|
if (e != nil) != (expect == "deny") {
|
|
return fmt.Errorf("AMQP identity expectation failed")
|
|
}
|
|
return json.NewEncoder(os.Stdout).Encode(map[string]any{"mode": mode, "expect": expect, "matched": true})
|
|
}
|
|
if mode == "tls" {
|
|
if name := os.Getenv("PROBE_SERVER_NAME"); name != "" {
|
|
tc.ServerName = name
|
|
}
|
|
req, _ := http.NewRequestWithContext(ctx, "GET", target, nil)
|
|
if strings.Contains(target, "otel-collector") && strings.Contains(target, "/v1/") {
|
|
req, _ = http.NewRequestWithContext(ctx, "POST", target, strings.NewReader("{}"))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if method := os.Getenv("PROBE_METHOD"); method != "" {
|
|
req.Method = method
|
|
}
|
|
client := http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{TLSClientConfig: tc}}
|
|
r, e := client.Do(req)
|
|
denied := e != nil
|
|
if e != nil {
|
|
var n net.Error
|
|
if errors.As(e, &n) && n.Timeout() {
|
|
return fmt.Errorf("timeout is not identity denial")
|
|
}
|
|
if errors.Is(e, syscall.ECONNREFUSED) {
|
|
return fmt.Errorf("connection refused is not identity denial")
|
|
}
|
|
}
|
|
if r != nil {
|
|
defer r.Body.Close()
|
|
io.Copy(io.Discard, r.Body)
|
|
denied = r.StatusCode == 401 || r.StatusCode == 403
|
|
}
|
|
if expect == "deny" && !denied {
|
|
return fmt.Errorf("TLS/identity denial missing")
|
|
}
|
|
if expect != "deny" && denied {
|
|
return fmt.Errorf("authorized TLS request failed")
|
|
}
|
|
// Prove a reachable TLS listener independently: a failed TCP connect is never accepted as an identity denial.
|
|
if denied {
|
|
address := strings.TrimPrefix(strings.Split(target[8:], "/")[0], "https://")
|
|
c, e := net.DialTimeout("tcp", address, 2*time.Second)
|
|
if e != nil {
|
|
return fmt.Errorf("network failure is not a security denial")
|
|
}
|
|
c.Close()
|
|
}
|
|
return json.NewEncoder(os.Stdout).Encode(map[string]any{"mode": mode, "expect": expect, "matched": true})
|
|
}
|
|
stop, err := openbao.Start(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer stop()
|
|
role := os.Getenv("SERVICE_ROLE")
|
|
out := map[string]any{"mode": mode, "role": role}
|
|
check := func(name string, allowed bool, err error) error {
|
|
ok := (err == nil) == allowed
|
|
out[name] = ok
|
|
if !ok {
|
|
return fmt.Errorf("authorization mismatch: %s", name)
|
|
}
|
|
return nil
|
|
}
|
|
switch mode {
|
|
case "db":
|
|
cfg, e := config.New()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
conn, e := pgx.Connect(ctx, cfg.Postgres.GetURI())
|
|
if e != nil {
|
|
return fmt.Errorf("DB connection failed")
|
|
}
|
|
defer conn.Close(ctx)
|
|
for _, q := range []struct {
|
|
name, sql string
|
|
allow bool
|
|
}{{"jobs_read", "SELECT id FROM attachment_jobs LIMIT 0", true}, {"password_read_denied", "SELECT password_hash FROM users LIMIT 0", false}, {"session_read_denied", "SELECT token_hash FROM refresh_tokens LIMIT 0", false}, {"messages_read_denied", "SELECT id FROM messages LIMIT 0", false}, {"ddl_denied", "CREATE TABLE security_probe_should_not_exist(id int)", false}} {
|
|
_, e := conn.Exec(ctx, q.sql)
|
|
if e = check(q.name, q.allow, e); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
case "s3":
|
|
cfg, e := config.LoadAttachment()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
s := objectstore.New(cfg)
|
|
key := "results/security-probe/" + fmt.Sprint(time.Now().UnixNano())
|
|
e = s.Put(ctx, key, "application/octet-stream", bytes.NewReader([]byte("synthetic")), 9)
|
|
if os.Getenv("PROBE_OLD_SECRET") == "1" {
|
|
var denied smithy.APIError
|
|
if !errors.As(e, &denied) || (denied.ErrorCode() != "InvalidAccessKeyId" && denied.ErrorCode() != "AccessDenied" && denied.ErrorCode() != "SignatureDoesNotMatch") {
|
|
return fmt.Errorf("old S3 secret was not explicitly denied")
|
|
}
|
|
return json.NewEncoder(os.Stdout).Encode(map[string]any{"old_s3_secret_rejected": true})
|
|
}
|
|
if e = check("results_write", true, e); e != nil {
|
|
return e
|
|
}
|
|
_, e = s.Get(ctx, key)
|
|
if e = check("results_read", true, e); e != nil {
|
|
return e
|
|
}
|
|
defer s.Delete(ctx, key)
|
|
for _, key := range []string{"originals/security-denied", "forbidden/security-denied"} {
|
|
if os.Getenv("PROBE_BASELINE") == "1" {
|
|
defer s.Delete(ctx, key)
|
|
}
|
|
e = s.Put(ctx, key, "application/octet-stream", bytes.NewReader([]byte("x")), 1)
|
|
if e = check(key, os.Getenv("PROBE_BASELINE") == "1", e); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
case "redis":
|
|
cfg, e := config.New()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
r := redis.NewClient(cfg.Redis.BuildRedisOptions())
|
|
defer r.Close()
|
|
if e = check("ping", true, r.Ping(ctx).Err()); e != nil {
|
|
return e
|
|
}
|
|
if e = check("foreign_key_denied", false, r.Get(ctx, "forbidden:security-probe").Err()); e != nil {
|
|
return e
|
|
}
|
|
if e = check("config_denied", false, r.ConfigGet(ctx, "*").Err()); e != nil {
|
|
return e
|
|
}
|
|
case "amqp":
|
|
dial := func() (*amqp.Connection, *amqp.Channel, error) {
|
|
conn, e := amqp.DialConfig("amqps://broker:5671/attachments", amqp.Config{TLSClientConfig: tc, SASL: []amqp.Authentication{&amqp.ExternalAuth{}}})
|
|
if e != nil {
|
|
return nil, nil, e
|
|
}
|
|
ch, e := conn.Channel()
|
|
return conn, ch, e
|
|
}
|
|
conn, ch, e := dial()
|
|
if e != nil {
|
|
return fmt.Errorf("authorized AMQP connection failed")
|
|
}
|
|
defer conn.Close()
|
|
_, e = ch.QueueInspect("attachments.v1")
|
|
if e = check("queue_read", true, e); e != nil {
|
|
return e
|
|
}
|
|
ch.Close()
|
|
ch, _ = conn.Channel()
|
|
baseline := os.Getenv("PROBE_BASELINE") == "1"
|
|
queue := "attachments.security-probe"
|
|
_, e = ch.QueueDeclare(queue, true, false, false, false, nil)
|
|
if e = check("configure_profile", baseline, e); e != nil {
|
|
return e
|
|
}
|
|
ch, _ = conn.Channel()
|
|
destination := "attachments.v1"
|
|
if baseline {
|
|
destination = queue
|
|
}
|
|
// Synchronous confirm/error reporting avoids accepting an async ACL failure as success.
|
|
if e = ch.Confirm(false); e != nil {
|
|
return e
|
|
}
|
|
confirms := ch.NotifyPublish(make(chan amqp.Confirmation, 1))
|
|
closed := ch.NotifyClose(make(chan *amqp.Error, 1))
|
|
e = ch.PublishWithContext(ctx, "", destination, false, false, amqp.Publishing{Body: []byte("synthetic-probe")})
|
|
if e == nil {
|
|
select {
|
|
case ack := <-confirms:
|
|
if !ack.Ack {
|
|
e = fmt.Errorf("not confirmed")
|
|
}
|
|
case <-closed:
|
|
e = fmt.Errorf("broker denied publish")
|
|
case <-ctx.Done():
|
|
return fmt.Errorf("broker probe timed out")
|
|
}
|
|
}
|
|
time.Sleep(200 * time.Millisecond)
|
|
if e == nil && ch.IsClosed() {
|
|
e = fmt.Errorf("denied")
|
|
}
|
|
if e = check("publish_profile", baseline, e); e != nil {
|
|
return e
|
|
}
|
|
if baseline {
|
|
cleanup, _ := conn.Channel()
|
|
defer cleanup.Close()
|
|
_, e = cleanup.QueueDelete(queue, false, false, false)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
}
|
|
default:
|
|
return fmt.Errorf("unknown probe mode")
|
|
}
|
|
return json.NewEncoder(os.Stdout).Encode(out)
|
|
}
|
|
|
|
var _ = tls.VersionTLS12
|