SPB Git

Repository Public

pki.go 13.2 KB 414 lines go

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Command Center (MCC)8 * File             : services/internal/pki/pki.go9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-command-center11 * Project Website  : https://clustr.spboucher.ai12 * Created          : 2026-11-1813 * Last Modified    : 2026-11-1814 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Package pki is the private certificate authority of the agent data plane.43//44// One ECDSA P-256 CA signs two kinds of leaf certificates:45//   - the ingest server certificate (ExtKeyUsage serverAuth, short-lived,46//     re-issued in memory, the key never touches the disk);47//   - agent client certificates (ExtKeyUsage clientAuth only, 30 days,48//     CN = agent id, SAN URI mcc://agent/<agent-id>).49//50// Because the usages are disjoint, a stolen agent key cannot impersonate the51// ingest service, and the server key cannot authenticate as an agent.52package pki5354import (55	"context"56	"crypto/ecdsa"57	"crypto/elliptic"58	"crypto/rand"59	"crypto/sha256"60	"crypto/tls"61	"crypto/x509"62	"crypto/x509/pkix"63	"encoding/hex"64	"encoding/pem"65	"errors"66	"fmt"67	"math/big"68	"net/url"69	"os"70	"path/filepath"71	"strings"72	"time"7374	"github.com/google/uuid"75	"github.com/jackc/pgx/v5/pgconn"76)7778const (79	caCertFile = "agent-ca.crt"80	caKeyFile  = "agent-ca.key"8182	// AgentCertTTL is the lifetime of an agent client certificate.83	AgentCertTTL = 30 * 24 * time.Hour84	// ServerCertTTL is the lifetime of the ingest server certificate.85	ServerCertTTL = 72 * time.Hour86	caTTL         = 10 * 365 * 24 * time.Hour87	backdate      = 5 * time.Minute // tolerated clock skew of a verifier88)8990// CA holds the authority. The private key stays inside the package.91type CA struct {92	Cert *x509.Certificate93	PEM  []byte94	key  *ecdsa.PrivateKey95}9697// LoadOrCreate loads the CA from dir, creating it (dir 0700, files 0600) on98// first use. Creation is safe against a concurrent starter: the key file is99// created exclusively and the loser loads the winner's files.100func LoadOrCreate(dir string) (*CA, error) {101	if err := os.MkdirAll(dir, 0o700); err != nil {102		return nil, fmt.Errorf("pki: secrets dir: %w", err)103	}104	if err := os.Chmod(dir, 0o700); err != nil {105		return nil, fmt.Errorf("pki: secrets dir mode: %w", err)106	}107	keyPath, certPath := filepath.Join(dir, caKeyFile), filepath.Join(dir, caCertFile)108	for attempt := 0; attempt < 20; attempt++ {109		ca, err := load(keyPath, certPath)110		if err == nil {111			return ca, nil112		}113		if !errors.Is(err, os.ErrNotExist) {114			return nil, err115		}116		if _, statErr := os.Stat(keyPath); statErr == nil {117			// Key present, certificate not yet: another process is creating it.118			time.Sleep(100 * time.Millisecond)119			continue120		}121		if err := create(keyPath, certPath); err != nil && !errors.Is(err, os.ErrExist) {122			return nil, err123		}124	}125	return nil, errors.New("pki: CA files are incomplete (key without certificate); remove both to recreate")126}127128func load(keyPath, certPath string) (*CA, error) {129	keyPEM, err := os.ReadFile(keyPath)130	if err != nil {131		return nil, err132	}133	certPEM, err := os.ReadFile(certPath)134	if err != nil {135		return nil, err136	}137	if st, err := os.Stat(keyPath); err == nil && st.Mode().Perm()&0o077 != 0 {138		return nil, fmt.Errorf("pki: %s must not be readable by group or others (mode %o)", keyPath, st.Mode().Perm())139	}140	kb, _ := pem.Decode(keyPEM)141	if kb == nil {142		return nil, errors.New("pki: CA key is not PEM")143	}144	key, err := x509.ParseECPrivateKey(kb.Bytes)145	if err != nil {146		return nil, fmt.Errorf("pki: CA key: %w", err)147	}148	cb, _ := pem.Decode(certPEM)149	if cb == nil {150		return nil, errors.New("pki: CA certificate is not PEM")151	}152	cert, err := x509.ParseCertificate(cb.Bytes)153	if err != nil {154		return nil, fmt.Errorf("pki: CA certificate: %w", err)155	}156	pub, ok := cert.PublicKey.(*ecdsa.PublicKey)157	if !ok || !pub.Equal(&key.PublicKey) {158		return nil, errors.New("pki: CA certificate does not match the CA key")159	}160	if !cert.IsCA {161		return nil, errors.New("pki: stored certificate is not a CA")162	}163	return &CA{Cert: cert, PEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}), key: key}, nil164}165166func create(keyPath, certPath string) error {167	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)168	if err != nil {169		return err170	}171	now := time.Now().UTC()172	tmpl := &x509.Certificate{173		SerialNumber:          newSerial(),174		Subject:               pkix.Name{CommonName: "MCC Agent CA", Organization: []string{"MacLustr Command Center"}},175		NotBefore:             now.Add(-backdate),176		NotAfter:              now.Add(caTTL),177		IsCA:                  true,178		BasicConstraintsValid: true,179		MaxPathLen:            0,180		MaxPathLenZero:        true,181		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,182	}183	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)184	if err != nil {185		return err186	}187	keyDER, err := x509.MarshalECPrivateKey(key)188	if err != nil {189		return err190	}191	// Exclusive creation of the key decides the winner.192	kf, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)193	if err != nil {194		return err195	}196	if _, err := kf.Write(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})); err != nil {197		kf.Close()198		os.Remove(keyPath)199		return err200	}201	if err := kf.Sync(); err != nil {202		kf.Close()203		os.Remove(keyPath)204		return err205	}206	kf.Close()207	if err := WriteFileAtomic(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil {208		os.Remove(keyPath)209		return err210	}211	return nil212}213214// WriteFileAtomic writes data to a temporary file in the same directory,215// fsyncs it and renames it over path.216func WriteFileAtomic(path string, data []byte, mode os.FileMode) error {217	f, err := os.CreateTemp(filepath.Dir(path), ".tmp-*")218	if err != nil {219		return err220	}221	tmp := f.Name()222	defer os.Remove(tmp)223	if err := f.Chmod(mode); err != nil {224		f.Close()225		return err226	}227	if _, err := f.Write(data); err != nil {228		f.Close()229		return err230	}231	if err := f.Sync(); err != nil {232		f.Close()233		return err234	}235	if err := f.Close(); err != nil {236		return err237	}238	if err := os.Rename(tmp, path); err != nil {239		return err240	}241	if d, err := os.Open(filepath.Dir(path)); err == nil {242		d.Sync()243		d.Close()244	}245	return nil246}247248func newSerial() *big.Int {249	b := make([]byte, 16)250	if _, err := rand.Read(b); err != nil {251		panic("pki: entropy source failed: " + err.Error())252	}253	b[0] &= 0x7f // positive254	if b[0] == 0 {255		b[0] = 1256	}257	return new(big.Int).SetBytes(b)258}259260// SerialString is the canonical text form of a certificate serial (lowercase hex).261func SerialString(n *big.Int) string { return hex.EncodeToString(n.Bytes()) }262263// Fingerprint returns "sha256:<hex>" of a DER certificate.264func Fingerprint(der []byte) string {265	h := sha256.Sum256(der)266	return "sha256:" + hex.EncodeToString(h[:])267}268269// ParseFingerprint validates "sha256:<64 hex>" (the prefix is optional,270// colons between bytes are accepted) and returns the digest.271func ParseFingerprint(s string) ([]byte, error) {272	s = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(s)), "sha256:")273	s = strings.ReplaceAll(s, ":", "")274	b, err := hex.DecodeString(s)275	if err != nil || len(b) != sha256.Size {276		return nil, errors.New("pki: fingerprint must be sha256:<64 hex digits>")277	}278	return b, nil279}280281// Fingerprint of the CA certificate.282func (ca *CA) Fingerprint() string { return Fingerprint(ca.Cert.Raw) }283284// Pool returns a pool containing only this CA.285func (ca *CA) Pool() *x509.CertPool {286	p := x509.NewCertPool()287	p.AddCert(ca.Cert)288	return p289}290291// IssueServer creates a fresh key and server certificate for the given DNS292// name. The chain carries the CA certificate so an enrolling agent can pin it.293func (ca *CA) IssueServer(serverName string, now time.Time) (*tls.Certificate, error) {294	if serverName == "" {295		return nil, errors.New("pki: empty server name")296	}297	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)298	if err != nil {299		return nil, err300	}301	tmpl := &x509.Certificate{302		SerialNumber:          newSerial(),303		Subject:               pkix.Name{CommonName: serverName},304		DNSNames:              []string{serverName},305		NotBefore:             now.Add(-backdate),306		NotAfter:              now.Add(ServerCertTTL),307		KeyUsage:              x509.KeyUsageDigitalSignature,308		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},309		BasicConstraintsValid: true,310	}311	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.Cert, &key.PublicKey, ca.key)312	if err != nil {313		return nil, err314	}315	leaf, err := x509.ParseCertificate(der)316	if err != nil {317		return nil, err318	}319	return &tls.Certificate{Certificate: [][]byte{der, ca.Cert.Raw}, PrivateKey: key, Leaf: leaf}, nil320}321322// ErrBadCSR is returned for a request the CA refuses to sign.323var ErrBadCSR = errors.New("pki: invalid certificate request")324325// ParseCSR decodes and checks a PEM certificate request: valid self326// signature and an ECDSA P-256 key. Everything else in the request (subject,327// SANs, extensions) is ignored: the CA decides the identity.328func ParseCSR(csrPEM []byte) (*x509.CertificateRequest, error) {329	b, _ := pem.Decode(csrPEM)330	if b == nil || b.Type != "CERTIFICATE REQUEST" {331		return nil, ErrBadCSR332	}333	csr, err := x509.ParseCertificateRequest(b.Bytes)334	if err != nil {335		return nil, ErrBadCSR336	}337	if err := csr.CheckSignature(); err != nil {338		return nil, ErrBadCSR339	}340	pub, ok := csr.PublicKey.(*ecdsa.PublicKey)341	if !ok || pub.Curve != elliptic.P256() {342		return nil, ErrBadCSR343	}344	return csr, nil345}346347// AgentURI is the SAN URI identifying an agent.348func AgentURI(agentID uuid.UUID) *url.URL {349	return &url.URL{Scheme: "mcc", Host: "agent", Path: "/" + agentID.String()}350}351352// AgentIDFromCert extracts the agent id of a verified client certificate. CN353// and SAN URI must agree.354func AgentIDFromCert(c *x509.Certificate) (uuid.UUID, error) {355	id, err := uuid.Parse(c.Subject.CommonName)356	if err != nil {357		return uuid.Nil, errors.New("pki: certificate CN is not an agent id")358	}359	want := AgentURI(id).String()360	for _, u := range c.URIs {361		if u.String() == want {362			return id, nil363		}364	}365	return uuid.Nil, errors.New("pki: certificate has no matching agent URI")366}367368// SignAgent signs the key of a parsed CSR as the client certificate of agentID.369func (ca *CA) SignAgent(csr *x509.CertificateRequest, agentID uuid.UUID, now time.Time) (certPEM []byte, cert *x509.Certificate, err error) {370	tmpl := &x509.Certificate{371		SerialNumber:          newSerial(),372		Subject:               pkix.Name{CommonName: agentID.String()},373		URIs:                  []*url.URL{AgentURI(agentID)},374		NotBefore:             now.Add(-backdate),375		NotAfter:              now.Add(AgentCertTTL),376		KeyUsage:              x509.KeyUsageDigitalSignature,377		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},378		BasicConstraintsValid: true,379	}380	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.Cert, csr.PublicKey, ca.key)381	if err != nil {382		return nil, nil, err383	}384	cert, err = x509.ParseCertificate(der)385	if err != nil {386		return nil, nil, err387	}388	return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), cert, nil389}390391// Published is the value of the settings row "pki.ca", read by the control392// API to show the agent install hint. It contains public material only.393type Published struct {394	PEM         string    `json:"pem"`395	Fingerprint string    `json:"fingerprint"` // sha256:<hex> of the DER certificate396	NotAfter    time.Time `json:"not_after"`397	ServerName  string    `json:"server_name"`398	Endpoints   []string  `json:"endpoints"`399}400401// Publish stores the CA certificate and fingerprint in settings("pki.ca").402func (ca *CA) Publish(ctx context.Context, db interface {403	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)404}, serverName string, endpoints []string) error {405	if endpoints == nil {406		endpoints = []string{}407	}408	_, err := db.Exec(ctx, `insert into settings(key, value) values ('pki.ca', $1)409		on conflict (key) do update set value = excluded.value, updated_at = now()410		where settings.value is distinct from excluded.value`,411		Published{PEM: string(ca.PEM), Fingerprint: ca.Fingerprint(), NotAfter: ca.Cert.NotAfter.UTC(), ServerName: serverName, Endpoints: endpoints})412	return err413}414
Files main
Menu

Theme