You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
213 lines
7.1 KiB
Go
213 lines
7.1 KiB
Go
package peermigration
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/ed25519"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"crypto/x509/pkix"
|
|
"encoding/hex"
|
|
"encoding/pem"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math/big"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
identityFileName = "identity.pem"
|
|
maxIdentityBytes = 32 << 10
|
|
identityLifetime = 10 * 365 * 24 * time.Hour
|
|
)
|
|
|
|
var agentIdentityPattern = regexp.MustCompile(`^[1-9][0-9]{0,18}$`)
|
|
|
|
// Identity is an automatically managed host identity. Operators never provide
|
|
// certificate paths: the Agent creates this file once under its private
|
|
// PeerMigration state directory and peers authenticate it by an exact SHA-256
|
|
// pin delivered over the already authenticated control channel.
|
|
type Identity struct {
|
|
certificate tls.Certificate
|
|
fingerprint string
|
|
}
|
|
|
|
func LoadOrCreateIdentity(stateRoot, agentID string) (*Identity, error) {
|
|
if stateRoot == "" || !filepath.IsAbs(stateRoot) || filepath.Clean(stateRoot) != stateRoot ||
|
|
!agentIdentityPattern.MatchString(agentID) {
|
|
return nil, errors.New("peer migration identity location or Agent ID is invalid")
|
|
}
|
|
if err := os.MkdirAll(stateRoot, 0700); err != nil {
|
|
return nil, fmt.Errorf("create peer migration identity directory: %w", err)
|
|
}
|
|
path := filepath.Join(stateRoot, identityFileName)
|
|
raw, err := readIdentityFile(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
raw, err = createIdentityFile(path, agentID, time.Now())
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return parseIdentity(raw, agentID, time.Now())
|
|
}
|
|
|
|
func (i *Identity) Fingerprint() string {
|
|
if i == nil {
|
|
return ""
|
|
}
|
|
return i.fingerprint
|
|
}
|
|
|
|
func (i *Identity) ServerTLSConfig() (*tls.Config, error) {
|
|
if i == nil || len(i.certificate.Certificate) != 1 || !sha256Pattern.MatchString(i.fingerprint) {
|
|
return nil, errors.New("peer migration host identity is unavailable")
|
|
}
|
|
return &tls.Config{
|
|
MinVersion: tls.VersionTLS13,
|
|
Certificates: []tls.Certificate{i.certificate},
|
|
}, nil
|
|
}
|
|
|
|
// PinnedClientTLSConfig accepts only the exact automatically generated source
|
|
// identity advertised by the panel. InsecureSkipVerify is deliberately paired
|
|
// with full certificate parsing, validity/signature verification, and an exact
|
|
// DER fingerprint comparison; there is no unauthenticated fallback.
|
|
func PinnedClientTLSConfig(expectedFingerprint string) (*tls.Config, error) {
|
|
expectedFingerprint = string(bytes.ToLower([]byte(expectedFingerprint)))
|
|
if !sha256Pattern.MatchString(expectedFingerprint) {
|
|
return nil, errors.New("peer migration source identity pin is invalid")
|
|
}
|
|
return &tls.Config{
|
|
MinVersion: tls.VersionTLS13,
|
|
InsecureSkipVerify: true, // Exact certificate pinning is enforced below.
|
|
VerifyConnection: func(state tls.ConnectionState) error {
|
|
if state.Version != tls.VersionTLS13 || len(state.PeerCertificates) != 1 {
|
|
return errors.New("peer migration source TLS identity is invalid")
|
|
}
|
|
certificate := state.PeerCertificates[0]
|
|
digest := sha256.Sum256(certificate.Raw)
|
|
if hex.EncodeToString(digest[:]) != expectedFingerprint {
|
|
return errors.New("peer migration source TLS identity does not match its pin")
|
|
}
|
|
roots := x509.NewCertPool()
|
|
roots.AddCert(certificate)
|
|
_, err := certificate.Verify(x509.VerifyOptions{
|
|
Roots: roots, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
})
|
|
if err != nil {
|
|
return errors.New("peer migration source TLS identity is not valid")
|
|
}
|
|
return nil
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
func readIdentityFile(path string) ([]byte, error) {
|
|
info, err := os.Lstat(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() < 1 || info.Size() > maxIdentityBytes {
|
|
return nil, errors.New("peer migration identity file is not a protected regular file")
|
|
}
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
raw, err := io.ReadAll(io.LimitReader(file, maxIdentityBytes+1))
|
|
if err != nil || len(raw) > maxIdentityBytes {
|
|
return nil, errors.New("read bounded peer migration identity")
|
|
}
|
|
return raw, nil
|
|
}
|
|
|
|
func createIdentityFile(path, agentID string, now time.Time) ([]byte, error) {
|
|
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("generate peer migration identity: %w", err)
|
|
}
|
|
serialLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
|
serial, err := rand.Int(rand.Reader, serialLimit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("generate peer migration certificate serial: %w", err)
|
|
}
|
|
template := &x509.Certificate{
|
|
SerialNumber: serial,
|
|
Subject: pkix.Name{CommonName: "virt-agent-" + agentID},
|
|
NotBefore: now.Add(-5 * time.Minute),
|
|
NotAfter: now.Add(identityLifetime),
|
|
KeyUsage: x509.KeyUsageDigitalSignature,
|
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
BasicConstraintsValid: true,
|
|
}
|
|
certificateDER, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create peer migration certificate: %w", err)
|
|
}
|
|
privateDER, err := x509.MarshalPKCS8PrivateKey(privateKey)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("encode peer migration private key: %w", err)
|
|
}
|
|
var encoded bytes.Buffer
|
|
if err := pem.Encode(&encoded, &pem.Block{Type: "CERTIFICATE", Bytes: certificateDER}); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := pem.Encode(&encoded, &pem.Block{Type: "PRIVATE KEY", Bytes: privateDER}); err != nil {
|
|
return nil, err
|
|
}
|
|
if encoded.Len() > maxIdentityBytes {
|
|
return nil, errors.New("generated peer migration identity is too large")
|
|
}
|
|
root := filepath.Dir(path)
|
|
temporary, err := os.CreateTemp(root, ".identity-*.tmp")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create peer migration identity: %w", err)
|
|
}
|
|
temporaryPath := temporary.Name()
|
|
defer os.Remove(temporaryPath)
|
|
if err := temporary.Chmod(0600); err != nil {
|
|
temporary.Close()
|
|
return nil, err
|
|
}
|
|
if _, err := temporary.Write(encoded.Bytes()); err != nil {
|
|
temporary.Close()
|
|
return nil, err
|
|
}
|
|
if err := temporary.Sync(); err != nil {
|
|
temporary.Close()
|
|
return nil, err
|
|
}
|
|
if err := temporary.Close(); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := os.Rename(temporaryPath, path); err != nil {
|
|
return nil, fmt.Errorf("publish peer migration identity: %w", err)
|
|
}
|
|
if err := syncDirectory(root); err != nil {
|
|
return nil, fmt.Errorf("sync peer migration identity directory: %w", err)
|
|
}
|
|
return encoded.Bytes(), nil
|
|
}
|
|
|
|
func parseIdentity(raw []byte, agentID string, now time.Time) (*Identity, error) {
|
|
certificate, err := tls.X509KeyPair(raw, raw)
|
|
if err != nil || len(certificate.Certificate) != 1 {
|
|
return nil, errors.New("decode peer migration identity")
|
|
}
|
|
leaf, err := x509.ParseCertificate(certificate.Certificate[0])
|
|
if err != nil || leaf.Subject.CommonName != "virt-agent-"+agentID ||
|
|
now.Before(leaf.NotBefore) || !now.Before(leaf.NotAfter) ||
|
|
leaf.CheckSignature(leaf.SignatureAlgorithm, leaf.RawTBSCertificate, leaf.Signature) != nil {
|
|
return nil, errors.New("peer migration identity is invalid or expired")
|
|
}
|
|
certificate.Leaf = leaf
|
|
digest := sha256.Sum256(leaf.Raw)
|
|
return &Identity{certificate: certificate, fingerprint: hex.EncodeToString(digest[:])}, nil
|
|
}
|