forked from mtusi2026/mtusi2026lab7
Лабораторная 7
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var validUntil atomic.Int64
|
||||
|
||||
func Valid() bool { return os.Getenv("BAO_ROLE") == "" || time.Now().Unix() < validUntil.Load() }
|
||||
|
||||
// Certificates are locally bootstrapped, scoped, expiring identities. No root or
|
||||
// permanent bootstrap token is ever mounted in an application container.
|
||||
func LoadSecrets(ctx context.Context) error {
|
||||
role := os.Getenv("BAO_ROLE")
|
||||
if role == "" {
|
||||
return nil
|
||||
}
|
||||
if !strings.HasPrefix(os.Getenv("BAO_ADDR"), "https://") {
|
||||
return fmt.Errorf("secret authority must use HTTPS")
|
||||
}
|
||||
tlsConfig, e := ClientTLS()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
client := &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 3 * time.Second}
|
||||
call := func(ctx context.Context, method, path, token string, body any, out any) error {
|
||||
b, _ := json.Marshal(body)
|
||||
req, e := http.NewRequestWithContext(ctx, method, os.Getenv("BAO_ADDR")+"/v1/"+path, bytes.NewReader(b))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("X-Vault-Token", token)
|
||||
}
|
||||
res, e := client.Do(req)
|
||||
if e != nil {
|
||||
return fmt.Errorf("secret authority unavailable")
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode >= 300 {
|
||||
return fmt.Errorf("secret authority rejected request")
|
||||
}
|
||||
if out != nil {
|
||||
return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(out)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
refresh := func() error {
|
||||
c, cancel := context.WithTimeout(context.Background(), 6*time.Second)
|
||||
defer cancel()
|
||||
var auth struct {
|
||||
Auth struct {
|
||||
Token string `json:"client_token"`
|
||||
TTL int64 `json:"lease_duration"`
|
||||
} `json:"auth"`
|
||||
}
|
||||
if e := call(c, "POST", "auth/cert/login", "", map[string]string{"name": role}, &auth); e != nil {
|
||||
return e
|
||||
}
|
||||
var secret struct {
|
||||
Data map[string]string `json:"data"`
|
||||
}
|
||||
if e := call(c, "GET", "secret/"+role, auth.Auth.Token, nil, &secret); e != nil {
|
||||
return e
|
||||
}
|
||||
// Credentials are immutable during this process lifetime; rotation recreates
|
||||
// only affected services, never images. Refresh validates scoped auth/lease.
|
||||
if validUntil.Load() == 0 {
|
||||
for k, v := range secret.Data {
|
||||
if e := os.Setenv(k, v); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
validUntil.Store(time.Now().Unix() + auth.Auth.TTL)
|
||||
return nil
|
||||
}
|
||||
if e := refresh(); e != nil {
|
||||
return e
|
||||
}
|
||||
go func() {
|
||||
ticker := time.NewTicker(20 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
_ = refresh()
|
||||
if !Valid() && !strings.HasPrefix(role, "api") {
|
||||
os.Exit(75)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Package security centralizes verified TLS and fail-closed secret leases.
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ClientTLS() (*tls.Config, error) {
|
||||
ca, err := os.ReadFile(os.Getenv("TLS_CA_FILE"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CA unavailable")
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(ca) {
|
||||
return nil, fmt.Errorf("invalid CA")
|
||||
}
|
||||
c := &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}
|
||||
c.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||
pair, e := tls.LoadX509KeyPair(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE"))
|
||||
return &pair, e
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func ServerTLS() (*tls.Config, error) {
|
||||
c, err := ClientTLS()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.ClientCAs = c.RootCAs
|
||||
c.ClientAuth = tls.RequireAndVerifyClientCert
|
||||
c.GetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
p, e := tls.LoadX509KeyPair(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE"))
|
||||
return &p, e
|
||||
}
|
||||
c.VerifyConnection = func(s tls.ConnectionState) error {
|
||||
if len(s.PeerCertificates) == 0 {
|
||||
return fmt.Errorf("client identity missing")
|
||||
}
|
||||
cert := s.PeerCertificates[0]
|
||||
for _, san := range cert.DNSNames {
|
||||
if san == "lb" || san == os.Getenv("TLS_SERVER_NAME") {
|
||||
revoked, _ := os.ReadFile("/run/ca/revoked-serials")
|
||||
if strings.Contains("\n"+string(revoked)+"\n", "\n"+cert.SerialNumber.Text(16)+"\n") {
|
||||
return fmt.Errorf("revoked identity")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("client identity denied")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
Reference in New Issue
Block a user