Initial structure
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CertValidity is how long self-signed certs are valid for. We use a
|
||||
// long horizon because cert rotation is operator-driven, not automatic.
|
||||
const CertValidity = 10 * 365 * 24 * time.Hour
|
||||
|
||||
// buildSelfSignedCert produces an X.509 certificate signed by `priv`
|
||||
// itself, using the given common name. Returns the DER bytes.
|
||||
func buildSelfSignedCert(priv *rsa.PrivateKey, commonName string) ([]byte, error) {
|
||||
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{CommonName: commonName, Organization: []string{"quptime"}},
|
||||
NotBefore: time.Now().Add(-1 * time.Hour),
|
||||
NotAfter: time.Now().Add(CertValidity),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
|
||||
BasicConstraintsValid: true,
|
||||
IsCA: false,
|
||||
}
|
||||
return x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
|
||||
}
|
||||
|
||||
// Fingerprint computes the SHA-256 fingerprint of an X.509 certificate's
|
||||
// SubjectPublicKeyInfo (the same hash used by `openssl x509 -pubkey -noout
|
||||
// | openssl dgst -sha256`). Returns the lowercase hex digest with a
|
||||
// "sha256:" prefix to match SSH conventions.
|
||||
func Fingerprint(cert *x509.Certificate) string {
|
||||
return FingerprintFromSPKI(cert.RawSubjectPublicKeyInfo)
|
||||
}
|
||||
|
||||
// FingerprintFromSPKI is the underlying helper.
|
||||
func FingerprintFromSPKI(spki []byte) string {
|
||||
sum := sha256.Sum256(spki)
|
||||
return "sha256:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// FingerprintFromCertPEM parses a PEM-encoded certificate and returns
|
||||
// its fingerprint.
|
||||
func FingerprintFromCertPEM(certPEM []byte) (string, error) {
|
||||
block, _ := pem.Decode(certPEM)
|
||||
if block == nil {
|
||||
return "", errors.New("cert: no PEM block")
|
||||
}
|
||||
cert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse cert: %w", err)
|
||||
}
|
||||
return Fingerprint(cert), nil
|
||||
}
|
||||
|
||||
// FingerprintFromPubKeyPEM parses a public-key PEM and returns its
|
||||
// fingerprint over the same SPKI bytes.
|
||||
func FingerprintFromPubKeyPEM(pubPEM []byte) (string, error) {
|
||||
block, _ := pem.Decode(pubPEM)
|
||||
if block == nil {
|
||||
return "", errors.New("pubkey: no PEM block")
|
||||
}
|
||||
return FingerprintFromSPKI(block.Bytes), nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Package crypto handles the RSA key material every node uses for
|
||||
// mutual TLS authentication and for the trust-store fingerprint pinning.
|
||||
//
|
||||
// Keys are RSA-3072 (NIST 112-bit security, well within the safe band
|
||||
// through ~2030). They live PEM-encoded under <data_dir>/keys/.
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/jasper/quptime/internal/config"
|
||||
)
|
||||
|
||||
// KeySize is the RSA modulus size used by qu.
|
||||
const KeySize = 3072
|
||||
|
||||
// GenerateKeyPair creates a fresh RSA keypair and writes the private,
|
||||
// public, and self-signed certificate to the standard paths.
|
||||
// It refuses to overwrite existing keys.
|
||||
func GenerateKeyPair(commonName string) (*rsa.PrivateKey, error) {
|
||||
if _, err := os.Stat(config.PrivateKeyPath()); err == nil {
|
||||
return nil, errors.New("key material already exists; refusing to overwrite")
|
||||
}
|
||||
if err := config.EnsureDataDir(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
priv, err := rsa.GenerateKey(rand.Reader, KeySize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate rsa key: %w", err)
|
||||
}
|
||||
if err := writePEM(config.PrivateKeyPath(), "RSA PRIVATE KEY",
|
||||
x509.MarshalPKCS1PrivateKey(priv), 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pubDER, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := writePEM(config.PublicKeyPath(), "PUBLIC KEY", pubDER, 0o644); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
certDER, err := buildSelfSignedCert(priv, commonName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := writePEM(config.CertFilePath(), "CERTIFICATE", certDER, 0o644); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return priv, nil
|
||||
}
|
||||
|
||||
// LoadPrivateKey reads the on-disk RSA private key.
|
||||
func LoadPrivateKey() (*rsa.PrivateKey, error) {
|
||||
raw, err := os.ReadFile(config.PrivateKeyPath())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
block, _ := pem.Decode(raw)
|
||||
if block == nil {
|
||||
return nil, errors.New("private key: no PEM block")
|
||||
}
|
||||
switch block.Type {
|
||||
case "RSA PRIVATE KEY":
|
||||
return x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
case "PRIVATE KEY":
|
||||
k, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rk, ok := k.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("private key: not RSA")
|
||||
}
|
||||
return rk, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("private key: unexpected PEM type %q", block.Type)
|
||||
}
|
||||
}
|
||||
|
||||
// LoadCertPEM reads the self-signed cert file (used as the TLS leaf).
|
||||
func LoadCertPEM() ([]byte, error) {
|
||||
return os.ReadFile(config.CertFilePath())
|
||||
}
|
||||
|
||||
// LoadPublicKeyPEM reads the public-key PEM (exchanged out of band
|
||||
// during invite / join).
|
||||
func LoadPublicKeyPEM() ([]byte, error) {
|
||||
return os.ReadFile(config.PublicKeyPath())
|
||||
}
|
||||
|
||||
func writePEM(path, blockType string, der []byte, perm os.FileMode) error {
|
||||
encoded := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: der})
|
||||
return config.AtomicWrite(path, encoded, perm)
|
||||
}
|
||||
Reference in New Issue
Block a user