mirror of
https://github.com/saymrwulf/swisspost-evoting-go-poc.git
synced 2026-11-18 09:54:49 +00:00
Add multi-party transport-security layer (Rust-signed)
Foundation for the multi-party re-architecture: an authenticated, confidential message transport between the separate parties of the system. - identity.go: per-party Ed25519 + X25519 identities and an Ed25519 root CA. Certificates are real X.509, but signed through a crypto.Signer shim whose Sign() calls the Rust Ed25519 — so x509.CreateCertificate's signature bytes are produced in Rust. Verification extracts TBS bytes and calls the Rust verifier, never Go's x509 internals. No RSA anywhere. - envelope.go: signed inter-party messages over an injective length-prefixed encoding of all fields; sign/verify via Rust. - channel.go: X25519 ECDH (Rust) → session key → AES-256-GCM confidential payloads. - bus.go: CA-anchored directory + message router that verifies every request and reply signature before delivery (authenticity enforced at the boundary). Tests cover cert-chain verification (incl. foreign-CA rejection), envelope tamper rejection, forged-sender rejection at the bus, and secure-channel round-trip with associated-data binding. ARCHITECTURE.md documents the parties, the transport, and the message inventory. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
ec4be74e17
commit
f7cbe4f634
6 changed files with 648 additions and 0 deletions
78
ARCHITECTURE.md
Normal file
78
ARCHITECTURE.md
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
# Multi-Party Architecture
|
||||
|
||||
This PoC emulates the Swiss Post e-voting system's **trust structure**: the
|
||||
parties that in production run on separate machines under separate operators are
|
||||
modeled here as separate in-process endpoints that communicate **only** through
|
||||
an authenticated, confidential transport. No party reaches into another's
|
||||
private state; every inter-party message is Ed25519-signed and verified, and
|
||||
confidential channels are keyed by X25519 ECDH — all of that cryptography
|
||||
implemented in **Rust** (`pkg/transportsec` → `rust/transportsec`).
|
||||
|
||||
Scalability is explicitly out of scope (it remains a single-binary PoC). What is
|
||||
in scope is **full cryptographic emulation of the trust boundaries**.
|
||||
|
||||
## Parties
|
||||
|
||||
| Party | Role | Private state (never leaves the party) |
|
||||
|-------|------|----------------------------------------|
|
||||
| **Setup component** (SDM analog) | Generates election parameters, assembles voting cards and the return-codes mapping table | election-event seed, assembled card secrets |
|
||||
| **CC0–CC3** (4 control components) | Split-trust key generation; ballot proof checks; mix-net shuffle + partial decryption | each CC's ElGamal secret key, return-code secret, shuffle permutation & randomness |
|
||||
| **Electoral Board** (offline) | Final shuffle and decryption on the air-gapped side | EB secret key, board passwords |
|
||||
| **Voting server / ballot box** | Receives ballots, drives return-code extraction, stores the ballot box | mapping table, ballot box contents |
|
||||
| **Voter client** | Encrypts the ballot, produces ballot proofs, checks return codes | card secrets, encryption randomness, `vcSK` |
|
||||
| **Verifier / auditor** | Independently re-checks the entire public transcript | nothing — public data only |
|
||||
|
||||
## Transport security (all crypto in Rust)
|
||||
|
||||
```
|
||||
┌──────────────── Ed25519 root CA (Rust-signed X.509) ───────────────┐
|
||||
│ │
|
||||
issues identity certs (Ed25519, no RSA) binding party name → Ed25519 pubkey │
|
||||
│ │
|
||||
┌─────────▼──────────┐ signed Envelope ┌──────────▼─────────┐
|
||||
│ Party A (Identity)│ ───────────────────▶ │ Party B (Identity)│
|
||||
│ Ed25519 seed │ Ed25519 sig (Rust) │ verifies sig (Rust)│
|
||||
│ X25519 keypair │ ◀─────────────────── │ │
|
||||
└────────────────────┘ secure channel └────────────────────┘
|
||||
X25519 ECDH (Rust) → AES-256-GCM payloads
|
||||
```
|
||||
|
||||
- **Identity** (`pkg/transport/identity.go`): each party holds an Ed25519 signing
|
||||
key, an X25519 ECDH key, and an X.509 certificate. The CA signs certificates
|
||||
through a `crypto.Signer` shim whose `Sign` calls the Rust Ed25519 — so even
|
||||
`x509.CreateCertificate`'s signature bytes come from Rust. Certificate
|
||||
verification extracts the TBS bytes and calls the Rust verifier (never Go's
|
||||
x509 internals).
|
||||
- **Envelope** (`envelope.go`): a signed message `{from,to,type,nonce,payload}`.
|
||||
The signature covers an injective length-prefixed encoding of all fields.
|
||||
- **SecureChannel** (`channel.go`): X25519 ECDH shared secret → session key →
|
||||
AES-256-GCM. Used where a payload must be confidential, not just authentic.
|
||||
- **Directory + Bus** (`bus.go`): the directory admits a party only after its
|
||||
cert chains to the CA, binding the name to the cert's Ed25519 key. The bus
|
||||
routes envelopes and verifies every message's signature (request and reply)
|
||||
before delivery — this is where authenticity is enforced at the boundary.
|
||||
|
||||
## Why EdDSA / ECDH instead of the production RSA
|
||||
|
||||
The production system uses RSASSA-PSS signatures and RSA-based channel security.
|
||||
This PoC deliberately substitutes an **elliptic-curve stack** — Ed25519 for
|
||||
signatures, X25519 for key agreement — with **no RSA anywhere**, including the
|
||||
X.509 CA. This is a design choice for the PoC, not a claim about the production
|
||||
system.
|
||||
|
||||
## Message inventory (implemented incrementally)
|
||||
|
||||
Setup: CC key shares + Schnorr proofs → setup; setup → voter (card), → server
|
||||
(mapping table), → all (signed election config). Voting: voter → server (ballot);
|
||||
server → CCj (proof check); server ↔ CCj (return-code shares). Tally: server →
|
||||
CC0 (ballot box); CCj → CCj+1 (shuffle + partial decryption + proofs); CC3 → EB;
|
||||
EB → bulletin board (result + final proof). Audit: bulletin board → verifier
|
||||
(public transcript).
|
||||
|
||||
## Deferred trust-boundary hardening folded in here
|
||||
|
||||
Findings from the due-diligence pass that only matter once inputs are remote are
|
||||
addressed as parties are split: verifiers return errors instead of panicking on
|
||||
malformed peer input, group elements/proofs are re-validated on receipt, and the
|
||||
artifacts a remote verifier needs (padded mix input, per-stage decryption proofs,
|
||||
`vcPK`) are persisted into a serializable public transcript.
|
||||
127
pkg/transport/bus.go
Normal file
127
pkg/transport/bus.go
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
package transport
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Peer is the public identity information the directory holds for a party:
|
||||
// its CA-verified certificate and the Ed25519/X25519 public keys bound by it.
|
||||
type Peer struct {
|
||||
Name string
|
||||
EdPub []byte
|
||||
XPub []byte
|
||||
Cert *x509.Certificate
|
||||
}
|
||||
|
||||
// Directory maps party names to their verified public identities. A party is
|
||||
// only added after its certificate chains to the trusted CA (verified in Rust).
|
||||
type Directory struct {
|
||||
ca *CA
|
||||
peers map[string]*Peer
|
||||
}
|
||||
|
||||
// NewDirectory creates an empty directory anchored to a CA.
|
||||
func NewDirectory(ca *CA) *Directory {
|
||||
return &Directory{ca: ca, peers: make(map[string]*Peer)}
|
||||
}
|
||||
|
||||
// Register validates id's certificate against the CA and adds it. The XPub is
|
||||
// carried alongside (it is not part of the Ed25519 cert, but is distributed
|
||||
// through the same trusted enrollment step in this PoC).
|
||||
func (d *Directory) Register(id *Identity) error {
|
||||
if err := d.ca.VerifyCertificate(id.Cert); err != nil {
|
||||
return fmt.Errorf("register %s: %w", id.Name, err)
|
||||
}
|
||||
if id.Cert.Subject.CommonName != id.Name {
|
||||
return fmt.Errorf("register %s: cert CN %q does not match name", id.Name, id.Cert.Subject.CommonName)
|
||||
}
|
||||
// Bind the Ed25519 public key from the (verified) certificate, not from the
|
||||
// identity struct, so a party cannot register a cert for one key while
|
||||
// signing with another.
|
||||
certPub, ok := id.Cert.PublicKey.(ed25519.PublicKey)
|
||||
if !ok {
|
||||
return fmt.Errorf("register %s: certificate is not Ed25519", id.Name)
|
||||
}
|
||||
d.peers[id.Name] = &Peer{
|
||||
Name: id.Name,
|
||||
EdPub: []byte(certPub),
|
||||
XPub: id.XPub,
|
||||
Cert: id.Cert,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Lookup returns the peer for name, or an error if unknown.
|
||||
func (d *Directory) Lookup(name string) (*Peer, error) {
|
||||
p, ok := d.peers[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown party %q", name)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Handler processes an inbound envelope and optionally returns a reply.
|
||||
type Handler func(env *Envelope) (*Envelope, error)
|
||||
|
||||
// Bus is an in-process message router. It emulates the network between parties:
|
||||
// every message it carries has its Ed25519 signature verified (in Rust) against
|
||||
// the sender's directory entry before delivery, and replies are verified on the
|
||||
// way back. This is where authenticity is enforced at the transport boundary.
|
||||
type Bus struct {
|
||||
dir *Directory
|
||||
handlers map[string]Handler
|
||||
Log func(format string, args ...any)
|
||||
count int
|
||||
}
|
||||
|
||||
// NewBus creates a bus over a directory.
|
||||
func NewBus(dir *Directory) *Bus {
|
||||
return &Bus{
|
||||
dir: dir,
|
||||
handlers: make(map[string]Handler),
|
||||
Log: func(string, ...any) {},
|
||||
}
|
||||
}
|
||||
|
||||
// Handle registers the handler a party uses to receive messages addressed to it.
|
||||
func (b *Bus) Handle(name string, h Handler) { b.handlers[name] = h }
|
||||
|
||||
// Count returns the number of verified messages carried so far.
|
||||
func (b *Bus) Count() int { return b.count }
|
||||
|
||||
// Send verifies the request signature, delivers it to the recipient handler,
|
||||
// then verifies the reply signature (if any) before returning it.
|
||||
func (b *Bus) Send(env *Envelope) (*Envelope, error) {
|
||||
sender, err := b.dir.Lookup(env.From)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("send: %w", err)
|
||||
}
|
||||
if err := env.Verify(sender.EdPub); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.count++
|
||||
b.Log(" [transport] %s -> %s : %s (%d bytes, encrypted=%v) signature OK",
|
||||
env.From, env.To, env.Type, len(env.Payload), env.Encrypted)
|
||||
|
||||
h, ok := b.handlers[env.To]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("send: no handler for %q", env.To)
|
||||
}
|
||||
reply, err := h(env)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("handler %s: %w", env.To, err)
|
||||
}
|
||||
if reply != nil {
|
||||
replier, err := b.dir.Lookup(reply.From)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reply: %w", err)
|
||||
}
|
||||
if err := reply.Verify(replier.EdPub); err != nil {
|
||||
return nil, fmt.Errorf("reply verification: %w", err)
|
||||
}
|
||||
b.count++
|
||||
}
|
||||
return reply, nil
|
||||
}
|
||||
83
pkg/transport/channel.go
Normal file
83
pkg/transport/channel.go
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
package transport
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
|
||||
"github.com/user/evote/pkg/symmetric"
|
||||
"github.com/user/evote/pkg/transportsec"
|
||||
)
|
||||
|
||||
// deriveSessionKey turns a raw X25519 shared secret into a 32-byte AES key by
|
||||
// hashing it together with both parties' public keys (a lightweight KDF that
|
||||
// binds the key to the specific peer pair and avoids using the raw DH output
|
||||
// directly). The public keys are sorted so both ends derive the same key.
|
||||
func deriveSessionKey(shared, pubA, pubB []byte) []byte {
|
||||
h := sha256.New()
|
||||
h.Write([]byte("evote-transport-session-v1"))
|
||||
// Order-independent: hash the lexicographically smaller key first.
|
||||
if lessBytes(pubA, pubB) {
|
||||
h.Write(pubA)
|
||||
h.Write(pubB)
|
||||
} else {
|
||||
h.Write(pubB)
|
||||
h.Write(pubA)
|
||||
}
|
||||
h.Write(shared)
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
func lessBytes(a, b []byte) bool {
|
||||
for i := 0; i < len(a) && i < len(b); i++ {
|
||||
if a[i] != b[i] {
|
||||
return a[i] < b[i]
|
||||
}
|
||||
}
|
||||
return len(a) < len(b)
|
||||
}
|
||||
|
||||
// SecureChannel is a confidential channel between the local identity and a peer.
|
||||
// The session key is derived from an X25519 ECDH (performed in Rust); payloads
|
||||
// are sealed with AES-256-GCM. It complements envelope signing: sign-then-the
|
||||
// channel gives authenticity, the channel gives confidentiality.
|
||||
type SecureChannel struct {
|
||||
local *Identity
|
||||
peerName string
|
||||
peerXPub []byte
|
||||
sessionKey []byte
|
||||
}
|
||||
|
||||
// NewSecureChannel establishes a channel to a peer given the peer's X25519
|
||||
// public key. The ECDH is computed in Rust.
|
||||
func (id *Identity) NewSecureChannel(peerName string, peerXPub []byte) (*SecureChannel, error) {
|
||||
shared, err := transportsec.X25519SharedSecret(id.ECDHPrivate(), peerXPub)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ECDH %s<->%s: %w", id.Name, peerName, err)
|
||||
}
|
||||
return &SecureChannel{
|
||||
local: id,
|
||||
peerName: peerName,
|
||||
peerXPub: peerXPub,
|
||||
sessionKey: deriveSessionKey(shared, id.XPub, peerXPub),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// EncryptPayload seals plaintext with the session key, returning ciphertext with
|
||||
// the GCM nonce prepended (associatedData binds it to a context string).
|
||||
func (c *SecureChannel) EncryptPayload(plaintext, associatedData []byte) ([]byte, error) {
|
||||
ct, nonce, err := symmetric.Encrypt(c.sessionKey, plaintext, associatedData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(append([]byte{}, nonce...), ct...), nil
|
||||
}
|
||||
|
||||
// DecryptPayload opens a payload produced by EncryptPayload.
|
||||
func (c *SecureChannel) DecryptPayload(sealed, associatedData []byte) ([]byte, error) {
|
||||
const nonceSize = 12 // AES-GCM standard nonce
|
||||
if len(sealed) < nonceSize {
|
||||
return nil, fmt.Errorf("sealed payload too short")
|
||||
}
|
||||
nonce, ct := sealed[:nonceSize], sealed[nonceSize:]
|
||||
return symmetric.Decrypt(c.sessionKey, ct, nonce, associatedData)
|
||||
}
|
||||
77
pkg/transport/envelope.go
Normal file
77
pkg/transport/envelope.go
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
package transport
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/user/evote/pkg/transportsec"
|
||||
)
|
||||
|
||||
// Envelope is a single authenticated message from one party to another. The
|
||||
// signature (Ed25519, produced in Rust) covers the canonical byte encoding of
|
||||
// all other fields, so From/To/Type/Nonce/Payload are all integrity-protected.
|
||||
// Encrypted marks whether Payload is AES-GCM ciphertext (see SecureChannel).
|
||||
type Envelope struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Type string `json:"type"`
|
||||
Nonce uint64 `json:"nonce"`
|
||||
Encrypted bool `json:"encrypted"`
|
||||
Payload []byte `json:"payload"`
|
||||
Signature []byte `json:"signature"`
|
||||
}
|
||||
|
||||
// signingBytes returns the canonical bytes covered by the signature: a
|
||||
// length-prefixed concatenation of every field except the signature itself.
|
||||
// Length-prefixing makes the encoding injective (no field-boundary ambiguity).
|
||||
func (e *Envelope) signingBytes() []byte {
|
||||
var b []byte
|
||||
appendField := func(data []byte) {
|
||||
var l [8]byte
|
||||
binary.BigEndian.PutUint64(l[:], uint64(len(data)))
|
||||
b = append(b, l[:]...)
|
||||
b = append(b, data...)
|
||||
}
|
||||
appendField([]byte(e.From))
|
||||
appendField([]byte(e.To))
|
||||
appendField([]byte(e.Type))
|
||||
var nonce [8]byte
|
||||
binary.BigEndian.PutUint64(nonce[:], e.Nonce)
|
||||
appendField(nonce[:])
|
||||
if e.Encrypted {
|
||||
appendField([]byte{1})
|
||||
} else {
|
||||
appendField([]byte{0})
|
||||
}
|
||||
appendField(e.Payload)
|
||||
// Hash the concatenation to a fixed 32-byte digest that is what actually
|
||||
// gets signed (keeps signed inputs short and uniform).
|
||||
h := sha256.Sum256(b)
|
||||
return h[:]
|
||||
}
|
||||
|
||||
// Seal signs the envelope with the sender identity's Ed25519 key (via Rust).
|
||||
func (e *Envelope) Seal(sender *Identity) error {
|
||||
sig, err := transportsec.Ed25519Sign(sender.SigningSeed(), e.signingBytes())
|
||||
if err != nil {
|
||||
return fmt.Errorf("seal %s->%s: %w", e.From, e.To, err)
|
||||
}
|
||||
e.Signature = sig
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify checks the envelope signature against senderEdPub (via Rust).
|
||||
func (e *Envelope) Verify(senderEdPub []byte) error {
|
||||
if err := transportsec.Ed25519Verify(senderEdPub, e.signingBytes(), e.Signature); err != nil {
|
||||
return fmt.Errorf("envelope %s->%s type=%s: %w", e.From, e.To, e.Type, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalPayload JSON-encodes v into the payload.
|
||||
func MarshalPayload(v any) ([]byte, error) { return json.Marshal(v) }
|
||||
|
||||
// UnmarshalPayload JSON-decodes the payload into v.
|
||||
func UnmarshalPayload(data []byte, v any) error { return json.Unmarshal(data, v) }
|
||||
179
pkg/transport/identity.go
Normal file
179
pkg/transport/identity.go
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
// Package transport provides the authenticated, confidential message-passing
|
||||
// layer that connects the separate parties of the e-voting system (setup
|
||||
// component, control components, electoral board, voting server, voter clients,
|
||||
// verifier).
|
||||
//
|
||||
// Every inter-party message is Ed25519-signed and every confidential channel is
|
||||
// keyed by X25519 ECDH — both implemented in Rust (pkg/transportsec). Party
|
||||
// identities are X.509 certificates signed by a root CA using Ed25519 (no RSA,
|
||||
// no RSA CA signatures). The Ed25519 signing under CreateCertificate and all
|
||||
// certificate-signature verification are routed through the Rust library via a
|
||||
// crypto.Signer shim, so no signature is ever produced or checked by Go.
|
||||
package transport
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ed25519"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"time"
|
||||
|
||||
"github.com/user/evote/pkg/transportsec"
|
||||
)
|
||||
|
||||
// rustSigner is a crypto.Signer whose Ed25519 signing is performed in Rust.
|
||||
// It lets crypto/x509.CreateCertificate emit certificates whose signature bytes
|
||||
// are produced by transportsec (ed25519-dalek), not by Go's crypto/ed25519.
|
||||
type rustSigner struct {
|
||||
seed []byte // 32-byte Ed25519 seed
|
||||
pub ed25519.PublicKey
|
||||
}
|
||||
|
||||
func (s rustSigner) Public() crypto.PublicKey { return s.pub }
|
||||
|
||||
// Sign ignores the (already-hashed=identity) opts as required for Ed25519 and
|
||||
// signs the message directly through Rust.
|
||||
func (s rustSigner) Sign(_ io.Reader, message []byte, _ crypto.SignerOpts) ([]byte, error) {
|
||||
return transportsec.Ed25519Sign(s.seed, message)
|
||||
}
|
||||
|
||||
// Identity is a party's cryptographic identity: an Ed25519 signing key (for
|
||||
// message and certificate signatures), an X25519 key (for ECDH channel keys),
|
||||
// and an X.509 certificate binding the party name to its Ed25519 public key.
|
||||
type Identity struct {
|
||||
Name string
|
||||
|
||||
edSeed []byte // 32-byte Ed25519 seed (private)
|
||||
EdPub []byte // 32-byte Ed25519 public key
|
||||
|
||||
xPriv []byte // 32-byte X25519 private scalar
|
||||
XPub []byte // 32-byte X25519 public key
|
||||
|
||||
Cert *x509.Certificate
|
||||
CertDER []byte
|
||||
}
|
||||
|
||||
// SigningSeed exposes the Ed25519 seed to same-package channel/envelope code.
|
||||
func (id *Identity) SigningSeed() []byte { return id.edSeed }
|
||||
|
||||
// ECDHPrivate exposes the X25519 scalar to same-package channel code.
|
||||
func (id *Identity) ECDHPrivate() []byte { return id.xPriv }
|
||||
|
||||
// CA is a minimal root certificate authority that issues Ed25519 identity
|
||||
// certificates. Its own signing key is Rust-backed.
|
||||
type CA struct {
|
||||
signer rustSigner
|
||||
Cert *x509.Certificate
|
||||
CertDER []byte
|
||||
}
|
||||
|
||||
// serialCounter deterministically supplies certificate serial numbers.
|
||||
// (crypto/rand-based serials would make runs non-reproducible; a counter is
|
||||
// sufficient for a single-CA PoC and keeps ceremonies deterministic.)
|
||||
type serialCounter struct{ n int64 }
|
||||
|
||||
func (c *serialCounter) next() *big.Int { c.n++; return big.NewInt(c.n) }
|
||||
|
||||
// fixedNotBefore/After bound certificate validity. The values are fixed so
|
||||
// ceremonies are reproducible; time.Now is avoided deliberately.
|
||||
var (
|
||||
fixedNotBefore = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
fixedNotAfter = time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
)
|
||||
|
||||
// NewCA creates a self-signed Ed25519 root CA named name.
|
||||
func NewCA(name string, serials *serialCounter) (*CA, error) {
|
||||
seed, pub, err := transportsec.Ed25519GenerateKey()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CA keygen: %w", err)
|
||||
}
|
||||
signer := rustSigner{seed: seed, pub: ed25519.PublicKey(pub)}
|
||||
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serials.next(),
|
||||
Subject: pkix.Name{CommonName: name},
|
||||
NotBefore: fixedNotBefore,
|
||||
NotAfter: fixedNotAfter,
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
|
||||
}
|
||||
// Self-signed: parent == template, public key is the CA's own Ed25519 key,
|
||||
// signer is the Rust-backed CA signer.
|
||||
der, err := x509.CreateCertificate(nil, tmpl, tmpl, signer.pub, signer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CA self-sign: %w", err)
|
||||
}
|
||||
cert, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CA parse: %w", err)
|
||||
}
|
||||
return &CA{signer: signer, Cert: cert, CertDER: der}, nil
|
||||
}
|
||||
|
||||
// Issue creates an Identity for a party, with an Ed25519 cert signed by the CA.
|
||||
func (ca *CA) Issue(name string, serials *serialCounter) (*Identity, error) {
|
||||
edSeed, edPub, err := transportsec.Ed25519GenerateKey()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s ed keygen: %w", name, err)
|
||||
}
|
||||
xPriv, xPub, err := transportsec.X25519GenerateKey()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s x keygen: %w", name, err)
|
||||
}
|
||||
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serials.next(),
|
||||
Subject: pkix.Name{CommonName: name},
|
||||
NotBefore: fixedNotBefore,
|
||||
NotAfter: fixedNotAfter,
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
}
|
||||
// Subject public key is the party's Ed25519 key; the signature is produced
|
||||
// by the CA's Rust-backed signer.
|
||||
der, err := x509.CreateCertificate(nil, tmpl, ca.Cert, ed25519.PublicKey(edPub), ca.signer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s cert sign: %w", name, err)
|
||||
}
|
||||
cert, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s cert parse: %w", name, err)
|
||||
}
|
||||
|
||||
return &Identity{
|
||||
Name: name,
|
||||
edSeed: edSeed,
|
||||
EdPub: edPub,
|
||||
xPriv: xPriv,
|
||||
XPub: xPub,
|
||||
Cert: cert,
|
||||
CertDER: der,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// VerifyCertificate checks that cert was signed by the CA, with the Ed25519
|
||||
// signature verified in Rust rather than by Go's x509 internals.
|
||||
func (ca *CA) VerifyCertificate(cert *x509.Certificate) error {
|
||||
return verifyCertSignature(cert, ca.Cert.PublicKey.(ed25519.PublicKey))
|
||||
}
|
||||
|
||||
// verifyCertSignature verifies an X.509 certificate's Ed25519 signature over its
|
||||
// TBS bytes using the Rust verifier.
|
||||
func verifyCertSignature(cert *x509.Certificate, caPub ed25519.PublicKey) error {
|
||||
if cert.SignatureAlgorithm != x509.PureEd25519 {
|
||||
return fmt.Errorf("unexpected signature algorithm %v (want Ed25519)", cert.SignatureAlgorithm)
|
||||
}
|
||||
if err := transportsec.Ed25519Verify(caPub, cert.RawTBSCertificate, cert.Signature); err != nil {
|
||||
return fmt.Errorf("certificate signature invalid: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PEM renders a certificate as PEM (for logging/inspection).
|
||||
func PEM(der []byte) string {
|
||||
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
|
||||
}
|
||||
104
pkg/transport/transport_test.go
Normal file
104
pkg/transport/transport_test.go
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newTestPKI(t *testing.T, names ...string) (*CA, *Directory, map[string]*Identity) {
|
||||
t.Helper()
|
||||
serials := &serialCounter{}
|
||||
ca, err := NewCA("evote-root-ca", serials)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCA: %v", err)
|
||||
}
|
||||
dir := NewDirectory(ca)
|
||||
ids := make(map[string]*Identity)
|
||||
for _, n := range names {
|
||||
id, err := ca.Issue(n, serials)
|
||||
if err != nil {
|
||||
t.Fatalf("issue %s: %v", n, err)
|
||||
}
|
||||
if err := dir.Register(id); err != nil {
|
||||
t.Fatalf("register %s: %v", n, err)
|
||||
}
|
||||
ids[n] = id
|
||||
}
|
||||
return ca, dir, ids
|
||||
}
|
||||
|
||||
func TestCertificateChainVerifies(t *testing.T) {
|
||||
ca, _, ids := newTestPKI(t, "cc0")
|
||||
if err := ca.VerifyCertificate(ids["cc0"].Cert); err != nil {
|
||||
t.Fatalf("issued cert should verify: %v", err)
|
||||
}
|
||||
// A cert from a different CA must not verify against this one.
|
||||
serials := &serialCounter{}
|
||||
other, _ := NewCA("evil-ca", serials)
|
||||
forged, _ := other.Issue("cc0", serials)
|
||||
if err := ca.VerifyCertificate(forged.Cert); err == nil {
|
||||
t.Fatal("cert from foreign CA must not verify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvelopeSignVerifyRoundTrip(t *testing.T) {
|
||||
_, dir, ids := newTestPKI(t, "server", "cc1")
|
||||
env := &Envelope{From: "server", To: "cc1", Type: "ballot", Nonce: 1, Payload: []byte("hello cc1")}
|
||||
if err := env.Seal(ids["server"]); err != nil {
|
||||
t.Fatalf("seal: %v", err)
|
||||
}
|
||||
peer, _ := dir.Lookup("server")
|
||||
if err := env.Verify(peer.EdPub); err != nil {
|
||||
t.Fatalf("honest envelope rejected: %v", err)
|
||||
}
|
||||
// Tamper the payload → signature must fail.
|
||||
env.Payload = []byte("hello attacker")
|
||||
if err := env.Verify(peer.EdPub); err == nil {
|
||||
t.Fatal("tampered payload accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusRejectsForgedSender(t *testing.T) {
|
||||
_, dir, ids := newTestPKI(t, "server", "cc1")
|
||||
bus := NewBus(dir)
|
||||
bus.Handle("cc1", func(env *Envelope) (*Envelope, error) { return nil, nil })
|
||||
|
||||
// Envelope claims to be from "server" but is signed by cc1's key.
|
||||
env := &Envelope{From: "server", To: "cc1", Type: "spoof", Nonce: 1, Payload: []byte("x")}
|
||||
if err := env.Seal(ids["cc1"]); err != nil {
|
||||
t.Fatalf("seal: %v", err)
|
||||
}
|
||||
if _, err := bus.Send(env); err == nil {
|
||||
t.Fatal("bus accepted a message signed by the wrong party")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecureChannelRoundTrip(t *testing.T) {
|
||||
_, _, ids := newTestPKI(t, "cc0", "cc1")
|
||||
ch01, err := ids["cc0"].NewSecureChannel("cc1", ids["cc1"].XPub)
|
||||
if err != nil {
|
||||
t.Fatalf("channel cc0->cc1: %v", err)
|
||||
}
|
||||
ch10, err := ids["cc1"].NewSecureChannel("cc0", ids["cc0"].XPub)
|
||||
if err != nil {
|
||||
t.Fatalf("channel cc1->cc0: %v", err)
|
||||
}
|
||||
|
||||
msg := []byte("partial decryption shares")
|
||||
ad := []byte("stage-2")
|
||||
sealed, err := ch01.EncryptPayload(msg, ad)
|
||||
if err != nil {
|
||||
t.Fatalf("encrypt: %v", err)
|
||||
}
|
||||
opened, err := ch10.DecryptPayload(sealed, ad)
|
||||
if err != nil {
|
||||
t.Fatalf("decrypt: %v", err)
|
||||
}
|
||||
if !bytes.Equal(opened, msg) {
|
||||
t.Fatal("secure channel round-trip mismatch")
|
||||
}
|
||||
// Wrong associated data must fail authentication.
|
||||
if _, err := ch10.DecryptPayload(sealed, []byte("stage-3")); err == nil {
|
||||
t.Fatal("decryption succeeded under wrong associated data")
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue